Commit graph

8950 commits

Author SHA1 Message Date
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
Eric Snow f201628073
gh-117953: Other Cleanups in the Extensions Machinery (gh-118206)
This change will make some later changes simpler.
2024-05-03 00:51:43 +00: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
Sam Gross 16acecd779
Remove stray __cplusplus guard in sysmodule.c (#118511) 2024-05-02 13:51:28 -04: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
Raphael Gaschignard 2770d5caca
gh-105879: Add support for keyword arguments to eval and exec (#105885)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2024-05-02 08:55:29 -07:00
Mark Shannon 72867c962c
GH-118095: Unify the behavior of tier 2 FOR_ITER branch micro-ops (GH-118420)
* Target _FOR_ITER_TIER_TWO at POP_TOP following the matching END_FOR

* Modify _GUARD_NOT_EXHAUSTED_RANGE, _GUARD_NOT_EXHAUSTED_LIST and _GUARD_NOT_EXHAUSTED_TUPLE so that they also target the POP_TOP following the matching END_FOR
2024-05-02 16:17:59 +01:00
NGRsoftlab 7d2ffada0a
gh-116180: Check the globals argument in PyRun_* C API (GH-116637)
It used to crash when passing NULL or non-dict as globals.
Now it sets a SystemError.
2024-05-02 16:43:03 +03:00
Crowthebird 7c97dc8c95
gh-118216: Don't consider dotted __future__ imports (#118267) 2024-05-02 06:32:20 -07: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
Irit Katriel 6763bfcc0f
gh-118272: set stacktop to 0 before freeing contents, to avoid access to invalid objects during GC (#118478) 2024-05-01 21:51:40 +01:00
Hugo van Kemenade 3b3f8dea57
gh-117225: Move colorize functionality to own internal module (#118283) 2024-05-01 12:27:06 -06: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
Anthony Shaw beb653cc24
gh-117958: Expose JIT code via method in UOpExecutor (#117959) 2024-05-01 07:11:14 -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 7fabcc727d
gh-117657: Don't specialize RESUME_CHECK when specialization is disabled (GH-118349) 2024-04-30 21:51:59 +00: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
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
Nice Zombies 9a75d56d5d
gh-118379: Use PyTuple_Pack instead of Py_BuildValue if possible (GH-118381) 2024-04-30 17:55:15 +03:00
Malcolm Smith 3b268f4edc
gh-116622: Redirect stdout and stderr to system log when embedded in an Android app (#118063) 2024-04-30 16:00:31 +02:00
Mark Shannon 5b05d452cd
GH-118095: Add tier 2 support for YIELD_VALUE (GH-118380) 2024-04-30 11:33:13 +01:00
Savannah Ostrowski 8b56d82c59
GH-118306: Update JIT to use LLVM 18 (GH-118307) 2024-04-29 21:09:16 +00:00
Alex Turner 2ba1aed596
gh-117657: TSAN fix race on gstate->young.count (#118313) 2024-04-29 20:26:26 +00: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
Tian Gao 375c94c75d
gh-107674: Lazy load line number to improve performance of tracing (GH-118127) 2024-04-29 09:54:52 +01: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
Jelle Zijlstra 2326d6c868
gh-109118: Make comprehensions work within annotation scopes, but without inlining (#118160)
Co-authored-by: Carl Meyer <carl@oddbird.net>
2024-04-28 06:21:28 -07:00
Sam Gross 5a90de0d4c
gh-116749: Disable GIL by default in free-threaded build (#118295)
Switch GIL to disabled by default in free-threaded build so that the
free-threaded CIs catch thread-safety issues.
2024-04-26 14:22:29 -04: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
neonene 63add11704
gh-117680: Fix msvc warning in instruction_sequence.c (#118326) 2024-04-26 17:20:30 +01:00
Tian Gao 0f99861332
gh-117385: Remove unhooked events on sys.settrace (GH-117386) 2024-04-26 17:01:44 +01: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
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
Eric Snow 85ec1c2dc6
gh-117953: Fix Refleaks Introduced by gh-118194 (gh-118250)
A couple of refleaks slipped through in gh-118194. This takes care of them.

(AKA _Py_ext_module_loader_info_init() does not steal references.)
2024-04-24 21:23:45 +00: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 1acd249798
gh-117953: Let update_global_state_for_extension() Caller Decide If Singlephase or Not (gh-118193)
This change makes other upcoming changes simpler.
2024-04-24 16:28:35 +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 83235f7791
GH-115419: Move setting the instruction pointer to error exit stubs (GH-118088) 2024-04-24 14:41:30 +01: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
Guido van Rossum 7e87d30f1f
gh-118074: Immortal executors are not GC-able (#118182)
Better version of gh-118117.
Just check for immortality instead of an address range check.
2024-04-23 13:38:23 -07:00
mpage 2e7771a03d
gh-117657: Quiet TSAN warnings about remaining non-atomic accesses of tstate->state (#118165)
Quiet TSAN warnings about remaining non-atomic accesses of `tstate->state`
2024-04-23 10:20:14 -07: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
Joe Jevnik eb927e9fc8
gh-68114: Fix handling for removed PyArg_ParseTuple 'w' formatters (GH-8204)
Co-authored-by: Joe Jevnik <joe@quantopian.com>
Co-authored-by: Petr Viktorin <encukou@gmail.com>
2024-04-23 13:15:15 +02:00
Guido van Rossum 1b85b3424c
GH-118074: Executors in the COLD_EXITS array are not GC'able (#118117) 2024-04-22 16:20:39 -07:00
Jelle Zijlstra 85f727c5fb
gh-109118: Allow lambdas in annotation scopes in classes (#118019) 2024-04-22 12:50:26 -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
Russell Keith-Magee ab99438900
gh-114099: Modify preprocessor symbol usage to support older macOS SDKs (GH-118073)
Co-authored-by: Joshua Root jmr@macports.org
2024-04-19 14:56:33 -04: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
Tian Gao a09e472992
gh-117535: Change unknown filename of warnings from sys to <sys> (#118018) 2024-04-18 20:50:09 -07:00
Donghee Na 94444ea45a
gh-112069: Add _PySet_NextEntryRef to be thread-safe. (gh-117990) 2024-04-19 00:18:22 +09:00
Guido van Rossum 40f4d641a9
GH-118036: Fix a bug with CALL_STAT_INC (#117933)
We were under-counting calls in `_PyEvalFramePushAndInit`
because the `CALL_STAT_INC` macro was redefined to a no-op
for the Tier 2 interpreter. The fix is not to `#undef` it at all.
This results in ~37% more "Frames pushed" reported
under "Call stats".
2024-04-18 07:59:02 -07: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
Mark Shannon e32f6e9e4b
GH-115419: Tidy up tier 2 optimizer. Merge peephole pass into main pass (GH-117997) 2024-04-18 11:09:30 +01:00
Kirill Podoprigora cd7cf15588
gh-118023: Fix reference leak (#118025) 2024-04-18 07:32:32 +00:00
mpage 0d29302155
gh-117657: Quiet erroneous TSAN reports of data races in _PySeqLock (#117955)
Quiet erroneous TSAN reports of data races in `_PySeqLock`

TSAN reports a couple of data races between the compare/exchange in
`_PySeqLock_LockWrite` and the non-atomic loads in `_PySeqLock_{Abandon,Unlock}Write`.
This is another instance of TSAN incorrectly modeling failed compare/exchange
as a write instead of a load.
2024-04-17 17:19:28 +00: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
Jeff Glass acf69e09c6
gh-115178: Add Counts of UOp Pairs to pystats (GH-115181) 2024-04-16 14:27:18 +01:00
mpage 0d5238373d
gh-117657: Quiet more TSAN warnings due to incorrect modeling of compare/exchange (#117830) 2024-04-15 12:17:55 -04:00
mpage 6e0b327690
gh-117657: Quiet TSAN warning about a data race between start_the_world() and tstate_try_attach() (#117828)
TSAN erroneously reports a data race between the `_Py_atomic_compare_exchange_int`
on `tstate->state` in `tstate_try_attach()` and the non-atomic load of
`tstate->state` in `start_the_world`. The `_Py_atomic_compare_exchange_int` fails,
but TSAN erroneously treats it as a store.
2024-04-15 12:17:33 -04: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 3a8c1ca7e7
gh-117764: Fix and add signatures for many builtins (GH-117769) 2024-04-12 13:56:41 +03:00
Serhiy Storchaka 2638c28be0
gh-117764: Add signatures for some functions in the sys module (GH-117770)
Use Argument Clinic if possible.
2024-04-12 09:12:48 +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
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
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
Tian Gao 57183241af
gh-107674: Remove some unnecessary code in instrumentation code (GH-117393) 2024-04-09 09:54:28 +01: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
Brandt Bucher 62aeb0ee69
GH-117512: Allow 64-bit JIT operands on 32-bit platforms (GH-117527) 2024-04-06 08:26:43 -07:00
Erlend E. Aasland 757b62493b
gh-117457: Regen executor cases post PR #117477 (#117559) 2024-04-05 10:13:00 +00:00
Michael Droettboom 0edde64a41
GH-117457: Correct pystats uop "miss" counts (GH-117477) 2024-04-04 15:49:18 -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
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
Eric Snow 976bcb2379
gh-76785: Raise InterpreterError, Not RuntimeError (gh-117489)
I had meant to switch everything to InterpreterError when I added it a while back.  At the time I missed a few key spots.

As part of this, I've added print-the-exception to _PyXI_InitTypes() and fixed an error case in `_PyStaticType_InitBuiltin().
2024-04-03 10:58:39 -06:00
Eric Snow 65524ab388
gh-76785: Fix a Refleak in _interpreters.new_config() (gh-117491)
This is a follow-up to gh-117170 and gh-117485.
2024-04-03 01:10:26 +00: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
Guido van Rossum 8eda146e87
Fix successor opcode name printing in Tier 2 DEOPT debug message (#117471) 2024-04-02 18:25:48 +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
Guido van Rossum ddf814db74
Silence compiler warnings in gc.c (#117422) 2024-04-01 16:13:38 +00:00
Steve (Gadget) Barnes 3de09cadde
gh-91565: Replace bugs.python.org links with Devguide/GitHub ones (GH-91568)
Co-authored-by: Hugo van Kemenade <hugovk@users.noreply.github.com>
Co-authored-by: Oleg Iarygin <oleg@arhadthedev.net>
Co-authored-by: Petr Viktorin <encukou@gmail.com>
Co-authored-by: Ezio Melotti <ezio.melotti@gmail.com>
2024-04-01 13:02:07 +00:00
Sam Gross bfc57d43d8
gh-117303: Don't detach in PyThreadState_DeleteCurrent() (#117304)
This fixes a crash in `test_threading.test_reinit_tls_after_fork()` when
running with the GIL disabled. We already properly handle the case where
the thread state is `_Py_THREAD_ATTACHED` in `tstate_delete_common()` --
we just need to remove an assertion.

Keeping the thread attached means that a stop-the-world pause, such as
for a `fork()`, won't commence until we remove our thread state from the
interpreter's linked list. This prevents a crash when the child process
tries to clean up the dead thread states.
2024-03-29 18:58:08 -04:00
Erlend E. Aasland 05e0b67a43
gh-116664: In _warnings.c, make filters_version access thread-safe (#117374)
- assert that the lock is held in already_warned()
- protect 'filters_version' increment in warnings_filters_mutated_impl()
2024-03-29 21:23:28 +01:00
Sam Gross 01bd74eadb
gh-117300: Use stop the world to make sys._current_frames and sys._current_exceptions thread-safe. (#117301)
This adds a stop the world pause to make the two functions thread-safe
when the GIL is disabled in the free-threaded build.

Additionally, the main test thread may call `sys._current_exceptions()` as
soon as `g_raised.set()` is called. The background thread may not yet reach
the `leave_g.wait()` line.
2024-03-29 15:33:06 -04: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
Sam Gross f05fb2e65c
gh-112529: Don't untrack tuples or dicts with zero refcount (#117370)
The free-threaded GC sometimes sees objects with zero refcount. This can
happen due to the delay in merging biased reference counting fields,
and, in the future, due to deferred reference counting. We should not
untrack these objects or they will never be collected.

This fixes the refleaks in the free-threaded build.
2024-03-29 13:33:04 -04:00
Erlend E. Aasland ddf95b5f16
gh-116664: Fix unused var warnings in _warnings.c in non-free-threaded builds (#117373)
The warnings were introduced by commit c1712ef06.
2024-03-29 17:26:06 +00:00
Michael Droettboom 26d328b2ba
GH-117121: Add pystats to JIT builds (GH-117346) 2024-03-28 15:23:08 -07: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
Sam Gross 8dbfdb2957
gh-110481: Fix biased reference counting queue initialization. (#117271)
The biased reference counting queue must be initialized from the bound
(active) thread because it uses `_Py_ThreadId()` as the key in a hash
table.
2024-03-28 09:28:39 -04:00
Jelle Zijlstra 4c71d51a4b
gh-117266: Fix crashes on user-created AST subclasses (GH-117276)
Fix crashes on user-created AST subclasses
2024-03-28 11:30:31 +01:00
Russell Keith-Magee f006338017
gh-114099: Additions to standard library to support iOS (GH-117052)
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
Co-authored-by: Malcolm Smith <smith@chaquo.com>
Co-authored-by: Ned Deily <nad@python.org>
2024-03-28 03:59:33 -04: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
Kirill Podoprigora eebea7e515
gh-117176: Fix compiler warning in Python/optimizer_bytecodes.c (GH-117199) 2024-03-24 20:34:55 +02:00
Ken Jin 6c83352bfe
gh-117180: Complete call sequence when trace stack overflow (GH-117184)
---------

Co-authored-by: Peter Lazorchak <lazorchakp@gmail.com>
Co-authored-by: Guido van Rossum <gvanrossum@users.noreply.github.com>
Co-authored-by: Guido van Rossum <gvanrossum@gmail.com>
2024-03-24 06:19:17 +08: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
Eric Snow b3d25df8d3
gh-105716: Fix _PyInterpreterState_IsRunningMain() For Embedders (gh-117140)
When I added _PyInterpreterState_IsRunningMain() and friends last year, I tried to accommodate applications that embed Python but don't call _PyInterpreterState_SetRunningMain() (not that they're expected to).  That mostly worked fine until my recent changes in gh-117049, where the subtleties with the fallback code led to failures; the change ended up breaking test_tools.test_freeze, which exercises a basic embedding situation.

The simplest fix is to drop the fallback code I originally added to _PyInterpreterState_IsRunningMain() (and later to _PyThreadState_IsRunningMain()).  I've kept the fallback in the _xxsubinterpreters module though.  I've also updated Py_FrozenMain() to call _PyInterpreterState_SetRunningMain().
2024-03-21 18:20:20 -06: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
Sam Gross e728303532
gh-116522: Stop the world before fork() and during shutdown (#116607)
This changes the free-threaded build to perform a stop-the-world pause
before deleting other thread states when forking and during shutdown.
This fixes some crashes when using multiprocessing and during shutdown
when running with `PYTHON_GIL=0`.

This also changes `PyOS_BeforeFork` to acquire the runtime lock
(i.e., `HEAD_LOCK(&_PyRuntime)`) before forking to ensure that data
protected by the runtime lock (and not just the GIL or stop-the-world)
is in a consistent state before forking.
2024-03-21 10:01:16 -04:00
Mark Shannon 63289b9dfb
GH-117066: Tier 2 optimizer: Don't throw away good traces if we can't optimize them perfectly. (GH-117067) 2024-03-20 18:24:02 +00:00
Brett Simmers 9221ef2d8c
gh-116908: Only write to _pending_calls.calls_to_do with atomic operations (#117044)
These writes to `pending->calls_to_do` need to be atomic, because other threads
can read (atomically) from `calls_to_do` without holding `pending->mutex`.
2024-03-20 11:18:26 -04:00
Mark Shannon 15309329b6
GH-108362: Incremental Cycle GC (GH-116206) 2024-03-20 08:54:42 +00:00
Serhiy Storchaka 2d17309cc7
gh-117041: Add "-X gil" in the Python CLI help (GH-117042) 2024-03-19 23:30:25 +02:00
Serhiy Storchaka b85572c47d
gh-90300: Improve the Python CLI help output (GH-115853)
* document equivalent command-line options for all environment variables
* document equivalent environment variables for all command-line options
* reduce the size of variable and option descriptions to minimum
* remove the ending period in single-sentence descriptions

Co-authored-by: Éric <merwok@netwok.org>
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
2024-03-19 19:26:32 +02:00
Brandt Bucher 2c82592ab4
GH-116017: Put JIT code and data on the same page (GH-116845) 2024-03-19 08:47:28 -07:00
Michael Droettboom 0f278012e8
gh-116808: Fix optimized trace length histogram (GH-116827) 2024-03-19 11:06:43 +00:00
Bogdan Romanyuk a8e93d3dca
gh-115756: make PyCode_GetFirstFree an unstable API (GH-115781) 2024-03-19 09:20:38 +00:00
Guido van Rossum 9c7b3688e6
gh-108716: Cleanup remaining deepfreeze infrastructure (#116919)
Keep Tools/build/deepfreeze.py around (we may repurpose it for deepfreezing non-code objects),
and keep basic "clean" targets that remove the output of former deep-freeze activities,
to keep the build directories of current devs clean.
2024-03-18 11:13:11 -07: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
Guido van Rossum 76d0868907
Cleanup tier2 debug output (#116920)
Various tweaks, including a slight refactor of the special cases for `_PUSH_FRAME`/`_POP_FRAME` to show the actual operand emitted.
2024-03-18 11:08:43 -07:00
Victor Stinner 1d95451be1
gh-63207: Use GetSystemTimePreciseAsFileTime() in time.time() (#116822) 2024-03-18 17:13:01 +01:00
Erlend E. Aasland 762f489b31
gh-116664: Ensure thread-safe dict access in _warnings (#116768)
Replace _PyDict_GetItemWithError() with PyDict_GetItemRef().
2024-03-18 09:37:48 +00: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
Donghee Na 20578a1f68
gh-112536: Add TSAN builds on Github Actions (#116872) 2024-03-16 11:10:37 +01:00
Mark Shannon 950667ed07
GH-115802: Reduce the size of _INIT_CALL_PY_EXACT_ARGS. (GH-116856) 2024-03-15 17:16:30 +00:00
Tian Gao 59e30f41ed
gh-116735: Use MISSING for CALL event if argument is absent (GH-116737) 2024-03-15 14:46:18 +00: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 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
Victor Stinner 846ad5a26a
gh-88494: Use QueryPerformanceCounter() for time.monotonic() (#116781)
On Windows, time.monotonic() now uses the QueryPerformanceCounter()
clock to have a resolution better than 1 us, instead of the
gGetTickCount64() clock which has a resolution of 15.6 ms.
2024-03-14 16:42:41 +01:00