]> git.cworth.org Git - apitrace/blob - common/os_posix.cpp
Move mutex abstraction to os_thread.hpp.
[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/time.h>
34 #include <sys/wait.h>
35 #include <sys/stat.h>
36 #include <fcntl.h>
37 #include <signal.h>
38
39 #if defined(__linux__)
40 #include <linux/limits.h> // PATH_MAX
41 #endif
42
43 #ifdef __APPLE__
44 #include <sys/syslimits.h> // PATH_MAX
45 #include <mach-o/dyld.h>
46 #endif
47
48 #ifndef PATH_MAX
49 #warning PATH_MAX undefined
50 #define PATH_MAX 4096
51 #endif
52
53 #include "os.hpp"
54 #include "os_string.hpp"
55
56
57 namespace os {
58
59
60 String
61 getProcessName(void)
62 {
63     String path;
64     size_t size = PATH_MAX;
65     char *buf = path.buf(size);
66
67     // http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe
68 #ifdef __APPLE__
69     uint32_t len = size;
70     if (_NSGetExecutablePath(buf, &len) != 0) {
71         *buf = 0;
72         return path;
73     }
74     len = strlen(buf);
75 #else
76     ssize_t len;
77     len = readlink("/proc/self/exe", buf, size - 1);
78     if (len == -1) {
79         // /proc/self/exe is not available on setuid processes, so fallback to
80         // /proc/self/cmdline.
81         int fd = open("/proc/self/cmdline", O_RDONLY);
82         if (fd >= 0) {
83             len = read(fd, buf, size - 1);
84             close(fd);
85         }
86     }
87     if (len <= 0) {
88         snprintf(buf, size, "%i", (int)getpid());
89         return path;
90     }
91 #endif
92     path.truncate(len);
93
94     return path;
95 }
96
97 String
98 getCurrentDir(void)
99 {
100     String path;
101     size_t size = PATH_MAX;
102     char *buf = path.buf(size);
103
104     getcwd(buf, size);
105     buf[size - 1] = 0;
106     
107     path.truncate();
108     return path;
109 }
110
111 bool
112 String::exists(void) const
113 {
114     struct stat st;
115     int err;
116
117     err = stat(str(), &st);
118     if (err) {
119         return false;
120     }
121
122     if (!S_ISREG(st.st_mode))
123         return false;
124
125     return true;
126 }
127
128 int execute(char * const * args)
129 {
130     pid_t pid = fork();
131     if (pid == 0) {
132         // child
133         execvp(args[0], args);
134         fprintf(stderr, "error: failed to execute %s\n", args[0]);
135         exit(-1);
136     } else {
137         // parent
138         if (pid == -1) {
139             fprintf(stderr, "error: failed to fork\n");
140             return -1;
141         }
142         int status = -1;
143         waitpid(pid, &status, 0);
144         return status;
145     }
146 }
147
148 void
149 log(const char *format, ...)
150 {
151     va_list ap;
152     va_start(ap, format);
153     fflush(stdout);
154     vfprintf(stderr, format, ap);
155     va_end(ap);
156 }
157
158 long long
159 getTime(void)
160 {
161     struct timeval tv;
162     gettimeofday(&tv, NULL);
163     return tv.tv_usec + tv.tv_sec*1000000LL;
164 }
165
166 void
167 abort(void)
168 {
169     exit(0);
170 }
171
172
173 static void (*gCallback)(void) = NULL;
174
175 #define NUM_SIGNALS 16
176
177 struct sigaction old_actions[NUM_SIGNALS];
178
179
180 /*
181  * See also:
182  * - http://sourceware.org/git/?p=glibc.git;a=blob;f=debug/segfault.c
183  * - http://ggi.cvs.sourceforge.net/viewvc/ggi/ggi-core/libgg/gg/cleanup.c?view=markup
184  */
185 static void
186 signalHandler(int sig, siginfo_t *info, void *context)
187 {
188     static int recursion_count = 0;
189
190     fprintf(stderr, "apitrace: warning: caught signal %i\n", sig);
191
192     if (recursion_count) {
193         fprintf(stderr, "apitrace: warning: recursion handling signal %i\n", sig);
194     } else {
195         if (gCallback) {
196             ++recursion_count;
197             gCallback();
198             --recursion_count;
199         }
200     }
201
202     struct sigaction *old_action;
203     if (sig >= NUM_SIGNALS) {
204         /* This should never happen */
205         fprintf(stderr, "error: unexpected signal %i\n", sig);
206         raise(SIGKILL);
207     }
208     old_action = &old_actions[sig];
209
210     if (old_action->sa_flags & SA_SIGINFO) {
211         // Handler is in sa_sigaction
212         old_action->sa_sigaction(sig, info, context);
213     } else {
214         if (old_action->sa_handler == SIG_DFL) {
215             fprintf(stderr, "apitrace: info: taking default action for signal %i\n", sig);
216
217 #if 1
218             struct sigaction dfl_action;
219             dfl_action.sa_handler = SIG_DFL;
220             sigemptyset (&dfl_action.sa_mask);
221             dfl_action.sa_flags = 0;
222             sigaction(sig, &dfl_action, NULL);
223
224             raise(sig);
225 #else
226             raise(SIGKILL);
227 #endif
228         } else if (old_action->sa_handler == SIG_IGN) {
229             /* ignore */
230         } else {
231             /* dispatch to handler */
232             old_action->sa_handler(sig);
233         }
234     }
235 }
236
237 void
238 setExceptionCallback(void (*callback)(void))
239 {
240     assert(!gCallback);
241     if (!gCallback) {
242         gCallback = callback;
243
244         struct sigaction new_action;
245         new_action.sa_sigaction = signalHandler;
246         sigemptyset(&new_action.sa_mask);
247         new_action.sa_flags = SA_SIGINFO | SA_RESTART;
248
249
250         for (int sig = 1; sig < NUM_SIGNALS; ++sig) {
251             // SIGKILL and SIGSTOP can't be handled
252             if (sig != SIGKILL && sig != SIGSTOP) {
253                 if (sigaction(sig,  NULL, &old_actions[sig]) >= 0) {
254                     sigaction(sig,  &new_action, NULL);
255                 }
256             }
257         }
258     }
259 }
260
261 void
262 resetExceptionCallback(void)
263 {
264     gCallback = NULL;
265 }
266
267 } /* namespace os */
268