diff --git a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po index 973143ea..623c5436 100644 --- a/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/en/LC_MESSAGES/userspace-api/abi.po @@ -183,6 +183,33 @@ msgstr "" "headers; SQLite uses standard ``libsqlite3.so.0`` POSIX VFS. Historical ABI snapshots stay " "unchanged, and compatibility checks continue covering first-party interfaces." +msgid "带进程文件描述符的快照" +msgstr "Snapshots with process file descriptors" + +msgid "" +"```` 中的 ``reliefos_task_snapshot_pidfds()`` 和原有 " +"``reliefos_task_snapshot()`` 使用相同的进程记录和时间戳约定。调用者为 ``tasks`` 和 ``pidfds`` " +"各提供至少 ``capacity`` 个元素;成功返回的行数同时 适用于两个数组。每一行的 ``pidfds`` 值是带 " +"``FD_CLOEXEC`` 的独立描述符, 或在无法取得稳定描述符时为 ``-1``。调用者负责关闭返回范围内的所有非负值。" +msgstr "" +"``reliefos_task_snapshot_pidfds()`` in ```` uses the " +"same process records and timestamp conventions as " +"``reliefos_task_snapshot()``. Provide at least ``capacity`` elements in " +"each of ``tasks`` and ``pidfds``. On success, the returned row count " +"applies to both arrays. Each entry in ``pidfds`` is a separate descriptor" +" with ``FD_CLOEXEC``, or ``-1`` if a stable descriptor is unavailable. " +"The caller must close every nonnegative descriptor in the returned range." + +msgid "" +"任务管理器用描述符绑定选中的进程。打开结束任务确认框时,它复制该描述符, 不因列表刷新改变目标;如果进程已退出或描述符不可用,不退回按数字 PID" +" 发送信号。" +msgstr "" +"Task Manager identifies the selected process by its descriptor. It " +"duplicates the descriptor before opening the End Task confirmation, so " +"refreshing the list cannot change the target. If the process has exited " +"or no descriptor is available, Task Manager does not fall back to " +"signaling a numeric PID." + msgid "按任务选择 uname 系统名" msgstr "Selecting the uname system name per task" diff --git a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po index c325bdc5..1617198e 100644 --- a/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po +++ b/Documentation/locale/ja/LC_MESSAGES/userspace-api/abi.po @@ -152,6 +152,29 @@ msgstr "" "VFS は安定した互換 API ではありません。実装詳細に依存するプログラムは SDK の対応ヘッダーで再コンパイルする必要があります。SQLite は標準 ``libsqlite3.so.0``" " の POSIX VFS を使います。過去の ABI スナップショットは保持し、互換性検査は引き続き第一者の API を対象にします。" +msgid "带进程文件描述符的快照" +msgstr "プロセスファイルディスクリプター付きのスナップショット" + +msgid "" +"```` 中的 ``reliefos_task_snapshot_pidfds()`` 和原有 " +"``reliefos_task_snapshot()`` 使用相同的进程记录和时间戳约定。调用者为 ``tasks`` 和 ``pidfds`` " +"各提供至少 ``capacity`` 个元素;成功返回的行数同时 适用于两个数组。每一行的 ``pidfds`` 值是带 " +"``FD_CLOEXEC`` 的独立描述符, 或在无法取得稳定描述符时为 ``-1``。调用者负责关闭返回范围内的所有非负值。" +msgstr "" +"```` の ``reliefos_task_snapshot_pidfds()`` は、既存の " +"``reliefos_task_snapshot()`` と同じプロセスレコードとタイムスタンプの規約を使用します。呼び出し側は " +"``tasks`` と ``pidfds`` にそれぞれ ``capacity`` " +"個以上の要素を用意します。成功時の戻り値は両方の配列に共通する行数です。``pidfds`` の各要素は ``FD_CLOEXEC`` " +"付きの個別のディスクリプター、または安定したディスクリプターを取得できない場合は ``-1`` です。返された範囲の 0 " +"以上のディスクリプターはすべて呼び出し側で閉じてください。" + +msgid "" +"任务管理器用描述符绑定选中的进程。打开结束任务确认框时,它复制该描述符, 不因列表刷新改变目标;如果进程已退出或描述符不可用,不退回按数字 PID" +" 发送信号。" +msgstr "" +"タスクマネージャーは、選択したプロセスをディスクリプターで識別します。タスクの終了を確認するダイアログを開く前にディスクリプターを複製するため、一覧が更新されても対象は変わりません。プロセスが終了済みの場合やディスクリプターが取得できない場合に、数値" +" PID を使ってシグナルを送信することはありません。" + msgid "按任务选择 uname 系统名" msgstr "タスクごとの uname システム名の選択" diff --git a/Documentation/userspace-api/abi.rst b/Documentation/userspace-api/abi.rst index 91f7772d..f8b51422 100644 --- a/Documentation/userspace-api/abi.rst +++ b/Documentation/userspace-api/abi.rst @@ -42,6 +42,18 @@ vDSO 提供已实现的时间接口,失败或不支持的时钟保留 syscall X11 应用通过 Xorg 通信。未知或旧兼容路径不能当作新的公开接口。 +带进程文件描述符的快照 +---------------------- + +```` 中的 ``reliefos_task_snapshot_pidfds()`` 和原有 +``reliefos_task_snapshot()`` 使用相同的进程记录和时间戳约定。调用者为 +``tasks`` 和 ``pidfds`` 各提供至少 ``capacity`` 个元素;成功返回的行数同时 +适用于两个数组。每一行的 ``pidfds`` 值是带 ``FD_CLOEXEC`` 的独立描述符, +或在无法取得稳定描述符时为 ``-1``。调用者负责关闭返回范围内的所有非负值。 + +任务管理器用描述符绑定选中的进程。打开结束任务确认框时,它复制该描述符, +不因列表刷新改变目标;如果进程已退出或描述符不可用,不退回按数字 PID 发送信号。 + 按任务选择 uname 系统名 ======================== diff --git a/configs/nls/po/taskmgr/ja_JP.po b/configs/nls/po/taskmgr/ja_JP.po index 5761c1ba..e8ced83f 100644 --- a/configs/nls/po/taskmgr/ja_JP.po +++ b/configs/nls/po/taskmgr/ja_JP.po @@ -535,8 +535,14 @@ msgid "Task Manager" msgstr "タスクマネージャー" #: userland/apps/taskmgr/main.cpp:575 -msgid "Task ended" -msgstr "タスクを終了しました" +msgid "Termination signal sent." +msgstr "終了シグナルを送信しました。" + +msgid "A stable handle for this process is unavailable." +msgstr "このプロセスの安定したハンドルを取得できません。" + +msgid "The selected process has already exited." +msgstr "選択したプロセスは既に終了しています。" #: userland/apps/taskmgr/main.cpp:482 msgid "Tasks " diff --git a/configs/nls/po/taskmgr/taskmgr.pot b/configs/nls/po/taskmgr/taskmgr.pot index 77715aa3..3168bd03 100644 --- a/configs/nls/po/taskmgr/taskmgr.pot +++ b/configs/nls/po/taskmgr/taskmgr.pot @@ -527,7 +527,13 @@ msgid "Task Manager" msgstr "" #: userland/apps/taskmgr/main.cpp:575 -msgid "Task ended" +msgid "Termination signal sent." +msgstr "" + +msgid "A stable handle for this process is unavailable." +msgstr "" + +msgid "The selected process has already exited." msgstr "" #: userland/apps/taskmgr/main.cpp:482 diff --git a/configs/nls/po/taskmgr/zh_CN.po b/configs/nls/po/taskmgr/zh_CN.po index 339201f6..321254aa 100644 --- a/configs/nls/po/taskmgr/zh_CN.po +++ b/configs/nls/po/taskmgr/zh_CN.po @@ -535,8 +535,14 @@ msgid "Task Manager" msgstr "任务管理器" #: userland/apps/taskmgr/main.cpp:575 -msgid "Task ended" -msgstr "任务已结束" +msgid "Termination signal sent." +msgstr "已发送终止信号。" + +msgid "A stable handle for this process is unavailable." +msgstr "无法获取此进程的稳定句柄。" + +msgid "The selected process has already exited." +msgstr "选中的进程已退出。" #: userland/apps/taskmgr/main.cpp:482 msgid "Tasks " diff --git a/include/reliefos/system.h b/include/reliefos/system.h index ea95973f..0432f6c4 100644 --- a/include/reliefos/system.h +++ b/include/reliefos/system.h @@ -54,6 +54,10 @@ struct reliefos_task_snapshot { unsigned long reliefos_uptime_ms(void); int reliefos_task_snapshot(struct reliefos_task_info *tasks, uint32_t capacity, uint64_t *tick); +/* Like task_snapshot, with one owned close-on-exec pidfd (or -1 when + * unavailable) per returned row. Caller closes every nonnegative entry. */ +int reliefos_task_snapshot_pidfds(struct reliefos_task_info *tasks, int *pidfds, + uint32_t capacity, uint64_t *tick); int reliefos_task_kill(uint32_t pid); #endif diff --git a/kernel/reliefnt b/kernel/reliefnt index e61feb30..b63f26ef 160000 --- a/kernel/reliefnt +++ b/kernel/reliefnt @@ -1 +1 @@ -Subproject commit e61feb30f3719ce26ff21c7726b0997109a33d35 +Subproject commit b63f26ef18638282fe9f501dcc9d247e29777b76 diff --git a/tools/tests/procsys_status_test.c b/tools/tests/procsys_status_test.c index ce8efd55..d5801473 100644 --- a/tools/tests/procsys_status_test.c +++ b/tools/tests/procsys_status_test.c @@ -1,32 +1,43 @@ -#define _POSIX_C_SOURCE 200809L +#define _GNU_SOURCE #include #include #include #include #include +#include #include #include int fixture_open(const char *path, int flags, ...); +int fixture_openat(int dir, const char *path, int flags, ...); +long fixture_syscall(long number, ...); +int fixture_poll(struct pollfd *fds, nfds_t count, int timeout); ssize_t fixture_read(int fd, void *buffer, size_t size); int fixture_close(int fd); int fixture_readdir(int fd, struct reliefos_dir_entry *entry); int fixture_getpwuid_r(uid_t uid, struct passwd *record, char *buffer, size_t size, struct passwd **result); #define open fixture_open +#define openat fixture_openat +#define syscall fixture_syscall +#define poll fixture_poll #define read fixture_read #define close fixture_close #define getpwuid_r fixture_getpwuid_r #define reliefos_readdir fixture_readdir #include "../../userland/runtime/src/procsys.c" #undef open +#undef openat +#undef syscall +#undef poll #undef read #undef close #undef getpwuid_r #undef reliefos_readdir -static unsigned cursor, offset, closes; -static int current_file, missing_status; -uint64_t reliefos_uptime_ms(void) { return 123; } +#include + +static unsigned cursor, offset, closes, handle_closes; +static int current_file, missing_status, pidfd_missing, exited_after_read; int fixture_open(const char *path, int flags, ...) { (void)flags; @@ -37,6 +48,30 @@ int fixture_open(const char *path, int flags, ...) current_file = 2; return missing_status ? -1 : 1; } +int fixture_openat(int dir, const char *path, int flags, ...) +{ + (void)flags; + if (dir == 0) { assert(!strcmp(path, "42")); return 2; } + assert(dir == 2); + if (!strcmp(path, "stat")) return fixture_open("/proc/42/stat", flags); + assert(!strcmp(path, "status")); + return fixture_open("/proc/42/status", flags); +} +long fixture_syscall(long number, ...) +{ + va_list args; + va_start(args, number); + assert(number == SYS_pidfd_open && va_arg(args, long) == 42L && va_arg(args, long) == 0L); + va_end(args); + if (pidfd_missing) { errno = ENOSYS; return -1; } + return 7; +} +int fixture_poll(struct pollfd *fds, nfds_t count, int timeout) +{ + assert(count == 1 && timeout == 0 && fds->fd == 7 && fds->events == POLLIN); + fds->revents = exited_after_read ? POLLIN | POLLHUP : 0; + return !!fds->revents; +} ssize_t fixture_read(int fd, void *buffer, size_t size) { assert(fd == 1); @@ -48,7 +83,13 @@ ssize_t fixture_read(int fd, void *buffer, size_t size) memcpy(buffer, text + offset, length); offset += length; return length; } -int fixture_close(int fd) { assert(fd == 0 || fd == 1); ++closes; return 0; } +int fixture_close(int fd) +{ + assert(fd == 0 || fd == 1 || fd == 2 || fd == 7); + if (fd == 7) ++handle_closes; + ++closes; + return 0; +} int fixture_readdir(int fd, struct reliefos_dir_entry *entry) { assert(fd == 0); @@ -72,5 +113,16 @@ int main(void) missing_status = 1; assert(reliefos_task_snapshot(&task, 1, NULL) == 1); assert(task.uid == UINT32_MAX && task.memory_kib == 0 && closes == 5); - puts("PASS task snapshot: status UID/RSS, account resolution, partial reads and fd cleanup"); + missing_status = 0; + int fd = -1; + assert(reliefos_task_snapshot_pidfds(&task, &fd, 1, NULL) == 1); + assert(fd == 7 && task.pid == 42 && task.uid == 1001 && handle_closes == 0); + assert(fixture_close(fd) == 0); + exited_after_read = 1; + assert(reliefos_task_snapshot_pidfds(&task, &fd, 1, NULL) == 0); + assert(handle_closes == 2); + pidfd_missing = 1; + assert(reliefos_task_snapshot_pidfds(&task, &fd, 1, NULL) == 1); + assert(fd == -1 && task.pid == 42 && handle_closes == 2); + puts("PASS task snapshot: metadata, pidfd ownership, discarded stale row and old-kernel fallback"); } diff --git a/userland/apps/taskmgr/main.cpp b/userland/apps/taskmgr/main.cpp index 3b99c4a0..438f49d9 100644 --- a/userland/apps/taskmgr/main.cpp +++ b/userland/apps/taskmgr/main.cpp @@ -3,7 +3,6 @@ extern "C" { #include #include #include -#include } #include "fltk_support.h" @@ -27,10 +26,15 @@ extern "C" { #include #include +#include +#include +#include +#include #include #include #include #include +#include #include namespace { @@ -72,6 +76,7 @@ PerformanceView *performance_view; Fl_Scroll *performance_scroll; struct reliefos_task_info tasks[RELIEFOS_TASK_MAX]; +int task_pidfds[RELIEFOS_TASK_MAX]; struct reliefos_task_info previous_tasks[RELIEFOS_TASK_MAX]; uint32_t task_cpu_percent[RELIEFOS_TASK_MAX]; uint32_t previous_task_cpu_percent[RELIEFOS_TASK_MAX]; @@ -158,6 +163,26 @@ struct reliefos_task_info *selected_task() return index >= 0 ? &tasks[index] : NULL; } +int selected_pidfd() +{ + int index = selected_pid ? task_index_by_pid(selected_pid) : -1; + return index >= 0 ? task_pidfds[index] : -1; +} + +int pidfd_ready(int fd) +{ + struct pollfd check = {fd, POLLIN, 0}; + int result; + do { result = poll(&check, 1, 0); } while (result < 0 && errno == EINTR); + return result; +} + +void close_task_pidfds() +{ + for (uint32_t i = 0; i < task_count; ++i) + if (task_pidfds[i] >= 0) close(task_pidfds[i]); +} + const char *task_user_name(const struct reliefos_task_info *task) { if (task && task->username[0]) return task->username; @@ -183,7 +208,7 @@ int selected_task_killable() void update_controls() { if (button_end_task) { - if (active_tab == TASKMGR_TAB_PROCESSES && selected_task_killable()) + if (active_tab == TASKMGR_TAB_PROCESSES && selected_task_killable() && selected_pidfd() >= 0) button_end_task->activate(); else button_end_task->deactivate(); } @@ -205,10 +230,24 @@ void refresh_tasks() uint64_t sample_total = perf_info.busy_ticks + perf_info.idle_ticks; uint64_t tick_delta = 0; int select_position = 0; - int count = reliefos_task_snapshot(tasks, RELIEFOS_TASK_MAX, &next_tick); + int next_fds[RELIEFOS_TASK_MAX]; + int old_selection = selected_pidfd(); + int count = reliefos_task_snapshot_pidfds(tasks, next_fds, RELIEFOS_TASK_MAX, &next_tick); (void)next_tick; + if (selected_pid) { + int new_selection = -1; + for (int i = 0; i < count; ++i) { + if (tasks[i].pid == selected_pid) { new_selection = next_fds[i]; break; } + } + // Check the old handle only after sampling the new row. If its PID + // was reused, the old handle must already be readable or hung up. + if ((old_selection >= 0 && (new_selection < 0 || pidfd_ready(old_selection) != 0)) || + (old_selection < 0 && new_selection >= 0)) selected_pid = 0; + } + close_task_pidfds(); task_count = count > 0 ? (uint32_t)count : 0; if (task_count > RELIEFOS_TASK_MAX) task_count = RELIEFOS_TASK_MAX; + for (uint32_t i = 0; i < task_count; ++i) task_pidfds[i] = next_fds[i]; if (previous_sample_total && sample_total > previous_sample_total) tick_delta = sample_total - previous_sample_total; for (uint32_t i = 0; i < task_count; ++i) { @@ -549,18 +588,35 @@ void kill_selected_task() set_status(T("Cannot end protected or non-user task")); return; } + int selected = selected_pidfd(); + if (selected < 0) { + set_status(T("A stable handle for this process is unavailable.")); + return; + } + // The modal dialog runs the sampling timer. Duplicate the original + // description before entering it; neither a refresh nor FD/PID reuse + // can change the target of this confirmation. + int handle = fcntl(selected, F_DUPFD_CLOEXEC, 0); + if (handle < 0) { + set_status(T("End Task failed")); + return; + } const uint32_t pid = task->pid; char prompt[RELIEFOS_TASK_NAME_LEN + 96]; snprintf(prompt, sizeof(prompt), T("End task %s (PID %u)?"), task->name, pid); - if (!confirm_dialog(T("End Task"), prompt)) return; - // The modal dialog runs the sampling timer; its next snapshot can - // replace tasks[]. Act on the PID named in the confirmation. - if (reliefos_task_kill(pid) < 0) { - set_status(T("End Task failed")); + if (!confirm_dialog(T("End Task"), prompt)) { + close(handle); return; } - set_status(T("Task ended")); + int ready = pidfd_ready(handle); + int error = ready > 0 ? ESRCH : ready < 0 ? errno : 0; + if (!error && syscall(SYS_pidfd_send_signal, (long)handle, (long)SIGTERM, 0L, 0L) < 0) + error = errno; + close(handle); refresh_all(); + if (error == ESRCH) set_status(T("The selected process has already exited.")); + else if (error) set_status(T("End Task failed")); + else set_status(T("Termination signal sent.")); } void show_task_details() @@ -896,5 +952,8 @@ int main(int argc, char **argv) puts("[taskmgr.elf] FLTK task manager ready"); fflush(stdout); Fl::add_timeout(0.5, timer_callback); - return Fl::run(); + int result = Fl::run(); + Fl::remove_timeout(timer_callback); + close_task_pidfds(); + return result; } diff --git a/userland/runtime/src/procsys.c b/userland/runtime/src/procsys.c index a4e7ba61..58c0535d 100644 --- a/userland/runtime/src/procsys.c +++ b/userland/runtime/src/procsys.c @@ -1,11 +1,13 @@ /* procfs-backed system/task compatibility exports. */ -#ifndef _POSIX_C_SOURCE -#define _POSIX_C_SOURCE 200809L +#ifndef _GNU_SOURCE +#define _GNU_SOURCE #endif #include #include #include #include +#include +#include #include #include #include @@ -26,9 +28,10 @@ static void ps_copy(char *dst, uint32_t capacity, const char *src) dst[i] = 0; } -static int ps_read_file(const char *path, char *buffer, uint32_t capacity) +static int ps_read_file_at(int dir, const char *path, char *buffer, uint32_t capacity) { - int fd = open(path, RELIEFOS_O_RDONLY, 0); + int fd = dir == AT_FDCWD ? open(path, O_RDONLY | O_CLOEXEC) : + openat(dir, path, O_RDONLY | O_CLOEXEC); uint32_t len = 0; if (fd < 0) return -1; buffer[0] = 0; @@ -43,6 +46,11 @@ static int ps_read_file(const char *path, char *buffer, uint32_t capacity) return 0; } +static int ps_read_file(const char *path, char *buffer, uint32_t capacity) +{ + return ps_read_file_at(AT_FDCWD, path, buffer, capacity); +} + static uint64_t ps_parse_number(const char *text, uint32_t *position) { uint64_t value = 0; @@ -189,11 +197,11 @@ int reliefos_machine_identity(struct reliefos_machine_identity *identity) /* Linux stat's comm may contain spaces and closing parentheses. The final * closing parenthesis delimits it; token positions after state are fixed. */ -static int ps_parse_stat(const char *path, struct reliefos_task_info *task) +static int ps_parse_stat(int dir, const char *path, struct reliefos_task_info *task) { char text[1024]; uint32_t pos = 0; - if (ps_read_file(path, text, sizeof(text)) < 0) return -1; + if (ps_read_file_at(dir, path, text, sizeof(text)) < 0) return -1; const char *start = strchr(text, '('), *end = strrchr(text, ')'); if (!start || !end || end <= start || end[1] != ' ' || !end[2] || end[3] != ' ') return -1; memset(task, 0, sizeof(*task)); @@ -217,61 +225,96 @@ static int ps_parse_stat(const char *path, struct reliefos_task_info *task) return 0; } -int reliefos_task_snapshot(struct reliefos_task_info *tasks, uint32_t capacity, - uint64_t *tick) +static void ps_read_task_status(int dir, const char *path, struct reliefos_task_info *task) +{ + char status[512], password_buffer[1024]; + struct passwd record, *account = NULL; + /* Identity and ReliefOS-specific metadata are named status fields, + * never extra columns in the Linux stat ABI. */ + if (ps_read_file_at(dir, path, status, sizeof(status)) == 0) { + const char *value = strstr(status, "\nVmRSS:\t"); + if (value) { uint32_t pos = 8; task->memory_kib = (uint32_t)ps_parse_number(value, &pos); } + value = strstr(status, "\nUid:\t"); + if (value) { uint32_t pos = 6; task->uid = (uint32_t)ps_parse_number(value, &pos); } + const char *keys[] = {"\nLeonOSRole:\t", "\nLeonOSFlags:\t"}; + uint32_t *fields[] = {&task->role, &task->flags}; + for (unsigned i = 0; i < 2; ++i) { + value = strstr(status, keys[i]); + if (value) { uint32_t pos = (uint32_t)strlen(keys[i]); *fields[i] = (uint32_t)ps_parse_number(value, &pos); } + } + } + if (task->uid != UINT32_MAX && getpwuid_r(task->uid, &record, password_buffer, + sizeof(password_buffer), &account) == 0 && account && account->pw_name) + ps_copy(task->username, sizeof(task->username), account->pw_name); +} + +static int ps_task_snapshot(struct reliefos_task_info *tasks, int *pidfds, + uint32_t capacity, uint64_t *tick) { int fd; struct reliefos_dir_entry entry; uint32_t count = 0; if (tick) *tick = reliefos_uptime_ms(); if (!tasks || !capacity) return 0; - fd = open("/proc", RELIEFOS_O_RDONLY, 0); + fd = open("/proc", O_RDONLY | O_DIRECTORY | O_CLOEXEC); if (fd < 0) return -1; - while (reliefos_readdir(fd, &entry) > 0 && count < capacity) { - char path[RELIEFOS_FS_PATH_LEN]; + int pidfds_supported = pidfds != NULL; + while (count < capacity && reliefos_readdir(fd, &entry) > 0) { if (entry.name[0] < '0' || entry.name[0] > '9') continue; - { - uint32_t pos = 0; - ps_copy(path, sizeof(path), "/proc/"); - while (path[pos]) ++pos; - ps_copy(path + pos, sizeof(path) - pos, entry.name); - pos += (uint32_t)strlen(entry.name); - ps_copy(path + pos, sizeof(path) - pos, "/stat"); + uint32_t pos = 0; + uint64_t pid = ps_parse_number(entry.name, &pos); + if (entry.name[pos] || !pid || pid > INT_MAX) continue; + if (!pidfds) { + char path[RELIEFOS_FS_PATH_LEN]; + snprintf(path, sizeof(path), "/proc/%u/stat", (unsigned)pid); + if (ps_parse_stat(AT_FDCWD, path, &tasks[count]) != 0) continue; + snprintf(path, sizeof(path), "/proc/%u/status", (unsigned)pid); + ps_read_task_status(AT_FDCWD, path, &tasks[count]); + ++count; + continue; } - if (ps_parse_stat(path, &tasks[count]) == 0) { - char status[512], password_buffer[1024]; - struct passwd record, *account = NULL; - /* Identity and ReliefOS-specific metadata are named status fields, - * never extra columns in the Linux stat ABI. */ - char *suffix = strrchr(path, '/'); - ps_copy(suffix + 1, (uint32_t)(sizeof(path) - (suffix + 1 - path)), "status"); - if (ps_read_file(path, status, sizeof(status)) == 0) { - const char *value = strstr(status, "\nVmRSS:\t"); - if (value) { - uint32_t pos = 8; - tasks[count].memory_kib = (uint32_t)ps_parse_number(value, &pos); - } - value = strstr(status, "\nUid:\t"); - if (value) { - uint32_t pos = 6; - tasks[count].uid = (uint32_t)ps_parse_number(value, &pos); - } - const char *keys[] = {"\nLeonOSRole:\t", "\nLeonOSFlags:\t"}; - uint32_t *fields[] = {&tasks[count].role, &tasks[count].flags}; - for (unsigned i = 0; i < 2; ++i) { - const char *value = strstr(status, keys[i]); - if (value) { uint32_t pos = (uint32_t)strlen(keys[i]); *fields[i] = (uint32_t)ps_parse_number(value, &pos); } - } + int handle = pidfds_supported ? (int)syscall(SYS_pidfd_open, (long)pid, 0L) : -1; + if (handle < 0 && pidfds_supported && errno == ENOSYS) pidfds_supported = 0; + /* Bind the directory after opening the handle and check its liveness + * after the last metadata read. A stale pidfd is always readable, + * including after reap, so a recycled /proc/PID cannot be paired + * with the old handle. Paths within the row use the pinned directory. */ + int dir = openat(fd, entry.name, O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir < 0 || ps_parse_stat(dir, "stat", &tasks[count]) != 0 || tasks[count].pid != pid) { + if (dir >= 0) close(dir); + if (handle >= 0) close(handle); + continue; + } + ps_read_task_status(dir, "status", &tasks[count]); + close(dir); + if (handle >= 0) { + struct pollfd check = {handle, POLLIN, 0}; + int ready; + do { ready = poll(&check, 1, 0); } while (ready < 0 && errno == EINTR); + if (ready != 0) { + close(handle); + if (ready > 0 && tasks[count].state != 3) continue; + handle = -1; } - if (tasks[count].uid != UINT32_MAX && getpwuid_r(tasks[count].uid, &record, password_buffer, - sizeof(password_buffer), &account) == 0 && account && account->pw_name) - ps_copy(tasks[count].username, sizeof(tasks[count].username), account->pw_name); - ++count; } + pidfds[count++] = handle; } close(fd); return (int)count; } + +int reliefos_task_snapshot(struct reliefos_task_info *tasks, uint32_t capacity, + uint64_t *tick) +{ + return ps_task_snapshot(tasks, NULL, capacity, tick); +} + +int reliefos_task_snapshot_pidfds(struct reliefos_task_info *tasks, int *pidfds, + uint32_t capacity, uint64_t *tick) +{ + if (!pidfds && tasks && capacity) { errno = EINVAL; return -1; } + return ps_task_snapshot(tasks, pidfds, capacity, tick); +} /* Published libleonos.so.2 aliases; keep these in the defining translation unit. */ extern __typeof__(reliefos_machine_identity) leonos_machine_identity __attribute__((alias("reliefos_machine_identity"))); extern __typeof__(reliefos_perf_info) leonos_perf_info __attribute__((alias("reliefos_perf_info")));