]> git.saurik.com Git - cycript.git/blob - Java/Execute.cpp
ee2d2bee15e18cc3d508b6f5627609037736d2b9
[cycript.git] / Java / Execute.cpp
1 /* Cycript - The Truly Universal Scripting Language
2 * Copyright (C) 2009-2016 Jay Freeman (saurik)
3 */
4
5 /* GNU Affero General Public License, Version 3 {{{ */
6 /*
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.
11
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.
16
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/>.
19 **/
20 /* }}} */
21
22 #include <map>
23 #include <sstream>
24 #include <vector>
25
26 #include <dlfcn.h>
27
28 #if defined(__APPLE__) && !defined(__arm__)
29 #include <JavaVM/jni.h>
30 #else
31 #include <jni.h>
32 #endif
33
34 #ifdef __ANDROID__
35 // XXX: this is deprecated?!?!?!?!?!?!
36 #include <sys/system_properties.h>
37 #endif
38
39 #include "cycript.hpp"
40 #include "Error.hpp"
41 #include "Execute.hpp"
42 #include "Internal.hpp"
43 #include "JavaScript.hpp"
44 #include "Pooling.hpp"
45
46 #define _jnicall(expr) ({ \
47 jint _value(expr); \
48 if (_value != JNI_OK) \
49 CYThrow("_jnicall(%s) == %d", #expr, _value); \
50 })
51
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)); \
57 } \
58 _value; })
59
60 #define _envcallv(jni, expr) do { \
61 jni->expr; \
62 if (jthrowable _error = jni->ExceptionOccurred()) { \
63 jni->ExceptionClear(); \
64 throw CYJavaError(CYJavaLocal<jthrowable>(jni, _error)); \
65 } \
66 } while (false)
67
68 #define CYJavaTry \
69 CYJavaEnv jni(env); \
70 auto &protect(*reinterpret_cast<CYProtect *>(jprotect)); \
71 _disused JSContextRef context(protect); \
72 _disused JSObjectRef object(protect); \
73 try
74 #define CYJavaCatch(value) \
75 catch (const CYException &error) { \
76 jni->Throw(CYCastJavaObject(jni, context, error.CastJSValue(context, "Error")).cast<jthrowable>()); \
77 return value; \
78 }
79
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)
89
90 enum CYJavaPrimitive : char {
91 CYJavaPrimitiveObject,
92 CYJavaPrimitiveVoid,
93 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
94 CYJavaPrimitive ## Type,
95 CYJavaForEachPrimitive
96 #undef CYJavaForEachPrimitive_
97 };
98
99 template <typename Type_>
100 struct IsJavaPrimitive { static const bool value = false; };
101
102 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
103 template <> \
104 struct IsJavaPrimitive<j ## type> { static const bool value = true; };
105 CYJavaForEachPrimitive
106 #undef CYJavaForEachPrimitive_
107
108 // Java References {{{
109 template <typename Value_>
110 struct CYJavaRef {
111 JNIEnv *jni_;
112 Value_ value_;
113
114 _finline CYJavaRef(JNIEnv *jni, Value_ value) :
115 jni_(jni),
116 value_(value)
117 {
118 }
119
120 _finline operator Value_() const {
121 return value_;
122 }
123
124 _finline JNIEnv *jni() const {
125 return jni_;
126 }
127
128 // XXX: this is only needed to support CYJavaEnv relying on C variadics
129 _finline Value_ get() const {
130 return value_;
131 }
132
133 template <typename Other_>
134 _finline CYJavaRef<Other_> cast() const {
135 return {jni_, static_cast<Other_>(value_)};
136 }
137
138 // XXX: this should be tied into CYJavaFrame
139 Value_ leak() {
140 Value_ value(value_);
141 value_ = NULL;
142 return value;
143 }
144 };
145
146 template <typename Value_, void (JNIEnv::*Delete_)(jobject)>
147 struct CYJavaDelete :
148 CYJavaRef<Value_>
149 {
150 _finline CYJavaDelete(JNIEnv *jni, Value_ value) :
151 CYJavaRef<Value_>(jni, value)
152 {
153 }
154
155 void clear() {
156 if (this->value_ != NULL)
157 (this->jni_->*Delete_)(this->value_);
158 this->value_ = NULL;
159 }
160
161 ~CYJavaDelete() {
162 clear();
163 }
164 };
165
166 template <typename Value_>
167 struct CYJavaGlobal :
168 CYJavaDelete<Value_, &JNIEnv::DeleteGlobalRef>
169 {
170 typedef CYJavaDelete<Value_, &JNIEnv::DeleteGlobalRef> CYJavaBase;
171
172 CYJavaGlobal() :
173 CYJavaBase(NULL, NULL)
174 {
175 }
176
177 template <typename Other_>
178 CYJavaGlobal(const CYJavaRef<Other_> &other) :
179 CYJavaBase(other.jni_, static_cast<Other_>(other.jni_->NewGlobalRef(other.value_)))
180 {
181 }
182
183 CYJavaGlobal(const CYJavaGlobal<Value_> &other) :
184 CYJavaGlobal(static_cast<const CYJavaRef<Value_> &>(other))
185 {
186 }
187
188 CYJavaGlobal(CYJavaGlobal &&value) :
189 CYJavaBase(value.jni_, value.value_)
190 {
191 value.value_ = NULL;
192 }
193 };
194
195 template <typename Value_>
196 struct CYJavaLocal :
197 CYJavaDelete<Value_, &JNIEnv::DeleteLocalRef>
198 {
199 typedef CYJavaDelete<Value_, &JNIEnv::DeleteLocalRef> CYJavaBase;
200
201 CYJavaLocal() :
202 CYJavaBase(NULL, NULL)
203 {
204 }
205
206 CYJavaLocal(JNIEnv *jni, Value_ value) :
207 CYJavaBase(jni, value)
208 {
209 }
210
211 template <typename Other_>
212 CYJavaLocal(const CYJavaRef<Other_> &other) :
213 CYJavaLocal(other.jni_, static_cast<Other_>(other.jni_->NewLocalRef(other.value_)))
214 {
215 }
216
217 template <typename Other_>
218 CYJavaLocal(CYJavaRef<Other_> &&other) :
219 CYJavaLocal(other.jni_, other.value_)
220 {
221 other.value_ = NULL;
222 }
223
224 CYJavaLocal(CYJavaLocal &&other) :
225 CYJavaLocal(static_cast<CYJavaRef<Value_> &&>(other))
226 {
227 }
228
229 template <typename Other_>
230 CYJavaLocal &operator =(CYJavaLocal<Other_> &&other) {
231 this->clear();
232 this->jni_ = other.jni_;
233 this->value_ = other.value_;
234 other.value_ = NULL;
235 return *this;
236 }
237 };
238 // }}}
239 // Java Strings {{{
240 static CYJavaLocal<jstring> CYCastJavaString(const CYJavaRef<jobject> &value);
241
242 class CYJavaUTF8String :
243 public CYUTF8String
244 {
245 private:
246 const CYJavaRef<jstring> &value_;
247
248 public:
249 CYJavaUTF8String(const CYJavaRef<jstring> &value) :
250 value_(value)
251 {
252 _assert(value);
253 JNIEnv *jni(value.jni());
254 size = jni->GetStringUTFLength(value);
255 data = jni->GetStringUTFChars(value, NULL);
256 }
257
258 CYJavaUTF8String(CYJavaRef<jstring> &&) = delete;
259
260 ~CYJavaUTF8String() {
261 JNIEnv *jni(value_.jni());
262 jni->ReleaseStringUTFChars(value_, data);
263 }
264
265 CYJavaUTF8String(const CYJavaUTF8String &) = delete;
266 };
267
268 CYJavaUTF8String CYCastUTF8String(const CYJavaRef<jstring> &value) {
269 return {value};
270 }
271
272 JSStringRef CYCopyJSString(const CYJavaRef<jstring> &value) {
273 return CYCopyJSString(CYCastUTF8String(value));
274 }
275 // }}}
276 // Java Error {{{
277 struct CYJavaError :
278 CYException
279 {
280 CYJavaGlobal<jthrowable> value_;
281
282 CYJavaError(const CYJavaRef<jthrowable> &value) :
283 value_(value)
284 {
285 }
286
287 virtual const char *PoolCString(CYPool &pool) const {
288 auto string(CYCastJavaString(value_.cast<jobject>()));
289 return CYPoolCString(pool, CYJavaUTF8String(string));
290 }
291
292 virtual JSValueRef CastJSValue(JSContextRef context, const char *name) const;
293 };
294 // }}}
295
296 struct CYJavaFrame {
297 JNIEnv *jni_;
298
299 CYJavaFrame(JNIEnv *jni, jint capacity) :
300 jni_(jni)
301 {
302 _assert(jni->PushLocalFrame(capacity) == 0);
303 }
304
305 ~CYJavaFrame() {
306 operator ()(NULL);
307 }
308
309 operator JNIEnv *() const {
310 return jni_;
311 }
312
313 jobject operator ()(jobject object) {
314 JNIEnv *jni(jni_);
315 jni_ = NULL;
316 return jni->PopLocalFrame(object);
317 }
318 };
319
320 struct CYJavaEnv {
321 private:
322 JNIEnv *jni;
323
324 public:
325 CYJavaEnv(JNIEnv *jni) :
326 jni(jni)
327 {
328 }
329
330 template <typename Other_>
331 CYJavaEnv(const CYJavaRef<Other_> &value) :
332 jni(value.jni())
333 {
334 }
335
336 operator JNIEnv *() const {
337 return jni;
338 }
339
340 JNIEnv *operator ->() const {
341 return jni;
342 }
343
344 CYJavaLocal<jclass> FindClass(const char *name) const {
345 return {jni, _envcall(jni, FindClass(name))};
346 }
347
348 CYJavaLocal<jclass> GetObjectClass(jobject object) const {
349 return {jni, _envcall(jni, GetObjectClass(object))};
350 }
351
352 CYJavaLocal<jclass> GetSuperclass(jclass _class) const {
353 return {jni, _envcall(jni, GetSuperclass(_class))};
354 }
355
356 CYJavaLocal<jobject> NewObject(jclass _class, jmethodID method, ...) const {
357 va_list args;
358 va_start(args, method);
359 jobject object(_envcall(jni, NewObjectV(_class, method, args)));
360 va_end(args);
361 return {jni, object};
362 }
363
364 CYJavaLocal<jobject> NewObjectA(jclass _class, jmethodID method, jvalue *args) const {
365 return {jni, _envcall(jni, NewObjectA(_class, method, args))};
366 }
367
368 CYJavaLocal<jstring> NewString(const jchar *data, jsize size) const {
369 return {jni, _envcall(jni, NewString(data, size))};
370 }
371
372 #define CYJavaEnv_(Code) \
373 template <typename... Args_> \
374 void Code(Args_ &&... args) const { \
375 _envcallv(jni, Code(cy::Forward<Args_>(args)...)); \
376 }
377
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_
384
385 CYJavaEnv_(CallVoidMethod)
386 CYJavaEnv_(CallStaticVoidMethod)
387 CYJavaEnv_(CallVoidMethodA)
388 CYJavaEnv_(CallStaticVoidMethodA)
389 CYJavaEnv_(SetObjectArrayElement)
390 CYJavaEnv_(SetObjectField)
391 CYJavaEnv_(SetStaticObjectField)
392 #undef CYJavaEnv_
393
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)...)); \
398 }
399
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_
409
410 CYJavaEnv_(FromReflectedField)
411 CYJavaEnv_(FromReflectedMethod)
412 CYJavaEnv_(GetArrayLength)
413 CYJavaEnv_(GetMethodID)
414 CYJavaEnv_(GetStaticMethodID)
415 CYJavaEnv_(IsSameObject)
416 CYJavaEnv_(RegisterNatives)
417 #undef CYJavaEnv_
418
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)...)))}; \
423 }
424
425 CYJavaEnv_(CallObjectMethod)
426 CYJavaEnv_(CallStaticObjectMethod)
427 CYJavaEnv_(CallObjectMethodA)
428 CYJavaEnv_(CallStaticObjectMethodA)
429 CYJavaEnv_(GetObjectArrayElement)
430 CYJavaEnv_(GetObjectField)
431 CYJavaEnv_(GetStaticObjectField)
432 #undef CYJavaEnv_
433 };
434
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);
440 }
441
442 static JSValueRef CYCastJSValue(JSContextRef context, const CYJavaRef<jobject> &value);
443
444 template <typename Other_>
445 static _finline JSValueRef CYCastJSValue(JSContextRef context, const CYJavaRef<Other_> &value) {
446 return CYCastJSValue(context, value.template cast<jobject>());
447 }
448
449 template <typename Type_>
450 static _finline JSValueRef CYJavaCastJSValue(JSContextRef context, Type_ value) {
451 return CYCastJSValue(context, value);
452 }
453
454 static _finline JSValueRef CYJavaCastJSValue(JSContextRef context, jboolean value) {
455 return CYCastJSValue(context, static_cast<bool>(value));
456 }
457
458 JSValueRef CYJavaError::CastJSValue(JSContextRef context, const char *name) const {
459 return CYCastJSValue(context, value_);
460 }
461
462 static std::map<std::string, CYJavaPrimitive> Primitives_;
463
464 static CYJavaPrimitive CYJavaGetPrimitive(JSContextRef context, const CYJavaRef<jclass> &type, jmethodID Class$get$$Name) {
465 CYJavaEnv jni(type);
466 auto string(jni.CallObjectMethod<jstring>(type, Class$get$$Name));
467 _assert(string);
468
469 CYJavaUTF8String name(string);
470 auto primitive(Primitives_.find(name));
471 return primitive != Primitives_.end() ? primitive->second : CYJavaPrimitiveObject;
472 }
473
474 typedef std::vector<CYJavaPrimitive> CYJavaShorty;
475
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);
482 return shorty;
483 }
484
485 struct CYJavaField {
486 jfieldID field_;
487 CYJavaPrimitive primitive_;
488 };
489
490 typedef std::map<std::string, CYJavaField> CYJavaFieldMap;
491
492 struct CYJavaSignature {
493 CYJavaGlobal<jobject> reflected_;
494 jmethodID method_;
495 CYJavaPrimitive primitive_;
496 CYJavaShorty shorty_;
497
498 CYJavaSignature(const CYJavaRef<jobject> &reflected, jmethodID method, CYJavaPrimitive primitive, const CYJavaShorty &shorty) :
499 reflected_(reflected),
500 method_(method),
501 primitive_(primitive),
502 shorty_(shorty)
503 {
504 }
505
506 // XXX: the shorty doesn't store enough information
507 bool operator <(const CYJavaSignature &rhs) const {
508 return shorty_ < rhs.shorty_;
509 }
510 };
511
512 typedef std::set<CYJavaSignature> CYJavaOverload;
513 typedef std::map<unsigned, CYJavaOverload> CYJavaOverloads;
514
515 struct CYJavaMethod :
516 CYRoot
517 {
518 CYJavaOverloads overloads_;
519
520 CYJavaMethod(const CYJavaOverloads &overloads) :
521 overloads_(overloads)
522 {
523 }
524 };
525
526 struct CYJavaStaticMethod :
527 CYRoot
528 {
529 CYJavaOverloads overloads_;
530
531 CYJavaStaticMethod(const CYJavaOverloads &overloads) :
532 overloads_(overloads)
533 {
534 }
535 };
536
537 struct CYJavaClass :
538 CYRoot
539 {
540 CYJavaGlobal<jclass> value_;
541 bool interface_;
542
543 CYJavaFieldMap static_;
544 CYJavaFieldMap instance_;
545 CYJavaOverloads overloads_;
546
547 CYJavaClass(const CYJavaRef<jclass> &value, bool interface) :
548 value_(value),
549 interface_(interface)
550 {
551 }
552 };
553
554 static JSObjectRef CYGetJavaClass(JSContextRef context, const CYJavaRef<jclass> &_class);
555
556 struct CYJavaObject :
557 CYRoot
558 {
559 CYJavaGlobal<jobject> value_;
560 CYJavaClass *table_;
561
562 CYJavaObject(const CYJavaRef<jobject> &value, CYJavaClass *table) :
563 value_(value),
564 table_(table)
565 {
566 }
567
568 JSValueRef GetPrototype(JSContextRef context) const;
569 };
570
571 struct CYJavaInterior :
572 CYRoot
573 {
574 CYJavaGlobal<jobject> value_;
575 CYJavaClass *table_;
576
577 CYJavaInterior(const CYJavaRef<jobject> &value, CYJavaClass *table) :
578 value_(value),
579 table_(table)
580 {
581 }
582 };
583
584 struct CYJavaStaticInterior :
585 CYRoot
586 {
587 CYJavaGlobal<jclass> value_;
588 CYJavaClass *table_;
589
590 CYJavaStaticInterior(const CYJavaRef<jclass> &value, CYJavaClass *table) :
591 value_(value),
592 table_(table)
593 {
594 }
595 };
596
597 struct CYJavaArray :
598 CYRoot
599 {
600 CYJavaGlobal<jarray> value_;
601 CYJavaPrimitive primitive_;
602
603 CYJavaArray(const CYJavaRef<jarray> &value, CYJavaPrimitive primitive) :
604 value_(value),
605 primitive_(primitive)
606 {
607 }
608
609 JSValueRef GetPrototype(JSContextRef context) const;
610 };
611
612 struct CYJavaPackage :
613 CYRoot
614 {
615 JNIEnv *jni_;
616
617 typedef std::vector<std::string> Path;
618 Path package_;
619
620 _finline CYJavaPackage(JNIEnv *jni, const Path &package) :
621 jni_(jni),
622 package_(package)
623 {
624 }
625 };
626
627 JSValueRef CYJavaObject::GetPrototype(JSContextRef context) const {
628 CYJavaEnv jni(value_);
629 return CYGetProperty(context, CYGetJavaClass(context, jni.GetObjectClass(value_)), prototype_s);
630 }
631
632 JSValueRef CYJavaArray::GetPrototype(JSContextRef context) const {
633 return CYGetCachedObject(context, CYJSString("Array_prototype"));
634 }
635
636 static JSValueRef CYCastJSValue(JSContextRef context, const CYJavaRef<jobject> &value) {
637 if (!value)
638 return CYJSNull(context);
639 CYJavaEnv jni(value);
640
641 auto _class(jni.GetObjectClass(value));
642 if (jni.IsSameObject(_class, jni.FindClass("java/lang/String")))
643 return CYCastJSValue(context, CYJSString(value.cast<jstring>()));
644
645 auto Class$(jni.FindClass("java/lang/Class"));
646 auto Class$isArray(jni.GetMethodID(Class$, "isArray", "()Z"));
647 if (jni.CallBooleanMethod(_class, Class$isArray)) {
648 auto Class$getComponentType(jni.GetMethodID(Class$, "getComponentType", "()Ljava/lang/Class;"));
649 auto component(jni.CallObjectMethod<jclass>(_class, Class$getComponentType));
650 auto Class$getName(jni.GetMethodID(Class$, "getName", "()Ljava/lang/String;"));
651 return CYPrivate<CYJavaArray>::Make(context, value.cast<jarray>(), CYJavaGetPrimitive(context, component, Class$getName));
652 }
653
654 auto Wrapper$(jni.FindClass("Cycript$Wrapper"));
655 if (jni.IsSameObject(_class, Wrapper$)) {
656 auto Wrapper$getProtect(jni.GetMethodID(Wrapper$, "getProtect", "()J"));
657 auto &protect(*reinterpret_cast<CYProtect *>(jni.CallLongMethod(value, Wrapper$getProtect)));
658 return protect;
659 }
660
661 CYJavaClass *table(reinterpret_cast<CYJavaClass *>(JSObjectGetPrivate(CYGetJavaClass(context, _class))));
662 return CYPrivate<CYJavaObject>::Make(context, value, table);
663 }
664
665 static _finline JSObjectRef CYCastJSObject(JSContextRef context, const CYJavaRef<jobject> &value) {
666 return CYCastJSObject(context, CYCastJSValue(context, value));
667 }
668
669 static CYJavaLocal<jstring> CYCastJavaString(const CYJavaEnv &jni, JSContextRef context, CYUTF16String value) {
670 return jni.NewString(value.data, value.size);
671 }
672
673 static CYJavaLocal<jstring> CYCastJavaString(const CYJavaEnv &jni, JSContextRef context, JSStringRef value) {
674 return CYCastJavaString(jni, context, CYCastUTF16String(value));
675 }
676
677 #define CYCastJava$(T, Type, jtype, Cast) \
678 _disused static CYJavaLocal<jobject> CYCastJava ## Type(const CYJavaEnv &jni, JSContextRef context, JSValueRef value) { \
679 auto Type$(jni.FindClass("java/lang/" #Type)); \
680 auto Type$init$(jni.GetMethodID(Type$, "<init>", "(" #T ")V")); \
681 return jni.NewObject(Type$, Type$init$, static_cast<jtype>(Cast(context, value))); \
682 }
683
684 CYCastJava$(Z, Boolean, jboolean, CYCastBool)
685 CYCastJava$(B, Byte, jbyte, CYCastDouble)
686 CYCastJava$(C, Character, jchar, CYCastDouble)
687 CYCastJava$(S, Short, jshort, CYCastDouble)
688 CYCastJava$(I, Integer, jint, CYCastDouble)
689 CYCastJava$(J, Long, jlong, CYCastDouble)
690 CYCastJava$(F, Float, jfloat, CYCastDouble)
691 CYCastJava$(D, Double, jdouble, CYCastDouble)
692
693 static CYJavaClass *CYGetJavaTable(JSContextRef context, JSObjectRef object) {
694 if (!JSValueIsObjectOfClass(context, object, CYPrivate<CYJavaClass>::Class_))
695 return NULL;
696 return reinterpret_cast<CYJavaClass *>(JSObjectGetPrivate(object));
697 }
698
699 static CYJavaObject *CYGetJavaObject(JSContextRef context, JSObjectRef object) {
700 if (!JSValueIsObjectOfClass(context, object, CYPrivate<CYJavaObject>::Class_))
701 return NULL;
702 return reinterpret_cast<CYJavaObject *>(JSObjectGetPrivate(object));
703 }
704
705 static CYJavaLocal<jobject> CYCastJavaObject(const CYJavaEnv &jni, JSContextRef context, JSObjectRef value) {
706 if (CYJavaObject *internal = CYGetJavaObject(context, value))
707 return internal->value_;
708
709 auto Wrapper$(jni.FindClass("Cycript$Wrapper"));
710 auto Wrapper$$init$(jni.GetMethodID(Wrapper$, "<init>", "(J)V"));
711 CYProtect *protect(new CYProtect(context, value));
712 return jni.NewObject(Wrapper$, Wrapper$$init$, reinterpret_cast<jlong>(protect));
713 }
714
715 static CYJavaLocal<jobject> CYCastJavaObject(const CYJavaEnv &jni, JSContextRef context, JSValueRef value) {
716 switch (JSValueGetType(context, value)) {
717 case kJSTypeNull:
718 return {jni, NULL};
719 case kJSTypeBoolean:
720 return CYCastJavaBoolean(jni, context, value);
721 case kJSTypeNumber:
722 return CYCastJavaDouble(jni, context, value);
723 case kJSTypeString:
724 return CYCastJavaString(jni, context, CYJSString(context, value));
725 case kJSTypeObject:
726 return CYCastJavaObject(jni, context, CYCastJSObject(context, value));
727
728 case kJSTypeUndefined:
729 // XXX: I am currently relying on this for dynamic proxy of void method
730 return {jni, NULL};
731 default:
732 _assert(false);
733 }
734 }
735
736 static JSObjectRef CYGetJavaClass(JSContextRef context, const CYJavaRef<jclass> &value) {
737 CYJavaEnv jni(value);
738 CYJavaFrame frame(jni, 64);
739
740 JSObjectRef global(CYGetGlobalObject(context));
741 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
742
743 auto Class$(jni.FindClass("java/lang/Class"));
744 auto Class$getName(jni.GetMethodID(Class$, "getName", "()Ljava/lang/String;"));
745
746 CYJSString name(jni.CallObjectMethod<jstring>(value, Class$getName));
747 JSValueRef cached(CYGetProperty(context, cy, name));
748 if (!JSValueIsUndefined(context, cached))
749 return CYCastJSObject(context, cached);
750
751 JSObjectRef constructor;
752 JSObjectRef prototype;
753
754 {
755
756 auto Class$isInterface(jni.GetMethodID(Class$, "isInterface", "()Z"));
757
758 auto Class$getDeclaredConstructors(jni.GetMethodID(Class$, "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;"));
759 auto Class$getDeclaredFields(jni.GetMethodID(Class$, "getDeclaredFields", "()[Ljava/lang/reflect/Field;"));
760 auto Class$getDeclaredMethods(jni.GetMethodID(Class$, "getDeclaredMethods", "()[Ljava/lang/reflect/Method;"));
761
762 auto Constructor$(jni.FindClass("java/lang/reflect/Constructor"));
763 //auto Constructor$getModifiers(jni.GetMethodID(Constructor$, "getModifiers", "()I"));
764 auto Constructor$getParameterTypes(jni.GetMethodID(Constructor$, "getParameterTypes", "()[Ljava/lang/Class;"));
765
766 auto Field$(jni.FindClass("java/lang/reflect/Field"));
767 auto Field$getModifiers(jni.GetMethodID(Field$, "getModifiers", "()I"));
768 auto Field$getName(jni.GetMethodID(Field$, "getName", "()Ljava/lang/String;"));
769 auto Field$getType(jni.GetMethodID(Field$, "getType", "()Ljava/lang/Class;"));
770
771 auto Method$(jni.FindClass("java/lang/reflect/Method"));
772 auto Method$getModifiers(jni.GetMethodID(Method$, "getModifiers", "()I"));
773 auto Method$getName(jni.GetMethodID(Method$, "getName", "()Ljava/lang/String;"));
774 auto Method$getParameterTypes(jni.GetMethodID(Method$, "getParameterTypes", "()[Ljava/lang/Class;"));
775 auto Method$getReturnType(jni.GetMethodID(Method$, "getReturnType", "()Ljava/lang/Class;"));
776
777 auto Modifier$(jni.FindClass("java/lang/reflect/Modifier"));
778 auto Modifier$isStatic(jni.GetStaticMethodID(Modifier$, "isStatic", "(I)Z"));
779
780 auto interface(jni.CallBooleanMethod(value, Class$isInterface));
781 auto table(new CYJavaClass(value, interface));
782
783 for (CYJavaLocal<jclass> prototype(value); prototype; prototype = jni.GetSuperclass(prototype)) {
784 auto fields(jni.CallObjectMethod<jobjectArray>(prototype, Class$getDeclaredFields));
785
786 for (jsize i(0), e(jni.GetArrayLength(fields)); i != e; ++i) {
787 auto field(jni.GetObjectArrayElement<jobject>(fields, e - i - 1));
788 auto modifiers(jni.CallIntMethod(field, Field$getModifiers));
789 auto instance(!jni.CallStaticBooleanMethod(Modifier$, Modifier$isStatic, modifiers));
790 auto &map(instance ? table->instance_ : table->static_);
791 auto string(jni.CallObjectMethod<jstring>(field, Field$getName));
792 CYJavaUTF8String name(string);
793 auto id(jni.FromReflectedField(field));
794 auto type(jni.CallObjectMethod<jclass>(field, Field$getType));
795 map.insert(std::make_pair(std::string(name), CYJavaField{id, CYJavaGetPrimitive(context, type, Class$getName)}));
796 }
797 }
798
799 constructor = JSObjectMake(context, CYPrivate<CYJavaClass>::Class_, table);
800
801 prototype = JSObjectMake(context, NULL, NULL);
802 CYSetProperty(context, constructor, prototype_s, prototype, kJSPropertyAttributeDontEnum);
803
804 auto constructors(jni.CallObjectMethod<jobjectArray>(value, Class$getDeclaredConstructors));
805
806 for (jsize i(0), e(jni.GetArrayLength(constructors)); i != e; ++i) {
807 auto constructor(jni.GetObjectArrayElement<jobject>(constructors, i));
808 auto parameters(jni.CallObjectMethod<jobjectArray>(constructor, Constructor$getParameterTypes));
809 CYJavaShorty shorty(CYJavaGetShorty(context, parameters, Class$getName));
810 auto id(jni.FromReflectedMethod(constructor));
811 table->overloads_[shorty.size()].insert(CYJavaSignature(constructor, id, CYJavaPrimitiveObject, shorty));
812 }
813
814 std::map<std::pair<bool, std::string>, CYJavaOverloads> entries;
815
816 bool base(false);
817 for (CYJavaLocal<jclass> prototype(value); prototype; prototype = jni.GetSuperclass(prototype)) {
818 auto methods(jni.CallObjectMethod<jobjectArray>(prototype, Class$getDeclaredMethods));
819
820 for (jsize i(0), e(jni.GetArrayLength(methods)); i != e; ++i) {
821 auto method(jni.GetObjectArrayElement<jobject>(methods, i));
822 auto modifiers(jni.CallIntMethod(method, Method$getModifiers));
823 auto instance(!jni.CallStaticBooleanMethod(Modifier$, Modifier$isStatic, modifiers));
824 auto string(jni.CallObjectMethod<jstring>(method, Method$getName));
825 CYJavaUTF8String name(string);
826
827 auto parameters(jni.CallObjectMethod<jobjectArray>(method, Method$getParameterTypes));
828 CYJavaShorty shorty(CYJavaGetShorty(context, parameters, Class$getName));
829
830 CYJavaOverload *overload;
831 if (!base)
832 overload = &entries[std::make_pair(instance, std::string(name))][shorty.size()];
833 else {
834 auto entry(entries.find(std::make_pair(instance, std::string(name))));
835 if (entry == entries.end())
836 continue;
837 overload = &entry->second[shorty.size()];
838 }
839
840 auto type(jni.CallObjectMethod<jclass>(method, Method$getReturnType));
841 auto primitive(CYJavaGetPrimitive(context, type, Class$getName));
842 auto id(jni.FromReflectedMethod(method));
843 overload->insert(CYJavaSignature(method, id, primitive, shorty));
844 }
845
846 base = true;
847 }
848
849 for (const auto &entry : entries) {
850 bool instance(entry.first.first);
851 CYJSString name(entry.first.second);
852 auto &overload(entry.second);
853 if (instance)
854 CYSetProperty(context, prototype, name, CYPrivate<CYJavaMethod>::Make(context, overload), kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete);
855 else
856 CYSetProperty(context, constructor, name, CYPrivate<CYJavaStaticMethod>::Make(context, overload), kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete);
857 }
858
859 }
860
861 // XXX: for some reason kJSPropertyAttributeDontEnum doesn't work if there's already a property with the same name
862 // by not linking the prototypes until after we set the properties, we hide the parent property from this issue :(
863
864 if (auto super = jni.GetSuperclass(value)) {
865 JSObjectRef parent(CYGetJavaClass(context, super));
866 CYSetPrototype(context, constructor, parent);
867 CYSetPrototype(context, prototype, CYGetProperty(context, parent, prototype_s));
868 }
869
870 CYSetProperty(context, cy, name, constructor);
871 return constructor;
872 }
873
874 static void CYCastJavaNumeric(jvalue &value, CYJavaPrimitive primitive, JSContextRef context, JSValueRef argument) {
875 switch (primitive) {
876 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
877 case CYJavaPrimitive ## Type: \
878 value.t = static_cast<j ## type>(CYCastDouble(context, argument)); \
879 break;
880 CYJavaForEachPrimitive
881 #undef CYJavaForEachPrimitive_
882 default:
883 _assert(false);
884 }
885 }
886
887 static bool CYCastJavaArguments(const CYJavaFrame &frame, const CYJavaShorty &shorty, JSContextRef context, const JSValueRef arguments[], jvalue *array) {
888 CYJavaEnv jni(frame);
889
890 for (size_t index(0); index != shorty.size(); ++index) {
891 JSValueRef argument(arguments[index]);
892 JSType type(JSValueGetType(context, argument));
893 jvalue &value(array[index]);
894
895 switch (CYJavaPrimitive primitive = shorty[index]) {
896 case CYJavaPrimitiveObject:
897 // XXX: figure out a way to tie this in to the CYJavaFrame
898 value.l = CYCastJavaObject(jni, context, argument).leak();
899 break;
900
901 case CYJavaPrimitiveBoolean:
902 if (type != kJSTypeBoolean)
903 return false;
904 value.z = CYCastBool(context, argument);
905 break;
906
907 case CYJavaPrimitiveCharacter:
908 if (type == kJSTypeNumber)
909 CYCastJavaNumeric(value, primitive, context, argument);
910 else if (type != kJSTypeString)
911 return false;
912 else {
913 CYJSString string(context, argument);
914 if (JSStringGetLength(string) != 1)
915 return false;
916 else
917 value.c = JSStringGetCharactersPtr(string)[0];
918 }
919 break;
920
921 case CYJavaPrimitiveByte:
922 case CYJavaPrimitiveShort:
923 case CYJavaPrimitiveInteger:
924 case CYJavaPrimitiveLong:
925 case CYJavaPrimitiveFloat:
926 case CYJavaPrimitiveDouble:
927 if (type != kJSTypeNumber)
928 return false;
929 CYCastJavaNumeric(value, primitive, context, argument);
930 break;
931
932 default:
933 _assert(false);
934 }
935 }
936
937 return true;
938 }
939
940 static JSValueRef JavaMethod_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
941 auto internal(CYPrivate<CYJavaMethod>::Get(context, object));
942 CYJavaObject *self(CYGetJavaObject(context, _this));
943 _assert(self != NULL);
944 CYJavaEnv jni(self->value_);
945
946 auto overload(internal->overloads_.find(count));
947 if (overload != internal->overloads_.end())
948 for (auto signature(overload->second.begin()); signature != overload->second.end(); ++signature) {
949 CYJavaFrame frame(jni, count + 16);
950 jvalue array[count];
951 if (!CYCastJavaArguments(frame, signature->shorty_, context, arguments, array))
952 continue;
953 jvalue *values(array);
954 switch (signature->primitive_) {
955 case CYJavaPrimitiveObject:
956 return CYCastJSValue(context, jni.CallObjectMethodA<jobject>(self->value_, signature->method_, values));
957 case CYJavaPrimitiveVoid:
958 jni.CallVoidMethodA(self->value_, signature->method_, values);
959 return CYJSUndefined(context);
960 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
961 case CYJavaPrimitive ## Type: \
962 return CYJavaCastJSValue(context, jni.Call ## Typ ## MethodA(self->value_, signature->method_, values));
963 CYJavaForEachPrimitive
964 #undef CYJavaForEachPrimitive_
965 default: _assert(false);
966 }
967 }
968
969 CYThrow("invalid method call");
970 } CYCatch(NULL) }
971
972 static JSValueRef JavaStaticMethod_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
973 auto internal(CYPrivate<CYJavaStaticMethod>::Get(context, object));
974 CYJavaClass *table(CYGetJavaTable(context, _this));
975 CYJavaEnv jni(table->value_);
976
977 auto overload(internal->overloads_.find(count));
978 if (overload != internal->overloads_.end())
979 for (auto signature(overload->second.begin()); signature != overload->second.end(); ++signature) {
980 CYJavaFrame frame(jni, count + 16);
981 jvalue array[count];
982 if (!CYCastJavaArguments(frame, signature->shorty_, context, arguments, array))
983 continue;
984 jvalue *values(array);
985 switch (signature->primitive_) {
986 case CYJavaPrimitiveObject:
987 return CYCastJSValue(context, jni.CallStaticObjectMethodA<jobject>(table->value_, signature->method_, values));
988 case CYJavaPrimitiveVoid:
989 jni.CallStaticVoidMethodA(table->value_, signature->method_, values);
990 return CYJSUndefined(context);
991 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
992 case CYJavaPrimitive ## Type: \
993 return CYJavaCastJSValue(context, jni.CallStatic ## Typ ## MethodA(table->value_, signature->method_, values));
994 CYJavaForEachPrimitive
995 #undef CYJavaForEachPrimitive_
996 default: _assert(false);
997 }
998 }
999
1000 CYThrow("invalid method call");
1001 } CYCatch(NULL) }
1002
1003 static JSObjectRef JavaClass_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1004 auto table(CYPrivate<CYJavaClass>::Get(context, object));
1005 CYJavaEnv jni(table->value_);
1006 jclass _class(table->value_);
1007
1008 if (table->interface_ && count == 1) {
1009 auto Cycript$(jni.FindClass("Cycript"));
1010 auto Cycript$Make(jni.GetStaticMethodID(Cycript$, "proxy", "(Ljava/lang/Class;LCycript$Wrapper;)Ljava/lang/Object;"));
1011 return CYCastJSObject(context, jni.CallObjectMethod<jobject>(Cycript$, Cycript$Make, _class, CYCastJavaObject(jni, context, CYCastJSObject(context, arguments[0])).get()));
1012 }
1013
1014 auto overload(table->overloads_.find(count));
1015 if (overload != table->overloads_.end())
1016 for (auto signature(overload->second.begin()); signature != overload->second.end(); ++signature) {
1017 CYJavaFrame frame(jni, count + 16);
1018 jvalue array[count];
1019 if (!CYCastJavaArguments(frame, signature->shorty_, context, arguments, array))
1020 continue;
1021 jvalue *values(array);
1022 auto object(jni.NewObjectA(_class, signature->method_, values));
1023 return CYCastJSObject(context, object);
1024 }
1025
1026 CYThrow("invalid constructor call");
1027 } CYCatchObject() }
1028
1029 static bool JavaStaticInterior_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1030 auto internal(CYPrivate<CYJavaStaticInterior>::Get(context, object));
1031 CYJavaClass *table(internal->table_);
1032 CYPool pool;
1033 auto name(CYPoolUTF8String(pool, context, property));
1034 auto field(table->static_.find(name));
1035 if (field == table->static_.end())
1036 return false;
1037 return true;
1038 }
1039
1040 static JSValueRef JavaStaticInterior_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1041 auto internal(CYPrivate<CYJavaStaticInterior>::Get(context, object));
1042 CYJavaClass *table(internal->table_);
1043 CYJavaEnv jni(table->value_);
1044 CYPool pool;
1045 auto name(CYPoolUTF8String(pool, context, property));
1046 auto field(table->static_.find(name));
1047 if (field == table->static_.end())
1048 return NULL;
1049
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);
1059 }
1060 } CYCatch(NULL) }
1061
1062 static bool JavaStaticInterior_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1063 auto internal(CYPrivate<CYJavaStaticInterior>::Get(context, object));
1064 CYJavaClass *table(internal->table_);
1065 CYJavaEnv jni(table->value_);
1066 CYPool pool;
1067 auto name(CYPoolUTF8String(pool, context, property));
1068 auto field(table->static_.find(name));
1069 if (field == table->static_.end())
1070 return false;
1071
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)); \
1078 break;
1079 CYJavaForEachPrimitive
1080 #undef CYJavaForEachPrimitive_
1081 default: _assert(false);
1082 }
1083
1084 return true;
1085 } CYCatch(false) }
1086
1087 static void JavaStaticInterior_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1088 auto internal(CYPrivate<CYJavaStaticInterior>::Get(context, object));
1089 CYJavaClass *table(internal->table_);
1090 for (const auto &field : table->static_)
1091 JSPropertyNameAccumulatorAddName(names, CYJSString(field.first));
1092 }
1093
1094 static JSValueRef JavaClass_getProperty_class(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1095 auto table(CYPrivate<CYJavaClass>::Get(context, object));
1096 return CYCastJSValue(context, table->value_);
1097 } CYCatch(NULL) }
1098
1099 static bool JavaInterior_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1100 auto internal(CYPrivate<CYJavaInterior>::Get(context, object));
1101 CYJavaClass *table(internal->table_);
1102 CYPool pool;
1103 auto name(CYPoolUTF8String(pool, context, property));
1104 auto field(table->instance_.find(name));
1105 if (field == table->instance_.end())
1106 return false;
1107 return true;
1108 }
1109
1110 static JSValueRef JavaInterior_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1111 auto internal(CYPrivate<CYJavaInterior>::Get(context, object));
1112 CYJavaEnv jni(internal->value_);
1113 CYJavaClass *table(internal->table_);
1114 CYPool pool;
1115 auto name(CYPoolUTF8String(pool, context, property));
1116 auto field(table->instance_.find(name));
1117 if (field == table->instance_.end())
1118 return NULL;
1119
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);
1129 }
1130 } CYCatch(NULL) }
1131
1132 static bool JavaInterior_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1133 auto internal(CYPrivate<CYJavaInterior>::Get(context, object));
1134 CYJavaEnv jni(internal->value_);
1135 CYJavaClass *table(internal->table_);
1136 CYPool pool;
1137 auto name(CYPoolUTF8String(pool, context, property));
1138 auto field(table->instance_.find(name));
1139 if (field == table->instance_.end())
1140 return false;
1141
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)); \
1148 break;
1149 CYJavaForEachPrimitive
1150 #undef CYJavaForEachPrimitive_
1151 default: _assert(false);
1152 }
1153
1154 return true;
1155 } CYCatch(false) }
1156
1157 static void JavaInterior_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1158 auto internal(CYPrivate<CYJavaInterior>::Get(context, object));
1159 CYJavaClass *table(internal->table_);
1160 for (const auto &field : table->instance_)
1161 JSPropertyNameAccumulatorAddName(names, CYJSString(field.first));
1162 }
1163
1164 static JSValueRef JavaObject_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1165 auto internal(CYPrivate<CYJavaObject>::Get(context, object));
1166 CYJavaEnv jni(internal->value_);
1167 return CYGetJavaClass(context, jni.GetObjectClass(internal->value_));
1168 } CYCatch(NULL) }
1169
1170 static JSValueRef JavaClass_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1171 auto internal(CYPrivate<CYJavaClass>::Get(context, object));
1172 return CYPrivate<CYJavaStaticInterior>::Make(context, internal->value_, internal);
1173 } CYCatch(NULL) }
1174
1175 static JSValueRef JavaObject_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1176 auto internal(CYPrivate<CYJavaObject>::Get(context, object));
1177 return CYPrivate<CYJavaInterior>::Make(context, internal->value_, internal->table_);
1178 } CYCatch(NULL) }
1179
1180 static JSValueRef JavaClass_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1181 auto internal(CYPrivate<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)));
1186 } CYCatch(NULL) }
1187
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()));
1191 } CYCatch(NULL) }
1192
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()));
1196 } CYCatch(NULL) }
1197
1198 static JSValueRef JavaArray_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1199 auto internal(CYPrivate<CYJavaArray>::Get(context, object));
1200 CYJavaEnv jni(internal->value_);
1201 if (JSStringIsEqual(property, length_s))
1202 return CYCastJSValue(context, jni.GetArrayLength(internal->value_));
1203
1204 CYPool pool;
1205 ssize_t offset;
1206 if (!CYGetOffset(pool, context, property, offset))
1207 return NULL;
1208
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); \
1217 } break;
1218 CYJavaForEachPrimitive
1219 #undef CYJavaForEachPrimitive_
1220 default: _assert(false);
1221 }
1222 } CYCatch(NULL) }
1223
1224 static bool JavaArray_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1225 auto internal(CYPrivate<CYJavaArray>::Get(context, object));
1226 CYJavaEnv jni(internal->value_);
1227
1228 CYPool pool;
1229 ssize_t offset;
1230 if (!CYGetOffset(pool, context, property, offset))
1231 return false;
1232
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); \
1241 } break;
1242 CYJavaForEachPrimitive
1243 #undef CYJavaForEachPrimitive_
1244 default: _assert(false);
1245 }
1246
1247 return true;
1248 } CYCatch(false) }
1249
1250 static JNIEnv *GetJNI(JSContextRef context, JNIEnv *&env);
1251
1252 static JSValueRef JavaPackage_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1253 auto internal(CYPrivate<CYJavaPackage>::Get(context, _this));
1254 std::ostringstream name;
1255 for (auto &package : internal->package_)
1256 name << package << '.';
1257 name << '*';
1258 return CYCastJSValue(context, CYJSString(name.str()));
1259 } CYCatch(NULL) }
1260
1261 static bool CYJavaPackage_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1262 return true;
1263 }
1264
1265 static JSValueRef CYJavaPackage_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1266 auto internal(CYPrivate<CYJavaPackage>::Get(context, object));
1267 CYJavaPackage::Path package(internal->package_);
1268
1269 CYPool pool;
1270 const char *next(CYPoolCString(pool, context, property));
1271
1272 std::ostringstream name;
1273 for (auto &package : internal->package_)
1274 name << package << '/';
1275 name << next;
1276
1277 if (internal->jni_ == NULL)
1278 GetJNI(context, internal->jni_);
1279 JNIEnv *jni(internal->jni_);
1280
1281 if (auto _class = jni->FindClass(name.str().c_str()))
1282 return CYGetJavaClass(context, CYJavaLocal<jclass>(jni, _class));
1283 jni->ExceptionClear();
1284
1285 package.push_back(next);
1286 return CYPrivate<CYJavaPackage>::Make(context, jni, package);
1287 } CYCatch(NULL) }
1288
1289 static void Cycript_delete(JNIEnv *env, jclass api, jlong jprotect) { CYJavaTry {
1290 delete &protect;
1291 } CYJavaCatch() }
1292
1293 static jobject Cycript_handle(JNIEnv *env, jclass api, jlong jprotect, jstring property, jobjectArray jarguments) { CYJavaTry {
1294 JSValueRef function(CYGetProperty(context, object, CYJSString(CYJavaRef<jstring>(jni, property))));
1295 if (JSValueIsUndefined(context, function))
1296 return NULL;
1297
1298 size_t count(jarguments == NULL ? 0 : jni.GetArrayLength(jarguments));
1299 JSValueRef arguments[count];
1300 for (size_t index(0); index != count; ++index)
1301 arguments[index] = CYCastJSValue(context, jni.GetObjectArrayElement<jobject>(jarguments, index));
1302
1303 return CYCastJavaObject(jni, context, CYCallAsFunction(context, CYCastJSObject(context, function), object, count, arguments)).leak();
1304 } CYJavaCatch(NULL) }
1305
1306 static JNINativeMethod Cycript_[] = {
1307 {(char *) "delete", (char *) "(J)V", (void *) &Cycript_delete},
1308 {(char *) "handle", (char *) "(JLjava/lang/String;[Ljava/lang/Object;)Ljava/lang/Object;", (void *) &Cycript_handle},
1309 };
1310
1311 template <typename Type_>
1312 static _finline void dlset(Type_ &function, const char *name, void *handle) {
1313 function = reinterpret_cast<Type_>(dlsym(handle, name));
1314 }
1315
1316 jint CYJavaVersion(JNI_VERSION_1_4);
1317
1318 static JavaVM *CYGetJavaVM(jint (*$JNI_GetCreatedJavaVMs)(JavaVM **, jsize, jsize *)) {
1319 jsize capacity(16);
1320 JavaVM *jvms[capacity];
1321 jsize size;
1322 _jnicall($JNI_GetCreatedJavaVMs(jvms, capacity, &size));
1323 if (size == 0)
1324 return NULL;
1325 return jvms[0];
1326 }
1327
1328 static JavaVM *CYGetJavaVM(JSContextRef context) {
1329 CYPool pool;
1330 void *handle(RTLD_DEFAULT);
1331 std::string library;
1332
1333 jint (*$JNI_GetCreatedJavaVMs)(JavaVM **jvms, jsize capacity, jsize *size);
1334 dlset($JNI_GetCreatedJavaVMs, "JNI_GetCreatedJavaVMs", handle);
1335
1336 if ($JNI_GetCreatedJavaVMs != NULL) {
1337 if (JavaVM *jvm = CYGetJavaVM($JNI_GetCreatedJavaVMs))
1338 return jvm;
1339 } else {
1340 std::vector<const char *> guesses;
1341
1342 #ifdef __ANDROID__
1343 char android[PROP_VALUE_MAX];
1344 if (__system_property_get("persist.sys.dalvik.vm.lib", android) != 0)
1345 guesses.push_back(android);
1346 #endif
1347
1348 guesses.push_back("/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/jli/libjli.dylib");
1349 //guesses.push_back("/System/Library/Frameworks/JavaVM.framework/JavaVM");
1350 guesses.push_back("libjvm.dylib");
1351
1352 guesses.push_back("libart.so");
1353 guesses.push_back("libdvm.so");
1354 guesses.push_back("libjvm.so");
1355
1356 for (const char *guess : guesses) {
1357 handle = dlopen(guess, RTLD_LAZY | RTLD_GLOBAL);
1358 if (handle != NULL) {
1359 library = guess;
1360 break;
1361 }
1362 }
1363
1364 if (library.size() == 0)
1365 return NULL;
1366
1367 dlset($JNI_GetCreatedJavaVMs, "JNI_GetCreatedJavaVMs", handle);
1368 if (JavaVM *jvm = CYGetJavaVM($JNI_GetCreatedJavaVMs))
1369 return jvm;
1370 }
1371
1372 std::vector<JavaVMOption> options;
1373
1374 {
1375 std::ostringstream option;
1376 option << "-Djava.class.path=";
1377 option << CYPoolLibraryPath(pool) << "/libcycript.jar";
1378 if (const char *classpath = getenv("CLASSPATH"))
1379 option << ':' << classpath;
1380 options.push_back(JavaVMOption{pool.strdup(option.str().c_str()), NULL});
1381 }
1382
1383 // To use libnativehelper to access JNI_GetCreatedJavaVMs, you need JniInvocation.
1384 // ...but there can only be one JniInvocation, and assuradely the other VM has it.
1385 // Essentially, this API makes no sense. We need it for AndroidRuntime, though :/.
1386
1387 if (void *libnativehelper = dlopen("libnativehelper.so", RTLD_LAZY | RTLD_GLOBAL)) {
1388 class JniInvocation$;
1389 JniInvocation$ *(*JniInvocation$$init$)(JniInvocation$ *self)(NULL);
1390 bool (*JniInvocation$Init)(JniInvocation$ *self, const char *library)(NULL);
1391 JniInvocation$ *(*JniInvocation$finalize)(JniInvocation$ *self)(NULL);
1392
1393 dlset(JniInvocation$$init$, "_ZN13JniInvocationC1Ev", libnativehelper);
1394 dlset(JniInvocation$Init, "_ZN13JniInvocation4InitEPKc", libnativehelper);
1395 dlset(JniInvocation$finalize, "_ZN13JniInvocationD1Ev", libnativehelper);
1396
1397 if (JniInvocation$$init$ == NULL)
1398 dlclose(libnativehelper);
1399 else {
1400 // XXX: we should attach a pool to the VM itself and deallocate this there
1401 //auto invocation(pool.calloc<JniInvocation$>(1, 1024));
1402 //_assert(JniInvocation$finalize != NULL);
1403 //pool.atexit(reinterpret_cast<void (*)(void *)>(JniInvocation$finalize), invocation);
1404
1405 auto invocation(static_cast<JniInvocation$ *>(calloc(1, 1024)));
1406 JniInvocation$$init$(invocation);
1407
1408 _assert(JniInvocation$Init != NULL);
1409 JniInvocation$Init(invocation, NULL);
1410
1411 dlset($JNI_GetCreatedJavaVMs, "JNI_GetCreatedJavaVMs", libnativehelper);
1412 if (JavaVM *jvm = CYGetJavaVM($JNI_GetCreatedJavaVMs))
1413 return jvm;
1414 }
1415 }
1416
1417 JavaVM *jvm;
1418 JNIEnv *env;
1419
1420 if (void *libandroid_runtime = dlopen("libandroid_runtime.so", RTLD_LAZY | RTLD_GLOBAL)) {
1421 class AndroidRuntime$;
1422 AndroidRuntime$ *(*AndroidRuntime$$init$)(AndroidRuntime$ *self, char *args, unsigned int size)(NULL);
1423 int (*AndroidRuntime$startVm)(AndroidRuntime$ *self, JavaVM **jvm, JNIEnv **env)(NULL);
1424 int (*AndroidRuntime$startReg)(JNIEnv *env)(NULL);
1425 int (*AndroidRuntime$addOption)(AndroidRuntime$ *self, const char *option, void *extra)(NULL);
1426 int (*AndroidRuntime$addVmArguments)(AndroidRuntime$ *self, int, const char *const argv[])(NULL);
1427 AndroidRuntime$ *(*AndroidRuntime$finalize)(AndroidRuntime$ *self)(NULL);
1428
1429 dlset(AndroidRuntime$$init$, "_ZN7android14AndroidRuntimeC1EPcj", libandroid_runtime);
1430 dlset(AndroidRuntime$startVm, "_ZN7android14AndroidRuntime7startVmEPP7_JavaVMPP7_JNIEnv", libandroid_runtime);
1431 dlset(AndroidRuntime$startReg, "_ZN7android14AndroidRuntime8startRegEP7_JNIEnv", libandroid_runtime);
1432 dlset(AndroidRuntime$addOption, "_ZN7android14AndroidRuntime9addOptionEPKcPv", libandroid_runtime);
1433 dlset(AndroidRuntime$addVmArguments, "_ZN7android14AndroidRuntime14addVmArgumentsEiPKPKc", libandroid_runtime);
1434 dlset(AndroidRuntime$finalize, "_ZN7android14AndroidRuntimeD1Ev", libandroid_runtime);
1435
1436 // XXX: it would also be interesting to attach this to a global pool
1437 AndroidRuntime$ *runtime(pool.calloc<AndroidRuntime$>(1, 1024));
1438
1439 _assert(AndroidRuntime$$init$ != NULL);
1440 AndroidRuntime$$init$(runtime, NULL, 0);
1441
1442 if (AndroidRuntime$addOption == NULL) {
1443 _assert(AndroidRuntime$addVmArguments != NULL);
1444 std::vector<const char *> arguments;
1445 for (const auto &option : options)
1446 arguments.push_back(option.optionString);
1447 AndroidRuntime$addVmArguments(runtime, arguments.size(), arguments.data());
1448 } else for (const auto &option : options)
1449 AndroidRuntime$addOption(runtime, option.optionString, option.extraInfo);
1450
1451 int failure;
1452
1453 _assert(AndroidRuntime$startVm != NULL);
1454 failure = AndroidRuntime$startVm(runtime, &jvm, &env);
1455 _assert(failure == 0);
1456
1457 _assert(AndroidRuntime$startReg != NULL);
1458 failure = AndroidRuntime$startReg(env);
1459 _assert(failure == 0);
1460
1461 return jvm;
1462 }
1463
1464 jint (*$JNI_CreateJavaVM)(JavaVM **jvm, void **, void *);
1465 dlset($JNI_CreateJavaVM, "JNI_CreateJavaVM", handle);
1466
1467 JavaVMInitArgs args;
1468 memset(&args, 0, sizeof(args));
1469 args.version = CYJavaVersion;
1470 args.nOptions = options.size();
1471 args.options = options.data();
1472 _jnicall($JNI_CreateJavaVM(&jvm, reinterpret_cast<void **>(&env), &args));
1473 return jvm;
1474 }
1475
1476 static JNIEnv *GetJNI(JSContextRef context, JNIEnv *&env) {
1477 auto jvm(CYGetJavaVM(context));
1478 _assert(jvm != NULL);
1479 _jnicall(jvm->GetEnv(reinterpret_cast<void **>(&env), CYJavaVersion));
1480 CYJavaEnv jni(env);
1481
1482 // XXX: this happens once per stub :/
1483
1484 auto Cycript$(jni.FindClass("Cycript"));
1485 jni.RegisterNatives(Cycript$, Cycript_, sizeof(Cycript_) / sizeof(Cycript_[0]));
1486
1487 JSObjectRef java(CYGetCachedObject(context, CYJSString("Java")));
1488 JSValueRef arguments[1];
1489 arguments[0] = CYCastJSValue(context, CYJSString("setup"));
1490 CYCallAsFunction(context, CYCastJSObject(context, CYGetProperty(context, java, CYJSString("emit"))), java, 1, arguments);
1491
1492 return env;
1493 }
1494
1495 static JSStaticValue JavaClass_staticValues[3] = {
1496 {"class", &JavaClass_getProperty_class, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1497 {"$cyi", &JavaClass_getProperty_$cyi, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1498 {NULL, NULL, NULL, 0}
1499 };
1500
1501 static JSStaticFunction JavaClass_staticFunctions[2] = {
1502 {"toCYON", &JavaClass_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1503 {NULL, NULL, 0}
1504 };
1505
1506 static JSStaticValue JavaObject_staticValues[3] = {
1507 {"constructor", &JavaObject_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1508 {"$cyi", &JavaObject_getProperty_$cyi, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1509 {NULL, NULL, NULL, 0}
1510 };
1511
1512 static JSStaticFunction JavaMethod_staticFunctions[2] = {
1513 {"toCYON", &JavaMethod_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1514 {NULL, NULL, 0}
1515 };
1516
1517 static JSStaticFunction JavaStaticMethod_staticFunctions[2] = {
1518 {"toCYON", &JavaStaticMethod_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1519 {NULL, NULL, 0}
1520 };
1521
1522 static JSStaticFunction JavaPackage_staticFunctions[2] = {
1523 {"toCYON", &JavaPackage_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1524 {NULL, NULL, 0}
1525 };
1526
1527 void CYJava_Initialize() {
1528 Primitives_.insert(std::make_pair("void", CYJavaPrimitiveVoid));
1529 #define CYJavaForEachPrimitive_(T, t, Typ, Type, type) \
1530 Primitives_.insert(std::make_pair(#type, CYJavaPrimitive ## Type));
1531 CYJavaForEachPrimitive
1532 #undef CYJavaForEachPrimitive_
1533
1534 JSClassDefinition definition;
1535
1536 definition = kJSClassDefinitionEmpty;
1537 definition.className = "JavaClass";
1538 definition.staticValues = JavaClass_staticValues;
1539 definition.staticFunctions = JavaClass_staticFunctions;
1540 definition.callAsConstructor = &JavaClass_callAsConstructor;
1541 definition.finalize = &CYFinalize;
1542 CYPrivate<CYJavaClass>::Class_ = JSClassCreate(&definition);
1543
1544 definition = kJSClassDefinitionEmpty;
1545 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
1546 definition.className = "JavaInterior";
1547 definition.hasProperty = &JavaInterior_hasProperty;
1548 definition.getProperty = &JavaInterior_getProperty;
1549 definition.setProperty = &JavaInterior_setProperty;
1550 definition.getPropertyNames = &JavaInterior_getPropertyNames;
1551 definition.finalize = &CYFinalize;
1552 CYPrivate<CYJavaInterior>::Class_ = JSClassCreate(&definition);
1553
1554 definition = kJSClassDefinitionEmpty;
1555 definition.className = "JavaMethod";
1556 definition.staticFunctions = JavaMethod_staticFunctions;
1557 definition.callAsFunction = &JavaMethod_callAsFunction;
1558 definition.finalize = &CYFinalize;
1559 CYPrivate<CYJavaMethod>::Class_ = JSClassCreate(&definition);
1560
1561 definition = kJSClassDefinitionEmpty;
1562 definition.className = "JavaStaticMethod";
1563 definition.staticFunctions = JavaStaticMethod_staticFunctions;
1564 definition.callAsFunction = &JavaStaticMethod_callAsFunction;
1565 definition.finalize = &CYFinalize;
1566 CYPrivate<CYJavaStaticMethod>::Class_ = JSClassCreate(&definition);
1567
1568 definition = kJSClassDefinitionEmpty;
1569 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
1570 definition.className = "JavaObject";
1571 definition.staticValues = JavaObject_staticValues;
1572 definition.finalize = &CYFinalize;
1573 CYPrivate<CYJavaObject>::Class_ = JSClassCreate(&definition);
1574
1575 definition = kJSClassDefinitionEmpty;
1576 definition.className = "JavaArray";
1577 definition.getProperty = &JavaArray_getProperty;
1578 definition.setProperty = &JavaArray_setProperty;
1579 definition.finalize = &CYFinalize;
1580 CYPrivate<CYJavaArray>::Class_ = JSClassCreate(&definition);
1581
1582 definition = kJSClassDefinitionEmpty;
1583 definition.className = "JavaPackage";
1584 definition.staticFunctions = JavaPackage_staticFunctions;
1585 definition.hasProperty = &CYJavaPackage_hasProperty;
1586 definition.getProperty = &CYJavaPackage_getProperty;
1587 definition.finalize = &CYFinalize;
1588 CYPrivate<CYJavaPackage>::Class_ = JSClassCreate(&definition);
1589
1590 definition = kJSClassDefinitionEmpty;
1591 definition.attributes = kJSClassAttributeNoAutomaticPrototype;
1592 definition.className = "JavaStaticInterior";
1593 definition.hasProperty = &JavaStaticInterior_hasProperty;
1594 definition.getProperty = &JavaStaticInterior_getProperty;
1595 definition.setProperty = &JavaStaticInterior_setProperty;
1596 definition.getPropertyNames = &JavaStaticInterior_getPropertyNames;
1597 definition.finalize = &CYFinalize;
1598 CYPrivate<CYJavaStaticInterior>::Class_ = JSClassCreate(&definition);
1599 }
1600
1601 void CYJava_SetupContext(JSContextRef context) {
1602 JSObjectRef global(CYGetGlobalObject(context));
1603 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
1604 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
1605 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
1606 //JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
1607
1608 JSObjectRef Java(JSObjectMake(context, NULL, NULL));
1609 CYSetProperty(context, cycript, CYJSString("Java"), Java);
1610 CYSetProperty(context, cy, CYJSString("Java"), Java);
1611
1612 JSObjectRef Packages(CYPrivate<CYJavaPackage>::Make(context, nullptr, CYJavaPackage::Path()));
1613 CYSetProperty(context, all, CYJSString("Packages"), Packages, kJSPropertyAttributeDontEnum);
1614
1615 for (auto name : (const char *[]) {"java", "javax", "android", "com", "net", "org"}) {
1616 CYJSString js(name);
1617 CYSetProperty(context, all, js, CYPrivate<CYJavaPackage>::Make(context, nullptr, CYJavaPackage::Path(1, name)), kJSPropertyAttributeDontEnum);
1618 }
1619 }
1620
1621 static CYHook CYJavaHook = {
1622 NULL,
1623 NULL,
1624 NULL,
1625 &CYJava_Initialize,
1626 &CYJava_SetupContext,
1627 NULL,
1628 };
1629
1630 CYRegisterHook CYJava(&CYJavaHook);