]> git.cworth.org Git - apitrace/blob - common/os_posix.cpp
retrace: Don't try to recreate existing directories.
[apitrace] / common / os_posix.cpp
1 /**************************************************************************
2  *
3  * Copyright 2010-2011 VMware, Inc.
4  * All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  *
24  **************************************************************************/
25
26
27 #include <assert.h>
28 #include <string.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31
32 #include <unistd.h>
33 #include <sys/wait.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 #include <signal.h>
37
38 #if defined(__linux__)
39 #include <linux/limits.h> // PATH_MAX
40 #endif
41
42 #ifdef __APPLE__
43 #include <sys/syslimits.h> // PATH_MAX
44 #include <mach-o/dyld.h>
45 #endif
46
47 #ifdef ANDROID
48 #include <android/log.h>
49 #endif
50
51 #ifndef PATH_MAX
52 #warning PATH_MAX undefined
53 #define PATH_MAX 4096
54 #endif
55
56 #include "os.hpp"
57 #include "os_string.hpp"
58
59
60 namespace os {
61
62
63 String
64 getProcessName(void)
65 {
66     String path;
67     size_t size = PATH_MAX;
68     char *buf = path.buf(size);
69
70     // http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe
71 #ifdef __APPLE__
72     uint32_t len = size;
73     if (_NSGetExecutablePath(buf, &len) != 0) {
74         *buf = 0;
75         return path;
76     }
77     len = strlen(buf);
78 #else
79     ssize_t len;
80     len = readlink("/proc/self/exe", buf, size - 1);
81     if (len == -1) {
82         // /proc/self/exe is not available on setuid processes, so fallback to
83         // /proc/self/cmdline.
84         int fd = open("/proc/self/cmdline", O_RDONLY);
85         if (fd >= 0) {
86             len = read(fd, buf, size - 1);
87             close(fd);
88         }
89     }
90     if (len <= 0) {
91         snprintf(buf, size, "%i", (int)getpid());
92         return path;
93     }
94 #endif
95     path.truncate(len);
96
97     return path;
98 }
99
100 String
101 getCurrentDir(void)
102 {
103     String path;
104     size_t size = PATH_MAX;
105     char *buf = path.buf(size);
106
107     getcwd(buf, size);
108     buf[size - 1] = 0;
109     
110     path.truncate();
111     return path;
112 }
113
114 bool
115 createDirectory(const String &path)
116 {
117     return mkdir(path, 0777) == 0;
118 }
119
120 bool
121 String::exists(void) const
122 {
123     struct stat st;
124     int err;
125
126     err = stat(str(), &st);
127     if (err) {
128         return false;
129     }
130
131     return true;
132 }
133
134 int execute(char * const * args)
135 {
136     pid_t pid = fork();
137     if (pid == 0) {
138         // child
139         execvp(args[0], args);
140         fprintf(stderr, "error: failed to execute:");
141         for (unsigned i = 0; args[i]; ++i) {
142             fprintf(stderr, " %s", args[i]);
143         }
144         fprintf(stderr, "\n");
145         exit(-1);
146     } else {
147         // parent
148         if (pid == -1) {
149             fprintf(stderr, "error: failed to fork\n");
150             return -1;
151         }
152         int status = -1;
153         int ret;
154         waitpid(pid, &status, 0);
155         if (WIFEXITED(status)) {
156             ret = WEXITSTATUS(status);
157         } else if (WIFSIGNALED(status)) {
158             // match shell return code
159             ret = WTERMSIG(status) + 128;
160         } else {
161             ret = 128;
162         }
163         return ret;
164     }
165 }
166
167 static volatile bool logging = false;
168
169 void
170 log(const char *format, ...)
171 {
172     logging = true;
173     va_list ap;
174     va_start(ap, format);
175     fflush(stdout);
176 #ifdef ANDROID
177     __android_log_vprint(ANDROID_LOG_DEBUG, "apitrace", format, ap);
178 #else
179     static FILE *log = NULL;
180     if (!log) {
181         // Duplicate stderr file descriptor, to prevent applications from
182         // redirecting our debug messages to somewhere else.
183         //
184         // Another alternative would be to log to /dev/tty when available.
185         log = fdopen(dup(STDERR_FILENO), "at");
186     }
187     vfprintf(log, format, ap);
188     fflush(log);
189 #endif
190     va_end(ap);
191     logging = false;
192 }
193
194 #if defined(__APPLE__)
195 long long timeFrequency = 0LL;
196 #endif
197
198 void
199 abort(void)
200 {
201     _exit(1);
202 }
203
204
205 static void (*gCallback)(void) = NULL;
206
207 #define NUM_SIGNALS 16
208
209 struct sigaction old_actions[NUM_SIGNALS];
210
211
212 /*
213  * See also:
214  * - http://sourceware.org/git/?p=glibc.git;a=blob;f=debug/segfault.c
215  * - http://ggi.cvs.sourceforge.net/viewvc/ggi/ggi-core/libgg/gg/cleanup.c?view=markup
216  */
217 static void
218 signalHandler(int sig, siginfo_t *info, void *context)
219 {
220     /*
221      * There are several signals that can happen when logging to stdout/stderr.
222      * For example, SIGPIPE will be emitted if stderr is a pipe with no
223      * readers.  Therefore ignore any signal while logging by returning
224      * immediately, to prevent deadlocks.
225      */
226     if (logging) {
227         return;
228     }
229
230     static int recursion_count = 0;
231
232     log("apitrace: warning: caught signal %i\n", sig);
233
234     if (recursion_count) {
235         log("apitrace: warning: recursion handling signal %i\n", sig);
236     } else {
237         if (gCallback) {
238             ++recursion_count;
239             gCallback();
240             --recursion_count;
241         }
242     }
243
244     struct sigaction *old_action;
245     if (sig >= NUM_SIGNALS) {
246         /* This should never happen */
247         log("error: unexpected signal %i\n", sig);
248         raise(SIGKILL);
249     }
250     old_action = &old_actions[sig];
251
252     if (old_action->sa_flags & SA_SIGINFO) {
253         // Handler is in sa_sigaction
254         old_action->sa_sigaction(sig, info, context);
255     } else {
256         if (old_action->sa_handler == SIG_DFL) {
257             log("apitrace: info: taking default action for signal %i\n", sig);
258
259 #if 1
260             struct sigaction dfl_action;
261             dfl_action.sa_handler = SIG_DFL;
262             sigemptyset (&dfl_action.sa_mask);
263             dfl_action.sa_flags = 0;
264             sigaction(sig, &dfl_action, NULL);
265
266             raise(sig);
267 #else
268             raise(SIGKILL);
269 #endif
270         } else if (old_action->sa_handler == SIG_IGN) {
271             /* ignore */
272         } else {
273             /* dispatch to handler */
274             old_action->sa_handler(sig);
275         }
276     }
277 }
278
279 void
280 setExceptionCallback(void (*callback)(void))
281 {
282     assert(!gCallback);
283     if (!gCallback) {
284         gCallback = callback;
285
286         struct sigaction new_action;
287         new_action.sa_sigaction = signalHandler;
288         sigemptyset(&new_action.sa_mask);
289         new_action.sa_flags = SA_SIGINFO | SA_RESTART;
290
291
292         for (int sig = 1; sig < NUM_SIGNALS; ++sig) {
293             // SIGKILL and SIGSTOP can't be handled.
294             if (sig == SIGKILL || sig == SIGSTOP) {
295                 continue;
296             }
297
298             /*
299              * SIGPIPE can be emitted when writing to stderr that is redirected
300              * to a pipe without readers.  It is also very unlikely to ocurr
301              * inside graphics APIs, and most applications where it can occur
302              * normally already ignore it.  In summary, it is unlikely that a
303              * SIGPIPE will cause abnormal termination, which it is likely that
304              * intercepting here will cause problems, so simple don't intercept
305              * it here.
306              */
307             if (sig == SIGPIPE) {
308                 continue;
309             }
310
311             if (sigaction(sig,  NULL, &old_actions[sig]) >= 0) {
312                 sigaction(sig,  &new_action, NULL);
313             }
314         }
315     }
316 }
317
318 void
319 resetExceptionCallback(void)
320 {
321     gCallback = NULL;
322 }
323
324 } /* namespace os */
325