-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathpythonx.cpp
More file actions
1656 lines (1297 loc) · 55.6 KB
/
pythonx.cpp
File metadata and controls
1656 lines (1297 loc) · 55.6 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
#include <cstddef>
#include <erl_nif.h>
#include <fine.hpp>
#include <iostream>
#include <map>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <string>
#include <thread>
#include <tuple>
#include <variant>
#include "python.hpp"
extern "C" void pythonx_handle_io_write(const char *message,
const char *eval_info_bytes, bool type);
extern "C" void
pythonx_handle_send_tagged_object(const char *pid_bytes, const char *tag,
pythonx::python::PyObjectPtr *py_object,
const char *eval_info_bytes);
namespace pythonx {
using namespace python;
// State
std::mutex init_mutex;
bool is_initialized = false;
std::wstring python_home_path_w;
std::wstring python_executable_path_w;
std::map<std::string, std::tuple<PyObjectPtr, PyObjectPtr>> compilation_cache;
std::mutex compilation_cache_mutex;
PyInterpreterStatePtr interpreter_state;
std::map<std::thread::id, PyThreadStatePtr> thread_states;
std::mutex thread_states_mutex;
// Wrapper around the Python Global Interpreter Lock (GIL).
//
// To acquire the GIL, the caller simply needs to initialize a new
// guard object. Once the guard object's lifetime ends, the GIL is
// automatically released. This is the use of RAII [1] pattern,
// similarly to `std::lock_guard`.
//
// [1]: https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization
class PyGILGuard {
// The simplest way to implement this guard is to use `PyGILState_Ensure`
// and `PyGILState_Release`, however this can lead to segfaults when
// using libraries depending on pybind11.
//
// pybind11 is a popular library for writing C extensions in Python
// packages. It provides convenient C++ API on top of the Python C
// API. In particular, it provides conveniences for dealing with
// GIL, one of them being `gil_scoped_acquire`. The implementation
// has a bug that results in a dangling pointer being used. This
// bug only appears when the code runs in a non-main thread that
// manages the `gil_scoped_acquire` checks if the calling thread
// already holds GIL with `PyGILState_Ensure` and `PyGILState_Release`.
// Specifically, the GIL, in which case it stores the pointer to
// the corresponding `PyThreadState`. After `PyGILState_Release`,
// the thread state is freed, but subsequent usage of `gil_scoped_acquire`
// still re-uses the pointer. This issues has been reported in [1].
//
// In our case, we evaluate Python code dirty scheduler threads.
// This means that the threads are reused and we acquire the GIL
// every time. In order to avoid the pybind11 bug, we want to avoid
// using `PyGILState_Release`, and instead have a permanent `PyThreadState`
// for each of the dirty scheduler threads. We do this by creating
// new state when the given scheduler thread obtains the GIL for
// the first time. Then, we use `PyEval_RestoreThread` and `PyEval_SaveThread`
// to acquire and release the GIL respectively.
//
// NOTE: the dirty scheduler thread pool is fixed, so the map does
// not grow beyond that. If we ever need to acquire the GIL from
// other threads, we should extend this implementation to either
// allow removing the state on destruction, or have a variant with
// `PyGILState_Ensure` and `PyGILState_Release`, as long as it does
// not fall into the bug described above.
//
// [1]: https://github.com/pybind/pybind11/issues/2888
public:
PyGILGuard() {
auto thread_id = std::this_thread::get_id();
PyThreadStatePtr state;
{
auto guard = std::lock_guard<std::mutex>(thread_states_mutex);
if (thread_states.find(thread_id) == thread_states.end()) {
// Note that PyThreadState_New does not require GIL to be held.
state = PyThreadState_New(interpreter_state);
thread_states[thread_id] = state;
} else {
state = thread_states[thread_id];
}
}
PyEval_RestoreThread(state);
}
~PyGILGuard() { PyEval_SaveThread(); }
};
// Ensures the given object refcount is decremented when the guard
// goes out of scope.
class PyDecRefGuard {
PyObjectPtr py_object;
public:
PyDecRefGuard() : py_object(nullptr) {}
PyDecRefGuard(PyObjectPtr py_object) : py_object(py_object) {}
~PyDecRefGuard() {
if (this->py_object != nullptr) {
Py_DecRef(this->py_object);
}
}
PyDecRefGuard &operator=(PyObjectPtr py_object) {
this->py_object = py_object;
return *this;
}
};
void ensure_initialized() {
auto init_guard = std::lock_guard<std::mutex>(init_mutex);
if (!is_initialized) {
throw std::runtime_error("Python interpreter has not been initialized");
}
}
namespace atoms {
auto ElixirPythonxError = fine::Atom("Elixir.Pythonx.Error");
auto ElixirPythonxJanitor = fine::Atom("Elixir.Pythonx.Janitor");
auto ElixirPythonxObject = fine::Atom("Elixir.Pythonx.Object");
auto decref = fine::Atom("decref");
auto integer = fine::Atom("integer");
auto lines = fine::Atom("lines");
auto list = fine::Atom("list");
auto map = fine::Atom("map");
auto map_set = fine::Atom("map_set");
auto output = fine::Atom("output");
auto remote_info = fine::Atom("remote_info");
auto resource = fine::Atom("resource");
auto tuple = fine::Atom("tuple");
} // namespace atoms
struct PyObjectResource {
PyObjectPtr py_object;
PyObjectResource(PyObjectPtr py_object) : py_object(py_object) {}
void destructor(ErlNifEnv *env) {
// Decrementing refcount requires GIL and we should not block in
// the destructor, so we send a message to a known process and let
// it decrement the refcount for us. Also see [1].
//
// [1]:https://erlangforums.com/t/how-to-deal-with-destructors-that-can-take-a-while-to-run-and-possibly-block-the-scheduler/4290
if (!is_initialized) {
// If we allow multiple initializations, we need to add a counter
// and check that py_object comes from the current initialization
return;
}
auto ptr = reinterpret_cast<uint64_t>(this->py_object);
auto janitor_name = fine::encode(env, atoms::ElixirPythonxJanitor);
ErlNifPid janitor_pid;
if (enif_whereis_pid(env, janitor_name, &janitor_pid)) {
auto msg_env = enif_alloc_env();
auto msg = fine::encode(msg_env, std::make_tuple(atoms::decref, ptr));
enif_send(env, &janitor_pid, msg_env, msg);
enif_free_env(msg_env);
} else {
std::cerr << "[pythonx] whereis(Pythonx.Janitor) failed. This is "
"unexpected and a Python object will not be deallocated"
<< std::endl;
}
}
};
FINE_RESOURCE(PyObjectResource);
// A resource that notifies the given process upon garbage collection.
struct GCNotifier {
ErlNifPid pid;
ErlNifEnv *message_env;
ERL_NIF_TERM message_term;
GCNotifier(ErlNifPid pid, ErlNifEnv *message_env, ERL_NIF_TERM message_term)
: pid(pid), message_env(message_env), message_term(message_term) {}
void destructor(ErlNifEnv *env) {
enif_send(env, &pid, message_env, message_term);
enif_free_env(message_env);
}
};
FINE_RESOURCE(GCNotifier);
struct ExObject {
fine::ResourcePtr<PyObjectResource> resource;
std::optional<fine::Term> remote_info;
ExObject() {}
ExObject(fine::ResourcePtr<PyObjectResource> resource) : resource(resource) {}
static constexpr auto module = &atoms::ElixirPythonxObject;
static constexpr auto fields() {
return std::make_tuple(
std::make_tuple(&ExObject::resource, &atoms::resource),
std::make_tuple(&ExObject::remote_info, &atoms::remote_info));
}
};
struct ExError {
std::vector<fine::Term> lines;
ExError() {}
ExError(std::vector<fine::Term> lines) : lines(lines) {}
static constexpr auto module = &atoms::ElixirPythonxError;
static constexpr auto fields() {
return std::make_tuple(std::make_tuple(&ExError::lines, &atoms::lines));
}
static constexpr auto is_exception = true;
};
struct EvalInfo {
fine::Term stdout_device;
fine::Term stderr_device;
ErlNifEnv *env;
std::thread::id thread_id;
};
void raise_formatting_error_if_failed(PyObjectPtr py_object) {
if (py_object == NULL) {
throw std::runtime_error("failed while formatting a python error");
}
}
void raise_formatting_error_if_failed(const char *buffer) {
if (buffer == NULL) {
throw std::runtime_error("failed while formatting a python error");
}
}
void raise_formatting_error_if_failed(Py_ssize_t size) {
if (size == -1) {
throw std::runtime_error("failed while formatting a python error");
}
}
ExError build_py_error_from_current(ErlNifEnv *env) {
PyObjectPtr py_type, py_value, py_traceback;
PyErr_Fetch(&py_type, &py_value, &py_traceback);
// If the error indicator was set, type should not be NULL, but value
// and traceback might.
if (py_type == NULL) {
throw std::runtime_error("build_py_error_from_current should only be "
"called when the error indicator is set");
}
auto type = ExObject(fine::make_resource<PyObjectResource>(py_type));
// Default value and traceback to None object.
py_value = py_value == NULL ? Py_BuildValue("") : py_value;
py_traceback = py_traceback == NULL ? Py_BuildValue("") : py_traceback;
// Format the exception. Note that if anything raises an error here,
// we throw a runtime exception, instead of a Python one, otherwise
// we could go into an infinite loop.
auto py_traceback_module = PyImport_ImportModule("traceback");
raise_formatting_error_if_failed(py_traceback_module);
auto py_traceback_module_guard = PyDecRefGuard(py_traceback_module);
auto format_exception =
PyObject_GetAttrString(py_traceback_module, "format_exception");
raise_formatting_error_if_failed(format_exception);
auto format_exception_guard = PyDecRefGuard(format_exception);
auto format_exception_args = PyTuple_Pack(3, py_type, py_value, py_traceback);
raise_formatting_error_if_failed(format_exception_args);
auto format_exception_args_guard = PyDecRefGuard(format_exception_args);
auto py_lines = PyObject_Call(format_exception, format_exception_args, NULL);
raise_formatting_error_if_failed(py_lines);
auto py_lines_guard = PyDecRefGuard(py_lines);
auto size = PyList_Size(py_lines);
raise_formatting_error_if_failed(size);
auto terms = std::vector<fine::Term>();
terms.reserve(size);
for (Py_ssize_t i = 0; i < size; i++) {
auto py_line = PyList_GetItem(py_lines, i);
raise_formatting_error_if_failed(py_line);
Py_ssize_t size;
auto buffer = PyUnicode_AsUTF8AndSize(py_line, &size);
raise_formatting_error_if_failed(buffer);
// The buffer is immutable and lives as long as the Python object,
// so we create the term as a resource binary to make it zero-copy.
Py_IncRef(py_line);
auto ex_object_resource = fine::make_resource<PyObjectResource>(py_line);
auto binary_term =
fine::make_resource_binary(env, ex_object_resource, buffer, size);
terms.push_back(binary_term);
}
return ExError(std::move(terms));
}
void raise_py_error(ErlNifEnv *env) {
fine::raise(env, build_py_error_from_current(env));
}
void raise_if_failed(ErlNifEnv *env, PyObjectPtr py_object) {
if (py_object == NULL) {
raise_py_error(env);
}
}
void raise_if_failed(ErlNifEnv *env, const char *buffer) {
if (buffer == NULL) {
raise_py_error(env);
}
}
void raise_if_failed(ErlNifEnv *env, Py_ssize_t size) {
if (size == -1) {
raise_py_error(env);
}
}
ERL_NIF_TERM py_str_to_binary_term(ErlNifEnv *env, PyObjectPtr py_object) {
Py_ssize_t size;
auto buffer = PyUnicode_AsUTF8AndSize(py_object, &size);
raise_if_failed(env, buffer);
// The buffer is immutable and lives as long as the Python object,
// so we create the term as a resource binary to make it zero-copy.
Py_IncRef(py_object);
auto ex_object_resource = fine::make_resource<PyObjectResource>(py_object);
return fine::make_resource_binary(env, ex_object_resource, buffer, size);
}
ERL_NIF_TERM py_bytes_to_binary_term(ErlNifEnv *env, PyObjectPtr py_object) {
Py_ssize_t size;
char *buffer;
auto result = PyBytes_AsStringAndSize(py_object, &buffer, &size);
raise_if_failed(env, result);
// The buffer is immutable and lives as long as the Python object,
// so we create the term as a resource binary to make it zero-copy.
Py_IncRef(py_object);
auto ex_object_resource = fine::make_resource<PyObjectResource>(py_object);
return fine::make_resource_binary(env, ex_object_resource, buffer, size);
}
fine::Ok<> init(ErlNifEnv *env, std::string python_dl_path,
ErlNifBinary python_home_path,
ErlNifBinary python_executable_path,
std::vector<ErlNifBinary> sys_paths) {
auto init_guard = std::lock_guard<std::mutex>(init_mutex);
if (is_initialized) {
throw std::runtime_error("Python interpreter has already been initialized");
}
// Raises runtime error on failure, which is propagated automatically
load_python_library(python_dl_path);
// The path needs to be available for the whole interpreter lifetime,
// so we store it in a global variable.
python_home_path_w = std::wstring(
python_home_path.data, python_home_path.data + python_home_path.size);
python_executable_path_w =
std::wstring(python_executable_path.data,
python_executable_path.data + python_executable_path.size);
// As part of the initialization, sys.path gets set. It is important
// that it gets set correctly, so that the built-in modules can be
// found, otherwise the initialization fails. This logic is internal
// to Python, but we can configure base paths used to infer sys.path.
// The Limited API exposes Py_SetPythonHome and Py_SetProgramName and
// it appears that setting either of them alone should be sufficient.
//
// Py_SetProgramName has the advantage that, when set to the executable
// inside venv, it results in the packages directory being added to
// sys.path automatically, however, when tested, this did not work
// as expected in Python 3.10 on Windows. For this reason we prefer
// to use Py_SetPythonHome and add other paths to sys.path manually.
//
// Even then, we still want to set Py_SetProgramName to a Python
// executable, otherwise `sys.executable` is going to point to the
// BEAM executable (`argv[0]`), which can be problematic.
//
// In the end, the most reliable combination seems to be to set both,
// and also add the extra sys.path manually.
//
// Note that Python home is the directory with lib/ child directory
// containing the built-in Python modules [1].
//
// [1]: https://docs.python.org/3/using/cmdline.html#envvar-PYTHONHOME
Py_SetPythonHome(python_home_path_w.c_str());
Py_SetProgramName(python_executable_path_w.c_str());
Py_InitializeEx(0);
interpreter_state = PyInterpreterState_Get();
// In order to use any of the Python C API functions, the calling
// thread must hold the GIL. Since every NIF call may run on a
// different dirty scheduler thread, we need to acquire the GIL at
// the beginning of each NIF and release it afterwards.
//
// After initializing the Python interpreter above, the current
// thread automatically holds the GIL, so we explicitly release it.
// See pyo3 [1] for an extra reference.
//
// [1]: https://github.com/PyO3/pyo3/blob/v0.23.3/src/gil.rs#L63-L74
thread_states[std::this_thread::get_id()] = PyEval_SaveThread();
is_initialized = true;
// We still hold the init_mutex, so we can obtain the GIL guard
// before any other concurrent NIF. At this point we marked the
// interpreter as initialized and now we continue with further
// preparation using Python APIs. If any exception is subsequently
// raised, it will propagate as expected, and since the interpreter
// is initialized, the exception formatting will also work.
auto gil_guard = PyGILGuard();
// Add extra paths to sys.path
auto py_sys = PyImport_AddModule("sys");
raise_if_failed(env, py_sys);
auto py_sys_path = PyObject_GetAttrString(py_sys, "path");
raise_if_failed(env, py_sys_path);
auto py_sys_path_guard = PyDecRefGuard(py_sys_path);
for (const auto &path : sys_paths) {
auto py_path = PyUnicode_FromStringAndSize(
reinterpret_cast<const char *>(path.data), path.size);
raise_if_failed(env, py_path);
auto py_path_guard = PyDecRefGuard(py_path);
raise_if_failed(env, PyList_Append(py_sys_path, py_path));
}
// Define global stdout and stdin overrides
auto py_builtins = PyEval_GetBuiltins();
raise_if_failed(env, py_builtins);
auto py_exec = PyDict_GetItemString(py_builtins, "exec");
raise_if_failed(env, py_exec);
const char code[] = R"(
import ctypes
import io
import sys
import inspect
import types
import sys
pythonx_handle_io_write = ctypes.CFUNCTYPE(
None, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_bool
)(pythonx_handle_io_write_ptr)
pythonx_handle_send_tagged_object = ctypes.CFUNCTYPE(
None, ctypes.c_char_p, ctypes.c_char_p, ctypes.py_object, ctypes.c_char_p
)(pythonx_handle_send_tagged_object_ptr)
def get_eval_info_bytes():
# The evaluation caller has __pythonx_eval_info_bytes__ set in
# their globals. It is not available in globals() here, because
# the globals dict in function definitions is fixed at definition
# time. To find the current evaluation globals, we look at the
# call stack using the inspect module and find the caller with
# __pythonx_eval_info_bytes__ in globals. We look specifically
# for the outermost caller, because intermediate functions could
# be defined by previous evaluations, in which case they would
# have __pythonx_eval_info_bytes__ in their globals, corresponding
# to that previous evaluation. When called within a thread, the
# evaluation caller is not in the stack, so __pythonx_eval_info_bytes__
# will be found in the thread entrypoint function globals.
call_stack = inspect.stack()
eval_info_bytes = next(
frame_info.frame.f_globals["__pythonx_eval_info_bytes__"]
for frame_info in reversed(call_stack)
if "__pythonx_eval_info_bytes__" in frame_info.frame.f_globals
)
return eval_info_bytes
class Stdout(io.TextIOBase):
def __init__(self, type):
self.type = type
def write(self, string):
pythonx_handle_io_write(string.encode("utf-8"), get_eval_info_bytes(), self.type)
return len(string)
class Stdin(io.IOBase):
def read(self, size=None):
raise RuntimeError("stdin not supported")
sys.stdout = Stdout(0)
sys.stderr = Stdout(1)
sys.stdin = Stdin()
pythonx = types.ModuleType("pythonx")
class PID:
def __init__(self, bytes):
self.bytes = bytes
def __repr__(self):
return "<pythonx.PID>"
pythonx.PID = PID
def send_tagged_object(pid, tag, object):
pythonx_handle_send_tagged_object(pid.bytes, tag.encode("utf-8"), object, get_eval_info_bytes())
pythonx.send_tagged_object = send_tagged_object
sys.modules["pythonx"] = pythonx
)";
auto py_code = PyUnicode_FromStringAndSize(code, sizeof(code) - 1);
raise_if_failed(env, py_code);
auto py_code_guard = PyDecRefGuard(py_code);
auto py_globals = PyDict_New();
raise_if_failed(env, py_globals);
auto py_globals_guard = PyDecRefGuard(py_globals);
raise_if_failed(
env, PyDict_SetItemString(py_globals, "__builtins__", py_builtins));
auto py_pythonx_handle_io_write_ptr = PyLong_FromUnsignedLongLong(
reinterpret_cast<uintptr_t>(pythonx_handle_io_write));
raise_if_failed(env, py_pythonx_handle_io_write_ptr);
auto py_pythonx_handle_io_write_ptr_guard =
PyDecRefGuard(py_pythonx_handle_io_write_ptr);
raise_if_failed(env, PyDict_SetItemString(py_globals,
"pythonx_handle_io_write_ptr",
py_pythonx_handle_io_write_ptr));
auto py_pythonx_handle_send_tagged_object_ptr = PyLong_FromUnsignedLongLong(
reinterpret_cast<uintptr_t>(pythonx_handle_send_tagged_object));
raise_if_failed(env, py_pythonx_handle_send_tagged_object_ptr);
auto py_pythonx_handle_send_tagged_object_ptr_guard =
PyDecRefGuard(py_pythonx_handle_send_tagged_object_ptr);
raise_if_failed(env, PyDict_SetItemString(
py_globals, "pythonx_handle_send_tagged_object_ptr",
py_pythonx_handle_send_tagged_object_ptr));
auto py_exec_args = PyTuple_Pack(2, py_code, py_globals);
raise_if_failed(env, py_exec_args);
auto py_exec_args_guard = PyDecRefGuard(py_exec_args);
auto py_result = PyObject_Call(py_exec, py_exec_args, NULL);
raise_if_failed(env, py_result);
Py_DecRef(py_result);
return fine::Ok<>();
}
FINE_NIF(init, ERL_NIF_DIRTY_JOB_CPU_BOUND);
fine::Ok<> janitor_decref(ErlNifEnv *env, uint64_t ptr) {
auto init_guard = std::lock_guard<std::mutex>(init_mutex);
// If the interpreter is no longer initialized, ignore the call
if (is_initialized) {
auto gil_guard = PyGILGuard();
auto object = reinterpret_cast<PyObjectPtr>(ptr);
Py_DecRef(object);
}
return fine::Ok<>();
}
FINE_NIF(janitor_decref, ERL_NIF_DIRTY_JOB_CPU_BOUND);
ExObject none_new(ErlNifEnv *env) {
ensure_initialized();
auto gil_guard = PyGILGuard();
// Note that Limited API has Py_GetConstant, but only since v3.13
auto py_none = Py_BuildValue("");
raise_if_failed(env, py_none);
return ExObject(fine::make_resource<PyObjectResource>(py_none));
}
FINE_NIF(none_new, ERL_NIF_DIRTY_JOB_CPU_BOUND);
ExObject false_new(ErlNifEnv *env) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto py_bool = PyBool_FromLong(0);
raise_if_failed(env, py_bool);
return ExObject(fine::make_resource<PyObjectResource>(py_bool));
}
FINE_NIF(false_new, ERL_NIF_DIRTY_JOB_CPU_BOUND);
ExObject true_new(ErlNifEnv *env) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto py_bool = PyBool_FromLong(1);
raise_if_failed(env, py_bool);
return ExObject(fine::make_resource<PyObjectResource>(py_bool));
}
FINE_NIF(true_new, ERL_NIF_DIRTY_JOB_CPU_BOUND);
ExObject long_from_int64(ErlNifEnv *env, int64_t number) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto py_long = PyLong_FromLongLong(number);
raise_if_failed(env, py_long);
return ExObject(fine::make_resource<PyObjectResource>(py_long));
}
FINE_NIF(long_from_int64, ERL_NIF_DIRTY_JOB_CPU_BOUND);
ExObject long_from_string(ErlNifEnv *env, std::string string, int64_t base) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto py_long =
PyLong_FromString(string.c_str(), NULL, static_cast<int>(base));
raise_if_failed(env, py_long);
return ExObject(fine::make_resource<PyObjectResource>(py_long));
}
FINE_NIF(long_from_string, ERL_NIF_DIRTY_JOB_CPU_BOUND);
ExObject float_new(ErlNifEnv *env, double number) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto py_float = PyFloat_FromDouble(number);
raise_if_failed(env, py_float);
return ExObject(fine::make_resource<PyObjectResource>(py_float));
}
FINE_NIF(float_new, ERL_NIF_DIRTY_JOB_CPU_BOUND);
ExObject bytes_from_binary(ErlNifEnv *env, ErlNifBinary binary) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto py_object = PyBytes_FromStringAndSize(
reinterpret_cast<const char *>(binary.data), binary.size);
raise_if_failed(env, py_object);
return ExObject(fine::make_resource<PyObjectResource>(py_object));
}
FINE_NIF(bytes_from_binary, ERL_NIF_DIRTY_JOB_CPU_BOUND);
ExObject unicode_from_string(ErlNifEnv *env, ErlNifBinary binary) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto py_object = PyUnicode_FromStringAndSize(
reinterpret_cast<const char *>(binary.data), binary.size);
raise_if_failed(env, py_object);
return ExObject(fine::make_resource<PyObjectResource>(py_object));
}
FINE_NIF(unicode_from_string, ERL_NIF_DIRTY_JOB_CPU_BOUND);
fine::Term unicode_to_string(ErlNifEnv *env, ExObject ex_object) {
ensure_initialized();
auto gil_guard = PyGILGuard();
return py_str_to_binary_term(env, ex_object.resource->py_object);
}
FINE_NIF(unicode_to_string, ERL_NIF_DIRTY_JOB_CPU_BOUND);
ExObject dict_new(ErlNifEnv *env) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto py_dict = PyDict_New();
raise_if_failed(env, py_dict);
return ExObject(fine::make_resource<PyObjectResource>(py_dict));
}
FINE_NIF(dict_new, ERL_NIF_DIRTY_JOB_CPU_BOUND);
fine::Ok<> dict_set_item(ErlNifEnv *env, ExObject ex_object, ExObject ex_key,
ExObject ex_value) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto result =
PyDict_SetItem(ex_object.resource->py_object, ex_key.resource->py_object,
ex_value.resource->py_object);
raise_if_failed(env, result);
return fine::Ok<>();
}
FINE_NIF(dict_set_item, ERL_NIF_DIRTY_JOB_CPU_BOUND);
ExObject tuple_new(ErlNifEnv *env, uint64_t size) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto py_tuple = PyTuple_New(size);
raise_if_failed(env, py_tuple);
return ExObject(fine::make_resource<PyObjectResource>(py_tuple));
}
FINE_NIF(tuple_new, ERL_NIF_DIRTY_JOB_CPU_BOUND);
fine::Ok<> tuple_set_item(ErlNifEnv *env, ExObject ex_object, uint64_t index,
ExObject ex_value) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto result = PyTuple_SetItem(ex_object.resource->py_object, index,
ex_value.resource->py_object);
raise_if_failed(env, result);
// PyTuple_SetItem steals a reference, so we add one back
Py_IncRef(ex_value.resource->py_object);
return fine::Ok<>();
}
FINE_NIF(tuple_set_item, ERL_NIF_DIRTY_JOB_CPU_BOUND);
ExObject list_new(ErlNifEnv *env, uint64_t size) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto py_tuple = PyList_New(size);
raise_if_failed(env, py_tuple);
return ExObject(fine::make_resource<PyObjectResource>(py_tuple));
}
FINE_NIF(list_new, ERL_NIF_DIRTY_JOB_CPU_BOUND);
fine::Ok<> list_set_item(ErlNifEnv *env, ExObject ex_object, uint64_t index,
ExObject ex_value) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto result = PyList_SetItem(ex_object.resource->py_object, index,
ex_value.resource->py_object);
raise_if_failed(env, result);
// PyList_SetItem steals a reference, so we add one back
Py_IncRef(ex_value.resource->py_object);
return fine::Ok<>();
}
FINE_NIF(list_set_item, ERL_NIF_DIRTY_JOB_CPU_BOUND);
ExObject set_new(ErlNifEnv *env) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto py_set = PySet_New(NULL);
raise_if_failed(env, py_set);
return ExObject(fine::make_resource<PyObjectResource>(py_set));
}
FINE_NIF(set_new, ERL_NIF_DIRTY_JOB_CPU_BOUND);
fine::Ok<> set_add(ErlNifEnv *env, ExObject ex_object, ExObject ex_key) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto result =
PySet_Add(ex_object.resource->py_object, ex_key.resource->py_object);
raise_if_failed(env, result);
return fine::Ok<>();
}
FINE_NIF(set_add, ERL_NIF_DIRTY_JOB_CPU_BOUND);
ExObject pid_new(ErlNifEnv *env, ErlNifPid pid) {
ensure_initialized();
auto gil_guard = PyGILGuard();
// ErlNifPid is self-contained struct, not bound to any env, so it's
// safe to copy [1].
//
// [1]: https://www.erlang.org/doc/apps/erts/erl_nif.html#ErlNifPid
auto py_pid_bytes = PyBytes_FromStringAndSize(
reinterpret_cast<const char *>(&pid), sizeof(ErlNifPid));
raise_if_failed(env, py_pid_bytes);
auto py_pythonx = PyImport_AddModule("pythonx");
raise_if_failed(env, py_pythonx);
auto py_PID = PyObject_GetAttrString(py_pythonx, "PID");
raise_if_failed(env, py_PID);
auto py_PID_guard = PyDecRefGuard(py_PID);
auto py_PID_args = PyTuple_Pack(1, py_pid_bytes);
raise_if_failed(env, py_PID_args);
auto py_PID_args_guard = PyDecRefGuard(py_PID_args);
auto py_pid = PyObject_Call(py_PID, py_PID_args, NULL);
raise_if_failed(env, py_pid);
return ExObject(fine::make_resource<PyObjectResource>(py_pid));
}
FINE_NIF(pid_new, ERL_NIF_DIRTY_JOB_CPU_BOUND);
ExObject object_repr(ErlNifEnv *env, ExObject ex_object) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto py_repr = PyObject_Repr(ex_object.resource->py_object);
raise_if_failed(env, py_repr);
return ExObject(fine::make_resource<PyObjectResource>(py_repr));
}
FINE_NIF(object_repr, ERL_NIF_DIRTY_JOB_CPU_BOUND);
fine::Term decode_once(ErlNifEnv *env, ExObject ex_object) {
ensure_initialized();
auto gil_guard = PyGILGuard();
auto py_object = ex_object.resource->py_object;
auto is_none = Py_IsNone(py_object);
raise_if_failed(env, is_none);
if (is_none) {
return fine::encode(env, std::nullopt);
}
auto is_true = Py_IsTrue(py_object);
raise_if_failed(env, is_true);
if (is_true) {
return fine::encode(env, true);
}
auto is_false = Py_IsFalse(py_object);
raise_if_failed(env, is_false);
if (is_false) {
return fine::encode(env, false);
}
auto py_builtins = PyEval_GetBuiltins();
raise_if_failed(env, py_builtins);
auto py_int_type = PyDict_GetItemString(py_builtins, "int");
raise_if_failed(env, py_int_type);
auto is_long = PyObject_IsInstance(py_object, py_int_type);
raise_if_failed(env, is_long);
if (is_long) {
int overflow;
auto integer = PyLong_AsLongLongAndOverflow(py_object, &overflow);
if (PyErr_Occurred() != NULL) {
raise_py_error(env);
}
if (overflow == 0) {
return enif_make_int64(env, integer);
}
// Integer over 64 bits
auto py_str = PyObject_Str(py_object);
raise_if_failed(env, py_str);
auto py_str_guard = PyDecRefGuard(py_str);
auto binary_term = py_str_to_binary_term(env, py_str);
return fine::encode(
env, std::make_tuple(atoms::integer, fine::Term(binary_term)));
}
auto py_float_type = PyDict_GetItemString(py_builtins, "float");
raise_if_failed(env, py_float_type);
auto is_float = PyObject_IsInstance(py_object, py_float_type);
raise_if_failed(env, is_float);
if (is_float) {
double number = PyFloat_AsDouble(py_object);
if (PyErr_Occurred() != NULL) {
raise_py_error(env);
}
return enif_make_double(env, number);
}
auto py_tuple_type = PyDict_GetItemString(py_builtins, "tuple");
raise_if_failed(env, py_tuple_type);
auto is_tuple = PyObject_IsInstance(py_object, py_tuple_type);
raise_if_failed(env, is_tuple);
if (is_tuple) {
auto size = PyTuple_Size(py_object);
raise_if_failed(env, size);
auto terms = std::vector<ERL_NIF_TERM>();
terms.reserve(size);
for (Py_ssize_t i = 0; i < size; i++) {
auto py_item = PyTuple_GetItem(py_object, i);
raise_if_failed(env, py_item);
Py_IncRef(py_item);
auto ex_item = ExObject(fine::make_resource<PyObjectResource>(py_item));
terms.push_back(fine::encode(env, ex_item));
}
auto items = enif_make_list_from_array(env, terms.data(),
static_cast<unsigned int>(size));
return fine::encode(env, std::make_tuple(atoms::tuple, fine::Term(items)));
}
auto py_list_type = PyDict_GetItemString(py_builtins, "list");
raise_if_failed(env, py_list_type);
auto is_list = PyObject_IsInstance(py_object, py_list_type);
raise_if_failed(env, is_list);
if (is_list) {
auto size = PyList_Size(py_object);
raise_if_failed(env, size);
auto terms = std::vector<ERL_NIF_TERM>();
terms.reserve(size);
for (Py_ssize_t i = 0; i < size; i++) {
auto py_item = PyList_GetItem(py_object, i);
raise_if_failed(env, py_item);
Py_IncRef(py_item);
auto ex_item = ExObject(fine::make_resource<PyObjectResource>(py_item));
terms.push_back(fine::encode(env, ex_item));
}
auto items = enif_make_list_from_array(env, terms.data(),
static_cast<unsigned int>(size));
return fine::encode(env, std::make_tuple(atoms::list, fine::Term(items)));
}
auto py_dict_type = PyDict_GetItemString(py_builtins, "dict");
raise_if_failed(env, py_dict_type);
auto is_dict = PyObject_IsInstance(py_object, py_dict_type);
raise_if_failed(env, is_dict);
if (is_dict) {
auto size = PyDict_Size(py_object);
raise_if_failed(env, size);
auto terms = std::vector<ERL_NIF_TERM>();
terms.reserve(size);