Commit graph

8832 commits

Author SHA1 Message Date
Victor Stinner
d12d8c50cd
gh-111178: Fix function signatures in odictobject.c (#131160)
Add _PyODictObject_CAST() macro.
2025-03-13 10:14:59 +00:00
Victor Stinner
50e9eba32c
gh-111178: Fix function signatures in rangeobject.c (#131161) 2025-03-13 09:56:06 +00:00
Victor Stinner
0c6c52f496
gh-111178: Fix PyRangeIter_Type deallocator (#131162)
Don't use PyObject_Free() as tp_dealloc to avoid an undefined
behavior. Instead, use the default deallocator which just calls
tp_free which is PyObject_Free().
2025-03-13 10:46:20 +01:00
Victor Stinner
36978f7ef3
gh-111178: Fix function signatures in iterobject.c (#131163) 2025-03-13 10:42:59 +01:00
Victor Stinner
2ed671b5e3
gh-111178: Change Argument Clinic signature for @staticmethod (#131157) (#131159)
Use "PyObject*", instead of "void*", for `@staticmethod` functions to
fix an undefined behavior.
2025-03-13 10:22:58 +01:00
Mark Shannon
f30376c650
GH-127705: Fix _Py_RefcntAdd to handle objects becoming immortal (GH-131140) 2025-03-12 16:54:10 +00:00
Victor Stinner
061da44bac
gh-111178: Change Argument Clinic signature for @classmethod (#131157)
Use "PyObject*", instead of "PyTypeObject*", for `@classmethod`
functions to fix an undefined behavior.
2025-03-12 17:42:07 +01:00
T. Wouters
de2f7da77d
gh-115999: Add free-threaded specialization for FOR_ITER (#128798)
Add free-threaded versions of existing specialization for FOR_ITER (list, tuples, fast range iterators and generators), without significantly affecting their thread-safety. (Iterating over shared lists/tuples/ranges should be fine like before. Reusing iterators between threads is not fine, like before. Sharing generators between threads is a recipe for significant crashes, like before.)
2025-03-12 16:21:46 +01:00
Pieter Eendebak
1fb7e2aeb7
gh-120608: Make reversed iterator work with free-threading (#120971)
Co-authored-by: Sam Gross <colesbury@gmail.com>
Co-authored-by: Kumar Aditya <kumaraditya@python.org>
Co-authored-by: Łukasz Langa <lukasz@langa.pl>
2025-03-12 12:39:52 +01:00
Daniel Pope
e0637cebe5
gh-129349: Accept bytes in bytes.fromhex()/bytearray.fromhex() (#129844)
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Co-authored-by: Victor Stinner <vstinner@python.org>
2025-03-12 11:40:11 +01:00
Victor Stinner
48cca72a7f
gh-111178: Fix function signatures in rangeobject.c (#131101) 2025-03-12 07:29:20 +01:00
Sam Gross
c00ac57824
gh-131113: Fix data race in dict.popitem() (gh-131115)
The clearing of the key, hash, and value need to use atomic operations
to avoid a data race with concurrent read operations.
2025-03-11 19:15:22 -04:00
Victor Stinner
9d759b63d8
gh-111178: Change Argument Clinic signature for METH_O (#130682)
Use "PyObject*" for METH_O functions to fix an undefined behavior.
2025-03-11 16:33:36 +01:00
Mark Shannon
2bef8ea8ea
GH-127705: Use _PyStackRefs in the default build. (GH-127875) 2025-03-10 14:06:56 +00:00
Sam Gross
12db45211d
gh-130851: Only intern constants of types generated by the compiler (#130901)
The free-threading build interns and immortalizes most constants
generated by the bytecode compiler. However, users can construct their
own code objects with arbitrary constants. We should not intern or
immortalize these objects if they are not of a type that we know how to
handle.

This change fixes a reference leak failure in the recently added
`test_code.test_unusual_constants` test. It also addresses a potential
crash that could occur when attempting to destroy an immortalized
object during interpreter shutdown.
2025-03-07 10:34:53 -05:00
Shantanu
0a9ae5ed48
gh-130932: Fix incorrect exception handling in _PyModule_IsPossiblyShadowing (#130934)
I chose to not raise an exception here because I think it would be
confusing for module attribute access to start raising something other
than AttributeError if e.g. the cwd goes away

Without the change in moduleobject.c
```
./python.exe -m unittest test.test_import.ImportTests.test_script_shadowing_stdlib_cwd_failure
...
Assertion failed: (PyErr_Occurred()), function _PyObject_SetAttributeErrorContext, file object.c, line 1253.
```
2025-03-06 23:41:28 -08:00
mpage
d7bb7c7817
gh-118331: Fix a couple of issues when list allocation fails (#130811)
* Fix use after free in list objects

Set the items pointer in the list object to NULL after the items array
is freed during list deallocation. Otherwise, we can end up with a list
object added to the free list that contains a pointer to an already-freed
items array.

* Mark `_PyList_FromStackRefStealOnSuccess` as escaping

I think technically it's not escaping, because the only object that
can be decrefed if allocation fails is an exact list, which cannot
execute arbitrary code when it is destroyed. However, this seems less
intrusive than trying to special cases objects in the assert in `_Py_Dealloc`
that checks for non-null stackpointers and shouldn't matter for performance.
2025-03-05 10:42:09 -08:00
Sam Gross
2905690a91
gh-130851: Don't crash when deduping unusual code constants (#130853)
The bytecode compiler only generates a few different types of constants,
like str, int, tuple, slices, etc. Users can construct code objects with
various unusual constants, including ones that are not hashable or not
even constant.

The free threaded build previously crashed with a fatal error when
confronted with these constants. Instead, treat distinct objects of
otherwise unhandled types as not equal for the purposes of deduplication.
2025-03-05 15:04:49 +01:00
Mark Shannon
78d50e91ff
GH-127705: better double free message. (GH-130785)
* Add location information when accessing already closed stackref

* Add #def option to track closed stackrefs to provide precise information for use after free and double frees.
2025-03-05 14:00:42 +00:00
Sam Gross
2f6e0e9f70
gh-130794: Process interpreter QSBR queue in _PyMem_AbandonDelayed. (gh-130808)
This avoids a case where the interpreter's queue of memory to be freed
could grow rapidly if there are many short lived threads.
2025-03-04 18:04:04 -05:00
Jelle Zijlstra
dc6d66f44c
gh-105499: Merge typing.Union and types.UnionType (#105511)
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Co-authored-by: Ken Jin <kenjin@python.org>
Co-authored-by: Carl Meyer <carl@oddbird.net>
2025-03-04 11:44:19 -08:00
Tomas R.
e091520fdb
gh-126085: Add tp_iter to TypeAliasType to allow star unpacking (#127981) 2025-03-04 11:34:59 -08:00
Donghee Na
80e6d3ec49
gh-130547: Fix race between dict_dealloc and split_keys_entry_added (gh-130778) 2025-03-04 22:50:33 +09:00
Victor Stinner
0b6e98c841
gh-111178: Fix function signatures in structseq.c (#130683) 2025-03-04 10:33:45 +01:00
Victor Stinner
ed8675c571
gh-111178: Fix function signatures of unicodeiter (#130684) 2025-03-04 10:33:09 +01:00
Neil Schemenauer
813bc5694b
gh-130599: use static constants str-to-int conversion (gh-130714)
Avoid a data race in free-threaded builds due to mutating global arrays at
runtime.  Instead, compute the constants with an external Python script and
then define them as static global constant arrays.  These constants are
used by `long_from_non_binary_base()`.
2025-03-03 19:00:50 -08:00
Tomas R.
bbf197913c
gh-124445: Allow specializing generic ParamSpec aliases (#124512)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
2025-03-03 14:58:33 -08:00
Sergey Miryanov
3a7f17c7e2
gh-130790: Remove references about unicode's readiness from comments (#130801) 2025-03-03 19:18:09 +00:00
Bénédikt Tran
ddc27f9c38
gh-128974: Fix UnicodeError.__str__ when custom attributes have side-effects (#128975)
Fix some crashes when (custom) attributes of `UnicodeError` objects implement `object.__str__` with side-effects.
2025-03-01 12:01:20 +01:00
Hugo Beauzée-Luyssen
830f04b505
Postpone <stdbool.h> inclusion after Python.h (#130641)
Remove inclusions prior to Python.h.

<stdbool.h> will cause <features.h> to be included before Python.h can
define some macros to enable some additional features, causing multiple
types not to be defined down the line.
2025-02-28 10:09:27 +01:00
Tian Gao
6140b0896e
gh-127271: Remove the PyCell_Get usage for framelocalsproxy (#130383) 2025-02-27 18:12:04 -05:00
Tomasz Pytel
e85f81f430
gh-129107: fix thread safety of bytearray where two critical sections are needed (#130227) 2025-02-27 20:29:58 +05:30
Victor Stinner
daeb0efaf4
gh-111178: Fix function signatures in sliceobject.c (#130575)
Rename slicehash() to slice_hash() for consistency.
2025-02-26 21:37:22 +01:00
Victor Stinner
d5d4cbbd8f
gh-111178: Fix function signatures in namespaceobject.c (#130590) 2025-02-26 21:35:56 +01:00
Sam Gross
45bc120d45
gh-130519: Fix crash in QSBR when destructor reenters QSBR (gh-130553)
The `free_work_item()` function in QSBR may call arbitrary code via
Python object destructors, which may reenter the QSBR code. Reorder
the processing of work items to be robust to reentrancy.

Also fix the TODO for the out of memory situation.
2025-02-26 14:55:15 -05:00
Neil Schemenauer
baae9cb159
gh-117657: Use an atomic store to set type flags. (gh-127588)
The `PyType_HasFeature()` function reads the flags with a relaxed atomic
load and without holding the type lock.  To avoid data races, use atomic
stores if `PyType_Ready()` has already been called.
2025-02-25 21:24:20 -08:00
Serhiy Storchaka
0ef4ffeefd
gh-130163: Fix crashes related to PySys_GetObject() (GH-130503)
The use of PySys_GetObject() and _PySys_GetAttr(), which return a borrowed
reference, has been replaced by using one of the following functions, which
return a strong reference and distinguish a missing attribute from an error:
_PySys_GetOptionalAttr(), _PySys_GetOptionalAttrString(),
_PySys_GetRequiredAttr(), and _PySys_GetRequiredAttrString().
2025-02-25 23:04:27 +02:00
Sam Gross
f963239ff1
gh-130202: Fix bug in _PyObject_ResurrectEnd in free threaded build (gh-130281)
This fixes a fairly subtle bug involving finalizers and resurrection in
debug free threaded builds: if `_PyObject_ResurrectEnd` returns `1`
(i.e., the object was resurrected by a finalizer), it's not safe to
access the object because it might still be deallocated. For example:

 * The finalizer may have exposed the object to another thread. That
   thread may hold the last reference and concurrently deallocate it any
   time after `_PyObject_ResurrectEnd()` returns `1`.
 * `_PyObject_ResurrectEnd()` may call `_Py_brc_queue_object()`, which
   may internally deallocate the object immediately if the owning thread
   is dead.

Therefore, it's important not to access the object after it's
resurrected. We only violate this in two cases, and only in debug
builds:

 * We assert that the object is tracked appropriately. This is now moved
   up betewen the finalizer and the `_PyObject_ResurrectEnd()` call.

 * The `--with-trace-refs` builds may need to remember the object if
   it's resurrected. This is now handled by `_PyObject_ResurrectStart()`
   and `_PyObject_ResurrectEnd()`.

Note that `--with-trace-refs` is currently disabled in `--disable-gil`
builds because the refchain hash table isn't thread-safe, but this
refactoring avoids an additional thread-safety issue.
2025-02-25 12:03:28 -05:00
Sergey B Kirpichev
f39a07be47
gh-87790: support thousands separators for formatting fractional part of floats (#125304)
```pycon
>>> f"{123_456.123_456:_._f}"  # Whole and fractional
'123_456.123_456'
>>> f"{123_456.123_456:_f}"    # Integer component only
'123_456.123456'
>>> f"{123_456.123_456:._f}"   # Fractional component only
'123456.123_456'
>>> f"{123_456.123_456:.4_f}"  # with precision
'123456.1_235'
```
2025-02-25 16:27:07 +01:00
Bénédikt Tran
ecde940025
gh-111178: fix UBSan failures in Objects/typevarobject.c (GH-129800)
Fix UBSan failures for `typealiasobject`, `paramspecobject`, `typevarobject`, `typevartupleobject`, `paramspecattrobject`

Use _PyCFunction_CAST macros

Use macro for `constevaluatorobject` casts
2025-02-25 13:12:47 +01:00
Bénédikt Tran
3d40317ed2
gh-111178: fix UBSan failures in Objects/typeobject.c (#129799)
Fix UBSan failures for `PyTypeObject`.
Introduce a macro cast for `superobject` and remove redundant casts.
Rename the unused parameter in getter/setter methods  to `closure`
for semantic purposes.
2025-02-25 10:44:59 +00:00
Mark Shannon
014223649c
GH-130396: Use computed stack limits on linux (GH-130398)
* Implement C recursion protection with limit pointers for Linux, MacOS and Windows

* Remove calls to PyOS_CheckStack

* Add stack protection to parser

* Make tests more robust to low stacks

* Improve error messages for stack overflow
2025-02-25 09:24:48 +00:00
Petr Viktorin
ef29104f7d
GH-91079: Revert "GH-91079: Implement C stack limits using addresses, not counters. (GH-130007)" for now (GH130413)
Revert "GH-91079: Implement C stack limits using addresses, not counters. (GH-130007)" for now

Unfortunatlely, the change broke some buildbots.

This reverts commit 2498c22fa0.
2025-02-24 11:16:08 +01:00
Dino Viehland
6c450f44c2
gh-130313: Avoid locking when clearing objects (#130126)
Avoid locking when clearing objects in the free-threaded build
2025-02-20 13:32:57 -08:00
Sam Gross
ca22147547
gh-111924: Fix data races when swapping allocators (gh-130287)
CPython current temporarily changes `PYMEM_DOMAIN_RAW` to the default
allocator during initialization and shutdown. The motivation is to
ensure that core runtime structures are allocated and freed using the
same allocator. However, modifying the current allocator changes global
state and is not thread-safe even with the GIL. Other threads may be
allocating or freeing objects use PYMEM_DOMAIN_RAW; they are not
required to hold the GIL to call PyMem_RawMalloc/PyMem_RawFree.

This adds new internal-only functions like `_PyMem_DefaultRawMalloc`
that aren't affected by calls to `PyMem_SetAllocator()`, so they're
appropriate for Python runtime initialization and finalization. Use
these calls in places where we previously swapped to the default raw
allocator.
2025-02-20 11:31:15 -05:00
Tian Gao
ccf17323c2
gh-128396: Fix a crash when inline comprehension has the same local variable as the outside scope (#130235) 2025-02-19 12:11:17 -05:00
Mark Shannon
2498c22fa0
GH-91079: Implement C stack limits using addresses, not counters. (GH-130007)
* Implement C recursion protection with limit pointers

* Remove calls to PyOS_CheckStack

* Add stack protection to parser

* Make tests more robust to low stacks

* Improve error messages for stack overflow
2025-02-19 11:44:57 +00:00
Tomasz Pytel
1b6bef8086
gh-129107: make bytearray iterator thread safe (#130096)
Co-authored-by: Kumar Aditya <kumaraditya@python.org>
2025-02-19 15:42:45 +05:30
T. Wouters
388e1ca9f0
gh-115999: Make list and tuple iteration more thread-safe. (#128637)
Make tuple iteration more thread-safe, and actually test concurrent iteration of tuple, range and list. (This is prep work for enabling specialization of FOR_ITER in free-threaded builds.) The basic premise is:

Iterating over a shared iterable (list, tuple or range) should be safe, not involve data races, and behave like iteration normally does.

Using a shared iterator should not crash or involve data races, and should only produce items regular iteration would produce. It is not guaranteed to produce all items, or produce each item only once. (This is not the case for range iteration even after this PR.)

Providing stronger guarantees is possible for some of these iterators, but it's not always straight-forward and can significantly hamper the common case. Since iterators in general aren't shared between threads, and it's simply impossible to concurrently use many iterators (like generators), better to make sharing iterators without explicit synchronization clearly wrong.

Specific issues fixed in order to make the tests pass:

 - List iteration could occasionally fail an assertion when a shared list was shrunk and an item past the new end was retrieved concurrently. There's still some unsafety when deleting/inserting multiple items through for example slice assignment, which uses memmove/memcpy.

 - Tuple iteration could occasionally crash when the iterator's reference to the tuple was cleared on exhaustion. Like with list iteration, in free-threaded builds we can't safely and efficiently clear the iterator's reference to the iterable (doing it safely would mean extra, slow refcount operations), so just keep the iterable reference around.
2025-02-18 16:52:46 -08:00
Sam Gross
b9d2ee687c
gh-129701: Fix a data race in intern_common in the free threaded build (GH-130089)
* gh-129701: Fix a data race in `intern_common` in the free threaded build

* Use a mutex to avoid potentially returning a non-immortalized string,
  because immortalization happens after the insertion into the interned
  dict.

* Use `Py_DECREF()` calls instead of `Py_SET_REFCNT(s, Py_REFCNT(s) - 2)`
  for thread-safety. This code path isn't performance sensistive, so
  just use `Py_DECREF()` unconditionally for simplicity.
2025-02-17 14:15:40 +01:00