Debian Codegraph @

lib/program_name.c

raw symbols SCIP
1 /*
2 * fstrcmp - fuzzy string compare library
3 * Copyright (C) 2009 Peter Miller
4 * Written by Peter Miller <[email protected]>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation; either version 3 of the
9 * License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <lib/ac/assert.h>
21 #include <lib/ac/stdlib.h>
22 #include <lib/ac/string.h>
23 #include <lib/ac/unistd.h>
24
25 #include <lib/program_name.h>
26
27
28 static char progname[256];
29
30
31 static void
32 fstrcmp_program_name_set_real(const char *name)
33 {
34 const char *cp;
35
36 if (!name)
37 name = "";
38 progname[0] = '\0';
39 if (!name)
40 return;
41
42 cp = name;
43 for (;;)
44 {
45 char *pnp;
46
47 if (*cp == '/')
48 {
49 /*
50 * Weird but true: some Unix implementations allow trailing
51 * slashes on command names. Ugh. Not POSIX conforming, either.
52 */
53 ++cp;
54 continue;
55 }
56 if (*cp == '\0')
57 break;
58
59 /*
60 * Libtool produces "temporary" binaries before "make install"
61 * that have "lt-" prefixes. Rip them off when we see them.
62 */
63 if (0 == memcmp(cp, "lt-", 3))
64 cp += 3;
65
66 pnp = progname;
67 for (;;)
68 {
69 if (pnp < progname + sizeof(progname) - 1)
70 *pnp++ = *cp;
71 ++cp;
72 if (*cp == '\0' || *cp == '/')
73 break;
74 }
75 *pnp = '\0';
76 }
77 }
78
79
80 const char *
81 fstrcmp_program_name_get(void)
82 {
83 if (progname[0])
84 return progname;
85
86 /*
87 * Does procfs have something useful?
88 */
89 {
90 int n;
91 char buf[2000];
92
93 n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
94 if (n > 0)
95 {
96 buf[n] = 0;
97 fstrcmp_program_name_set_real(buf);
98 }
99 }
100 if (progname[0])
101 return progname;
102
103 /*
104 * bash(1) sets the "_" environment variable,
105 * use that if available.
106 */
107 fstrcmp_program_name_set_real(getenv("_"));
108 if (progname[0])
109 return progname;
110
111 return "";
112 }
113
114
115 void
116 fstrcmp_program_name_set(const char *name)
117 {
118 fstrcmp_program_name_set_real(name);
119 }