1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #define	__EXTENSIONS__
29 #include <string.h>
30 #undef	__EXTENSIONS__
31 
32 #include <libgen.h>
33 #include <limits.h>
34 #include <stdio.h>
35 #include <errno.h>
36 #include <unistd.h>
37 #include <zone.h>
38 
39 #include "Pcontrol.h"
40 
41 /*
42  * Pexecname.c - Way too much code to attempt to derive the full pathname of
43  * the executable file from a process handle, be it dead or alive.
44  */
45 
46 /*
47  * Once we've computed a cwd and a relative path, we use try_exec() to
48  * form an absolute path, call resolvepath() on it, and then let the
49  * caller's function do the final confirmation.
50  */
51 static int
52 try_exec(const char *cwd, const char *path, char *buf,
53     int (*isexec)(const char *, void *), void *isdata)
54 {
55 	int i;
56 
57 	if (path[0] != '/')
58 		(void) snprintf(buf, PATH_MAX, "%s/%s", cwd, path);
59 	else
60 		(void) strcpy(buf, path);
61 
62 	dprintf("try_exec \"%s\"\n", buf);
63 
64 	if ((i = resolvepath(buf, buf, PATH_MAX)) > 0) {
65 		buf[i] = '\0';
66 		return (isexec(buf, isdata));
67 	}
68 
69 	return (0); /* resolvepath failed */
70 }
71 
72 /*
73  * The Pfindexec function contains the logic for the executable name dance.
74  * The caller provides a possible executable name or likely directory (the
75  * aout parameter), and a function which is responsible for doing any
76  * final confirmation on the executable pathname once a possible full
77  * pathname has been chosen.
78  */
79 char *
80 Pfindexec(struct ps_prochandle *P, const char *aout,
81     int (*isexec)(const char *, void *), void *isdata)
82 {
83 	char cwd[PATH_MAX * 2];
84 	char path[PATH_MAX];
85 	char buf[PATH_MAX];
86 	struct stat st;
87 	uintptr_t addr;
88 	char *p = path, *q;
89 
90 	if (P->execname)
91 		return (P->execname); /* Already found */
92 
93 	errno = 0; /* Set to zero so we can tell if stat() failed */
94 
95 	/*
96 	 * First try: use the provided default value, if it is not a directory.
97 	 * If the aout parameter turns out to be a directory, this is
98 	 * interpreted as the directory to use as an alternate cwd for
99 	 * our subsequent attempts to locate the executable.
100 	 */
101 	if (aout != NULL && stat(aout, &st) == 0 && !S_ISDIR(st.st_mode)) {
102 		if (try_exec(".", aout, buf, isexec, isdata))
103 			goto found;
104 		else
105 			aout = ".";
106 
107 	} else if (aout == NULL || errno != 0)
108 		aout = ".";
109 
110 	/*
111 	 * At this point 'aout' is either "." or an alternate cwd.  We use
112 	 * realpath(3c) to turn this into a full pathname free of ".", "..",
113 	 * and symlinks.  If this fails for some reason, fall back to "."
114 	 */
115 	if (realpath(aout, cwd) == NULL)
116 		(void) strcpy(cwd, ".");
117 
118 	/*
119 	 * Second try: read the string pointed to by the AT_SUN_EXECNAME
120 	 * auxv element, saved when the program was exec'd.  If the full
121 	 * pathname try_exec() forms fails, try again using just the
122 	 * basename appended to our cwd.  If that also fails, and the process
123 	 * is in a zone, try again with the zone path instead of our cwd.
124 	 */
125 	if ((addr = Pgetauxval(P, AT_SUN_EXECNAME)) != (uintptr_t)-1L &&
126 	    Pread_string(P, path, sizeof (path), (off_t)addr) > 0) {
127 		char		zpath[PATH_MAX];
128 		const psinfo_t	*pi = Ppsinfo(P);
129 
130 		if (try_exec(cwd, path, buf, isexec, isdata))
131 			goto found;
132 
133 		if (strchr(path, '/') != NULL && (p = basename(path)) != NULL &&
134 		    try_exec(cwd, p, buf, isexec, isdata))
135 			goto found;
136 
137 		if (getzoneid() == GLOBAL_ZONEID &&
138 		    pi->pr_zoneid != GLOBAL_ZONEID &&
139 		    zone_getattr(pi->pr_zoneid, ZONE_ATTR_ROOT, zpath,
140 			sizeof (zpath)) != -1) {
141 			/*
142 			 * try_exec() only combines its cwd and path arguments
143 			 * if path is relative; but in our case even an absolute
144 			 * path inside a zone is a relative path from the global
145 			 * zone perspective. So we turn a non-global zone's
146 			 * absolute path into a relative path here before
147 			 * calling try_exec().
148 			 */
149 			p = (path[0] == '/') ? path + 1 : path;
150 			if (try_exec(zpath, p, buf, isexec, isdata))
151 				goto found;
152 		}
153 	}
154 
155 	/*
156 	 * Third try: try using the first whitespace-separated token
157 	 * saved in the psinfo_t's pr_psargs (the initial value of argv[0]).
158 	 */
159 	if (Ppsinfo(P) != NULL) {
160 		(void) strncpy(path, P->psinfo.pr_psargs, PRARGSZ);
161 		path[PRARGSZ] = '\0';
162 
163 		if ((p = strchr(path, ' ')) != NULL)
164 			*p = '\0';
165 
166 		if (try_exec(cwd, path, buf, isexec, isdata))
167 			goto found;
168 
169 		if (strchr(path, '/') != NULL && (p = basename(path)) != NULL &&
170 		    try_exec(cwd, p, buf, isexec, isdata))
171 			goto found;
172 	}
173 
174 	/*
175 	 * Fourth try: read the string pointed to by argv[0] out of the
176 	 * stack in the process's address space.
177 	 */
178 	if (P->psinfo.pr_argv != NULL &&
179 	    Pread(P, &addr, sizeof (addr), P->psinfo.pr_argv) != -1 &&
180 	    Pread_string(P, path, sizeof (path), (off_t)addr) > 0) {
181 
182 		if (try_exec(cwd, path, buf, isexec, isdata))
183 			goto found;
184 
185 		if (strchr(path, '/') != NULL && (p = basename(path)) != NULL &&
186 		    try_exec(cwd, p, buf, isexec, isdata))
187 			goto found;
188 	}
189 
190 	/*
191 	 * Fifth try: read the process's $PATH environment variable and
192 	 * search each directory named there for the name matching pr_fname.
193 	 */
194 	if (Pgetenv(P, "PATH", cwd, sizeof (cwd)) != NULL) {
195 		/*
196 		 * If the name from pr_psargs contains pr_fname as its
197 		 * leading string, then accept the name from pr_psargs
198 		 * because more bytes are saved there.  Otherwise use
199 		 * pr_fname because this gives us new information.
200 		 */
201 		(void) strncpy(path, P->psinfo.pr_psargs, PRARGSZ);
202 		path[PRARGSZ] = '\0';
203 
204 		if ((p = strchr(path, ' ')) != NULL)
205 			*p = '\0';
206 
207 		if (strchr(path, '/') != NULL || strncmp(path,
208 		    P->psinfo.pr_fname, strlen(P->psinfo.pr_fname)) != 0)
209 			(void) strcpy(path, P->psinfo.pr_fname);
210 
211 		/*
212 		 * Now iterate over the $PATH elements, trying to form
213 		 * an executable pathname with each one.
214 		 */
215 		for (p = strtok_r(cwd, ":", &q); p != NULL;
216 		    p = strtok_r(NULL, ":", &q)) {
217 
218 			if (*p != '/')
219 				continue; /* Ignore anything relative */
220 
221 			if (try_exec(p, path, buf, isexec, isdata))
222 				goto found;
223 		}
224 	}
225 
226 	errno = ENOENT;
227 	return (NULL);
228 
229 found:
230 	if ((P->execname = strdup(buf)) == NULL)
231 		dprintf("failed to malloc; executable name is \"%s\"", buf);
232 
233 	return (P->execname);
234 }
235 
236 /*
237  * Callback function for Pfindexec().  We return a match if we can stat the
238  * suggested pathname and confirm its device and inode number match our
239  * previous information about the /proc/<pid>/object/a.out file.
240  */
241 static int
242 stat_exec(const char *path, struct stat64 *stp)
243 {
244 	struct stat64 st;
245 
246 	return (stat64(path, &st) == 0 && S_ISREG(st.st_mode) &&
247 	    stp->st_dev == st.st_dev && stp->st_ino == st.st_ino);
248 }
249 
250 /*
251  * Return the full pathname for the executable file.  If the process handle is
252  * a core file, we've already tried our best to get the executable name.
253  * Otherwise, we make an attempt using Pfindexec().
254  */
255 char *
256 Pexecname(struct ps_prochandle *P, char *buf, size_t buflen)
257 {
258 	if (P->execname == NULL && P->state != PS_DEAD && P->state != PS_IDLE) {
259 		char exec_name[PATH_MAX];
260 		char cwd[PATH_MAX];
261 		char proc_cwd[64];
262 		struct stat64 st;
263 		int ret;
264 
265 		/*
266 		 * Try to get the path information first.
267 		 */
268 		(void) snprintf(exec_name, sizeof (exec_name),
269 		    "%s/%d/path/a.out", procfs_path, (int)P->pid);
270 		if ((ret = readlink(exec_name, buf, buflen - 1)) > 0) {
271 			buf[ret] = '\0';
272 			return (buf);
273 		}
274 
275 		/*
276 		 * Stat the executable file so we can compare Pfindexec's
277 		 * suggestions to the actual device and inode number.
278 		 */
279 		(void) snprintf(exec_name, sizeof (exec_name),
280 		    "%s/%d/object/a.out", procfs_path, (int)P->pid);
281 
282 		if (stat64(exec_name, &st) != 0 || !S_ISREG(st.st_mode))
283 			return (NULL);
284 
285 		/*
286 		 * Attempt to figure out the current working directory of the
287 		 * target process.  This only works if the target process has
288 		 * not changed its current directory since it was exec'd.
289 		 */
290 		(void) snprintf(proc_cwd, sizeof (proc_cwd),
291 		    "%s/%d/path/cwd", procfs_path, (int)P->pid);
292 
293 		if ((ret = readlink(proc_cwd, cwd, PATH_MAX - 1)) > 0)
294 			cwd[ret] = '\0';
295 
296 		(void) Pfindexec(P, ret > 0 ? cwd : NULL,
297 		    (int (*)(const char *, void *))stat_exec, &st);
298 	}
299 
300 	if (P->execname != NULL) {
301 		(void) strncpy(buf, P->execname, buflen);
302 		return (buf);
303 	}
304 
305 	return (NULL);
306 }
307