Commit Graph
10701 Commits
Author SHA1 Message Date
Vankudothu Adhi Naik b3683c0ffd gh-160682: Track running function objects in free-threaded GC (#160707) 2026-10-26 20:15:13 +05:30
Stan Ulbrych c5d09789ea Fix ignored error returns in sys initialization, _ctypes and _interpchannels (#160614) 2026-10-26 14:37:44 +00:00
Lysandros Nikolaou aa0e4109a8 gh-153568: Use a managed dict for AST nodes (#160616)
AST nodes had an explicit `__dict__` slot, so every node built by
`ast.parse` allocated its own dict. With `Py_TPFLAGS_MANAGED_DICT`,
node attributes are stored as inline values with shared keys instead.

`ast.parse` is ~15.8% faster, walking trees is ~15.9% faster, and
the memory used by the AST trees is reduced by ~51.6%.
2026-10-25 10:08:26 -07:00
Gregory P. Smith 9a235416c1 gh-159188: Do not immortalize constants in compile() of an AST (GH-159198)
In the free-threaded build, compile() of a source string sets
suppress_co_const_immortalization so that its output is the same as in
the default build.  The branch for AST objects returned before that, so
constants were replaced by the immortal ones of the interpreter's table
while a tuple of names (such as co_names) which was the same object was
not, and the marshal output depended on the code objects created before
in the process.
2026-10-24 23:59:27 -07:00
Inada NaokiandEmma Smith b26fc41b5c Remove obsolete and unused configure macros (#159513)
Co-authored-by: Emma Smith <emma@emmatyping.dev>
2026-10-25 05:18:16 +00:00
Petr ViktorinandItamar Oren 18c935f72d gh-157384: Unify _Py_ext_module_loader_info initialization (GH-157758)
- Unify `_Py_ext_module_loader_info_init*` functions. The “core” one was entirely unused, and the difference between “builtin” and “extension” can be expressed in arguments.
- Consolidate getting & checking the module name from spec. (This improves error message wording for `imp.create_builtin` with empty name.)
- Allow non-ASCII names.

Core modules (`sys` and `builtins`) still don't go through the routine.

Co-authored-by: Itamar Oren <itamarost@gmail.com>
2026-10-23 22:01:22 +02:00
Zanie BlueandPablo Galindo Salgado 1ff83ad7ad gh-128883: Store ELF perf trampoline templates in read-only data (#160366)
CPython copies the trampoline templates into executable memory. Keep the
ELF source in .rodata so BOLT preserves its bytes and boundaries.

Co-authored-by: Pablo Galindo Salgado <Pablogsal@gmail.com>
2026-10-23 19:29:45 +00:00
Paul GanssleandStan Ulbrych 6854e79163 gh-158252: Add a C implementation for strptime (#158253)
Co-authored-by: Stan Ulbrych <stan@python.org>
2026-10-23 15:23:02 +00:00
Cody MaloneyandClaude Opus 5.5 3fc4d1f9b3 gh-87613: Allow Argument Clinic vectorcall on heap types (#160115)
Heap types have no static type object so switch from `Py_Is` to an
assert that the shadowed `tp_new` / `tp_init` function is the expected
one to validate the vectorcall is only used with the right type.

Heap types can have zero-argument `__new__` and `__init__` so add
support  for that producing the same error message via a new helper
`_PyArg_NoPositionalStack()`.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 03:13:30 +00:00
Donghee Na 1a80f6d454 gh-114258: Update _ctypes and tokenize to use AC where it can be. (gh-160404) 2026-10-23 02:42:16 +00:00
Zanie Blue badd5d5ceb gh-160368: Detect sem_clockwait at runtime on Linux (#160371)
When Python is built with older Linux libc headers, timed semaphore waits use the real-time clock even if `sem_clockwait` is available at runtime. Use a weak reference on supported compilers to select `sem_clockwait` at runtime, falling back to `sem_timedwait` when the symbol is absent. ThreadSanitizer builds continue to use the real-time clock.

Addresses [astral-sh/python-build-standalone#1176](https://github.com/astral-sh/python-build-standalone/issues/1176).
2026-10-23 00:32:56 +00:00
Kumar Aditya 4af1265767 gh-159493: insert super instructions after borrow analysis in compiler (GH-160032) 2026-10-22 16:58:29 -07:00
Sumit Kumar Das 85599d33d7 gh-156399: Don't specialize LOAD_ATTR_MODULE for module subclasses (GH-156474)
Fixes https://github.com/python/cpython/issues/156399
2026-10-22 16:53:35 -07:00
d6b77c8686 gh-156780: Emscripten: support building CPython with static linking (#156781)
Adds the ability to build Emscripten statically, so that it can be linked in as
an embedded library. Includes a test of the embedding case.
---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Russell Keith-Magee <russell@keith-magee.com>
2026-10-22 19:58:32 +00:00
Jelle Zijlstra f4f8b933e3 gh-159739: Preserve ContextVar cache updates from finalizers (#160197)
Resetting a ContextVar can finalize the replaced value, whose finalizer may set the variable again. Updating the lookup cache after releasing the old context root overwrites that newer cached value, so get() can return a stale value or use a freed object. Update the cache before the old root can be released. Backport to 3.15 and 3.14.
2026-10-22 12:36:56 -07:00
Vasiliy Kiryanov 1bc0ed1ea2 gh-132414: Make invalid command-line options visible in the error message (GH-157921) 2026-10-22 18:40:41 +00:00
Jelle Zijlstra 784b305df8 gh-159739: Hold the codec registry lock while unregistering (#160168)
Concurrent calls to codecs.unregister() can shrink the search path between its length check and indexed lookup in a free-threaded build. The lookup then returns NULL and an unconditional decref crashes the interpreter; hold the registry mutex across the scan and removal. Also reported in gh-157078. Backport to 3.15 and 3.14.
2026-10-22 18:24:53 +00:00
Jelle Zijlstra 0a5762621f gh-159739: Skip context watchers cleared during notification (#160164)
A context watcher callback can clear a later watcher while a context-switch notification is being dispatched. The dispatcher still uses its earlier snapshot of active watchers, so it calls a NULL callback and crashes; check that each callback is still registered before invoking it. Backport to 3.15 and 3.14.
2026-10-22 11:21:01 -07:00
Stan Ulbrych a930e524cb Fix unchecked NULL returns in several C modules (#160213) 2026-10-22 15:55:09 +00:00
Shardul Deshpande 4f5a67a32c gh-157194: Read the opcode atomically in the specializer (#157195) 2026-10-22 14:59:30 +05:30
Timur Mamedov 4ecf6ca1b3 gh-151818: Fix double-free in _CALL_LIST_APPEND on allocation failure (#151826)
_CALL_LIST_APPEND stole the arg stackref via PyStackRef_AsPyObjectSteal
and passed it to _PyList_AppendTakeRef. When the list's backing array
failed to grow, _PyList_AppendTakeRef decreffed the item, but the stale
stackref remained on the value stack. The exception unwinder then closed
it a second time, causing a double-free / use-after-free.

Fix by giving _PyList_AppendTakeRef a separate reference via Py_NewRef
and closing the stackref explicitly on success. On the error path the
stackref still holds a valid reference, so the exception unwinder can
safely close it.
2026-10-21 21:52:56 -07:00
Donghee Na aff7a2e23b gh-159111: Update vendored mimalloc to v2.5.2 (gh-159112)
* Update vendored mimalloc to v2.5.2

Upgrade mimalloc from v2.1.2 to v2.5.2 as-is from upstream.

v2.1.2: https://github.com/microsoft/mimalloc/releases/tag/v2.1.2
v2.5.2: https://github.com/microsoft/mimalloc/releases/tag/v2.5.2

* Re-apply CPython-specific changes to mimalloc v2.5.2

Most of the previous downstream changes were upstreamed in mimalloc
v2.1.3 - v2.1.7 (heap tags, _mi_heap_init/_mi_tld_init, MI_PRIM_THREAD_ID,
sub-processes, heap walk optimizations, platform fixes) and are dropped.

Remaining CPython-specific changes, all marked with a "CPython" comment:

- QSBR delayed page freeing for free-threaded builds (gh-115103,
  gh-145615): mi_page_t/mi_heap_t fields and _PyMem_mi_* hooks in
  page.c, heap.c and segment.c.
- debug_offset: preserve the first bytes of a PyObject (ob_tid, refcount
  fields) when filling freed or uninitialized memory in debug builds
  (gh-115491).
- Atomic mi_block_t.next loads/stores to avoid TSAN reports (gh-129748).
- Relax the owning thread assertion in _mi_free_delayed_block for
  free-threaded builds, since the GC traverses heaps of other threads.
- Call _mi_heap_delayed_free_partial() in mi_heap_visit_blocks()
  (gh-112532).
- Only count reclaimed pages up to MI_MEDIUM_OBJ_SIZE_MAX as a
  "right page" in mi_segment_reclaim (gh-115103).
- Rename the weak _ZSt15get_new_handlerv symbol and disable the
  mi_is_in_heap_region debug warning.
- Zero-initialize _mi_page_empty instead of a positional initializer.

* Update the free-threaded build to mimalloc v2.5.2 changes

mimalloc v2.1.4 replaced the list of abandoned segments with per-arena
bitmaps and introduced sub-processes (mi_subproc_t) to keep abandoned
segments of separate interpreters apart. Use them instead of the
CPython-specific mi_abandoned_pool_t:

- Each interpreter owns a mi_subproc_t created in init_interpreter().
- tstate_mimalloc_bind() sets tld->segments.subproc and uses the
  upstream _mi_heap_init() signature.
- The GC and sys.getallocatedblocks() visit abandoned segments with
  _PyMem_mi_visit_abandoned_blocks(), the upstream cursor API without
  the mi_option_visit_abandoned requirement, while STW.

* Update NEWS.d

* fix MSAN

* fix TSAN

* fix test_cext

* Disable THP

* Address code review

* Address code review

* Address code review

* nit

* Address code review

* Address code review
2026-10-21 17:41:07 -07:00
tonghuaroot (童话) ed144b722f gh-153014: Fix data race on the GC debug flag in free-threading builds (gh-153015)
In free-threading builds gc.set_debug() stored gcstate->debug with a plain
write while gc.get_debug() and the collector read it without synchronisation,
which ThreadSanitizer reports as a data race.  Access the flag with
FT_ATOMIC_STORE/LOAD_INT_RELAXED, consistent with how gc.enable()/disable() already handle gcstate->enabled.
2026-10-21 16:16:13 -07:00
Christian Aurich Zanettini Martins 50c24913a4 gh-159399: Fix crash in codecs.encode() on a concurrently unregistered codec (#159400)
* gh-159399: Fix crash in codecs.encode() on a concurrently unregistered codec

In the free-threaded build, codec_getitem() released the CodecInfo tuple
returned by _PyCodec_Lookup() before taking a reference to the encoder
or decoder it returns. If another thread cleared the lookup cache in
between with codecs.unregister(), the tuple could hold the last
reference to the item, which was then freed before it was increfed.

Take the reference before releasing the tuple, as
codec_getitem_checked() already does.

* Remove the free-threading stress test
2026-10-21 09:52:44 -07:00
Rafid AslamandLukasz Langa 81518cec90 gh-125873: Improve error message when PYTHONHOME is invalid (#126027)
Co-authored-by: Lukasz Langa <ambv@meta.com>
2026-10-21 00:57:56 -07:00
Jelle Zijlstra fab1405da8 gh-159739: Fix reference and error handling in warnings (#159758)
Do not release the borrowed skip_file_prefixes argument, and stop if
allocation of the fallback filename fails.
2026-10-20 21:34:23 -07:00
Jelle Zijlstra 2315d94664 gh-159739: Clear free-threaded GC worklists after early errors (#159979)
Backport to 3.15 and 3.14.
2026-10-20 21:32:19 -07:00
Gr4ph0s 39bc958bf9 gh-159860: Adjust QSBR cache line size from 64 to 128 on AArch64 (gh-159862) 2026-10-20 20:06:55 +00:00
Victor Stinner 14b43d4d3c gh-159603: Call pthread_attr_init() in hardware_stack_limits() (#159857)
Always call pthread_attr_init() in hardware_stack_limits(), not only
on FreeBSD (if pthread_attr_get_np() is available).

Emscripten: add pthread_attr_init() workaround.
2026-10-20 13:15:57 -05:00
Jelle ZijlstraandJelle Zijlstra 905aab60f7 gh-159739: Bound encoding-name lookahead in surrogatepass (#159785)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2026-10-20 10:23:14 -07:00
Jelle ZijlstraandJelle Zijlstra 7652a6dacc gh-159739: Avoid leaking references during free-threaded GC enumeration (#159781)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2026-10-20 10:20:43 -07:00
Arnold DumasandEthan Furman 25b17d4d51 bpo-24053: Add EXIT_SUCCESS and EXIT_FAILURE values in the sys module (GH-14773)
Co-authored-by: Ethan Furman <ethan@stoneleaf.us>
2026-10-20 10:10:10 -07:00
Kumar Aditya cb12c5e514 gh-157361: Implement aiter() in Python instead of C (#157687)
gh-157361: Implement aiter() in Python instead of C

Move both forms of aiter() into the frozen _pybuiltins module and remove
the C async_callable_iterator types. The callable form now returns an
iterator whose __anext__() is a plain coroutine, so call-graph tools can
see through it into the awaited result of the callable.
2026-10-20 15:33:36 +05:30
Victor Stinner 71ba39dc05 gh-159603: Use pthread_attr_get_np() on FreeBSD (#159604)
Use pthread_attr_get_np() on FreeBSD to get the stack size (and guard
size) of the current thread.

Check if pthread_attr_get_np() function and <pthread_np.h> header are
available in configure.

Update test_json.test_recursion. On FreeBSD 16 with a default stack size of
512 MB, the json C implementation no longer raises RecursionError in
test_highly_nested_objects_encoding(). Reduce also max_depth from 5,000 to
2,000 so test_highly_nested_objects_encoding() of the Python implementation
only takes 1.6 seconds, instead of 12 seconds.
2026-10-19 20:54:27 -07:00
Jelle Zijlstra 626394e0a3 gh-159739: Handle interpreter configuration encoding errors (#159747)
Propagate UTF-8 conversion errors before copying a string configuration
value.
2026-10-19 19:30:32 -07:00
Jelle ZijlstraandJelle Zijlstra 395d766d4f gh-159739: Release replaced PyInitConfig strings (GH-159769)
* gh-159739: Release replaced PyInitConfig strings

Backport to 3.15 and 3.14.

---------

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2026-10-19 22:56:57 +00:00
7641c5d691 gh-145019: improve SyntaxError when match patterns bind different names (#145939)
Co-authored-by: AN Long <aisk@users.noreply.github.com>
Co-authored-by: Petr Viktorin <encukou@gmail.com>
2026-10-19 13:02:04 -07:00
limadog9 f0f76de0c8 gh-158121: Preserve instruction events when line monitoring is disabled (#158456) 2026-10-19 12:17:16 -07:00
Han 036d309cf5 gh-130279: Fix missing exception handlers for jumps in loops (#159460) 2026-10-19 09:10:15 +01:00
Nathan Goldbaum 999855b07f gh-159041: Fix use-after-free in asyncio task tracking during thread state cleanup (#159073) 2026-10-19 10:16:36 +05:30
Pablo Galindo Salgado 6af655301a gh-159465: Improve incomplete input detection (#159466)
* gh-159465: Improve incomplete input detection

* gh-159465: Track newline effects and preserve parser layout

* gh-159465: Share incomplete-input error cleanup
2026-10-18 11:54:19 +01:00
Neil Schemenauer 010bebbf9f gh-159136: Avoid stop-the-world when setting function name attributes (gh-159269)
Setting __name__, __qualname__, __doc__ or __module__ on a function
stopped the world in the free-threaded build since gh-154826 and
gh-154851, making functools.wraps() orders of magnitude slower with
multiple threads.

Use the per-object critical section and _PyObject_XSetRefDelayed()
instead, as gen_set_name() already does.  Use acquire loads in the
readers and hold strong references across error reporting, tracing, and
eval-frame recording that may execute Python or detach the thread.  The
__code__, __defaults__, __kwdefaults__ and __closure__ setters still
stop the world to clear func_version.

Document synchronization requirements for direct field access and the
lifetime of borrowed function attributes.
2026-10-16 20:24:12 -07:00
Neil Schemenauer 801377967f gh-158973: Reset the warnings lock after fork in the child (gh-158974) 2026-10-16 20:11:09 -07:00
Victor Stinner 35a000974a Revert "gh-158445: Allocate memory in the heap in Py_GetVersion() (#158608)" (#159519)
This reverts commit f5e913c7f7.

Truncating the static buffer to 20 bytes caused a regression in debuggers
and crash reporters checking `version` static buffer, see:
https://github.com/python/cpython/pull/158608#issuecomment-6027641907
2026-10-16 10:49:53 +00:00
T. WoutersandMalcolm Smith 8ff41c2ae7 gh-159320: Enable stack size detection on Android (#159321)
Extend the use of pthread_getattr_np in stack size detection from any glibc linux to any glibc *or* android linux. Update tests for android's new recursion limit.

Co-authored-by: Malcolm Smith <smith@chaquo.com>
2026-10-14 14:11:01 +02:00
Brett Cannon 084aff869c GH-158628: Implement sys._wasi_info (GH-159039)
Starting off with WASI version, WASI SDK version, and whether cooperative multithreading is available. All values are required as WASI SDK is the officially  supported compiler according to PEP 11.
2026-10-13 23:53:38 +00:00
Itamar Oren 04862280a2 gh-157384: Set package context in PyImport_CreateModuleFromInitfunc() (GH-157387)
A single-phase init function that creates its module using only the
last component of a dotted name (as pybind11 does for submodules) got
a module whose __name__ was the short name.  Set the package context
while calling the init function, as the dynamic loader does, so the
module gets the full name from the spec.
2026-10-13 13:35:19 +00:00
Pablo Galindo Salgado f892b11f22 gh-153569: Simplify tokenizer source views and reader ownership (#158849)
Move source access and logical spans into the tokenizer source API, and keep input and encoding ownership in the reader. Export the incremental decoder helper for parser generator extensions.
2026-10-13 13:01:17 +00:00
Gregory P. Smith 627eabf31c gh-129724: Intern string constants in the compiler, not per code object (GH-159193)
The compiler merges equal constants of a module through its constant
cache.  intern_constants() then ran on each code object and rebuilt a
frozenset (or, in the free-threaded build, a slice) when one of its
strings was replaced by an already interned one, so a constant shared by
several functions was copied for some of them depending on which strings
happened to be interned in the process.  The class body's __qualname__
constant and co_qualname had the same problem.  marshal then wrote
different bytes for the same source.

Intern the eligible strings of the final constants of each code unit
after optimization and before the code object is created.  Tuples are
updated in place; a frozenset or slice is rebuilt once and stored in the
constant cache so that later units get the same object.  The same code
is used in both builds.

Which strings are interned does not change, except that identifier-like
strings in slice constants are now interned in the default build too.

TestConstantsIdentity compares the identity graph and the marshal
output of code compiled in differently prepared processes, including
names tuples shared with constants.
2026-10-12 21:37:55 -07:00
Gregory P. Smith 48f18f0adb gh-129724: gh-156504: Make marshal output independent of reference counts (GH-159192)
The marshal writer decided whether an object can be referenced later
(FLAG_REF) from its reference count, so the output for the same value
depended on what else in the process held a reference to its parts, and
differed between the default and the free-threaded builds' view of the
same objects.  This is the remaining cause of gh-129724 and the cause of
gh-156504.

FLAG_REF is now set exactly on the objects which are written more than
once in the dump.  The writer still makes one pass: it records the
position of the type byte of each object it remembers and of each
TYPE_REF, and when the dump is complete it sets the flags and renumbers
the references.  A reference count of one is only used to skip the
hashtable.  Interned strings are no longer flagged unconditionally.

The reader is unchanged and the format version is not bumped: both the
old and the new output are loaded by old and new readers.

PyMarshal_WriteObjectToFile() now builds the data in memory and writes
it with one fwrite(), since the flags are only known at the end.
Nothing is written if the object cannot be marshalled.
2026-10-13 04:22:29 +00:00