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_;
 
 118 static JSObjectRef Array_;
 
 119 static JSObjectRef Function_;
 
 121 static JSStringRef Result_;
 
 123 static JSStringRef length_;
 
 124 static JSStringRef message_;
 
 125 static JSStringRef name_;
 
 126 static JSStringRef toCYON_;
 
 127 static JSStringRef toJSON_;
 
 129 static Class NSCFBoolean_;
 
 131 static NSArray *Bridge_;
 
 139     static 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 operator delete(void *data) {
 
 148         apr_pool_destroy(reinterpret_cast<CYData *>(data)->pool_);
 
 151     static void Finalize(JSObjectRef object) {
 
 152         delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
 
 164     CYValue(void *value) :
 
 170 struct Selector_privateData :
 
 173     Selector_privateData(SEL value) :
 
 178     SEL GetValue() const {
 
 179         return reinterpret_cast<SEL>(value_);
 
 188         Transient     = (1 << 0),
 
 189         Uninitialized = (1 << 1),
 
 194     Instance(id value, Flags flags) :
 
 200     virtual ~Instance() {
 
 201         if ((flags_ & Transient) == 0)
 
 202             // XXX: does this handle background threads correctly?
 
 203             [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
 
 206     static JSObjectRef Make(JSContextRef context, id object, Flags flags) {
 
 207         return JSObjectMake(context, Instance_, new Instance(object, flags));
 
 210     id GetValue() const {
 
 211         return reinterpret_cast<id>(value_);
 
 214     bool IsUninitialized() const {
 
 215         return (flags_ & Uninitialized) != 0;
 
 221 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
 
 223 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
 
 224     lhs.name = apr_pstrdup(pool, rhs.name);
 
 225     if (rhs.type == NULL)
 
 228         lhs.type = new(pool) Type;
 
 229         Copy(pool, *lhs.type, *rhs.type);
 
 231     lhs.offset = rhs.offset;
 
 234 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
 
 235     size_t count(rhs.count);
 
 237     lhs.elements = new(pool) Element[count];
 
 238     for (size_t index(0); index != count; ++index)
 
 239         Copy(pool, lhs.elements[index], rhs.elements[index]);
 
 242 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
 
 243     lhs.primitive = rhs.primitive;
 
 244     lhs.name = apr_pstrdup(pool, rhs.name);
 
 245     lhs.flags = rhs.flags;
 
 247     if (sig::IsAggregate(rhs.primitive))
 
 248         Copy(pool, lhs.data.signature, rhs.data.signature);
 
 250         if (rhs.data.data.type != NULL) {
 
 251             lhs.data.data.type = new(pool) Type;
 
 252             Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
 
 255         lhs.data.data.size = rhs.data.data.size;
 
 259 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
 
 261     lhs.alignment = rhs.alignment;
 
 263     if (rhs.elements == NULL)
 
 267         while (rhs.elements[count] != NULL)
 
 270         lhs.elements = new(pool) ffi_type *[count + 1];
 
 271         lhs.elements[count] = NULL;
 
 273         for (size_t index(0); index != count; ++index) {
 
 274             // XXX: if these are libffi native then you can just take them
 
 275             ffi_type *ffi(new(pool) ffi_type);
 
 276             lhs.elements[index] = ffi;
 
 277             sig::Copy(pool, *ffi, *rhs.elements[index]);
 
 284 struct CStringMapLess :
 
 285     std::binary_function<const char *, const char *, bool>
 
 287     _finline bool operator ()(const char *lhs, const char *rhs) const {
 
 288         return strcmp(lhs, rhs) < 0;
 
 292 struct Type_privateData {
 
 298     Type_privateData(apr_pool_t *pool, sig::Type *type) :
 
 303             type_ = new(pool) sig::Type;
 
 304             sig::Copy(pool, *type_, *type);
 
 308     Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) :
 
 311         ffi_ = new(pool) ffi_type;
 
 312         sig::Copy(pool, *ffi_, *ffi);
 
 313         type_ = new(pool) sig::Type;
 
 314         sig::Copy(pool, *type_, *type);
 
 319             ffi_ = new(pool_) ffi_type;
 
 321             sig::Element element;
 
 323             element.type = type_;
 
 326             sig::Signature signature;
 
 327             signature.elements = &element;
 
 331             sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
 
 343     Type_privateData *type_;
 
 345     Pointer(void *value, sig::Type *type, JSObjectRef owner) :
 
 348         type_(new(pool_) Type_privateData(pool_, type))
 
 353 struct Struct_privateData :
 
 357     Type_privateData *type_;
 
 359     Struct_privateData(JSObjectRef owner) :
 
 365 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
 
 366 static TypeMap Types_;
 
 368 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
 
 369     Struct_privateData *internal(new Struct_privateData(owner));
 
 370     apr_pool_t *pool(internal->pool_);
 
 371     Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
 
 372     internal->type_ = typical;
 
 375         internal->value_ = data;
 
 377         size_t size(typical->GetFFI()->size);
 
 378         void *copy(apr_palloc(internal->pool_, size));
 
 379         memcpy(copy, data, size);
 
 380         internal->value_ = copy;
 
 383     return JSObjectMake(context, Struct_, internal);
 
 386 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
 
 391         if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
 
 392             switch ([[entry objectAtIndex:0] intValue]) {
 
 394                     sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
 
 398                     sig::Signature signature;
 
 399                     sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
 
 400                     type = signature.elements[0].type;
 
 406 struct Functor_privateData :
 
 409     sig::Signature signature_;
 
 412     Functor_privateData(const char *type, void (*value)()) :
 
 413         CYValue(reinterpret_cast<void *>(value))
 
 415         sig::Parse(pool_, &signature_, type, &Structor_);
 
 416         sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
 
 423     JSContextRef context_;
 
 424     JSObjectRef function_;
 
 426     ffoData(const char *type) :
 
 427         Functor_privateData(type, NULL)
 
 432 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
 
 433     Instance::Flags flags;
 
 436         flags = Instance::Transient;
 
 438         flags = Instance::None;
 
 439         object = [object retain];
 
 442     return Instance::Make(context, object, flags);
 
 445 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
 
 447         return [value UTF8String];
 
 449         size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
 
 450         char *string(new(pool) char[size]);
 
 451         if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
 
 452             @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
 
 457 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
 
 458     return JSValueMakeBoolean(context, value);
 
 461 JSValueRef CYCastJSValue(JSContextRef context, double value) {
 
 462     return JSValueMakeNumber(context, value);
 
 465 #define CYCastJSValue_(Type_) \
 
 466     JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
 
 467         return JSValueMakeNumber(context, static_cast<double>(value)); \
 
 471 CYCastJSValue_(unsigned int)
 
 472 CYCastJSValue_(long int)
 
 473 CYCastJSValue_(long unsigned int)
 
 474 CYCastJSValue_(long long int)
 
 475 CYCastJSValue_(long long unsigned int)
 
 477 JSValueRef CYJSUndefined(JSContextRef context) {
 
 478     return JSValueMakeUndefined(context);
 
 481 bool CYGetIndex(const char *value, ssize_t &index) {
 
 482     if (value[0] != '0') {
 
 484         index = strtol(value, &end, 10);
 
 485         if (value + strlen(value) == end)
 
 487     } else if (value[1] == '\0') {
 
 495 bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
 
 496     return CYGetIndex(CYPoolCString(pool, value), index);
 
 499 @interface NSMethodSignature (Cycript)
 
 500 - (NSString *) _typeString;
 
 503 @interface NSObject (Cycript)
 
 505 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
 
 506 - (JSType) cy$JSType;
 
 508 - (NSObject *) cy$toJSON:(NSString *)key;
 
 509 - (NSString *) cy$toCYON;
 
 510 - (NSString *) cy$toKey;
 
 512 - (NSObject *) cy$getProperty:(NSString *)name;
 
 513 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
 
 514 - (bool) cy$deleteProperty:(NSString *)name;
 
 519 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
 
 522 @interface NSString (Cycript)
 
 523 - (void *) cy$symbol;
 
 526 struct PropertyAttributes {
 
 531     const char *variable;
 
 544     PropertyAttributes(objc_property_t property) :
 
 556         name = property_getName(property);
 
 557         const char *attributes(property_getAttributes(property));
 
 559         for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
 
 561                 case 'R': readonly = true; break;
 
 562                 case 'C': copy = true; break;
 
 563                 case '&': retain = true; break;
 
 564                 case 'N': nonatomic = true; break;
 
 565                 case 'G': getter_ = token + 1; break;
 
 566                 case 'S': setter_ = token + 1; break;
 
 567                 case 'V': variable = token + 1; break;
 
 571         /*if (variable == NULL) {
 
 572             variable = property_getName(property);
 
 573             size_t size(strlen(variable));
 
 574             char *name(new(pool_) char[size + 2]);
 
 576             memcpy(name + 1, variable, size);
 
 577             name[size + 1] = '\0';
 
 582     const char *Getter() {
 
 584             getter_ = apr_pstrdup(pool_, name);
 
 588     const char *Setter() {
 
 589         if (setter_ == NULL && !readonly) {
 
 590             size_t length(strlen(name));
 
 592             char *temp(new(pool_) char[length + 5]);
 
 598                 temp[3] = toupper(name[0]);
 
 599                 memcpy(temp + 4, name + 1, length - 1);
 
 602             temp[length + 3] = ':';
 
 603             temp[length + 4] = '\0';
 
 612 @implementation NSObject (Cycript)
 
 614 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
 615     return CYMakeInstance(context, self, false);
 
 618 - (JSType) cy$JSType {
 
 619     return kJSTypeObject;
 
 622 - (NSObject *) cy$toJSON:(NSString *)key {
 
 623     return [self description];
 
 626 - (NSString *) cy$toCYON {
 
 627     return [[self cy$toJSON:@""] cy$toCYON];
 
 630 - (NSString *) cy$toKey {
 
 631     return [self cy$toCYON];
 
 634 - (NSObject *) cy$getProperty:(NSString *)name {
 
 635     /*if (![name isEqualToString:@"prototype"])
 
 636         NSLog(@"get:%@", name);*/
 
 640 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
 641     //NSLog(@"set:%@", name);
 
 645 - (bool) cy$deleteProperty:(NSString *)name {
 
 646     //NSLog(@"delete:%@", name);
 
 652 @implementation WebUndefined (Cycript)
 
 654 - (JSType) cy$JSType {
 
 655     return kJSTypeUndefined;
 
 658 - (NSObject *) cy$toJSON:(NSString *)key {
 
 662 - (NSString *) cy$toCYON {
 
 666 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
 667     return CYJSUndefined(context);
 
 672 @implementation NSNull (Cycript)
 
 674 - (JSType) cy$JSType {
 
 678 - (NSObject *) cy$toJSON:(NSString *)key {
 
 682 - (NSString *) cy$toCYON {
 
 688 @implementation NSArray (Cycript)
 
 690 - (NSString *) cy$toCYON {
 
 691     NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
 
 692     [json appendString:@"["];
 
 695     for (id object in self) {
 
 697             [json appendString:@","];
 
 700         if ([object cy$JSType] != kJSTypeUndefined)
 
 701             [json appendString:[object cy$toCYON]];
 
 703             [json appendString:@","];
 
 708     [json appendString:@"]"];
 
 712 - (NSObject *) cy$getProperty:(NSString *)name {
 
 713     if ([name isEqualToString:@"length"])
 
 714         return [NSNumber numberWithUnsignedInteger:[self count]];
 
 717     if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
 
 718         return [super cy$getProperty:name];
 
 720         return [self objectAtIndex:index];
 
 725 @implementation NSMutableArray (Cycript)
 
 727 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
 729     if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
 
 730         return [super cy$setProperty:name to:value];
 
 732         [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
 
 737 - (bool) cy$deleteProperty:(NSString *)name {
 
 739     if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
 
 740         return [super cy$deleteProperty:name];
 
 742         [self removeObjectAtIndex:index];
 
 749 @implementation NSDictionary (Cycript)
 
 751 - (NSString *) cy$toCYON {
 
 752     NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
 
 753     [json appendString:@"{"];
 
 756     for (id key in self) {
 
 758             [json appendString:@","];
 
 761         [json appendString:[key cy$toKey]];
 
 762         [json appendString:@":"];
 
 763         NSObject *object([self objectForKey:key]);
 
 764         [json appendString:[object cy$toCYON]];
 
 767     [json appendString:@"}"];
 
 771 - (NSObject *) cy$getProperty:(NSString *)name {
 
 772     return [self objectForKey:name];
 
 777 @implementation NSMutableDictionary (Cycript)
 
 779 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
 
 780     [self setObject:(value ?: [NSNull null]) forKey:name];
 
 784 - (bool) cy$deleteProperty:(NSString *)name {
 
 785     if ([self objectForKey:name] == nil)
 
 788         [self removeObjectForKey:name];
 
 795 @implementation NSNumber (Cycript)
 
 797 - (JSType) cy$JSType {
 
 798     // XXX: this just seems stupid
 
 799     return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
 
 802 - (NSObject *) cy$toJSON:(NSString *)key {
 
 806 - (NSString *) cy$toCYON {
 
 807     return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
 
 810 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
 
 811     return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
 
 816 @implementation NSString (Cycript)
 
 818 - (JSType) cy$JSType {
 
 819     return kJSTypeString;
 
 822 - (NSObject *) cy$toJSON:(NSString *)key {
 
 826 - (NSString *) cy$toCYON {
 
 827     // XXX: this should use the better code from Output.cpp
 
 828     CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
 
 830     CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
 
 831     CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
 
 832     CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
 
 833     CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
 
 834     CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
 
 836     CFStringInsert(json, 0, CFSTR("\""));
 
 837     CFStringAppend(json, CFSTR("\""));
 
 839     return [reinterpret_cast<const NSString *>(json) autorelease];
 
 842 - (NSString *) cy$toKey {
 
 843     const char *value([self UTF8String]);
 
 844     size_t size(strlen(value));
 
 849     if (DigitRange_[value[0]]) {
 
 851         if (!CYGetIndex(NULL, self, index) || index < 0)
 
 854         if (!WordStartRange_[value[0]])
 
 856         for (size_t i(1); i != size; ++i)
 
 857             if (!WordEndRange_[value[i]])
 
 864     return [self cy$toCYON];
 
 867 - (void *) cy$symbol {
 
 869     return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
 
 874 @interface CYJSObject : NSDictionary {
 
 876     JSContextRef context_;
 
 879 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
 
 881 - (NSString *) cy$toJSON:(NSString *)key;
 
 883 - (NSUInteger) count;
 
 884 - (id) objectForKey:(id)key;
 
 885 - (NSEnumerator *) keyEnumerator;
 
 886 - (void) setObject:(id)object forKey:(id)key;
 
 887 - (void) removeObjectForKey:(id)key;
 
 891 @interface CYJSArray : NSArray {
 
 893     JSContextRef context_;
 
 896 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
 
 898 - (NSUInteger) count;
 
 899 - (id) objectAtIndex:(NSUInteger)index;
 
 903 CYRange DigitRange_    (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
 
 904 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
 
 905 CYRange WordEndRange_  (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
 
 910     @catch (id error) { \
 
 911         CYThrow(context, error, exception); \
 
 915 void CYThrow(JSContextRef context, JSValueRef value);
 
 917 apr_status_t CYPoolRelease_(void *data) {
 
 918     id object(reinterpret_cast<id>(data));
 
 923 id CYPoolRelease(apr_pool_t *pool, id object) {
 
 926     else if (pool == NULL)
 
 927         return [object autorelease];
 
 929         apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
 
 934 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
 
 935     return (CFTypeRef) CYPoolRelease(pool, (id) object);
 
 938 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
 
 939     JSValueRef exception(NULL);
 
 940     bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
 
 941     CYThrow(context, exception);
 
 942     id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
 
 943     return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
 
 946 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
 
 947     if (!JSValueIsObjectOfClass(context, object, Instance_))
 
 948         return CYCastNSObject_(pool, context, object);
 
 950         Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
 951         return data->GetValue();
 
 955 JSStringRef CYCopyJSString(id value) {
 
 956     return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
 
 959 JSStringRef CYCopyJSString(const char *value) {
 
 960     return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
 
 963 JSStringRef CYCopyJSString(JSStringRef value) {
 
 964     return value == NULL ? NULL : JSStringRetain(value);
 
 967 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
 
 968     if (JSValueIsNull(context, value))
 
 970     JSValueRef exception(NULL);
 
 971     JSStringRef string(JSValueToStringCopy(context, value, &exception));
 
 972     CYThrow(context, exception);
 
 982             JSStringRelease(string_);
 
 986     CYJSString(const CYJSString &rhs) :
 
 987         string_(CYCopyJSString(rhs.string_))
 
 991     template <typename Arg0_>
 
 992     CYJSString(Arg0_ arg0) :
 
 993         string_(CYCopyJSString(arg0))
 
 997     template <typename Arg0_, typename Arg1_>
 
 998     CYJSString(Arg0_ arg0, Arg1_ arg1) :
 
 999         string_(CYCopyJSString(arg0, arg1))
 
1003     CYJSString &operator =(const CYJSString &rhs) {
 
1005         string_ = CYCopyJSString(rhs.string_);
 
1018     operator JSStringRef() const {
 
1023 CFStringRef CYCopyCFString(JSStringRef value) {
 
1024     return JSStringCopyCFString(kCFAllocatorDefault, value);
 
1027 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
 
1028     return CYCopyCFString(CYJSString(context, value));
 
1031 double CYCastDouble(const char *value, size_t size) {
 
1033     double number(strtod(value, &end));
 
1034     if (end != value + size)
 
1039 double CYCastDouble(const char *value) {
 
1040     return CYCastDouble(value, strlen(value));
 
1043 double CYCastDouble(JSContextRef context, JSValueRef value) {
 
1044     JSValueRef exception(NULL);
 
1045     double number(JSValueToNumber(context, value, &exception));
 
1046     CYThrow(context, exception);
 
1050 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
 
1051     double number(CYCastDouble(context, value));
 
1052     return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
 
1055 CFStringRef CYCopyCFString(const char *value) {
 
1056     return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
 
1059 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
 
1060     return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
 
1063 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
 
1064     return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
 
1067 bool CYCastBool(JSContextRef context, JSValueRef value) {
 
1068     return JSValueToBoolean(context, value);
 
1071 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
 
1075     switch (JSType type = JSValueGetType(context, value)) {
 
1076         case kJSTypeUndefined:
 
1077             object = [WebUndefined undefined];
 
1085         case kJSTypeBoolean:
 
1086             object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
 
1091             object = CYCopyCFNumber(context, value);
 
1096             object = CYCopyCFString(context, value);
 
1101             // XXX: this might could be more efficient
 
1102             object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
 
1107             @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
 
1114         return CYPoolRelease(pool, object);
 
1116         return CFRetain(object);
 
1119 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1120     return CYCFType(pool, context, value, true);
 
1123 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1124     return CYCFType(pool, context, value, false);
 
1127 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
 
1129     size_t size(JSPropertyNameArrayGetCount(names));
 
1130     NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
 
1131     for (size_t index(0); index != size; ++index)
 
1132         [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
 
1136 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1137     return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
 
1140 void CYThrow(JSContextRef context, JSValueRef value) {
 
1143     @throw CYCastNSObject(NULL, context, value);
 
1146 JSValueRef CYJSNull(JSContextRef context) {
 
1147     return JSValueMakeNull(context);
 
1150 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
 
1151     return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
 
1154 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
 
1155     return CYCastJSValue(context, CYJSString(value));
 
1158 JSValueRef CYCastJSValue(JSContextRef context, id value) {
 
1160         return CYJSNull(context);
 
1161     else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
 
1162         return [value cy$JSValueInContext:context];
 
1164         return CYMakeInstance(context, value, false);
 
1167 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
 
1168     JSValueRef exception(NULL);
 
1169     JSObjectRef object(JSValueToObject(context, value, &exception));
 
1170     CYThrow(context, exception);
 
1174 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
 
1175     JSValueRef exception(NULL);
 
1176     JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
 
1177     CYThrow(context, exception);
 
1181 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
 
1182     JSValueRef exception(NULL);
 
1183     JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
 
1184     CYThrow(context, exception);
 
1188 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
 
1189     JSValueRef exception(NULL);
 
1190     JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
 
1191     CYThrow(context, exception);
 
1194 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
 
1195     if (exception == NULL)
 
1197     *exception = CYCastJSValue(context, error);
 
1200 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
 
1201     JSValueRef exception(NULL);
 
1202     JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
 
1203     CYThrow(context, exception);
 
1207 bool CYIsCallable(JSContextRef context, JSValueRef value) {
 
1208     // XXX: this isn't actually correct
 
1209     return value != NULL && JSValueIsObject(context, value);
 
1212 @implementation CYJSObject
 
1214 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
 
1215     if ((self = [super init]) != nil) {
 
1221 - (NSObject *) cy$toJSON:(NSString *)key {
 
1222     JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
 
1223     if (!CYIsCallable(context_, toJSON))
 
1224         return [super cy$toJSON:key];
 
1226         JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
 
1227         JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
 
1228         // XXX: do I really want an NSNull here?!
 
1229         return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
 
1233 - (NSString *) cy$toCYON {
 
1234     JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
 
1235     if (!CYIsCallable(context_, toCYON))
 
1236         return [super cy$toCYON];
 
1238         JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
 
1239         return CYCastNSString(NULL, CYJSString(context_, value));
 
1243 - (NSUInteger) count {
 
1244     JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
 
1245     size_t size(JSPropertyNameArrayGetCount(names));
 
1246     JSPropertyNameArrayRelease(names);
 
1250 - (id) objectForKey:(id)key {
 
1251     return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
 
1254 - (NSEnumerator *) keyEnumerator {
 
1255     JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
 
1256     NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
 
1257     JSPropertyNameArrayRelease(names);
 
1261 - (void) setObject:(id)object forKey:(id)key {
 
1262     CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
 
1265 - (void) removeObjectForKey:(id)key {
 
1266     JSValueRef exception(NULL);
 
1267     (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
 
1268     CYThrow(context_, exception);
 
1273 @implementation CYJSArray
 
1275 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
 
1276     if ((self = [super init]) != nil) {
 
1282 - (NSUInteger) count {
 
1283     return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
 
1286 - (id) objectAtIndex:(NSUInteger)index {
 
1287     JSValueRef exception(NULL);
 
1288     JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
 
1289     CYThrow(context_, exception);
 
1290     return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
 
1295 CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
 
1298             id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
 
1299             return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
 
1304 const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
 
1305     if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
 
1306         const char *string(CYPoolCString(pool, json));
 
1312 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
 
1316     JSObjectRef object_;
 
1324         // XXX: delete object_? ;(
 
1327     static CYInternal *Get(id self) {
 
1328         CYInternal *internal(NULL);
 
1329         if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
 
1330             // XXX: do something epic? ;P
 
1336     static CYInternal *Set(id self) {
 
1337         CYInternal *internal(NULL);
 
1338         if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
 
1339             if (internal == NULL) {
 
1340                 internal = new CYInternal();
 
1341                 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
 
1344             // XXX: do something epic? ;P
 
1350     JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
 
1351         if (object_ == NULL)
 
1353         return CYGetProperty(context, object_, name);
 
1356     void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
 
1357         if (object_ == NULL)
 
1358             object_ = JSObjectMake(context, NULL, NULL);
 
1359         CYSetProperty(context, object_, name, value);
 
1363 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
1367         NSString *self(CYCastNSObject(pool, context, object));
 
1368         NSString *name(CYCastNSString(pool, property));
 
1370         if (CYInternal *internal = CYInternal::Get(self))
 
1371             if (JSValueRef value = internal->GetProperty(context, property))
 
1375             if (NSObject *data = [self cy$getProperty:name])
 
1376                 return CYCastJSValue(context, data);
 
1379         if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
 
1380             PropertyAttributes attributes(property);
 
1381             SEL sel(sel_registerName(attributes.Getter()));
 
1382             return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
 
1389 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
1393         NSString *self(CYCastNSObject(pool, context, object));
 
1394         NSString *name(CYCastNSString(pool, property));
 
1395         NSString *data(CYCastNSObject(pool, context, value));
 
1398             if ([self cy$setProperty:name to:data])
 
1402         if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
 
1403             PropertyAttributes attributes(property);
 
1404             if (const char *setter = attributes.Setter()) {
 
1405                 SEL sel(sel_registerName(setter));
 
1406                 JSValueRef arguments[1] = {value};
 
1407                 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
 
1412         if (CYInternal *internal = CYInternal::Set(self)) {
 
1413             internal->SetProperty(context, property, value);
 
1421 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
1424             NSString *self(CYCastNSObject(NULL, context, object));
 
1425             NSString *name(CYCastNSString(NULL, property));
 
1426             return [self cy$deleteProperty:name];
 
1431 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
1433         Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
 
1434         JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
 
1439 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
 
1440     Selector_privateData *data(new Selector_privateData(sel));
 
1441     return JSObjectMake(context, Selector_, data);
 
1444 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, JSObjectRef owner) {
 
1445     Pointer *data(new Pointer(pointer, type, owner));
 
1446     return JSObjectMake(context, Pointer_, data);
 
1449 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
 
1450     Functor_privateData *data(new Functor_privateData(type, function));
 
1451     return JSObjectMake(context, Functor_, data);
 
1454 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
 
1456         const char *string([CYCastNSString(NULL, value) UTF8String]);
 
1459         size_t size(JSStringGetMaximumUTF8CStringSize(value));
 
1460         char *string(new(pool) char[size]);
 
1461         JSStringGetUTF8CString(value, string, size);
 
1466 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
 
1467     return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
 
1470 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
 
1471     return CYGetIndex(CYPoolCString(pool, value), index);
 
1474 // XXX: this macro is unhygenic
 
1475 #define CYCastCString(context, value) ({ \
 
1477     if (value == NULL) \
 
1479     else if (JSStringRef string = CYCopyJSString(context, value)) { \
 
1480         size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
 
1481         utf8 = reinterpret_cast<char *>(alloca(size)); \
 
1482         JSStringGetUTF8CString(string, utf8, size); \
 
1483         JSStringRelease(string); \
 
1489 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
 
1490     switch (JSValueGetType(context, value)) {
 
1493         /*case kJSTypeString:
 
1494             return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
 
1496             if (JSValueIsObjectOfClass(context, value, Pointer_)) {
 
1497                 Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
 
1498                 return data->value_;
 
1501             double number(CYCastDouble(context, value));
 
1502             if (std::isnan(number))
 
1503                 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
 
1504             return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
 
1508 template <typename Type_>
 
1509 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
 
1510     return reinterpret_cast<Type_>(CYCastPointer_(context, value));
 
1513 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
 
1514     if (JSValueIsObjectOfClass(context, value, Selector_)) {
 
1515         Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
 
1516         return reinterpret_cast<SEL>(data->value_);
 
1518         return CYCastPointer<SEL>(context, value);
 
1521 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
 
1522     switch (type->primitive) {
 
1523         case sig::boolean_P:
 
1524             *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
 
1527 #define CYPoolFFI_(primitive, native) \
 
1528         case sig::primitive ## _P: \
 
1529             *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
 
1532         CYPoolFFI_(uchar, unsigned char)
 
1533         CYPoolFFI_(char, char)
 
1534         CYPoolFFI_(ushort, unsigned short)
 
1535         CYPoolFFI_(short, short)
 
1536         CYPoolFFI_(ulong, unsigned long)
 
1537         CYPoolFFI_(long, long)
 
1538         CYPoolFFI_(uint, unsigned int)
 
1539         CYPoolFFI_(int, int)
 
1540         CYPoolFFI_(ulonglong, unsigned long long)
 
1541         CYPoolFFI_(longlong, long long)
 
1542         CYPoolFFI_(float, float)
 
1543         CYPoolFFI_(double, double)
 
1546         case sig::typename_P:
 
1547             *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
 
1550         case sig::selector_P:
 
1551             *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
 
1554         case sig::pointer_P:
 
1555             *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
 
1559             *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
 
1562         case sig::struct_P: {
 
1563             uint8_t *base(reinterpret_cast<uint8_t *>(data));
 
1564             JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
 
1565             for (size_t index(0); index != type->data.signature.count; ++index) {
 
1566                 sig::Element *element(&type->data.signature.elements[index]);
 
1567                 ffi_type *field(ffi->elements[index]);
 
1570                 if (aggregate == NULL)
 
1573                     rhs = CYGetProperty(context, aggregate, index);
 
1574                     if (JSValueIsUndefined(context, rhs)) {
 
1575                         if (element->name != NULL)
 
1576                             rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
 
1579                         if (JSValueIsUndefined(context, rhs)) undefined:
 
1580                             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
 
1584                 CYPoolFFI(pool, context, element->type, field, base, rhs);
 
1586                 base += field->size;
 
1594             NSLog(@"CYPoolFFI(%c)\n", type->primitive);
 
1599 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner = NULL) {
 
1602     switch (type->primitive) {
 
1603         case sig::boolean_P:
 
1604             value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
 
1607 #define CYFromFFI_(primitive, native) \
 
1608         case sig::primitive ## _P: \
 
1609             value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
 
1612         CYFromFFI_(uchar, unsigned char)
 
1613         CYFromFFI_(char, char)
 
1614         CYFromFFI_(ushort, unsigned short)
 
1615         CYFromFFI_(short, short)
 
1616         CYFromFFI_(ulong, unsigned long)
 
1617         CYFromFFI_(long, long)
 
1618         CYFromFFI_(uint, unsigned int)
 
1619         CYFromFFI_(int, int)
 
1620         CYFromFFI_(ulonglong, unsigned long long)
 
1621         CYFromFFI_(longlong, long long)
 
1622         CYFromFFI_(float, float)
 
1623         CYFromFFI_(double, double)
 
1625         case sig::object_P: {
 
1626             if (id object = *reinterpret_cast<id *>(data)) {
 
1627                 value = CYCastJSValue(context, object);
 
1633         case sig::typename_P:
 
1634             value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
 
1637         case sig::selector_P:
 
1638             if (SEL sel = *reinterpret_cast<SEL *>(data))
 
1639                 value = CYMakeSelector(context, sel);
 
1643         case sig::pointer_P:
 
1644             if (void *pointer = *reinterpret_cast<void **>(data))
 
1645                 value = CYMakePointer(context, pointer, type->data.data.type, owner);
 
1650             if (char *utf8 = *reinterpret_cast<char **>(data))
 
1651                 value = CYCastJSValue(context, utf8);
 
1656             value = CYMakeStruct(context, data, type, ffi, owner);
 
1660             value = CYJSUndefined(context);
 
1664             value = CYJSNull(context);
 
1668             NSLog(@"CYFromFFI(%c)\n", type->primitive);
 
1675 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
 
1676     Type_privateData *typical(internal->type_);
 
1677     sig::Type *type(typical->type_);
 
1681     const char *name(CYPoolCString(pool, property));
 
1682     size_t length(strlen(name));
 
1683     double number(CYCastDouble(name, length));
 
1685     size_t count(type->data.signature.count);
 
1687     if (std::isnan(number)) {
 
1688         if (property == NULL)
 
1691         sig::Element *elements(type->data.signature.elements);
 
1693         for (size_t local(0); local != count; ++local) {
 
1694             sig::Element *element(&elements[local]);
 
1695             if (element->name != NULL && strcmp(name, element->name) == 0) {
 
1703         index = static_cast<ssize_t>(number);
 
1704         if (index != number || index < 0 || static_cast<size_t>(index) >= count)
 
1709     ffi_type **elements(typical->GetFFI()->elements);
 
1711     base = reinterpret_cast<uint8_t *>(internal->value_);
 
1712     for (ssize_t local(0); local != index; ++local)
 
1713         base += elements[local]->size;
 
1718 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
1720     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
1721     Type_privateData *typical(internal->type_);
 
1723     if (typical->type_ == NULL)
 
1727     if (!CYGetIndex(pool, property, index))
 
1730     ffi_type *ffi(typical->GetFFI());
 
1732     uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
 
1733     base += ffi->size * index;
 
1735     JSObjectRef owner(internal->owner_ ?: object);
 
1738         return CYFromFFI(context, typical->type_, ffi, base, false, owner);
 
1742 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
1744     Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
 
1745     Type_privateData *typical(internal->type_);
 
1747     if (typical->type_ == NULL)
 
1751     if (!CYGetIndex(pool, property, index))
 
1754     ffi_type *ffi(typical->GetFFI());
 
1756     uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
 
1757     base += ffi->size * index;
 
1760         CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
 
1765 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
1767     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
1768     Type_privateData *typical(internal->type_);
 
1773     if (!Index_(pool, internal, property, index, base))
 
1776     JSObjectRef owner(internal->owner_ ?: object);
 
1779         return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
 
1783 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
 
1785     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
1786     Type_privateData *typical(internal->type_);
 
1791     if (!Index_(pool, internal, property, index, base))
 
1795         CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
 
1800 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
 
1801     Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
 
1802     Type_privateData *typical(internal->type_);
 
1803     sig::Type *type(typical->type_);
 
1808     size_t count(type->data.signature.count);
 
1809     sig::Element *elements(type->data.signature.elements);
 
1813     for (size_t index(0); index != count; ++index) {
 
1815         name = elements[index].name;
 
1818             sprintf(number, "%lu", index);
 
1822         JSPropertyNameAccumulatorAddName(names, CYJSString(name));
 
1826 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)()) {
 
1828         if (setups + count != signature->count - 1)
 
1829             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
 
1831         size_t size(setups + count);
 
1833         memcpy(values, setup, sizeof(void *) * setups);
 
1835         for (size_t index(setups); index != size; ++index) {
 
1836             sig::Element *element(&signature->elements[index + 1]);
 
1837             ffi_type *ffi(cif->arg_types[index]);
 
1839             values[index] = new(pool) uint8_t[ffi->size];
 
1840             CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
 
1843         uint8_t value[cif->rtype->size];
 
1844         ffi_call(cif, function, value, values);
 
1846         return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
 
1850 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
 
1851     ffoData *data(reinterpret_cast<ffoData *>(arg));
 
1853     JSContextRef context(data->context_);
 
1855     size_t count(data->cif_.nargs);
 
1856     JSValueRef values[count];
 
1858     for (size_t index(0); index != count; ++index)
 
1859         values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index], false);
 
1861     JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
 
1862     CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
 
1865 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
 
1866     // XXX: in case of exceptions this will leak
 
1867     ffoData *data(new ffoData(type));
 
1869     ffi_closure *closure((ffi_closure *) _syscall(mmap(
 
1870         NULL, sizeof(ffi_closure),
 
1871         PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
 
1875     ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
 
1876     _assert(status == FFI_OK);
 
1878     _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
 
1880     data->value_ = closure;
 
1882     data->context_ = CYGetJSContext();
 
1883     data->function_ = function;
 
1885     return JSObjectMake(context, Functor_, data);
 
1888 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
1891         NSString *name(CYCastNSString(pool, property));
 
1892         if (Class _class = NSClassFromString(name))
 
1893             return CYMakeInstance(context, _class, true);
 
1894         if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
 
1895             switch ([[entry objectAtIndex:0] intValue]) {
 
1897                     return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
 
1899                     return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
 
1901                     // XXX: this is horrendously inefficient
 
1902                     sig::Signature signature;
 
1903                     sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
 
1905                     sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
 
1906                     return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol], false);
 
1912 bool stret(ffi_type *ffi_type) {
 
1913     return ffi_type->type == FFI_TYPE_STRUCT && (
 
1914         ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
 
1915         struct_forward_array[ffi_type->size] != 0
 
1920     int *_NSGetArgc(void);
 
1921     char ***_NSGetArgv(void);
 
1922     int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
 
1925 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
1927         NSLog(@"%s", CYCastCString(context, arguments[0]));
 
1928         return CYJSUndefined(context);
 
1932 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
 
1935     Class _class(object_getClass(self));
 
1936     if (Method method = class_getInstanceMethod(_class, _cmd))
 
1937         type = method_getTypeEncoding(method);
 
1940             NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
 
1942                 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
 
1943             type = CYPoolCString(pool, [method _typeString]);
 
1951     sig::Signature signature;
 
1952     sig::Parse(pool, &signature, type, &Structor_);
 
1955     sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
 
1957     void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
 
1958     return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
 
1961 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
1971             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
 
1973         if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
 
1974             Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
 
1975             self = data->GetValue();
 
1976             uninitialized = data->IsUninitialized();
 
1980             self = CYCastNSObject(pool, context, arguments[0]);
 
1981             uninitialized = false;
 
1985             return CYJSNull(context);
 
1987         _cmd = CYCastSEL(context, arguments[1]);
 
1990     return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
 
1993 MSHook(void, CYDealloc, id self, SEL sel) {
 
1994     CYInternal *internal;
 
1995     object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
 
1996     if (internal != NULL)
 
1998     _CYDealloc(self, sel);
 
2001 MSHook(void, objc_registerClassPair, Class _class) {
 
2002     Class super(class_getSuperclass(_class));
 
2003     if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
 
2004         class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
 
2005         MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
 
2008     _objc_registerClassPair(_class);
 
2011 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2014             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
 
2016         Class _class(CYCastNSObject(pool, context, arguments[0]));
 
2017         $objc_registerClassPair(_class);
 
2018         return CYJSUndefined(context);
 
2022 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2023     JSValueRef setup[count + 2];
 
2026     memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
 
2027     return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
 
2030 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2032     Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
 
2033     return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
 
2036 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2039             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
 
2040         const char *name(CYCastCString(context, arguments[0]));
 
2041         return CYMakeSelector(context, sel_registerName(name));
 
2045 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2048             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
 
2050         void *value(CYCastPointer<void *>(context, arguments[0]));
 
2051         const char *type(CYCastCString(context, arguments[1]));
 
2055         sig::Signature signature;
 
2056         sig::Parse(pool, &signature, type, &Structor_);
 
2058         return CYMakePointer(context, value, signature.elements[0].type, NULL);
 
2062 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2065             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
 
2066         const char *type(CYCastCString(context, arguments[1]));
 
2067         JSValueRef exception(NULL);
 
2068         if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
 
2069             JSObjectRef function(CYCastJSObject(context, arguments[0]));
 
2070             return CYMakeFunctor(context, function, type);
 
2071         } else if (exception != NULL) {
 
2074             void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
 
2075             return CYMakeFunctor(context, function, type);
 
2080 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2081     CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
 
2082     return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
 
2085 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
 
2089 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2091         CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
 
2092         return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
 
2096 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2097     return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
 
2100 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2102         CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
 
2104         sprintf(string, "%p", internal->value_);
 
2105         return CYCastJSValue(context, string);
 
2109 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2111         Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
2113             return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toCYON]));
 
2118 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2120         Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
2122             NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
 
2123             return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
 
2128 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2130         Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
 
2132             return CYCastJSValue(context, CYJSString([data->GetValue() description]));
 
2137 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2139         Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
2140         return CYCastJSValue(context, sel_getName(data->GetValue()));
 
2144 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2145     return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
 
2148 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2150         Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
2151         const char *name(sel_getName(data->GetValue()));
 
2153             return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
 
2158 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
 
2161             @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
 
2163         Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
 
2164         Class _class(CYCastNSObject(pool, context, arguments[0]));
 
2165         bool instance(CYCastBool(context, arguments[1]));
 
2166         SEL sel(data->GetValue());
 
2167         if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
 
2168             return CYCastJSValue(context, method_getTypeEncoding(method));
 
2169         else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
 
2170             return CYCastJSValue(context, CYJSString(type));
 
2172             return CYJSNull(context);
 
2176 static JSStaticValue CYValue_staticValues[2] = {
 
2177     {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
 
2178     {NULL, NULL, NULL, 0}
 
2181 static JSStaticFunction Pointer_staticFunctions[4] = {
 
2182     {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2183     {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2184     {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2188 static JSStaticFunction Functor_staticFunctions[4] = {
 
2189     {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2190     {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2191     {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2195 /*static JSStaticValue Selector_staticValues[2] = {
 
2196     {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
 
2197     {NULL, NULL, NULL, 0}
 
2200 static JSStaticFunction Instance_staticFunctions[4] = {
 
2201     {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2202     {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2203     {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2207 static JSStaticFunction Selector_staticFunctions[5] = {
 
2208     {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2209     {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2210     {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2211     {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
 
2215 CYDriver::CYDriver(const std::string &filename) :
 
2219     filename_(filename),
 
2225 CYDriver::~CYDriver() {
 
2229 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
 
2230     CYDriver::Error error;
 
2231     error.location_ = location;
 
2232     error.message_ = message;
 
2233     driver.errors_.push_back(error);
 
2236 void CYSetArgs(int argc, const char *argv[]) {
 
2237     JSContextRef context(CYGetJSContext());
 
2238     JSValueRef args[argc];
 
2239     for (int i(0); i != argc; ++i)
 
2240         args[i] = CYCastJSValue(context, argv[i]);
 
2241     JSValueRef exception(NULL);
 
2242     JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
 
2243     CYThrow(context, exception);
 
2244     CYSetProperty(context, System_, CYJSString("args"), array);
 
2247 JSObjectRef CYGetGlobalObject(JSContextRef context) {
 
2248     return JSContextGetGlobalObject(context);
 
2251 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
 
2252     JSStringRef script(JSStringCreateWithUTF8CString(code));
 
2254     JSContextRef context(CYGetJSContext());
 
2256     JSValueRef exception(NULL);
 
2257     JSValueRef result(JSEvaluateScript(context, script, NULL, NULL, 0, &exception));
 
2258     JSStringRelease(script);
 
2260     if (exception != NULL) { error:
 
2265     if (JSValueIsUndefined(context, result))
 
2268     const char *json(CYPoolCYONString(pool, context, result, &exception));
 
2269     if (exception != NULL)
 
2272     CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
 
2276 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
 
2277     while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
 
2285 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
 
2286     while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
 
2299     const char * volatile data_;
 
2302 // XXX: this is "tre lame"
 
2303 @interface CYClient_ : NSObject {
 
2306 - (void) execute:(NSValue *)value;
 
2310 @implementation CYClient_
 
2312 - (void) execute:(NSValue *)value {
 
2313     CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
 
2314     NSLog(@"b:%p", execute->data_);
 
2315     NSLog(@"s:%s", execute->data_);
 
2316     execute->data_ = CYExecute(execute->pool_, execute->data_);
 
2317     NSLog(@"a:%p", execute->data_);
 
2326     apr_thread_t *thread_;
 
2328     CYClient(int socket) :
 
2334         _syscall(close(socket_));
 
2337     void Handle() { _pooled
 
2338         CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
 
2342             if (!CYRecvAll(socket_, &size, sizeof(size)))
 
2346             char *data(new(pool) char[size + 1]);
 
2347             if (!CYRecvAll(socket_, data, size))
 
2351             CYDriver driver("");
 
2352             cy::parser parser(driver);
 
2354             driver.data_ = data;
 
2355             driver.size_ = size;
 
2358             if (parser.parse() != 0 || !driver.errors_.empty()) {
 
2360                 size = _not(size_t);
 
2362                 std::ostringstream str;
 
2363                 driver.source_->Show(str);
 
2364                 std::string code(str.str());
 
2365                 CYExecute_ execute = {pool, code.c_str()};
 
2366                 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
 
2367                 json = execute.data_;
 
2368                 size = json == NULL ? _not(size_t) : strlen(json);
 
2371             if (!CYSendAll(socket_, &size, sizeof(size)))
 
2374                 if (!CYSendAll(socket_, json, size))
 
2380 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
 
2381     CYClient *client(reinterpret_cast<CYClient *>(data));
 
2387 static void * APR_THREAD_FUNC Cyrver(apr_thread_t *thread, void *data) {
 
2389         int socket(_syscall(accept(Socket_, NULL, NULL)));
 
2390         CYClient *client(new CYClient(socket));
 
2391         apr_threadattr_t *attr;
 
2392         _aprcall(apr_threadattr_create(&attr, Pool_));
 
2393         _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
 
2399 MSInitialize { _pooled
 
2400     _aprcall(apr_initialize());
 
2401     _aprcall(apr_pool_create(&Pool_, NULL));
 
2403     Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
 
2404     NSCFBoolean_ = objc_getClass("NSCFBoolean");
 
2406     Socket_ = _syscall(socket(PF_UNIX, SOCK_STREAM, 0));
 
2408     struct sockaddr_un address;
 
2409     memset(&address, 0, sizeof(address));
 
2410     address.sun_family = AF_UNIX;
 
2412     pid_t pid(getpid());
 
2413     sprintf(address.sun_path, "/tmp/.s.cy.%u", pid);
 
2416         _syscall(bind(Socket_, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
 
2417         _syscall(listen(Socket_, 0));
 
2419         apr_threadattr_t *attr;
 
2420         _aprcall(apr_threadattr_create(&attr, Pool_));
 
2422         apr_thread_t *thread;
 
2423         _aprcall(apr_thread_create(&thread, attr, &Cyrver, NULL, Pool_));
 
2425         NSLog(@"failed to setup Cyrver");
 
2429 JSGlobalContextRef CYGetJSContext() {
 
2430     if (Context_ == NULL) {
 
2431         JSClassDefinition definition;
 
2433         definition = kJSClassDefinitionEmpty;
 
2434         definition.className = "Pointer";
 
2435         definition.staticFunctions = Pointer_staticFunctions;
 
2436         definition.getProperty = &Pointer_getProperty;
 
2437         definition.setProperty = &Pointer_setProperty;
 
2438         definition.finalize = &CYData::Finalize;
 
2439         Pointer_ = JSClassCreate(&definition);
 
2441         definition = kJSClassDefinitionEmpty;
 
2442         definition.className = "Functor";
 
2443         definition.staticFunctions = Functor_staticFunctions;
 
2444         definition.callAsFunction = &Functor_callAsFunction;
 
2445         definition.finalize = &CYData::Finalize;
 
2446         Functor_ = JSClassCreate(&definition);
 
2448         definition = kJSClassDefinitionEmpty;
 
2449         definition.className = "Struct";
 
2450         definition.getProperty = &Struct_getProperty;
 
2451         definition.setProperty = &Struct_setProperty;
 
2452         definition.getPropertyNames = &Struct_getPropertyNames;
 
2453         definition.finalize = &CYData::Finalize;
 
2454         Struct_ = JSClassCreate(&definition);
 
2456         definition = kJSClassDefinitionEmpty;
 
2457         definition.className = "Selector";
 
2458         definition.staticValues = CYValue_staticValues;
 
2459         //definition.staticValues = Selector_staticValues;
 
2460         definition.staticFunctions = Selector_staticFunctions;
 
2461         definition.callAsFunction = &Selector_callAsFunction;
 
2462         definition.finalize = &CYData::Finalize;
 
2463         Selector_ = JSClassCreate(&definition);
 
2465         definition = kJSClassDefinitionEmpty;
 
2466         definition.className = "Instance";
 
2467         definition.staticValues = CYValue_staticValues;
 
2468         definition.staticFunctions = Instance_staticFunctions;
 
2469         definition.getProperty = &Instance_getProperty;
 
2470         definition.setProperty = &Instance_setProperty;
 
2471         definition.deleteProperty = &Instance_deleteProperty;
 
2472         definition.callAsConstructor = &Instance_callAsConstructor;
 
2473         definition.finalize = &CYData::Finalize;
 
2474         Instance_ = JSClassCreate(&definition);
 
2476         definition = kJSClassDefinitionEmpty;
 
2477         definition.className = "Runtime";
 
2478         definition.getProperty = &Runtime_getProperty;
 
2479         Runtime_ = JSClassCreate(&definition);
 
2481         definition = kJSClassDefinitionEmpty;
 
2482         //definition.getProperty = &Global_getProperty;
 
2483         JSClassRef Global(JSClassCreate(&definition));
 
2485         JSGlobalContextRef context(JSGlobalContextCreate(Global));
 
2488         JSObjectRef global(CYGetGlobalObject(context));
 
2490         JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
 
2491         CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
 
2493         CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
 
2494         CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
 
2495         CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
 
2497         MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
 
2499         CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
 
2500         CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
 
2502         System_ = JSObjectMake(context, NULL, NULL);
 
2503         CYSetProperty(context, global, CYJSString("system"), System_);
 
2504         CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
 
2505         //CYSetProperty(context, System_, CYJSString("global"), global);
 
2507         CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
 
2509         Result_ = JSStringCreateWithUTF8CString("_");
 
2511         length_ = JSStringCreateWithUTF8CString("length");
 
2512         message_ = JSStringCreateWithUTF8CString("message");
 
2513         name_ = JSStringCreateWithUTF8CString("name");
 
2514         toCYON_ = JSStringCreateWithUTF8CString("toCYON");
 
2515         toJSON_ = JSStringCreateWithUTF8CString("toJSON");
 
2517         Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
 
2518         Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));