This repository was archived by the owner on Feb 13, 2025. It is now read-only.
forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathprickelpit.c
More file actions
2475 lines (2135 loc) · 71 KB
/
prickelpit.c
File metadata and controls
2475 lines (2135 loc) · 71 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 "Python.h"
#ifdef STACKLESS
#include <stddef.h> /* for offsetof() */
#include "compile.h"
#include "pycore_stackless.h"
#include "pycore_slp_prickelpit.h"
/******************************************************
type template and support for pickle helper types
******************************************************/
#if PY_VERSION_HEX >= 0x030502C1
/* issue25718 got fixed in 3.4.4rc1 */
#define NO_STATE_FORMAT "()"
#define NO_STATE_ARG /* nothing */
#else
/* Bug http://bugs.python.org/issue25718 requires, that the state object for
* mutable types has a boolean value of True. Immutable types use a different
* copy.copy() mechanism.
*/
#define NO_STATE_FORMAT "(O)"
#define NO_STATE_ARG ,Py_None
#endif
/* check that we really have the right wrapper type */
static int is_wrong_type(PyTypeObject *type)
{
/* this works because the tp_base's name was modified to
* point into the wrapper's name
*/
if (type->tp_base == NULL ||
strrchr(type->tp_name, '.')+1 != type->tp_base->tp_name) {
PyErr_SetString(PyExc_TypeError, "incorrect wrapper type");
return -1;
}
return 0;
}
/* supporting __setstate__ for the wrapper type */
static PyObject *
generic_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject *inst;
/* we don't want to support derived types here. */
if (is_wrong_type(type))
return NULL;
assert(type->tp_base->tp_new != NULL);
inst = type->tp_base->tp_new(type->tp_base, args, kwds);
if (inst != NULL)
Py_TYPE(inst) = type;
return inst;
}
int
slp_generic_init(PyObject *ob, PyObject *args, PyObject *kwds)
{
initproc init = Py_TYPE(ob)->tp_base->tp_init;
if (init)
return init(ob, args, kwds);
return 0;
}
static PyObject *
generic_setstate(PyObject *self, PyObject *args)
{
if (is_wrong_type(Py_TYPE(self))) return NULL;
Py_TYPE(self) = Py_TYPE(self)->tp_base;
Py_INCREF(self);
return self;
}
/* redirecting cls.__new__ */
static PyObject *
_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
{
PyTypeObject *type;
PyObject *newfunc, *res = NULL;
if (self == NULL || !PyType_Check(self))
Py_FatalError("__new__() called with non-type 'self'");
type = (PyTypeObject *)self;
if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
PyErr_Format(PyExc_TypeError,
"%s.__new__(): not enough arguments",
type->tp_name);
return NULL;
}
if (is_wrong_type(type)) return NULL;
newfunc = PyObject_GetAttrString((PyObject *) type->tp_base, "__new__");
if (newfunc != NULL) {
res = PyObject_Call(newfunc, args, kwds);
Py_DECREF(newfunc);
}
return res;
}
/* just in case that setstate gets not called, we need to protect* */
static void
_wrap_dealloc(PyObject *ob)
{
Py_TYPE(ob) = Py_TYPE(ob)->tp_base;
if (Py_TYPE(ob)->tp_dealloc != NULL)
Py_TYPE(ob)->tp_dealloc(ob);
}
static int
_wrap_traverse(PyObject *ob, visitproc visit, void *arg)
{
PyTypeObject *type = Py_TYPE(ob);
int ret = 0;
Py_TYPE(ob) = type->tp_base;
if (Py_TYPE(ob)->tp_traverse != NULL)
ret = Py_TYPE(ob)->tp_traverse(ob, visit, arg);
Py_TYPE(ob) = type;
return ret;
}
static int
_wrap_clear(PyObject *ob)
{
Py_TYPE(ob) = Py_TYPE(ob)->tp_base;
if (Py_TYPE(ob)->tp_clear != NULL)
Py_TYPE(ob)->tp_clear(ob);
return 0;
}
#define MAKE_WRAPPERTYPE(type, prefix, name, reduce, newfunc, setstate) \
\
static PyMethodDef prefix##_methods[] = { \
{"__reduce__", (PyCFunction)reduce, METH_NOARGS, NULL}, \
{"__setstate__", (PyCFunction)setstate, METH_O, NULL}, \
{"__new__", (PyCFunction)(void(*)(void))_new_wrapper, METH_VARARGS | METH_KEYWORDS, \
PyDoc_STR("wwwwwaaaaaT.__new__(S, ...) -> " \
"a new object with type S, a subtype of T")}, \
{NULL, NULL} \
}; \
\
static struct _typeobject wrap_##type = { \
PyVarObject_HEAD_INIT(&PyType_Type, 0) \
.tp_name = "_stackless._wrap." name, \
.tp_dealloc = (destructor)_wrap_dealloc, \
.tp_getattro = PyObject_GenericGetAttr, \
.tp_setattro = PyObject_GenericSetAttr, \
.tp_traverse = (traverseproc) _wrap_traverse, \
.tp_clear = (inquiry) _wrap_clear, \
.tp_methods = prefix##_methods, \
.tp_base = &type, \
.tp_init = slp_generic_init, \
.tp_new = newfunc, \
};
PyDoc_STRVAR(set_reduce_frame__doc__,
"set_reduce_frame(func) -- set the function used to reduce frames during pickling.\n"
"The function takes a frame as its sole argument and must return a pickleable object.\n");
static PyObject *
set_reduce_frame(PyObject *self, PyObject *func)
{
PyThreadState * ts = _PyThreadState_GET();
if (func == Py_None) {
Py_CLEAR(ts->interp->st.reduce_frame_func);
} else {
if (!PyCallable_Check(func)) {
TYPE_ERROR("func must be callable", NULL);
}
Py_INCREF(func);
Py_XSETREF(ts->interp->st.reduce_frame_func, func);
}
Py_RETURN_NONE;
}
PyObject *
slp_reduce_frame(PyFrameObject * frame) {
PyThreadState * ts = _PyThreadState_GET();
if (!PyFrame_Check(frame) || ts->interp->st.reduce_frame_func == NULL) {
Py_INCREF(frame);
return (PyObject *)frame;
}
return PyObject_CallFunctionObjArgs(ts->interp->st.reduce_frame_func, (PyObject *)frame, NULL);
}
/* Helper function for gen_setstate and tb_setstate.
* It unwraps the first argument of the args tuple, if it is a _Frame_Wrapper.
* Returns a new reference to an argument tuple.
*
* This functionality is required, to adhere to the __reduce__/__setstate__ protocol.
* It requires, that __setstate__ accepts the state returned by __reduce__. (copy.copy()
* depends on it.)
*/
static PyObject *
unwrap_frame_arg(PyObject * args) {
PyThreadState * ts = _PyThreadState_GET();
PyObject *wrapper_type, *arg0, *result;
int is_instance;
Py_ssize_t len, i;
if (!PyTuple_Check(args)) {
Py_INCREF(args);
return args;
}
if ((len = PyTuple_Size(args)) < 1) {
if (len < 0)
return NULL;
Py_INCREF(args);
return args;
}
if ((arg0 = PyTuple_GetItem(args, 0)) == NULL) /* arg0 is a borrowed reference */
return NULL;
if ((wrapper_type = PyObject_GetAttrString(
ts->interp->st.reduce_frame_func, "__self__")) == NULL)
return NULL;
is_instance = PyObject_IsInstance(arg0, wrapper_type);
Py_DECREF(wrapper_type);
if (is_instance == 0) {
Py_INCREF(args);
return args;
} else if (is_instance == -1) {
return NULL;
}
if ((arg0 = PyObject_GetAttrString(arg0, "frame")) == NULL)
return NULL;
if ((result = PyTuple_New(len)) == NULL) {
Py_DECREF(arg0);
return NULL;
}
if (PyTuple_SetItem(result, 0, arg0)) { /* steals ref to arg0 */
Py_DECREF(arg0);
Py_DECREF(result);
return NULL;
}
for (i=1; i<len; i++) {
if ((arg0 = PyTuple_GetItem(args, i)) == NULL) {
Py_DECREF(result);
return NULL;
}
/* arg0 is a borrowed reference */
Py_INCREF(arg0);
if (PyTuple_SetItem(result, i, arg0)) { /* steals ref to arg0 */
Py_DECREF(arg0);
Py_DECREF(result);
return NULL;
}
}
return result;
}
static struct PyMethodDef _new_methoddef[] = {
{"__new__", (PyCFunction)(void(*)(void))_new_wrapper, METH_VARARGS | METH_KEYWORDS,
PyDoc_STR("T.__new__(S, ...) -> "
"a new object with type S, a subtype of T.__base__")},
{0}
};
static int init_type(PyTypeObject *t, int (*initchain)(PyObject *), PyObject * mod)
{
PyMethodDescrObject *reduce;
PyWrapperDescrObject *init;
PyObject *func;
const char *name = strrchr(t->tp_name, '.')+1;
/* we patch the type to use *our* name, which makes no difference */
assert (strcmp(name, t->tp_base->tp_name) == 0);
t->tp_base->tp_name = name;
t->tp_basicsize = t->tp_base->tp_basicsize;
t->tp_itemsize = t->tp_base->tp_itemsize;
/* PEP-590 Vectorcall-protocol requires to copy tp_descr_get, tp_vectorcall_offset
* and tp_call from the base class
*/
t->tp_descr_get = t->tp_base->tp_descr_get;
t->tp_vectorcall_offset = t->tp_base->tp_vectorcall_offset;
t->tp_call = t->tp_base->tp_call;
t->tp_flags = t->tp_base->tp_flags & ~Py_TPFLAGS_READY;
if (PyObject_SetAttrString(mod, name, (PyObject *) t))
return -1;
/* patch the method descriptors to require the base type */
if (PyType_Ready(t)) return -1;
init = (PyWrapperDescrObject *) PyDict_GetItemString(t->tp_dict,
"__init__");
PyDescr_TYPE(init) = t->tp_base;
reduce = (PyMethodDescrObject *) PyDict_GetItemString(t->tp_dict,
"__reduce__");
PyDescr_TYPE(reduce) = t->tp_base;
/* insert the __new__ replacement which is special */
func = PyCFunction_New(_new_methoddef, (PyObject *)t);
if (func == NULL || PyDict_SetItemString(t->tp_dict, "__new__", func))
return -1;
if (initchain != NULL)
return initchain(mod);
return 0;
}
/* root of init function chain */
#define initchain NULL
/* helper to execute a bit of code which simplifies things */
static PyObject *
run_script(char *src, char *retname)
{
PyObject *globals = PyDict_New();
PyObject *retval;
if (globals == NULL)
return NULL;
if (PyDict_SetItemString(globals, "__builtins__",
PyEval_GetBuiltins()) != 0)
return NULL;
retval = PyRun_String(src, Py_file_input, globals, globals);
if (retval != NULL) {
Py_DECREF(retval);
retval = PyMapping_GetItemString(globals, retname);
}
PyDict_Clear(globals);
Py_DECREF(globals);
return retval;
}
/******************************************************
default execute function for invalid frames
******************************************************/
/*
* note that every new execute function should also create
* a different call of this function.
*/
PyObject *
slp_cannot_execute(PyCFrameObject *f, const char *exec_name, PyObject *retval)
{
/*
* Special rule for frame execution functions: we now own a reference to retval!
*/
/*
* show an error message and raise exception.
*/
PyThreadState *tstate = _PyThreadState_GET();
/* if we already have an exception, we keep it */
if (retval != NULL) {
Py_DECREF(retval);
PyErr_Format(PyExc_RuntimeError, "cannot execute invalid frame with "
"'%.100s': frame had a C state that can't be restored or an invalid code object.",
exec_name);
}
SLP_STORE_NEXT_FRAME(tstate, f->f_back);
return NULL;
}
/* registering and retrieval of frame exec functions */
/* unfortunately, this object is not public,
* so we need to repeat it here:
*/
typedef struct {
PyObject_HEAD
PyObject *dict;
} proxyobject;
int
slp_register_execute(PyTypeObject *t, char *name, PyFrame_ExecFunc *good,
PyFrame_ExecFunc *bad)
{
PyObject *g = NULL, *b = NULL, *nameobj = NULL;
PyObject *tup = NULL, *dic = NULL;
PyObject *o;
proxyobject *dp = NULL;
int ret = -1;
/*
WE CANNOT BE DOING THIS HERE, AS THE EXCEPTION CLASSES ARE NOT INITIALISED.
assert(PyObject_IsSubclass((PyObject *)t, (PyObject *)&PyFrame_Type) ||
PyObject_IsSubclass((PyObject *)t,
(PyObject *)&PyCFrame_Type));
*/
if (0
|| PyType_Ready(t) || name == NULL
|| (nameobj = PyUnicode_FromString(name)) == NULL
|| (g = PyLong_FromVoidPtr(good)) == NULL
|| (b = PyLong_FromVoidPtr(bad)) == NULL
|| (tup = Py_BuildValue("OO", g, b)) == NULL
)
goto err_exit;
dp = (proxyobject*) PyDict_GetItemString(t->tp_dict, "_exec_map");
if ((dic = dp ? dp->dict : NULL) == NULL) {
if (0
|| (dic = PyDict_New()) == NULL
|| (dp = (proxyobject *) PyDictProxy_New(dic)) == NULL
|| PyDict_SetItemString(t->tp_dict, "_exec_map",
(PyObject *) dp)
)
goto err_exit;
}
else {
Py_INCREF(dic);
Py_INCREF(dp);
}
if (0
|| (o = PyDict_SetDefault(dp->dict, nameobj, tup)) == NULL
|| !PyObject_RichCompareBool(o, tup, Py_EQ)
|| (o = PyDict_SetDefault(dp->dict, g, nameobj)) == NULL
|| !PyObject_RichCompareBool(o, nameobj, Py_EQ)
|| (o = PyDict_SetDefault(dp->dict, b, nameobj)) == NULL
|| !PyObject_RichCompareBool(o, nameobj, Py_EQ)
) {
if (! PyErr_Occurred())
PyErr_SetString(PyExc_SystemError, "duplicate/ambiguous exec func");
goto err_exit;
}
PyErr_Clear();
ret = 0;
err_exit:
Py_XDECREF(nameobj);
Py_XDECREF(g);
Py_XDECREF(b);
Py_XDECREF(tup);
Py_XDECREF(dic);
Py_XDECREF(dp);
return ret;
}
int
slp_find_execfuncs(PyTypeObject *type, PyObject *exec_name,
PyFrame_ExecFunc **good, PyFrame_ExecFunc **bad)
{
PyObject *g, *b;
proxyobject *dp = (proxyobject *)
PyDict_GetItemString(type->tp_dict, "_exec_map");
PyObject *dic = dp ? dp->dict : NULL;
PyObject *exec_tup = dic ? PyDict_GetItem(dic, exec_name) : NULL;
if (0
|| exec_tup == NULL
|| !PyArg_ParseTuple(exec_tup, "OO", &g, &b)
|| (*good = (PyFrame_ExecFunc*)PyLong_AsVoidPtr(g)) == NULL
|| (*bad = (PyFrame_ExecFunc*)PyLong_AsVoidPtr(b)) == NULL) {
char msg[500];
PyErr_Clear();
sprintf(msg, "Frame exec function '%.20s' not defined for %s",
_PyUnicode_AsString(exec_name), type->tp_name);
PyErr_SetString(PyExc_ValueError, msg);
return -1;
}
return 0;
}
PyObject *
slp_find_execname(PyCFrameObject *cf, int *valid)
{
PyObject *exec_name = NULL;
proxyobject *dp = (proxyobject *)
PyDict_GetItemString(Py_TYPE(cf)->tp_dict, "_exec_map");
PyObject *dic = dp ? dp->dict : NULL;
PyObject *exec_addr = PyLong_FromVoidPtr(cf->f_execute);
assert(valid != NULL);
if (exec_addr == NULL) return NULL;
exec_name = dic ? PyDict_GetItem(dic, exec_addr) : NULL;
if (exec_name == NULL) {
char msg[500];
PyErr_Clear();
sprintf(msg, "frame exec function at %p is not registered!",
(void *)cf->f_execute);
PyErr_SetString(PyExc_ValueError, msg);
*valid = 0;
}
else {
PyFrame_ExecFunc *good, *bad;
if (slp_find_execfuncs(Py_TYPE(cf), exec_name, &good, &bad)) {
exec_name = NULL;
goto err_exit;
}
if (cf->f_execute == bad)
*valid = 0;
else if (cf->f_execute != good) {
PyErr_SetString(PyExc_SystemError,
"inconsistent c?frame function registration");
goto err_exit;
}
}
err_exit:
Py_XDECREF(exec_addr);
Py_XINCREF(exec_name);
return exec_name;
}
/******************************************************
pickling of objects that may contain NULLs
******************************************************/
/*
* To restore arrays which can contain NULLs, we add an extra
* tuple at the beginning, which contains the positions of
* all objects which are meant to be a real NULL.
*/
PyObject *
slp_into_tuple_with_nulls(PyObject **start, Py_ssize_t length)
{
PyObject *res = PyTuple_New(length+1);
PyObject *nulls = PyTuple_New(0);
Py_ssize_t i, nullcount = 0;
if (res == NULL)
return NULL;
for (i=0; i<length; ++i) {
PyObject *ob = start[i];
if (ob == NULL) {
/* store None, and add the position to nulls */
PyObject *pos = PyLong_FromSsize_t(i);
if (pos == NULL)
return NULL;
ob = Py_None;
if (_PyTuple_Resize(&nulls, ++nullcount))
return NULL;
PyTuple_SET_ITEM(nulls, nullcount-1, pos);
}
Py_INCREF(ob);
PyTuple_SET_ITEM(res, i+1, ob);
}
/* save NULL positions as first element */
PyTuple_SET_ITEM(res, 0, nulls);
return res;
}
Py_ssize_t
slp_from_tuple_with_nulls(PyObject **start, PyObject *tup)
{
Py_ssize_t i, length = PyTuple_GET_SIZE(tup)-1;
PyObject *nulls;
if (length < 0) return 0;
/* put the values into the array */
for (i=0; i<length; ++i) {
PyObject *ob = PyTuple_GET_ITEM(tup, i+1);
Py_INCREF(ob);
start[i] = ob;
}
nulls = PyTuple_GET_ITEM(tup, 0);
if (!PyTuple_Check(nulls)) {
/* XXX we should report this error */
return length;
}
/* wipe the NULL positions */
for (i=0; i<PyTuple_GET_SIZE(nulls); ++i) {
PyObject *pos = PyTuple_GET_ITEM(nulls, i);
if (PyLong_CheckExact(pos)) {
int p = PyLong_AS_LONG(pos);
if (p >= 0 && p < length) {
PyObject *hold = start[p];
start[p] = NULL;
Py_XDECREF(hold);
}
}
}
return length;
}
/******************************************************
pickling of code objects
******************************************************/
#define codetuplefmt "liiiiiiSOOOSSiSOO"
/* Index of co_code in the tuple given to code_new */
static const Py_ssize_t code_co_code_index = 6;
/*
* An unused (invalid) opcode. See opcode.h for a list of used opcodes.
* If Stackless unpickles a code object with an invalid magic number, it prefixes
* co_code with this opcode.
*
* frame_setstate tests if the first opcode of the code of the frame is CODE_INVALID_OPCODE
* and eventually marks a frame as invalid.
*/
static const char CODE_INVALID_OPCODE = 0;
static struct _typeobject wrap_PyCode_Type;
static long bytecode_magic = 0;
static PyObject *
code_reduce(PyCodeObject * co, PyObject *unused)
{
if (0 >= bytecode_magic) {
bytecode_magic = PyImport_GetMagicNumber();
if (-1 == bytecode_magic)
return NULL;
}
PyObject *tup = Py_BuildValue(
"(O(" codetuplefmt ")())",
&wrap_PyCode_Type,
bytecode_magic,
co->co_argcount,
co->co_posonlyargcount,
co->co_kwonlyargcount,
co->co_nlocals,
co->co_stacksize,
co->co_flags,
co->co_code,
co->co_consts,
co->co_names,
co->co_varnames,
co->co_filename,
co->co_name,
co->co_firstlineno,
co->co_lnotab,
co->co_freevars,
co->co_cellvars
);
return tup;
}
static PyObject *
code_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
long magic = 0;
if (0 >= bytecode_magic) {
bytecode_magic = PyImport_GetMagicNumber();
if (-1 == bytecode_magic)
return NULL;
}
assert(PyTuple_CheckExact(args));
if (PyTuple_GET_SIZE(args) == sizeof(codetuplefmt) - 1) {
/* */
magic = PyLong_AsLong(PyTuple_GET_ITEM(args, 0));
if (-1 == magic && PyErr_Occurred()) {
return NULL;
}
args = PyTuple_GetSlice(args, 1, sizeof(codetuplefmt) - 1);
} else {
PyErr_SetString(PyExc_IndexError, "code_new: Argument tuple has wrong size.");
return NULL;
}
if (NULL == args)
return NULL;
if (bytecode_magic != magic) {
if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "Unpickling code object with invalid magic number %ld", magic)) {
Py_DECREF(args);
return NULL;
}
PyObject *code = PyTuple_GET_ITEM(args, code_co_code_index);
if (NULL == code) {
Py_DECREF(args);
return NULL;
}
if (!PyBytes_Check(code)) {
Py_DECREF(args);
PyErr_SetString(PyExc_TypeError,
"Unpickling code object: code is not a bytes object");
return NULL;
}
Py_ssize_t code_len = PyBytes_Size(code);
assert(code_len <= INT_MAX);
assert(code_len % sizeof(_Py_CODEUNIT) == 0);
/* Now prepend an invalid opcode to the code.
*/
PyObject *code2 = PyBytes_FromStringAndSize(NULL, code_len + sizeof(_Py_CODEUNIT));
char *p = PyBytes_AS_STRING(code2);
p[0] = Py_BUILD_ASSERT_EXPR(sizeof(_Py_CODEUNIT) == 2) + CODE_INVALID_OPCODE;
p[1] = 0; /* Argument */
memcpy(p + sizeof(_Py_CODEUNIT), PyBytes_AS_STRING(code), code_len);
if (PyTuple_SetItem(args, code_co_code_index, code2)) {
Py_DECREF(args);
return NULL;
}
}
PyObject *retval = generic_new(type, args, kwds);
Py_DECREF(args);
return retval;
}
MAKE_WRAPPERTYPE(PyCode_Type, code, "code", code_reduce, code_new,
generic_setstate)
static int init_codetype(PyObject * mod)
{
return init_type(&wrap_PyCode_Type, initchain, mod);
}
#undef initchain
#define initchain init_codetype
/******************************************************
pickling addition to cell objects
******************************************************/
/*
* cells create cycles via function closures.
* We therefore need to use the 3-element protocol
* of __reduce__
* We must also export this type to funcobject where
* a typecheck of the function_closure member is done,
* since a function may get a __setstate__ call with
* a partially initialized cell object.
*/
static PyTypeObject wrap_PyCell_Type;
PyTypeObject *_Pywrap_PyCell_Type = &wrap_PyCell_Type;
static PyObject *
cell_reduce(PyCellObject *cell, PyObject *unused)
{
PyObject *tup = NULL;
if (cell->ob_ref == NULL) {
tup = Py_BuildValue("(O()())", &wrap_PyCell_Type);
}
else {
tup = Py_BuildValue("(O()(O))", &wrap_PyCell_Type, cell->ob_ref);
}
return tup;
}
static PyObject *
cell_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject *ob;
if (is_wrong_type(type)) return NULL;
if (!PyArg_ParseTuple (args, "", &ob))
return NULL;
ob = PyCell_New(NULL);
if (ob != NULL)
Py_TYPE(ob) = type;
return ob;
}
/* note that args is a tuple, although we use METH_O */
static PyObject *
cell_setstate(PyObject *self, PyObject *args)
{
PyCellObject *cell = (PyCellObject *) self;
PyObject *ob = NULL;
if (is_wrong_type(Py_TYPE(self))) return NULL;
if (!PyArg_ParseTuple (args, "|O", &ob))
return NULL;
Py_XINCREF(ob);
Py_CLEAR(cell->ob_ref);
cell->ob_ref = ob;
Py_INCREF(self);
Py_TYPE(self) = Py_TYPE(self)->tp_base;
return self;
}
MAKE_WRAPPERTYPE(PyCell_Type, cell, "cell", cell_reduce, cell_new, cell_setstate)
static int init_celltype(PyObject * mod)
{
return init_type(&wrap_PyCell_Type, initchain, mod);
}
#undef initchain
#define initchain init_celltype
/******************************************************
pickling addition to function objects
******************************************************/
#define functuplefmt_pre38 "OOOOOO"
#define functuplefmt functuplefmt_pre38 "OOOOO"
static PyTypeObject wrap_PyFunction_Type;
static PyObject *
func_reduce(PyFunctionObject * func, PyObject *unused)
{
/* See funcobject.c: some attribute can't be NULL. */
assert(func->func_code);
assert(func->func_globals);
assert(func->func_name);
assert(func->func_doc);
assert(func->func_qualname);
PyObject *dict = PyObject_GenericGetDict((PyObject *)func, NULL);
if (NULL == dict)
return NULL;
PyObject *tup = Py_BuildValue(
"(O()(" functuplefmt "))",
&wrap_PyFunction_Type,
/* Standard function constructor arguments. */
func->func_code,
func->func_globals,
func->func_name,
func->func_defaults != NULL ? func->func_defaults : Py_None,
func->func_closure != NULL ? func->func_closure : Py_None,
func->func_module != NULL ? func->func_module : Py_None,
func->func_kwdefaults != NULL ? func->func_kwdefaults : Py_None,
func->func_doc,
dict,
func->func_annotations != NULL ? func->func_annotations : Py_None,
func->func_qualname
);
Py_DECREF(dict);
return tup;
}
static PyObject *
func_new(PyTypeObject *type, PyObject *args, PyObject *kewd)
{
PyObject *ob = NULL, *co = NULL, *globals = NULL;
/* create a fake function for later initialization */
if (is_wrong_type(type)) return NULL;
if ((co = Py_CompileString("", "", Py_file_input)) != NULL)
if ((globals = PyDict_New()) != NULL)
if ((ob = PyFunction_New(co, globals)) != NULL)
Py_TYPE(ob) = type;
Py_XDECREF(co);
Py_XDECREF(globals);
return ob;
}
#define COPY(src, dest, attr) Py_XINCREF(src->attr); Py_CLEAR(dest->attr); \
dest->attr = src->attr
static PyObject *
func_setstate(PyObject *self, PyObject *args)
{
PyFunctionObject *fu;
PyObject *args2;
char *pcode;
if (is_wrong_type(Py_TYPE(self))) return NULL;
Py_TYPE(self) = Py_TYPE(self)->tp_base;
/* Test for an invalid code object */
args2 = PyTuple_GetItem(args, 0);
if (NULL==args2)
return NULL;
if (! PyCode_Check(args2)) {
PyErr_SetString(PyExc_TypeError, "func_setstate: value for func_code is not a code object");
return NULL;
}
pcode = PyBytes_AsString(((PyCodeObject *) args2)->co_code);
if (NULL == pcode)
return NULL;
if (*pcode == CODE_INVALID_OPCODE) {
/* invalid code object, was pickled with a different version of python */
if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "Unpickling function with invalid code object: %V",
PyTuple_GetItem(args, 2), "~ name is missing ~"))
return NULL;
}
args2 = PyTuple_GetSlice(args, 0, 5);
if (args2 == NULL)
return NULL;
fu = (PyFunctionObject *) Py_TYPE(self)->tp_new(Py_TYPE(self), args2, NULL);
Py_DECREF(args2);
if (fu == NULL)
return NULL;
PyFunctionObject *target = (PyFunctionObject *) self;
COPY(fu, target, func_code);
COPY(fu, target, func_globals);
COPY(fu, target, func_name);
COPY(fu, target, func_defaults);
COPY(fu, target, func_closure);
Py_DECREF(fu);
args2 = PyTuple_GetItem(args, 5);
if (NULL == args2)
return NULL;
Py_INCREF(args2);
Py_XSETREF(target->func_module, args2);
if (PyTuple_GET_SIZE(args) != sizeof(functuplefmt_pre38)-1) {
/* Stackless 3.8 and up */
if (PyTuple_GET_SIZE(args) != sizeof(functuplefmt)-1) {
PyErr_Format(PyExc_IndexError, "function.__setstate__ expects a tuple of length %d", (int)sizeof(functuplefmt)-1);
return NULL;
}
args2 = PyTuple_GET_ITEM(args, 6);
if (PyFunction_SetKwDefaults(self, args2))
return NULL;
args2 = PyTuple_GET_ITEM(args, 7);
Py_INCREF(args2);
Py_XSETREF(target->func_doc, args2);
args2 = PyTuple_GET_ITEM(args, 8);
if (args2 != Py_None && PyObject_GenericSetDict(self, args2, NULL))
return NULL;
args2 = PyTuple_GET_ITEM(args, 9);
if (PyFunction_SetAnnotations(self, args2))
return NULL;
args2 = PyTuple_GET_ITEM(args, 10);
if(!PyUnicode_Check(args2)) {
PyErr_SetString(PyExc_TypeError, "__qualname__ must be set to a string object");
return NULL;
}
Py_INCREF(args2);
Py_XSETREF(target->func_qualname, args2);
}
Py_INCREF(self);
return self;
}
#undef COPY
MAKE_WRAPPERTYPE(PyFunction_Type, func, "function", func_reduce, func_new,
func_setstate)
static int init_functype(PyObject * mod)
{
return init_type(&wrap_PyFunction_Type, initchain, mod);
}
#undef initchain
#define initchain init_functype
/******************************************************
pickling addition to frame objects
******************************************************/
#define frametuplefmt "O)(OiBOiOOiiOO"
SLP_DEF_INVALID_EXEC(slp_channel_seq_callback)
SLP_DEF_INVALID_EXEC(slp_tp_init_callback)
static PyTypeObject wrap_PyFrame_Type;
static PyObject *
frameobject_reduce(PyFrameObject *f, PyObject *unused)
{
int i;
PyObject **f_stacktop;
PyObject *blockstack_as_tuple = NULL, *localsplus_as_tuple = NULL,
*res = NULL;
int valid = 1;
int have_locals = f->f_locals != NULL;
PyObject * dummy_locals = NULL;
PyObject * f_trace = NULL;
PyThreadState *ts = _PyThreadState_GET();
if (!have_locals)
if ((dummy_locals = PyDict_New()) == NULL)
return NULL;
blockstack_as_tuple = PyTuple_New (f->f_iblock);
if (blockstack_as_tuple == NULL) goto err_exit;
for (i = 0; i < f->f_iblock; i++) {
PyObject *tripel = Py_BuildValue("iii",
f->f_blockstack[i].b_type,
f->f_blockstack[i].b_handler,
f->f_blockstack[i].b_level);
if (!tripel) goto err_exit;
PyTuple_SET_ITEM(blockstack_as_tuple, i, tripel);
}
f_stacktop = f->f_stacktop;
if (f_stacktop != NULL) {
if (f_stacktop < f->f_valuestack) {
PyErr_SetString(PyExc_ValueError, "stack underflow");
goto err_exit;