Skip to content

Commit 60132db

Browse files
vstinnerpicnixz
andauthored
[3.14] gh-151218: Replace sys.flags in PyConfig_Set() (#151402) (#151553)
gh-151218: Replace sys.flags in PyConfig_Set() (#151402) PyConfig_Set() and sys.set_int_max_str_digits() now replace sys.flags (create a new object), instead of modifying sys.flags in-place. Modifying sys.flags in-place can lead to data races when multiple threads are reading or writing sys.flags in parallel. Use _Py_atomic functions to get and set max_str_digits members. (cherry picked from commit b16d23f) Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
1 parent af459e5 commit 60132db

9 files changed

Lines changed: 111 additions & 23 deletions

File tree

Doc/c-api/init_config.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,10 @@ Some options are read from the :mod:`sys` attributes. For example, the option
623623
624624
.. versionadded:: 3.14
625625
626+
.. versionchanged:: next
627+
The function now replaces :data:`sys.flags` (create a new object),
628+
instead of modifying :data:`sys.flags` in-place.
629+
626630
627631
.. _pyconfig_api:
628632

Lib/test/test_capi/test_config.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,9 +355,11 @@ def expect_bool_not(value):
355355
for value in new_values:
356356
expected, expect_flag = expect_func(value)
357357

358+
old_flags = sys.flags
358359
config_set(name, value)
359360
self.assertEqual(config_get(name), expected)
360361
self.assertEqual(getattr(sys.flags, sys_flag), expect_flag)
362+
self.assertIsNot(sys.flags, old_flags)
361363
if name == "write_bytecode":
362364
self.assertEqual(getattr(sys, "dont_write_bytecode"),
363365
expect_flag)
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import sys
2+
import unittest
3+
from test.support import threading_helper
4+
5+
6+
class SysModuleTest(unittest.TestCase):
7+
def test_int_max_str_digits_thread(self):
8+
# gh-151218: Check that it's safe to call get_int_max_str_digits() and
9+
# set_int_max_str_digits() in parallel. Previously, this test triggered
10+
# warnings in TSan on a free threaded build.
11+
12+
old_limit = sys.get_int_max_str_digits()
13+
self.addCleanup(sys.set_int_max_str_digits, old_limit)
14+
15+
def worker(worker_id):
16+
if not worker_id:
17+
for i in range (20_000):
18+
sys.get_int_max_str_digits()
19+
else:
20+
for i in range (20_000):
21+
sys.set_int_max_str_digits(4300 + (i & 7))
22+
23+
workers = [lambda: worker(i) for i in range(5)]
24+
threading_helper.run_concurrently(workers)
25+
26+
27+
if __name__ == "__main__":
28+
unittest.main()

Lib/test/test_sys.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1336,6 +1336,26 @@ def test_pystats(self):
13361336
def test_disable_gil_abi(self):
13371337
self.assertEqual('t' in sys.abiflags, support.Py_GIL_DISABLED)
13381338

1339+
def test_int_max_str_digits(self):
1340+
old_limit = sys.get_int_max_str_digits()
1341+
self.assertIsInstance(old_limit, int)
1342+
self.assertGreaterEqual(old_limit, 0)
1343+
self.addCleanup(sys.set_int_max_str_digits, old_limit)
1344+
1345+
sys.set_int_max_str_digits(0)
1346+
self.assertEqual(sys.get_int_max_str_digits(), 0)
1347+
1348+
sys.set_int_max_str_digits(2_048)
1349+
self.assertEqual(sys.get_int_max_str_digits(), 2_048)
1350+
1351+
with self.assertRaises(ValueError):
1352+
# the minimum is 640 digits
1353+
sys.set_int_max_str_digits(5)
1354+
with self.assertRaises(ValueError):
1355+
sys.set_int_max_str_digits(-2)
1356+
with self.assertRaises(TypeError):
1357+
sys.set_int_max_str_digits(2_048.0)
1358+
13391359

13401360
@test.support.cpython_only
13411361
class UnraisableHookTest(unittest.TestCase):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:c:func:`PyConfig_Set` and :func:`sys.set_int_max_str_digits` now replace
2+
:data:`sys.flags` (create a new object), instead of modifying :data:`sys.flags`
3+
in-place. Patch by Victor Stinner.

Objects/longobject.c

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2049,7 +2049,7 @@ long_to_decimal_string_internal(PyObject *aa,
20492049
if (size_a >= 10 * _PY_LONG_MAX_STR_DIGITS_THRESHOLD
20502050
/ (3 * PyLong_SHIFT) + 2) {
20512051
PyInterpreterState *interp = _PyInterpreterState_GET();
2052-
int max_str_digits = interp->long_state.max_str_digits;
2052+
int max_str_digits = _Py_atomic_load_int(&interp->long_state.max_str_digits);
20532053
if ((max_str_digits > 0) &&
20542054
(max_str_digits / (3 * PyLong_SHIFT) <= (size_a - 11) / 10)) {
20552055
PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_STR,
@@ -2130,7 +2130,7 @@ long_to_decimal_string_internal(PyObject *aa,
21302130
}
21312131
if (strlen > _PY_LONG_MAX_STR_DIGITS_THRESHOLD) {
21322132
PyInterpreterState *interp = _PyInterpreterState_GET();
2133-
int max_str_digits = interp->long_state.max_str_digits;
2133+
int max_str_digits = _Py_atomic_load_int(&interp->long_state.max_str_digits);
21342134
Py_ssize_t strlen_nosign = strlen - negative;
21352135
if ((max_str_digits > 0) && (strlen_nosign > max_str_digits)) {
21362136
Py_DECREF(scratch);
@@ -2942,7 +2942,7 @@ long_from_string_base(const char **str, int base, PyLongObject **res)
29422942
* quadratic algorithm. */
29432943
if (digits > _PY_LONG_MAX_STR_DIGITS_THRESHOLD) {
29442944
PyInterpreterState *interp = _PyInterpreterState_GET();
2945-
int max_str_digits = interp->long_state.max_str_digits;
2945+
int max_str_digits = _Py_atomic_load_int(&interp->long_state.max_str_digits);
29462946
if ((max_str_digits > 0) && (digits > max_str_digits)) {
29472947
PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_INT,
29482948
max_str_digits, digits);

Python/initconfig.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4374,7 +4374,8 @@ config_get(const PyConfig *config, const PyConfigSpec *spec,
43744374

43754375
if (strcmp(spec->name, "int_max_str_digits") == 0) {
43764376
PyInterpreterState *interp = _PyInterpreterState_GET();
4377-
return PyLong_FromLong(interp->long_state.max_str_digits);
4377+
int maxdigits = _Py_atomic_load_int(&interp->long_state.max_str_digits);
4378+
return PyLong_FromLong(maxdigits);
43784379
}
43794380
}
43804381

Python/pylifecycle.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,8 @@ interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
417417
}
418418
}
419419

420-
tstate->interp->long_state.max_str_digits = config->int_max_str_digits;
420+
_Py_atomic_store_int(&tstate->interp->long_state.max_str_digits,
421+
config->int_max_str_digits);
421422

422423
// Update the sys module for the new configuration
423424
if (_PySys_UpdateConfig(tstate) < 0) {

Python/sysmodule.c

Lines changed: 47 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1899,7 +1899,8 @@ sys_get_int_max_str_digits_impl(PyObject *module)
18991899
/*[clinic end generated code: output=0042f5e8ae0e8631 input=61bf9f99bc8b112d]*/
19001900
{
19011901
PyInterpreterState *interp = _PyInterpreterState_GET();
1902-
return PyLong_FromLong(interp->long_state.max_str_digits);
1902+
int maxdigits = _Py_atomic_load_int(&interp->long_state.max_str_digits);
1903+
return PyLong_FromLong(maxdigits);
19031904
}
19041905

19051906

@@ -3434,14 +3435,39 @@ sys_set_flag(PyObject *flags, Py_ssize_t pos, PyObject *value)
34343435
int
34353436
_PySys_SetFlagObj(Py_ssize_t pos, PyObject *value)
34363437
{
3437-
PyObject *flags = _PySys_GetRequiredAttrString("flags");
3438-
if (flags == NULL) {
3439-
return -1;
3438+
PyObject *new_flags = NULL;
3439+
PyObject *flags_str = &_Py_ID(flags); // immortal ref
3440+
3441+
PyObject *old_flags = _PySys_GetRequiredAttr(flags_str);
3442+
if (old_flags == NULL) {
3443+
goto error;
34403444
}
34413445

3442-
sys_set_flag(flags, pos, value);
3443-
Py_DECREF(flags);
3444-
return 0;
3446+
new_flags = PyStructSequence_New(&FlagsType);
3447+
if (new_flags == NULL) {
3448+
goto error;
3449+
}
3450+
3451+
for (Py_ssize_t i = 0; i < (Py_ssize_t)(Py_ARRAY_LENGTH(flags_fields) - 1); i++) {
3452+
if (i != pos) {
3453+
PyObject *old_value;
3454+
old_value = PyStructSequence_GET_ITEM(old_flags, i); // borrowed ref
3455+
sys_set_flag(new_flags, i, old_value);
3456+
}
3457+
else {
3458+
sys_set_flag(new_flags, pos, value);
3459+
}
3460+
}
3461+
3462+
int res = _PySys_SetAttr(flags_str, new_flags);
3463+
Py_DECREF(old_flags);
3464+
Py_DECREF(new_flags);
3465+
return res;
3466+
3467+
error:
3468+
Py_XDECREF(old_flags);
3469+
Py_XDECREF(new_flags);
3470+
return -1;
34453471
}
34463472

34473473

@@ -3465,8 +3491,6 @@ set_flags_from_config(PyInterpreterState *interp, PyObject *flags)
34653491
const PyPreConfig *preconfig = &interp->runtime->preconfig;
34663492
const PyConfig *config = _PyInterpreterState_GetConfig(interp);
34673493

3468-
// _PySys_UpdateConfig() modifies sys.flags in-place:
3469-
// Py_XDECREF() is needed in this case.
34703494
Py_ssize_t pos = 0;
34713495
#define SetFlagObj(expr) \
34723496
do { \
@@ -3889,7 +3913,7 @@ _PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
38893913
/* implementation */
38903914
SET_SYS("implementation", make_impl_info(version_info));
38913915

3892-
// sys.flags: updated in-place later by _PySys_UpdateConfig()
3916+
// sys.flags: updated later by _PySys_UpdateConfig()
38933917
ENSURE_INFO_TYPE(FlagsType, flags_desc);
38943918
SET_SYS("flags", make_flags(tstate->interp));
38953919

@@ -4007,16 +4031,21 @@ _PySys_UpdateConfig(PyThreadState *tstate)
40074031
#undef COPY_LIST
40084032
#undef COPY_WSTR
40094033

4010-
// sys.flags
4011-
PyObject *flags = _PySys_GetRequiredAttrString("flags");
4012-
if (flags == NULL) {
4034+
// replace sys.flags
4035+
PyObject *new_flags = PyStructSequence_New(&FlagsType);
4036+
if (new_flags == NULL) {
40134037
return -1;
40144038
}
4015-
if (set_flags_from_config(interp, flags) < 0) {
4016-
Py_DECREF(flags);
4039+
if (set_flags_from_config(interp, new_flags) < 0) {
4040+
Py_DECREF(new_flags);
4041+
return -1;
4042+
}
4043+
4044+
res = _PySys_SetAttr(&_Py_ID(flags), new_flags);
4045+
Py_DECREF(new_flags);
4046+
if (res < 0) {
40174047
return -1;
40184048
}
4019-
Py_DECREF(flags);
40204049

40214050
SET_SYS("dont_write_bytecode", PyBool_FromLong(!config->write_bytecode));
40224051

@@ -4517,7 +4546,7 @@ _PySys_SetIntMaxStrDigits(int maxdigits)
45174546
// Set PyInterpreterState.long_state.max_str_digits
45184547
// and PyInterpreterState.config.int_max_str_digits.
45194548
PyInterpreterState *interp = _PyInterpreterState_GET();
4520-
interp->long_state.max_str_digits = maxdigits;
4521-
interp->config.int_max_str_digits = maxdigits;
4549+
_Py_atomic_store_int(&interp->long_state.max_str_digits, maxdigits);
4550+
_Py_atomic_store_int(&interp->config.int_max_str_digits, maxdigits);
45224551
return 0;
45234552
}

0 commit comments

Comments
 (0)