Skip to content

Commit b16d23f

Browse files
vstinnerpicnixz
andauthored
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. Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
1 parent 2ce2600 commit b16d23f

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
@@ -356,9 +356,11 @@ def expect_bool_not(value):
356356
for value in new_values:
357357
expected, expect_flag = expect_func(value)
358358

359+
old_flags = sys.flags
359360
config_set(name, value)
360361
self.assertEqual(config_get(name), expected)
361362
self.assertEqual(getattr(sys.flags, sys_flag), expect_flag)
363+
self.assertIsNot(sys.flags, old_flags)
362364
if name == "write_bytecode":
363365
self.assertEqual(getattr(sys, "dont_write_bytecode"),
364366
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
@@ -1349,6 +1349,26 @@ def test_pystats(self):
13491349
def test_disable_gil_abi(self):
13501350
self.assertEqual('t' in sys.abiflags, support.Py_GIL_DISABLED)
13511351

1352+
def test_int_max_str_digits(self):
1353+
old_limit = sys.get_int_max_str_digits()
1354+
self.assertIsInstance(old_limit, int)
1355+
self.assertGreaterEqual(old_limit, 0)
1356+
self.addCleanup(sys.set_int_max_str_digits, old_limit)
1357+
1358+
sys.set_int_max_str_digits(0)
1359+
self.assertEqual(sys.get_int_max_str_digits(), 0)
1360+
1361+
sys.set_int_max_str_digits(2_048)
1362+
self.assertEqual(sys.get_int_max_str_digits(), 2_048)
1363+
1364+
with self.assertRaises(ValueError):
1365+
# the minimum is 640 digits
1366+
sys.set_int_max_str_digits(5)
1367+
with self.assertRaises(ValueError):
1368+
sys.set_int_max_str_digits(-2)
1369+
with self.assertRaises(TypeError):
1370+
sys.set_int_max_str_digits(2_048.0)
1371+
13521372

13531373
@test.support.cpython_only
13541374
@test.support.force_not_colorized_test_class
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
@@ -2125,7 +2125,7 @@ long_to_decimal_string_internal(PyObject *aa,
21252125
if (size_a >= 10 * _PY_LONG_MAX_STR_DIGITS_THRESHOLD
21262126
/ (3 * PyLong_SHIFT) + 2) {
21272127
PyInterpreterState *interp = _PyInterpreterState_GET();
2128-
int max_str_digits = interp->long_state.max_str_digits;
2128+
int max_str_digits = _Py_atomic_load_int(&interp->long_state.max_str_digits);
21292129
if ((max_str_digits > 0) &&
21302130
(max_str_digits / (3 * PyLong_SHIFT) <= (size_a - 11) / 10)) {
21312131
PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_STR,
@@ -2206,7 +2206,7 @@ long_to_decimal_string_internal(PyObject *aa,
22062206
}
22072207
if (strlen > _PY_LONG_MAX_STR_DIGITS_THRESHOLD) {
22082208
PyInterpreterState *interp = _PyInterpreterState_GET();
2209-
int max_str_digits = interp->long_state.max_str_digits;
2209+
int max_str_digits = _Py_atomic_load_int(&interp->long_state.max_str_digits);
22102210
Py_ssize_t strlen_nosign = strlen - negative;
22112211
if ((max_str_digits > 0) && (strlen_nosign > max_str_digits)) {
22122212
Py_DECREF(scratch);
@@ -3021,7 +3021,7 @@ long_from_string_base(const char **str, int base, PyLongObject **res)
30213021
* quadratic algorithm. */
30223022
if (digits > _PY_LONG_MAX_STR_DIGITS_THRESHOLD) {
30233023
PyInterpreterState *interp = _PyInterpreterState_GET();
3024-
int max_str_digits = interp->long_state.max_str_digits;
3024+
int max_str_digits = _Py_atomic_load_int(&interp->long_state.max_str_digits);
30253025
if ((max_str_digits > 0) && (digits > max_str_digits)) {
30263026
PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_INT,
30273027
max_str_digits, digits);

Python/initconfig.c

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

46424642
if (strcmp(spec->name, "int_max_str_digits") == 0) {
46434643
PyInterpreterState *interp = _PyInterpreterState_GET();
4644-
return PyLong_FromLong(interp->long_state.max_str_digits);
4644+
int maxdigits = _Py_atomic_load_int(&interp->long_state.max_str_digits);
4645+
return PyLong_FromLong(maxdigits);
46454646
}
46464647
}
46474648

Python/pylifecycle.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -429,7 +429,8 @@ interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
429429
}
430430
}
431431

432-
tstate->interp->long_state.max_str_digits = config->int_max_str_digits;
432+
_Py_atomic_store_int(&tstate->interp->long_state.max_str_digits,
433+
config->int_max_str_digits);
433434

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

Python/sysmodule.c

Lines changed: 47 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1874,7 +1874,8 @@ sys_get_int_max_str_digits_impl(PyObject *module)
18741874
/*[clinic end generated code: output=0042f5e8ae0e8631 input=77fb74e987ba7ecb]*/
18751875
{
18761876
PyInterpreterState *interp = _PyInterpreterState_GET();
1877-
return PyLong_FromLong(interp->long_state.max_str_digits);
1877+
int maxdigits = _Py_atomic_load_int(&interp->long_state.max_str_digits);
1878+
return PyLong_FromLong(maxdigits);
18781879
}
18791880

18801881

@@ -3490,14 +3491,39 @@ sys_set_flag(PyObject *flags, Py_ssize_t pos, PyObject *value)
34903491
int
34913492
_PySys_SetFlagObj(Py_ssize_t pos, PyObject *value)
34923493
{
3493-
PyObject *flags = PySys_GetAttrString("flags");
3494-
if (flags == NULL) {
3495-
return -1;
3494+
PyObject *new_flags = NULL;
3495+
PyObject *flags_str = &_Py_ID(flags); // immortal ref
3496+
3497+
PyObject *old_flags = PySys_GetAttr(flags_str);
3498+
if (old_flags == NULL) {
3499+
goto error;
34963500
}
34973501

3498-
sys_set_flag(flags, pos, value);
3499-
Py_DECREF(flags);
3500-
return 0;
3502+
new_flags = PyStructSequence_New(&FlagsType);
3503+
if (new_flags == NULL) {
3504+
goto error;
3505+
}
3506+
3507+
for (Py_ssize_t i = 0; i < (Py_ssize_t)(Py_ARRAY_LENGTH(flags_fields) - 1); i++) {
3508+
if (i != pos) {
3509+
PyObject *old_value;
3510+
old_value = PyStructSequence_GET_ITEM(old_flags, i); // borrowed ref
3511+
sys_set_flag(new_flags, i, old_value);
3512+
}
3513+
else {
3514+
sys_set_flag(new_flags, pos, value);
3515+
}
3516+
}
3517+
3518+
int res = _PySys_SetAttr(flags_str, new_flags);
3519+
Py_DECREF(old_flags);
3520+
Py_DECREF(new_flags);
3521+
return res;
3522+
3523+
error:
3524+
Py_XDECREF(old_flags);
3525+
Py_XDECREF(new_flags);
3526+
return -1;
35013527
}
35023528

35033529

@@ -3521,8 +3547,6 @@ set_flags_from_config(PyInterpreterState *interp, PyObject *flags)
35213547
const PyPreConfig *preconfig = &interp->runtime->preconfig;
35223548
const PyConfig *config = _PyInterpreterState_GetConfig(interp);
35233549

3524-
// _PySys_UpdateConfig() modifies sys.flags in-place:
3525-
// Py_XDECREF() is needed in this case.
35263550
Py_ssize_t pos = 0;
35273551
#define SetFlagObj(expr) \
35283552
do { \
@@ -4033,7 +4057,7 @@ _PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
40334057
/* implementation */
40344058
SET_SYS("implementation", make_impl_info(version_info));
40354059

4036-
// sys.flags: updated in-place later by _PySys_UpdateConfig()
4060+
// sys.flags: updated later by _PySys_UpdateConfig()
40374061
ENSURE_INFO_TYPE(FlagsType, flags_desc);
40384062
SET_SYS("flags", make_flags(tstate->interp));
40394063

@@ -4153,16 +4177,21 @@ _PySys_UpdateConfig(PyThreadState *tstate)
41534177
#undef COPY_LIST
41544178
#undef COPY_WSTR
41554179

4156-
// sys.flags
4157-
PyObject *flags = PySys_GetAttrString("flags");
4158-
if (flags == NULL) {
4180+
// replace sys.flags
4181+
PyObject *new_flags = PyStructSequence_New(&FlagsType);
4182+
if (new_flags == NULL) {
41594183
return -1;
41604184
}
4161-
if (set_flags_from_config(interp, flags) < 0) {
4162-
Py_DECREF(flags);
4185+
if (set_flags_from_config(interp, new_flags) < 0) {
4186+
Py_DECREF(new_flags);
4187+
return -1;
4188+
}
4189+
4190+
res = _PySys_SetAttr(&_Py_ID(flags), new_flags);
4191+
Py_DECREF(new_flags);
4192+
if (res < 0) {
41634193
return -1;
41644194
}
4165-
Py_DECREF(flags);
41664195

41674196
SET_SYS("dont_write_bytecode", PyBool_FromLong(!config->write_bytecode));
41684197

@@ -4675,7 +4704,7 @@ _PySys_SetIntMaxStrDigits(int maxdigits)
46754704
// Set PyInterpreterState.long_state.max_str_digits
46764705
// and PyInterpreterState.config.int_max_str_digits.
46774706
PyInterpreterState *interp = _PyInterpreterState_GET();
4678-
interp->long_state.max_str_digits = maxdigits;
4679-
interp->config.int_max_str_digits = maxdigits;
4707+
_Py_atomic_store_int(&interp->long_state.max_str_digits, maxdigits);
4708+
_Py_atomic_store_int(&interp->config.int_max_str_digits, maxdigits);
46804709
return 0;
46814710
}

0 commit comments

Comments
 (0)