forked from ninia/jep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyembed.c
1477 lines (1257 loc) · 43.4 KB
/
pyembed.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
jep - Java Embedded Python
Copyright (c) 2004-2021 JEP AUTHORS.
This file is licensed under the the zlib/libpng License.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*****************************************************************************
This file handles two main things:
- startup, shutdown of interpreters.
(those are the pyembed_* functions)
- setting of parameters
(the pyembed_set*)
The really interesting stuff is not here. :-) This file simply makes calls
to the type definitions for pyjobject, etc.
*****************************************************************************
*/
#if STDC_HEADERS
#include <stdio.h>
#endif
#include "Jep.h"
/*
* fixes compiler warnings about PyMarshal_ReadLongFromFile and
* PyMarshal_ReadLastObjectFromFile
*/
#include "marshal.h"
#ifdef __unix__
#ifdef PYTHON_LDLIBRARY
/* see comments near dlopen() in pyembed_startup */
#include <dlfcn.h>
#endif
#endif
#ifdef __APPLE__
#ifndef WITH_NEXT_FRAMEWORK
#include <crt_externs.h>
// workaround for
// http://bugs.python.org/issue1602133
char **environ = NULL;
#endif
#endif
static PyThreadState *mainThreadState = NULL;
/* Saved for cross thread access to shared modules. */
static PyObject* mainThreadModules = NULL;
static PyObject* mainThreadModulesLock = NULL;
static int pyembed_is_version_unsafe(void);
static void handle_startup_exception(JNIEnv*, const char*);
static PyObject* pyembed_findclass(PyObject*, PyObject*);
static PyObject* pyembed_forname(PyObject*, PyObject*);
static PyObject* pyembed_jproxy(PyObject*, PyObject*);
static int maybe_pyc_file(FILE*, const char*, const char*, int);
static void pyembed_run_pyc(JepThread*, FILE*);
static struct PyMethodDef jep_methods[] = {
{
"findClass",
pyembed_findclass,
METH_VARARGS,
"Find and instantiate a system class, somewhat faster than forName."
},
{
"forName",
pyembed_forname,
METH_VARARGS,
"Find and return a jclass object using the supplied ClassLoader."
},
{
"jarray",
pyjarray_new_v,
METH_VARARGS,
"Returns a new Java Array.\n"
"Accepts:\n "
"(size, typecode, [fill]) or "
"(size, jclass)\n"
"\n"
"Java arrays behave much like lists, except the size is fixed at\n"
"creation and all the components of a jarray have the same type.\n"
"The component type is specified at object creation time by using a\n"
"jclass or type code. Java Object arrays are created by using a jclass\n"
"for the component type and Java primitive arrays are created by using\n"
"a type code for the component type.\n"
"The following type codes are defined:\n"
" Type code Java Primitive Type\n"
" 'z' boolean\n"
" 'b' byte\n"
" 'c' char\n"
" 's' short\n"
" 'i' int\n"
" 'j' long\n"
" 'f' float\n"
" 'd' double\n"
},
{
"jproxy",
pyembed_jproxy,
METH_VARARGS,
"Create a Proxy class for a Python object.\n"
"Accepts two arguments: ([a class object], [list of java interfaces "
"to implement, string names])"
},
{ NULL, NULL }
};
static struct PyModuleDef jep_module_def = {
PyModuleDef_HEAD_INIT,
"_jep", /* m_name */
"_jep", /* m_doc */
-1, /* m_size */
jep_methods, /* m_methods */
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
/*
* Initialize the _jep module.
*
* Return 0 on success and -1 on failure.
*/
static int initjep(JNIEnv *env, jboolean hasSharedModules)
{
PyObject *sysmodules = PyImport_GetModuleDict();
PyObject *modjep = PyDict_GetItemString(sysmodules, "_jep");
if (!modjep && PyErr_Occurred()) {
handle_startup_exception(env, "Error checking for exisitng module _jep");
} else if (!modjep) {
modjep = PyModule_Create(&jep_module_def);
if (!modjep) {
handle_startup_exception(env, "Couldn't create module _jep");
return -1;
}
if (PyDict_SetItemString(sysmodules, "_jep", modjep) == -1) {
Py_DECREF(modjep);
handle_startup_exception(env, "Couldn't set _jep on sys.modules");
return -1;
}
PyModule_AddStringConstant(modjep, "JBOOLEAN_ID", "z");
PyModule_AddStringConstant(modjep, "JINT_ID", "i");
PyModule_AddStringConstant(modjep, "JLONG_ID", "j");
PyModule_AddStringConstant(modjep, "JDOUBLE_ID", "d");
PyModule_AddStringConstant(modjep, "JSHORT_ID", "s");
PyModule_AddStringConstant(modjep, "JFLOAT_ID", "f");
PyModule_AddStringConstant(modjep, "JCHAR_ID", "c");
PyModule_AddStringConstant(modjep, "JBYTE_ID", "b");
PyModule_AddIntConstant(modjep, "JEP_NUMPY_ENABLED", JEP_NUMPY_ENABLED);
PyObject *javaAttrCache = PyDict_New();
if (!javaAttrCache) {
Py_DECREF(modjep);
return -1;
}
PyObject *javaTypeCache = PyDict_New();
if (!javaTypeCache) {
Py_DECREF(modjep);
return -1;
}
if (PyModule_AddObject(modjep, "__javaTypeCache__", javaTypeCache)) {
Py_DECREF(javaTypeCache);
Py_DECREF(modjep);
return -1;
}
if (hasSharedModules) {
Py_INCREF(mainThreadModules);
PyModule_AddObject(modjep, "mainInterpreterModules", mainThreadModules);
Py_INCREF(mainThreadModulesLock);
PyModule_AddObject(modjep, "mainInterpreterModulesLock", mainThreadModulesLock);
}
/* still held by sys.modules. */
Py_DECREF(modjep);
}
return 0;
}
void pyembed_preinit(JNIEnv *env,
jint noSiteFlag,
jint noUserSiteDirectory,
jint ignoreEnvironmentFlag,
jint verboseFlag,
jint optimizeFlag,
jint dontWriteBytecodeFlag,
jint hashRandomizationFlag,
jstring pythonHome)
{
if (noSiteFlag >= 0) {
Py_NoSiteFlag = noSiteFlag;
}
if (noUserSiteDirectory >= 0) {
Py_NoUserSiteDirectory = noUserSiteDirectory;
}
if (ignoreEnvironmentFlag >= 0) {
Py_IgnoreEnvironmentFlag = ignoreEnvironmentFlag;
}
if (verboseFlag >= 0) {
Py_VerboseFlag = verboseFlag;
}
if (optimizeFlag >= 0) {
Py_OptimizeFlag = optimizeFlag;
}
if (dontWriteBytecodeFlag >= 0) {
Py_DontWriteBytecodeFlag = dontWriteBytecodeFlag;
}
if (hashRandomizationFlag >= 0) {
Py_HashRandomizationFlag = hashRandomizationFlag;
}
if (pythonHome) {
const char* homeAsUTF = (*env)->GetStringUTFChars(env, pythonHome, NULL);
wchar_t* homeForPython = Py_DecodeLocale(homeAsUTF, NULL);
(*env)->ReleaseStringUTFChars(env, pythonHome, homeAsUTF);
Py_SetPythonHome(homeForPython);
// Python documentation says that the string should not be changed for
// the duration of the program so it can never be freed.
}
}
/*
* MSVC requires tp_base to be set at runtime instead of in the type
* declaration. :/ Otherwise we could just set tp_base in the type declaration
* and be done with it. Since we are building an inheritance tree of types, we
* need to ensure that all the tp_base are set for the subtypes before we
* possibly use those subtypes.
*
* Furthermore, we need to ensure that the inheritance tree is built in the
* correct order, i.e. from the top down. For example, we need to set that
* PyJCollection's tp_base extends PyJIterable before we set that PyJList's
* tp_base extends PyJCollection. Interfaces that are not extending another
* interface should not set tp_base because interfaces are added to Python
* types using multiple inheritance and only one superclass can define a
* custom structure.
*
* See https://docs.python.org/3/extending/newtypes.html
*/
static int pyjtypes_ready(void)
{
if (PyType_Ready(&PyJObject_Type) < 0) {
return -1;
}
if (!PyJClass_Type.tp_base) {
PyJClass_Type.tp_base = &PyJObject_Type;
}
if (PyType_Ready(&PyJClass_Type) < 0) {
return -1;
}
if (!PyJNumber_Type.tp_base) {
PyJNumber_Type.tp_base = &PyJObject_Type;
}
if (PyType_Ready(&PyJNumber_Type) < 0) {
return -1;
}
if (PyType_Ready(&PyJIterable_Type) < 0) {
return -1;
}
if (PyType_Ready(&PyJIterator_Type) < 0) {
return -1;
}
if (!PyJCollection_Type.tp_base) {
PyJCollection_Type.tp_base = &PyJIterable_Type;
}
if (PyType_Ready(&PyJCollection_Type) < 0) {
return -1;
}
if (!PyJList_Type.tp_base) {
PyJList_Type.tp_base = &PyJCollection_Type;
}
if (PyType_Ready(&PyJList_Type) < 0) {
return -1;
}
if (PyType_Ready(&PyJMap_Type) < 0) {
return -1;
}
if (!PyJBuffer_Type.tp_base) {
PyJBuffer_Type.tp_base = &PyJObject_Type;
}
if (PyType_Ready(&PyJBuffer_Type) < 0) {
return -1;
}
if (PyType_Ready(&PyJAutoCloseable_Type) < 0) {
return -1;
}
return 0;
}
static void handle_startup_exception(JNIEnv *env, const char* excMsg)
{
jclass excClass = (*env)->FindClass(env, "java/lang/IllegalStateException");
if (PyErr_Occurred()) {
PyErr_Print();
}
if (excClass != NULL) {
(*env)->ThrowNew(env, excClass, excMsg);
}
}
void pyembed_startup(JNIEnv *env, jobjectArray sharedModulesArgv)
{
PyObject* sysModule = NULL;
PyObject* threadingModule = NULL;
PyObject* lockCreator = NULL;
#ifdef _DLFCN_H
/*
* In some Linux distros, Python modules are compiled without a dependency
* on libpython, instead they rely on the Python symbols to be available
* globally. Unfortunatly JNI does not load the libraries globally so the
* symbols are not available which causes those Python modules to fail to
* load. To get around this dlopen is used to promote libpython into the
* global namespace.
*
* This is most notably a problem on Ubuntu which statically links libpython
* into the python executable which means that all modules rely on Python
* symbols being available globally.
*
* An alternative mechanism on Linux to get the libpython symbols globally
* is to use LD_PRELOAD to load libpython, this still might be necessary
* if dlopen fails for some reason.
*/
void* dlresult = dlopen(PYTHON_LDLIBRARY,
RTLD_LAZY | RTLD_NOLOAD | RTLD_GLOBAL);
if (dlresult) {
// The dynamic linker maintains reference counts so closing it is a no-op.
dlclose(dlresult);
} else {
/*
* Ignore errors and hope that the library is loaded globally or the
* extensions are linked. If developers need to debug the cause they
* should print the result of dlerror.
*/
dlerror();
}
#endif
#ifdef __APPLE__
#ifndef WITH_NEXT_FRAMEWORK
// workaround for
// http://bugs.python.org/issue1602133
environ = *_NSGetEnviron();
#endif
#endif
if (mainThreadState != NULL) {
// this shouldn't happen but to be safe, don't initialize twice
return;
}
if (pyembed_is_version_unsafe()) {
return;
}
Py_Initialize();
#if PY_MAJOR_VERSION < 4 && PY_MINOR_VERSION < 7
PyEval_InitThreads();
#endif
if (pyjtypes_ready()) {
handle_startup_exception(env, "Failed to initialize PyJTypes");
return;
}
/*
* Save a global reference to the sys.modules form the main thread to
* support shared modules
*/
sysModule = PyImport_ImportModule("sys");
if (sysModule == NULL) {
handle_startup_exception(env, "Failed to import sys module");
return;
}
mainThreadModules = PyObject_GetAttrString(sysModule, "modules");
if (mainThreadModules == NULL) {
handle_startup_exception(env, "Failed to get sys.modules");
return;
}
Py_DECREF(sysModule);
threadingModule = PyImport_ImportModule("threading");
if (threadingModule == NULL) {
handle_startup_exception(env, "Failed to import threading module");
return;
}
lockCreator = PyObject_GetAttrString(threadingModule, "Lock");
if (lockCreator == NULL) {
handle_startup_exception(env, "Failed to get Lock attribute");
return;
}
mainThreadModulesLock = PyObject_CallObject(lockCreator, NULL);
if (mainThreadModulesLock == NULL) {
handle_startup_exception(env, "Failed to get main thread modules lock");
return;
}
Py_DECREF(threadingModule);
Py_DECREF(lockCreator);
// save a pointer to the main PyThreadState object
mainThreadState = PyThreadState_Get();
/*
* Workaround for shared modules sys.argv. Set sys.argv on the main thread.
* See github issue #81.
*/
if (sharedModulesArgv != NULL) {
wchar_t **argv = NULL;
jsize count = 0;
int i = 0;
count = (*env)->GetArrayLength(env, sharedModulesArgv);
(*env)->PushLocalFrame(env, count * 2);
argv = (wchar_t**) malloc(count * sizeof(wchar_t*));
for (i = 0; i < count; i++) {
char* arg = NULL;
wchar_t* argt = NULL;
int k = 0;
jstring jarg = (*env)->GetObjectArrayElement(env, sharedModulesArgv, i);
if (jarg == NULL) {
PyEval_ReleaseThread(mainThreadState);
(*env)->PopLocalFrame(env, NULL);
THROW_JEP(env, "Received null argv.");
for (k = 0; k < i; k++) {
free(argv[k]);
}
free(argv);
return;
}
arg = (char*) (*env)->GetStringUTFChars(env, jarg, NULL);
argt = malloc((strlen(arg) + 1) * sizeof(wchar_t));
mbstowcs(argt, arg, strlen(arg) + 1);
(*env)->ReleaseStringUTFChars(env, jarg, arg);
argv[i] = argt;
}
PySys_SetArgvEx(count, argv, 0);
// free memory
for (i = 0; i < count; i++) {
free(argv[i]);
}
free(argv);
(*env)->PopLocalFrame(env, NULL);
}
PyEval_ReleaseThread(mainThreadState);
}
/*
* Verify the Python major.minor at runtime matches the Python major.minor
* that Jep was built against. If they don't match, refuse to initialize Jep
* and instead throw an exception because a mismatch could cause a JVM crash.
*/
int pyembed_is_version_unsafe(void)
{
const char *pyversion = NULL;
char *version = NULL;
char *major = NULL;
char *minor = NULL;
int i = 0;
pyversion = Py_GetVersion();
version = malloc(strlen(pyversion) + 1);
strcpy(version, pyversion);
major = version;
while (version[i] != '\0') {
if (!isdigit(version[i])) {
version[i] = '\0';
if (minor == NULL) {
minor = version + i + 1;
}
}
i += 1;
}
if (atoi(major) != PY_MAJOR_VERSION || atoi(minor) != PY_MINOR_VERSION) {
char *msg;
JNIEnv *env = pyembed_get_env();
msg = malloc(sizeof(char) * 200);
memset(msg, '\0', 200);
sprintf(msg,
"Jep will not initialize because it was compiled against Python %i.%i but is running against Python %s.%s",
PY_MAJOR_VERSION, PY_MINOR_VERSION, major, minor);
THROW_JEP(env, msg);
free(version);
free(msg);
return 1;
}
free(version);
return 0;
}
void pyembed_shutdown(JavaVM *vm)
{
JNIEnv *env;
// shut down python first
PyEval_AcquireThread(mainThreadState);
Py_Finalize();
if ((*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6) != JNI_OK) {
// failed to get a JNIEnv*, we can hope it's just shutting down fast
return;
} else {
// delete global references
unref_cache_primitive_classes(env);
unref_cache_frequent_classes(env);
}
}
/*
* Import a module on the main thread. This must be called from the same thread
* as pyembed_startup. On success the specified module will be available in the
* mainThreadModules. On failure this function will raise a java exception.
*/
void pyembed_shared_import(JNIEnv *env, jstring module)
{
const char *moduleName = NULL;
PyObject *pymodule = NULL;
PyEval_AcquireThread(mainThreadState);
moduleName = (*env)->GetStringUTFChars(env, module, 0);
pymodule = PyImport_ImportModule(moduleName);
if (pymodule) {
Py_DECREF(pymodule);
} else {
process_py_exception(env);
}
(*env)->ReleaseStringUTFChars(env, module, moduleName);
PyEval_ReleaseThread(mainThreadState);
}
intptr_t pyembed_thread_init(JNIEnv *env, jobject cl, jobject caller,
jboolean hasSharedModules, jboolean usesubinterpreter)
{
JepThread *jepThread;
PyObject *tdict, *globals;
if (cl == NULL) {
THROW_JEP(env, "Invalid Classloader.");
return 0;
}
/*
* Do not use PyMem_Malloc because PyGILState_Check() returns false since
* the mainThreadState was created on a different thread. When python is
* compiled with debug it checks the state and fails.
*/
jepThread = malloc(sizeof(JepThread));
if (!jepThread) {
THROW_JEP(env, "Out of memory.");
return 0;
}
if (usesubinterpreter) {
PyEval_AcquireThread(mainThreadState);
jepThread->tstate = Py_NewInterpreter();
/*
* Py_NewInterpreter() seems to take the thread state, but we're going to
* save/release and reacquire it since that doesn't seem documented
*/
PyEval_SaveThread();
} else {
jepThread->tstate = PyThreadState_New(mainThreadState->interp);
}
PyEval_AcquireThread(jepThread->tstate);
// store java.lang.Class objects for later use.
// it's a noop if already done, but to synchronize, have the lock first
if (!cache_frequent_classes(env)) {
printf("WARNING: Failed to get and cache frequent class types!\n");
}
if (!cache_primitive_classes(env)) {
printf("WARNING: Failed to get and cache primitive class types!\n");
}
if (usesubinterpreter) {
PyObject *mod_main = PyImport_AddModule("__main__"); /* borrowed */
if (mod_main == NULL) {
THROW_JEP(env, "Couldn't add module __main__.");
PyEval_ReleaseThread(jepThread->tstate);
free(jepThread);
return 0;
}
globals = PyModule_GetDict(mod_main);
Py_INCREF(globals);
} else {
globals = PyDict_New();
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
}
if (initjep(env, hasSharedModules)) {
return 0;
}
// init static module
jepThread->globals = globals;
jepThread->env = env;
jepThread->classloader = (*env)->NewGlobalRef(env, cl);
jepThread->caller = (*env)->NewGlobalRef(env, caller);
if ((tdict = PyThreadState_GetDict()) != NULL) {
PyObject *key, *t;
t = PyCapsule_New((void *) jepThread, NULL, NULL);
key = PyUnicode_FromString(DICT_KEY);
PyDict_SetItem(tdict, key, t); /* takes ownership */
Py_DECREF(key);
Py_DECREF(t);
}
PyEval_ReleaseThread(jepThread->tstate);
return (intptr_t) jepThread;
}
void pyembed_thread_close(JNIEnv *env, intptr_t _jepThread)
{
JepThread *jepThread;
PyObject *tdict, *key;
jepThread = (JepThread *) _jepThread;
if (!jepThread) {
printf("WARNING: thread_close, invalid JepThread pointer.\n");
return;
}
PyEval_AcquireThread(jepThread->tstate);
key = PyUnicode_FromString(DICT_KEY);
if ((tdict = PyThreadState_GetDict()) != NULL && key != NULL) {
PyDict_DelItem(tdict, key);
}
Py_DECREF(key);
Py_CLEAR(jepThread->globals);
if (jepThread->classloader) {
(*env)->DeleteGlobalRef(env, jepThread->classloader);
}
if (jepThread->caller) {
(*env)->DeleteGlobalRef(env, jepThread->caller);
}
if (jepThread->tstate->interp == mainThreadState->interp) {
PyThreadState_Clear(jepThread->tstate);
PyEval_ReleaseThread(jepThread->tstate);
PyThreadState_Delete(jepThread->tstate);
} else {
Py_EndInterpreter(jepThread->tstate);
PyThreadState_Swap(mainThreadState);
PyEval_ReleaseThread(mainThreadState);
}
free(jepThread);
}
JNIEnv* pyembed_get_env(void)
{
JavaVM *jvm;
JNIEnv *env;
jsize nVMs;
JNI_GetCreatedJavaVMs(&jvm, 1, &nVMs);
/*
* If the thread is already part of the JVM, the daemon status is not
* changed. If this is a new thread, started by Python then this tells
* Java to allow the process to exit even if the thread is still attached.
* Since there are no hooks to detach the thread later daemon is the only
* way to let the process exit normally.
*/
(*jvm)->AttachCurrentThreadAsDaemon(jvm, (void**) &env, NULL);
return env;
}
// get thread struct when called from internals.
// NULL if not found.
// hold the lock before calling.
JepThread* pyembed_get_jepthread(void)
{
PyObject *tdict, *t, *key;
JepThread *ret = NULL;
key = PyUnicode_FromString(DICT_KEY);
if ((tdict = PyThreadState_GetDict()) != NULL && key != NULL) {
t = PyDict_GetItem(tdict, key); /* borrowed */
if (t != NULL && !PyErr_Occurred()) {
ret = (JepThread*) PyCapsule_GetPointer(t, NULL);
}
}
Py_XDECREF(key);
if (!ret && !PyErr_Occurred()) {
PyErr_SetString(PyExc_RuntimeError,
"No Jep instance available on current thread.");
}
return ret;
}
static PyObject* pyembed_jproxy(PyObject *self, PyObject *args)
{
JepThread *jepThread;
JNIEnv *env = NULL;
PyObject *pytarget;
PyObject *interfaces;
PyObject *result;
jobject classes;
Py_ssize_t inum, i;
jobject proxy;
if (!PyArg_ParseTuple(args, "OO!:jproxy",
&pytarget,
&PyList_Type,
&interfaces)) {
return NULL;
}
jepThread = pyembed_get_jepthread();
if (!jepThread) {
if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_RuntimeError, "Invalid JepThread pointer.");
}
return NULL;
}
env = jepThread->env;
inum = (int) PyList_GET_SIZE(interfaces);
if (inum < 1) {
return PyErr_Format(PyExc_ValueError, "Empty interface list.");
}
// now convert string list to java array
classes = (*env)->NewObjectArray(env, (jsize) inum, JSTRING_TYPE, NULL);
if (process_java_exception(env) || !classes) {
return NULL;
}
for (i = 0; i < inum; i++) {
const char *str;
jstring jstr;
PyObject *item;
item = PyList_GET_ITEM(interfaces, i);
if (!PyUnicode_Check(item)) {
return PyErr_Format(PyExc_ValueError, "Item %zd not a string.", i);
}
str = PyUnicode_AsUTF8(item);
jstr = (*env)->NewStringUTF(env, (const char *) str);
(*env)->SetObjectArrayElement(env, classes, (jsize) i, jstr);
(*env)->DeleteLocalRef(env, jstr);
}
// do the deed
proxy = jep_Proxy_newProxyInstance(env,
jepThread->caller,
(jlong) (intptr_t) pytarget,
classes);
(*env)->DeleteLocalRef(env, classes);
if (process_java_exception(env) || !proxy) {
return NULL;
}
// make sure target doesn't get garbage collected
Py_INCREF(pytarget);
jclass clazz = (*env)->GetObjectClass(env, proxy);
result = jobject_As_PyJObject(env, proxy, clazz);
(*env)->DeleteLocalRef(env, clazz);
(*env)->DeleteLocalRef(env, proxy);
return result;
}
static PyObject* pyembed_forname(PyObject *self, PyObject *args)
{
JNIEnv *env = NULL;
char *name;
jobject cl;
jclass objclazz;
jstring jstr;
JepThread *jepThread;
PyObject *result;
if (!PyArg_ParseTuple(args, "s", &name)) {
return NULL;
}
jepThread = pyembed_get_jepthread();
if (!jepThread) {
if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_RuntimeError, "Invalid JepThread pointer.");
}
return NULL;
}
env = jepThread->env;
cl = jepThread->classloader;
jstr = (*env)->NewStringUTF(env, (const char *) name);
if (process_java_exception(env) || !jstr) {
return NULL;
}
objclazz = java_lang_ClassLoader_loadClass(env, cl, jstr);
(*env)->DeleteLocalRef(env, jstr);
if (process_java_exception(env) || !objclazz) {
return NULL;
}
result = PyJClass_Wrap(env, objclazz);
(*env)->DeleteLocalRef(env, objclazz);
return result;
}
static PyObject* pyembed_findclass(PyObject *self, PyObject *args)
{
JNIEnv *env = NULL;
PyObject *result = NULL;
char *name, *p;
jclass clazz;
JepThread *jepThread;
if (!PyArg_ParseTuple(args, "s", &name)) {
return NULL;
}
jepThread = pyembed_get_jepthread();
if (!jepThread) {
if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_RuntimeError, "Invalid JepThread pointer.");
}
return NULL;
}
env = jepThread->env;
// replace '.' with '/'
// i'm told this is okay to do with unicode.
for (p = name; *p != '\0'; p++) {
if (*p == '.') {
*p = '/';
}
}
clazz = (*env)->FindClass(env, name);
if (process_java_exception(env)) {
return NULL;
}
result = PyJClass_Wrap(env, clazz);
(*env)->DeleteLocalRef(env, clazz);
return result;
}
/*
* Invoke callable object. Hold the thread state lock before calling.
*/
jobject pyembed_invoke_as(JNIEnv *env,
PyObject *callable,
jobjectArray args,
jobject kwargs,
jclass expectedType)
{
jobject ret = NULL;
PyObject *pyargs = NULL; /* a tuple */
PyObject *pykwargs = NULL; /* a dictionary */
PyObject *pyret = NULL;
int arglen = 0;
Py_ssize_t i = 0;
if (!PyCallable_Check(callable)) {
THROW_JEP(env, "pyembed:invoke Invalid callable.");
return NULL;
}
if (args != NULL) {
arglen = (*env)->GetArrayLength(env, args);
pyargs = PyTuple_New(arglen);
} else {
// pyargs should be a Tuple of size 0 if no args
pyargs = PyTuple_New(arglen);
}
// convert Java arguments to a Python tuple
for (i = 0; i < arglen; i++) {
jobject val;
PyObject *pyval;
val = (*env)->GetObjectArrayElement(env, args, (jsize) i);
if ((*env)->ExceptionCheck(env)) { /* careful, NULL is okay */
goto EXIT;
}
pyval = jobject_As_PyObject(env, val);
if (!pyval) {
goto EXIT;
}
PyTuple_SET_ITEM(pyargs, i, pyval); /* steals */
if (val) {
(*env)->DeleteLocalRef(env, val);
}
}
// convert Java arguments to a Python dictionary
if (kwargs != NULL) {
jobject entrySet;
jobject itr;
pykwargs = PyDict_New();
entrySet = java_util_Map_entrySet(env, kwargs);
if ((*env)->ExceptionCheck(env)) {
goto EXIT;
}
itr = java_lang_Iterable_iterator(env, entrySet);
if ((*env)->ExceptionCheck(env)) {
goto EXIT;
}
while (java_util_Iterator_hasNext(env, itr)) {
jobject next;
jobject key;
jobject value;
PyObject *pykey;
PyObject *pyval;
next = java_util_Iterator_next(env, itr);
if (!next) {
if (!(*env)->ExceptionCheck(env)) {
THROW_JEP(env, "Map.entrySet().iterator().next() returned null");
}
goto EXIT;
}
// convert Map.Entry's key to a PyObject*
key = java_util_Map_Entry_getKey(env, next);
if ((*env)->ExceptionCheck(env)) {
goto EXIT;
}
pykey = jobject_As_PyObject(env, key);
if (!pykey) {
goto EXIT;
}
// convert Map.Entry's value to a PyObject*
value = java_util_Map_Entry_getValue(env, next);
if ((*env)->ExceptionCheck(env)) {