X-Git-Url: https://git.saurik.com/cycript.git/blobdiff_plain/4b645e23d2abde4de1ced347750b070f89b685c3..7ab9e6779d33d38b29b313153a6b109574699617:/Java/Execute.cpp diff --git a/Java/Execute.cpp b/Java/Execute.cpp index 757d643..98bf103 100644 --- a/Java/Execute.cpp +++ b/Java/Execute.cpp @@ -1,5 +1,5 @@ -/* Cycript - Optimizing JavaScript Compiler/Runtime - * Copyright (C) 2009-2015 Jay Freeman (saurik) +/* Cycript - The Truly Universal Scripting Language + * Copyright (C) 2009-2016 Jay Freeman (saurik) */ /* GNU Affero General Public License, Version 3 {{{ */ @@ -23,13 +23,21 @@ #include #include -#ifdef __APPLE__ +#include + +#if defined(__APPLE__) && !defined(__arm__) #include #else #include #endif +#ifdef __ANDROID__ +// XXX: this is deprecated?!?!?!?!?!?! +#include +#endif + #include "cycript.hpp" +#include "Error.hpp" #include "Execute.hpp" #include "Internal.hpp" #include "JavaScript.hpp" @@ -45,7 +53,7 @@ __typeof__(jni->expr) _value(jni->expr); \ if (jthrowable _error = jni->ExceptionOccurred()) { \ jni->ExceptionClear(); \ - CYThrow("_envcall(%s): %p", #expr, _error); \ + throw CYJavaError(CYJavaLocal(jni, _error)); \ } \ _value; }) @@ -53,162 +61,391 @@ _value; }) jni->expr; \ if (jthrowable _error = jni->ExceptionOccurred()) { \ jni->ExceptionClear(); \ - CYThrow("_envcall(%s): %p", #expr, _error); \ + throw CYJavaError(CYJavaLocal(jni, _error)); \ } \ } while (false) -extern "C" { - // Android's jni.h seriously doesn't declare these :/ - jint JNI_CreateJavaVM(JavaVM **, void **, void *); - jint JNI_GetCreatedJavaVMs(JavaVM **, jsize, jsize *); -} - -JNIEnv *GetJNI() { - static JavaVM *jvm(NULL); - static JNIEnv *jni(NULL); +#define CYJavaTry \ + CYJavaEnv jni(env); \ + auto &protect(*reinterpret_cast(jprotect)); \ + _disused JSContextRef context(protect); \ + _disused JSObjectRef object(protect); \ + try +#define CYJavaCatch(value) \ + catch (const CYException &error) { \ + jni->Throw(CYCastJavaObject(jni, context, error.CastJSValue(context, "Error")).cast()); \ + return value; \ + } - if (jni != NULL) - return jni; - jint version(JNI_VERSION_1_4); +#define CYJavaForEachPrimitive \ + CYJavaForEachPrimitive_(Z, z, Boolean, Boolean, boolean) \ + CYJavaForEachPrimitive_(B, b, Byte, Byte, byte) \ + CYJavaForEachPrimitive_(C, c, Char, Character, char) \ + CYJavaForEachPrimitive_(S, s, Short, Short, short) \ + CYJavaForEachPrimitive_(I, i, Int, Integer, int) \ + CYJavaForEachPrimitive_(J, j, Long, Long, long) \ + CYJavaForEachPrimitive_(F, f, Float, Float, float) \ + CYJavaForEachPrimitive_(D, d, Double, Double, double) - jsize capacity(16); - JavaVM *jvms[capacity]; - jsize size; - _jnicall(JNI_GetCreatedJavaVMs(jvms, capacity, &size)); +enum CYJavaPrimitive : char { + CYJavaPrimitiveObject, + CYJavaPrimitiveVoid, +#define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \ + CYJavaPrimitive ## Type, +CYJavaForEachPrimitive +#undef CYJavaForEachPrimitive_ +}; - if (size != 0) { - jvm = jvms[0]; - _jnicall(jvm->GetEnv(reinterpret_cast(&jni), version)); - } else { - JavaVMInitArgs args; - memset(&args, 0, sizeof(args)); - args.version = version; - _jnicall(JNI_CreateJavaVM(&jvm, reinterpret_cast(&jni), &args)); - } +template +struct IsJavaPrimitive { static const bool value = false; }; - return jni; -} +#define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \ + template <> \ + struct IsJavaPrimitive { static const bool value = true; }; +CYJavaForEachPrimitive +#undef CYJavaForEachPrimitive_ -class CYJavaUTF8String : - public CYUTF8String -{ - private: +// Java References {{{ +template +struct CYJavaRef { JNIEnv *jni_; - jstring value_; + Value_ value_; - public: - CYJavaUTF8String(JNIEnv *jni, jstring value) : + _finline CYJavaRef(JNIEnv *jni, Value_ value) : jni_(jni), value_(value) { - _assert(value != NULL); - size = jni_->GetStringUTFLength(value_); - data = jni_->GetStringUTFChars(value_, NULL); } - ~CYJavaUTF8String() { - if (value_ != NULL) - jni_->ReleaseStringUTFChars(value_, data); + _finline operator Value_() const { + return value_; } - CYJavaUTF8String(const CYJavaUTF8String &) = delete; + _finline JNIEnv *jni() const { + return jni_; + } - CYJavaUTF8String(CYJavaUTF8String &&rhs) : - jni_(rhs.jni_), - value_(rhs.value_) - { - rhs.value_ = NULL; + // XXX: this is only needed to support CYJavaEnv relying on C variadics + _finline Value_ get() const { + return value_; + } + + template + _finline CYJavaRef cast() const { + return {jni_, static_cast(value_)}; + } + + // XXX: this should be tied into CYJavaFrame + Value_ leak() { + Value_ value(value_); + value_ = NULL; + return value; } }; -CYJavaUTF8String CYCastUTF8String(JNIEnv *jni, jstring value) { - return CYJavaUTF8String(jni, value); -} +template +struct CYJavaDelete : + CYJavaRef +{ + _finline CYJavaDelete(JNIEnv *jni, Value_ value) : + CYJavaRef(jni, value) + { + } -JSStringRef CYCopyJSString(JNIEnv *jni, jstring value) { - return CYCopyJSString(CYCastUTF8String(jni, value)); -} + void clear() { + if (this->value_ != NULL) + (this->jni_->*Delete_)(this->value_); + this->value_ = NULL; + } + + ~CYJavaDelete() { + clear(); + } +}; template -struct CYJavaGlobal { - JNIEnv *jni_; - Value_ value_; +struct CYJavaGlobal : + CYJavaDelete +{ + typedef CYJavaDelete CYJavaBase; CYJavaGlobal() : - jni_(NULL), - value_(NULL) + CYJavaBase(NULL, NULL) { } - CYJavaGlobal(JNIEnv *jni, Value_ value) : - jni_(jni), - value_(static_cast(_envcall(jni_, NewGlobalRef(value)))) + template + CYJavaGlobal(const CYJavaRef &other) : + CYJavaBase(other.jni_, static_cast(other.jni_->NewGlobalRef(other.value_))) { } - CYJavaGlobal(const CYJavaGlobal &value) : - CYJavaGlobal(value.jni_, value.value_) + CYJavaGlobal(const CYJavaGlobal &other) : + CYJavaGlobal(static_cast &>(other)) { } CYJavaGlobal(CYJavaGlobal &&value) : - jni_(value.jni_), - value_(value.value_) + CYJavaBase(value.jni_, value.value_) { value.value_ = NULL; } +}; - ~CYJavaGlobal() { - if (value_ != NULL) - _envcallv(jni_, DeleteGlobalRef(value_)); +template +struct CYJavaLocal : + CYJavaDelete +{ + typedef CYJavaDelete CYJavaBase; + + CYJavaLocal() : + CYJavaBase(NULL, NULL) + { } - operator bool() const { - return value_ != NULL; + CYJavaLocal(JNIEnv *jni, Value_ value) : + CYJavaBase(jni, value) + { } - operator JNIEnv *() const { - return jni_; + template + CYJavaLocal(const CYJavaRef &other) : + CYJavaLocal(other.jni_, static_cast(other.jni_->NewLocalRef(other.value_))) + { } - operator Value_() const { - return value_; + template + CYJavaLocal(CYJavaRef &&other) : + CYJavaLocal(other.jni_, other.value_) + { + other.value_ = NULL; + } + + CYJavaLocal(CYJavaLocal &&other) : + CYJavaLocal(static_cast &&>(other)) + { + } + + template + CYJavaLocal &operator =(CYJavaLocal &&other) { + this->clear(); + this->jni_ = other.jni_; + this->value_ = other.value_; + other.value_ = NULL; + return *this; } }; +// }}} +// Java Strings {{{ +static CYJavaLocal CYCastJavaString(const CYJavaRef &value); -template -struct CYJavaValue : - CYPrivate +class CYJavaUTF8String : + public CYUTF8String { - CYJavaGlobal value_; + private: + const CYJavaRef &value_; - CYJavaValue(JNIEnv *jni, Value_ value) : - value_(jni, value) + public: + CYJavaUTF8String(const CYJavaRef &value) : + value_(value) { + _assert(value); + JNIEnv *jni(value.jni()); + size = jni->GetStringUTFLength(value); + data = jni->GetStringUTFChars(value, NULL); + } + + CYJavaUTF8String(CYJavaRef &&) = delete; + + ~CYJavaUTF8String() { + JNIEnv *jni(value_.jni()); + jni->ReleaseStringUTFChars(value_, data); } - CYJavaValue(const CYJavaValue &) = delete; + CYJavaUTF8String(const CYJavaUTF8String &) = delete; }; -#define CYJavaForEachPrimitive \ - CYJavaForEachPrimitive_(Z, z, Boolean, Boolean, boolean) \ - CYJavaForEachPrimitive_(B, b, Byte, Byte, byte) \ - CYJavaForEachPrimitive_(C, c, Char, Character, char) \ - CYJavaForEachPrimitive_(S, s, Short, Short, short) \ - CYJavaForEachPrimitive_(I, i, Int, Integer, int) \ - CYJavaForEachPrimitive_(J, j, Long, Long, long) \ - CYJavaForEachPrimitive_(F, f, Float, Float, float) \ - CYJavaForEachPrimitive_(D, d, Double, Double, double) +CYJavaUTF8String CYCastUTF8String(const CYJavaRef &value) { + return {value}; +} + +JSStringRef CYCopyJSString(const CYJavaRef &value) { + return CYCopyJSString(CYCastUTF8String(value)); +} +// }}} +// Java Error {{{ +struct CYJavaError : + CYException +{ + CYJavaGlobal value_; + + CYJavaError(const CYJavaRef &value) : + value_(value) + { + } + + virtual const char *PoolCString(CYPool &pool) const { + auto string(CYCastJavaString(value_.cast())); + return CYPoolCString(pool, CYJavaUTF8String(string)); + } + + virtual JSValueRef CastJSValue(JSContextRef context, const char *name) const; +}; +// }}} + +struct CYJavaFrame { + JNIEnv *jni_; + + CYJavaFrame(JNIEnv *jni, jint capacity) : + jni_(jni) + { + _assert(jni->PushLocalFrame(capacity) == 0); + } + + ~CYJavaFrame() { + operator ()(NULL); + } + + operator JNIEnv *() const { + return jni_; + } + + jobject operator ()(jobject object) { + JNIEnv *jni(jni_); + jni_ = NULL; + return jni->PopLocalFrame(object); + } +}; + +struct CYJavaEnv { + private: + JNIEnv *jni; + + public: + CYJavaEnv(JNIEnv *jni) : + jni(jni) + { + } + + template + CYJavaEnv(const CYJavaRef &value) : + jni(value.jni()) + { + } + + operator JNIEnv *() const { + return jni; + } + + JNIEnv *operator ->() const { + return jni; + } + + CYJavaLocal FindClass(const char *name) const { + return {jni, _envcall(jni, FindClass(name))}; + } + + CYJavaLocal GetObjectClass(jobject object) const { + return {jni, _envcall(jni, GetObjectClass(object))}; + } + + CYJavaLocal GetSuperclass(jclass _class) const { + return {jni, _envcall(jni, GetSuperclass(_class))}; + } + + CYJavaLocal NewObject(jclass _class, jmethodID method, ...) const { + va_list args; + va_start(args, method); + jobject object(_envcall(jni, NewObjectV(_class, method, args))); + va_end(args); + return {jni, object}; + } + + CYJavaLocal NewObjectA(jclass _class, jmethodID method, jvalue *args) const { + return {jni, _envcall(jni, NewObjectA(_class, method, args))}; + } + + CYJavaLocal NewString(const jchar *data, jsize size) const { + return {jni, _envcall(jni, NewString(data, size))}; + } + +#define CYJavaEnv_(Code) \ + template \ + void Code(Args_ &&... args) const { \ + _envcallv(jni, Code(cy::Forward(args)...)); \ + } -enum CYJavaPrimitive : char { - CYJavaPrimitiveObject, - CYJavaPrimitiveVoid, #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \ - CYJavaPrimitive ## Type, + CYJavaEnv_(Get ## Typ ## ArrayRegion) \ + CYJavaEnv_(Set ## Typ ## Field) \ + CYJavaEnv_(SetStatic ## Typ ## Field) CYJavaForEachPrimitive #undef CYJavaForEachPrimitive_ + + CYJavaEnv_(CallVoidMethod) + CYJavaEnv_(CallStaticVoidMethod) + CYJavaEnv_(CallVoidMethodA) + CYJavaEnv_(CallStaticVoidMethodA) + CYJavaEnv_(SetObjectArrayElement) + CYJavaEnv_(SetObjectField) + CYJavaEnv_(SetStaticObjectField) +#undef CYJavaEnv_ + +#define CYJavaEnv_(Code) \ + template \ + auto Code(Args_ &&... args) const -> decltype(jni->Code(cy::Forward(args)...)) { \ + return _envcall(jni, Code(cy::Forward(args)...)); \ + } + +#define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \ + CYJavaEnv_(Call ## Typ ## Method) \ + CYJavaEnv_(CallStatic ## Typ ## Method) \ + CYJavaEnv_(Call ## Typ ## MethodA) \ + CYJavaEnv_(CallStatic ## Typ ## MethodA) \ + CYJavaEnv_(Get ## Typ ## Field) \ + CYJavaEnv_(GetStatic ## Typ ## Field) +CYJavaForEachPrimitive +#undef CYJavaForEachPrimitive_ + + CYJavaEnv_(FromReflectedField) + CYJavaEnv_(FromReflectedMethod) + CYJavaEnv_(GetArrayLength) + CYJavaEnv_(GetMethodID) + CYJavaEnv_(GetStaticMethodID) + CYJavaEnv_(IsSameObject) + CYJavaEnv_(RegisterNatives) +#undef CYJavaEnv_ + +#define CYJavaEnv_(Code) \ + template \ + auto Code(Args_ &&... args) const -> CYJavaLocal { \ + return {jni, static_cast(_envcall(jni, Code(cy::Forward(args)...)))}; \ + } + + CYJavaEnv_(CallObjectMethod) + CYJavaEnv_(CallStaticObjectMethod) + CYJavaEnv_(CallObjectMethodA) + CYJavaEnv_(CallStaticObjectMethodA) + CYJavaEnv_(GetObjectArrayElement) + CYJavaEnv_(GetObjectField) + CYJavaEnv_(GetStaticObjectField) +#undef CYJavaEnv_ }; +static CYJavaLocal CYCastJavaString(const CYJavaRef &value) { + CYJavaEnv jni(value); + auto Object$(jni.FindClass("java/lang/Object")); + auto Object$toString(jni.GetMethodID(Object$, "toString", "()Ljava/lang/String;")); + return jni.CallObjectMethod(value, Object$toString); +} + +static JSValueRef CYCastJSValue(JSContextRef context, const CYJavaRef &value); + +template +static _finline JSValueRef CYCastJSValue(JSContextRef context, const CYJavaRef &value) { + return CYCastJSValue(context, value.template cast()); +} + template static _finline JSValueRef CYJavaCastJSValue(JSContextRef context, Type_ value) { return CYCastJSValue(context, value); @@ -218,23 +455,30 @@ static _finline JSValueRef CYJavaCastJSValue(JSContextRef context, jboolean valu return CYCastJSValue(context, static_cast(value)); } +JSValueRef CYJavaError::CastJSValue(JSContextRef context, const char *name) const { + return CYCastJSValue(context, value_); +} + static std::map Primitives_; -static CYJavaPrimitive CYJavaGetPrimitive(JNIEnv *jni, jobject type, jmethodID Class$get$$Name) { - jstring string(static_cast(_envcall(jni, CallObjectMethod(type, Class$get$$Name)))); - _assert(string != NULL); - CYJavaUTF8String name(jni, string); +static CYJavaPrimitive CYJavaGetPrimitive(JSContextRef context, const CYJavaRef &type, jmethodID Class$get$$Name) { + CYJavaEnv jni(type); + auto string(jni.CallObjectMethod(type, Class$get$$Name)); + _assert(string); + + CYJavaUTF8String name(string); auto primitive(Primitives_.find(name)); return primitive != Primitives_.end() ? primitive->second : CYJavaPrimitiveObject; } typedef std::vector CYJavaShorty; -static CYJavaShorty CYJavaGetShorty(JNIEnv *jni, jobjectArray types, jmethodID Class$get$$Name) { - size_t count(_envcall(jni, GetArrayLength(types))); +static CYJavaShorty CYJavaGetShorty(JSContextRef context, const CYJavaRef &types, jmethodID Class$get$$Name) { + CYJavaEnv jni(types); + size_t count(jni.GetArrayLength(types)); CYJavaShorty shorty(count); for (size_t index(0); index != count; ++index) - shorty[index] = CYJavaGetPrimitive(jni, _envcall(jni, GetObjectArrayElement(types, index)), Class$get$$Name); + shorty[index] = CYJavaGetPrimitive(context, jni.GetObjectArrayElement(types, index), Class$get$$Name); return shorty; } @@ -246,67 +490,82 @@ struct CYJavaField { typedef std::map CYJavaFieldMap; struct CYJavaSignature { - jmethodID method_; CYJavaGlobal reflected_; + jmethodID method_; CYJavaPrimitive primitive_; CYJavaShorty shorty_; - CYJavaSignature(JNIEnv *jni, jmethodID method, jobject reflected, CYJavaPrimitive primitive, const CYJavaShorty &shorty) : + CYJavaSignature(const CYJavaRef &reflected, jmethodID method, CYJavaPrimitive primitive, const CYJavaShorty &shorty) : + reflected_(reflected), method_(method), - reflected_(jni, reflected), primitive_(primitive), shorty_(shorty) { } - CYJavaSignature(unsigned count) : - shorty_(count) - { - } - + // XXX: the shorty doesn't store enough information bool operator <(const CYJavaSignature &rhs) const { - return shorty_.size() < rhs.shorty_.size(); + return shorty_ < rhs.shorty_; } }; -typedef std::multiset CYJavaOverload; +typedef std::set CYJavaOverload; +typedef std::map CYJavaOverloads; struct CYJavaMethod : - CYPrivate + CYRoot { - JNIEnv *jni_; - CYJavaOverload overload_; - - // XXX: figure out move constructors on Apple's crappy toolchain - CYJavaMethod(JNIEnv *jni, const CYJavaOverload &overload) : - jni_(jni), - overload_(overload) + CYUTF8String type_; + CYUTF8String name_; + CYJavaOverloads overloads_; + + CYJavaMethod(CYUTF8String type, CYUTF8String name, const CYJavaOverloads &overloads) : + type_(CYPoolUTF8String(*pool_, type)), + name_(CYPoolUTF8String(*pool_, name)), + overloads_(overloads) { } }; +struct CYJavaInstanceMethod : + CYJavaMethod +{ + using CYJavaMethod::CYJavaMethod; +}; + +struct CYJavaStaticMethod : + CYJavaMethod +{ + using CYJavaMethod::CYJavaMethod; +}; + struct CYJavaClass : - CYJavaValue + CYRoot { + CYJavaGlobal value_; + bool interface_; + CYJavaFieldMap static_; CYJavaFieldMap instance_; - CYJavaOverload overload_; + CYJavaOverloads overloads_; - CYJavaClass(JNIEnv *jni, jclass value) : - CYJavaValue(jni, value) + CYJavaClass(const CYJavaRef &value, bool interface) : + value_(value), + interface_(interface) { } }; -static JSObjectRef CYGetJavaClass(JSContextRef context, JNIEnv *jni, jclass _class); +static JSObjectRef CYGetJavaClass(JSContextRef context, const CYJavaRef &_class); struct CYJavaObject : - CYJavaValue + CYRoot { + CYJavaGlobal value_; CYJavaClass *table_; - CYJavaObject(JNIEnv *jni, jobject value, CYJavaClass *table) : - CYJavaValue(jni, value), + CYJavaObject(const CYJavaRef &value, CYJavaClass *table) : + value_(value), table_(table) { } @@ -315,36 +574,39 @@ struct CYJavaObject : }; struct CYJavaInterior : - CYJavaValue + CYRoot { + CYJavaGlobal value_; CYJavaClass *table_; - CYJavaInterior(JNIEnv *jni, jobject value, CYJavaClass *table) : - CYJavaValue(jni, value), + CYJavaInterior(const CYJavaRef &value, CYJavaClass *table) : + value_(value), table_(table) { } }; -struct CYJavaStatic : - CYJavaValue +struct CYJavaStaticInterior : + CYRoot { + CYJavaGlobal value_; CYJavaClass *table_; - CYJavaStatic(JNIEnv *jni, jobject value, CYJavaClass *table) : - CYJavaValue(jni, value), + CYJavaStaticInterior(const CYJavaRef &value, CYJavaClass *table) : + value_(value), table_(table) { } }; struct CYJavaArray : - CYJavaValue + CYRoot { + CYJavaGlobal value_; CYJavaPrimitive primitive_; - CYJavaArray(JNIEnv *jni, jarray value, CYJavaPrimitive primitive) : - CYJavaValue(jni, value), + CYJavaArray(const CYJavaRef &value, CYJavaPrimitive primitive) : + value_(value), primitive_(primitive) { } @@ -353,60 +615,75 @@ struct CYJavaArray : }; struct CYJavaPackage : - CYPrivate + CYRoot { + JNIEnv *jni_; + typedef std::vector Path; Path package_; - _finline CYJavaPackage(const Path &package) : + _finline CYJavaPackage(JNIEnv *jni, const Path &package) : + jni_(jni), package_(package) { } }; JSValueRef CYJavaObject::GetPrototype(JSContextRef context) const { - JNIEnv *jni(value_); - return CYGetProperty(context, CYGetJavaClass(context, jni, _envcall(jni, GetObjectClass(value_))), prototype_s); + CYJavaEnv jni(value_); + return CYGetProperty(context, CYGetJavaClass(context, jni.GetObjectClass(value_)), prototype_s); } JSValueRef CYJavaArray::GetPrototype(JSContextRef context) const { return CYGetCachedObject(context, CYJSString("Array_prototype")); } -static JSValueRef CYCastJSValue(JSContextRef context, JNIEnv *jni, jobject value) { - if (value == NULL) +static JSValueRef CYCastJSValue(JSContextRef context, const CYJavaRef &value) { + if (!value) return CYJSNull(context); + CYJavaEnv jni(value); + + auto _class(jni.GetObjectClass(value)); + if (jni.IsSameObject(_class, jni.FindClass("java/lang/String"))) + return CYCastJSValue(context, CYJSString(value.cast())); + + auto Class$(jni.FindClass("java/lang/Class")); + auto Class$isArray(jni.GetMethodID(Class$, "isArray", "()Z")); + if (jni.CallBooleanMethod(_class, Class$isArray)) { + auto Class$getComponentType(jni.GetMethodID(Class$, "getComponentType", "()Ljava/lang/Class;")); + auto component(jni.CallObjectMethod(_class, Class$getComponentType)); + auto Class$getName(jni.GetMethodID(Class$, "getName", "()Ljava/lang/String;")); + return CYPrivate::Make(context, value.cast(), CYJavaGetPrimitive(context, component, Class$getName)); + } - jclass _class(_envcall(jni, GetObjectClass(value))); - if (_envcall(jni, IsSameObject(_class, _envcall(jni, FindClass("java/lang/String"))))) - return CYCastJSValue(context, CYJSString(CYJavaUTF8String(jni, static_cast(value)))); - - jclass Class$(_envcall(jni, FindClass("java/lang/Class"))); - jmethodID Class$isArray(_envcall(jni, GetMethodID(Class$, "isArray", "()Z"))); - if (_envcall(jni, CallBooleanMethod(_class, Class$isArray))) { - jmethodID Class$getComponentType(_envcall(jni, GetMethodID(Class$, "getComponentType", "()Ljava/lang/Class;"))); - jclass component(static_cast(_envcall(jni, CallObjectMethod(_class, Class$getComponentType)))); - jmethodID Class$getName(_envcall(jni, GetMethodID(Class$, "getName", "()Ljava/lang/String;"))); - return CYJavaArray::Make(context, jni, static_cast(value), CYJavaGetPrimitive(jni, component, Class$getName)); + auto Wrapper$(jni.FindClass("Cycript$Wrapper")); + if (jni.IsSameObject(_class, Wrapper$)) { + auto Wrapper$getProtect(jni.GetMethodID(Wrapper$, "getProtect", "()J")); + auto &protect(*reinterpret_cast(jni.CallLongMethod(value, Wrapper$getProtect))); + return protect; } - CYJavaClass *table(reinterpret_cast(JSObjectGetPrivate(CYGetJavaClass(context, jni, _class)))); - return CYJavaObject::Make(context, jni, value, table); + CYJavaClass *table(reinterpret_cast(JSObjectGetPrivate(CYGetJavaClass(context, _class)))); + return CYPrivate::Make(context, value, table); } -static jstring CYCastJavaString(JNIEnv *jni, CYUTF16String value) { - return _envcall(jni, NewString(value.data, value.size)); +static _finline JSObjectRef CYCastJSObject(JSContextRef context, const CYJavaRef &value) { + return CYCastJSObject(context, CYCastJSValue(context, value)); } -static jstring CYCastJavaString(JNIEnv *jni, JSStringRef value) { - return CYCastJavaString(jni, CYCastUTF16String(value)); +static CYJavaLocal CYCastJavaString(const CYJavaEnv &jni, JSContextRef context, CYUTF16String value) { + return jni.NewString(value.data, value.size); +} + +static CYJavaLocal CYCastJavaString(const CYJavaEnv &jni, JSContextRef context, JSStringRef value) { + return CYCastJavaString(jni, context, CYCastUTF16String(value)); } #define CYCastJava$(T, Type, jtype, Cast) \ -_disused static jobject CYCastJava ## Type(JNIEnv *jni, JSContextRef context, JSValueRef value) { \ - jclass Type$(_envcall(jni, FindClass("java/lang/" #Type))); \ - jmethodID Type$init$(_envcall(jni, GetMethodID(Type$, "", "(" #T ")V"))); \ - return _envcall(jni, NewObject(Type$, Type$init$, static_cast(Cast(context, value)))); \ +_disused static CYJavaLocal CYCastJava ## Type(const CYJavaEnv &jni, JSContextRef context, JSValueRef value) { \ + auto Type$(jni.FindClass("java/lang/" #Type)); \ + auto Type$init$(jni.GetMethodID(Type$, "", "(" #T ")V")); \ + return jni.NewObject(Type$, Type$init$, static_cast(Cast(context, value))); \ } CYCastJava$(Z, Boolean, jboolean, CYCastBool) @@ -418,132 +695,182 @@ CYCastJava$(J, Long, jlong, CYCastDouble) CYCastJava$(F, Float, jfloat, CYCastDouble) CYCastJava$(D, Double, jdouble, CYCastDouble) -static jobject CYCastJavaObject(JNIEnv *jni, JSContextRef context, JSObjectRef value) { - JSObjectRef object(CYCastJSObject(context, value)); - if (JSValueIsObjectOfClass(context, value, CYJavaObject::Class_)) { - CYJavaObject *internal(reinterpret_cast(JSObjectGetPrivate(object))); +static CYJavaClass *CYGetJavaTable(JSContextRef context, JSObjectRef object) { + if (!JSValueIsObjectOfClass(context, object, CYPrivate::Class_)) + return NULL; + return reinterpret_cast(JSObjectGetPrivate(object)); +} + +static CYJavaObject *CYGetJavaObject(JSContextRef context, JSObjectRef object) { + if (!JSValueIsObjectOfClass(context, object, CYPrivate::Class_)) + return NULL; + return reinterpret_cast(JSObjectGetPrivate(object)); +} + +static CYJavaLocal CYCastJavaObject(const CYJavaEnv &jni, JSContextRef context, JSObjectRef value) { + if (CYJavaObject *internal = CYGetJavaObject(context, value)) return internal->value_; - } - _assert(false); + auto Wrapper$(jni.FindClass("Cycript$Wrapper")); + auto Wrapper$$init$(jni.GetMethodID(Wrapper$, "", "(J)V")); + CYProtect *protect(new CYProtect(context, value)); + return jni.NewObject(Wrapper$, Wrapper$$init$, reinterpret_cast(protect)); } -static jobject CYCastJavaObject(JNIEnv *jni, JSContextRef context, JSValueRef value) { +static CYJavaLocal CYCastJavaObject(const CYJavaEnv &jni, JSContextRef context, JSValueRef value) { switch (JSValueGetType(context, value)) { case kJSTypeNull: - return NULL; + return {jni, NULL}; case kJSTypeBoolean: return CYCastJavaBoolean(jni, context, value); case kJSTypeNumber: return CYCastJavaDouble(jni, context, value); case kJSTypeString: - return CYCastJavaString(jni, CYJSString(context, value)); + return CYCastJavaString(jni, context, CYJSString(context, value)); case kJSTypeObject: return CYCastJavaObject(jni, context, CYCastJSObject(context, value)); case kJSTypeUndefined: + // XXX: I am currently relying on this for dynamic proxy of void method + return {jni, NULL}; default: _assert(false); } } -static JSObjectRef CYGetJavaClass(JSContextRef context, JNIEnv *jni, jclass value) { +static JSObjectRef CYGetJavaClass(JSContextRef context, const CYJavaRef &value) { + CYJavaEnv jni(value); + CYJavaFrame frame(jni, 64); + JSObjectRef global(CYGetGlobalObject(context)); JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s))); - jclass Class$(_envcall(jni, FindClass("java/lang/Class"))); - jmethodID Class$getName(_envcall(jni, GetMethodID(Class$, "getName", "()Ljava/lang/String;"))); + auto Class$(jni.FindClass("java/lang/Class")); + auto Class$getName(jni.GetMethodID(Class$, "getName", "()Ljava/lang/String;")); + + auto string(jni.CallObjectMethod(value, Class$getName)); + CYJavaUTF8String utf8(string); + CYJSString name(utf8); - CYJSString name(jni, static_cast(_envcall(jni, CallObjectMethod(value, Class$getName)))); JSValueRef cached(CYGetProperty(context, cy, name)); if (!JSValueIsUndefined(context, cached)) return CYCastJSObject(context, cached); - jmethodID Class$getDeclaredConstructors(_envcall(jni, GetMethodID(Class$, "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;"))); - jmethodID Class$getDeclaredFields(_envcall(jni, GetMethodID(Class$, "getDeclaredFields", "()[Ljava/lang/reflect/Field;"))); - jmethodID Class$getDeclaredMethods(_envcall(jni, GetMethodID(Class$, "getDeclaredMethods", "()[Ljava/lang/reflect/Method;"))); + JSObjectRef constructor; + JSObjectRef prototype; + + { + + auto Class$isInterface(jni.GetMethodID(Class$, "isInterface", "()Z")); - jclass Constructor$(_envcall(jni, FindClass("java/lang/reflect/Constructor"))); - //jmethodID Constructor$getModifiers(_envcall(jni, GetMethodID(Constructor$, "getModifiers", "()I"))); - jmethodID Constructor$getParameterTypes(_envcall(jni, GetMethodID(Constructor$, "getParameterTypes", "()[Ljava/lang/Class;"))); + auto Class$getDeclaredConstructors(jni.GetMethodID(Class$, "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;")); + auto Class$getDeclaredFields(jni.GetMethodID(Class$, "getDeclaredFields", "()[Ljava/lang/reflect/Field;")); + auto Class$getDeclaredMethods(jni.GetMethodID(Class$, "getDeclaredMethods", "()[Ljava/lang/reflect/Method;")); - jclass Field$(_envcall(jni, FindClass("java/lang/reflect/Field"))); - jmethodID Field$getModifiers(_envcall(jni, GetMethodID(Field$, "getModifiers", "()I"))); - jmethodID Field$getName(_envcall(jni, GetMethodID(Field$, "getName", "()Ljava/lang/String;"))); - jmethodID Field$getType(_envcall(jni, GetMethodID(Field$, "getType", "()Ljava/lang/Class;"))); + auto Constructor$(jni.FindClass("java/lang/reflect/Constructor")); + //auto Constructor$getModifiers(jni.GetMethodID(Constructor$, "getModifiers", "()I")); + auto Constructor$getParameterTypes(jni.GetMethodID(Constructor$, "getParameterTypes", "()[Ljava/lang/Class;")); - jclass Method$(_envcall(jni, FindClass("java/lang/reflect/Method"))); - jmethodID Method$getModifiers(_envcall(jni, GetMethodID(Method$, "getModifiers", "()I"))); - jmethodID Method$getName(_envcall(jni, GetMethodID(Method$, "getName", "()Ljava/lang/String;"))); - jmethodID Method$getParameterTypes(_envcall(jni, GetMethodID(Method$, "getParameterTypes", "()[Ljava/lang/Class;"))); - jmethodID Method$getReturnType(_envcall(jni, GetMethodID(Method$, "getReturnType", "()Ljava/lang/Class;"))); + auto Field$(jni.FindClass("java/lang/reflect/Field")); + auto Field$getModifiers(jni.GetMethodID(Field$, "getModifiers", "()I")); + auto Field$getName(jni.GetMethodID(Field$, "getName", "()Ljava/lang/String;")); + auto Field$getType(jni.GetMethodID(Field$, "getType", "()Ljava/lang/Class;")); - jclass Modifier$(_envcall(jni, FindClass("java/lang/reflect/Modifier"))); - jmethodID Modifier$isStatic(_envcall(jni, GetStaticMethodID(Modifier$, "isStatic", "(I)Z"))); + auto Method$(jni.FindClass("java/lang/reflect/Method")); + auto Method$getModifiers(jni.GetMethodID(Method$, "getModifiers", "()I")); + auto Method$getName(jni.GetMethodID(Method$, "getName", "()Ljava/lang/String;")); + auto Method$getParameterTypes(jni.GetMethodID(Method$, "getParameterTypes", "()[Ljava/lang/Class;")); + auto Method$getReturnType(jni.GetMethodID(Method$, "getReturnType", "()Ljava/lang/Class;")); - CYJavaClass *table(new CYJavaClass(jni, value)); + auto Modifier$(jni.FindClass("java/lang/reflect/Modifier")); + auto Modifier$isStatic(jni.GetStaticMethodID(Modifier$, "isStatic", "(I)Z")); - for (jclass prototype(value); prototype != NULL; prototype = _envcall(jni, GetSuperclass(prototype))) { - jobjectArray fields(static_cast(_envcall(jni, CallObjectMethod(prototype, Class$getDeclaredFields)))); + auto interface(jni.CallBooleanMethod(value, Class$isInterface)); + auto table(new CYJavaClass(value, interface)); - for (jsize i(0), e(_envcall(jni, GetArrayLength(fields))); i != e; ++i) { - jobject field(_envcall(jni, GetObjectArrayElement(fields, e - i - 1))); - jint modifiers(_envcall(jni, CallIntMethod(field, Field$getModifiers))); - bool instance(!_envcall(jni, CallStaticBooleanMethod(Modifier$, Modifier$isStatic, modifiers))); + for (CYJavaLocal prototype(value); prototype; prototype = jni.GetSuperclass(prototype)) { + auto fields(jni.CallObjectMethod(prototype, Class$getDeclaredFields)); + + for (jsize i(0), e(jni.GetArrayLength(fields)); i != e; ++i) { + auto field(jni.GetObjectArrayElement(fields, e - i - 1)); + auto modifiers(jni.CallIntMethod(field, Field$getModifiers)); + auto instance(!jni.CallStaticBooleanMethod(Modifier$, Modifier$isStatic, modifiers)); auto &map(instance ? table->instance_ : table->static_); - CYJavaUTF8String name(jni, static_cast(_envcall(jni, CallObjectMethod(field, Field$getName)))); - jfieldID id(_envcall(jni, FromReflectedField(field))); - jobject type(_envcall(jni, CallObjectMethod(field, Field$getType))); - map.insert(std::make_pair(std::string(name), CYJavaField{id, CYJavaGetPrimitive(jni, type, Class$getName)})); + auto string(jni.CallObjectMethod(field, Field$getName)); + CYJavaUTF8String name(string); + auto id(jni.FromReflectedField(field)); + auto type(jni.CallObjectMethod(field, Field$getType)); + map.insert(std::make_pair(std::string(name), CYJavaField{id, CYJavaGetPrimitive(context, type, Class$getName)})); } } - JSObjectRef constructor(JSObjectMake(context, CYJavaClass::Class_, table)); + constructor = JSObjectMake(context, CYPrivate::Class_, table); - JSObjectRef prototype(JSObjectMake(context, NULL, NULL)); + prototype = JSObjectMake(context, NULL, NULL); CYSetProperty(context, constructor, prototype_s, prototype, kJSPropertyAttributeDontEnum); - jobjectArray constructors(static_cast(_envcall(jni, CallObjectMethod(value, Class$getDeclaredConstructors)))); + auto constructors(jni.CallObjectMethod(value, Class$getDeclaredConstructors)); - for (jsize i(0), e(_envcall(jni, GetArrayLength(constructors))); i != e; ++i) { - jobject constructor(_envcall(jni, GetObjectArrayElement(constructors, i))); - jobjectArray parameters(static_cast(_envcall(jni, CallObjectMethod(constructor, Constructor$getParameterTypes)))); - CYJavaShorty shorty(CYJavaGetShorty(jni, parameters, Class$getName)); - jmethodID id(_envcall(jni, FromReflectedMethod(constructor))); - table->overload_.insert(CYJavaSignature(jni, id, constructor, CYJavaPrimitiveObject, shorty)); + for (jsize i(0), e(jni.GetArrayLength(constructors)); i != e; ++i) { + auto constructor(jni.GetObjectArrayElement(constructors, i)); + auto parameters(jni.CallObjectMethod(constructor, Constructor$getParameterTypes)); + CYJavaShorty shorty(CYJavaGetShorty(context, parameters, Class$getName)); + auto id(jni.FromReflectedMethod(constructor)); + table->overloads_[shorty.size()].insert(CYJavaSignature(constructor, id, CYJavaPrimitiveObject, shorty)); } - jobjectArray methods(static_cast(_envcall(jni, CallObjectMethod(value, Class$getDeclaredMethods)))); - - std::map, CYJavaOverload> entries; + std::map, CYJavaOverloads> entries; + + bool base(false); + for (CYJavaLocal prototype(value); prototype; prototype = jni.GetSuperclass(prototype)) { + auto methods(jni.CallObjectMethod(prototype, Class$getDeclaredMethods)); + + for (jsize i(0), e(jni.GetArrayLength(methods)); i != e; ++i) { + auto method(jni.GetObjectArrayElement(methods, i)); + auto modifiers(jni.CallIntMethod(method, Method$getModifiers)); + auto instance(!jni.CallStaticBooleanMethod(Modifier$, Modifier$isStatic, modifiers)); + auto string(jni.CallObjectMethod(method, Method$getName)); + CYJavaUTF8String name(string); + + auto parameters(jni.CallObjectMethod(method, Method$getParameterTypes)); + CYJavaShorty shorty(CYJavaGetShorty(context, parameters, Class$getName)); + + CYJavaOverload *overload; + if (!base) + overload = &entries[std::make_pair(instance, std::string(name))][shorty.size()]; + else { + auto entry(entries.find(std::make_pair(instance, std::string(name)))); + if (entry == entries.end()) + continue; + overload = &entry->second[shorty.size()]; + } + + auto type(jni.CallObjectMethod(method, Method$getReturnType)); + auto primitive(CYJavaGetPrimitive(context, type, Class$getName)); + auto id(jni.FromReflectedMethod(method)); + overload->insert(CYJavaSignature(method, id, primitive, shorty)); + } - for (jsize i(0), e(_envcall(jni, GetArrayLength(methods))); i != e; ++i) { - jobject method(_envcall(jni, GetObjectArrayElement(methods, i))); - jint modifiers(_envcall(jni, CallIntMethod(method, Method$getModifiers))); - bool instance(!_envcall(jni, CallStaticBooleanMethod(Modifier$, Modifier$isStatic, modifiers))); - CYJavaUTF8String name(jni, static_cast(_envcall(jni, CallObjectMethod(method, Method$getName)))); - jobjectArray parameters(static_cast(_envcall(jni, CallObjectMethod(method, Method$getParameterTypes)))); - CYJavaShorty shorty(CYJavaGetShorty(jni, parameters, Class$getName)); - jobject type(_envcall(jni, CallObjectMethod(method, Method$getReturnType))); - auto primitive(CYJavaGetPrimitive(jni, type, Class$getName)); - jmethodID id(_envcall(jni, FromReflectedMethod(method))); - entries[std::make_pair(instance, std::string(name))].insert(CYJavaSignature(jni, id, method, primitive, shorty)); + base = true; } for (const auto &entry : entries) { bool instance(entry.first.first); - CYJSString name(entry.first.second); + CYJSString method(entry.first.second); auto &overload(entry.second); - auto target(instance ? prototype : constructor); - JSValueRef wrapper(CYJavaMethod::Make(context, jni, overload)); - CYSetProperty(context, target, name, wrapper, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete); + if (instance) + CYSetProperty(context, prototype, method, CYPrivate::Make(context, utf8, entry.first.second.c_str(), overload), kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete); + else + CYSetProperty(context, constructor, method, CYPrivate::Make(context, utf8, entry.first.second.c_str(), overload), kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete); + } + } // XXX: for some reason kJSPropertyAttributeDontEnum doesn't work if there's already a property with the same name // by not linking the prototypes until after we set the properties, we hide the parent property from this issue :( - if (jclass super = _envcall(jni, GetSuperclass(value))) { - JSObjectRef parent(CYGetJavaClass(context, jni, super)); + if (auto super = jni.GetSuperclass(value)) { + JSObjectRef parent(CYGetJavaClass(context, super)); CYSetPrototype(context, constructor, parent); CYSetPrototype(context, prototype, CYGetProperty(context, parent, prototype_s)); } @@ -565,7 +892,9 @@ CYJavaForEachPrimitive } } -static bool CYCastJavaArguments(JNIEnv *jni, const CYJavaShorty &shorty, JSContextRef context, const JSValueRef arguments[], jvalue *array) { +static bool CYCastJavaArguments(const CYJavaFrame &frame, const CYJavaShorty &shorty, JSContextRef context, const JSValueRef arguments[], jvalue *array) { + CYJavaEnv jni(frame); + for (size_t index(0); index != shorty.size(); ++index) { JSValueRef argument(arguments[index]); JSType type(JSValueGetType(context, argument)); @@ -573,7 +902,8 @@ static bool CYCastJavaArguments(JNIEnv *jni, const CYJavaShorty &shorty, JSConte switch (CYJavaPrimitive primitive = shorty[index]) { case CYJavaPrimitiveObject: - value.l = CYCastJavaObject(jni, context, argument); + // XXX: figure out a way to tie this in to the CYJavaFrame + value.l = CYCastJavaObject(jni, context, argument).leak(); break; case CYJavaPrimitiveBoolean: @@ -615,22 +945,60 @@ static bool CYCastJavaArguments(JNIEnv *jni, const CYJavaShorty &shorty, JSConte return true; } -static JSValueRef JavaMethod_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry { - CYJavaMethod *internal(reinterpret_cast(JSObjectGetPrivate(object))); - JNIEnv *jni(internal->jni_); - jobject self(CYCastJavaObject(jni, context, _this)); +static JSValueRef JavaInstanceMethod_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry { + auto internal(CYPrivate::Get(context, object)); + CYJavaObject *self(CYGetJavaObject(context, _this)); + _assert(self != NULL); + CYJavaEnv jni(self->value_); + + auto overload(internal->overloads_.find(count)); + if (overload != internal->overloads_.end()) + for (auto signature(overload->second.begin()); signature != overload->second.end(); ++signature) { + CYJavaFrame frame(jni, count + 16); + jvalue array[count]; + if (!CYCastJavaArguments(frame, signature->shorty_, context, arguments, array)) + continue; + jvalue *values(array); + switch (signature->primitive_) { + case CYJavaPrimitiveObject: + return CYCastJSValue(context, jni.CallObjectMethodA(self->value_, signature->method_, values)); + case CYJavaPrimitiveVoid: + jni.CallVoidMethodA(self->value_, signature->method_, values); + return CYJSUndefined(context); +#define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \ + case CYJavaPrimitive ## Type: \ + return CYJavaCastJSValue(context, jni.Call ## Typ ## MethodA(self->value_, signature->method_, values)); +CYJavaForEachPrimitive +#undef CYJavaForEachPrimitive_ + default: _assert(false); + } + } - CYJavaSignature bound(count); - for (auto overload(internal->overload_.lower_bound(bound)), e(internal->overload_.upper_bound(bound)); overload != e; ++overload) { + CYThrow("invalid method call"); +} CYCatch(NULL) } + +static JSValueRef JavaStaticMethod_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry { + auto internal(CYPrivate::Get(context, object)); + CYJavaClass *table(CYGetJavaTable(context, _this)); + CYJavaEnv jni(table->value_); + + auto overload(internal->overloads_.find(count)); + if (overload != internal->overloads_.end()) + for (auto signature(overload->second.begin()); signature != overload->second.end(); ++signature) { + CYJavaFrame frame(jni, count + 16); jvalue array[count]; - if (!CYCastJavaArguments(jni, overload->shorty_, context, arguments, array)) + if (!CYCastJavaArguments(frame, signature->shorty_, context, arguments, array)) continue; - switch (overload->primitive_) { + jvalue *values(array); + switch (signature->primitive_) { case CYJavaPrimitiveObject: - return CYCastJSValue(context, jni, _envcall(jni, CallObjectMethodA(self, overload->method_, array))); + return CYCastJSValue(context, jni.CallStaticObjectMethodA(table->value_, signature->method_, values)); + case CYJavaPrimitiveVoid: + jni.CallStaticVoidMethodA(table->value_, signature->method_, values); + return CYJSUndefined(context); #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \ case CYJavaPrimitive ## Type: \ - return CYJavaCastJSValue(context, _envcall(jni, Call ## Typ ## MethodA(self, overload->method_, array))); + return CYJavaCastJSValue(context, jni.CallStatic ## Typ ## MethodA(table->value_, signature->method_, values)); CYJavaForEachPrimitive #undef CYJavaForEachPrimitive_ default: _assert(false); @@ -641,24 +1009,33 @@ CYJavaForEachPrimitive } CYCatch(NULL) } static JSObjectRef JavaClass_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry { - CYJavaClass *table(reinterpret_cast(JSObjectGetPrivate(object))); - JNIEnv *jni(table->value_); + auto table(CYPrivate::Get(context, object)); + CYJavaEnv jni(table->value_); + jclass _class(table->value_); + + if (table->interface_ && count == 1) { + auto Cycript$(jni.FindClass("Cycript")); + auto Cycript$Make(jni.GetStaticMethodID(Cycript$, "proxy", "(Ljava/lang/Class;LCycript$Wrapper;)Ljava/lang/Object;")); + return CYCastJSObject(context, jni.CallObjectMethod(Cycript$, Cycript$Make, _class, CYCastJavaObject(jni, context, CYCastJSObject(context, arguments[0])).get())); + } - CYJavaSignature bound(count); - for (auto overload(table->overload_.lower_bound(bound)), e(table->overload_.upper_bound(bound)); overload != e; ++overload) { + auto overload(table->overloads_.find(count)); + if (overload != table->overloads_.end()) + for (auto signature(overload->second.begin()); signature != overload->second.end(); ++signature) { + CYJavaFrame frame(jni, count + 16); jvalue array[count]; - if (!CYCastJavaArguments(jni, overload->shorty_, context, arguments, array)) + if (!CYCastJavaArguments(frame, signature->shorty_, context, arguments, array)) continue; - jobject object(_envcall(jni, NewObjectA(table->value_, overload->method_, array))); - // XXX: going through JSValueRef is kind of dumb, no? - return CYCastJSObject(context, CYCastJSValue(context, jni, object)); + jvalue *values(array); + auto object(jni.NewObjectA(_class, signature->method_, values)); + return CYCastJSObject(context, object); } CYThrow("invalid constructor call"); -} CYCatch(NULL) } +} CYCatchObject() } -static bool JavaStatic_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) { - CYJavaStatic *internal(reinterpret_cast(JSObjectGetPrivate(object))); +static bool JavaStaticInterior_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) { + auto internal(CYPrivate::Get(context, object)); CYJavaClass *table(internal->table_); CYPool pool; auto name(CYPoolUTF8String(pool, context, property)); @@ -668,10 +1045,10 @@ static bool JavaStatic_hasProperty(JSContextRef context, JSObjectRef object, JSS return true; } -static JSValueRef JavaStatic_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry { - CYJavaStatic *internal(reinterpret_cast(JSObjectGetPrivate(object))); +static JSValueRef JavaStaticInterior_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry { + auto internal(CYPrivate::Get(context, object)); CYJavaClass *table(internal->table_); - JNIEnv *jni(table->value_); + CYJavaEnv jni(table->value_); CYPool pool; auto name(CYPoolUTF8String(pool, context, property)); auto field(table->static_.find(name)); @@ -680,20 +1057,20 @@ static JSValueRef JavaStatic_getProperty(JSContextRef context, JSObjectRef objec switch (field->second.primitive_) { case CYJavaPrimitiveObject: - return CYCastJSValue(context, jni, _envcall(jni, GetStaticObjectField(table->value_, field->second.field_))); + return CYCastJSValue(context, jni.GetStaticObjectField(table->value_, field->second.field_)); #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \ case CYJavaPrimitive ## Type: \ - return CYJavaCastJSValue(context, _envcall(jni, GetStatic ## Typ ## Field(table->value_, field->second.field_))); + return CYJavaCastJSValue(context, jni.GetStatic ## Typ ## Field(table->value_, field->second.field_)); CYJavaForEachPrimitive #undef CYJavaForEachPrimitive_ default: _assert(false); } } CYCatch(NULL) } -static bool JavaStatic_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry { - CYJavaStatic *internal(reinterpret_cast(JSObjectGetPrivate(object))); +static bool JavaStaticInterior_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry { + auto internal(CYPrivate::Get(context, object)); CYJavaClass *table(internal->table_); - JNIEnv *jni(table->value_); + CYJavaEnv jni(table->value_); CYPool pool; auto name(CYPoolUTF8String(pool, context, property)); auto field(table->static_.find(name)); @@ -702,10 +1079,10 @@ static bool JavaStatic_setProperty(JSContextRef context, JSObjectRef object, JSS switch (field->second.primitive_) { case CYJavaPrimitiveObject: - _envcallv(jni, SetStaticObjectField(table->value_, field->second.field_, CYCastJavaObject(jni, context, value))); + jni.SetStaticObjectField(table->value_, field->second.field_, CYCastJavaObject(jni, context, value)); #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \ case CYJavaPrimitive ## Type: \ - _envcallv(jni, SetStatic ## Typ ## Field(table->value_, field->second.field_, CYCastDouble(context, value))); \ + jni.SetStatic ## Typ ## Field(table->value_, field->second.field_, CYCastDouble(context, value)); \ break; CYJavaForEachPrimitive #undef CYJavaForEachPrimitive_ @@ -715,20 +1092,20 @@ CYJavaForEachPrimitive return true; } CYCatch(false) } -static void JavaStatic_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) { - CYJavaStatic *internal(reinterpret_cast(JSObjectGetPrivate(object))); +static void JavaStaticInterior_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) { + auto internal(CYPrivate::Get(context, object)); CYJavaClass *table(internal->table_); for (const auto &field : table->static_) JSPropertyNameAccumulatorAddName(names, CYJSString(field.first)); } static JSValueRef JavaClass_getProperty_class(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry { - CYJavaClass *table(reinterpret_cast(JSObjectGetPrivate(object))); - return CYCastJSValue(context, table->value_, table->value_); + auto table(CYPrivate::Get(context, object)); + return CYCastJSValue(context, table->value_); } CYCatch(NULL) } static bool JavaInterior_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) { - CYJavaInterior *internal(reinterpret_cast(JSObjectGetPrivate(object))); + auto internal(CYPrivate::Get(context, object)); CYJavaClass *table(internal->table_); CYPool pool; auto name(CYPoolUTF8String(pool, context, property)); @@ -739,8 +1116,8 @@ static bool JavaInterior_hasProperty(JSContextRef context, JSObjectRef object, J } static JSValueRef JavaInterior_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry { - CYJavaInterior *internal(reinterpret_cast(JSObjectGetPrivate(object))); - JNIEnv *jni(internal->value_); + auto internal(CYPrivate::Get(context, object)); + CYJavaEnv jni(internal->value_); CYJavaClass *table(internal->table_); CYPool pool; auto name(CYPoolUTF8String(pool, context, property)); @@ -750,10 +1127,10 @@ static JSValueRef JavaInterior_getProperty(JSContextRef context, JSObjectRef obj switch (field->second.primitive_) { case CYJavaPrimitiveObject: - return CYCastJSValue(context, jni, _envcall(jni, GetObjectField(internal->value_, field->second.field_))); + return CYCastJSValue(context, jni.GetObjectField(internal->value_, field->second.field_)); #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \ case CYJavaPrimitive ## Type: \ - return CYJavaCastJSValue(context, _envcall(jni, Get ## Typ ## Field(internal->value_, field->second.field_))); + return CYJavaCastJSValue(context, jni.Get ## Typ ## Field(internal->value_, field->second.field_)); CYJavaForEachPrimitive #undef CYJavaForEachPrimitive_ default: _assert(false); @@ -761,8 +1138,8 @@ CYJavaForEachPrimitive } CYCatch(NULL) } static bool JavaInterior_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry { - CYJavaInterior *internal(reinterpret_cast(JSObjectGetPrivate(object))); - JNIEnv *jni(internal->value_); + auto internal(CYPrivate::Get(context, object)); + CYJavaEnv jni(internal->value_); CYJavaClass *table(internal->table_); CYPool pool; auto name(CYPoolUTF8String(pool, context, property)); @@ -772,10 +1149,10 @@ static bool JavaInterior_setProperty(JSContextRef context, JSObjectRef object, J switch (field->second.primitive_) { case CYJavaPrimitiveObject: - _envcallv(jni, SetObjectField(table->value_, field->second.field_, CYCastJavaObject(jni, context, value))); + jni.SetObjectField(table->value_, field->second.field_, CYCastJavaObject(jni, context, value)); #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \ case CYJavaPrimitive ## Type: \ - _envcallv(jni, Set ## Typ ## Field(table->value_, field->second.field_, CYCastDouble(context, value))); \ + jni.Set ## Typ ## Field(table->value_, field->second.field_, CYCastDouble(context, value)); \ break; CYJavaForEachPrimitive #undef CYJavaForEachPrimitive_ @@ -786,48 +1163,61 @@ CYJavaForEachPrimitive } CYCatch(false) } static void JavaInterior_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) { - CYJavaInterior *internal(reinterpret_cast(JSObjectGetPrivate(object))); + auto internal(CYPrivate::Get(context, object)); CYJavaClass *table(internal->table_); for (const auto &field : table->instance_) JSPropertyNameAccumulatorAddName(names, CYJSString(field.first)); } static JSValueRef JavaObject_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry { - CYJavaObject *internal(reinterpret_cast(JSObjectGetPrivate(object))); - JNIEnv *jni(internal->value_); - return CYGetJavaClass(context, jni, _envcall(jni, GetObjectClass(internal->value_))); + auto internal(CYPrivate::Get(context, object)); + CYJavaEnv jni(internal->value_); + return CYGetJavaClass(context, jni.GetObjectClass(internal->value_)); } CYCatch(NULL) } static JSValueRef JavaClass_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry { - CYJavaClass *internal(reinterpret_cast(JSObjectGetPrivate(object))); - JNIEnv *jni(internal->value_); - return CYJavaStatic::Make(context, jni, internal->value_, internal); + auto internal(CYPrivate::Get(context, object)); + return CYPrivate::Make(context, internal->value_, internal); } CYCatch(NULL) } static JSValueRef JavaObject_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry { - CYJavaObject *internal(reinterpret_cast(JSObjectGetPrivate(object))); - JNIEnv *jni(internal->value_); - return CYJavaInterior::Make(context, jni, internal->value_, internal->table_); + auto internal(CYPrivate::Get(context, object)); + return CYPrivate::Make(context, internal->value_, internal->table_); } CYCatch(NULL) } static JSValueRef JavaClass_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry { - CYJavaClass *internal(reinterpret_cast(JSObjectGetPrivate(_this))); - JNIEnv *jni(internal->value_); - jclass Class$(_envcall(jni, FindClass("java/lang/Class"))); - jmethodID Class$getCanonicalName(_envcall(jni, GetMethodID(Class$, "getCanonicalName", "()Ljava/lang/String;"))); - return CYCastJSValue(context, CYJSString(jni, static_cast(_envcall(jni, CallObjectMethod(internal->value_, Class$getCanonicalName))))); + auto internal(CYPrivate::Get(context, _this)); + CYJavaEnv jni(internal->value_); + auto Class$(jni.FindClass("java/lang/Class")); + auto Class$getCanonicalName(jni.GetMethodID(Class$, "getCanonicalName", "()Ljava/lang/String;")); + return CYCastJSValue(context, CYJSString(jni.CallObjectMethod(internal->value_, Class$getCanonicalName))); } CYCatch(NULL) } static JSValueRef JavaMethod_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry { + auto internal(CYPrivate::Get(context, _this)); std::ostringstream cyon; + if (false) + cyon << internal->type_ << "." << internal->name_; + else { + bool comma(false); + for (auto overload(internal->overloads_.begin()); overload != internal->overloads_.end(); ++overload) + for (auto signature(overload->second.begin()); signature != overload->second.end(); ++signature) { + if (comma) + cyon << std::endl; + else + comma = true; + auto string(CYCastJavaString(signature->reflected_)); + cyon << CYJavaUTF8String(string); + } + } return CYCastJSValue(context, CYJSString(cyon.str())); } CYCatch(NULL) } static JSValueRef JavaArray_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry { - CYJavaArray *internal(reinterpret_cast(JSObjectGetPrivate(object))); - JNIEnv *jni(internal->value_); + auto internal(CYPrivate::Get(context, object)); + CYJavaEnv jni(internal->value_); if (JSStringIsEqual(property, length_s)) - return CYCastJSValue(context, _envcall(jni, GetArrayLength(internal->value_))); + return CYCastJSValue(context, jni.GetArrayLength(internal->value_)); CYPool pool; ssize_t offset; @@ -835,12 +1225,12 @@ static JSValueRef JavaArray_getProperty(JSContextRef context, JSObjectRef object return NULL; if (internal->primitive_ == CYJavaPrimitiveObject) - return CYCastJSValue(context, jni, _envcall(jni, GetObjectArrayElement(static_cast(internal->value_.value_), offset))); + return CYCastJSValue(context, jni.GetObjectArrayElement(static_cast(internal->value_.value_), offset)); else switch (internal->primitive_) { #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \ case CYJavaPrimitive ## Type: { \ j ## type element; \ - _envcallv(jni, Get ## Typ ## ArrayRegion(static_cast(internal->value_.value_), offset, 1, &element)); \ + jni.Get ## Typ ## ArrayRegion(static_cast(internal->value_.value_), offset, 1, &element); \ return CYJavaCastJSValue(context, element); \ } break; CYJavaForEachPrimitive @@ -850,8 +1240,8 @@ CYJavaForEachPrimitive } CYCatch(NULL) } static bool JavaArray_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry { - CYJavaArray *internal(reinterpret_cast(JSObjectGetPrivate(object))); - JNIEnv *jni(internal->value_); + auto internal(CYPrivate::Get(context, object)); + CYJavaEnv jni(internal->value_); CYPool pool; ssize_t offset; @@ -859,12 +1249,12 @@ static bool JavaArray_setProperty(JSContextRef context, JSObjectRef object, JSSt return false; if (internal->primitive_ == CYJavaPrimitiveObject) - _envcallv(jni, SetObjectArrayElement(static_cast(internal->value_.value_), offset, CYCastJavaObject(jni, context, value))); + jni.SetObjectArrayElement(static_cast(internal->value_.value_), offset, CYCastJavaObject(jni, context, value)); else switch (internal->primitive_) { #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \ case CYJavaPrimitive ## Type: { \ j ## type element; \ - _envcallv(jni, Get ## Typ ## ArrayRegion(static_cast(internal->value_.value_), offset, 1, &element)); \ + jni.Get ## Typ ## ArrayRegion(static_cast(internal->value_.value_), offset, 1, &element); \ return CYJavaCastJSValue(context, element); \ } break; CYJavaForEachPrimitive @@ -875,8 +1265,10 @@ CYJavaForEachPrimitive return true; } CYCatch(false) } +static JNIEnv *GetJNI(JSContextRef context, JNIEnv *&env); + static JSValueRef JavaPackage_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry { - CYJavaPackage *internal(reinterpret_cast(JSObjectGetPrivate(_this))); + auto internal(CYPrivate::Get(context, _this)); std::ostringstream name; for (auto &package : internal->package_) name << package << '.'; @@ -889,7 +1281,7 @@ static bool CYJavaPackage_hasProperty(JSContextRef context, JSObjectRef object, } static JSValueRef CYJavaPackage_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry { - CYJavaPackage *internal(reinterpret_cast(JSObjectGetPrivate(object))); + auto internal(CYPrivate::Get(context, object)); CYJavaPackage::Path package(internal->package_); CYPool pool; @@ -900,15 +1292,224 @@ static JSValueRef CYJavaPackage_getProperty(JSContextRef context, JSObjectRef ob name << package << '/'; name << next; - JNIEnv *jni(GetJNI()); - if (jclass _class = jni->FindClass(name.str().c_str())) - return CYGetJavaClass(context, jni, _class); + if (internal->jni_ == NULL) + GetJNI(context, internal->jni_); + JNIEnv *jni(internal->jni_); + + if (auto _class = jni->FindClass(name.str().c_str())) + return CYGetJavaClass(context, CYJavaLocal(jni, _class)); jni->ExceptionClear(); package.push_back(next); - return CYJavaPackage::Make(context, package); + return CYPrivate::Make(context, jni, package); } CYCatch(NULL) } +static void Cycript_delete(JNIEnv *env, jclass api, jlong jprotect) { CYJavaTry { + delete &protect; +} CYJavaCatch() } + +static jobject Cycript_handle(JNIEnv *env, jclass api, jlong jprotect, jstring property, jobjectArray jarguments) { CYJavaTry { + JSValueRef function(CYGetProperty(context, object, CYJSString(CYJavaRef(jni, property)))); + if (JSValueIsUndefined(context, function)) + return NULL; + + size_t count(jarguments == NULL ? 0 : jni.GetArrayLength(jarguments)); + JSValueRef arguments[count]; + for (size_t index(0); index != count; ++index) + arguments[index] = CYCastJSValue(context, jni.GetObjectArrayElement(jarguments, index)); + + return CYCastJavaObject(jni, context, CYCallAsFunction(context, CYCastJSObject(context, function), object, count, arguments)).leak(); +} CYJavaCatch(NULL) } + +static JNINativeMethod Cycript_[] = { + {(char *) "delete", (char *) "(J)V", (void *) &Cycript_delete}, + {(char *) "handle", (char *) "(JLjava/lang/String;[Ljava/lang/Object;)Ljava/lang/Object;", (void *) &Cycript_handle}, +}; + +template +static _finline void dlset(Type_ &function, const char *name, void *handle) { + function = reinterpret_cast(dlsym(handle, name)); +} + +jint CYJavaVersion(JNI_VERSION_1_4); + +static JavaVM *CYGetJavaVM(jint (*$JNI_GetCreatedJavaVMs)(JavaVM **, jsize, jsize *)) { + jsize capacity(16); + JavaVM *jvms[capacity]; + jsize size; + _jnicall($JNI_GetCreatedJavaVMs(jvms, capacity, &size)); + if (size == 0) + return NULL; + return jvms[0]; +} + +static JavaVM *CYGetJavaVM(JSContextRef context) { + CYPool pool; + void *handle(RTLD_DEFAULT); + std::string library; + + jint (*$JNI_GetCreatedJavaVMs)(JavaVM **jvms, jsize capacity, jsize *size); + dlset($JNI_GetCreatedJavaVMs, "JNI_GetCreatedJavaVMs", handle); + + if ($JNI_GetCreatedJavaVMs != NULL) { + if (JavaVM *jvm = CYGetJavaVM($JNI_GetCreatedJavaVMs)) + return jvm; + } else { + std::vector guesses; + +#ifdef __ANDROID__ + char android[PROP_VALUE_MAX]; + if (__system_property_get("persist.sys.dalvik.vm.lib", android) != 0) + guesses.push_back(android); +#endif + + guesses.push_back("/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/jli/libjli.dylib"); + //guesses.push_back("/System/Library/Frameworks/JavaVM.framework/JavaVM"); + guesses.push_back("libjvm.dylib"); + + guesses.push_back("libart.so"); + guesses.push_back("libdvm.so"); + guesses.push_back("libjvm.so"); + + for (const char *guess : guesses) { + handle = dlopen(guess, RTLD_LAZY | RTLD_GLOBAL); + if (handle != NULL) { + library = guess; + break; + } + } + + if (library.size() == 0) + return NULL; + + dlset($JNI_GetCreatedJavaVMs, "JNI_GetCreatedJavaVMs", handle); + if (JavaVM *jvm = CYGetJavaVM($JNI_GetCreatedJavaVMs)) + return jvm; + } + + std::vector options; + + { + std::ostringstream option; + option << "-Djava.class.path="; + option << CYPoolLibraryPath(pool) << "/libcycript.jar"; + if (const char *classpath = getenv("CLASSPATH")) + option << ':' << classpath; + options.push_back(JavaVMOption{pool.strdup(option.str().c_str()), NULL}); + } + + // To use libnativehelper to access JNI_GetCreatedJavaVMs, you need JniInvocation. + // ...but there can only be one JniInvocation, and assuradely the other VM has it. + // Essentially, this API makes no sense. We need it for AndroidRuntime, though :/. + + if (void *libnativehelper = dlopen("libnativehelper.so", RTLD_LAZY | RTLD_GLOBAL)) { + class JniInvocation$; + JniInvocation$ *(*JniInvocation$$init$)(JniInvocation$ *self)(NULL); + bool (*JniInvocation$Init)(JniInvocation$ *self, const char *library)(NULL); + JniInvocation$ *(*JniInvocation$finalize)(JniInvocation$ *self)(NULL); + + dlset(JniInvocation$$init$, "_ZN13JniInvocationC1Ev", libnativehelper); + dlset(JniInvocation$Init, "_ZN13JniInvocation4InitEPKc", libnativehelper); + dlset(JniInvocation$finalize, "_ZN13JniInvocationD1Ev", libnativehelper); + + if (JniInvocation$$init$ == NULL) + dlclose(libnativehelper); + else { + // XXX: we should attach a pool to the VM itself and deallocate this there + //auto invocation(pool.calloc(1, 1024)); + //_assert(JniInvocation$finalize != NULL); + //pool.atexit(reinterpret_cast(JniInvocation$finalize), invocation); + + auto invocation(static_cast(calloc(1, 1024))); + JniInvocation$$init$(invocation); + + _assert(JniInvocation$Init != NULL); + JniInvocation$Init(invocation, NULL); + + dlset($JNI_GetCreatedJavaVMs, "JNI_GetCreatedJavaVMs", libnativehelper); + if (JavaVM *jvm = CYGetJavaVM($JNI_GetCreatedJavaVMs)) + return jvm; + } + } + + JavaVM *jvm; + JNIEnv *env; + + if (void *libandroid_runtime = dlopen("libandroid_runtime.so", RTLD_LAZY | RTLD_GLOBAL)) { + class AndroidRuntime$; + AndroidRuntime$ *(*AndroidRuntime$$init$)(AndroidRuntime$ *self, char *args, unsigned int size)(NULL); + int (*AndroidRuntime$startVm)(AndroidRuntime$ *self, JavaVM **jvm, JNIEnv **env)(NULL); + int (*AndroidRuntime$startReg)(JNIEnv *env)(NULL); + int (*AndroidRuntime$addOption)(AndroidRuntime$ *self, const char *option, void *extra)(NULL); + int (*AndroidRuntime$addVmArguments)(AndroidRuntime$ *self, int, const char *const argv[])(NULL); + AndroidRuntime$ *(*AndroidRuntime$finalize)(AndroidRuntime$ *self)(NULL); + + dlset(AndroidRuntime$$init$, "_ZN7android14AndroidRuntimeC1EPcj", libandroid_runtime); + dlset(AndroidRuntime$startVm, "_ZN7android14AndroidRuntime7startVmEPP7_JavaVMPP7_JNIEnv", libandroid_runtime); + dlset(AndroidRuntime$startReg, "_ZN7android14AndroidRuntime8startRegEP7_JNIEnv", libandroid_runtime); + dlset(AndroidRuntime$addOption, "_ZN7android14AndroidRuntime9addOptionEPKcPv", libandroid_runtime); + dlset(AndroidRuntime$addVmArguments, "_ZN7android14AndroidRuntime14addVmArgumentsEiPKPKc", libandroid_runtime); + dlset(AndroidRuntime$finalize, "_ZN7android14AndroidRuntimeD1Ev", libandroid_runtime); + + // XXX: it would also be interesting to attach this to a global pool + AndroidRuntime$ *runtime(pool.calloc(1, 1024)); + + _assert(AndroidRuntime$$init$ != NULL); + AndroidRuntime$$init$(runtime, NULL, 0); + + if (AndroidRuntime$addOption == NULL) { + _assert(AndroidRuntime$addVmArguments != NULL); + std::vector arguments; + for (const auto &option : options) + arguments.push_back(option.optionString); + AndroidRuntime$addVmArguments(runtime, arguments.size(), arguments.data()); + } else for (const auto &option : options) + AndroidRuntime$addOption(runtime, option.optionString, option.extraInfo); + + int failure; + + _assert(AndroidRuntime$startVm != NULL); + failure = AndroidRuntime$startVm(runtime, &jvm, &env); + _assert(failure == 0); + + _assert(AndroidRuntime$startReg != NULL); + failure = AndroidRuntime$startReg(env); + _assert(failure == 0); + + return jvm; + } + + jint (*$JNI_CreateJavaVM)(JavaVM **jvm, void **, void *); + dlset($JNI_CreateJavaVM, "JNI_CreateJavaVM", handle); + + JavaVMInitArgs args; + memset(&args, 0, sizeof(args)); + args.version = CYJavaVersion; + args.nOptions = options.size(); + args.options = options.data(); + _jnicall($JNI_CreateJavaVM(&jvm, reinterpret_cast(&env), &args)); + return jvm; +} + +static JNIEnv *GetJNI(JSContextRef context, JNIEnv *&env) { + auto jvm(CYGetJavaVM(context)); + _assert(jvm != NULL); + _jnicall(jvm->GetEnv(reinterpret_cast(&env), CYJavaVersion)); + CYJavaEnv jni(env); + + // XXX: this happens once per stub :/ + + auto Cycript$(jni.FindClass("Cycript")); + jni.RegisterNatives(Cycript$, Cycript_, sizeof(Cycript_) / sizeof(Cycript_[0])); + + JSObjectRef java(CYGetCachedObject(context, CYJSString("Java"))); + JSValueRef arguments[1]; + arguments[0] = CYCastJSValue(context, CYJSString("setup")); + CYCallAsFunction(context, CYCastJSObject(context, CYGetProperty(context, java, CYJSString("emit"))), java, 1, arguments); + + return env; +} + static JSStaticValue JavaClass_staticValues[3] = { {"class", &JavaClass_getProperty_class, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, {"$cyi", &JavaClass_getProperty_$cyi, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, @@ -926,7 +1527,12 @@ static JSStaticValue JavaObject_staticValues[3] = { {NULL, NULL, NULL, 0} }; -static JSStaticFunction JavaMethod_staticFunctions[2] = { +static JSStaticFunction JavaInstanceMethod_staticFunctions[2] = { + {"toCYON", &JavaMethod_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, + {NULL, NULL, 0} +}; + +static JSStaticFunction JavaStaticMethod_staticFunctions[2] = { {"toCYON", &JavaMethod_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete}, {NULL, NULL, 0} }; @@ -951,7 +1557,7 @@ CYJavaForEachPrimitive definition.staticFunctions = JavaClass_staticFunctions; definition.callAsConstructor = &JavaClass_callAsConstructor; definition.finalize = &CYFinalize; - CYJavaClass::Class_ = JSClassCreate(&definition); + CYPrivate::Class_ = JSClassCreate(&definition); definition = kJSClassDefinitionEmpty; definition.attributes = kJSClassAttributeNoAutomaticPrototype; @@ -961,28 +1567,40 @@ CYJavaForEachPrimitive definition.setProperty = &JavaInterior_setProperty; definition.getPropertyNames = &JavaInterior_getPropertyNames; definition.finalize = &CYFinalize; - CYJavaInterior::Class_ = JSClassCreate(&definition); + CYPrivate::Class_ = JSClassCreate(&definition); definition = kJSClassDefinitionEmpty; definition.className = "JavaMethod"; - definition.staticFunctions = JavaMethod_staticFunctions; - definition.callAsFunction = &JavaMethod_callAsFunction; definition.finalize = &CYFinalize; - CYJavaMethod::Class_ = JSClassCreate(&definition); + CYPrivate::Class_ = JSClassCreate(&definition); + + definition = kJSClassDefinitionEmpty; + definition.className = "JavaInstanceMethod"; + definition.parentClass = CYPrivate::Class_; + definition.staticFunctions = JavaInstanceMethod_staticFunctions; + definition.callAsFunction = &JavaInstanceMethod_callAsFunction; + CYPrivate::Class_ = JSClassCreate(&definition); + + definition = kJSClassDefinitionEmpty; + definition.className = "JavaStaticMethod"; + definition.parentClass = CYPrivate::Class_; + definition.staticFunctions = JavaStaticMethod_staticFunctions; + definition.callAsFunction = &JavaStaticMethod_callAsFunction; + CYPrivate::Class_ = JSClassCreate(&definition); definition = kJSClassDefinitionEmpty; definition.attributes = kJSClassAttributeNoAutomaticPrototype; definition.className = "JavaObject"; definition.staticValues = JavaObject_staticValues; definition.finalize = &CYFinalize; - CYJavaObject::Class_ = JSClassCreate(&definition); + CYPrivate::Class_ = JSClassCreate(&definition); definition = kJSClassDefinitionEmpty; definition.className = "JavaArray"; definition.getProperty = &JavaArray_getProperty; definition.setProperty = &JavaArray_setProperty; definition.finalize = &CYFinalize; - CYJavaArray::Class_ = JSClassCreate(&definition); + CYPrivate::Class_ = JSClassCreate(&definition); definition = kJSClassDefinitionEmpty; definition.className = "JavaPackage"; @@ -990,35 +1608,36 @@ CYJavaForEachPrimitive definition.hasProperty = &CYJavaPackage_hasProperty; definition.getProperty = &CYJavaPackage_getProperty; definition.finalize = &CYFinalize; - CYJavaPackage::Class_ = JSClassCreate(&definition); + CYPrivate::Class_ = JSClassCreate(&definition); definition = kJSClassDefinitionEmpty; definition.attributes = kJSClassAttributeNoAutomaticPrototype; - definition.className = "JavaStatic"; - definition.hasProperty = &JavaStatic_hasProperty; - definition.getProperty = &JavaStatic_getProperty; - definition.setProperty = &JavaStatic_setProperty; - definition.getPropertyNames = &JavaStatic_getPropertyNames; + definition.className = "JavaStaticInterior"; + definition.hasProperty = &JavaStaticInterior_hasProperty; + definition.getProperty = &JavaStaticInterior_getProperty; + definition.setProperty = &JavaStaticInterior_setProperty; + definition.getPropertyNames = &JavaStaticInterior_getPropertyNames; definition.finalize = &CYFinalize; - CYJavaStatic::Class_ = JSClassCreate(&definition); + CYPrivate::Class_ = JSClassCreate(&definition); } void CYJava_SetupContext(JSContextRef context) { JSObjectRef global(CYGetGlobalObject(context)); - //JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s))); + JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s))); JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript")))); JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all")))); //JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls")))); JSObjectRef Java(JSObjectMake(context, NULL, NULL)); CYSetProperty(context, cycript, CYJSString("Java"), Java); + CYSetProperty(context, cy, CYJSString("Java"), Java); - JSObjectRef Packages(CYJavaPackage::Make(context, CYJavaPackage::Path())); - CYSetProperty(context, all, CYJSString("Packages"), Packages); + JSObjectRef Packages(CYPrivate::Make(context, nullptr, CYJavaPackage::Path())); + CYSetProperty(context, all, CYJSString("Packages"), Packages, kJSPropertyAttributeDontEnum); for (auto name : (const char *[]) {"java", "javax", "android", "com", "net", "org"}) { CYJSString js(name); - CYSetProperty(context, all, js, CYGetProperty(context, Packages, js)); + CYSetProperty(context, all, js, CYPrivate::Make(context, nullptr, CYJavaPackage::Path(1, name)), kJSPropertyAttributeDontEnum); } }