1: /* Provide relocatable programs.
2: Copyright (C) 2003-2019 Free Software Foundation, Inc.
3: Written by Bruno Haible <bruno@clisp.org>, 2003.
4:
5: This program is free software: you can redistribute it and/or modify
6: it under the terms of the GNU General Public License as published by
7: the Free Software Foundation; either version 3 of the License, or
8: (at your option) any later version.
9:
10: This program is distributed in the hope that it will be useful,
11: but WITHOUT ANY WARRANTY; without even the implied warranty of
12: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13: GNU General Public License for more details.
14:
15: You should have received a copy of the GNU General Public License
16: along with this program. If not, see <https://www.gnu.org/licenses/>. */
17:
18:
19: #define _GL_USE_STDLIB_ALLOC 1
20: #include <config.h>
21:
22: /* Specification. */
23: #include "progname.h"
24:
25: #include <errno.h>
26: #include <stdbool.h>
27: #include <stdio.h>
28: #include <stdlib.h>
29: #include <string.h>
30: #include <fcntl.h>
31: #include <unistd.h>
32: #include <sys/stat.h>
33:
34: /* Get declaration of _NSGetExecutablePath on Mac OS X 10.2 or newer. */
35: #if HAVE_MACH_O_DYLD_H
36: # include <mach-o/dyld.h>
37: #endif
38:
39: #if defined _WIN32 && !defined __CYGWIN__
40: # define WINDOWS_NATIVE
41: #endif
42:
43: #ifdef WINDOWS_NATIVE
44: # define WIN32_LEAN_AND_MEAN
45: # include <windows.h>
46: #endif
47:
48: #ifdef __EMX__
49: # define INCL_DOS
50: # include <os2.h>
51: #endif
52:
53: #include "relocatable.h"
54:
55: #ifdef NO_XMALLOC
56: # include "areadlink.h"
57: # define xreadlink areadlink
58: #else
59: # include "xreadlink.h"
60: #endif
61:
62: #ifdef NO_XMALLOC
63: # define xmalloc malloc
64: # define xstrdup strdup
65: #else
66: # include "xalloc.h"
67: #endif
68:
69: #ifndef O_EXEC
70: # define O_EXEC O_RDONLY /* This is often close enough in older systems. */
71: #endif
72:
73: /* Declare canonicalize_file_name.
74: The <stdlib.h> included above may be the system's one, not the gnulib
75: one. */
76: extern char * canonicalize_file_name (const char *name);
77:
78: /* Pathname support.
79: ISSLASH(C) tests whether C is a directory separator character.
80: IS_PATH_WITH_DIR(P) tests whether P contains a directory specification.
81: */
82: #if (defined _WIN32 && !defined __CYGWIN__) || defined __EMX__ || defined __DJGPP__
83: /* Native Windows, OS/2, DOS */
84: # define ISSLASH(C) ((C) == '/' || (C) == '\\')
85: # define HAS_DEVICE(P) \
86: ((((P)[0] >= 'A' && (P)[0] <= 'Z') || ((P)[0] >= 'a' && (P)[0] <= 'z')) \
87: && (P)[1] == ':')
88: # define IS_PATH_WITH_DIR(P) \
89: (strchr (P, '/') != NULL || strchr (P, '\\') != NULL || HAS_DEVICE (P))
90: # define FILE_SYSTEM_PREFIX_LEN(P) (HAS_DEVICE (P) ? 2 : 0)
91: #else
92: /* Unix */
93: # define ISSLASH(C) ((C) == '/')
94: # define IS_PATH_WITH_DIR(P) (strchr (P, '/') != NULL)
95: # define FILE_SYSTEM_PREFIX_LEN(P) 0
96: #endif
97:
98: /* Use the system functions, not the gnulib overrides in this file. */
99: #undef sprintf
100:
101: #undef set_program_name
102:
103:
104: #if ENABLE_RELOCATABLE
105:
106: #ifdef __sun
107:
108: /* Helper function, from gnulib module 'safe-read'. */
109: static size_t
110: safe_read (int fd, void *buf, size_t count)
111: {
112: for (;;)
113: {
114: ssize_t result = read (fd, buf, count);
115:
116: if (0 <= result || errno != EINTR)
117: return result;
118: }
119: }
120:
121: /* Helper function, from gnulib module 'full-read'. */
122: static size_t
123: full_read (int fd, void *buf, size_t count)
124: {
125: size_t total = 0;
126: const char *ptr = (const char *) buf;
127:
128: while (count > 0)
129: {
130: size_t n = safe_read (fd, ptr, count);
131: if (n == (size_t) -1)
132: break;
133: if (n == 0)
134: {
135: errno = 0;
136: break;
137: }
138: total += n;
139: ptr += n;
140: count -= n;
141: }
142:
143: return total;
144: }
145:
146: #endif
147:
148: #if defined __linux__ || defined __CYGWIN__
149: /* File descriptor of the executable.
150: (Only used to verify that we find the correct executable.) */
151: static int executable_fd = -1;
152: #endif
153:
154: /* Tests whether a given pathname may belong to the executable. */
155: static bool
156: maybe_executable (const char *filename)
157: {
158: /* The native Windows API lacks the access() function. */
159: #if !defined WINDOWS_NATIVE
160: if (access (filename, X_OK) < 0)
161: return false;
162: #endif
163:
164: #if defined __linux__ || defined __CYGWIN__
165: if (executable_fd >= 0)
166: {
167: /* If we already have an executable_fd, check that filename points to
168: the same inode. */
169: struct stat statexe;
170: struct stat statfile;
171:
172: if (fstat (executable_fd, &statexe) >= 0)
173: {
174: if (stat (filename, &statfile) < 0)
175: return false;
176: if (!(statfile.st_dev
177: && statfile.st_dev == statexe.st_dev
178: && statfile.st_ino == statexe.st_ino))
179: return false;
180: }
181: }
182: #endif
183:
184: return true;
185: }
186:
187: /* Determine the full pathname of the current executable, freshly allocated.
188: Return NULL if unknown.
189: Guaranteed to work on Linux and native Windows. Likely to work on the
190: other Unixes (maybe except BeOS), under most conditions. */
191: static char *
192: find_executable (const char *argv0)
193: {
194: #if defined WINDOWS_NATIVE
195: /* Native Windows only.
196: On Cygwin, it is better to use the Cygwin provided /proc interface, than
197: to use native Windows API and cygwin_conv_to_posix_path, because it
198: supports longer file names
199: (see <https://cygwin.com/ml/cygwin/2011-01/msg00410.html>). */
200: char location[MAX_PATH];
201: int length = GetModuleFileName (NULL, location, sizeof (location));
202: if (length < 0)
203: return NULL;
204: if (!IS_PATH_WITH_DIR (location))
205: /* Shouldn't happen. */
206: return NULL;
207: return xstrdup (location);
208: #elif defined __EMX__
209: PPIB ppib;
210: char location[CCHMAXPATH];
211:
212: /* See http://cyberkinetica.homeunix.net/os2tk45/cp1/619_L2H_DosGetInfoBlocksSynt.html
213: for specification of DosGetInfoBlocks(). */
214: if (DosGetInfoBlocks (NULL, &ppib))
215: return NULL;
216:
217: /* See http://cyberkinetica.homeunix.net/os2tk45/cp1/1247_L2H_DosQueryModuleNameSy.html
218: for specification of DosQueryModuleName(). */
219: if (DosQueryModuleName (ppib->pib_hmte, sizeof (location), location))
220: return NULL;
221:
222: _fnslashify (location);
223:
224: return xstrdup (location);
225: #else /* Unix */
226: # if defined __linux__
227: /* The executable is accessible as /proc/<pid>/exe. In newer Linux
228: versions, also as /proc/self/exe. Linux >= 2.1 provides a symlink
229: to the true pathname; older Linux versions give only device and ino,
230: enclosed in brackets, which we cannot use here. */
231: {
232: char *link;
233:
234: link = xreadlink ("/proc/self/exe");
235: if (link != NULL && link[0] != '[')
236: return link;
237: if (executable_fd < 0)
238: executable_fd = open ("/proc/self/exe", O_EXEC, 0);
239:
240: {
241: char buf[6+10+5];
242: sprintf (buf, "/proc/%d/exe", getpid ());
243: link = xreadlink (buf);
244: if (link != NULL && link[0] != '[')
245: return link;
246: if (executable_fd < 0)
247: executable_fd = open (buf, O_EXEC, 0);
248: }
249: }
250: # endif
251: # if defined __ANDROID__ || defined __FreeBSD_kernel__
252: /* On Android and GNU/kFreeBSD, the executable is accessible as
253: /proc/<pid>/exe and /proc/self/exe. */
254: {
255: char *link;
256:
257: link = xreadlink ("/proc/self/exe");
258: if (link != NULL)
259: return link;
260: }
261: # endif
262: # if defined __FreeBSD__ || defined __DragonFly__
263: /* In FreeBSD >= 5.0, the executable is accessible as /proc/<pid>/file and
264: /proc/curproc/file. */
265: {
266: char *link;
267:
268: link = xreadlink ("/proc/curproc/file");
269: if (link != NULL)
270: {
271: if (strcmp (link, "unknown") != 0)
272: return link;
273: free (link);
274: }
275: }
276: # endif
277: # if defined __NetBSD__
278: /* In NetBSD >= 4.0, the executable is accessible as /proc/<pid>/exe and
279: /proc/curproc/exe. */
280: {
281: char *link;
282:
283: link = xreadlink ("/proc/curproc/exe");
284: if (link != NULL)
285: return link;
286: }
287: # endif
288: # if defined __sun
289: /* On Solaris >= 11.4, /proc/<pid>/execname and /proc/self/execname contains
290: the name of the executable, either as an absolute file name or relative to
291: the current directory. */
292: {
293: char namebuf[4096];
294: int fd = open ("/proc/self/execname", O_RDONLY, 0);
295: if (fd >= 0)
296: {
297: size_t len = full_read (fd, namebuf, sizeof (namebuf));
298: close (fd);
299: if (len > 0 && len < sizeof (namebuf))
300: {
301: namebuf[len] = '\0';
302: return canonicalize_file_name (namebuf);
303: }
304: }
305: }
306: # endif
307: # if defined __CYGWIN__
308: /* The executable is accessible as /proc/<pid>/exe, at least in
309: Cygwin >= 1.5. */
310: {
311: char *link;
312:
313: link = xreadlink ("/proc/self/exe");
314: if (link != NULL)
315: return link;
316: if (executable_fd < 0)
317: executable_fd = open ("/proc/self/exe", O_EXEC, 0);
318: }
319: # endif
320: # if HAVE_MACH_O_DYLD_H && HAVE__NSGETEXECUTABLEPATH
321: /* On Mac OS X 10.2 or newer, the function
322: int _NSGetExecutablePath (char *buf, uint32_t *bufsize);
323: can be used to retrieve the executable's full path. */
324: char location[4096];
325: unsigned int length = sizeof (location);
326: if (_NSGetExecutablePath (location, &length) == 0
327: && location[0] == '/')
328: return canonicalize_file_name (location);
329: # endif
330: /* Guess the executable's full path. We assume the executable has been
331: called via execlp() or execvp() with properly set up argv[0]. The
332: login(1) convention to add a '-' prefix to argv[0] is not supported. */
333: {
334: bool has_slash = false;
335: {
336: const char *p;
337: for (p = argv0; *p; p++)
338: if (*p == '/')
339: {
340: has_slash = true;
341: break;
342: }
343: }
344: if (!has_slash)
345: {
346: /* exec searches paths without slashes in the directory list given
347: by $PATH. */
348: const char *path = getenv ("PATH");
349:
350: if (path != NULL)
351: {
352: const char *p;
353: const char *p_next;
354:
355: for (p = path; *p; p = p_next)
356: {
357: const char *q;
358: size_t p_len;
359: char *concat_name;
360:
361: for (q = p; *q; q++)
362: if (*q == ':')
363: break;
364: p_len = q - p;
365: p_next = (*q == '\0' ? q : q + 1);
366:
367: /* We have a path item at p, of length p_len.
368: Now concatenate the path item and argv0. */
369: concat_name = (char *) xmalloc (p_len + strlen (argv0) + 2);
370: # ifdef NO_XMALLOC
371: if (concat_name == NULL)
372: return NULL;
373: # endif
374: if (p_len == 0)
375: /* An empty PATH element designates the current directory. */
376: strcpy (concat_name, argv0);
377: else
378: {
379: memcpy (concat_name, p, p_len);
380: concat_name[p_len] = '/';
381: strcpy (concat_name + p_len + 1, argv0);
382: }
383: if (maybe_executable (concat_name))
384: return canonicalize_file_name (concat_name);
385: free (concat_name);
386: }
387: }
388: /* Not found in the PATH, assume the current directory. */
389: }
390: /* exec treats paths containing slashes as relative to the current
391: directory. */
392: if (maybe_executable (argv0))
393: return canonicalize_file_name (argv0);
394: }
395: /* No way to find the executable. */
396: return NULL;
397: #endif
398: }
399:
400: /* Full pathname of executable, or NULL. */
401: static char *executable_fullname;
402:
403: static void
404: prepare_relocate (const char *orig_installprefix, const char *orig_installdir,
405: const char *argv0)
406: {
407: char *curr_prefix;
408:
409: /* Determine the full pathname of the current executable. */
410: executable_fullname = find_executable (argv0);
411:
412: /* Determine the current installation prefix from it. */
413: curr_prefix = compute_curr_prefix (orig_installprefix, orig_installdir,
414: executable_fullname);
415: if (curr_prefix != NULL)
416: {
417: /* Now pass this prefix to all copies of the relocate.c source file. */
418: set_relocation_prefix (orig_installprefix, curr_prefix);
419:
420: free (curr_prefix);
421: }
422: }
423:
424: /* Set program_name, based on argv[0], and original installation prefix and
425: directory, for relocatability. */
426: void
427: set_program_name_and_installdir (const char *argv0,
428: const char *orig_installprefix,
429: const char *orig_installdir)
430: {
431: const char *argv0_stripped = argv0;
432:
433: /* Relocatable programs are renamed to .bin by install-reloc. Or, more
434: generally, their suffix is changed from $exeext to .bin$exeext.
435: Remove the ".bin" here. */
436: {
437: size_t argv0_len = strlen (argv0);
438: const size_t exeext_len = sizeof (EXEEXT) - sizeof ("");
439: if (argv0_len > 4 + exeext_len)
440: if (memcmp (argv0 + argv0_len - exeext_len - 4, ".bin", 4) == 0)
441: {
442: if (sizeof (EXEEXT) > sizeof (""))
443: {
444: /* Compare using an inlined copy of c_strncasecmp(), because
445: the filenames may have undergone a case conversion since
446: they were packaged. In other words, EXEEXT may be ".exe"
447: on one system and ".EXE" on another. */
448: static const char exeext[] = EXEEXT;
449: const char *s1 = argv0 + argv0_len - exeext_len;
450: const char *s2 = exeext;
451: for (; *s1 != '\0'; s1++, s2++)
452: {
453: unsigned char c1 = *s1;
454: unsigned char c2 = *s2;
455: if ((c1 >= 'A' && c1 <= 'Z' ? c1 - 'A' + 'a' : c1)
456: != (c2 >= 'A' && c2 <= 'Z' ? c2 - 'A' + 'a' : c2))
457: goto done_stripping;
458: }
459: }
460: /* Remove ".bin" before EXEEXT or its equivalent. */
461: {
462: char *shorter = (char *) xmalloc (argv0_len - 4 + 1);
463: #ifdef NO_XMALLOC
464: if (shorter != NULL)
465: #endif
466: {
467: memcpy (shorter, argv0, argv0_len - exeext_len - 4);
468: if (sizeof (EXEEXT) > sizeof (""))
469: memcpy (shorter + argv0_len - exeext_len - 4,
470: argv0 + argv0_len - exeext_len - 4,
471: exeext_len);
472: shorter[argv0_len - 4] = '\0';
473: argv0_stripped = shorter;
474: }
475: }
476: done_stripping: ;
477: }
478: }
479:
480: set_program_name (argv0_stripped);
481:
482: prepare_relocate (orig_installprefix, orig_installdir, argv0);
483: }
484:
485: /* Return the full pathname of the current executable, based on the earlier
486: call to set_program_name_and_installdir. Return NULL if unknown. */
487: char *
488: get_full_program_name (void)
489: {
490: return executable_fullname;
491: }
492:
493: #endif
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>