-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQorePythonProgram.cpp
More file actions
2909 lines (2508 loc) · 107 KB
/
Copy pathQorePythonProgram.cpp
File metadata and controls
2909 lines (2508 loc) · 107 KB
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
/* -*- mode: c++; indent-tabs-mode: nil -*- */
/** @file QorePythonProgram.cpp defines the QorePythonProgram class */
/*
QorePythonProgram.qpp
Qore Programming Language
Copyright 2020 - 2022 Qore Technologies, s.r.o.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "QC_PythonProgram.h"
#include "QorePythonPrivateData.h"
#include "QorePythonClass.h"
#include "QoreLoader.h"
#include "PythonQoreClass.h"
#include "QoreMetaPathFinder.h"
#include "PythonCallableCallReferenceNode.h"
#include "PythonQoreCallable.h"
#include "ModuleNamespace.h"
#include "QorePythonStackLocationHelper.h"
#include <structmember.h>
#include <frameobject.h>
#include <datetime.h>
#include <vector>
#include <string>
static const char* this_file = q_basenameptr(__FILE__);
// type used for imported Qore namespaces in Python; a plan type with only a dictionary
struct PythonQoreNs {
PyObject_HEAD
PyObject* dict;
};
static strvec_t get_dot_path_list(const std::string str) {
strvec_t rv;
size_t start = 0;
while (true) {
size_t pos = str.find('.', start);
rv.push_back(str.substr(start, pos - start));
if (pos == std::string::npos) {
break;
}
start = pos + 1;
}
return rv;
}
#ifdef DEBUG
// from Python internal code
static bool _qore_PyThreadState_IsCurrent(PyThreadState* tstate) {
// Must be the tstate for this thread
return tstate == _qore_PyRuntimeGILState_GetThreadState();
}
#endif
// static member declarations
QorePythonProgram::py_thr_map_t QorePythonProgram::py_thr_map;
QorePythonProgram::py_global_tid_map_t QorePythonProgram::py_global_tid_map;
QoreThreadLock QorePythonProgram::py_thr_lck;
unsigned QorePythonProgram::pgm_count = 0;
QorePythonProgram::QorePythonProgram() : save_object_callback(nullptr) {
printd(5, "QorePythonProgram::QorePythonProgram() this: %p\n", this);
assert(PyGILState_Check());
PyThreadState* python;
if (PyGILState_Check()) {
assert(_qore_PyRuntimeGILState_GetThreadState() == PyGILState_GetThisThreadState());
python = PyGILState_GetThisThreadState();
interpreter = python->interp;
} else {
python = nullptr;
interpreter = _PyGILState_GetInterpreterStateUnsafe();
}
owns_interpreter = false;
createQoreProgram();
// insert thread state into thread map
AutoLocker al(py_thr_lck);
assert(py_thr_map.find(this) == py_thr_map.end());
int tid = q_gettid();
py_thr_map[this] = {{tid, {python, false}}};
py_global_tid_map[tid].insert(python);
++pgm_count;
needs_deregistration = qpy_register(this);
}
QorePythonProgram::QorePythonProgram(QoreProgram* qpgm, QoreNamespace* pyns)
: qpgm(qpgm), pyns(pyns), save_object_callback(nullptr) {
printd(5, "QorePythonProgram::QorePythonProgram() this: %p GIL thread state: %p\n", this,
PyGILState_GetThisThreadState());
QorePythonGilHelper qpgh;
//printd(5, "QorePythonProgram::QorePythonProgram() GIL thread state: %p\n", PyGILState_GetThisThreadState());
ExceptionSink xsink;
if (createInterpreter(qpgh, &xsink)) {
valid = false;
return;
}
// ensure that the __main__ module is created
// returns a borrowed reference
module = PyImport_AddModule("__main__");
module.py_ref();
import(&xsink, "builtins");
if (xsink) {
valid = false;
return;
}
//assert(!xsink);
// returns a borrowed reference
setGlobalDictionary(*module);
assert(!PyErr_Occurred());
// import qoreloader module
QorePythonReferenceHolder qoreloader(PyImport_ImportModule("qoreloader"));
if (!qoreloader) {
if (!checkPythonException(&xsink)) {
xsink.raiseException("PYTHON-COMPILE-ERROR", "cannot load the 'qoreloader' module");
}
return;
}
PyDict_SetItemString(module_dict, "qoreloader", *qoreloader);
needs_deregistration = qpy_register(this);
}
QorePythonProgram::QorePythonProgram(const QoreString& source_code, const QoreString& source_label, int start,
ExceptionSink* xsink) : save_object_callback(nullptr) {
printd(5, "QorePythonProgram::QorePythonProgram() this: %p\n", this);
TempEncodingHelper src_code(source_code, QCS_UTF8, xsink);
if (*xsink) {
xsink->appendLastDescription(" (while processing the \"source_code\" argument)");
return;
}
TempEncodingHelper src_label(source_label, QCS_UTF8, xsink);
if (*xsink) {
xsink->appendLastDescription(" (while processing the \"source_label\" argument)");
return;
}
//printd(5, "QorePythonProgram::QorePythonProgram() GIL thread state: %p\n", PyGILState_GetThisThreadState());
QorePythonGilHelper qpgh;
//printd(5, "QorePythonProgram::QorePythonProgram() GIL thread state: %p\n", PyGILState_GetThisThreadState());
if (createInterpreter(qpgh, xsink)) {
return;
}
// import qoreloader module
QorePythonReferenceHolder qoreloader(PyImport_ImportModule("qoreloader"));
if (!qoreloader) {
if (!checkPythonException(xsink)) {
xsink->raiseException("PYTHON-COMPILE-ERROR", "cannot load the 'qoreloader' module");
}
return;
}
//printd(5, "QorePythonProgram::QorePythonProgram() loaded qoreloader: %p\n", *qoreloader);
// parse and compile code
python_code = (PyObject*)Py_CompileString(src_code->c_str(), src_label->c_str(), start);
if (!python_code) {
if (!checkPythonException(xsink)) {
xsink->raiseException("PYTHON-COMPILE-ERROR", "parsing and compilation failed");
}
return;
}
assert(!module);
// create module for code
QorePythonReferenceHolder new_module(PyImport_ExecCodeModule(src_label->c_str(), *python_code));
if (!new_module) {
if (!checkPythonException(xsink)) {
xsink->raiseException("PYTHON-COMPILE-ERROR", "compile failed");
}
return;
}
module = new_module.release();
// returns a borrowed reference
setGlobalDictionary(*module);
PyDict_SetItemString(module_dict, "qoreloader", *qoreloader);
// use the parent Program object as the source for importing
qpgm = getProgram();
owns_qore_program_ref = false;
pyns = qpgm->findNamespace(QORE_PYTHON_NS_NAME);
assert(pyns);
//printd(5, "QorePythonProgram::QorePythonProgram() this: %p pgm: %p rootns: %p\n", this, qpgm,
// qpgm->getRootNS());
// create Qore program object with the same restrictions as the parent
//createQoreProgram();
needs_deregistration = qpy_register(this);
}
int QorePythonProgram::setGlobalDictionary(PyObject* mod) {
module_dict = PyModule_GetDict(mod);
assert(module_dict);
// returns a borrowed reference
builtin_dict = PyDict_GetItemString(module_dict, "__builtins__");
assert(builtin_dict);
return 0;
}
void QorePythonProgram::createQoreProgram() {
// create Qore program object with the same restrictions as the parent
QoreProgram* pgm = getProgram();
int64 parse_options = pgm ? pgm->getParseOptions64() : 0;
qpgm = new QoreProgram(parse_options);
owns_qore_program_ref = true;
pyns = PNS->copy();
qpgm->getRootNS()->addNamespace(pyns);
qpgm->setExternalData(QORE_PYTHON_MODULE_NAME, this);
//printd(5, "QorePythonProgram::createQoreProgram() this: %p pgm: %p rootns: %p\n", this, qpgm,
// qpgm->getRootNS());
}
QorePythonProgram* QorePythonProgram::getExecutionContext() {
QorePythonProgram* pypgm = reinterpret_cast<QorePythonProgram*>(q_get_thread_local_data(python_u_tld_key));
if (pypgm && pypgm->qpgm) {
return pypgm;
}
//printd(5, "QorePythonProgram::getExecutionContext() current pypgm context %p has no Qore Program context\n",
// pypgm);
return getContext();
}
QorePythonProgram* QorePythonProgram::getContext() {
QorePythonProgram* pypgm;
// first try to get the actual Program context
QoreProgram* pgm = getProgram();
if (pgm) {
pypgm = static_cast<QorePythonProgram*>(pgm->getExternalData(QORE_PYTHON_MODULE_NAME));
if (pypgm) {
//printd(5, "QorePythonProgram::getContext() got local program context pgm: %p pypgm: %p\n", pgm, pypgm);
return pypgm;
}
}
pgm = qore_get_call_program_context();
if (pgm) {
pypgm = static_cast<QorePythonProgram*>(pgm->getExternalData(QORE_PYTHON_MODULE_NAME));
if (pypgm) {
//printd(5, "QorePythonProgram::getContext() got local call context pgm: %p pypgm: %p\n", pgm, pypgm);
return pypgm;
}
}
//printd(5, "QorePythonProgram::getContext() got global program context pypgm: %p\n", pypgm);
return qore_python_pgm;
}
int QorePythonProgram::staticInit() {
PyDateTime_IMPORT;
assert(PyDateTimeAPI);
return 0;
}
void QorePythonProgram::waitForThreadsIntern() {
while (pgm_thr_cnt) {
++pgm_thr_waiting;
pgm_thr_cond.wait(py_thr_lck);
--pgm_thr_waiting;
}
}
void QorePythonProgram::deleteIntern(ExceptionSink* xsink) {
if (destroyed) {
return;
}
destroyed = true;
if (needs_deregistration) {
qpy_deregister(this);
}
printd(5, "QorePythonProgram::deleteIntern() this: %p i: %p oi: %d\n", this, interpreter, owns_interpreter);
if (q_libqore_exiting()) {
#ifdef DEBUG
qpgm = nullptr;
#endif
return;
}
if (qpgm && owns_qore_program_ref) {
// remove the external data before dereferencing
qpgm->removeExternalData(QORE_PYTHON_MODULE_NAME);
qpgm->waitForTerminationAndDeref(xsink);
}
qpgm = nullptr;
// remove all thread states; the objects will be deleted by Python when the interpreter is destroyed
{
AutoLocker al(py_thr_lck);
if (interpreter) {
// wait for threads to complete before deleting entries
waitForThreadsIntern();
py_thr_map_t::iterator i = py_thr_map.find(this);
assert(i != py_thr_map.end());
//printd(5, "QorePythonProgram::deleteIntern() this: %p removing all thread states for pgm (delta: %d)\n",
// this, (int)i->second.size());
for (auto& ti : i->second) {
//printd(5, "QorePythonProgram::deleteIntern() this: %p removing TID %d\n", this, ti.first);
py_global_tid_map_t::iterator gi = py_global_tid_map.find(ti.first);
assert(gi != py_global_tid_map.end());
py_thr_set_t::iterator thr_i = gi->second.find(ti.second.state);
if (thr_i != gi->second.end()) {
gi->second.erase(thr_i);
}
}
py_thr_map.erase(i);
assert(pgm_count > 0);
--pgm_count;
}
}
if ((interpreter && owns_interpreter)) {
{
QorePythonHelper qph(this);
for (auto& i : obj_sink) {
Py_DECREF(i);
}
for (auto& i : meth_vec) {
delete i;
}
meth_vec.clear();
module.purge();
python_code.purge();
for (auto& i : py_cls_map) {
delete i.second;
}
py_cls_map.clear();
valid = false;
}
if (interpreter && owns_interpreter) {
// grab the GIL with the main thread lock
QorePythonGilHelper pgh;
{
// enforce serialization
AutoLocker al(py_thr_lck);
assert(_qore_PyRuntimeGILState_GetThreadState());
PyInterpreterState_Clear(interpreter);
}
PyInterpreterState_Delete(interpreter);
interpreter = nullptr;
owns_interpreter = false;
}
}
if (save_object_callback) {
save_object_callback = nullptr;
}
//printd(5, "QorePythonProgram::deleteIntern() this: %p\n", this);
}
QoreValue QorePythonProgram::eval(ExceptionSink* xsink, const QoreString& source_code, const QoreString& source_label,
int input, bool encapsulate) {
TempEncodingHelper src_code(source_code, QCS_UTF8, xsink);
if (*xsink) {
xsink->appendLastDescription(" (while processing the \"source_code\" argument)");
return QoreValue();
}
TempEncodingHelper src_label(source_label, QCS_UTF8, xsink);
if (*xsink) {
xsink->appendLastDescription(" (while processing the \"source_label\" argument)");
return QoreValue();
}
// ensure atomic access to the Python interpreter (GIL) and manage the Python thread state
QorePythonHelper qph(this);
if (checkValid(xsink)) {
return QoreValue();
}
QorePythonReferenceHolder return_value;
QorePythonReferenceHolder python_code;
{
//printd(5, "QorePythonProgram::QorePythonProgram() GIL thread state: %p\n", PyGILState_GetThisThreadState());
// parse and compile code
python_code = (PyObject*)Py_CompileString(src_code->c_str(), src_label->c_str(), input);
if (!python_code) {
if (!checkPythonException(xsink)) {
xsink->raiseException("PYTHON-COMPILE-ERROR", "parsing and compilation failed");
}
return QoreValue();
}
}
PyObject* main_dict;
if (encapsulate) {
// returns a borrowed reference
PyObject* main = PyImport_AddModule("__main__");
// returns a borrowed reference
main_dict = PyModule_GetDict(main);
} else {
assert(module);
// returns a borrowed reference
main_dict = PyModule_GetDict(*module);
}
return_value = PyEval_EvalCode(*python_code, main_dict, main_dict);
// check for Python exceptions
if (checkPythonException(xsink)) {
return QoreValue();
}
return getQoreValue(xsink, return_value);
}
void QorePythonProgram::pythonThreadCleanup(void*) {
int tid = q_gettid();
//printd(5, "QorePythonProgram::pythonThreadCleanup()\n");
// issue #4651: when called when the Qore library and the python module are initialized from Java during static
// process destruction, exit handlers may have already destroyed the static objects in this module
if (py_thr_lck.trylock()) {
return;
}
// delete all thread states for the tid
for (auto& i : py_thr_map) {
py_tid_map_t::iterator ti = i.second.find(tid);
if (ti != i.second.end()) {
//printd(5, "QorePythonProgram::pythonThreadCleanup() deleting state %p for TID %d", ti->second, tid);
i.second.erase(ti);
}
}
// delete reverse lookups
py_global_tid_map_t::iterator gi = py_global_tid_map.find(tid);
if (gi != py_global_tid_map.end()) {
//printd(5, "QorePythonProgram::pythonThreadCleanup() deleting global info for TID %d", tid);
py_global_tid_map.erase(gi);
}
//printd(5, "QorePythonProgram::pythonThreadCleanup() done\n");
py_thr_lck.unlock();
}
bool QorePythonProgram::haveGil() {
if (!_qore_PyCeval_GetGilLockedStatus()) {
return false;
}
PyThreadState* tstate = _qore_PyCeval_GetThreadState();
if (!tstate) {
return false;
}
int tid = q_gettid();
AutoLocker al(py_thr_lck);
py_global_tid_map_t::iterator i = py_global_tid_map.find(tid);
if (i != py_global_tid_map.end()) {
return i->second.find(tstate) != i->second.end();
}
return false;
}
bool QorePythonProgram::haveGilUnlocked(PyThreadState* check_tstate) {
if (!_qore_PyCeval_GetGilLockedStatus()) {
return false;
}
PyThreadState* tstate = _qore_PyCeval_GetThreadState();
return tstate == check_tstate;
}
int QorePythonProgram::createInterpreter(QorePythonGilHelper& qpgh, ExceptionSink* xsink) {
assert(PyGILState_Check());
PyThreadState* python;
{
// enforce serialization
AutoLocker al(py_thr_lck);
python = Py_NewInterpreter();
if (!python) {
if (xsink) {
xsink->raiseException("PYTHON-COMPILE-ERROR", "error creating the Python subinterpreter");
}
return -1;
}
assert(python->gilstate_counter == 1);
//printd(5, "QorePythonProgram::createInterpreter() created thead state: %p\n", python);
// NOTE: we have to reenable PyGILState_Check() here
_QORE_PYTHON_REENABLE_GIL_CHECK
qpgh.set(python);
}
interpreter = python->interp;
owns_interpreter = true;
printd(5, "QorePythonProgram::createInterpreter() interpreter: %p\n", interpreter);
// save thread state
int tid = q_gettid();
AutoLocker al(py_thr_lck);
{
py_thr_map_t::iterator ti = py_thr_map.lower_bound(this);
if (ti == py_thr_map.end() || ti->first != this) {
py_thr_map.insert(ti, {this, {{tid, {python, true}}}});
} else {
ti->second[tid] = {python, true};
}
}
{
py_global_tid_map_t::iterator i = py_global_tid_map.lower_bound(tid);
if (i == py_global_tid_map.end() || i->first != tid) {
py_global_tid_map.insert(i, {tid, {python}});
} else {
i->second.insert(python);
}
//printd(5, "QorePythonProgram::createInterpreter() inserted TID %d -> %p\n", tid, python);
}
++pgm_count;
//printd(5, "QorePythonProgram::createInterpreter() this: %p\n", this);
return setRecursionLimit(xsink);
}
int QorePythonProgram::getRecursionLimit() {
#if QORE_VERSION_CODE > 10007
//printd(5, "QorePythonProgram::getRecursionLimit() stack remaining: %lld total size: %lld\n",
// q_thread_stack_remaining(), q_thread_get_this_stack_size());
// for some reason the recusion depth needs to be calculated smaller with smaller stack sizes
// testing results in using an estimated 6K python stack frame size for stacks 1M and smaller
// and 10K for larger stacks
int64 ss = (int64)q_thread_stack_remaining();
int64 lim;
if (ss > (1024 * 1024)) {
lim = (int64)q_thread_stack_remaining() / PYTHON_LARGE_STACK_FACTOR;
} else {
lim = (int64)q_thread_stack_remaining() / PYTHON_SMALL_STACK_FACTOR;
}
#else // q_thread_stack_remaining() was broken in Qore < 1.0.8
int64 lim = (int64)q_thread_get_stack_size() / PYTHON_SMALL_STACK_FACTOR;
#endif
return lim;
}
int QorePythonProgram::setRecursionLimit(ExceptionSink* xsink) {
QorePythonReferenceHolder sys(PyImport_ImportModule("sys"));
if (!sys) {
if (!checkPythonException(xsink)) {
xsink->raiseException("PYTHON-ERROR", "cannot load the 'sys' module");
}
return -1;
}
if (!PyObject_HasAttrString(*sys, "setrecursionlimit")) {
xsink->raiseException("PYTHON-ERROR", "'sys.setrecursionlimit' not found");
return -1;
}
QorePythonReferenceHolder func(PyObject_GetAttrString(*sys, "setrecursionlimit"));
assert(PyCFunction_Check(*func));
//printd(5, "QorePythonProgram::setRecursionLimit() setrecursionlimit: %s\n", Py_TYPE(*func)->tp_name);
// use the q_thread_stack_remaining() API if Qore >= 1.0.8
QorePythonReferenceHolder py_args(PyTuple_New(1));
PyTuple_SET_ITEM(*py_args, 0, PyLong_FromLongLong(getRecursionLimit()));
QorePythonReferenceHolder return_value(PyCFunction_Call(*func, *py_args, nullptr));
return checkPythonException(xsink);
}
QorePythonThreadInfo QorePythonProgram::setContext() const {
if (!valid) {
return {nullptr, nullptr, nullptr, PyGILState_UNLOCKED, 0, false};
}
assert(interpreter);
PyThreadState* python = getAcquireThreadState();
// create new thread state if necessary
if (!python) {
python = PyThreadState_New(interpreter);
printd(5, "QorePythonProgram::setContext() this: %p created new thread context: %p (py_thr_map: %p "
"size: %d)\n", this, python, &py_thr_map, (int)py_thr_map.size());
assert(python);
assert(python->gilstate_counter == 1);
// the thread state will be deleted when the thread terminates or the interpreter is deleted
int tid = q_gettid();
AutoLocker al(py_thr_lck);
{
py_thr_map_t::iterator i = py_thr_map.find(this);
if (i == py_thr_map.end()) {
py_thr_map[this] = {{tid, {python, owns_interpreter}}};
} else {
assert(i->second.find(tid) == i->second.end());
i->second[tid] = {python, owns_interpreter};
}
assert(py_thr_map.find(this) != py_thr_map.end());
}
{
py_global_tid_map_t::iterator i = py_global_tid_map.lower_bound(tid);
if (i == py_global_tid_map.end() || i->first != tid) {
py_global_tid_map.insert(i, {tid, py_thr_set_t {python,}});
} else {
i->second.insert(python);
}
//printd(5, "QorePythonProgram::setContext() inserted TID %d -> %p\n", tid, python);
}
//printd(5, "QorePythonProgram::setContext() this: %p\n", this);
}
printd(5, "QorePythonProgram::setContext() got thread context: %p (GIL: %d hG: %d) refs: %d\n", python,
PyGILState_Check(), haveGil(), python->gilstate_counter);
PyGILState_STATE g_state;
// the TSS state needs to be restored in any case
PyThreadState* tss_state = PyGILState_GetThisThreadState();
PyThreadState* t_state, * ceval_state;
// set new TSS thread state
if (tss_state != python) {
_qore_PyGILState_SetThisThreadState(python);
}
// are we currently holding the GIL?
if (_qore_has_gil(tss_state)) {
// set GIL context
ceval_state = _qore_PyCeval_SwapThreadState(python);
g_state = PyGILState_LOCKED;
} else {
ceval_state = nullptr;
PyEval_RestoreThread(python);
g_state = PyGILState_UNLOCKED;
}
t_state = _qore_PyRuntimeGILState_GetThreadState();
if (t_state != python) {
PyThreadState_Swap(python);
}
// now we have the GIL
assert(PyGILState_Check());
assert(haveGilUnlocked(python));
assert(_qore_PyCeval_GetThreadState() == python);
assert(_qore_PyRuntimeGILState_GetThreadState() == python);
// TSS state
assert(PyGILState_GetThisThreadState() == python);
//printd(5, "QorePythonProgram::setContext() old thread context: %p\n", t_state);
++python->gilstate_counter;
// calculate new recursion depth
int recursion_depth = PyThreadState_GetRecursionLimit(python);
// be conservative when calculating the new recursion depth
int new_recursion_depth = q_thread_stack_used() / PYTHON_SMALL_STACK_FACTOR;
//printd(5, "QorePythonProgram::setContext() recursion_depth: %d -> %d\n", python->recursion_depth,
// new_recursion_depth);
PyThreadState_UpdateRecursionLimit(python, new_recursion_depth);
return {tss_state, t_state, ceval_state, g_state, recursion_depth, true};
}
void QorePythonProgram::releaseContext(const QorePythonThreadInfo& oldstate) const {
if (!oldstate.valid) {
return;
}
//struct _gilstate_runtime_state* gilstate = &_PyRuntime.gilstate;
PyThreadState* python = getReleaseThreadState();
assert(python);
assert(_qore_PyThreadState_IsCurrent(python));
//printd(5, "QorePythonProgram::releaseContext() rd: %d -> ord: %d\n", PyThreadState_GetRecursionLimit(python),
// oldstate.recursion_depth);
// restore recursion depth
PyThreadState_UpdateRecursionLimit(python, oldstate.recursion_depth);
// restore the old state
if (oldstate.ceval_state != python) {
// set GIL context
_qore_PyCeval_SwapThreadState(oldstate.ceval_state);
}
--python->gilstate_counter;
//printd(5, "QorePythonProgram::releaseContext() t_state: %p g_state: %d\n", oldstate.t_state, oldstate.g_state);
if (oldstate.g_state == PyGILState_UNLOCKED) {
PyEval_ReleaseThread(python);
// NOTE we cannot assert !PyGILState_Check() here, as we have released the GIL, and another thread may have
// created a new interpreter, which will temporarily disbale the GIL check, which would cause
// PyGILState_Check() to return 1
} else {
if (python != oldstate.t_state) {
PyThreadState_Swap(oldstate.t_state);
}
}
// set new TSS thread state
if (oldstate.tss_state != python) {
_qore_PyGILState_SetThisThreadState(oldstate.tss_state);
}
}
PythonQoreClass* QorePythonProgram::findCreatePythonClass(const QoreClass& cls, const char* mod_name) {
printd(5, "QorePythonProgram::findCreatePythonClass() %s.%s\n", mod_name, cls.getName());
py_cls_map_t::iterator i = py_cls_map.lower_bound(&cls);
if (i != py_cls_map.end() && i->first == &cls) {
printd(5, "QorePythonProgram::findCreatePythonClass() returning existing %s.%s\n", mod_name, cls.getName());
return i->second;
}
std::unique_ptr<PythonQoreClass> py_cls(new PythonQoreClass(this, mod_name, cls, i));
PyTypeObject* t = py_cls->getPythonType();
printd(5, "QorePythonProgram::findCreatePythonClass() returning new %s.%s type: %p (%s)\n", mod_name,
cls.getName(), t, t->tp_name);
//py_cls_map.insert(i, py_cls_map_t::value_type(&cls, py_cls.get()));
return py_cls.release();
}
struct func_capsule_t {
const QoreExternalFunction& func;
QorePythonProgram* py_pgm;
DLLLOCAL func_capsule_t(const QoreExternalFunction& func, QorePythonProgram* py_pgm)
: func(func), py_pgm(py_pgm) {
}
};
static void func_capsule_destructor(PyObject* func_capsule) {
func_capsule_t* fc = reinterpret_cast<func_capsule_t*>(PyCapsule_GetPointer(func_capsule, nullptr));
delete fc;
}
int QorePythonProgram::importQoreFunctionToPython(PyObject* mod, const QoreExternalFunction& func) {
printd(5, "QorePythonProgram::importQoreFunctionToPython() %s()\n", func.getName());
std::unique_ptr<func_capsule_t> fc(new func_capsule_t(func, this));
QorePythonReferenceHolder capsule(PyCapsule_New((void*)fc.release(), nullptr, func_capsule_destructor));
std::unique_ptr<PyMethodDef> funcdef(new PyMethodDef);
funcdef->ml_name = func.getName();
funcdef->ml_meth = callQoreFunction;
funcdef->ml_flags = METH_VARARGS;
funcdef->ml_doc = nullptr;
meth_vec.push_back(funcdef.get());
QorePythonReferenceHolder pyfunc(PyCFunction_New(funcdef.release(), *capsule));
assert(pyfunc);
if (PyObject_SetAttrString(mod, func.getName(), *pyfunc)) {
assert(PyErr_Occurred());
printd(5, "QorePythonProgram::importQoreFunctionToPython() error setting function %s in %p (%s)\n",
func.getName(), mod, Py_TYPE(mod)->tp_name);
return -1;
}
printd(5, "QorePythonProgram::importQoreFunctionToPython() ns: %p (%s) %s = %p\n", mod, Py_TYPE(mod)->tp_name,
func.getName(), &func);
return 0;
}
int QorePythonProgram::saveQoreObjectFromPython(const QoreValue& rv, ExceptionSink& xsink) {
// save object in thread-local data if relevant
if (rv.getType() != NT_OBJECT) {
return 0;
}
//printd(5, "QorePythonProgram::saveQoreObjectFromPython() this: %p val: %s soc: %p\n", this,
// rv.getFullTypeName(), *save_object_callback);
if (save_object_callback) {
ReferenceHolder<QoreListNode> args(new QoreListNode(autoTypeInfo), &xsink);
args->push(rv.refSelf(), &xsink);
save_object_callback->execValue(*args, &xsink);
if (xsink) {
raisePythonException(xsink);
return -1;
}
return 0;
}
return saveQoreObjectFromPythonDefault(rv, xsink);
}
int QorePythonProgram::saveQoreObjectFromPythonDefault(const QoreValue& rv, ExceptionSink& xsink) {
QoreHashNode* data = qpgm->getThreadData();
assert(data);
const char* domain_name;
// get key name where to save the data if possible
QoreValue v = data->getKeyValue("_python_save");
if (v.getType() != NT_STRING) {
domain_name = "_python_save";
} else {
domain_name = v.get<const QoreStringNode>()->c_str();
}
QoreValue kv = data->getKeyValue(domain_name);
// ignore operation if domain exists but is not a list
if (!kv || kv.getType() == NT_LIST) {
QoreListNode* list;
ReferenceHolder<QoreListNode> list_holder(&xsink);
if (!kv) {
// we need to assign list in data *after* we prepend the object to the list
// in order to manage object counts
list = new QoreListNode(autoTypeInfo);
list_holder = list;
} else {
list = kv.get<QoreListNode>();
}
// prepend to list to ensure FILO destruction order
list->splice(0, 0, rv, &xsink);
if (!xsink && list_holder) {
data->setKeyValue(domain_name, list_holder.release(), &xsink);
}
if (xsink) {
raisePythonException(xsink);
return -1;
}
//printd(5, "saveQoreObjectFromPythonDefault() domain: '%s' obj: %p %s\n", domain_name, rv.get<QoreObject>(),
// rv.get<QoreObject>()->getClassName());
} else {
//printd(5, "saveQoreObjectFromPythonDefault() NOT SAVING domain: '%s' HAS KEY v: %s (kv: %s)\n", domain_name,
// rv.getFullTypeName(), kv.getFullTypeName());
}
return 0;
}
void QorePythonProgram::raisePythonException(ExceptionSink& xsink) {
assert(xsink);
QoreValue err(xsink.getExceptionErr());
QoreValue desc(xsink.getExceptionDesc());
QoreValue arg(xsink.getExceptionArg());
ExceptionSink xsink2;
QorePythonReferenceHolder tuple(PyTuple_New(arg ? 3 : 2));
QorePythonReferenceHolder ex_arg(getPythonValue(err, &xsink2));
if (ex_arg) {
PyTuple_SET_ITEM(*tuple, 0, ex_arg.release());
} else {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(*tuple, 0, Py_None);
}
ex_arg = getPythonValue(desc, &xsink2);
if (ex_arg) {
PyTuple_SET_ITEM(*tuple, 1, ex_arg.release());
} else {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(*tuple, 1, Py_None);
}
if (arg) {
ex_arg = getPythonValue(arg, &xsink2);
if (ex_arg) {
PyTuple_SET_ITEM(*tuple, 2, ex_arg.release());
} else {
Py_INCREF(Py_None);
PyTuple_SET_ITEM(*tuple, 2, Py_None);
}
}
xsink.clear();
ex_arg = PyObject_CallObject((PyObject*)&PythonQoreException_Type, *tuple);
//printd(5, "QorePythonProgram::raisePythonException() py_ex: %p %s\n", *ex_arg, Py_TYPE(*ex_arg)->tp_name);
PyErr_SetObject((PyObject*)&PythonQoreException_Type, *ex_arg);
}
// import Qore definitions to Python
void QorePythonProgram::importQoreToPython(PyObject* mod, const QoreNamespace& ns, const char* mod_name) {
//printd(5, "QorePythonProgram::importQoreToPython() mod: %p (%d) ns: %p '%s' mod name: '%s'\n", mod,
// Py_REFCNT(mod), &ns, ns.getName(), mod_name);
// import all functions
QoreNamespaceFunctionIterator fi(ns);
while (fi.next()) {
const QoreExternalFunction& func = fi.get();
// do not import deprecated functions
if (func.getCodeFlags() & QCF_DEPRECATED) {
continue;
}
if (importQoreFunctionToPython(mod, func)) {
return;
}
}
// import all constants
QoreNamespaceConstantIterator consti(ns);
while (consti.next()) {
if (importQoreConstantToPython(mod, consti.get())) {
return;
}
}
// import all classes
QoreNamespaceClassIterator clsi(ns);
while (clsi.next()) {
if (importQoreClassToPython(mod, clsi.get(), mod_name)) {
return;
}
}
// import all subnamespaces as modules
QoreNamespaceNamespaceIterator ni(ns);
while (ni.next()) {
if (importQoreNamespaceToPython(mod, ni.get())) {
return;
}
}
}
int QorePythonProgram::importQoreConstantToPython(PyObject* mod, const QoreExternalConstant& constant) {
//printd(5, "QorePythonProgram::importQoreConstantToPython() %s\n", constant.getName());
ExceptionSink xsink;
ValueHolder qoreval(constant.getReferencedValue(), &xsink);
if (!xsink) {
QorePythonReferenceHolder val(qore_python_pgm->getPythonValue(*qoreval, &xsink));
if (!xsink) {
if (!PyObject_SetAttrString(mod, constant.getName(), *val)) {
return 0;
}
}
}
raisePythonException(xsink);
return -1;
}
int QorePythonProgram::importQoreClassToPython(PyObject* mod, const QoreClass& cls, const char* mod_name) {
PyTypeObject* py_cls = findCreatePythonClass(cls, mod_name)->getPythonType();
//printd(5, "QorePythonProgram::importQoreClassToPython() py_cls: %p ('%s') cn: '%s' mod_name: '%s'\n", py_cls,
// py_cls->tp_name, cls.getName(), mod_name);
PyObject* clsobj = (PyObject*)py_cls;
if (PyObject_SetAttrString(mod, cls.getName(), clsobj)) {
return -1;
}
return 0;
}
int QorePythonProgram::importQoreNamespaceToPython(PyObject* mod, const QoreNamespace& ns) {
//printd(5, "QorePythonProgram::importQoreNamespaceToPython() %s\n", ns.getName());
assert(PyModule_Check(mod));
QoreStringMaker nsname("%s.%s", PyModule_GetName(mod), ns.getName());
// create a submodule
QorePythonReferenceHolder new_mod(newModule(nsname.c_str(), &ns));
printd(5, "QorePythonProgram::importQoreNamespaceToPython() (mod) created new module '%s'\n", nsname.c_str());
importQoreToPython(*new_mod, ns, nsname.c_str());
if (PyObject_SetAttrString(mod, ns.getName(), *new_mod)) {
return -1;
}
return 0;
}
PyObject* QorePythonProgram::newModule(const char* name, const QoreNamespace* ns_pkg) {
//QorePythonReferenceHolder new_mod(PyModule_New(name));
QorePythonReferenceHolder new_mod(ModuleNamespace_New(name, ns_pkg));
if (ns_pkg) {
std::string nspath = ns_pkg->getPath();
QorePythonReferenceHolder path(PyUnicode_FromStringAndSize(nspath.c_str(), nspath.size()));
PyObject_SetAttrString(*new_mod, "__path__", *path);
}
saveModule(name, *new_mod);
return new_mod.release();
}
PyObject* QorePythonProgram::newModule(const char* name, const char* path) {
QorePythonReferenceHolder new_mod(PyModule_New(name));
QorePythonReferenceHolder py_path(PyUnicode_FromStringAndSize(path, strlen(path)));