1 /* Cycript - Remove Execution Server and Disassembler
 
   2  * Copyright (C) 2009  Jay Freeman (saurik)
 
   5 /* Modified BSD License {{{ */
 
   7  *        Redistribution and use in source and binary
 
   8  * forms, with or without modification, are permitted
 
   9  * provided that the following conditions are met:
 
  11  * 1. Redistributions of source code must retain the
 
  12  *    above copyright notice, this list of conditions
 
  13  *    and the following disclaimer.
 
  14  * 2. Redistributions in binary form must reproduce the
 
  15  *    above copyright notice, this list of conditions
 
  16  *    and the following disclaimer in the documentation
 
  17  *    and/or other materials provided with the
 
  19  * 3. The name of the author may not be used to endorse
 
  20  *    or promote products derived from this software
 
  21  *    without specific prior written permission.
 
  23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
 
  24  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
 
  25  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 
  26  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 
  27  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
 
  28  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 
  29  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 
  30  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 
  31  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 
  32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 
  33  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 
  34  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 
  35  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 
  36  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
  42 #include <substrate.h>
 
  43 #include "cycript.hpp"
 
  45 #include "sig/parse.hpp"
 
  46 #include "sig/ffi_type.hpp"
 
  48 #include "Pooling.hpp"
 
  53 #include <CoreFoundation/CoreFoundation.h>
 
  54 #include <CoreFoundation/CFLogUtilities.h>
 
  56 #include <WebKit/WebScriptObject.h>
 
  58 #include <sys/types.h>
 
  59 #include <sys/socket.h>
 
  60 #include <netinet/in.h>
 
  66 #include <ext/stdio_filebuf.h>
 
  74 #include "Cycript.tab.hh"
 
  78 #include <apr-1/apr_thread_proc.h>
 
  83 #define _assert(test) do { \
 
  85         @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
 
  88 #define _trace() do { \
 
  89     CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
 
  94     NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
 
  96 #define CYPoolCatch(value) \
 
  97     @catch (NSException *error) { \
 
  98         _saved = [error retain]; \
 
 104             [_saved autorelease]; \
 
 108 static JSGlobalContextRef Context_;
 
 109 static JSObjectRef System_;
 
 111 static JSClassRef Functor_;
 
 112 static JSClassRef Instance_;
 
 113 static JSClassRef Pointer_;
 
 114 static JSClassRef Runtime_;
 
 115 static JSClassRef Selector_;
 
 116 static JSClassRef Struct_;
 
 117 static JSClassRef Type_;
 
 119 static JSObjectRef Array_;
 
 120 static JSObjectRef Function_;
 
 122 static JSStringRef Result_;
 
 124 static JSStringRef length_;
 
 125 static JSStringRef message_;
 
 126 static JSStringRef name_;
 
 127 static JSStringRef toCYON_;
 
 128 static JSStringRef toJSON_;
 
 130 static Class NSCFBoolean_;
 
 132 static NSArray *Bridge_;
 
 140     static void *operator new(size_t size, apr_pool_t *pool) {
 
 141         void *data(apr_palloc(pool, size));
 
 142         reinterpret_cast<CYData *>(data)->pool_ = pool;
 
 146     static void *operator new(size_t size) {
 
 148         apr_pool_create(&pool, NULL);
 
 149         return operator new(size, pool);
 
 152     static void operator delete(void *data) {
 
 153         apr_pool_destroy(reinterpret_cast<CYData *>(data)->pool_);
 
 156     static void Finalize(JSObjectRef object) {
 
 157         delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
 
 169     CYValue(void *value) :
 
 175 struct Selector_privateData :
 
 178     Selector_privateData(SEL value) :
 
 183     SEL GetValue() const {
 
 184         return reinterpret_cast<SEL>(value_);
 
 193         Transient     = (1 << 0),
 
 194         Uninitialized = (1 << 1),
 
 199     Instance(id value, Flags flags) :
 
 205     virtual ~Instance() {
 
 206         if ((flags_ & Transient) == 0)
 
 207             // XXX: does this handle background threads correctly?
 
 208             [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
 
 211     static JSObjectRef Make(JSContextRef context, id object, Flags flags) {
 
 212         return JSObjectMake(context, Instance_, new Instance(object, flags));
 
 215     id GetValue() const {
 
 216         return reinterpret_cast<id>(value_);
 
 219     bool IsUninitialized() const {
 
 220         return (flags_ & Uninitialized) != 0;
 
 226 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
 
 228 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
 
 229     lhs.name = apr_pstrdup(pool, rhs.name);
 
 230     if (rhs.type == NULL)
 
 233         lhs.type = new(pool) Type;
 
 234         Copy(pool, *lhs.type, *rhs.type);
 
 236     lhs.offset = rhs.offset;
 
 239 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
 
 240     size_t count(rhs.count);
 
 242     lhs.elements = new(pool) Element[count];
 
 243     for (size_t index(0); index != count; ++index)
 
 244         Copy(pool, lhs.elements[index], rhs.elements[index]);
 
 247 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
 
 248     lhs.primitive = rhs.primitive;
 
 249     lhs.name = apr_pstrdup(pool, rhs.name);
 
 250     lhs.flags = rhs.flags;
 
 252     if (sig::IsAggregate(rhs.primitive))
 
 253         Copy(pool, lhs.data.signature, rhs.data.signature);
 
 255         if (rhs.data.data.type != NULL) {
 
 256             lhs.data.data.type = new(pool) Type;
 
 257             Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
 
 260         lhs.data.data.size = rhs.data.data.size;
 
 264 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
 
 266     lhs.alignment = rhs.alignment;
 
 268     if (rhs.elements == NULL)
 
 272         while (rhs.elements[count] != NULL)
 
 275         lhs.elements = new(pool) ffi_type *[count + 1];
 
 276         lhs.elements[count] = NULL;
 
 278         for (size_t index(0); index != count; ++index) {
 
 279             // XXX: if these are libffi native then you can just take them
 
 280             ffi_type *ffi(new(pool) ffi_type);
 
 281             lhs.elements[index] = ffi;
 
 282             sig::Copy(pool, *ffi, *rhs.elements[index]);
 
 289 struct CStringMapLess :
 
 290     std::binary_function<const char *, const char *, bool>
 
 292     _finline bool operator ()(const char *lhs, const char *rhs) const {
 
 293         return strcmp(lhs, rhs) < 0;
 
 297 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
 
 302         if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
 
 303             switch ([[entry objectAtIndex:0] intValue]) {
 
 305                     sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
 
 309                     sig::Signature signature;
 
 310                     sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
 
 311                     type = signature.elements[0].type;
 
 317 struct Type_privateData :
 
 323     void Set(sig::Type *type) {
 
 324         type_ = new(pool_) sig::Type;
 
 325         sig::Copy(pool_, *type_, *type);
 
 328     Type_privateData(const char *type) :
 
 331         sig::Signature signature;
 
 332         sig::Parse(pool_, &signature, type, &Structor_);
 
 333         type_ = signature.elements[0].type;
 
 336     Type_privateData(sig::Type *type) :
 
 343     Type_privateData(sig::Type *type, ffi_type *ffi) {
 
 344         ffi_ = new(pool_) ffi_type;
 
 345         sig::Copy(pool_, *ffi_, *ffi);
 
 351             ffi_ = new(pool_) ffi_type;
 
 353             sig::Element element;
 
 355             element.type = type_;
 
 358             sig::Signature signature;
 
 359             signature.elements = &element;
 
 363             sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
 
 375     Type_privateData *type_;
 
 377     Pointer(void *value, sig::Type *type, JSObjectRef owner) :
 
 380         type_(new(pool_) Type_privateData(type))
 
 385 struct Struct_privateData :
 
 389     Type_privateData *type_;
 
 391     Struct_privateData(JSObjectRef owner) :
 
 397 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
 
 398 static TypeMap Types_;
 
 400 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
 
 401     Struct_privateData *internal(new Struct_privateData(owner));
 
 402     apr_pool_t *pool(internal->pool_);
 
 403     Type_privateData *typical(new(pool) Type_privateData(type, ffi));
 
 404     internal->type_ = typical;
 
 407         internal->value_ = data;
 
 409         size_t size(typical->GetFFI()->size);
 
 410         void *copy(apr_palloc(internal->pool_, size));
 
 411         memcpy(copy, data, size);
 
 412         internal->value_ = copy;
 
 415     return JSObjectMake(context, Struct_, internal);
 
 418 struct Functor_privateData :
 
 421     sig::Signature signature_;
 
 424     Functor_privateData(const char *type, void (*value)()) :
 
 425         CYValue(reinterpret_cast<void *>(value))
 
 427         sig::Parse(pool_, &signature_, type, &Structor_);
 
 428         sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
 
 435     JSContextRef context_;
 
 436     JSObjectRef function_;
 
 438     ffoData(const char *type) :
 
 439         Functor_privateData(type, NULL)
 
 444 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
 
 445     Instance::Flags flags;
 
 448         flags = Instance::Transient;
 
 450         flags = Instance::None;
 
 451         object = [object retain];
 
 454     return Instance::Make(context, object, flags);
 
 457 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
 
 459         return [value UTF8String];
 
 461         size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
 
 462         char *string(new(pool) char[size]);
 
 463         if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
 
 464             @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
 
 469 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
 
 470     return JSValueMakeBoolean(context, value);
 
 473 JSValueRef CYCastJSValue(JSContextRef context, double value) {
 
 474     return JSValueMakeNumber(context, value);
 
 477 #define CYCastJSValue_(Type_) \
 
 478     JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
 
 479         return JSValueMakeNumber(context, static_cast<double>(value)); \
 
 483 CYCastJSValue_(unsigned int)
 
 484 CYCastJSValue_(long int)
 
 485 CYCastJSValue_(long unsigned int)
 
 486 CYCastJSValue_(long long int)
 
 487 CYCastJSValue_(long long unsigned int)
 
 489 JSValueRef CYJSUndefined(JSContextRef context) {
 
 490     return JSValueMakeUndefined(context);
 
 493 bool CYGetIndex(const char *value, ssize_t &index) {
 
 494     if (value[0] != '0') {
 
 496         index = strtol(value, &end, 10);
 
 497         if (value + strlen(value) == end)
 
 499     } else if (value[1] == '\0') {
 
 507 bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
 
 508     return CYGetIndex(CYPoolCString(pool, value), index);
 
 511 @interface NSMethodSignature (Cycript)
 
 512 - (NSString *) _typeString;
 
 515 @interface NSObject (Cycript)
 
 517 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
 
 518 - (JSType) cy$JSType;
 
 520 - (NSObject *) cy$toJSON:(NSString *)key;
 
 521 - (NSString *) cy$toCYON;
 
 522 - (NSString *) cy$toKey;
 
 524 - (NSObject *) cy$getProperty:(NSString *)name;
 
 525 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
 
 526 - (bool) cy$deleteProperty:(NSString *)name;
 
 531 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
 
 534 @interface NSString (Cycript)
 
 535 - (void *) cy$symbol;
 
 538 struct PropertyAttributes {
 
 543     const char *variable;
 
 556     PropertyAttributes(objc_property_t property) :
 
 568         name = property_getName(property);
 
 569         const char *attributes(property_getAttributes(property));
 
 571         for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
 
 573                 case 'R': readonly = true; break;
 
 574                 case 'C': copy = true; break;
 
 575                 case '&': retain = true; break;
 
 576                 case 'N': nonatomic = true; break;
 
 577                 case 'G': getter_ = token + 1; break;
 
 578                 case 'S': setter_ = token + 1; break;
 
 579                 case 'V': variable = token + 1; break;
 
 583         /*if (variable == NULL) {
 
 584             variable = property_getName(property);
 
 585             size_t size(strlen(variable));
 
 586             char *name(new(pool_) char[size + 2]);
 
 588             memcpy(name + 1, variable, size);
 
 589             name[size + 1] = '\0';
 
 594     const char *Getter() {
 
 596             getter_ = apr_pstrdup(pool_, name);
 
 600     const char *Setter() {
 
 601         if (setter_ == NULL && !readonly) {
 
 602             size_t length(strlen(name));
 
 604             char *temp(new(pool_) char[length + 5]);
 
 610                 temp[3] = toupper(name[0]);
 
 611                 memcpy(temp + 4, name + 1, length - 1);
 
 614             temp[length + 3] = ':';
 
 615             temp[length + 4] = '\0';
 
 624 @implementation NSObject (Cycript)
 
 626 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
 627     return CYMakeInstance(context, self, false);
 
 630 - (JSType) cy$JSType {
 
 631     return kJSTypeObject;
 
 634 - (NSObject *) cy$toJSON:(NSString *)key {
 
 635     return [self description];
 
 638 - (NSString *) cy$toCYON {
 
 639     return [[self cy$toJSON:@""] cy$toCYON];
 
 642 - (NSString *) cy$toKey {
 
 643     return [self cy$toCYON];
 
 646 - (NSObject *) cy$getProperty:(NSString *)name {
 
 647     /*if (![name isEqualToString:@"prototype"])
 
 648         NSLog(@"get:%@", name);*/
 
 652 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
 653     //NSLog(@"set:%@", name);
 
 657 - (bool) cy$deleteProperty:(NSString *)name {
 
 658     //NSLog(@"delete:%@", name);
 
 664 @implementation WebUndefined (Cycript)
 
 666 - (JSType) cy$JSType {
 
 667     return kJSTypeUndefined;
 
 670 - (NSObject *) cy$toJSON:(NSString *)key {
 
 674 - (NSString *) cy$toCYON {
 
 678 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
 679     return CYJSUndefined(context);
 
 684 @implementation NSNull (Cycript)
 
 686 - (JSType) cy$JSType {
 
 690 - (NSObject *) cy$toJSON:(NSString *)key {
 
 694 - (NSString *) cy$toCYON {
 
 700 @implementation NSArray (Cycript)
 
 702 - (NSString *) cy$toCYON {
 
 703     NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
 
 704     [json appendString:@"["];
 
 707     for (id object in self) {
 
 709             [json appendString:@","];
 
 712         if ([object cy$JSType] != kJSTypeUndefined)
 
 713             [json appendString:[object cy$toCYON]];
 
 715             [json appendString:@","];
 
 720     [json appendString:@"]"];
 
 724 - (NSObject *) cy$getProperty:(NSString *)name {
 
 725     if ([name isEqualToString:@"length"])
 
 726         return [NSNumber numberWithUnsignedInteger:[self count]];
 
 729     if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
 
 730         return [super cy$getProperty:name];
 
 732         return [self objectAtIndex:index];
 
 737 @implementation NSMutableArray (Cycript)
 
 739 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
 741     if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
 
 742         return [super cy$setProperty:name to:value];
 
 744         [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
 
 749 - (bool) cy$deleteProperty:(NSString *)name {
 
 751     if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
 
 752         return [super cy$deleteProperty:name];
 
 754         [self removeObjectAtIndex:index];
 
 761 @implementation NSDictionary (Cycript)
 
 763 - (NSString *) cy$toCYON {
 
 764     NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
 
 765     [json appendString:@"{"];
 
 768     for (id key in self) {
 
 770             [json appendString:@","];
 
 773         [json appendString:[key cy$toKey]];
 
 774         [json appendString:@":"];
 
 775         NSObject *object([self objectForKey:key]);
 
 776         [json appendString:[object cy$toCYON]];
 
 779     [json appendString:@"}"];
 
 783 - (NSObject *) cy$getProperty:(NSString *)name {
 
 784     return [self objectForKey:name];
 
 789 @implementation NSMutableDictionary (Cycript)
 
 791 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
 792     [self setObject:(value ?: [NSNull null]) forKey:name];
 
 796 - (bool) cy$deleteProperty:(NSString *)name {
 
 797     if ([self objectForKey:name] == nil)
 
 800         [self removeObjectForKey:name];
 
 807 @implementation NSNumber (Cycript)
 
 809 - (JSType) cy$JSType {
 
 810     // XXX: this just seems stupid
 
 811     return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
 
 814 - (NSObject *) cy$toJSON:(NSString *)key {
 
 818 - (NSString *) cy$toCYON {
 
 819     return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
 
 822 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
 823     return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
 
 828 @implementation NSString (Cycript)
 
 830 - (JSType) cy$JSType {
 
 831     return kJSTypeString;
 
 834 - (NSObject *) cy$toJSON:(NSString *)key {
 
 838 - (NSString *) cy$toCYON {
 
 839     // XXX: this should use the better code from Output.cpp
 
 840     CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
 
 842     CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
 
 843     CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
 
 844     CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
 
 845     CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
 
 846     CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
 
 848     CFStringInsert(json, 0, CFSTR("\""));
 
 849     CFStringAppend(json, CFSTR("\""));
 
 851     return [reinterpret_cast<const NSString *>(json) autorelease];
 
 854 - (NSString *) cy$toKey {
 
 855     const char *value([self UTF8String]);
 
 856     size_t size(strlen(value));
 
 861     if (DigitRange_[value[0]]) {
 
 863         if (!CYGetIndex(NULL, self, index) || index < 0)
 
 866         if (!WordStartRange_[value[0]])
 
 868         for (size_t i(1); i != size; ++i)
 
 869             if (!WordEndRange_[value[i]])
 
 876     return [self cy$toCYON];
 
 879 - (void *) cy$symbol {
 
 881     return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
 
 886 @interface CYJSObject : NSDictionary {
 
 888     JSContextRef context_;
 
 891 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
 
 893 - (NSString *) cy$toJSON:(NSString *)key;
 
 895 - (NSUInteger) count;
 
 896 - (id) objectForKey:(id)key;
 
 897 - (NSEnumerator *) keyEnumerator;
 
 898 - (void) setObject:(id)object forKey:(id)key;
 
 899 - (void) removeObjectForKey:(id)key;
 
 903 @interface CYJSArray : NSArray {
 
 905     JSContextRef context_;
 
 908 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
 
 910 - (NSUInteger) count;
 
 911 - (id) objectAtIndex:(NSUInteger)index;
 
 915 CYRange DigitRange_    (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
 
 916 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
 
 917 CYRange WordEndRange_  (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
 
 922     @catch (id error) { \
 
 923         CYThrow(context, error, exception); \
 
 927 void CYThrow(JSContextRef context, JSValueRef value);
 
 929 apr_status_t CYPoolRelease_(void *data) {
 
 930     id object(reinterpret_cast<id>(data));
 
 935 id CYPoolRelease(apr_pool_t *pool, id object) {
 
 938     else if (pool == NULL)
 
 939         return [object autorelease];
 
 941         apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
 
 946 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
 
 947     return (CFTypeRef) CYPoolRelease(pool, (id) object);
 
 950 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
 
 951     JSValueRef exception(NULL);
 
 952     bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
 
 953     CYThrow(context, exception);
 
 954     id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
 
 955     return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
 
 958 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
 
 959     if (!JSValueIsObjectOfClass(context, object, Instance_))
 
 960         return CYCastNSObject_(pool, context, object);
 
 962         Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
 963         return data->GetValue();
 
 967 JSStringRef CYCopyJSString(id value) {
 
 968     return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
 
 971 JSStringRef CYCopyJSString(const char *value) {
 
 972     return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
 
 975 JSStringRef CYCopyJSString(JSStringRef value) {
 
 976     return value == NULL ? NULL : JSStringRetain(value);
 
 979 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
 
 980     if (JSValueIsNull(context, value))
 
 982     JSValueRef exception(NULL);
 
 983     JSStringRef string(JSValueToStringCopy(context, value, &exception));
 
 984     CYThrow(context, exception);
 
 994             JSStringRelease(string_);
 
 998     CYJSString(const CYJSString &rhs) :
 
 999         string_(CYCopyJSString(rhs.string_))
 
1003     template <typename Arg0_>
 
1004     CYJSString(Arg0_ arg0) :
 
1005         string_(CYCopyJSString(arg0))
 
1009     template <typename Arg0_, typename Arg1_>
 
1010     CYJSString(Arg0_ arg0, Arg1_ arg1) :
 
1011         string_(CYCopyJSString(arg0, arg1))
 
1015     CYJSString &operator =(const CYJSString &rhs) {
 
1017         string_ = CYCopyJSString(rhs.string_);
 
1030     operator JSStringRef() const {
 
1035 CFStringRef CYCopyCFString(JSStringRef value) {
 
1036     return JSStringCopyCFString(kCFAllocatorDefault, value);
 
1039 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
 
1040     return CYCopyCFString(CYJSString(context, value));
 
1043 double CYCastDouble(const char *value, size_t size) {
 
1045     double number(strtod(value, &end));
 
1046     if (end != value + size)
 
1051 double CYCastDouble(const char *value) {
 
1052     return CYCastDouble(value, strlen(value));
 
1055 double CYCastDouble(JSContextRef context, JSValueRef value) {
 
1056     JSValueRef exception(NULL);
 
1057     double number(JSValueToNumber(context, value, &exception));
 
1058     CYThrow(context, exception);
 
1062 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
 
1063     double number(CYCastDouble(context, value));
 
1064     return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
 
1067 CFStringRef CYCopyCFString(const char *value) {
 
1068     return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
 
1071 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
 
1072     return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
 
1075 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
 
1076     return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
 
1079 bool CYCastBool(JSContextRef context, JSValueRef value) {
 
1080     return JSValueToBoolean(context, value);
 
1083 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
 
1087     switch (JSType type = JSValueGetType(context, value)) {
 
1088         case kJSTypeUndefined:
 
1089             object = [WebUndefined undefined];
 
1097         case kJSTypeBoolean:
 
1098             object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
 
1103             object = CYCopyCFNumber(context, value);
 
1108             object = CYCopyCFString(context, value);
 
1113             // XXX: this might could be more efficient
 
1114             object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
 
1119             @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
 
1126         return CYPoolRelease(pool, object);
 
1128         return CFRetain(object);
 
1131 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1132     return CYCFType(pool, context, value, true);
 
1135 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1136     return CYCFType(pool, context, value, false);
 
1139 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
 
1141     size_t size(JSPropertyNameArrayGetCount(names));
 
1142     NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
 
1143     for (size_t index(0); index != size; ++index)
 
1144         [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
 
1148 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1149     return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
 
1152 void CYThrow(JSContextRef context, JSValueRef value) {
 
1155     @throw CYCastNSObject(NULL, context, value);
 
1158 JSValueRef CYJSNull(JSContextRef context) {
 
1159     return JSValueMakeNull(context);
 
1162 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
 
1163     return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
 
1166 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
 
1167     return CYCastJSValue(context, CYJSString(value));
 
1170 JSValueRef CYCastJSValue(JSContextRef context, id value) {
 
1172         return CYJSNull(context);
 
1173     else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
 
1174         return [value cy$JSValueInContext:context];
 
1176         return CYMakeInstance(context, value, false);
 
1179 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
 
1180     JSValueRef exception(NULL);
 
1181     JSObjectRef object(JSValueToObject(context, value, &exception));
 
1182     CYThrow(context, exception);
 
1186 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
 
1187     JSValueRef exception(NULL);
 
1188     JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
 
1189     CYThrow(context, exception);
 
1193 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
 
1194     JSValueRef exception(NULL);
 
1195     JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
 
1196     CYThrow(context, exception);
 
1200 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
 
1201     JSValueRef exception(NULL);
 
1202     JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
 
1203     CYThrow(context, exception);
 
1206 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
 
1207     if (exception == NULL)
 
1209     *exception = CYCastJSValue(context, error);
 
1212 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
 
1213     JSValueRef exception(NULL);
 
1214     JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
 
1215     CYThrow(context, exception);
 
1219 bool CYIsCallable(JSContextRef context, JSValueRef value) {
 
1220     // XXX: this isn't actually correct
 
1221     return value != NULL && JSValueIsObject(context, value);
 
1224 @implementation CYJSObject
 
1226 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
 
1227     if ((self = [super init]) != nil) {
 
1233 - (NSObject *) cy$toJSON:(NSString *)key {
 
1234     JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
 
1235     if (!CYIsCallable(context_, toJSON))
 
1236         return [super cy$toJSON:key];
 
1238         JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
 
1239         JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
 
1240         // XXX: do I really want an NSNull here?!
 
1241         return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
 
1245 - (NSString *) cy$toCYON {
 
1246     JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
 
1247     if (!CYIsCallable(context_, toCYON))
 
1248         return [super cy$toCYON];
 
1250         JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
 
1251         return CYCastNSString(NULL, CYJSString(context_, value));
 
1255 - (NSUInteger) count {
 
1256     JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
 
1257     size_t size(JSPropertyNameArrayGetCount(names));
 
1258     JSPropertyNameArrayRelease(names);
 
1262 - (id) objectForKey:(id)key {
 
1263     return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
 
1266 - (NSEnumerator *) keyEnumerator {
 
1267     JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
 
1268     NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
 
1269     JSPropertyNameArrayRelease(names);
 
1273 - (void) setObject:(id)object forKey:(id)key {
 
1274     CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
 
1277 - (void) removeObjectForKey:(id)key {
 
1278     JSValueRef exception(NULL);
 
1279     (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
 
1280     CYThrow(context_, exception);
 
1285 @implementation CYJSArray
 
1287 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
 
1288     if ((self = [super init]) != nil) {
 
1294 - (NSUInteger) count {
 
1295     return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
 
1298 - (id) objectAtIndex:(NSUInteger)index {
 
1299     JSValueRef exception(NULL);
 
1300     JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
 
1301     CYThrow(context_, exception);
 
1302     return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
 
1307 CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
 
1310             id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
 
1311             return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
 
1316 const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
 
1317     if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
 
1318         const char *string(CYPoolCString(pool, json));
 
1324 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
 
1328     JSObjectRef object_;
 
1336         // XXX: delete object_? ;(
 
1339     static CYInternal *Get(id self) {
 
1340         CYInternal *internal(NULL);
 
1341         if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
 
1342             // XXX: do something epic? ;P
 
1348     static CYInternal *Set(id self) {
 
1349         CYInternal *internal(NULL);
 
1350         if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
 
1351             if (internal == NULL) {
 
1352                 internal = new CYInternal();
 
1353                 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
 
1356             // XXX: do something epic? ;P
 
1362     JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
 
1363         if (object_ == NULL)
 
1365         return CYGetProperty(context, object_, name);
 
1368     void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
 
1369         if (object_ == NULL)
 
1370             object_ = JSObjectMake(context, NULL, NULL);
 
1371         CYSetProperty(context, object_, name, value);
 
1375 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
1379         NSString *self(CYCastNSObject(pool, context, object));
 
1380         NSString *name(CYCastNSString(pool, property));
 
1382         if (CYInternal *internal = CYInternal::Get(self))
 
1383             if (JSValueRef value = internal->GetProperty(context, property))
 
1387             if (NSObject *data = [self cy$getProperty:name])
 
1388                 return CYCastJSValue(context, data);
 
1391         if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
 
1392             PropertyAttributes attributes(property);
 
1393             SEL sel(sel_registerName(attributes.Getter()));
 
1394             return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
 
1401 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
1405         NSString *self(CYCastNSObject(pool, context, object));
 
1406         NSString *name(CYCastNSString(pool, property));
 
1407         NSString *data(CYCastNSObject(pool, context, value));
 
1410             if ([self cy$setProperty:name to:data])
 
1414         if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
 
1415             PropertyAttributes attributes(property);
 
1416             if (const char *setter = attributes.Setter()) {
 
1417                 SEL sel(sel_registerName(setter));
 
1418                 JSValueRef arguments[1] = {value};
 
1419                 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
 
1424         if (CYInternal *internal = CYInternal::Set(self)) {
 
1425             internal->SetProperty(context, property, value);
 
1433 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
1436             NSString *self(CYCastNSObject(NULL, context, object));
 
1437             NSString *name(CYCastNSString(NULL, property));
 
1438             return [self cy$deleteProperty:name];
 
1443 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
1445         Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
1446         JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
 
1451 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
 
1452     Selector_privateData *data(new Selector_privateData(sel));
 
1453     return JSObjectMake(context, Selector_, data);
 
1456 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, JSObjectRef owner) {
 
1457     Pointer *data(new Pointer(pointer, type, owner));
 
1458     return JSObjectMake(context, Pointer_, data);
 
1461 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
 
1462     Functor_privateData *data(new Functor_privateData(type, function));
 
1463     return JSObjectMake(context, Functor_, data);
 
1466 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
 
1468         const char *string([CYCastNSString(NULL, value) UTF8String]);
 
1471         size_t size(JSStringGetMaximumUTF8CStringSize(value));
 
1472         char *string(new(pool) char[size]);
 
1473         JSStringGetUTF8CString(value, string, size);
 
1478 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1479     return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
 
1482 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
 
1483     return CYGetIndex(CYPoolCString(pool, value), index);
 
1486 // XXX: this macro is unhygenic
 
1487 #define CYCastCString(context, value) ({ \
 
1489     if (value == NULL) \
 
1491     else if (JSStringRef string = CYCopyJSString(context, value)) { \
 
1492         size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
 
1493         utf8 = reinterpret_cast<char *>(alloca(size)); \
 
1494         JSStringGetUTF8CString(string, utf8, size); \
 
1495         JSStringRelease(string); \
 
1501 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
 
1502     switch (JSValueGetType(context, value)) {
 
1505         /*case kJSTypeString:
 
1506             return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
 
1508             if (JSValueIsObjectOfClass(context, value, Pointer_)) {
 
1509                 Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
 
1510                 return data->value_;
 
1513             double number(CYCastDouble(context, value));
 
1514             if (std::isnan(number))
 
1515                 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
 
1516             return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
 
1520 template <typename Type_>
 
1521 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
 
1522     return reinterpret_cast<Type_>(CYCastPointer_(context, value));
 
1525 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
 
1526     if (JSValueIsObjectOfClass(context, value, Selector_)) {
 
1527         Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
 
1528         return reinterpret_cast<SEL>(data->value_);
 
1530         return CYCastPointer<SEL>(context, value);
 
1533 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
 
1534     switch (type->primitive) {
 
1535         case sig::boolean_P:
 
1536             *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
 
1539 #define CYPoolFFI_(primitive, native) \
 
1540         case sig::primitive ## _P: \
 
1541             *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
 
1544         CYPoolFFI_(uchar, unsigned char)
 
1545         CYPoolFFI_(char, char)
 
1546         CYPoolFFI_(ushort, unsigned short)
 
1547         CYPoolFFI_(short, short)
 
1548         CYPoolFFI_(ulong, unsigned long)
 
1549         CYPoolFFI_(long, long)
 
1550         CYPoolFFI_(uint, unsigned int)
 
1551         CYPoolFFI_(int, int)
 
1552         CYPoolFFI_(ulonglong, unsigned long long)
 
1553         CYPoolFFI_(longlong, long long)
 
1554         CYPoolFFI_(float, float)
 
1555         CYPoolFFI_(double, double)
 
1558         case sig::typename_P:
 
1559             *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
 
1562         case sig::selector_P:
 
1563             *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
 
1566         case sig::pointer_P:
 
1567             *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
 
1571             *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
 
1574         case sig::struct_P: {
 
1575             uint8_t *base(reinterpret_cast<uint8_t *>(data));
 
1576             JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
 
1577             for (size_t index(0); index != type->data.signature.count; ++index) {
 
1578                 sig::Element *element(&type->data.signature.elements[index]);
 
1579                 ffi_type *field(ffi->elements[index]);
 
1582                 if (aggregate == NULL)
 
1585                     rhs = CYGetProperty(context, aggregate, index);
 
1586                     if (JSValueIsUndefined(context, rhs)) {
 
1587                         if (element->name != NULL)
 
1588                             rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
 
1591                         if (JSValueIsUndefined(context, rhs)) undefined:
 
1592                             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
 
1596                 CYPoolFFI(pool, context, element->type, field, base, rhs);
 
1598                 base += field->size;
 
1606             NSLog(@"CYPoolFFI(%c)\n", type->primitive);
 
1611 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner = NULL) {
 
1614     switch (type->primitive) {
 
1615         case sig::boolean_P:
 
1616             value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
 
1619 #define CYFromFFI_(primitive, native) \
 
1620         case sig::primitive ## _P: \
 
1621             value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
 
1624         CYFromFFI_(uchar, unsigned char)
 
1625         CYFromFFI_(char, char)
 
1626         CYFromFFI_(ushort, unsigned short)
 
1627         CYFromFFI_(short, short)
 
1628         CYFromFFI_(ulong, unsigned long)
 
1629         CYFromFFI_(long, long)
 
1630         CYFromFFI_(uint, unsigned int)
 
1631         CYFromFFI_(int, int)
 
1632         CYFromFFI_(ulonglong, unsigned long long)
 
1633         CYFromFFI_(longlong, long long)
 
1634         CYFromFFI_(float, float)
 
1635         CYFromFFI_(double, double)
 
1637         case sig::object_P: {
 
1638             if (id object = *reinterpret_cast<id *>(data)) {
 
1639                 value = CYCastJSValue(context, object);
 
1645         case sig::typename_P:
 
1646             value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
 
1649         case sig::selector_P:
 
1650             if (SEL sel = *reinterpret_cast<SEL *>(data))
 
1651                 value = CYMakeSelector(context, sel);
 
1655         case sig::pointer_P:
 
1656             if (void *pointer = *reinterpret_cast<void **>(data))
 
1657                 value = CYMakePointer(context, pointer, type->data.data.type, owner);
 
1662             if (char *utf8 = *reinterpret_cast<char **>(data))
 
1663                 value = CYCastJSValue(context, utf8);
 
1668             value = CYMakeStruct(context, data, type, ffi, owner);
 
1672             value = CYJSUndefined(context);
 
1676             value = CYJSNull(context);
 
1680             NSLog(@"CYFromFFI(%c)\n", type->primitive);
 
1687 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
 
1688     Type_privateData *typical(internal->type_);
 
1689     sig::Type *type(typical->type_);
 
1693     const char *name(CYPoolCString(pool, property));
 
1694     size_t length(strlen(name));
 
1695     double number(CYCastDouble(name, length));
 
1697     size_t count(type->data.signature.count);
 
1699     if (std::isnan(number)) {
 
1700         if (property == NULL)
 
1703         sig::Element *elements(type->data.signature.elements);
 
1705         for (size_t local(0); local != count; ++local) {
 
1706             sig::Element *element(&elements[local]);
 
1707             if (element->name != NULL && strcmp(name, element->name) == 0) {
 
1715         index = static_cast<ssize_t>(number);
 
1716         if (index != number || index < 0 || static_cast<size_t>(index) >= count)
 
1721     ffi_type **elements(typical->GetFFI()->elements);
 
1723     base = reinterpret_cast<uint8_t *>(internal->value_);
 
1724     for (ssize_t local(0); local != index; ++local)
 
1725         base += elements[local]->size;
 
1730 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
1732     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
1733     Type_privateData *typical(internal->type_);
 
1735     if (typical->type_ == NULL)
 
1739     if (!CYGetIndex(pool, property, index))
 
1742     ffi_type *ffi(typical->GetFFI());
 
1744     uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
 
1745     base += ffi->size * index;
 
1747     JSObjectRef owner(internal->owner_ ?: object);
 
1750         return CYFromFFI(context, typical->type_, ffi, base, false, owner);
 
1754 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
1756     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
1757     Type_privateData *typical(internal->type_);
 
1759     if (typical->type_ == NULL)
 
1763     if (!CYGetIndex(pool, property, index))
 
1766     ffi_type *ffi(typical->GetFFI());
 
1768     uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
 
1769     base += ffi->size * index;
 
1772         CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
 
1777 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
1779     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
1780     Type_privateData *typical(internal->type_);
 
1785     if (!Index_(pool, internal, property, index, base))
 
1788     JSObjectRef owner(internal->owner_ ?: object);
 
1791         return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
 
1795 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
1797     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
1798     Type_privateData *typical(internal->type_);
 
1803     if (!Index_(pool, internal, property, index, base))
 
1807         CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
 
1812 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
1813     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
1814     Type_privateData *typical(internal->type_);
 
1815     sig::Type *type(typical->type_);
 
1820     size_t count(type->data.signature.count);
 
1821     sig::Element *elements(type->data.signature.elements);
 
1825     for (size_t index(0); index != count; ++index) {
 
1827         name = elements[index].name;
 
1830             sprintf(number, "%lu", index);
 
1834         JSPropertyNameAccumulatorAddName(names, CYJSString(name));
 
1838 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)()) {
 
1840         if (setups + count != signature->count - 1)
 
1841             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
 
1843         size_t size(setups + count);
 
1845         memcpy(values, setup, sizeof(void *) * setups);
 
1847         for (size_t index(setups); index != size; ++index) {
 
1848             sig::Element *element(&signature->elements[index + 1]);
 
1849             ffi_type *ffi(cif->arg_types[index]);
 
1851             values[index] = new(pool) uint8_t[ffi->size];
 
1852             CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
 
1855         uint8_t value[cif->rtype->size];
 
1856         ffi_call(cif, function, value, values);
 
1858         return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
 
1862 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
 
1863     ffoData *data(reinterpret_cast<ffoData *>(arg));
 
1865     JSContextRef context(data->context_);
 
1867     size_t count(data->cif_.nargs);
 
1868     JSValueRef values[count];
 
1870     for (size_t index(0); index != count; ++index)
 
1871         values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index], false);
 
1873     JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
 
1874     CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
 
1877 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
 
1878     // XXX: in case of exceptions this will leak
 
1879     ffoData *data(new ffoData(type));
 
1881     ffi_closure *closure((ffi_closure *) _syscall(mmap(
 
1882         NULL, sizeof(ffi_closure),
 
1883         PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
 
1887     ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
 
1888     _assert(status == FFI_OK);
 
1890     _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
 
1892     data->value_ = closure;
 
1894     data->context_ = CYGetJSContext();
 
1895     data->function_ = function;
 
1897     return JSObjectMake(context, Functor_, data);
 
1900 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
1903         NSString *name(CYCastNSString(pool, property));
 
1904         if (Class _class = NSClassFromString(name))
 
1905             return CYMakeInstance(context, _class, true);
 
1906         if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
 
1907             switch ([[entry objectAtIndex:0] intValue]) {
 
1909                     return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
 
1911                     return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
 
1913                     // XXX: this is horrendously inefficient
 
1914                     sig::Signature signature;
 
1915                     sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
 
1917                     sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
 
1918                     return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol], false);
 
1924 bool stret(ffi_type *ffi_type) {
 
1925     return ffi_type->type == FFI_TYPE_STRUCT && (
 
1926         ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
 
1927         struct_forward_array[ffi_type->size] != 0
 
1932     int *_NSGetArgc(void);
 
1933     char ***_NSGetArgv(void);
 
1934     int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
 
1937 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
1939         NSLog(@"%s", CYCastCString(context, arguments[0]));
 
1940         return CYJSUndefined(context);
 
1944 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
 
1947     Class _class(object_getClass(self));
 
1948     if (Method method = class_getInstanceMethod(_class, _cmd))
 
1949         type = method_getTypeEncoding(method);
 
1953                 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
 
1955                     @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
 
1956                 type = CYPoolCString(pool, [method _typeString]);
 
1965     sig::Signature signature;
 
1966     sig::Parse(pool, &signature, type, &Structor_);
 
1969     sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
 
1971     void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
 
1972     return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
 
1975 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
1985             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
 
1987         if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
 
1988             Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
 
1989             self = data->GetValue();
 
1990             uninitialized = data->IsUninitialized();
 
1994             self = CYCastNSObject(pool, context, arguments[0]);
 
1995             uninitialized = false;
 
1999             return CYJSNull(context);
 
2001         _cmd = CYCastSEL(context, arguments[1]);
 
2004     return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
 
2007 MSHook(void, CYDealloc, id self, SEL sel) {
 
2008     CYInternal *internal;
 
2009     object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
 
2010     if (internal != NULL)
 
2012     _CYDealloc(self, sel);
 
2015 MSHook(void, objc_registerClassPair, Class _class) {
 
2016     Class super(class_getSuperclass(_class));
 
2017     if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
 
2018         class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
 
2019         MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
 
2022     _objc_registerClassPair(_class);
 
2025 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2028             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
 
2030         Class _class(CYCastNSObject(pool, context, arguments[0]));
 
2031         $objc_registerClassPair(_class);
 
2032         return CYJSUndefined(context);
 
2036 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2037     JSValueRef setup[count + 2];
 
2040     memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
 
2041     return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
 
2044 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2046     Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
 
2047     return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
 
2050 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2053             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
 
2054         const char *name(CYCastCString(context, arguments[0]));
 
2055         return CYMakeSelector(context, sel_registerName(name));
 
2059 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2062             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
 
2064         void *value(CYCastPointer<void *>(context, arguments[0]));
 
2065         const char *type(CYCastCString(context, arguments[1]));
 
2069         sig::Signature signature;
 
2070         sig::Parse(pool, &signature, type, &Structor_);
 
2072         return CYMakePointer(context, value, signature.elements[0].type, NULL);
 
2076 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
 
2077     Type_privateData *internal(new Type_privateData(type));
 
2078     return JSObjectMake(context, Type_, internal);
 
2081 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2084             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
 
2085         const char *type(CYCastCString(context, arguments[0]));
 
2086         return CYMakeType(context, object, type);
 
2090 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2093             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
 
2094         Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
 
2095         sig::Type *type(internal->type_);
 
2096         ffi_type *ffi(internal->GetFFI());
 
2098         uint8_t value[ffi->size];
 
2100         CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
 
2101         return CYFromFFI(context, type, ffi, value, false);
 
2105 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2108             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
 
2109         Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
 
2111         void *value(malloc(internal->GetFFI()->size));
 
2112         return CYMakePointer(context, value, internal->type_, NULL);
 
2116 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2119             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
 
2120         const char *type(CYCastCString(context, arguments[1]));
 
2121         JSValueRef exception(NULL);
 
2122         if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
 
2123             JSObjectRef function(CYCastJSObject(context, arguments[0]));
 
2124             return CYMakeFunctor(context, function, type);
 
2125         } else if (exception != NULL) {
 
2128             void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
 
2129             return CYMakeFunctor(context, function, type);
 
2134 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2135     CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
 
2136     return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
 
2139 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2143 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2145         CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
 
2146         return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
 
2150 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2151     return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
 
2154 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2156         CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
 
2158         sprintf(string, "%p", internal->value_);
 
2159         return CYCastJSValue(context, string);
 
2163 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2165         Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
2167             return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toCYON]));
 
2172 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2174         Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
2176             NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
 
2177             return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
 
2182 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2184         Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
2186             return CYCastJSValue(context, CYJSString([data->GetValue() description]));
 
2191 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2193         Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
2194         return CYCastJSValue(context, sel_getName(data->GetValue()));
 
2198 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2199     return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
 
2202 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2204         Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
2205         const char *name(sel_getName(data->GetValue()));
 
2207             return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
 
2212 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2215             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
 
2217         Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
2218         Class _class(CYCastNSObject(pool, context, arguments[0]));
 
2219         bool instance(CYCastBool(context, arguments[1]));
 
2220         SEL sel(data->GetValue());
 
2221         if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
 
2222             return CYCastJSValue(context, method_getTypeEncoding(method));
 
2223         else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
 
2224             return CYCastJSValue(context, CYJSString(type));
 
2226             return CYJSNull(context);
 
2230 static JSStaticValue CYValue_staticValues[2] = {
 
2231     {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
 
2232     {NULL, NULL, NULL, 0}
 
2235 static JSStaticFunction Pointer_staticFunctions[4] = {
 
2236     {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2237     {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2238     {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2242 static JSStaticFunction Functor_staticFunctions[4] = {
 
2243     {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2244     {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2245     {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2249 /*static JSStaticValue Selector_staticValues[2] = {
 
2250     {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
 
2251     {NULL, NULL, NULL, 0}
 
2254 static JSStaticFunction Instance_staticFunctions[4] = {
 
2255     {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2256     {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2257     {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2261 static JSStaticFunction Selector_staticFunctions[5] = {
 
2262     {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2263     {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2264     {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2265     {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2269 CYDriver::CYDriver(const std::string &filename) :
 
2273     filename_(filename),
 
2279 CYDriver::~CYDriver() {
 
2283 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
 
2284     CYDriver::Error error;
 
2285     error.location_ = location;
 
2286     error.message_ = message;
 
2287     driver.errors_.push_back(error);
 
2290 void CYSetArgs(int argc, const char *argv[]) {
 
2291     JSContextRef context(CYGetJSContext());
 
2292     JSValueRef args[argc];
 
2293     for (int i(0); i != argc; ++i)
 
2294         args[i] = CYCastJSValue(context, argv[i]);
 
2295     JSValueRef exception(NULL);
 
2296     JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
 
2297     CYThrow(context, exception);
 
2298     CYSetProperty(context, System_, CYJSString("args"), array);
 
2301 JSObjectRef CYGetGlobalObject(JSContextRef context) {
 
2302     return JSContextGetGlobalObject(context);
 
2305 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
 
2306     JSStringRef script(JSStringCreateWithUTF8CString(code));
 
2308     JSContextRef context(CYGetJSContext());
 
2310     JSValueRef exception(NULL);
 
2311     JSValueRef result(JSEvaluateScript(context, script, NULL, NULL, 0, &exception));
 
2312     JSStringRelease(script);
 
2314     if (exception != NULL) { error:
 
2319     if (JSValueIsUndefined(context, result))
 
2322     const char *json(CYPoolCYONString(pool, context, result, &exception));
 
2323     if (exception != NULL)
 
2326     CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
 
2330 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
 
2331     while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
 
2339 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
 
2340     while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
 
2353     const char * volatile data_;
 
2356 // XXX: this is "tre lame"
 
2357 @interface CYClient_ : NSObject {
 
2360 - (void) execute:(NSValue *)value;
 
2364 @implementation CYClient_
 
2366 - (void) execute:(NSValue *)value {
 
2367     CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
 
2368     NSLog(@"b:%p", execute->data_);
 
2369     NSLog(@"s:%s", execute->data_);
 
2370     execute->data_ = CYExecute(execute->pool_, execute->data_);
 
2371     NSLog(@"a:%p", execute->data_);
 
2380     apr_thread_t *thread_;
 
2382     CYClient(int socket) :
 
2388         _syscall(close(socket_));
 
2391     void Handle() { _pooled
 
2392         CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
 
2396             if (!CYRecvAll(socket_, &size, sizeof(size)))
 
2400             char *data(new(pool) char[size + 1]);
 
2401             if (!CYRecvAll(socket_, data, size))
 
2405             CYDriver driver("");
 
2406             cy::parser parser(driver);
 
2408             driver.data_ = data;
 
2409             driver.size_ = size;
 
2412             if (parser.parse() != 0 || !driver.errors_.empty()) {
 
2414                 size = _not(size_t);
 
2416                 std::ostringstream str;
 
2417                 driver.source_->Show(str);
 
2418                 std::string code(str.str());
 
2419                 CYExecute_ execute = {pool, code.c_str()};
 
2420                 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
 
2421                 json = execute.data_;
 
2422                 size = json == NULL ? _not(size_t) : strlen(json);
 
2425             if (!CYSendAll(socket_, &size, sizeof(size)))
 
2428                 if (!CYSendAll(socket_, json, size))
 
2434 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
 
2435     CYClient *client(reinterpret_cast<CYClient *>(data));
 
2441 static void * APR_THREAD_FUNC Cyrver(apr_thread_t *thread, void *data) {
 
2443         int socket(_syscall(accept(Socket_, NULL, NULL)));
 
2444         CYClient *client(new CYClient(socket));
 
2445         apr_threadattr_t *attr;
 
2446         _aprcall(apr_threadattr_create(&attr, Pool_));
 
2447         _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
 
2454     pid_t pid(getpid());
 
2456     sprintf(path, "/tmp/.s.cy.%u", pid);
 
2460 MSInitialize { _pooled
 
2461     _aprcall(apr_initialize());
 
2462     _aprcall(apr_pool_create(&Pool_, NULL));
 
2464     Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
 
2465     NSCFBoolean_ = objc_getClass("NSCFBoolean");
 
2467     Socket_ = _syscall(socket(PF_UNIX, SOCK_STREAM, 0));
 
2469     struct sockaddr_un address;
 
2470     memset(&address, 0, sizeof(address));
 
2471     address.sun_family = AF_UNIX;
 
2473     pid_t pid(getpid());
 
2474     sprintf(address.sun_path, "/tmp/.s.cy.%u", pid);
 
2477         _syscall(bind(Socket_, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
 
2479         _syscall(listen(Socket_, 0));
 
2481         apr_threadattr_t *attr;
 
2482         _aprcall(apr_threadattr_create(&attr, Pool_));
 
2484         apr_thread_t *thread;
 
2485         _aprcall(apr_thread_create(&thread, attr, &Cyrver, NULL, Pool_));
 
2487         NSLog(@"failed to setup Cyrver");
 
2491 JSGlobalContextRef CYGetJSContext() {
 
2492     if (Context_ == NULL) {
 
2493         JSClassDefinition definition;
 
2495         definition = kJSClassDefinitionEmpty;
 
2496         definition.className = "Functor";
 
2497         definition.staticFunctions = Functor_staticFunctions;
 
2498         definition.callAsFunction = &Functor_callAsFunction;
 
2499         definition.finalize = &CYData::Finalize;
 
2500         Functor_ = JSClassCreate(&definition);
 
2502         definition = kJSClassDefinitionEmpty;
 
2503         definition.className = "Instance";
 
2504         definition.staticValues = CYValue_staticValues;
 
2505         definition.staticFunctions = Instance_staticFunctions;
 
2506         definition.getProperty = &Instance_getProperty;
 
2507         definition.setProperty = &Instance_setProperty;
 
2508         definition.deleteProperty = &Instance_deleteProperty;
 
2509         definition.callAsConstructor = &Instance_callAsConstructor;
 
2510         definition.finalize = &CYData::Finalize;
 
2511         Instance_ = JSClassCreate(&definition);
 
2513         definition = kJSClassDefinitionEmpty;
 
2514         definition.className = "Pointer";
 
2515         definition.staticFunctions = Pointer_staticFunctions;
 
2516         definition.getProperty = &Pointer_getProperty;
 
2517         definition.setProperty = &Pointer_setProperty;
 
2518         definition.finalize = &CYData::Finalize;
 
2519         Pointer_ = JSClassCreate(&definition);
 
2521         definition = kJSClassDefinitionEmpty;
 
2522         definition.className = "Selector";
 
2523         definition.staticValues = CYValue_staticValues;
 
2524         //definition.staticValues = Selector_staticValues;
 
2525         definition.staticFunctions = Selector_staticFunctions;
 
2526         definition.callAsFunction = &Selector_callAsFunction;
 
2527         definition.finalize = &CYData::Finalize;
 
2528         Selector_ = JSClassCreate(&definition);
 
2530         definition = kJSClassDefinitionEmpty;
 
2531         definition.className = "Struct";
 
2532         definition.getProperty = &Struct_getProperty;
 
2533         definition.setProperty = &Struct_setProperty;
 
2534         definition.getPropertyNames = &Struct_getPropertyNames;
 
2535         definition.finalize = &CYData::Finalize;
 
2536         Struct_ = JSClassCreate(&definition);
 
2538         definition = kJSClassDefinitionEmpty;
 
2539         definition.className = "Type";
 
2540         definition.callAsFunction = &Type_callAsFunction;
 
2541         definition.callAsConstructor = &Type_callAsConstructor;
 
2542         definition.finalize = &CYData::Finalize;
 
2543         Type_ = JSClassCreate(&definition);
 
2545         definition = kJSClassDefinitionEmpty;
 
2546         definition.className = "Runtime";
 
2547         definition.getProperty = &Runtime_getProperty;
 
2548         Runtime_ = JSClassCreate(&definition);
 
2550         definition = kJSClassDefinitionEmpty;
 
2551         //definition.getProperty = &Global_getProperty;
 
2552         JSClassRef Global(JSClassCreate(&definition));
 
2554         JSGlobalContextRef context(JSGlobalContextCreate(Global));
 
2557         JSObjectRef global(CYGetGlobalObject(context));
 
2559         JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
 
2560         CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
 
2562         CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
 
2563         CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, NULL));
 
2564         CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
 
2565         CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
 
2566         CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
 
2568         MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
 
2570         CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
 
2571         CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
 
2573         System_ = JSObjectMake(context, NULL, NULL);
 
2574         CYSetProperty(context, global, CYJSString("system"), System_);
 
2575         CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
 
2576         //CYSetProperty(context, System_, CYJSString("global"), global);
 
2578         CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
 
2580         Result_ = JSStringCreateWithUTF8CString("_");
 
2582         length_ = JSStringCreateWithUTF8CString("length");
 
2583         message_ = JSStringCreateWithUTF8CString("message");
 
2584         name_ = JSStringCreateWithUTF8CString("name");
 
2585         toCYON_ = JSStringCreateWithUTF8CString("toCYON");
 
2586         toJSON_ = JSStringCreateWithUTF8CString("toJSON");
 
2588         Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
 
2589         Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));