Commit Graph
10688 Commits
Author SHA1 Message Date
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
Victor Stinner 8992704916 gh-144175: Remove internal _PyArg_ParseStack() function (#159150)
Replace internal _PyArg_ParseStack() with public PyArg_ParseArray()
in Argument Clinic.
2026-10-12 19:56:53 +02:00
Suren Nihalani 0babcdd547 gh-152315: Add a suggestion for missing self parameters (GH-152326) 2026-10-12 11:23:35 -04:00
Gregory P. Smith 1967a87ad3 gh-159184: Do not compare set elements when marshalling a set (GH-159196)
Set elements are written in the order of their dumps.  They were sorted
as (dump, element) pairs, so elements with the same dump were compared.
That raised TypeError for a set of several complex NaNs, which the
compiler can produce by constant folding, making the module impossible
to marshal.

Sort (dump, index, element) tuples, in which the indexes are all
different.  Elements with the same dump stay in the order of the set,
as float NaNs did before.
2026-10-11 15:53:04 -07:00
Gregory P. Smith cd71799c47 gh-159185: Fix marshalling of a set modified while its elements are marshalled (GH-159195)
Marshalling a set element can run Python code (__buffer__, an audit
hook) which changes the set.  The number of elements was read before
the loop, so a set which grew was written past the end of the list and
one which shrank left NULL items in the list which was then sorted.
Raise RuntimeError("set changed size during iteration") instead.
2026-10-11 14:09:04 -07:00
Pablo Galindo Salgado e878e1e968 gh-159137: Untrack tuples and count survivors in move_unreachable() (#159154) 2026-10-11 16:01:50 +00:00
Pablo Galindo Salgado fbbf4f48c4 gh-159137: Skip redundant GC resurrection analysis (#159138) 2026-10-10 22:46:49 +00:00
Hood Chatham 0ec3aee262 gh-129040: Use wasm-gc to handle pointer casts in wasi (GH-158617)
This makes it so that in wasi builds if `-DPY_CALL_TRAMPOLINE` is passed, a call trampoline adaptor is used to prevent traps when there is a call signature mismatch between a C slot handler and the signature that the interpreter uses to call it.

This requires Clang >= 22. PEP 11 specifies that builds of Python 3.15 use WASI SDK version 33 which includes clang 23.1.0, so this could be used with Python 3.15 WASI builds but not earlier ones.

It requires a WebAssembly runtime that supports wasm-gc. Wasmtime has supported wasm-gc since version 27.0 released November 25, 2024. Some other runtimes still don't support it, but for those runtimes people can use builds with the trampoline disabled.

This also removed the Emscripten trampoline support for JS runtimes with no wasm-gc support. This removes a lot of implementation complexity and allows WASI and Emscripten to share code. The main concern is that it drops support for some very old iPhones, but every iPhone model released since 2018 is compatible with versions of Safari that support wasm-gc.

Tests were added that define handlers with various wrong numbers of arguments. The tests also run on non-webassembly platforms since they should work there as well.
2026-10-09 22:25:44 +00:00
Brittany Reynoso a6e636148e gh-158820: Add null checks to avoid segfaults with lazy imports at shutdown (GH-158821)
Destructors can run after finalization has cleared the interpreter's
lazy_modules set and lazy_pending_submodules dict. Declaring or
resolving a lazy import from one of them passed NULL to PySet_Add(),
PySet_Discard() or the pending-submodules lookup.

Treat the bookkeeping as a no-op once the state is gone, as the other
readers of this state already do.
2026-10-09 13:57:05 +02:00
Victor Stinner 15dd7356f3 gh-158893: Add internal _Py_strerror() function (#158982)
Add a new internal _Py_strerror() function to Python/fileutils.c. It
uses strerror_r() if available, or use strerror() otherwise.

Replace all strerror(code) calls with _Py_strerror(code).
2026-10-07 20:31:27 +00:00
Bhuvansh 7d3fca4e04 gh-153354: Fix bool conversion in generated __annotate__ (#153360) 2026-10-06 19:34:54 -07:00
Victor Stinner 6318730aee gh-158893: Make os.strerror() thread-safe (#158927)
Make os.strerror() thread-safe: use the reentrant strerror_r()
function if available.

* The configure script now checks if strerror_r() is supported.
* Add a stress test to test_free_threading.test_os (new module).
* Add a comment on decode_current_locale() assertion which fails if
  the input string is mutated.
* Add an assertion to _Py_DecodeLocale() to detect if the input
  string was mutated during the function call.
2026-10-06 23:02:13 +02:00
Pablo Galindo Salgado 114de198c0 gh-156545, gh-158539: Fix deep flamegraph export on small C stacks and macOS runtime lookup (#158874) 2026-10-05 20:56:24 +01:00
3f9118f1d1 gh-151157: Speed up PyObject_CallMethod via _PyObject_GetMethod (#151158)
* Speed up PyObject_CallMethod via _PyObject_GetMethod

PyObject_CallMethod (and _PyObject_CallMethod, PyEval_CallMethod,
_PyObject_CallMethodId and the _SizeT variant) resolved the method with
PyObject_GetAttr, which builds a temporary bound-method object on every call,
then called it.

Resolve the method with _PyObject_GetMethod instead (the same lookup the
interpreter uses for obj.name(...)) and call it directly via
_PyObject_VectorcallPrepend, skipping the bound-method allocation.  Behaviour
is unchanged: same attribute semantics, same "attribute of type ... is not
callable" error, and the historical
PyObject_CallMethod(o, m, "O", tuple) -> o.m(*tuple) unpacking.

The shared helper callmethod() and _PyObject_CallMethodFormat() are no longer
needed: their only caller (traceback.c) now uses PyObject_CallFunction, so both
are removed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Use _PyObject_GetMethodStackRef so method calls scale in free-threading

Resolve the method in callmethod_va() via _PyObject_GetMethodStackRef()
instead of _PyObject_GetMethod(). The StackRef variant returns the method
as a deferred reference, avoiding the per-call atomic refcount on the
shared method object that otherwise serializes threads in the
free-threaded build.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* rename to callmethod

* review comments

* review comments

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Kumar Aditya <kumaraditya@python.org>
Co-authored-by: Inada Naoki <songofacandy@gmail.com>
2026-10-05 18:44:28 +00:00