Imported Upstream version 2.9.0
[debian/cc1111] / support / Util / 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    alloca replaced with malloc()/free() pair */
10
11 #include "system.h"
12 #include "findme.h"
13
14 const char * findProgramPath(const char * argv0) {
15     char * path = getenv("PATH");
16     char * pathbuf;
17     char * start, * chptr;
18     char * buf;
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     start = pathbuf = malloc(strlen(path) + 1);
28     if (pathbuf == NULL) return NULL;
29     buf = malloc(strlen(path) + strlen(argv0) + sizeof("/"));
30     if (buf == NULL) return NULL;       /* XXX can't happen */
31     strcpy(pathbuf, path);
32
33     chptr = NULL;
34     /*@-branchstate@*/
35     do {
36         if ((chptr = strchr(start, ':')))
37             *chptr = '\0';
38         sprintf(buf, "%s/%s", start, argv0);
39
40         if (!access(buf, X_OK)) {
41             free(pathbuf);
42             return buf;
43         }
44
45         if (chptr) 
46             start = chptr + 1;
47         else
48             start = NULL;
49     } while (start && *start);
50     /*@=branchstate@*/
51
52     free(buf);
53     free(pathbuf);
54
55     return NULL;
56 }