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/>.
28 #if defined(__APPLE__) && !defined(__arm__)
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 #define CYJavaForEachPrimitive \
81 CYJavaForEachPrimitive_(Z, z, Boolean, Boolean, boolean) \
82 CYJavaForEachPrimitive_(B, b, Byte, Byte, byte) \
83 CYJavaForEachPrimitive_(C, c, Char, Character, char) \
84 CYJavaForEachPrimitive_(S, s, Short, Short, short) \
85 CYJavaForEachPrimitive_(I, i, Int, Integer, int) \
86 CYJavaForEachPrimitive_(J, j, Long, Long, long) \
87 CYJavaForEachPrimitive_(F, f, Float, Float, float) \
88 CYJavaForEachPrimitive_(D, d, Double, Double, double)
90 enum CYJavaPrimitive
: char {
91 CYJavaPrimitiveObject
,
93 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
94 CYJavaPrimitive ## Type,
95 CYJavaForEachPrimitive
96 #undef CYJavaForEachPrimitive_
99 template <typename Type_
>
100 struct IsJavaPrimitive
{ static const bool value
= false; };
102 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
104 struct IsJavaPrimitive<j ## type> { static const bool value = true; };
105 CYJavaForEachPrimitive
106 #undef CYJavaForEachPrimitive_
108 // Java References {{{
109 template <typename Value_
>
114 _finline
CYJavaRef(JNIEnv
*jni
, Value_ value
) :
120 _finline
operator Value_() const {
124 _finline JNIEnv
*jni() const {
128 // XXX: this is only needed to support CYJavaEnv relying on C variadics
129 _finline Value_
get() const {
133 template <typename Other_
>
134 _finline CYJavaRef
<Other_
> cast() const {
135 return {jni_
, static_cast<Other_
>(value_
)};
138 // XXX: this should be tied into CYJavaFrame
140 Value_
value(value_
);
146 template <typename Value_
, void (JNIEnv::*Delete_
)(jobject
)>
147 struct CYJavaDelete
:
150 _finline
CYJavaDelete(JNIEnv
*jni
, Value_ value
) :
151 CYJavaRef
<Value_
>(jni
, value
)
156 if (this->value_
!= NULL
)
157 (this->jni_
->*Delete_
)(this->value_
);
166 template <typename Value_
>
167 struct CYJavaGlobal
:
168 CYJavaDelete
<Value_
, &JNIEnv::DeleteGlobalRef
>
170 typedef CYJavaDelete
<Value_
, &JNIEnv::DeleteGlobalRef
> CYJavaBase
;
173 CYJavaBase(NULL
, NULL
)
177 template <typename Other_
>
178 CYJavaGlobal(const CYJavaRef
<Other_
> &other
) :
179 CYJavaBase(other
.jni_
, static_cast<Other_
>(other
.jni_
->NewGlobalRef(other
.value_
)))
183 CYJavaGlobal(const CYJavaGlobal
<Value_
> &other
) :
184 CYJavaGlobal(static_cast<const CYJavaRef
<Value_
> &>(other
))
188 CYJavaGlobal(CYJavaGlobal
&&value
) :
189 CYJavaBase(value
.jni_
, value
.value_
)
195 template <typename Value_
>
197 CYJavaDelete
<Value_
, &JNIEnv::DeleteLocalRef
>
199 typedef CYJavaDelete
<Value_
, &JNIEnv::DeleteLocalRef
> CYJavaBase
;
202 CYJavaBase(NULL
, NULL
)
206 CYJavaLocal(JNIEnv
*jni
, Value_ value
) :
207 CYJavaBase(jni
, value
)
211 template <typename Other_
>
212 CYJavaLocal(const CYJavaRef
<Other_
> &other
) :
213 CYJavaLocal(other
.jni_
, static_cast<Other_
>(other
.jni_
->NewLocalRef(other
.value_
)))
217 template <typename Other_
>
218 CYJavaLocal(CYJavaRef
<Other_
> &&other
) :
219 CYJavaLocal(other
.jni_
, other
.value_
)
224 CYJavaLocal(CYJavaLocal
&&other
) :
225 CYJavaLocal(static_cast<CYJavaRef
<Value_
> &&>(other
))
229 template <typename Other_
>
230 CYJavaLocal
&operator =(CYJavaLocal
<Other_
> &&other
) {
232 this->jni_
= other
.jni_
;
233 this->value_
= other
.value_
;
240 static CYJavaLocal
<jstring
> CYCastJavaString(const CYJavaRef
<jobject
> &value
);
242 class CYJavaUTF8String
:
246 const CYJavaRef
<jstring
> *value_
;
249 CYJavaUTF8String(const CYJavaRef
<jstring
> &value
) :
253 JNIEnv
*jni(value
.jni());
254 size
= jni
->GetStringUTFLength(value
);
255 data
= jni
->GetStringUTFChars(value
, NULL
);
258 CYJavaUTF8String(const CYJavaRef
<jobject
> &value
) :
259 CYJavaUTF8String(CYCastJavaString(value
))
263 ~CYJavaUTF8String() {
264 if (value_
!= NULL
) {
265 JNIEnv
*jni(value_
->jni());
266 jni
->ReleaseStringUTFChars(*value_
, data
);
270 CYJavaUTF8String(const CYJavaUTF8String
&) = delete;
272 CYJavaUTF8String(CYJavaUTF8String
&&rhs
) :
279 CYJavaUTF8String
CYCastUTF8String(const CYJavaRef
<jstring
> &value
) {
280 return CYJavaUTF8String(value
);
283 JSStringRef
CYCopyJSString(const CYJavaRef
<jstring
> &value
) {
284 return CYCopyJSString(CYCastUTF8String(value
));
291 CYJavaGlobal
<jthrowable
> value_
;
293 CYJavaError(const CYJavaRef
<jthrowable
> &value
) :
298 virtual const char *PoolCString(CYPool
&pool
) const {
299 return CYPoolCString(pool
, CYJavaUTF8String(value_
.cast
<jobject
>()));
302 virtual JSValueRef
CastJSValue(JSContextRef context
, const char *name
) const;
309 CYJavaFrame(JNIEnv
*jni
, jint capacity
) :
312 _assert(jni
->PushLocalFrame(capacity
) == 0);
319 operator JNIEnv
*() const {
323 jobject
operator ()(jobject object
) {
326 return jni
->PopLocalFrame(object
);
335 CYJavaEnv(JNIEnv
*jni
) :
340 template <typename Other_
>
341 CYJavaEnv(const CYJavaRef
<Other_
> &value
) :
346 operator JNIEnv
*() const {
350 JNIEnv
*operator ->() const {
354 CYJavaLocal
<jclass
> FindClass(const char *name
) const {
355 return {jni
, _envcall(jni
, FindClass(name
))};
358 CYJavaLocal
<jclass
> GetObjectClass(jobject object
) const {
359 return {jni
, _envcall(jni
, GetObjectClass(object
))};
362 CYJavaLocal
<jclass
> GetSuperclass(jclass _class
) const {
363 return {jni
, _envcall(jni
, GetSuperclass(_class
))};
366 CYJavaLocal
<jobject
> NewObject(jclass _class
, jmethodID method
, ...) const {
368 va_start(args
, method
);
369 jobject
object(_envcall(jni
, NewObjectV(_class
, method
, args
)));
371 return {jni
, object
};
374 CYJavaLocal
<jobject
> NewObjectA(jclass _class
, jmethodID method
, jvalue
*args
) const {
375 return {jni
, _envcall(jni
, NewObjectA(_class
, method
, args
))};
378 CYJavaLocal
<jstring
> NewString(const jchar
*data
, jsize size
) const {
379 return {jni
, _envcall(jni
, NewString(data
, size
))};
382 #define CYJavaEnv_(Code) \
383 template <typename... Args_> \
384 void Code(Args_ &&... args) const { \
385 _envcallv(jni, Code(cy::Forward<Args_>(args)...)); \
388 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
389 CYJavaEnv_(Get ## Typ ## ArrayRegion) \
390 CYJavaEnv_(Set ## Typ ## Field) \
391 CYJavaEnv_(SetStatic ## Typ ## Field)
392 CYJavaForEachPrimitive
393 #undef CYJavaForEachPrimitive_
395 CYJavaEnv_(CallVoidMethod
)
396 CYJavaEnv_(CallStaticVoidMethod
)
397 CYJavaEnv_(CallVoidMethodA
)
398 CYJavaEnv_(CallStaticVoidMethodA
)
399 CYJavaEnv_(SetObjectArrayElement
)
400 CYJavaEnv_(SetObjectField
)
401 CYJavaEnv_(SetStaticObjectField
)
404 #define CYJavaEnv_(Code) \
405 template <typename... Args_> \
406 auto Code(Args_ &&... args) const -> decltype(jni->Code(cy::Forward<Args_>(args)...)) { \
407 return _envcall(jni, Code(cy::Forward<Args_>(args)...)); \
410 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
411 CYJavaEnv_(Call ## Typ ## Method) \
412 CYJavaEnv_(CallStatic ## Typ ## Method) \
413 CYJavaEnv_(Call ## Typ ## MethodA) \
414 CYJavaEnv_(CallStatic ## Typ ## MethodA) \
415 CYJavaEnv_(Get ## Typ ## Field) \
416 CYJavaEnv_(GetStatic ## Typ ## Field)
417 CYJavaForEachPrimitive
418 #undef CYJavaForEachPrimitive_
420 CYJavaEnv_(FromReflectedField
)
421 CYJavaEnv_(FromReflectedMethod
)
422 CYJavaEnv_(GetArrayLength
)
423 CYJavaEnv_(GetMethodID
)
424 CYJavaEnv_(GetStaticMethodID
)
425 CYJavaEnv_(IsSameObject
)
426 CYJavaEnv_(RegisterNatives
)
429 #define CYJavaEnv_(Code) \
430 template <typename Other_, typename... Args_> \
431 auto Code(Args_ &&... args) const -> CYJavaLocal<Other_> { \
432 return {jni, static_cast<Other_>(_envcall(jni, Code(cy::Forward<Args_>(args)...)))}; \
435 CYJavaEnv_(CallObjectMethod
)
436 CYJavaEnv_(CallStaticObjectMethod
)
437 CYJavaEnv_(CallObjectMethodA
)
438 CYJavaEnv_(CallStaticObjectMethodA
)
439 CYJavaEnv_(GetObjectArrayElement
)
440 CYJavaEnv_(GetObjectField
)
441 CYJavaEnv_(GetStaticObjectField
)
445 static CYJavaLocal
<jstring
> CYCastJavaString(const CYJavaRef
<jobject
> &value
) {
446 CYJavaEnv
jni(value
);
447 auto Object$
(jni
.FindClass("java/lang/Object"));
448 auto Object$
toString(jni
.GetMethodID(Object$
, "toString", "()Ljava/lang/String;"));
449 return jni
.CallObjectMethod
<jstring
>(value
, Object$toString
);
452 template <typename Internal_
, typename Value_
>
456 CYJavaGlobal
<Value_
> value_
;
458 CYJavaValue(const CYJavaRef
<Value_
> &value
) :
463 CYJavaValue(const CYJavaValue
&) = delete;
466 static JSValueRef
CYCastJSValue(JSContextRef context
, const CYJavaRef
<jobject
> &value
);
468 template <typename Other_
>
469 static _finline JSValueRef
CYCastJSValue(JSContextRef context
, const CYJavaRef
<Other_
> &value
) {
470 return CYCastJSValue(context
, value
.template cast
<jobject
>());
473 template <typename Type_
>
474 static _finline JSValueRef
CYJavaCastJSValue(JSContextRef context
, Type_ value
) {
475 return CYCastJSValue(context
, value
);
478 static _finline JSValueRef
CYJavaCastJSValue(JSContextRef context
, jboolean value
) {
479 return CYCastJSValue(context
, static_cast<bool>(value
));
482 JSValueRef
CYJavaError::CastJSValue(JSContextRef context
, const char *name
) const {
483 return CYCastJSValue(context
, value_
);
486 static std::map
<std::string
, CYJavaPrimitive
> Primitives_
;
488 static CYJavaPrimitive
CYJavaGetPrimitive(JSContextRef context
, const CYJavaRef
<jclass
> &type
, jmethodID Class$get$$Name
) {
490 auto string(jni
.CallObjectMethod
<jstring
>(type
, Class$get$$Name
));
493 CYJavaUTF8String
name(string
);
494 auto primitive(Primitives_
.find(name
));
495 return primitive
!= Primitives_
.end() ? primitive
->second
: CYJavaPrimitiveObject
;
498 typedef std::vector
<CYJavaPrimitive
> CYJavaShorty
;
500 static CYJavaShorty
CYJavaGetShorty(JSContextRef context
, const CYJavaRef
<jobjectArray
> &types
, jmethodID Class$get$$Name
) {
501 CYJavaEnv
jni(types
);
502 size_t count(jni
.GetArrayLength(types
));
503 CYJavaShorty
shorty(count
);
504 for (size_t index(0); index
!= count
; ++index
)
505 shorty
[index
] = CYJavaGetPrimitive(context
, jni
.GetObjectArrayElement
<jclass
>(types
, index
), Class$get$$Name
);
511 CYJavaPrimitive primitive_
;
514 typedef std::map
<std::string
, CYJavaField
> CYJavaFieldMap
;
516 struct CYJavaSignature
{
517 CYJavaGlobal
<jobject
> reflected_
;
519 CYJavaPrimitive primitive_
;
520 CYJavaShorty shorty_
;
522 CYJavaSignature(const CYJavaRef
<jobject
> &reflected
, jmethodID method
, CYJavaPrimitive primitive
, const CYJavaShorty
&shorty
) :
523 reflected_(reflected
),
525 primitive_(primitive
),
530 CYJavaSignature(unsigned count
) :
535 bool operator <(const CYJavaSignature
&rhs
) const {
536 return shorty_
.size() < rhs
.shorty_
.size();
540 typedef std::multiset
<CYJavaSignature
> CYJavaOverload
;
542 struct CYJavaMethod
:
543 CYPrivate
<CYJavaMethod
>
545 CYJavaOverload overload_
;
547 CYJavaMethod(const CYJavaOverload
&overload
) :
553 struct CYJavaStaticMethod
:
554 CYPrivate
<CYJavaStaticMethod
>
556 CYJavaOverload overload_
;
558 CYJavaStaticMethod(const CYJavaOverload
&overload
) :
565 CYJavaValue
<CYJavaClass
, jclass
>
569 CYJavaFieldMap static_
;
570 CYJavaFieldMap instance_
;
571 CYJavaOverload overload_
;
573 CYJavaClass(const CYJavaRef
<jclass
> &value
, bool interface
) :
575 interface_(interface
)
580 static JSObjectRef
CYGetJavaClass(JSContextRef context
, const CYJavaRef
<jclass
> &_class
);
582 struct CYJavaObject
:
583 CYJavaValue
<CYJavaObject
, jobject
>
587 CYJavaObject(const CYJavaRef
<jobject
> &value
, CYJavaClass
*table
) :
593 JSValueRef
GetPrototype(JSContextRef context
) const;
596 struct CYJavaInterior
:
597 CYJavaValue
<CYJavaInterior
, jobject
>
601 CYJavaInterior(const CYJavaRef
<jobject
> &value
, CYJavaClass
*table
) :
608 struct CYJavaStaticInterior
:
609 CYJavaValue
<CYJavaStaticInterior
, jclass
>
613 CYJavaStaticInterior(const CYJavaRef
<jclass
> &value
, CYJavaClass
*table
) :
621 CYJavaValue
<CYJavaArray
, jarray
>
623 CYJavaPrimitive primitive_
;
625 CYJavaArray(const CYJavaRef
<jarray
> &value
, CYJavaPrimitive primitive
) :
627 primitive_(primitive
)
631 JSValueRef
GetPrototype(JSContextRef context
) const;
634 struct CYJavaPackage
:
635 CYPrivate
<CYJavaPackage
>
639 typedef std::vector
<std::string
> Path
;
642 _finline
CYJavaPackage(JNIEnv
*jni
, const Path
&package
) :
649 JSValueRef
CYJavaObject::GetPrototype(JSContextRef context
) const {
650 CYJavaEnv
jni(value_
);
651 return CYGetProperty(context
, CYGetJavaClass(context
, jni
.GetObjectClass(value_
)), prototype_s
);
654 JSValueRef
CYJavaArray::GetPrototype(JSContextRef context
) const {
655 return CYGetCachedObject(context
, CYJSString("Array_prototype"));
658 static JSValueRef
CYCastJSValue(JSContextRef context
, const CYJavaRef
<jobject
> &value
) {
660 return CYJSNull(context
);
661 CYJavaEnv
jni(value
);
663 auto _class(jni
.GetObjectClass(value
));
664 if (jni
.IsSameObject(_class
, jni
.FindClass("java/lang/String")))
665 return CYCastJSValue(context
, CYJSString(value
.cast
<jstring
>()));
667 auto Class$
(jni
.FindClass("java/lang/Class"));
668 auto Class$
isArray(jni
.GetMethodID(Class$
, "isArray", "()Z"));
669 if (jni
.CallBooleanMethod(_class
, Class$isArray
)) {
670 auto Class$
getComponentType(jni
.GetMethodID(Class$
, "getComponentType", "()Ljava/lang/Class;"));
671 auto component(jni
.CallObjectMethod
<jclass
>(_class
, Class$getComponentType
));
672 auto Class$
getName(jni
.GetMethodID(Class$
, "getName", "()Ljava/lang/String;"));
673 return CYJavaArray::Make(context
, value
.cast
<jarray
>(), CYJavaGetPrimitive(context
, component
, Class$getName
));
676 auto Wrapper$
(jni
.FindClass("Cycript$Wrapper"));
677 if (jni
.IsSameObject(_class
, Wrapper$
)) {
678 auto Wrapper$
getProtect(jni
.GetMethodID(Wrapper$
, "getProtect", "()J"));
679 auto &protect(*reinterpret_cast<CYProtect
*>(jni
.CallLongMethod(value
, Wrapper$getProtect
)));
683 CYJavaClass
*table(reinterpret_cast<CYJavaClass
*>(JSObjectGetPrivate(CYGetJavaClass(context
, _class
))));
684 return CYJavaObject::Make(context
, value
, table
);
687 static _finline JSObjectRef
CYCastJSObject(JSContextRef context
, const CYJavaRef
<jobject
> &value
) {
688 return CYCastJSObject(context
, CYCastJSValue(context
, value
));
691 static CYJavaLocal
<jstring
> CYCastJavaString(const CYJavaEnv
&jni
, JSContextRef context
, CYUTF16String value
) {
692 return jni
.NewString(value
.data
, value
.size
);
695 static CYJavaLocal
<jstring
> CYCastJavaString(const CYJavaEnv
&jni
, JSContextRef context
, JSStringRef value
) {
696 return CYCastJavaString(jni
, context
, CYCastUTF16String(value
));
699 #define CYCastJava$(T, Type, jtype, Cast) \
700 _disused static CYJavaLocal<jobject> CYCastJava ## Type(const CYJavaEnv &jni, JSContextRef context, JSValueRef value) { \
701 auto Type$(jni.FindClass("java/lang/" #Type)); \
702 auto Type$init$(jni.GetMethodID(Type$, "<init>", "(" #T ")V")); \
703 return jni.NewObject(Type$, Type$init$, static_cast<jtype>(Cast(context, value))); \
706 CYCastJava$
(Z
, Boolean
, jboolean
, CYCastBool
)
707 CYCastJava$
(B
, Byte
, jbyte
, CYCastDouble
)
708 CYCastJava$
(C
, Character
, jchar
, CYCastDouble
)
709 CYCastJava$
(S
, Short
, jshort
, CYCastDouble
)
710 CYCastJava$
(I
, Integer
, jint
, CYCastDouble
)
711 CYCastJava$
(J
, Long
, jlong
, CYCastDouble
)
712 CYCastJava$
(F
, Float
, jfloat
, CYCastDouble
)
713 CYCastJava$
(D
, Double
, jdouble
, CYCastDouble
)
715 static CYJavaClass
*CYGetJavaTable(JSContextRef context
, JSObjectRef object
) {
716 if (!JSValueIsObjectOfClass(context
, object
, CYJavaClass::Class_
))
718 return reinterpret_cast<CYJavaClass
*>(JSObjectGetPrivate(object
));
721 static CYJavaObject
*CYGetJavaObject(JSContextRef context
, JSObjectRef object
) {
722 if (!JSValueIsObjectOfClass(context
, object
, CYJavaObject::Class_
))
724 return reinterpret_cast<CYJavaObject
*>(JSObjectGetPrivate(object
));
727 static CYJavaLocal
<jobject
> CYCastJavaObject(const CYJavaEnv
&jni
, JSContextRef context
, JSObjectRef value
) {
728 if (CYJavaObject
*internal
= CYGetJavaObject(context
, value
))
729 return internal
->value_
;
731 auto Wrapper$
(jni
.FindClass("Cycript$Wrapper"));
732 auto Wrapper$$init$
(jni
.GetMethodID(Wrapper$
, "<init>", "(J)V"));
733 CYProtect
*protect(new CYProtect(context
, value
));
734 return jni
.NewObject(Wrapper$
, Wrapper$$init$
, reinterpret_cast<jlong
>(protect
));
737 static CYJavaLocal
<jobject
> CYCastJavaObject(const CYJavaEnv
&jni
, JSContextRef context
, JSValueRef value
) {
738 switch (JSValueGetType(context
, value
)) {
742 return CYCastJavaBoolean(jni
, context
, value
);
744 return CYCastJavaDouble(jni
, context
, value
);
746 return CYCastJavaString(jni
, context
, CYJSString(context
, value
));
748 return CYCastJavaObject(jni
, context
, CYCastJSObject(context
, value
));
750 case kJSTypeUndefined
:
751 // XXX: I am currently relying on this for dynamic proxy of void method
758 static JSObjectRef
CYGetJavaClass(JSContextRef context
, const CYJavaRef
<jclass
> &value
) {
759 CYJavaEnv
jni(value
);
760 CYJavaFrame
frame(jni
, 64);
762 JSObjectRef
global(CYGetGlobalObject(context
));
763 JSObjectRef
cy(CYCastJSObject(context
, CYGetProperty(context
, global
, cy_s
)));
765 auto Class$
(jni
.FindClass("java/lang/Class"));
766 auto Class$
getName(jni
.GetMethodID(Class$
, "getName", "()Ljava/lang/String;"));
768 CYJSString
name(jni
.CallObjectMethod
<jstring
>(value
, Class$getName
));
769 JSValueRef
cached(CYGetProperty(context
, cy
, name
));
770 if (!JSValueIsUndefined(context
, cached
))
771 return CYCastJSObject(context
, cached
);
773 JSObjectRef constructor
;
774 JSObjectRef prototype
;
778 auto Class$
isInterface(jni
.GetMethodID(Class$
, "isInterface", "()Z"));
780 auto Class$
getDeclaredConstructors(jni
.GetMethodID(Class$
, "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;"));
781 auto Class$
getDeclaredFields(jni
.GetMethodID(Class$
, "getDeclaredFields", "()[Ljava/lang/reflect/Field;"));
782 auto Class$
getDeclaredMethods(jni
.GetMethodID(Class$
, "getDeclaredMethods", "()[Ljava/lang/reflect/Method;"));
784 auto Constructor$
(jni
.FindClass("java/lang/reflect/Constructor"));
785 //auto Constructor$getModifiers(jni.GetMethodID(Constructor$, "getModifiers", "()I"));
786 auto Constructor$
getParameterTypes(jni
.GetMethodID(Constructor$
, "getParameterTypes", "()[Ljava/lang/Class;"));
788 auto Field$
(jni
.FindClass("java/lang/reflect/Field"));
789 auto Field$
getModifiers(jni
.GetMethodID(Field$
, "getModifiers", "()I"));
790 auto Field$
getName(jni
.GetMethodID(Field$
, "getName", "()Ljava/lang/String;"));
791 auto Field$
getType(jni
.GetMethodID(Field$
, "getType", "()Ljava/lang/Class;"));
793 auto Method$
(jni
.FindClass("java/lang/reflect/Method"));
794 auto Method$
getModifiers(jni
.GetMethodID(Method$
, "getModifiers", "()I"));
795 auto Method$
getName(jni
.GetMethodID(Method$
, "getName", "()Ljava/lang/String;"));
796 auto Method$
getParameterTypes(jni
.GetMethodID(Method$
, "getParameterTypes", "()[Ljava/lang/Class;"));
797 auto Method$
getReturnType(jni
.GetMethodID(Method$
, "getReturnType", "()Ljava/lang/Class;"));
799 auto Modifier$
(jni
.FindClass("java/lang/reflect/Modifier"));
800 auto Modifier$
isStatic(jni
.GetStaticMethodID(Modifier$
, "isStatic", "(I)Z"));
802 auto interface(jni
.CallBooleanMethod(value
, Class$isInterface
));
803 auto table(new CYJavaClass(value
, interface
));
805 for (CYJavaLocal
<jclass
> prototype(value
); prototype
; prototype
= jni
.GetSuperclass(prototype
)) {
806 auto fields(jni
.CallObjectMethod
<jobjectArray
>(prototype
, Class$getDeclaredFields
));
808 for (jsize
i(0), e(jni
.GetArrayLength(fields
)); i
!= e
; ++i
) {
809 auto field(jni
.GetObjectArrayElement
<jobject
>(fields
, e
- i
- 1));
810 auto modifiers(jni
.CallIntMethod(field
, Field$getModifiers
));
811 auto instance(!jni
.CallStaticBooleanMethod(Modifier$
, Modifier$isStatic
, modifiers
));
812 auto &map(instance
? table
->instance_
: table
->static_
);
813 CYJavaUTF8String
name(jni
.CallObjectMethod
<jstring
>(field
, Field$getName
));
814 auto id(jni
.FromReflectedField(field
));
815 auto type(jni
.CallObjectMethod
<jclass
>(field
, Field$getType
));
816 map
.insert(std::make_pair(std::string(name
), CYJavaField
{id
, CYJavaGetPrimitive(context
, type
, Class$getName
)}));
820 constructor
= JSObjectMake(context
, CYJavaClass::Class_
, table
);
822 prototype
= JSObjectMake(context
, NULL
, NULL
);
823 CYSetProperty(context
, constructor
, prototype_s
, prototype
, kJSPropertyAttributeDontEnum
);
825 auto constructors(jni
.CallObjectMethod
<jobjectArray
>(value
, Class$getDeclaredConstructors
));
827 for (jsize
i(0), e(jni
.GetArrayLength(constructors
)); i
!= e
; ++i
) {
828 auto constructor(jni
.GetObjectArrayElement
<jobject
>(constructors
, i
));
829 auto parameters(jni
.CallObjectMethod
<jobjectArray
>(constructor
, Constructor$getParameterTypes
));
830 CYJavaShorty
shorty(CYJavaGetShorty(context
, parameters
, Class$getName
));
831 auto id(jni
.FromReflectedMethod(constructor
));
832 table
->overload_
.insert(CYJavaSignature(constructor
, id
, CYJavaPrimitiveObject
, shorty
));
835 auto methods(jni
.CallObjectMethod
<jobjectArray
>(value
, Class$getDeclaredMethods
));
837 std::map
<std::pair
<bool, std::string
>, CYJavaOverload
> entries
;
839 for (jsize
i(0), e(jni
.GetArrayLength(methods
)); i
!= e
; ++i
) {
840 auto method(jni
.GetObjectArrayElement
<jobject
>(methods
, i
));
841 auto modifiers(jni
.CallIntMethod(method
, Method$getModifiers
));
842 auto instance(!jni
.CallStaticBooleanMethod(Modifier$
, Modifier$isStatic
, modifiers
));
843 CYJavaUTF8String
name(jni
.CallObjectMethod
<jstring
>(method
, Method$getName
));
844 auto parameters(jni
.CallObjectMethod
<jobjectArray
>(method
, Method$getParameterTypes
));
845 CYJavaShorty
shorty(CYJavaGetShorty(context
, parameters
, Class$getName
));
846 auto type(jni
.CallObjectMethod
<jclass
>(method
, Method$getReturnType
));
847 auto primitive(CYJavaGetPrimitive(context
, type
, Class$getName
));
848 auto id(jni
.FromReflectedMethod(method
));
849 entries
[std::make_pair(instance
, std::string(name
))].insert(CYJavaSignature(method
, id
, primitive
, shorty
));
852 for (const auto &entry
: entries
) {
853 bool instance(entry
.first
.first
);
854 CYJSString
name(entry
.first
.second
);
855 auto &overload(entry
.second
);
857 CYSetProperty(context
, prototype
, name
, CYJavaMethod::Make(context
, overload
), kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
);
859 CYSetProperty(context
, constructor
, name
, CYJavaStaticMethod::Make(context
, overload
), kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
);
864 // XXX: for some reason kJSPropertyAttributeDontEnum doesn't work if there's already a property with the same name
865 // by not linking the prototypes until after we set the properties, we hide the parent property from this issue :(
867 if (auto super
= jni
.GetSuperclass(value
)) {
868 JSObjectRef
parent(CYGetJavaClass(context
, super
));
869 CYSetPrototype(context
, constructor
, parent
);
870 CYSetPrototype(context
, prototype
, CYGetProperty(context
, parent
, prototype_s
));
873 CYSetProperty(context
, cy
, name
, constructor
);
877 static void CYCastJavaNumeric(jvalue
&value
, CYJavaPrimitive primitive
, JSContextRef context
, JSValueRef argument
) {
879 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
880 case CYJavaPrimitive ## Type: \
881 value.t = static_cast<j ## type>(CYCastDouble(context, argument)); \
883 CYJavaForEachPrimitive
884 #undef CYJavaForEachPrimitive_
890 static bool CYCastJavaArguments(const CYJavaFrame
&frame
, const CYJavaShorty
&shorty
, JSContextRef context
, const JSValueRef arguments
[], jvalue
*array
) {
891 CYJavaEnv
jni(frame
);
893 for (size_t index(0); index
!= shorty
.size(); ++index
) {
894 JSValueRef
argument(arguments
[index
]);
895 JSType
type(JSValueGetType(context
, argument
));
896 jvalue
&value(array
[index
]);
898 switch (CYJavaPrimitive primitive
= shorty
[index
]) {
899 case CYJavaPrimitiveObject
:
900 // XXX: figure out a way to tie this in to the CYJavaFrame
901 value
.l
= CYCastJavaObject(jni
, context
, argument
).leak();
904 case CYJavaPrimitiveBoolean
:
905 if (type
!= kJSTypeBoolean
)
907 value
.z
= CYCastBool(context
, argument
);
910 case CYJavaPrimitiveCharacter
:
911 if (type
== kJSTypeNumber
)
912 CYCastJavaNumeric(value
, primitive
, context
, argument
);
913 else if (type
!= kJSTypeString
)
916 CYJSString
string(context
, argument
);
917 if (JSStringGetLength(string
) != 1)
920 value
.c
= JSStringGetCharactersPtr(string
)[0];
924 case CYJavaPrimitiveByte
:
925 case CYJavaPrimitiveShort
:
926 case CYJavaPrimitiveInteger
:
927 case CYJavaPrimitiveLong
:
928 case CYJavaPrimitiveFloat
:
929 case CYJavaPrimitiveDouble
:
930 if (type
!= kJSTypeNumber
)
932 CYCastJavaNumeric(value
, primitive
, context
, argument
);
943 static JSValueRef
JavaMethod_callAsFunction(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
944 auto internal(CYJavaMethod::Get(context
, object
));
945 CYJavaObject
*self(CYGetJavaObject(context
, _this
));
946 _assert(self
!= NULL
);
947 CYJavaEnv
jni(self
->value_
);
949 CYJavaSignature
bound(count
);
950 for (auto overload(internal
->overload_
.lower_bound(bound
)), e(internal
->overload_
.upper_bound(bound
)); overload
!= e
; ++overload
) {
951 CYJavaFrame
frame(jni
, count
+ 16);
953 if (!CYCastJavaArguments(frame
, overload
->shorty_
, context
, arguments
, array
))
955 jvalue
*values(array
);
956 switch (overload
->primitive_
) {
957 case CYJavaPrimitiveObject
:
958 return CYCastJSValue(context
, jni
.CallObjectMethodA
<jobject
>(self
->value_
, overload
->method_
, values
));
959 case CYJavaPrimitiveVoid
:
960 jni
.CallVoidMethodA(self
->value_
, overload
->method_
, values
);
961 return CYJSUndefined(context
);
962 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
963 case CYJavaPrimitive ## Type: \
964 return CYJavaCastJSValue(context, jni.Call ## Typ ## MethodA(self->value_, overload->method_, values));
965 CYJavaForEachPrimitive
966 #undef CYJavaForEachPrimitive_
967 default: _assert(false);
971 CYThrow("invalid method call");
974 static JSValueRef
JavaStaticMethod_callAsFunction(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
975 auto internal(CYJavaStaticMethod::Get(context
, object
));
976 CYJavaClass
*table(CYGetJavaTable(context
, _this
));
977 CYJavaEnv
jni(table
->value_
);
979 CYJavaSignature
bound(count
);
980 for (auto overload(internal
->overload_
.lower_bound(bound
)), e(internal
->overload_
.upper_bound(bound
)); overload
!= e
; ++overload
) {
981 CYJavaFrame
frame(jni
, count
+ 16);
983 if (!CYCastJavaArguments(frame
, overload
->shorty_
, context
, arguments
, array
))
985 jvalue
*values(array
);
986 switch (overload
->primitive_
) {
987 case CYJavaPrimitiveObject
:
988 return CYCastJSValue(context
, jni
.CallStaticObjectMethodA
<jobject
>(table
->value_
, overload
->method_
, values
));
989 case CYJavaPrimitiveVoid
:
990 jni
.CallStaticVoidMethodA(table
->value_
, overload
->method_
, values
);
991 return CYJSUndefined(context
);
992 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
993 case CYJavaPrimitive ## Type: \
994 return CYJavaCastJSValue(context, jni.CallStatic ## Typ ## MethodA(table->value_, overload->method_, values));
995 CYJavaForEachPrimitive
996 #undef CYJavaForEachPrimitive_
997 default: _assert(false);
1001 CYThrow("invalid method call");
1004 static JSObjectRef
JavaClass_callAsConstructor(JSContextRef context
, JSObjectRef object
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
1005 auto table(CYJavaClass::Get(context
, object
));
1006 CYJavaEnv
jni(table
->value_
);
1007 jclass
_class(table
->value_
);
1009 if (table
->interface_
&& count
== 1) {
1010 auto Cycript$
(jni
.FindClass("Cycript"));
1011 auto Cycript$
Make(jni
.GetStaticMethodID(Cycript$
, "proxy", "(Ljava/lang/Class;LCycript$Wrapper;)Ljava/lang/Object;"));
1012 return CYCastJSObject(context
, jni
.CallObjectMethod
<jobject
>(Cycript$
, Cycript$Make
, _class
, CYCastJavaObject(jni
, context
, CYCastJSObject(context
, arguments
[0])).get()));
1015 CYJavaSignature
bound(count
);
1016 for (auto overload(table
->overload_
.lower_bound(bound
)), e(table
->overload_
.upper_bound(bound
)); overload
!= e
; ++overload
) {
1017 CYJavaFrame
frame(jni
, count
+ 16);
1018 jvalue array
[count
];
1019 if (!CYCastJavaArguments(frame
, overload
->shorty_
, context
, arguments
, array
))
1021 jvalue
*values(array
);
1022 auto object(jni
.NewObjectA(_class
, overload
->method_
, values
));
1023 return CYCastJSObject(context
, object
);
1026 CYThrow("invalid constructor call");
1029 static bool JavaStaticInterior_hasProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
) {
1030 auto internal(CYJavaStaticInterior::Get(context
, object
));
1031 CYJavaClass
*table(internal
->table_
);
1033 auto name(CYPoolUTF8String(pool
, context
, property
));
1034 auto field(table
->static_
.find(name
));
1035 if (field
== table
->static_
.end())
1040 static JSValueRef
JavaStaticInterior_getProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1041 auto internal(CYJavaStaticInterior::Get(context
, object
));
1042 CYJavaClass
*table(internal
->table_
);
1043 CYJavaEnv
jni(table
->value_
);
1045 auto name(CYPoolUTF8String(pool
, context
, property
));
1046 auto field(table
->static_
.find(name
));
1047 if (field
== table
->static_
.end())
1050 switch (field
->second
.primitive_
) {
1051 case CYJavaPrimitiveObject
:
1052 return CYCastJSValue(context
, jni
.GetStaticObjectField
<jobject
>(table
->value_
, field
->second
.field_
));
1053 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1054 case CYJavaPrimitive ## Type: \
1055 return CYJavaCastJSValue(context, jni.GetStatic ## Typ ## Field(table->value_, field->second.field_));
1056 CYJavaForEachPrimitive
1057 #undef CYJavaForEachPrimitive_
1058 default: _assert(false);
1062 static bool JavaStaticInterior_setProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef value
, JSValueRef
*exception
) { CYTry
{
1063 auto internal(CYJavaStaticInterior::Get(context
, object
));
1064 CYJavaClass
*table(internal
->table_
);
1065 CYJavaEnv
jni(table
->value_
);
1067 auto name(CYPoolUTF8String(pool
, context
, property
));
1068 auto field(table
->static_
.find(name
));
1069 if (field
== table
->static_
.end())
1072 switch (field
->second
.primitive_
) {
1073 case CYJavaPrimitiveObject
:
1074 jni
.SetStaticObjectField(table
->value_
, field
->second
.field_
, CYCastJavaObject(jni
, context
, value
));
1075 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1076 case CYJavaPrimitive ## Type: \
1077 jni.SetStatic ## Typ ## Field(table->value_, field->second.field_, CYCastDouble(context, value)); \
1079 CYJavaForEachPrimitive
1080 #undef CYJavaForEachPrimitive_
1081 default: _assert(false);
1087 static void JavaStaticInterior_getPropertyNames(JSContextRef context
, JSObjectRef object
, JSPropertyNameAccumulatorRef names
) {
1088 auto internal(CYJavaStaticInterior::Get(context
, object
));
1089 CYJavaClass
*table(internal
->table_
);
1090 for (const auto &field
: table
->static_
)
1091 JSPropertyNameAccumulatorAddName(names
, CYJSString(field
.first
));
1094 static JSValueRef
JavaClass_getProperty_class(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1095 auto table(CYJavaClass::Get(context
, object
));
1096 return CYCastJSValue(context
, table
->value_
);
1099 static bool JavaInterior_hasProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
) {
1100 auto internal(CYJavaInterior::Get(context
, object
));
1101 CYJavaClass
*table(internal
->table_
);
1103 auto name(CYPoolUTF8String(pool
, context
, property
));
1104 auto field(table
->instance_
.find(name
));
1105 if (field
== table
->instance_
.end())
1110 static JSValueRef
JavaInterior_getProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1111 auto internal(CYJavaInterior::Get(context
, object
));
1112 CYJavaEnv
jni(internal
->value_
);
1113 CYJavaClass
*table(internal
->table_
);
1115 auto name(CYPoolUTF8String(pool
, context
, property
));
1116 auto field(table
->instance_
.find(name
));
1117 if (field
== table
->instance_
.end())
1120 switch (field
->second
.primitive_
) {
1121 case CYJavaPrimitiveObject
:
1122 return CYCastJSValue(context
, jni
.GetObjectField
<jobject
>(internal
->value_
, field
->second
.field_
));
1123 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1124 case CYJavaPrimitive ## Type: \
1125 return CYJavaCastJSValue(context, jni.Get ## Typ ## Field(internal->value_, field->second.field_));
1126 CYJavaForEachPrimitive
1127 #undef CYJavaForEachPrimitive_
1128 default: _assert(false);
1132 static bool JavaInterior_setProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef value
, JSValueRef
*exception
) { CYTry
{
1133 auto internal(CYJavaInterior::Get(context
, object
));
1134 CYJavaEnv
jni(internal
->value_
);
1135 CYJavaClass
*table(internal
->table_
);
1137 auto name(CYPoolUTF8String(pool
, context
, property
));
1138 auto field(table
->instance_
.find(name
));
1139 if (field
== table
->instance_
.end())
1142 switch (field
->second
.primitive_
) {
1143 case CYJavaPrimitiveObject
:
1144 jni
.SetObjectField(table
->value_
, field
->second
.field_
, CYCastJavaObject(jni
, context
, value
));
1145 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1146 case CYJavaPrimitive ## Type: \
1147 jni.Set ## Typ ## Field(table->value_, field->second.field_, CYCastDouble(context, value)); \
1149 CYJavaForEachPrimitive
1150 #undef CYJavaForEachPrimitive_
1151 default: _assert(false);
1157 static void JavaInterior_getPropertyNames(JSContextRef context
, JSObjectRef object
, JSPropertyNameAccumulatorRef names
) {
1158 auto internal(CYJavaInterior::Get(context
, object
));
1159 CYJavaClass
*table(internal
->table_
);
1160 for (const auto &field
: table
->instance_
)
1161 JSPropertyNameAccumulatorAddName(names
, CYJSString(field
.first
));
1164 static JSValueRef
JavaObject_getProperty_constructor(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1165 auto internal(CYJavaObject::Get(context
, object
));
1166 CYJavaEnv
jni(internal
->value_
);
1167 return CYGetJavaClass(context
, jni
.GetObjectClass(internal
->value_
));
1170 static JSValueRef JavaClass_getProperty_$
cyi(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1171 auto internal(CYJavaClass::Get(context
, object
));
1172 return CYJavaStaticInterior::Make(context
, internal
->value_
, internal
);
1175 static JSValueRef JavaObject_getProperty_$
cyi(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1176 auto internal(CYJavaObject::Get(context
, object
));
1177 return CYJavaInterior::Make(context
, internal
->value_
, internal
->table_
);
1180 static JSValueRef
JavaClass_callAsFunction_toCYON(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
1181 auto internal(CYJavaClass::Get(context
, _this
));
1182 CYJavaEnv
jni(internal
->value_
);
1183 auto Class$
(jni
.FindClass("java/lang/Class"));
1184 auto Class$
getCanonicalName(jni
.GetMethodID(Class$
, "getCanonicalName", "()Ljava/lang/String;"));
1185 return CYCastJSValue(context
, CYJSString(jni
.CallObjectMethod
<jstring
>(internal
->value_
, Class$getCanonicalName
)));
1188 static JSValueRef
JavaMethod_callAsFunction_toCYON(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
1189 std::ostringstream cyon
;
1190 return CYCastJSValue(context
, CYJSString(cyon
.str()));
1193 static JSValueRef
JavaStaticMethod_callAsFunction_toCYON(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
1194 std::ostringstream cyon
;
1195 return CYCastJSValue(context
, CYJSString(cyon
.str()));
1198 static JSValueRef
JavaArray_getProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1199 auto internal(CYJavaArray::Get(context
, object
));
1200 CYJavaEnv
jni(internal
->value_
);
1201 if (JSStringIsEqual(property
, length_s
))
1202 return CYCastJSValue(context
, jni
.GetArrayLength(internal
->value_
));
1206 if (!CYGetOffset(pool
, context
, property
, offset
))
1209 if (internal
->primitive_
== CYJavaPrimitiveObject
)
1210 return CYCastJSValue(context
, jni
.GetObjectArrayElement
<jobject
>(static_cast<jobjectArray
>(internal
->value_
.value_
), offset
));
1211 else switch (internal
->primitive_
) {
1212 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1213 case CYJavaPrimitive ## Type: { \
1214 j ## type element; \
1215 jni.Get ## Typ ## ArrayRegion(static_cast<j ## type ## Array>(internal->value_.value_), offset, 1, &element); \
1216 return CYJavaCastJSValue(context, element); \
1218 CYJavaForEachPrimitive
1219 #undef CYJavaForEachPrimitive_
1220 default: _assert(false);
1224 static bool JavaArray_setProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef value
, JSValueRef
*exception
) { CYTry
{
1225 auto internal(CYJavaArray::Get(context
, object
));
1226 CYJavaEnv
jni(internal
->value_
);
1230 if (!CYGetOffset(pool
, context
, property
, offset
))
1233 if (internal
->primitive_
== CYJavaPrimitiveObject
)
1234 jni
.SetObjectArrayElement(static_cast<jobjectArray
>(internal
->value_
.value_
), offset
, CYCastJavaObject(jni
, context
, value
));
1235 else switch (internal
->primitive_
) {
1236 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1237 case CYJavaPrimitive ## Type: { \
1238 j ## type element; \
1239 jni.Get ## Typ ## ArrayRegion(static_cast<j ## type ## Array>(internal->value_.value_), offset, 1, &element); \
1240 return CYJavaCastJSValue(context, element); \
1242 CYJavaForEachPrimitive
1243 #undef CYJavaForEachPrimitive_
1244 default: _assert(false);
1250 static JSValueRef
JavaPackage_callAsFunction_toCYON(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
1251 auto internal(CYJavaPackage::Get(context
, _this
));
1252 std::ostringstream name
;
1253 for (auto &package
: internal
->package_
)
1254 name
<< package
<< '.';
1256 return CYCastJSValue(context
, CYJSString(name
.str()));
1259 static bool CYJavaPackage_hasProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
) {
1263 static JSValueRef
CYJavaPackage_getProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1264 auto internal(CYJavaPackage::Get(context
, object
));
1265 CYJavaPackage::Path
package(internal
->package_
);
1268 const char *next(CYPoolCString(pool
, context
, property
));
1270 std::ostringstream name
;
1271 for (auto &package
: internal
->package_
)
1272 name
<< package
<< '/';
1275 JNIEnv
*jni(internal
->jni_
);
1276 if (auto _class
= jni
->FindClass(name
.str().c_str()))
1277 return CYGetJavaClass(context
, CYJavaLocal
<jclass
>(jni
, _class
));
1278 jni
->ExceptionClear();
1280 package
.push_back(next
);
1281 return CYJavaPackage::Make(context
, jni
, package
);
1284 static void Cycript_delete(JNIEnv
*env
, jclass api
, jlong jprotect
) { CYJavaTry
{
1288 static jobject
Cycript_handle(JNIEnv
*env
, jclass api
, jlong jprotect
, jstring property
, jobjectArray jarguments
) { CYJavaTry
{
1289 JSValueRef
function(CYGetProperty(context
, object
, CYJSString(CYJavaRef
<jstring
>(jni
, property
))));
1290 if (JSValueIsUndefined(context
, function
))
1293 size_t count(jarguments
== NULL
? 0 : jni
.GetArrayLength(jarguments
));
1294 JSValueRef arguments
[count
];
1295 for (size_t index(0); index
!= count
; ++index
)
1296 arguments
[index
] = CYCastJSValue(context
, jni
.GetObjectArrayElement
<jobject
>(jarguments
, index
));
1298 return CYCastJavaObject(jni
, context
, CYCallAsFunction(context
, CYCastJSObject(context
, function
), object
, count
, arguments
)).leak();
1299 } CYJavaCatch(NULL
) }
1301 static JNINativeMethod Cycript_
[] = {
1302 {(char *) "delete", (char *) "(J)V", (void *) &Cycript_delete
},
1303 {(char *) "handle", (char *) "(JLjava/lang/String;[Ljava/lang/Object;)Ljava/lang/Object;", (void *) &Cycript_handle
},
1306 template <typename Type_
>
1307 static _finline
void dlset(Type_
&function
, const char *name
, void *handle
) {
1308 function
= reinterpret_cast<Type_
>(dlsym(handle
, name
));
1311 jint
CYJavaVersion(JNI_VERSION_1_4
);
1313 static JavaVM
*CYGetJavaVM(jint (*$JNI_GetCreatedJavaVMs
)(JavaVM
**, jsize
, jsize
*)) {
1315 JavaVM
*jvms
[capacity
];
1317 _jnicall($
JNI_GetCreatedJavaVMs(jvms
, capacity
, &size
));
1323 static JavaVM
*CYGetJavaVM(JSContextRef context
) {
1325 void *handle(RTLD_DEFAULT
);
1326 std::string library
;
1328 jint (*$JNI_GetCreatedJavaVMs
)(JavaVM
**jvms
, jsize capacity
, jsize
*size
);
1329 dlset($JNI_GetCreatedJavaVMs
, "JNI_GetCreatedJavaVMs", handle
);
1331 if ($JNI_GetCreatedJavaVMs
!= NULL
) {
1332 if (JavaVM
*jvm
= CYGetJavaVM($JNI_GetCreatedJavaVMs
))
1335 std::vector
<const char *> guesses
;
1338 char android
[PROP_VALUE_MAX
];
1339 if (__system_property_get("persist.sys.dalvik.vm.lib", android
) != 0)
1340 guesses
.push_back(android
);
1343 guesses
.push_back("/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/jli/libjli.dylib");
1344 //guesses.push_back("/System/Library/Frameworks/JavaVM.framework/JavaVM");
1345 guesses
.push_back("libjvm.dylib");
1347 guesses
.push_back("libart.so");
1348 guesses
.push_back("libdvm.so");
1349 guesses
.push_back("libjvm.so");
1351 for (const char *guess
: guesses
) {
1352 handle
= dlopen(guess
, RTLD_LAZY
| RTLD_GLOBAL
);
1353 if (handle
!= NULL
) {
1359 if (library
.size() == 0)
1362 dlset($JNI_GetCreatedJavaVMs
, "JNI_GetCreatedJavaVMs", handle
);
1363 if (JavaVM
*jvm
= CYGetJavaVM($JNI_GetCreatedJavaVMs
))
1367 std::vector
<JavaVMOption
> options
;
1370 std::ostringstream option
;
1371 option
<< "-Djava.class.path=";
1372 option
<< CYPoolLibraryPath(pool
) << "/libcycript.jar";
1373 if (const char *classpath
= getenv("CLASSPATH"))
1374 option
<< ':' << classpath
;
1375 options
.push_back(JavaVMOption
{pool
.strdup(option
.str().c_str()), NULL
});
1378 // To use libnativehelper to access JNI_GetCreatedJavaVMs, you need JniInvocation.
1379 // ...but there can only be one JniInvocation, and assuradely the other VM has it.
1380 // Essentially, this API makes no sense. We need it for AndroidRuntime, though :/.
1382 if (void *libnativehelper
= dlopen("libnativehelper.so", RTLD_LAZY
| RTLD_GLOBAL
)) {
1383 class JniInvocation$
;
1384 JniInvocation$
*(*JniInvocation$$init$
)(JniInvocation$
*self
)(NULL
);
1385 bool (*JniInvocation$Init
)(JniInvocation$
*self
, const char *library
)(NULL
);
1386 JniInvocation$
*(*JniInvocation$finalize
)(JniInvocation$
*self
)(NULL
);
1388 dlset(JniInvocation$$init$
, "_ZN13JniInvocationC1Ev", libnativehelper
);
1389 dlset(JniInvocation$Init
, "_ZN13JniInvocation4InitEPKc", libnativehelper
);
1390 dlset(JniInvocation$finalize
, "_ZN13JniInvocationD1Ev", libnativehelper
);
1392 if (JniInvocation$$init$
== NULL
)
1393 dlclose(libnativehelper
);
1395 // XXX: we should attach a pool to the VM itself and deallocate this there
1396 //auto invocation(pool.calloc<JniInvocation$>(1, 1024));
1397 //_assert(JniInvocation$finalize != NULL);
1398 //pool.atexit(reinterpret_cast<void (*)(void *)>(JniInvocation$finalize), invocation);
1400 auto invocation(static_cast<JniInvocation$
*>(calloc(1, 1024)));
1401 JniInvocation$$init$
(invocation
);
1403 _assert(JniInvocation$Init
!= NULL
);
1404 JniInvocation$
Init(invocation
, NULL
);
1406 dlset($JNI_GetCreatedJavaVMs
, "JNI_GetCreatedJavaVMs", libnativehelper
);
1407 if (JavaVM
*jvm
= CYGetJavaVM($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
**env
)(NULL
);
1419 int (*AndroidRuntime$startReg
)(JNIEnv
*env
)(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
, &env
);
1450 _assert(failure
== 0);
1452 _assert(AndroidRuntime$startReg
!= NULL
);
1453 failure
= AndroidRuntime$
startReg(env
);
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 **>(&env
), &args
));
1471 static JNIEnv
*GetJNI(JSContextRef context
) {
1472 auto jvm(CYGetJavaVM(context
));
1477 _jnicall(jvm
->GetEnv(reinterpret_cast<void **>(&env
), CYJavaVersion
));
1480 auto Cycript$
(jni
.FindClass("Cycript"));
1481 jni
.RegisterNatives(Cycript$
, Cycript_
, sizeof(Cycript_
) / sizeof(Cycript_
[0]));
1486 static JSStaticValue JavaClass_staticValues
[3] = {
1487 {"class", &JavaClass_getProperty_class
, NULL
, kJSPropertyAttributeReadOnly
| kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1488 {"$cyi", &JavaClass_getProperty_$cyi
, NULL
, kJSPropertyAttributeReadOnly
| kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1489 {NULL
, NULL
, NULL
, 0}
1492 static JSStaticFunction JavaClass_staticFunctions
[2] = {
1493 {"toCYON", &JavaClass_callAsFunction_toCYON
, kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1497 static JSStaticValue JavaObject_staticValues
[3] = {
1498 {"constructor", &JavaObject_getProperty_constructor
, NULL
, kJSPropertyAttributeReadOnly
| kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1499 {"$cyi", &JavaObject_getProperty_$cyi
, NULL
, kJSPropertyAttributeReadOnly
| kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1500 {NULL
, NULL
, NULL
, 0}
1503 static JSStaticFunction JavaMethod_staticFunctions
[2] = {
1504 {"toCYON", &JavaMethod_callAsFunction_toCYON
, kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1508 static JSStaticFunction JavaStaticMethod_staticFunctions
[2] = {
1509 {"toCYON", &JavaStaticMethod_callAsFunction_toCYON
, kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1513 static JSStaticFunction JavaPackage_staticFunctions
[2] = {
1514 {"toCYON", &JavaPackage_callAsFunction_toCYON
, kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1518 void CYJava_Initialize() {
1519 Primitives_
.insert(std::make_pair("void", CYJavaPrimitiveVoid
));
1520 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1521 Primitives_.insert(std::make_pair(#type, CYJavaPrimitive ## Type));
1522 CYJavaForEachPrimitive
1523 #undef CYJavaForEachPrimitive_
1525 JSClassDefinition definition
;
1527 definition
= kJSClassDefinitionEmpty
;
1528 definition
.className
= "JavaClass";
1529 definition
.staticValues
= JavaClass_staticValues
;
1530 definition
.staticFunctions
= JavaClass_staticFunctions
;
1531 definition
.callAsConstructor
= &JavaClass_callAsConstructor
;
1532 definition
.finalize
= &CYFinalize
;
1533 CYJavaClass::Class_
= JSClassCreate(&definition
);
1535 definition
= kJSClassDefinitionEmpty
;
1536 definition
.attributes
= kJSClassAttributeNoAutomaticPrototype
;
1537 definition
.className
= "JavaInterior";
1538 definition
.hasProperty
= &JavaInterior_hasProperty
;
1539 definition
.getProperty
= &JavaInterior_getProperty
;
1540 definition
.setProperty
= &JavaInterior_setProperty
;
1541 definition
.getPropertyNames
= &JavaInterior_getPropertyNames
;
1542 definition
.finalize
= &CYFinalize
;
1543 CYJavaInterior::Class_
= JSClassCreate(&definition
);
1545 definition
= kJSClassDefinitionEmpty
;
1546 definition
.className
= "JavaMethod";
1547 definition
.staticFunctions
= JavaMethod_staticFunctions
;
1548 definition
.callAsFunction
= &JavaMethod_callAsFunction
;
1549 definition
.finalize
= &CYFinalize
;
1550 CYJavaMethod::Class_
= JSClassCreate(&definition
);
1552 definition
= kJSClassDefinitionEmpty
;
1553 definition
.className
= "JavaStaticMethod";
1554 definition
.staticFunctions
= JavaStaticMethod_staticFunctions
;
1555 definition
.callAsFunction
= &JavaStaticMethod_callAsFunction
;
1556 definition
.finalize
= &CYFinalize
;
1557 CYJavaStaticMethod::Class_
= JSClassCreate(&definition
);
1559 definition
= kJSClassDefinitionEmpty
;
1560 definition
.attributes
= kJSClassAttributeNoAutomaticPrototype
;
1561 definition
.className
= "JavaObject";
1562 definition
.staticValues
= JavaObject_staticValues
;
1563 definition
.finalize
= &CYFinalize
;
1564 CYJavaObject::Class_
= JSClassCreate(&definition
);
1566 definition
= kJSClassDefinitionEmpty
;
1567 definition
.className
= "JavaArray";
1568 definition
.getProperty
= &JavaArray_getProperty
;
1569 definition
.setProperty
= &JavaArray_setProperty
;
1570 definition
.finalize
= &CYFinalize
;
1571 CYJavaArray::Class_
= JSClassCreate(&definition
);
1573 definition
= kJSClassDefinitionEmpty
;
1574 definition
.className
= "JavaPackage";
1575 definition
.staticFunctions
= JavaPackage_staticFunctions
;
1576 definition
.hasProperty
= &CYJavaPackage_hasProperty
;
1577 definition
.getProperty
= &CYJavaPackage_getProperty
;
1578 definition
.finalize
= &CYFinalize
;
1579 CYJavaPackage::Class_
= JSClassCreate(&definition
);
1581 definition
= kJSClassDefinitionEmpty
;
1582 definition
.attributes
= kJSClassAttributeNoAutomaticPrototype
;
1583 definition
.className
= "JavaStaticInterior";
1584 definition
.hasProperty
= &JavaStaticInterior_hasProperty
;
1585 definition
.getProperty
= &JavaStaticInterior_getProperty
;
1586 definition
.setProperty
= &JavaStaticInterior_setProperty
;
1587 definition
.getPropertyNames
= &JavaStaticInterior_getPropertyNames
;
1588 definition
.finalize
= &CYFinalize
;
1589 CYJavaStaticInterior::Class_
= JSClassCreate(&definition
);
1592 void CYJava_SetupContext(JSContextRef context
) {
1593 JNIEnv
*jni(GetJNI(context
));
1597 JSObjectRef
global(CYGetGlobalObject(context
));
1598 //JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
1599 JSObjectRef
cycript(CYCastJSObject(context
, CYGetProperty(context
, global
, CYJSString("Cycript"))));
1600 JSObjectRef
all(CYCastJSObject(context
, CYGetProperty(context
, cycript
, CYJSString("all"))));
1601 //JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
1603 JSObjectRef
Java(JSObjectMake(context
, NULL
, NULL
));
1604 CYSetProperty(context
, cycript
, CYJSString("Java"), Java
);
1606 JSObjectRef
Packages(CYJavaPackage::Make(context
, jni
, CYJavaPackage::Path()));
1607 CYSetProperty(context
, all
, CYJSString("Packages"), Packages
);
1609 for (auto name
: (const char *[]) {"java", "javax", "android", "com", "net", "org"}) {
1610 CYJSString
js(name
);
1611 CYSetProperty(context
, all
, js
, CYGetProperty(context
, Packages
, js
));
1615 static CYHook CYJavaHook
= {
1620 &CYJava_SetupContext
,
1624 CYRegisterHook
CYJava(&CYJavaHook
);