]> git.saurik.com Git - cycript.git/blobdiff - Tweak.mm
Hierarchialization.
[cycript.git] / Tweak.mm
index 2be2afc3a8344010fa8677be5a6e31c1f0de516d..21c91a135ba7d06f896f48ee9a3f30d9830293f4 100644 (file)
--- a/Tweak.mm
+++ b/Tweak.mm
@@ -134,6 +134,14 @@ class _H {
 
 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
 
+void *operator new(size_t size, apr_pool_t *pool) {
+    return apr_palloc(pool, size);
+}
+
+void *operator new [](size_t size, apr_pool_t *pool) {
+    return apr_palloc(pool, size);
+}
+
 static JSContextRef Context_;
 
 static JSClassRef ffi_;
@@ -154,6 +162,10 @@ struct Client {
     CFSocketRef socket_;
 };
 
+JSObjectRef CYMakeObject(JSContextRef context, id object) {
+    return JSObjectMake(context, joc_, [object retain]);
+}
+
 @interface NSMethodSignature (Cyrver)
 - (NSString *) _typeString;
 @end
@@ -170,7 +182,7 @@ struct Client {
 }
 
 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
-    return JSObjectMake(context, joc_, [self retain]);
+    return CYMakeObject(context, self);
 }
 
 @end
@@ -264,7 +276,7 @@ struct Client {
 
 @end
 
-@interface CY$JSObject : NSDictionary {
+@interface CYJSObject : NSDictionary {
     JSObjectRef object_;
     JSContextRef context_;
 }
@@ -279,7 +291,7 @@ struct Client {
 
 @end
 
-@interface CY$JSArray : NSArray {
+@interface CYJSArray : NSArray {
     JSObjectRef object_;
     JSContextRef context_;
 }
@@ -295,30 +307,82 @@ JSContextRef JSGetContext() {
     return Context_;
 }
 
+#define CYCatch \
+    @catch (id error) { \
+        CYThrow(context, error, exception); \
+        return NULL; \
+    }
+
 void CYThrow(JSContextRef context, JSValueRef value);
 
-id JSObjectToNSObject(JSContextRef context, JSObjectRef object) {
+id CYCastNSObject(JSContextRef context, JSObjectRef object) {
     if (JSValueIsObjectOfClass(context, object, joc_))
         return reinterpret_cast<id>(JSObjectGetPrivate(object));
     JSValueRef exception(NULL);
     bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
     CYThrow(context, exception);
     if (array)
-        return [[[CY$JSArray alloc] initWithJSObject:object inContext:context] autorelease];
-    return [[[CY$JSObject alloc] initWithJSObject:object inContext:context] autorelease];
+        return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
+    return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
+}
+
+JSStringRef CYCopyJSString(id value) {
+    return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
+}
+
+JSStringRef CYCopyJSString(const char *value) {
+    return JSStringCreateWithUTF8CString(value);
+}
+
+JSStringRef CYCopyJSString(JSStringRef value) {
+    return JSStringRetain(value);
+}
+
+JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
+    JSValueRef exception(NULL);
+    JSStringRef string(JSValueToStringCopy(context, value, &exception));
+    CYThrow(context, exception);
+    return string;
 }
 
+// XXX: this is not a safe handle
+class CYString {
+  private:
+    JSStringRef string_;
+
+  public:
+    template <typename Arg0_>
+    CYString(Arg0_ arg0) {
+        string_ = CYCopyJSString(arg0);
+    }
+
+    template <typename Arg0_, typename Arg1_>
+    CYString(Arg0_ arg0, Arg1_ arg1) {
+        string_ = CYCopyJSString(arg0, arg1);
+    }
+
+    ~CYString() {
+        JSStringRelease(string_);
+    }
+
+    operator JSStringRef() const {
+        return string_;
+    }
+};
+
 CFStringRef CYCopyCFString(JSStringRef value) {
     return JSStringCopyCFString(kCFAllocatorDefault, value);
 }
 
 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
+    return CYCopyCFString(CYString(context, value));
+}
+
+CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
     JSValueRef exception(NULL);
-    JSStringRef string(JSValueToStringCopy(context, value, &exception));
+    double number(JSValueToNumber(context, value, &exception));
     CYThrow(context, exception);
-    CFStringRef object(CYCopyCFString(string));
-    JSStringRelease(string);
-    return object;
+    return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
 }
 
 NSString *CYCastNSString(JSStringRef value) {
@@ -326,39 +390,21 @@ NSString *CYCastNSString(JSStringRef value) {
 }
 
 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
-    JSType type(JSValueGetType(context, value));
-
-    switch (type) {
+    switch (JSValueGetType(context, value)) {
         case kJSTypeUndefined:
             return CFRetain([WebUndefined undefined]);
-        break;
-
         case kJSTypeNull:
             return nil;
-        break;
-
         case kJSTypeBoolean:
             return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
-        break;
-
-        case kJSTypeNumber: {
-            JSValueRef exception(NULL);
-            double number(JSValueToNumber(context, value, &exception));
-            CYThrow(context, exception);
-            return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
-        } break;
-
+        case kJSTypeNumber:
+            return CYCopyCFNumber(context, value);
         case kJSTypeString:
             return CYCopyCFString(context, value);
-        break;
-
         case kJSTypeObject:
-            return CFRetain((CFTypeRef) JSObjectToNSObject(context, (JSObjectRef) value));
-        break;
-
+            return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
         default:
             _assert(false);
-        break;
     }
 }
 
@@ -385,43 +431,11 @@ JSValueRef CYCastJSValue(JSContextRef context, id value) {
     return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
 }
 
-JSStringRef CYCopyJSString(id value) {
-    return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
-}
-
-JSStringRef CYCopyJSString(const char *value) {
-    return JSStringCreateWithUTF8CString(value);
-}
-
-JSStringRef CYCopyJSString(JSStringRef value) {
-    return JSStringRetain(value);
-}
-
-// XXX: this is not a safe handle
-class CYString {
-  private:
-    JSStringRef string_;
-
-  public:
-    template <typename Type_>
-    CYString(Type_ value) {
-        string_ = CYCopyJSString(value);
-    }
-
-    ~CYString() {
-        JSStringRelease(string_);
-    }
-
-    operator JSStringRef() const {
-        return string_;
-    }
-};
-
 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
     *exception = CYCastJSValue(context, error);
 }
 
-@implementation CY$JSObject
+@implementation CYJSObject
 
 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
     if ((self = [super init]) != nil) {
@@ -466,7 +480,7 @@ void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
 
 @end
 
-@implementation CY$JSArray
+@implementation CYJSArray
 
 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
     if ((self = [super init]) != nil) {
@@ -578,13 +592,54 @@ static JSValueRef joc_getProperty(JSContextRef context, JSObjectRef object, JSSt
 
 typedef id jocData;
 
+static JSObjectRef joc_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
+    @try {
+        id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
+        return CYMakeObject(context, [[data alloc] autorelease]);
+    } CYCatch
+}
+
 struct ptrData {
+    apr_pool_t *pool_;
     void *value_;
+    sig::Type type_;
+
+    void *operator new(size_t size) {
+        apr_pool_t *pool;
+        apr_pool_create(&pool, NULL);
+        void *data(apr_palloc(pool, size));
+        reinterpret_cast<ptrData *>(data)->pool_ = pool;
+        return data;;
+    }
+
+    ptrData(void *value) :
+        value_(value)
+    {
+    }
+};
+
+struct ffiData : ptrData {
+    sig::Signature signature_;
+    ffi_cif cif_;
+
+    ffiData(void (*value)(), const char *type) :
+        ptrData(reinterpret_cast<void *>(value))
+    {
+        sig::Parse(pool_, &signature_, type);
+        sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
+    }
+};
+
+struct selData : ptrData {
+    selData(SEL value) :
+        ptrData(value)
+    {
+    }
 };
 
 static void ptr_finalize(JSObjectRef object) {
     ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
-    free(data);
+    apr_pool_destroy(data->pool_);
 }
 
 static void joc_finalize(JSObjectRef object) {
@@ -592,10 +647,10 @@ static void joc_finalize(JSObjectRef object) {
     [data release];
 }
 
-static JSValueRef obc_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
+static JSValueRef obc_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) { _pooled
     NSString *name([(NSString *) JSStringCopyCFString(kCFAllocatorDefault, propertyName) autorelease]);
     if (Class _class = NSClassFromString(name))
-        return JSObjectMake(context, joc_, [_class retain]);
+        return CYMakeObject(context, _class);
     return NULL;
 }
 
@@ -605,36 +660,57 @@ void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, J
     CYThrow(context, exception);
 }
 
-struct ffiData {
-    apr_pool_t *pool_;
-    void (*function_)();
-    const char *type_;
-    sig::Signature signature_;
-    ffi_cif cif_;
-};
-
 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
     size_t size(JSStringGetMaximumUTF8CStringSize(value));
-    char *string(reinterpret_cast<char *>(apr_palloc(pool, size)));
+    char *string(new(pool) char[size]);
     JSStringGetUTF8CString(value, string, size);
     JSStringRelease(value);
     return string;
 }
 
+char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
+    return CYPoolCString(pool, CYString(context, value));
+}
+
+// XXX: this macro is dangerous
+#define CYCastCString(context, value) ({ \
+    JSValueRef exception(NULL); \
+    JSStringRef string(JSValueToStringCopy(context, value, &exception)); \
+    CYThrow(context, exception); \
+    size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
+    char *utf8(reinterpret_cast<char *>(alloca(size))); \
+    JSStringGetUTF8CString(string, utf8, size); \
+    JSStringRelease(string); \
+    utf8; \
+})
+
 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
     if (JSValueIsNull(context, value))
         return NULL;
-    else if (JSValueIsObjectOfClass(context, value, sel_))
-        return reinterpret_cast<SEL>(JSObjectGetPrivate((JSObjectRef) value));
-    else {
-        JSValueRef exception(NULL);
-        JSStringRef string(JSValueToStringCopy(context, value, &exception));
-        CYThrow(context, exception);
-        size_t size(JSStringGetMaximumUTF8CStringSize(string));
-        char utf8[size];
-        JSStringGetUTF8CString(string, utf8, size);
-        JSStringRelease(string);
-        return sel_registerName(utf8);
+    else if (JSValueIsObjectOfClass(context, value, sel_)) {
+        selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
+        return reinterpret_cast<SEL>(data->value_);
+    } else
+        return sel_registerName(CYCastCString(context, value));
+}
+
+void *CYCastPointer(JSContextRef context, JSValueRef value) {
+    switch (JSValueGetType(context, value)) {
+        case kJSTypeNull:
+            return NULL;
+        case kJSTypeString:
+            return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
+        case kJSTypeObject:
+            // XXX: maybe support more than just pointers, like ffis and sels
+            if (JSValueIsObjectOfClass(context, value, ptr_)) {
+                ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
+                return data->value_;
+            }
+        default:
+            JSValueRef exception(NULL);
+            double number(JSValueToNumber(context, value, &exception));
+            CYThrow(context, exception);
+            return reinterpret_cast<void *>(static_cast<uintptr_t>(number));
     }
 }
 
@@ -674,31 +750,13 @@ void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *da
             *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
         break;
 
-        case sig::pointer_P: {
-            void *&pointer(*reinterpret_cast<void **>(data));
-            if (JSValueIsNull(context, value))
-                pointer = NULL;
-            else if (JSValueIsObjectOfClass(context, value, ptr_)) {
-                ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
-                pointer = data->value_;
-            } else {
-                JSValueRef exception(NULL);
-                double number(JSValueToNumber(context, value, &exception));
-                CYThrow(context, exception);
-                pointer = reinterpret_cast<void *>(static_cast<uintptr_t>(number));
-            }
-        } break;
+        case sig::pointer_P:
+            *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
+        break;
 
-        case sig::string_P: {
-            JSValueRef exception(NULL);
-            JSStringRef string(JSValueToStringCopy(context, value, &exception));
-            CYThrow(context, exception);
-            size_t size(JSStringGetMaximumUTF8CStringSize(string));
-            char *utf8(reinterpret_cast<char *>(apr_palloc(pool, size)));
-            JSStringGetUTF8CString(string, utf8, size);
-            JSStringRelease(string);
-            *reinterpret_cast<char **>(data) = utf8;
-        } break;
+        case sig::string_P:
+            *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
+        break;
 
         case sig::struct_P:
             goto fail;
@@ -744,14 +802,15 @@ JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
         } break;
 
         case sig::selector_P: {
-            SEL sel(*reinterpret_cast<SEL *>(data));
-            value = sel == NULL ? JSValueMakeNull(context) : JSObjectMake(context, sel_, sel);
+            if (SEL sel = *reinterpret_cast<SEL *>(data)) {
+                selData *data(new selData(sel));
+                value = JSObjectMake(context, sel_, data);
+            } else value = JSValueMakeNull(context);
         } break;
 
         case sig::pointer_P: {
             if (void *pointer = *reinterpret_cast<void **>(data)) {
-                ptrData *data(reinterpret_cast<ptrData *>(malloc(sizeof(ptrData))));
-                data->value_ = pointer;
+                ptrData *data(new ptrData(pointer));
                 value = JSObjectMake(context, ptr_, data);
             } else value = JSValueMakeNull(context);
         } break;
@@ -794,7 +853,7 @@ class CYPool {
     }
 };
 
-static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
+static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
     @try {
         if (count != signature->count - 1)
             [NSException raise:NSInvalidArgumentException format:@"incorrect number of arguments to ffi function"];
@@ -804,7 +863,8 @@ static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSVal
 
         for (unsigned index(0); index != count; ++index) {
             sig::Element *element(&signature->elements[index + 1]);
-            values[index] = apr_palloc(pool, cif->arg_types[index]->size);
+            // XXX: alignment?
+            values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
             CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
         }
 
@@ -812,10 +872,7 @@ static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSVal
         ffi_call(cif, function, value, values);
 
         return CYFromFFI(context, signature->elements[0].type, value);
-    } @catch (id error) {
-        CYThrow(context, error, exception);
-        return NULL;
-    }
+    } CYCatch
 }
 
 bool stret(ffi_type *ffi_type) {
@@ -842,10 +899,7 @@ static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObje
             [NSException raise:NSInvalidArgumentException format:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self];
 
         type = [[method _typeString] UTF8String];
-    } @catch (id error) {
-        CYThrow(context, error, exception);
-        return NULL;
-    }
+    } CYCatch
 
     CYPool pool;
 
@@ -853,7 +907,7 @@ static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObje
     sig::Parse(pool, &signature, type);
 
     ffi_cif cif;
-    sig::sig_ffi_cif(pool, &sig::sig_objc_ffi_type, &signature, &cif);
+    sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
 
     void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
     return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
@@ -861,29 +915,22 @@ static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObje
 
 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
     ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
-    return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, data->function_);
+    return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
 }
 
-static void ffi_finalize(JSObjectRef object) {
-    ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
-    apr_pool_destroy(data->pool_);
+JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
+    ffiData *data(new ffiData(function, type));
+    return JSObjectMake(context, ffi_, data);
 }
 
-void CYSetFunction(JSContextRef context, JSObjectRef object, const char *name, void (*function)(), const char *type) {
-    apr_pool_t *pool;
-    apr_pool_create(&pool, NULL);
-
-    ffiData *data(reinterpret_cast<ffiData *>(apr_palloc(pool, sizeof(ffiData))));
-
-    data->pool_ = pool;
-    data->function_ = function;
-    data->type_ = apr_pstrdup(pool, type);
-
-    sig::Parse(pool, &data->signature_, type);
-    sig::sig_ffi_cif(pool, &sig::sig_objc_ffi_type, &data->signature_, &data->cif_);
-
-    JSObjectRef value(JSObjectMake(context, ffi_, data));
-    CYSetProperty(context, object, name, value);
+JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+    @try {
+        if (count != 2)
+            [NSException raise:NSInvalidArgumentException format:@"incorrect number of arguments to ffi constructor"];
+        void (*function)() = reinterpret_cast<void (*)()>(CYCastPointer(context, arguments[0]));
+        const char *type(CYCastCString(context, arguments[1]));
+        return CYMakeFunction(context, function, type);
+    } CYCatch
 }
 
 JSValueRef ptr_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef *exception) {
@@ -926,25 +973,27 @@ MSInitialize { _pooled
     definition.getProperty = &obc_getProperty;
     JSClassRef obc(JSClassCreate(&definition));
 
-    definition = kJSClassDefinitionEmpty;
-    definition.className = "ffi";
-    definition.callAsFunction = &ffi_callAsFunction;
-    definition.finalize = &ffi_finalize;
-    ffi_ = JSClassCreate(&definition);
-
     definition = kJSClassDefinitionEmpty;
     definition.className = "ptr";
     definition.staticValues = ptr_staticValues;
     definition.finalize = &ptr_finalize;
     ptr_ = JSClassCreate(&definition);
 
+    definition = kJSClassDefinitionEmpty;
+    definition.className = "ffi";
+    definition.parentClass = ptr_;
+    definition.callAsFunction = &ffi_callAsFunction;
+    ffi_ = JSClassCreate(&definition);
+
     definition = kJSClassDefinitionEmpty;
     definition.className = "sel";
+    definition.parentClass = ptr_;
     sel_ = JSClassCreate(&definition);
 
     definition = kJSClassDefinitionEmpty;
     definition.className = "joc";
     definition.getProperty = &joc_getProperty;
+    definition.callAsConstructor = &joc_callAsConstructor;
     definition.finalize = &joc_finalize;
     joc_ = JSClassCreate(&definition);
 
@@ -953,8 +1002,11 @@ MSInitialize { _pooled
 
     JSObjectRef global(JSContextGetGlobalObject(context));
 
+    CYSetProperty(context, global, "ffi", JSObjectMakeConstructor(context, ffi_, &ffi));
+    CYSetProperty(context, global, "obc", JSObjectMake(context, obc, NULL));
+
 #define CYSetFunction_(name, type) \
-    CYSetFunction(context, global, #name, reinterpret_cast<void (*)()>(&name), type)
+    CYSetProperty(context, global, #name, CYMakeFunction(context, reinterpret_cast<void (*)()>(&name), type))
 
     CYSetFunction_(class_addIvar, "B#*LC*");
     CYSetFunction_(class_addMethod, "B#:^?*");