Commit Graph
10678 Commits
Author SHA1 Message Date
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
cfd6cf7154 gh-157407: Use _PyUnicode_AsUTF8NoNUL for AC 's' and 'z' converters (#158210)
* gh-157407: Use _PyUnicode_AsUTF8NoNUL for AC 's' and 'z' converters

The code was doing the same as the helper added in GH-111957 but inline.
That resulted in significantly more `.text` for most functions. Refactor
the Arguemnt Clinic converters code to deduplicate a bit while keeping
generated code close to original.

On my Linux x64 box this reduces `.text` by ~6200 bytes in a clang
release build (no PGO or LTO). Performance is flat.

The helper was already exported for `_sqlite3`, update the comment that
it is used in AC generated code as well.

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

* Update Include/internal/pycore_unicodeobject.h

Co-authored-by: Pieter Eendebak <pieter.eendebak@gmail.com>

* Remove NEWS, add period

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Pieter Eendebak <pieter.eendebak@gmail.com>
2026-10-05 17:03:27 +00:00
Pablo Galindo Salgado 0b8aa89a05 gh-153569: Simplify tokenizer state (#158124)
* Use diagnostic line for missing-brace errors

* Keep implicit prepared newline metadata in the reader

* Reuse parsed formatted string kind in lexer

* Transfer owned tokenizer encoding strings

* Remove unused tokenizer state and redundant branches

* Avoid rescanning partial decoded tokenizer lines

* Reuse prepared tokenizer line terminators for CR detection

* Reuse interactive tokenizer chunks without carriage returns

* Release tokenizer constructor resources on allocation failure

* Narrow interactive newline normalization wrapper

* Close duplicated tokenizer descriptors when fdopen fails

* Preserve cached tokenizer lines when newline allocation fails

* Collect cycles involving tokenizer readline callbacks

* Preserve buffered text when decoding source files

* Clear the transferred syntax error line before cleanup

* Propagate tokenizer column conversion failures

* Allocate parser repetition buffers on first match

* Allocate type comment storage only when needed

* Reuse decoded multiline text when counting token columns

* Skip empty decoded tokenizer chunks

* Check parser array growth before allocating

* Name tokenizer bounds and derive byte lengths from their data

* Set the tokenizer exception when file input size overflows

* gh-153569: Send exact line endings in the REPL test

* Share parser repetition buffer growth

* Fold Unicode input coverage into the existing REPL test

* Keep parser array growth policy private

* Drop obsolete bitmap stress from source discard test

* Preserve input failures while scanning string literals

* fixup! Preserve input failures while scanning string literals

* fixup! fixup! Preserve input failures while scanning string literals

* gh-153569: Remove assertion-only lexer bookkeeping
2026-10-05 14:28:51 +01:00
Victor Stinner 30ce3d462d gh-158585: Simplify PyBytesWriter_Finish() (#158822)
PyBytesWriter_Finish() doesn't need to check the size. It's known to
be valid.

PyBytesWriter_Create() now only calls byteswriter_resize() if the
size is larger than the small buffer.

Remove byteswriter_data() function: call static inline
_PyBytesWriter_GetData() function directly.
2026-10-05 04:47:04 +02:00
Maurycy Pawłowski-WierońskiandPablo Galindo Salgado 5fecd448bb gh-155811: Add a seqcount to gc_stats to prevent torn reads (#155828)
* update_seq

* no need for XCHGL, MOVL is enough?

* gh-155811: Retry an inconsistent GC snapshot once

---------

Co-authored-by: Pablo Galindo Salgado <Pablogsal@gmail.com>
2026-10-05 01:49:56 +00:00
Stan UlbrychandVictor Stinner b93fb19a6e Run a job that the test suite with MSan to the CI (#158625)
* Run the test suite with MSan in CI

* Additional fixes

* Add `_Py_MSAN_UNPOISON_STRING`

* Apply Victor's suggestions

Co-authored-by: Victor Stinner <victor.stinner@gmail.com>

* Apply Victor's suggestions

Co-authored-by: Victor Stinner <victor.stinner@gmail.com>

---------

Co-authored-by: Victor Stinner <victor.stinner@gmail.com>
2026-10-05 02:11:42 +01:00
Maurycy Pawłowski-WierońskiandPablo Galindo Salgado 7d25916b41 gh-154194: Degrade frames in Tachyon instead of failing the sample (#154195)
* degrade gracefully

* news

* better NEWS wording

* do not raise on MAX_REMOTE_STR_READ

* bye MAX_REMOTE_STR_READ

* fix -m asyncio ps|pstree

* test truncation and linetable sentinel

* simpler

* simpler

* redundant now

* respect #157790 in the news

---------

Co-authored-by: Pablo Galindo Salgado <Pablogsal@gmail.com>
2026-10-05 00:37:21 +00:00
Victor Stinner d19febb00c Rework locale encoding C functions (#158680)
Add output_length to _Py_EncodeLocale(), _Py_EncodeUTF8(),
encode_current_locale() and encode_ascii(). So unicode_encode_locale() and
wstr_to_utf8() can now use the output_length, instead of having to compute
strlen().

* Rename functions:

  * _Py_DecodeUTF8Ex() => _Py_DecodeUTF8()
  * _Py_EncodeUTF8Ex() => _Py_EncodeUTF8()
  * _Py_EncodeLocaleEx() => _Py_EncodeLocale()
  * _Py_DecodeLocaleEx() => _Py_DecodeLocale()

* Add tests on Py_DecodeLocale() and Py_EncodeLocale() in test_codecs.
  Clarify also their documentation.
* _Py_EncodeLocale() and _Py_DecodeLocale() now sets all output parameters on
  error. Add more tests on these output parameters.
* Add encode_current_locale_impl() to simplify encode_current_locale().
* Remove reason parameter of _Py_EncodeLocale() and _Py_DecodeLocale() to
  simplify the code. Only the UTF-8 decoder used specific reasons.
* _Py_EncodeUTF8() now uses size_t instead of Py_ssize_t to iterate
  on the input string.
* On error, encode_current_locale_impl() now returns ENCODE_ERROR (new
  constant) instead of DECODE_ERROR.
* Mark _Py_EncodeLocaleRaw() as static (it's not used outside fileutils.c).
2026-10-04 23:22:18 +02:00
Pengyu Lee 1b015e66f0 gh-157906: fix an incorrect architecture macro check in free-threaded GC (gh-157907)
Fix typo in free-threaded GC prefetch check for 32-bit x86 MSVC.
2026-10-03 11:36:01 -07:00
Victor Stinner b42fdf6b44 Fix _PyOS_GetOpt() error message for non-ASCII characters (#158626)
Replace %c with %lc.
2026-10-03 15:37:58 +02:00
Victor Stinner f5e913c7f7 gh-158445: Allocate memory in the heap in Py_GetVersion() (#158608)
Py_GetVersion() now allocates memory on the heap, instead of using a
static buffer, to no longer truncate the version if it's longer than
299 bytes.

Update Py_GetCompiler() and Py_GetBuildInfo() tests: they are now
always a part of sys.version.
2026-10-03 15:15:08 +02:00