feat(libkernel): implement execv, execvp and execve process replacement #9669
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/9669"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from boykopovar/AnyPS5. Originally posted by fogydes on 2026-10-22T07:37:18Z.
What
execv,execvpandexecve(libkernel) replace the running process image with the already-converted executable of the requested guest program instead of throwing. The path resolves with the same rulesposix_spawnuses: it must be under/app0/,/app0/eboot.binmaps to the running image itself, anything else is found beside the running image under its flattened name, andexecvpwalks the guestPATH(FreeBSD 11's_PATH_DEFPATHwhen unset). Argument validation follows FreeBSD 11.4'sexec_copyin_argsandexecvPe:EBADFfor a null path (measured on a console) andEFAULTfor a nullargv; an emptyargv, a nullenvpand entries without=are copied through; the combined string bytes of the arguments and ofexecve'senvp(or the hostenvironfor the implicitexecv/execvpenvironment) beyond 262144 returnE2BIG; the lookup also rejects a regular file without execute permission withEACCES(a 0644 file measured on a console; on Windows the check runs libcaccess's ACLFILE_EXECUTEsince host files carry no Unix mode bits) and a path through a regular file withENOTDIR, and thePATHsearch keeps going past non-regular or inexecutable candidates, keeping theirEACCES, ending withEACCESorENOENT. On Linux the image is genuinely replaced through the hostfexecveon anO_CLOEXECdescriptor of the converted target: the pid, descriptors and working directory survive as POSIX requires, buffers are discarded and no exit handlers run; a converted target that is not an x86-64 Linux ELF returnsENOEXEC(measured on a console) and one that rejects execute permissionEACCES, while a target that cannot be opened still throws like LoadExec, leaving the process intact. On Windows there is no replace; the converted target is validated as an x86-64 PE image first and a non-image returnsENOEXECbefore the relay starts; the replacement reuses the LoadExec relay: the converted target starts suspended with the duplicated parent handle (ANYPS5_LOADEXEC_PARENT), descriptors 0-2 and the caller's argv (ANYPS5_LOADEXEC_ARGV_SKIP=1), its environment inheriting the host variables withexecve'senvpoverriding same-named host ones (theenvpalone is not reproduced and the new image's guest environment table still starts empty, both recorded in the debt; a follow-up can seed it from the relay), and the caller then terminates itself (TerminateProcess) with status 0 and no exit handlers; because the replacement's entry waits for the caller to die before it starts, the caller cannot wait for the replacement's exit status, so aposix_spawnparent waiting on an execed child reads 0, not the replacement's own status (recorded in the debt; a follow-up could re-register the parent's wait handle), and a failing relay terminates the suspended child and throws; the host pid changes and descriptors beyond 0-2 do not survive, both inherited from the LoadExec model. On both hosts the registered shutdown andatexit/__cxa_atexithandlers do not run across a successful exec, and a missing converted executable still throws (NotImplemented_nid_no_patch) likeposix_spawn. A target outside/app0/also still throws the round-mean error; the byte limit and the null-argvEFAULTare not measured on a console.Tested
Windows 11 x64, MinGW-w64 GCC 15.2: the
exec_argumentsstart-to-end relay test passes (the first image validates the rejections: null pathEBADFand null argvEFAULT, an emptyargvand a nullenvpaccepted, an unpaired env entry copied, each with an absent path returningENOENT, oversizedargvand oversizedenvpeach rejected withE2BIG, theexecvpPATHmissENOENT, the missing-conversion throw, a path beyond a regular file rejected withENOTDIRand a converted target without an executable image rejected withENOEXEC, then it execspicker/second.binthroughexecve; the replacement verifies entry/getargv arguments including spaces, quotes, backslashes and Unicode, the exact envp list (EXEC_SECONDset, inheritedPATHabsent, relay variables removed), the image-directory cwd reset, thefirst/launch/secondevent order with no shutdown/guest-exit/host-exit handler run, and two distinct host pids; return code 0 from the terminated caller);guest_execvppasses with its validation battery rewritten for the new behaviour, andguest_waitpid,guest_posix_spawnandloadexec_argumentspass unchanged. Linux x64 Debian (gcc 14.2, WSL2): the same five tests pass, withexec_argumentsadditionally rejecting a 0644 regular file withEACCESin the POSIX build, keeping pid retention (the replacement keeps the pid, return code 37 from the replacement) and the POSIX cwd preservation. No real title run end to end.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)execv); PPSA85300 (execvp, discussion #7971)Imported from boykopovar/AnyPS5. Originally posted by fogydes on 2026-10-22T07:51:33Z.
Same flag as on #9133, and the cause is the same commit: the progress report only counts a function as implemented when its body — directly or through any helper — no longer reaches
NotImplemented_nid_no_patch(tools/progress.py, theSTUB_WRAPPERclosure feedingscan_library). Nothing actually reverted.waitpidcomes from the posix_spawn branch this one depends on, and its Linux arm throws for child-death signals 16/29/30 (no console mapping, recorded indocs/dev/debt/libkernel.md), so the classifier moves it back to stubs.The three
execfunctions themselves stay in the todo count for the same rule: their resolution paths still throw for the cases the convention reservesNotImplemented_nid_no_patchfor — a program outside/app0/and a requested guest program with no converted executable available. Those throws are deliberate and debt-documented; everything the converted image exists for is implemented and covered byguest_execvpand the newexec_argumentsrelay test.Imported from boykopovar/AnyPS5. Originally posted by fogydes on 2026-10-22T08:12:52Z.
The relinker matrix on the head of this PR fails exactly once:
conventions_function_bodies_shard_11 (Timeout)on job 119700497742, 229/230 tests pass, and the windows, ubuntu relinker and relinker-asan jobs pass.Nothing in the diff plausibly slows that shard: adding three exec exports to libkernel does not touch the function-body scanner's input in bulk. Per CONTRIBUTING, ctest runs in parallel on CI, so a slow test competes for the cores and times out on some attempts and not on others; a 120 s budget crossing on a macOS runner is the usual shape. I would re-run the failed job; if the shard timeout reproduces on several PRs in a row, the shard is near its budget and the right move per CODCONTRIBUTING would be splitting/shrinking it rather than raising the timeout.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T09:03:02Z.
Review: DISMISSED
The process replacement path has a concrete E2BIG gap: the byte total always uses the inherited environ, even for execve, where the supplied envp replaces it. A large envp with a small inherited environment therefore bypasses the advertised 262144-byte check; the current oversized-input test exercises argv only. Please select the environment vector based on implicitEnvironment, include that vector in the total, and add an execve case whose envp alone exceeds the limit.\n\nReview validation: exact-head diff-check passed;
python3 tools/check_conventions.py --base upstream/mainpassed; hosted Linux/Windows relinker jobs and their newtest_exec_argumentscoverage passed. The macOS clang relinker job built successfully and ran 229/230 tests;conventions_function_bodies_shard_11timed out at 30 seconds. I inspected its log; this is a timeout, not an assertion failure. Local runtime fixture execution was not repeated in this environment.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T11:39:45Z.
I found a live overlap with #9526: both branches add a
docs/dev/debt/libc.mdentry at the same insertion point, and their pairwise three-way merge currently conflicts in that file. Please coordinate landing order with #9526’s author and declareDepends onif either branch must land first; retain both debt entries when rebasing. This is a documentation insertion conflict, not an overlap in the process-replacement implementation.Imported from boykopovar/AnyPS5. Originally posted by harisibrar1 on 2026-10-22T13:08:01Z.
Review: COMMENTED
Checked against main
3ca07d086d, FreeBSD releng/11.4sys/kern/kern_exec.c(exec_copyin_args),sys/sys/syslimits.handlib/libc/gen/exec.c. I didn't repeat the envp E2BIG point @MarcZX10 already raised:fexecve(..., environment)(Process.cpp:679) and the Windows block built only from the guest entries (:440) start the replacement without LD_LIBRARY_PATH, DISPLAY, WAYLAND_DISPLAY, XDG_RUNTIME_DIR, HOME andAPS5_*/ANYPS5_*on Linux, and without SystemRoot, PATH and TEMP on Windows. Meanwhile the new image's guest environment still starts empty (emptyEnvironmentand libc's static table), sogetenv("FOO")afterexecve(..., {"FOO=1", NULL})returns NULL. The test passes becauseSecondEnvironment()(GuestExecHost.cpp:98-110) copies the host's LD_LIBRARY_PATH and the test root into the guest envp. Could the host environment be kept as is, with the guest envp passed separately and seeded into the guest table? Or throw for a non-empty envp until that exists, and record it in the debt file.TerminateProcess(GetCurrentProcess(), 0)(:448), and #9133'sWaitChildProcess_nid_no_patchwaits on that handle. So a parent thatposix_spawns a.bin, which thenexecvs b.bin, gets status 0 fromwaitpidimmediately, and b.bin's real exit code is never reported.test_exec_arguments.py:92asserts this (0 on Windows, 37 on Linux). Could the caller wait on the replacement and exit with its code? If that's out of scope, it should at least be in the debt entry.exec_copyin_args(kern_exec.c:1172-1262), only a NULL argv gives EFAULT. An empty argv is accepted, but here it returns EFAULT (:654). A NULL envv is accepted (if (envv)), but execve here returns EFAULT (:695). An env entry without=is copied unchecked, but here it returns EFAULT (:660). ARG_MAX (262144) counts only string bytes including the NUL, so addingsizeof(char*)per entry (:314) makes argv = path + 29,999 × "a" (about 60 KB of strings) fail with E2BIG. Since the console behaviour is unverified, could these follow FreeBSD or throw, rather than return errors of their own?GuestExecHost.cpp:127/129/131would need updating to match.LoadExec.cpp:158on main throws for the same check, and throwing here would match it.ExecProgramFound(:245-262) takes the first PATH entry that merely exists. A directory or data file earlier in PATH then throws, where FreeBSD'sexecvPewould keep searching after EACCES.Reviewed with AI assistance (Claude Code); the checks above were run locally on my machine.
Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-23T04:42:24Z.
Review: COMMENTED
macOS check of the non-Windows branches (M2 Max, macOS 27.2, Apple clang 21, x86-64 under Rosetta).
maindoesn't link on macOS, so I applied this PR's diff (headbe747c9a03, docs excluded) onto the macOS port in #8658 (4e0468722f); the only conflict was one adjacentexterndeclaration inlibkernel/System/src/Process.cpp.Two files don't compile on macOS:
libkernel/System/src/Process.cpp:802(ExecProgram):error: use of undeclared identifier 'fexecve'. macOS has nofexecve, so the#elsebranch needs an Apple path, for exampleexecveon the validated path.libSceLibcInternal/Spawn.cpp:124,127(OwnExecutable,__APPLE__branch):error: use of undeclared identifier '_NSGetExecutablePath'. It is declared in<mach-o/dyld.h>, not<crt_externs.h>. A one-line test file compiles with the first header and fails with the second.Two runtime problems on macOS in the same
#elsebranches:ExecOwnExecutable()inProcess.cppandOwnExecutablePath()inGuestExecvp.cppread/proc/self/exe, which doesn't exist on macOS (read_symlinkgivesENOENT). Everyexec*call would therefore throwexec: cannot read /proc/self/exe.Spawn.cppalready has the_NSGetExecutablePathbranch; these two could reuse it.fexecveaccepts only an x86-64 ELF (7f 45 4c 46, machine 62). On macOS the relinker writes a Mach-O executable (MacOsMachOPatcherin #8658'sConversion.cpp), so a converted target would fail withENOEXECeven after the compile errors above are fixed.libc/src/Process.cpp,GuestPosixSpawn.cppandGuestExecvp.cppcompile on macOS. I did not link or run the exec tests. The PR currently conflicts withmain, so this is for the next rebase.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-24T02:34:58Z.
Review: CHANGES_REQUESTED
Thanks for this. Points to fix before it can land:
core/libs/prx/libkernel/System/src/Process.cpp:656: the E2BIG total always addsenviron, even forexecve, where the suppliedenvpreplaces it. A small inherited environment plus anenvpover 262144 bytes passes. Measureenvironmentwhen!implicitEnvironmentandenvironotherwise, and add anexecvetest whereenvpalone exceeds the limit (the current test covers argv only). Same point as @MarcZX10's review.Process.cpp:679(and the Windows block at:440):execvehands the replacement only the guestenvp, so it starts without the emulator's host variables (LD_LIBRARY_PATH,DISPLAY,WAYLAND_DISPLAY,XDG_RUNTIME_DIR,HOME,APS5_*/ANYPS5_*on Linux;SystemRoot,PATH,TEMPon Windows), which the converted program needs to start. Please see @harisibrar1's review and keep the host runtime variables in the replacement environment.Process.cpp:679:fexecvedoes not exist on macOS (use of undeclared identifier 'fexecve', per @jotitadev's build), and therelinker (macos-latest, clang++)job is red. The#elsebranch needs an Apple path (e.g.execveon the validated path) or an explicit throw recorded in the debt file.main, anddocs/dev/debt/libc.mdcollides with #9526 at the same insertion point; keep both entries when rebasing. It is also stacked on #9133, which is still open, so it can only land after it.Welcome back once these are addressed.
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-24T06:33:44Z.
Review: CHANGES_REQUESTED
Thanks for the update. The E2BIG count, the macOS path and the conflicts are fixed. One point is still open:
core/libs/prx/libkernel/System/src/Process.cpp:794(ExecProgram) andExecReplaceWindows(:477):execvestarts the replacement with only the guestenvp, and the guestenvironhere is an empty array (environ_nid_postfix,:579). So a converted program that callsexecv/execvestarts withoutLD_LIBRARY_PATH,DISPLAY,WAYLAND_DISPLAY,XDG_RUNTIME_DIR,HOMEandAPS5_*/ANYPS5_*on Linux, orSystemRoot,PATHandTEMPon Windows, which the relinked program needs to start.GuestExecHost.cpp:190pins that the hostPATHis dropped. Keep the host runtime variables in the replacement environment (add them to the guestenvpunless it sets them), and change the test to assert they arrive. The debt line then no longer needs "the inherited environment is lost".Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-25T18:36:11Z.
Review: CHANGES_REQUESTED
The environment point is met on this head (host
environkept, guestenvpoverriding same-named entries, asserted in the test). New measurements from @rooklz on a PS5 contradict three error paths here:core/libs/prx/libkernel/System/src/Process.cpp:817: a null path must giveEBADF(9), notEFAULT; updateGuestExecHost.cpp:124and the debt line. A nullargvis not covered by the measurement, so keep what FreeBSD says for it and say so in the debt line.Process.cpp:341-345and:835: a regular file without the execute bit must fail withEACCES(0644 file measured), not pass the lookup and then throw in the Linuxaccess(X_OK)check. The debt line "a regular guest file passes without execute-bit checks" is false against the console.Process.cpp:337: a path through a regular file (file/x) givesENOTDIR, notENOENT.ENOEXECon the console; the guest-file case should return it instead of throwing where the converted target can be told apart.E2BIGbefore the path lookup and the directory →EACCESrows already match. Theexecvprow withPATHset at run time is unresolved by that measurement; keep the debt line honest about it. The branch also conflicts withmainand sits on #9133; we will rebase once the errno points are in.Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-26T10:11:22Z.
Review: CHANGES_REQUESTED
The null path now returns
EBADF(Process.cpp:805, asserted atGuestExecHost.cpp:124, debt line updated). Three of @rooklz's console measurements are still not followed:Process.cpp:312-316and:334: a regular file without the execute bit must fail withEACCES(0644 file measured). The lookup only checksis_regular_file, and the Linux path then throws at:824(access(X_OK)). Check the mode bits in the lookup and returnEACCES(forexecvp, keep it as the rememberedEACCESlike the other candidates). The debt line "a regular guest file passes without execute-bit checks" is false against the console and needs to change.Process.cpp:308: a path through a regular file (file/x) givesENOTDIR(20), notENOENT. Add a test row.Process.cpp:824: a 0755 file that is not an executable image givesENOEXECon the console. Where the converted target can be told apart (not an x86-64 ELF), returnENOEXECinstead of throwing, and cover it inGuestExecvp.cpporGuestExecHost.cpp.If you disagree with any of these, say why and we will judge it on that. The Windows and WSL runs you listed are noted; the full Build still runs in the merge queue.