Tcl Source Code

Artifact [f2c3f66aab]
Login

Artifact f2c3f66aabb757f72e18739f860cb7ce9d311837289c6ef877c603201cfbe78e:

Attachment "forkhang.c" to ticket [be38540b32] added by serhiy.storchaka 2026-10-13 16:13:20.
/*
 * Reproducer for [be38540b32]: a child process created by fork() can
 * deadlock in its first Tcl_Alloc() if another thread held a lock of the
 * threaded allocator at the time of the fork.
 *
 * Build:  cc -o forkhang forkhang.c -pthread -I<tcl>/generic -I<tcl>/unix \
 *             -L<tcl>/unix -ltcl9.1 -Wl,-rpath,<tcl>/unix
 * Run:    ./forkhang [forks]       (default 20000; about 3 ms per fork)
 *
 * Prints the number of children that did not exit within 3 seconds;
 * exits with status 1 if there were any.  The race is rare: about one
 * hang per 15000 forks on Linux, so run it a few times (or several
 * copies in parallel).
 */

#include <tcl.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

static volatile int done = 0;

/* Threads that keep allocating, so that the shared lists are busy. */
static void *
Churn(void *arg)
{
    (void)arg;
    while (!done) {
	void *p[64];
	for (int i = 0; i < 64; i++) {
	    p[i] = Tcl_Alloc(16 + 97 * i);
	}
	for (int i = 0; i < 64; i++) {
	    Tcl_Free(p[i]);
	}
    }
    return NULL;
}

/* Short-lived Tcl threads: creating and freeing their caches takes the
 * allocator's list lock. */
static Tcl_ThreadCreateType
ShortLived(void *arg)
{
    (void)arg;
    Tcl_Free(Tcl_Alloc(5000));
    Tcl_FinalizeThread();
    TCL_THREAD_CREATE_RETURN;
}

static int numForks, numHung;

/* This thread never allocates in the parent, so the child's first
 * allocation has to create a cache, which needs the list lock. */
static void *
Forker(void *arg)
{
    (void)arg;
    for (int i = 0; i < numForks; i++) {
	pid_t pid = fork();
	if (pid == 0) {
	    Tcl_Free(Tcl_Alloc(200));
	    _exit(0);
	}
	struct timespec tick = {0, 2000000};
	int status, k;
	for (k = 0; k < 1500; k++) {
	    if (waitpid(pid, &status, WNOHANG) == pid) {
		break;
	    }
	    nanosleep(&tick, NULL);
	}
	if (k == 1500) {
	    numHung++;
	    kill(pid, SIGKILL);
	    waitpid(pid, &status, 0);
	}
    }
    done = 1;
    return NULL;
}

int
main(int argc, char **argv)
{
    pthread_t churn[4], forker;

    numForks = (argc > 1) ? atoi(argv[1]) : 20000;
    Tcl_FindExecutable(argv[0]);
    Tcl_DeleteInterp(Tcl_CreateInterp());

    for (int i = 0; i < 4; i++) {
	pthread_create(&churn[i], NULL, Churn, NULL);
    }
    pthread_create(&forker, NULL, Forker, NULL);
    while (!done) {
	Tcl_ThreadId id;
	for (int i = 0; i < 64 && !done; i++) {
	    Tcl_CreateThread(&id, ShortLived, NULL, TCL_THREAD_STACK_DEFAULT,
		    TCL_THREAD_NOFLAGS);
	}
	usleep(1000);
    }
    pthread_join(forker, NULL);
    for (int i = 0; i < 4; i++) {
	pthread_join(churn[i], NULL);
    }
    printf("%d of %d children hung\n", numHung, numForks);
    return numHung != 0;
}