OSDN Git Service

It's 2011 now.
[qt-creator-jp/qt-creator-jp.git] / src / plugins / debugger / shared / dbgwinutils.cpp
1 /**************************************************************************
2 **
3 ** This file is part of Qt Creator
4 **
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6 **
7 ** Contact: Nokia Corporation (qt-info@nokia.com)
8 **
9 ** No Commercial Usage
10 **
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
14 ** this package.
15 **
16 ** GNU Lesser General Public License Usage
17 **
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file.  Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Nokia gives you certain additional
26 ** rights.  These rights are described in the Nokia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** If you have questions regarding the use of this file, please contact
30 ** Nokia at qt-info@nokia.com.
31 **
32 **************************************************************************/
33
34 #include "winutils.h"
35 #include "dbgwinutils.h"
36 #include "debuggerdialogs.h"
37 #include "breakpoint.h"
38
39 #include <QtCore/QDebug>
40 #include <QtCore/QString>
41 #include <QtCore/QTextStream>
42
43 // Enable Win API of XP SP1 and later
44 #ifdef Q_OS_WIN
45 #    define _WIN32_WINNT 0x0502
46 #    include <windows.h>
47 #    include <utils/winutils.h>
48 #    if !defined(PROCESS_SUSPEND_RESUME) // Check flag for MinGW
49 #        define PROCESS_SUSPEND_RESUME (0x0800)
50 #    endif // PROCESS_SUSPEND_RESUME
51 #endif // Q_OS_WIN
52
53 #include <tlhelp32.h>
54 #include <psapi.h>
55 #include <QtCore/QLibrary>
56
57 namespace Debugger {
58 namespace Internal {
59
60 // Resolve QueryFullProcessImageNameW out of kernel32.dll due
61 // to incomplete MinGW import libs and it not being present
62 // on Windows XP.
63 static inline BOOL queryFullProcessImageName(HANDLE h,
64                                                    DWORD flags,
65                                                    LPWSTR buffer,
66                                                    DWORD *size)
67 {
68     // Resolve required symbols from the kernel32.dll
69     typedef BOOL (WINAPI *QueryFullProcessImageNameWProtoType)
70                  (HANDLE, DWORD, LPWSTR, PDWORD);
71     static QueryFullProcessImageNameWProtoType queryFullProcessImageNameW = 0;
72     if (!queryFullProcessImageNameW) {
73         QLibrary kernel32Lib(QLatin1String("kernel32.dll"), 0);
74         if (kernel32Lib.isLoaded() || kernel32Lib.load())
75             queryFullProcessImageNameW = (QueryFullProcessImageNameWProtoType)kernel32Lib.resolve("QueryFullProcessImageNameW");
76     }
77     if (!queryFullProcessImageNameW)
78         return FALSE;
79     // Read out process
80     return (*queryFullProcessImageNameW)(h, flags, buffer, size);
81 }
82
83 static inline QString imageName(DWORD processId)
84 {
85     QString  rc;
86     HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION , FALSE, processId);
87     if (handle == INVALID_HANDLE_VALUE)
88         return rc;
89     WCHAR buffer[MAX_PATH];
90     DWORD bufSize = MAX_PATH;
91     if (queryFullProcessImageName(handle, 0, buffer, &bufSize))
92         rc = QString::fromUtf16(reinterpret_cast<const ushort*>(buffer));
93     CloseHandle(handle);
94     return rc;
95 }
96
97 QList<ProcData> winProcessList()
98 {
99     QList<ProcData> rc;
100
101     PROCESSENTRY32 pe;
102     pe.dwSize = sizeof(PROCESSENTRY32);
103     HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
104     if (snapshot == INVALID_HANDLE_VALUE)
105         return rc;
106
107     for (bool hasNext = Process32First(snapshot, &pe); hasNext; hasNext = Process32Next(snapshot, &pe)) {
108         ProcData procData;
109         procData.ppid = QString::number(pe.th32ProcessID);
110         procData.name = QString::fromUtf16(reinterpret_cast<ushort*>(pe.szExeFile));
111         procData.image = imageName(pe.th32ProcessID);
112         rc.push_back(procData);
113     }
114     CloseHandle(snapshot);
115     return rc;
116 }
117
118 bool winResumeThread(unsigned long dwThreadId, QString *errorMessage)
119 {
120     bool ok = false;
121     HANDLE handle = NULL;
122     do {
123         if (!dwThreadId)
124             break;
125
126         handle = OpenThread(SYNCHRONIZE |THREAD_QUERY_INFORMATION |THREAD_SUSPEND_RESUME,
127                             FALSE, dwThreadId);
128         if (handle==NULL) {
129             *errorMessage = QString::fromLatin1("Unable to open thread %1: %2").
130                             arg(dwThreadId).arg(Utils::winErrorMessage(GetLastError()));
131             break;
132         }
133         if (ResumeThread(handle) == DWORD(-1)) {
134             *errorMessage = QString::fromLatin1("Unable to resume thread %1: %2").
135                             arg(dwThreadId).arg(Utils::winErrorMessage(GetLastError()));
136             break;
137         }
138         ok = true;
139     } while (false);
140     if (handle != NULL)
141         CloseHandle(handle);
142     return ok;
143 }
144
145 // Open the process and break into it
146 bool winDebugBreakProcess(unsigned long  pid, QString *errorMessage)
147 {
148     bool ok = false;
149     HANDLE inferior = NULL;
150     do {
151         const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION
152                 |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ
153                 |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME ;
154         inferior = OpenProcess(rights, FALSE, pid);
155         if (inferior == NULL) {
156             *errorMessage = QString::fromLatin1("Cannot open process %1: %2").
157                     arg(pid).arg(Utils::winErrorMessage(GetLastError()));
158             break;
159         }
160         if (!DebugBreakProcess(inferior)) {
161             *errorMessage = QString::fromLatin1("DebugBreakProcess failed: %1").arg(Utils::winErrorMessage(GetLastError()));
162             break;
163         }
164         ok = true;
165     } while (false);
166     if (inferior != NULL)
167         CloseHandle(inferior);
168     return ok;
169 }
170
171 unsigned long winGetCurrentProcessId()
172 {
173     return GetCurrentProcessId();
174 }
175
176 // Helper for normalizing file names:
177 // Map the device paths in  a file name to back to drive letters
178 // "/Device/HarddiskVolume1/file.cpp" -> "C:/file.cpp"
179
180 static bool mapDeviceToDriveLetter(QString *s)
181 {
182     enum { bufSize = 512 };
183     // Retrieve drive letters and get their device names.
184     // Do not cache as it may change due to removable/network drives.
185     TCHAR driveLetters[bufSize];
186     if (!GetLogicalDriveStrings(bufSize-1, driveLetters))
187         return false;
188
189     TCHAR driveName[MAX_PATH];
190     TCHAR szDrive[3] = TEXT(" :");
191     for (const TCHAR *driveLetter = driveLetters; *driveLetter; driveLetter++) {
192         szDrive[0] = *driveLetter; // Look up each device name
193         if (QueryDosDevice(szDrive, driveName, MAX_PATH)) {
194             const QString deviceName = QString::fromWCharArray(driveName);
195             if (s->startsWith(deviceName)) {
196                 s->replace(0, deviceName.size(), QString::fromWCharArray(szDrive));
197                 return true;
198             }
199         }
200     }
201     return false;
202 }
203
204 // Determine normalized case of a Windows file name (camelcase.cpp -> CamelCase.cpp)
205 // Restriction: File needs to exists and be non-empty and will be to be opened/mapped.
206 // This is the MSDN-recommended way of doing that.
207
208 QString winNormalizeFileName(const QString &f)
209 {
210     HANDLE hFile = CreateFile((const wchar_t*)f.utf16(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
211     if(hFile == INVALID_HANDLE_VALUE)
212         return f;
213     // Get the file size. We need a non-empty file to map it.
214     DWORD dwFileSizeHi = 0;
215     DWORD dwFileSizeLo = GetFileSize(hFile, &dwFileSizeHi);
216     if (dwFileSizeLo == 0 && dwFileSizeHi == 0) {
217         CloseHandle(hFile);
218         return f;
219     }
220     // Create a file mapping object.
221     HANDLE hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 1, NULL);
222     if (!hFileMap)  {
223         CloseHandle(hFile);
224         return f;
225     }
226
227     // Create a file mapping to get the file name.
228     void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);
229     if (!pMem) {
230         CloseHandle(hFileMap);
231         CloseHandle(hFile);
232         return f;
233     }
234
235     QString rc;
236     WCHAR pszFilename[MAX_PATH];
237     pszFilename[0] = 0;
238     // Get a file name of the form "/Device/HarddiskVolume1/file.cpp"
239     if (GetMappedFileName (GetCurrentProcess(), pMem, pszFilename, MAX_PATH)) {
240         rc = QString::fromWCharArray(pszFilename);
241         if (!mapDeviceToDriveLetter(&rc))
242             rc.clear();
243     }
244
245     UnmapViewOfFile(pMem);
246     CloseHandle(hFileMap);
247     CloseHandle(hFile);
248     return rc.isEmpty() ? f : rc;
249 }
250
251 bool isWinProcessBeingDebugged(unsigned long pid)
252 {
253     HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
254     if (processHandle == NULL)
255         return false;
256     BOOL debugged = FALSE;
257     CheckRemoteDebuggerPresent(processHandle, &debugged);
258     CloseHandle(processHandle);
259     return debugged != FALSE;
260 }
261
262 // Simple exception formatting
263 void formatWindowsException(unsigned long code, quint64 address,
264                             unsigned long flags, quint64 info1, quint64 info2,
265                             QTextStream &str)
266 {
267     str.setIntegerBase(16);
268     str << "\nException at 0x"  << address
269             <<  ", code: 0x" << code << ": ";
270     switch (code) {
271     case winExceptionCppException:
272         str << "C++ exception";
273         break;
274     case winExceptionStartupCompleteTrap:
275         str << "Startup complete";
276         break;
277     case winExceptionDllNotFound:
278         str << "DLL not found";
279         break;
280     case winExceptionDllEntryPointNoFound:
281         str << "DLL entry point not found";
282         break;
283     case winExceptionDllInitFailed:
284         str << "DLL failed to initialize";
285         break;
286     case winExceptionMissingSystemFile:
287         str << "System file is missing";
288         break;
289     case winExceptionRpcServerUnavailable:
290         str << "RPC server unavailable";
291         break;
292     case winExceptionRpcServerInvalid:
293         str << "Invalid RPC server";
294         break;
295     case EXCEPTION_ACCESS_VIOLATION: {
296             const bool writeOperation = info1;
297             str << (writeOperation ? "write" : "read")
298                 << " access violation at: 0x" << info2;
299     }
300         break;
301     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
302         str << "arrary bounds exceeded";
303         break;
304     case EXCEPTION_BREAKPOINT:
305         str << "breakpoint";
306         break;
307     case EXCEPTION_DATATYPE_MISALIGNMENT:
308         str << "datatype misalignment";
309         break;
310     case EXCEPTION_FLT_DENORMAL_OPERAND:
311         str << "floating point exception";
312         break;
313     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
314         str << "division by zero";
315         break;
316     case EXCEPTION_FLT_INEXACT_RESULT:
317         str << " floating-point operation cannot be represented exactly as a decimal fraction";
318         break;
319     case EXCEPTION_FLT_INVALID_OPERATION:
320         str << "invalid floating-point operation";
321         break;
322     case EXCEPTION_FLT_OVERFLOW:
323         str << "floating-point overflow";
324         break;
325     case EXCEPTION_FLT_STACK_CHECK:
326         str << "floating-point operation stack over/underflow";
327         break;
328     case  EXCEPTION_FLT_UNDERFLOW:
329         str << "floating-point UNDERFLOW";
330         break;
331     case  EXCEPTION_ILLEGAL_INSTRUCTION:
332         str << "invalid instruction";
333         break;
334     case EXCEPTION_IN_PAGE_ERROR:
335         str << "page in error";
336         break;
337     case EXCEPTION_INT_DIVIDE_BY_ZERO:
338         str << "integer division by zero";
339         break;
340     case EXCEPTION_INT_OVERFLOW:
341         str << "integer overflow";
342         break;
343     case EXCEPTION_INVALID_DISPOSITION:
344         str << "invalid disposition to exception dispatcher";
345         break;
346     case EXCEPTION_NONCONTINUABLE_EXCEPTION:
347         str << "attempt to continue execution after noncontinuable exception";
348         break;
349     case EXCEPTION_PRIV_INSTRUCTION:
350         str << "privileged instruction";
351         break;
352     case EXCEPTION_SINGLE_STEP:
353         str << "single step";
354         break;
355     case EXCEPTION_STACK_OVERFLOW:
356         str << "stack_overflow";
357         break;
358     }
359     str << ", flags=0x" << flags;
360     if (flags == EXCEPTION_NONCONTINUABLE) {
361         str << " (execution cannot be continued)";
362     }
363     str.setIntegerBase(10);
364 }
365
366 bool isDebuggerWinException(long code)
367 {
368     return code ==EXCEPTION_BREAKPOINT || code == EXCEPTION_SINGLE_STEP;
369 }
370
371 bool isFatalWinException(long code)
372 {
373     switch (code) {
374     case EXCEPTION_BREAKPOINT:
375     case EXCEPTION_SINGLE_STEP:
376     case winExceptionStartupCompleteTrap: // Mysterious exception at start of application
377     case winExceptionRpcServerUnavailable:
378     case winExceptionRpcServerInvalid:
379     case winExceptionDllNotFound:
380     case winExceptionDllEntryPointNoFound:
381     case winExceptionCppException:
382         return false;
383     default:
384         break;
385     }
386     return true;
387 }
388
389 // Special function names in MSVC runtime
390 const char *winMSVCThrowFunction = "CxxThrowException";
391 const char *winMSVCCatchFunction = "__CxxCallCatchBlock";
392
393 BreakpointParameters fixWinMSVCBreakpoint(const BreakpointParameters &p)
394 {
395     if (p.type == BreakpointAtThrow) {
396         BreakpointParameters rc(BreakpointByFunction);
397         rc.functionName = QLatin1String(winMSVCThrowFunction);
398         return rc;
399     }
400     if (p.type == BreakpointAtCatch) {
401         BreakpointParameters rc(BreakpointByFunction);
402         rc.functionName = QLatin1String(winMSVCCatchFunction);
403         return rc;
404     }
405     if (p.type == BreakpointAtMain) {
406         BreakpointParameters rc(BreakpointByFunction);
407         rc.functionName = QLatin1String("main");
408         return rc;
409     }
410     return p;
411 }
412
413 } // namespace Internal
414 } // namespace Debugger