Make hard-linking work when a device has an st_dev of 0.
[rsync/rsync.git] / popt / findme.c
1 /** \ingroup popt
2  * \file popt/findme.c
3  */
4
5 /* (C) 1998-2002 Red Hat, Inc. -- Licensing details are in the COPYING
6    file accompanying popt source distributions, available from 
7    ftp://ftp.rpm.org/pub/rpm/dist. */
8
9 #include "system.h"
10 #include "findme.h"
11
12 const char * findProgramPath(const char * argv0)
13 {
14     char * path = getenv("PATH");
15     char * pathbuf;
16     char * start, * chptr;
17     char * buf;
18     size_t bufsize;
19
20     if (argv0 == NULL) return NULL;     /* XXX can't happen */
21     /* If there is a / in the argv[0], it has to be an absolute path */
22     if (strchr(argv0, '/'))
23         return xstrdup(argv0);
24
25     if (path == NULL) return NULL;
26
27     bufsize = strlen(path) + 1;
28     start = pathbuf = alloca(bufsize);
29     if (pathbuf == NULL) return NULL;   /* XXX can't happen */
30     strlcpy(pathbuf, path, bufsize);
31     bufsize += sizeof "/" - 1 + strlen(argv0);
32     buf = malloc(bufsize);
33     if (buf == NULL) return NULL;       /* XXX can't happen */
34
35     chptr = NULL;
36     /*@-branchstate@*/
37     do {
38         if ((chptr = strchr(start, ':')))
39             *chptr = '\0';
40         snprintf(buf, bufsize, "%s/%s", start, argv0);
41
42         if (!access(buf, X_OK))
43             return buf;
44
45         if (chptr) 
46             start = chptr + 1;
47         else
48             start = NULL;
49     } while (start && *start);
50     /*@=branchstate@*/
51
52     free(buf);
53
54     return NULL;
55 }