From 0dc168a8c0162e664273207eff93a054667f0513 Mon Sep 17 00:00:00 2001 From: Bananymous Date: Wed, 6 Dec 2023 18:14:00 +0200 Subject: [PATCH] LibC: Implement basic execvp --- libc/unistd.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/libc/unistd.cpp b/libc/unistd.cpp index ced04a3e39..c59b7c3d30 100644 --- a/libc/unistd.cpp +++ b/libc/unistd.cpp @@ -180,6 +180,48 @@ int execve(const char* pathname, char* const argv[], char* const envp[]) return syscall(SYS_EXEC, pathname, argv, envp); } +int execvp(const char* file, char* const argv[]) +{ + char buffer[1024]; + const char* pathname = file; + + // do path resolution if file doesn't contain / + if (strchr(file, '/') == nullptr) + { + const char* cur = getenv("PATH"); + if (!cur) + { + errno = ENOENT; + return -1; + } + + while (*cur) + { + const char* end = strchrnul(cur, ':'); + size_t len = end - cur; + + ASSERT(strlen(file) + 1 + len < sizeof(buffer)); + + strncpy(buffer, cur, len); + strcat(buffer, "/"); + strcat(buffer, file); + + struct stat st; + if (stat(buffer, &st) == 0) + { + pathname = buffer; + break; + } + + cur = end; + if (*cur) + cur++; + } + } + + return execve(pathname, argv, environ); +} + pid_t fork(void) { return syscall(SYS_FORK);