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(CYJavaRef
<jstring
> &&) = delete;
260 ~CYJavaUTF8String() {
261 JNIEnv
*jni(value_
.jni());
262 jni
->ReleaseStringUTFChars(value_
, data
);
265 CYJavaUTF8String(const CYJavaUTF8String
&) = delete;
268 CYJavaUTF8String
CYCastUTF8String(const CYJavaRef
<jstring
> &value
) {
272 JSStringRef
CYCopyJSString(const CYJavaRef
<jstring
> &value
) {
273 return CYCopyJSString(CYCastUTF8String(value
));
280 CYJavaGlobal
<jthrowable
> value_
;
282 CYJavaError(const CYJavaRef
<jthrowable
> &value
) :
287 virtual const char *PoolCString(CYPool
&pool
) const {
288 auto string(CYCastJavaString(value_
.cast
<jobject
>()));
289 return CYPoolCString(pool
, CYJavaUTF8String(string
));
292 virtual JSValueRef
CastJSValue(JSContextRef context
, const char *name
) const;
299 CYJavaFrame(JNIEnv
*jni
, jint capacity
) :
302 _assert(jni
->PushLocalFrame(capacity
) == 0);
309 operator JNIEnv
*() const {
313 jobject
operator ()(jobject object
) {
316 return jni
->PopLocalFrame(object
);
325 CYJavaEnv(JNIEnv
*jni
) :
330 template <typename Other_
>
331 CYJavaEnv(const CYJavaRef
<Other_
> &value
) :
336 operator JNIEnv
*() const {
340 JNIEnv
*operator ->() const {
344 CYJavaLocal
<jclass
> FindClass(const char *name
) const {
345 return {jni
, _envcall(jni
, FindClass(name
))};
348 CYJavaLocal
<jclass
> GetObjectClass(jobject object
) const {
349 return {jni
, _envcall(jni
, GetObjectClass(object
))};
352 CYJavaLocal
<jclass
> GetSuperclass(jclass _class
) const {
353 return {jni
, _envcall(jni
, GetSuperclass(_class
))};
356 CYJavaLocal
<jobject
> NewObject(jclass _class
, jmethodID method
, ...) const {
358 va_start(args
, method
);
359 jobject
object(_envcall(jni
, NewObjectV(_class
, method
, args
)));
361 return {jni
, object
};
364 CYJavaLocal
<jobject
> NewObjectA(jclass _class
, jmethodID method
, jvalue
*args
) const {
365 return {jni
, _envcall(jni
, NewObjectA(_class
, method
, args
))};
368 CYJavaLocal
<jstring
> NewString(const jchar
*data
, jsize size
) const {
369 return {jni
, _envcall(jni
, NewString(data
, size
))};
372 #define CYJavaEnv_(Code) \
373 template <typename... Args_> \
374 void Code(Args_ &&... args) const { \
375 _envcallv(jni, Code(cy::Forward<Args_>(args)...)); \
378 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
379 CYJavaEnv_(Get ## Typ ## ArrayRegion) \
380 CYJavaEnv_(Set ## Typ ## Field) \
381 CYJavaEnv_(SetStatic ## Typ ## Field)
382 CYJavaForEachPrimitive
383 #undef CYJavaForEachPrimitive_
385 CYJavaEnv_(CallVoidMethod
)
386 CYJavaEnv_(CallStaticVoidMethod
)
387 CYJavaEnv_(CallVoidMethodA
)
388 CYJavaEnv_(CallStaticVoidMethodA
)
389 CYJavaEnv_(SetObjectArrayElement
)
390 CYJavaEnv_(SetObjectField
)
391 CYJavaEnv_(SetStaticObjectField
)
394 #define CYJavaEnv_(Code) \
395 template <typename... Args_> \
396 auto Code(Args_ &&... args) const -> decltype(jni->Code(cy::Forward<Args_>(args)...)) { \
397 return _envcall(jni, Code(cy::Forward<Args_>(args)...)); \
400 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
401 CYJavaEnv_(Call ## Typ ## Method) \
402 CYJavaEnv_(CallStatic ## Typ ## Method) \
403 CYJavaEnv_(Call ## Typ ## MethodA) \
404 CYJavaEnv_(CallStatic ## Typ ## MethodA) \
405 CYJavaEnv_(Get ## Typ ## Field) \
406 CYJavaEnv_(GetStatic ## Typ ## Field)
407 CYJavaForEachPrimitive
408 #undef CYJavaForEachPrimitive_
410 CYJavaEnv_(FromReflectedField
)
411 CYJavaEnv_(FromReflectedMethod
)
412 CYJavaEnv_(GetArrayLength
)
413 CYJavaEnv_(GetMethodID
)
414 CYJavaEnv_(GetStaticMethodID
)
415 CYJavaEnv_(IsSameObject
)
416 CYJavaEnv_(RegisterNatives
)
419 #define CYJavaEnv_(Code) \
420 template <typename Other_, typename... Args_> \
421 auto Code(Args_ &&... args) const -> CYJavaLocal<Other_> { \
422 return {jni, static_cast<Other_>(_envcall(jni, Code(cy::Forward<Args_>(args)...)))}; \
425 CYJavaEnv_(CallObjectMethod
)
426 CYJavaEnv_(CallStaticObjectMethod
)
427 CYJavaEnv_(CallObjectMethodA
)
428 CYJavaEnv_(CallStaticObjectMethodA
)
429 CYJavaEnv_(GetObjectArrayElement
)
430 CYJavaEnv_(GetObjectField
)
431 CYJavaEnv_(GetStaticObjectField
)
435 static CYJavaLocal
<jstring
> CYCastJavaString(const CYJavaRef
<jobject
> &value
) {
436 CYJavaEnv
jni(value
);
437 auto Object$
(jni
.FindClass("java/lang/Object"));
438 auto Object$
toString(jni
.GetMethodID(Object$
, "toString", "()Ljava/lang/String;"));
439 return jni
.CallObjectMethod
<jstring
>(value
, Object$toString
);
442 static JSValueRef
CYCastJSValue(JSContextRef context
, const CYJavaRef
<jobject
> &value
);
444 template <typename Other_
>
445 static _finline JSValueRef
CYCastJSValue(JSContextRef context
, const CYJavaRef
<Other_
> &value
) {
446 return CYCastJSValue(context
, value
.template cast
<jobject
>());
449 template <typename Type_
>
450 static _finline JSValueRef
CYJavaCastJSValue(JSContextRef context
, Type_ value
) {
451 return CYCastJSValue(context
, value
);
454 static _finline JSValueRef
CYJavaCastJSValue(JSContextRef context
, jboolean value
) {
455 return CYCastJSValue(context
, static_cast<bool>(value
));
458 JSValueRef
CYJavaError::CastJSValue(JSContextRef context
, const char *name
) const {
459 return CYCastJSValue(context
, value_
);
462 static std::map
<std::string
, CYJavaPrimitive
> Primitives_
;
464 static CYJavaPrimitive
CYJavaGetPrimitive(JSContextRef context
, const CYJavaRef
<jclass
> &type
, jmethodID Class$get$$Name
) {
466 auto string(jni
.CallObjectMethod
<jstring
>(type
, Class$get$$Name
));
469 CYJavaUTF8String
name(string
);
470 auto primitive(Primitives_
.find(name
));
471 return primitive
!= Primitives_
.end() ? primitive
->second
: CYJavaPrimitiveObject
;
474 typedef std::vector
<CYJavaPrimitive
> CYJavaShorty
;
476 static CYJavaShorty
CYJavaGetShorty(JSContextRef context
, const CYJavaRef
<jobjectArray
> &types
, jmethodID Class$get$$Name
) {
477 CYJavaEnv
jni(types
);
478 size_t count(jni
.GetArrayLength(types
));
479 CYJavaShorty
shorty(count
);
480 for (size_t index(0); index
!= count
; ++index
)
481 shorty
[index
] = CYJavaGetPrimitive(context
, jni
.GetObjectArrayElement
<jclass
>(types
, index
), Class$get$$Name
);
487 CYJavaPrimitive primitive_
;
490 typedef std::map
<std::string
, CYJavaField
> CYJavaFieldMap
;
492 struct CYJavaSignature
{
493 CYJavaGlobal
<jobject
> reflected_
;
495 CYJavaPrimitive primitive_
;
496 CYJavaShorty shorty_
;
498 CYJavaSignature(const CYJavaRef
<jobject
> &reflected
, jmethodID method
, CYJavaPrimitive primitive
, const CYJavaShorty
&shorty
) :
499 reflected_(reflected
),
501 primitive_(primitive
),
506 // XXX: the shorty doesn't store enough information
507 bool operator <(const CYJavaSignature
&rhs
) const {
508 return shorty_
< rhs
.shorty_
;
512 typedef std::set
<CYJavaSignature
> CYJavaOverload
;
513 typedef std::map
<unsigned, CYJavaOverload
> CYJavaOverloads
;
515 struct CYJavaMethod
:
520 CYJavaOverloads overloads_
;
522 CYJavaMethod(CYUTF8String type
, CYUTF8String name
, const CYJavaOverloads
&overloads
) :
523 type_(CYPoolUTF8String(*pool_
, type
)),
524 name_(CYPoolUTF8String(*pool_
, name
)),
525 overloads_(overloads
)
530 struct CYJavaInstanceMethod
:
533 using CYJavaMethod::CYJavaMethod
;
536 struct CYJavaStaticMethod
:
539 using CYJavaMethod::CYJavaMethod
;
545 CYJavaGlobal
<jclass
> value_
;
548 CYJavaFieldMap static_
;
549 CYJavaFieldMap instance_
;
550 CYJavaOverloads overloads_
;
552 CYJavaClass(const CYJavaRef
<jclass
> &value
, bool interface
) :
554 interface_(interface
)
559 static JSObjectRef
CYGetJavaClass(JSContextRef context
, const CYJavaRef
<jclass
> &_class
);
561 struct CYJavaObject
:
564 CYJavaGlobal
<jobject
> value_
;
567 CYJavaObject(const CYJavaRef
<jobject
> &value
, CYJavaClass
*table
) :
573 JSValueRef
GetPrototype(JSContextRef context
) const;
576 struct CYJavaInterior
:
579 CYJavaGlobal
<jobject
> value_
;
582 CYJavaInterior(const CYJavaRef
<jobject
> &value
, CYJavaClass
*table
) :
589 struct CYJavaStaticInterior
:
592 CYJavaGlobal
<jclass
> value_
;
595 CYJavaStaticInterior(const CYJavaRef
<jclass
> &value
, CYJavaClass
*table
) :
605 CYJavaGlobal
<jarray
> value_
;
606 CYJavaPrimitive primitive_
;
608 CYJavaArray(const CYJavaRef
<jarray
> &value
, CYJavaPrimitive primitive
) :
610 primitive_(primitive
)
614 JSValueRef
GetPrototype(JSContextRef context
) const;
617 struct CYJavaPackage
:
622 typedef std::vector
<std::string
> Path
;
625 _finline
CYJavaPackage(JNIEnv
*jni
, const Path
&package
) :
632 JSValueRef
CYJavaObject::GetPrototype(JSContextRef context
) const {
633 CYJavaEnv
jni(value_
);
634 return CYGetProperty(context
, CYGetJavaClass(context
, jni
.GetObjectClass(value_
)), prototype_s
);
637 JSValueRef
CYJavaArray::GetPrototype(JSContextRef context
) const {
638 return CYGetCachedObject(context
, CYJSString("Array_prototype"));
641 static JSValueRef
CYCastJSValue(JSContextRef context
, const CYJavaRef
<jobject
> &value
) {
643 return CYJSNull(context
);
644 CYJavaEnv
jni(value
);
646 auto _class(jni
.GetObjectClass(value
));
647 if (jni
.IsSameObject(_class
, jni
.FindClass("java/lang/String")))
648 return CYCastJSValue(context
, CYJSString(value
.cast
<jstring
>()));
650 auto Class$
(jni
.FindClass("java/lang/Class"));
651 auto Class$
isArray(jni
.GetMethodID(Class$
, "isArray", "()Z"));
652 if (jni
.CallBooleanMethod(_class
, Class$isArray
)) {
653 auto Class$
getComponentType(jni
.GetMethodID(Class$
, "getComponentType", "()Ljava/lang/Class;"));
654 auto component(jni
.CallObjectMethod
<jclass
>(_class
, Class$getComponentType
));
655 auto Class$
getName(jni
.GetMethodID(Class$
, "getName", "()Ljava/lang/String;"));
656 return CYPrivate
<CYJavaArray
>::Make(context
, value
.cast
<jarray
>(), CYJavaGetPrimitive(context
, component
, Class$getName
));
659 auto Wrapper$
(jni
.FindClass("Cycript$Wrapper"));
660 if (jni
.IsSameObject(_class
, Wrapper$
)) {
661 auto Wrapper$
getProtect(jni
.GetMethodID(Wrapper$
, "getProtect", "()J"));
662 auto &protect(*reinterpret_cast<CYProtect
*>(jni
.CallLongMethod(value
, Wrapper$getProtect
)));
666 CYJavaClass
*table(reinterpret_cast<CYJavaClass
*>(JSObjectGetPrivate(CYGetJavaClass(context
, _class
))));
667 return CYPrivate
<CYJavaObject
>::Make(context
, value
, table
);
670 static _finline JSObjectRef
CYCastJSObject(JSContextRef context
, const CYJavaRef
<jobject
> &value
) {
671 return CYCastJSObject(context
, CYCastJSValue(context
, value
));
674 static CYJavaLocal
<jstring
> CYCastJavaString(const CYJavaEnv
&jni
, JSContextRef context
, CYUTF16String value
) {
675 return jni
.NewString(value
.data
, value
.size
);
678 static CYJavaLocal
<jstring
> CYCastJavaString(const CYJavaEnv
&jni
, JSContextRef context
, JSStringRef value
) {
679 return CYCastJavaString(jni
, context
, CYCastUTF16String(value
));
682 #define CYCastJava$(T, Type, jtype, Cast) \
683 _disused static CYJavaLocal<jobject> CYCastJava ## Type(const CYJavaEnv &jni, JSContextRef context, JSValueRef value) { \
684 auto Type$(jni.FindClass("java/lang/" #Type)); \
685 auto Type$init$(jni.GetMethodID(Type$, "<init>", "(" #T ")V")); \
686 return jni.NewObject(Type$, Type$init$, static_cast<jtype>(Cast(context, value))); \
689 CYCastJava$
(Z
, Boolean
, jboolean
, CYCastBool
)
690 CYCastJava$
(B
, Byte
, jbyte
, CYCastDouble
)
691 CYCastJava$
(C
, Character
, jchar
, CYCastDouble
)
692 CYCastJava$
(S
, Short
, jshort
, CYCastDouble
)
693 CYCastJava$
(I
, Integer
, jint
, CYCastDouble
)
694 CYCastJava$
(J
, Long
, jlong
, CYCastDouble
)
695 CYCastJava$
(F
, Float
, jfloat
, CYCastDouble
)
696 CYCastJava$
(D
, Double
, jdouble
, CYCastDouble
)
698 static CYJavaClass
*CYGetJavaTable(JSContextRef context
, JSObjectRef object
) {
699 if (!JSValueIsObjectOfClass(context
, object
, CYPrivate
<CYJavaClass
>::Class_
))
701 return reinterpret_cast<CYJavaClass
*>(JSObjectGetPrivate(object
));
704 static CYJavaObject
*CYGetJavaObject(JSContextRef context
, JSObjectRef object
) {
705 if (!JSValueIsObjectOfClass(context
, object
, CYPrivate
<CYJavaObject
>::Class_
))
707 return reinterpret_cast<CYJavaObject
*>(JSObjectGetPrivate(object
));
710 static CYJavaLocal
<jobject
> CYCastJavaObject(const CYJavaEnv
&jni
, JSContextRef context
, JSObjectRef value
) {
711 if (CYJavaObject
*internal
= CYGetJavaObject(context
, value
))
712 return internal
->value_
;
714 auto Wrapper$
(jni
.FindClass("Cycript$Wrapper"));
715 auto Wrapper$$init$
(jni
.GetMethodID(Wrapper$
, "<init>", "(J)V"));
716 CYProtect
*protect(new CYProtect(context
, value
));
717 return jni
.NewObject(Wrapper$
, Wrapper$$init$
, reinterpret_cast<jlong
>(protect
));
720 static CYJavaLocal
<jobject
> CYCastJavaObject(const CYJavaEnv
&jni
, JSContextRef context
, JSValueRef value
) {
721 switch (JSValueGetType(context
, value
)) {
725 return CYCastJavaBoolean(jni
, context
, value
);
727 return CYCastJavaDouble(jni
, context
, value
);
729 return CYCastJavaString(jni
, context
, CYJSString(context
, value
));
731 return CYCastJavaObject(jni
, context
, CYCastJSObject(context
, value
));
733 case kJSTypeUndefined
:
734 // XXX: I am currently relying on this for dynamic proxy of void method
741 static JSObjectRef
CYGetJavaClass(JSContextRef context
, const CYJavaRef
<jclass
> &value
) {
742 CYJavaEnv
jni(value
);
743 CYJavaFrame
frame(jni
, 64);
745 JSObjectRef
global(CYGetGlobalObject(context
));
746 JSObjectRef
cy(CYCastJSObject(context
, CYGetProperty(context
, global
, cy_s
)));
748 auto Class$
(jni
.FindClass("java/lang/Class"));
749 auto Class$
getName(jni
.GetMethodID(Class$
, "getName", "()Ljava/lang/String;"));
751 auto string(jni
.CallObjectMethod
<jstring
>(value
, Class$getName
));
752 CYJavaUTF8String
utf8(string
);
753 CYJSString
name(utf8
);
755 JSValueRef
cached(CYGetProperty(context
, cy
, name
));
756 if (!JSValueIsUndefined(context
, cached
))
757 return CYCastJSObject(context
, cached
);
759 JSObjectRef constructor
;
760 JSObjectRef prototype
;
764 auto Class$
isInterface(jni
.GetMethodID(Class$
, "isInterface", "()Z"));
766 auto Class$
getDeclaredConstructors(jni
.GetMethodID(Class$
, "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;"));
767 auto Class$
getDeclaredFields(jni
.GetMethodID(Class$
, "getDeclaredFields", "()[Ljava/lang/reflect/Field;"));
768 auto Class$
getDeclaredMethods(jni
.GetMethodID(Class$
, "getDeclaredMethods", "()[Ljava/lang/reflect/Method;"));
770 auto Constructor$
(jni
.FindClass("java/lang/reflect/Constructor"));
771 //auto Constructor$getModifiers(jni.GetMethodID(Constructor$, "getModifiers", "()I"));
772 auto Constructor$
getParameterTypes(jni
.GetMethodID(Constructor$
, "getParameterTypes", "()[Ljava/lang/Class;"));
774 auto Field$
(jni
.FindClass("java/lang/reflect/Field"));
775 auto Field$
getModifiers(jni
.GetMethodID(Field$
, "getModifiers", "()I"));
776 auto Field$
getName(jni
.GetMethodID(Field$
, "getName", "()Ljava/lang/String;"));
777 auto Field$
getType(jni
.GetMethodID(Field$
, "getType", "()Ljava/lang/Class;"));
779 auto Method$
(jni
.FindClass("java/lang/reflect/Method"));
780 auto Method$
getModifiers(jni
.GetMethodID(Method$
, "getModifiers", "()I"));
781 auto Method$
getName(jni
.GetMethodID(Method$
, "getName", "()Ljava/lang/String;"));
782 auto Method$
getParameterTypes(jni
.GetMethodID(Method$
, "getParameterTypes", "()[Ljava/lang/Class;"));
783 auto Method$
getReturnType(jni
.GetMethodID(Method$
, "getReturnType", "()Ljava/lang/Class;"));
785 auto Modifier$
(jni
.FindClass("java/lang/reflect/Modifier"));
786 auto Modifier$
isStatic(jni
.GetStaticMethodID(Modifier$
, "isStatic", "(I)Z"));
788 auto interface(jni
.CallBooleanMethod(value
, Class$isInterface
));
789 auto table(new CYJavaClass(value
, interface
));
791 for (CYJavaLocal
<jclass
> prototype(value
); prototype
; prototype
= jni
.GetSuperclass(prototype
)) {
792 auto fields(jni
.CallObjectMethod
<jobjectArray
>(prototype
, Class$getDeclaredFields
));
794 for (jsize
i(0), e(jni
.GetArrayLength(fields
)); i
!= e
; ++i
) {
795 auto field(jni
.GetObjectArrayElement
<jobject
>(fields
, e
- i
- 1));
796 auto modifiers(jni
.CallIntMethod(field
, Field$getModifiers
));
797 auto instance(!jni
.CallStaticBooleanMethod(Modifier$
, Modifier$isStatic
, modifiers
));
798 auto &map(instance
? table
->instance_
: table
->static_
);
799 auto string(jni
.CallObjectMethod
<jstring
>(field
, Field$getName
));
800 CYJavaUTF8String
name(string
);
801 auto id(jni
.FromReflectedField(field
));
802 auto type(jni
.CallObjectMethod
<jclass
>(field
, Field$getType
));
803 map
.insert(std::make_pair(std::string(name
), CYJavaField
{id
, CYJavaGetPrimitive(context
, type
, Class$getName
)}));
807 constructor
= JSObjectMake(context
, CYPrivate
<CYJavaClass
>::Class_
, table
);
809 prototype
= JSObjectMake(context
, NULL
, NULL
);
810 CYSetProperty(context
, constructor
, prototype_s
, prototype
, kJSPropertyAttributeDontEnum
);
812 auto constructors(jni
.CallObjectMethod
<jobjectArray
>(value
, Class$getDeclaredConstructors
));
814 for (jsize
i(0), e(jni
.GetArrayLength(constructors
)); i
!= e
; ++i
) {
815 auto constructor(jni
.GetObjectArrayElement
<jobject
>(constructors
, i
));
816 auto parameters(jni
.CallObjectMethod
<jobjectArray
>(constructor
, Constructor$getParameterTypes
));
817 CYJavaShorty
shorty(CYJavaGetShorty(context
, parameters
, Class$getName
));
818 auto id(jni
.FromReflectedMethod(constructor
));
819 table
->overloads_
[shorty
.size()].insert(CYJavaSignature(constructor
, id
, CYJavaPrimitiveObject
, shorty
));
822 std::map
<std::pair
<bool, std::string
>, CYJavaOverloads
> entries
;
825 for (CYJavaLocal
<jclass
> prototype(value
); prototype
; prototype
= jni
.GetSuperclass(prototype
)) {
826 auto methods(jni
.CallObjectMethod
<jobjectArray
>(prototype
, Class$getDeclaredMethods
));
828 for (jsize
i(0), e(jni
.GetArrayLength(methods
)); i
!= e
; ++i
) {
829 auto method(jni
.GetObjectArrayElement
<jobject
>(methods
, i
));
830 auto modifiers(jni
.CallIntMethod(method
, Method$getModifiers
));
831 auto instance(!jni
.CallStaticBooleanMethod(Modifier$
, Modifier$isStatic
, modifiers
));
832 auto string(jni
.CallObjectMethod
<jstring
>(method
, Method$getName
));
833 CYJavaUTF8String
name(string
);
835 auto parameters(jni
.CallObjectMethod
<jobjectArray
>(method
, Method$getParameterTypes
));
836 CYJavaShorty
shorty(CYJavaGetShorty(context
, parameters
, Class$getName
));
838 CYJavaOverload
*overload
;
840 overload
= &entries
[std::make_pair(instance
, std::string(name
))][shorty
.size()];
842 auto entry(entries
.find(std::make_pair(instance
, std::string(name
))));
843 if (entry
== entries
.end())
845 overload
= &entry
->second
[shorty
.size()];
848 auto type(jni
.CallObjectMethod
<jclass
>(method
, Method$getReturnType
));
849 auto primitive(CYJavaGetPrimitive(context
, type
, Class$getName
));
850 auto id(jni
.FromReflectedMethod(method
));
851 overload
->insert(CYJavaSignature(method
, id
, primitive
, shorty
));
857 for (const auto &entry
: entries
) {
858 bool instance(entry
.first
.first
);
859 CYJSString
method(entry
.first
.second
);
860 auto &overload(entry
.second
);
862 CYSetProperty(context
, prototype
, method
, CYPrivate
<CYJavaInstanceMethod
>::Make(context
, utf8
, entry
.first
.second
.c_str(), overload
), kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
);
864 CYSetProperty(context
, constructor
, method
, CYPrivate
<CYJavaStaticMethod
>::Make(context
, utf8
, entry
.first
.second
.c_str(), overload
), kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
);
869 // XXX: for some reason kJSPropertyAttributeDontEnum doesn't work if there's already a property with the same name
870 // by not linking the prototypes until after we set the properties, we hide the parent property from this issue :(
872 if (auto super
= jni
.GetSuperclass(value
)) {
873 JSObjectRef
parent(CYGetJavaClass(context
, super
));
874 CYSetPrototype(context
, constructor
, parent
);
875 CYSetPrototype(context
, prototype
, CYGetProperty(context
, parent
, prototype_s
));
878 CYSetProperty(context
, cy
, name
, constructor
);
882 static void CYCastJavaNumeric(jvalue
&value
, CYJavaPrimitive primitive
, JSContextRef context
, JSValueRef argument
) {
884 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
885 case CYJavaPrimitive ## Type: \
886 value.t = static_cast<j ## type>(CYCastDouble(context, argument)); \
888 CYJavaForEachPrimitive
889 #undef CYJavaForEachPrimitive_
895 static bool CYCastJavaArguments(const CYJavaFrame
&frame
, const CYJavaShorty
&shorty
, JSContextRef context
, const JSValueRef arguments
[], jvalue
*array
) {
896 CYJavaEnv
jni(frame
);
898 for (size_t index(0); index
!= shorty
.size(); ++index
) {
899 JSValueRef
argument(arguments
[index
]);
900 JSType
type(JSValueGetType(context
, argument
));
901 jvalue
&value(array
[index
]);
903 switch (CYJavaPrimitive primitive
= shorty
[index
]) {
904 case CYJavaPrimitiveObject
:
905 // XXX: figure out a way to tie this in to the CYJavaFrame
906 value
.l
= CYCastJavaObject(jni
, context
, argument
).leak();
909 case CYJavaPrimitiveBoolean
:
910 if (type
!= kJSTypeBoolean
)
912 value
.z
= CYCastBool(context
, argument
);
915 case CYJavaPrimitiveCharacter
:
916 if (type
== kJSTypeNumber
)
917 CYCastJavaNumeric(value
, primitive
, context
, argument
);
918 else if (type
!= kJSTypeString
)
921 CYJSString
string(context
, argument
);
922 if (JSStringGetLength(string
) != 1)
925 value
.c
= JSStringGetCharactersPtr(string
)[0];
929 case CYJavaPrimitiveByte
:
930 case CYJavaPrimitiveShort
:
931 case CYJavaPrimitiveInteger
:
932 case CYJavaPrimitiveLong
:
933 case CYJavaPrimitiveFloat
:
934 case CYJavaPrimitiveDouble
:
935 if (type
!= kJSTypeNumber
)
937 CYCastJavaNumeric(value
, primitive
, context
, argument
);
948 static JSValueRef
JavaInstanceMethod_callAsFunction(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
949 auto internal(CYPrivate
<CYJavaInstanceMethod
>::Get(context
, object
));
950 CYJavaObject
*self(CYGetJavaObject(context
, _this
));
951 _assert(self
!= NULL
);
952 CYJavaEnv
jni(self
->value_
);
954 auto overload(internal
->overloads_
.find(count
));
955 if (overload
!= internal
->overloads_
.end())
956 for (auto signature(overload
->second
.begin()); signature
!= overload
->second
.end(); ++signature
) {
957 CYJavaFrame
frame(jni
, count
+ 16);
959 if (!CYCastJavaArguments(frame
, signature
->shorty_
, context
, arguments
, array
))
961 jvalue
*values(array
);
962 switch (signature
->primitive_
) {
963 case CYJavaPrimitiveObject
:
964 return CYCastJSValue(context
, jni
.CallObjectMethodA
<jobject
>(self
->value_
, signature
->method_
, values
));
965 case CYJavaPrimitiveVoid
:
966 jni
.CallVoidMethodA(self
->value_
, signature
->method_
, values
);
967 return CYJSUndefined(context
);
968 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
969 case CYJavaPrimitive ## Type: \
970 return CYJavaCastJSValue(context, jni.Call ## Typ ## MethodA(self->value_, signature->method_, values));
971 CYJavaForEachPrimitive
972 #undef CYJavaForEachPrimitive_
973 default: _assert(false);
977 CYThrow("invalid method call");
980 static JSValueRef
JavaStaticMethod_callAsFunction(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
981 auto internal(CYPrivate
<CYJavaStaticMethod
>::Get(context
, object
));
982 CYJavaClass
*table(CYGetJavaTable(context
, _this
));
983 CYJavaEnv
jni(table
->value_
);
985 auto overload(internal
->overloads_
.find(count
));
986 if (overload
!= internal
->overloads_
.end())
987 for (auto signature(overload
->second
.begin()); signature
!= overload
->second
.end(); ++signature
) {
988 CYJavaFrame
frame(jni
, count
+ 16);
990 if (!CYCastJavaArguments(frame
, signature
->shorty_
, context
, arguments
, array
))
992 jvalue
*values(array
);
993 switch (signature
->primitive_
) {
994 case CYJavaPrimitiveObject
:
995 return CYCastJSValue(context
, jni
.CallStaticObjectMethodA
<jobject
>(table
->value_
, signature
->method_
, values
));
996 case CYJavaPrimitiveVoid
:
997 jni
.CallStaticVoidMethodA(table
->value_
, signature
->method_
, values
);
998 return CYJSUndefined(context
);
999 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1000 case CYJavaPrimitive ## Type: \
1001 return CYJavaCastJSValue(context, jni.CallStatic ## Typ ## MethodA(table->value_, signature->method_, values));
1002 CYJavaForEachPrimitive
1003 #undef CYJavaForEachPrimitive_
1004 default: _assert(false);
1008 CYThrow("invalid method call");
1011 static JSObjectRef
JavaClass_callAsConstructor(JSContextRef context
, JSObjectRef object
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
1012 auto table(CYPrivate
<CYJavaClass
>::Get(context
, object
));
1013 CYJavaEnv
jni(table
->value_
);
1014 jclass
_class(table
->value_
);
1016 if (table
->interface_
&& count
== 1) {
1017 auto Cycript$
(jni
.FindClass("Cycript"));
1018 auto Cycript$
Make(jni
.GetStaticMethodID(Cycript$
, "proxy", "(Ljava/lang/Class;LCycript$Wrapper;)Ljava/lang/Object;"));
1019 return CYCastJSObject(context
, jni
.CallObjectMethod
<jobject
>(Cycript$
, Cycript$Make
, _class
, CYCastJavaObject(jni
, context
, CYCastJSObject(context
, arguments
[0])).get()));
1022 auto overload(table
->overloads_
.find(count
));
1023 if (overload
!= table
->overloads_
.end())
1024 for (auto signature(overload
->second
.begin()); signature
!= overload
->second
.end(); ++signature
) {
1025 CYJavaFrame
frame(jni
, count
+ 16);
1026 jvalue array
[count
];
1027 if (!CYCastJavaArguments(frame
, signature
->shorty_
, context
, arguments
, array
))
1029 jvalue
*values(array
);
1030 auto object(jni
.NewObjectA(_class
, signature
->method_
, values
));
1031 return CYCastJSObject(context
, object
);
1034 CYThrow("invalid constructor call");
1037 static bool JavaStaticInterior_hasProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
) {
1038 auto internal(CYPrivate
<CYJavaStaticInterior
>::Get(context
, object
));
1039 CYJavaClass
*table(internal
->table_
);
1041 auto name(CYPoolUTF8String(pool
, context
, property
));
1042 auto field(table
->static_
.find(name
));
1043 if (field
== table
->static_
.end())
1048 static JSValueRef
JavaStaticInterior_getProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1049 auto internal(CYPrivate
<CYJavaStaticInterior
>::Get(context
, object
));
1050 CYJavaClass
*table(internal
->table_
);
1051 CYJavaEnv
jni(table
->value_
);
1053 auto name(CYPoolUTF8String(pool
, context
, property
));
1054 auto field(table
->static_
.find(name
));
1055 if (field
== table
->static_
.end())
1058 switch (field
->second
.primitive_
) {
1059 case CYJavaPrimitiveObject
:
1060 return CYCastJSValue(context
, jni
.GetStaticObjectField
<jobject
>(table
->value_
, field
->second
.field_
));
1061 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1062 case CYJavaPrimitive ## Type: \
1063 return CYJavaCastJSValue(context, jni.GetStatic ## Typ ## Field(table->value_, field->second.field_));
1064 CYJavaForEachPrimitive
1065 #undef CYJavaForEachPrimitive_
1066 default: _assert(false);
1070 static bool JavaStaticInterior_setProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef value
, JSValueRef
*exception
) { CYTry
{
1071 auto internal(CYPrivate
<CYJavaStaticInterior
>::Get(context
, object
));
1072 CYJavaClass
*table(internal
->table_
);
1073 CYJavaEnv
jni(table
->value_
);
1075 auto name(CYPoolUTF8String(pool
, context
, property
));
1076 auto field(table
->static_
.find(name
));
1077 if (field
== table
->static_
.end())
1080 switch (field
->second
.primitive_
) {
1081 case CYJavaPrimitiveObject
:
1082 jni
.SetStaticObjectField(table
->value_
, field
->second
.field_
, CYCastJavaObject(jni
, context
, value
));
1083 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1084 case CYJavaPrimitive ## Type: \
1085 jni.SetStatic ## Typ ## Field(table->value_, field->second.field_, CYCastDouble(context, value)); \
1087 CYJavaForEachPrimitive
1088 #undef CYJavaForEachPrimitive_
1089 default: _assert(false);
1095 static void JavaStaticInterior_getPropertyNames(JSContextRef context
, JSObjectRef object
, JSPropertyNameAccumulatorRef names
) {
1096 auto internal(CYPrivate
<CYJavaStaticInterior
>::Get(context
, object
));
1097 CYJavaClass
*table(internal
->table_
);
1098 for (const auto &field
: table
->static_
)
1099 JSPropertyNameAccumulatorAddName(names
, CYJSString(field
.first
));
1102 static JSValueRef
JavaClass_getProperty_class(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1103 auto table(CYPrivate
<CYJavaClass
>::Get(context
, object
));
1104 return CYCastJSValue(context
, table
->value_
);
1107 static bool JavaInterior_hasProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
) {
1108 auto internal(CYPrivate
<CYJavaInterior
>::Get(context
, object
));
1109 CYJavaClass
*table(internal
->table_
);
1111 auto name(CYPoolUTF8String(pool
, context
, property
));
1112 auto field(table
->instance_
.find(name
));
1113 if (field
== table
->instance_
.end())
1118 static JSValueRef
JavaInterior_getProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1119 auto internal(CYPrivate
<CYJavaInterior
>::Get(context
, object
));
1120 CYJavaEnv
jni(internal
->value_
);
1121 CYJavaClass
*table(internal
->table_
);
1123 auto name(CYPoolUTF8String(pool
, context
, property
));
1124 auto field(table
->instance_
.find(name
));
1125 if (field
== table
->instance_
.end())
1128 switch (field
->second
.primitive_
) {
1129 case CYJavaPrimitiveObject
:
1130 return CYCastJSValue(context
, jni
.GetObjectField
<jobject
>(internal
->value_
, field
->second
.field_
));
1131 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1132 case CYJavaPrimitive ## Type: \
1133 return CYJavaCastJSValue(context, jni.Get ## Typ ## Field(internal->value_, field->second.field_));
1134 CYJavaForEachPrimitive
1135 #undef CYJavaForEachPrimitive_
1136 default: _assert(false);
1140 static bool JavaInterior_setProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef value
, JSValueRef
*exception
) { CYTry
{
1141 auto internal(CYPrivate
<CYJavaInterior
>::Get(context
, object
));
1142 CYJavaEnv
jni(internal
->value_
);
1143 CYJavaClass
*table(internal
->table_
);
1145 auto name(CYPoolUTF8String(pool
, context
, property
));
1146 auto field(table
->instance_
.find(name
));
1147 if (field
== table
->instance_
.end())
1150 switch (field
->second
.primitive_
) {
1151 case CYJavaPrimitiveObject
:
1152 jni
.SetObjectField(table
->value_
, field
->second
.field_
, CYCastJavaObject(jni
, context
, value
));
1153 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1154 case CYJavaPrimitive ## Type: \
1155 jni.Set ## Typ ## Field(table->value_, field->second.field_, CYCastDouble(context, value)); \
1157 CYJavaForEachPrimitive
1158 #undef CYJavaForEachPrimitive_
1159 default: _assert(false);
1165 static void JavaInterior_getPropertyNames(JSContextRef context
, JSObjectRef object
, JSPropertyNameAccumulatorRef names
) {
1166 auto internal(CYPrivate
<CYJavaInterior
>::Get(context
, object
));
1167 CYJavaClass
*table(internal
->table_
);
1168 for (const auto &field
: table
->instance_
)
1169 JSPropertyNameAccumulatorAddName(names
, CYJSString(field
.first
));
1172 static JSValueRef
JavaObject_getProperty_constructor(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1173 auto internal(CYPrivate
<CYJavaObject
>::Get(context
, object
));
1174 CYJavaEnv
jni(internal
->value_
);
1175 return CYGetJavaClass(context
, jni
.GetObjectClass(internal
->value_
));
1178 static JSValueRef JavaClass_getProperty_$
cyi(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1179 auto internal(CYPrivate
<CYJavaClass
>::Get(context
, object
));
1180 return CYPrivate
<CYJavaStaticInterior
>::Make(context
, internal
->value_
, internal
);
1183 static JSValueRef JavaObject_getProperty_$
cyi(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1184 auto internal(CYPrivate
<CYJavaObject
>::Get(context
, object
));
1185 return CYPrivate
<CYJavaInterior
>::Make(context
, internal
->value_
, internal
->table_
);
1188 static JSValueRef
JavaClass_callAsFunction_toCYON(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
1189 auto internal(CYPrivate
<CYJavaClass
>::Get(context
, _this
));
1190 CYJavaEnv
jni(internal
->value_
);
1191 auto Class$
(jni
.FindClass("java/lang/Class"));
1192 auto Class$
getCanonicalName(jni
.GetMethodID(Class$
, "getCanonicalName", "()Ljava/lang/String;"));
1193 return CYCastJSValue(context
, CYJSString(jni
.CallObjectMethod
<jstring
>(internal
->value_
, Class$getCanonicalName
)));
1196 static JSValueRef
JavaMethod_callAsFunction_toCYON(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
1197 auto internal(CYPrivate
<CYJavaMethod
>::Get(context
, _this
));
1198 std::ostringstream cyon
;
1200 cyon
<< internal
->type_
<< "." << internal
->name_
;
1203 for (auto overload(internal
->overloads_
.begin()); overload
!= internal
->overloads_
.end(); ++overload
)
1204 for (auto signature(overload
->second
.begin()); signature
!= overload
->second
.end(); ++signature
) {
1209 auto string(CYCastJavaString(signature
->reflected_
));
1210 cyon
<< CYJavaUTF8String(string
);
1213 return CYCastJSValue(context
, CYJSString(cyon
.str()));
1216 static JSValueRef
JavaArray_getProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1217 auto internal(CYPrivate
<CYJavaArray
>::Get(context
, object
));
1218 CYJavaEnv
jni(internal
->value_
);
1219 if (JSStringIsEqual(property
, length_s
))
1220 return CYCastJSValue(context
, jni
.GetArrayLength(internal
->value_
));
1224 if (!CYGetOffset(pool
, context
, property
, offset
))
1227 if (internal
->primitive_
== CYJavaPrimitiveObject
)
1228 return CYCastJSValue(context
, jni
.GetObjectArrayElement
<jobject
>(static_cast<jobjectArray
>(internal
->value_
.value_
), offset
));
1229 else switch (internal
->primitive_
) {
1230 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1231 case CYJavaPrimitive ## Type: { \
1232 j ## type element; \
1233 jni.Get ## Typ ## ArrayRegion(static_cast<j ## type ## Array>(internal->value_.value_), offset, 1, &element); \
1234 return CYJavaCastJSValue(context, element); \
1236 CYJavaForEachPrimitive
1237 #undef CYJavaForEachPrimitive_
1238 default: _assert(false);
1242 static bool JavaArray_setProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef value
, JSValueRef
*exception
) { CYTry
{
1243 auto internal(CYPrivate
<CYJavaArray
>::Get(context
, object
));
1244 CYJavaEnv
jni(internal
->value_
);
1248 if (!CYGetOffset(pool
, context
, property
, offset
))
1251 if (internal
->primitive_
== CYJavaPrimitiveObject
)
1252 jni
.SetObjectArrayElement(static_cast<jobjectArray
>(internal
->value_
.value_
), offset
, CYCastJavaObject(jni
, context
, value
));
1253 else switch (internal
->primitive_
) {
1254 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1255 case CYJavaPrimitive ## Type: { \
1256 j ## type element; \
1257 jni.Get ## Typ ## ArrayRegion(static_cast<j ## type ## Array>(internal->value_.value_), offset, 1, &element); \
1258 return CYJavaCastJSValue(context, element); \
1260 CYJavaForEachPrimitive
1261 #undef CYJavaForEachPrimitive_
1262 default: _assert(false);
1268 static JNIEnv
*GetJNI(JSContextRef context
, JNIEnv
*&env
);
1270 static JSValueRef
JavaPackage_callAsFunction_toCYON(JSContextRef context
, JSObjectRef object
, JSObjectRef _this
, size_t count
, const JSValueRef arguments
[], JSValueRef
*exception
) { CYTry
{
1271 auto internal(CYPrivate
<CYJavaPackage
>::Get(context
, _this
));
1272 std::ostringstream name
;
1273 for (auto &package
: internal
->package_
)
1274 name
<< package
<< '.';
1276 return CYCastJSValue(context
, CYJSString(name
.str()));
1279 static bool CYJavaPackage_hasProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
) {
1283 static JSValueRef
CYJavaPackage_getProperty(JSContextRef context
, JSObjectRef object
, JSStringRef property
, JSValueRef
*exception
) { CYTry
{
1284 auto internal(CYPrivate
<CYJavaPackage
>::Get(context
, object
));
1285 CYJavaPackage::Path
package(internal
->package_
);
1288 const char *next(CYPoolCString(pool
, context
, property
));
1290 std::ostringstream name
;
1291 for (auto &package
: internal
->package_
)
1292 name
<< package
<< '/';
1295 if (internal
->jni_
== NULL
)
1296 GetJNI(context
, internal
->jni_
);
1297 JNIEnv
*jni(internal
->jni_
);
1299 if (auto _class
= jni
->FindClass(name
.str().c_str()))
1300 return CYGetJavaClass(context
, CYJavaLocal
<jclass
>(jni
, _class
));
1301 jni
->ExceptionClear();
1303 package
.push_back(next
);
1304 return CYPrivate
<CYJavaPackage
>::Make(context
, jni
, package
);
1307 static void Cycript_delete(JNIEnv
*env
, jclass api
, jlong jprotect
) { CYJavaTry
{
1311 static jobject
Cycript_handle(JNIEnv
*env
, jclass api
, jlong jprotect
, jstring property
, jobjectArray jarguments
) { CYJavaTry
{
1312 JSValueRef
function(CYGetProperty(context
, object
, CYJSString(CYJavaRef
<jstring
>(jni
, property
))));
1313 if (JSValueIsUndefined(context
, function
))
1316 size_t count(jarguments
== NULL
? 0 : jni
.GetArrayLength(jarguments
));
1317 JSValueRef arguments
[count
];
1318 for (size_t index(0); index
!= count
; ++index
)
1319 arguments
[index
] = CYCastJSValue(context
, jni
.GetObjectArrayElement
<jobject
>(jarguments
, index
));
1321 return CYCastJavaObject(jni
, context
, CYCallAsFunction(context
, CYCastJSObject(context
, function
), object
, count
, arguments
)).leak();
1322 } CYJavaCatch(NULL
) }
1324 static JNINativeMethod Cycript_
[] = {
1325 {(char *) "delete", (char *) "(J)V", (void *) &Cycript_delete
},
1326 {(char *) "handle", (char *) "(JLjava/lang/String;[Ljava/lang/Object;)Ljava/lang/Object;", (void *) &Cycript_handle
},
1329 template <typename Type_
>
1330 static _finline
void dlset(Type_
&function
, const char *name
, void *handle
) {
1331 function
= reinterpret_cast<Type_
>(dlsym(handle
, name
));
1334 jint
CYJavaVersion(JNI_VERSION_1_4
);
1336 static JavaVM
*CYGetJavaVM(jint (*$JNI_GetCreatedJavaVMs
)(JavaVM
**, jsize
, jsize
*)) {
1338 JavaVM
*jvms
[capacity
];
1340 _jnicall($
JNI_GetCreatedJavaVMs(jvms
, capacity
, &size
));
1346 static JavaVM
*CYGetJavaVM(JSContextRef context
) {
1348 void *handle(RTLD_DEFAULT
);
1349 std::string library
;
1351 jint (*$JNI_GetCreatedJavaVMs
)(JavaVM
**jvms
, jsize capacity
, jsize
*size
);
1352 dlset($JNI_GetCreatedJavaVMs
, "JNI_GetCreatedJavaVMs", handle
);
1354 if ($JNI_GetCreatedJavaVMs
!= NULL
) {
1355 if (JavaVM
*jvm
= CYGetJavaVM($JNI_GetCreatedJavaVMs
))
1358 std::vector
<const char *> guesses
;
1361 char android
[PROP_VALUE_MAX
];
1362 if (__system_property_get("persist.sys.dalvik.vm.lib", android
) != 0)
1363 guesses
.push_back(android
);
1366 guesses
.push_back("/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/jli/libjli.dylib");
1367 //guesses.push_back("/System/Library/Frameworks/JavaVM.framework/JavaVM");
1368 guesses
.push_back("libjvm.dylib");
1370 guesses
.push_back("libart.so");
1371 guesses
.push_back("libdvm.so");
1372 guesses
.push_back("libjvm.so");
1374 for (const char *guess
: guesses
) {
1375 handle
= dlopen(guess
, RTLD_LAZY
| RTLD_GLOBAL
);
1376 if (handle
!= NULL
) {
1382 if (library
.size() == 0)
1385 dlset($JNI_GetCreatedJavaVMs
, "JNI_GetCreatedJavaVMs", handle
);
1386 if (JavaVM
*jvm
= CYGetJavaVM($JNI_GetCreatedJavaVMs
))
1390 std::vector
<JavaVMOption
> options
;
1393 std::ostringstream option
;
1394 option
<< "-Djava.class.path=";
1395 option
<< CYPoolLibraryPath(pool
) << "/libcycript.jar";
1396 if (const char *classpath
= getenv("CLASSPATH"))
1397 option
<< ':' << classpath
;
1398 options
.push_back(JavaVMOption
{pool
.strdup(option
.str().c_str()), NULL
});
1401 // To use libnativehelper to access JNI_GetCreatedJavaVMs, you need JniInvocation.
1402 // ...but there can only be one JniInvocation, and assuradely the other VM has it.
1403 // Essentially, this API makes no sense. We need it for AndroidRuntime, though :/.
1405 if (void *libnativehelper
= dlopen("libnativehelper.so", RTLD_LAZY
| RTLD_GLOBAL
)) {
1406 class JniInvocation$
;
1407 JniInvocation$
*(*JniInvocation$$init$
)(JniInvocation$
*self
)(NULL
);
1408 bool (*JniInvocation$Init
)(JniInvocation$
*self
, const char *library
)(NULL
);
1409 JniInvocation$
*(*JniInvocation$finalize
)(JniInvocation$
*self
)(NULL
);
1411 dlset(JniInvocation$$init$
, "_ZN13JniInvocationC1Ev", libnativehelper
);
1412 dlset(JniInvocation$Init
, "_ZN13JniInvocation4InitEPKc", libnativehelper
);
1413 dlset(JniInvocation$finalize
, "_ZN13JniInvocationD1Ev", libnativehelper
);
1415 if (JniInvocation$$init$
== NULL
)
1416 dlclose(libnativehelper
);
1418 // XXX: we should attach a pool to the VM itself and deallocate this there
1419 //auto invocation(pool.calloc<JniInvocation$>(1, 1024));
1420 //_assert(JniInvocation$finalize != NULL);
1421 //pool.atexit(reinterpret_cast<void (*)(void *)>(JniInvocation$finalize), invocation);
1423 auto invocation(static_cast<JniInvocation$
*>(calloc(1, 1024)));
1424 JniInvocation$$init$
(invocation
);
1426 _assert(JniInvocation$Init
!= NULL
);
1427 JniInvocation$
Init(invocation
, NULL
);
1429 dlset($JNI_GetCreatedJavaVMs
, "JNI_GetCreatedJavaVMs", libnativehelper
);
1430 if (JavaVM
*jvm
= CYGetJavaVM($JNI_GetCreatedJavaVMs
))
1438 if (void *libandroid_runtime
= dlopen("libandroid_runtime.so", RTLD_LAZY
| RTLD_GLOBAL
)) {
1439 class AndroidRuntime$
;
1440 AndroidRuntime$
*(*AndroidRuntime$$init$
)(AndroidRuntime$
*self
, char *args
, unsigned int size
)(NULL
);
1441 int (*AndroidRuntime$startVm
)(AndroidRuntime$
*self
, JavaVM
**jvm
, JNIEnv
**env
)(NULL
);
1442 int (*AndroidRuntime$startReg
)(JNIEnv
*env
)(NULL
);
1443 int (*AndroidRuntime$addOption
)(AndroidRuntime$
*self
, const char *option
, void *extra
)(NULL
);
1444 int (*AndroidRuntime$addVmArguments
)(AndroidRuntime$
*self
, int, const char *const argv
[])(NULL
);
1445 AndroidRuntime$
*(*AndroidRuntime$finalize
)(AndroidRuntime$
*self
)(NULL
);
1447 dlset(AndroidRuntime$$init$
, "_ZN7android14AndroidRuntimeC1EPcj", libandroid_runtime
);
1448 dlset(AndroidRuntime$startVm
, "_ZN7android14AndroidRuntime7startVmEPP7_JavaVMPP7_JNIEnv", libandroid_runtime
);
1449 dlset(AndroidRuntime$startReg
, "_ZN7android14AndroidRuntime8startRegEP7_JNIEnv", libandroid_runtime
);
1450 dlset(AndroidRuntime$addOption
, "_ZN7android14AndroidRuntime9addOptionEPKcPv", libandroid_runtime
);
1451 dlset(AndroidRuntime$addVmArguments
, "_ZN7android14AndroidRuntime14addVmArgumentsEiPKPKc", libandroid_runtime
);
1452 dlset(AndroidRuntime$finalize
, "_ZN7android14AndroidRuntimeD1Ev", libandroid_runtime
);
1454 // XXX: it would also be interesting to attach this to a global pool
1455 AndroidRuntime$
*runtime(pool
.calloc
<AndroidRuntime$
>(1, 1024));
1457 _assert(AndroidRuntime$$init$
!= NULL
);
1458 AndroidRuntime$$init$
(runtime
, NULL
, 0);
1460 if (AndroidRuntime$addOption
== NULL
) {
1461 _assert(AndroidRuntime$addVmArguments
!= NULL
);
1462 std::vector
<const char *> arguments
;
1463 for (const auto &option
: options
)
1464 arguments
.push_back(option
.optionString
);
1465 AndroidRuntime$
addVmArguments(runtime
, arguments
.size(), arguments
.data());
1466 } else for (const auto &option
: options
)
1467 AndroidRuntime$
addOption(runtime
, option
.optionString
, option
.extraInfo
);
1471 _assert(AndroidRuntime$startVm
!= NULL
);
1472 failure
= AndroidRuntime$
startVm(runtime
, &jvm
, &env
);
1473 _assert(failure
== 0);
1475 _assert(AndroidRuntime$startReg
!= NULL
);
1476 failure
= AndroidRuntime$
startReg(env
);
1477 _assert(failure
== 0);
1482 jint (*$JNI_CreateJavaVM
)(JavaVM
**jvm
, void **, void *);
1483 dlset($JNI_CreateJavaVM
, "JNI_CreateJavaVM", handle
);
1485 JavaVMInitArgs args
;
1486 memset(&args
, 0, sizeof(args
));
1487 args
.version
= CYJavaVersion
;
1488 args
.nOptions
= options
.size();
1489 args
.options
= options
.data();
1490 _jnicall($
JNI_CreateJavaVM(&jvm
, reinterpret_cast<void **>(&env
), &args
));
1494 static JNIEnv
*GetJNI(JSContextRef context
, JNIEnv
*&env
) {
1495 auto jvm(CYGetJavaVM(context
));
1496 _assert(jvm
!= NULL
);
1497 _jnicall(jvm
->GetEnv(reinterpret_cast<void **>(&env
), CYJavaVersion
));
1500 // XXX: this happens once per stub :/
1502 auto Cycript$
(jni
.FindClass("Cycript"));
1503 jni
.RegisterNatives(Cycript$
, Cycript_
, sizeof(Cycript_
) / sizeof(Cycript_
[0]));
1505 JSObjectRef
java(CYGetCachedObject(context
, CYJSString("Java")));
1506 JSValueRef arguments
[1];
1507 arguments
[0] = CYCastJSValue(context
, CYJSString("setup"));
1508 CYCallAsFunction(context
, CYCastJSObject(context
, CYGetProperty(context
, java
, CYJSString("emit"))), java
, 1, arguments
);
1513 static JSStaticValue JavaClass_staticValues
[3] = {
1514 {"class", &JavaClass_getProperty_class
, NULL
, kJSPropertyAttributeReadOnly
| kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1515 {"$cyi", &JavaClass_getProperty_$cyi
, NULL
, kJSPropertyAttributeReadOnly
| kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1516 {NULL
, NULL
, NULL
, 0}
1519 static JSStaticFunction JavaClass_staticFunctions
[2] = {
1520 {"toCYON", &JavaClass_callAsFunction_toCYON
, kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1524 static JSStaticValue JavaObject_staticValues
[3] = {
1525 {"constructor", &JavaObject_getProperty_constructor
, NULL
, kJSPropertyAttributeReadOnly
| kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1526 {"$cyi", &JavaObject_getProperty_$cyi
, NULL
, kJSPropertyAttributeReadOnly
| kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1527 {NULL
, NULL
, NULL
, 0}
1530 static JSStaticFunction JavaInstanceMethod_staticFunctions
[2] = {
1531 {"toCYON", &JavaMethod_callAsFunction_toCYON
, kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1535 static JSStaticFunction JavaStaticMethod_staticFunctions
[2] = {
1536 {"toCYON", &JavaMethod_callAsFunction_toCYON
, kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1540 static JSStaticFunction JavaPackage_staticFunctions
[2] = {
1541 {"toCYON", &JavaPackage_callAsFunction_toCYON
, kJSPropertyAttributeDontEnum
| kJSPropertyAttributeDontDelete
},
1545 void CYJava_Initialize() {
1546 Primitives_
.insert(std::make_pair("void", CYJavaPrimitiveVoid
));
1547 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1548 Primitives_.insert(std::make_pair(#type, CYJavaPrimitive ## Type));
1549 CYJavaForEachPrimitive
1550 #undef CYJavaForEachPrimitive_
1552 JSClassDefinition definition
;
1554 definition
= kJSClassDefinitionEmpty
;
1555 definition
.className
= "JavaClass";
1556 definition
.staticValues
= JavaClass_staticValues
;
1557 definition
.staticFunctions
= JavaClass_staticFunctions
;
1558 definition
.callAsConstructor
= &JavaClass_callAsConstructor
;
1559 definition
.finalize
= &CYFinalize
;
1560 CYPrivate
<CYJavaClass
>::Class_
= JSClassCreate(&definition
);
1562 definition
= kJSClassDefinitionEmpty
;
1563 definition
.attributes
= kJSClassAttributeNoAutomaticPrototype
;
1564 definition
.className
= "JavaInterior";
1565 definition
.hasProperty
= &JavaInterior_hasProperty
;
1566 definition
.getProperty
= &JavaInterior_getProperty
;
1567 definition
.setProperty
= &JavaInterior_setProperty
;
1568 definition
.getPropertyNames
= &JavaInterior_getPropertyNames
;
1569 definition
.finalize
= &CYFinalize
;
1570 CYPrivate
<CYJavaInterior
>::Class_
= JSClassCreate(&definition
);
1572 definition
= kJSClassDefinitionEmpty
;
1573 definition
.className
= "JavaMethod";
1574 definition
.finalize
= &CYFinalize
;
1575 CYPrivate
<CYJavaMethod
>::Class_
= JSClassCreate(&definition
);
1577 definition
= kJSClassDefinitionEmpty
;
1578 definition
.className
= "JavaInstanceMethod";
1579 definition
.parentClass
= CYPrivate
<CYJavaMethod
>::Class_
;
1580 definition
.staticFunctions
= JavaInstanceMethod_staticFunctions
;
1581 definition
.callAsFunction
= &JavaInstanceMethod_callAsFunction
;
1582 CYPrivate
<CYJavaInstanceMethod
>::Class_
= JSClassCreate(&definition
);
1584 definition
= kJSClassDefinitionEmpty
;
1585 definition
.className
= "JavaStaticMethod";
1586 definition
.parentClass
= CYPrivate
<CYJavaMethod
>::Class_
;
1587 definition
.staticFunctions
= JavaStaticMethod_staticFunctions
;
1588 definition
.callAsFunction
= &JavaStaticMethod_callAsFunction
;
1589 CYPrivate
<CYJavaStaticMethod
>::Class_
= JSClassCreate(&definition
);
1591 definition
= kJSClassDefinitionEmpty
;
1592 definition
.attributes
= kJSClassAttributeNoAutomaticPrototype
;
1593 definition
.className
= "JavaObject";
1594 definition
.staticValues
= JavaObject_staticValues
;
1595 definition
.finalize
= &CYFinalize
;
1596 CYPrivate
<CYJavaObject
>::Class_
= JSClassCreate(&definition
);
1598 definition
= kJSClassDefinitionEmpty
;
1599 definition
.className
= "JavaArray";
1600 definition
.getProperty
= &JavaArray_getProperty
;
1601 definition
.setProperty
= &JavaArray_setProperty
;
1602 definition
.finalize
= &CYFinalize
;
1603 CYPrivate
<CYJavaArray
>::Class_
= JSClassCreate(&definition
);
1605 definition
= kJSClassDefinitionEmpty
;
1606 definition
.className
= "JavaPackage";
1607 definition
.staticFunctions
= JavaPackage_staticFunctions
;
1608 definition
.hasProperty
= &CYJavaPackage_hasProperty
;
1609 definition
.getProperty
= &CYJavaPackage_getProperty
;
1610 definition
.finalize
= &CYFinalize
;
1611 CYPrivate
<CYJavaPackage
>::Class_
= JSClassCreate(&definition
);
1613 definition
= kJSClassDefinitionEmpty
;
1614 definition
.attributes
= kJSClassAttributeNoAutomaticPrototype
;
1615 definition
.className
= "JavaStaticInterior";
1616 definition
.hasProperty
= &JavaStaticInterior_hasProperty
;
1617 definition
.getProperty
= &JavaStaticInterior_getProperty
;
1618 definition
.setProperty
= &JavaStaticInterior_setProperty
;
1619 definition
.getPropertyNames
= &JavaStaticInterior_getPropertyNames
;
1620 definition
.finalize
= &CYFinalize
;
1621 CYPrivate
<CYJavaStaticInterior
>::Class_
= JSClassCreate(&definition
);
1624 void CYJava_SetupContext(JSContextRef context
) {
1625 JSObjectRef
global(CYGetGlobalObject(context
));
1626 JSObjectRef
cy(CYCastJSObject(context
, CYGetProperty(context
, global
, cy_s
)));
1627 JSObjectRef
cycript(CYCastJSObject(context
, CYGetProperty(context
, global
, CYJSString("Cycript"))));
1628 JSObjectRef
all(CYCastJSObject(context
, CYGetProperty(context
, cycript
, CYJSString("all"))));
1629 //JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
1631 JSObjectRef
Java(JSObjectMake(context
, NULL
, NULL
));
1632 CYSetProperty(context
, cycript
, CYJSString("Java"), Java
);
1633 CYSetProperty(context
, cy
, CYJSString("Java"), Java
);
1635 JSObjectRef
Packages(CYPrivate
<CYJavaPackage
>::Make(context
, nullptr, CYJavaPackage::Path()));
1636 CYSetProperty(context
, all
, CYJSString("Packages"), Packages
, kJSPropertyAttributeDontEnum
);
1638 for (auto name
: (const char *[]) {"java", "javax", "android", "com", "net", "org"}) {
1639 CYJSString
js(name
);
1640 CYSetProperty(context
, all
, js
, CYPrivate
<CYJavaPackage
>::Make(context
, nullptr, CYJavaPackage::Path(1, name
)), kJSPropertyAttributeDontEnum
);
1644 static CYHook CYJavaHook
= {
1649 &CYJava_SetupContext
,
1653 CYRegisterHook
CYJava(&CYJavaHook
);