]> git.saurik.com Git - cycript.git/blobdiff - Library.mm
Added Instance constructor instance (for Instance.prototype), implemented Type class...
[cycript.git] / Library.mm
index 6605c567a007a5055274d0ee912480506e66211a..c4289e7086a8d937c709cae8f01709384b9ecfc4 100644 (file)
@@ -58,6 +58,8 @@
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
+#include <sys/un.h>
+
 #include <sys/mman.h>
 
 #include <iostream>
 #include <set>
 #include <map>
 
+#include <sstream>
 #include <cmath>
 
 #include "Parser.hpp"
 #include "Cycript.tab.hh"
 
+#include <fcntl.h>
+
+#include <apr-1/apr_thread_proc.h>
+
 #undef _assert
 #undef _trace
 
@@ -107,10 +114,13 @@ static JSClassRef Pointer_;
 static JSClassRef Runtime_;
 static JSClassRef Selector_;
 static JSClassRef Struct_;
+static JSClassRef Type_;
 
 static JSObjectRef Array_;
 static JSObjectRef Function_;
 
+static JSStringRef Result_;
+
 static JSStringRef length_;
 static JSStringRef message_;
 static JSStringRef name_;
@@ -123,39 +133,50 @@ static NSArray *Bridge_;
 
 struct CYData {
     apr_pool_t *pool_;
-    void *value_;
-
-    CYData() {
-    }
 
-    CYData(void *value) :
-        value_(value)
-    {
+    virtual ~CYData() {
     }
 
-    virtual ~CYData() {
+    static void *operator new(size_t size, apr_pool_t *pool) {
+        void *data(apr_palloc(pool, size));
+        reinterpret_cast<CYData *>(data)->pool_ = pool;
+        return data;
     }
 
-    void *operator new(size_t size) {
+    static void *operator new(size_t size) {
         apr_pool_t *pool;
         apr_pool_create(&pool, NULL);
-        void *data(apr_palloc(pool, size));
-        reinterpret_cast<CYData *>(data)->pool_ = pool;
-        return data;;
+        return operator new(size, pool);
+    }
+
+    static void operator delete(void *data) {
+        apr_pool_destroy(reinterpret_cast<CYData *>(data)->pool_);
     }
 
     static void Finalize(JSObjectRef object) {
-        CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
-        data->~CYData();
-        apr_pool_destroy(data->pool_);
+        delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
     }
 };
 
-struct Selector_privateData :
+struct CYValue :
     CYData
+{
+    void *value_;
+
+    CYValue() {
+    }
+
+    CYValue(void *value) :
+        value_(value)
+    {
+    }
+};
+
+struct Selector_privateData :
+    CYValue
 {
     Selector_privateData(SEL value) :
-        CYData(value)
+        CYValue(value)
     {
     }
 
@@ -165,7 +186,7 @@ struct Selector_privateData :
 };
 
 struct Instance :
-    CYData
+    CYValue
 {
     enum Flags {
         None          = 0,
@@ -176,14 +197,15 @@ struct Instance :
     Flags flags_;
 
     Instance(id value, Flags flags) :
-        CYData(value),
+        CYValue(value),
         flags_(flags)
     {
     }
 
     virtual ~Instance() {
         if ((flags_ & Transient) == 0)
-            [GetValue() release];
+            // XXX: does this handle background threads correctly?
+            [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
     }
 
     static JSObjectRef Make(JSContextRef context, id object, Flags flags) {
@@ -272,29 +294,56 @@ struct CStringMapLess :
     }
 };
 
-struct Type_privateData {
-    apr_pool_t *pool_;
+void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
+    if (name == NULL)
+        return;
+
+    CYPoolTry {
+        if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
+            switch ([[entry objectAtIndex:0] intValue]) {
+                case 0: {
+                    sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
+                } break;
+
+                case 1: {
+                    sig::Signature signature;
+                    sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
+                    type = signature.elements[0].type;
+                } break;
+            }
+    } CYPoolCatch()
+}
 
+struct Type_privateData :
+    CYData
+{
     ffi_type *ffi_;
     sig::Type *type_;
 
-    Type_privateData(apr_pool_t *pool, sig::Type *type) :
-        pool_(pool),
+    void Set(sig::Type *type) {
+        type_ = new(pool_) sig::Type;
+        sig::Copy(pool_, *type_, *type);
+    }
+
+    Type_privateData(const char *type) :
         ffi_(NULL)
     {
-        if (type != NULL) {
-            type_ = new(pool) sig::Type;
-            sig::Copy(pool, *type_, *type);
-        }
+        sig::Signature signature;
+        sig::Parse(pool_, &signature, type, &Structor_);
+        type_ = signature.elements[0].type;
     }
 
-    Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) :
-        pool_(pool)
+    Type_privateData(sig::Type *type) :
+        ffi_(NULL)
     {
-        ffi_ = new(pool) ffi_type;
-        sig::Copy(pool, *ffi_, *ffi);
-        type_ = new(pool) sig::Type;
-        sig::Copy(pool, *type_, *type);
+        if (type != NULL)
+            Set(type);
+    }
+
+    Type_privateData(sig::Type *type, ffi_type *ffi) {
+        ffi_ = new(pool_) ffi_type;
+        sig::Copy(pool_, *ffi_, *ffi);
+        Set(type);
     }
 
     ffi_type *GetFFI() {
@@ -320,21 +369,21 @@ struct Type_privateData {
 };
 
 struct Pointer :
-    CYData
+    CYValue
 {
     JSObjectRef owner_;
     Type_privateData *type_;
 
     Pointer(void *value, sig::Type *type, JSObjectRef owner) :
-        CYData(value),
+        CYValue(value),
         owner_(owner),
-        type_(new(pool_) Type_privateData(pool_, type))
+        type_(new(pool_) Type_privateData(type))
     {
     }
 };
 
 struct Struct_privateData :
-    CYData
+    CYValue
 {
     JSObjectRef owner_;
     Type_privateData *type_;
@@ -351,7 +400,7 @@ static TypeMap Types_;
 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
     Struct_privateData *internal(new Struct_privateData(owner));
     apr_pool_t *pool(internal->pool_);
-    Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
+    Type_privateData *typical(new(pool) Type_privateData(type, ffi));
     internal->type_ = typical;
 
     if (owner != NULL)
@@ -366,30 +415,14 @@ JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_
     return JSObjectMake(context, Struct_, internal);
 }
 
-void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *type) {
-    if (name == NULL)
-        return;
-
-    CYPoolTry {
-        if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]]) {
-            switch ([[entry objectAtIndex:0] intValue]) {
-                case 0:
-                    static CYPool Pool_;
-                    sig::Parse(Pool_, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
-                break;
-            }
-        }
-    } CYPoolCatch()
-}
-
 struct Functor_privateData :
-    CYData
+    CYValue
 {
     sig::Signature signature_;
     ffi_cif cif_;
 
     Functor_privateData(const char *type, void (*value)()) :
-        CYData(reinterpret_cast<void *>(value))
+        CYValue(reinterpret_cast<void *>(value))
     {
         sig::Parse(pool_, &signature_, type, &Structor_);
         sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
@@ -408,7 +441,7 @@ struct ffoData :
     }
 };
 
-JSValueRef CYMakeInstance(JSContextRef context, id object, bool transient) {
+JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
     Instance::Flags flags;
 
     if (transient)
@@ -481,25 +514,24 @@ bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
 
 @interface NSObject (Cycript)
 
+- (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
 - (JSType) cy$JSType;
 
 - (NSObject *) cy$toJSON:(NSString *)key;
 - (NSString *) cy$toCYON;
 - (NSString *) cy$toKey;
 
-- (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
-
 - (NSObject *) cy$getProperty:(NSString *)name;
 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
 - (bool) cy$deleteProperty:(NSString *)name;
 
 @end
 
-@interface NSString (Cycript)
-- (void *) cy$symbol;
+@protocol Cycript
+- (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
 @end
 
-@interface NSNumber (Cycript)
+@interface NSString (Cycript)
 - (void *) cy$symbol;
 @end
 
@@ -591,6 +623,10 @@ struct PropertyAttributes {
 
 @implementation NSObject (Cycript)
 
+- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
+    return CYMakeInstance(context, self, false);
+}
+
 - (JSType) cy$JSType {
     return kJSTypeObject;
 }
@@ -607,10 +643,6 @@ struct PropertyAttributes {
     return [self cy$toCYON];
 }
 
-- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
-    return CYMakeInstance(context, self, false);
-}
-
 - (NSObject *) cy$getProperty:(NSString *)name {
     /*if (![name isEqualToString:@"prototype"])
         NSLog(@"get:%@", name);*/
@@ -791,10 +823,6 @@ struct PropertyAttributes {
     return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
 }
 
-- (void *) cy$symbol {
-    return [self pointerValue];
-}
-
 @end
 
 @implementation NSString (Cycript)
@@ -888,10 +916,6 @@ CYRange DigitRange_    (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
 CYRange WordEndRange_  (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
 
-JSGlobalContextRef CYGetJSContext() {
-    return Context_;
-}
-
 #define CYTry \
     @try
 #define CYCatch \
@@ -1144,7 +1168,12 @@ JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
 }
 
 JSValueRef CYCastJSValue(JSContextRef context, id value) {
-    return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context];
+    if (value == nil)
+        return CYJSNull(context);
+    else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
+        return [value cy$JSValueInContext:context];
+    else
+        return CYMakeInstance(context, value, false);
 }
 
 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
@@ -1292,6 +1321,57 @@ const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef
     } else return NULL;
 }
 
+// XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
+struct CYInternal :
+    CYData
+{
+    JSObjectRef object_;
+
+    CYInternal() :
+        object_(NULL)
+    {
+    }
+
+    ~CYInternal() {
+        // XXX: delete object_? ;(
+    }
+
+    static CYInternal *Get(id self) {
+        CYInternal *internal(NULL);
+        if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
+            // XXX: do something epic? ;P
+        }
+
+        return internal;
+    }
+
+    static CYInternal *Set(id self) {
+        CYInternal *internal(NULL);
+        if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
+            if (internal == NULL) {
+                internal = new CYInternal();
+                object_setIvar(self, ivar, reinterpret_cast<id>(internal));
+            }
+        } else {
+            // XXX: do something epic? ;P
+        }
+
+        return internal;
+    }
+
+    JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
+        if (object_ == NULL)
+            return NULL;
+        return CYGetProperty(context, object_, name);
+    }
+
+    void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
+        if (object_ == NULL)
+            object_ = JSObjectMake(context, NULL, NULL);
+        CYSetProperty(context, object_, name, value);
+    }
+};
+
 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
     CYPool pool;
 
@@ -1299,6 +1379,10 @@ static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object,
         NSString *self(CYCastNSObject(pool, context, object));
         NSString *name(CYCastNSString(pool, property));
 
+        if (CYInternal *internal = CYInternal::Get(self))
+            if (JSValueRef value = internal->GetProperty(context, property))
+                return value;
+
         CYPoolTry {
             if (NSObject *data = [self cy$getProperty:name])
                 return CYCastJSValue(context, data);
@@ -1337,6 +1421,11 @@ static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStr
             }
         }
 
+        if (CYInternal *internal = CYInternal::Set(self)) {
+            internal->SetProperty(context, property, value);
+            return true;
+        }
+
         return false;
     } CYCatch
 }
@@ -1374,31 +1463,20 @@ JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *
     return JSObjectMake(context, Functor_, data);
 }
 
-const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
+const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
     if (pool == NULL) {
         const char *string([CYCastNSString(NULL, value) UTF8String]);
-        if (length != NULL)
-            *length = strlen(string);
         return string;
     } else {
         size_t size(JSStringGetMaximumUTF8CStringSize(value));
         char *string(new(pool) char[size]);
         JSStringGetUTF8CString(value, string, size);
-        // XXX: this is ironic
-        if (length != NULL)
-            *length = strlen(string);
         return string;
     }
 }
 
-const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
-    if (!JSValueIsNull(context, value))
-        return CYPoolCString(pool, CYJSString(context, value), length);
-    else {
-        if (length != NULL)
-            *length = 0;
-        return NULL;
-    }
+const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
+    return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
 }
 
 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
@@ -1612,8 +1690,8 @@ bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property
     if (type == NULL)
         return false;
 
-    size_t length;
-    const char *name(CYPoolCString(pool, property, &length));
+    const char *name(CYPoolCString(pool, property));
+    size_t length(strlen(name));
     double number(CYCastDouble(name, length));
 
     size_t count(type->data.signature.count);
@@ -1800,12 +1878,11 @@ JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char
     // XXX: in case of exceptions this will leak
     ffoData *data(new ffoData(type));
 
-    ffi_closure *closure;
-    _syscall(closure = (ffi_closure *) mmap(
+    ffi_closure *closure((ffi_closure *) _syscall(mmap(
         NULL, sizeof(ffi_closure),
         PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
         -1, 0
-    ));
+    )));
 
     ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
     _assert(status == FFI_OK);
@@ -1864,25 +1941,6 @@ static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjec
     } CYCatch
 }
 
-static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
-    CYTry {
-        CYPool pool;
-
-        int argc(CYCastDouble(context, arguments[0]));
-        char **argv(CYCastPointer<char **>(context, arguments[1]));
-        NSString *principal(CYCastNSObject(pool, context, arguments[2]));
-        NSString *delegate(CYCastNSObject(pool, context, arguments[3]));
-
-        argc = *_NSGetArgc() - 1;
-        argv = *_NSGetArgv() + 1;
-        for (int i(0); i != argc; ++i)
-            NSLog(@"argv[%i]=%s", i, argv[i]);
-
-        _pooled
-        return CYCastJSValue(context, UIApplicationMain(argc, argv, principal, delegate));
-    } CYCatch
-}
-
 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
     const char *type;
 
@@ -1890,12 +1948,14 @@ JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _c
     if (Method method = class_getInstanceMethod(_class, _cmd))
         type = method_getTypeEncoding(method);
     else {
-        CYPoolTry {
-            NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
-            if (method == nil)
-                @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
-            type = CYPoolCString(pool, [method _typeString]);
-        } CYPoolCatch(NULL)
+        CYTry {
+            CYPoolTry {
+                NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
+                if (method == nil)
+                    @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
+                type = CYPoolCString(pool, [method _typeString]);
+            } CYPoolCatch(NULL)
+        } CYCatch
     }
 
     void *setup[2];
@@ -1944,6 +2004,35 @@ static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObje
     return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
 }
 
+MSHook(void, CYDealloc, id self, SEL sel) {
+    CYInternal *internal;
+    object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
+    if (internal != NULL)
+        delete internal;
+    _CYDealloc(self, sel);
+}
+
+MSHook(void, objc_registerClassPair, Class _class) {
+    Class super(class_getSuperclass(_class));
+    if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
+        class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
+        MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
+    }
+
+    _objc_registerClassPair(_class);
+}
+
+static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    CYTry {
+        if (count != 1)
+            @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
+        CYPool pool;
+        Class _class(CYCastNSObject(pool, context, arguments[0]));
+        $objc_registerClassPair(_class);
+        return CYJSUndefined(context);
+    } CYCatch
+}
+
 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     JSValueRef setup[count + 2];
     setup[0] = _this;
@@ -1967,6 +2056,63 @@ JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count,
     } CYCatch
 }
 
+JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    CYTry {
+        if (count != 2)
+            @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
+
+        void *value(CYCastPointer<void *>(context, arguments[0]));
+        const char *type(CYCastCString(context, arguments[1]));
+
+        CYPool pool;
+
+        sig::Signature signature;
+        sig::Parse(pool, &signature, type, &Structor_);
+
+        return CYMakePointer(context, value, signature.elements[0].type, NULL);
+    } CYCatch
+}
+
+JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
+    Type_privateData *internal(new Type_privateData(type));
+    return JSObjectMake(context, Type_, internal);
+}
+
+JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    CYTry {
+        if (count != 1)
+            @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
+        const char *type(CYCastCString(context, arguments[0]));
+        return CYMakeType(context, object, type);
+    } CYCatch
+}
+
+static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    CYTry {
+        if (count != 1)
+            @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
+        Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
+        sig::Type *type(internal->type_);
+        ffi_type *ffi(internal->GetFFI());
+        // XXX: alignment?
+        uint8_t value[ffi->size];
+        CYPool pool;
+        CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
+        return CYFromFFI(context, type, ffi, value, false);
+    } CYCatch
+}
+
+static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    CYTry {
+        if (count > 1)
+            @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
+        Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
+        // XXX: alignment?
+        void *value(malloc(internal->GetFFI()->size));
+        return CYMakePointer(context, value, internal->type_, NULL);
+    } CYCatch
+}
+
 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYTry {
         if (count != 2)
@@ -1985,50 +2131,50 @@ JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count,
     } CYCatch
 }
 
-JSValueRef CYData_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
-    CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
-    return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
+JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+    CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
+    return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
 }
 
 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
     return Function_;
 }
 
-static JSValueRef CYData_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYTry {
-        CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(_this)));
-        return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
+        CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
+        return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
     } CYCatch
 }
 
-static JSValueRef CYData_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
-    return CYData_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
+static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
 }
 
-static JSValueRef CYData_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYTry {
-        CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(_this)));
+        CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
         char string[32];
-        sprintf(string, "%p", data->value_);
+        sprintf(string, "%p", internal->value_);
         return CYCastJSValue(context, string);
     } CYCatch
 }
 
 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYTry {
-        Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
+        Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
         CYPoolTry {
-            return CYCastJSValue(context, CYJSString([data->GetValue() cy$toCYON]));
+            return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toCYON]));
         } CYPoolCatch(NULL)
     } CYCatch
 }
 
 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     CYTry {
-        Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
+        Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
         CYPoolTry {
             NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
-            return CYCastJSValue(context, CYJSString([data->GetValue() cy$toJSON:key]));
+            return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
         } CYPoolCatch(NULL)
     } CYCatch
 }
@@ -2081,22 +2227,22 @@ static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef
     } CYCatch
 }
 
-static JSStaticValue CYData_staticValues[2] = {
-    {"value", &CYData_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
+static JSStaticValue CYValue_staticValues[2] = {
+    {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
     {NULL, NULL, NULL, 0}
 };
 
 static JSStaticFunction Pointer_staticFunctions[4] = {
-    {"toCYON", &CYData_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
-    {"toJSON", &CYData_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
-    {"valueOf", &CYData_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
     {NULL, NULL, 0}
 };
 
 static JSStaticFunction Functor_staticFunctions[4] = {
-    {"toCYON", &CYData_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
-    {"toJSON", &CYData_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
-    {"valueOf", &CYData_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+    {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
     {NULL, NULL, 0}
 };
 
@@ -2156,94 +2302,292 @@ JSObjectRef CYGetGlobalObject(JSContextRef context) {
     return JSContextGetGlobalObject(context);
 }
 
+const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
+    JSStringRef script(JSStringCreateWithUTF8CString(code));
+
+    JSContextRef context(CYGetJSContext());
+
+    JSValueRef exception(NULL);
+    JSValueRef result(JSEvaluateScript(context, script, NULL, NULL, 0, &exception));
+    JSStringRelease(script);
+
+    if (exception != NULL) { error:
+        result = exception;
+        exception = NULL;
+    }
+
+    if (JSValueIsUndefined(context, result))
+        return NULL;
+
+    const char *json(CYPoolCYONString(pool, context, result, &exception));
+    if (exception != NULL)
+        goto error;
+
+    CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
+    return json;
+}
+
+bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
+    while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
+        data += writ;
+        size -= writ;
+    } else
+        return false;
+    return true;
+}
+
+bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
+    while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
+        data += writ;
+        size -= writ;
+    } else
+        return false;
+    return true;
+}
+
+static int Socket_;
+apr_pool_t *Pool_;
+
+struct CYExecute_ {
+    apr_pool_t *pool_;
+    const char * volatile data_;
+};
+
+// XXX: this is "tre lame"
+@interface CYClient_ : NSObject {
+}
+
+- (void) execute:(NSValue *)value;
+
+@end
+
+@implementation CYClient_
+
+- (void) execute:(NSValue *)value {
+    CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
+    NSLog(@"b:%p", execute->data_);
+    NSLog(@"s:%s", execute->data_);
+    execute->data_ = CYExecute(execute->pool_, execute->data_);
+    NSLog(@"a:%p", execute->data_);
+}
+
+@end
+
+struct CYClient :
+    CYData
+{
+    int socket_;
+    apr_thread_t *thread_;
+
+    CYClient(int socket) :
+        socket_(socket)
+    {
+    }
+
+    ~CYClient() {
+        _syscall(close(socket_));
+    }
+
+    void Handle() { _pooled
+        CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
+
+        for (;;) {
+            size_t size;
+            if (!CYRecvAll(socket_, &size, sizeof(size)))
+                return;
+
+            CYPool pool;
+            char *data(new(pool) char[size + 1]);
+            if (!CYRecvAll(socket_, data, size))
+                return;
+            data[size] = '\0';
+
+            CYDriver driver("");
+            cy::parser parser(driver);
+
+            driver.data_ = data;
+            driver.size_ = size;
+
+            const char *json;
+            if (parser.parse() != 0 || !driver.errors_.empty()) {
+                json = NULL;
+                size = _not(size_t);
+            } else {
+                std::ostringstream str;
+                driver.source_->Show(str);
+                std::string code(str.str());
+                CYExecute_ execute = {pool, code.c_str()};
+                [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
+                json = execute.data_;
+                size = json == NULL ? _not(size_t) : strlen(json);
+            }
+
+            if (!CYSendAll(socket_, &size, sizeof(size)))
+                return;
+            if (json != NULL)
+                if (!CYSendAll(socket_, json, size))
+                    return;
+        }
+    }
+};
+
+static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
+    CYClient *client(reinterpret_cast<CYClient *>(data));
+    client->Handle();
+    delete client;
+    return NULL;
+}
+
+static void * APR_THREAD_FUNC Cyrver(apr_thread_t *thread, void *data) {
+    for (;;) {
+        int socket(_syscall(accept(Socket_, NULL, NULL)));
+        CYClient *client(new CYClient(socket));
+        apr_threadattr_t *attr;
+        _aprcall(apr_threadattr_create(&attr, Pool_));
+        _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
+    }
+
+    return NULL;
+}
+
+void Unlink() {
+    pid_t pid(getpid());
+    char path[104];
+    sprintf(path, "/tmp/.s.cy.%u", pid);
+    unlink(path);
+}
+
 MSInitialize { _pooled
-    apr_initialize();
+    _aprcall(apr_initialize());
+    _aprcall(apr_pool_create(&Pool_, NULL));
 
     Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
-
     NSCFBoolean_ = objc_getClass("NSCFBoolean");
 
-    JSClassDefinition definition;
-
-    definition = kJSClassDefinitionEmpty;
-    definition.className = "Pointer";
-    definition.staticFunctions = Pointer_staticFunctions;
-    definition.getProperty = &Pointer_getProperty;
-    definition.setProperty = &Pointer_setProperty;
-    definition.finalize = &CYData::Finalize;
-    Pointer_ = JSClassCreate(&definition);
-
-    definition = kJSClassDefinitionEmpty;
-    definition.className = "Functor";
-    definition.staticFunctions = Functor_staticFunctions;
-    definition.callAsFunction = &Functor_callAsFunction;
-    definition.finalize = &CYData::Finalize;
-    Functor_ = JSClassCreate(&definition);
-
-    definition = kJSClassDefinitionEmpty;
-    definition.className = "Struct";
-    definition.getProperty = &Struct_getProperty;
-    definition.setProperty = &Struct_setProperty;
-    definition.getPropertyNames = &Struct_getPropertyNames;
-    definition.finalize = &CYData::Finalize;
-    Struct_ = JSClassCreate(&definition);
-
-    definition = kJSClassDefinitionEmpty;
-    definition.className = "Selector";
-    definition.staticValues = CYData_staticValues;
-    //definition.staticValues = Selector_staticValues;
-    definition.staticFunctions = Selector_staticFunctions;
-    definition.callAsFunction = &Selector_callAsFunction;
-    definition.finalize = &CYData::Finalize;
-    Selector_ = JSClassCreate(&definition);
-
-    definition = kJSClassDefinitionEmpty;
-    definition.className = "Instance";
-    definition.staticValues = CYData_staticValues;
-    definition.staticFunctions = Instance_staticFunctions;
-    definition.getProperty = &Instance_getProperty;
-    definition.setProperty = &Instance_setProperty;
-    definition.deleteProperty = &Instance_deleteProperty;
-    definition.callAsConstructor = &Instance_callAsConstructor;
-    definition.finalize = &CYData::Finalize;
-    Instance_ = JSClassCreate(&definition);
-
-    definition = kJSClassDefinitionEmpty;
-    definition.className = "Runtime";
-    definition.getProperty = &Runtime_getProperty;
-    Runtime_ = JSClassCreate(&definition);
-
-    definition = kJSClassDefinitionEmpty;
-    //definition.getProperty = &Global_getProperty;
-    JSClassRef Global(JSClassCreate(&definition));
-
-    JSGlobalContextRef context(JSGlobalContextCreate(Global));
-    Context_ = context;
-
-    JSObjectRef global(CYGetGlobalObject(context));
-
-    JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
-    CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
-
-    CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
-    CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
-
-    CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
-    CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
-
-    System_ = JSObjectMake(context, NULL, NULL);
-    CYSetProperty(context, global, CYJSString("system"), System_);
-    CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
-    //CYSetProperty(context, System_, CYJSString("global"), global);
-
-    CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
-
-    length_ = JSStringCreateWithUTF8CString("length");
-    message_ = JSStringCreateWithUTF8CString("message");
-    name_ = JSStringCreateWithUTF8CString("name");
-    toCYON_ = JSStringCreateWithUTF8CString("toCYON");
-    toJSON_ = JSStringCreateWithUTF8CString("toJSON");
-
-    Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
-    Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
+    Socket_ = _syscall(socket(PF_UNIX, SOCK_STREAM, 0));
+
+    struct sockaddr_un address;
+    memset(&address, 0, sizeof(address));
+    address.sun_family = AF_UNIX;
+
+    pid_t pid(getpid());
+    sprintf(address.sun_path, "/tmp/.s.cy.%u", pid);
+
+    try {
+        _syscall(bind(Socket_, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
+        atexit(&Unlink);
+        _syscall(listen(Socket_, 0));
+
+        apr_threadattr_t *attr;
+        _aprcall(apr_threadattr_create(&attr, Pool_));
+
+        apr_thread_t *thread;
+        _aprcall(apr_thread_create(&thread, attr, &Cyrver, NULL, Pool_));
+    } catch (...) {
+        NSLog(@"failed to setup Cyrver");
+    }
+}
+
+JSGlobalContextRef CYGetJSContext() {
+    if (Context_ == NULL) {
+        JSClassDefinition definition;
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Functor";
+        definition.staticFunctions = Functor_staticFunctions;
+        definition.callAsFunction = &Functor_callAsFunction;
+        definition.finalize = &CYData::Finalize;
+        Functor_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Instance";
+        definition.staticValues = CYValue_staticValues;
+        definition.staticFunctions = Instance_staticFunctions;
+        definition.getProperty = &Instance_getProperty;
+        definition.setProperty = &Instance_setProperty;
+        definition.deleteProperty = &Instance_deleteProperty;
+        definition.callAsConstructor = &Instance_callAsConstructor;
+        definition.finalize = &CYData::Finalize;
+        Instance_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Pointer";
+        definition.staticFunctions = Pointer_staticFunctions;
+        definition.getProperty = &Pointer_getProperty;
+        definition.setProperty = &Pointer_setProperty;
+        definition.finalize = &CYData::Finalize;
+        Pointer_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Selector";
+        definition.staticValues = CYValue_staticValues;
+        //definition.staticValues = Selector_staticValues;
+        definition.staticFunctions = Selector_staticFunctions;
+        definition.callAsFunction = &Selector_callAsFunction;
+        definition.finalize = &CYData::Finalize;
+        Selector_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Struct";
+        definition.getProperty = &Struct_getProperty;
+        definition.setProperty = &Struct_setProperty;
+        definition.getPropertyNames = &Struct_getPropertyNames;
+        definition.finalize = &CYData::Finalize;
+        Struct_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Type";
+        definition.callAsFunction = &Type_callAsFunction;
+        definition.callAsConstructor = &Type_callAsConstructor;
+        definition.finalize = &CYData::Finalize;
+        Type_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        definition.className = "Runtime";
+        definition.getProperty = &Runtime_getProperty;
+        Runtime_ = JSClassCreate(&definition);
+
+        definition = kJSClassDefinitionEmpty;
+        //definition.getProperty = &Global_getProperty;
+        JSClassRef Global(JSClassCreate(&definition));
+
+        JSGlobalContextRef context(JSGlobalContextCreate(Global));
+        Context_ = context;
+
+        JSObjectRef global(CYGetGlobalObject(context));
+
+        JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
+        CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
+
+        CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
+        CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, NULL));
+        CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
+        CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
+        CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
+
+        MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
+
+        CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
+        CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
+
+        System_ = JSObjectMake(context, NULL, NULL);
+        CYSetProperty(context, global, CYJSString("system"), System_);
+        CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
+        //CYSetProperty(context, System_, CYJSString("global"), global);
+
+        CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
+
+        Result_ = JSStringCreateWithUTF8CString("_");
+
+        length_ = JSStringCreateWithUTF8CString("length");
+        message_ = JSStringCreateWithUTF8CString("message");
+        name_ = JSStringCreateWithUTF8CString("name");
+        toCYON_ = JSStringCreateWithUTF8CString("toCYON");
+        toJSON_ = JSStringCreateWithUTF8CString("toJSON");
+
+        Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
+        Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
+    }
+
+    return Context_;
 }