1 /* Cycript - The Truly Universal Scripting Language
2 * Copyright (C) 2009-2016 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
29 #include <JavaVM/jni.h>
35 // XXX: this is deprecated?!?!?!?!?!?!
36 #include <sys/system_properties.h>
39 #include "cycript.hpp"
41 #include "Execute.hpp"
42 #include "Internal.hpp"
43 #include "JavaScript.hpp"
44 #include "Pooling.hpp"
46 #define _jnicall(expr) ({ \
48 if (_value != JNI_OK) \
49 CYThrow("_jnicall(%s) == %d", #expr, _value); \
52 #define _envcall(jni, expr) ({ \
53 __typeof__(jni->expr) _value(jni->expr); \
54 if (jthrowable _error = jni->ExceptionOccurred()) { \
55 jni->ExceptionClear(); \
56 throw CYJavaError(CYJavaLocal<jthrowable>(jni, _error)); \
60 #define _envcallv(jni, expr) do { \
62 if (jthrowable _error = jni->ExceptionOccurred()) { \
63 jni->ExceptionClear(); \
64 throw CYJavaError(CYJavaLocal<jthrowable>(jni, _error)); \
70 auto &protect(*reinterpret_cast<CYProtect *>(jprotect)); \
71 _disused JSContextRef context(protect); \
72 _disused JSObjectRef object(protect); \
74 #define CYJavaCatch(value) \
75 catch (const CYException &error) { \
76 jni->Throw(CYCastJavaObject(jni, context, error.CastJSValue(context, "Error")).cast<jthrowable>()); \
80 static JNIEnv
*GetJNI(JSContextRef context
);
82 #define CYJavaForEachPrimitive \
83 CYJavaForEachPrimitive_(Z, z, Boolean, Boolean, boolean) \
84 CYJavaForEachPrimitive_(B, b, Byte, Byte, byte) \
85 CYJavaForEachPrimitive_(C, c, Char, Character, char) \
86 CYJavaForEachPrimitive_(S, s, Short, Short, short) \
87 CYJavaForEachPrimitive_(I, i, Int, Integer, int) \
88 CYJavaForEachPrimitive_(J, j, Long, Long, long) \
89 CYJavaForEachPrimitive_(F, f, Float, Float, float) \
90 CYJavaForEachPrimitive_(D, d, Double, Double, double)
92 enum CYJavaPrimitive
: char {
93 CYJavaPrimitiveObject
,
95 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
96 CYJavaPrimitive ## Type,
97 CYJavaForEachPrimitive
98 #undef CYJavaForEachPrimitive_
101 template <typename Type_
>
102 struct IsJavaPrimitive
{ static const bool value
= false; };
104 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
106 struct IsJavaPrimitive<j ## type> { static const bool value = true; };
107 CYJavaForEachPrimitive
108 #undef CYJavaForEachPrimitive_
110 // Java References {{{
111 template <typename Value_
>
116 _finline
CYJavaRef(JNIEnv
*jni
, Value_ value
) :
122 _finline
operator Value_() const {
126 _finline JNIEnv
*jni() const {
130 // XXX: this is only needed to support CYJavaEnv relying on C variadics
131 _finline Value_
get() const {
135 template <typename Other_
>
136 _finline CYJavaRef
<Other_
> cast() const {
137 return {jni_
, static_cast<Other_
>(value_
)};
140 // XXX: this should be tied into CYJavaFrame
142 Value_
value(value_
);
148 template <typename Value_
, void (JNIEnv::*Delete_
)(jobject
)>
149 struct CYJavaDelete
:
152 _finline
CYJavaDelete(JNIEnv
*jni
, Value_ value
) :
153 CYJavaRef
<Value_
>(jni
, value
)
158 if (this->value_
!= NULL
)
159 (this->jni_
->*Delete_
)(this->value_
);
168 template <typename Value_
>
169 struct CYJavaGlobal
:
170 CYJavaDelete
<Value_
, &JNIEnv::DeleteGlobalRef
>
172 typedef CYJavaDelete
<Value_
, &JNIEnv::DeleteGlobalRef
> CYJavaBase
;
175 CYJavaBase(NULL
, NULL
)
179 template <typename Other_
>
180 CYJavaGlobal(const CYJavaRef
<Other_
> &other
) :
181 CYJavaBase(other
.jni_
, static_cast<Other_
>(other
.jni_
->NewGlobalRef(other
.value_
)))
185 CYJavaGlobal(const CYJavaGlobal
<Value_
> &other
) :
186 CYJavaGlobal(static_cast<const CYJavaRef
<Value_
> &>(other
))
190 CYJavaGlobal(CYJavaGlobal
&&value
) :
191 CYJavaBase(value
.jni_
, value
.value_
)
197 template <typename Value_
>
199 CYJavaDelete
<Value_
, &JNIEnv::DeleteLocalRef
>
201 typedef CYJavaDelete
<Value_
, &JNIEnv::DeleteLocalRef
> CYJavaBase
;
204 CYJavaBase(NULL
, NULL
)
208 CYJavaLocal(JNIEnv
*jni
, Value_ value
) :
209 CYJavaBase(jni
, value
)
213 template <typename Other_
>
214 CYJavaLocal(const CYJavaRef
<Other_
> &other
) :
215 CYJavaLocal(other
.jni_
, static_cast<Other_
>(other
.jni_
->NewLocalRef(other
.value_
)))
219 template <typename Other_
>
220 CYJavaLocal(CYJavaRef
<Other_
> &&other
) :
221 CYJavaLocal(other
.jni_
, other
.value_
)
226 CYJavaLocal(CYJavaLocal
&&other
) :
227 CYJavaLocal(static_cast<CYJavaRef
<Value_
> &&>(other
))
231 template <typename Other_
>
232 CYJavaLocal
&operator =(CYJavaLocal
<Other_
> &&other
) {
234 this->jni_
= other
.jni_
;
235 this->value_
= other
.value_
;
242 static CYJavaLocal
<jstring
> CYCastJavaString(const CYJavaRef
<jobject
> &value
);
244 class CYJavaUTF8String
:
248 const CYJavaRef
<jstring
> *value_
;
251 CYJavaUTF8String(const CYJavaRef
<jstring
> &value
) :
255 JNIEnv
*jni(value
.jni());
256 size
= jni
->GetStringUTFLength(value
);
257 data
= jni
->GetStringUTFChars(value
, NULL
);
260 CYJavaUTF8String(const CYJavaRef
<jobject
> &value
) :
261 CYJavaUTF8String(CYCastJavaString(value
))
265 ~CYJavaUTF8String() {
266 if (value_
!= NULL
) {
267 JNIEnv
*jni(value_
->jni());
268 jni
->ReleaseStringUTFChars(*value_
, data
);
272 CYJavaUTF8String(const CYJavaUTF8String
&) = delete;
274 CYJavaUTF8String(CYJavaUTF8String
&&rhs
) :
281 CYJavaUTF8String
CYCastUTF8String(const CYJavaRef
<jstring
> &value
) {
282 return CYJavaUTF8String(value
);
285 JSStringRef
CYCopyJSString(const CYJavaRef
<jstring
> &value
) {
286 return CYCopyJSString(CYCastUTF8String(value
));
293 CYJavaGlobal
<jthrowable
> value_
;
295 CYJavaError(const CYJavaRef
<jthrowable
> &value
) :
300 virtual const char *PoolCString(CYPool
&pool
) const {
301 return CYPoolCString(pool
, CYJavaUTF8String(value_
.cast
<jobject
>()));
304 virtual JSValueRef
CastJSValue(JSContextRef context
, const char *name
) const;
311 CYJavaFrame(JNIEnv
*jni
, jint capacity
) :
314 _assert(jni
->PushLocalFrame(capacity
) == 0);
321 operator JNIEnv
*() const {
325 jobject
operator ()(jobject object
) {
328 return jni
->PopLocalFrame(object
);
337 CYJavaEnv(JNIEnv
*jni
) :
342 template <typename Other_
>
343 CYJavaEnv(const CYJavaRef
<Other_
> &value
) :
348 operator JNIEnv
*() const {
352 JNIEnv
*operator ->() const {
356 CYJavaLocal
<jclass
> FindClass(const char *name
) const {
357 return {jni
, _envcall(jni
, FindClass(name
))};
360 CYJavaLocal
<jclass
> GetObjectClass(jobject object
) const {
361 return {jni
, _envcall(jni
, GetObjectClass(object
))};
364 CYJavaLocal
<jclass
> GetSuperclass(jclass _class
) const {
365 return {jni
, _envcall(jni
, GetSuperclass(_class
))};
368 CYJavaLocal
<jobject
> NewObject(jclass _class
, jmethodID method
, ...) const {
370 va_start(args
, method
);
371 jobject
object(_envcall(jni
, NewObjectV(_class
, method
, args
)));
373 return {jni
, object
};
376 CYJavaLocal
<jobject
> NewObjectA(jclass _class
, jmethodID method
, jvalue
*args
) const {
377 return {jni
, _envcall(jni
, NewObjectA(_class
, method
, args
))};
380 CYJavaLocal
<jstring
> NewString(const jchar
*data
, jsize size
) const {
381 return {jni
, _envcall(jni
, NewString(data
, size
))};
384 #define CYJavaEnv_(Code) \
385 template <typename... Args_> \
386 void Code(Args_ &&... args) const { \
387 _envcallv(jni, Code(cy::Forward<Args_>(args)...)); \
390 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
391 CYJavaEnv_(Get ## Typ ## ArrayRegion) \
392 CYJavaEnv_(Set ## Typ ## Field) \
393 CYJavaEnv_(SetStatic ## Typ ## Field)
394 CYJavaForEachPrimitive
395 #undef CYJavaForEachPrimitive_
397 CYJavaEnv_(CallVoidMethod
)
398 CYJavaEnv_(CallStaticVoidMethod
)
399 CYJavaEnv_(CallVoidMethodA
)
400 CYJavaEnv_(CallStaticVoidMethodA
)
401 CYJavaEnv_(SetObjectArrayElement
)
402 CYJavaEnv_(SetObjectField
)
403 CYJavaEnv_(SetStaticObjectField
)
406 #define CYJavaEnv_(Code) \
407 template <typename... Args_> \
408 auto Code(Args_ &&... args) const -> decltype(jni->Code(cy::Forward<Args_>(args)...)) { \
409 return _envcall(jni, Code(cy::Forward<Args_>(args)...)); \
412 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
413 CYJavaEnv_(Call ## Typ ## Method) \
414 CYJavaEnv_(CallStatic ## Typ ## Method) \
415 CYJavaEnv_(Call ## Typ ## MethodA) \
416 CYJavaEnv_(CallStatic ## Typ ## MethodA) \
417 CYJavaEnv_(Get ## Typ ## Field) \
418 CYJavaEnv_(GetStatic ## Typ ## Field)
419 CYJavaForEachPrimitive
420 #undef CYJavaForEachPrimitive_
422 CYJavaEnv_(FromReflectedField
)
423 CYJavaEnv_(FromReflectedMethod
)
424 CYJavaEnv_(GetArrayLength
)
425 CYJavaEnv_(GetMethodID
)
426 CYJavaEnv_(GetStaticMethodID
)
427 CYJavaEnv_(IsSameObject
)
428 CYJavaEnv_(RegisterNatives
)
431 #define CYJavaEnv_(Code) \
432 template <typename Other_, typename... Args_> \
433 auto Code(Args_ &&... args) const -> CYJavaLocal<Other_> { \
434 return {jni, static_cast<Other_>(_envcall(jni, Code(cy::Forward<Args_>(args)...)))}; \
437 CYJavaEnv_(CallObjectMethod
)
438 CYJavaEnv_(CallStaticObjectMethod
)
439 CYJavaEnv_(CallObjectMethodA
)
440 CYJavaEnv_(CallStaticObjectMethodA
)
441 CYJavaEnv_(GetObjectArrayElement
)
442 CYJavaEnv_(GetObjectField
)
443 CYJavaEnv_(GetStaticObjectField
)
447 static CYJavaLocal
<jstring
> CYCastJavaString(const CYJavaRef
<jobject
> &value
) {
448 CYJavaEnv
jni(value
);
449 auto Object$
(jni
.FindClass("java/lang/Object"));
450 auto Object$
toString(jni
.GetMethodID(Object$
, "toString", "()Ljava/lang/String;"));
451 return jni
.CallObjectMethod
<jstring
>(value
, Object$toString
);
454 template <typename Internal_
, typename Value_
>
458 CYJavaGlobal
<Value_
> value_
;
460 CYJavaValue(const CYJavaRef
<Value_
> &value
) :
465 CYJavaValue(const CYJavaValue
&) = delete;
468 static JSValueRef
CYCastJSValue(JSContextRef context
, const CYJavaRef
<jobject
> &value
);
470 template <typename Other_
>
471 static _finline JSValueRef
CYCastJSValue(JSContextRef context
, const CYJavaRef
<Other_
> &value
) {
472 return CYCastJSValue(context
, value
.template cast
<jobject
>());
475 template <typename Type_
>
476 static _finline JSValueRef
CYJavaCastJSValue(JSContextRef context
, Type_ value
) {
477 return CYCastJSValue(context
, value
);
480 static _finline JSValueRef
CYJavaCastJSValue(JSContextRef context
, jboolean value
) {
481 return CYCastJSValue(context
, static_cast<bool>(value
));
484 JSValueRef
CYJavaError::CastJSValue(JSContextRef context
, const char *name
) const {
485 return CYCastJSValue(context
, value_
);
488 static std::map
<std::string
, CYJavaPrimitive
> Primitives_
;
490 static CYJavaPrimitive
CYJavaGetPrimitive(JSContextRef context
, const CYJavaRef
<jclass
> &type
, jmethodID Class$get$$Name
) {
492 auto string(jni
.CallObjectMethod
<jstring
>(type
, Class$get$$Name
));
495 CYJavaUTF8String
name(string
);
496 auto primitive(Primitives_
.find(name
));
497 return primitive
!= Primitives_
.end() ? primitive
->second
: CYJavaPrimitiveObject
;
500 typedef std::vector
<CYJavaPrimitive
> CYJavaShorty
;
502 static CYJavaShorty
CYJavaGetShorty(JSContextRef context
, const CYJavaRef
<jobjectArray
> &types
, jmethodID Class$get$$Name
) {
503 CYJavaEnv
jni(types
);
504 size_t count(jni
.GetArrayLength(types
));
505 CYJavaShorty
shorty(count
);
506 for (size_t index(0); index
!= count
; ++index
)
507 shorty
[index
] = CYJavaGetPrimitive(context
, jni
.GetObjectArrayElement
<jclass
>(types
, index
), Class$get$$Name
);
513 CYJavaPrimitive primitive_
;
516 typedef std::map
<std::string
, CYJavaField
> CYJavaFieldMap
;
518 struct CYJavaSignature
{
519 CYJavaGlobal
<jobject
> reflected_
;
521 CYJavaPrimitive primitive_
;
522 CYJavaShorty shorty_
;
524 CYJavaSignature(const CYJavaRef
<jobject
> &reflected
, jmethodID method
, CYJavaPrimitive primitive
, const CYJavaShorty
&shorty
) :
525 reflected_(reflected
),
527 primitive_(primitive
),
532 CYJavaSignature(unsigned count
) :
537 bool operator <(const CYJavaSignature
&rhs
) const {
538 return shorty_
.size() < rhs
.shorty_
.size();
542 typedef std::multiset
<CYJavaSignature
> CYJavaOverload
;
544 struct CYJavaMethod
:
545 CYPrivate
<CYJavaMethod
>
547 CYJavaOverload overload_
;
549 CYJavaMethod(const CYJavaOverload
&overload
) :
555 struct CYJavaStaticMethod
:
556 CYPrivate
<CYJavaStaticMethod
>
558 CYJavaOverload overload_
;
560 CYJavaStaticMethod(const CYJavaOverload
&overload
) :
567 CYJavaValue
<CYJavaClass
, jclass
>
571 CYJavaFieldMap static_
;
572 CYJavaFieldMap instance_
;
573 CYJavaOverload overload_
;
575 CYJavaClass(const CYJavaRef
<jclass
> &value
, bool interface
) :
577 interface_(interface
)
582 static JSObjectRef
CYGetJavaClass(JSContextRef context
, const CYJavaRef
<jclass
> &_class
);
584 struct CYJavaObject
:
585 CYJavaValue
<CYJavaObject
, jobject
>
589 CYJavaObject(const CYJavaRef
<jobject
> &value
, CYJavaClass
*table
) :
595 JSValueRef
GetPrototype(JSContextRef context
) const;
598 struct CYJavaInterior
:
599 CYJavaValue
<CYJavaInterior
, jobject
>
603 CYJavaInterior(const CYJavaRef
<jobject
> &value
, CYJavaClass
*table
) :
610 struct CYJavaStaticInterior
:
611 CYJavaValue
<CYJavaStaticInterior
, jclass
>
615 CYJavaStaticInterior(const CYJavaRef
<jclass
> &value
, CYJavaClass
*table
) :
623 CYJavaValue
<CYJavaArray
, jarray
>
625 CYJavaPrimitive primitive_
;
627 CYJavaArray(const CYJavaRef
<jarray
> &value
, CYJavaPrimitive primitive
) :
629 primitive_(primitive
)
633 JSValueRef
GetPrototype(JSContextRef context
) const;
636 struct CYJavaPackage
:
637 CYPrivate
<CYJavaPackage
>
639 typedef std::vector
<std::string
> Path
;
642 _finline
CYJavaPackage(const Path
&package
) :
648 JSValueRef
CYJavaObject::GetPrototype(JSContextRef context
) const {
649 CYJavaEnv
jni(value_
);
650 return CYGetProperty(context
, CYGetJavaClass(context
, jni
.GetObjectClass(value_
)), prototype_s
);
653 JSValueRef
CYJavaArray::GetPrototype(JSContextRef context
) const {
654 return CYGetCachedObject(context
, CYJSString("Array_prototype"));
657 static JSValueRef
CYCastJSValue(JSContextRef context
, const CYJavaRef
<jobject
> &value
) {
659 return CYJSNull(context
);
660 CYJavaEnv
jni(value
);
662 auto _class(jni
.GetObjectClass(value
));
663 if (jni
.IsSameObject(_class
, jni
.FindClass("java/lang/String")))
664 return CYCastJSValue(context
, CYJSString(value
.cast
<jstring
>()));
666 auto Class$
(jni
.FindClass("java/lang/Class"));
667 auto Class$
isArray(jni
.GetMethodID(Class$
, "isArray", "()Z"));
668 if (jni
.CallBooleanMethod(_class
, Class$isArray
)) {
669 auto Class$
getComponentType(jni
.GetMethodID(Class$
, "getComponentType", "()Ljava/lang/Class;"));
670 auto component(jni
.CallObjectMethod
<jclass
>(_class
, Class$getComponentType
));
671 auto Class$
getName(jni
.GetMethodID(Class$
, "getName", "()Ljava/lang/String;"));
672 return CYJavaArray::Make(context
, value
.cast
<jarray
>(), CYJavaGetPrimitive(context
, component
, Class$getName
));
675 auto Wrapper$
(jni
.FindClass("Cycript$Wrapper"));
676 if (jni
.IsSameObject(_class
, Wrapper$
)) {
677 auto Wrapper$
getProtect(jni
.GetMethodID(Wrapper$
, "getProtect", "()J"));
678 auto &protect(*reinterpret_cast<CYProtect
*>(jni
.CallLongMethod(value
, Wrapper$getProtect
)));
682 CYJavaClass
*table(reinterpret_cast<CYJavaClass
*>(JSObjectGetPrivate(CYGetJavaClass(context
, _class
))));
683 return CYJavaObject::Make(context
, value
, table
);
686 static _finline JSObjectRef
CYCastJSObject(JSContextRef context
, const CYJavaRef
<jobject
> &value
) {
687 return CYCastJSObject(context
, CYCastJSValue(context
, value
));
690 static CYJavaLocal
<jstring
> CYCastJavaString(const CYJavaEnv
&jni
, JSContextRef context
, CYUTF16String value
) {
691 return jni
.NewString(value
.data
, value
.size
);
694 static CYJavaLocal
<jstring
> CYCastJavaString(const CYJavaEnv
&jni
, JSContextRef context
, JSStringRef value
) {
695 return CYCastJavaString(jni
, context
, CYCastUTF16String(value
));
698 #define CYCastJava$(T, Type, jtype, Cast) \
699 _disused static CYJavaLocal<jobject> CYCastJava ## Type(const CYJavaEnv &jni, JSContextRef context, JSValueRef value) { \
700 auto Type$(jni.FindClass("java/lang/" #Type)); \
701 auto Type$init$(jni.GetMethodID(Type$, "<init>", "(" #T ")V")); \
702 return jni.NewObject(Type$, Type$init$, static_cast<jtype>(Cast(context, value))); \
705 CYCastJava$
(Z
, Boolean
, jboolean
, CYCastBool
)
706 CYCastJava$
(B
, Byte
, jbyte
, CYCastDouble
)
707 CYCastJava$
(C
, Character
, jchar
, CYCastDouble
)
708 CYCastJava$
(S
, Short
, jshort
, CYCastDouble
)
709 CYCastJava$
(I
, Integer
, jint
, CYCastDouble
)
710 CYCastJava$
(J
, Long
, jlong
, CYCastDouble
)
711 CYCastJava$
(F
, Float
, jfloat
, CYCastDouble
)
712 CYCastJava$
(D
, Double
, jdouble
, CYCastDouble
)
714 static CYJavaClass
*CYGetJavaTable(JSContextRef context
, JSObjectRef object
) {
715 if (!JSValueIsObjectOfClass(context
, object
, CYJavaClass::Class_
))
717 return reinterpret_cast<CYJavaClass
*>(JSObjectGetPrivate(object
));
720 static CYJavaObject
*CYGetJavaObject(JSContextRef context
, JSObjectRef object
) {
721 if (!JSValueIsObjectOfClass(context
, object
, CYJavaObject::Class_
))
723 return reinterpret_cast<CYJavaObject
*>(JSObjectGetPrivate(object
));
726 static CYJavaLocal
<jobject
> CYCastJavaObject(const CYJavaEnv
&jni
, JSContextRef context
, JSObjectRef value
) {
727 if (CYJavaObject
*internal
= CYGetJavaObject(context
, value
))
728 return internal
->value_
;
730 auto Wrapper$
(jni
.FindClass("Cycript$Wrapper"));
731 auto Wrapper$$init$
(jni
.GetMethodID(Wrapper$
, "<init>", "(J)V"));
732 CYProtect
*protect(new CYProtect(context
, value
));
733 return jni
.NewObject(Wrapper$
, Wrapper$$init$
, reinterpret_cast<jlong
>(protect
));
736 static CYJavaLocal
<jobject
> CYCastJavaObject(const CYJavaEnv
&jni
, JSContextRef context
, JSValueRef value
) {
737 switch (JSValueGetType(context
, value
)) {
741 return CYCastJavaBoolean(jni
, context
, value
);
743 return CYCastJavaDouble(jni
, context
, value
);
745 return CYCastJavaString(jni
, context
, CYJSString(context
, value
));
747 return CYCastJavaObject(jni
, context
, CYCastJSObject(context
, value
));
749 case kJSTypeUndefined
:
750 // XXX: I am currently relying on this for dynamic proxy of void method
757 static JSObjectRef
CYGetJavaClass(JSContextRef context
, const CYJavaRef
<jclass
> &value
) {
758 CYJavaEnv
jni(value
);
759 CYJavaFrame
frame(jni
, 64);
761 JSObjectRef
global(CYGetGlobalObject(context
));
762 JSObjectRef
cy(CYCastJSObject(context
, CYGetProperty(context
, global
, cy_s
)));
764 auto Class$
(jni
.FindClass("java/lang/Class"));
765 auto Class$
getName(jni
.GetMethodID(Class$
, "getName", "()Ljava/lang/String;"));
767 CYJSString
name(jni
.CallObjectMethod
<jstring
>(value
, Class$getName
));
768 JSValueRef
cached(CYGetProperty(context
, cy
, name
));
769 if (!JSValueIsUndefined(context
, cached
))
770 return CYCastJSObject(context
, cached
);
772 JSObjectRef constructor
;
773 JSObjectRef prototype
;
777 auto Class$
isInterface(jni
.GetMethodID(Class$
, "isInterface", "()Z"));
779 auto Class$
getDeclaredConstructors(jni
.GetMethodID(Class$
, "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;"));
780 auto Class$
getDeclaredFields(jni
.GetMethodID(Class$
, "getDeclaredFields", "()[Ljava/lang/reflect/Field;"));
781 auto Class$
getDeclaredMethods(jni
.GetMethodID(Class$
, "getDeclaredMethods", "()[Ljava/lang/reflect/Method;"));
783 auto Constructor$
(jni
.FindClass("java/lang/reflect/Constructor"));
784 //auto Constructor$getModifiers(jni.GetMethodID(Constructor$, "getModifiers", "()I"));
785 auto Constructor$
getParameterTypes(jni
.GetMethodID(Constructor$
, "getParameterTypes", "()[Ljava/lang/Class;"));
787 auto Field$
(jni
.FindClass("java/lang/reflect/Field"));
788 auto Field$
getModifiers(jni
.GetMethodID(Field$
, "getModifiers", "()I"));
789 auto Field$
getName(jni
.GetMethodID(Field$
, "getName", "()Ljava/lang/String;"));
790 auto Field$
getType(jni
.GetMethodID(Field$
, "getType", "()Ljava/lang/Class;"));
792 auto Method$
(jni
.FindClass("java/lang/reflect/Method"));
793 auto Method$
getModifiers(jni
.GetMethodID(Method$
, "getModifiers", "()I"));
794 auto Method$
getName(jni
.GetMethodID(Method$
, "getName", "()Ljava/lang/String;"));
795 auto Method$
getParameterTypes(jni
.GetMethodID(Method$
, "getParameterTypes", "()[Ljava/lang/Class;"));
796 auto Method$
getReturnType(jni
.GetMethodID(Method$
, "getReturnType", "()Ljava/lang/Class;"));
798 auto Modifier$
(jni
.FindClass("java/lang/reflect/Modifier"));
799 auto Modifier$
isStatic(jni
.GetStaticMethodID(Modifier$
, "isStatic", "(I)Z"));
801 auto interface(jni
.CallBooleanMethod(value
, Class$isInterface
));
802 auto table(new CYJavaClass(value
, interface
));
804 for (CYJavaLocal
<jclass
> prototype(value
); prototype
; prototype
= jni
.GetSuperclass(prototype
)) {
805 auto fields(jni
.CallObjectMethod
<jobjectArray
>(prototype
, Class$getDeclaredFields
));
807 for (jsize
i(0), e(jni
.GetArrayLength(fields
)); i
!= e
; ++i
) {
808 auto field(jni
.GetObjectArrayElement
<jobject
>(fields
, e
- i
- 1));
809 auto modifiers(jni
.CallIntMethod(field
, Field$getModifiers
));
810 auto instance(!jni
.CallStaticBooleanMethod(Modifier$
, Modifier$isStatic
, modifiers
));
811 auto &map(instance
? table
->instance_
: table
->static_
);
812 CYJavaUTF8String
name(jni
.CallObjectMethod
<jstring
>(field
, Field$getName
));
813 auto id(jni
.FromReflectedField(field
));
814 auto type(jni
.CallObjectMethod
<jclass
>(field
, Field$getType
));
815 map
.insert(std::make_pair(std::string(name
), CYJavaField
{id
, CYJavaGetPrimitive(context
, type
, Class$getName
)}));
819 constructor
= JSObjectMake(context
, CYJavaClass::Class_
, table
);
821 prototype
= JSObjectMake(context
, NULL
, NULL
);
822 CYSetProperty(context
, constructor
, prototype_s
, prototype
, kJSPropertyAttributeDontEnum
);
824 auto constructors(jni
.CallObjectMethod
<jobjectArray
>(value
, Class$getDeclaredConstructors
));
826 for (jsize
i(0), e(jni
.GetArrayLength(constructors
)); i
!= e
; ++i
) {
827 auto constructor(jni
.GetObjectArrayElement
<jobject
>(constructors
, i
));
828 auto parameters(jni
.CallObjectMethod
<jobjectArray
>(constructor
, Constructor$getParameterTypes
));
829 CYJavaShorty
shorty(CYJavaGetShorty(context
, parameters
, Class$getName
));
830 auto id(jni
.FromReflectedMethod(constructor
));
831 table
->overload_
.insert(CYJavaSignature(constructor
, id
, CYJavaPrimitiveObject
, shorty
));
834 auto methods(jni
.CallObjectMethod
<jobjectArray
>(value
, Class$getDeclaredMethods
));
836 std::map
<std::pair
<bool, std::string
>, CYJavaOverload
> entries
;
838 for (jsize
i(0), e(jni
.GetArrayLength(methods
)); i
!= e
; ++i
) {
839 auto method(jni
.GetObjectArrayElement
<jobject
>(methods
, i
));
840 auto modifiers(jni
.CallIntMethod(method
, Method$getModifiers
));
841 auto instance(!jni
.CallStaticBooleanMethod(Modifier$
, Modifier$isStatic
, modifiers
));
842 CYJavaUTF8String
name(jni
.CallObjectMethod
<jstring
>(method
, Method$getName
));
843 auto parameters(jni
.CallObjectMethod
<jobjectArray
>(method
, Method$getParameterTypes
));
844 CYJavaShorty
shorty(CYJavaGetShorty(context
, parameters
, Class$getName
));
845 auto type(jni
.CallObjectMethod
<jclass
>(method
, Method$getReturnType
));
846 auto primitive(CYJavaGetPrimitive(context
, type
, Class$getName
));
847 auto id(jni
.FromReflectedMethod(method
));
848 entries
[std::make_pair(instance
, std::string(name
))].insert(CYJavaSignature(method
, id
, primitive
, shorty
));
851 for (const auto &entry
: entries
) {
852 bool instance(entry
.first
.first
);
853 CYJSString
name(entry
.first
.second
);
854 auto &overload(entry
.second
);
856 CYSetProperty(context
, prototype
, name
, CYJavaMethod::Make(context
, overload
), kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
);
858 CYSetProperty(context
, constructor
, name
, CYJavaStaticMethod::Make(context
, overload
), kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
);
863 // XXX: for some reason kJSPropertyAttributeDontEnum doesn't work if there's already a property with the same name
864 // by not linking the prototypes until after we set the properties, we hide the parent property from this issue :(
866 if (auto super
= jni
.GetSuperclass(value
)) {
867 JSObjectRef
parent(CYGetJavaClass(context
, super
));
868 CYSetPrototype(context
, constructor
, parent
);
869 CYSetPrototype(context
, prototype
, CYGetProperty(context
, parent
, prototype_s
));
872 CYSetProperty(context
, cy
, name
, constructor
);
876 static void CYCastJavaNumeric(jvalue
&value
, CYJavaPrimitive primitive
, JSContextRef context
, JSValueRef argument
) {
878 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
879 case CYJavaPrimitive ## Type: \
880 value.t = static_cast<j ## type>(CYCastDouble(context, argument)); \
882 CYJavaForEachPrimitive
883 #undef CYJavaForEachPrimitive_
889 static bool CYCastJavaArguments(const CYJavaFrame
&frame
, const CYJavaShorty
&shorty
, JSContextRef context
, const JSValueRef arguments
[], jvalue
*array
) {
890 CYJavaEnv
jni(frame
);
892 for (size_t index(0); index
!= shorty
.size(); ++index
) {
893 JSValueRef
argument(arguments
[index
]);
894 JSType
type(JSValueGetType(context
, argument
));
895 jvalue
&value(array
[index
]);
897 switch (CYJavaPrimitive primitive
= shorty
[index
]) {
898 case CYJavaPrimitiveObject
:
899 // XXX: figure out a way to tie this in to the CYJavaFrame
900 value
.l
= CYCastJavaObject(jni
, context
, argument
).leak();
903 case CYJavaPrimitiveBoolean
:
904 if (type
!= kJSTypeBoolean
)
906 value
.z
= CYCastBool(context
, argument
);
909 case CYJavaPrimitiveCharacter
:
910 if (type
== kJSTypeNumber
)
911 CYCastJavaNumeric(value
, primitive
, context
, argument
);
912 else if (type
!= kJSTypeString
)
915 CYJSString
string(context
, argument
);
916 if (JSStringGetLength(string
) != 1)
919 value
.c
= JSStringGetCharactersPtr(string
)[0];
923 case CYJavaPrimitiveByte
:
924 case CYJavaPrimitiveShort
:
925 case CYJavaPrimitiveInteger
:
926 case CYJavaPrimitiveLong
:
927 case CYJavaPrimitiveFloat
:
928 case CYJavaPrimitiveDouble
:
929 if (type
!= kJSTypeNumber
)
931 CYCastJavaNumeric(value
, primitive
, context
, argument
);
942 static JSValueRef
JavaMethod_callAsFunction(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
943 auto internal(CYJavaMethod::Get(context
, object
));
944 CYJavaObject
*self(CYGetJavaObject(context
, _this
));
945 _assert(self
!= NULL
);
946 CYJavaEnv
jni(self
->value_
);
948 CYJavaSignature
bound(count
);
949 for (auto overload(internal
->overload_
.lower_bound(bound
)), e(internal
->overload_
.upper_bound(bound
)); overload
!= e
; ++overload
) {
950 CYJavaFrame
frame(jni
, count
+ 16);
952 if (!CYCastJavaArguments(frame
, overload
->shorty_
, context
, arguments
, array
))
954 jvalue
*values(array
);
955 switch (overload
->primitive_
) {
956 case CYJavaPrimitiveObject
:
957 return CYCastJSValue(context
, jni
.CallObjectMethodA
<jobject
>(self
->value_
, overload
->method_
, values
));
958 case CYJavaPrimitiveVoid
:
959 jni
.CallVoidMethodA(self
->value_
, overload
->method_
, values
);
960 return CYJSUndefined(context
);
961 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
962 case CYJavaPrimitive ## Type: \
963 return CYJavaCastJSValue(context, jni.Call ## Typ ## MethodA(self->value_, overload->method_, values));
964 CYJavaForEachPrimitive
965 #undef CYJavaForEachPrimitive_
966 default: _assert(false);
970 CYThrow("invalid method call");
973 static JSValueRef
JavaStaticMethod_callAsFunction(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
974 auto internal(CYJavaStaticMethod::Get(context
, object
));
975 CYJavaClass
*table(CYGetJavaTable(context
, _this
));
976 CYJavaEnv
jni(table
->value_
);
978 CYJavaSignature
bound(count
);
979 for (auto overload(internal
->overload_
.lower_bound(bound
)), e(internal
->overload_
.upper_bound(bound
)); overload
!= e
; ++overload
) {
980 CYJavaFrame
frame(jni
, count
+ 16);
982 if (!CYCastJavaArguments(frame
, overload
->shorty_
, context
, arguments
, array
))
984 jvalue
*values(array
);
985 switch (overload
->primitive_
) {
986 case CYJavaPrimitiveObject
:
987 return CYCastJSValue(context
, jni
.CallStaticObjectMethodA
<jobject
>(table
->value_
, overload
->method_
, values
));
988 case CYJavaPrimitiveVoid
:
989 jni
.CallStaticVoidMethodA(table
->value_
, overload
->method_
, values
);
990 return CYJSUndefined(context
);
991 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
992 case CYJavaPrimitive ## Type: \
993 return CYJavaCastJSValue(context, jni.CallStatic ## Typ ## MethodA(table->value_, overload->method_, values));
994 CYJavaForEachPrimitive
995 #undef CYJavaForEachPrimitive_
996 default: _assert(false);
1000 CYThrow("invalid method call");
1003 static JSObjectRef
JavaClass_callAsConstructor(JSContextRef context
, JSObjectRef object
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
1004 auto table(CYJavaClass::Get(context
, object
));
1005 CYJavaEnv
jni(table
->value_
);
1006 jclass
_class(table
->value_
);
1008 if (table
->interface_
&& count
== 1) {
1009 auto Cycript$
(jni
.FindClass("Cycript"));
1010 auto Cycript$
Make(jni
.GetStaticMethodID(Cycript$
, "proxy", "(Ljava/lang/Class;LCycript$Wrapper;)Ljava/lang/Object;"));
1011 return CYCastJSObject(context
, jni
.CallObjectMethod
<jobject
>(Cycript$
, Cycript$Make
, _class
, CYCastJavaObject(jni
, context
, CYCastJSObject(context
, arguments
[0])).get()));
1014 CYJavaSignature
bound(count
);
1015 for (auto overload(table
->overload_
.lower_bound(bound
)), e(table
->overload_
.upper_bound(bound
)); overload
!= e
; ++overload
) {
1016 CYJavaFrame
frame(jni
, count
+ 16);
1017 jvalue array
[count
];
1018 if (!CYCastJavaArguments(frame
, overload
->shorty_
, context
, arguments
, array
))
1020 jvalue
*values(array
);
1021 auto object(jni
.NewObjectA(_class
, overload
->method_
, values
));
1022 return CYCastJSObject(context
, object
);
1025 CYThrow("invalid constructor call");
1028 static bool JavaStaticInterior_hasProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
) {
1029 auto internal(CYJavaStaticInterior::Get(context
, object
));
1030 CYJavaClass
*table(internal
->table_
);
1032 auto name(CYPoolUTF8String(pool
, context
, property
));
1033 auto field(table
->static_
.find(name
));
1034 if (field
== table
->static_
.end())
1039 static JSValueRef
JavaStaticInterior_getProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1040 auto internal(CYJavaStaticInterior::Get(context
, object
));
1041 CYJavaClass
*table(internal
->table_
);
1042 CYJavaEnv
jni(table
->value_
);
1044 auto name(CYPoolUTF8String(pool
, context
, property
));
1045 auto field(table
->static_
.find(name
));
1046 if (field
== table
->static_
.end())
1049 switch (field
->second
.primitive_
) {
1050 case CYJavaPrimitiveObject
:
1051 return CYCastJSValue(context
, jni
.GetStaticObjectField
<jobject
>(table
->value_
, field
->second
.field_
));
1052 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1053 case CYJavaPrimitive ## Type: \
1054 return CYJavaCastJSValue(context, jni.GetStatic ## Typ ## Field(table->value_, field->second.field_));
1055 CYJavaForEachPrimitive
1056 #undef CYJavaForEachPrimitive_
1057 default: _assert(false);
1061 static bool JavaStaticInterior_setProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef value
, JSValueRef
*exception
) { CYTry
{
1062 auto internal(CYJavaStaticInterior::Get(context
, object
));
1063 CYJavaClass
*table(internal
->table_
);
1064 CYJavaEnv
jni(table
->value_
);
1066 auto name(CYPoolUTF8String(pool
, context
, property
));
1067 auto field(table
->static_
.find(name
));
1068 if (field
== table
->static_
.end())
1071 switch (field
->second
.primitive_
) {
1072 case CYJavaPrimitiveObject
:
1073 jni
.SetStaticObjectField(table
->value_
, field
->second
.field_
, CYCastJavaObject(jni
, context
, value
));
1074 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1075 case CYJavaPrimitive ## Type: \
1076 jni.SetStatic ## Typ ## Field(table->value_, field->second.field_, CYCastDouble(context, value)); \
1078 CYJavaForEachPrimitive
1079 #undef CYJavaForEachPrimitive_
1080 default: _assert(false);
1086 static void JavaStaticInterior_getPropertyNames(JSContextRef context
, JSObjectRef object
, JSPropertyNameAccumulatorRef names
) {
1087 auto internal(CYJavaStaticInterior::Get(context
, object
));
1088 CYJavaClass
*table(internal
->table_
);
1089 for (const auto &field
: table
->static_
)
1090 JSPropertyNameAccumulatorAddName(names
, CYJSString(field
.first
));
1093 static JSValueRef
JavaClass_getProperty_class(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1094 auto table(CYJavaClass::Get(context
, object
));
1095 return CYCastJSValue(context
, table
->value_
);
1098 static bool JavaInterior_hasProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
) {
1099 auto internal(CYJavaInterior::Get(context
, object
));
1100 CYJavaClass
*table(internal
->table_
);
1102 auto name(CYPoolUTF8String(pool
, context
, property
));
1103 auto field(table
->instance_
.find(name
));
1104 if (field
== table
->instance_
.end())
1109 static JSValueRef
JavaInterior_getProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1110 auto internal(CYJavaInterior::Get(context
, object
));
1111 CYJavaEnv
jni(internal
->value_
);
1112 CYJavaClass
*table(internal
->table_
);
1114 auto name(CYPoolUTF8String(pool
, context
, property
));
1115 auto field(table
->instance_
.find(name
));
1116 if (field
== table
->instance_
.end())
1119 switch (field
->second
.primitive_
) {
1120 case CYJavaPrimitiveObject
:
1121 return CYCastJSValue(context
, jni
.GetObjectField
<jobject
>(internal
->value_
, field
->second
.field_
));
1122 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1123 case CYJavaPrimitive ## Type: \
1124 return CYJavaCastJSValue(context, jni.Get ## Typ ## Field(internal->value_, field->second.field_));
1125 CYJavaForEachPrimitive
1126 #undef CYJavaForEachPrimitive_
1127 default: _assert(false);
1131 static bool JavaInterior_setProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef value
, JSValueRef
*exception
) { CYTry
{
1132 auto internal(CYJavaInterior::Get(context
, object
));
1133 CYJavaEnv
jni(internal
->value_
);
1134 CYJavaClass
*table(internal
->table_
);
1136 auto name(CYPoolUTF8String(pool
, context
, property
));
1137 auto field(table
->instance_
.find(name
));
1138 if (field
== table
->instance_
.end())
1141 switch (field
->second
.primitive_
) {
1142 case CYJavaPrimitiveObject
:
1143 jni
.SetObjectField(table
->value_
, field
->second
.field_
, CYCastJavaObject(jni
, context
, value
));
1144 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1145 case CYJavaPrimitive ## Type: \
1146 jni.Set ## Typ ## Field(table->value_, field->second.field_, CYCastDouble(context, value)); \
1148 CYJavaForEachPrimitive
1149 #undef CYJavaForEachPrimitive_
1150 default: _assert(false);
1156 static void JavaInterior_getPropertyNames(JSContextRef context
, JSObjectRef object
, JSPropertyNameAccumulatorRef names
) {
1157 auto internal(CYJavaInterior::Get(context
, object
));
1158 CYJavaClass
*table(internal
->table_
);
1159 for (const auto &field
: table
->instance_
)
1160 JSPropertyNameAccumulatorAddName(names
, CYJSString(field
.first
));
1163 static JSValueRef
JavaObject_getProperty_constructor(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1164 auto internal(CYJavaObject::Get(context
, object
));
1165 CYJavaEnv
jni(internal
->value_
);
1166 return CYGetJavaClass(context
, jni
.GetObjectClass(internal
->value_
));
1169 static JSValueRef JavaClass_getProperty_$
cyi(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1170 auto internal(CYJavaClass::Get(context
, object
));
1171 return CYJavaStaticInterior::Make(context
, internal
->value_
, internal
);
1174 static JSValueRef JavaObject_getProperty_$
cyi(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1175 auto internal(CYJavaObject::Get(context
, object
));
1176 return CYJavaInterior::Make(context
, internal
->value_
, internal
->table_
);
1179 static JSValueRef
JavaClass_callAsFunction_toCYON(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
1180 auto internal(CYJavaClass::Get(context
, _this
));
1181 CYJavaEnv
jni(internal
->value_
);
1182 auto Class$
(jni
.FindClass("java/lang/Class"));
1183 auto Class$
getCanonicalName(jni
.GetMethodID(Class$
, "getCanonicalName", "()Ljava/lang/String;"));
1184 return CYCastJSValue(context
, CYJSString(jni
.CallObjectMethod
<jstring
>(internal
->value_
, Class$getCanonicalName
)));
1187 static JSValueRef
JavaMethod_callAsFunction_toCYON(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
1188 std::ostringstream cyon
;
1189 return CYCastJSValue(context
, CYJSString(cyon
.str()));
1192 static JSValueRef
JavaStaticMethod_callAsFunction_toCYON(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
1193 std::ostringstream cyon
;
1194 return CYCastJSValue(context
, CYJSString(cyon
.str()));
1197 static JSValueRef
JavaArray_getProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1198 auto internal(CYJavaArray::Get(context
, object
));
1199 CYJavaEnv
jni(internal
->value_
);
1200 if (JSStringIsEqual(property
, length_s
))
1201 return CYCastJSValue(context
, jni
.GetArrayLength(internal
->value_
));
1205 if (!CYGetOffset(pool
, context
, property
, offset
))
1208 if (internal
->primitive_
== CYJavaPrimitiveObject
)
1209 return CYCastJSValue(context
, jni
.GetObjectArrayElement
<jobject
>(static_cast<jobjectArray
>(internal
->value_
.value_
), offset
));
1210 else switch (internal
->primitive_
) {
1211 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1212 case CYJavaPrimitive ## Type: { \
1213 j ## type element; \
1214 jni.Get ## Typ ## ArrayRegion(static_cast<j ## type ## Array>(internal->value_.value_), offset, 1, &element); \
1215 return CYJavaCastJSValue(context, element); \
1217 CYJavaForEachPrimitive
1218 #undef CYJavaForEachPrimitive_
1219 default: _assert(false);
1223 static bool JavaArray_setProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef value
, JSValueRef
*exception
) { CYTry
{
1224 auto internal(CYJavaArray::Get(context
, object
));
1225 CYJavaEnv
jni(internal
->value_
);
1229 if (!CYGetOffset(pool
, context
, property
, offset
))
1232 if (internal
->primitive_
== CYJavaPrimitiveObject
)
1233 jni
.SetObjectArrayElement(static_cast<jobjectArray
>(internal
->value_
.value_
), offset
, CYCastJavaObject(jni
, context
, value
));
1234 else switch (internal
->primitive_
) {
1235 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1236 case CYJavaPrimitive ## Type: { \
1237 j ## type element; \
1238 jni.Get ## Typ ## ArrayRegion(static_cast<j ## type ## Array>(internal->value_.value_), offset, 1, &element); \
1239 return CYJavaCastJSValue(context, element); \
1241 CYJavaForEachPrimitive
1242 #undef CYJavaForEachPrimitive_
1243 default: _assert(false);
1249 static JSValueRef
JavaPackage_callAsFunction_toCYON(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
1250 auto internal(CYJavaPackage::Get(context
, _this
));
1251 std::ostringstream name
;
1252 for (auto &package
: internal
->package_
)
1253 name
<< package
<< '.';
1255 return CYCastJSValue(context
, CYJSString(name
.str()));
1258 static bool CYJavaPackage_hasProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
) {
1262 static JSValueRef
CYJavaPackage_getProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1263 auto internal(CYJavaPackage::Get(context
, object
));
1264 CYJavaPackage::Path
package(internal
->package_
);
1267 const char *next(CYPoolCString(pool
, context
, property
));
1269 std::ostringstream name
;
1270 for (auto &package
: internal
->package_
)
1271 name
<< package
<< '/';
1274 JNIEnv
*jni(GetJNI(context
));
1275 if (auto _class
= jni
->FindClass(name
.str().c_str()))
1276 return CYGetJavaClass(context
, CYJavaLocal
<jclass
>(jni
, _class
));
1277 jni
->ExceptionClear();
1279 package
.push_back(next
);
1280 return CYJavaPackage::Make(context
, package
);
1283 static void Cycript_delete(JNIEnv
*env
, jclass api
, jlong jprotect
) { CYJavaTry
{
1287 static jobject
Cycript_handle(JNIEnv
*env
, jclass api
, jlong jprotect
, jstring property
, jobjectArray jarguments
) { CYJavaTry
{
1288 JSValueRef
function(CYGetProperty(context
, object
, CYJSString(CYJavaRef
<jstring
>(jni
, property
))));
1289 if (JSValueIsUndefined(context
, function
))
1292 size_t count(jarguments
== NULL
? 0 : jni
.GetArrayLength(jarguments
));
1293 JSValueRef arguments
[count
];
1294 for (size_t index(0); index
!= count
; ++index
)
1295 arguments
[index
] = CYCastJSValue(context
, jni
.GetObjectArrayElement
<jobject
>(jarguments
, index
));
1297 return CYCastJavaObject(jni
, context
, CYCallAsFunction(context
, CYCastJSObject(context
, function
), object
, count
, arguments
)).leak();
1298 } CYJavaCatch(NULL
) }
1300 static JNINativeMethod Cycript_
[] = {
1301 {(char *) "delete", (char *) "(J)V", (void *) &Cycript_delete
},
1302 {(char *) "handle", (char *) "(JLjava/lang/String;[Ljava/lang/Object;)Ljava/lang/Object;", (void *) &Cycript_handle
},
1305 template <typename Type_
>
1306 static _finline
void dlset(Type_
&function
, const char *name
, void *handle
) {
1307 function
= reinterpret_cast<Type_
>(dlsym(handle
, name
));
1310 jint
CYJavaVersion(JNI_VERSION_1_4
);
1312 static JNIEnv
*CYGetCreatedJava(jint (*$JNI_GetCreatedJavaVMs
)(JavaVM
**, jsize
, jsize
*)) {
1314 JavaVM
*jvms
[capacity
];
1316 _jnicall($
JNI_GetCreatedJavaVMs(jvms
, capacity
, &size
));
1319 JavaVM
*jvm(jvms
[0]);
1321 _jnicall(jvm
->GetEnv(reinterpret_cast<void **>(&jni
), CYJavaVersion
));
1325 static JNIEnv
*GetJNI_(JSContextRef context
) {
1326 static JavaVM
*jvm(NULL
);
1327 static JNIEnv
*jni(NULL
);
1333 void *handle(RTLD_DEFAULT
);
1334 std::string library
;
1336 jint (*$JNI_GetCreatedJavaVMs
)(JavaVM
**jvms
, jsize capacity
, jsize
*size
);
1337 dlset($JNI_GetCreatedJavaVMs
, "JNI_GetCreatedJavaVMs", handle
);
1339 if ($JNI_GetCreatedJavaVMs
!= NULL
) {
1340 if (JNIEnv
*jni
= CYGetCreatedJava($JNI_GetCreatedJavaVMs
))
1343 std::vector
<const char *> guesses
;
1346 char android
[PROP_VALUE_MAX
];
1347 if (__system_property_get("persist.sys.dalvik.vm.lib", android
) != 0)
1348 guesses
.push_back(android
);
1351 guesses
.push_back("libart.so");
1352 guesses
.push_back("libdvm.so");
1353 guesses
.push_back("libjvm.so");
1355 for (const char *guess
: guesses
) {
1356 handle
= dlopen(guess
, RTLD_LAZY
| RTLD_GLOBAL
);
1357 if (handle
!= NULL
) {
1363 _assert(library
.size() != 0);
1365 dlset($JNI_GetCreatedJavaVMs
, "JNI_GetCreatedJavaVMs", handle
);
1366 if (JNIEnv
*jni
= CYGetCreatedJava($JNI_GetCreatedJavaVMs
))
1370 std::vector
<JavaVMOption
> options
;
1373 std::ostringstream option
;
1374 option
<< "-Djava.class.path=";
1375 option
<< CYPoolLibraryPath(pool
) << "/libcycript.jar";
1376 if (const char *classpath
= getenv("CLASSPATH"))
1377 option
<< ':' << classpath
;
1378 options
.push_back(JavaVMOption
{pool
.strdup(option
.str().c_str()), NULL
});
1381 // To use libnativehelper to access JNI_GetCreatedJavaVMs, you need JniInvocation.
1382 // ...but there can only be one JniInvocation, and assuradely the other VM has it.
1383 // Essentially, this API makes no sense. We need it for AndroidRuntime, though :/.
1385 if (void *libnativehelper
= dlopen("libnativehelper.so", RTLD_LAZY
| RTLD_GLOBAL
)) {
1386 class JniInvocation$
;
1387 JniInvocation$
*(*JniInvocation$$init$
)(JniInvocation$
*self
)(NULL
);
1388 bool (*JniInvocation$Init
)(JniInvocation$
*self
, const char *library
)(NULL
);
1389 JniInvocation$
*(*JniInvocation$finalize
)(JniInvocation$
*self
)(NULL
);
1391 dlset(JniInvocation$$init$
, "_ZN13JniInvocationC1Ev", libnativehelper
);
1392 dlset(JniInvocation$Init
, "_ZN13JniInvocation4InitEPKc", libnativehelper
);
1393 dlset(JniInvocation$finalize
, "_ZN13JniInvocationD1Ev", libnativehelper
);
1395 if (JniInvocation$$init$
== NULL
)
1396 dlclose(libnativehelper
);
1398 // XXX: we should attach a pool to the VM itself and deallocate this there
1399 //auto invocation(pool.calloc<JniInvocation$>(1, 1024));
1400 //_assert(JniInvocation$finalize != NULL);
1401 //pool.atexit(reinterpret_cast<void (*)(void *)>(JniInvocation$finalize), invocation);
1403 auto invocation(static_cast<JniInvocation$
*>(calloc(1, 1024)));
1404 JniInvocation$$init$
(invocation
);
1406 _assert(JniInvocation$Init
!= NULL
);
1407 JniInvocation$
Init(invocation
, NULL
);
1409 dlset($JNI_GetCreatedJavaVMs
, "JNI_GetCreatedJavaVMs", libnativehelper
);
1410 if (JNIEnv
*jni
= CYGetCreatedJava($JNI_GetCreatedJavaVMs
))
1415 if (void *libandroid_runtime
= dlopen("libandroid_runtime.so", RTLD_LAZY
| RTLD_GLOBAL
)) {
1416 class AndroidRuntime$
;
1417 AndroidRuntime$
*(*AndroidRuntime$$init$
)(AndroidRuntime$
*self
, char *args
, unsigned int size
)(NULL
);
1418 int (*AndroidRuntime$startVm
)(AndroidRuntime$
*self
, JavaVM
**jvm
, JNIEnv
**jni
)(NULL
);
1419 int (*AndroidRuntime$startReg
)(JNIEnv
*jni
)(NULL
);
1420 int (*AndroidRuntime$addOption
)(AndroidRuntime$
*self
, const char *option
, void *extra
)(NULL
);
1421 int (*AndroidRuntime$addVmArguments
)(AndroidRuntime$
*self
, int, const char *const argv
[])(NULL
);
1422 AndroidRuntime$
*(*AndroidRuntime$finalize
)(AndroidRuntime$
*self
)(NULL
);
1424 dlset(AndroidRuntime$$init$
, "_ZN7android14AndroidRuntimeC1EPcj", libandroid_runtime
);
1425 dlset(AndroidRuntime$startVm
, "_ZN7android14AndroidRuntime7startVmEPP7_JavaVMPP7_JNIEnv", libandroid_runtime
);
1426 dlset(AndroidRuntime$startReg
, "_ZN7android14AndroidRuntime8startRegEP7_JNIEnv", libandroid_runtime
);
1427 dlset(AndroidRuntime$addOption
, "_ZN7android14AndroidRuntime9addOptionEPKcPv", libandroid_runtime
);
1428 dlset(AndroidRuntime$addVmArguments
, "_ZN7android14AndroidRuntime14addVmArgumentsEiPKPKc", libandroid_runtime
);
1429 dlset(AndroidRuntime$finalize
, "_ZN7android14AndroidRuntimeD1Ev", libandroid_runtime
);
1431 // XXX: it would also be interesting to attach this to a global pool
1432 AndroidRuntime$
*runtime(pool
.calloc
<AndroidRuntime$
>(1, 1024));
1434 _assert(AndroidRuntime$$init$
!= NULL
);
1435 AndroidRuntime$$init$
(runtime
, NULL
, 0);
1437 if (AndroidRuntime$addOption
== NULL
) {
1438 _assert(AndroidRuntime$addVmArguments
!= NULL
);
1439 std::vector
<const char *> arguments
;
1440 for (const auto &option
: options
)
1441 arguments
.push_back(option
.optionString
);
1442 AndroidRuntime$
addVmArguments(runtime
, arguments
.size(), arguments
.data());
1443 } else for (const auto &option
: options
)
1444 AndroidRuntime$
addOption(runtime
, option
.optionString
, option
.extraInfo
);
1448 _assert(AndroidRuntime$startVm
!= NULL
);
1449 failure
= AndroidRuntime$
startVm(runtime
, &jvm
, &jni
);
1450 _assert(failure
== 0);
1452 _assert(AndroidRuntime$startReg
!= NULL
);
1453 failure
= AndroidRuntime$
startReg(jni
);
1454 _assert(failure
== 0);
1459 jint (*$JNI_CreateJavaVM
)(JavaVM
**jvm
, void **, void *);
1460 dlset($JNI_CreateJavaVM
, "JNI_CreateJavaVM", handle
);
1462 JavaVMInitArgs args
;
1463 memset(&args
, 0, sizeof(args
));
1464 args
.version
= CYJavaVersion
;
1465 args
.nOptions
= options
.size();
1466 args
.options
= options
.data();
1467 _jnicall($
JNI_CreateJavaVM(&jvm
, reinterpret_cast<void **>(&jni
), &args
));
1471 static JNIEnv
*GetJNI(JSContextRef context
) {
1472 CYJavaEnv
jni(GetJNI_(context
));
1473 auto Cycript$
(jni
.FindClass("Cycript"));
1474 jni
.RegisterNatives(Cycript$
, Cycript_
, sizeof(Cycript_
) / sizeof(Cycript_
[0]));
1478 static JSStaticValue JavaClass_staticValues
[3] = {
1479 {"class", &JavaClass_getProperty_class
, NULL
, kJSPropertyAttributeReadOnly
| kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1480 {"$cyi", &JavaClass_getProperty_$cyi
, NULL
, kJSPropertyAttributeReadOnly
| kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1481 {NULL
, NULL
, NULL
, 0}
1484 static JSStaticFunction JavaClass_staticFunctions
[2] = {
1485 {"toCYON", &JavaClass_callAsFunction_toCYON
, kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1489 static JSStaticValue JavaObject_staticValues
[3] = {
1490 {"constructor", &JavaObject_getProperty_constructor
, NULL
, kJSPropertyAttributeReadOnly
| kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1491 {"$cyi", &JavaObject_getProperty_$cyi
, NULL
, kJSPropertyAttributeReadOnly
| kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1492 {NULL
, NULL
, NULL
, 0}
1495 static JSStaticFunction JavaMethod_staticFunctions
[2] = {
1496 {"toCYON", &JavaMethod_callAsFunction_toCYON
, kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1500 static JSStaticFunction JavaStaticMethod_staticFunctions
[2] = {
1501 {"toCYON", &JavaStaticMethod_callAsFunction_toCYON
, kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1505 static JSStaticFunction JavaPackage_staticFunctions
[2] = {
1506 {"toCYON", &JavaPackage_callAsFunction_toCYON
, kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1510 void CYJava_Initialize() {
1511 Primitives_
.insert(std::make_pair("void", CYJavaPrimitiveVoid
));
1512 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1513 Primitives_.insert(std::make_pair(#type, CYJavaPrimitive ## Type));
1514 CYJavaForEachPrimitive
1515 #undef CYJavaForEachPrimitive_
1517 JSClassDefinition definition
;
1519 definition
= kJSClassDefinitionEmpty
;
1520 definition
.className
= "JavaClass";
1521 definition
.staticValues
= JavaClass_staticValues
;
1522 definition
.staticFunctions
= JavaClass_staticFunctions
;
1523 definition
.callAsConstructor
= &JavaClass_callAsConstructor
;
1524 definition
.finalize
= &CYFinalize
;
1525 CYJavaClass::Class_
= JSClassCreate(&definition
);
1527 definition
= kJSClassDefinitionEmpty
;
1528 definition
.attributes
= kJSClassAttributeNoAutomaticPrototype
;
1529 definition
.className
= "JavaInterior";
1530 definition
.hasProperty
= &JavaInterior_hasProperty
;
1531 definition
.getProperty
= &JavaInterior_getProperty
;
1532 definition
.setProperty
= &JavaInterior_setProperty
;
1533 definition
.getPropertyNames
= &JavaInterior_getPropertyNames
;
1534 definition
.finalize
= &CYFinalize
;
1535 CYJavaInterior::Class_
= JSClassCreate(&definition
);
1537 definition
= kJSClassDefinitionEmpty
;
1538 definition
.className
= "JavaMethod";
1539 definition
.staticFunctions
= JavaMethod_staticFunctions
;
1540 definition
.callAsFunction
= &JavaMethod_callAsFunction
;
1541 definition
.finalize
= &CYFinalize
;
1542 CYJavaMethod::Class_
= JSClassCreate(&definition
);
1544 definition
= kJSClassDefinitionEmpty
;
1545 definition
.className
= "JavaStaticMethod";
1546 definition
.staticFunctions
= JavaStaticMethod_staticFunctions
;
1547 definition
.callAsFunction
= &JavaStaticMethod_callAsFunction
;
1548 definition
.finalize
= &CYFinalize
;
1549 CYJavaStaticMethod::Class_
= JSClassCreate(&definition
);
1551 definition
= kJSClassDefinitionEmpty
;
1552 definition
.attributes
= kJSClassAttributeNoAutomaticPrototype
;
1553 definition
.className
= "JavaObject";
1554 definition
.staticValues
= JavaObject_staticValues
;
1555 definition
.finalize
= &CYFinalize
;
1556 CYJavaObject::Class_
= JSClassCreate(&definition
);
1558 definition
= kJSClassDefinitionEmpty
;
1559 definition
.className
= "JavaArray";
1560 definition
.getProperty
= &JavaArray_getProperty
;
1561 definition
.setProperty
= &JavaArray_setProperty
;
1562 definition
.finalize
= &CYFinalize
;
1563 CYJavaArray::Class_
= JSClassCreate(&definition
);
1565 definition
= kJSClassDefinitionEmpty
;
1566 definition
.className
= "JavaPackage";
1567 definition
.staticFunctions
= JavaPackage_staticFunctions
;
1568 definition
.hasProperty
= &CYJavaPackage_hasProperty
;
1569 definition
.getProperty
= &CYJavaPackage_getProperty
;
1570 definition
.finalize
= &CYFinalize
;
1571 CYJavaPackage::Class_
= JSClassCreate(&definition
);
1573 definition
= kJSClassDefinitionEmpty
;
1574 definition
.attributes
= kJSClassAttributeNoAutomaticPrototype
;
1575 definition
.className
= "JavaStaticInterior";
1576 definition
.hasProperty
= &JavaStaticInterior_hasProperty
;
1577 definition
.getProperty
= &JavaStaticInterior_getProperty
;
1578 definition
.setProperty
= &JavaStaticInterior_setProperty
;
1579 definition
.getPropertyNames
= &JavaStaticInterior_getPropertyNames
;
1580 definition
.finalize
= &CYFinalize
;
1581 CYJavaStaticInterior::Class_
= JSClassCreate(&definition
);
1584 void CYJava_SetupContext(JSContextRef context
) {
1585 JSObjectRef
global(CYGetGlobalObject(context
));
1586 //JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
1587 JSObjectRef
cycript(CYCastJSObject(context
, CYGetProperty(context
, global
, CYJSString("Cycript"))));
1588 JSObjectRef
all(CYCastJSObject(context
, CYGetProperty(context
, cycript
, CYJSString("all"))));
1589 //JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
1591 JSObjectRef
Java(JSObjectMake(context
, NULL
, NULL
));
1592 CYSetProperty(context
, cycript
, CYJSString("Java"), Java
);
1594 JSObjectRef
Packages(CYJavaPackage::Make(context
, CYJavaPackage::Path()));
1595 CYSetProperty(context
, all
, CYJSString("Packages"), Packages
);
1597 for (auto name
: (const char *[]) {"java", "javax", "android", "com", "net", "org"}) {
1598 CYJSString
js(name
);
1599 CYSetProperty(context
, all
, js
, CYGetProperty(context
, Packages
, js
));
1603 static CYHook CYJavaHook
= {
1608 &CYJava_SetupContext
,
1612 CYRegisterHook
CYJava(&CYJavaHook
);