symbolgroupnode.cpp 68.2 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
Eike Ziller's avatar
Eike Ziller committed
3
4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8
9
10
11
** 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
Eike Ziller's avatar
Eike Ziller committed
12
13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
15
16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18
19
20
21
22
23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
hjk's avatar
hjk committed
24
**
Eike Ziller's avatar
Eike Ziller committed
25
26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
con's avatar
con committed
27
28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
30
31
32
33
34
35
36

#include "symbolgroupnode.h"
#include "symbolgroup.h"
#include "symbolgroupvalue.h"
#include "stringutils.h"
#include "base64.h"
#include "containers.h"
37
#include "extensioncontext.h"
38
39
40
41
42
43
44
45
46
47

#include <algorithm>

typedef std::vector<int>::size_type VectorIndexType;
typedef std::vector<std::string> StringVector;

enum { BufSize = 2048 };

static inline void indentStream(std::ostream &str, unsigned depth)
{
Friedemann Kleint's avatar
Friedemann Kleint committed
48
    for (unsigned d = 0; d < depth; ++d)
49
50
51
        str << "  ";
}

52
53
54
55
56
57
58
59
60
61
62
63
64
static inline void debugNodeFlags(std::ostream &str, unsigned f)
{
    if (!f)
        return;
    str << " node-flags=" << f;
    if (f & SymbolGroupNode::Uninitialized)
        str << " UNINITIALIZED";
    if (f & SymbolGroupNode::SimpleDumperNotApplicable)
        str << " DumperNotApplicable";
    if (f & SymbolGroupNode::SimpleDumperOk)
        str << " DumperOk";
    if (f & SymbolGroupNode::SimpleDumperFailed)
        str << " DumperFailed";
65
66
    if (f & SymbolGroupNode::ExpandedByRequest)
        str << " ExpandedByRequest";
67
68
69
70
71
72
    if (f & SymbolGroupNode::AdditionalSymbol)
        str << " AdditionalSymbol";
    if (f & SymbolGroupNode::Obscured)
        str << " Obscured";
    if (f & SymbolGroupNode::ComplexDumperOk)
        str << " ComplexDumperOk";
73
    if (f & SymbolGroupNode::WatchNode)
Friedemann Kleint's avatar
Friedemann Kleint committed
74
        str << " WatchNode";
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
    str << ' ';
}

// Some helper to conveniently dump flags to a stream
struct DebugNodeFlags
{
    DebugNodeFlags(unsigned f) : m_f(f) {}
    const unsigned m_f;
};

inline std::ostream &operator<<(std::ostream &str, const DebugNodeFlags &f)
{
    debugNodeFlags(str, f.m_f);
    return str;
}

91
92
/*!
  \class AbstractSymbolGroupNode
93

94
95
    \brief The AbstractSymbolGroupNode class is an abstract base class for a
    node of SymbolGroup providing the child list interface.
96
97
    \ingroup qtcreatorcdbext
*/
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
AbstractSymbolGroupNode::AbstractSymbolGroupNode(const std::string &name,
                                                 const std::string &iname) :
    m_name(name), m_iname(iname), m_parent(0), m_flags(0)
{
}

AbstractSymbolGroupNode::~AbstractSymbolGroupNode()
{
}

std::string AbstractSymbolGroupNode::absoluteFullIName() const
{
    std::string rc = iName();
    for (const AbstractSymbolGroupNode *p = m_parent; p; p = p->m_parent) {
        rc.insert(0, 1, SymbolGroupNodeVisitor::iNamePathSeparator);
        rc.insert(0, p->iName());
    }
    return rc;
}

AbstractSymbolGroupNode *AbstractSymbolGroupNode::childAt(unsigned i) const
{
    const AbstractSymbolGroupNodePtrVector &c = children();
    return i < c.size() ? c.at(i) : static_cast<AbstractSymbolGroupNode *>(0);
}

unsigned AbstractSymbolGroupNode::indexByIName(const char *n) const
{
    const AbstractSymbolGroupNodePtrVector &c = children();
    const VectorIndexType size = c.size();
Friedemann Kleint's avatar
Friedemann Kleint committed
128
    for (VectorIndexType i = 0; i < size; ++i)
129
130
131
132
133
134
135
136
137
138
139
140
141
        if ( c.at(i)->iName() == n )
            return unsigned(i);
    return unsigned(-1);
}

AbstractSymbolGroupNode *AbstractSymbolGroupNode::childByIName(const char *n) const
{
    const unsigned index = indexByIName(n);
    if (index != unsigned(-1))
        return children().at(index);
    return 0;
}

142
143
144
145
146
147
unsigned AbstractSymbolGroupNode::indexOf(const AbstractSymbolGroupNode *n) const
{
    const AbstractSymbolGroupNodePtrVector::const_iterator it = std::find(children().begin(), children().end(), n);
    return it != children().end() ? unsigned(it - children().begin()) : unsigned(-1);
}

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
bool AbstractSymbolGroupNode::accept(SymbolGroupNodeVisitor &visitor,
                                     const std::string &parentIname,
                                     unsigned child, unsigned depth)
{
    // If we happen to be the root node, just skip over
    const bool invisibleRoot = !m_parent;
    const unsigned childDepth = invisibleRoot ? 0 : depth + 1;

    std::string fullIname = parentIname;
    if (!fullIname.empty())
        fullIname.push_back(SymbolGroupNodeVisitor::iNamePathSeparator);
    fullIname += m_iname;

    const SymbolGroupNodeVisitor::VisitResult vr =
            invisibleRoot ? SymbolGroupNodeVisitor::VisitContinue :
                            visitor.visit(this, fullIname, child, depth);
    switch (vr) {
    case SymbolGroupNodeVisitor::VisitStop:
        return true;
    case SymbolGroupNodeVisitor::VisitSkipChildren:
        break;
    case SymbolGroupNodeVisitor::VisitContinue: {
170
        AbstractSymbolGroupNodePtrVector c = children();
171
        if (visitor.sortChildrenAlphabetically() && !testFlags(SymbolGroupNode::PreSortedChildren)) {
172
173
174
175
            std::sort(c.begin(), c.end(), [](AbstractSymbolGroupNode *a, AbstractSymbolGroupNode *b) {
                return a->name() < b->name();
            });
        }
176
        const unsigned childCount = unsigned(c.size());
Friedemann Kleint's avatar
Friedemann Kleint committed
177
        for (unsigned i = 0; i < childCount; ++i)
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
            if (c.at(i)->accept(visitor, fullIname, i, childDepth))
                return true;
        if (!invisibleRoot)
            visitor.childrenVisited(this, depth);
    }
        break;
    }
    return false;
}

void AbstractSymbolGroupNode::debug(std::ostream &str, const std::string &visitingFullIname,
                                    unsigned /* verbosity */, unsigned depth) const
{
    indentStream(str, 2 * depth);
    str << "AbstractSymbolGroupNode " << visitingFullIname
        << " with " << children().size() << " children\n";
}

void AbstractSymbolGroupNode::dumpBasicData(std::ostream &str, const std::string &aName,
                                         const std::string &aFullIname,
                                         const std::string &type /* = "" */,
                                         const std::string &expression /* = "" */)
{
    str << "iname=\"" << aFullIname << "\",name=\"" << aName << '"';
    if (!type.empty())
        str << ",type=\"" << type << '"';
204
205
206
207
    if (WatchesSymbolGroup::isWatchIname(aFullIname))
        str << ",exp=\"" << aName << '"';
    else if (!expression.empty())
        str << ",exp=\"" << expression << '"';
208
209
210
211
212
213
214
215
216
}

void AbstractSymbolGroupNode::setParent(AbstractSymbolGroupNode *n)
{
    if (m_parent)
        dprintf("Internal error: Attempt to change non-null parent of %s", m_name.c_str());
    m_parent = n;
}

217
218
/*! \class BaseSymbolGroupNode

219
220
    \brief The BaseSymbolGroupNode class is the base class for a node of
    SymbolGroup with a flat list of children.
221
222
223
    \ingroup qtcreatorcdbext
*/

224
225
226
227
228
229
230
231
232
233
BaseSymbolGroupNode::BaseSymbolGroupNode(const std::string &name, const std::string &iname) :
    AbstractSymbolGroupNode(name, iname)
{
}

BaseSymbolGroupNode::~BaseSymbolGroupNode()
{
    removeChildren();
}

234
235
236
237
238
239
240
241
242
void BaseSymbolGroupNode::removeChildAt(unsigned n)
{
    if (VectorIndexType(n) >= m_children.size())
        return;
    const AbstractSymbolGroupNodePtrVector::iterator it = m_children.begin() + n;
    delete *it;
    m_children.erase(it, it + 1);
}

243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
void BaseSymbolGroupNode::removeChildren()
{
    if (!m_children.empty()) {
        const AbstractSymbolGroupNodePtrVectorIterator end = m_children.end();
        for (AbstractSymbolGroupNodePtrVectorIterator it = m_children.begin(); it != end; ++it)
            delete *it;
        m_children.clear();
    }
}

void BaseSymbolGroupNode::addChild(AbstractSymbolGroupNode *c)
{
    c->setParent(this);
    m_children.push_back(c);
}

// ----------- Helpers: Stream DEBUG_SYMBOL_PARAMETERS

std::ostream &operator<<(std::ostream &str, const DEBUG_SYMBOL_PARAMETERS &parameters)
{
    str << "parent=";
264
    if (parameters.ParentSymbol == DEBUG_ANY_ID)
265
        str << "DEBUG_ANY_ID";
266
    else
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
        str << parameters.ParentSymbol ;
    if (parameters.Flags != 0 && parameters.Flags != 1)
        str << " flags=" << parameters.Flags;
    // Detailed flags:
    if (parameters.Flags & DEBUG_SYMBOL_EXPANDED)
        str << " EXPANDED";
    if (parameters.Flags & DEBUG_SYMBOL_READ_ONLY)
        str << " READONLY";
    if (parameters.Flags & DEBUG_SYMBOL_IS_ARRAY)
        str << " ARRAY";
    if (parameters.Flags & DEBUG_SYMBOL_IS_FLOAT)
        str << " FLOAT";
    if (parameters.Flags & DEBUG_SYMBOL_IS_ARGUMENT)
        str << " ARGUMENT";
    if (parameters.Flags & DEBUG_SYMBOL_IS_LOCAL)
        str << " LOCAL";
    str << " typeId=" << parameters.TypeId;
    if (parameters.SubElements)
        str << " subElements=" << parameters.SubElements;
    return str;
}

289
290
/*!
    \class DumpParameters
291

292
293
    \brief The DumpParameters class contains all parameters for GDBMI dumping
    of a symbol group in one class.
294
295
296
297
298
    The debugging engine passes maps of type names/inames to special
    integer values indicating hex/dec, etc.
    \ingroup qtcreatorcdbext
*/

299
300
301
302
303
304
DumpParameters::DumpParameters() : dumpFlags(0)
{
}

// typeformats: decode hex-encoded name, value pairs:
// '414A=2,...' -> map of "AB:2".
305
306
DumpParameters::FormatMap DumpParameters::decodeFormatArgument(const std::string &f,
                                                               bool isHex)
307
{
308
309
310
311
    extern const char *stdStringTypeC;
    extern const char *stdWStringTypeC;
    extern const char *stdWStringWCharTypeC;

312
313
314
315
316
317
318
319
    FormatMap rc;
    const std::string::size_type size = f.size();
    // Split 'hexname=4,'
    for (std::string::size_type pos = 0; pos < size ; ) {
        // Cut out key
        const std::string::size_type equalsPos = f.find('=', pos);
        if (equalsPos == std::string::npos)
            return rc;
320
321
322
        const std::string name = isHex ?
          stringFromHex(f.c_str() + pos, f.c_str() + equalsPos) :
          f.substr(pos, equalsPos - pos);
323
324
325
326
327
328
329
330
        // Search for number
        const std::string::size_type numberPos = equalsPos + 1;
        std::string::size_type nextPos = f.find(',', numberPos);
        if (nextPos == std::string::npos)
            nextPos = size;
        int format;
        if (!integerFromString(f.substr(numberPos, nextPos - numberPos), &format))
            return rc;
331
332
333
334
335
336
337
        if (name == "std::basic_string") {  // Python dumper naming convention for types
            rc.insert(FormatMap::value_type(stdStringTypeC, format));
            rc.insert(FormatMap::value_type(stdWStringTypeC, format));
            rc.insert(FormatMap::value_type(stdWStringWCharTypeC, format));
        } else {
            rc.insert(FormatMap::value_type(name, format));
        }
338
339
340
341
342
343
344
345
346
347
348
349
350
        pos = nextPos + 1;
    }
    return rc;
}

int DumpParameters::format(const std::string &type, const std::string &iname) const
{
    if (!individualFormats.empty()) {
        const FormatMap::const_iterator iit = individualFormats.find(iname);
        if (iit != individualFormats.end())
            return iit->second;
    }
    if (!typeFormats.empty()) {
351
352
353
354
355
356
        // Strip 'struct' / 'class' prefixes and pointer types
        // when called with a raw cdb types.
        std::string stripped = SymbolGroupValue::stripClassPrefixes(type);
        if (stripped != type)
            stripped = SymbolGroupValue::stripPointerType(stripped);
        const FormatMap::const_iterator tit = typeFormats.find(stripped);
357
358
359
360
361
362
        if (tit != typeFormats.end())
            return tit->second;
    }
    return -1;
}

hjk's avatar
hjk committed
363
364
365
// Watch data pointer format requests. This should match the values
// in DisplayFormat in watchhandler.h.
enum PointerFormats
366
367
{
    FormatAuto = 0,
hjk's avatar
hjk committed
368
369
370
371
    FormatLatin1String = 101,
    FormatUtf8String = 102,
    FormatUtf16String = 104,
    FormatUcs4String = 105
372
373
374
};

/* Recode arrays/pointers of char*, wchar_t according to users
375
376
377
378
379
 * specification. Handles char formats for 'char *', '0x834478 "hallo.."'
 * and 'wchar_t *', '0x834478 "hallo.."', 'wchar_t[56] "hallo"', etc.
 * This is done by retrieving the address (from the pointer value for
 * pointers, using passed in-address for arrays) and the length
 * (in characters excluding \0)
380
 * of the CDB output, converting it to memory size, fetching the data
381
 * from memory, and recoding it using the encoding
382
383
 * defined in watchutils.cpp.
 * As a special case, if there is no user-defined format and the
384
385
386
387
388
389
390
391
392
393
394
 * CDB output contains '?'/'.' (CDB version?)  indicating non-printable
 * characters, switch to a suitable type such that the watchmodel
 * formatting options trigger.
 * This is split into a check step that returns a struct containing
 * an allocated buffer with the raw data/size and recommended format
 * (or 0 if recoding is not applicable) and the actual recoding step.
 * Step 1) is used by std::string dumpers to potentially reformat
 * the arrays. */

DumpParameterRecodeResult
DumpParameters::checkRecode(const std::string &type,
395
                            const std::string &iname,
396
                            const std::wstring &value,
397
                            const SymbolGroupValueContext &ctx,
398
399
                            ULONG64 address,
                            const DumpParameters *dp /* =0 */)
400
{
401
402
403
    enum ReformatType { ReformatNone, ReformatPointer, ReformatArray };

    DumpParameterRecodeResult result;
404
405
    if (SymbolGroupValue::verbose > 2) {
        DebugPrint debugPrint;
406
        debugPrint << '>' << __FUNCTION__ << ' ' << iname << '/' << type;
407
408
409
        if (dp)
            debugPrint << " option format: " << dp->format(type, iname);
    }
410
411
412
413
    // We basically handle char formats for 'char *', '0x834478 "hallo.."'
    // and 'wchar_t *', '0x834478 "hallo.."'
    // Determine address and length from the pointer value output,
    // read the raw memory and recode if that is possible.
414
415
416
417
418
419
420
421
422
    if (type.empty() || value.empty())
        return result;
    const std::wstring::size_type quote2 = value.size() - 1;
    if (value.at(quote2) != L'"')
        return result;
    ReformatType reformatType = ReformatNone;
    switch (type.at(type.size() - 1)) {
    case '*':
        reformatType = ReformatPointer;
Orgad Shaneh's avatar
Orgad Shaneh committed
423
        if (value.compare(0, 2, L"0x") != 0)
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
            return result;
        break;
    case ']':
        reformatType = ReformatArray;
        break;
    default:
        return result;
    }
    // Check for a reformattable type (do not trigger for a 'std::string *').
    if (type.compare(0, 4, "char") == 0
        || type.compare(0, 13, "unsigned char") == 0) {
    } else if (type.compare(0, 7, "wchar_t", 0, 7) == 0
               || type.compare(0, 14, "unsigned short") == 0) {
        result.isWide = true;
    } else {
        return result;
    }
    // Empty string?
    const std::wstring::size_type quote1 = value.find(L'"', 2);
    if (quote1 == std::wstring::npos || quote2 == quote1)
        return result;
    const std::wstring::size_type length = quote2 - quote1 - 1;
    if (!length)
        return result;
    // Choose format
    result.recommendedFormat = dp ? dp->format(type, iname) : FormatAuto;
    // The user did not specify any format, still, there are '?'/'.'
    // (indicating non-printable) in what the debugger prints.
    // Reformat in this case. If there are no '?'-> all happy.
    if (result.recommendedFormat < FormatLatin1String) {
        const bool hasNonPrintable = value.find(L'?', quote1 + 1) != std::wstring::npos
                || value.find(L'.', quote1 + 1) != std::wstring::npos;
456
        if (!hasNonPrintable)
457
            return result; // All happy, no need to re-encode
458
        // Pass as on 8-bit such that Watchmodel's reformatting can trigger.
459
460
        result.recommendedFormat = result.isWide ?
            FormatUtf16String : FormatLatin1String;
461
    }
462
463
464
465
466
467
468
469
470
471
472
473
    // Get address from value if it is a pointer.
    if (reformatType == ReformatPointer) {
        address = 0;
        if (!integerFromWString(value.substr(0, quote1 - 1), &address) || !address)
            return result;
    }
    // Get real size (excluding 0) if this is for example a wchar_t *.
    // Make fit to 2/4 character boundaries.
    const std::string elementType = reformatType == ReformatPointer ?
        SymbolGroupValue::stripPointerType(type) :
        SymbolGroupValue::stripArrayType(type);
    const unsigned elementSize = SymbolGroupValue::sizeOf(elementType.c_str());
474
    if (!elementSize)
475
476
477
478
479
480
481
482
483
484
485
486
487
488
        return result;
    result.size = length * elementSize;
    switch (result.recommendedFormat) {
    case FormatUtf16String: // Paranoia: make sure buffer is terminated at 2 byte borders
        if (result.size % 2)
            result.size &= ~1;
        break;
    case FormatUcs4String: // Paranoia: make sure buffer is terminated at 4 byte borders
        if (result.size % 4)
            result.size &= ~3;
        break;
    }
    result.buffer = new unsigned char[result.size];
    std::fill(result.buffer, result.buffer + result.size, 0);
489
    ULONG obtained = 0;
490
491
    if (FAILED(ctx.dataspaces->ReadVirtual(address, result.buffer, ULONG(result.size), &obtained))) {
        delete [] result.buffer;
492
493
494
        DebugPrint() << __FUNCTION__ << " ReadVirtual() failed to read "
                     << result.size << " bytes from 0x" << std::hex
                     << address << std::dec << " for " << iname << '.';
495
        result = DumpParameterRecodeResult();
496
    }
497
498
499
500
501
    if (SymbolGroupValue::verbose > 2)
        DebugPrint()
            << '<' << __FUNCTION__ << ' ' << iname << " format="
            << result.recommendedFormat << " size="
            << result.size << " data=" << dumpMemory(result.buffer, result.size);
502
503
504
505
506
507
508
509
510
511
512
513
514
    return result;
}

bool DumpParameters::recode(const std::string &type,
                            const std::string &iname,
                            const SymbolGroupValueContext &ctx,
                            ULONG64 address,
                            std::wstring *value, int *encoding) const
{
    const DumpParameterRecodeResult check
        = checkRecode(type, iname, *value, ctx, address, this);
    if (!check.buffer)
        return false;
515
    // Recode raw memory
516
    switch (check.recommendedFormat) {
517
    case FormatLatin1String:
518
519
        *value = dataToHexW(check.buffer, check.buffer + check.size); // Latin1 + 0
        *encoding = DumpEncodingHex_Latin1_WithQuotes;
520
521
        break;
    case FormatUtf8String:
522
523
        *value = dataToHexW(check.buffer, check.buffer + check.size); // UTF8 + 0
        *encoding = DumpEncodingHex_Utf8_LittleEndian_WithQuotes;
524
525
        break;
    case FormatUtf16String: // Paranoia: make sure buffer is terminated at 2 byte borders
526
527
        *value = base64EncodeToWString(check.buffer, check.size);
        *encoding = DumpEncodingBase64_Utf16_WithQuotes;
528
529
        break;
    case FormatUcs4String: // Paranoia: make sure buffer is terminated at 4 byte borders
530
531
        *value = dataToHexW(check.buffer, check.buffer + check.size); // UTF16 + 0
        *encoding = DumpEncodingHex_Ucs4_LittleEndian_WithQuotes;
532
533
        break;
    }
534
    delete [] check.buffer;
535
536
537
    return true;
}

538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
std::ostream &operator<<(std::ostream &os, const DumpParameters &d)
{
    if (d.dumpFlags & DumpParameters::DumpHumanReadable)
        os << ", human-readable";
    if (d.dumpFlags & DumpParameters::DumpComplexDumpers)
        os << ", complex dumpers";
    if (!d.typeFormats.empty()) {
        os << ", type formats: ";
        DumpParameters::FormatMap::const_iterator cend = d.typeFormats.end();
        for (DumpParameters::FormatMap::const_iterator it = d.typeFormats.begin(); it != cend; ++it)
            os << ' ' << it->first << ':' << it->second;
        os << '\n';
    }
    if (!d.individualFormats.empty()) {
        os << ", individual formats: ";
        DumpParameters::FormatMap::const_iterator cend = d.individualFormats.end();
554
        for (DumpParameters::FormatMap::const_iterator it = d.individualFormats.begin(); it != cend; ++it)
555
556
557
558
559
560
            os << ' ' << it->first << ':' << it->second;
        os << '\n';
    }
    return os;
}

561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
// --------- ErrorSymbolGroupNode
ErrorSymbolGroupNode::ErrorSymbolGroupNode(const std::string &name, const std::string &iname) :
    BaseSymbolGroupNode(name, iname)
{
}

int ErrorSymbolGroupNode::dump(std::ostream &str, const std::string &fullIname,
                               const DumpParameters &, const SymbolGroupValueContext &)
{
    dumpBasicData(str, name(), fullIname, "<unknown>", std::string());
    str << ",valueencoded=\"0\",value=\"<Error>\",valueenabled=\"false\",valueeditable=\"false\"";
    return 0;
}

void ErrorSymbolGroupNode::debug(std::ostream &os, const std::string &visitingFullIname,
                                 unsigned , unsigned depth) const
{
    indentStream(os, 2 * depth);
    os << "ErrorSymbolGroupNode '" << name() << "','" << iName() << "', '" << visitingFullIname << "'\n";
}

582
583
/*! \class SymbolGroupNode

584
585
 \brief The SymbolGroupNode class represents a \e real node within a symbol
 group, identified by its index in IDebugSymbolGroup.
586
587
588
589

 Provides accessors for fixed-up symbol group value and a dumping facility
 consisting of:
 \list
590
 \li 'Simple' dumping done when running the DumpVisitor. This produces one
591
592
593
594
    line of formatted output shown for the class. These values
    values are always displayed, while still allowing for expansion of the structure
    in the debugger.
    It also pre-determines some information for complex dumping (type, container).
595
 \li 'Complex' dumping: Obscures the symbol group children by fake children, for
596
597
598
599
600
601
    example container children, to be run when calling SymbolGroup::dump with an iname.
    The fake children are appended to the child list (other children are just marked as
    obscured for GDBMI dumping so that SymbolGroupValue expressions still work as before).
 \endlist

 The dumping is mostly based on SymbolGroupValue expressions.
602
603
 in the debugger. Evaluating those dumpers might expand symbol nodes, but those
 are not marked as 'ExpandedByRequest'. This stops the dump recursion to prevent
604
605
 outputting data that were not explicitly expanded by the watch handler.
 \ingroup qtcreatorcdbext */
606
607
608

SymbolGroupNode::SymbolGroupNode(SymbolGroup *symbolGroup,
                                 ULONG index,
609
                                 const std::string &module,
610
                                 const std::string &name,
611
612
613
614
615
                                 const std::string &iname)
    : BaseSymbolGroupNode(name, iname)
    , m_symbolGroup(symbolGroup)
    , m_module(module)
    , m_index(index)
616
    , m_dumperValueEncoding(0)
617
618
619
620
    , m_dumperType(-1)
    , m_dumperContainerSize(-1)
    , m_dumperSpecialInfo(0)
    , m_memory(0)
621
622
623
624
625
{
    memset(&m_parameters, 0, sizeof(DEBUG_SYMBOL_PARAMETERS));
    m_parameters.ParentSymbol = DEBUG_ANY_ID;
}

626
627
628
629
630
SymbolGroupNode::~SymbolGroupNode()
{
    delete m_memory;
}

631
632
633
634
635
636
637
const SymbolGroupNode *SymbolGroupNode::symbolGroupNodeParent() const
{
    if (const AbstractSymbolGroupNode *p = parent())
        return p->asSymbolGroupNode();
    return 0;
}

638
639
640
641
642
643
644
SymbolGroupNode *SymbolGroupNode::symbolGroupNodeParent()
{
    if (AbstractSymbolGroupNode *p = parent())
        return p->asSymbolGroupNode();
    return 0;
}

645
646
647
648
649
650
651
652
653
654
655
bool SymbolGroupNode::isArrayElement() const
{
    if (const SymbolGroupNode *p = symbolGroupNodeParent())
        return (p->m_parameters.Flags & DEBUG_SYMBOL_IS_ARRAY) != 0;
    return false;
}

// Notify about expansion of a node:
// Adapt our index and those of our children if we are behind it.
// Return true if a modification was required to be able to terminate the
// recursion.
656
bool SymbolGroupNode::notifyIndexesMoved(ULONG index, bool inserted, ULONG offset)
657
658
{
    typedef AbstractSymbolGroupNodePtrVector::const_reverse_iterator ReverseIt;
659
660
661
662
663

    if (SymbolGroupValue::verbose > 2)
        DebugPrint() << "notifyIndexesMoved: #" << this->index() << " '" << name()
                     << "' index=" << index << " insert="
                     << inserted << " offset=" << offset;
664
665
666
667
668
    // Looping backwards over the children. If a subtree has no modifications,
    // (meaning all other indexes are smaller) we can stop.
    const ReverseIt rend = children().rend();
    for (ReverseIt it = children().rbegin(); it != rend; ++it) {
        if (SymbolGroupNode *c = (*it)->asSymbolGroupNode())
669
            if (!c->notifyIndexesMoved(index, inserted, offset))
670
671
672
673
674
675
676
                return false;
    }

    // Correct our own + parent index if applicable.
    if (m_index == DEBUG_ANY_ID || m_index < index)
        return false;

677
    if (inserted)
678
        m_index += offset;
679
    else
680
681
        m_index -= offset;
    if (m_parameters.ParentSymbol != DEBUG_ANY_ID && m_parameters.ParentSymbol >= index) {
682
        if (inserted)
683
            m_parameters.ParentSymbol += offset;
684
        else
685
686
            m_parameters.ParentSymbol -= offset;
    }
687
688
689
    return true;
}

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
static inline void fixNameAndIname(unsigned &unnamedId, unsigned &templateId,
                                   std::string &iname, std::string &name)
{
    if (name.empty() || name == "__formal") {
        const std::string number = toString(unnamedId++);
        name = "<unnamed "  + number + '>';
        iname = "unnamed#" + number;
    } else {
        // Fix names: fix complicated template base names
        // Long template base classes 'std::tree_base<Key....>' -> 'std::tree<>'
        // for nice display
        std::string::size_type templatePos = name.find('<');
        if (templatePos != std::string::npos) {
            name.erase(templatePos + 1, name.size() - templatePos - 1);
            name.push_back('>');
        }

        // Fix array iname "[0]" -> "0" for sorting to work correctly
        if (!iname.empty() && iname.at(0) == '[') {
            const std::string::size_type last = iname.size() - 1;
            if (iname.at(last) == ']') {
                iname.erase(last, 1);
                iname.erase(0, 1);
                return;
            }
        }
        // Fix inames: arrays and long, complicated template base names
        // Long template base classes 'std::tree_base<Key....' -> 'tree@t1',
        // usable as identifier and command line parameter
        templatePos = iname.find('<');
        if (templatePos != std::string::npos) {
            iname.erase(templatePos, iname.size() - templatePos);
            if (iname.compare(0, 5, "std::") == 0)
                iname.erase(0, 5);
            iname.append("@t");
            iname.append(toString(templateId++));
        }
727
728
729
    }
}

730
731
static inline void addShadowCount(const StringVector::size_type count,
                                  std::string &iname, std::string &name)
732
{
733
734
735
736
737
738
    const std::string number = toString(count);
    name += " <shadowed ";
    name += number;
    name += '>';
    iname += '#';
    iname += number;
739
740
741
742
743
744
745
746
747
748
749
750
751
752
}

// Fix up names and inames
static inline void fixNames(bool isTopLevel, StringVector *names, StringVector *inames)
{
    if (names->empty())
        return;
    unsigned unnamedId = 1;
    unsigned templateId = 1;
    /* 1) Fix name="__formal", which occurs when someone writes "void foo(int /* x * /)..."
     * 2) Fix array inames for sorting: "[6]" -> name="[6]",iname="6"
     * 3) For toplevels: Fix shadowed variables in the order the debugger expects them:
       \code
       int x;             // Occurrence (1), should be reported as name="x <shadowed 1>"/iname="x#1"
753
       if (true)
754
755
          int x = 5; (2)  // Occurrence (2), should be reported as name="x"/iname="x"
      \endcode */
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770

    const ExtensionContext::CdbVersion cdbVersion = ExtensionContext::instance().cdbVersion();
    const bool reverseOrder = cdbVersion.major == 6 && cdbVersion.minor < 10;
    if (reverseOrder) {
        StringVector::reverse_iterator nameIt = names->rbegin();
        const StringVector::reverse_iterator namesEnd = names->rend();
        StringVector::reverse_iterator iNameIt = inames->rbegin();
        for (; nameIt != namesEnd ; ++nameIt, ++iNameIt) {
            std::string &name = *nameIt;
            std::string &iname = *iNameIt;
            fixNameAndIname(unnamedId, templateId, iname, name);
            if (isTopLevel) {
                if (const StringVector::size_type count = std::count(nameIt + 1, namesEnd, name))
                    addShadowCount(count, iname, name);
            }
771
        }
772
773
774
775
776
777
778
779
780
781
782
    } else {
        StringVector::iterator nameIt = names->begin();
        const StringVector::iterator namesEnd = names->end();
        StringVector::iterator iNameIt = inames->begin();
        for (; nameIt != namesEnd ; ++nameIt, ++iNameIt) {
            std::string &name = *nameIt;
            std::string &iname = *iNameIt;
            fixNameAndIname(unnamedId, templateId, iname, name);
            if (isTopLevel) {
                if (const StringVector::size_type count = std::count(nameIt + 1, namesEnd, name))
                    addShadowCount(count, iname, name);
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
            }
        }
    }
}

// Index: Index of symbol, parameterOffset: Looking only at a part of the symbol array, offset
void SymbolGroupNode::parseParameters(VectorIndexType index,
                                      VectorIndexType parameterOffset,
                                      const SymbolGroup::SymbolParameterVector &vec)
{
    static char buf[BufSize];

    const bool isTopLevel = index == DEBUG_ANY_ID;
    if (isTopLevel) {
        m_parameters.Flags |= DEBUG_SYMBOL_EXPANDED;
    } else {
        m_parameters = vec.at(index - parameterOffset);
        if (m_parameters.SubElements == 0 || !(m_parameters.Flags & DEBUG_SYMBOL_EXPANDED))
            return; // No children
    }
    if (m_parameters.SubElements > 1)
        reserveChildren(m_parameters.SubElements);

    const VectorIndexType size = vec.size();
    // Scan the top level elements
    StringVector names;
    names.reserve(size);
    // Pass 1) Determine names. We need the complete set first in order to do some corrections.
    const VectorIndexType startIndex = isTopLevel ? 0 : index + 1;
Friedemann Kleint's avatar
Friedemann Kleint committed
812
    for (VectorIndexType pos = startIndex - parameterOffset; pos < size ; ++pos) {
813
814
        if (vec.at(pos).ParentSymbol == index) {
            const VectorIndexType symbolGroupIndex = pos + parameterOffset;
David Schulz's avatar
David Schulz committed
815
            if (FAILED(m_symbolGroup->debugSymbolGroup()->GetSymbolName(ULONG(symbolGroupIndex), buf, BufSize, NULL)))
816
817
818
819
820
821
822
823
824
                buf[0] = '\0';
            names.push_back(std::string(buf));
        }
    }
    // 2) Fix names
    StringVector inames = names;
    fixNames(isTopLevel, &names, &inames);
    // Pass 3): Add nodes with fixed names
    StringVector::size_type nameIndex = 0;
Friedemann Kleint's avatar
Friedemann Kleint committed
825
    for (VectorIndexType pos = startIndex - parameterOffset; pos < size ; ++pos) {
826
827
828
829
        if (vec.at(pos).ParentSymbol == index) {
            const VectorIndexType symbolGroupIndex = pos + parameterOffset;
            SymbolGroupNode *child = new SymbolGroupNode(m_symbolGroup,
                                                         ULONG(symbolGroupIndex),
830
                                                         m_module,
831
832
833
834
835
836
837
838
839
840
841
                                                         names.at(nameIndex),
                                                         inames.at(nameIndex));
            child->parseParameters(symbolGroupIndex, parameterOffset, vec);
            addChild(child);
            nameIndex++;
        }
    }
    if (isTopLevel)
        m_parameters.SubElements = ULONG(children().size());
}

842
843
SymbolGroupNode *SymbolGroupNode::create(SymbolGroup *sg, const std::string &module,
                                         const std::string &name, const SymbolGroup::SymbolParameterVector &vec)
844
{
845
    SymbolGroupNode *rc = new SymbolGroupNode(sg, DEBUG_ANY_ID, module, name, name);
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
    rc->parseParameters(DEBUG_ANY_ID, 0, vec);
    return rc;
}

// Fix some oddities in CDB values

static inline bool isHexDigit(wchar_t c)
{
    return (c >= L'0' && c <= L'9') || (c >= L'a' && c <= L'f') || (c >= L'A' && c <= L'F');
}

static void fixValue(const std::string &type, std::wstring *value)
{
    // Pointers/Unsigned integers: fix '0x00000000`00000AD bla' ... to "0xAD bla"
    const bool isHexNumber = value->size() > 3 && value->compare(0, 2, L"0x") == 0 && isHexDigit(value->at(2));
    if (isHexNumber) {
        // Remove dumb 64bit separator
863
864
865
        const size_t separator = value->find(L'`');
        if (separator != std::wstring::npos)
            value->erase(separator, 1);
866
867
868
869
870
871
872
873
874
875
876
        const std::string::size_type firstNonNullDigit = value->find_first_not_of(L"0", 2);
        // No on-null digits: plain null ptr.
        if (firstNonNullDigit == std::string::npos || value->at(firstNonNullDigit) == ' ') {
            *value = L"0x0";
        } else {
        // Strip
            if (firstNonNullDigit > 2)
                value->erase(2, firstNonNullDigit - 2);
        }
    }

hjk's avatar
hjk committed
877
878
879
880
881
882
883
884
    // Strip a vtable "0x13f37b7c8 module!Class::`vftable'" to a plain pointer.
    if (SymbolGroupValue::isVTableType(type)) {
        const std::wstring::size_type blankPos = value->find(L' ', 2);
        if (blankPos != std::wstring::npos)
            value->erase(blankPos, value->size() - blankPos);
        return;
    }

885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
    // Pointers: fix '0x00000000`00000AD class bla' ... to "0xAD", but leave
    // 'const char *' values as is ('0x00000000`00000AD "hallo").
    if (!type.empty() && type.at(type.size() - 1) == L'*') {
        // Strip ' Class bla"
        std::wstring::size_type classPos = value->find(L" struct", 2);
        if (classPos == std::string::npos)
            classPos = value->find(L" class", 2);
        if (classPos != std::string::npos)
            value->erase(classPos, value->size() - classPos);
        return;
    }

    // unsigned hex ints that are not pointers: Convert to decimal as not to confuse watch model:
    if (isHexNumber) {
        ULONG64 uv;
        std::wistringstream str(*value);
        str >> std::hex >> uv;
        if (!str.fail()) {
            *value = toWString(uv);
            return;
        }
    }

    // Integers: fix '0n10' -> '10'
    if (value->size() >= 3 && value->compare(0, 2, L"0n") == 0
        && (isdigit(value->at(2)) || value->at(2) == L'-')) {
        value->erase(0, 2);
        return;
    }
    // Fix long class names on std containers 'class std::tree<...>' -> 'class std::tree<>'
    if (value->compare(0, 6, L"class ") == 0 || value->compare(0, 7, L"struct ") == 0) {
        const std::string::size_type openTemplate = value->find(L'<');
        if (openTemplate != std::string::npos) {
            value->erase(openTemplate + 1, value->size() - openTemplate - 2);
            return;
        }
    }
}

// Check for ASCII-encode-able stuff. Plain characters + tabs at the most, no newline.
static bool isSevenBitClean(const wchar_t *buf, size_t size)
{
    const wchar_t *bufEnd = buf + size;
    for (const wchar_t *bufPtr = buf; bufPtr < bufEnd; bufPtr++) {
        const wchar_t c = *bufPtr;
        if (c > 127 || (c < 32 && c != 9))
            return false;
    }
    return true;
}

std::string SymbolGroupNode::type() const
{
    static char buf[BufSize];
    const HRESULT hr = m_symbolGroup->debugSymbolGroup()->GetSymbolTypeName(m_index, buf, BufSize, NULL);
    return SUCCEEDED(hr) ? std::string(buf) : std::string();
}

unsigned SymbolGroupNode::size() const
{
    DEBUG_SYMBOL_ENTRY entry;
    if (SUCCEEDED(m_symbolGroup->debugSymbolGroup()->GetSymbolEntryInformation(m_index, &entry)))
        return entry.Size;
    return 0;
}

ULONG64 SymbolGroupNode::address() const
{
    ULONG64 address = 0;
    const HRESULT hr = m_symbolGroup->debugSymbolGroup()->GetSymbolOffset(m_index, &address);
    if (SUCCEEDED(hr))
        return address;
    return 0;
}

std::wstring SymbolGroupNode::symbolGroupRawValue() const
{
    // Determine size and return allocated buffer
    const ULONG maxValueSize = 262144;
    ULONG obtainedSize = 0;
    HRESULT hr = m_symbolGroup->debugSymbolGroup()->GetSymbolValueTextWide(m_index, NULL, maxValueSize, &obtainedSize);
    if (FAILED(hr))
        return std::wstring();
    if (obtainedSize > maxValueSize)
        obtainedSize = maxValueSize;
    wchar_t *buffer = new wchar_t[obtainedSize];
    hr = m_symbolGroup->debugSymbolGroup()->GetSymbolValueTextWide(m_index, buffer, obtainedSize, &obtainedSize);
    if (FAILED(hr)) // Whoops, should not happen
        buffer[0] = 0;
    const std::wstring rc(buffer);
    delete [] buffer;
    return rc;
}

std::wstring SymbolGroupNode::symbolGroupFixedValue() const
{
    std::wstring value = symbolGroupRawValue();
    fixValue(type(), &value);
    return value;
}

986
987
988
989
990
991
992
993
994
995
996
997
998
// A quick check if symbol is valid by checking for inaccessible value
bool SymbolGroupNode::isMemoryAccessible() const
{
    static const char notAccessibleValueC[] = "<Memory access error>";
    char buffer[sizeof(notAccessibleValueC)];
    ULONG obtained = 0;
    if (FAILED(symbolGroup()->debugSymbolGroup()->GetSymbolValueText(m_index, buffer, sizeof(notAccessibleValueC), &obtained)))
            return false;
    if (obtained < sizeof(notAccessibleValueC))
        return true;
    return strcmp(buffer, notAccessibleValueC) != 0;
}

999
1000
1001
// Complex dumpers: Get container/fake children
void SymbolGroupNode::runComplexDumpers(const SymbolGroupValueContext &ctx)
{
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
    if (symbolGroupDebug) {
        DebugPrint dp;
        dp << "SymbolGroupNode::runComplexDumpers "  << name() << '/'
           << absoluteFullIName() << ' ' << m_index << ' ' << DebugNodeFlags(flags())
           << " type: ";
        formatKnownTypeFlags(dp, static_cast<KnownType>(m_dumperType));
        if (m_dumperSpecialInfo)
            dp << std::hex << std::showbase << " Special " << m_dumperSpecialInfo;
    }

    if ((testFlags(ComplexDumperOk) || !testFlags(SimpleDumperOk)))
        return;
1014

1015
1016
1017
1018
1019
    const bool isContainer = (m_dumperType & KT_ContainerType) != 0;
    const bool otherDumper = (m_dumperType & KT_HasComplexDumper) != 0;
    if (!isContainer && !otherDumper)
        return;
    if (isContainer && m_dumperContainerSize <= 0)
1020
        return;
1021

1022
    addFlags(ComplexDumperOk);
1023
1024
1025
    const AbstractSymbolGroupNodePtrVector ctChildren = otherDumper ?
             dumpComplexType(this, m_dumperType, m_dumperSpecialInfo, ctx) :
             containerChildren(this, m_dumperType, m_dumperContainerSize, ctx);
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
    m_dumperContainerSize = int(ctChildren.size()); // Just in case...
    if (ctChildren.empty())
        return;

    // Mark current children as obscured. We cannot show both currently
    // as this would upset the numerical sorting of the watch model
    AbstractSymbolGroupNodePtrVectorConstIterator cend = children().end();
    for (AbstractSymbolGroupNodePtrVectorConstIterator it = children().begin(); it != cend; ++it)
        (*it)->addFlags(Obscured);
    // Add children and mark them as referenced by us.
    cend = ctChildren.end();
    for (AbstractSymbolGroupNodePtrVectorConstIterator it = ctChildren.begin(); it != cend; ++it)
        addChild(*it);
}

// Run dumpers, format simple in-line dumper value and retrieve fake children
1042
1043
1044
bool SymbolGroupNode::runSimpleDumpers(const SymbolGroupValueContext &ctx)
{
    if (symbolGroupDebug)
1045
        DebugPrint() << ">SymbolGroupNode::runSimpleDumpers "  << name() << '/'
1046
1047
1048
1049
1050
1051
1052
                        << absoluteFullIName() << ' ' << m_index << DebugNodeFlags(flags());
    if (testFlags(Uninitialized))
        return false;
    if (testFlags(SimpleDumperOk))
        return true;
    if (testFlags(SimpleDumperMask))
        return false;
1053
    addFlags(dumpSimpleType(this , ctx, &m_dumperValue, &m_dumperValueEncoding,
1054
1055
                            &m_dumperType, &m_dumperContainerSize,
                            &m_dumperSpecialInfo, &m_memory));
1056
    if (symbolGroupDebug)
1057
1058
        DebugPrint() << "<SymbolGroupNode::runSimpleDumpers " << name() << " '"
                     << wStringToString(m_dumperValue) << "' Type="
1059
1060
1061
1062
                     << m_dumperType << ' ' << DebugNodeFlags(flags());
    return testFlags(SimpleDumperOk);
}

1063
std::wstring SymbolGroupNode::simpleDumpValue(const SymbolGroupValueContext &ctx, int *encoding)
1064
1065
1066
{
    if (testFlags(Uninitialized))
        return L"<not in scope>";
1067
1068
    if (runSimpleDumpers(ctx)) {
        *encoding = m_dumperValueEncoding;
1069
        return m_dumperValue;
1070
    }
1071
1072
1073
    return symbolGroupFixedValue();
}

1074
int SymbolGroupNode::dump(std::ostream &str, const std::string &visitingFullIname,
1075
1076
                           const DumpParameters &p, const SymbolGroupValueContext &ctx)
{
1077
    return dumpNode(str, name(), visitingFullIname, p, ctx);
1078
1079
}

1080
1081
// Return a watch expression basically as "*(type *)(address)"
static inline std::string watchExpression(ULONG64 address,
1082
                                          const std::string &typeIn,
1083
1084
1085
                                          int /* kType */,
                                          const std::string &module)
{
1086
1087
1088
1089
    std::string type = SymbolGroupValue::stripClassPrefixes(typeIn);
    // Try to make watch expressions faster by at least qualifying
    // templates with the local module. We cannot do expensive type
    // lookup here.
1090
1091
    // We could insert a placeholder here for non-POD types indicating
    // that a type lookup should be done when inserting watches?
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
    if (!module.empty() && type.find('>') != std::string::npos) {
        type.insert(0, 1, '!');
        type.insert(0, module);
    }
    if (SymbolGroupValue::isArrayType(type))
        type = SymbolGroupValue::stripArrayType(type);

    std::ostringstream str;
    str << "*(" << SymbolGroupValue::pointerType(type) << ')'
        << std::hex << std::showbase << address;
1102
1103
1104
    return str.str();
}

1105
1106
1107
1108
1109
int SymbolGroupNode::dumpNode(std::ostream &str,
                              const std::string &aName,
                              const std::string &aFullIName,
                              const DumpParameters &dumpParameters,
                              const SymbolGroupValueContext &ctx)
1110
1111
{
    const std::string t = type();
1112
    const ULONG64 addr = address();
1113
1114
1115
1116
    // Use name as watchExpression in case evaluation failed (watch group item
    // names are the expression).
    const std::string watchExp = t.empty() ? aName : watchExpression(addr, t, m_dumperType, m_module);
    SymbolGroupNode::dumpBasicData(str, aName, aFullIName, t, watchExp);
1117

1118
1119
    int encoding = 0;
    std::wstring value = simpleDumpValue(ctx, &encoding);
1120
1121

    if (addr) {
1122
        str << std::hex << std::showbase << ",addr=\"" << addr << '"';
1123
1124
1125
1126
1127
1128
1129
1130
1131
        if (SymbolGroupValue::isPointerType(t)) {
            std::string::size_type pointerPos = value.rfind(L"0x");
            if (pointerPos != std::string::npos) {
                ULONG64 referencedAddr = 0;
                std::wistringstream istr(value.substr(pointerPos + 2u));
                istr >> std::hex >> referencedAddr;
                if (referencedAddr)
                    str << ",origaddr=\"" << referencedAddr << '"';
            }
1132
1133
1134
        }
        str << std::noshowbase << std::dec;
    }
1135
1136
    const ULONG s = size();
    if (s)
1137
        str << ",size=\"" << s << '"';
1138
1139
1140
1141
    const bool uninitialized = flags() & Uninitialized;
    bool valueEditable = !uninitialized;
    bool valueEnabled = !uninitialized;

1142
1143
1144
    if (encoding) {
        str << ",valueencoded=\"" << encoding << "\",value=\"" << gdbmiWStringFormat(value) <<'"';
    } else if (dumpParameters.recode(t, aFullIName, ctx, addr, &value, &encoding)) {
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
        str << ",valueencoded=\"" << encoding
            << "\",value=\"" << gdbmiWStringFormat(value) <<'"';
    } else { // As is: ASCII or base64?
        if (isSevenBitClean(value.c_str(), value.size())) {
            str << ",valueencoded=\"" << DumpEncodingAscii << "\",value=\""
                << gdbmiWStringFormat(value) << '"';
        } else {
            str << ",valueencoded=\"" << DumpEncodingBase64_Utf16 << "\",value=\"";
            base64Encode(str, reinterpret_cast<const unsigned char *>(value.c_str()), value.size() * sizeof(wchar_t));
            str << '"';
        }
1156
1157
1158
        const int format = dumpParameters.format(t, aFullIName);
        if (format > 0)
            dumpEditValue(this, ctx, format, str);
1159
1160
1161
1162
1163
1164
1165
    }
    // Children: Dump all known non-obscured or subelements
    unsigned childCountGuess = 0;
    if (!uninitialized) {
        if (m_dumperContainerSize > 0) {
            childCountGuess = m_dumperContainerSize; // See Obscured handling
        } else {
1166
            if (children().empty())
1167
                childCountGuess = m_parameters.SubElements; // Guess
1168
            else
1169
1170
1171
                childCountGuess = unsigned(children().size());
        }
    }
1172
1173
    // No children..suppose we are editable and enabled.
    if (m_parameters.Flags & DEBUG_SYMBOL_READ_ONLY) {
1174
        valueEditable = false;
1175
1176
1177
1178
    } else {
        if (childCountGuess != 0 && !(m_dumperType & KT_Editable))
            valueEditable = false;
    }
1179
    str << ",valueenabled=\"" << (valueEnabled ? "true" : "false") << '"'
1180
1181
        << ",valueeditable=\"" << (valueEditable ? "true" : "false") << '"';
    return childCountGuess;
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
}

void SymbolGroupNode::debug(std::ostream &str,
                            const std::string &visitingFullIname,
                            unsigned verbosity, unsigned depth) const
{
    indentStream(str, depth);
    const std::string fullIname = absoluteFullIName();
    str << "AbsIname=" << fullIname << '"';
    if (fullIname != visitingFullIname)
        str << ",VisitIname=\"" <<visitingFullIname;
1193
    str << "\",module=\"" << m_module << "\",index=" << m_index;
1194
1195
    if (const VectorIndexType childCount = children().size())
        str << ", Children=" << childCount;
1196
    str << ' ' << m_parameters << DebugNodeFlags(flags());
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
    if (verbosity) {
        str << ",name=\"" << name() << "\", Address=0x" << std::hex << address() << std::dec
            << " Type=\"" << type() << '"';
        if (m_dumperType >= 0) {
            str << " ,dumperType=" << m_dumperType;
            if (m_dumperType & KT_Qt_Type)
                str << " qt";
            if (m_dumperType & KT_STL_Type)
                str << " STL";
            if (m_dumperType & KT_ContainerType)
                str << " container(" << m_dumperContainerSize << ')';
        }
1209
        if (!testFlags(Uninitialized))
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
            str << " Value=\"" << gdbmiWStringFormat(symbolGroupRawValue()) << '"';
        str << '\n'; // Potentially multiline
    }
    str << '\n';
}

static inline std::string msgCannotCast(const std::string &nodeName,
                                        const std::string &fromType,
                                        const std::string &toType,
                                        const std::string &why)
{
    std::ostringstream str;
    str << "Cannot cast node '" << nodeName << "' from '" << fromType
        << "' to '" << toType << "': " << why;
    return str.str();
}

1227
1228
1229
1230
1231
1232
1233
1234
1235
static std::string msgExpandFailed(const std::string &name, const std::string &iname,
                                   ULONG index, const std::string &why)
{
    std::ostringstream str;
    str << "Expansion of '" << name << "'/'" << iname << " (index: " << index
        << ") failed: " << why;
    return str.str();
}

1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
static std::string msgCollapseFailed(const std::string &name, const std::string &iname,
                                     ULONG index, const std::string &why)
{
    std::ostringstream str;
    str << "Collapsing of '" << name << "'/'" << iname << " (index: " << index
        << ") failed: " << why;
    return str.str();
}

bool SymbolGroupNode::collapse(std::string *errorMessage)
{
    if (!isExpanded())
        return true;
    SymbolGroupNode *sParent = symbolGroupNodeParent();
    if (!sParent) {
        *errorMessage = msgCollapseFailed(name(), absoluteFullIName(), m_index, "Cannot collapse root.");
        ExtensionContext::instance().report('X', 0, 0, "Error", "%s", errorMessage->c_str());
        return false;
    }
    // Get current number of children
    const ULONG next = nextSymbolIndex();
    HRESULT hr = m_symbolGroup->debugSymbolGroup()->ExpandSymbol(m_index, FALSE);
    if (FAILED(hr)) {
        *errorMessage = msgCollapseFailed(name(), absoluteFullIName(), m_index, msgDebugEngineComFailed("ExpandSymbol(FALSE)", hr));
        ExtensionContext::instance().report('X', 0, 0, "Error", "%s", errorMessage->c_str());
        return false;
    }
    removeChildren();
    if (next)
        sParent->notifyIndexesMoved(m_index + 1, false, next - m_index - 1);
    return true;
}

1269
1270
1271
// Expand!
bool SymbolGroupNode::expand(std::string *errorMessage)
{
1272
1273
1274
1275
    if (symbolGroupDebug)
        DebugPrint() << "SymbolGroupNode::expand "  << name()
                     <<'/' << absoluteFullIName() << ' '
                    << m_index << DebugNodeFlags(flags());
1276
    if (isExpanded())
1277
1278
        return true;
    if (!canExpand()) {
1279
1280
        *errorMessage = msgExpandFailed(name(), absoluteFullIName(), m_index,
                                        "No subelements to expand in node.");
1281
1282
1283
        return false;
    }
    if (flags() & Uninitialized) {
1284
1285
        *errorMessage = msgExpandFailed(name(), absoluteFullIName(), m_index,
                                        "Refusing to expand uninitialized node.");
1286
1287
1288
1289
1290
1291
        return false;
    }

    const HRESULT hr = m_symbolGroup->debugSymbolGroup()->ExpandSymbol(m_index, TRUE);

    if (FAILED(hr)) {
1292
        *errorMessage = msgExpandFailed(name(), absoluteFullIName(), m_index, msgDebugEngineComFailed("ExpandSymbol", hr));
1293
        ExtensionContext::instance().report('X', 0, 0, "Error", "%s", errorMessage->c_str());
1294
1295
1296
1297
1298
1299
1300
        return false;
    }
    SymbolGroup::SymbolParameterVector parameters;
    // Retrieve parameters (including self, re-retrieve symbol parameters to get new 'expanded' flag
    // and corrected SubElement count (might be estimate))
    if (!SymbolGroup::getSymbolParameters(m_symbolGroup->debugSymbolGroup(),
                                          m_index, m_parameters.SubElements + 1,
1301
1302
                                          &parameters, errorMessage)) {
        *errorMessage = msgExpandFailed(name(), absoluteFullIName(), m_index, *errorMessage);
1303
        return false;
1304
    }
1305
    // Before inserting children, correct indexes on whole group
1306
    m_symbolGroup->root()->notifyIndexesMoved(m_index + 1, true, parameters.at(0).SubElements);
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
    // Parse parameters, correct our own) and create child nodes.
    parseParameters(m_index, m_index, parameters);
    return true;
}

bool SymbolGroupNode::expandRunComplexDumpers(const SymbolGroupValueContext &ctx,
                                              std::string *errorMessage)
{
    if (isExpanded() || testFlags(ComplexDumperOk))
        return true;
    if (!expand(errorMessage))
        return false;
1319
1320
    // Run simple dumpers to obtain type and run complex dumpers
    if (runSimpleDumpers(ctx) && testFlags(SimpleDumperOk))
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
        runComplexDumpers(ctx);
    return true;
}

bool SymbolGroupNode::typeCast(const std::string &desiredType, std::string *errorMessage)
{
    const std::string fromType = type();
    if (fromType == desiredType)
        return true;
    if (isExpanded()) {
        *errorMessage = msgCannotCast(absoluteFullIName(), fromType, desiredType, "Already expanded");
        return false;
    }
    HRESULT hr = m_symbolGroup->debugSymbolGroup()->OutputAsType(m_index, desiredType.c_str());
    if (FAILED(hr)) {
        *errorMessage = msgCannotCast(absoluteFullIName(), fromType, desiredType, msgDebugEngineComFailed("OutputAsType", hr));
        return false;
    }
    hr = m_symbolGroup->debugSymbolGroup()->GetSymbolParameters(m_index, 1, &m_parameters);
    if (FAILED(hr)) { // Should never fail
        *errorMessage = msgCannotCast(absoluteFullIName(), fromType, desiredType, msgDebugEngineComFailed("GetSymbolParameters", hr));
        return false;
    }
    return true;
}

1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
// Find the index of the next symbol in the group, that is, right sibling.
// Go up the tree if we are that last sibling. 0 indicates none found (last sibling)
ULONG SymbolGroupNode::nextSymbolIndex() const
{
    const SymbolGroupNode *sParent = symbolGroupNodeParent();
    if (!sParent)
        return 0;
    const unsigned myIndex = sParent->indexOf(this);
    const AbstractSymbolGroupNodePtrVector &siblings = sParent->children();
    // Find any 'real' SymbolGroupNode to our right.
    const unsigned size = unsigned(siblings.size());
Friedemann Kleint's avatar
Friedemann Kleint committed
1358
    for (unsigned i = myIndex + 1; i < size; ++i)
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
        if (const SymbolGroupNode *s = siblings.at(i)->asSymbolGroupNode())
            return s->index();
    return sParent->nextSymbolIndex();
}

// Remove self off parent and return the indexes to be shifted or unsigned(-1).
bool SymbolGroupNode::removeSelf(SymbolGroupNode *root, std::string *errorMessage)
{
    SymbolGroupNode *sParent = symbolGroupNodeParent();
    if (m_index == DEBUG_ANY_ID || !sParent) {
        *errorMessage = "SymbolGroupNode::removeSelf: Internal error 1.";
        return false;
    }
    const unsigned parentPosition = sParent->indexOf(this);
    if (parentPosition == unsigned(-1)) {
        *errorMessage = "SymbolGroupNode::removeSelf: Internal error 2.";
        return false;
    }
    // Determine the index for the following symbols to be subtracted by finding the next
    // 'real' SymbolGroupNode child (right or up the tree-right) and taking its index
    const ULONG oldIndex = index();
    const ULONG nextSymbolIdx = nextSymbolIndex();
    const ULONG offset = nextSymbolIdx >  oldIndex ? nextSymbolIdx - oldIndex : 0;
    if (SymbolGroupValue::verbose)
        DebugPrint() << "SymbolGroupNode::removeSelf #" << index() << " '" << name()
                     << "' at pos=" << parentPosition<< " (" << sParent->children().size()
                     << ") of parent '" << sParent->name()
                     << "' nextIndex=" << nextSymbolIdx << " offset=" << offset << *errorMessage;
    // Remove from symbol group
    const HRESULT hr = symbolGroup()->debugSymbolGroup()->RemoveSymbolByIndex(oldIndex);
    if (FAILED(hr)) {
        *errorMessage = msgDebugEngineComFailed("RemoveSymbolByIndex", hr);
        return false;
    }
    // Move the following symbol indexes: We no longer exist below here.
    sParent ->removeChildAt(parentPosition);
    if (offset)
        root->notifyIndexesMoved(oldIndex + 1, false, offset);
    return true;
}

1400
1401
1402
1403
1404
1405
1406
1407
static inline std::string msgCannotAddSymbol(const std::string &name, const std::string &why)
{
    std::ostringstream str;
    str << "Cannot add symbol '" << name << "': " << why;
    return str.str();
}

// For root nodes, only: Add a new symbol by name
1408
1409
SymbolGroupNode *SymbolGroupNode::addSymbolByName(const std::string &module,
                                                  const std::string &name,
1410
                                                  const std::string &displayName,
1411
1412
1413
1414
                                                  const std::string &iname,
                                                  std::string *errorMessage)
{
    ULONG index = DEBUG_ANY_ID; // Append
David Schulz's avatar
David Schulz committed
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425

    char buf[BufSize];
    CIDebugSymbolGroup *symbolGroup = m_symbolGroup->debugSymbolGroup();
    SymbolParameterVector indexParameters(1, DEBUG_SYMBOL_PARAMETERS());

    static const char separator = '.';
    std::string::size_type partStart = 0;
    std::string::size_type partEnd = name.find(separator);
    std::string namePart = name.substr(0, partEnd);

    HRESULT hr = symbolGroup->AddSymbol(namePart.c_str(), &index);
1426
    if (FAILED(hr)) {
David Schulz's avatar
David Schulz committed
1427
        *errorMessage = msgCannotAddSymbol(namePart, msgDebugEngineComFailed("AddSymbol", hr));
1428
        ExtensionContext::instance().report('X', 0, 0, "Error", "%s", errorMessage->c_str());
1429
1430
        return 0;
    }
David Schulz's avatar
David Schulz committed
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469