File: debugger.cpp

package info (click to toggle)
sasm 3.10.1-1
  • links: PTS
  • area: main
  • in suites: buster
  • size: 3,308 kB
  • sloc: cpp: 7,166; pascal: 1,596; asm: 81; makefile: 7; ansic: 5
file content (775 lines) | stat: -rw-r--r-- 28,833 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
/****************************************************************************
** SASM - simple IDE for assembler development
** Copyright (C) 2013 Dmitriy Manushin
** Contact: site: http://dman95.github.io/SASM/
**          e-mail: Dman1095@gmail.com
**
** This file is part of SASM.
**
** SASM is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** SASM is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with SASM.  If not, see <http://www.gnu.org/licenses/>.
**
** Этот файл — часть SASM.
**
** SASM - свободная программа: вы можете перераспространять ее и/или
** изменять ее на условиях Стандартной общественной лицензии GNU в том виде,
** в каком она была опубликована Фондом свободного программного обеспечения;
** либо версии 3 лицензии, либо (по вашему выбору) любой более поздней
** версии.
**
** SASM распространяется в надежде, что она будет полезной,
** но БЕЗО ВСЯКИХ ГАРАНТИЙ; даже без неявной гарантии ТОВАРНОГО ВИДА
** или ПРИГОДНОСТИ ДЛЯ ОПРЕДЕЛЕННЫХ ЦЕЛЕЙ. Подробнее см. в Стандартной
** общественной лицензии GNU.
**
** Вы должны были получить копию Стандартной общественной лицензии GNU
** вместе с этой программой. Если это не так, см.
** <http://www.gnu.org/licenses/>.)
**
****************************************************************************/

#include "debugger.h"

/**
 * @file debugger.cpp
 * Sets debugger information and runs the debugger.
 */

namespace {
    // read struct like {<name1> = <value1>, ,,, <nameN> = <valueN>}
    // from stream. Values may be simple or complex, like {v1, v2, v3 .. }
    // all i have to be simple, two-level complex values unsupported
    bool readStruct(QTextStream& str, QMap<QString, QString>* map);
}


Debugger::Debugger(QTextEdit *tEdit, const QString &path, QString tmp, Assembler *assembler, QWidget *parent)
    : QObject(parent)
{
    QSettings settings("SASM Project", "SASM");
    c = 0;
    pid = 0;
    firstAction = true;
    textEdit = tEdit;
    tmpPath = tmp;
    registersOk = true;
    this->assembler = assembler;
    #ifdef Q_OS_WIN32
        QString gdb;
        QString objdump;
        if (settings.value("mode", QString("x86")).toString() == "x86") {
            gdb = QCoreApplication::applicationDirPath() + "/MinGW/bin/gdb.exe";
            objdump = QCoreApplication::applicationDirPath() + "/MinGW/bin/objdump.exe";
            if (! QFile::exists(gdb))
                gdb = QCoreApplication::applicationDirPath() + "/Windows/MinGW/bin/gdb.exe";
            if (! QFile::exists(objdump))
                objdump = QCoreApplication::applicationDirPath() + "/Windows/MinGW/bin/objdump.exe";
            exitMessage = "mingw_CRTStartup";
        } else {
            gdb = QCoreApplication::applicationDirPath() + "/MinGW64/bin/gdb.exe";
            objdump = QCoreApplication::applicationDirPath() + "/MinGW/bin/objdump.exe";
            if (! QFile::exists(gdb))
                gdb = QCoreApplication::applicationDirPath() + "/Windows/MinGW64/bin/gdb.exe";
            if (! QFile::exists(objdump))
                objdump = QCoreApplication::applicationDirPath() + "/Windows/MinGW/bin/objdump.exe";
            exitMessage = "__fu0__set_invalid_parameter_handler";
        }
    #else
        QString gdb = "gdb";
        QString objdump = "objdump";
        exitMessage = "libc_start_main";
    #endif
    cExitMessage = QRegExp("\\[Inferior .* exited");

    connect(this, SIGNAL(wasStopped()), this, SLOT(emitStarted()));

    //determine entry point
    QProcess objdumpProcess;
    QProcessEnvironment objdumpEnvironment = QProcessEnvironment::systemEnvironment();
    QStringList objdumpArguments;
    objdumpArguments << "-f" << path;
	objdumpEnvironment.insert("LC_MESSAGES", "en_US");
	objdumpProcess.setProcessEnvironment(objdumpEnvironment);
    objdumpProcess.start(objdump, objdumpArguments);
    objdumpProcess.waitForFinished();
    QString objdumpResult = QString(objdumpProcess.readAllStandardOutput());
    QString startAddress("start address ");
    int index = objdumpResult.indexOf(startAddress);
    objdumpResult = objdumpResult.mid(index + startAddress.length());
    entryPoint = objdumpResult.toLongLong(0, 16);


    QStringList arguments;
    arguments << path;

    process = new QProcess;
    process->start(gdb, arguments);

    QObject::connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputToBuffer()));
    QObject::connect(process, SIGNAL(readyReadStandardError()), this, SLOT(readOutputToBuffer()));

    bufferTimer = new QTimer;
    QObject::connect(bufferTimer, SIGNAL(timeout()), this, SLOT(processOutput()), Qt::QueuedConnection);
    bufferTimer->start(10);
}

void Debugger::emitStarted()
{
    disconnect(this, SIGNAL(wasStopped()), this, SLOT(emitStarted()));
    emit started();
}

void Debugger::readOutputToBuffer()
{
    if (!process)
        return;
    QByteArray error = process->readAllStandardError();
    errorBuffer += QString::fromLocal8Bit(error.constData(), error.size());
    QByteArray output = process->readAllStandardOutput();
    buffer += QString::fromLocal8Bit(output.constData(), output.size());
}

void Debugger::processOutput()
{
    bufferTimer->stop();
    int index = buffer.indexOf(QString("(gdb)"));
    int linefeedIndex = errorBuffer.indexOf("\n");
    if (index != -1) { //if whole message ready to processing (end of whole message is "(gdb)")
        QString output = buffer.left(index);
        QString error = errorBuffer.left(linefeedIndex);
        buffer.remove(0, index + 5); //remove processed message
        errorBuffer.remove(0, linefeedIndex + 1);
        processMessage(output, error);
    }
    bufferTimer->start(10);
}

void Debugger::processMessage(QString output, QString error)
{
    if (error.indexOf("PC register is not available") != -1) {
        emit printLog(tr("GDB error\n"), Qt::red);
        emit finished();
        return;
    }
    if (c == 0) { //in start wait for printing of start gdb text like this:
        /*GNU gdb (GDB) 7.4
        Copyright (C) 2012 Free Software Foundation, Inc.
        License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
        This is free software: you are free to change and redistribute it.
        There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
        and "show warranty" for details.
        This GDB was configured as "i686-pc-mingw32".
        For bug reporting instructions, please see:
        <http://www.gnu.org/software/gdb/bugs/>...
        Reading symbols from C:\Users\Dmitri\Dropbox\Projects\SASMstatic\release\Program\SASMprog.exe...
        done.
        (gdb)*/
        c++;
        doInput(QString("disas main\n"), none);
        return;
    }

    if (c == 1) {
    if (error.indexOf("No symbol",0,Qt::CaseInsensitive)!=-1) {
            dbgSymbols = false;
        } else {
            dbgSymbols = true;
        }
    }

    if (dbgSymbols) { //debug symbols exists
        if (c == 1 && output != " ") {
            //next disassembly top part of code for setting according with program in memory and program in file
            /*Dump of assembler code for function sasmStartL:
               0x00401390 <+0>:	xor    %eax,%eax
               0x00401392 <+2>:	ret
               0x00401393 <+3>:	add    %dl,-0x77(%ebp)
            End of assembler dump.*/
            //we need first number (0x00401390)

            //count offset
            QRegExp r = QRegExp("0x[0-9a-fA-F]{8,16}");
            int index = r.indexIn(output);
            offset = output.mid(index, r.matchedLength()).toULongLong(0, 16);
            //take offset in hexadecimal representation (10 symbols) from string and convert it to int
            c++;
            processLst(); //count accordance
            run(); //perform Debugger::run(), that run program and open I/O files
            return;
        }

        //determine run of program
        //wait for message like this: Breakpoint 1, 0x00401390 in sasmStartL ()
        if (c == 2 && output.indexOf(QString(" in ")) != -1) {
            c++;
            actionTypeQueue.enqueue(ni);
            doInput("info inferiors\n", none);
        }

        //if an error with the wrong name of the section has occurred
        if ((c == 2 && output.indexOf(QString("Make breakpoint pending on future shared library load")) != -1)
                || (c == 1 && output == " ")) {
            actionTypeQueue.enqueue(anyAction);
            processAction(tr("An error has occurred in the debugger. Please check the names of the sections."));
            QObject::disconnect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputToBuffer()));
            emit finished();
        }
    } else { //debug symbols does not exists (for example, non-gcc linker)
        if (c == 1) {
            offset = entryPoint; //changes in processLst()
            c++;
            processLst(); //count accordance
            run(); //perform Debugger::run(), that run program and open I/O files
            return;
        }

        //determine run of program
        //wait for message like this: Breakpoint 1, 0x00401390 in sasmStartL ()
        if (c == 2 && output.indexOf(QString(" in ")) != -1) {
            c++;
            actionTypeQueue.enqueue(ni);
            doInput("info inferiors\n", none);
        }
    }

    //interrupt while debugging (program was stopped)
    #ifdef Q_OS_WIN32
        QString interruptSig("SIGTRAP");
    #else
        QString interruptSig("SIGINT");
    #endif
    if (output.indexOf(interruptSig) != -1) {
        stopped = true;
        emit wasStopped();
        return;
    }

    if (!pid) {
        QRegExp r("Num +Description +Executable");
        int index = output.indexOf(r);
        if (index != -1) {
            QString processString("process ");
            r = QRegExp(processString + "[0-9]+");
            index = output.indexOf(r);
            output = output.mid(index + processString.length());
            output = output.split(QChar(' ')).at(0);
            pid = output.toULongLong(0, 10);
            return;
        }
    }

    //process all actions after start
    if (c == 3)
        if (output.indexOf(QString("$1 =")) == -1) //input file
            processAction(output, error);
}

void Debugger::processAction(QString output, QString error)
{
    bool backtrace = (output.indexOf(QRegExp("#\\d+  0x[0-9a-fA-F]{8,16} in .* ()")) != -1);
    if (output.indexOf(exitMessage) != -1 && !backtrace) {
        doInput("c\n", none);
        return;
    }
    if (output.indexOf(QRegExp(cExitMessage)) != -1) { //if debug finished
        //print output - message like bottom
            /*Breakpoint 1, 0x08048510 in sasmStartL ()
            "
            " Continuing.
            abccba123 //program output
            567 //program output
            [Inferior 1 (process 5693) exited normally]
            " */

        QRegExp continuingMsg("Continuing.\r?\n");
        QRegExp inferiorMsg("\\[Inferior ");
        int continuingIndex = continuingMsg.indexIn(output);
        int continuingLength = continuingMsg.matchedLength();
        int inferiorIndex = inferiorMsg.indexIn(output);
        if (continuingIndex != -1) {
            int outputLength = inferiorIndex - continuingIndex - continuingLength;
            if (outputLength > 0) {
                QString msg = output.mid(continuingIndex + continuingLength, outputLength); //program output
                emit printOutput(msg);
            }
        }

        //exit from debugging
        QObject::disconnect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputToBuffer()));
        emit finished();
        return;
    }
    if (actionTypeQueue.isEmpty()) {
        return;
    }
    DebugActionType actionType = actionTypeQueue.dequeue();

    if (actionType == breakpoint)
        return;

    if (actionType == si || actionType == ni || actionType == showLine) {
        //message is: line number + data
        //print line number and other data if si or ni and print line number only if showLine
        //scan line number in memory
        QRegExp r = QRegExp("0x[0-9a-fA-F]{8,16}");
        int index = r.indexIn(output);

        //print output
        if (index > 1 && !firstAction) {
            QString msg = output.left(index); //left part - probably output of program;
            msg.remove(0, 1); //remove first whitespace
            QRegExp continuingMsg("Continuing.\r?\n");
            QRegExp breakpointMsg("\r?\nBreakpoint \\d+, ");
            QRegExp threadMsg("\\[Switching to Thread [^\\]]*\\]\r?\n");
            QRegExp signalMsg("\r?\n(Program received signal.*)");
            msg.remove(continuingMsg);
            msg.remove(breakpointMsg);
            msg.remove(threadMsg);
            if (signalMsg.indexIn(msg) != -1) {
                QString recievedSignal = signalMsg.cap(1);
                if (QRegExp("SIG(TRAP|INT)").indexIn(recievedSignal) == -1) {
                    emit printLog(recievedSignal, Qt::red);
                }
                msg.remove(signalMsg);
            }
            emit printOutput(msg);
        }
        firstAction = false;

        quint64 lineNumber = output.mid(index, r.matchedLength()).toULongLong(0, 16);
        //take line number in hexadecimal representation
        //(10 symbols) in memory from string and convert it to int

        //find line number in accordance array and get number line in file with code
        bool found = false;
        for (int i = lines.count() - 1; i >= 0; i--) {
            if (lineNumber == lines[i].numInMem) {
                lineNumber = lines[i].numInCode;
                found = true;
                break;
            }
        }

        if (!found) {
            //output = tr("Inside the macro or outside the program.") + '\n';
            emit inMacro();
            return;
        } else { //if found highlight and print it
            //highlight line number
            emit highlightLine(lineNumber);
            stopped = true;
            emit wasStopped();

            //print string number and all after it
            //output = QString::number(lineNumber) + tr(" line") + output.mid(output.indexOf("()") + 2);
            if (actionType == showLine)
                return;
            output.remove(0, output.indexOf("()") + 2);
        }
    }

    if (actionType == anyAction) {
        if (output[output.length() - 1] != '\n')
            output += QChar('\n');
        //process as ni or si
        if (output.indexOf(QRegExp("0x[0-9a-fA-F]{8,16} in ")) != -1
                && !backtrace) {
            actionTypeQueue.enqueue(showLine);
            processAction(output);
        }
        if (!error.isEmpty()) {
            if (output != " \n")
                output = error + output;
            else
                output = error;
        }
    }

    if (actionType == infoMemory) {
        bool isValid = false;
        if (output.indexOf(QString("No symbol")) == -1 &&
                output.indexOf(QString("no debug info")) == -1 && output != QString(" ")) {
            //if variable exists (isValid = true)
            isValid = true;
            int index = output.indexOf(QRegExp("\\$\\d+ = .*"));
            if (index == -1)
                isValid = false;
            else {
                output = output.right(output.length() - index);
                output = output.right(output.length() - output.indexOf(QChar('=')) - 1);
                for (int i = output.size() - 1; i >= 0; i--) {
                    if (output[i].isSpace())
                        output.remove(i, 1);
                }
            }
        }
        memoryInfo info;
        if (isValid)
            info.value = output;
        info.isValid = isValid;
        watches.append(info);
        if (watchesCount == watches.size()) {
            emit printMemory(watches);
            watches.clear();
        }
        return;
    }

    if (actionType == infoRegisters) {
        QTextStream registersStream(&output);
        QList<registersInfo> registers;
        registersInfo info;
        QSettings settings("SASM Project", "SASM");

        QSet<QString> general;
        QString ip;
        QSet<QString> segment;
        segment << "cs" << "ds" << "ss" << "es" << "fs" << "gs";
        QSet<QString> flags;
        flags << "eflags" << "mxcsr";
        QSet<QString> fpu_info;
        fpu_info << "fctrl" << "fstat" << "ftag" << "fiseg" << "fioff" << "foseg" << "fooff" << "fop";
        QRegExp mmx("mm\\d+");
        QRegExp xmm("xmm\\d+");
        QRegExp ymm("ymm\\d+");
        QRegExp fpu_stack("st\\d+");

        if (settings.value("mode", QString("x86")).toString() == "x86") {
            //x86
            general << "eax" << "ebx" << "ecx" << "edx" << "esi" << "edi" << "esp" << "ebp";
            ip = "eip";
        } else {
            //x64
            general << "rax" << "rbx" << "rcx" << "rdx" << "rsi" << "rdi" << "rsp" << "rbp" <<
                       "r8" << "r9" << "r10" << "r11" << "r12" << "r13" << "r14" << "r15";
            ip = "rip";
        }

        for (int i = 0; !registersStream.atEnd(); i++) {
            registersStream >> info.name;

            if (info.name.isEmpty()) {
                // last empty line
                break;
            }

            if (general.contains(info.name) || segment.contains(info.name) || fpu_info.contains(info.name)) {
                registersStream >> info.hexValue >> info.decValue;
            } else if ((info.name == ip) || flags.contains(info.name) || fpu_stack.exactMatch(info.name)) {
                registersStream >> info.hexValue;
                registersStream.skipWhiteSpace();
                info.decValue = registersStream.readLine();
            } else if (mmx.exactMatch(info.name) || xmm.exactMatch(info.name) || ymm.exactMatch(info.name)) {
                QMap<QString, QString> fields;

                if (!readStruct(registersStream, &fields)) {
                    // bad news
                    emit printLog(QString("can not parse register data: ") + info.name + "\n", Qt::red);
                    break;
                }

                if (mmx.exactMatch(info.name))
                    info.decValue = fields["v8_int8"];
                else if (xmm.exactMatch(info.name))
                    info.decValue = fields["uint128"];
                else if (ymm.exactMatch(info.name))
                    info.decValue = fields["v2_int128"];

                info.hexValue = "";
            } else {
                // unknown register, try to skip it.
                registersStream.readLine();
                emit printLog(QString("unknown register: ") + info.name + "\n", Qt::red);
                continue;
            }

            registers.append(info);
            if (i == 0 && info.name != "eax" && info.name != "rax" && registersOk) {
                doInput(QString("info registers\n"), infoRegisters);
                registersOk = false;
                return;
            }
        }

        emit printRegisters(registers);
        return;
    }

    if (output == QString("\r\n") || output == QString("\n") ||
            output == QString("\r\n\n") || output == QString("\n\n")) //if empty
        return;

    //print information to log field
    emit printLog(output);
}

bool Debugger::isStopped()
{
    return stopped;
}

void Debugger::pause()
{
    if (pid == 0)
	return;
    actionTypeQueue.clear();
    #ifdef Q_OS_WIN32
        HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
        if (proc != NULL) {
    	    DebugBreakProcess(proc);
    	    CloseHandle(proc);
        }
    #else
    	kill(pid, SIGINT);
    #endif
}

void Debugger::doInput(QString command, DebugActionType actionType)
{
    if (actionType != none)
        actionTypeQueue.enqueue(actionType);
    //put \n after commands!
    if (actionType == ni || actionType == si || actionType == showLine) {
        emit highlightLine(-2); //does not turn off debug mode
        stopped = false;
    }
    if (process)
        process->write(command.toLatin1());
}

void Debugger::setWatchesCount(int count)
{
    watchesCount = count;
}

void Debugger::processLst()
{
    //set accordance with .lst file and program in memory
    QFile lst;
    lst.setFileName(Common::pathInTemp("program.lst"));
    if (lst.open(QIODevice::ReadOnly)) {
        //heuristic:
        //if debug symbols exists - offset is difference between main labels in listing and in executable
        //otherwise - offset is difference between entry point, labeled as "start", in listing and in executable
        quint64 mainOffset;
        if (dbgSymbols)
            mainOffset = assembler->getMainOffset(lst, "main");
        else
            mainOffset = assembler->getMainOffset(lst, "start");
        lst.close();
        if ((qint64) mainOffset == -1) {
            actionTypeQueue.enqueue(anyAction);
            processAction(
                tr("Entry point was not found! Entry point should have label \"main\" (if gcc linker is used) or \"start\" (otherwise)."));
            QObject::disconnect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputToBuffer()));
            emit finished();
            return;
        }
        offset -= mainOffset;
        lst.open(QIODevice::ReadOnly);
        assembler->parseLstFile(lst, lines, offset);
        lst.close();
        if (lines.isEmpty()) {
            actionTypeQueue.enqueue(anyAction);
            processAction(
                tr("Executable sections were not found! ") +
                tr("For correct debugging executable sections should have name \".text\" or \".code\" (for MASM only)."));
            QObject::disconnect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutputToBuffer()));
            emit finished();
            return;
        }
    }
}

void Debugger::run()
{
    //set breakpoint on main, run program amd open output and input files
    //put \n after commands!
    //b main and run before others!
    if (dbgSymbols)
        doInput(QString("b main\n"), none);
    else {
        doInput("b *0x" + QString::number(entryPoint, 16) + "\n", none);
    }
    doInput(QString("cd " + tmpPath + "\n"), none);
    doInput(QString("run\n"), none);
    doInput(QString("p dup2(open(\"input.txt\",0),0)\n"), none);
}

void Debugger::changeBreakpoint(quint64 lineNumber, bool isAdded)
{
    bool wasStarted = false;
    if (!isStopped()) {
        wasStarted = true;
        QEventLoop eventLoop;
        connect(this, SIGNAL(wasStopped()), &eventLoop, SLOT(quit()));
        pause();
        eventLoop.exec();
    }
    quint64 numInMem = 0;
    LineNum brkpoint;
    for (int i = 0; i < lines.count(); i++) //find address of line
        if (lineNumber <= lines[i].numInCode) {
            numInMem = lines[i].numInMem;
            break;
        }
    brkpoint.numInCode = lineNumber;
    brkpoint.numInMem = numInMem;

    LineNum pair;
    int count = 0;
    foreach (pair, breakPairs) {
        if (pair.numInMem == numInMem)
            count++;
    }
    if (isAdded) { //if breakpoint was added then set it
        breakPairs.append(brkpoint);
        if (count == 0)
            doInput(QString("b *0x") + QString::number(numInMem, 16) + QString("\n"), breakpoint);
    } else { //if breakpoint was deleted then remove it
        breakPairs.removeOne(brkpoint);
        if (count == 1)
            doInput(QString("clear *0x") + QString::number(numInMem, 16) + QString("\n"), breakpoint);
    }
    if (wasStarted)
        emit needToContinue();
}

Debugger::~Debugger() {
    emit highlightLine(-1);
    if (process->state() == QProcess::Running) {
        doInput("quit\n", none);
        process->waitForFinished(1000);
        if (process->state() == QProcess::Running) { //if still running
            doInput("quit\n", none);
            process->terminate();
        }
    }
    delete process;
    process = 0;
    lines.clear();
    delete bufferTimer;
}

namespace {

    // read struct like {<name1> = <value1>, ,,, <nameN> = <valueN>}
    // from stream. Values may be simple or complex, like {v1, v2, v3 .. }
    // all vi have to be simple, two-level complex values unsupported
    //
    // test end of stream before any reading, desperately trying not to hang on it
    bool readStruct(QTextStream& str, QMap<QString, QString>* map) {
        str.skipWhiteSpace();
        if (str.atEnd())
            return false;

        QChar c;
        str >> c;
        if (c != '{')
            return false;

        // struct begin
        while (!str.atEnd()) {
            str.skipWhiteSpace();

            // may be it just empty
            str >> c;
            if (c == '}')
                return true;

            // read name, until space or '='
            QString name;
            name += c;

            for (;;) {
                if (str.atEnd())
                    return false;
                str >> c;
                if (c.isSpace() || (c == '=')) break;
                name += c;
            }

            // read '='
            if (c != '=') {
                str.skipWhiteSpace();

                if (str.atEnd())
                    return false;
                str >> c;
                if (c != '=') // it has to be assignment
                    return false;
            }

            str.skipWhiteSpace();

            // read value, simple (until space, or ',', or '}') or complex (until '}')
            QString value;

            if (str.atEnd())
                return false;
            str >> c;

            if (c != '{') {
                // simple value
                value += c;

                for (;;) {
                    if (str.atEnd())
                        return false;
                    str >> c;
                    if (c.isSpace() || (c == ',') || (c == '}')) break;
                    value += c;
                }
            } else {
                // complex value
                value += '{';

                for (;;) {
                    if (str.atEnd())
                        return false;
                    str >> c;
                    if (c == '}') break;
                    if (c.isSpace()) {
                        // replace all space characters by simple space
                        // and skip spaces after '{' and after space
                        if (!value.endsWith('{') && !value.endsWith(' '))
                            value += ' ';
                    } else {
                        value += c;
                    }
                }

                value += '}';
                c = ' '; // it was not last }, just end of value
            }

            (*map)[name] = value;

            // to next name-value pair
            if (c.isSpace()) {
                str.skipWhiteSpace();
                if (str.atEnd())
                    return false;
                str >> c;
            }

            if (c == '}')  // end of struct
                return true;
            if (c != ',')  // it has to be comma
                return false;

        }

        return false;
    }
}