1/*
2 * Copyright © 2003 Felix Kuehling
3 * Copyright © 2018 Advanced Micro Devices, Inc.
4 * All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sub license, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
16 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 * NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS, AUTHORS
18 * AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21 * USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 * The above copyright notice and this permission notice (including the
24 * next paragraph) shall be included in all copies or substantial portions
25 * of the Software.
26 */
27
28#include "u_process.h"
29#include "detect_os.h"
30#include "macros.h"
31#include <string.h>
32#include <errno.h>
33#include <stdlib.h>
34
35#undef GET_PROGRAM_NAME
36
37#if DETECT_OS_WINDOWS
38#include <windows.h>
39#else
40#include <unistd.h>
41#endif
42
43#if DETECT_OS_APPLE
44#include <mach-o/dyld.h>
45#endif
46
47#if DETECT_OS_FREEBSD
48#include <sys/types.h>
49#include <sys/sysctl.h>
50#endif
51
52#if defined(__linux__) && defined(HAVE_PROGRAM_INVOCATION_NAME)
53
54static char *path = NULL;
55
56static void __freeProgramPath()
57{
58   free(path);
59   path = NULL;
60}
61
62static const char *
63__getProgramName()
64{
65   char * arg = strrchr(program_invocation_name, '/');
66   if (arg) {
67      /* If the / character was found this is likely a linux path or
68       * an invocation path for a 64-bit wine program.
69       *
70       * However, some programs pass command line arguments into argv[0].
71       * Strip these arguments out by using the realpath only if it was
72       * a prefix of the invocation name.
73       */
74      if (!path) {
75         path = realpath("/proc/self/exe", NULL);
76         atexit(__freeProgramPath);
77      }
78
79      if (path && strncmp(path, program_invocation_name, strlen(path)) == 0) {
80         /* This shouldn't be null because path is a a prefix,
81          * but check it anyway since path is static. */
82         char * name = strrchr(path, '/');
83         if (name)
84            return name + 1;
85      }
86
87      return arg+1;
88   }
89
90   /* If there was no '/' at all we likely have a windows like path from
91    * a wine application.
92    */
93   arg = strrchr(program_invocation_name, '\\');
94   if (arg)
95      return arg+1;
96
97   return program_invocation_name;
98}
99#    define GET_PROGRAM_NAME() __getProgramName()
100#elif defined(HAVE_PROGRAM_INVOCATION_NAME)
101#    define GET_PROGRAM_NAME() program_invocation_short_name
102#elif defined(__FreeBSD__) && (__FreeBSD__ >= 2)
103#    include <osreldate.h>
104#    if (__FreeBSD_version >= 440000)
105#        define GET_PROGRAM_NAME() getprogname()
106#    endif
107#elif defined(__NetBSD__)
108#    include <sys/param.h>
109#    if defined(__NetBSD_Version__) && (__NetBSD_Version__ >= 106000100)
110#        define GET_PROGRAM_NAME() getprogname()
111#    endif
112#elif defined(__DragonFly__)
113#    define GET_PROGRAM_NAME() getprogname()
114#elif defined(__APPLE__)
115#    define GET_PROGRAM_NAME() getprogname()
116#elif defined(ANDROID)
117#    define GET_PROGRAM_NAME() getprogname()
118#elif defined(__sun)
119/* Solaris has getexecname() which returns the full path - return just
120   the basename to match BSD getprogname() */
121#    include <libgen.h>
122
123static const char *
124__getProgramName()
125{
126    static const char *progname;
127
128    if (progname == NULL) {
129        const char *e = getexecname();
130        if (e != NULL) {
131            /* Have to make a copy since getexecname can return a readonly
132               string, but basename expects to be able to modify its arg. */
133            char *n = strdup(e);
134            if (n != NULL) {
135                progname = basename(n);
136            }
137        }
138    }
139    return progname;
140}
141
142#    define GET_PROGRAM_NAME() __getProgramName()
143#elif defined(WIN32)
144static const char *
145__getProgramName()
146{
147   static const char *progname;
148   if (progname == NULL) {
149      static char buf[MAX_PATH];
150      GetModuleFileNameA(NULL, buf, sizeof(buf));
151      progname = strrchr(buf, '\\');
152      if (progname)
153         progname++;
154      else
155         progname = buf;
156   }
157   return progname;
158}
159#        define GET_PROGRAM_NAME() __getProgramName()
160#elif defined(__HAIKU__)
161#    include <libgen.h>
162extern char **__libc_argv;
163extern int __libc_argc;
164
165static const char *
166__getProgramName()
167{
168    static const char *progname;
169
170    if (progname == NULL) {
171        char *n = strdup(__libc_argv[0]);
172        if (n != NULL) {
173            progname = basename(n);
174        }
175    }
176    return progname;
177}
178#    define GET_PROGRAM_NAME() __getProgramName()
179#endif
180
181#if !defined(GET_PROGRAM_NAME)
182#    if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__UCLIBC__) || defined(ANDROID)
183/* This is a hack. It's said to work on OpenBSD, NetBSD and GNU.
184 * Rogelio M.Serrano Jr. reported it's also working with UCLIBC. It's
185 * used as a last resort, if there is no documented facility available. */
186static const char *
187__getProgramName()
188{
189    extern const char *__progname;
190    char * arg = strrchr(__progname, '/');
191    if (arg)
192        return arg+1;
193    else
194        return __progname;
195}
196#        define GET_PROGRAM_NAME() __getProgramName()
197#    else
198#        define GET_PROGRAM_NAME() ""
199#        pragma message ( "Warning: Per application configuration won't work with your OS version." )
200#    endif
201#endif
202
203const char *
204util_get_process_name(void)
205{
206   return GET_PROGRAM_NAME();
207}
208
209size_t
210util_get_process_exec_path(char* process_path, size_t len)
211{
212#if DETECT_OS_WINDOWS
213   return GetModuleFileNameA(NULL, process_path, len);
214#elif DETECT_OS_APPLE
215   uint32_t bufSize = len;
216   int result = _NSGetExecutablePath(process_path, &bufSize);
217
218   return (result == 0) ? strlen(process_path) : 0;
219#elif DETECT_OS_FREEBSD
220   int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
221
222   (void) sysctl(mib, 4, process_path, &len, NULL, 0);
223   process_path[len - 1] = '\0';
224
225   return len;
226#elif DETECT_OS_UNIX
227   ssize_t r;
228
229   if ((r = readlink("/proc/self/exe", process_path, len)) > 0)
230      goto success;
231   if ((r = readlink("/proc/curproc/exe", process_path, len)) > 0)
232      goto success;
233   if ((r = readlink("/proc/curproc/file", process_path, len)) > 0)
234      goto success;
235
236    return 0;
237success:
238   if (r == len)
239      return 0;
240
241    process_path[r] = '\0';
242    return r;
243
244#endif
245   return 0;
246}
247