1 /**************************************************************************
3 ** This file is part of Qt Creator
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
7 ** Contact: Nokia Corporation (qt-info@nokia.com)
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
16 ** GNU Lesser General Public License Usage
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.
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.
29 ** If you have questions regarding the use of this file, please contact
30 ** Nokia at qt-info@nokia.com.
32 **************************************************************************/
35 #include "dbgwinutils.h"
36 #include "debuggerdialogs.h"
37 #include "breakpoint.h"
39 #include <QtCore/QDebug>
40 #include <QtCore/QString>
41 #include <QtCore/QTextStream>
43 // Enable Win API of XP SP1 and later
45 # define _WIN32_WINNT 0x0502
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
55 #include <QtCore/QLibrary>
60 // Resolve QueryFullProcessImageNameW out of kernel32.dll due
61 // to incomplete MinGW import libs and it not being present
63 static inline BOOL queryFullProcessImageName(HANDLE h,
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");
77 if (!queryFullProcessImageNameW)
80 return (*queryFullProcessImageNameW)(h, flags, buffer, size);
83 static inline QString imageName(DWORD processId)
86 HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION , FALSE, processId);
87 if (handle == INVALID_HANDLE_VALUE)
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));
97 QList<ProcData> winProcessList()
102 pe.dwSize = sizeof(PROCESSENTRY32);
103 HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
104 if (snapshot == INVALID_HANDLE_VALUE)
107 for (bool hasNext = Process32First(snapshot, &pe); hasNext; hasNext = Process32Next(snapshot, &pe)) {
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);
114 CloseHandle(snapshot);
118 bool winResumeThread(unsigned long dwThreadId, QString *errorMessage)
121 HANDLE handle = NULL;
126 handle = OpenThread(SYNCHRONIZE |THREAD_QUERY_INFORMATION |THREAD_SUSPEND_RESUME,
129 *errorMessage = QString::fromLatin1("Unable to open thread %1: %2").
130 arg(dwThreadId).arg(Utils::winErrorMessage(GetLastError()));
133 if (ResumeThread(handle) == DWORD(-1)) {
134 *errorMessage = QString::fromLatin1("Unable to resume thread %1: %2").
135 arg(dwThreadId).arg(Utils::winErrorMessage(GetLastError()));
145 // Open the process and break into it
146 bool winDebugBreakProcess(unsigned long pid, QString *errorMessage)
149 HANDLE inferior = NULL;
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()));
160 if (!DebugBreakProcess(inferior)) {
161 *errorMessage = QString::fromLatin1("DebugBreakProcess failed: %1").arg(Utils::winErrorMessage(GetLastError()));
166 if (inferior != NULL)
167 CloseHandle(inferior);
171 unsigned long winGetCurrentProcessId()
173 return GetCurrentProcessId();
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"
180 static bool mapDeviceToDriveLetter(QString *s)
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))
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));
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.
208 QString winNormalizeFileName(const QString &f)
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)
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) {
220 // Create a file mapping object.
221 HANDLE hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 1, NULL);
227 // Create a file mapping to get the file name.
228 void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);
230 CloseHandle(hFileMap);
236 WCHAR pszFilename[MAX_PATH];
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))
245 UnmapViewOfFile(pMem);
246 CloseHandle(hFileMap);
248 return rc.isEmpty() ? f : rc;
251 bool isWinProcessBeingDebugged(unsigned long pid)
253 HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
254 if (processHandle == NULL)
256 BOOL debugged = FALSE;
257 CheckRemoteDebuggerPresent(processHandle, &debugged);
258 CloseHandle(processHandle);
259 return debugged != FALSE;
262 // Simple exception formatting
263 void formatWindowsException(unsigned long code, quint64 address,
264 unsigned long flags, quint64 info1, quint64 info2,
267 str.setIntegerBase(16);
268 str << "\nException at 0x" << address
269 << ", code: 0x" << code << ": ";
271 case winExceptionCppException:
272 str << "C++ exception";
274 case winExceptionStartupCompleteTrap:
275 str << "Startup complete";
277 case winExceptionDllNotFound:
278 str << "DLL not found";
280 case winExceptionDllEntryPointNoFound:
281 str << "DLL entry point not found";
283 case winExceptionDllInitFailed:
284 str << "DLL failed to initialize";
286 case winExceptionMissingSystemFile:
287 str << "System file is missing";
289 case winExceptionRpcServerUnavailable:
290 str << "RPC server unavailable";
292 case winExceptionRpcServerInvalid:
293 str << "Invalid RPC server";
295 case EXCEPTION_ACCESS_VIOLATION: {
296 const bool writeOperation = info1;
297 str << (writeOperation ? "write" : "read")
298 << " access violation at: 0x" << info2;
301 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
302 str << "arrary bounds exceeded";
304 case EXCEPTION_BREAKPOINT:
307 case EXCEPTION_DATATYPE_MISALIGNMENT:
308 str << "datatype misalignment";
310 case EXCEPTION_FLT_DENORMAL_OPERAND:
311 str << "floating point exception";
313 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
314 str << "division by zero";
316 case EXCEPTION_FLT_INEXACT_RESULT:
317 str << " floating-point operation cannot be represented exactly as a decimal fraction";
319 case EXCEPTION_FLT_INVALID_OPERATION:
320 str << "invalid floating-point operation";
322 case EXCEPTION_FLT_OVERFLOW:
323 str << "floating-point overflow";
325 case EXCEPTION_FLT_STACK_CHECK:
326 str << "floating-point operation stack over/underflow";
328 case EXCEPTION_FLT_UNDERFLOW:
329 str << "floating-point UNDERFLOW";
331 case EXCEPTION_ILLEGAL_INSTRUCTION:
332 str << "invalid instruction";
334 case EXCEPTION_IN_PAGE_ERROR:
335 str << "page in error";
337 case EXCEPTION_INT_DIVIDE_BY_ZERO:
338 str << "integer division by zero";
340 case EXCEPTION_INT_OVERFLOW:
341 str << "integer overflow";
343 case EXCEPTION_INVALID_DISPOSITION:
344 str << "invalid disposition to exception dispatcher";
346 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
347 str << "attempt to continue execution after noncontinuable exception";
349 case EXCEPTION_PRIV_INSTRUCTION:
350 str << "privileged instruction";
352 case EXCEPTION_SINGLE_STEP:
353 str << "single step";
355 case EXCEPTION_STACK_OVERFLOW:
356 str << "stack_overflow";
359 str << ", flags=0x" << flags;
360 if (flags == EXCEPTION_NONCONTINUABLE) {
361 str << " (execution cannot be continued)";
363 str.setIntegerBase(10);
366 bool isDebuggerWinException(long code)
368 return code ==EXCEPTION_BREAKPOINT || code == EXCEPTION_SINGLE_STEP;
371 bool isFatalWinException(long 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:
389 // Special function names in MSVC runtime
390 const char *winMSVCThrowFunction = "CxxThrowException";
391 const char *winMSVCCatchFunction = "__CxxCallCatchBlock";
393 BreakpointParameters fixWinMSVCBreakpoint(const BreakpointParameters &p)
395 if (p.type == BreakpointAtThrow) {
396 BreakpointParameters rc(BreakpointByFunction);
397 rc.functionName = QLatin1String(winMSVCThrowFunction);
400 if (p.type == BreakpointAtCatch) {
401 BreakpointParameters rc(BreakpointByFunction);
402 rc.functionName = QLatin1String(winMSVCCatchFunction);
405 if (p.type == BreakpointAtMain) {
406 BreakpointParameters rc(BreakpointByFunction);
407 rc.functionName = QLatin1String("main");
413 } // namespace Internal
414 } // namespace Debugger