Commit Graph

5455 Commits

Author SHA1 Message Date
Irit Katriel 6e9863d7a3
gh-118692: Avoid creating unnecessary StopIteration instances for monitoring (#119216) 2024-05-21 20:42:51 +00:00
Victor Stinner f6da790122
gh-111389: Add PyHASH_MULTIPLIER constant (#119214) 2024-05-21 19:51:51 +02:00
Mark Shannon f5c6b9977a
GH-118910: Less boilerplate in the tier 2 optimizer (#118913) 2024-05-10 17:43:23 +01:00
Petr Viktorin 941eea0a27
gh-118771: Ensure names defined in optimizer.h start with Py/_Py (GH-118825) 2024-05-10 18:20:12 +02:00
Jelle Zijlstra 13d7cf997b
gh-118895: Call PyType_Ready() on typing.NoDefault (#118897) 2024-05-10 08:42:00 -07:00
Alex Turner 33d20199af
gh-117657: Fix QSBR race condition (#118843)
`_Py_qsbr_unregister` is called when the PyThreadState is already
detached, so the access to `tstate->qsbr` isn't safe without locking the
shared mutex. Grab the `struct _qsbr_shared` from the interpreter
instead.
2024-05-10 10:26:35 -04:00
Sam Gross db5af7da09
gh-118789: Restore hidden `_PyWeakref_ClearRef` (#118797)
_PyWeakref_ClearRef was previously exposed in the public C-API, although
it begins with an underscore and is not documented. It's used by a few
C-API extensions. There is currently no alternative public API that can
replace its use.

_PyWeakref_ClearWeakRefsExceptCallbacks is the only thread-safe way to
use _PyWeakref_ClearRef in the free-threaded build. This exposes the C
symbol, but does not make the API public.
2024-05-10 15:54:18 +02:00
Sam Gross 46c808172f
Revert "gh-115432: Add critical section variant that handles a NULL object (#115433)" (#118861)
This reverts commit ad4f909e0e.

The API ended up not being used.
2024-05-09 18:33:53 -04:00
Sam Gross 71cc0651e7
gh-116984: Make mimalloc header includes relative to the current file (#118808)
Some embedders and extensions include parts of the internal API. The
pycore_mimalloc.h file is transitively include by a number of other
internal headers. This avoids include errors for code that was
already including those headers.
2024-05-09 16:03:45 -04:00
mpage cb6f75a32c
gh-117657: Fix data races when writing / reading `ob_gc_bits` (#118292)
Use relaxed atomics when reading / writing to the field. There are still a
few places in the GC where we do not use atomics. Those should be safe as
the world is stopped.
2024-05-08 16:03:39 -04:00
Thomas Wouters 7768ff1e41 Python 3.14.0a0 2024-05-08 16:57:05 +02:00
Thomas Wouters 2268289a47 Python 3.13.0b1 2024-05-08 11:21:00 +02:00
Brett Simmers 853163d3b5
gh-116322: Enable the GIL while loading C extension modules (#118560)
Add the ability to enable/disable the GIL at runtime, and use that in
the C module loading code.

We can't know before running a module init function if it supports
free-threading, so the GIL is temporarily enabled before doing so. If
the module declares support for running without the GIL, the GIL is
later disabled. Otherwise, the GIL is permanently enabled, and will
never be disabled again for the life of the current interpreter.
2024-05-06 23:07:23 -04:00
Dino Viehland ff6cbb2503
gh-112075: use per-thread dict version pool (#118676)
use thread state set of dict versions
2024-05-07 00:22:26 +00:00
Sam Gross 723d4d2fe8
gh-118527: Intern code consts in free-threaded build (#118667)
We already intern and immortalize most string constants. In the
free-threaded build, other constants can be a source of reference count
contention because they are shared by all threads running the same code
objects.
2024-05-06 20:12:39 -04:00
Dino Viehland 636b8d94c9
gh-112075: Fix race in constructing dict for instance (#118499) 2024-05-06 23:31:09 +00:00
Mark Shannon 616b745b89
GH-115709: Invalidate executors when a local variable is changed via frame.f_locals (#118639)
Also fix unrelated assert in debug Tier2/JIT builds.
2024-05-06 21:21:06 +00:00
Dino Viehland 5a1618a2c8
gh-118362: Fix thread safety around lookups from the type cache in the face of concurrent mutators (#118454)
Add _PyType_LookupRef and use incref before setting attribute on type
Makes setting an attribute on a class and signaling type modified atomic
Avoid adding re-entrancy exposing the type cache in an inconsistent state by decrefing after type is updated
2024-05-06 10:50:35 -07:00
Petr Viktorin 417dd3aca7
gh-116322: Rename PyModule_ExperimentalSetGIL to PyUnstable_Module_SetGIL (GH-118645) 2024-05-06 18:59:36 +02:00
Serhiy Storchaka 153b3f7530
gh-118465: Add __firstlineno__ attribute to class (GH-118475)
It is set by compiler with the line number of the first line of
the class definition.
2024-05-06 12:02:37 +03:00
Guido van Rossum 40cc809902
gh-117549: Don't use designated initializers in headers (#118580)
The designated initializer syntax in static inline functions in pycore_backoff.h
causes problems for C++ or MSVC users who aren't yet using C++20.
While internal, pycore_backoff.h is included (indirectly, via pycore_code.h)
by some key 3rd party software that does so for speed.
2024-05-05 19:28:55 +00:00
Victor Stinner aa61f8bfcf
gh-110850: Remove _PyTime_TimeUnchecked() function (#118552)
Use the new public Raw functions:

* _PyTime_PerfCounterUnchecked() with PyTime_PerfCounterRaw()
* _PyTime_TimeUnchecked() with PyTime_TimeRaw()
* _PyTime_MonotonicUnchecked() with PyTime_MonotonicRaw()

Remove internal functions:

* _PyTime_PerfCounterUnchecked()
* _PyTime_TimeUnchecked()
* _PyTime_MonotonicUnchecked()
2024-05-05 12:15:19 +02:00
Pablo Galindo Salgado 1b22d801b8
gh-118518: Allow perf to work without frame pointers (#112254) 2024-05-05 03:07:29 +02:00
Davide Rizzo 08d169f14a
gh-109617: fix ncurses incompatibility on macOS with Xcode 15 (#111258)
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
Co-authored-by: Łukasz Langa <lukasz@langa.pl>
2024-05-04 23:41:47 +02:00
Eric Snow 291cfa454b
gh-117953: Track Extra Details in Global Extensions Cache (gh-118532)
We have only been tracking each module's PyModuleDef.  However, there are some problems with that.  For example, in some cases we load single-phase init extension modules from def->m_base.m_init or def->m_base.m_copy, but if multiple modules share a def then we can end up with unexpected behavior.

With this change, we track the following:

* PyModuleDef (same as before)
* for some modules, its init function or a copy of its __dict__, but specific to that module
* whether it is a builtin/core module or a "dynamic" extension
* the interpreter (ID) that owns the cached __dict__ (only if cached)

This also makes it easier to remember the module's kind (e.g. single-phase init) and if loading it previously failed, which I'm doing separately.
2024-05-04 21:24:02 +00:00
Ken Jin 978fba58ae
gh-117139: Fix missing semicolon (GH-118573) 2024-05-04 15:45:49 +00:00
Tian Gao b034f14a4b
gh-74929: Implement PEP 667 (GH-115153) 2024-05-04 12:12:10 +01:00
Mark Shannon 1ab6356ebe
GH-118095: Use broader specializations of CALL in tier 1, for better tier 2 support of calls. (GH-118322)
* Add CALL_PY_GENERAL, CALL_BOUND_METHOD_GENERAL and call CALL_NON_PY_GENERAL specializations.

* Remove CALL_PY_WITH_DEFAULTS specialization

* Use CALL_NON_PY_GENERAL in more cases when otherwise failing to specialize
2024-05-04 12:11:11 +01:00
Irit Katriel 85af789961
gh-111997: C-API for signalling monitoring events (#116413) 2024-05-04 08:23:50 +00:00
Mark Shannon da2cfc4cb6
GH-113464: Remove the extra jump via `_SIDE_EXIT` in `_EXIT_TRACE` (GH-118545) 2024-05-04 08:50:24 +01:00
mpage 37d0950022
gh-117657: Disable the function/code cache in free-threaded builds (#118301)
This is only used by the specializing interpreter and the tier 2
optimizer, both of which are disabled in free-threaded builds.
2024-05-03 16:21:04 -04:00
Brett Simmers c2627d6eea
gh-116322: Add Py_mod_gil module slot (#116882)
This PR adds the ability to enable the GIL if it was disabled at
interpreter startup, and modifies the multi-phase module initialization
path to enable the GIL when loading a module, unless that module's spec
includes a slot indicating it can run safely without the GIL.

PEP 703 called the constant for the slot `Py_mod_gil_not_used`; I went
with `Py_MOD_GIL_NOT_USED` for consistency with gh-104148.

A warning will be issued up to once per interpreter for the first
GIL-using module that is loaded. If `-v` is given, a shorter message
will be printed to stderr every time a GIL-using module is loaded
(including the first one that issues a warning).
2024-05-03 11:30:55 -04:00
Jelle Zijlstra ca269e58c2
gh-116126: Implement PEP 696 (#116129)
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
2024-05-03 06:17:32 -07:00
Brett Simmers f8290df63f
gh-116738: Make `_codecs` module thread-safe (#117530)
The module itself is a thin wrapper around calls to functions in
`Python/codecs.c`, so that's where the meaningful changes happened:

- Move codecs-related state that lives on `PyInterpreterState` to a
  struct declared in `pycore_codecs.h`.

- In free-threaded builds, add a mutex to `codecs_state` to synchronize
  operations on `search_path`. Because `search_path_mutex` is used as a
  normal mutex and not a critical section, we must be extremely careful
  with operations called while holding it.

- The codec registry is explicitly initialized as part of
  `_PyUnicode_InitEncodings` to simplify thread-safety.
2024-05-02 18:25:36 -04:00
Dino Viehland 1e67b9207c
gh-117657: Fix TSAN list set failure (#118260)
* Fix TSAN list set failure

* Relaxed atomic is sufficient, add targetted test

* More list

* Remove atomic assign in list

* Fixup white space
2024-05-02 13:03:05 -07:00
Pablo Galindo Salgado 6bcbee09df
gh-93502: Add new C-API functions to trace object creation and destruction (#115945) 2024-05-02 19:30:00 +02:00
Mark Shannon 67bba9dd0f
GH-117442: Check eval-breaker at start (rather than end) of tier 2 loops (GH-118482) 2024-05-02 13:10:31 +01:00
Eric Snow 526ca4c09e
gh-117953: Work Relative to Specific Extension Kinds in the Import Machinery (gh-118205)
This change will make some later changes simpler.
2024-05-01 17:40:28 -06:00
Mark Shannon 39981fd07a
GH-118095: Make sure that progress is made if there are pending calls being handled. (GH-118484) 2024-05-01 22:18:31 +01:00
Victor Stinner b52c753e0f
gh-110850: Add PyTime_TimeRaw() function (#118394)
Add "Raw" variant of PyTime functions:

* PyTime_MonotonicRaw()
* PyTime_PerfCounterRaw()
* PyTime_TimeRaw()

Changes:

* Add documentation and tests. Tests release the GIL while calling
  raw clock functions.
* py_get_system_clock() and py_get_monotonic_clock() now check that
  the GIL is hold by the caller if raise_exc is non-zero.
* Reimplement "Unchecked" functions with raw clock functions.

Co-authored-by: Petr Viktorin <encukou@gmail.com>
2024-05-01 18:05:01 +00:00
Brandt Bucher 49baa656cb
GH-115802: Use the GHC calling convention in JIT code (GH-118287) 2024-05-01 08:05:53 -07:00
Irit Katriel c1bf4874c1
gh-116767: fix crash on 'async with' with many context managers (GH-118348)
Account for `add_stopiteration_handler` pushing a block for `async with`.
To allow generator functions that previously almost hit the `CO_MAXBLOCKS`
limit by nesting non-async blocks, the limit is increased by 1.
This increase allows one more block in non-generator functions.
2024-05-01 13:01:16 +02:00
Mark Shannon f6fab21721
GH-118095: Make invalidating and clearing executors memory safe (GH-118459) 2024-05-01 11:34:50 +01:00
Guido van Rossum 7d83f7bcc4
gh-118335: Configure Tier 2 interpreter at build time (#118339)
The code for Tier 2 is now only compiled when configured
with `--enable-experimental-jit[=yes|interpreter]`.

We drop support for `PYTHON_UOPS` and -`Xuops`,
but you can disable the interpreter or JIT
at runtime by setting `PYTHON_JIT=0`.
You can also build it without enabling it by default
using `--enable-experimental-jit=yes-off`;
enable with `PYTHON_JIT=1`.

On Windows, the `build.bat` script supports
`--experimental-jit`, `--experimental-jit-off`,
`--experimental-interpreter`.

In the C code, `_Py_JIT` is defined as before
when the JIT is enabled; the new variable
`_Py_TIER2` is defined when the JIT *or* the
interpreter is enabled. It is actually a bitmask:
1: JIT; 2: default-off; 4: interpreter.
2024-04-30 18:26:34 -07:00
Ken Jin dc6b12d1b2
gh-117139: Add header for tagged pointers (GH-118330)
---------

Co-authored-by: Sam Gross <655866+colesbury@users.noreply.github.com>
2024-05-01 04:46:13 +08:00
Victor Stinner e93c39b47e
gh-118422: Fix run_fileexflags() test (#118429)
Don't test the undefined behavior of fileno()
on a closed file, but use fstat() as a reliable
test if the file was closed or not.
2024-04-30 22:32:55 +02:00
Victor Stinner 587388ff22
gh-118124: Use static_assert() in Py_BUILD_ASSERT() on C11 (#118398)
Use static_assert() in Py_BUILD_ASSERT() and Py_BUILD_ASSERT_EXPR()
on C11 and newer and C++11 and newer.

Add tests to test_cext and test_cppext.
2024-04-30 22:29:48 +02:00
Dino Viehland 19d468a3ab
[gh-117657] Fix some issues with TSAN in typeobject (#118249)
Fix some racing reads in typebobject.c
2024-04-30 12:37:38 -07:00
Sam Gross b2c3b70c71
gh-118332: Fix deadlock involving stop the world (#118412)
Avoid detaching thread state when stopping the world. When re-attaching
the thread state, the thread would attempt to resume the top-most
critical section, which might now be held by a thread paused for our
stop-the-world request.
2024-04-30 15:01:28 -04:00
Dino Viehland 4a1cf66c5c
gh-117657: Fix small issues with instrumentation and TSAN (#118064)
Small TSAN fixups for instrumentation
2024-04-30 11:38:05 -07:00
Irit Katriel 1f16b4ce56
gh-118272: Clear generator frame's locals when the generator is closed (#118277)
Co-authored-by: Thomas Grainger <tagrain@gmail.com>
2024-04-30 19:32:25 +01:00
Mark Shannon 5b05d452cd
GH-118095: Add tier 2 support for YIELD_VALUE (GH-118380) 2024-04-30 11:33:13 +01:00
Sam Gross 79688b5b0e
gh-118331: Handle errors in _PyObject_SetManagedDict (#118334)
When detaching a dict, the `copy_values` call may fail due to
out-of-memory errors. This can be triggered by test_no_memory in
test_repl.
2024-04-29 15:49:01 -04:00
Eric Snow 529a160be6
gh-117953: Share More Machinery Code Between Builtin and Dynamic Extensions (gh-118204)
This change will make some later changes simpler. It also brings more consistent behavior and lower maintenance costs.
2024-04-29 12:53:04 -06:00
Sam Gross 7ccacb220d
gh-117783: Immortalize objects that use deferred reference counting (#118112)
Deferred reference counting is not fully implemented yet. As a temporary
measure, we immortalize objects that would use deferred reference
counting to avoid multi-threaded scaling bottlenecks.

This is only performed in the free-threaded build once the first
non-main thread is started. Additionally, some tests, including refleak
tests, suppress this behavior.
2024-04-29 14:36:02 -04:00
Eric Snow 44f57a952e
gh-117953: Split Up _PyImport_LoadDynamicModuleWithSpec() (gh-118203)
Basically, I've turned most of _PyImport_LoadDynamicModuleWithSpec() into two new functions (_PyImport_GetModInitFunc() and _PyImport_RunModInitFunc()) and moved the rest of it out into _imp_create_dynamic_impl().  There shouldn't be any changes in behavior.

This change makes some future changes simpler.  This is particularly relevant to potentially calling each module init function in the main interpreter first.  Thus the critical part of the PR is the addition of _PyImport_RunModInitFunc(), which is strictly focused on running the init func and validating the result.  A later PR will take it a step farther by capturing error information rather than raising exceptions.

FWIW, this change also helps readers by clarifying a bit more about what happens when an extension/builtin module is imported.
2024-04-29 09:29:07 -06:00
Mark Shannon ab6eda0ee5
GH-118095: Allow a variant of RESUME_CHECK in tier 2 (GH-118286) 2024-04-29 07:54:05 +01:00
Eric Snow 1d33925176
gh-110693: Use a Larger Queue for Per-Interpreter Pending Calls (gh-118302)
This is an improvement over the status quo, reducing the likelihood of completely filling the pending calls queue.  However, the problem won't go away completely unless we move to an unbounded linked list or add a mechanism for waiting until the queue isn't full.
2024-04-26 19:13:44 -06:00
Mark Shannon 3e06c7f719
GH-118095: Add dynamic exit support and FOR_ITER_GEN support to tier 2 (GH-118279) 2024-04-26 18:08:50 +01:00
mpage a5eeb832c2
gh-117657: Fix race data race in `_Py_IsOwnedByCurrentThread()` (#118258) 2024-04-26 10:39:08 -04:00
Eric Snow 09c2947581
gh-110693: Pending Calls Machinery Cleanups (gh-118296)
This does some cleanup in preparation for later changes.
2024-04-26 01:05:51 +00:00
Dino Viehland 5da0280648
gh-117657: Fixes a few small TSAN issues in dictobject (#118200)
Fixup TSAN errors for dict
2024-04-25 08:53:29 -07:00
mpage f14e9f9154
gh-117657: Fix data race in `_Py_IsImmortal` (#118261)
The load of `ob_ref_local races with stores. Using a relaxed load is
sufficient; stores to the field are relaxed.
2024-04-25 11:31:57 -04:00
neonene 2c45148912
gh-117578: Introduce _PyType_GetModuleByDef2 private function (GH-117661)
Co-authored-by: Erlend E. Aasland <erlend.aasland@protonmail.com>
Co-authored-by: Petr Viktorin <encukou@gmail.com>
2024-04-25 13:51:31 +02:00
Mark Shannon f180b31e76
GH-118095: Handle `RETURN_GENERATOR` in tier 2 (GH-118180) 2024-04-25 11:32:47 +01:00
Nice Zombies 10bb90ed49
gh-102511: Speed up os.path.splitroot() with native helpers (GH-118089) 2024-04-25 10:07:38 +01:00
Itamar Oren 796b3fb280
gh-118207: Rename the COMMON_FIELDS macro in funcobject.h and undef it after use (GH-118208) 2024-04-25 08:49:15 +02:00
Eric Snow 5865fa5f9b
gh-117953: Add Internal struct _Py_ext_module_loader_info (gh-118194)
This helps with a later change that splits up _PyImport_LoadDynamicModuleWithSpec().
2024-04-24 17:42:01 +00:00
Eric Snow 03e3e31723
gh-76785: Rename _xxsubinterpreters to _interpreters (gh-117791)
See https://discuss.python.org/t/pep-734-multiple-interpreters-in-the-stdlib/41147/26.
2024-04-24 16:18:24 +00:00
Eric Snow af3c1d817d
gh-117953: Cleanups For fix_up_extension() in import.c (gh-118192)
These are cleanups I've pulled out of gh-118116.  Mostly, this change moves code around to align with some future changes and to improve clarity a little.  There is one very small change in behavior: we now add the module to the per-interpreter caches after updating the global state, rather than before.
2024-04-24 09:55:48 -06:00
Mark Shannon 77cd0428b6
GH-118095: Convert DEOPT_IFs on likely side exits to EXIT_IFs (GH-118106)
Covert DEOPT_IFs on likely side exits to EXIT_IFs
2024-04-24 14:37:55 +01:00
Irit Katriel 0aa0fc3d3c
gh-117901: Add option for compiler's codegen to save nested instruction sequences for introspection (#118007) 2024-04-24 09:46:17 +00:00
Oleg Iarygin 258408239a
gh-118189: Revert accidentally added incl.tar (#118190) 2024-04-23 17:38:33 +00:00
Eric Snow 23950beff8
gh-117953: Small Cleanup of Extensions-Related Machinery Code (gh-118167)
This is a collection of very basic cleanups I've pulled out of gh-118116.  It is mostly renaming variables and moving a couple bits of code in functionally equivalent ways.
2024-04-23 08:25:50 -06:00
Shantanu 8e86579cae
gh-95754: Better error when script shadows a standard library or third party module (#113769) 2024-04-22 18:24:21 -07:00
Guido van Rossum 4c7bfdff90
Remove more remnants of deepfreeze (#118159) 2024-04-22 12:17:57 -07:00
Mark Shannon a6647d16ab
GH-115480: Reduce guard strength for binary ops when type of one operand is known already (GH-118050) 2024-04-22 13:34:06 +01:00
Dino Viehland 8b541c017e
gh-112075: Make instance attributes stored in inline "dict" thread safe (#114742)
Make instance attributes stored in inline "dict" thread safe on free-threaded builds
2024-04-21 22:57:05 -07:00
Dino Viehland 07525c9a85
gh-116818: Make `sys.settrace`, `sys.setprofile`, and monitoring thread-safe (#116775)
Makes sys.settrace, sys.setprofile, and monitoring generally thread-safe.

Mostly uses a stop-the-world approach and synchronization around the code object's _co_instrumentation_version.  There may be a little bit of extra synchronization around the monitoring data that's required to be TSAN clean.
2024-04-19 14:47:42 -07:00
Mark Shannon 7e6fa5fced
GH-116202: Incorporate invalidation check into _START_EXECUTOR. (GH-118044) 2024-04-19 09:26:42 +01:00
Mark Shannon d3bd6b5f3f
GH-115419: Improve list of escaping functions (GH-118054) 2024-04-19 09:25:07 +01:00
Donghee Na 710c01be94
gh-112069: Make PySet_GET_SIZE to be atomic safe. (gh-118053)
gh-112069: Make PySet_GET_SIZE to be atomic operation
2024-04-19 06:40:28 +09:00
Donghee Na 94444ea45a
gh-112069: Add _PySet_NextEntryRef to be thread-safe. (gh-117990) 2024-04-19 00:18:22 +09:00
Victor Stinner 340a02b590
gh-117987: Restore several functions removed in Python 3.13 alpha 1 (GH-117993)
Restore these functions removed in Python 3.13 alpha 1:

* Py_SetPythonHome()
* Py_SetProgramName()
* PySys_SetArgvEx()
* PySys_SetArgv()
2024-04-18 15:20:38 +02:00
Irit Katriel c179c0e6cb
gh-117680: make _PyInstructionSequence a PyObject and use it in tests (#117629) 2024-04-17 16:42:04 +01:00
Victor Stinner 75eed5b373
gh-117929: Restore removed PyEval_InitThreads() function (#117931) 2024-04-17 15:01:28 +02:00
Mark Shannon 147cd0581e
GH-117760: Streamline the trashcan mechanism (GH-117763) 2024-04-17 11:08:05 +01:00
Victor Stinner 919784737c
gh-117645: Increase WASI stack size from 512 KiB to 8 MiB (#117674)
Increase also the initial memory from 10 MiB to 20 MiB.

Reenable test_dynamic on WASI build.
2024-04-16 23:26:54 +02:00
Jeff Glass acf69e09c6
gh-115178: Add Counts of UOp Pairs to pystats (GH-115181) 2024-04-16 14:27:18 +01:00
Mark Shannon c053d52edd
GH-115776: Static object are immortal, so mark them as such. (GH-117673) 2024-04-16 12:51:41 +01:00
Victor Stinner 2cc916e147
gh-117613: Enhance test_clinic @defining_class tests (#117896) 2024-04-16 09:32:51 +02:00
Eric Snow eca53620e3
gh-94673: Clarify About Runtime State Related to Static Builtin Types (gh-117761)
Guido pointed out to me that some details about the per-interpreter state for the builtin types aren't especially clear.  I'm addressing that by:

* adding a comment explaining that state
* adding some asserts to point out the relationship between each index and the interp/global runtime state
2024-04-12 16:39:27 -06:00
Sam Gross 4ad8f090cc
gh-117376: Partial implementation of deferred reference counting (#117696)
This marks objects as using deferred refrence counting using the
`ob_gc_bits` field in the free-threaded build and collects those objects
during GC.
2024-04-12 17:36:20 +00:00
Serhiy Storchaka 39a6b29756
gh-117764: Use Argument Clinic for signal.set_wakeup_fd() (GH-117777) 2024-04-12 11:21:00 +00:00
Erlend E. Aasland deb921f851
gh-117431: Adapt bytes and bytearray .find() and friends to Argument Clinic (#117502)
This change gives a significant speedup, as the METH_FASTCALL calling
convention is now used. The following bytes and bytearray methods are adapted:

- count()
- find()
- index()
- rfind()
- rindex()

Co-authored-by: Inada Naoki <songofacandy@gmail.com>
2024-04-12 07:40:55 +00:00
Eric Snow fd259fdabe
gh-76785: Handle Legacy Interpreters Properly (gh-117490)
This is similar to the situation with threading._DummyThread.  The methods (incl. __del__()) of interpreters.Interpreter objects must be careful with interpreters not created by interpreters.create().  The simplest thing to start with is to disable any method that modifies or runs in the interpreter.  As part of this, the runtime keeps track of where an interpreter was created.  We also handle interpreter "refcounts" properly.
2024-04-11 23:23:25 +00:00
Brett Simmers f268e328ed
gh-116738: Make _abc module thread-safe (#117488)
A collection of small changes aimed at making the `_abc` module safe to
use in a free-threaded build.
2024-04-11 18:13:25 -04:00
Sam Gross 25f6ff5d3e
gh-117649: Raise ImportError for unsupported modules in free-threaded build (#117651)
The free-threaded build does not currently support the combination of
single-phase init modules and non-isolated subinterpreters. Ensure that
`check_multi_interp_extensions` is always `True` for subinterpreters in
the free-threaded build so that importing these modules raises an
`ImportError`.
2024-04-11 15:00:54 -04:00
Sam Gross 39d381f91e
gh-111506: Error if the limited API is used in free-threaded build (#117762)
Issue a build time error if both `Py_LIMITED_API` and `Py_GIL_DISABLED`
are defined.
2024-04-11 13:49:52 -04:00
Eric Snow 993c3cca16
gh-76785: Add More Tests to test_interpreters.test_api (gh-117662)
In addition to the increase test coverage, this is a precursor to sorting out how we handle interpreters created directly via the C-API.
2024-04-10 18:37:01 -06:00
Sam Gross 79eec66e3d
gh-112536: Define `_Py_THREAD_SANITIZER` on GCC when TSan is enabled (#117702)
The `__has_feature(thread_sanitizer)` is a Clang-ism. Although new
versions of GCC implement `__has_feature`, the `defined(__has_feature)`
check still fails on GCC so we don't use that code path.
2024-04-10 10:20:05 -04:00
Thomas Wouters 54084e2fe4 Post 3.13.0a6 2024-04-09 20:40:50 +02:00
Thomas Wouters 57aee2a02c Python 3.13.0a6 2024-04-09 11:56:22 +02:00
Sam Gross 1a6594f661
gh-117439: Make refleak checking thread-safe without the GIL (#117469)
This keeps track of the per-thread total reference count operations in
PyThreadState in the free-threaded builds. The count is merged into the
interpreter's total when the thread exits.
2024-04-08 12:11:36 -04:00
mpage df73179048
gh-111926: Make weakrefs thread-safe in free-threaded builds (#117168)
Most mutable data is protected by a striped lock that is keyed on the
referenced object's address. The weakref's hash is protected using the
weakref's per-object lock.
 
Note that this only affects free-threaded builds. Apart from some minor
refactoring, the added code is all either gated by `ifdef`s or is a no-op
(e.g. `Py_BEGIN_CRITICAL_SECTION`).
2024-04-08 10:58:38 -04:00
Ken Jin 375425abd1
Cases generator: Remove type_prop and passthrough (#117614) 2024-04-08 06:26:52 +08:00
Steve Dower 687616877b
gh-111140: PyLong_From/AsNativeBytes: Take *flags* rather than just *endianness* (GH-116053) 2024-04-05 16:21:16 +02:00
Michael Droettboom b5e60918af
gh-117549: Match declaration order for _Py_BackoffCounter initializer (#117551)
Otherwise it might not compile with C++ (or certain C compilers/flags?).
2024-04-04 14:14:35 -07:00
Dino Viehland 434bc593df
gh-112075: Make _PyDict_LoadGlobal thread safe (#117529)
Make _PyDict_LoadGlobal threadsafe
2024-04-04 12:26:07 -07:00
Irit Katriel 04697bcfaf
gh-117494: extract the Instruction Sequence data structure into a separate file (#117496) 2024-04-04 15:47:26 +00:00
Guido van Rossum 060a96f1a9
gh-116968: Reimplement Tier 2 counters (#117144)
Introduce a unified 16-bit backoff counter type (``_Py_BackoffCounter``),
shared between the Tier 1 adaptive specializer and the Tier 2 optimizer. The
API used for adaptive specialization counters is changed but the behavior is
(supposed to be) identical.

The behavior of the Tier 2 counters is changed:
- There are no longer dynamic thresholds (we never varied these).
- All counters now use the same exponential backoff.
- The counter for ``JUMP_BACKWARD`` starts counting down from 16.
- The ``temperature`` in side exits starts counting down from 64.
2024-04-04 15:03:27 +00:00
Victor Stinner 2057c92125
gh-114329: Fix PyList_GetItemRef() limited C API definition (#117520) 2024-04-03 21:02:42 +00:00
Peter Lazorchak 1c43468886
gh-116168: Remove extra `_CHECK_STACK_SPACE` uops (#117242)
This merges all `_CHECK_STACK_SPACE` uops in a trace into a single `_CHECK_STACK_SPACE_OPERAND` uop that checks whether there is enough stack space for all calls included in the entire trace.
2024-04-03 17:14:18 +00:00
Erlend E. Aasland 595bb496b0
gh-117431: Adapt bytes and bytearray .startswith() and .endswith() to Argument Clinic (#117495)
This change gives a significant speedup, as the METH_FASTCALL calling
convention is now used.
2024-04-03 13:11:14 +02:00
Eric Snow f341d6017d
gh-76785: Add PyInterpreterConfig Helpers (gh-117170)
These helpers make it easier to customize and inspect the config used to initialize interpreters.  This is especially valuable in our tests.  I found inspiration from the PyConfig API for the PyInterpreterConfig dict conversion stuff.  As part of this PR I've also added a bunch of tests.
2024-04-02 20:35:52 +00:00
Mark Shannon c32dc47aca
GH-115776: Embed the values array into the object, for "normal" Python objects. (GH-116115) 2024-04-02 11:59:21 +01:00
Irit Katriel 1d5479b236
gh-117411: move PyFutureFeatures to pycore_symtable.h and make it private (#117412) 2024-04-02 10:34:49 +00:00
Sam Gross 19c1dd60c5
gh-117323: Make `cell` thread-safe in free-threaded builds (#117330)
Use critical sections to lock around accesses to cell contents. The critical sections are no-ops in the default (with GIL) build.
2024-03-29 13:35:43 -04:00
Erlend E. Aasland c1712ef066
gh-116664: Make module state Py_SETREF's in _warnings thread-safe (#116959)
Mark the swap operations as critical sections.

Add an internal Py_BEGIN_CRITICAL_SECTION_MUT API that takes a PyMutex
pointer instead of a PyObject pointer.
2024-03-28 15:05:08 +00:00
Irit Katriel 262fb911ab
gh-117288: Allocate fewer label IDs in _PyCfg_ToInstructionSequence (#117290) 2024-03-27 17:38:19 +00:00
Irit Katriel 79be75735c
gh-115775: Compiler adds __static_attributes__ field to classes (#115913) 2024-03-26 15:18:17 +00:00
Mark Shannon 8bef34f625
GH-117108: Set the "old space bit" to "visited" for all young objects (#117213)
Change old space bit of young objects from 0 to gcstate->visited_space.
This ensures that any object created *and* collected during cycle GC has the bit set correctly.
2024-03-26 11:11:42 +00:00
Mark Shannon bf82f77957
GH-116422: Tier2 hot/cold splitting (GH-116813)
Splits the "cold" path, deopts and exits, from the "hot" path, reducing the size of most jitted instructions, at the cost of slower exits.
2024-03-26 09:35:11 +00:00
Mark Shannon 23e4f80ce2
A few minor tweaks to get stats working and compiling cleanly. (#117219)
Fixes a compilation error when configured with `--enable-pystats`,
an array size issue, and an unused variable.
2024-03-25 13:43:51 -07:00
Victor Stinner 507896d97d
gh-116936: Add PyType_GetModuleByDef() to the limited C API (#116937) 2024-03-25 16:32:20 +00:00
Victor Stinner 9967b568ed
gh-117008: Fix functools test_recursive_pickle() (#117009)
Use support.infinite_recursion() in test_recursive_pickle() of
test_functools to prevent a stack overflow on "ARM64 Windows
Non-Debug" buildbot.

Lower Py_C_RECURSION_LIMIT to 1,000 frames on Windows ARM64.
2024-03-23 13:01:20 +01:00
Mark Shannon e28477f214
GH-117108: Change the size of the GC increment to about 1% of the total heap size. (GH-117120) 2024-03-22 18:43:25 +00:00
Serhiy Storchaka e2e0b4b4b9
gh-113024: C API: Add PyObject_GenericHash() function (GH-113025) 2024-03-22 20:19:10 +02:00
Malcolm Smith 3ec57307e7
gh-71052: Add Android build script and instructions (#116426) 2024-03-22 00:52:29 +01:00
Guido van Rossum 570a82d46a
gh-117045: Add code object to function version cache (#117028)
Changes to the function version cache:

- In addition to the function object, also store the code object,
  and allow the latter to be retrieved even if the function has been evicted.
- Stop assigning new function versions after a critical attribute (e.g. `__code__`)
  has been modified; the version is permanently reset to zero in this case.
- Changes to `__annotations__` are no longer considered critical. (This fixes gh-109998.)

Changes to the Tier 2 optimization machinery:

- If we cannot map a function version to a function, but it is still mapped to a code object,
  we continue projecting the trace.
  The operand of the `_PUSH_FRAME` and `_POP_FRAME` opcodes can be either NULL,
  a function object, or a code object with the lowest bit set.

This allows us to trace through code that calls an ephemeral function,
i.e., a function that may not be alive when we are constructing the executor,
e.g. a generator expression or certain nested functions.
We will lose globals removal inside such functions,
but we can still do other peephole operations
(and even possibly [call inlining](https://github.com/python/cpython/pull/116290),
if we decide to do it), which only need the code object.
As before, if we cannot retrieve the code object from the cache, we stop projecting.
2024-03-21 12:37:41 -07:00
Sam Gross 1f72fb5447
gh-116522: Refactor `_PyThreadState_DeleteExcept` (#117131)
Split `_PyThreadState_DeleteExcept` into two functions:

- `_PyThreadState_RemoveExcept` removes all thread states other than one
  passed as an argument. It returns the removed thread states as a
  linked list.

- `_PyThreadState_DeleteList` deletes those dead thread states. It may
  call destructors, so we want to "start the world" before calling
  `_PyThreadState_DeleteList` to avoid potential deadlocks.
2024-03-21 11:21:02 -07:00
Michael Droettboom 50369e6c34
gh-116996: Add pystats about _Py_uop_analyse_and_optimize (GH-116997) 2024-03-22 01:27:46 +08:00
Eric Snow 617158e078
gh-76785: Drop PyInterpreterID_Type (gh-117101)
I added it quite a while ago as a strategy for managing interpreter lifetimes relative to the PEP 554 (now 734) implementation.  Relatively recently I refactored that implementation to no longer rely on InterpreterID objects.  Thus now I'm removing it.
2024-03-21 17:15:02 +00:00
Victor Stinner 8bea6c411d
gh-115754: Add Py_GetConstant() function (#116883)
Add Py_GetConstant() and Py_GetConstantBorrowed() functions.

In the limited C API version 3.13, getting Py_None, Py_False,
Py_True, Py_Ellipsis and Py_NotImplemented singletons is now
implemented as function calls at the stable ABI level to hide
implementation details. Getting these constants still return borrowed
references.

Add _testlimitedcapi/object.c and test_capi/test_object.py to test
Py_GetConstant() and Py_GetConstantBorrowed() functions.
2024-03-21 16:07:00 +00:00
Eric Snow 5a76d1be8e
gh-105716: Update interp->threads.main After Fork (gh-117049)
I missed this in gh-109921.

We also update Py_Exit() to call _PyInterpreterState_SetNotRunningMain(), if necessary.
2024-03-21 10:06:35 -06:00
Eric Snow bbee57fa8c
gh-76785: Clean Up Interpreter ID Conversions (gh-117048)
Mostly we unify the two different implementations of the conversion code (from PyObject * to int64_t.  We also drop the PyArg_ParseTuple()-style converter function, as well as rename and move PyInterpreterID_LookUp().
2024-03-21 09:56:12 -06:00
Victor Stinner 104602a607
gh-105927: Limit PyWeakref_GetRef() to limited C API 3.13 (#117091) 2024-03-20 23:52:23 +01:00
Serhiy Storchaka 519b2ae22b
gh-117021: Fix integer overflow in PyLong_AsPid() on non-Windows 64-bit platforms (GH-117064) 2024-03-20 15:39:53 +02:00
Mark Shannon 15309329b6
GH-108362: Incremental Cycle GC (GH-116206) 2024-03-20 08:54:42 +00:00
Bogdan Romanyuk a8e93d3dca
gh-115756: make PyCode_GetFirstFree an unstable API (GH-115781) 2024-03-19 09:20:38 +00:00
Sam Gross 165cb4578c
gh-116941: Fix pyatomic_std.h syntax errors (#116967) 2024-03-18 17:05:43 -04:00
Victor Stinner a9c304cf02
gh-116869: Make C API compatible with ISO C90 (#116950)
Make the C API compatible with -Werror=declaration-after-statement
compiler flag again.
2024-03-18 20:16:58 +01:00
Guido van Rossum 7e1f38f2de
gh-116916: Remove separate next_func_version counter (#116918)
Somehow we ended up with two separate counter variables tracking "the next function version".
Most likely this was a historical accident where an old branch was updated incorrectly.
This PR merges the two counters into a single one: `interp->func_state.next_version`.
2024-03-18 11:11:10 -07:00
Victor Stinner f139d840fb
gh-116869: Fix redefinition of the _PyOptimizerObject type (#116963)
Defining a type twice is a C11 feature and so makes the C API
incompatible with C99. Fix the issue by only defining the type once.

Example of warning (treated as an error):

    In file included from Include/Python.h:122:
    Include/cpython/optimizer.h:77:3: error: redefinition of typedef
    '_PyOptimizerObject' is a C11 feature [-Werror,-Wtypedef-redefinition]
    } _PyOptimizerObject;
    ^
    build/Include/cpython/optimizer.h:60:35: note: previous definition is here
    typedef struct _PyOptimizerObject _PyOptimizerObject;
                                    ^
2024-03-18 16:14:42 +00:00
Victor Stinner 5e0a070dfe
gh-116809: Restore removed _PyErr_ChainExceptions1() function (#116900) 2024-03-16 21:37:11 +01:00
mpage 33da0e844c
gh-114271: Fix race in `Thread.join()` (#114839)
There is a race between when `Thread._tstate_lock` is released[^1] in `Thread._wait_for_tstate_lock()`
and when `Thread._stop()` asserts[^2] that it is unlocked. Consider the following execution
involving threads A, B, and C:

1. A starts.
2. B joins A, blocking on its `_tstate_lock`.
3. C joins A, blocking on its `_tstate_lock`.
4. A finishes and releases its `_tstate_lock`.
5. B acquires A's `_tstate_lock` in `_wait_for_tstate_lock()`, releases it, but is swapped
   out before calling `_stop()`.
6. C is scheduled, acquires A's `_tstate_lock` in `_wait_for_tstate_lock()` but is swapped
   out before releasing it.
7. B is scheduled, calls `_stop()`, which asserts that A's `_tstate_lock` is not held.
   However, C holds it, so the assertion fails.

The race can be reproduced[^3] by inserting sleeps at the appropriate points in
the threading code. To do so, run the `repro_join_race.py` from the linked repo.

There are two main parts to this PR:

1. `_tstate_lock` is replaced with an event that is attached to `PyThreadState`.
   The event is set by the runtime prior to the thread being cleared (in the same
   place that `_tstate_lock` was released). `Thread.join()` blocks waiting for the
   event to be set.
2. `_PyInterpreterState_WaitForThreads()` provides the ability to wait for all
   non-daemon threads to exit. To do so, an `is_daemon` predicate was added to
   `PyThreadState`. This field is set each time a thread is created. `threading._shutdown()`
   now calls into `_PyInterpreterState_WaitForThreads()` instead of waiting on
   `_tstate_lock`s.

[^1]: 441affc9e7/Lib/threading.py (L1201)
[^2]: 441affc9e7/Lib/threading.py (L1115)
[^3]: 8194653279

---------

Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>
Co-authored-by: Antoine Pitrou <antoine@python.org>
2024-03-16 13:56:30 +01:00
Mark Shannon 2cf18a4430
GH-116422: Modify a few uops so that they can be supported by tier 2 with hot/cold splitting (GH-116832) 2024-03-15 10:48:00 +00:00
Victor Stinner 7bbb9b57e6
gh-111696, PEP 737: Add %T and %N to PyUnicode_FromFormat() (#116839) 2024-03-14 22:23:00 +00:00
Victor Stinner c432df6d56
gh-111696, PEP 737: Add PyType_GetModuleName() function (#116824)
Co-authored-by: Eric Snow <ericsnowcurrently@gmail.com>
2024-03-14 18:17:43 +00:00
Mark Shannon 61e54bfcee
GH-116422: Factor out eval breaker checks at end of calls into its own micro-op. (GH-116817) 2024-03-14 16:31:47 +00:00