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) :
286 type_ = new(pool) sig::Type;
287 sig::Copy(pool, *type_, *type);
291 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) :
294 ffi_ = new(pool) ffi_type;
295 sig::Copy(pool, *ffi_, *ffi);
296 type_ = new(pool) sig::Type;
297 sig::Copy(pool, *type_, *type);
302 ffi_ = new(pool_) ffi_type;
304 sig::Element element;
306 element.type = type_;
309 sig::Signature signature;
310 signature.elements = &element;
314 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
326 Type_privateData *type_;
328 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
331 type_(new(pool_) Type_privateData(pool_, type))
336 struct Struct_privateData :
340 Type_privateData *type_;
342 Struct_privateData(JSObjectRef owner) :
348 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
349 static TypeMap Types_;
351 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
352 Struct_privateData *internal(new Struct_privateData(owner));
353 apr_pool_t *pool(internal->pool_);
354 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
355 internal->type_ = typical;
358 internal->value_ = data;
360 size_t size(typical->GetFFI()->size);
361 void *copy(apr_palloc(internal->pool_, size));
362 memcpy(copy, data, size);
363 internal->value_ = copy;
366 return JSObjectMake(context, Struct_, internal);
369 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *type) {
374 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]]) {
375 switch ([[entry objectAtIndex:0] intValue]) {
378 sig::Parse(Pool_, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
385 struct Functor_privateData :
388 sig::Signature signature_;
391 Functor_privateData(const char *type, void (*value)()) :
392 CYData(reinterpret_cast<void *>(value))
394 sig::Parse(pool_, &signature_, type, &Structor_);
395 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
402 JSContextRef context_;
403 JSObjectRef function_;
405 ffoData(const char *type) :
406 Functor_privateData(type, NULL)
411 JSValueRef CYMakeInstance(JSContextRef context, id object, bool transient) {
412 Instance::Flags flags;
415 flags = Instance::Transient;
417 flags = Instance::None;
418 object = [object retain];
421 return Instance::Make(context, object, flags);
424 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
426 return [value UTF8String];
428 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
429 char *string(new(pool) char[size]);
430 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
431 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
436 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
437 return JSValueMakeBoolean(context, value);
440 JSValueRef CYCastJSValue(JSContextRef context, double value) {
441 return JSValueMakeNumber(context, value);
444 #define CYCastJSValue_(Type_) \
445 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
446 return JSValueMakeNumber(context, static_cast<double>(value)); \
450 CYCastJSValue_(unsigned int)
451 CYCastJSValue_(long int)
452 CYCastJSValue_(long unsigned int)
453 CYCastJSValue_(long long int)
454 CYCastJSValue_(long long unsigned int)
456 JSValueRef CYJSUndefined(JSContextRef context) {
457 return JSValueMakeUndefined(context);
460 bool CYGetIndex(const char *value, ssize_t &index) {
461 if (value[0] != '0') {
463 index = strtol(value, &end, 10);
464 if (value + strlen(value) == end)
466 } else if (value[1] == '\0') {
474 bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
475 return CYGetIndex(CYPoolCString(pool, value), index);
478 @interface NSMethodSignature (Cycript)
479 - (NSString *) _typeString;
482 @interface NSObject (Cycript)
484 - (JSType) cy$JSType;
486 - (NSObject *) cy$toJSON:(NSString *)key;
487 - (NSString *) cy$toCYON;
488 - (NSString *) cy$toKey;
490 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
492 - (NSObject *) cy$getProperty:(NSString *)name;
493 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
494 - (bool) cy$deleteProperty:(NSString *)name;
498 @interface NSString (Cycript)
499 - (void *) cy$symbol;
502 @interface NSNumber (Cycript)
503 - (void *) cy$symbol;
506 struct PropertyAttributes {
511 const char *variable;
524 PropertyAttributes(objc_property_t property) :
536 name = property_getName(property);
537 const char *attributes(property_getAttributes(property));
539 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
541 case 'R': readonly = true; break;
542 case 'C': copy = true; break;
543 case '&': retain = true; break;
544 case 'N': nonatomic = true; break;
545 case 'G': getter_ = token + 1; break;
546 case 'S': setter_ = token + 1; break;
547 case 'V': variable = token + 1; break;
551 /*if (variable == NULL) {
552 variable = property_getName(property);
553 size_t size(strlen(variable));
554 char *name(new(pool_) char[size + 2]);
556 memcpy(name + 1, variable, size);
557 name[size + 1] = '\0';
562 const char *Getter() {
564 getter_ = apr_pstrdup(pool_, name);
568 const char *Setter() {
569 if (setter_ == NULL && !readonly) {
570 size_t length(strlen(name));
572 char *temp(new(pool_) char[length + 5]);
578 temp[3] = toupper(name[0]);
579 memcpy(temp + 4, name + 1, length - 1);
582 temp[length + 3] = ':';
583 temp[length + 4] = '\0';
592 @implementation NSObject (Cycript)
594 - (JSType) cy$JSType {
595 return kJSTypeObject;
598 - (NSObject *) cy$toJSON:(NSString *)key {
599 return [self description];
602 - (NSString *) cy$toCYON {
603 return [[self cy$toJSON:@""] cy$toCYON];
606 - (NSString *) cy$toKey {
607 return [self cy$toCYON];
610 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
611 return CYMakeInstance(context, self, false);
614 - (NSObject *) cy$getProperty:(NSString *)name {
615 /*if (![name isEqualToString:@"prototype"])
616 NSLog(@"get:%@", name);*/
620 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
621 //NSLog(@"set:%@", name);
625 - (bool) cy$deleteProperty:(NSString *)name {
626 //NSLog(@"delete:%@", name);
632 @implementation WebUndefined (Cycript)
634 - (JSType) cy$JSType {
635 return kJSTypeUndefined;
638 - (NSObject *) cy$toJSON:(NSString *)key {
642 - (NSString *) cy$toCYON {
646 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
647 return CYJSUndefined(context);
652 @implementation NSNull (Cycript)
654 - (JSType) cy$JSType {
658 - (NSObject *) cy$toJSON:(NSString *)key {
662 - (NSString *) cy$toCYON {
668 @implementation NSArray (Cycript)
670 - (NSString *) cy$toCYON {
671 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
672 [json appendString:@"["];
675 for (id object in self) {
677 [json appendString:@","];
680 if ([object cy$JSType] != kJSTypeUndefined)
681 [json appendString:[object cy$toCYON]];
683 [json appendString:@","];
688 [json appendString:@"]"];
692 - (NSObject *) cy$getProperty:(NSString *)name {
693 if ([name isEqualToString:@"length"])
694 return [NSNumber numberWithUnsignedInteger:[self count]];
697 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
698 return [super cy$getProperty:name];
700 return [self objectAtIndex:index];
705 @implementation NSMutableArray (Cycript)
707 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
709 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
710 return [super cy$setProperty:name to:value];
712 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
717 - (bool) cy$deleteProperty:(NSString *)name {
719 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
720 return [super cy$deleteProperty:name];
722 [self removeObjectAtIndex:index];
729 @implementation NSDictionary (Cycript)
731 - (NSString *) cy$toCYON {
732 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
733 [json appendString:@"{"];
736 for (id key in self) {
738 [json appendString:@","];
741 [json appendString:[key cy$toKey]];
742 [json appendString:@":"];
743 NSObject *object([self objectForKey:key]);
744 [json appendString:[object cy$toCYON]];
747 [json appendString:@"}"];
751 - (NSObject *) cy$getProperty:(NSString *)name {
752 return [self objectForKey:name];
757 @implementation NSMutableDictionary (Cycript)
759 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
760 [self setObject:(value ?: [NSNull null]) forKey:name];
764 - (bool) cy$deleteProperty:(NSString *)name {
765 if ([self objectForKey:name] == nil)
768 [self removeObjectForKey:name];
775 @implementation NSNumber (Cycript)
777 - (JSType) cy$JSType {
778 // XXX: this just seems stupid
779 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
782 - (NSObject *) cy$toJSON:(NSString *)key {
786 - (NSString *) cy$toCYON {
787 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
790 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
791 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
794 - (void *) cy$symbol {
795 return [self pointerValue];
800 @implementation NSString (Cycript)
802 - (JSType) cy$JSType {
803 return kJSTypeString;
806 - (NSObject *) cy$toJSON:(NSString *)key {
810 - (NSString *) cy$toCYON {
811 // XXX: this should use the better code from Output.cpp
812 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
814 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
815 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
816 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
817 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
818 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
820 CFStringInsert(json, 0, CFSTR("\""));
821 CFStringAppend(json, CFSTR("\""));
823 return [reinterpret_cast<const NSString *>(json) autorelease];
826 - (NSString *) cy$toKey {
827 const char *value([self UTF8String]);
828 size_t size(strlen(value));
833 if (DigitRange_[value[0]]) {
835 if (!CYGetIndex(NULL, self, index) || index < 0)
838 if (!WordStartRange_[value[0]])
840 for (size_t i(1); i != size; ++i)
841 if (!WordEndRange_[value[i]])
848 return [self cy$toCYON];
851 - (void *) cy$symbol {
853 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
858 @interface CYJSObject : NSDictionary {
860 JSContextRef context_;
863 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
865 - (NSString *) cy$toJSON:(NSString *)key;
867 - (NSUInteger) count;
868 - (id) objectForKey:(id)key;
869 - (NSEnumerator *) keyEnumerator;
870 - (void) setObject:(id)object forKey:(id)key;
871 - (void) removeObjectForKey:(id)key;
875 @interface CYJSArray : NSArray {
877 JSContextRef context_;
880 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
882 - (NSUInteger) count;
883 - (id) objectAtIndex:(NSUInteger)index;
887 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
888 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
889 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
891 JSGlobalContextRef CYGetJSContext() {
898 @catch (id error) { \
899 CYThrow(context, error, exception); \
903 void CYThrow(JSContextRef context, JSValueRef value);
905 apr_status_t CYPoolRelease_(void *data) {
906 id object(reinterpret_cast<id>(data));
911 id CYPoolRelease(apr_pool_t *pool, id object) {
914 else if (pool == NULL)
915 return [object autorelease];
917 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
922 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
923 return (CFTypeRef) CYPoolRelease(pool, (id) object);
926 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
927 JSValueRef exception(NULL);
928 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
929 CYThrow(context, exception);
930 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
931 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
934 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
935 if (!JSValueIsObjectOfClass(context, object, Instance_))
936 return CYCastNSObject_(pool, context, object);
938 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
939 return data->GetValue();
943 JSStringRef CYCopyJSString(id value) {
944 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
947 JSStringRef CYCopyJSString(const char *value) {
948 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
951 JSStringRef CYCopyJSString(JSStringRef value) {
952 return value == NULL ? NULL : JSStringRetain(value);
955 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
956 if (JSValueIsNull(context, value))
958 JSValueRef exception(NULL);
959 JSStringRef string(JSValueToStringCopy(context, value, &exception));
960 CYThrow(context, exception);
970 JSStringRelease(string_);
974 CYJSString(const CYJSString &rhs) :
975 string_(CYCopyJSString(rhs.string_))
979 template <typename Arg0_>
980 CYJSString(Arg0_ arg0) :
981 string_(CYCopyJSString(arg0))
985 template <typename Arg0_, typename Arg1_>
986 CYJSString(Arg0_ arg0, Arg1_ arg1) :
987 string_(CYCopyJSString(arg0, arg1))
991 CYJSString &operator =(const CYJSString &rhs) {
993 string_ = CYCopyJSString(rhs.string_);
1006 operator JSStringRef() const {
1011 CFStringRef CYCopyCFString(JSStringRef value) {
1012 return JSStringCopyCFString(kCFAllocatorDefault, value);
1015 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
1016 return CYCopyCFString(CYJSString(context, value));
1019 double CYCastDouble(const char *value, size_t size) {
1021 double number(strtod(value, &end));
1022 if (end != value + size)
1027 double CYCastDouble(const char *value) {
1028 return CYCastDouble(value, strlen(value));
1031 double CYCastDouble(JSContextRef context, JSValueRef value) {
1032 JSValueRef exception(NULL);
1033 double number(JSValueToNumber(context, value, &exception));
1034 CYThrow(context, exception);
1038 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1039 double number(CYCastDouble(context, value));
1040 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1043 CFStringRef CYCopyCFString(const char *value) {
1044 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1047 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1048 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1051 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1052 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1055 bool CYCastBool(JSContextRef context, JSValueRef value) {
1056 return JSValueToBoolean(context, value);
1059 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1063 switch (JSType type = JSValueGetType(context, value)) {
1064 case kJSTypeUndefined:
1065 object = [WebUndefined undefined];
1073 case kJSTypeBoolean:
1074 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1079 object = CYCopyCFNumber(context, value);
1084 object = CYCopyCFString(context, value);
1089 // XXX: this might could be more efficient
1090 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1095 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1102 return CYPoolRelease(pool, object);
1104 return CFRetain(object);
1107 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1108 return CYCFType(pool, context, value, true);
1111 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1112 return CYCFType(pool, context, value, false);
1115 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1117 size_t size(JSPropertyNameArrayGetCount(names));
1118 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1119 for (size_t index(0); index != size; ++index)
1120 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1124 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1125 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1128 void CYThrow(JSContextRef context, JSValueRef value) {
1131 @throw CYCastNSObject(NULL, context, value);
1134 JSValueRef CYJSNull(JSContextRef context) {
1135 return JSValueMakeNull(context);
1138 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1139 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1142 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1143 return CYCastJSValue(context, CYJSString(value));
1146 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1147 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context];
1150 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1151 JSValueRef exception(NULL);
1152 JSObjectRef object(JSValueToObject(context, value, &exception));
1153 CYThrow(context, exception);
1157 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1158 JSValueRef exception(NULL);
1159 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1160 CYThrow(context, exception);
1164 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1165 JSValueRef exception(NULL);
1166 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1167 CYThrow(context, exception);
1171 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1172 JSValueRef exception(NULL);
1173 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1174 CYThrow(context, exception);
1177 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1178 if (exception == NULL)
1180 *exception = CYCastJSValue(context, error);
1183 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1184 JSValueRef exception(NULL);
1185 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1186 CYThrow(context, exception);
1190 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1191 // XXX: this isn't actually correct
1192 return value != NULL && JSValueIsObject(context, value);
1195 @implementation CYJSObject
1197 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1198 if ((self = [super init]) != nil) {
1204 - (NSObject *) cy$toJSON:(NSString *)key {
1205 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1206 if (!CYIsCallable(context_, toJSON))
1207 return [super cy$toJSON:key];
1209 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1210 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1211 // XXX: do I really want an NSNull here?!
1212 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1216 - (NSString *) cy$toCYON {
1217 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1218 if (!CYIsCallable(context_, toCYON))
1219 return [super cy$toCYON];
1221 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1222 return CYCastNSString(NULL, CYJSString(context_, value));
1226 - (NSUInteger) count {
1227 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1228 size_t size(JSPropertyNameArrayGetCount(names));
1229 JSPropertyNameArrayRelease(names);
1233 - (id) objectForKey:(id)key {
1234 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1237 - (NSEnumerator *) keyEnumerator {
1238 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1239 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1240 JSPropertyNameArrayRelease(names);
1244 - (void) setObject:(id)object forKey:(id)key {
1245 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1248 - (void) removeObjectForKey:(id)key {
1249 JSValueRef exception(NULL);
1250 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1251 CYThrow(context_, exception);
1256 @implementation CYJSArray
1258 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1259 if ((self = [super init]) != nil) {
1265 - (NSUInteger) count {
1266 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1269 - (id) objectAtIndex:(NSUInteger)index {
1270 JSValueRef exception(NULL);
1271 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1272 CYThrow(context_, exception);
1273 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1278 CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1281 id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1282 return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
1287 const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1288 if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
1289 const char *string(CYPoolCString(pool, json));
1295 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1299 NSString *self(CYCastNSObject(pool, context, object));
1300 NSString *name(CYCastNSString(pool, property));
1303 if (NSObject *data = [self cy$getProperty:name])
1304 return CYCastJSValue(context, data);
1307 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1308 PropertyAttributes attributes(property);
1309 SEL sel(sel_registerName(attributes.Getter()));
1310 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
1317 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1321 NSString *self(CYCastNSObject(pool, context, object));
1322 NSString *name(CYCastNSString(pool, property));
1323 NSString *data(CYCastNSObject(pool, context, value));
1326 if ([self cy$setProperty:name to:data])
1330 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1331 PropertyAttributes attributes(property);
1332 if (const char *setter = attributes.Setter()) {
1333 SEL sel(sel_registerName(setter));
1334 JSValueRef arguments[1] = {value};
1335 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
1344 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1347 NSString *self(CYCastNSObject(NULL, context, object));
1348 NSString *name(CYCastNSString(NULL, property));
1349 return [self cy$deleteProperty:name];
1354 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1356 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1357 JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
1362 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1363 Selector_privateData *data(new Selector_privateData(sel));
1364 return JSObjectMake(context, Selector_, data);
1367 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, JSObjectRef owner) {
1368 Pointer *data(new Pointer(pointer, type, owner));
1369 return JSObjectMake(context, Pointer_, data);
1372 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1373 Functor_privateData *data(new Functor_privateData(type, function));
1374 return JSObjectMake(context, Functor_, data);
1377 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1379 const char *string([CYCastNSString(NULL, value) UTF8String]);
1381 *length = strlen(string);
1384 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1385 char *string(new(pool) char[size]);
1386 JSStringGetUTF8CString(value, string, size);
1387 // XXX: this is ironic
1389 *length = strlen(string);
1394 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1395 if (!JSValueIsNull(context, value))
1396 return CYPoolCString(pool, CYJSString(context, value), length);
1404 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1405 return CYGetIndex(CYPoolCString(pool, value), index);
1408 // XXX: this macro is unhygenic
1409 #define CYCastCString(context, value) ({ \
1411 if (value == NULL) \
1413 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1414 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1415 utf8 = reinterpret_cast<char *>(alloca(size)); \
1416 JSStringGetUTF8CString(string, utf8, size); \
1417 JSStringRelease(string); \
1423 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1424 switch (JSValueGetType(context, value)) {
1427 /*case kJSTypeString:
1428 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1430 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1431 Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1432 return data->value_;
1435 double number(CYCastDouble(context, value));
1436 if (std::isnan(number))
1437 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1438 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1442 template <typename Type_>
1443 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1444 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1447 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1448 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1449 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1450 return reinterpret_cast<SEL>(data->value_);
1452 return CYCastPointer<SEL>(context, value);
1455 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1456 switch (type->primitive) {
1457 case sig::boolean_P:
1458 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1461 #define CYPoolFFI_(primitive, native) \
1462 case sig::primitive ## _P: \
1463 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1466 CYPoolFFI_(uchar, unsigned char)
1467 CYPoolFFI_(char, char)
1468 CYPoolFFI_(ushort, unsigned short)
1469 CYPoolFFI_(short, short)
1470 CYPoolFFI_(ulong, unsigned long)
1471 CYPoolFFI_(long, long)
1472 CYPoolFFI_(uint, unsigned int)
1473 CYPoolFFI_(int, int)
1474 CYPoolFFI_(ulonglong, unsigned long long)
1475 CYPoolFFI_(longlong, long long)
1476 CYPoolFFI_(float, float)
1477 CYPoolFFI_(double, double)
1480 case sig::typename_P:
1481 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1484 case sig::selector_P:
1485 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1488 case sig::pointer_P:
1489 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1493 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1496 case sig::struct_P: {
1497 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1498 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1499 for (size_t index(0); index != type->data.signature.count; ++index) {
1500 sig::Element *element(&type->data.signature.elements[index]);
1501 ffi_type *field(ffi->elements[index]);
1504 if (aggregate == NULL)
1507 rhs = CYGetProperty(context, aggregate, index);
1508 if (JSValueIsUndefined(context, rhs)) {
1509 if (element->name != NULL)
1510 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1513 if (JSValueIsUndefined(context, rhs)) undefined:
1514 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1518 CYPoolFFI(pool, context, element->type, field, base, rhs);
1520 base += field->size;
1528 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1533 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner = NULL) {
1536 switch (type->primitive) {
1537 case sig::boolean_P:
1538 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1541 #define CYFromFFI_(primitive, native) \
1542 case sig::primitive ## _P: \
1543 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1546 CYFromFFI_(uchar, unsigned char)
1547 CYFromFFI_(char, char)
1548 CYFromFFI_(ushort, unsigned short)
1549 CYFromFFI_(short, short)
1550 CYFromFFI_(ulong, unsigned long)
1551 CYFromFFI_(long, long)
1552 CYFromFFI_(uint, unsigned int)
1553 CYFromFFI_(int, int)
1554 CYFromFFI_(ulonglong, unsigned long long)
1555 CYFromFFI_(longlong, long long)
1556 CYFromFFI_(float, float)
1557 CYFromFFI_(double, double)
1559 case sig::object_P: {
1560 if (id object = *reinterpret_cast<id *>(data)) {
1561 value = CYCastJSValue(context, object);
1567 case sig::typename_P:
1568 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1571 case sig::selector_P:
1572 if (SEL sel = *reinterpret_cast<SEL *>(data))
1573 value = CYMakeSelector(context, sel);
1577 case sig::pointer_P:
1578 if (void *pointer = *reinterpret_cast<void **>(data))
1579 value = CYMakePointer(context, pointer, type->data.data.type, owner);
1584 if (char *utf8 = *reinterpret_cast<char **>(data))
1585 value = CYCastJSValue(context, utf8);
1590 value = CYMakeStruct(context, data, type, ffi, owner);
1594 value = CYJSUndefined(context);
1598 value = CYJSNull(context);
1602 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1609 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1610 Type_privateData *typical(internal->type_);
1611 sig::Type *type(typical->type_);
1616 const char *name(CYPoolCString(pool, property, &length));
1617 double number(CYCastDouble(name, length));
1619 size_t count(type->data.signature.count);
1621 if (std::isnan(number)) {
1622 if (property == NULL)
1625 sig::Element *elements(type->data.signature.elements);
1627 for (size_t local(0); local != count; ++local) {
1628 sig::Element *element(&elements[local]);
1629 if (element->name != NULL && strcmp(name, element->name) == 0) {
1637 index = static_cast<ssize_t>(number);
1638 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
1643 ffi_type **elements(typical->GetFFI()->elements);
1645 base = reinterpret_cast<uint8_t *>(internal->value_);
1646 for (ssize_t local(0); local != index; ++local)
1647 base += elements[local]->size;
1652 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1654 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1655 Type_privateData *typical(internal->type_);
1657 if (typical->type_ == NULL)
1661 if (!CYGetIndex(pool, property, index))
1664 ffi_type *ffi(typical->GetFFI());
1666 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1667 base += ffi->size * index;
1669 JSObjectRef owner(internal->owner_ ?: object);
1672 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
1676 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1678 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1679 Type_privateData *typical(internal->type_);
1681 if (typical->type_ == NULL)
1685 if (!CYGetIndex(pool, property, index))
1688 ffi_type *ffi(typical->GetFFI());
1690 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1691 base += ffi->size * index;
1694 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
1699 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1701 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1702 Type_privateData *typical(internal->type_);
1707 if (!Index_(pool, internal, property, index, base))
1710 JSObjectRef owner(internal->owner_ ?: object);
1713 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
1717 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1719 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1720 Type_privateData *typical(internal->type_);
1725 if (!Index_(pool, internal, property, index, base))
1729 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
1734 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1735 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1736 Type_privateData *typical(internal->type_);
1737 sig::Type *type(typical->type_);
1742 size_t count(type->data.signature.count);
1743 sig::Element *elements(type->data.signature.elements);
1747 for (size_t index(0); index != count; ++index) {
1749 name = elements[index].name;
1752 sprintf(number, "%lu", index);
1756 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1760 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)()) {
1762 if (setups + count != signature->count - 1)
1763 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1765 size_t size(setups + count);
1767 memcpy(values, setup, sizeof(void *) * setups);
1769 for (size_t index(setups); index != size; ++index) {
1770 sig::Element *element(&signature->elements[index + 1]);
1771 ffi_type *ffi(cif->arg_types[index]);
1773 values[index] = new(pool) uint8_t[ffi->size];
1774 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1777 uint8_t value[cif->rtype->size];
1778 ffi_call(cif, function, value, values);
1780 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
1784 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1785 ffoData *data(reinterpret_cast<ffoData *>(arg));
1787 JSContextRef context(data->context_);
1789 size_t count(data->cif_.nargs);
1790 JSValueRef values[count];
1792 for (size_t index(0); index != count; ++index)
1793 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index], false);
1795 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1796 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1799 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1800 // XXX: in case of exceptions this will leak
1801 ffoData *data(new ffoData(type));
1803 ffi_closure *closure;
1804 _syscall(closure = (ffi_closure *) mmap(
1805 NULL, sizeof(ffi_closure),
1806 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1810 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1811 _assert(status == FFI_OK);
1813 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1815 data->value_ = closure;
1817 data->context_ = CYGetJSContext();
1818 data->function_ = function;
1820 return JSObjectMake(context, Functor_, data);
1823 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1826 NSString *name(CYCastNSString(pool, property));
1827 if (Class _class = NSClassFromString(name))
1828 return CYMakeInstance(context, _class, true);
1829 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1830 switch ([[entry objectAtIndex:0] intValue]) {
1832 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1834 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1836 // XXX: this is horrendously inefficient
1837 sig::Signature signature;
1838 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
1840 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1841 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol], false);
1847 bool stret(ffi_type *ffi_type) {
1848 return ffi_type->type == FFI_TYPE_STRUCT && (
1849 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1850 struct_forward_array[ffi_type->size] != 0
1855 int *_NSGetArgc(void);
1856 char ***_NSGetArgv(void);
1857 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1860 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1862 NSLog(@"%s", CYCastCString(context, arguments[0]));
1863 return CYJSUndefined(context);
1867 static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1871 int argc(CYCastDouble(context, arguments[0]));
1872 char **argv(CYCastPointer<char **>(context, arguments[1]));
1873 NSString *principal(CYCastNSObject(pool, context, arguments[2]));
1874 NSString *delegate(CYCastNSObject(pool, context, arguments[3]));
1876 argc = *_NSGetArgc() - 1;
1877 argv = *_NSGetArgv() + 1;
1878 for (int i(0); i != argc; ++i)
1879 NSLog(@"argv[%i]=%s", i, argv[i]);
1882 return CYCastJSValue(context, UIApplicationMain(argc, argv, principal, delegate));
1886 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
1889 Class _class(object_getClass(self));
1890 if (Method method = class_getInstanceMethod(_class, _cmd))
1891 type = method_getTypeEncoding(method);
1894 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1896 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1897 type = CYPoolCString(pool, [method _typeString]);
1905 sig::Signature signature;
1906 sig::Parse(pool, &signature, type, &Structor_);
1909 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1911 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1912 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
1915 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1925 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1927 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
1928 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
1929 self = data->GetValue();
1930 uninitialized = data->IsUninitialized();
1934 self = CYCastNSObject(pool, context, arguments[0]);
1935 uninitialized = false;
1939 return CYJSNull(context);
1941 _cmd = CYCastSEL(context, arguments[1]);
1944 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
1947 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1948 JSValueRef setup[count + 2];
1951 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
1952 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1955 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1957 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1958 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1961 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1964 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1965 const char *name(CYCastCString(context, arguments[0]));
1966 return CYMakeSelector(context, sel_registerName(name));
1970 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1973 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1974 const char *type(CYCastCString(context, arguments[1]));
1975 JSValueRef exception(NULL);
1976 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1977 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1978 return CYMakeFunctor(context, function, type);
1979 } else if (exception != NULL) {
1982 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1983 return CYMakeFunctor(context, function, type);
1988 JSValueRef CYData_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1989 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
1990 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1993 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1997 static JSValueRef CYData_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1999 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(_this)));
2000 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
2004 static JSValueRef CYData_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2005 return CYData_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
2008 static JSValueRef CYData_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2010 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(_this)));
2012 sprintf(string, "%p", data->value_);
2013 return CYCastJSValue(context, string);
2017 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2019 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2021 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toCYON]));
2026 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2028 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2030 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
2031 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toJSON:key]));
2036 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2038 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2040 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
2045 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2047 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2048 return CYCastJSValue(context, sel_getName(data->GetValue()));
2052 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2053 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2056 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2058 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2059 const char *name(sel_getName(data->GetValue()));
2061 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
2066 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2069 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
2071 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2072 Class _class(CYCastNSObject(pool, context, arguments[0]));
2073 bool instance(CYCastBool(context, arguments[1]));
2074 SEL sel(data->GetValue());
2075 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
2076 return CYCastJSValue(context, method_getTypeEncoding(method));
2077 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2078 return CYCastJSValue(context, CYJSString(type));
2080 return CYJSNull(context);
2084 static JSStaticValue CYData_staticValues[2] = {
2085 {"value", &CYData_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2086 {NULL, NULL, NULL, 0}
2089 static JSStaticFunction Pointer_staticFunctions[4] = {
2090 {"toCYON", &CYData_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2091 {"toJSON", &CYData_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2092 {"valueOf", &CYData_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2096 static JSStaticFunction Functor_staticFunctions[4] = {
2097 {"toCYON", &CYData_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2098 {"toJSON", &CYData_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2099 {"valueOf", &CYData_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2103 /*static JSStaticValue Selector_staticValues[2] = {
2104 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2105 {NULL, NULL, NULL, 0}
2108 static JSStaticFunction Instance_staticFunctions[4] = {
2109 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2110 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2111 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2115 static JSStaticFunction Selector_staticFunctions[5] = {
2116 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2117 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2118 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2119 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2123 CYDriver::CYDriver(const std::string &filename) :
2127 filename_(filename),
2133 CYDriver::~CYDriver() {
2137 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
2138 CYDriver::Error error;
2139 error.location_ = location;
2140 error.message_ = message;
2141 driver.errors_.push_back(error);
2144 void CYSetArgs(int argc, const char *argv[]) {
2145 JSContextRef context(CYGetJSContext());
2146 JSValueRef args[argc];
2147 for (int i(0); i != argc; ++i)
2148 args[i] = CYCastJSValue(context, argv[i]);
2149 JSValueRef exception(NULL);
2150 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
2151 CYThrow(context, exception);
2152 CYSetProperty(context, System_, CYJSString("args"), array);
2155 JSObjectRef CYGetGlobalObject(JSContextRef context) {
2156 return JSContextGetGlobalObject(context);
2159 MSInitialize { _pooled
2162 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
2164 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2166 JSClassDefinition definition;
2168 definition = kJSClassDefinitionEmpty;
2169 definition.className = "Pointer";
2170 definition.staticFunctions = Pointer_staticFunctions;
2171 definition.getProperty = &Pointer_getProperty;
2172 definition.setProperty = &Pointer_setProperty;
2173 definition.finalize = &CYData::Finalize;
2174 Pointer_ = JSClassCreate(&definition);
2176 definition = kJSClassDefinitionEmpty;
2177 definition.className = "Functor";
2178 definition.staticFunctions = Functor_staticFunctions;
2179 definition.callAsFunction = &Functor_callAsFunction;
2180 definition.finalize = &CYData::Finalize;
2181 Functor_ = JSClassCreate(&definition);
2183 definition = kJSClassDefinitionEmpty;
2184 definition.className = "Struct";
2185 definition.getProperty = &Struct_getProperty;
2186 definition.setProperty = &Struct_setProperty;
2187 definition.getPropertyNames = &Struct_getPropertyNames;
2188 definition.finalize = &CYData::Finalize;
2189 Struct_ = JSClassCreate(&definition);
2191 definition = kJSClassDefinitionEmpty;
2192 definition.className = "Selector";
2193 definition.staticValues = CYData_staticValues;
2194 //definition.staticValues = Selector_staticValues;
2195 definition.staticFunctions = Selector_staticFunctions;
2196 definition.callAsFunction = &Selector_callAsFunction;
2197 definition.finalize = &CYData::Finalize;
2198 Selector_ = JSClassCreate(&definition);
2200 definition = kJSClassDefinitionEmpty;
2201 definition.className = "Instance";
2202 definition.staticValues = CYData_staticValues;
2203 definition.staticFunctions = Instance_staticFunctions;
2204 definition.getProperty = &Instance_getProperty;
2205 definition.setProperty = &Instance_setProperty;
2206 definition.deleteProperty = &Instance_deleteProperty;
2207 definition.callAsConstructor = &Instance_callAsConstructor;
2208 definition.finalize = &CYData::Finalize;
2209 Instance_ = JSClassCreate(&definition);
2211 definition = kJSClassDefinitionEmpty;
2212 definition.className = "Runtime";
2213 definition.getProperty = &Runtime_getProperty;
2214 Runtime_ = JSClassCreate(&definition);
2216 definition = kJSClassDefinitionEmpty;
2217 //definition.getProperty = &Global_getProperty;
2218 JSClassRef Global(JSClassCreate(&definition));
2220 JSGlobalContextRef context(JSGlobalContextCreate(Global));
2223 JSObjectRef global(CYGetGlobalObject(context));
2225 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
2226 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
2228 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
2229 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
2231 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
2232 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
2234 System_ = JSObjectMake(context, NULL, NULL);
2235 CYSetProperty(context, global, CYJSString("system"), System_);
2236 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
2237 //CYSetProperty(context, System_, CYJSString("global"), global);
2239 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
2241 length_ = JSStringCreateWithUTF8CString("length");
2242 message_ = JSStringCreateWithUTF8CString("message");
2243 name_ = JSStringCreateWithUTF8CString("name");
2244 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
2245 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
2247 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
2248 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));