-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQorePythonProgram.cpp
More file actions
4160 lines (3697 loc) · 168 KB
/
Copy pathQorePythonProgram.cpp
File metadata and controls
4160 lines (3697 loc) · 168 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 - 2026 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;
}
#if defined(DEBUG) && !defined(Py_GIL_DISABLED)
// 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;
QoreThreadLock QorePythonProgram::main_ts_lck;
unsigned QorePythonProgram::pgm_count = 0;
QorePythonProgram::QorePythonProgram() : save_object_callback(nullptr) {
printd(5, "QorePythonProgram::QorePythonProgram() this: %p\n", this);
qpy_global_register(this);
#if PY_VERSION_HEX >= 0x030D0000
// Python 3.13+: PyGILState_Check() and PyGILState_GetThisThreadState() check Python's
// Thread Specific Storage (TSS/autoTSSkey). When external modules like JNI are loaded,
// they can clear or corrupt Python's TSS without affecting actual GIL ownership.
// Use our own tracking exclusively - it's maintained independently and remains reliable.
assert(_qore_PyCeval_GetGilLockedStatus());
PyThreadState* python = _qore_PyRuntimeGILState_GetThreadState();
assert(python);
interpreter = python->interp;
#else
assert(PyGILState_Check());
bool have_gil = PyGILState_Check();
PyThreadState* python;
if (have_gil) {
assert(_qore_PyRuntimeGILState_GetThreadState() == PyGILState_GetThisThreadState());
python = PyGILState_GetThisThreadState();
interpreter = python->interp;
} else {
python = nullptr;
interpreter = _PyGILState_GetInterpreterStateUnsafe();
}
#endif
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) {
qpy_global_register(this);
// Two-phase locking to avoid deadlocks:
// Phase 1: Use main_ts_lck to serialize mainThreadState access during GIL acquisition
// Phase 2: Use py_thr_lck for thread map updates (after we have our own thread state)
// This avoids deadlock because:
// - Constructor: main_ts_lck -> GIL -> py_thr_lck (acquires in this order)
// - setContext/releaseContext: py_thr_lck (brief) -> GIL (no conflict with main_ts_lck)
AutoLocker mts_al(main_ts_lck);
QorePythonGilHelper qpgh;
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);
qpy_global_register(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());
// Two-phase locking to avoid deadlocks:
// Phase 1: Use main_ts_lck to serialize mainThreadState access during GIL acquisition
// Phase 2: Use py_thr_lck for thread map updates (inside createInterpreter, after we have our own thread state)
// This avoids deadlock because:
// - Constructor: main_ts_lck -> GIL -> py_thr_lck (acquires in this order)
// - setContext/releaseContext: py_thr_lck (brief) -> GIL (no conflict with main_ts_lck)
AutoLocker mts_al(main_ts_lck);
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();
QoreParseOptions parse_options = pgm ? pgm->getParseOptions() : QoreParseOptions();
qpgm = new QoreProgram(parse_options);
owns_qore_program_ref = true;
pyns = PNS->copy();
qpgm->getRootNS()->addNamespace(pyns);
qpgm->setExternalData(QORE_PYTHON_MODULE_NAME, this);
// Inherit sandbox manager from parent program
if (pgm) {
QoreSandboxManagerHelper smh(pgm);
if (smh) {
qpgm->setSandboxManager(smh.get());
}
}
//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;
// Deregister from global validity tracking FIRST, before anything else
qpy_global_deregister(this);
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)) {
#ifdef Py_GIL_DISABLED
// In free-threading mode, we need a thread state for this interpreter during cleanup
// Create one before any cleanup operations
PyThreadState* cleanup_tstate = PyThreadState_New(interpreter);
if (cleanup_tstate) {
PyThreadState_Swap(cleanup_tstate);
}
// Clean up Python objects with proper thread state active
for (auto& i : obj_sink) {
Py_DECREF(i);
}
obj_sink.clear();
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;
// Properly clean up thread state before interpreter deletion
// Must detach and delete thread state before clearing/deleting interpreter
PyThreadState_Swap(nullptr);
PyThreadState_Clear(cleanup_tstate);
PyThreadState_Delete(cleanup_tstate);
// Use PyInterpreterState_Clear and PyInterpreterState_Delete
// Py_EndInterpreter causes issues with weak references
PyInterpreterState_Clear(interpreter);
PyInterpreterState_Delete(interpreter);
// Signal that an interpreter has been destroyed - must be AFTER deletion
qpy_interpreter_destroyed();
interpreter = nullptr;
owns_interpreter = false;
#else
{
QorePythonHelper qph(this);
for (auto& i : obj_sink) {
Py_DECREF(i);
}
// NOTE: Do NOT delete meth_vec items here - Python function objects still reference them
// They will be deleted after PyInterpreterState_Clear below
module.purge();
python_code.purge();
// CRITICAL: Clear method objects from type dictionaries BEFORE releasing py_type.
// Method objects reference PyMethodDef structures that will be freed after cleanup.
// If method objects survive (e.g., due to references from the main interpreter),
// they'll be traversed during GC and cause use-after-free crashes.
for (auto& i : py_cls_map) {
i.second->clearMethods();
}
// Release Python references from PythonQoreClass objects BEFORE interpreter cleanup.
// We must do this while the interpreter is still valid.
// The actual deletion of PythonQoreClass objects (and their PyMethodDef structures)
// happens AFTER PyInterpreterState_Clear to avoid use-after-free during GC.
for (auto& i : py_cls_map) {
i.second->release();
}
valid = false;
}
if (interpreter && owns_interpreter) {
#if PY_VERSION_HEX >= 0x030D0000
// Python 3.13+ requires that when calling PyInterpreterState_Clear on a sub-interpreter,
// the current thread must have a thread state from that interpreter attached.
// Create a temporary thread state for the sub-interpreter.
{
// Acquire the GIL with main interpreter - keep it held through entire cleanup
QorePythonGilHelper pgh;
// CRITICAL: If Python is shutting down, pgh won't acquire the GIL.
// Skip all Python API cleanup in this case to avoid crashes.
if (!pgh.isInitialized()) {
printd(5, "QorePythonProgram::deleteIntern() skipping cleanup - Python is shutting down\n");
// Clear the interpreter pointer to prevent double-cleanup attempts
interpreter = nullptr;
return;
}
PyThreadState* sub_tstate = PyThreadState_New(interpreter);
assert(sub_tstate);
// Swap to the sub-interpreter's thread state
PyThreadState* old_tstate = PyThreadState_Swap(sub_tstate);
{
// enforce serialization
AutoLocker al(py_thr_lck);
// CRITICAL: Clear our thread state cache BEFORE PyInterpreterState_Clear/Delete.
// PyInterpreterState_Delete() calls zapthreads() which frees all thread states
// attached to this interpreter. If we don't clear our cache, we'll have
// dangling pointers to freed memory.
py_thr_map.erase(this);
PyInterpreterState_Clear(interpreter);
}
// CRITICAL: Before calling PyInterpreterState_Delete, we must clear bound_gilstate
// for ALL thread states of this interpreter (including sub_tstate).
// PyInterpreterState_Delete calls zapthreads which deletes remaining thread states,
// and each delete will call unbind_gilstate_tstate which asserts TSS == tstate.
// Since we'll swap TSS to main interpreter before delete, these assertions will fail.
//
// The _status.bound_gilstate field is in the public cpython/pystate.h header,
// so this works without internal Python headers.
PyThreadState* tstate = PyInterpreterState_ThreadHead(interpreter);
while (tstate) {
qore_py_set_bound_gilstate(tstate, 0);
tstate = PyThreadState_Next(tstate);
}
// Now swap back to the main interpreter's thread state
PyThreadState_Swap(old_tstate);
// Delete sub_tstate - its bound_gilstate is already 0 so no TSS assertion
PyThreadState_Delete(sub_tstate);
// Now delete the interpreter - all thread states have bound_gilstate=0
PyInterpreterState_Delete(interpreter);
interpreter = nullptr; // Clear pointer to prevent dangling reference
}
// QorePythonGilHelper destructor releases the GIL here
#else
// grab the GIL with the main thread lock
QorePythonGilHelper pgh;
// CRITICAL: If Python is shutting down, pgh won't acquire the GIL.
// Skip all Python API cleanup in this case to avoid crashes.
if (!pgh.isInitialized()) {
printd(5, "QorePythonProgram::deleteIntern() skipping cleanup - Python is shutting down\n");
// Clear the interpreter pointer to prevent double-cleanup attempts
interpreter = nullptr;
return;
}
{
// enforce serialization
AutoLocker al(py_thr_lck);
// CRITICAL: Clear our thread state cache BEFORE PyInterpreterState_Clear/Delete.
// PyInterpreterState_Delete() calls zapthreads() which frees all thread states
// attached to this interpreter. If we don't clear our cache, we'll have
// dangling pointers to freed memory.
py_thr_map.erase(this);
// Clear bound_gilstate for all thread states to avoid TSS assertions in 3.12+
PyThreadState* tstate = PyInterpreterState_ThreadHead(interpreter);
while (tstate) {
qore_py_set_bound_gilstate(tstate, 0);
tstate = PyThreadState_Next(tstate);
}
assert(_qore_PyRuntimeGILState_GetThreadState());
PyInterpreterState_Clear(interpreter);
}
PyInterpreterState_Delete(interpreter);
interpreter = nullptr; // Clear pointer to prevent dangling reference
#endif
// Signal that an interpreter has been destroyed - must be AFTER deletion
qpy_interpreter_destroyed();
// Now it's safe to delete PyMethodDef structures since the interpreter is gone
// and Python function objects no longer reference them
for (auto& i : meth_vec) {
delete i;
}
meth_vec.clear();
// Now it's safe to delete PythonQoreClass objects since the interpreter is gone
// and Python method objects no longer reference their PyMethodDef structures
for (auto& i : py_cls_map) {
delete i.second;
}
py_cls_map.clear();
interpreter = nullptr;
owns_interpreter = false;
} else {
// If we don't own the interpreter, still need to clean up
for (auto& i : meth_vec) {
delete i;
}
meth_vec.clear();
for (auto& i : py_cls_map) {
delete i.second;
}
py_cls_map.clear();
}
#endif
}
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, xsink);
if (*xsink || 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) {
#ifndef Py_GIL_DISABLED
#if PY_VERSION_HEX >= 0x030D0000
// Python 3.13+: Use our own tracking since Python's TSS can be cleared by external modules
// (like JNI) without affecting our actual GIL ownership. PyGILState_Check() is unreliable.
assert(_qore_PyCeval_GetGilLockedStatus());
#else
assert(PyGILState_Check());
#endif
#endif
PyThreadState* python;
// NOTE: py_thr_lck must be held by caller to serialize interpreter creation
// and prevent multiple threads from using mainThreadState concurrently.
{
#ifdef Py_GIL_DISABLED
// In free-threading mode, use Py_NewInterpreterFromConfig with appropriate settings
// Share main obmalloc to avoid per-interpreter heap issues
// Require multi-phase init extensions for sub-interpreter compatibility
PyInterpreterConfig config = {
.use_main_obmalloc = 1, // Share main allocator
.allow_fork = 0,
.allow_exec = 0,
.allow_threads = 1,
.allow_daemon_threads = 0,
.check_multi_interp_extensions = 1, // Require multi-phase init extensions
.gil = PyInterpreterConfig_SHARED_GIL, // Shared GIL (no real GIL in free-threading)
};
// CRITICAL: Release the GIL state before creating the sub-interpreter.
// PyGILState_Ensure() (called in QorePythonGilHelper constructor) initializes thread-local
// mimalloc heap data for the main interpreter. If we don't release it, the new sub-interpreter's
// thread state will have a NULL mimalloc heap, causing crashes on any memory allocation.
// This releases the main interpreter's thread state so that Py_NewInterpreterFromConfig can
// properly initialize mimalloc for the new sub-interpreter.
qpgh.releaseBeforeSubInterpreter();
PyStatus status = Py_NewInterpreterFromConfig(&python, &config);
if (PyStatus_Exception(status)) {
if (xsink) {
xsink->raiseException("PYTHON-COMPILE-ERROR", "error creating the Python subinterpreter: %s",
status.err_msg ? status.err_msg : "unknown error");
}
return -1;
}
#else
python = Py_NewInterpreter();
#endif
if (!python) {
if (xsink) {
xsink->raiseException("PYTHON-COMPILE-ERROR", "error creating the Python subinterpreter");
}
return -1;
}
_QORE_GILSTATE_COUNTER_ASSERT_ONE(python);
//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);
// Ensure the sub-interpreter has a usable sys.path (stdlib + extension modules).
const char* pyhome = getenv("PYTHONHOME");
const char* pypath = getenv("PYTHONPATH");
if ((pyhome && *pyhome) || (pypath && *pypath)) {
#ifdef _Q_WINDOWS
const char path_sep = ';';
#else
const char path_sep = ':';
#endif
std::string path;
if (pypath) {
path += pypath;
}
if (pyhome && *pyhome) {
if (!path.empty()) {
path += path_sep;
}
path += pyhome;
path += "/Lib";
path += path_sep;
path += pyhome;
path += "/Modules";
}
PyObject* sys_path = PySys_GetObject("path"); // borrowed
if (!sys_path || !PyList_Check(sys_path)) {
sys_path = PyList_New(0);
if (sys_path) {
PySys_SetObject("path", sys_path);
Py_DECREF(sys_path);
}
}
if (sys_path && PyList_Check(sys_path)) {
size_t start = 0;
// Preserve empty entries to keep CWD semantics (ex: leading/trailing separators).
while (start <= path.size()) {
size_t end = path.find(path_sep, start);
if (end == std::string::npos) {
end = path.size();
}
std::string entry = path.substr(start, end - start);
PyObject* py_entry = PyUnicode_DecodeFSDefault(entry.c_str());
if (py_entry) {
PyList_Append(sys_path, py_entry);
Py_DECREF(py_entry);
}
start = end + 1;
}
}
}
// Ensure PyDateTimeAPI is initialized for this interpreter; the macro only runs if the
// global pointer is null, so clear it to avoid stale main-interpreter state.
PyDateTimeAPI = nullptr;
PyDateTime_IMPORT;
if (!PyDateTimeAPI) {
PyErr_Clear();
}
}
interpreter = python->interp;
owns_interpreter = true;
printd(5, "QorePythonProgram::createInterpreter() interpreter: %p\n", interpreter);
if (!PyDateTimeAPI) {
PyDateTime_IMPORT;
if (!PyDateTimeAPI) {
PyErr_Clear();
PyDateTimeAPI = nullptr;
}
}
// save thread state
// NOTE: Acquire py_thr_lck here for thread map updates.
// The caller holds main_ts_lck (not py_thr_lck) to serialize mainThreadState access.
// This allows setContext/releaseContext to use py_thr_lck without conflicting with main_ts_lck.
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);
}
// setContext() - Acquire the Python execution context for the current thread
//
// This function manages thread state and GIL acquisition to allow safe Python API calls.
// It handles multiple complex scenarios:
// 1. Creating new thread states for threads that don't have one yet
// 2. Reusing cached thread states for threads that have called Python before
// 3. Cross-interpreter thread state switching when a thread moves between PythonPrograms
// 4. Detection and handling of Python-created threads (e.g., threading.Thread callbacks)
// 5. Stale TSS (Thread-Specific Storage) cleanup when interpreters are deleted
//
// Returns QorePythonThreadInfo containing saved state for releaseContext() to restore.
// The caller MUST call releaseContext() when done with Python operations.
//
// Thread safety: Uses py_thr_lck for thread map access, but GIL acquisition happens outside
// the lock to avoid deadlocks. See design/python-module.md for detailed documentation.
QorePythonThreadInfo QorePythonProgram::setContext(bool check_interrupt) const {
// CRITICAL: Check if Python is shutting down before any Python API calls.
// After Py_FinalizeEx(), calling PyGILState_Ensure() or PyEval_RestoreThread() will crash.
if (python_shutdown || !Py_IsInitialized()) {
return {nullptr, nullptr, nullptr, nullptr, PyGILState_UNLOCKED, 0, false};
}
if (!valid) {
return {nullptr, nullptr, nullptr, nullptr, PyGILState_UNLOCKED, 0, false};
}
// Check for interrupt before acquiring any state (only if requested)
if (check_interrupt) {
if (qore_check_cancel(nullptr, "Python execution")) {
return {nullptr, nullptr, nullptr, nullptr, PyGILState_UNLOCKED, 0, false};
}
}
// Safety check: verify our interpreter is still in the global list of interpreters.
// This can happen when another PythonProgram that owned the shared interpreter
// has been destroyed, deleting the interpreter out from under us.
if (!interpreter) {
return {nullptr, nullptr, nullptr, nullptr, PyGILState_UNLOCKED, 0, false};
}
// Check if interpreter is still valid by verifying it's in the global list
{
PyInterpreterState* interp = PyInterpreterState_Head();
bool found = false;
while (interp) {
if (interp == interpreter) {
found = true;
break;
}
interp = PyInterpreterState_Next(interp);
}
if (!found) {
// Interpreter has been deleted - mark ourselves as invalid and return
const_cast<QorePythonProgram*>(this)->valid = false;
return {nullptr, nullptr, nullptr, nullptr, PyGILState_UNLOCKED, 0, false};
}
}
assert(interpreter);
PyThreadState* python = getAcquireThreadState();
// CRITICAL: Verify the cached thread state's interpreter matches ours.
// The thread state's interp pointer can become stale if:
// 1. PyInterpreterState_Clear was called (sets tstate->interp = NULL)
// 2. The thread state was somehow detached from the interpreter
// If the cached thread state isn't in the interpreter's thread list, it's stale/invalid.
if (python) {
bool found = false;
PyThreadState* ts = PyInterpreterState_ThreadHead(interpreter);
while (ts) {
if (ts == python) {
found = true;
break;
}
ts = PyThreadState_Next(ts);
}
if (!found) {
printd(5, "QorePythonProgram::setContext() cached thread state %p not found in interpreter %p "
"thread list - will create new\n", python, interpreter);
// Remove this thread's entry from the cache - it's invalid
{
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()) {
i->second.erase(tid);
}
py_global_tid_map_t::iterator gi = py_global_tid_map.find(tid);
if (gi != py_global_tid_map.end()) {
gi->second.erase(python);
if (gi->second.empty()) {
py_global_tid_map.erase(gi);
}
}
// Don't decrement pgm_thr_cnt here - getAcquireThreadState already incremented it