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