xref: /freebsd/lib/libproc/proc_create.c (revision d91f8db5f1822c43cd256f19aae1d059e4b25a26)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2008 John Birrell (jb@freebsd.org)
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/types.h>
33 #include <sys/sysctl.h>
34 #include <sys/user.h>
35 #include <sys/wait.h>
36 
37 #include <err.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <limits.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 
45 #include <libelf.h>
46 #include <libprocstat.h>
47 
48 #include "_libproc.h"
49 
50 extern char * const *environ;
51 
52 static int	getelfclass(int);
53 static int	proc_init(pid_t, int, int, struct proc_handle **);
54 
55 static int
56 getelfclass(int fd)
57 {
58 	GElf_Ehdr ehdr;
59 	Elf *e;
60 	int class;
61 
62 	class = ELFCLASSNONE;
63 
64 	if ((e = elf_begin(fd, ELF_C_READ, NULL)) == NULL)
65 		goto out;
66 	if (gelf_getehdr(e, &ehdr) == NULL)
67 		goto out;
68 	class = ehdr.e_ident[EI_CLASS];
69 out:
70 	(void)elf_end(e);
71 	return (class);
72 }
73 
74 static int
75 proc_init(pid_t pid, int flags, int status, struct proc_handle **pphdl)
76 {
77 	struct kinfo_proc *kp;
78 	struct proc_handle *phdl;
79 	int error, class, count, fd;
80 
81 	error = ENOMEM;
82 	if ((phdl = malloc(sizeof(*phdl))) == NULL)
83 		goto out;
84 
85 	memset(phdl, 0, sizeof(*phdl));
86 	phdl->public.pid = pid;
87 	phdl->flags = flags;
88 	phdl->status = status;
89 	phdl->procstat = procstat_open_sysctl();
90 	if (phdl->procstat == NULL)
91 		goto out;
92 
93 	/* Obtain a path to the executable. */
94 	if ((kp = procstat_getprocs(phdl->procstat, KERN_PROC_PID, pid,
95 	    &count)) == NULL)
96 		goto out;
97 	error = procstat_getpathname(phdl->procstat, kp, phdl->execpath,
98 	    sizeof(phdl->execpath));
99 	procstat_freeprocs(phdl->procstat, kp);
100 	if (error != 0)
101 		goto out;
102 
103 	/* Use it to determine the data model for the process. */
104 	if ((fd = open(phdl->execpath, O_RDONLY)) < 0) {
105 		error = errno;
106 		goto out;
107 	}
108 	class = getelfclass(fd);
109 	switch (class) {
110 	case ELFCLASS64:
111 		phdl->model = PR_MODEL_LP64;
112 		break;
113 	case ELFCLASS32:
114 		phdl->model = PR_MODEL_ILP32;
115 		break;
116 	case ELFCLASSNONE:
117 	default:
118 		error = EINVAL;
119 		break;
120 	}
121 	(void)close(fd);
122 
123 out:
124 	*pphdl = phdl;
125 	return (error);
126 }
127 
128 int
129 proc_attach(pid_t pid, int flags, struct proc_handle **pphdl)
130 {
131 	struct proc_handle *phdl;
132 	int error, status;
133 
134 	if (pid == 0 || (pid == getpid() && (flags & PATTACH_RDONLY) == 0))
135 		return (EINVAL);
136 	if (elf_version(EV_CURRENT) == EV_NONE)
137 		return (ENOENT);
138 
139 	/*
140 	 * Allocate memory for the process handle, a structure containing
141 	 * all things related to the process.
142 	 */
143 	error = proc_init(pid, flags, PS_RUN, &phdl);
144 	if (error != 0)
145 		goto out;
146 
147 	if ((flags & PATTACH_RDONLY) == 0) {
148 		if (ptrace(PT_ATTACH, proc_getpid(phdl), 0, 0) != 0) {
149 			error = errno;
150 			DPRINTF("ERROR: cannot ptrace child process %d", pid);
151 			goto out;
152 		}
153 
154 		/* Wait for the child process to stop. */
155 		if (waitpid(pid, &status, WUNTRACED) == -1) {
156 			error = errno;
157 			DPRINTF("ERROR: child process %d didn't stop as expected", pid);
158 			goto out;
159 		}
160 
161 		/* Check for an unexpected status. */
162 		if (!WIFSTOPPED(status))
163 			DPRINTFX("ERROR: child process %d status 0x%x", pid, status);
164 		else
165 			phdl->status = PS_STOP;
166 
167 		if ((flags & PATTACH_NOSTOP) != 0)
168 			proc_continue(phdl);
169 	}
170 
171 out:
172 	if (error != 0 && phdl != NULL) {
173 		proc_free(phdl);
174 		phdl = NULL;
175 	}
176 	*pphdl = phdl;
177 	return (error);
178 }
179 
180 int
181 proc_create(const char *file, char * const *argv, char * const *envp,
182     proc_child_func *pcf, void *child_arg, struct proc_handle **pphdl)
183 {
184 	struct proc_handle *phdl;
185 	int error, status;
186 	pid_t pid;
187 
188 	if (elf_version(EV_CURRENT) == EV_NONE)
189 		return (ENOENT);
190 
191 	error = 0;
192 	phdl = NULL;
193 
194 	if ((pid = fork()) == -1)
195 		error = errno;
196 	else if (pid == 0) {
197 		/* The child expects to be traced. */
198 		if (ptrace(PT_TRACE_ME, 0, 0, 0) != 0)
199 			_exit(1);
200 
201 		if (pcf != NULL)
202 			(*pcf)(child_arg);
203 
204 		if (envp != NULL)
205 			environ = envp;
206 
207 		execvp(file, argv);
208 
209 		_exit(2);
210 		/* NOTREACHED */
211 	} else {
212 		/* Wait for the child process to stop. */
213 		if (waitpid(pid, &status, WUNTRACED) == -1) {
214 			error = errno;
215 			DPRINTF("ERROR: child process %d didn't stop as expected", pid);
216 			goto bad;
217 		}
218 
219 		/* Check for an unexpected status. */
220 		if (!WIFSTOPPED(status)) {
221 			error = ENOENT;
222 			DPRINTFX("ERROR: child process %d status 0x%x", pid, status);
223 			goto bad;
224 		}
225 
226 		/* The parent owns the process handle. */
227 		error = proc_init(pid, 0, PS_IDLE, &phdl);
228 		if (error == 0)
229 			phdl->status = PS_STOP;
230 
231 bad:
232 		if (error != 0 && phdl != NULL) {
233 			proc_free(phdl);
234 			phdl = NULL;
235 		}
236 	}
237 	*pphdl = phdl;
238 	return (error);
239 }
240 
241 void
242 proc_free(struct proc_handle *phdl)
243 {
244 	struct file_info *file;
245 	size_t i;
246 
247 	for (i = 0; i < phdl->nmappings; i++) {
248 		file = phdl->mappings[i].file;
249 		if (file != NULL && --file->refs == 0) {
250 			if (file->elf != NULL) {
251 				(void)elf_end(file->elf);
252 				(void)close(file->fd);
253 				if (file->symtab.nsyms > 0)
254 					free(file->symtab.index);
255 				if (file->dynsymtab.nsyms > 0)
256 					free(file->dynsymtab.index);
257 			}
258 			free(file);
259 		}
260 	}
261 	if (phdl->maparrsz > 0)
262 		free(phdl->mappings);
263 	if (phdl->procstat != NULL)
264 		procstat_close(phdl->procstat);
265 	if (phdl->rdap != NULL)
266 		rd_delete(phdl->rdap);
267 	free(phdl);
268 }
269