aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/debugger/watchdata.cpp
blob: b5036f34ed247b7fb7a77489948e84a28c158810 (plain)
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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

// NOTE: Don't add dependencies to other files.
// This is used in the debugger auto-tests.

#include "watchdata.h"
#include "watchutils.h"
#include "debuggerprotocol.h"

#include <QDebug>

namespace Debugger {
namespace Internal {

bool isPointerType(const QString &type)
{
    return type.endsWith('*') || type.endsWith("* const");
}

bool isIntType(const QString &type)
{
    if (type.isEmpty())
        return false;
    switch (type.at(0).unicode()) {
        case 'b':
            return type == "bool";
        case 'c':
            return type.startsWith("char") &&
                    (  type == "char"
                    || type == "char8_t"
                    || type == "char16_t"
                    || type == "char32_t" );
        case 'i':
            return type.startsWith("int") &&
                    (  type == "int"
                    || type == "int8_t"
                    || type == "int16_t"
                    || type == "int32_t"
                    || type == "int64_t");
        case 'l':
            return type == "long"
                || type == "long int"
                || type == "long unsigned int";
        case 'p':
            return type == "ptrdiff_t";
        case 'q':
            return type == "qint8" || type == "quint8"
                || type == "qint16" || type == "quint16"
                || type == "qint32" || type == "quint32"
                || type == "qint64" || type == "quint64"
                || type == "qlonglong" || type == "qulonglong";
        case 's':
            return type == "short"
                || type == "signed"
                || type == "size_t"
                || type == "std::size_t"
                || type == "std::ptrdiff_t"
                || (type.startsWith("signed") &&
                    (  type == "signed char"
                    || type == "signed short"
                    || type == "signed short int"
                    || type == "signed long"
                    || type == "signed long int"
                    || type == "signed long long"
                    || type == "signed long long int"));
        case 'u':
            return type == "unsigned"
                || (type.startsWith("unsigned") &&
                    (  type == "unsigned char"
                    || type == "unsigned short"
                    || type == "unsigned short int"
                    || type == "unsigned int"
                    || type == "unsigned long"
                    || type == "unsigned long int"
                    || type == "unsigned long long"
                    || type == "unsigned long long int"))
                || (type.startsWith("uint") &&
                    (  type == "uint8_t"
                    || type == "uint16_t"
                    || type == "uint32_t"
                    || type == "uint64_t"));
        default:
            return false;
    }
}

bool isFloatType(const QString &type)
{
    return type == "float" || type == "double" || type == "qreal" || type == "number";
}

bool isIntOrFloatType(const QString &type)
{
    return isIntType(type) || isFloatType(type);
}

WatchItem::WatchItem() :
    id(WatchItem::InvalidId),
    address(0),
    origaddr(0),
    size(0),
    bitpos(0),
    bitsize(0),
    elided(0),
    arrayIndex(-1),
    sortGroup(0),
    wantsChildren(false),
    valueEnabled(true),
    valueEditable(true),
    autoDerefCount(0),
    outdated(false)
{
}

bool WatchItem::isVTablePointer() const
{
    // First case: Cdb only. No user type can be named like this, this is safe.
    // Second case: Python dumper only.
    return type.startsWith("__fptr()") || (type.isEmpty() && name == "[vptr]");
}

void WatchItem::setError(const QString &msg)
{
    value = msg;
    wantsChildren = false;
    valueEnabled = false;
    valueEditable = false;
}

void WatchItem::setValue(const QString &value0)
{
    value = value0;
    if (value == "{...}") {
        value.clear();
        wantsChildren = true; // at least one...
    }
}

QString WatchItem::toString() const
{
    const char *doubleQuoteComma = "\",";
    QString res;
    QTextStream str(&res);
    str << '{';
    if (!iname.isEmpty())
        str << "iname=\"" << iname << doubleQuoteComma;
    if (!name.isEmpty() && name != iname)
        str << "name=\"" << name << doubleQuoteComma;
    if (address) {
        str.setIntegerBase(16);
        str << "addr=\"0x" << address << doubleQuoteComma;
        str.setIntegerBase(10);
    }
    if (origaddr) {
        str.setIntegerBase(16);
        str << "referencingaddr=\"0x" << origaddr << doubleQuoteComma;
        str.setIntegerBase(10);
    }
    if (!exp.isEmpty())
        str << "exp=\"" << exp << doubleQuoteComma;

    if (!value.isEmpty())
        str << "value=\"" << value << doubleQuoteComma;

    if (elided)
        str << "valueelided=\"" << elided << doubleQuoteComma;

    if (!editvalue.isEmpty())
        str << "editvalue=\"<...>\",";

    str << "type=\"" << type << doubleQuoteComma;

    str << "wantsChildren=\"" << (wantsChildren ? "true" : "false") << doubleQuoteComma;

    str.flush();
    if (res.endsWith(','))
        res.truncate(res.size() - 1);
    return res + '}';
}

QString WatchItem::msgNotInScope()
{
    //: Value of variable in Debugger Locals display for variables out
    //: of scope (stopped above initialization).
    static const QString rc =
        QCoreApplication::translate("Debugger::Internal::WatchItem", "<not in scope>");
    return rc;
}

const QString &WatchItem::shadowedNameFormat()
{
    //: Display of variables shadowed by variables of the same name
    //: in nested scopes: Variable %1 is the variable name, %2 is a
    //: simple count.
    static const QString format =
        QCoreApplication::translate("Debugger::Internal::WatchItem", "%1 <shadowed %2>");
    return format;
}

QString WatchItem::shadowedName(const QString &name, int seen)
{
    if (seen <= 0)
        return name;
    return shadowedNameFormat().arg(name).arg(seen);
}

QString WatchItem::hexAddress() const
{
    if (address)
        return "0x" + QString::number(address, 16);
    return QString();
}

template <class T>
QString decodeItemHelper(const T &t)
{
    return QString::number(t);
}

QString decodeItemHelper(const double &t)
{
    return QString::number(t, 'g', 16);
}

class ArrayDataDecoder
{
public:
    template <class T>
    void decodeArrayHelper(int childSize)
    {
        const QByteArray ba = QByteArray::fromHex(rawData.toUtf8());
        const auto p = (const T*)ba.data();
        for (int i = 0, n = ba.size() / sizeof(T); i < n; ++i) {
            auto child = new WatchItem;
            child->arrayIndex = i;
            child->value = decodeItemHelper(p[i]);
            child->size = childSize;
            child->type = childType;
            child->address = addrbase + i * addrstep;
            child->valueEditable = true;
            item->appendChild(child);
        }
    }

    void decode()
    {
        if (addrstep == 0)
            addrstep = encoding.size;
        switch (encoding.type) {
            case DebuggerEncoding::HexEncodedSignedInteger:
                switch (encoding.size) {
                    case 1:
                        return decodeArrayHelper<signed char>(encoding.size);
                    case 2:
                        return decodeArrayHelper<short>(encoding.size);
                    case 4:
                        return decodeArrayHelper<int>(encoding.size);
                    case 8:
                        return decodeArrayHelper<qint64>(encoding.size);
                }
                break;
            case DebuggerEncoding::HexEncodedUnsignedInteger:
                switch (encoding.size) {
                    case 1:
                        return decodeArrayHelper<uchar>(encoding.size);
                    case 2:
                        return decodeArrayHelper<ushort>(encoding.size);
                    case 4:
                        return decodeArrayHelper<uint>(encoding.size);
                    case 8:
                        return decodeArrayHelper<quint64>(encoding.size);
                }
                break;
            case DebuggerEncoding::HexEncodedFloat:
                switch (encoding.size) {
                    case 4:
                        return decodeArrayHelper<float>(encoding.size);
                    case 8:
                        return decodeArrayHelper<double>(encoding.size);
                }
            default:
                break;
        }
        qDebug() << "ENCODING ERROR: " << encoding.toString();
    }

    WatchItem *item;
    QString rawData;
    QString childType;
    DebuggerEncoding encoding;
    quint64 addrbase;
    quint64 addrstep;
};

static bool sortByName(const WatchItem *a, const WatchItem *b)
{
    if (a->sortGroup != b->sortGroup)
        return a->sortGroup > b->sortGroup;

    return a->name < b->name;
}

void WatchItem::parseHelper(const GdbMi &input, bool maySort)
{
    GdbMi mi = input["type"];
    if (mi.isValid())
        type = mi.data();

    editvalue = input["editvalue"].data();
    editformat = input["editformat"].data();
    editencoding = DebuggerEncoding(input["editencoding"].data());

    // We need it for UVSC engine!
    mi = input["id"];
    if (mi.isValid())
        id = mi.toInt();

    mi = input["valueelided"];
    if (mi.isValid())
        elided = mi.toInt();

    mi = input["bitpos"];
    if (mi.isValid())
        bitpos = mi.toInt();

    mi = input["bitsize"];
    if (mi.isValid())
        bitsize = mi.toInt();

    mi = input["origaddr"];
    if (mi.isValid())
        origaddr = mi.toAddress();

    mi = input["address"];
    if (mi.isValid()) {
        address = mi.toAddress();
        if (exp.isEmpty()) {
            if (iname.startsWith("local.") && iname.count('.') == 1)
                // Solve one common case of adding 'class' in
                // *(class X*)0xdeadbeef for gdb.
                exp = name;
            else
                exp = "*(" + type + "*)" + hexAddress();
        }
    }

    mi = input["value"];
    QString enc = input["valueencoded"].data();
    if (mi.isValid() || !enc.isEmpty()) {
        setValue(decodeData(mi.data(), enc));
        mi = input["valuesuffix"];
        if (mi.isValid())
            value += mi.data();
    }

    mi = input["size"];
    if (mi.isValid())
        size = mi.toInt();

    mi = input["exp"];
    if (mi.isValid())
        exp = mi.data();

    mi = input["time"];
    if (mi.isValid())
        time = mi.data().toFloat();

    mi = input["sortgroup"];
    if (mi.isValid())
        sortGroup = mi.toInt();

    mi = input["valueenabled"];
    if (mi.data() == "true")
        valueEnabled = true;
    else if (mi.data() == "false")
        valueEnabled = false;

    mi = input["valueeditable"];
    if (mi.data() == "true")
        valueEditable = true;
    else if (mi.data() == "false")
        valueEditable = false;

    mi = input["autoderefcount"];
    if (mi.isValid()) {
        bool ok = false;
        uint derefCount = mi.data().toUInt(&ok);
        if (ok)
            autoDerefCount = derefCount;
    }

    mi = input["numchild"]; // GDB/MI
    if (mi.isValid())
        setHasChildren(mi.toInt() > 0);
    mi = input["haschild"]; // native-mixed
    if (mi.isValid())
        setHasChildren(mi.toInt() > 0);

    mi = input["arraydata"];
    if (mi.isValid()) {
        ArrayDataDecoder decoder;
        decoder.item = this;
        decoder.rawData = mi.data();
        decoder.childType = input["childtype"].data();
        decoder.addrbase = input["addrbase"].toAddress();
        decoder.addrstep = input["addrstep"].toAddress();
        decoder.encoding = DebuggerEncoding(input["arrayencoding"].data());
        decoder.decode();
    } else {
        const GdbMi children = input["children"];
        if (children.isValid()) {
            bool ok = false;
            // Try not to repeat data too often.
            const GdbMi childType = input["childtype"];
            const GdbMi childNumChild = input["childnumchild"];

            qulonglong addressBase = input["addrbase"].data().toULongLong(&ok, 0);
            qulonglong addressStep = input["addrstep"].data().toULongLong(&ok, 0);

            int i = -1;
            for (const GdbMi &subinput : children) {
                ++i;
                auto child = new WatchItem;
                if (childType.isValid())
                    child->type = childType.data();
                if (childNumChild.isValid())
                    child->setHasChildren(childNumChild.toInt() > 0);
                GdbMi name = subinput["name"];
                QString nn;
                if (name.isValid()) {
                    nn = name.data();
                    child->name = nn;
                } else {
                    nn.setNum(i);
                    child->name = QString("[%1]").arg(i);
                }
                GdbMi iname = subinput["iname"];
                if (iname.isValid())
                    child->iname = iname.data();
                else
                    child->iname = this->iname + '.' + nn;
                if (addressStep) {
                    child->address = addressBase + i * addressStep;
                    child->exp = "*(" + child->type + "*)0x"
                                      + QString::number(child->address, 16);
                }
                QString key = subinput["key"].data();
                if (!key.isEmpty())
                    child->name = decodeData(key, subinput["keyencoded"].data());
                child->name = subinput["keyprefix"].data() + child->name;
                child->parseHelper(subinput, maySort);
                appendChild(child);
            }

            if (maySort && input["sortable"].toInt())
                sortChildren(&sortByName);
        }
    }
}

void WatchItem::parse(const GdbMi &data, bool maySort)
{
    iname = data["iname"].data();

    GdbMi wname = data["wname"];
    if (wname.isValid()) // Happens (only) for watched expressions.
        name = fromHex(wname.data());
    else
        name = data["name"].data();

    parseHelper(data, maySort);

    if (wname.isValid())
        exp = name;

    time = data["time"].data().toFloat();
}

// Format a tooltip row with aligned colon.
static void formatToolTipRow(QTextStream &str, const QString &category, const QString &value)
{
    QString val = value.toHtmlEscaped();
    val.replace('\n', "<br>");
    str << "<tr><td>" << category << "</td><td>";
    if (!category.isEmpty())
        str << ':';
    str << "</td><td>" << val << "</td></tr>";
}

QString WatchItem::toToolTip() const
{
    QString res;
    QTextStream str(&res);
    str << "<html><body><table>";
    formatToolTipRow(str, tr("Name"), name);
    formatToolTipRow(str, tr("Expression"), expression());
    formatToolTipRow(str, tr("Internal Type"), type);
    bool ok;
    const quint64 intValue = value.toULongLong(&ok);
    if (ok && intValue) {
        formatToolTipRow(str, tr("Value"), "(dec)  " + value);
        formatToolTipRow(str, QString(), "(hex)  " + QString::number(intValue, 16));
        formatToolTipRow(str, QString(), "(oct)  " + QString::number(intValue, 8));
        formatToolTipRow(str, QString(), "(bin)  " + QString::number(intValue, 2));
    } else {
        QString val = value;
        if (val.size() > 1000) {
            val.truncate(1000);
            val += ' ';
            val += tr("... <cut off>");
        }
        formatToolTipRow(str, tr("Value"), val);
    }
    if (address)
        formatToolTipRow(str, tr("Object Address"), formatToolTipAddress(address));
    if (origaddr)
        formatToolTipRow(str, tr("Pointer Address"), formatToolTipAddress(origaddr));
    if (arrayIndex >= 0)
        formatToolTipRow(str, tr("Array Index"), QString::number(arrayIndex));
    if (size)
        formatToolTipRow(str, tr("Static Object Size"), tr("%n bytes", nullptr, size));
    formatToolTipRow(str, tr("Internal ID"), internalName());
    formatToolTipRow(str, tr("Creation Time in ms"), QString::number(int(time * 1000)));
    formatToolTipRow(str, tr("Source"), sourceExpression());
    str << "</table></body></html>";
    return res;
}

bool WatchItem::isLocal() const
{
    if (arrayIndex >= 0)
        if (const WatchItem *p = parent())
            return p->isLocal();
    return iname.startsWith("local.");
}

bool WatchItem::isWatcher() const
{
    if (arrayIndex >= 0)
        if (const WatchItem *p = parent())
            return p->isWatcher();
    return iname.startsWith("watch.");
}

bool WatchItem::isInspect() const
{
    if (arrayIndex >= 0)
        if (const WatchItem *p = parent())
            return p->isInspect();
    return iname.startsWith("inspect.");
}

QString WatchItem::internalName() const
{
    if (arrayIndex >= 0) {
        if (const WatchItem *p = parent())
            return p->iname + '.' + QString::number(arrayIndex);
    }
    return iname;
}

QString WatchItem::realName() const
{
    if (arrayIndex >= 0)
        return QString::fromLatin1("[%1]").arg(arrayIndex);
    return name;
}

QString WatchItem::expression() const
{
    if (!exp.isEmpty())
         return exp;
    if (quint64 addr = address) {
        if (!type.isEmpty())
            return QString("*(%1*)0x%2").arg(type).arg(addr, 0, 16);
    }
    const WatchItem *p = parent();
    if (p && !p->exp.isEmpty())
        return QString("(%1).%2").arg(p->exp, name);
    return name;
}

QString WatchItem::sourceExpression() const
{
    const WatchItem *p = parent();
    if (!p)
        return {}; // Root

    const WatchItem *pp = p->parent();
    if (!pp)
        return {}; // local

    const WatchItem *ppp = pp->parent();
    if (!ppp)
        return name; // local.x -> 'x'

    // Enforce some arbitrary, but fixed limit to avoid excessive creation
    // of very likely unused strings which are for convenience only.
    if (arrayIndex >= 0 && arrayIndex <= 16)
        return QString("%1[%2]").arg(p->sourceExpression()).arg(arrayIndex);

    if (p->name == '*')
        return QString("%1->%2").arg(pp->sourceExpression(), name);

    return QString("%1.%2").arg(p->sourceExpression(), name);
}

int WatchItem::guessSize() const
{
    if (size != 0)
        return size;
    if (type == "double")
        return 8;
    if (type == "float")
        return 4;
    if (type == "qfloat16")
        return 2;
    return 0;
}

} // namespace Internal
} // namespace Debugger