From 2a01fe0325524f7745f60a528d1f3076c098d89d Mon Sep 17 00:00:00 2001 From: Ron Yorston Date: Thu, 16 May 2024 12:42:46 +0100 Subject: win32: ensure PIDs are read early in procps_scan() Recent changes to allow orphaned processes to report a parent PID of 1 rely on the assumption that Process32First/Process32Next return parents before children. This isn't guaranteed by the API. Obtain all known PIDs on the first call to procps_scan() so that dead parents can be detected reliably. Costs 48 bytes. --- include/libbb.h | 3 +-- win32/process.c | 25 +++++++++++++++---------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/include/libbb.h b/include/libbb.h index 8d5537114..d37d4e64c 100644 --- a/include/libbb.h +++ b/include/libbb.h @@ -2148,9 +2148,8 @@ typedef struct procps_status_t { DIR *dir; #else HANDLE snapshot; - unsigned *pids; + DWORD *pids; int npids; - int maxpids; #endif IF_FEATURE_SHOW_THREADS(DIR *task_dir;) uint8_t shift_pages_to_bytes; diff --git a/win32/process.c b/win32/process.c index 9dd4bc1db..bbb04678f 100644 --- a/win32/process.c +++ b/win32/process.c @@ -605,6 +605,16 @@ UNUSED_PARAM free(sp); return NULL; } + if (Process32First(sp->snapshot, &pe)) { + int maxpids = 0; + do { + if (sp->npids == maxpids) { + maxpids += NPIDS; + sp->pids = xrealloc(sp->pids, sizeof(DWORD) * maxpids); + } + sp->pids[sp->npids++] = pe.th32ProcessID; + } while (Process32Next(sp->snapshot, &pe)); + } ret = Process32First(sp->snapshot, &pe); } else { @@ -665,12 +675,7 @@ UNUSED_PARAM break; } } - - if (sp->npids == sp->maxpids) { - sp->maxpids += NPIDS; - sp->pids = xrealloc(sp->pids, sizeof(unsigned) * sp->maxpids); - } - sp->pids[sp->npids++] = sp->pid = pe.th32ProcessID; + sp->pid = pe.th32ProcessID; if (sp->pid == getpid()) { comm = applet_name; @@ -787,10 +792,10 @@ static int kill_signal(pid_t pid, int sig) } /** - * If the process ID is positive invoke the callback for that process - * only. If negative or zero invoke the callback for all descendants - * of the indicated process. Zero indicates the current process; negative - * indicates the process with process ID -pid. + * If the process ID is positive signal that process only. If negative + * or zero signal all descendants of the indicated process. Zero + * indicates the current process; negative indicates the process with + * process ID -pid. */ static int kill_pids(pid_t pid, int sig) { -- cgit v1.2.3-55-g6feb