Debian Codegraph @

mypyc/lib-rt/misc_ops.c

raw
1 #include "pythoncapi_compat.h"
2
3 // Misc primitive operations + C helpers
4 //
5 // These are registered in mypyc.primitives.misc_ops.
6
7 #include <Python.h>
8 #include <patchlevel.h>
9 #include "CPy.h"
10
11 PyObject *CPy_GetCoro(PyObject *obj)
12 {
13 // If the type has an __await__ method, call it,
14 // otherwise, fallback to calling __iter__.
15 PyAsyncMethods* async_struct = Py_TYPE(obj)->tp_as_async;
16 if (async_struct != NULL && async_struct->am_await != NULL) {
17 return (async_struct->am_await)(obj);
18 } else {
19 // TODO: We should check that the type is a generator decorated with
20 // asyncio.coroutine
21 return PyObject_GetIter(obj);
22 }
23 }
24
25 PyObject *CPyIter_Send(PyObject *iter, PyObject *val)
26 {
27 // Do a send, or a next if second arg is None.
28 // (This behavior is to match the PEP 380 spec for yield from.)
29 if (Py_IsNone(val)) {
30 return CPyIter_Next(iter);
31 } else {
32 return PyObject_CallMethodOneArg(iter, mypyc_interned_str.send, val);
33 }
34 }
35
36 // A somewhat hairy implementation of specifically most of the error handling
37 // in `yield from` error handling. The point here is to reduce code size.
38 //
39 // This implements most of the bodies of the `except` blocks in the
40 // pseudocode in PEP 380.
41 //
42 // Returns true (1) if a StopIteration was received and we should return.
43 // Returns false (0) if a value should be yielded.
44 // In both cases the value is stored in outp.
45 // Signals an error (2) if the an exception should be propagated.
46 int CPy_YieldFromErrorHandle(PyObject *iter, PyObject **outp)
47 {
48 PyObject *exc_type = (PyObject *)Py_TYPE(CPy_ExcState()->exc_value);
49 PyObject *type, *value, *traceback;
50 PyObject *_m;
51 PyObject *res;
52 *outp = NULL;
53
54 if (PyErr_GivenExceptionMatches(exc_type, PyExc_GeneratorExit)) {
55 _m = PyObject_GetAttr(iter, mypyc_interned_str.close_);
56 if (_m) {
57 res = PyObject_CallNoArgs(_m);
58 Py_DECREF(_m);
59 if (!res)
60 return 2;
61 Py_DECREF(res);
62 } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
63 PyErr_Clear();
64 } else {
65 return 2;
66 }
67 } else {
68 _m = PyObject_GetAttr(iter, mypyc_interned_str.throw_);
69 if (_m) {
70 _CPy_GetExcInfo(&type, &value, &traceback);
71 res = PyObject_CallFunctionObjArgs(_m, type, value, traceback, NULL);
72 Py_DECREF(type);
73 Py_DECREF(value);
74 Py_DECREF(traceback);
75 Py_DECREF(_m);
76 if (res) {
77 *outp = res;
78 return 0;
79 } else {
80 res = CPy_FetchStopIterationValue();
81 if (res) {
82 *outp = res;
83 return 1;
84 } else {
85 return 2;
86 }
87 }
88 } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
89 PyErr_Clear();
90 } else {
91 return 2;
92 }
93 }
94
95 CPy_Reraise();
96 return 2;
97 }
98
99 PyObject *CPy_FetchStopIterationValue(void)
100 {
101 PyObject *val = NULL;
102 _PyGen_FetchStopIterationValue(&val);
103 return val;
104 }
105
106 static bool _CPy_IsSafeMetaClass(PyTypeObject *metaclass) {
107 // mypyc classes can't work with metaclasses in
108 // general. Through some various nasty hacks we *do*
109 // manage to work with TypingMeta and its friends.
110 if (metaclass == &PyType_Type)
111 return true;
112 PyObject *module = PyObject_GetAttr((PyObject *)metaclass, mypyc_interned_str.__module__);
113 if (!module) {
114 PyErr_Clear();
115 return false;
116 }
117
118 bool matches = false;
119 if (PyUnicode_CompareWithASCIIString(module, "typing") == 0 &&
120 (strcmp(metaclass->tp_name, "TypingMeta") == 0
121 || strcmp(metaclass->tp_name, "GenericMeta") == 0
122 || strcmp(metaclass->tp_name, "_ProtocolMeta") == 0)) {
123 matches = true;
124 } else if (PyUnicode_CompareWithASCIIString(module, "typing_extensions") == 0 &&
125 strcmp(metaclass->tp_name, "_ProtocolMeta") == 0) {
126 matches = true;
127 } else if (PyUnicode_CompareWithASCIIString(module, "abc") == 0 &&
128 strcmp(metaclass->tp_name, "ABCMeta") == 0) {
129 matches = true;
130 }
131 Py_DECREF(module);
132 return matches;
133 }
134
135 #if CPY_3_13_FEATURES
136
137 // Adapted from CPython 3.13.0b3
138 /* Determine the most derived metatype. */
139 PyObject *CPy_CalculateMetaclass(PyObject *metatype, PyObject *bases)
140 {
141 Py_ssize_t i, nbases;
142 PyTypeObject *winner;
143 PyObject *tmp;
144 PyTypeObject *tmptype;
145
146 /* Determine the proper metatype to deal with this,
147 and check for metatype conflicts while we're at it.
148 Note that if some other metatype wins to contract,
149 it's possible that its instances are not types. */
150
151 nbases = PyTuple_GET_SIZE(bases);
152 winner = (PyTypeObject *)metatype;
153 for (i = 0; i < nbases; i++) {
154 tmp = PyTuple_GET_ITEM(bases, i);
155 tmptype = Py_TYPE(tmp);
156 if (PyType_IsSubtype(winner, tmptype))
157 continue;
158 if (PyType_IsSubtype(tmptype, winner)) {
159 winner = tmptype;
160 continue;
161 }
162 /* else: */
163 PyErr_SetString(PyExc_TypeError,
164 "metaclass conflict: "
165 "the metaclass of a derived class "
166 "must be a (non-strict) subclass "
167 "of the metaclasses of all its bases");
168 return NULL;
169 }
170 return (PyObject *)winner;
171 }
172
173 #else
174
175 PyObject *CPy_CalculateMetaclass(PyObject *metatype, PyObject *bases) {
176 return (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)metatype, bases);
177 }
178
179 #endif
180
181 // Create a heap type based on a template non-heap type.
182 // This is super hacky and maybe we should suck it up and use PyType_FromSpec instead.
183 // We allow bases to be NULL to represent just inheriting from object.
184 // We don't support NULL bases and a non-type metaclass.
185 PyObject *CPyType_FromTemplate(PyObject *template,
186 PyObject *orig_bases,
187 PyObject *modname) {
188 PyTypeObject *template_ = (PyTypeObject *)template;
189 PyHeapTypeObject *t = NULL;
190 PyTypeObject *dummy_class = NULL;
191 PyObject *name = NULL;
192 PyObject *bases = NULL;
193 PyObject *slots;
194
195 // If the type of the class (the metaclass) is NULL, we default it
196 // to being type. (This allows us to avoid needing to initialize
197 // it explicitly on windows.)
198 if (!Py_TYPE(template_)) {
199 Py_SET_TYPE(template_, &PyType_Type);
200 }
201 PyTypeObject *metaclass = Py_TYPE(template_);
202
203 if (orig_bases) {
204 bases = update_bases(orig_bases);
205 // update_bases doesn't increment the refcount if nothing changes,
206 // so we do it to make sure we have distinct "references" to both
207 if (bases == orig_bases)
208 Py_INCREF(bases);
209
210 // Find the appropriate metaclass from our base classes. We
211 // care about this because Generic uses a metaclass prior to
212 // Python 3.7.
213 metaclass = (PyTypeObject *)CPy_CalculateMetaclass((PyObject *)metaclass, bases);
214 if (!metaclass)
215 goto error;
216
217 if (!_CPy_IsSafeMetaClass(metaclass)) {
218 PyErr_SetString(PyExc_TypeError, "mypyc classes can't have a metaclass");
219 goto error;
220 }
221 }
222
223 name = PyUnicode_FromString(template_->tp_name);
224 if (!name)
225 goto error;
226
227 if (template_->tp_doc) {
228 // cpython expects tp_doc to be heap-allocated so convert it here to
229 // avoid segfaults on deallocation.
230 Py_ssize_t size = strlen(template_->tp_doc) + 1;
231 char *doc = (char *)PyMem_Malloc(size);
232 if (!doc)
233 goto error;
234 memcpy(doc, template_->tp_doc, size);
235 template_->tp_doc = doc;
236 }
237
238 // Allocate the type and then copy the main stuff in.
239 t = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
240 if (!t)
241 goto error;
242 memcpy((char *)t + sizeof(PyVarObject),
243 (char *)template_ + sizeof(PyVarObject),
244 sizeof(PyTypeObject) - sizeof(PyVarObject));
245
246 if (bases != orig_bases) {
247 if (PyObject_SetAttr((PyObject *)t, mypyc_interned_str.__orig_bases__, orig_bases) < 0)
248 goto error;
249 }
250
251 // Having tp_base set is I think required for stuff to get
252 // inherited in PyType_Ready, which we needed for subclassing
253 // BaseException. XXX: Taking the first element is wrong I think though.
254 if (bases) {
255 t->ht_type.tp_base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);
256 Py_INCREF((PyObject *)t->ht_type.tp_base);
257 }
258
259 t->ht_name = name;
260 Py_INCREF(name);
261 t->ht_qualname = name;
262 t->ht_type.tp_bases = bases;
263 // references stolen so NULL these out
264 bases = name = NULL;
265
266 if (PyType_Ready((PyTypeObject *)t) < 0)
267 goto error;
268
269 assert(t->ht_type.tp_base != NULL);
270
271 // XXX: This is a terrible hack to work around a cpython check on
272 // the mro. It was needed for mypy.stats. I need to investigate
273 // what is actually going on here.
274 Py_INCREF(metaclass);
275 Py_SET_TYPE(t, metaclass);
276
277 if (dummy_class) {
278 if (PyDict_Merge(t->ht_type.tp_dict, dummy_class->tp_dict, 0) != 0)
279 goto error;
280 // This is the *really* tasteless bit. GenericMeta's __new__
281 // in certain versions of typing sets _gorg to point back to
282 // the class. We need to override it to keep it from pointing
283 // to the proxy.
284 if (PyDict_SetItemString(t->ht_type.tp_dict, "_gorg", (PyObject *)t) < 0)
285 goto error;
286 }
287
288 // Reject anything that would give us a nontrivial __slots__,
289 // because the layout will conflict
290 slots = PyObject_GetAttr((PyObject *)t, mypyc_interned_str.__slots__);
291 if (slots) {
292 // don't fail on an empty __slots__
293 int is_true = PyObject_IsTrue(slots);
294 Py_DECREF(slots);
295 if (is_true > 0)
296 PyErr_SetString(PyExc_TypeError, "mypyc classes can't have __slots__");
297 if (is_true != 0)
298 goto error;
299 } else {
300 PyErr_Clear();
301 }
302
303 if (PyObject_SetAttr((PyObject *)t, mypyc_interned_str.__module__, modname) < 0)
304 goto error;
305
306 Py_XDECREF(dummy_class);
307
308 // Unlike the tp_doc slots of most other object, a heap type's tp_doc
309 // must be heap allocated.
310 if (template_->tp_doc) {
311 // Silently truncate the docstring if it contains a null byte
312 Py_ssize_t size = strlen(template_->tp_doc) + 1;
313 char *tp_doc = (char *)PyMem_Malloc(size);
314 if (tp_doc == NULL) {
315 PyErr_NoMemory();
316 goto error;
317 }
318
319 memcpy(tp_doc, template_->tp_doc, size);
320 t->ht_type.tp_doc = tp_doc;
321 }
322
323 #if PY_MINOR_VERSION == 11
324 // This is a hack. Python 3.11 doesn't include good public APIs to work with managed
325 // dicts, which are the default for heap types. So we try to opt-out until Python 3.12.
326 t->ht_type.tp_flags &= ~Py_TPFLAGS_MANAGED_DICT;
327 #endif
328 return (PyObject *)t;
329
330 error:
331 Py_XDECREF(t);
332 Py_XDECREF(bases);
333 Py_XDECREF(dummy_class);
334 Py_XDECREF(name);
335 return NULL;
336 }
337
338 // Call __init_subclass__ on the appropriate base class of type.
339 // This is separated from CPyType_FromTemplate so that class attributes
340 // can be set before __init_subclass__ is called.
341 bool CPy_InitSubclass(PyObject *type) {
342 if (init_subclass((PyTypeObject *)type, NULL)) {
343 return false;
344 }
345 return true;
346 }
347
348 static int _CPy_UpdateObjFromDict(PyObject *obj, PyObject *dict)
349 {
350 Py_ssize_t pos = 0;
351 PyObject *key, *value;
352 while (PyDict_Next(dict, &pos, &key, &value)) {
353 if (PyObject_SetAttr(obj, key, value) != 0) {
354 return -1;
355 }
356 }
357 return 0;
358 }
359
360 /* Support for our partial built-in support for dataclasses.
361 *
362 * Take a class we want to make a dataclass, remove any descriptors
363 * for annotated attributes, swap in the actual values of the class
364 * variables invoke dataclass, and then restore all of the
365 * descriptors.
366 *
367 * The purpose of all this is that dataclasses uses the values of
368 * class variables to drive which attributes are required and what the
369 * default values/factories are for optional attributes. This means
370 * that the class dict needs to contain those values instead of getset
371 * descriptors for the attributes when we invoke dataclass.
372 *
373 * We need to remove descriptors for attributes even when there is no
374 * default value for them, or else dataclass will think the descriptor
375 * is the default value. We remove only the attributes, since we don't
376 * want dataclasses to try generating functions when they are already
377 * implemented.
378 *
379 * Args:
380 * dataclass_dec: The decorator to apply
381 * tp: The class we are making a dataclass
382 * dict: The dictionary containing values that dataclasses needs
383 * annotations: The type annotation dictionary
384 * dataclass_type: A str object with the return value of util.py:dataclass_type()
385 */
386 int
387 CPyDataclass_SleightOfHand(PyObject *dataclass_dec, PyObject *tp,
388 PyObject *dict, PyObject *annotations,
389 PyObject *dataclass_type) {
390 PyTypeObject *ttp = (PyTypeObject *)tp;
391 Py_ssize_t pos;
392 PyObject *res = NULL;
393
394 /* Make a copy of the original class __dict__ */
395 PyObject *orig_dict = PyDict_Copy(ttp->tp_dict);
396 if (!orig_dict) {
397 goto fail;
398 }
399
400 /* Delete anything that had an annotation */
401 pos = 0;
402 PyObject *key;
403 while (PyDict_Next(annotations, &pos, &key, NULL)) {
404 // Check and delete key. Key may be absent from tp for InitVar variables.
405 if (PyObject_HasAttr(tp, key) == 1 && PyObject_DelAttr(tp, key) != 0) {
406 goto fail;
407 }
408 }
409
410 /* Copy in all the attributes that we want dataclass to see */
411 if (_CPy_UpdateObjFromDict(tp, dict) != 0) {
412 goto fail;
413 }
414
415 /* Run the @dataclass descriptor */
416 res = PyObject_CallOneArg(dataclass_dec, tp);
417 if (!res) {
418 goto fail;
419 }
420 const char *dataclass_type_ptr = PyUnicode_AsUTF8(dataclass_type);
421 if (dataclass_type_ptr == NULL) {
422 goto fail;
423 }
424 if (strcmp(dataclass_type_ptr, "attr") == 0 ||
425 strcmp(dataclass_type_ptr, "attr-auto") == 0) {
426 // These attributes are added or modified by @attr.s(slots=True).
427 const char * const keys[] = {"__attrs_attrs__", "__attrs_own_setattr__", "__init__", ""};
428 for (const char * const *key_iter = keys; **key_iter != '\0'; key_iter++) {
429 PyObject *value = NULL;
430 int rv = PyObject_GetOptionalAttrString(res, *key_iter, &value);
431 if (rv == 1) {
432 PyObject_SetAttrString(tp, *key_iter, value);
433 Py_DECREF(value);
434 } else if (rv == -1) {
435 goto fail;
436 }
437 }
438 }
439
440 /* Copy back the original contents of the dict */
441 if (_CPy_UpdateObjFromDict(tp, orig_dict) != 0) {
442 goto fail;
443 }
444
445 Py_DECREF(res);
446 Py_DECREF(orig_dict);
447 return 1;
448
449 fail:
450 Py_XDECREF(res);
451 Py_XDECREF(orig_dict);
452 return 0;
453 }
454
455 // Support for pickling; reusable getstate and setstate functions
456 PyObject *
457 CPyPickle_SetState(PyObject *obj, PyObject *state)
458 {
459 if (_CPy_UpdateObjFromDict(obj, state) != 0) {
460 return NULL;
461 }
462 Py_RETURN_NONE;
463 }
464
465 PyObject *
466 CPyPickle_GetState(PyObject *obj)
467 {
468 PyObject *attrs = NULL, *state = NULL;
469
470 attrs = PyObject_GetAttr((PyObject *)Py_TYPE(obj), mypyc_interned_str.__mypyc_attrs__);
471 if (!attrs) {
472 goto fail;
473 }
474 if (!PyTuple_Check(attrs)) {
475 PyErr_SetString(PyExc_TypeError, "__mypyc_attrs__ is not a tuple");
476 goto fail;
477 }
478 state = PyDict_New();
479 if (!state) {
480 goto fail;
481 }
482
483 // Collect all the values of attributes in __mypyc_attrs__
484 // Attributes that are missing we just ignore
485 int i;
486 for (i = 0; i < PyTuple_GET_SIZE(attrs); i++) {
487 PyObject *key = PyTuple_GET_ITEM(attrs, i);
488 PyObject *value = PyObject_GetAttr(obj, key);
489 if (!value) {
490 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
491 PyErr_Clear();
492 continue;
493 }
494 goto fail;
495 }
496 int result = PyDict_SetItem(state, key, value);
497 Py_DECREF(value);
498 if (result != 0) {
499 goto fail;
500 }
501 }
502
503 Py_DECREF(attrs);
504
505 return state;
506 fail:
507 Py_XDECREF(attrs);
508 Py_XDECREF(state);
509 return NULL;
510 }
511
512 CPyTagged CPyTagged_Id(PyObject *o) {
513 return CPyTagged_FromVoidPtr(o);
514 }
515
516 #define MAX_INT_CHARS 22
517 #define _PyUnicode_LENGTH(op) \
518 (((PyASCIIObject *)(op))->length)
519
520 // using snprintf or PyUnicode_FromFormat was way slower than
521 // boxing the int and calling PyObject_Str on it, so we implement our own
522 static int fmt_ssize_t(char *out, Py_ssize_t n) {
523 bool neg = n < 0;
524 if (neg) n = -n;
525
526 // buf gets filled backward and then we copy it forward
527 char buf[MAX_INT_CHARS];
528 int i = 0;
529 do {
530 buf[i] = (n % 10) + '0';
531 n /= 10;
532 i++;
533 } while (n);
534
535
536 int len = i;
537 int j = 0;
538 if (neg) {
539 out[j++] = '-';
540 len++;
541 }
542
543 for (; j < len; j++, i--) {
544 out[j] = buf[i-1];
545 }
546 out[j] = '\0';
547
548 return len;
549 }
550
551 static PyObject *CPyTagged_ShortToStr(Py_ssize_t n) {
552 PyObject *obj = PyUnicode_New(MAX_INT_CHARS, 127);
553 if (!obj) return NULL;
554 int len = fmt_ssize_t((char *)PyUnicode_1BYTE_DATA(obj), n);
555 _PyUnicode_LENGTH(obj) = len;
556 return obj;
557 }
558
559 PyObject *CPyTagged_Str(CPyTagged n) {
560 if (CPyTagged_CheckShort(n)) {
561 return CPyTagged_ShortToStr(CPyTagged_ShortAsSsize_t(n));
562 } else {
563 return PyObject_Str(CPyTagged_AsObject(n));
564 }
565 }
566
567 static PyObject *CPyTagged_ShortToAsciiBytes(Py_ssize_t n) {
568 PyObject *obj = PyBytes_FromStringAndSize(NULL, MAX_INT_CHARS);
569 if (!obj) return NULL;
570 int len = fmt_ssize_t(PyBytes_AsString(obj), n);
571 Py_SET_SIZE(obj, len);
572 return obj;
573 }
574
575 PyObject *CPyTagged_AsciiBytes(CPyTagged n) {
576 if (CPyTagged_CheckShort(n)) {
577 return CPyTagged_ShortToAsciiBytes(CPyTagged_ShortAsSsize_t(n));
578 }
579 PyObject *str = PyObject_Str(CPyTagged_AsObject(n));
580 PyObject *bytes = PyUnicode_AsASCIIString(str);
581 CPy_DECREF(str);
582 return bytes;
583 }
584
585 void CPyDebug_Print(const char *msg) {
586 printf("%s\n", msg);
587 fflush(stdout);
588 }
589
590 void CPyDebug_PrintObject(PyObject *obj) {
591 // Printing can cause errors. We don't want this to affect any existing
592 // state so we'll save any existing error and restore it at the end.
593 PyObject *exc_type, *exc_value, *exc_traceback;
594 PyErr_Fetch(&exc_type, &exc_value, &exc_traceback);
595
596 if (PyObject_Print(obj, stderr, 0) == -1) {
597 PyErr_Print();
598 } else {
599 fprintf(stderr, "\n");
600 }
601 fflush(stderr);
602
603 PyErr_Restore(exc_type, exc_value, exc_traceback);
604 }
605
606 int CPySequence_CheckUnpackCount(PyObject *sequence, Py_ssize_t expected) {
607 Py_ssize_t actual = Py_SIZE(sequence);
608 if (unlikely(actual != expected)) {
609 if (actual < expected) {
610 PyErr_Format(PyExc_ValueError, "not enough values to unpack (expected %zd, got %zd)",
611 expected, actual);
612 } else {
613 PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %zd)", expected);
614 }
615 return -1;
616 }
617 return 0;
618 }
619
620 // Parse an integer (size_t) encoded as a variable-length binary sequence.
621 static const char *parse_int(const char *s, size_t *len) {
622 Py_ssize_t n = 0;
623 while ((unsigned char)*s >= 0x80) {
624 n = (n << 7) + (*s & 0x7f);
625 s++;
626 }
627 n = (n << 7) | *s++;
628 *len = n;
629 return s;
630 }
631
632 // Initialize static constant array of literal values
633 int CPyStatics_Initialize(PyObject **statics,
634 const char * const *strings,
635 const char * const *bytestrings,
636 const char * const *ints,
637 const double *floats,
638 const double *complex_numbers,
639 const int *tuples,
640 const int *frozensets) {
641 PyObject **result = statics;
642 // Start with some hard-coded values
643 *result++ = Py_None;
644 Py_INCREF(Py_None);
645 *result++ = Py_False;
646 Py_INCREF(Py_False);
647 *result++ = Py_True;
648 Py_INCREF(Py_True);
649 if (strings) {
650 for (; **strings != '\0'; strings++) {
651 size_t num;
652 const char *data = *strings;
653 data = parse_int(data, &num);
654 while (num-- > 0) {
655 size_t len;
656 data = parse_int(data, &len);
657 PyObject *obj = PyUnicode_DecodeUTF8(data, len, "surrogatepass");
658 if (obj == NULL) {
659 return -1;
660 }
661 PyUnicode_InternInPlace(&obj);
662 *result++ = obj;
663 data += len;
664 }
665 }
666 }
667 if (bytestrings) {
668 for (; **bytestrings != '\0'; bytestrings++) {
669 size_t num;
670 const char *data = *bytestrings;
671 data = parse_int(data, &num);
672 while (num-- > 0) {
673 size_t len;
674 data = parse_int(data, &len);
675 PyObject *obj = PyBytes_FromStringAndSize(data, len);
676 if (obj == NULL) {
677 return -1;
678 }
679 *result++ = obj;
680 data += len;
681 }
682 }
683 }
684 if (ints) {
685 for (; **ints != '\0'; ints++) {
686 size_t num;
687 const char *data = *ints;
688 data = parse_int(data, &num);
689 while (num-- > 0) {
690 char *end;
691 PyObject *obj = PyLong_FromString(data, &end, 10);
692 if (obj == NULL) {
693 return -1;
694 }
695 data = end;
696 data++;
697 *result++ = obj;
698 }
699 }
700 }
701 if (floats) {
702 size_t num = (size_t)*floats++;
703 while (num-- > 0) {
704 PyObject *obj = PyFloat_FromDouble(*floats++);
705 if (obj == NULL) {
706 return -1;
707 }
708 *result++ = obj;
709 }
710 }
711 if (complex_numbers) {
712 size_t num = (size_t)*complex_numbers++;
713 while (num-- > 0) {
714 double real = *complex_numbers++;
715 double imag = *complex_numbers++;
716 PyObject *obj = PyComplex_FromDoubles(real, imag);
717 if (obj == NULL) {
718 return -1;
719 }
720 *result++ = obj;
721 }
722 }
723 if (tuples) {
724 int num = *tuples++;
725 while (num-- > 0) {
726 int num_items = *tuples++;
727 PyObject *obj = PyTuple_New(num_items);
728 if (obj == NULL) {
729 return -1;
730 }
731 int i;
732 for (i = 0; i < num_items; i++) {
733 PyObject *item = statics[*tuples++];
734 Py_INCREF(item);
735 PyTuple_SET_ITEM(obj, i, item);
736 }
737 *result++ = obj;
738 }
739 }
740 if (frozensets) {
741 int num = *frozensets++;
742 while (num-- > 0) {
743 int num_items = *frozensets++;
744 PyObject *obj = PyFrozenSet_New(NULL);
745 if (obj == NULL) {
746 return -1;
747 }
748 for (int i = 0; i < num_items; i++) {
749 PyObject *item = statics[*frozensets++];
750 Py_INCREF(item);
751 if (PySet_Add(obj, item) == -1) {
752 return -1;
753 }
754 }
755 *result++ = obj;
756 }
757 }
758 return 0;
759 }
760
761 // Call super(type(self), self)
762 PyObject *
763 CPy_Super(PyObject *builtins, PyObject *self) {
764 PyObject *super_type = PyObject_GetAttr(builtins, mypyc_interned_str.super);
765 if (!super_type)
766 return NULL;
767 PyObject *result = PyObject_CallFunctionObjArgs(
768 super_type, (PyObject*)Py_TYPE(self), self, NULL);
769 Py_DECREF(super_type);
770 return result;
771 }
772
773 static bool import_single(PyObject *mod_id, PyObject **mod_static,
774 PyObject *globals_id, PyObject *globals_name, PyObject *globals) {
775 if (Py_IsNone(*mod_static)) {
776 CPyModule *mod = PyImport_Import(mod_id);
777 if (mod == NULL) {
778 return false;
779 }
780 *mod_static = mod;
781 }
782
783 PyObject *mod_dict = PyImport_GetModuleDict();
784 CPyModule *globals_mod = CPyDict_GetItem(mod_dict, globals_id);
785 if (globals_mod == NULL) {
786 return false;
787 }
788 int ret = CPyDict_SetItem(globals, globals_name, globals_mod);
789 Py_DECREF(globals_mod);
790 if (ret < 0) {
791 return false;
792 }
793
794 return true;
795 }
796
797 // Table-driven import helper. See transform_import() in irbuild for the details.
798 bool CPyImport_ImportMany(PyObject *modules, CPyModule **statics[], PyObject *globals,
799 PyObject *tb_path, PyObject *tb_function, Py_ssize_t *tb_lines) {
800 for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(modules); i++) {
801 PyObject *module = PyTuple_GET_ITEM(modules, i);
802 PyObject *mod_id = PyTuple_GET_ITEM(module, 0);
803 PyObject *globals_id = PyTuple_GET_ITEM(module, 1);
804 PyObject *globals_name = PyTuple_GET_ITEM(module, 2);
805
806 if (!import_single(mod_id, statics[i], globals_id, globals_name, globals)) {
807 assert(PyErr_Occurred() && "error indicator should be set on bad import!");
808 PyObject *typ, *val, *tb;
809 PyErr_Fetch(&typ, &val, &tb);
810 const char *path = PyUnicode_AsUTF8(tb_path);
811 if (path == NULL) {
812 path = "<unable to display>";
813 }
814 const char *function = PyUnicode_AsUTF8(tb_function);
815 if (function == NULL) {
816 function = "<unable to display>";
817 }
818 PyErr_Restore(typ, val, tb);
819 CPy_AddTraceback(path, function, tb_lines[i], globals);
820 return false;
821 }
822 }
823 return true;
824 }
825
826 // This helper function is a simplification of cpython/ceval.c/import_from()
827 static PyObject *CPyImport_ImportFrom(PyObject *module, PyObject *package_name,
828 PyObject *import_name, PyObject *as_name) {
829 // check if the imported module has an attribute by that name
830 PyObject *x = PyObject_GetAttr(module, import_name);
831 if (x == NULL) {
832 // Attribute lookup failed. The name may still be a submodule that's
833 // been imported already; look it up directly in sys.modules.
834 PyObject *fullmodname = PyUnicode_FromFormat("%U.%U", package_name, import_name);
835 if (fullmodname == NULL) {
836 goto fail;
837 }
838 PyErr_Clear();
839 x = PyImport_GetModule(fullmodname);
840 Py_DECREF(fullmodname);
841 if (x == NULL) {
842 goto fail;
843 }
844 }
845 return x;
846
847 fail:
848 PyErr_Clear();
849 PyObject *package_path = PyModule_GetFilenameObject(module);
850 PyObject *path_for_msg = package_path != NULL ? package_path : Py_None;
851 PyObject *errmsg = PyUnicode_FromFormat("cannot import name %R from %R (%S)",
852 import_name, package_name, path_for_msg);
853 // NULL checks for errmsg and package_name done by PyErr_SetImportError.
854 PyErr_SetImportError(errmsg, package_name, package_path);
855 Py_XDECREF(package_path);
856 Py_XDECREF(errmsg);
857 return NULL;
858 }
859
860 PyObject *CPyImport_ImportFromMany(PyObject *mod_id, PyObject *names, PyObject *as_names,
861 PyObject *globals) {
862 PyObject *mod = PyImport_ImportModuleLevelObject(mod_id, globals, 0, names, 0);
863 if (mod == NULL) {
864 return NULL;
865 }
866
867 for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(names); i++) {
868 PyObject *name = PyTuple_GET_ITEM(names, i);
869 PyObject *as_name = PyTuple_GET_ITEM(as_names, i);
870 PyObject *obj = CPyImport_ImportFrom(mod, mod_id, name, as_name);
871 if (obj == NULL) {
872 Py_DECREF(mod);
873 return NULL;
874 }
875 int ret = CPyDict_SetItem(globals, as_name, obj);
876 Py_DECREF(obj);
877 if (ret < 0) {
878 Py_DECREF(mod);
879 return NULL;
880 }
881 }
882 return mod;
883 }
884
885 // Import attributes from an already-imported native module and store them
886 // in the globals dict. Returns the module on success, NULL on error.
887 PyObject *CPyImport_GetNativeAttrs(PyObject *mod_id, PyObject *names,
888 PyObject *as_names, PyObject *globals) {
889 PyObject *mod = PyImport_GetModule(mod_id);
890 if (mod == NULL) {
891 if (!PyErr_Occurred()) {
892 PyErr_Format(PyExc_ImportError, "module '%U' is not in sys.modules", mod_id);
893 }
894 return NULL;
895 }
896 for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(names); i++) {
897 PyObject *name = PyTuple_GET_ITEM(names, i);
898 PyObject *as_name = PyTuple_GET_ITEM(as_names, i);
899 PyObject *obj = PyObject_GetAttr(mod, name);
900 if (obj == NULL) {
901 Py_DECREF(mod);
902 return NULL;
903 }
904 int ret = CPyDict_SetItem(globals, as_name, obj);
905 Py_DECREF(obj);
906 if (ret < 0) {
907 Py_DECREF(mod);
908 return NULL;
909 }
910 }
911 return mod;
912 }
913
914 // From CPython
915 static PyObject *
916 CPy_BinopTypeError(PyObject *left, PyObject *right, const char *op) {
917 PyErr_Format(PyExc_TypeError,
918 "unsupported operand type(s) for %.100s: "
919 "'%.100s' and '%.100s'",
920 op,
921 Py_TYPE(left)->tp_name,
922 Py_TYPE(right)->tp_name);
923 return NULL;
924 }
925
926 PyObject *
927 CPy_CallReverseOpMethod(PyObject *left,
928 PyObject *right,
929 const char *op,
930 PyObject *method) {
931 // Look up reverse method
932 PyObject *m = PyObject_GetAttr(right, method);
933 if (m == NULL) {
934 // If reverse method not defined, generate TypeError instead AttributeError
935 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
936 CPy_BinopTypeError(left, right, op);
937 }
938 return NULL;
939 }
940 // Call reverse method
941 PyObject *result = PyObject_CallOneArg(m, left);
942 Py_DECREF(m);
943 return result;
944 }
945
946 PyObject *CPySingledispatch_RegisterFunction(PyObject *singledispatch_func,
947 PyObject *cls,
948 PyObject *func) {
949 PyObject *registry = PyObject_GetAttr(singledispatch_func, mypyc_interned_str.registry);
950 PyObject *register_func = NULL;
951 PyObject *typing = NULL;
952 PyObject *get_type_hints = NULL;
953 PyObject *type_hints = NULL;
954
955 if (registry == NULL) goto fail;
956 if (func == NULL) {
957 // one argument case
958 if (PyType_Check(cls)) {
959 // passed a class
960 // bind cls to the first argument so that register gets called again with both the
961 // class and the function
962 register_func = PyObject_GetAttr(singledispatch_func, mypyc_interned_str.register_);
963 if (register_func == NULL) goto fail;
964 return PyMethod_New(register_func, cls);
965 }
966 // passed a function
967 PyObject *annotations = PyFunction_GetAnnotations(cls);
968 const char *invalid_first_arg_msg =
969 "Invalid first argument to `register()`: %R. "
970 "Use either `@register(some_class)` or plain `@register` "
971 "on an annotated function.";
972
973 if (annotations == NULL) {
974 PyErr_Format(PyExc_TypeError, invalid_first_arg_msg, cls);
975 goto fail;
976 }
977
978 Py_INCREF(annotations);
979
980 func = cls;
981 typing = PyImport_ImportModule("typing");
982 if (typing == NULL) goto fail;
983 get_type_hints = PyObject_GetAttr(typing, mypyc_interned_str.get_type_hints);
984
985 type_hints = PyObject_CallOneArg(get_type_hints, func);
986 PyObject *argname;
987 Py_ssize_t pos = 0;
988 if (!PyDict_Next(type_hints, &pos, &argname, &cls)) {
989 // the functools implementation raises the same type error if annotations is an empty dict
990 PyErr_Format(PyExc_TypeError, invalid_first_arg_msg, cls);
991 goto fail;
992 }
993 if (!PyType_Check(cls)) {
994 const char *invalid_annotation_msg = "Invalid annotation for %R. %R is not a class.";
995 PyErr_Format(PyExc_TypeError, invalid_annotation_msg, argname, cls);
996 goto fail;
997 }
998 }
999 if (PyDict_SetItem(registry, cls, func) == -1) {
1000 goto fail;
1001 }
1002
1003 // clear the cache so we consider the newly added function when dispatching
1004 PyObject *dispatch_cache = PyObject_GetAttr(singledispatch_func, mypyc_interned_str.dispatch_cache);
1005 if (dispatch_cache == NULL) goto fail;
1006 PyDict_Clear(dispatch_cache);
1007
1008 Py_INCREF(func);
1009 return func;
1010
1011 fail:
1012 Py_XDECREF(registry);
1013 Py_XDECREF(register_func);
1014 Py_XDECREF(typing);
1015 Py_XDECREF(get_type_hints);
1016 Py_XDECREF(type_hints);
1017 return NULL;
1018
1019 }
1020
1021 // Adapted from ceval.c GET_AITER
1022 PyObject *CPy_GetAIter(PyObject *obj)
1023 {
1024 unaryfunc getter = NULL;
1025 PyTypeObject *type = Py_TYPE(obj);
1026
1027 if (type->tp_as_async != NULL) {
1028 getter = type->tp_as_async->am_aiter;
1029 }
1030
1031 if (getter == NULL) {
1032 PyErr_Format(PyExc_TypeError,
1033 "'async for' requires an object with "
1034 "__aiter__ method, got %.100s",
1035 type->tp_name);
1036 Py_DECREF(obj);
1037 return NULL;
1038 }
1039
1040 PyObject *iter = (*getter)(obj);
1041 if (!iter) {
1042 return NULL;
1043 }
1044
1045 if (Py_TYPE(iter)->tp_as_async == NULL ||
1046 Py_TYPE(iter)->tp_as_async->am_anext == NULL) {
1047
1048 PyErr_Format(PyExc_TypeError,
1049 "'async for' received an object from __aiter__ "
1050 "that does not implement __anext__: %.100s",
1051 Py_TYPE(iter)->tp_name);
1052 Py_DECREF(iter);
1053 return NULL;
1054 }
1055
1056 return iter;
1057 }
1058
1059 // Adapted from ceval.c GET_ANEXT
1060 PyObject *CPy_GetANext(PyObject *aiter)
1061 {
1062 unaryfunc getter = NULL;
1063 PyObject *next_iter = NULL;
1064 PyObject *awaitable = NULL;
1065 PyTypeObject *type = Py_TYPE(aiter);
1066
1067 if (PyAsyncGen_CheckExact(aiter)) {
1068 awaitable = type->tp_as_async->am_anext(aiter);
1069 if (awaitable == NULL) {
1070 goto error;
1071 }
1072 } else {
1073 if (type->tp_as_async != NULL){
1074 getter = type->tp_as_async->am_anext;
1075 }
1076
1077 if (getter != NULL) {
1078 next_iter = (*getter)(aiter);
1079 if (next_iter == NULL) {
1080 goto error;
1081 }
1082 }
1083 else {
1084 PyErr_Format(PyExc_TypeError,
1085 "'async for' requires an iterator with "
1086 "__anext__ method, got %.100s",
1087 type->tp_name);
1088 goto error;
1089 }
1090
1091 awaitable = CPyCoro_GetAwaitableIter(next_iter);
1092 if (awaitable == NULL) {
1093 _PyErr_FormatFromCause(
1094 PyExc_TypeError,
1095 "'async for' received an invalid object "
1096 "from __anext__: %.100s",
1097 Py_TYPE(next_iter)->tp_name);
1098
1099 Py_DECREF(next_iter);
1100 goto error;
1101 } else {
1102 Py_DECREF(next_iter);
1103 }
1104 }
1105
1106 return awaitable;
1107 error:
1108 return NULL;
1109 }
1110
1111 #if CPY_3_11_FEATURES
1112
1113 // Return obj.__name__ (specialized to type objects, which are the most common target).
1114 PyObject *CPy_GetName(PyObject *obj) {
1115 if (PyType_Check(obj)) {
1116 return PyType_GetName((PyTypeObject *)obj);
1117 }
1118 return PyObject_GetAttr(obj, mypyc_interned_str.__name__);
1119 }
1120
1121 #endif
1122
1123 #ifdef MYPYC_LOG_TRACE
1124
1125 // This is only compiled in if trace logging is enabled by user
1126
1127 static int TraceCounter = 0;
1128 static const int TRACE_EVERY_NTH = 1009; // Should be a prime number
1129 #define TRACE_LOG_FILE_NAME "mypyc_trace.txt"
1130 static FILE *TraceLogFile = NULL;
1131
1132 // Log a tracing event on every Nth call
1133 void CPyTrace_LogEvent(const char *location, const char *line, const char *op, const char *details) {
1134 if (TraceLogFile == NULL) {
1135 if ((TraceLogFile = fopen(TRACE_LOG_FILE_NAME, "w")) == NULL) {
1136 fprintf(stderr, "error: Could not open trace file %s\n", TRACE_LOG_FILE_NAME);
1137 abort();
1138 }
1139 }
1140 if (TraceCounter == 0) {
1141 fprintf(TraceLogFile, "%s:%s:%s:%s\n", location, line, op, details);
1142 }
1143 TraceCounter++;
1144 if (TraceCounter == TRACE_EVERY_NTH) {
1145 TraceCounter = 0;
1146 }
1147 }
1148
1149 #endif
1150
1151 #if CPY_3_12_FEATURES
1152
1153 // Copied from Python 3.12.3, since this struct is internal to CPython. It defines
1154 // the structure of typing.TypeAliasType objects. We need it since compute_value is
1155 // not part of the public API, and we need to set it to match Python runtime semantics.
1156 //
1157 // IMPORTANT: This needs to be kept in sync with CPython!
1158 typedef struct {
1159 PyObject_HEAD
1160 PyObject *name;
1161 #if CPY_3_15_FEATURES
1162 PyObject *qualname;
1163 #endif
1164 PyObject *type_params;
1165 PyObject *compute_value;
1166 PyObject *value;
1167 PyObject *module;
1168 } typealiasobject;
1169
1170 void CPy_SetTypeAliasTypeComputeFunction(PyObject *alias, PyObject *compute_value) {
1171 typealiasobject *obj = (typealiasobject *)alias;
1172 if (obj->value != NULL) {
1173 Py_DECREF(obj->value);
1174 }
1175 obj->value = NULL;
1176 Py_INCREF(compute_value);
1177 if (obj->compute_value != NULL) {
1178 Py_DECREF(obj->compute_value);
1179 }
1180 obj->compute_value = compute_value;
1181 }
1182
1183 #endif
1184
1185 #ifdef _WIN32
1186 #define SEP "\\"
1187 #else
1188 #define SEP "/"
1189 #endif
1190
1191 // Cached class references for __spec__ / __loader__ construction.
1192 static PyObject *CPyImport_ModuleSpecClass = NULL;
1193 static PyObject *CPyImport_ExtFileLoaderClass = NULL;
1194 static PyObject *CPyImport_SpecKwnames = NULL; // ("origin", "is_package")
1195
1196 // Initialize cached references for ModuleSpec and ExtensionFileLoader.
1197 // Returns 0 on success, -1 on error.
1198 static int CPyImport_InitSpecClasses(void) {
1199 if (CPyImport_ModuleSpecClass != NULL) {
1200 return 0;
1201 }
1202 PyObject *machinery = PyImport_ImportModule("importlib.machinery");
1203 if (machinery == NULL) {
1204 return -1;
1205 }
1206 CPyImport_ModuleSpecClass = PyObject_GetAttrString(machinery, "ModuleSpec");
1207 CPyImport_ExtFileLoaderClass = PyObject_GetAttrString(machinery, "ExtensionFileLoader");
1208 Py_DECREF(machinery);
1209 if (CPyImport_ModuleSpecClass == NULL || CPyImport_ExtFileLoaderClass == NULL) {
1210 Py_CLEAR(CPyImport_ModuleSpecClass);
1211 Py_CLEAR(CPyImport_ExtFileLoaderClass);
1212 return -1;
1213 }
1214 PyObject *origin_str = PyUnicode_InternFromString("origin");
1215 PyObject *is_package_str = PyUnicode_InternFromString("is_package");
1216 if (origin_str == NULL || is_package_str == NULL) {
1217 CPyError_OutOfMemory();
1218 }
1219 CPyImport_SpecKwnames = PyTuple_Pack(2, origin_str, is_package_str);
1220 Py_DECREF(origin_str);
1221 Py_DECREF(is_package_str);
1222 if (CPyImport_SpecKwnames == NULL) {
1223 CPyError_OutOfMemory();
1224 }
1225 return 0;
1226 }
1227
1228 // Set __package__ before executing the module body so it is available
1229 // during module initialization. For a package, __package__ is the module
1230 // name itself. For a non-package submodule "a.b.c", it is "a.b". For a
1231 // top-level non-package module, it is "".
1232 static int CPyImport_SetModulePackage(PyObject *modobj, PyObject *module_name,
1233 Py_ssize_t is_package) {
1234 PyObject *pkg = NULL;
1235 int rc = PyObject_GetOptionalAttrString(modobj, "__package__", &pkg);
1236 if (rc < 0) {
1237 return -1;
1238 }
1239 if (pkg != NULL && pkg != Py_None) {
1240 Py_DECREF(pkg);
1241 return 0;
1242 }
1243 Py_XDECREF(pkg);
1244
1245 PyObject *package_name = NULL;
1246 if (is_package) {
1247 package_name = module_name;
1248 Py_INCREF(package_name);
1249 } else {
1250 Py_ssize_t name_len = PyUnicode_GetLength(module_name);
1251 if (name_len < 0) {
1252 return -1;
1253 }
1254 Py_ssize_t dot = PyUnicode_FindChar(module_name, '.', 0, name_len, -1);
1255 if (dot >= 0) {
1256 package_name = PyUnicode_Substring(module_name, 0, dot);
1257 } else {
1258 package_name = PyUnicode_FromString("");
1259 }
1260 }
1261 if (package_name == NULL) {
1262 return -1;
1263 }
1264 rc = PyObject_SetAttrString(modobj, "__package__", package_name);
1265 Py_DECREF(package_name);
1266 return rc;
1267 }
1268
1269 // Derive and set __file__ on modobj from the shared library path, module name,
1270 // and extension suffix. Returns 0 on success, -1 on error.
1271 static int CPyImport_SetModuleFile(PyObject *modobj, PyObject *module_name,
1272 PyObject *shared_lib_file, PyObject *ext_suffix,
1273 Py_ssize_t is_package) {
1274 PyObject *file = NULL;
1275 int rc = PyObject_GetOptionalAttrString(modobj, "__file__", &file);
1276 if (rc < 0) {
1277 return -1;
1278 }
1279 if (file != NULL) {
1280 // __file__ already set, nothing to do.
1281 Py_DECREF(file);
1282 return 0;
1283 }
1284 // Derive __file__ from the shared lib's directory, the module
1285 // name, and the extension suffix. Two layouts:
1286 //
1287 // Monolithic: one shared lib above the package tree holds many
1288 // modules, so append the full dotted module path.
1289 // separate=True: each module has its own "<segment>__mypyc.so"
1290 // next to the module, so dirname(shared_lib) is already inside
1291 // the parent package. Append only the last segment.
1292 //
1293 // Detect the separate=True case by matching the shared lib's
1294 // basename against "<last_segment>__mypyc<ext>".
1295 PyObject *derived_file = NULL;
1296 if (shared_lib_file != NULL && shared_lib_file != Py_None &&
1297 PyUnicode_Check(shared_lib_file)) {
1298 Py_ssize_t sf_len = PyUnicode_GetLength(shared_lib_file);
1299 // Find the last path separator, checking both '/' and '\\'
1300 // for cross-platform support.
1301 Py_ssize_t sep = PyUnicode_FindChar(shared_lib_file, '/', 0, sf_len, -1);
1302 Py_ssize_t bsep = PyUnicode_FindChar(shared_lib_file, '\\', 0, sf_len, -1);
1303 if (bsep > sep) {
1304 sep = bsep;
1305 }
1306 // Use the same separator character found in the path, or
1307 // the platform default if no separator was found.
1308 Py_UCS4 sep_char = sep >= 0
1309 ? PyUnicode_ReadChar(shared_lib_file, sep)
1310 : (Py_UCS4)SEP[0];
1311 PyObject *dot_str = PyUnicode_FromString(".");
1312 PyObject *sep_str = PyUnicode_FromOrdinal(sep_char);
1313 if (dot_str == NULL || sep_str == NULL) {
1314 CPyError_OutOfMemory();
1315 }
1316 PyObject *module_path = PyUnicode_Replace(module_name, dot_str, sep_str, -1);
1317 Py_DECREF(dot_str);
1318 Py_DECREF(sep_str);
1319 if (module_path == NULL) {
1320 return -1;
1321 }
1322
1323 // Compute the module's last dotted segment for the separate=True check.
1324 Py_ssize_t name_len = PyUnicode_GetLength(module_name);
1325 Py_ssize_t last_dot = PyUnicode_FindChar(module_name, '.', 0, name_len, -1);
1326 PyObject *last_segment;
1327 if (last_dot >= 0) {
1328 last_segment = PyUnicode_Substring(module_name, last_dot + 1, name_len);
1329 } else {
1330 last_segment = module_name;
1331 Py_INCREF(last_segment);
1332 }
1333 if (last_segment == NULL) {
1334 Py_DECREF(module_path);
1335 return -1;
1336 }
1337 // Compare shared_lib_file basename against "<last_segment>__mypyc<ext>".
1338 PyObject *expected_basename = PyUnicode_FromFormat(
1339 "%U__mypyc%U", last_segment, ext_suffix);
1340 PyObject *actual_basename;
1341 if (sep >= 0) {
1342 actual_basename = PyUnicode_Substring(shared_lib_file, sep + 1, sf_len);
1343 } else {
1344 actual_basename = shared_lib_file;
1345 Py_INCREF(actual_basename);
1346 }
1347 int is_per_module_lib = 0;
1348 if (expected_basename != NULL && actual_basename != NULL) {
1349 is_per_module_lib =
1350 (PyUnicode_Compare(expected_basename, actual_basename) == 0);
1351 }
1352 Py_XDECREF(expected_basename);
1353 Py_XDECREF(actual_basename);
1354
1355 // For packages, __file__ should point to __init__<ext>,
1356 // e.g. "a/b/__init__.cpython-312-x86_64-linux-gnu.so".
1357 PyObject *file_path = is_per_module_lib ? last_segment : module_path;
1358 if (sep >= 0) {
1359 PyObject *dir = PyUnicode_Substring(shared_lib_file, 0, sep);
1360 if (dir != NULL) {
1361 if (is_package) {
1362 derived_file = PyUnicode_FromFormat(
1363 "%U%c%U%c__init__%U", dir, (int)sep_char,
1364 file_path, (int)sep_char, ext_suffix);
1365 } else {
1366 derived_file = PyUnicode_FromFormat(
1367 "%U%c%U%U", dir, (int)sep_char,
1368 file_path, ext_suffix);
1369 }
1370 Py_DECREF(dir);
1371 }
1372 } else {
1373 if (is_package) {
1374 derived_file = PyUnicode_FromFormat(
1375 "%U%c__init__%U", file_path, (int)SEP[0], ext_suffix);
1376 } else {
1377 derived_file = PyUnicode_FromFormat("%U%U", file_path, ext_suffix);
1378 }
1379 }
1380 Py_DECREF(last_segment);
1381 Py_DECREF(module_path);
1382 }
1383 if (derived_file == NULL && !PyErr_Occurred()) {
1384 derived_file = module_name;
1385 Py_INCREF(derived_file);
1386 }
1387 if (derived_file == NULL ||
1388 PyObject_SetAttrString(modobj, "__file__", derived_file) < 0) {
1389 Py_XDECREF(derived_file);
1390 return -1;
1391 }
1392 Py_DECREF(derived_file);
1393 return 0;
1394 }
1395
1396 // Set __path__ to [dirname(__file__)] on a package module if not already set.
1397 // Returns 0 on success, -1 on error.
1398 static int CPyImport_SetModulePath(PyObject *modobj) {
1399 PyObject *existing_path = NULL;
1400 int rc = PyObject_GetOptionalAttrString(modobj, "__path__", &existing_path);
1401 if (rc < 0) {
1402 return -1;
1403 }
1404 if (existing_path != NULL) {
1405 Py_DECREF(existing_path);
1406 return 0;
1407 }
1408 PyObject *file = NULL;
1409 rc = PyObject_GetOptionalAttrString(modobj, "__file__", &file);
1410 if (rc <= 0) {
1411 return rc;
1412 }
1413 PyObject *os_path = PyImport_ImportModule("os.path");
1414 if (os_path == NULL) {
1415 Py_DECREF(file);
1416 return -1;
1417 }
1418 PyObject *dir = PyObject_CallMethod(os_path, "dirname", "O", file);
1419 Py_DECREF(os_path);
1420 Py_DECREF(file);
1421 if (dir == NULL) {
1422 return -1;
1423 }
1424 PyObject *path_list = PyList_New(1);
1425 if (path_list == NULL) {
1426 CPyError_OutOfMemory();
1427 }
1428 PyList_SET_ITEM(path_list, 0, dir); // steals ref to dir
1429 int ret = PyObject_SetAttrString(modobj, "__path__", path_list);
1430 Py_DECREF(path_list);
1431 return ret;
1432 }
1433
1434 // Set __spec__ and __loader__ on modobj if not already set.
1435 // Returns 0 on success, -1 on error.
1436 static int CPyImport_SetModuleSpec(PyObject *modobj, PyObject *module_name,
1437 Py_ssize_t is_package) {
1438 PyObject *spec = NULL;
1439 int rc = PyObject_GetOptionalAttrString(modobj, "__spec__", &spec);
1440 if (rc < 0) {
1441 return -1;
1442 }
1443 if (spec != NULL && spec != Py_None) {
1444 // __spec__ already set.
1445 Py_DECREF(spec);
1446 return 0;
1447 }
1448 Py_XDECREF(spec);
1449 if (CPyImport_InitSpecClasses() < 0) {
1450 return -1;
1451 }
1452 PyObject *file = NULL;
1453 if (PyObject_GetOptionalAttrString(modobj, "__file__", &file) < 0) {
1454 return -1;
1455 }
1456 if (file == NULL) {
1457 file = Py_None;
1458 Py_INCREF(file);
1459 }
1460 // ExtensionFileLoader(name, path)
1461 PyObject *loader = PyObject_CallFunctionObjArgs(
1462 CPyImport_ExtFileLoaderClass, module_name, file, NULL);
1463 if (loader == NULL) {
1464 Py_DECREF(file);
1465 return -1;
1466 }
1467 // ModuleSpec(name, loader, *, origin=file, is_package=is_package)
1468 PyObject *is_pkg_obj = is_package ? Py_True : Py_False;
1469 PyObject *spec_args[] = {NULL, module_name, loader, file, is_pkg_obj};
1470 spec = PyObject_Vectorcall(
1471 CPyImport_ModuleSpecClass,
1472 spec_args + 1,
1473 2 | PY_VECTORCALL_ARGUMENTS_OFFSET,
1474 CPyImport_SpecKwnames);
1475 Py_DECREF(file);
1476 if (spec == NULL) {
1477 Py_DECREF(loader);
1478 return -1;
1479 }
1480 if (is_package) {
1481 // Set submodule_search_locations from __path__
1482 PyObject *path = NULL;
1483 if (PyObject_GetOptionalAttrString(modobj, "__path__", &path) < 0) {
1484 Py_DECREF(spec);
1485 Py_DECREF(loader);
1486 return -1;
1487 }
1488 if (path != NULL) {
1489 if (PyObject_SetAttrString(spec, "submodule_search_locations", path) < 0) {
1490 Py_DECREF(path);
1491 Py_DECREF(spec);
1492 Py_DECREF(loader);
1493 return -1;
1494 }
1495 Py_DECREF(path);
1496 }
1497 }
1498 if (PyObject_SetAttrString(modobj, "__spec__", spec) < 0 ||
1499 PyObject_SetAttrString(modobj, "__loader__", loader) < 0) {
1500 Py_DECREF(spec);
1501 Py_DECREF(loader);
1502 return -1;
1503 }
1504 Py_DECREF(spec);
1505 Py_DECREF(loader);
1506 return 0;
1507 }
1508
1509 PyObject *CPyImport_ImportNative(PyObject *module_name,
1510 PyObject *(*init_only_fn)(void),
1511 int (*exec_fn)(PyObject *),
1512 CPyModule **module_static,
1513 PyObject *shared_lib_file, PyObject *ext_suffix,
1514 Py_ssize_t is_package) {
1515 PyObject *parent_module = NULL;
1516 PyObject *child_name = NULL;
1517 PyObject *exc_type, *exc_val, *exc_tb;
1518 Py_ssize_t name_len = PyUnicode_GetLength(module_name);
1519 if (name_len < 0) {
1520 return NULL;
1521 }
1522 Py_ssize_t dot = PyUnicode_FindChar(module_name, '.', 0, name_len, -1);
1523 if (dot >= 0) {
1524 // Import the parent package first to preserve import ordering semantics.
1525 PyObject *parent_name = PyUnicode_Substring(module_name, 0, dot);
1526 if (parent_name == NULL) {
1527 CPyError_OutOfMemory();
1528 }
1529 child_name = PyUnicode_Substring(module_name, dot + 1, name_len);
1530 if (child_name == NULL) {
1531 CPyError_OutOfMemory();
1532 }
1533 parent_module = PyImport_Import(parent_name);
1534 Py_DECREF(parent_name);
1535 if (parent_module == NULL) {
1536 Py_DECREF(child_name);
1537 return NULL;
1538 }
1539 }
1540
1541 // Create the module object without executing the module body.
1542 // CPyInitOnly_* uses an internal static to cache the module object.
1543 // We then check sys.modules to determine whether the module body
1544 // has already been executed (or is being executed in a circular import).
1545 PyObject *module_dict = PyImport_GetModuleDict();
1546 if (module_dict == NULL) {
1547 Py_XDECREF(parent_module);
1548 Py_XDECREF(child_name);
1549 return NULL;
1550 }
1551
1552 PyObject *existing = PyDict_GetItemWithError(module_dict, module_name);
1553 if (existing != NULL) {
1554 if (*module_static != NULL) {
1555 if (existing == (PyObject *)*module_static) {
1556 Py_INCREF(existing);
1557 Py_XDECREF(parent_module);
1558 Py_XDECREF(child_name);
1559 return existing;
1560 }
1561 PyErr_Format(PyExc_ImportError,
1562 "native module '%U' in sys.modules was replaced after initialization",
1563 module_name);
1564 Py_XDECREF(parent_module);
1565 Py_XDECREF(child_name);
1566 return NULL;
1567 }
1568 }
1569 if (PyErr_Occurred()) {
1570 Py_XDECREF(parent_module);
1571 Py_XDECREF(child_name);
1572 return NULL;
1573 }
1574
1575 PyObject *modobj = init_only_fn();
1576 if (modobj == NULL) {
1577 Py_XDECREF(parent_module);
1578 Py_XDECREF(child_name);
1579 return NULL;
1580 }
1581
1582 if (PyObject_SetItem(module_dict, module_name, modobj) < 0) {
1583 goto fail;
1584 }
1585
1586 if (*module_static != (CPyModule *)modobj) {
1587 PyErr_Format(PyExc_ImportError,
1588 "native module '%U' was initialized inconsistently",
1589 module_name);
1590 goto fail;
1591 }
1592
1593 if (CPyImport_SetDunderAttrs(modobj, module_name, shared_lib_file, ext_suffix, is_package) < 0) {
1594 goto fail;
1595 }
1596
1597 // Now execute the module body, with __file__ and __package__ already set.
1598 if (exec_fn(modobj) != 0) {
1599 goto fail;
1600 }
1601
1602 // Match CPython import semantics: publish parent.child only after the
1603 // child module finished executing successfully.
1604 if (parent_module != NULL && PyObject_SetAttr(parent_module, child_name, modobj) < 0) {
1605 goto fail;
1606 }
1607
1608 Py_XDECREF(parent_module);
1609 Py_XDECREF(child_name);
1610 return modobj;
1611
1612 fail:
1613 // Clean up on failure so that a subsequent import attempt will retry
1614 // initialization.
1615 PyErr_Fetch(&exc_type, &exc_val, &exc_tb);
1616 PyObject_DelItem(module_dict, module_name);
1617 PyErr_Clear();
1618 PyErr_Restore(exc_type, exc_val, exc_tb);
1619 Py_XDECREF(parent_module);
1620 Py_XDECREF(child_name);
1621 Py_CLEAR(*module_static);
1622 return NULL;
1623 }
1624
1625 int CPyImport_SetDunderAttrs(PyObject *module, PyObject *module_name, PyObject *shared_lib_file,
1626 PyObject *ext_suffix, Py_ssize_t is_package)
1627 {
1628 int res = CPyImport_SetModulePackage(module, module_name, is_package);
1629 if (res < 0) {
1630 return res;
1631 }
1632
1633 res = CPyImport_SetModuleFile(module, module_name, shared_lib_file, ext_suffix,
1634 is_package);
1635 if (res < 0) {
1636 return res;
1637 }
1638
1639 if (is_package) {
1640 res = CPyImport_SetModulePath(module);
1641 if (res < 0) {
1642 return res;
1643 }
1644 }
1645
1646 return CPyImport_SetModuleSpec(module, module_name, is_package);
1647 }
1648
1649 #if CPY_3_14_FEATURES
1650
1651 #include "internal/pycore_object.h"
1652
1653 void CPy_SetImmortal(PyObject *obj) {
1654 _Py_SetImmortal(obj);
1655 }
1656
1657 #endif