[libc-commits] [libc] [libc] Support execution of scripts without shebangs in execvpe (PR #240040)

Pavel Labath via libc-commits libc-commits at lists.llvm.org
Thu Nov 12 02:04:30 PST 2026


================
@@ -63,18 +63,52 @@ LIBC_INLINE ErrorOr<int> exec_with_arg_list(const char *arg0, va_list *args,
   return exec(argv);
 }
 
-// TODO: POSIX requires that if execve fails with ENOEXEC, the file is executed
-// using the system shell (as if by `sh -- file args...`). The kernel only
-// handles ELF, "#!" scripts, and binfmt_misc formats, so shebang-less scripts
-// currently fail with ENOEXEC instead of being run by /bin/sh.
-LIBC_INLINE ErrorOr<int> execvpe(cpp::string_view file, char *const argv[],
+LIBC_INLINE ErrorOr<int> execve_shell_fallback(const char *path,
+                                               char *const argv[],
+                                               char *const envp[]) {
+  size_t argc = 0;
+  if (argv != nullptr) {
+    while (argv[argc] != nullptr)
+      ++argc;
+  }
+  size_t count = (argc > 0) ? argc : 1;
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wvla"
+#if __has_warning("-Wvla-cxx-extension")
+#pragma GCC diagnostic ignored "-Wvla-cxx-extension"
+#endif
+  char *new_argv[count + 2];
+#pragma GCC diagnostic pop
+  new_argv[0] = const_cast<char *>("sh");
+  new_argv[1] = const_cast<char *>(path);
+  if (argv != nullptr && argc > 1) {
+    for (size_t i = 1; i < argc; ++i)
+      new_argv[i + 1] = argv[i];
+  }
+  new_argv[count + 1] = nullptr;
+
+  constexpr const char *DEFAULT_BSHELL = "/bin/sh";
+  return linux_syscalls::execve(DEFAULT_BSHELL, new_argv, envp);
+}
+
+LIBC_INLINE ErrorOr<int> execve_with_shell_fallback(const char *path,
+                                                    char *const argv[],
+                                                    char *const envp[]) {
+  auto ret = linux_syscalls::execve(path, argv, envp);
+  if (!ret && ret.error() == ENOEXEC)
----------------
labath wrote:

I wouldn't create a separate function for this. Just invert the condition here (https://llvm.org/docs/CodingStandards.html#use-early-exits-and-continue-to-simplify-code), and inline the other function

https://github.com/llvm/llvm-project/pull/240040


More information about the libc-commits mailing list