Introduce basic (not-yet-compressing) implementation of Compressor
[quassel.git] / src / common / logbacktrace_win.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2014 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "quassel.h"
22
23 #include <windows.h>
24 #include <dbghelp.h>
25 #include <stdio.h>
26
27 // #include <QDebug>
28 #include <QFile>
29 #include <QTextStream>
30
31 void loadHelpStackFrame(IMAGEHLP_STACK_FRAME &ihsf, const STACKFRAME64 &stackFrame)
32 {
33     ZeroMemory(&ihsf, sizeof(IMAGEHLP_STACK_FRAME));
34     ihsf.InstructionOffset = stackFrame.AddrPC.Offset;
35     ihsf.FrameOffset = stackFrame.AddrFrame.Offset;
36 }
37
38
39 BOOL CALLBACK EnumSymbolsCB(PSYMBOL_INFO symInfo, ULONG size, PVOID user)
40 {
41     QStringList *params = (QStringList *)user;
42     if (symInfo->Flags & SYMFLAG_PARAMETER) {
43         params->append(symInfo->Name);
44     }
45     return TRUE;
46 }
47
48
49 struct EnumModulesContext {
50     HANDLE hProcess;
51     QTextStream &stream;
52     EnumModulesContext(HANDLE hProcess, QTextStream &stream) : hProcess(hProcess), stream(stream) {}
53 };
54
55 BOOL CALLBACK EnumModulesCB(LPCSTR ModuleName, DWORD64 BaseOfDll, PVOID UserContext)
56 {
57     IMAGEHLP_MODULE64 mod;
58     EnumModulesContext *context = (EnumModulesContext *)UserContext;
59     mod.SizeOfStruct = sizeof(IMAGEHLP_MODULE64);
60     if (SymGetModuleInfo64(context->hProcess, BaseOfDll, &mod)) {
61         QString line = QString("%1 0x%2 Image: %3").arg(mod.ModuleName, -14)
62                        .arg(BaseOfDll, 8, 16, QLatin1Char('0'))
63                        .arg(mod.LoadedImageName);
64         // qDebug() << qPrintable(line);
65         context->stream << line << '\n';
66
67         QString pdbName(mod.LoadedPdbName);
68         if (!pdbName.isEmpty()) {
69             QString line2 = QString("%1 %2").arg("", 32).arg(pdbName);
70             // qDebug() << qPrintable(line2);
71             context->stream << line2 << '\n';
72         }
73     }
74     return TRUE;
75 }
76
77
78 #if defined(_M_IX86) && defined(Q_CC_MSVC)
79 // Disable global optimization and ignore /GS waning caused by
80 // inline assembly.
81 // not needed with mingw cause we can tell mingw which registers we use
82   #pragma optimize("g", off)
83   #pragma warning(push)
84   #pragma warning(disable : 4748)
85 #endif
86 void Quassel::logBacktrace(const QString &filename)
87 {
88     DWORD MachineType;
89     CONTEXT Context;
90     STACKFRAME64 StackFrame;
91
92 #ifdef _M_IX86
93     ZeroMemory(&Context, sizeof(CONTEXT));
94     Context.ContextFlags = CONTEXT_CONTROL;
95
96 #ifdef __MINGW32__
97     asm ("Label:\n\t"
98          "movl %%ebp,%0;\n\t"
99          "movl %%esp,%1;\n\t"
100          "movl $Label,%%eax;\n\t"
101          "movl %%eax,%2;\n\t"
102          : "=r" (Context.Ebp), "=r" (Context.Esp), "=r" (Context.Eip)
103          : //no input
104          : "eax");
105 #else
106     _asm {
107 Label:
108         mov[Context.Ebp], ebp;
109         mov[Context.Esp], esp;
110         mov eax, [Label];
111         mov[Context.Eip], eax;
112     }
113 #endif
114 #else
115     RtlCaptureContext(&Context);
116 #endif
117
118     ZeroMemory(&StackFrame, sizeof(STACKFRAME64));
119 #ifdef _M_IX86
120     MachineType                 = IMAGE_FILE_MACHINE_I386;
121     StackFrame.AddrPC.Offset    = Context.Eip;
122     StackFrame.AddrPC.Mode      = AddrModeFlat;
123     StackFrame.AddrFrame.Offset = Context.Ebp;
124     StackFrame.AddrFrame.Mode   = AddrModeFlat;
125     StackFrame.AddrStack.Offset = Context.Esp;
126     StackFrame.AddrStack.Mode   = AddrModeFlat;
127 #elif _M_X64
128     MachineType                 = IMAGE_FILE_MACHINE_AMD64;
129     StackFrame.AddrPC.Offset    = Context.Rip;
130     StackFrame.AddrPC.Mode      = AddrModeFlat;
131     StackFrame.AddrFrame.Offset = Context.Rsp;
132     StackFrame.AddrFrame.Mode   = AddrModeFlat;
133     StackFrame.AddrStack.Offset = Context.Rsp;
134     StackFrame.AddrStack.Mode   = AddrModeFlat;
135 #elif _M_IA64
136     MachineType                 = IMAGE_FILE_MACHINE_IA64;
137     StackFrame.AddrPC.Offset    = Context.StIIP;
138     StackFrame.AddrPC.Mode      = AddrModeFlat;
139     StackFrame.AddrFrame.Offset = Context.IntSp;
140     StackFrame.AddrFrame.Mode   = AddrModeFlat;
141     StackFrame.AddrBStore.Offset = Context.RsBSP;
142     StackFrame.AddrBStore.Mode  = AddrModeFlat;
143     StackFrame.AddrStack.Offset = Context.IntSp;
144     StackFrame.AddrStack.Mode   = AddrModeFlat;
145 #else
146   #error "Unsupported platform"
147 #endif
148
149     //EnterCriticalSection(&DbgHelpLock);
150
151     QFile logFile(filename);
152     logFile.open(QIODevice::Append);
153     QTextStream logStream(&logFile);
154
155     HANDLE hProcess = GetCurrentProcess();
156     HANDLE hThread = GetCurrentThread();
157     SymInitialize(hProcess, NULL, TRUE);
158
159     DWORD64 dwDisplacement;
160
161     ULONG64 buffer[(sizeof(SYMBOL_INFO) +
162                     MAX_SYM_NAME*sizeof(TCHAR) +
163                     sizeof(ULONG64) - 1) /  sizeof(ULONG64)];
164     PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer;
165     pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
166     pSymbol->MaxNameLen = MAX_SYM_NAME;
167
168     IMAGEHLP_MODULE64 mod;
169     mod.SizeOfStruct = sizeof(IMAGEHLP_MODULE64);
170
171     IMAGEHLP_STACK_FRAME ihsf;
172     ZeroMemory(&ihsf, sizeof(IMAGEHLP_STACK_FRAME));
173
174     int i = 0;
175     while (StackWalk64(MachineType, hProcess, hThread, &StackFrame, &Context, NULL, NULL, NULL, NULL)) {
176         if (i == 128)
177             break;
178
179         loadHelpStackFrame(ihsf, StackFrame);
180         if (StackFrame.AddrPC.Offset != 0) { // Valid frame.
181             QString fileName("???");
182             if (SymGetModuleInfo64(hProcess, ihsf.InstructionOffset, &mod)) {
183                 fileName = QString(mod.ImageName);
184                 int slashPos = fileName.lastIndexOf('\\');
185                 if (slashPos != -1)
186                     fileName = fileName.mid(slashPos + 1);
187             }
188             QString funcName;
189             if (SymFromAddr(hProcess, ihsf.InstructionOffset, &dwDisplacement, pSymbol)) {
190                 funcName = QString(pSymbol->Name);
191             }
192             else {
193                 funcName = QString("0x%1").arg(ihsf.InstructionOffset, 8, 16, QLatin1Char('0'));
194             }
195             QStringList params;
196             SymSetContext(hProcess, &ihsf, NULL);
197             SymEnumSymbols(hProcess, 0, NULL, EnumSymbolsCB, (PVOID)&params);
198
199             QString debugLine = QString("#%1 %2 0x%3 %4(%5)").arg(i, 3, 10)
200                                 .arg(fileName, -20)
201                                 .arg(ihsf.InstructionOffset, 8, 16, QLatin1Char('0'))
202                                 .arg(funcName)
203                                 .arg(params.join(", "));
204             // qDebug() << qPrintable(debugLine);
205             logStream << debugLine << '\n';
206             i++;
207         }
208         else {
209             break; // we're at the end.
210         }
211     }
212
213     // qDebug() << "List of linked Modules:";
214     logStream << "\n\nList of linked Modules:\n";
215     EnumModulesContext modulesContext(hProcess, logStream);
216     SymEnumerateModules64(hProcess, EnumModulesCB, (PVOID)&modulesContext);
217
218     logFile.close();
219 }
220
221
222 #if defined(_M_IX86) && defined(Q_CC_MSVC)
223   #pragma warning(pop)
224   #pragma optimize("g", on)
225 #endif