qtcreatorcdbextension.cpp 42.6 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
hjk's avatar
hjk committed
3 4
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8 9 10 11 12 13 14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15 16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22 23 24 25
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
29 30 31 32 33

#include "extensioncontext.h"
#include "outputcallback.h"
#include "eventcallback.h"
#include "symbolgroup.h"
34
#include "symbolgroupvalue.h"
35 36 37 38 39 40 41 42
#include "stringutils.h"
#include "gdbmihelpers.h"

#include <cstdio>
#include <sstream>
#include <list>
#include <iterator>

43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
/*!
    \group qtcreatorcdbext
    \title Qt Creator CDB extension

    \brief  QtCreatorCDB ext is an extension loaded into CDB.exe (see cdbengine.cpp).


    It provides

    \list
    \o Notification about the state of the debugging session:
    \list
        \o idle: (hooked with .idle_cmd) debuggee stopped
        \o accessible: Debuggee stopped, cdb.exe accepts commands
        \o inaccessible: Debuggee runs, no way to post commands
        \o session active/inactive: Lost debuggee, terminating.
    \endlist
    \o Hook up with output/event callbacks and produce formatted output
    \o Provide some extension commands that produce output in a standardized (GDBMI)
       format that ends up in handleExtensionMessage().
63
    \endlist
64
*/
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

// Data struct and helpers for formatting help
struct CommandDescription {
    const char *name;
    const char *description;
    const char *usage;
};

// Single line of usage: For reporting usage errors back as a single line
static std::string singleLineUsage(const CommandDescription &d)
{
    std::string rc = "Usage: ";
    const char *endOfLine = strchr(d.usage, '\n');
    rc += endOfLine ? std::string(d.usage, endOfLine -  d.usage) : std::string(d.usage);
    return rc;
}

// Format description of a command
std::ostream &operator<<(std::ostream &str, const CommandDescription &d)
{
    str << "Command '" << d.name << "': " << d.description << '\n';
    if (d.usage[0])
        str << "Usage: " << d.name << ' ' << d.usage << '\n';
    str << '\n';
    return str;
}

enum Command {
    CmdPid,
    CmdExpandlocals,
    CmdLocals,
96
    CmdWatches,
97 98 99 100 101 102 103 104 105 106
    CmdDumplocal,
    CmdTypecast,
    CmdAddsymbol,
    CmdAssign,
    CmdThreads,
    CmdRegisters,
    CmdModules,
    CmdIdle,
    CmdHelp,
    CmdMemory,
107
    CmdExpression,
108
    CmdStack,
109
    CmdShutdownex,
110
    CmdAddWatch,
111
    CmdWidgetAt,
112
    CmdBreakPoints,
113 114
    CmdTest,
    CmdSetParameter
115 116 117 118 119 120 121
};

static const CommandDescription commandDescriptions[] = {
{"pid",
 "Prints inferior process id and hooks up output callbacks.",
 "[-t token]"},
{"expandlocals", "Expands local variables by iname in symbol group.",
122 123 124
 "[-t token] [-c] <frame-number> <iname1-list>\n"
 "iname1-list: Comma-separated list of inames\n"
 "-c complex dumpers"},
125 126
{"locals",
 "Prints local variables of symbol group in GDBMI or debug format",
127 128
 "[-t token] [-v] [T formats] [-I formats] [-f debugfilter] [-c] [-h] [-d]\n[-e expand-list] [-u uninitialized-list]\n"
 "[-W] [-w watch-iname watch-expression] <frame-number> [iname]\n"
129
 "-h human-readable output\n"
130
 "-v increase verboseness of dumping\n"
131
 "-d debug output\n"
132
 "-f debug_filter\n"
133
 "-c complex dumpers\n"
134
 "-e expand-list        Comma-separated list of inames to be expanded beforehand\n"
135 136
 "-u uninitialized-list Comma-separated list of uninitialized inames\n"
 "-I formatmap          map of 'hex-encoded-iname=typecode'\n"
137
 "-T formatmap          map of 'hex-encoded-type-name=typecode'\n"
138
 "-D                    Discard existing symbol group\n"
139 140 141 142 143
 "-W                    Synchronize watch items (-w)\n"
 "-w iname expression   Watch item"},
{"watches",
 "Prints watches variables of symbol group in GDBMI or debug format",
 "[-t token] [-v] [T formats] [-I formats] [-f debugfilter] [-c] [-h] [-d] <iname>\n"
144
 "-h human-readable output\n"
145 146 147 148 149
 "-v increase verboseness of dumping\n"
 "-d debug output\n"
 "-f debug_filter\n"
 "-c complex dumpers\n"
 "-I formatmap          map of 'hex-encoded-iname=typecode'\n"
150
 "-T formatmap          map of 'hex-encoded-type-name=typecode'"},
151 152 153 154 155 156 157
{"dumplocal", "Dumps local variable using simple dumpers (testing command).",
 "[-t token] <frame-number> <iname>"},
{"typecast","Performs a type cast on an unexpanded iname of symbol group.",
 "[-t token] <frame-number> <iname> <desired-type>"},
{"addsymbol","Adds a symbol to symbol group (testing command).",
 "[-t token] <frame-number> <name-expression> [optional-iname]"},
{"assign","Assigns a value to a variable in current symbol group.",
158 159 160 161
 "[-t token] [-h] <iname=value>\n"
 "-h    Data are hex-encoded, binary data\n"
 "-u    Data are hex-encoded, UTF16 data"
},
162 163 164 165 166 167 168 169
{"threads","Lists threads in GDBMI format.","[-t token]"},
{"registers","Lists registers in GDBMI format","[-t token]"},
{"modules","Lists modules in GDBMI format.","[-t token]"},
{"idle",
 "Reports stop reason in GDBMI format.\n"
 "Intended to be used with .idle_cmd to obtain proper stop notification.",""},
{"help","Prints help.",""},
{"memory","Prints memory contents in Base64 encoding.","[-t token] <address> <length>"},
170
{"expression","Prints expression value.","[-t token] <expression>"},
171
{"stack","Prints stack in GDBMI format.","[-t token] [max-frames]"},
172
{"shutdownex","Unhooks output callbacks.\nNeeds to be called explicitly only in case of remote debugging.",""},
173
{"addwatch","Add watch expression","<iname> <expression>"},
174
{"widgetat","Return address of widget at position","<x> <y>"},
175
{"breakpoints","List breakpoints with modules","[-h] [-v]"},
176 177
{"test","Testing command","-T type | -w watch-expression"},
{"setparameter","Set parameter","maxStringLength=value maxStackDepth=value"}
178
};
179 180 181 182

typedef std::vector<std::string> StringVector;
typedef std::list<std::string> StringList;

183 184 185 186 187
static inline bool isOption(const std::string &opt)
{
    return opt.size() == 2 && opt.at(0) == '-' && opt != "--";
}

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
// Helper for commandTokens() below:
// Simple splitting of command lines allowing for '"'-quoted tokens
// 'typecast local.i "class QString *"' -> ('typecast','local.i','class QString *')
template<class Inserter>
static inline void splitCommand(PCSTR args, Inserter it)
{
    enum State { WhiteSpace, WithinToken, WithinQuoted };

    State state = WhiteSpace;
    std::string current;
    for (PCSTR p = args; *p; p++) {
        char c = *p;
        switch (state) {
        case WhiteSpace:
            switch (c) {
            case ' ':
                break;
            case '"':
                state = WithinQuoted;
                current.clear();
                break;
            default:
                state = WithinToken;
                current.clear();
                current.push_back(c);
                break;
            }
            break;
        case WithinToken:
            switch (c) {
            case ' ':
                state = WhiteSpace;
                *it = current;
                ++it;
                break;
            default:
                current.push_back(c);
                break;
            }
            break;
        case WithinQuoted:
            switch (c) {
            case '"':
                state = WhiteSpace;
                *it = current;
                ++it;
                break;
            default:
                current.push_back(c);
                break;
            }
            break;
        }
    }
    if (state == WithinToken) {
        *it = current;
        ++it;
    }
}

248 249 250 251 252 253 254 255 256 257 258
// Split & Parse the arguments of a command and extract the
// optional first integer token argument ('command -t <number> remaining arguments')
// Each command takes the 'token' argument and includes it in its output
// so that the calling CDB engine in Qt Creator can match the callback.

template<class StringContainer>
static inline StringContainer commandTokens(PCSTR args, int *token = 0)
{
    typedef StringContainer::iterator ContainerIterator;

    if (token)
259
        *token = -1; // Handled as 'display' in engine, so that user can type commands
260
    StringContainer tokens;
261
    splitCommand(args, std::back_inserter(tokens));
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    // Check for token
    ContainerIterator it = tokens.begin();
    if (it != tokens.end() && *it == "-t" && ++it != tokens.end()) {
        if (token)
            std::istringstream(*it) >> *token;
        tokens.erase(tokens.begin(), ++it);
    }
    return tokens;
}

// Extension command 'pid':
// Report back PID so that Qt Creator engine knows whom to DebugBreakProcess.
extern "C" HRESULT CALLBACK pid(CIDebugClient *client, PCSTR args)
{
    ExtensionContext::instance().hookCallbacks(client);

    int token;
    commandTokens<StringList>(args, &token);
280
    dprintf("Qt Creator CDB extension version 2.7 (Qt 5 support) %d bit built %s.\n",
281
            sizeof(void *) * 8, __DATE__);
282
    if (const ULONG pid = currentProcessId(client))
283
        ExtensionContext::instance().report('R', token, 0, "pid", "%u", pid);
284
    else
285
        ExtensionContext::instance().report('N', token, 0, "pid", "0");
286 287 288 289 290 291 292 293 294 295 296 297 298 299
    return S_OK;
}

// Extension command 'expandlocals':
// Expand a comma-separated iname-list of local variables.

extern "C" HRESULT CALLBACK expandlocals(CIDebugClient *client, PCSTR args)
{
    ExtensionCommandContext exc(client);
    unsigned frame = 0;
    SymbolGroup *symGroup = 0;
    std::string errorMessage;

    int token;
300
    StringList tokens = commandTokens<StringList>(args, &token);
301
    StringVector inames;
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    bool runComplexDumpers = false;
    do {
        if (!tokens.empty() && tokens.front() == "-c") {
            runComplexDumpers = true;
            tokens.pop_front();
        }
        if (tokens.empty() || !integerFromString(tokens.front(), &frame))  {
            errorMessage = singleLineUsage(commandDescriptions[CmdExpandlocals]);
            break;
        }
        tokens.pop_front();
        if (tokens.empty()) {
            errorMessage = singleLineUsage(commandDescriptions[CmdExpandlocals]);
            break;
        }
        split(tokens.front(), ',', std::back_inserter(inames));
    } while (false);

    if (errorMessage.empty())
321
        symGroup = ExtensionContext::instance().symbolGroup(exc.symbols(), exc.threadId(), frame, &errorMessage);
322 323

    if (!symGroup) {
324
        ExtensionContext::instance().report('N', token, 0, "expandlocals", errorMessage.c_str());
325
        return S_OK;
326
    }
327 328

    const unsigned succeeded = runComplexDumpers ?
329
        symGroup->expandListRunComplexDumpers(inames, SymbolGroupValueContext(exc.dataSpaces(), exc.symbols()), &errorMessage) :
330 331
        symGroup->expandList(inames, &errorMessage);

332
    ExtensionContext::instance().report('R', token, 0, "expandlocals", "%u/%u %s",
333
                                        succeeded, unsigned(inames.size()), errorMessage.c_str());
334 335 336
    return S_OK;
}

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
// Parameters to be shared between watch/locals dump commands
struct DumpCommandParameters
{
    DumpCommandParameters() : debugOutput(0), verbose(0) {}

    // Check option off front and remove if parsed
    enum ParseOptionResult { Ok, Error, OtherOption, EndOfOptions };
    ParseOptionResult parseOption(StringList *options);

    unsigned debugOutput;
    std::string debugFilter;
    DumpParameters dumpParameters;
    unsigned verbose;
};

DumpCommandParameters::ParseOptionResult DumpCommandParameters::parseOption(StringList *options)
{
    // Parse all options and erase valid ones from the list
    if (options->empty())
        return DumpCommandParameters::EndOfOptions;

    const std::string &opt = options->front();
    if (!isOption(opt))
        return DumpCommandParameters::EndOfOptions;
    const char option = opt.at(1);
    bool knownOption = true;
    switch (option) {
    case 'd':
        debugOutput++;
        break;
    case 'h':
        dumpParameters.dumpFlags |= DumpParameters::DumpHumanReadable;
        break;
    case 'c':
        dumpParameters.dumpFlags |= DumpParameters::DumpComplexDumpers;
        break;
    case 'f':
        if (options->size() < 2)
            return Error;
        options->pop_front();
        debugFilter = options->front();
        break;
    case 'v':
        verbose++;
        break;
    case 'T': // typeformats: 'hex'ed name = formatnumber,...'
        if (options->size() < 2)
            return Error;
        options->pop_front();
        if (options->front().empty())
            return Error;
388 389
        dumpParameters.typeFormats =
            DumpParameters::decodeFormatArgument(options->front(), true);
390
        break;
391
    case 'I': // individual formats: iname= formatnumber,...'
392 393 394
        if (options->size() < 2)
            return Error;
        options->pop_front();
395 396
        dumpParameters.individualFormats =
            DumpParameters::decodeFormatArgument(options->front(), false);
397 398 399 400 401 402 403 404 405 406
        break;
    default:
        knownOption = false;
        break;
    } // case option
    if (knownOption)
        options->pop_front();
    return knownOption ? Ok : OtherOption;
}

407 408 409 410
// Extension command 'locals':
// Display local variables of symbol group in GDBMI or debug output form.
// Takes an optional iname which is expanded before displaying (for updateWatchData)

411
static std::string commmandLocals(ExtensionCommandContext &commandExtCtx,PCSTR args, int *token, std::string *errorMessage)
412
{
413 414 415
    typedef WatchesSymbolGroup::InameExpressionMap InameExpressionMap;
    typedef InameExpressionMap::value_type InameExpressionMapEntry;

416
    // Parse the command
417 418
    ExtensionContext &extCtx = ExtensionContext::instance();
    DumpCommandParameters parameters;
419 420
    std::string iname;
    StringList tokens = commandTokens<StringList>(args, token);
421 422
    StringVector expandedInames;
    StringVector uninitializedInames;
423 424
    InameExpressionMap watcherInameExpressionMap;
    bool watchSynchronization = false;
425
    bool discardSymbolGroup = false;
426
    // Parse away options
427 428 429
    for (bool optionLeft = true;  optionLeft && !tokens.empty(); ) {
        switch (parameters.parseOption(&tokens)) {
        case DumpCommandParameters::Ok:
430
            break;
431 432 433 434 435
        case DumpCommandParameters::Error:
            *errorMessage = singleLineUsage(commandDescriptions[CmdLocals]);
            return std::string();
        case DumpCommandParameters::OtherOption: {
            const char option = tokens.front().at(1);
436
            tokens.pop_front();
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
            switch (option) {
            case 'u':
                if (tokens.empty()) {
                    *errorMessage = singleLineUsage(commandDescriptions[CmdLocals]);
                    return std::string();
                }
                split(tokens.front(), ',', std::back_inserter(uninitializedInames));
                tokens.pop_front();
                break;
            case 'e':
                if (tokens.empty()) {
                    *errorMessage = singleLineUsage(commandDescriptions[CmdLocals]);
                    return std::string();
                }
                split(tokens.front(), ',', std::back_inserter(expandedInames));
                tokens.pop_front();
                break;
            case 'w':  { // Watcher iname exp
                if (tokens.size() < 2) {
                    *errorMessage = singleLineUsage(commandDescriptions[CmdLocals]);
                    return std::string();
                }
                const std::string iname = tokens.front();
                tokens.pop_front();
                const std::string expression = tokens.front();
                tokens.pop_front();
                watcherInameExpressionMap.insert(InameExpressionMapEntry(iname, expression));
464 465
            }
            break;
466 467 468
            case 'W':
                watchSynchronization = true;
                break;
469 470 471
            case 'D':
                discardSymbolGroup = true;
                break;
472 473 474 475 476
            } // case option
        }
        break;
        case DumpCommandParameters::EndOfOptions:
            optionLeft = false;
477
            break;
478 479
        }
    }
480
    // Frame and iname
481
    unsigned frame;
482 483
    if (tokens.empty() || !integerFromString(tokens.front(), &frame)) {
        *errorMessage = singleLineUsage(commandDescriptions[CmdLocals]);
484 485 486 487 488 489 490
        return std::string();
    }

    tokens.pop_front();
    if (!tokens.empty())
        iname = tokens.front();

491
    const SymbolGroupValueContext dumpContext(commandExtCtx.dataSpaces(), commandExtCtx.symbols());
492 493
    if (discardSymbolGroup)
        extCtx.discardSymbolGroup();
494
    SymbolGroup * const symGroup = extCtx.symbolGroup(commandExtCtx.symbols(), commandExtCtx.threadId(), frame, errorMessage);
495 496
    if (!symGroup)
        return std::string();
497

498 499
    if (!uninitializedInames.empty())
        symGroup->markUninitialized(uninitializedInames);
500

501
    SymbolGroupValue::verbose = parameters.verbose;
502 503
    if (SymbolGroupValue::verbose)
        DebugPrint() << parameters.dumpParameters;
504 505 506 507 508 509 510 511 512 513 514 515

    // Synchronize watches if desired.
    WatchesSymbolGroup *watchesSymbolGroup = extCtx.watchesSymbolGroup();
    if (watchSynchronization) {
        if (watcherInameExpressionMap.empty()) { // No watches..kill group.
            watchesSymbolGroup = 0;
            extCtx.discardWatchesSymbolGroup();
            if (SymbolGroupValue::verbose)
                DebugPrint() << "Discarding watchers";
        } else {
            // Force group into existence
            watchesSymbolGroup = extCtx.watchesSymbolGroup(commandExtCtx.symbols(), errorMessage);
516
            if (!watchesSymbolGroup || !watchesSymbolGroup->synchronize(commandExtCtx.symbols(), watcherInameExpressionMap, errorMessage))
517 518 519 520 521
                return std::string();
        }
    }

    // Pre-expand.
522
    if (!expandedInames.empty()) {
523
        if (parameters.dumpParameters.dumpFlags & DumpParameters::DumpComplexDumpers) {
524
            symGroup->expandListRunComplexDumpers(expandedInames, dumpContext, errorMessage);
525 526
            if (watchesSymbolGroup)
                watchesSymbolGroup->expandListRunComplexDumpers(expandedInames, dumpContext, errorMessage);
527 528
        } else {
            symGroup->expandList(expandedInames, errorMessage);
529 530
            if (watchesSymbolGroup)
                watchesSymbolGroup->expandList(expandedInames, errorMessage);
531 532 533
        }
    }

534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
    // Debug output: Join the 2 symbol groups if no iname is given.
    if (parameters.debugOutput) {
        std::string debugRc = symGroup->debug(iname, parameters.debugFilter, parameters.debugOutput - 1);
        if (iname.empty() && watchesSymbolGroup) {
            debugRc.push_back('\n');
            debugRc += watchesSymbolGroup->debug(iname, parameters.debugFilter, parameters.debugOutput - 1);
        }
        return debugRc;
    }

    // Dump all: Join the 2 symbol groups '[local.x][watch.0]'->'[local.x,watch.0]'
    if (iname.empty()) {
        std::string dumpRc = symGroup->dump(dumpContext, parameters.dumpParameters);
        if (!dumpRc.empty() && watchesSymbolGroup) {
            std::string watchesDump = watchesSymbolGroup->dump(dumpContext, parameters.dumpParameters);
            if (!watchesDump.empty()) {
                dumpRc.erase(dumpRc.size() - 1, 1); // Strip ']'
                watchesDump[0] = ','; // '[' -> '.'
                dumpRc += watchesDump;
            }
        }
        return dumpRc;
    }
557

558
    return symGroup->dump(iname, dumpContext, parameters.dumpParameters, errorMessage);
559 560 561 562 563 564 565 566
}

extern "C" HRESULT CALLBACK locals(CIDebugClient *client, PCSTR args)
{
    ExtensionCommandContext exc(client);
    std::string errorMessage;
    int token;
    const std::string output = commmandLocals(exc, args, &token, &errorMessage);
567
    SymbolGroupValue::verbose = 0;
568
    if (output.empty())
569
        ExtensionContext::instance().report('N', token, 0, "locals", errorMessage.c_str());
570
    else
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
        ExtensionContext::instance().reportLong('R', token, "locals", output);
    return S_OK;
}

// Extension command 'locals':
// Display local variables of symbol group in GDBMI or debug output form.
// Takes an optional iname which is expanded before displaying (for updateWatchData)

static std::string commmandWatches(ExtensionCommandContext &exc, PCSTR args, int *token, std::string *errorMessage)
{
    // Parse the command
    DumpCommandParameters parameters;
    StringList tokens = commandTokens<StringList>(args, token);
    // Parse away options
    for (bool optionLeft = true;  optionLeft && !tokens.empty(); ) {
        switch (parameters.parseOption(&tokens)) {
        case DumpCommandParameters::Ok:
            break;
        case DumpCommandParameters::Error:
        case DumpCommandParameters::OtherOption:
            *errorMessage = singleLineUsage(commandDescriptions[CmdWatches]);
            return std::string();
        case DumpCommandParameters::EndOfOptions:
            optionLeft = false;
            break;
        }
    }
    const std::string iname = tokens.empty() ? std::string() : tokens.front();
    if (iname.empty() && !parameters.debugOutput) {
        *errorMessage = singleLineUsage(commandDescriptions[CmdWatches]);
        return std::string();
    }

    const SymbolGroupValueContext dumpContext(exc.dataSpaces(), exc.symbols());
    SymbolGroup * const symGroup = ExtensionContext::instance().watchesSymbolGroup(exc.symbols(), errorMessage);
    if (!symGroup)
        return std::string();
    SymbolGroupValue::verbose = parameters.verbose;

    if (parameters.debugOutput)
        return symGroup->debug(iname, parameters.debugFilter, parameters.debugOutput - 1);
    return symGroup->dump(iname, dumpContext, parameters.dumpParameters, errorMessage);
}

extern "C" HRESULT CALLBACK watches(CIDebugClient *client, PCSTR args)
{
    ExtensionCommandContext exc(client);
    std::string errorMessage = "e";
    int token = 0;
    const std::string output = commmandWatches(exc, args, &token, &errorMessage);
    SymbolGroupValue::verbose = 0;
622
    if (output.empty())
623
        ExtensionContext::instance().report('N', token, 0, "locals", errorMessage.c_str());
624
    else
625
        ExtensionContext::instance().reportLong('R', token, "locals", output);
626 627 628
    return S_OK;
}

629 630 631 632 633 634 635 636 637
// Extension command 'dumplocal':
// Dump a local variable using dumpers (testing command).

static std::string dumplocalHelper(ExtensionCommandContext &exc,PCSTR args, int *token, std::string *errorMessage)
{
    // Parse the command
    StringList tokens = commandTokens<StringList>(args, token);
    // Frame and iname
    unsigned frame;
638 639
    if (tokens.empty() || integerFromString(tokens.front(), &frame)) {
        *errorMessage = singleLineUsage(commandDescriptions[CmdDumplocal]);
640 641 642 643
        return std::string();
    }
    tokens.pop_front();
    if (tokens.empty()) {
644
        *errorMessage = singleLineUsage(commandDescriptions[CmdDumplocal]);
645 646 647 648 649 650 651 652
        return std::string();
    }
    const std::string iname = tokens.front();

    SymbolGroup * const symGroup = ExtensionContext::instance().symbolGroup(exc.symbols(), exc.threadId(), frame, errorMessage);
    if (!symGroup)
        return std::string();

653 654
    AbstractSymbolGroupNode *n = symGroup->find(iname);
    if (!n || !n->asSymbolGroupNode()) {
655 656 657 658
        *errorMessage = "No such iname " + iname;
        return std::string();
    }
    std::wstring value;
659
    if (!dumpSimpleType(n->asSymbolGroupNode(), SymbolGroupValueContext(exc.dataSpaces(), exc.symbols()), &value)) {
660 661 662 663 664 665 666 667 668 669 670 671
        *errorMessage = "Cannot dump " + iname;
        return std::string();
    }
    return wStringToString(value);
}

extern "C" HRESULT CALLBACK dumplocal(CIDebugClient *client, PCSTR  argsIn)
{
    ExtensionCommandContext exc(client);
    std::string errorMessage;
    int token = 0;
    const std::string value = dumplocalHelper(exc,argsIn, &token, &errorMessage);
672
    if (value.empty())
673
        ExtensionContext::instance().report('N', token, 0, "dumplocal", errorMessage.c_str());
674
    else
675
        ExtensionContext::instance().reportLong('R', token, "dumplocal", value);
676 677 678
    return S_OK;
}

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
// Extension command 'typecast':
// Change the type of a symbol group entry (testing purposes)

extern "C" HRESULT CALLBACK typecast(CIDebugClient *client, PCSTR args)
{
    ExtensionCommandContext exc(client);
    unsigned frame = 0;
    SymbolGroup *symGroup = 0;
    std::string errorMessage;

    int token;
    const StringVector tokens = commandTokens<StringVector>(args, &token);
    std::string iname;
    std::string desiredType;
    if (tokens.size() == 3u && integerFromString(tokens.front(), &frame)) {
        symGroup = ExtensionContext::instance().symbolGroup(exc.symbols(), exc.threadId(), frame, &errorMessage);
        iname = tokens.at(1);
        desiredType = tokens.at(2);
    } else {
        errorMessage = singleLineUsage(commandDescriptions[CmdTypecast]);
    }
700
    if (symGroup != 0 && symGroup->typeCast(iname, desiredType, &errorMessage))
701
        ExtensionContext::instance().report('R', token, 0, "typecast", "OK");
702
    else
703
        ExtensionContext::instance().report('N', token, 0, "typecast", errorMessage.c_str());
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
    return S_OK;
}

// Extension command 'addsymbol':
// Adds a symbol to a symbol group by name (testing purposes)

extern "C" HRESULT CALLBACK addsymbol(CIDebugClient *client, PCSTR args)
{
    ExtensionCommandContext exc(client);
    unsigned frame = 0;
    SymbolGroup *symGroup = 0;
    std::string errorMessage;

    int token;
    const StringVector tokens = commandTokens<StringVector>(args, &token);
    std::string name;
    std::string iname;
    if (tokens.size() >= 2u && integerFromString(tokens.front(), &frame)) {
        symGroup = ExtensionContext::instance().symbolGroup(exc.symbols(), exc.threadId(), frame, &errorMessage);
        name = tokens.at(1);
        if (tokens.size() >= 3)
            iname = tokens.at(2);
    } else {
        errorMessage = singleLineUsage(commandDescriptions[CmdAddsymbol]);
    }
729
    if (symGroup != 0 && symGroup->addSymbol(std::string(), name, iname, &errorMessage))
730
        ExtensionContext::instance().report('R', token, 0, "addsymbol", "OK");
731
    else
732
        ExtensionContext::instance().report('N', token, 0, "addsymbol", errorMessage.c_str());
733 734 735
    return S_OK;
}

736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
extern "C" HRESULT CALLBACK addwatch(CIDebugClient *client, PCSTR argsIn)
{
    ExtensionCommandContext exc(client);

    std::string errorMessage;
    std::string watchExpression;
    std::string iname;

    int token = 0;
    bool success = false;
    do {
        StringList tokens = commandTokens<StringList>(argsIn, &token);
        if (tokens.size() != 2) {
            errorMessage = singleLineUsage(commandDescriptions[CmdAddWatch]);
            break;
        }
        iname = tokens.front();
        tokens.pop_front();
        watchExpression = tokens.front();

        WatchesSymbolGroup *watchesSymGroup = ExtensionContext::instance().watchesSymbolGroup(exc.symbols(), &errorMessage);
        if (!watchesSymGroup)
            break;
759
        success = watchesSymGroup->addWatch(exc.symbols(), iname, watchExpression, &errorMessage);
760 761
    } while (false);

762
    if (success)
763
        ExtensionContext::instance().report('R', token, 0, "addwatch", "Ok");
764
    else
765 766 767 768
        ExtensionContext::instance().report('N', token, 0, "addwatch", errorMessage.c_str());
    return S_OK;
}

769 770 771 772 773 774 775 776 777
// Extension command 'assign':
// Assign locals by iname: 'assign locals.x=5'

extern "C" HRESULT CALLBACK assign(CIDebugClient *client, PCSTR argsIn)
{
    ExtensionCommandContext exc(client);

    std::string errorMessage;
    bool success = false;
778
    AssignEncoding enc = AssignPlainValue;
779 780
    int token = 0;
    do {
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
        StringList tokens = commandTokens<StringList>(argsIn, &token);
        if (tokens.empty()) {
            errorMessage = singleLineUsage(commandDescriptions[CmdAssign]);
            break;
        }

        if (tokens.front() == "-h") {
            enc = AssignHexEncoded;
            tokens.pop_front();
        } else if (tokens.front() == "-u") {
            enc = AssignHexEncodedUtf16;
            tokens.pop_front();
        }

        if (tokens.empty()) {
            errorMessage = singleLineUsage(commandDescriptions[CmdAssign]);
            break;
        }

800
        // Parse 'assign locals.x=5'
801
        const std::string::size_type equalsPos = tokens.front().find('=');
802
        if (equalsPos == std::string::npos) {
803
            errorMessage = singleLineUsage(commandDescriptions[CmdAssign]);
804 805 806 807 808 809 810 811 812 813 814 815 816
            break;
        }
        const std::string iname = tokens.front().substr(0, equalsPos);
        const std::string value = tokens.front().substr(equalsPos + 1, tokens.front().size() - equalsPos - 1);
        // get the symbolgroup
        const int currentFrame = ExtensionContext::instance().symbolGroupFrame();
        if (currentFrame < 0) {
            errorMessage = "No current frame.";
            break;
        }
        SymbolGroup *symGroup = ExtensionContext::instance().symbolGroup(exc.symbols(), exc.threadId(), currentFrame, &errorMessage);
        if (!symGroup)
            break;
817 818 819
        success = symGroup->assign(iname, enc, value,
                                   SymbolGroupValueContext(exc.dataSpaces(), exc.symbols()),
                                   &errorMessage);
820 821
    } while (false);

822
    if (success)
823
        ExtensionContext::instance().report('R', token, 0, "assign", "Ok");
824
    else
825
        ExtensionContext::instance().report('N', token, 0, "assign", errorMessage.c_str());
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
    return S_OK;
}

// Extension command 'threads':
// List all thread info in GDBMI syntax

extern "C" HRESULT CALLBACK threads(CIDebugClient *client, PCSTR  argsIn)
{
    ExtensionCommandContext exc(client);
    std::string errorMessage;

    int token;
    commandTokens<StringList>(argsIn, &token);

    const std::string gdbmi = gdbmiThreadList(exc.systemObjects(),
                                              exc.symbols(),
                                              exc.control(),
                                              exc.advanced(),
                                              &errorMessage);
845
    if (gdbmi.empty())
846
        ExtensionContext::instance().report('N', token, 0, "threads", errorMessage.c_str());
847
    else
848
        ExtensionContext::instance().reportLong('R', token, "threads", gdbmi);
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    return S_OK;
}

// Extension command 'registers':
// List all registers in GDBMI syntax

extern "C" HRESULT CALLBACK registers(CIDebugClient *Client, PCSTR argsIn)
{
    ExtensionCommandContext exc(Client);
    std::string errorMessage;

    int token;
    const StringList tokens = commandTokens<StringList>(argsIn, &token);
    const bool humanReadable = !tokens.empty() && tokens.front() == "-h";
    const std::string regs = gdbmiRegisters(exc.registers(), exc.control(), humanReadable, IncludePseudoRegisters, &errorMessage);
864
    if (regs.empty())
865
        ExtensionContext::instance().report('N', token, 0, "registers", errorMessage.c_str());
866
    else
867
        ExtensionContext::instance().reportLong('R', token, "registers", regs);
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
    return S_OK;
}

// Extension command 'modules':
// List all modules in GDBMI syntax

extern "C" HRESULT CALLBACK modules(CIDebugClient *Client, PCSTR argsIn)
{
    ExtensionCommandContext exc(Client);
    std::string errorMessage;

    int token;
    const StringList tokens = commandTokens<StringList>(argsIn, &token);
    const bool humanReadable = !tokens.empty() && tokens.front() == "-h";
    const std::string modules = gdbmiModules(exc.symbols(), humanReadable, &errorMessage);
883
    if (modules.empty())
884
        ExtensionContext::instance().report('N', token, 0, "modules", errorMessage.c_str());
885
    else
886
        ExtensionContext::instance().reportLong('R', token, "modules", modules);
887 888 889 890 891
    return S_OK;
}

// Report stop of debuggee to Creator. This is hooked up as .idle_cmd command
// by the Creator engine to reliably get notified about stops.
892
extern "C" HRESULT CALLBACK idle(CIDebugClient *client, PCSTR)
893
{
894
    ExtensionContext::instance().notifyIdleCommand(client);
895 896 897
    return S_OK;
}

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
// Extension command 'setparameter':
// Parse a list of parameters: 'key=value'

extern "C" HRESULT CALLBACK setparameter(CIDebugClient *, PCSTR args)
{
    int token;
    StringVector tokens = commandTokens<StringVector>(args, &token);
    const size_t count = tokens.size();
    size_t success = 0;
    for (size_t i = 0; i < count; ++i) {
        const std::string &token = tokens.at(i);
        const std::string::size_type equalsPos = token.find('=');
        if (equalsPos != std::string::npos) {
            const std::string value = token.substr(equalsPos + 1, token.size() - 1 - equalsPos);
            if (!token.compare(0, equalsPos, "maxStringLength")) {
                if (integerFromString(value, &ExtensionContext::instance().parameters().maxStringLength))
                    ++success;
            } else if (!token.compare(0, equalsPos, "maxStackDepth")) {
                if (integerFromString(value, &ExtensionContext::instance().parameters().maxStackDepth))
                    ++success;
            }
        }
    }
    if (success != count)
        DebugPrint() << "Errors parsing setparameters command '" << args << '\'';
    return S_OK;
}

926 927 928 929 930
// Extension command 'help':
// Display version

extern "C" HRESULT CALLBACK help(CIDebugClient *, PCSTR)
{
931 932 933 934 935 936 937
    std::ostringstream str;
    str << "### Qt Creator CDB extension built " << __DATE__ << "\n\n";

    const size_t commandCount = sizeof(commandDescriptions)/sizeof(CommandDescription);
    std::copy(commandDescriptions, commandDescriptions + commandCount,
              std::ostream_iterator<CommandDescription>(str));
    dprintf("%s\n", str.str().c_str());
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
    return S_OK;
}

// Extension command 'memory':
// Display memory as base64

extern "C" HRESULT CALLBACK memory(CIDebugClient *Client, PCSTR argsIn)
{
    ExtensionCommandContext exc(Client);
    std::string errorMessage;
    std::string memory;

    int token;
    ULONG64 address = 0;
    ULONG length = 0;

    const StringVector tokens = commandTokens<StringVector>(argsIn, &token);
    if (tokens.size()  == 2
            && integerFromString(tokens.front(), &address)
            && integerFromString(tokens.at(1), &length)) {
        memory = memoryToBase64(exc.dataSpaces(), address, length, &errorMessage);
    } else {
960
        errorMessage = singleLineUsage(commandDescriptions[CmdMemory]);
961 962 963
    }

    if (memory.empty()) {
964
        ExtensionContext::instance().report('N', token, 0, "memory", errorMessage.c_str());
965
    } else {
966
        ExtensionContext::instance().reportLong('R', token, "memory", memory);
967
        if (!errorMessage.empty())
968
            ExtensionContext::instance().report('W', token, 0, "memory", errorMessage.c_str());
969 970 971 972
    }
    return S_OK;
}

973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
extern "C" HRESULT CALLBACK expression(CIDebugClient *Client, PCSTR argsIn)
{
    ExtensionCommandContext exc(Client);
    std::string errorMessage;
    LONG64 value = 0;
    int token = 0;

    do {
        const StringVector tokens = commandTokens<StringVector>(argsIn, &token);
        if (tokens.size()  != 1) {

            errorMessage = singleLineUsage(commandDescriptions[CmdExpression]);
            break;
        }
        if (!evaluateInt64Expression(exc.control(), tokens.front(), &value, &errorMessage))
            break;
    } while (false);

991
    if (errorMessage.empty())
992
        ExtensionContext::instance().reportLong('R', token, "expression", toString(value));
993
    else
994 995 996 997
        ExtensionContext::instance().report('N', token, 0, "expression", errorMessage.c_str());
    return S_OK;
}

998 999 1000 1001 1002 1003 1004 1005 1006 1007
// Extension command 'stack'
// Report stack correctly as 'k' does not list instruction pointer
// correctly.
extern "C" HRESULT CALLBACK stack(CIDebugClient *Client, PCSTR argsIn)
{
    ExtensionCommandContext exc(Client);
    std::string errorMessage;

    int token;
    bool humanReadable = false;
1008
    unsigned maxFrames = ExtensionContext::maxStackFrames;
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020

    StringList tokens = commandTokens<StringList>(argsIn, &token);
    if (!tokens.empty() && tokens.front() == "-h") {
         humanReadable = true;
         tokens.pop_front();
    }
    if (!tokens.empty())
        integerFromString(tokens.front(), &maxFrames);

    const std::string stack = gdbmiStack(exc.control(), exc.symbols(),
                                         maxFrames, humanReadable, &errorMessage);

1021
    if (stack.empty())
1022
        ExtensionContext::instance().report('N', token, 0, "stack", errorMessage.c_str());
1023
    else
1024
        ExtensionContext::instance().reportLong('R', token, "stack", stack);
1025 1026 1027
    return S_OK;
}

1028 1029 1030 1031 1032 1033 1034 1035 1036
// Extension command 'shutdownex' (shutdown is reserved):
// Unhook the output callbacks. This is normally done by the session
// inaccessible notification, however, this does not work for remote-controlled sessions.
extern "C" HRESULT CALLBACK shutdownex(CIDebugClient *, PCSTR)
{
    ExtensionContext::instance().unhookCallbacks();
    return S_OK;
}

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
extern "C" HRESULT CALLBACK widgetat(CIDebugClient *client, PCSTR argsIn)
{
    ExtensionCommandContext exc(client);
    int token = 0;
    std::string widgetAddress;
    std::string errorMessage;

    do {
        int x = -1;
        int y = -1;

        const StringVector tokens = commandTokens<StringVector>(argsIn, &token);
        if (tokens.size() != 2) {
            errorMessage = singleLineUsage(commandDescriptions[CmdWidgetAt]);
            break;
        }
        if (!integerFromString(tokens.front(), &x) || !integerFromString(tokens.at(1), &y)) {
            errorMessage = singleLineUsage(commandDescriptions[CmdWidgetAt]);
            break;
        }
        widgetAddress = widgetAt(SymbolGroupValueContext(exc.dataSpaces(), exc.symbols()),
                                 x, y, &errorMessage);
    } while (false);

1061
    if (widgetAddress.empty())
1062
        ExtensionContext::instance().report('N', token, 0, "widgetat", errorMessage.c_str());
1063
    else
1064 1065 1066 1067
        ExtensionContext::instance().reportLong('R', token, "widgetat", widgetAddress);
    return S_OK;
}

1068 1069 1070 1071 1072 1073
extern "C" HRESULT CALLBACK breakpoints(CIDebugClient *client, PCSTR argsIn)
{
    ExtensionCommandContext exc(client);
    int token;
    std::string errorMessage;
    bool humanReadable = false;
1074
    unsigned verbose = 0;
1075 1076 1077 1078 1079 1080 1081
    StringList tokens = commandTokens<StringList>(argsIn, &token);
    while (!tokens.empty() && tokens.front().size() == 2 && tokens.front().at(0) == '-') {
        switch (tokens.front().at(1)) {
        case 'h':
            humanReadable = true;
            break;
        case 'v':
1082
            verbose++;
1083 1084 1085 1086
            break;
        }
        tokens.pop_front();
    }
1087 1088
    const std::string bp = gdbmiBreakpoints(exc.control(), exc.symbols(), exc.dataSpaces(),
                                            humanReadable, verbose, &errorMessage);
1089
    if (bp.empty())
1090
        ExtensionContext::instance().report('N', token, 0, "breakpoints", errorMessage.c_str());
1091
    else
1092 1093 1094 1095
        ExtensionContext::instance().reportLong('R', token, "breakpoints", bp);
    return S_OK;
}

1096 1097
extern "C" HRESULT CALLBACK test(CIDebugClient *client, PCSTR argsIn)
{
1098
    enum Mode { Invalid, TestType, TestFixWatchExpression };
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
    ExtensionCommandContext exc(client);

    std::string testType;
    Mode mode = Invalid;
    int token = 0;
    StringList tokens = commandTokens<StringList>(argsIn, &token);
    // Parse away options
    while (!tokens.empty() && tokens.front().size() == 2 && tokens.front().at(0) == '-') {
        const char option = tokens.front().at(1);
        tokens.pop_front();
        switch (option) {
        case 'T':
            mode = TestType;
            if (!tokens.empty()) {
                testType = tokens.front();
                tokens.pop_front();
            }
            break;
1117 1118 1119 1120 1121 1122 1123
        case 'w':
            mode = TestFixWatchExpression;
            if (!tokens.empty()) {
                testType = tokens.front();
                tokens.pop_front();
            }
            break;
1124 1125 1126 1127 1128 1129 1130 1131
        } // case option
    }  // for options

    // Frame and iname
    if (mode == Invalid || testType.empty()) {
        ExtensionContext::instance().report('N', token, 0, "test", singleLineUsage(commandDescriptions[CmdTest]).c_str());
    } else {
        std::ostringstream str;
1132 1133 1134 1135 1136
        switch (mode) {
        case Invalid:
            break;
        case TestType: {
            const KnownType kt = knownType(testType, 0);
1137 1138 1139
            const std::string fixed = SymbolGroupValue::stripConst(testType);
            const unsigned size = SymbolGroupValue::sizeOf(fixed.c_str());
            str << '"' << testType <<  "\" (" << fixed << ") " << kt << " [";
1140
            formatKnownTypeFlags(str, kt);
1141
            str << "] size=" << size;
1142 1143 1144 1145 1146 1147
        }
            break;
        case TestFixWatchExpression:
            str << testType << " -> " << WatchesSymbolGroup::fixWatchExpression(exc.symbols(), testType);
            break;
        }
1148 1149 1150 1151 1152
        ExtensionContext::instance().reportLong('R', token, "test", str.str());
    }
    return S_OK;
}

1153 1154
// Hook for dumping Known Structs.
// Shows up in 'dv' (appended) as well as IDebugSymbolGroup::GetValueText.
1155

1156
extern "C"  HRESULT CALLBACK KnownStructOutput(ULONG Flag, ULONG64 Address, PSTR StructName, PSTR Buffer, PULONG BufferSize)
1157
{
1158
    static const char knownTypesC[] = "HWND__\0"; // implicitly adds terminating 0
1159
    if (Flag == DEBUG_KNOWN_STRUCT_GET_NAMES) {
1160
        memcpy(Buffer, knownTypesC, sizeof(knownTypesC));
1161 1162 1163
        return S_OK;
    }
    // Usually 260 chars buf
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
    if (!strcmp(StructName, "HWND__")) {
        // Dump a HWND. This is usually passed around as 'HWND*' with an (opaque) pointer value.
        // CDB dereferences it and passes it on here, which is why we get it as address.
        RECT rectangle;
        enum { BufSize = 1000 };
        char buf[BufSize];
        std::ostringstream str;

        HWND hwnd;
        memset(&rectangle, 0, sizeof(RECT));
        memset(&hwnd, 0, sizeof(HWND));
        // Coerce the address into a HWND (little endian)
        memcpy(&hwnd, &Address, SymbolGroupValue::pointerSize());
        // Dump geometry and class.
        if (GetWindowRect(hwnd, &rectangle) && GetClassNameA(hwnd, buf, BufSize))
            str << ' ' << rectangle.left << '+' << rectangle.top << '+'
                << (rectangle.right - rectangle.left) << 'x' << (rectangle.bottom - rectangle.top)
                << " '" << buf << '\'';
        // Check size for string + 1;
        const std::string rc = str.str();
        const ULONG requiredBufferLength = static_cast<ULONG>(rc.size()) + 1;
        if (requiredBufferLength >= *BufferSize) {
            *BufferSize = requiredBufferLength;
            return  S_FALSE;
        }
        strcpy(Buffer, rc.c_str());
    }

1192 1193
    return S_OK;
}