cdbsymbolgroupcontext.cpp 26.8 KB
Newer Older
1
2
3
4
5
6
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
26
** contact the sales department at http://www.qtsoftware.com/contact.
27
28
29
30
31
32
**
**************************************************************************/

#include "cdbsymbolgroupcontext.h"
#include "cdbdebugengine_p.h"
#include "watchhandler.h"
Friedemann Kleint's avatar
Friedemann Kleint committed
33
#include "watchutils.h"
hjk's avatar
hjk committed
34

Friedemann Kleint's avatar
Friedemann Kleint committed
35
#include <QtCore/QTextStream>
36
#include <QtCore/QCoreApplication>
37
#include <QtCore/QRegExp>
Friedemann Kleint's avatar
Friedemann Kleint committed
38

Friedemann Kleint's avatar
Friedemann Kleint committed
39
enum { debug = 0 };
40
enum { debugInternalDumpers = 0 };
Friedemann Kleint's avatar
Friedemann Kleint committed
41

42
43
44
45
static inline QString msgSymbolNotFound(const QString &s)
{
    return QString::fromLatin1("The symbol '%1' could not be found.").arg(s);
}
46

47
48
49
50
51
static inline QString msgOutOfScope()
{
    return QCoreApplication::translate("SymbolGroup", "Out of scope");
}

hjk's avatar
hjk committed
52
53
54
55
static inline bool isTopLevelSymbol(const DEBUG_SYMBOL_PARAMETERS &p)
{
    return p.ParentSymbol == DEBUG_ANY_ID;
}
56

Friedemann Kleint's avatar
Friedemann Kleint committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
static inline void debugSymbolFlags(unsigned long f, QTextStream &str)
{
    if (f & DEBUG_SYMBOL_EXPANDED)
        str << "DEBUG_SYMBOL_EXPANDED";
    if (f & DEBUG_SYMBOL_READ_ONLY)
        str << "|DEBUG_SYMBOL_READ_ONLY";
    if (f & DEBUG_SYMBOL_IS_ARRAY)
        str << "|DEBUG_SYMBOL_IS_ARRAY";
    if (f & DEBUG_SYMBOL_IS_FLOAT)
        str << "|DEBUG_SYMBOL_IS_FLOAT";
    if (f & DEBUG_SYMBOL_IS_ARGUMENT)
        str << "|DEBUG_SYMBOL_IS_ARGUMENT";
    if (f & DEBUG_SYMBOL_IS_LOCAL)
        str << "|DEBUG_SYMBOL_IS_LOCAL";
}

hjk's avatar
hjk committed
73
QTextStream &operator<<(QTextStream &str, const DEBUG_SYMBOL_PARAMETERS &p)
Friedemann Kleint's avatar
Friedemann Kleint committed
74
75
{
    str << " Type=" << p.TypeId << " parent=";
76
    if (isTopLevelSymbol(p)) {
Friedemann Kleint's avatar
Friedemann Kleint committed
77
78
        str << "<ROOT>";
    } else {
hjk's avatar
hjk committed
79
        str << p.ParentSymbol;
Friedemann Kleint's avatar
Friedemann Kleint committed
80
81
82
83
84
    }
    str << " Subs=" << p.SubElements << " flags=" << p.Flags << '/';
    debugSymbolFlags(p.Flags, str);
    return str;
}
85
86
87
88
89
90
91
92
93
94
95

// A helper function to extract a string value from a member function of
// IDebugSymbolGroup2 taking the symbol index and a character buffer.
// Pass in the the member function as '&IDebugSymbolGroup2::GetSymbolNameWide'

typedef HRESULT  (__stdcall IDebugSymbolGroup2::*WideStringRetrievalFunction)(ULONG, PWSTR, ULONG, PULONG);

static inline QString getSymbolString(IDebugSymbolGroup2 *sg,
                                      WideStringRetrievalFunction wsf,
                                      unsigned long index)
{
96
97
98
    // Template type names can get quite long....
    enum { BufSize = 1024 };
    static WCHAR nameBuffer[BufSize + 1];
99
100
    // Name
    ULONG nameLength;
101
    const HRESULT hr = (sg->*wsf)(index, nameBuffer, BufSize, &nameLength);
102
103
    if (SUCCEEDED(hr)) {
        nameBuffer[nameLength] = 0;
104
        return QString::fromUtf16(reinterpret_cast<const ushort *>(nameBuffer));
105
106
107
108
109
    }
    return QString();
}

namespace Debugger {
hjk's avatar
hjk committed
110
namespace Internal {
111

112
113
114
115
116
117
118
119
120
121

CdbSymbolGroupRecursionContext::CdbSymbolGroupRecursionContext(CdbSymbolGroupContext *ctx,
                                                         int ido,
                                                         CIDebugDataSpaces *ds) :
    context(ctx),
    internalDumperOwner(ido),
    dataspaces(ds)
{
}

122
123
124
125
126
127
128
129
130
static inline CdbSymbolGroupContext::SymbolState getSymbolState(const DEBUG_SYMBOL_PARAMETERS &p)
{
    if (p.SubElements == 0u)
        return CdbSymbolGroupContext::LeafSymbol;
    return (p.Flags & DEBUG_SYMBOL_EXPANDED) ?
               CdbSymbolGroupContext::ExpandedSymbol :
               CdbSymbolGroupContext::CollapsedSymbol;
}

131
CdbSymbolGroupContext::CdbSymbolGroupContext(const QString &prefix,
132
                                             CIDebugSymbolGroup *symbolGroup) :
133
134
    m_prefix(prefix),
    m_nameDelimiter(QLatin1Char('.')),
135
136
    m_symbolGroup(symbolGroup),
    m_unnamedSymbolNumber(1)
137
138
139
140
141
142
143
144
{
}

CdbSymbolGroupContext::~CdbSymbolGroupContext()
{
    m_symbolGroup->Release();
}

Friedemann Kleint's avatar
Friedemann Kleint committed
145
CdbSymbolGroupContext *CdbSymbolGroupContext::create(const QString &prefix,
146
                                                     CIDebugSymbolGroup *symbolGroup,
Friedemann Kleint's avatar
Friedemann Kleint committed
147
148
                                                     QString *errorMessage)
{
hjk's avatar
hjk committed
149
    CdbSymbolGroupContext *rc = new CdbSymbolGroupContext(prefix, symbolGroup);
Friedemann Kleint's avatar
Friedemann Kleint committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
    if (!rc->init(errorMessage)) {
        delete rc;
        return 0;
    }
    return rc;
}

bool CdbSymbolGroupContext::init(QString *errorMessage)
{
    // retrieve the root symbols
    ULONG count;
    HRESULT hr = m_symbolGroup->GetNumberSymbols(&count);
    if (FAILED(hr)) {
        *errorMessage = msgComFailed("GetNumberSymbols", hr);
        return false;
    }

167
168
169
    if (count) {
        m_symbolParameters.reserve(3u * count);
        m_symbolParameters.resize(count);
Friedemann Kleint's avatar
Friedemann Kleint committed
170

171
172
173
174
175
176
        hr = m_symbolGroup->GetSymbolParameters(0, count, symbolParameters());
        if (FAILED(hr)) {
            *errorMessage = QString::fromLatin1("In %1: %2 (%3 symbols)").arg(QLatin1String(Q_FUNC_INFO), msgComFailed("GetSymbolParameters", hr)).arg(count);
            return false;
        }
        populateINameIndexMap(m_prefix, DEBUG_ANY_ID, 0, count);
Friedemann Kleint's avatar
Friedemann Kleint committed
177
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
178
    if (debug)
179
        qDebug() << Q_FUNC_INFO << '\n'<< toString();
Friedemann Kleint's avatar
Friedemann Kleint committed
180
181
182
    return true;
}

183
184
void CdbSymbolGroupContext::populateINameIndexMap(const QString &prefix, unsigned long parentId,
                                                  unsigned long start, unsigned long count)
Friedemann Kleint's avatar
Friedemann Kleint committed
185
{
186
187
    // Make the entries for iname->index mapping. We might encounter
    // already expanded subitems when doing it for top-level, recurse in that case.
Friedemann Kleint's avatar
Friedemann Kleint committed
188
    const QString symbolPrefix = prefix + m_nameDelimiter;
Friedemann Kleint's avatar
Friedemann Kleint committed
189
    if (debug)
190
191
192
193
194
195
196
197
        qDebug() << Q_FUNC_INFO << '\n'<< symbolPrefix << start << count;
    const unsigned long end = m_symbolParameters.size();
    unsigned long seenChildren = 0;
    // Skip over expanded children
    for (unsigned long i = start; i < end && seenChildren < count; i++) {
        const DEBUG_SYMBOL_PARAMETERS &p = m_symbolParameters.at(i);
        if (parentId == p.ParentSymbol) {
            seenChildren++;
198
199
200
201
202
203
204
205
206
            // "__formal" occurs when someone writes "void foo(int /* x */)..."
            static const QString unnamedFormalParameter = QLatin1String("__formal");
            QString symbolName = getSymbolString(m_symbolGroup, &IDebugSymbolGroup2::GetSymbolNameWide, i);
            if (symbolName == unnamedFormalParameter) {
                symbolName = QLatin1String("<unnamed");
                symbolName += QString::number(m_unnamedSymbolNumber++);
                symbolName += QLatin1Char('>');
            }
            const QString name = symbolPrefix + symbolName;
207
208
209
210
            m_inameIndexMap.insert(name, i);
            if (getSymbolState(p) == ExpandedSymbol)
                populateINameIndexMap(name, i, i + 1, p.SubElements);
        }
Friedemann Kleint's avatar
Friedemann Kleint committed
211
212
213
    }
}

Friedemann Kleint's avatar
Friedemann Kleint committed
214
QString CdbSymbolGroupContext::toString(bool verbose) const
Friedemann Kleint's avatar
Friedemann Kleint committed
215
216
217
218
219
220
221
{
    QString rc;
    QTextStream str(&rc);
    const int count = m_symbolParameters.size();
    for (int i = 0; i < count; i++) {
        str << i << ' ';
        const DEBUG_SYMBOL_PARAMETERS &p = m_symbolParameters.at(i);
222
        if (!isTopLevelSymbol(p))
Friedemann Kleint's avatar
Friedemann Kleint committed
223
224
225
226
227
228
            str << "    ";
        str << getSymbolString(m_symbolGroup, &IDebugSymbolGroup2::GetSymbolNameWide, i);
        if (p.Flags & DEBUG_SYMBOL_IS_LOCAL)
            str << " '" << getSymbolString(m_symbolGroup, &IDebugSymbolGroup2::GetSymbolTypeNameWide, i);
        str << p << '\n';
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
229
230
231
232
233
234
    if (verbose) {
        str << "NameIndexMap\n";
        NameIndexMap::const_iterator ncend = m_inameIndexMap.constEnd();
        for (NameIndexMap::const_iterator it = m_inameIndexMap.constBegin() ; it != ncend; ++it)
            str << it.key() << ' ' << it.value() << '\n';
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
235
236
237
    return rc;
}

238
239
240
241
CdbSymbolGroupContext::SymbolState CdbSymbolGroupContext::symbolState(unsigned long index) const
{
    return getSymbolState(m_symbolParameters.at(index));
}
Friedemann Kleint's avatar
Friedemann Kleint committed
242

243
CdbSymbolGroupContext::SymbolState CdbSymbolGroupContext::symbolState(const QString &prefix) const
Friedemann Kleint's avatar
Friedemann Kleint committed
244
{
245
246
    if (prefix == m_prefix) // root
        return ExpandedSymbol;
Friedemann Kleint's avatar
Friedemann Kleint committed
247
248
    unsigned long index;
    if (!lookupPrefix(prefix, &index)) {
249
        qWarning("WARNING %s: %s\n", Q_FUNC_INFO, qPrintable(msgSymbolNotFound(prefix)));
Friedemann Kleint's avatar
Friedemann Kleint committed
250
251
252
253
254
255
256
257
258
        return LeafSymbol;
    }
    return symbolState(index);
}

// Find index of a prefix
bool CdbSymbolGroupContext::lookupPrefix(const QString &prefix, unsigned long *index) const
{
    *index = 0;
259
    const NameIndexMap::const_iterator it = m_inameIndexMap.constFind(prefix);
Friedemann Kleint's avatar
Friedemann Kleint committed
260
261
262
263
    if (it == m_inameIndexMap.constEnd())
        return false;
    *index = it.value();
    return true;
Friedemann Kleint's avatar
Friedemann Kleint committed
264
265
266
267
268
269
270
}

/* Retrieve children and get the position. */
bool CdbSymbolGroupContext::getChildSymbolsPosition(const QString &prefix,
                                                    unsigned long *start,
                                                    unsigned long *parentId,
                                                    QString *errorMessage)
271
{
Friedemann Kleint's avatar
Friedemann Kleint committed
272
    if (debug)
Friedemann Kleint's avatar
Friedemann Kleint committed
273
        qDebug() << Q_FUNC_INFO << '\n'<< prefix;
274

Friedemann Kleint's avatar
Friedemann Kleint committed
275
276
277
278
279
    *start = *parentId = 0;
    // Root item?
    if (prefix == m_prefix) {
        *start = 0;
        *parentId = DEBUG_ANY_ID;
Friedemann Kleint's avatar
Friedemann Kleint committed
280
        if (debug)
281
            qDebug() << '<' << prefix << "at" << *start;
Friedemann Kleint's avatar
Friedemann Kleint committed
282
283
284
285
286
287
288
        return true;
    }
    // Get parent index, make sure it is expanded
    NameIndexMap::const_iterator nit = m_inameIndexMap.constFind(prefix);
    if (nit == m_inameIndexMap.constEnd()) {
        *errorMessage = QString::fromLatin1("'%1' not found.").arg(prefix);
        return false;
289
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
290
291
292
293
    *parentId = nit.value();
    *start = nit.value() + 1;
    if (!expandSymbol(prefix, *parentId, errorMessage))
        return false;
Friedemann Kleint's avatar
Friedemann Kleint committed
294
    if (debug)
295
        qDebug() << '<' << prefix << "at" << *start;
Friedemann Kleint's avatar
Friedemann Kleint committed
296
    return true;
297
298
}

299
300
301
302
303
static inline QString msgExpandFailed(const QString &prefix, unsigned long index, const QString &why)
{
    return QString::fromLatin1("Unable to expand '%1' %2: %3").arg(prefix).arg(index).arg(why);
}

Friedemann Kleint's avatar
Friedemann Kleint committed
304
305
// Expand a symbol using the symbol group interface.
bool CdbSymbolGroupContext::expandSymbol(const QString &prefix, unsigned long index, QString *errorMessage)
306
{
Friedemann Kleint's avatar
Friedemann Kleint committed
307
    if (debug)
308
        qDebug() << '>' << Q_FUNC_INFO << '\n' << prefix << index;
309

310
311
312
313
314
    switch (symbolState(index)) {
    case LeafSymbol:
        *errorMessage = QString::fromLatin1("Attempt to expand leaf node '%1' %2!").arg(prefix).arg(index);
        return false;
    case ExpandedSymbol:
Friedemann Kleint's avatar
Friedemann Kleint committed
315
        return true;
316
317
318
    case CollapsedSymbol:
        break;
    }
319

Friedemann Kleint's avatar
Friedemann Kleint committed
320
321
    HRESULT hr = m_symbolGroup->ExpandSymbol(index, TRUE);
    if (FAILED(hr)) {
322
        *errorMessage = msgExpandFailed(prefix, index, msgComFailed("ExpandSymbol", hr));
Friedemann Kleint's avatar
Friedemann Kleint committed
323
324
325
326
327
328
329
        return false;
    }
    // Hopefully, this will never fail, else data structure will be foobar.
    const ULONG oldSize = m_symbolParameters.size();
    ULONG newSize;
    hr = m_symbolGroup->GetNumberSymbols(&newSize);
    if (FAILED(hr)) {
330
        *errorMessage = msgExpandFailed(prefix, index, msgComFailed("GetNumberSymbols", hr));
Friedemann Kleint's avatar
Friedemann Kleint committed
331
332
        return false;
    }
333

Friedemann Kleint's avatar
Friedemann Kleint committed
334
335
336
    // Retrieve the new parameter structs which will be inserted
    // after the parents, offsetting consecutive indexes.
    m_symbolParameters.resize(newSize);
337

Friedemann Kleint's avatar
Friedemann Kleint committed
338
339
    hr = m_symbolGroup->GetSymbolParameters(0, newSize, symbolParameters());
    if (FAILED(hr)) {
340
        *errorMessage = msgExpandFailed(prefix, index, msgComFailed("GetSymbolParameters", hr));
Friedemann Kleint's avatar
Friedemann Kleint committed
341
        return false;
342
    }
Friedemann Kleint's avatar
Friedemann Kleint committed
343
344
345
346
347
348
349
350
    // The new symbols are inserted after the parent symbol.
    // We need to correct the following values in the name->index map
    const unsigned long newSymbolCount = newSize - oldSize;
    const NameIndexMap::iterator nend = m_inameIndexMap.end();
    for (NameIndexMap::iterator it = m_inameIndexMap.begin(); it != nend; ++it)
        if (it.value() > index)
            it.value() += newSymbolCount;
    // insert the new symbols
351
    populateINameIndexMap(prefix, index, index + 1, newSymbolCount);
Friedemann Kleint's avatar
Friedemann Kleint committed
352
    if (debug > 1)
353
        qDebug() << '<' << Q_FUNC_INFO << '\n' << prefix << index << '\n' << toString();
Friedemann Kleint's avatar
Friedemann Kleint committed
354
    return true;
355
356
357
358
359
}

void CdbSymbolGroupContext::clear()
{
    m_symbolParameters.clear();
Friedemann Kleint's avatar
Friedemann Kleint committed
360
361
362
    m_inameIndexMap.clear();
}

363
QString CdbSymbolGroupContext::symbolINameAt(unsigned long index) const
364
{
365
366
    return m_inameIndexMap.key(index);
}
367

368
static inline QString hexSymbolOffset(CIDebugSymbolGroup *sg, unsigned long index)
369
370
371
372
373
374
375
{
    ULONG64 rc = 0;
    if (FAILED(sg->GetSymbolOffset(index, &rc)))
        rc = 0;
    return QLatin1String("0x") + QString::number(rc, 16);
}

376
377
378
379
380
381
382
383
384
385
386
387
388
389
// check for "0x000", "0x000 class X"
static inline bool isNullPointer(const WatchData &wd)
{
    if (!isPointerType(wd.type))
        return false;
    static const QRegExp hexNullPattern(QLatin1String("0x0+"));
    Q_ASSERT(hexNullPattern.isValid());
    const int blankPos = wd.value.indexOf(QLatin1Char(' '));
    if (blankPos == -1)
        return hexNullPattern.exactMatch(wd.value);
    const QString addr = wd.value.mid(0, blankPos);
    return hexNullPattern.exactMatch(addr);
}

390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// Fix a symbol group value. It is set to the class type for
// expandable classes (type="class std::foo<..>[*]",
// value="std::foo<...>[*]". This is not desired
// as it widens the value column for complex std::template types.
// Remove the inner template type.

static inline QString removeInnerTemplateType(QString value)
{
    const int firstBracketPos = value.indexOf(QLatin1Char('<'));
    const int lastBracketPos = firstBracketPos != -1 ? value.lastIndexOf(QLatin1Char('>')) : -1;
    if (lastBracketPos != -1)
        value.replace(firstBracketPos + 1, lastBracketPos - firstBracketPos -1, QLatin1String("..."));
    return value;
}

static inline QString fixValue(const QString &value)
{
    if (value.size() < 20 || value.endsWith(QLatin1Char('"')))
        return value;
    return removeInnerTemplateType(value);
}

412
413
WatchData CdbSymbolGroupContext::symbolAt(unsigned long index) const
{
414
    WatchData wd;
415
    wd.iname = symbolINameAt(index);
416
    wd.exp = wd.iname;
417
    const int lastDelimiterPos = wd.iname.lastIndexOf(m_nameDelimiter);
418
419
420
    // For class hierarchies, we get sometimes complicated std::template types here.
    // Remove them for display
    wd.name = removeInnerTemplateType(lastDelimiterPos == -1 ? wd.iname : wd.iname.mid(lastDelimiterPos + 1));
421
    wd.addr = hexSymbolOffset(m_symbolGroup, index);
422
423
424
425
    const QString type = getSymbolString(m_symbolGroup, &IDebugSymbolGroup2::GetSymbolTypeNameWide, index);
    const QString value = getSymbolString(m_symbolGroup, &IDebugSymbolGroup2::GetSymbolValueTextWide, index);
    wd.setType(type);
    wd.setValue(fixValue(value));
426
    wd.setChildrenNeeded(); // compensate side effects of above setters
Friedemann Kleint's avatar
Friedemann Kleint committed
427
428
    // Figure out children. The SubElement is only a guess unless the symbol,
    // is expanded, so, we leave this as a guess for later updates.
429
    // If the symbol has children (expanded or not), we leave the 'Children' flag
430
431
432
433
    // in 'needed' state. Suppress 0-pointers right ("0x000 class X")
    // here as they only lead to children with memory access errors.
    const bool hasChildren = m_symbolParameters.at(index).SubElements && !isNullPointer(wd);
    wd.setHasChildren(hasChildren);
Friedemann Kleint's avatar
Friedemann Kleint committed
434
    if (debug > 1)
435
        qDebug() << Q_FUNC_INFO << index << '\n' << wd.toString();
Friedemann Kleint's avatar
Friedemann Kleint committed
436
437
438
    return wd;
}

439
440
441
442
443
444
445
WatchData CdbSymbolGroupContext::dumpSymbolAt(CIDebugDataSpaces *ds, unsigned long index)
{
    WatchData rc = symbolAt(index);
    dump(ds, &rc);
    return rc;
}

446
447
448
449
450
451
452
453
454
455
456
bool CdbSymbolGroupContext::assignValue(const QString &iname, const QString &value,
                                        QString *newValue, QString *errorMessage)
{
    if (debugCDB)
        qDebug() << Q_FUNC_INFO << '\n' << iname << value;
    const NameIndexMap::const_iterator it = m_inameIndexMap.constFind(iname);
    if (it == m_inameIndexMap.constEnd()) {
        *errorMessage = msgSymbolNotFound(iname);
        return false;
    }
    const unsigned long  index = it.value();
457
    const HRESULT hr = m_symbolGroup->WriteSymbolWide(index, reinterpret_cast<PCWSTR>(value.utf16()));
458
459
460
461
462
463
464
465
466
467
    if (FAILED(hr)) {
        *errorMessage = QString::fromLatin1("Unable to assign '%1' to '%2': %3").
                        arg(value, iname, msgComFailed("WriteSymbolWide", hr));
        return false;
    }
    if (newValue)
        *newValue = getSymbolString(m_symbolGroup, &IDebugSymbolGroup2::GetSymbolValueTextWide, index);
    return true;
}

Friedemann Kleint's avatar
Friedemann Kleint committed
468
469
// format an array of integers as "0x323, 0x2322, ..."
template <class Integer>
470
static QString formatArrayHelper(const Integer *array, int size, int base = 10)
Friedemann Kleint's avatar
Friedemann Kleint committed
471
472
473
{
    QString rc;
    const QString hexPrefix = QLatin1String("0x");
hjk's avatar
hjk committed
474
    const QString separator = QLatin1String(", ");
475
    const bool hex = base == 16;
Friedemann Kleint's avatar
Friedemann Kleint committed
476
477
478
    for (int i = 0; i < size; i++) {
        if (i)
            rc += separator;
479
480
481
        if (hex)
            rc += hexPrefix;
        rc += QString::number(array[i], base);
Friedemann Kleint's avatar
Friedemann Kleint committed
482
483
484
485
486
487
    }
    return rc;
}

QString CdbSymbolGroupContext::hexFormatArray(const unsigned short *array, int size)
{
488
    return formatArrayHelper(array, size, 16);
Friedemann Kleint's avatar
Friedemann Kleint committed
489
490
}

491
492
493
494
495
496
497
498
499
500
501
502
// Helper to format an integer with
// a hex prefix in case base = 16
template <class Integer>
        inline QString formatInteger(Integer value, int base)
{
    QString rc;
    if (base == 16)
        rc = QLatin1String("0x");
    rc += QString::number(value, base);
    return rc;
}

503
QString CdbSymbolGroupContext::debugValueToString(const DEBUG_VALUE &dv, CIDebugControl *ctl,
504
505
                                                  QString *qType,
                                                  int integerBase)
Friedemann Kleint's avatar
Friedemann Kleint committed
506
507
508
{
    switch (dv.Type) {
    case DEBUG_VALUE_INT8:
509
510
511
        if (qType)
            *qType = QLatin1String("char");
        return formatInteger(dv.I8, integerBase);
Friedemann Kleint's avatar
Friedemann Kleint committed
512
    case DEBUG_VALUE_INT16:
513
514
515
        if (qType)
            *qType = QLatin1String("short");
        return formatInteger(static_cast<short>(dv.I16), integerBase);
Friedemann Kleint's avatar
Friedemann Kleint committed
516
    case DEBUG_VALUE_INT32:
517
518
519
        if (qType)
            *qType = QLatin1String("long");
        return formatInteger(static_cast<long>(dv.I32), integerBase);
Friedemann Kleint's avatar
Friedemann Kleint committed
520
    case DEBUG_VALUE_INT64:
521
522
523
        if (qType)
            *qType = QLatin1String("long long");
        return formatInteger(static_cast<long long>(dv.I64), integerBase);
Friedemann Kleint's avatar
Friedemann Kleint committed
524
    case DEBUG_VALUE_FLOAT32:
525
526
        if (qType)
            *qType = QLatin1String("float");
Friedemann Kleint's avatar
Friedemann Kleint committed
527
528
        return QString::number(dv.F32);
    case DEBUG_VALUE_FLOAT64:
529
530
        if (qType)
            *qType = QLatin1String("double");
Friedemann Kleint's avatar
Friedemann Kleint committed
531
532
533
534
535
536
537
        return QString::number(dv.F64);
    case DEBUG_VALUE_FLOAT80:
    case DEBUG_VALUE_FLOAT128: { // Convert to double
            DEBUG_VALUE doubleValue;
            double d = 0.0;
            if (SUCCEEDED(ctl->CoerceValue(const_cast<DEBUG_VALUE*>(&dv), DEBUG_VALUE_FLOAT64, &doubleValue)))
                d = dv.F64;
538
539
            if (qType)
                *qType = QLatin1String(dv.Type == DEBUG_VALUE_FLOAT80 ? "80bit-float" : "128bit-float");
Friedemann Kleint's avatar
Friedemann Kleint committed
540
541
542
            return QString::number(d);
        }
    case DEBUG_VALUE_VECTOR64: {
543
544
545
546
547
548
549
550
            if (qType)
                *qType = QLatin1String("64bit-vector");
            QString rc = QLatin1String("bytes: ");
            rc += formatArrayHelper(dv.VI8, 8, integerBase);
            rc += QLatin1String(" long: ");
            rc += formatArrayHelper(dv.VI32, 2, integerBase);
            return rc;
        }
Friedemann Kleint's avatar
Friedemann Kleint committed
551
    case DEBUG_VALUE_VECTOR128: {
552
553
554
555
556
557
558
559
            if (qType)
                *qType = QLatin1String("128bit-vector");
            QString rc = QLatin1String("bytes: ");
            rc += formatArrayHelper(dv.VI8, 16, integerBase);
            rc += QLatin1String(" long long: ");
            rc += formatArrayHelper(dv.VI64, 2, integerBase);
            return rc;
        }
Friedemann Kleint's avatar
Friedemann Kleint committed
560
    }
561
562
563
    if (qType)
        *qType = QString::fromLatin1("Unknown type #%1:").arg(dv.Type);
    return formatArrayHelper(dv.RawBytes, 24, integerBase);
Friedemann Kleint's avatar
Friedemann Kleint committed
564
565
}

566
bool CdbSymbolGroupContext::debugValueToInteger(const DEBUG_VALUE &dv, qint64 *value)
Friedemann Kleint's avatar
Friedemann Kleint committed
567
{
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
    *value = 0;
    switch (dv.Type) {
    case DEBUG_VALUE_INT8:
        *value = dv.I8;
        return true;
    case DEBUG_VALUE_INT16:
        *value = static_cast<short>(dv.I16);
        return true;
    case DEBUG_VALUE_INT32:
        *value = static_cast<long>(dv.I32);
        return true;
    case DEBUG_VALUE_INT64:
        *value = static_cast<long long>(dv.I64);
        return true;
    default:
        break;
Friedemann Kleint's avatar
Friedemann Kleint committed
584
    }
585
    return false;
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
/* The special type dumpers have an integer return code meaning:
 *  0:  ok
 *  1:  Dereferencing or retrieving memory failed, this is out of scope,
 *      do not try to query further.
 * > 1: A structural error was encountered, that is, the implementation
 *      of the class changed (Qt or say, a different STL implementation).
 *      Visibly warn about it.
 * To add further types, have a look at the toString() output of the
 * symbol group. */

static QString msgStructuralError(const QString &type, int code)
{
    return QString::fromLatin1("Warning: Internal dumper for '%1' failed with %2.").arg(type).arg(code);
}

static inline bool isStdStringOrPointer(const QString &type)
{
#define STD_WSTRING "std::basic_string<unsigned short,std::char_traits<unsigned short>,std::allocator<unsigned short> >"
#define STD_STRING "std::basic_string<char,std::char_traits<char>,std::allocator<char> >"
    return type.endsWith(QLatin1String(STD_STRING))
            || type.endsWith(QLatin1String(STD_STRING" *"))
            || type.endsWith(QLatin1String(STD_WSTRING))
            || type.endsWith(QLatin1String(STD_WSTRING" *"));
#undef STD_WSTRING
#undef STD_STRING
}

CdbSymbolGroupContext::DumperResult
        CdbSymbolGroupContext::dump(CIDebugDataSpaces *ds, WatchData *wd)
{
    DumperResult rc = DumperNotHandled;
    do {
        // Is this a previously detected Null-Pointer?
        if (wd->isHasChildrenKnown() && !wd->hasChildren)
            break;
        // QString
        if (wd->type.endsWith(QLatin1String("QString")) || wd->type.endsWith(QLatin1String("QString *"))) {
            const int drc = dumpQString(ds, wd);
            switch (drc) {
            case 0:
                rc = DumperOk;
                break;
            case 1:
                rc = DumperError;
                break;
            default:
                qWarning("%s\n", qPrintable(msgStructuralError(wd->type, drc)));
                rc = DumperNotHandled;
                break;
            }
        }
        // StdString
        if (isStdStringOrPointer(wd->type)) {
            const int drc = dumpStdString(wd);
            switch (drc) {
            case 0:
                rc = DumperOk;
                break;
            case 1:
                rc = DumperError;
                break;
            default:
                qWarning("%s\n", qPrintable(msgStructuralError(wd->type, drc)));
                rc = DumperNotHandled;
                break;
            }

        }
    } while (false);
    if (debugInternalDumpers)
        qDebug() << "CdbSymbolGroupContext::dump" << rc << wd->toString();
    return rc;
}

// Get integer value of symbol group
static inline bool getIntValue(CIDebugSymbolGroup *sg, int index, int *value)
{
    const QString valueS = getSymbolString(sg, &IDebugSymbolGroup2::GetSymbolValueTextWide, index);
    bool ok;
    *value = valueS.toInt(&ok);
    return ok;
}

// Get pointer value of symbol group ("0xAAB")
static inline bool getPointerValue(CIDebugSymbolGroup *sg, int index, quint64 *value)
{
    *value = 0;
    QString valueS = getSymbolString(sg, &IDebugSymbolGroup2::GetSymbolValueTextWide, index);
    if (!valueS.startsWith(QLatin1String("0x")))
        return false;
    valueS.remove(0, 2);
    bool ok;
    *value = valueS.toULongLong(&ok, 16);
    return ok;
}

int CdbSymbolGroupContext::dumpQString(CIDebugDataSpaces *ds, WatchData *wd)
{
    const int maxLength = 40;
    QString errorMessage;
    unsigned long stringIndex;
    if (!lookupPrefix(wd->iname, &stringIndex))
        return 1;

    // Expand string and it's "d" (step over 'static null')
    if (!expandSymbol(wd->iname, stringIndex, &errorMessage))
        return 2;
    const unsigned long dIndex = stringIndex + 4;
    if (!expandSymbol(wd->iname, dIndex, &errorMessage))
        return 3;
    const unsigned long sizeIndex = dIndex + 3;
    const unsigned long arrayIndex = dIndex + 4;
    // Get size and pointer
    int size;
    if (!getIntValue(m_symbolGroup, sizeIndex, &size))
        return 4;
    quint64 array;
    if (!getPointerValue(m_symbolGroup, arrayIndex, &array))
        return 5;
    // Fetch
    const bool truncated = size > maxLength;
    if (truncated)
        size = maxLength;
    const QChar doubleQuote = QLatin1Char('"');
    QString value(doubleQuote);
    if (size) {
        // Should this ever be a remote debugger, need to check byte order.
        unsigned short *buf =  new unsigned short[size + 1];
        unsigned long bytesRead;
        const HRESULT hr = ds->ReadVirtual(array, buf, size * sizeof(unsigned short), &bytesRead);
        if (FAILED(hr)) {
            delete [] buf;
            return 1;
        }
        buf[bytesRead / sizeof(unsigned short)] = 0;
        value += QString::fromUtf16(buf);
        delete [] buf;
        if (truncated)
            value += QLatin1String("...");
    }
    value += doubleQuote;
    wd->setValue(value);
    wd->setHasChildren(false);
    return 0;
}

int CdbSymbolGroupContext::dumpStdString(WatchData *wd)
{
    const int maxLength = 40;
    QString errorMessage;
    unsigned long stringIndex;
    if (!lookupPrefix(wd->iname, &stringIndex))
        return 1;

    // Expand string ->string_val->_bx.
    if (!expandSymbol(wd->iname, stringIndex, &errorMessage))
        return 1;
    const unsigned long bxIndex = stringIndex + 3;
    if (!expandSymbol(wd->iname, bxIndex, &errorMessage))
        return 2;
    // Check if size is something sane
    const int sizeIndex = stringIndex + 6;
    int size;
    if (!getIntValue(m_symbolGroup, sizeIndex, &size))
        return 3;
    if (size < 0)
        return 1;
    // Just copy over the value of the buf[]-array, which should be the string
    const QChar doubleQuote = QLatin1Char('"');
    const int bufIndex = stringIndex + 4;
    QString bufValue = getSymbolString(m_symbolGroup, &IDebugSymbolGroup2::GetSymbolValueTextWide, bufIndex);
    const int quotePos = bufValue.indexOf(doubleQuote);
    if (quotePos == -1)
        return 1;
    bufValue.remove(0, quotePos);
    if (bufValue.size() > maxLength) {
        bufValue.truncate(maxLength);
        bufValue += QLatin1String("...\"");
    }
    wd->setValue(bufValue);
    wd->setHasChildren(false);
    return 0;
}

hjk's avatar
hjk committed
772
773
} // namespace Internal
} // namespace Debugger