1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2002 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
11 #include <linux/limits.h>
12 #include <sys/socket.h>
14 #include <kern_util.h>
16 #include <um_malloc.h>
19 void (*pre_exec)(void*);
26 static int helper_child(void *arg)
28 struct helper_data *data = arg;
29 char **argv = data->argv;
32 if (data->pre_exec != NULL)
33 (*data->pre_exec)(data->pre_data);
34 err = execvp_noalloc(data->buf, argv[0], argv);
36 /* If the exec succeeds, we don't get here */
37 CATCH_EINTR(ret = write(data->fd, &err, sizeof(err)));
42 /* Returns either the pid of the child process we run or -E* on failure. */
43 int run_helper(void (*pre_exec)(void *), void *pre_data, char **argv)
45 struct helper_data data;
46 unsigned long stack, sp;
47 int pid, fds[2], ret, n;
49 stack = alloc_stack(0, __cant_sleep());
53 ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
56 printk(UM_KERN_ERR "run_helper : pipe failed, errno = %d\n",
61 ret = os_set_exec_close(fds[1]);
63 printk(UM_KERN_ERR "run_helper : setting FD_CLOEXEC failed, "
68 sp = stack + UM_KERN_PAGE_SIZE;
69 data.pre_exec = pre_exec;
70 data.pre_data = pre_data;
73 data.buf = __cant_sleep() ? uml_kmalloc(PATH_MAX, UM_GFP_ATOMIC) :
74 uml_kmalloc(PATH_MAX, UM_GFP_KERNEL);
75 pid = clone(helper_child, (void *) sp, CLONE_VM, &data);
78 printk(UM_KERN_ERR "run_helper : clone failed, errno = %d\n",
87 * Read the errno value from the child, if the exec failed, or get 0 if
88 * the exec succeeded because the pipe fd was set as close-on-exec.
90 n = read(fds[0], &ret, sizeof(ret));
96 printk(UM_KERN_ERR "run_helper : read on pipe failed, "
100 CATCH_EINTR(waitpid(pid, NULL, __WALL));
104 printk(UM_KERN_ERR "run_helper : failed to exec %s on host: %s\n",
105 argv[0], strerror(-ret));
114 free_stack(stack, 0);
118 int run_helper_thread(int (*proc)(void *), void *arg, unsigned int flags,
119 unsigned long *stack_out)
121 unsigned long stack, sp;
122 int pid, status, err;
124 stack = alloc_stack(0, __cant_sleep());
128 sp = stack + UM_KERN_PAGE_SIZE;
129 pid = clone(proc, (void *) sp, flags, arg);
132 printk(UM_KERN_ERR "run_helper_thread : clone failed, "
133 "errno = %d\n", errno);
136 if (stack_out == NULL) {
137 CATCH_EINTR(pid = waitpid(pid, &status, __WALL));
140 printk(UM_KERN_ERR "run_helper_thread - wait failed, "
141 "errno = %d\n", errno);
144 if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0))
145 printk(UM_KERN_ERR "run_helper_thread - thread "
146 "returned status 0x%x\n", status);
147 free_stack(stack, 0);
153 int helper_wait(int pid)
158 CATCH_EINTR(ret = waitpid(pid, &status, wflags));
160 printk(UM_KERN_ERR "helper_wait : waitpid process %d failed, "
161 "errno = %d\n", pid, errno);
163 } else if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
164 printk(UM_KERN_ERR "helper_wait : process %d exited with "
165 "status 0x%x\n", pid, status);