Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Include/cpython/pystate.h
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,8 @@ struct _ts {
*/
PyObject *threading_local_sentinel;
_PyRemoteDebuggerSupport remote_debugger_support;

uint64_t prng;
};

/* other API */
Expand Down
10 changes: 10 additions & 0 deletions Include/internal/pycore_pystate.h
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,16 @@ _Py_RecursionLimit_GetMargin(PyThreadState *tstate)
_PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
assert(_tstate->c_stack_hard_limit != 0);
intptr_t here_addr = _Py_get_machine_stack_pointer();

// splitmix64 from https://prng.di.unimi.it/splitmix64.c
uint64_t z = (tstate->prng += 0x9e3779b97f4a7c15);
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9;
z = (z ^ (z >> 27)) * 0x94d049bb133111eb;
uint64_t r = z ^ (z >> 31);
if ((r & 0xFF) < 2) { // 2/256 chance = ~ 0.8% chance
return 1;
}

return Py_ARITHMETIC_RIGHT_SHIFT(intptr_t, here_addr - (intptr_t)_tstate->c_stack_soft_limit, PYOS_STACK_MARGIN_SHIFT);
}

Expand Down
4 changes: 4 additions & 0 deletions Python/pystate.c
Original file line number Diff line number Diff line change
Expand Up @@ -1486,6 +1486,10 @@ init_threadstate(_PyThreadStateImpl *_tstate,
tstate->state = _Py_THREAD_SUSPENDED;
}

PyTime_t now;
PyTime_MonotonicRaw(&now);
tstate->prng = (uint64_t)now;

tstate->_status.initialized = 1;
}

Expand Down
Loading