| 1 | /**************************************************************************** |
| 2 | ** SASM - simple IDE for assembler development |
| 3 | ** Copyright (C) 2013 Dmitriy Manushin |
| 4 | ** Contact: site: http://dman95.github.io/SASM/ |
| 5 | ** e-mail: [email protected] |
| 6 | ** |
| 7 | ** This file is part of SASM. |
| 8 | ** |
| 9 | ** SASM is free software: you can redistribute it and/or modify |
| 10 | ** it under the terms of the GNU General Public License as published by |
| 11 | ** the Free Software Foundation, either version 3 of the License, or |
| 12 | ** (at your option) any later version. |
| 13 | ** |
| 14 | ** SASM is distributed in the hope that it will be useful, |
| 15 | ** but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 16 | ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 17 | ** GNU General Public License for more details. |
| 18 | ** |
| 19 | ** You should have received a copy of the GNU General Public License |
| 20 | ** along with SASM. If not, see <http://www.gnu.org/licenses/>. |
| 21 | ** |
| 22 | ** Этот файл — часть SASM. |
| 23 | ** |
| 24 | ** SASM - свободная программа: вы можете перераспространять ее и/или |
| 25 | ** изменять ее на условиях Стандартной общественной лицензии GNU в том виде, |
| 26 | ** в каком она была опубликована Фондом свободного программного обеспечения; |
| 27 | ** либо версии 3 лицензии, либо (по вашему выбору) любой более поздней |
| 28 | ** версии. |
| 29 | ** |
| 30 | ** SASM распространяется в надежде, что она будет полезной, |
| 31 | ** но БЕЗО ВСЯКИХ ГАРАНТИЙ; даже без неявной гарантии ТОВАРНОГО ВИДА |
| 32 | ** или ПРИГОДНОСТИ ДЛЯ ОПРЕДЕЛЕННЫХ ЦЕЛЕЙ. Подробнее см. в Стандартной |
| 33 | ** общественной лицензии GNU. |
| 34 | ** |
| 35 | ** Вы должны были получить копию Стандартной общественной лицензии GNU |
| 36 | ** вместе с этой программой. Если это не так, см. |
| 37 | ** <http://www.gnu.org/licenses/>.) |
| 38 | ** |
| 39 | ****************************************************************************/ |
| 40 | |
| 41 | #include "debugger.h" |
| 42 | |
| 43 | /** |
| 44 | * @file debugger.cpp |
| 45 | * Sets debugger information and runs the debugger. |
| 46 | */ |
| 47 | |
| 48 | namespace { |
| 49 | // read struct like {<name1> = <value1>, ,,, <nameN> = <valueN>} |
| 50 | // from stream. Values may be simple or complex, like {v1, v2, v3 .. } |
| 51 | // all i have to be simple, two-level complex values unsupported |
| 52 | bool readStruct(QTextStream& str, QMap<QString, QString>* map); |
| 53 | } |
| 54 | |
| 55 | |
| 56 | Debugger::Debugger(QTextEdit *tEdit, |
| 57 | const QString &exePathParam, |
| 58 | const QString &workingDirectoryPathParam, |
| 59 | const QString &inputPathParam, |
| 60 | Assembler *assembler, |
| 61 | QWidget *parent) |
| 62 | : QObject(parent) |
| 63 | { |
| 64 | QSettings settings("SASM Project", "SASM"); |
| 65 | gdbRun = false; |
| 66 | c = 0; |
| 67 | pid = 0; |
| 68 | firstAction = true; |
| 69 | textEdit = tEdit; |
| 70 | exePath = exePathParam; |
| 71 | workingDirectoryPath = workingDirectoryPathParam; |
| 72 | inputPath = inputPathParam; |
| 73 | registersOk = true; |
| 74 | this->assembler = assembler; |
| 75 | #ifdef Q_OS_WIN32 |
| 76 | QString gdb; |
| 77 | QString objdump; |
| 78 | if (settings.value("mode", QString("x86")).toString() == "x86") { |
| 79 | gdb = QCoreApplication::applicationDirPath() + "/MinGW/bin/gdb.exe"; |
| 80 | objdump = QCoreApplication::applicationDirPath() + "/MinGW/bin/objdump.exe"; |
| 81 | if (! QFile::exists(gdb)) |
| 82 | gdb = QCoreApplication::applicationDirPath() + "/Windows/MinGW/bin/gdb.exe"; |
| 83 | if (! QFile::exists(objdump)) |
| 84 | objdump = QCoreApplication::applicationDirPath() + "/Windows/MinGW/bin/objdump.exe"; |
| 85 | exitMessage = "mingw_CRTStartup"; |
| 86 | } else { |
| 87 | gdb = QCoreApplication::applicationDirPath() + "/MinGW64/bin/gdb.exe"; |
| 88 | objdump = QCoreApplication::applicationDirPath() + "/MinGW/bin/objdump.exe"; |
| 89 | if (! QFile::exists(gdb)) |
| 90 | gdb = QCoreApplication::applicationDirPath() + "/Windows/MinGW64/bin/gdb.exe"; |
| 91 | if (! QFile::exists(objdump)) |
| 92 | objdump = QCoreApplication::applicationDirPath() + "/Windows/MinGW/bin/objdump.exe"; |
| 93 | exitMessage = "__fu0__set_invalid_parameter_handler"; |
| 94 | } |
| 95 | #else |
| 96 | QString gdb = "gdb"; |
| 97 | QString objdump = "objdump"; |
| 98 | exitMessage = "libc_start"; |
| 99 | #endif |
| 100 | cExitMessage = QRegExp("\\[Inferior .* exited"); |
| 101 | |
| 102 | connect(this, SIGNAL(wasStopped()), this, SLOT(emitStarted())); |
| 103 | |
| 104 | //determine entry point |
| 105 | QProcess objdumpProcess; |
| 106 | QProcessEnvironment objdumpEnvironment = QProcessEnvironment::systemEnvironment(); |
| 107 | QStringList objdumpArguments; |
| 108 | objdumpArguments << "-f" << exePath; |
| 109 | objdumpEnvironment.insert("LC_MESSAGES", "en_US"); |
| 110 | objdumpProcess.setProcessEnvironment(objdumpEnvironment); |
| 111 | objdumpProcess.start(objdump, objdumpArguments); |
| 112 | objdumpProcess.waitForFinished(); |
| 113 | QString objdumpResult = QString(objdumpProcess.readAllStandardOutput()); |
| 114 | QString startAddress("start address "); |
| 115 | int index = objdumpResult.indexOf(startAddress); |
| 116 | objdumpResult = objdumpResult.mid(index + startAddress.length()); |
| 117 | entryPoint = objdumpResult.toLongLong(0, 16); |
| 118 | |
| 119 | |
| 120 | QStringList arguments; |
| 121 | arguments << "-nx" << exePath; |
| 122 | |
| 123 | process = new QProcess; |
| 124 | process->start(gdb, arguments); |
| 125 | |
| 126 | QObject::connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputToBuffer())); |
| 127 | QObject::connect(process, SIGNAL(readyReadStandardError()), this, SLOT(readOutputToBuffer())); |
| 128 | |
| 129 | bufferTimer = new QTimer; |
| 130 | QObject::connect(bufferTimer, SIGNAL(timeout()), this, SLOT(processOutput()), Qt::QueuedConnection); |
| 131 | bufferTimer->start(10); |
| 132 | |
| 133 | checkGdbRunTimer = new QTimer; |
| 134 | QObject::connect(checkGdbRunTimer, SIGNAL(timeout()), this, SLOT(checkGdbRun()), Qt::QueuedConnection); |
| 135 | checkGdbRunTimer->start(20000); |
| 136 | } |
| 137 | |
| 138 | void Debugger::emitStarted() |
| 139 | { |
| 140 | disconnect(this, SIGNAL(wasStopped()), this, SLOT(emitStarted())); |
| 141 | emit started(); |
| 142 | } |
| 143 | |
| 144 | void Debugger::readOutputToBuffer() |
| 145 | { |
| 146 | if (!process) |
| 147 | return; |
| 148 | QByteArray error = process->readAllStandardError(); |
| 149 | errorBuffer += QString::fromLocal8Bit(error.constData(), error.size()); |
| 150 | allErrorBuffer += QString::fromLocal8Bit(error.constData(), error.size()); |
| 151 | QByteArray output = process->readAllStandardOutput(); |
| 152 | buffer += QString::fromLocal8Bit(output.constData(), output.size()); |
| 153 | allBuffer += QString::fromLocal8Bit(output.constData(), output.size()); |
| 154 | } |
| 155 | |
| 156 | void Debugger::processOutput() |
| 157 | { |
| 158 | bufferTimer->stop(); |
| 159 | int index = buffer.indexOf(QString("(gdb)")); |
| 160 | /* static QString prevBuffer; // for debugging |
| 161 | if (prevBuffer != buffer) { |
| 162 | prevBuffer = buffer; |
| 163 | emit printLog(buffer, Qt::magenta); |
| 164 | } */ |
| 165 | int linefeedIndex = errorBuffer.indexOf("\n"); |
| 166 | if (index != -1) { //if whole message ready to processing (end of whole message is "(gdb)") |
| 167 | QString output = buffer.left(index); |
| 168 | QString error = errorBuffer.left(linefeedIndex); |
| 169 | buffer.remove(0, index + 5); //remove processed message |
| 170 | errorBuffer.remove(0, linefeedIndex + 1); |
| 171 | //emit printLog(output + "\n\n", Qt::blue); // for debugging |
| 172 | processMessage(output, error); |
| 173 | } |
| 174 | if (!commandQueue.isEmpty() && actionTypeQueue.size() <= commandQueue.size()) { // perform next command in order of queue |
| 175 | QString nextCommand = commandQueue.dequeue(); |
| 176 | if (process) |
| 177 | process->write(nextCommand.toLatin1()); |
| 178 | } |
| 179 | bufferTimer->start(10); |
| 180 | } |
| 181 | |
| 182 | void Debugger::checkGdbRun() |
| 183 | { |
| 184 | checkGdbRunTimer->stop(); |
| 185 | if (!gdbRun) { |
| 186 | emit printLog(tr("GDB error\n"), Qt::red); |
| 187 | emit printLog(allBuffer, Qt::red); |
| 188 | emit printLog(allErrorBuffer, Qt::red); |
| 189 | emit finished(); |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | void Debugger::processMessage(QString output, QString error) |
| 194 | { |
| 195 | if (error.indexOf("PC register is not available") != -1) { |
| 196 | emit printLog(tr("GDB error\n"), Qt::red); |
| 197 | emit finished(); |
| 198 | return; |
| 199 | } |
| 200 | if (c == 0) { //in start wait for printing of start gdb text like this: |
| 201 | /*GNU gdb (GDB) 7.4 |
| 202 | Copyright (C) 2012 Free Software Foundation, Inc. |
| 203 | License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> |
| 204 | This is free software: you are free to change and redistribute it. |
| 205 | There is NO WARRANTY, to the extent permitted by law. Type "show copying" |
| 206 | and "show warranty" for details. |
| 207 | This GDB was configured as "i686-pc-mingw32". |
| 208 | For bug reporting instructions, please see: |
| 209 | <http://www.gnu.org/software/gdb/bugs/>... |
| 210 | Reading symbols from C:\Users\Dmitri\Dropbox\Projects\SASMstatic\release\Program\SASMprog.exe... |
| 211 | done. |
| 212 | (gdb)*/ |
| 213 | c++; |
| 214 | doInput(QString("disas main\n"), none); |
| 215 | return; |
| 216 | } |
| 217 | |
| 218 | if (c == 1) { |
| 219 | if (error.indexOf("No symbol",0,Qt::CaseInsensitive)!=-1) { |
| 220 | dbgSymbols = false; |
| 221 | } else { |
| 222 | dbgSymbols = true; |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | if (dbgSymbols) { //debug symbols exists |
| 227 | if (c == 1 && output != " ") { |
| 228 | /*Dump of assembler code for function sasmStartL: |
| 229 | 0x00401390 <+0>: xor %eax,%eax |
| 230 | 0x00401392 <+2>: ret |
| 231 | 0x00401393 <+3>: add %dl,-0x77(%ebp) |
| 232 | End of assembler dump.*/ |
| 233 | //skip this information (for gdb 8.0) |
| 234 | c++; |
| 235 | run(); //perform Debugger::run(), that run program and open I/O files |
| 236 | return; |
| 237 | } |
| 238 | |
| 239 | //determine run of program |
| 240 | //wait for message like this: Breakpoint 1, 0x00401390 in sasmStartL () |
| 241 | if (c == 2 && output.indexOf(QString(" in ")) != -1) { |
| 242 | //set accordance between program in memory and program in file |
| 243 | //in example we need 0x00401390 |
| 244 | |
| 245 | //count offset |
| 246 | QRegExp r = QRegExp("0x[0-9a-fA-F]{8,16}"); |
| 247 | int index = r.indexIn(output); |
| 248 | //take offset in hexadecimal representation (10 symbols) from string and convert it to int |
| 249 | offset = output.mid(index, r.matchedLength()).toULongLong(0, 16); |
| 250 | processLst(); //count accordance |
| 251 | |
| 252 | c++; |
| 253 | actionTypeQueue.enqueue(ni); |
| 254 | doInput("info inferiors\n", none); |
| 255 | } |
| 256 | |
| 257 | //if an error with the wrong name of the section has occurred |
| 258 | if ((c == 2 && output.indexOf(QString("Make breakpoint pending on future shared library load")) != -1) |
| 259 | || (c == 1 && output == " ")) { |
| 260 | actionTypeQueue.enqueue(anyAction); |
| 261 | processAction(tr("An error has occurred in the debugger. Please check the names of the sections.")); |
| 262 | QObject::disconnect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputToBuffer())); |
| 263 | emit finished(); |
| 264 | } |
| 265 | } else { //debug symbols does not exists (for example, non-gcc linker) |
| 266 | if (c == 1) { |
| 267 | offset = entryPoint; //changes in processLst() |
| 268 | c++; |
| 269 | processLst(); //count accordance |
| 270 | run(); //perform Debugger::run(), that run program and open I/O files |
| 271 | return; |
| 272 | } |
| 273 | |
| 274 | //determine run of program |
| 275 | //wait for message like this: Breakpoint 1, 0x00401390 in sasmStartL () |
| 276 | if (c == 2 && output.indexOf(QString(" in ")) != -1) { |
| 277 | c++; |
| 278 | actionTypeQueue.enqueue(ni); |
| 279 | doInput("info inferiors\n", none); |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | //interrupt while debugging (program was stopped) |
| 284 | #ifdef Q_OS_WIN32 |
| 285 | QString interruptSig("SIGTRAP"); |
| 286 | #else |
| 287 | QString interruptSig("SIGINT"); |
| 288 | #endif |
| 289 | if (output.indexOf(interruptSig) != -1) { |
| 290 | stopped = true; |
| 291 | emit wasStopped(); |
| 292 | return; |
| 293 | } |
| 294 | |
| 295 | if (!pid) { |
| 296 | QRegExp r("Num +Description +(Connection +)?Executable"); |
| 297 | int index = output.indexOf(r); |
| 298 | if (index != -1) { |
| 299 | QString processString("process "); |
| 300 | r = QRegExp(processString + "[0-9]+"); |
| 301 | index = output.indexOf(r); |
| 302 | output = output.mid(index + processString.length()); |
| 303 | output = output.split(QChar(' ')).at(0); |
| 304 | pid = output.toULongLong(0, 10); |
| 305 | return; |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | //process all actions after start |
| 310 | if (c == 3) |
| 311 | if (output.indexOf(QString("$1 =")) == -1) //input file |
| 312 | processAction(output, error); |
| 313 | } |
| 314 | |
| 315 | void Debugger::processAction(QString output, QString error) |
| 316 | { |
| 317 | bool backtrace = (output.indexOf(QRegExp("#\\d+ 0x[0-9a-fA-F]{8,16} in .* ()")) != -1); |
| 318 | if (output.indexOf(exitMessage) != -1 && !backtrace) { |
| 319 | doInput("c\n", none); |
| 320 | return; |
| 321 | } |
| 322 | if (output.indexOf(QRegExp(cExitMessage)) != -1) { //if debug finished |
| 323 | //print output - message like bottom |
| 324 | /*Breakpoint 1, 0x08048510 in sasmStartL () |
| 325 | " |
| 326 | " Continuing. |
| 327 | abccba123 //program output |
| 328 | 567 //program output |
| 329 | [Inferior 1 (process 5693) exited normally] |
| 330 | " */ |
| 331 | |
| 332 | QRegExp continuingMsg("Continuing.\r?\n"); |
| 333 | QRegExp inferiorMsg("\\[Inferior "); |
| 334 | int continuingIndex = continuingMsg.indexIn(output); |
| 335 | int continuingLength = continuingMsg.matchedLength(); |
| 336 | int inferiorIndex = inferiorMsg.indexIn(output); |
| 337 | if (continuingIndex != -1) { |
| 338 | int outputLength = inferiorIndex - continuingIndex - continuingLength; |
| 339 | if (outputLength > 0) { |
| 340 | QString msg = output.mid(continuingIndex + continuingLength, outputLength); //program output |
| 341 | emit printOutput(msg); |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | //exit from debugging |
| 346 | QObject::disconnect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputToBuffer())); |
| 347 | emit finished(); |
| 348 | return; |
| 349 | } |
| 350 | if (actionTypeQueue.isEmpty()) { |
| 351 | return; |
| 352 | } |
| 353 | DebugActionType actionType = actionTypeQueue.dequeue(); |
| 354 | |
| 355 | if (actionType == breakpoint) |
| 356 | return; |
| 357 | |
| 358 | if (actionType == si || actionType == ni || actionType == showLine) { |
| 359 | //message is: line number + data |
| 360 | //print line number and other data if si or ni and print line number only if showLine |
| 361 | //scan line number in memory |
| 362 | QRegExp r = QRegExp("0x[0-9a-fA-F]{8,16}"); |
| 363 | int index = r.indexIn(output); |
| 364 | |
| 365 | //print output |
| 366 | if (index > 1 && !firstAction) { |
| 367 | QString msg = output.left(index); //left part - probably output of program; |
| 368 | msg.remove(0, 1); //remove first whitespace |
| 369 | QRegExp continuingMsg("Continuing.\r?\n"); |
| 370 | QRegExp breakpointMsg("\r?\nBreakpoint \\d+, "); |
| 371 | QRegExp threadMsg("\\[Switching to Thread [^\\]]*\\]\r?\n"); |
| 372 | QRegExp signalMsg("\r?\n(Program received signal.*)"); |
| 373 | msg.remove(continuingMsg); |
| 374 | msg.remove(breakpointMsg); |
| 375 | msg.remove(threadMsg); |
| 376 | if (signalMsg.indexIn(msg) != -1) { |
| 377 | QString recievedSignal = signalMsg.cap(1); |
| 378 | if (QRegExp("SIG(TRAP|INT)").indexIn(recievedSignal) == -1) { |
| 379 | emit printLog(recievedSignal, Qt::red); |
| 380 | } |
| 381 | msg.remove(signalMsg); |
| 382 | } |
| 383 | emit printOutput(msg); |
| 384 | } |
| 385 | firstAction = false; |
| 386 | |
| 387 | quint64 lineNumber = output.mid(index, r.matchedLength()).toULongLong(0, 16); |
| 388 | //take line number in hexadecimal representation |
| 389 | //(10 symbols) in memory from string and convert it to int |
| 390 | |
| 391 | //find line number in accordance array and get number line in file with code |
| 392 | bool found = false; |
| 393 | for (int i = lines.count() - 1; i >= 0; i--) { |
| 394 | if (lineNumber == lines[i].numInMem) { |
| 395 | lineNumber = lines[i].numInCode; |
| 396 | found = true; |
| 397 | break; |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | if (!found) { |
| 402 | //output = tr("Inside the macro or outside the program.") + '\n'; |
| 403 | emit inMacro(); |
| 404 | return; |
| 405 | } else { //if found highlight and print it |
| 406 | //highlight line number |
| 407 | gdbRun = true; |
| 408 | emit highlightLine(lineNumber); |
| 409 | stopped = true; |
| 410 | emit wasStopped(); |
| 411 | |
| 412 | //print string number and all after it |
| 413 | //output = QString::number(lineNumber) + tr(" line") + output.mid(output.indexOf("()") + 2); |
| 414 | if (actionType == showLine) |
| 415 | return; |
| 416 | output.remove(0, output.indexOf("()") + 2); |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | if (actionType == anyAction) { |
| 421 | if (output[output.length() - 1] != '\n') |
| 422 | output += QChar('\n'); |
| 423 | //process as ni or si |
| 424 | if (output.indexOf(QRegExp("0x[0-9a-fA-F]{8,16} in ")) != -1 |
| 425 | && !backtrace) { |
| 426 | actionTypeQueue.enqueue(showLine); |
| 427 | processAction(output); |
| 428 | } |
| 429 | if (!error.isEmpty()) { |
| 430 | if (output != " \n") |
| 431 | output = error + output; |
| 432 | else |
| 433 | output = error; |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | if (actionType == infoMemory) { |
| 438 | bool isValid = false; |
| 439 | if (output.indexOf(QString("No symbol")) == -1 && |
| 440 | output.indexOf(QString("no debug info")) == -1 && output != QString(" ")) { |
| 441 | //if variable exists (isValid = true) |
| 442 | isValid = true; |
| 443 | int index = output.indexOf(QRegExp("\\$\\d+ = .*")); |
| 444 | if (index == -1) |
| 445 | isValid = false; |
| 446 | else { |
| 447 | output = output.right(output.length() - index); |
| 448 | output = output.right(output.length() - output.indexOf(QChar('=')) - 1); |
| 449 | output = output.trimmed(); |
| 450 | } |
| 451 | } |
| 452 | memoryInfo info; |
| 453 | if (isValid) |
| 454 | info.value = output; |
| 455 | info.isValid = isValid; |
| 456 | watches.append(info); |
| 457 | if (watchesCount == watches.size()) { |
| 458 | emit printMemory(watches); |
| 459 | watches.clear(); |
| 460 | } |
| 461 | return; |
| 462 | } |
| 463 | |
| 464 | if (actionType == infoRegisters) { |
| 465 | QTextStream registersStream(&output); |
| 466 | QList<registersInfo> registers; |
| 467 | registersInfo info; |
| 468 | QSettings settings("SASM Project", "SASM"); |
| 469 | |
| 470 | QSet<QString> general; |
| 471 | QString ip; |
| 472 | QSet<QString> segment; |
| 473 | segment << "cs" << "ds" << "ss" << "es" << "fs" << "gs" << "fs_base" << "gs_base"; |
| 474 | QSet<QString> flags; |
| 475 | flags << "eflags" << "mxcsr"; |
| 476 | QSet<QString> fpu_info; |
| 477 | fpu_info << "fctrl" << "fstat" << "ftag" << "fiseg" << "fioff" << "foseg" << "fooff" << "fop"; |
| 478 | QRegExp mmx("mm\\d+"); |
| 479 | QRegExp xmm("xmm\\d+"); |
| 480 | QRegExp ymm("ymm\\d+"); |
| 481 | QRegExp fpu_stack("st\\d+"); |
| 482 | |
| 483 | if (settings.value("mode", QString("x86")).toString() == "x86") { |
| 484 | //x86 |
| 485 | general << "eax" << "ebx" << "ecx" << "edx" << "esi" << "edi" << "esp" << "ebp"; |
| 486 | ip = "eip"; |
| 487 | } else { |
| 488 | //x64 |
| 489 | general << "rax" << "rbx" << "rcx" << "rdx" << "rsi" << "rdi" << "rsp" << "rbp" << |
| 490 | "r8" << "r9" << "r10" << "r11" << "r12" << "r13" << "r14" << "r15"; |
| 491 | ip = "rip"; |
| 492 | } |
| 493 | |
| 494 | for (int i = 0; !registersStream.atEnd(); i++) { |
| 495 | registersStream >> info.name; |
| 496 | |
| 497 | if (info.name.isEmpty()) { |
| 498 | // last empty line |
| 499 | break; |
| 500 | } |
| 501 | |
| 502 | if (general.contains(info.name) || segment.contains(info.name) || fpu_info.contains(info.name) || |
| 503 | info.name == ip || flags.contains(info.name) || fpu_stack.exactMatch(info.name)) { |
| 504 | registersStream >> info.hexValue; |
| 505 | registersStream.skipWhiteSpace(); |
| 506 | info.decValue = registersStream.readLine(); |
| 507 | } else if (mmx.exactMatch(info.name) || xmm.exactMatch(info.name) || ymm.exactMatch(info.name)) { |
| 508 | QMap<QString, QString> fields; |
| 509 | |
| 510 | if (!readStruct(registersStream, &fields)) { |
| 511 | // bad news |
| 512 | emit printLog(QString("can not parse register data: ") + info.name + "\n", Qt::red); |
| 513 | break; |
| 514 | } |
| 515 | |
| 516 | if (mmx.exactMatch(info.name)) |
| 517 | info.decValue = fields["v8_int8"]; |
| 518 | else if (xmm.exactMatch(info.name)) |
| 519 | info.decValue = fields["uint128"]; |
| 520 | else if (ymm.exactMatch(info.name)) |
| 521 | info.decValue = fields["v2_int128"]; |
| 522 | |
| 523 | info.hexValue = ""; |
| 524 | } else { |
| 525 | // unknown register, try to skip it. |
| 526 | registersStream.readLine(); |
| 527 | emit printLog(QString("unknown register: ") + info.name + "\n", Qt::red); |
| 528 | continue; |
| 529 | } |
| 530 | |
| 531 | registers.append(info); |
| 532 | if (i == 0 && info.name != "eax" && info.name != "rax" && registersOk) { |
| 533 | doInput(QString("info registers\n"), infoRegisters); |
| 534 | registersOk = false; |
| 535 | return; |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | emit printRegisters(registers); |
| 540 | return; |
| 541 | } |
| 542 | |
| 543 | if (output == QString("\r\n") || output == QString("\n") || |
| 544 | output == QString("\r\n\n") || output == QString("\n\n")) //if empty |
| 545 | return; |
| 546 | |
| 547 | //print information to log field |
| 548 | emit printLog(output, QSettings("SASM Project", "SASM").value("fontcolor", QColor(30, 30, 30)).value<QColor>()); |
| 549 | } |
| 550 | |
| 551 | bool Debugger::isStopped() |
| 552 | { |
| 553 | return stopped; |
| 554 | } |
| 555 | |
| 556 | void Debugger::pause() |
| 557 | { |
| 558 | if (pid == 0) |
| 559 | return; |
| 560 | actionTypeQueue.clear(); |
| 561 | #ifdef Q_OS_WIN32 |
| 562 | HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid); |
| 563 | if (proc != NULL) { |
| 564 | DebugBreakProcess(proc); |
| 565 | CloseHandle(proc); |
| 566 | } |
| 567 | #else |
| 568 | kill(pid, SIGINT); |
| 569 | #endif |
| 570 | } |
| 571 | |
| 572 | void Debugger::doInput(QString command, DebugActionType actionType) |
| 573 | { |
| 574 | if (actionType != none) |
| 575 | actionTypeQueue.enqueue(actionType); |
| 576 | commandQueue.enqueue(command); |
| 577 | //put \n after commands! |
| 578 | if (actionType == ni || actionType == si || actionType == showLine) { |
| 579 | emit highlightLine(-2); //does not turn off debug mode |
| 580 | stopped = false; |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | void Debugger::setWatchesCount(int count) |
| 585 | { |
| 586 | watchesCount = count; |
| 587 | } |
| 588 | |
| 589 | void Debugger::processLst() |
| 590 | { |
| 591 | //set accordance with .lst file and program in memory |
| 592 | QFile lst; |
| 593 | lst.setFileName(Common::pathInTemp("program.lst")); |
| 594 | if (lst.open(QIODevice::ReadOnly)) { |
| 595 | //heuristic: |
| 596 | //if debug symbols exists - offset is difference between main labels in listing and in executable |
| 597 | //otherwise - offset is difference between entry point, labeled as "start", in listing and in executable |
| 598 | quint64 mainOffset; |
| 599 | if (dbgSymbols) |
| 600 | mainOffset = assembler->getMainOffset(lst, "main"); |
| 601 | else |
| 602 | mainOffset = assembler->getMainOffset(lst, "start"); |
| 603 | lst.close(); |
| 604 | if ((qint64) mainOffset == -1) { |
| 605 | actionTypeQueue.enqueue(anyAction); |
| 606 | processAction( |
| 607 | tr("Entry point was not found! Entry point should have label \"main\" (if gcc linker is used) or \"start\" (otherwise).")); |
| 608 | QObject::disconnect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputToBuffer())); |
| 609 | emit finished(); |
| 610 | return; |
| 611 | } |
| 612 | offset -= mainOffset; |
| 613 | lst.open(QIODevice::ReadOnly); |
| 614 | assembler->parseLstFile(lst, lines, offset); |
| 615 | lst.close(); |
| 616 | if (lines.isEmpty()) { |
| 617 | actionTypeQueue.enqueue(anyAction); |
| 618 | processAction( |
| 619 | tr("Executable sections were not found! ") + |
| 620 | tr("For correct debugging executable sections should have name \".text\" or \".code\" (for MASM only).")); |
| 621 | QObject::disconnect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputToBuffer())); |
| 622 | emit finished(); |
| 623 | return; |
| 624 | } |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | void Debugger::run() |
| 629 | { |
| 630 | //set breakpoint on main, run program amd open output and input files |
| 631 | //put \n after commands! |
| 632 | //b main and run before others! |
| 633 | if (dbgSymbols) |
| 634 | doInput(QString("b *main\n"), none); |
| 635 | else { |
| 636 | doInput("b *0x" + QString::number(entryPoint, 16) + "\n", none); |
| 637 | } |
| 638 | doInput(QString("cd " + workingDirectoryPath + "\n"), none); |
| 639 | #ifdef Q_OS_WIN32 |
| 640 | doInput(QString("run\n"), none); |
| 641 | QSettings settings("SASM Project", "SASM"); |
| 642 | if (settings.value("mode", QString("x86")).toString() == "x86") { |
| 643 | doInput(QString("p freopen(\"%1\", \"r\", (FILE *) {0, 0, 0, 1, 0, 0, 4096, 0, 0})\n").arg(inputPath), none); |
| 644 | } else { |
| 645 | doInput(QString("p freopen(\"%1\", \"r\", (FILE *) {0, 0, 0, 0, 0, 0, 1, 0, 0, 4096, 0, 0})\n").arg(inputPath), none); |
| 646 | } |
| 647 | #else |
| 648 | doInput(QString("run < %1\n").arg(inputPath), none); |
| 649 | doInput(QString("p 0\n"), none); |
| 650 | #endif |
| 651 | } |
| 652 | |
| 653 | void Debugger::changeBreakpoint(quint64 lineNumber, bool isAdded) |
| 654 | { |
| 655 | bool wasStarted = false; |
| 656 | if (!isStopped()) { |
| 657 | wasStarted = true; |
| 658 | QEventLoop eventLoop; |
| 659 | connect(this, SIGNAL(wasStopped()), &eventLoop, SLOT(quit())); |
| 660 | pause(); |
| 661 | eventLoop.exec(); |
| 662 | } |
| 663 | quint64 numInMem = 0; |
| 664 | LineNum brkpoint; |
| 665 | for (int i = 0; i < lines.count(); i++) //find address of line |
| 666 | if (lineNumber <= lines[i].numInCode) { |
| 667 | numInMem = lines[i].numInMem; |
| 668 | break; |
| 669 | } |
| 670 | brkpoint.numInCode = lineNumber; |
| 671 | brkpoint.numInMem = numInMem; |
| 672 | |
| 673 | LineNum pair; |
| 674 | int count = 0; |
| 675 | foreach (pair, breakPairs) { |
| 676 | if (pair.numInMem == numInMem) |
| 677 | count++; |
| 678 | } |
| 679 | if (isAdded) { //if breakpoint was added then set it |
| 680 | breakPairs.append(brkpoint); |
| 681 | if (count == 0) |
| 682 | doInput(QString("b *0x") + QString::number(numInMem, 16) + QString("\n"), breakpoint); |
| 683 | } else { //if breakpoint was deleted then remove it |
| 684 | breakPairs.removeOne(brkpoint); |
| 685 | if (count == 1) |
| 686 | doInput(QString("clear *0x") + QString::number(numInMem, 16) + QString("\n"), breakpoint); |
| 687 | } |
| 688 | if (wasStarted) |
| 689 | emit needToContinue(); |
| 690 | } |
| 691 | |
| 692 | Debugger::~Debugger() { |
| 693 | emit highlightLine(-1); |
| 694 | if (process->state() == QProcess::Running) { |
| 695 | doInput("quit\n", none); |
| 696 | process->waitForFinished(1000); |
| 697 | if (process->state() == QProcess::Running) { //if still running |
| 698 | doInput("quit\n", none); |
| 699 | process->terminate(); |
| 700 | } |
| 701 | } |
| 702 | delete process; |
| 703 | process = 0; |
| 704 | lines.clear(); |
| 705 | delete bufferTimer; |
| 706 | } |
| 707 | |
| 708 | namespace { |
| 709 | |
| 710 | // read struct like {<name1> = <value1>, ,,, <nameN> = <valueN>} |
| 711 | // from stream. Values may be simple or complex, like {v1, v2, v3 .. } |
| 712 | // all vi have to be simple, two-level complex values unsupported |
| 713 | // |
| 714 | // test end of stream before any reading, desperately trying not to hang on it |
| 715 | bool readStruct(QTextStream& str, QMap<QString, QString>* map) { |
| 716 | str.skipWhiteSpace(); |
| 717 | if (str.atEnd()) |
| 718 | return false; |
| 719 | |
| 720 | QChar c; |
| 721 | str >> c; |
| 722 | if (c != '{') |
| 723 | return false; |
| 724 | |
| 725 | // struct begin |
| 726 | while (!str.atEnd()) { |
| 727 | str.skipWhiteSpace(); |
| 728 | |
| 729 | // may be it just empty |
| 730 | str >> c; |
| 731 | if (c == '}') |
| 732 | return true; |
| 733 | |
| 734 | // read name, until space or '=' |
| 735 | QString name; |
| 736 | name += c; |
| 737 | |
| 738 | for (;;) { |
| 739 | if (str.atEnd()) |
| 740 | return false; |
| 741 | str >> c; |
| 742 | if (c.isSpace() || (c == '=')) break; |
| 743 | name += c; |
| 744 | } |
| 745 | |
| 746 | // read '=' |
| 747 | if (c != '=') { |
| 748 | str.skipWhiteSpace(); |
| 749 | |
| 750 | if (str.atEnd()) |
| 751 | return false; |
| 752 | str >> c; |
| 753 | if (c != '=') // it has to be assignment |
| 754 | return false; |
| 755 | } |
| 756 | |
| 757 | str.skipWhiteSpace(); |
| 758 | |
| 759 | // read value, simple (until space, or ',', or '}') or complex (until '}') |
| 760 | QString value; |
| 761 | |
| 762 | if (str.atEnd()) |
| 763 | return false; |
| 764 | str >> c; |
| 765 | |
| 766 | if (c != '{') { |
| 767 | // simple value |
| 768 | value += c; |
| 769 | |
| 770 | for (;;) { |
| 771 | if (str.atEnd()) |
| 772 | return false; |
| 773 | str >> c; |
| 774 | if (c.isSpace() || (c == ',') || (c == '}')) break; |
| 775 | value += c; |
| 776 | } |
| 777 | } else { |
| 778 | // complex value |
| 779 | value += '{'; |
| 780 | |
| 781 | for (;;) { |
| 782 | if (str.atEnd()) |
| 783 | return false; |
| 784 | str >> c; |
| 785 | if (c == '}') break; |
| 786 | if (c.isSpace()) { |
| 787 | // replace all space characters by simple space |
| 788 | // and skip spaces after '{' and after space |
| 789 | if (!value.endsWith('{') && !value.endsWith(' ')) |
| 790 | value += ' '; |
| 791 | } else { |
| 792 | value += c; |
| 793 | } |
| 794 | } |
| 795 | |
| 796 | value += '}'; |
| 797 | c = ' '; // it was not last }, just end of value |
| 798 | } |
| 799 | |
| 800 | (*map)[name] = value; |
| 801 | |
| 802 | // to next name-value pair |
| 803 | if (c.isSpace()) { |
| 804 | str.skipWhiteSpace(); |
| 805 | if (str.atEnd()) |
| 806 | return false; |
| 807 | str >> c; |
| 808 | } |
| 809 | |
| 810 | if (c == '}') // end of struct |
| 811 | return true; |
| 812 | if (c != ',') // it has to be comma |
| 813 | return false; |
| 814 | |
| 815 | } |
| 816 | |
| 817 | return false; |
| 818 | } |
| 819 | } |