progreloc.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. /* Provide relocatable programs.
  2. Copyright (C) 2003-2009 Free Software Foundation, Inc.
  3. Written by Bruno Haible <bruno@clisp.org>, 2003.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #include <config.h>
  15. /* Specification. */
  16. #include "progname.h"
  17. #include <stdbool.h>
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <fcntl.h>
  22. #include <unistd.h>
  23. #include <sys/stat.h>
  24. /* Get declaration of _NSGetExecutablePath on MacOS X 10.2 or newer. */
  25. #if HAVE_MACH_O_DYLD_H
  26. # include <mach-o/dyld.h>
  27. #endif
  28. #if defined _WIN32 || defined __WIN32__
  29. # define WIN32_NATIVE
  30. #endif
  31. #if defined WIN32_NATIVE || defined __CYGWIN__
  32. # define WIN32_LEAN_AND_MEAN
  33. # include <windows.h>
  34. #endif
  35. #include "canonicalize.h"
  36. #include "relocatable.h"
  37. #ifdef NO_XMALLOC
  38. # include "areadlink.h"
  39. # define xreadlink areadlink
  40. #else
  41. # include "xreadlink.h"
  42. #endif
  43. #ifdef NO_XMALLOC
  44. # define xmalloc malloc
  45. # define xstrdup strdup
  46. #else
  47. # include "xalloc.h"
  48. #endif
  49. /* Pathname support.
  50. ISSLASH(C) tests whether C is a directory separator character.
  51. IS_PATH_WITH_DIR(P) tests whether P contains a directory specification.
  52. */
  53. #if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__
  54. /* Win32, Cygwin, OS/2, DOS */
  55. # define ISSLASH(C) ((C) == '/' || (C) == '\\')
  56. # define HAS_DEVICE(P) \
  57. ((((P)[0] >= 'A' && (P)[0] <= 'Z') || ((P)[0] >= 'a' && (P)[0] <= 'z')) \
  58. && (P)[1] == ':')
  59. # define IS_PATH_WITH_DIR(P) \
  60. (strchr (P, '/') != NULL || strchr (P, '\\') != NULL || HAS_DEVICE (P))
  61. # define FILE_SYSTEM_PREFIX_LEN(P) (HAS_DEVICE (P) ? 2 : 0)
  62. #else
  63. /* Unix */
  64. # define ISSLASH(C) ((C) == '/')
  65. # define IS_PATH_WITH_DIR(P) (strchr (P, '/') != NULL)
  66. # define FILE_SYSTEM_PREFIX_LEN(P) 0
  67. #endif
  68. /* The results of open() in this file are not used with fchdir,
  69. therefore save some unnecessary work in fchdir.c. */
  70. #undef open
  71. #undef close
  72. #undef set_program_name
  73. #if ENABLE_RELOCATABLE
  74. #ifdef __linux__
  75. /* File descriptor of the executable.
  76. (Only used to verify that we find the correct executable.) */
  77. static int executable_fd = -1;
  78. #endif
  79. /* Tests whether a given pathname may belong to the executable. */
  80. static bool
  81. maybe_executable (const char *filename)
  82. {
  83. /* Woe32 lacks the access() function, but Cygwin doesn't. */
  84. #if !(defined WIN32_NATIVE && !defined __CYGWIN__)
  85. if (access (filename, X_OK) < 0)
  86. return false;
  87. #ifdef __linux__
  88. if (executable_fd >= 0)
  89. {
  90. /* If we already have an executable_fd, check that filename points to
  91. the same inode. */
  92. struct stat statexe;
  93. struct stat statfile;
  94. if (fstat (executable_fd, &statexe) >= 0)
  95. {
  96. if (stat (filename, &statfile) < 0)
  97. return false;
  98. if (!(statfile.st_dev
  99. && statfile.st_dev == statexe.st_dev
  100. && statfile.st_ino == statexe.st_ino))
  101. return false;
  102. }
  103. }
  104. #endif
  105. #endif
  106. return true;
  107. }
  108. /* Determine the full pathname of the current executable, freshly allocated.
  109. Return NULL if unknown.
  110. Guaranteed to work on Linux and Woe32. Likely to work on the other
  111. Unixes (maybe except BeOS), under most conditions. */
  112. static char *
  113. find_executable (const char *argv0)
  114. {
  115. #if defined WIN32_NATIVE || defined __CYGWIN__
  116. char location[MAX_PATH];
  117. int length = GetModuleFileName (NULL, location, sizeof (location));
  118. if (length < 0)
  119. return NULL;
  120. if (!IS_PATH_WITH_DIR (location))
  121. /* Shouldn't happen. */
  122. return NULL;
  123. {
  124. #if defined __CYGWIN__
  125. /* cygwin-1.5.13 (2005-03-01) or newer would also allow a Linux-like
  126. implementation: readlink of "/proc/self/exe". But using the
  127. result of the Win32 system call is simpler and is consistent with the
  128. code in relocatable.c. */
  129. /* On Cygwin, we need to convert paths coming from Win32 system calls
  130. to the Unix-like slashified notation. */
  131. static char location_as_posix_path[2 * MAX_PATH];
  132. /* There's no error return defined for cygwin_conv_to_posix_path.
  133. See cygwin-api/func-cygwin-conv-to-posix-path.html.
  134. Does it overflow the buffer of expected size MAX_PATH or does it
  135. truncate the path? I don't know. Let's catch both. */
  136. cygwin_conv_to_posix_path (location, location_as_posix_path);
  137. location_as_posix_path[MAX_PATH - 1] = '\0';
  138. if (strlen (location_as_posix_path) >= MAX_PATH - 1)
  139. /* A sign of buffer overflow or path truncation. */
  140. return NULL;
  141. /* Call canonicalize_file_name, because Cygwin supports symbolic links. */
  142. return canonicalize_file_name (location_as_posix_path);
  143. #else
  144. return xstrdup (location);
  145. #endif
  146. }
  147. #else /* Unix && !Cygwin */
  148. #ifdef __linux__
  149. /* The executable is accessible as /proc/<pid>/exe. In newer Linux
  150. versions, also as /proc/self/exe. Linux >= 2.1 provides a symlink
  151. to the true pathname; older Linux versions give only device and ino,
  152. enclosed in brackets, which we cannot use here. */
  153. {
  154. char *link;
  155. link = xreadlink ("/proc/self/exe");
  156. if (link != NULL && link[0] != '[')
  157. return link;
  158. if (executable_fd < 0)
  159. executable_fd = open ("/proc/self/exe", O_RDONLY, 0);
  160. {
  161. char buf[6+10+5];
  162. sprintf (buf, "/proc/%d/exe", getpid ());
  163. link = xreadlink (buf);
  164. if (link != NULL && link[0] != '[')
  165. return link;
  166. if (executable_fd < 0)
  167. executable_fd = open (buf, O_RDONLY, 0);
  168. }
  169. }
  170. #endif
  171. #if HAVE_MACH_O_DYLD_H && HAVE__NSGETEXECUTABLEPATH
  172. /* On MacOS X 10.2 or newer, the function
  173. int _NSGetExecutablePath (char *buf, uint32_t *bufsize);
  174. can be used to retrieve the executable's full path. */
  175. char location[4096];
  176. unsigned int length = sizeof (location);
  177. if (_NSGetExecutablePath (location, &length) == 0
  178. && location[0] == '/')
  179. return canonicalize_file_name (location);
  180. #endif
  181. /* Guess the executable's full path. We assume the executable has been
  182. called via execlp() or execvp() with properly set up argv[0]. The
  183. login(1) convention to add a '-' prefix to argv[0] is not supported. */
  184. {
  185. bool has_slash = false;
  186. {
  187. const char *p;
  188. for (p = argv0; *p; p++)
  189. if (*p == '/')
  190. {
  191. has_slash = true;
  192. break;
  193. }
  194. }
  195. if (!has_slash)
  196. {
  197. /* exec searches paths without slashes in the directory list given
  198. by $PATH. */
  199. const char *path = getenv ("PATH");
  200. if (path != NULL)
  201. {
  202. const char *p;
  203. const char *p_next;
  204. for (p = path; *p; p = p_next)
  205. {
  206. const char *q;
  207. size_t p_len;
  208. char *concat_name;
  209. for (q = p; *q; q++)
  210. if (*q == ':')
  211. break;
  212. p_len = q - p;
  213. p_next = (*q == '\0' ? q : q + 1);
  214. /* We have a path item at p, of length p_len.
  215. Now concatenate the path item and argv0. */
  216. concat_name = (char *) xmalloc (p_len + strlen (argv0) + 2);
  217. #ifdef NO_XMALLOC
  218. if (concat_name == NULL)
  219. return NULL;
  220. #endif
  221. if (p_len == 0)
  222. /* An empty PATH element designates the current directory. */
  223. strcpy (concat_name, argv0);
  224. else
  225. {
  226. memcpy (concat_name, p, p_len);
  227. concat_name[p_len] = '/';
  228. strcpy (concat_name + p_len + 1, argv0);
  229. }
  230. if (maybe_executable (concat_name))
  231. return canonicalize_file_name (concat_name);
  232. free (concat_name);
  233. }
  234. }
  235. /* Not found in the PATH, assume the current directory. */
  236. }
  237. /* exec treats paths containing slashes as relative to the current
  238. directory. */
  239. if (maybe_executable (argv0))
  240. return canonicalize_file_name (argv0);
  241. }
  242. /* No way to find the executable. */
  243. return NULL;
  244. #endif
  245. }
  246. /* Full pathname of executable, or NULL. */
  247. static char *executable_fullname;
  248. static void
  249. prepare_relocate (const char *orig_installprefix, const char *orig_installdir,
  250. const char *argv0)
  251. {
  252. char *curr_prefix;
  253. /* Determine the full pathname of the current executable. */
  254. executable_fullname = find_executable (argv0);
  255. /* Determine the current installation prefix from it. */
  256. curr_prefix = compute_curr_prefix (orig_installprefix, orig_installdir,
  257. executable_fullname);
  258. if (curr_prefix != NULL)
  259. {
  260. /* Now pass this prefix to all copies of the relocate.c source file. */
  261. set_relocation_prefix (orig_installprefix, curr_prefix);
  262. free (curr_prefix);
  263. }
  264. }
  265. /* Set program_name, based on argv[0], and original installation prefix and
  266. directory, for relocatability. */
  267. void
  268. set_program_name_and_installdir (const char *argv0,
  269. const char *orig_installprefix,
  270. const char *orig_installdir)
  271. {
  272. const char *argv0_stripped = argv0;
  273. /* Relocatable programs are renamed to .bin by install-reloc. Or, more
  274. generally, their suffix is changed from $exeext to .bin$exeext.
  275. Remove the ".bin" here. */
  276. {
  277. size_t argv0_len = strlen (argv0);
  278. const size_t exeext_len = sizeof (EXEEXT) - sizeof ("");
  279. if (argv0_len > 4 + exeext_len)
  280. if (memcmp (argv0 + argv0_len - exeext_len - 4, ".bin", 4) == 0)
  281. {
  282. if (sizeof (EXEEXT) > sizeof (""))
  283. {
  284. /* Compare using an inlined copy of c_strncasecmp(), because
  285. the filenames may have undergone a case conversion since
  286. they were packaged. In other words, EXEEXT may be ".exe"
  287. on one system and ".EXE" on another. */
  288. static const char exeext[] = EXEEXT;
  289. const char *s1 = argv0 + argv0_len - exeext_len;
  290. const char *s2 = exeext;
  291. for (; *s1 != '\0'; s1++, s2++)
  292. {
  293. unsigned char c1 = *s1;
  294. unsigned char c2 = *s2;
  295. if ((c1 >= 'A' && c1 <= 'Z' ? c1 - 'A' + 'a' : c1)
  296. != (c2 >= 'A' && c2 <= 'Z' ? c2 - 'A' + 'a' : c2))
  297. goto done_stripping;
  298. }
  299. }
  300. /* Remove ".bin" before EXEEXT or its equivalent. */
  301. {
  302. char *shorter = (char *) xmalloc (argv0_len - 4 + 1);
  303. #ifdef NO_XMALLOC
  304. if (shorter != NULL)
  305. #endif
  306. {
  307. memcpy (shorter, argv0, argv0_len - exeext_len - 4);
  308. if (sizeof (EXEEXT) > sizeof (""))
  309. memcpy (shorter + argv0_len - exeext_len - 4,
  310. argv0 + argv0_len - exeext_len - 4,
  311. exeext_len);
  312. shorter[argv0_len - 4] = '\0';
  313. argv0_stripped = shorter;
  314. }
  315. }
  316. done_stripping: ;
  317. }
  318. }
  319. set_program_name (argv0_stripped);
  320. prepare_relocate (orig_installprefix, orig_installdir, argv0);
  321. }
  322. /* Return the full pathname of the current executable, based on the earlier
  323. call to set_program_name_and_installdir. Return NULL if unknown. */
  324. char *
  325. get_full_program_name (void)
  326. {
  327. return executable_fullname;
  328. }
  329. #endif