]> git.cworth.org Git - apitrace/blob - common/os_win32.cpp
Abstract execv().
[apitrace] / common / os_win32.cpp
1 /**************************************************************************
2  *
3  * Copyright 2010 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 #include <windows.h>
27
28 #include <assert.h>
29 #include <string.h>
30 #include <stdio.h>
31
32 #include <string>
33
34 #include "os.hpp"
35 #include "os_path.hpp"
36
37
38 namespace os {
39
40
41 /* 
42  * Trick from http://locklessinc.com/articles/pthreads_on_windows/
43  */
44 static CRITICAL_SECTION
45 criticalSection = {
46     (PCRITICAL_SECTION_DEBUG)-1, -1, 0, 0, 0, 0
47 };
48
49
50 void
51 acquireMutex(void)
52 {
53     EnterCriticalSection(&criticalSection);
54 }
55
56
57 void
58 releaseMutex(void)
59 {
60     LeaveCriticalSection(&criticalSection);
61 }
62
63
64 Path
65 getProcessName(void)
66 {
67     Path path;
68     size_t size = MAX_PATH;
69     char *buf = path.buf(size);
70
71     DWORD nWritten = GetModuleFileNameA(NULL, buf, size);
72     (void)nWritten;
73
74     path.truncate();
75
76     return path;
77 }
78
79 Path
80 getCurrentDir(void)
81 {
82     Path path;
83     size_t size = MAX_PATH;
84     char *buf = path.buf(size);
85     
86     DWORD ret = GetCurrentDirectoryA(size, buf);
87     (void)ret;
88     
89     buf[size - 1] = 0;
90     path.truncate();
91
92     return path;
93 }
94
95 bool
96 Path::exists(void) const
97 {
98     DWORD attrs = GetFileAttributesA(str());
99     return attrs != INVALID_FILE_ATTRIBUTES;
100 }
101
102 /**
103  * Determine whether an argument should be quoted.
104  */
105 static bool
106 needsQuote(const char *arg)
107 {
108     char c;
109     while (true) {
110         c = *arg++;
111         if (c == '\0') {
112             break;
113         }
114         if (c == ' ' || c == '\t' || c == '\"') {
115             return true;
116         }
117         if (c == '\\') {
118             c = *arg++;
119             if (c == '\0') {
120                 break;
121             }
122             if (c == '"') {
123                 return true;
124             }
125         }
126     }
127     return false;
128 }
129
130 static void
131 quoteArg(std::string &s, const char *arg)
132 {
133     char c;
134     unsigned backslashes = 0;
135     
136     s.push_back('"');
137     while (true) {
138         c = *arg++;
139         switch (c)
140         if (c == '\0') {
141             break;
142         } else if (c == '"') {
143             while (backslashes) {
144                 s.push_back('\\');
145                 --backslashes;
146             }
147             s.push_back('\\');
148         } else {
149             if (c == '\\') {
150                 ++backslashes;
151             } else {
152                 backslashes = 0;
153             }
154         }
155         s.push_back(c);
156     }
157     s.push_back('"');
158 }
159
160 int execute(char * const * args)
161 {
162     std::string commandLine;
163    
164     const char *arg0 = *args;
165     const char *arg;
166     char sep = 0;
167     while ((arg = *args++) != NULL) {
168         if (sep) {
169             commandLine.push_back(sep);
170         }
171
172         if (needsQuote(arg)) {
173             quoteArg(commandLine, arg);
174         } else {
175             commandLine.append(arg);
176         }
177
178         sep = ' ';
179     }
180
181     STARTUPINFO startupInfo;
182     memset(&startupInfo, 0, sizeof(startupInfo));
183     startupInfo.cb = sizeof(startupInfo);
184
185     PROCESS_INFORMATION processInformation;
186
187     if (!CreateProcessA(NULL,
188                         const_cast<char *>(commandLine.c_str()), // only modified by CreateProcessW
189                         0, // process attributes
190                         0, // thread attributes
191                         FALSE, // inherit handles
192                         0, // creation flags,
193                         NULL, // environment
194                         NULL, // current directory
195                         &startupInfo,
196                         &processInformation
197                         )) {
198         log("error: failed to execute %s\n", arg0);
199     }
200
201     WaitForSingleObject(processInformation.hProcess, INFINITE);
202
203     DWORD exitCode = ~0;
204     GetExitCodeProcess(processInformation.hProcess, &exitCode);
205
206     CloseHandle(processInformation.hProcess);
207     CloseHandle(processInformation.hThread);
208
209     return (int)exitCode;
210 }
211
212 void
213 log(const char *format, ...)
214 {
215     char buf[4096];
216
217     va_list ap;
218     va_start(ap, format);
219     fflush(stdout);
220     vsnprintf(buf, sizeof buf, format, ap);
221     va_end(ap);
222
223     OutputDebugStringA(buf);
224
225     /*
226      * Also write the message to stderr, when a debugger is not present (to
227      * avoid duplicate messages in command line debuggers).
228      */
229 #if _WIN32_WINNT > 0x0400
230     if (!IsDebuggerPresent()) {
231         fflush(stdout);
232         fputs(buf, stderr);
233         fflush(stderr);
234     }
235 #endif
236 }
237
238 long long
239 getTime(void)
240 {
241     static LARGE_INTEGER frequency;
242     LARGE_INTEGER counter;
243     if (!frequency.QuadPart)
244         QueryPerformanceFrequency(&frequency);
245     QueryPerformanceCounter(&counter);
246     return counter.QuadPart*1000000LL/frequency.QuadPart;
247 }
248
249 void
250 abort(void)
251 {
252 #ifndef NDEBUG
253     DebugBreak();
254 #else
255     ExitProcess(0);
256 #endif
257 }
258
259
260 static LPTOP_LEVEL_EXCEPTION_FILTER prevExceptionFilter = NULL;
261 static void (*gCallback)(void) = NULL;
262
263 static LONG WINAPI
264 unhandledExceptionFilter(PEXCEPTION_POINTERS pExceptionInfo)
265 {
266     if (gCallback) {
267         gCallback();
268     }
269
270         if (prevExceptionFilter) {
271                 return prevExceptionFilter(pExceptionInfo);
272     } else {
273                 return EXCEPTION_CONTINUE_SEARCH;
274     }
275 }
276
277 void
278 setExceptionCallback(void (*callback)(void))
279 {
280     assert(!gCallback);
281
282     if (!gCallback) {
283         gCallback = callback;
284
285         assert(!prevExceptionFilter);
286
287         /*
288          * TODO: Unfortunately it seems that the CRT will reset the exception
289          * handler in certain circumnstances.  See
290          * http://www.codeproject.com/KB/winsdk/crash_hook.aspx
291          */
292         prevExceptionFilter = SetUnhandledExceptionFilter(unhandledExceptionFilter);
293     }
294 }
295
296 void
297 resetExceptionCallback(void)
298 {
299     gCallback = NULL;
300 }
301
302
303 } /* namespace os */