Skip to content

Commit d7b0f2c

Browse files
committed
Fix fork-child SIGSEGV and yield-from throw args
Forget JoinHandle of threads that did not survive fork instead of dropping them. Zero-reinit the import lock and condvars in the child rather than unlock/notify. Resume the world if os.fork() fails. Call a yield-from subiterator throw() without None fillers so a 1-arg throw stays 1-arg. Drop the stale Windows expectedFailure on logging queue config and unskip test_reinit_tls_after_fork plus the asyncio local_addr family test. Assisted-by: Grok:4.6
1 parent 76c356c commit d7b0f2c

7 files changed

Lines changed: 49 additions & 29 deletions

File tree

‎Lib/test/test_asyncio/test_events.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -789,7 +789,6 @@ def test_create_connection_local_addr(self):
789789
self.assertEqual(port, expected)
790790
tr.close()
791791

792-
@unittest.skipIf(sys.platform == "linux", "TODO: RUSTPYTHON; Flaky on CI")
793792
@socket_helper.skip_if_tcp_blackhole
794793
def test_create_connection_local_addr_skip_different_family(self):
795794
# See https://github.com/python/cpython/issues/86508

‎Lib/test/test_logging.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4108,7 +4108,6 @@ def _mpinit_issue121723(qspec, message_to_log):
41084108
# log a message (this creates a record put in the queue)
41094109
logging.getLogger().info(message_to_log)
41104110

4111-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON; SemLock not implemented on Windows")
41124111
@skip_if_tsan_fork
41134112
@support.requires_subprocess()
41144113
def test_multiprocessing_queues(self):

‎Lib/test/test_threading.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1568,7 +1568,6 @@ def thread1():
15681568
self.assertEqual(out.strip(), b"OK")
15691569
self.assertEqual(rc, 0)
15701570

1571-
@unittest.skip("TODO: RUSTPYTHON; - flaky, parking_lot mutex not fork-safe")
15721571
@skip_unless_reliable_fork
15731572
def test_reinit_tls_after_fork(self):
15741573
# Issue #13817: fork() would deadlock in a multithreaded program with

‎crates/vm/src/frame.rs‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3903,7 +3903,19 @@ impl ExecutingFrame<'_> {
39033903
Either::A(coro) => coro
39043904
.throw(jen, exc_type, exc_val, exc_tb, vm)
39053905
.to_pyresult(vm),
3906-
Either::B(meth) => meth.call((exc_type, exc_val, exc_tb), vm),
3906+
Either::B(meth) => {
3907+
// Omit trailing None so a 1-arg throw() stays 1-arg.
3908+
// Passing None fillers makes throw() look like the
3909+
// deprecated 3-arg form and warns under -W error.
3910+
let args = if !vm.is_none(&exc_tb) {
3911+
vec![exc_type, exc_val, exc_tb]
3912+
} else if !vm.is_none(&exc_val) {
3913+
vec![exc_type, exc_val]
3914+
} else {
3915+
vec![exc_type]
3916+
};
3917+
meth.call(args, vm)
3918+
}
39073919
};
39083920
return ret.map(ExecutionResult::Yield).or_else(|err| {
39093921
// Add traceback entry for the yield-from/await point.

‎crates/vm/src/stdlib/_imp.rs‎

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -51,33 +51,27 @@ mod lock {
5151
}
5252
}
5353

54-
/// Reset import lock after fork() — only if held by a dead thread.
54+
/// Reset the import lock after `fork()`.
5555
///
56-
/// `IMP_LOCK` is a reentrant mutex. If the *current* (surviving) thread
57-
/// held it at fork time, the child must be able to release it normally.
58-
/// Only reset if a now-dead thread was the owner.
56+
/// Always zero the lock. Other threads may have been parked on it at
57+
/// fork time; `unlock()` would walk those waiter queues. The child is
58+
/// single-threaded, so the lock starts unlocked.
5959
///
6060
/// # Safety
6161
///
6262
/// Must only be called from single-threaded child after fork().
6363
#[cfg(all(unix, feature = "host_env"))]
6464
pub(crate) unsafe fn reinit_after_fork() {
65-
if IMP_LOCK.is_locked() && !IMP_LOCK.is_owned_by_current_thread() {
66-
// Held by a dead thread — reset to unlocked.
67-
unsafe { rustpython_common::lock::zero_reinit_after_fork(&IMP_LOCK) };
68-
}
65+
// Do NOT call unlock() here — after fork(), unlock_slow() would try
66+
// to unpark stale waiters.
67+
unsafe { rustpython_common::lock::zero_reinit_after_fork(&IMP_LOCK) };
6968
}
7069

71-
/// Match CPython's `_PyImport_ReInitLock()` + `_PyImport_ReleaseLock()`
72-
/// behavior in the post-fork child:
73-
/// 1) if ownership metadata is stale (dead owner / changed tid), reset;
74-
/// 2) if current thread owns the lock, release it.
70+
/// Import lock is unlocked after [`reinit_after_fork`]. Kept as a named
71+
/// step in the child after-fork sequence.
7572
#[cfg(all(unix, feature = "host_env"))]
7673
pub(super) unsafe fn after_fork_child_reinit_and_release() {
7774
unsafe { reinit_after_fork() };
78-
if IMP_LOCK.is_locked() && IMP_LOCK.is_owned_by_current_thread() {
79-
unsafe { IMP_LOCK.unlock() };
80-
}
8175
}
8276
}
8377

‎crates/vm/src/stdlib/_thread.rs‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1399,14 +1399,20 @@ pub(crate) mod _thread {
13991399
}
14001400

14011401
inner_guard.state = ThreadHandleState::Done;
1402-
inner_guard.join_handle = None;
1402+
// The OS thread did not survive the fork. Dropping JoinHandle
1403+
// would pthread_detach a copied thread descriptor.
1404+
if let Some(handle) = inner_guard.join_handle.take() {
1405+
core::mem::forget(handle);
1406+
}
14031407
drop(inner_guard);
14041408

1405-
// Reinit and set the done event
1409+
// Reinit and set the done event. Do not notify: no other
1410+
// thread exists in the child, and notify_all would unpark
1411+
// waiters that did not survive the fork.
14061412
let (lock, cvar) = &*done_event;
14071413
reinit_parking_lot_mutex(lock);
1414+
reinit_parking_lot_condvar(cvar);
14081415
*lock.lock() = true;
1409-
cvar.notify_all();
14101416

14111417
true
14121418
});
@@ -1438,8 +1444,8 @@ pub(crate) mod _thread {
14381444

14391445
let (lock, cvar) = &*done_event;
14401446
reinit_parking_lot_mutex(lock);
1447+
reinit_parking_lot_condvar(cvar);
14411448
*lock.lock() = true;
1442-
cvar.notify_all();
14431449

14441450
false
14451451
});
@@ -1465,6 +1471,14 @@ pub(crate) mod _thread {
14651471
unsafe { rustpython_common::lock::zero_reinit_after_fork(mutex.raw()) };
14661472
}
14671473

1474+
/// Reset a parking_lot::Condvar after fork.
1475+
///
1476+
/// `notify_all()` would unpark waiters that did not survive the fork.
1477+
#[cfg(all(unix, feature = "host_env"))]
1478+
fn reinit_parking_lot_condvar(cvar: &parking_lot::Condvar) {
1479+
unsafe { rustpython_common::lock::zero_reinit_after_fork(cvar) };
1480+
}
1481+
14681482
// Thread handle state enum
14691483
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14701484
pub enum ThreadHandleState {

‎crates/vm/src/stdlib/posix.rs‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -655,8 +655,8 @@ pub mod module {
655655
#[cfg(feature = "threading")]
656656
crate::stdlib::_thread::after_fork_child(vm);
657657

658-
// CPython parity: reinit import lock ownership metadata in child
659-
// and release the lock acquired by PyOS_BeforeFork().
658+
// Reinit import lock ownership metadata in child and release the lock
659+
// acquired before fork.
660660
#[cfg(feature = "threading")]
661661
unsafe {
662662
crate::stdlib::_imp::after_fork_child_imp_lock_release()
@@ -858,15 +858,18 @@ pub mod module {
858858
Ok(0)
859859
}
860860
Ok(pid) => {
861-
// Match CPython timing: capture this before parent after-fork hooks
862-
// in case those hooks start threads.
861+
// Capture this before parent after-fork hooks in case those
862+
// hooks start threads.
863863
let num_os_threads = get_number_of_os_threads();
864864
py_os_after_fork_parent(vm);
865-
// Match CPython timing: warn only after parent callback path resumes world.
865+
// Warn only after parent callback path resumes the world.
866866
warn_if_multi_threaded("fork", num_os_threads, vm);
867867
Ok(pid)
868868
}
869-
Err(err) => Err(err.into_pyexception(vm)),
869+
Err(err) => {
870+
py_os_after_fork_parent(vm);
871+
Err(err.into_pyexception(vm))
872+
}
870873
}
871874
}
872875

0 commit comments

Comments
 (0)