Commit graph

8535 commits

Author SHA1 Message Date
gsallam 21f068d80c
gh-109587: Allow "precompiled" perf-trampolines to largely mitigate the cost of enabling perf-trampolines (#109666) 2023-10-27 03:57:29 +00:00
Irit Katriel a0c414c35d
gh-111354: define names for RESUME oparg values (#111365) 2023-10-26 16:30:18 +01:00
Irit Katriel 67a91f78e4
gh-109094: replace frame->prev_instr by frame->instr_ptr (#109095) 2023-10-26 13:43:10 +00:00
Mark Shannon b0699aa544
GH-111213: Fix a few broken stats (GH-111216) 2023-10-26 11:33:12 +01:00
Mark Shannon 5c9d4497ab
GH-111339: Change valid property of executors to is_valid() method (GH-111350) 2023-10-26 11:31:51 +01:00
Pablo Galindo Salgado 90a1b2859f
gh-67224: Show source lines in tracebacks when using the -c option when running Python (#111200) 2023-10-26 15:17:28 +09:00
scoder a8a89fcd1f
gh-106320: Re-add some PyLong/PyDict C-API functions (GH-#111162)
* gh-106320: Re-add _PyLong_FromByteArray(), _PyLong_AsByteArray() and _PyLong_GCD() to the public header files since they are used by third-party packages and there is no efficient replacement.

See https://github.com/python/cpython/issues/111140
See https://github.com/python/cpython/issues/111139

* gh-111262: Re-add _PyDict_Pop() to have a C-API until a new public one is designed.
2023-10-25 11:33:48 +02:00
Brandt Bucher e5168ff3f8
GH-109214: _SET_IP before _PUSH_FRAME (but not _POP_FRAME) (GH-111001) 2023-10-24 13:27:42 -07:00
Mark Shannon 52e902ccf0
GH-109369: Add machinery for deoptimizing tier2 executors, both individually and globally. (GH-110384) 2023-10-23 14:49:09 +01:00
Furkan Onder 32c37fe1ba
gh-67565: Remove redundant C-contiguity checks (GH-105521)
Co-authored-by: Stefan Krah <skrah@bytereef.org>
2023-10-23 12:54:46 +03:00
Irit Katriel b578e51f02
gh-111123: symtable should visit exception handlers before the else block (#111142) 2023-10-21 13:38:29 +01:00
Kirill Podoprigora 7162c3a1e8
gh-111133: Remove unnecessary PyFrozenSet_Check() calls in const folding (GH-111137)
frozenset does not support multiplication.
2023-10-20 23:37:38 +03:00
Nikita Sobolev 124259f9b3
gh-111132: Fix crash on interactive_filename in run_mod (#111136) 2023-10-20 21:31:26 +01:00
Eric Snow a77fa05124
gh-76785: Clean Up the Channels Module (gh-110568) 2023-10-17 23:51:52 +00:00
Eric Snow c58c63fdf6
gh-84570: Add Timeouts to SendChannel.send() and RecvChannel.recv() (gh-110567) 2023-10-17 23:05:49 +00:00
Eric Snow a53d7cb672
gh-84570: Send-Wait Fixes for _xxinterpchannels (gh-111006)
There were a few things I did in gh-110565 that need to be fixed. I also forgot to add tests in that PR.

(Note that this PR exposes a refleak introduced by gh-110246. I'll take care of that separately.)
2023-10-17 16:32:00 -06:00
Donghee Na 2dcc57008b
gh-109693: Remove pycore_atomic.h (gh-110992) 2023-10-18 00:33:50 +09:00
Victor Stinner be5e8a0103
gh-110964: Remove private _PyArg functions (#110966)
Move the following private functions and structures to
pycore_modsupport.h internal C API:

* _PyArg_BadArgument()
* _PyArg_CheckPositional()
* _PyArg_NoKeywords()
* _PyArg_NoPositional()
* _PyArg_ParseStack()
* _PyArg_ParseStackAndKeywords()
* _PyArg_Parser structure
* _PyArg_UnpackKeywords()
* _PyArg_UnpackKeywordsWithVararg()
* _PyArg_UnpackStack()
* _Py_ANY_VARARGS()

Changes:

* Python/getargs.h now includes pycore_modsupport.h to export
  functions.
* clinic.py now adds pycore_modsupport.h when one of these functions
  is used.
* Add pycore_modsupport.h includes when a C extension uses one of
  these functions.
* Define Py_BUILD_CORE_MODULE in C extensions which now include
  directly or indirectly (via code generated by Argument Clinic)
  pycore_modsupport.h:

  * _csv
  * _curses_panel
  * _dbm
  * _gdbm
  * _multiprocessing.posixshmem
  * _sqlite.row
  * _statistics
  * grp
  * resource
  * syslog

* _testcapi: bad_get() no longer uses METH_FASTCALL calling
  convention but METH_VARARGS. Replace _PyArg_UnpackStack() with
  PyArg_ParseTuple().
* _testcapi: add PYTESTCAPI_NEED_INTERNAL_API macro which is defined
  by _testcapi sub-modules which need the internal C API
  (pycore_modsupport.h): exceptions.c, float.c, vectorcall.c,
  watchers.c.
* Remove Include/cpython/modsupport.h header file.
  Include/modsupport.h no longer includes the removed header file.
* Fix mypy clinic.py
2023-10-17 14:30:31 +02:00
Donghee Na 86559ddfec
gh-109693: Update _gil_runtime_state.locked to use pyatomic.h (gh-110836) 2023-10-17 07:32:50 +09:00
Pablo Galindo Salgado b3c9faf056
gh-110912: Correctly display tracebacks for MemoryError exceptions using the traceback module (#110921) 2023-10-16 15:39:23 +01:00
Nikita Sobolev c2192a2bee
gh-110864: Fix _PyArg_UnpackKeywordsWithVararg overwriting vararg with NULL (#110868) 2023-10-16 13:42:44 +02:00
Łukasz Langa 84b7e9e3fa
gh-110722: Add PYTHON_PRESITE to import a module before site.py is run (#110769) 2023-10-14 23:32:57 +02:00
Serhiy Storchaka 7284e0ef84
gh-110815: Support non-ASCII keyword names in PyArg_ParseTupleAndKeywords() (GH-110816)
It already mostly worked, except in the case when invalid keyword
argument with non-ASCII name was passed to function with non-ASCII
parameter names. Then it crashed in the debug mode.
2023-10-14 08:50:03 +03:00
Pablo Galindo Salgado e1d8c65e1d
gh-110805: Allow the repl to show source code and complete tracebacks (#110775) 2023-10-13 09:25:37 +00:00
Donghee Na 2566434e59
gh-109693: Update _gil_runtime_state.last_holder to use pyatomic.h (#110605) 2023-10-13 10:07:27 +09:00
Pablo Galindo Salgado e7331365b4
gh-110721: Use the traceback module for PyErr_Display() and fallback to the C implementation (#110702) 2023-10-12 14:52:14 +00:00
Tian Gao 1e3460d9fa
gh-110752: Reset ceval.eval_breaker to 0 in interpreter_clear (GH-110753) 2023-10-12 15:10:21 +01:00
Irit Katriel 7dd3c2b800
gh-109094: remove redundant arg to _PyFrame_PushTrampolineUnchecked (GH-110759) 2023-10-12 11:02:42 +01:00
Mark Shannon 19b7ead5eb
GH-109214: Convert _SAVE_CURRENT_IP to _SET_IP in tier 2 trace creation. (GH-110755) 2023-10-12 10:34:32 +01:00
Lysandros Nikolaou 17d65547df
gh-104169: Fix test_peg_generator after tokenizer refactoring (#110727)
* Fix test_peg_generator after tokenizer refactoring
* Remove references to tokenizer.c in comments etc.
2023-10-12 09:34:35 +02:00
Lysandros Nikolaou 01481f2dc1
gh-104169: Refactor tokenizer into lexer and wrappers (#110684)
* The lexer, which include the actual lexeme producing logic, goes into
  the `lexer` directory.
* The wrappers, one wrapper per input mode (file, string, utf-8, and
  readline), go into the `tokenizer` directory and include logic for
  creating a lexer instance and managing the buffer for different modes.
---------

Co-authored-by: Pablo Galindo <pablogsal@gmail.com>
Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>
2023-10-11 15:14:44 +00:00
Zackery Spytz f83fa0b9eb
gh-84489: Properly handle trailing spaces in Py_BuildValue() format strings (GH-21158)
The docs state that the space, tab, colon, and comma characters are
ignored in Py_BuildValue() format strings.

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
2023-10-11 14:44:06 +03:00
Donghee Na 0362cbf908
gh-109595: Add -Xcpu_count=<n> cmdline for container users (#109667)
---------

Co-authored-by: Victor Stinner <vstinner@python.org>
Co-authored-by: Gregory P. Smith [Google LLC] <greg@krypto.org>
2023-10-10 19:00:09 +09:00
Brandt Bucher 982f1b7d6d
Remove an old macro from executor.c (#110597) 2023-10-10 08:45:23 +00:00
Donghee Na 67e8d416cc
gh-109693: Use pyatomic.h for signal module (gh-110480) 2023-10-10 08:26:29 +09:00
Eric Snow 7bd560ce8d
gh-76785: Add SendChannel.send_buffer() (#110246)
(This is still a test module.)
2023-10-09 07:39:51 -06:00
Tian Gao dd4bb0529e
gh-110514: Add PY_THROW to sys.setprofile events (GH-110524) 2023-10-09 09:38:45 +01:00
denballakh dd9d781da3
gh-110237: Check PyList_Append for errors in _PyEval_MatchClass (#110238) 2023-10-07 17:04:51 -07:00
Masaru Tsuchiyama de2a4036cb
gh-108277: Add os.timerfd_create() function (#108382)
Add wrapper for timerfd_create, timerfd_settime, and timerfd_gettime to os module.

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
Co-authored-by: Adam Turner <9087854+AA-Turner@users.noreply.github.com>
Co-authored-by: Erlend E. Aasland <erlend.aasland@protonmail.com>
Co-authored-by: Victor Stinner <vstinner@python.org>
2023-10-07 19:33:22 +02:00
Brett Cannon 5fd8821cf8
GH-110455: Guard assert(tstate->thread_id > 0) with #ifndef HAVE_PTHREAD_STUBS (GH-110487) 2023-10-06 16:12:19 -07:00
Victor Stinner bb057b3370
gh-85283: Add PySys_AuditTuple() function (#108965)
sys.audit() now has assertions to check that the event argument is
not NULL and that the format argument does not use the "N" format.

Add tests on PySys_AuditTuple().
2023-10-05 21:59:35 +00:00
Sam Gross 6e97a9647a
gh-109549: Add new states to PyThreadState to support PEP 703 (gh-109915)
This adds a new field 'state' to PyThreadState that can take on one of three values: _Py_THREAD_ATTACHED, _Py_THREAD_DETACHED, or _Py_THREAD_GC.  The "attached" and "detached" states correspond closely to acquiring and releasing the GIL.  The "gc" state is current unused, but will be used to implement stop-the-world GC for --disable-gil builds in the near future.
2023-10-05 09:46:33 -06:00
Michael Droettboom 9eb2489266
gh-109329: Add stat for "trace too short" (GH-110402) 2023-10-05 16:12:06 +01:00
Sam Gross cf6f23b0e3
gh-88402: Add new sysconfig variables on Windows (GH-110049)
Co-authored-by: Filipe Laíns <filipe.lains@gmail.com>
2023-10-04 22:50:29 +00:00
Eric Snow 80dc39e1dc
gh-110310: Add a Per-Interpreter XID Registry for Heap Types (gh-110311)
We do the following:

* add a per-interpreter XID registry (PyInterpreterState.xidregistry)
* put heap types there (keep static types in _PyRuntimeState.xidregistry)
* clear the registries during interpreter/runtime finalization
* avoid duplicate entries in the registry (when _PyCrossInterpreterData_RegisterClass() is called more than once for a type)
* use Py_TYPE() instead of PyObject_Type() in _PyCrossInterpreterData_Lookup()

The per-interpreter registry helps preserve isolation between interpreters.  This is important when heap types are registered, which is something we haven't been doing yet but I will likely do soon.
2023-10-04 16:35:27 -06:00
Michael Droettboom e561e98058
GH-109329: Add tier 2 stats (GH-109913) 2023-10-04 14:52:28 -07:00
Mark Shannon bf4bc36069
GH-109369: Merge all eval-breaker flags and monitoring version into one word. (GH-109846) 2023-10-04 16:09:48 +01:00
Guido van Rossum 7c149a76b2
gh-104909: Split more LOAD_ATTR specializations (GH-110317)
* Split LOAD_ATTR_MODULE

* Split LOAD_ATTR_WITH_HINT

* Split _GUARD_TYPE_VERSION out of the latter

* Split LOAD_ATTR_CLASS

* Split LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES

* Fix indent of DEOPT_IF in macros

* Split LOAD_ATTR_METHOD_LAZY_DICT

* Split LOAD_ATTR_NONDESCRIPTOR_NO_DICT

* Fix omission of _CHECK_ATTR_METHOD_LAZY_DICT
2023-10-04 16:08:02 +01:00
Guido van Rossum 625ecbe92e
gh-109979: Unify _GUARD_TYPE_VERSION{,_STORE} (#110301)
Now the target for `DEOPT_IF()` is auto-filled,
we don't need a separate `_GUARD_TYPE_VERSION_STORE` uop.
2023-10-03 22:37:21 +00:00
Guido van Rossum d67edcf0b3
gh-109979: Auto-generate the target for DEOPT_IF() (#110193)
In Python/bytecodes.c, you now write
```
    DEOPT_IF(condition);
```
The code generator expands this to
```
    DEOPT_IF(condition, opcode);
```
where `opcode` is the name of the unspecialized instruction.
This works inside macro expansions too.

**CAVEAT:** The entire `DEOPT_IF(condition)` statement must be on a single line.
If it isn't, the substitution will fail; an error will be printed by the code generator
and the C compiler will report some errors.
2023-10-03 10:13:50 -07:00
Victor Stinner d73501602f
gh-108867: Add PyThreadState_GetUnchecked() function (#108870)
Add PyThreadState_GetUnchecked() function: similar to
PyThreadState_Get(), but don't issue a fatal error if it is NULL. The
caller is responsible to check if the result is NULL. Previously,
this function was private and known as _PyThreadState_UncheckedGet().
2023-10-03 16:53:51 +00:00
Eric Snow f5198b09e1
gh-109860: Use a New Thread State When Switching Interpreters, When Necessary (gh-110245)
In a few places we switch to another interpreter without knowing if it has a thread state associated with the current thread.  For the main interpreter there wasn't much of a problem, but for subinterpreters we were *mostly* okay re-using the tstate created with the interpreter (located via PyInterpreterState_ThreadHead()).  There was a good chance that tstate wasn't actually in use by another thread.

However, there are no guarantees of that.  Furthermore, re-using an already used tstate is currently fragile.  To address this, now we create a new thread state in each of those places and use it.

One consequence of this change is that PyInterpreterState_ThreadHead() may not return NULL (though that won't happen for the main interpreter).
2023-10-03 09:20:48 -06:00
Eric Snow 1dd9dee45d
gh-105716: Support Background Threads in Subinterpreters Consistently (gh-109921)
The existence of background threads running on a subinterpreter was preventing interpreters from getting properly destroyed, as well as impacting the ability to run the interpreter again. It also affected how we wait for non-daemon threads to finish.

We add PyInterpreterState.threads.main, with some internal C-API functions.
2023-10-02 20:12:12 +00:00
Eric Snow a040a32ea2
gh-109853: Fix sys.path[0] For Subinterpreters (gh-109994)
This change makes sure sys.path[0] is set properly for subinterpreters. Before, it wasn't getting set at all. This PR does not address the broader concerns from gh-109853.
2023-10-02 19:59:05 +00:00
Victor Stinner d3728ddc57
gh-110014: Fix bootstrap_hash.c: remove debug code (#110161)
Oops, I commited debug code by mistake, sorry about that.
2023-09-30 22:21:20 +00:00
Victor Stinner 7513994c92
gh-110014: Include explicitly <unistd.h> header (#110155)
* Remove unused <locale.h> includes.
* Remove unused <fcntl.h> include in traceback.h.
* Remove redundant <assert.h> and <stddef.h> includes. They  are already
  included by "Python.h".
* Remove <object.h> include in faulthandler.c. Python.h already includes it.
* Add missing <stdbool.h> in pycore_pythread.h if HAVE_PTHREAD_STUBS
  is defined.
* Fix also warnings in pthread_stubs.h: don't redefine macros if they
  are already defined, like the __NEED_pthread_t macro.
2023-09-30 20:06:45 +00:00
Victor Stinner 74e425ec18
gh-110014: Fix _POSIX_THREADS and _POSIX_SEMAPHORES usage (#110139)
* pycore_pythread.h is now the central place to make sure that
  _POSIX_THREADS and _POSIX_SEMAPHORES macros are defined if
  available.
* Make sure that pycore_pythread.h is included when _POSIX_THREADS
  and _POSIX_SEMAPHORES macros are tested.
* PY_TIMEOUT_MAX is now defined as a constant, since its value
  depends on _POSIX_THREADS, instead of being defined as a macro.
* Prevent integer overflow in the preprocessor when computing
  PY_TIMEOUT_MAX_VALUE on Windows:
  replace "0xFFFFFFFELL * 1000 < LLONG_MAX"
  with "0xFFFFFFFELL < LLONG_MAX / 1000".
* Document the change and give hints how to fix affected code.
* Add an exception for PY_TIMEOUT_MAX  name to smelly.py
* Add PY_TIMEOUT_MAX to the stable ABI
2023-09-30 19:25:54 +02:00
Victor Stinner f3bb00ea12
gh-107954: Refactor initconfig.c: add CONFIG_SPEC (#110146)
Add a specification of the PyConfig structure to factorize the code.
2023-09-30 17:24:06 +00:00
Victor Stinner 8b626a47ba
gh-110079: Remove extern "C" { ...} in C code (#110080) 2023-09-29 10:56:49 +02:00
Victor Stinner 2e37a38bcb
gh-110052: Fix faulthandler for freed tstate (#110069)
faulthandler now detected freed interp and freed tstate, and no
longer dereference them.
2023-09-29 02:04:06 +00:00
Irit Katriel f580edcc6a
gh-109889: fix compiler's redundant NOP detection to look past NOPs with no lineno when looking for the next instruction's lineno (#109987) 2023-09-28 20:33:28 +01:00
Nikita Sobolev 3814bc1723
gh-110020: Fix unused variable warnings in bytecodes.c (GH-110023) 2023-09-28 15:31:32 +01:00
Guido van Rossum 5bb6f0fcba
gh-104909: Split some more insts into ops (#109943)
These are the most popular specializations of `LOAD_ATTR` and `STORE_ATTR`
that weren't already viable uops:

* Split LOAD_ATTR_METHOD_WITH_VALUES
* Split LOAD_ATTR_METHOD_NO_DICT
* Split LOAD_ATTR_SLOT
* Split STORE_ATTR_SLOT
* Split STORE_ATTR_INSTANCE_VALUE

Also:

* Add `-v` flag to code generator which prints a list of non-viable uops
  (easter-egg: it can print execution counts -- see source)
* Double _Py_UOP_MAX_TRACE_LENGTH to 128



I had dropped one of the DEOPT_IF() calls! :-(
2023-09-27 15:27:44 -07:00
Eric Snow 32466c97c0
gh-109793: Allow Switching Interpreters During Finalization (gh-109794)
Essentially, we should check the thread ID rather than the thread state pointer.
2023-09-27 13:41:06 -06:00
Sam Gross 773614e03a
gh-109740: Use 't' in --disable-gil SOABI (#109922)
Shared libraries for CPython 3.13 are now marked with a 't' for
threading. For example, `binascii.cpython-313t-darwin.so`.
2023-09-27 15:24:12 +00:00
Irit Katriel ea285ad8b6
gh-109923: set line number on the POP_TOP that follows a RETURN_GENERATOR (#109924) 2023-09-27 13:24:33 +01:00
Irit Katriel d73c12b88c
gh-109823: Adjust labels in compiler when removing an empty basic block which is a jump target (#109839) 2023-09-25 18:25:05 +00:00
Serhiy Storchaka 62c7015e89
gh-109521: Fix obscure cases handling in PyImport_GetImporter() (GH-109522)
PyImport_GetImporter() now sets RuntimeError if it fails to get sys.path_hooks
or sys.path_importer_cache or they are not list and dict correspondingly.

Previously it could return NULL without setting error in obscure cases,
crash or raise SystemError if these attributes have wrong type.
2023-09-23 09:39:24 +03:00
Serhiy Storchaka b8d1744e7b
gh-109611: Add convenient C API function _PyFile_Flush() (GH-109612) 2023-09-23 09:35:30 +03:00
Tian Gao d5611f2804
GH-107265: Add missing deoptimizations for ENTER_EXECUTOR's original opcode (GH-109420) 2023-09-22 14:13:31 -07:00
Irit Katriel 7c55399172
gh-109719: Fix missing jump target labels when compiler reorders cold/warm blocks (#109734) 2023-09-22 16:59:35 +00:00
Irit Katriel 9ccf0545ef
gh-109627: duplicated smalll exit blocks need to be assigned jump target labels (#109630) 2023-09-20 23:08:06 +00:00
Carl Meyer 32ffe58c12
gh-109390: add dump_symtable utility under #if 0 (#109391)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-09-20 10:55:56 -06:00
Eric Snow fd7e08a6f3
gh-76785: Use Pending Calls When Releasing Cross-Interpreter Data (gh-109556)
This fixes some crashes in the _xxinterpchannels module, due to a race between interpreters.
2023-09-19 15:01:34 -06:00
Sam Gross 0c89056fe5
gh-108724: Add PyMutex and _PyParkingLot APIs (gh-109344)
PyMutex is a one byte lock with fast, inlineable lock and unlock functions for the common uncontended case.  The design is based on WebKit's WTF::Lock.

PyMutex is built using the _PyParkingLot APIs, which provides a cross-platform futex-like API (based on WebKit's WTF::ParkingLot).  This internal API will be used for building other synchronization primitives used to implement PEP 703, such as one-time initialization and events.

This also includes tests and a mini benchmark in Tools/lockbench/lockbench.py to compare with the existing PyThread_type_lock.

Uncontended acquisition + release:
* Linux (x86-64): PyMutex: 11 ns, PyThread_type_lock: 44 ns
* macOS (arm64): PyMutex: 13 ns, PyThread_type_lock: 18 ns
* Windows (x86-64): PyMutex: 13 ns, PyThread_type_lock: 38 ns

PR Overview:

The primary purpose of this PR is to implement PyMutex, but there are a number of support pieces (described below).

* PyMutex:  A 1-byte lock that doesn't require memory allocation to initialize and is generally faster than the existing PyThread_type_lock.  The API is internal only for now.
* _PyParking_Lot:  A futex-like API based on the API of the same name in WebKit.  Used to implement PyMutex.
* _PyRawMutex:  A word sized lock used to implement _PyParking_Lot.
* PyEvent:  A one time event.  This was used a bunch in the "nogil" fork and is useful for testing the PyMutex implementation, so I've included it as part of the PR.
* pycore_llist.h:  Defines common operations on doubly-linked list.  Not strictly necessary (could do the list operations manually), but they come up frequently in the "nogil" fork. ( Similar to https://man.freebsd.org/cgi/man.cgi?queue)

---------

Co-authored-by: Eric Snow <ericsnowcurrently@gmail.com>
2023-09-19 09:54:29 -06:00
Serhiy Storchaka c829975428
Fix error handling in _PySys_UpdateConfig() (GH-109524) 2023-09-18 20:09:59 +03:00
Tian Gao 412f5e85d6
gh-109371: Fix monitoring with instruction events set (gh-109385) 2023-09-18 23:30:08 +09:00
Serhiy Storchaka add16f1a5e
gh-108511: Add C API functions which do not silently ignore errors (GH-109025)
Add the following functions:

* PyObject_HasAttrWithError()
* PyObject_HasAttrStringWithError()
* PyMapping_HasKeyWithError()
* PyMapping_HasKeyStringWithError()
2023-09-17 14:23:31 +03:00
Hood Chatham 6b179adb8c
gh-106213: Make Emscripten trampolines work with JSPI (GH-106219)
There is a WIP proposal to enable webassembly stack switching which have been
implemented in v8:

https://github.com/WebAssembly/js-promise-integration

It is not possible to switch stacks that contain JS frames so the Emscripten JS
trampolines that allow calling functions with the wrong number of arguments
don't work in this case. However, the js-promise-integration proposal requires
the [type reflection for Wasm/JS API](https://github.com/WebAssembly/js-types)
proposal, which allows us to actually count the number of arguments a function
expects.

For better compatibility with stack switching, this PR checks if type reflection
is available, and if so we use a switch block to decide the appropriate
signature. If type reflection is unavailable, we should use the current EMJS
trampoline.

We cache the function argument counts since when I didn't cache them performance
was negatively affected.

Co-authored-by: T. Wouters <thomas@python.org>
Co-authored-by: Brett Cannon <brett@python.org>
2023-09-15 15:04:21 -07:00
Carl Meyer 909adb5092
gh-109219: propagate free vars through type param scopes (#109377)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
2023-09-14 10:20:32 -06:00
Irit Katriel 4a54074a0f
gh-105658: fix excess trace events for except block ending with a conditional block (#109384) 2023-09-14 17:06:08 +01:00
Carl Meyer 1ce9ea0453
dump readable opcode names in flowgraph debug utility (#109392)
Co-authored-by: Irit Katriel <1055913+iritkatriel@users.noreply.github.com>
2023-09-14 14:28:21 +00:00
Brandt Bucher 6c13e13b13
GH-104584: Don't call executors from JUMP_BACKWARD (GH-109347) 2023-09-13 10:26:50 -07:00
Brandt Bucher 22e65eecaa
GH-105848: Replace KW_NAMES + CALL with LOAD_CONST + CALL_KW (GH-109300) 2023-09-13 10:25:45 -07:00
Jelle Zijlstra 987b4bc087
gh-109341: Fix crash on compiling invalid AST including TypeAlias (#109349) 2023-09-13 09:00:39 -07:00
Jelle Zijlstra 79101edb03
gh-109351: Fix crash when compiling AST with invalid NamedExpr (#109352) 2023-09-13 09:00:15 -07:00
Michael Droettboom 5dcbbd8861
GH-109330: Dump and compare stats using opcode names, not numbers (GH-109335) 2023-09-12 14:12:57 -07:00
Guido van Rossum b86ce91bfe
gh-106581: Honor 'always_exits' in write_components() (#109338)
I must have overlooked this when refactoring the code generator.
The Tier 1 interpreter contained a few silly things like
```
            goto resume_frame;
            STACK_SHRINK(1);
```
(and other variations, some where the unconditional `goto` was hidden in a macro).
2023-09-12 17:58:40 +00:00
Irit Katriel 8b55adfa8f
gh-109256: allocate opcode IDs for internal opcodes in their own range (#109269) 2023-09-12 10:36:17 +00:00
Nikita Sobolev 247ee1bf84
gh-109216: Fix possible memory leak in BUILD_MAP (#109257) 2023-09-12 15:07:22 +05:30
Jelle Zijlstra b88d9e75f6
gh-109118: Disallow nested scopes within PEP 695 scopes within classes (#109196)
Fixes #109118. Fixes #109194.

Co-authored-by: Carl Meyer <carl@oddbird.net>
2023-09-11 17:11:06 -07:00
Carl Meyer ceeb4173ae
gh-109195: fix source location for super load before LOAD_SUPER_ATTR (#109289) 2023-09-11 17:35:49 -06:00
Guido van Rossum fbaf77eb9b
gh-109214: Rename SAVE_IP to _SET_IP, and similar (#109285)
* Rename SAVE_IP to _SET_IP
* Rename EXIT_TRACE to _EXIT_TRACE
* Rename SAVE_CURRENT_IP to _SAVE_CURRENT_IP
* Rename INSERT to _INSERT (This is for Ken Jin's abstract interpreter)
* Rename IS_NONE to _IS_NONE
* Rename JUMP_TO_TOP to _JUMP_TO_TOP
2023-09-11 15:39:19 -07:00
Guido van Rossum bcce5e2718
gh-109039: Branch prediction for Tier 2 interpreter (#109038)
This adds a 16-bit inline cache entry to the conditional branch instructions POP_JUMP_IF_{FALSE,TRUE,NONE,NOT_NONE} and their instrumented variants, which is used to keep track of the branch direction.

Each time we encounter these instructions we shift the cache entry left by one and set the bottom bit to whether we jumped.

Then when it's time to translate such a branch to Tier 2 uops, we use the bit count from the cache entry to decided whether to continue translating the "didn't jump" branch or the "jumped" branch.

The counter is initialized to a pattern of alternating ones and zeros to avoid bias.

The .pyc file magic number is updated. There's a new test, some fixes for existing tests, and a few miscellaneous cleanups.
2023-09-11 18:20:24 +00:00
Irit Katriel ecd21a629a
gh-109179: Fix traceback display for SyntaxErrors with notes (#109197) 2023-09-11 19:18:34 +01:00
Victor Stinner 517cd82ea7
gh-108987: Fix _thread.start_new_thread() race condition (#109135)
Fix _thread.start_new_thread() race condition. If a thread is created
during Python finalization, the newly spawned thread now exits
immediately instead of trying to access freed memory and lead to a
crash.

thread_run() calls PyEval_AcquireThread() which checks if the thread
must exit. The problem was that tstate was dereferenced earlier in
_PyThreadState_Bind() which leads to a crash most of the time.

Move _PyThreadState_CheckConsistency() from thread_run() to
_PyThreadState_Bind().
2023-09-11 17:27:03 +02:00
Mark Shannon 4a69301ea4
GH-108976. Keep monitoring data structures valid during de-optimization during callback. (GH-109131) 2023-09-11 14:37:09 +01:00
云line 4297499696
gh-109207: Fix SystemError when printing symtable entry object. (GH-109225) 2023-09-10 15:04:24 +03:00
Jelle Zijlstra 17f994174d
gh-109118: Fix runtime crash when NameError happens in PEP 695 function (#109123) 2023-09-09 02:49:20 +00:00
Serhiy Storchaka 87a7faf6b6
Check the result of PySet_Contains() for error in Python/symtable.c (GH-109146) 2023-09-08 19:57:41 +03:00
Mark Shannon 501f2dc527
GH-108614: Unbreak emscripten build (GH-109132) 2023-09-08 17:54:45 +01:00
Pablo Galindo Salgado 6275c67ea6
gh-106922: Fix error location for constructs with spaces and parentheses (#108959) 2023-09-08 17:18:35 +01:00
Victor Stinner f63d37877a
gh-104690: thread_run() checks for tstate dangling pointer (#109056)
thread_run() of _threadmodule.c now calls
_PyThreadState_CheckConsistency() to check if tstate is a dangling
pointer when Python is built in debug mode.

Rename ceval_gil.c is_tstate_valid() to
_PyThreadState_CheckConsistency() to reuse it in _threadmodule.c.
2023-09-08 11:50:46 +02:00
Victor Stinner b0edf3b98e
GH-91079: Rename C_RECURSION_LIMIT to Py_C_RECURSION_LIMIT (#108507)
Symbols of the C API should be prefixed by "Py_" to avoid conflict
with existing names in 3rd party C extensions on "#include <Python.h>".

test.pythoninfo now logs Py_C_RECURSION_LIMIT constant and other
_testcapi and _testinternalcapi constants.
2023-09-08 09:48:28 +00:00
Mark Shannon 15d4c9fabc
GH-108716: Turn off deep-freezing of code objects. (GH-108722) 2023-09-08 10:34:40 +01:00
Irit Katriel 96396962ce
gh-109094: remove unnecessary updates of frame->prev_instr in instrumentation functions (#109076) 2023-09-07 18:23:11 +01:00
Mark Shannon 0858328ca2
GH-108614: Add RESUME_CHECK instruction (GH-108630) 2023-09-07 14:39:03 +01:00
Victor Stinner fd5989bda1
gh-108753: _Py_PrintSpecializationStats() uses Py_hexdigits (#109040) 2023-09-07 04:47:57 +02:00
Dong-hee Na 3bfa24e29f
gh-107265: Remove all ENTER_EXECUTOR when execute _Py_Instrument (gh-108539) 2023-09-07 09:53:54 +09:00
Brandt Bucher 6971e40c2e
GH-104584: Restore frame->stacktop on optimizer error (GH-108953) 2023-09-06 13:59:50 -07:00
Victor Stinner a0773b89df
gh-108753: Enhance pystats (#108754)
Statistics gathering is now off by default. Use the "-X pystats"
command line option or set the new PYTHONSTATS environment variable
to 1 to turn statistics gathering on at Python startup.

Statistics are no longer dumped at exit if statistics gathering was
off or statistics have been cleared.

Changes:

* Add PYTHONSTATS environment variable.
* sys._stats_dump() now returns False if statistics are not dumped
  because they are all equal to zero.
* Add PyConfig._pystats member.
* Add tests on sys functions and on setting PyConfig._pystats to 1.
* Add Include/cpython/pystats.h and Include/internal/pycore_pystats.h
  header files.
* Rename '_py_stats' variable to '_Py_stats'.
* Exclude Include/cpython/pystats.h from the Py_LIMITED_API.
* Move pystats.h include from object.h to Python.h.
* Add _Py_StatsOn() and _Py_StatsOff() functions. Remove
  '_py_stats_struct' variable from the API: make it static in
  specialize.c.
* Document API in Include/pystats.h and Include/cpython/pystats.h.
* Complete pystats documentation in Doc/using/configure.rst.
* Don't write "all zeros" stats: if _stats_off() and _stats_clear()
  or _stats_dump() were called.
* _PyEval_Fini() now always call _Py_PrintSpecializationStats() which
  does nothing if stats are all zeros.

Co-authored-by: Michael Droettboom <mdboom@gmail.com>
2023-09-06 15:54:59 +00:00
Victor Stinner b298b395e8
gh-108765: Cleanup #include in Python/*.c files (#108977)
Mention one symbol imported by each #include.
2023-09-06 15:56:08 +02:00
Mark Shannon 5a2a046151
GH-108390: Prevent non-local events being set with sys.monitoring.set_local_events() (GH-108420) 2023-09-05 08:03:53 +01:00
Victor Stinner 676593859e
gh-106320: Remove private _PyErr_WriteUnraisableMsg() (#108863)
Move the private _PyErr_WriteUnraisableMsg() functions to the
internal C API (pycore_pyerrors.h).

Move write_unraisable_exc() from _testcapi to _testinternalcapi.
2023-09-05 01:54:55 +02:00
Mark Shannon 5a3672cb39
GH-108614: Remove TIER_ONE and TIER_TWO from _PUSH_FRAME (GH-108725) 2023-09-04 11:36:57 +01:00
Victor Stinner 03c4080c71
gh-108765: Python.h no longer includes <ctype.h> (#108831)
Remove <ctype.h> in C files which don't use it; only sre.c and
_decimal.c still use it.

Remove _PY_PORT_CTYPE_UTF8_ISSUE code from pyport.h:

* Code added by commit b5047fd019
  in 2004 for MacOSX and FreeBSD.
* Test removed by commit 52ddaefb6b
  in 2007, since Python str type now uses locale independent
  functions like Py_ISALPHA() and Py_TOLOWER() and the Unicode
  database.

Modules/_sre/sre.c replaces _PY_PORT_CTYPE_UTF8_ISSUE with new
functions: sre_isalnum(), sre_tolower(), sre_toupper().

Remove unused includes:

* _localemodule.c: remove <stdio.h>.
* getargs.c: remove <float.h>.
* dynload_win.c: remove <direct.h>, it no longer calls _getcwd()
  since commit fb1f68ed7c (in 2001).
2023-09-03 18:54:27 +02:00
Victor Stinner a52213bf83
gh-108765: pystrhex: Replace stdlib.h abs() with Py_ABS() (#108830) 2023-09-02 23:15:54 +02:00
Victor Stinner e7de0c5901
gh-108765: Python.h no longer includes <sys/time.h> (#108775)
Python.h no longer includes <time.h>, <sys/select.h> and <sys/time.h>
standard header files.

* Add <time.h> include to xxsubtype.c.
* Add <sys/time.h> include to posixmodule.c and semaphore.c.
* readline.c includes <sys/select.h> instead of <sys/time.h>.
* resource.c no longer includes <time.h> and <sys/time.h>.
2023-09-02 17:51:19 +02:00
Victor Stinner 594b00057e
gh-108765: Python.h no longer includes <unistd.h> (#108783) 2023-09-02 16:50:18 +02:00
Victor Stinner 578ebc5d5f
gh-108767: Replace ctype.h functions with pyctype.h functions (#108772)
Replace <ctype.h> locale dependent functions with Python "pyctype.h"
locale independent functions:

* Replace isalpha() with Py_ISALPHA().
* Replace isdigit() with Py_ISDIGIT().
* Replace isxdigit() with Py_ISXDIGIT().
* Replace tolower() with Py_TOLOWER().

Leave Modules/_sre/sre.c unchanged, it uses locale dependent
functions on purpose.

Include explicitly <ctype.h> in _decimal.c to get isascii().
2023-09-01 18:36:53 +02:00
Victor Stinner b936cf4fe0
gh-108634: PyInterpreterState_New() no longer calls Py_FatalError() (#108748)
pycore_create_interpreter() now returns a status, rather than
calling Py_FatalError().

* PyInterpreterState_New() now calls Py_ExitStatusException() instead
  of calling Py_FatalError() directly.
* Replace Py_FatalError() with PyStatus in init_interpreter() and
  _PyObject_InitState().
* _PyErr_SetFromPyStatus() now raises RuntimeError, instead of
  ValueError. It can now call PyErr_NoMemory(), raise MemoryError,
  if it detects _PyStatus_NO_MEMORY() error message.
2023-09-01 12:43:30 +02:00
Irit Katriel 844f4c2e12
gh-108727: Fix segfault due to missing tp_dealloc definition for CounterOptimizer_Type (GH-108734) 2023-09-01 10:16:09 +01:00
Victor Stinner ad73674283
gh-107603: Argument Clinic: Only include pycore_gc.h if needed (#108726)
Argument Clinic now only includes pycore_gc.h if PyGC_Head is needed,
and only includes pycore_runtime.h if _Py_ID() is needed.

* Add 'condition' optional argument to Clinic.add_include().
* deprecate_keyword_use() includes pycore_runtime.h when using
  the _PyID() function.
* Fix rendering of includes: comments start at the column 35.
* Mark PC/clinic/_wmimodule.cpp.h and
  "Objects/stringlib/clinic/*.h.h" header files as generated in
  .gitattributes.

Effects:

* 42 header files generated by AC no longer include the internal C
  API, instead of 4 header files before. For example,
  Modules/clinic/_abc.c.h no longer includes the internal C API.
* Fix _testclinic_depr.c.h: it now always includes pycore_runtime.h
  to get _Py_ID().
2023-08-31 23:42:34 +02:00
Victor Stinner 13a00078b8
gh-108634: Py_TRACE_REFS uses a hash table (#108663)
Python built with "configure --with-trace-refs" (tracing references)
is now ABI compatible with Python release build and debug build.
Moreover, it now also supports the Limited API.

Change Py_TRACE_REFS build:

* Remove _PyObject_EXTRA_INIT macro.
* The PyObject structure no longer has two extra members (_ob_prev
  and _ob_next).
* Use a hash table (_Py_hashtable_t) to trace references (all
  objects): PyInterpreterState.object_state.refchain.
* Py_TRACE_REFS build is now ABI compatible with release build and
  debug build.
* Limited C API extensions can now be built with Py_TRACE_REFS:
  xxlimited, xxlimited_35, _testclinic_limited.
* No longer rename PyModule_Create2() and PyModule_FromDefAndSpec2()
  functions to PyModule_Create2TraceRefs() and
  PyModule_FromDefAndSpec2TraceRefs().
* _Py_PrintReferenceAddresses() is now called before
  finalize_interp_delete() which deletes the refchain hash table.
* test_tracemalloc find_trace() now also filters by size to ignore
  the memory allocated by _PyRefchain_Trace().

Test changes for Py_TRACE_REFS:

* Add test.support.Py_TRACE_REFS constant.
* Add test_sys.test_getobjects() to test sys.getobjects() function.
* test_exceptions skips test_recursion_normalizing_with_no_memory()
  and test_memory_error_in_PyErr_PrintEx() if Python is built with
  Py_TRACE_REFS.
* test_repl skips test_no_memory().
* test_capi skisp test_set_nomemory().
2023-08-31 18:33:34 +02:00
Mark Shannon 059bd4d299
GH-108614: Remove non-debug uses of #if TIER_ONE and #if TIER_TWO from _POP_FRAME op. (GH-108685) 2023-08-31 11:34:52 +01:00
Victor Stinner 9c03215a3e
gh-107149: Make PyUnstable_ExecutableKinds public (#108440)
Move PyUnstable_ExecutableKinds and associated macros from the
internal C API to the public C API.

Rename constants: replace "PY_" prefix with "PyUnstable_" prefix.
2023-08-31 09:56:06 +02:00
Carl Meyer d52c4482a8
gh-108654: restore comprehension locals before handling exception (#108659)
Co-authored-by: Dong-hee Na <donghee.na92@gmail.com>
2023-08-30 17:50:50 -06:00
Guido van Rossum 59e46932c8
gh-108488: Initialize JUMP_BACKWARD cache to 0, not 17 (#108591)
This mis-initialization caused the executor optimization to kick in sooner than intended. It also set the lower 4 bits of the counter to `1` -- those bits are supposed to be reserved (the actual counter is in the upper 12 bits).
2023-08-29 18:14:56 +00:00
Guido van Rossum 4f22152713
gh-107557: Remove unnecessary SAVE_IP instructions (#108583)
Also remove NOP instructions.

The "stubs" are not optimized in this fashion (their SAVE_IP should always be preserved since it's where to jump next, and they don't contain NOPs by their nature).
2023-08-29 16:51:51 +00:00
Victor Stinner 15c5a50797
gh-106320: Remove private pythonrun API (#108599)
Remove these private functions from the public C API:

* _PyRun_AnyFileObject()
* _PyRun_InteractiveLoopObject()
* _PyRun_SimpleFileObject()
* _Py_SourceAsString()

Move them to the internal C API: add a new pycore_pythonrun.h header
file. No longer export these functions.
2023-08-29 04:18:52 +02:00
Victor Stinner 0b6a4cb0df
gh-107149: Rename _PyUnstable_GetUnaryIntrinsicName() function (#108441)
* Rename _PyUnstable_GetUnaryIntrinsicName() to
  PyUnstable_GetUnaryIntrinsicName()
* Rename _PyUnstable_GetBinaryIntrinsicName()
  to PyUnstable_GetBinaryIntrinsicName().
2023-08-29 01:42:24 +02:00
Guido van Rossum 47d7eba889
gh-108487: Move assert(self != NULL) down beyond DEOPT_IF() (#108510) 2023-08-28 10:17:00 -07:00
Dong-hee Na 6cb48f0495
gh-107265: Fix initialize/remove_tools for ENTER_EXECUTOR case (gh-108482) 2023-08-27 12:31:29 +09:00
Serhiy Storchaka 2b15536fa9
gh-107913: Fix possible losses of OSError error codes (GH-107930)
Functions like PyErr_SetFromErrno() and SetFromWindowsErr() should be
called immediately after using the C API which sets errno or the Windows
error code.
2023-08-27 00:35:06 +03:00
Victor Stinner 8ba4714611
gh-106320: Remove private AC converter functions (#108505)
Move these private functions to the internal C API
(pycore_abstract.h):

* _Py_convert_optional_to_ssize_t()
* _PyNumber_Index()

Argument Clinic now emits #include "pycore_abstract.h" when these
functions are used.

The parser of the c-analyzer tool now uses a list of files which use
the limited C API, rather than a list of files using the internal C
API.
2023-08-26 04:05:17 +02:00
Brandt Bucher 4eae1e5342
GH-106581: Fix instrumentation in tier 2 (GH-108493) 2023-08-25 19:12:59 +00:00
Dong-hee Na 66b4d9c9f0
gh-107265: Revert "Ensure _PyCode_Quicken does not handle ENTER_EXECUTOR" (#108485)
This reverts commit d6ac5c7b10.

Reason: the assert we just added could be triggered (see issue).
2023-08-25 15:23:39 +00:00
Victor Stinner e59a95238b
gh-108444: Remove _PyLong_AsInt() function (#108461)
* Update Parser/asdl_c.py to regenerate Python/Python-ast.c.
* Remove _PyLong_AsInt() alias to PyLong_AsInt().
2023-08-25 11:13:59 +02:00
Guido van Rossum ddf66b54ed
gh-106581: Split CALL_BOUND_METHOD_EXACT_ARGS into uops (#108462)
Instead of using `GO_TO_INSTRUCTION(CALL_PY_EXACT_ARGS)` we just add the macro elements of the latter to the macro for the former. This requires lengthening the uops array in struct opcode_macro_expansion. (It also required changes to stacking.py that were merged already.)
2023-08-24 17:36:00 -07:00
Victor Stinner 546cab8444
gh-106320: Remove private _PyTraceback functions (#108453)
Move private functions to the internal C API (pycore_traceback.h):

* _Py_DisplaySourceLine()
* _PyTraceback_Add()
2023-08-24 23:35:47 +00:00
Dong-hee Na d6ac5c7b10
gh-107265: Ensure _PyCode_Quicken does not handle ENTER_EXECUTOR (gh-108460) 2023-08-24 23:03:26 +00:00
Victor Stinner b32d4cad15
gh-108444: Replace _PyLong_AsInt() with PyLong_AsInt() (#108459)
Change generated by the command:

sed -i -e 's!_PyLong_AsInt!PyLong_AsInt!g' \
    $(find -name "*.c" -o -name "*.h")
2023-08-25 01:01:30 +02:00
Victor Stinner 4e5a7284ee
gh-108444: Argument Clinic uses PyLong_AsInt() (#108458)
Argument Clinic now uses the new public PyLong_AsInt(), rather than
the old name _PyLong_AsInt().
2023-08-25 00:51:22 +02:00
Victor Stinner a071ecb4d1
gh-106320: Remove private _PySys functions (#108452)
Move private functions to the internal C API (pycore_sysmodule.h):

* _PySys_GetAttr()
* _PySys_GetSizeOf()

No longer export most of these functions.

Fix also a typo in Include/cpython/optimizer.h: add a missing space.
2023-08-24 20:02:09 +00:00
Victor Stinner 26893016a7
gh-106320: Remove private _PyDict functions (#108449)
Move private functions to the internal C API (pycore_dict.h):

* _PyDictView_Intersect()
* _PyDictView_New()
* _PyDict_ContainsId()
* _PyDict_DelItemId()
* _PyDict_DelItem_KnownHash()
* _PyDict_GetItemIdWithError()
* _PyDict_GetItem_KnownHash()
* _PyDict_HasSplitTable()
* _PyDict_NewPresized()
* _PyDict_Next()
* _PyDict_Pop()
* _PyDict_SetItemId()
* _PyDict_SetItem_KnownHash()
* _PyDict_SizeOf()

No longer export most of these functions.

Move also the _PyDictViewObject structure to the internal C API.

Move dict_getitem_knownhash() function from _testcapi to the
_testinternalcapi extension. Update test_capi.test_dict for this
change.
2023-08-24 20:01:50 +00:00
Guido van Rossum 88941d665f
gh-106581: Fix two bugs in the code generator's copy optimization (#108380)
I was comparing the last preceding poke with the *last* peek,
rather than the *first* peek.

Unfortunately this bug obscured another bug:
When the last preceding poke is UNUSED, the first peek disappears,
leaving the variable unassigned. This is how I fixed it:

- Rename CopyEffect to CopyItem.
- Change CopyItem to contain StackItems instead of StackEffects.
- Update those StackItems when adjusting the manager higher or lower.
- Assert that those StackItems' offsets are equivalent.
- Other clever things.

---------

Co-authored-by: Irit Katriel <1055913+iritkatriel@users.noreply.github.com>
2023-08-24 19:10:51 +00:00
Victor Stinner c55e73112c
gh-106320: Remove private PyLong C API functions (#108429)
Remove private PyLong C API functions:

* _PyLong_AsByteArray()
* _PyLong_DivmodNear()
* _PyLong_Format()
* _PyLong_Frexp()
* _PyLong_FromByteArray()
* _PyLong_FromBytes()
* _PyLong_GCD()
* _PyLong_Lshift()
* _PyLong_Rshift()

Move these functions to the internal C API. No longer export
_PyLong_FromBytes() function.
2023-08-24 18:53:50 +02:00
Victor Stinner 52c6a6e48a
gh-108308: Remove _PyDict_GetItemStringWithError() function (#108426)
Remove the internal _PyDict_GetItemStringWithError() function. It can
now be replaced with the new public PyDict_ContainsString() and
PyDict_GetItemStringRef() functions.

getargs.c now now uses a strong reference for current_arg.
find_keyword() returns a strong reference.
2023-08-24 17:34:22 +02:00
Victor Stinner 6726626646
gh-108314: Add PyDict_ContainsString() function (#108323) 2023-08-24 15:59:12 +02:00
Victor Stinner ec3527d196
gh-108308: config_dict_get() uses PyDict_GetItemRef() (#108371)
Replace _PyDict_GetItemStringWithError() with PyDict_GetItemRef() in
config_dict_get() to get a strong reference to the item.
2023-08-23 23:12:08 +02:00
Victor Stinner 4dc9f48930
gh-108308: Replace _PyDict_GetItemStringWithError() (#108372)
Replace _PyDict_GetItemStringWithError() calls with
PyDict_GetItemStringRef() which returns a strong reference to the
item.

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
2023-08-23 22:59:00 +02:00
Irit Katriel 72119d16a5
gh-105481: remove regen-opcode. Generated _PyOpcode_Caches in regen-cases. (#108367) 2023-08-23 18:39:00 +01:00
Dong-hee Na 2135bcd3ca
gh-107265: Ensure de_instrument does not handle ENTER_EXECUTOR (#108366) 2023-08-23 08:45:20 -07:00
Victor Stinner f5559f38d9
gh-108308: Replace PyDict_GetItem() with PyDict_GetItemRef() (#108309)
Replace PyDict_GetItem() calls with PyDict_GetItemRef()
or PyDict_GetItemWithError() to handle errors.

* Replace PyLong_AS_LONG() with _PyLong_AsInt()
  and check for errors.
* Check for PyDict_Contains() error.
* pycore_init_builtins() checks for _PyType_Lookup() failure.
2023-08-23 17:40:26 +02:00
Irit Katriel 2dfbd4f36d
gh-108113: Make it possible to optimize an AST (#108282) 2023-08-23 09:01:17 +01:00
Victor Stinner 615f6e946d
gh-106320: Remove _PyDict_GetItemStringWithError() function (#108313)
Remove private _PyDict_GetItemStringWithError() function of the
public C API: the new PyDict_GetItemStringRef() can be used instead.

* Move private _PyDict_GetItemStringWithError() to the internal C API.
* _testcapi get_code_extra_index() uses PyDict_GetItemStringRef().
  Avoid using private functions in _testcapi which tests the public C
  API.
2023-08-22 18:17:25 +00:00
Victor Stinner 6541fe4ad7
Ignore _Py_write_noraise() result: cast to (void) (#108291)
Code using _Py_write_noraise() usually cannot report. Ignore errors
is the least surprising behavior for users.
2023-08-22 14:28:20 +00:00
Irit Katriel a1cc74c4ee
gh-107901: Fix missing line number on BACKWARD_JUMP at the end of a for loop (#108242) 2023-08-21 23:44:31 +01:00
Irit Katriel 10a91d7e98
gh-108113: Make it possible to create an optimized AST (#108154) 2023-08-21 16:31:30 +00:00
Serhiy Storchaka 80bdebdd85
gh-107916: Save the error code before decoding the filename in PyErr_SetFromErrnoWithFilename() etc (GH-107929) 2023-08-21 14:16:31 +03:00
Nikita Sobolev db6dc6ce41
gh-107526: Revert "gh-100357: Convert several functions in bltinsmodule to AC" (#107542) 2023-08-20 17:54:10 -07:00
Serhiy Storchaka 633ea217a8
gh-107915: Handle errors in C API functions PyErr_Set*() and PyErr_Format() (GH-107918)
Such C API functions as PyErr_SetString(), PyErr_Format(),
PyErr_SetFromErrnoWithFilename() and many others no longer crash or
ignore errors if it failed to format the error message or decode the
filename. Instead, they keep a corresponding error.
2023-08-19 14:51:03 +03:00
Victor Stinner 3ff5ef2ad3
gh-108014: Add Py_IsFinalizing() function (#108032)
Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
2023-08-18 12:34:41 +02:00
Pablo Galindo Salgado 75b3db8445
gh-107944: Improve error message for function calls with bad keyword arguments (#107969) 2023-08-17 19:39:42 +01:00
Guido van Rossum 61c7249759
gh-106581: Project through calls (#108067)
This finishes the work begun in gh-107760. When, while projecting a superblock, we encounter a call to a short, simple function, the superblock will now enter the function using `_PUSH_FRAME`, continue through it, and leave it using `_POP_FRAME`, and then continue through the original code. Multiple frame pushes and pops are even possible. It is also possible to stop appending to the superblock in the middle of a called function, when running out of space or encountering an unsupported bytecode.
2023-08-17 11:29:58 -07:00
Mark Shannon 006e44f950
GH-108035: Remove the _PyCFrame struct as it is no longer needed for performance. (GH-108036) 2023-08-17 11:16:03 +01:00
Guido van Rossum dc8fdf5fd5
gh-106581: Split CALL_PY_EXACT_ARGS into uops (#107760)
* Split `CALL_PY_EXACT_ARGS` into uops

This is only the first step for doing `CALL` in Tier 2.
The next step involves tracing into the called code object and back.
After that we'll have to do the remaining `CALL` specialization.
Finally we'll have to deal with `KW_NAMES`.

Note: this moves setting `frame->return_offset` directly in front of
`DISPATCH_INLINED()`, to make it easier to move it into `_PUSH_FRAME`.
2023-08-16 16:26:43 -07:00
Irit Katriel 665a4391e1
gh-105481: generate op IDs from bytecode.c instead of hard coding them in opcode.py (#107971) 2023-08-16 22:25:18 +00:00
Nikita Sobolev bdd8ddfda1
gh-105724: Add location information to assert errors (GH-105935) 2023-08-16 11:35:38 +01:00
Ken Jin e28b0dc86d
gh-107557: Setup abstract interpretation (#107847)
Co-authored-by: Guido van Rossum <gvanrossum@users.noreply.github.com>
Co-authored-by: Jules <57632293+juliapoo@users.noreply.github.com>
2023-08-15 18:04:17 +00:00
Steve Dower 34e1917912
gh-106242: Minor fixup to avoid compiler warnings (GH-107983) 2023-08-15 17:02:32 +00:00
Irit Katriel 971a4c2751
gh-103082: remove assumption that INSTRUMENTED_LINE is the last instrumented opcode (#107978) 2023-08-15 16:40:05 +01:00
Finn Womack 0932272431
gh-106242: Fix path truncation in os.path.normpath (GH-106816) 2023-08-15 16:33:00 +01:00
Irit Katriel 608927b014
gh-103082: use IS_VALID_OPCODE instead of _PyOpcode_OpName to check if an opcode is defined (#107882) 2023-08-14 10:51:50 +01:00
Dong-hee Na bf707749e8
gh-106797: Remove warning logs from Python/generated_cases.c.h and executor_cases.c.h (gh-107889)
gh-106797: Remove warning logs from Python/generated_cases.c.h
2023-08-13 04:36:46 +09:00
Mark Shannon 37d8b904f8
GH-107674: Avoid allocating boxed ints for sys.settrace line events (GH-107780) 2023-08-10 13:35:02 +01:00
Irit Katriel bafedfbebd
gh-106149: move CFG and basicblock definitions into flowgraph.c, use them as opaque types in compile.c (#107639) 2023-08-10 13:03:47 +01:00
Mark Shannon 494e3d4436
GH-107774: Add missing audit event for PEP 669 (GH-107775) 2023-08-10 12:29:06 +01:00
Brandt Bucher 326f0ba1c5
GH-106485: Dematerialize instance dictionaries when possible (GH-106539) 2023-08-09 19:14:50 +00:00
Brandt Bucher a9caf9cf90
GH-105848: Simplify the arrangement of CALL's stack (GH-107788) 2023-08-09 18:19:39 +00:00
Mark Shannon 52fbcf61b5
GH-107724: Fix the signature of PY_THROW callback functions. (GH-107725) 2023-08-09 09:30:50 +01:00
Brandt Bucher ea72c6fe3b
GH-107596: Specialize str[int] (GH-107597) 2023-08-08 13:42:43 -07:00
Guido van Rossum 328d925244
gh-107758: Improvements to lltrace feature (#107757)
- The `dump_stack()` method could call a `__repr__` method implemented in Python,
  causing (infinite) recursion.
  I rewrote it to only print out the values for some fundamental types (`int`, `str`, etc.);
  for everything else it just prints `<type_name @ 0xdeadbeef>`.

- The lltrace-like feature for uops wrote to `stderr`, while the one in `ceval.c` writes to `stdout`;
  I changed the uops to write to stdout as well.
2023-08-07 21:36:25 -07:00
Eric Snow 430632d6f7
gh-107630: Initialize Each Interpreter's refchain Properly (gh-107733)
This finishes fixing the crashes in Py_TRACE_REFS builds.  We missed this part in gh-107567.
2023-08-07 13:14:56 -06:00
Ivin Lee 4e6fac7fcc
gh-106608: make uop trace variable length (#107531)
Executors are now more like tuples.
2023-08-04 21:10:46 -07:00
Brandt Bucher 05a824f294
GH-84436: Skip refcounting for known immortals (GH-107605) 2023-08-04 16:24:50 -07:00
Guido van Rossum 400835ea16
gh-106812: Refactor cases_generator to allow uops with array stack effects (#107564)
Introducing a new file, stacking.py, that takes over several responsibilities related to symbolic evaluation of push/pop operations, with more generality.
2023-08-04 09:35:56 -07:00
Mark Shannon 2ba7c7f7b1
Add some GC stats to Py_STATS (GH-107581) 2023-08-04 10:34:23 +01:00
Mark Shannon fa45958450
GH-107263: Increase C stack limit for most functions, except _PyEval_EvalFrameDefault() (GH-107535)
* Set C recursion limit to 1500, set cost of eval loop to 2 frames, and compiler mutliply to 2.
2023-08-04 10:10:29 +01:00
Eric Snow 58ef741867
gh-107080: Fix Py_TRACE_REFS Crashes Under Isolated Subinterpreters (gh-107567)
The linked list of objects was a global variable, which broke isolation between interpreters, causing crashes. To solve this, we've moved the linked list to each interpreter.
2023-08-03 19:51:08 +00:00
Eric Snow 017f047183
gh-107471: Fix Refleaks in test_import (gh-107569)
gh-107184 introduced a refleak in test_import.SubinterpImportTests (specifically test_singlephase_check_with_setting_and_override and test_single_init_extension_compat).  We fix it here by making sure _testsinglephase is removed from sys.modules whenever we clear the runtime's internal state for the module.

The underlying problem is strictly contained in the internal function _PyImport_ClearExtension() (AKA _testinternalcapi.clear_extension()), which is only used in tests.

(This also fixes an intermittent segfault introduced in the same place, in test_disallowed_reimport.)
2023-08-02 20:55:09 +00:00
Mark Shannon 0d30a5a409
GH-100964: Break cycles involving exception state when returning from generator (GH-107563) 2023-08-02 18:44:20 +01:00
Irit Katriel 2bd04d4234
gh-105481: combine regen-opcode-targets with regen-opcode to avoid calculating the specialized opcodes in two places (#107540) 2023-08-01 21:05:48 +01:00
Brandt Bucher dfb55d9d7f
Use tstate->interp to get the interpreter state in bytecodes.c (GH-107506) 2023-07-31 14:18:38 -07:00
Brandt Bucher 5e584eb704
GH-104584: Fix incorrect uoperands (GH-107513) 2023-07-31 21:16:57 +00:00
Guido van Rossum 5eb80a61f5
GH-104909: Move unused cache entries from uops to macros (#107444)
There's no need to use a dummy uop to skip unused cache entries. The macro syntax lets you write `unused/1` instead.

Similarly, move `unused/5` from op `_LOAD_ATTR_INSTANCE_VALUE` to macro `LOAD_ATTR_INSTANCE_VALUE`.
2023-07-31 08:55:33 -07:00
Georg Brandl f57b9fd2b6
no-issue: Fix typo in import.c (gh-107498) 2023-07-31 12:07:17 +00:00
Eric Snow 8ba4df91ae
gh-105699: Use a _Py_hashtable_t for the PyModuleDef Cache (gh-106974)
This fixes a crasher due to a race condition, triggered infrequently when two isolated (own GIL) subinterpreters simultaneously initialize their sys or builtins modules.  The crash happened due the combination of the "detached" thread state we were using and the "last holder" logic we use for the GIL.  It turns out it's tricky to use the same thread state for different threads.  Who could have guessed?

We solve the problem by eliminating the one object we were still sharing between interpreters.  We replace it with a low-level hashtable, using the "raw" allocator to avoid tying it to the main interpreter.

We also remove the accommodations for "detached" thread states, which were a dubious idea to start with.
2023-07-28 14:39:08 -06:00
Eric Snow 8bdae1424b
gh-101524: Only Use Public C-API in the _xxsubinterpreters Module (gh-107359)
The _xxsubinterpreters module should not rely on internal API.  Some of the functions it uses were recently moved there however.  Here we move them back (and expose them properly).
2023-07-27 15:30:16 -06:00
Eric Snow 75c974f535
gh-104621: Check for Incompatible Extensions in import_find_extension() (gh-107184)
This fixes a bug where incompatible modules could still be imported if attempted multiple times.
2023-07-27 15:08:38 -06:00