1 //===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "lldb/lldb-python.h" 11 12 #include <string> 13 #include <vector> 14 15 #include <getopt.h> 16 #include <stdlib.h> 17 18 #include "CommandObjectScript.h" 19 #include "lldb/Interpreter/CommandObjectRegexCommand.h" 20 21 #include "../Commands/CommandObjectApropos.h" 22 #include "../Commands/CommandObjectArgs.h" 23 #include "../Commands/CommandObjectBreakpoint.h" 24 #include "../Commands/CommandObjectDisassemble.h" 25 #include "../Commands/CommandObjectExpression.h" 26 #include "../Commands/CommandObjectFrame.h" 27 #include "../Commands/CommandObjectHelp.h" 28 #include "../Commands/CommandObjectLog.h" 29 #include "../Commands/CommandObjectMemory.h" 30 #include "../Commands/CommandObjectPlatform.h" 31 #include "../Commands/CommandObjectPlugin.h" 32 #include "../Commands/CommandObjectProcess.h" 33 #include "../Commands/CommandObjectQuit.h" 34 #include "../Commands/CommandObjectRegister.h" 35 #include "../Commands/CommandObjectSettings.h" 36 #include "../Commands/CommandObjectSource.h" 37 #include "../Commands/CommandObjectCommands.h" 38 #include "../Commands/CommandObjectSyntax.h" 39 #include "../Commands/CommandObjectTarget.h" 40 #include "../Commands/CommandObjectThread.h" 41 #include "../Commands/CommandObjectType.h" 42 #include "../Commands/CommandObjectVersion.h" 43 #include "../Commands/CommandObjectWatchpoint.h" 44 45 #include "lldb/Core/Debugger.h" 46 #include "lldb/Core/InputReader.h" 47 #include "lldb/Core/Log.h" 48 #include "lldb/Core/Stream.h" 49 #include "lldb/Core/Timer.h" 50 51 #include "lldb/Host/Host.h" 52 53 #include "lldb/Interpreter/Args.h" 54 #include "lldb/Interpreter/CommandReturnObject.h" 55 #include "lldb/Interpreter/CommandInterpreter.h" 56 #include "lldb/Interpreter/Options.h" 57 #include "lldb/Interpreter/ScriptInterpreterNone.h" 58 #include "lldb/Interpreter/ScriptInterpreterPython.h" 59 60 61 #include "lldb/Target/Process.h" 62 #include "lldb/Target/Thread.h" 63 #include "lldb/Target/TargetList.h" 64 65 #include "lldb/Utility/CleanUp.h" 66 67 using namespace lldb; 68 using namespace lldb_private; 69 70 71 static PropertyDefinition 72 g_properties[] = 73 { 74 { "expand-regex-aliases", OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, regular expression alias commands will show the expanded command that will be executed. This can be used to debug new regular expression alias commands." }, 75 { NULL , OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL } 76 }; 77 78 enum 79 { 80 ePropertyExpandRegexAliases = 0 81 }; 82 83 ConstString & 84 CommandInterpreter::GetStaticBroadcasterClass () 85 { 86 static ConstString class_name ("lldb.commandInterpreter"); 87 return class_name; 88 } 89 90 CommandInterpreter::CommandInterpreter 91 ( 92 Debugger &debugger, 93 ScriptLanguage script_language, 94 bool synchronous_execution 95 ) : 96 Broadcaster (&debugger, "lldb.command-interpreter"), 97 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))), 98 m_debugger (debugger), 99 m_synchronous_execution (synchronous_execution), 100 m_skip_lldbinit_files (false), 101 m_skip_app_init_files (false), 102 m_script_interpreter_ap (), 103 m_comment_char ('#'), 104 m_repeat_char ('!'), 105 m_batch_command_mode (false), 106 m_truncation_warning(eNoTruncation), 107 m_command_source_depth (0) 108 { 109 debugger.SetScriptLanguage (script_language); 110 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit"); 111 SetEventName (eBroadcastBitResetPrompt, "reset-prompt"); 112 SetEventName (eBroadcastBitQuitCommandReceived, "quit"); 113 CheckInWithManager (); 114 m_collection_sp->Initialize (g_properties); 115 } 116 117 bool 118 CommandInterpreter::GetExpandRegexAliases () const 119 { 120 const uint32_t idx = ePropertyExpandRegexAliases; 121 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0); 122 } 123 124 125 126 void 127 CommandInterpreter::Initialize () 128 { 129 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 130 131 CommandReturnObject result; 132 133 LoadCommandDictionary (); 134 135 // Set up some initial aliases. 136 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false); 137 if (cmd_obj_sp) 138 { 139 AddAlias ("q", cmd_obj_sp); 140 AddAlias ("exit", cmd_obj_sp); 141 } 142 143 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false); 144 if (cmd_obj_sp) 145 { 146 AddAlias ("attach", cmd_obj_sp); 147 } 148 149 cmd_obj_sp = GetCommandSPExact ("process detach",false); 150 if (cmd_obj_sp) 151 { 152 AddAlias ("detach", cmd_obj_sp); 153 } 154 155 cmd_obj_sp = GetCommandSPExact ("process continue", false); 156 if (cmd_obj_sp) 157 { 158 AddAlias ("c", cmd_obj_sp); 159 AddAlias ("continue", cmd_obj_sp); 160 } 161 162 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false); 163 if (cmd_obj_sp) 164 AddAlias ("b", cmd_obj_sp); 165 166 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false); 167 if (cmd_obj_sp) 168 AddAlias ("tbreak", cmd_obj_sp); 169 170 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false); 171 if (cmd_obj_sp) 172 { 173 AddAlias ("stepi", cmd_obj_sp); 174 AddAlias ("si", cmd_obj_sp); 175 } 176 177 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false); 178 if (cmd_obj_sp) 179 { 180 AddAlias ("nexti", cmd_obj_sp); 181 AddAlias ("ni", cmd_obj_sp); 182 } 183 184 cmd_obj_sp = GetCommandSPExact ("thread step-in", false); 185 if (cmd_obj_sp) 186 { 187 AddAlias ("s", cmd_obj_sp); 188 AddAlias ("step", cmd_obj_sp); 189 } 190 191 cmd_obj_sp = GetCommandSPExact ("thread step-over", false); 192 if (cmd_obj_sp) 193 { 194 AddAlias ("n", cmd_obj_sp); 195 AddAlias ("next", cmd_obj_sp); 196 } 197 198 cmd_obj_sp = GetCommandSPExact ("thread step-out", false); 199 if (cmd_obj_sp) 200 { 201 AddAlias ("finish", cmd_obj_sp); 202 } 203 204 cmd_obj_sp = GetCommandSPExact ("frame select", false); 205 if (cmd_obj_sp) 206 { 207 AddAlias ("f", cmd_obj_sp); 208 } 209 210 cmd_obj_sp = GetCommandSPExact ("thread select", false); 211 if (cmd_obj_sp) 212 { 213 AddAlias ("t", cmd_obj_sp); 214 } 215 216 cmd_obj_sp = GetCommandSPExact ("source list", false); 217 if (cmd_obj_sp) 218 { 219 AddAlias ("l", cmd_obj_sp); 220 AddAlias ("list", cmd_obj_sp); 221 } 222 223 cmd_obj_sp = GetCommandSPExact ("memory read", false); 224 if (cmd_obj_sp) 225 AddAlias ("x", cmd_obj_sp); 226 227 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false); 228 if (cmd_obj_sp) 229 AddAlias ("up", cmd_obj_sp); 230 231 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false); 232 if (cmd_obj_sp) 233 AddAlias ("down", cmd_obj_sp); 234 235 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false); 236 if (cmd_obj_sp) 237 AddAlias ("display", cmd_obj_sp); 238 239 cmd_obj_sp = GetCommandSPExact ("disassemble", false); 240 if (cmd_obj_sp) 241 AddAlias ("dis", cmd_obj_sp); 242 243 cmd_obj_sp = GetCommandSPExact ("disassemble", false); 244 if (cmd_obj_sp) 245 AddAlias ("di", cmd_obj_sp); 246 247 248 249 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false); 250 if (cmd_obj_sp) 251 AddAlias ("undisplay", cmd_obj_sp); 252 253 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false); 254 if (cmd_obj_sp) 255 AddAlias ("bt", cmd_obj_sp); 256 257 cmd_obj_sp = GetCommandSPExact ("target create", false); 258 if (cmd_obj_sp) 259 AddAlias ("file", cmd_obj_sp); 260 261 cmd_obj_sp = GetCommandSPExact ("target modules", false); 262 if (cmd_obj_sp) 263 AddAlias ("image", cmd_obj_sp); 264 265 266 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector); 267 268 cmd_obj_sp = GetCommandSPExact ("expression", false); 269 if (cmd_obj_sp) 270 { 271 AddAlias ("expr", cmd_obj_sp); 272 273 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp); 274 AddAlias ("p", cmd_obj_sp); 275 AddAlias ("print", cmd_obj_sp); 276 AddAlias ("call", cmd_obj_sp); 277 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp); 278 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp); 279 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp); 280 281 alias_arguments_vector_sp.reset (new OptionArgVector); 282 ProcessAliasOptionsArgs (cmd_obj_sp, "-O --", alias_arguments_vector_sp); 283 AddAlias ("po", cmd_obj_sp); 284 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp); 285 } 286 287 cmd_obj_sp = GetCommandSPExact ("process kill", false); 288 if (cmd_obj_sp) 289 { 290 AddAlias ("kill", cmd_obj_sp); 291 } 292 293 cmd_obj_sp = GetCommandSPExact ("process launch", false); 294 if (cmd_obj_sp) 295 { 296 alias_arguments_vector_sp.reset (new OptionArgVector); 297 #if defined (__arm__) 298 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp); 299 #else 300 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp); 301 #endif 302 AddAlias ("r", cmd_obj_sp); 303 AddAlias ("run", cmd_obj_sp); 304 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp); 305 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp); 306 } 307 308 cmd_obj_sp = GetCommandSPExact ("target symbols add", false); 309 if (cmd_obj_sp) 310 { 311 AddAlias ("add-dsym", cmd_obj_sp); 312 } 313 314 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false); 315 if (cmd_obj_sp) 316 { 317 alias_arguments_vector_sp.reset (new OptionArgVector); 318 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp); 319 AddAlias ("rbreak", cmd_obj_sp); 320 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp); 321 } 322 } 323 324 const char * 325 CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg) 326 { 327 // This function has not yet been implemented. 328 329 // Look for any embedded script command 330 // If found, 331 // get interpreter object from the command dictionary, 332 // call execute_one_command on it, 333 // get the results as a string, 334 // substitute that string for current stuff. 335 336 return arg; 337 } 338 339 340 void 341 CommandInterpreter::LoadCommandDictionary () 342 { 343 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); 344 345 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT *** 346 // 347 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref) 348 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use 349 // the cross-referencing stuff) are created!!! 350 // 351 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT *** 352 353 354 // Command objects that inherit from CommandObjectCrossref must be created before other command objects 355 // are created. This is so that when another command is created that needs to go into a crossref object, 356 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command 357 // objects into the CommandDictionary now, so they are ready for use when the other commands get created. 358 359 // Non-CommandObjectCrossref commands can now be created. 360 361 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage(); 362 363 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this)); 364 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this)); 365 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this)); 366 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this)); 367 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this)); 368 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this)); 369 // m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this)); 370 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this)); 371 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this)); 372 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this)); 373 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this)); 374 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this)); 375 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this)); 376 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this)); 377 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this)); 378 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this)); 379 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this)); 380 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language)); 381 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this)); 382 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this)); 383 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this)); 384 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this)); 385 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this)); 386 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this)); 387 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this)); 388 389 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"}, 390 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"}, 391 {"^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"}, 392 {"^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"}, 393 {"^(-.*)$", "breakpoint set %1"}, 394 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"}, 395 {"^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"}}; 396 397 size_t num_regexes = sizeof break_regexes/sizeof(char *[2]); 398 399 std::auto_ptr<CommandObjectRegexCommand> 400 break_regex_cmd_ap(new CommandObjectRegexCommand (*this, 401 "_regexp-break", 402 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.", 403 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2)); 404 405 if (break_regex_cmd_ap.get()) 406 { 407 bool success = true; 408 for (size_t i = 0; i < num_regexes; i++) 409 { 410 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]); 411 if (!success) 412 break; 413 } 414 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full"); 415 416 if (success) 417 { 418 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release()); 419 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp; 420 } 421 } 422 423 std::auto_ptr<CommandObjectRegexCommand> 424 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this, 425 "_regexp-tbreak", 426 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.", 427 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2)); 428 429 if (tbreak_regex_cmd_ap.get()) 430 { 431 bool success = true; 432 for (size_t i = 0; i < num_regexes; i++) 433 { 434 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer. 435 char buffer[1024]; 436 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o"); 437 assert (num_printed < 1024); 438 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer); 439 if (!success) 440 break; 441 } 442 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full"); 443 444 if (success) 445 { 446 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release()); 447 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp; 448 } 449 } 450 451 std::auto_ptr<CommandObjectRegexCommand> 452 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this, 453 "_regexp-attach", 454 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.", 455 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]", 2)); 456 if (attach_regex_cmd_ap.get()) 457 { 458 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") && 459 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach' 460 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") && 461 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) 462 { 463 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release()); 464 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp; 465 } 466 } 467 468 std::auto_ptr<CommandObjectRegexCommand> 469 down_regex_cmd_ap(new CommandObjectRegexCommand (*this, 470 "_regexp-down", 471 "Go down \"n\" frames in the stack (1 frame by default).", 472 "_regexp-down [n]", 2)); 473 if (down_regex_cmd_ap.get()) 474 { 475 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") && 476 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1")) 477 { 478 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release()); 479 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp; 480 } 481 } 482 483 std::auto_ptr<CommandObjectRegexCommand> 484 up_regex_cmd_ap(new CommandObjectRegexCommand (*this, 485 "_regexp-up", 486 "Go up \"n\" frames in the stack (1 frame by default).", 487 "_regexp-up [n]", 2)); 488 if (up_regex_cmd_ap.get()) 489 { 490 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") && 491 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) 492 { 493 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release()); 494 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp; 495 } 496 } 497 498 std::auto_ptr<CommandObjectRegexCommand> 499 display_regex_cmd_ap(new CommandObjectRegexCommand (*this, 500 "_regexp-display", 501 "Add an expression evaluation stop-hook.", 502 "_regexp-display expression", 2)); 503 if (display_regex_cmd_ap.get()) 504 { 505 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\"")) 506 { 507 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release()); 508 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp; 509 } 510 } 511 512 std::auto_ptr<CommandObjectRegexCommand> 513 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this, 514 "_regexp-undisplay", 515 "Remove an expression evaluation stop-hook.", 516 "_regexp-undisplay stop-hook-number", 2)); 517 if (undisplay_regex_cmd_ap.get()) 518 { 519 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1")) 520 { 521 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release()); 522 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp; 523 } 524 } 525 526 std::auto_ptr<CommandObjectRegexCommand> 527 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this, 528 "gdb-remote", 529 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.", 530 "gdb-remote [<hostname>:]<portnum>", 2)); 531 if (connect_gdb_remote_cmd_ap.get()) 532 { 533 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") && 534 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1")) 535 { 536 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release()); 537 m_command_dict[command_sp->GetCommandName ()] = command_sp; 538 } 539 } 540 541 std::auto_ptr<CommandObjectRegexCommand> 542 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this, 543 "kdp-remote", 544 "Connect to a remote KDP server. udp port 41139 is the default port number.", 545 "kdp-remote <hostname>[:<portnum>]", 2)); 546 if (connect_kdp_remote_cmd_ap.get()) 547 { 548 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") && 549 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) 550 { 551 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release()); 552 m_command_dict[command_sp->GetCommandName ()] = command_sp; 553 } 554 } 555 556 std::auto_ptr<CommandObjectRegexCommand> 557 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this, 558 "_regexp-bt", 559 "Show a backtrace. An optional argument is accepted; if that argument is a number, it specifies the number of frames to display. If that argument is 'all', full backtraces of all threads are displayed.", 560 "bt [<digit>|all]", 2)); 561 if (bt_regex_cmd_ap.get()) 562 { 563 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace 564 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and 565 // so now "bt 3" is the preferred form, in line with gdb. 566 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") && 567 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") && 568 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") && 569 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) 570 { 571 CommandObjectSP command_sp(bt_regex_cmd_ap.release()); 572 m_command_dict[command_sp->GetCommandName ()] = command_sp; 573 } 574 } 575 576 } 577 578 int 579 CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases, 580 StringList &matches) 581 { 582 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches); 583 584 if (include_aliases) 585 { 586 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches); 587 } 588 589 return matches.GetSize(); 590 } 591 592 CommandObjectSP 593 CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches) 594 { 595 CommandObject::CommandMap::iterator pos; 596 CommandObjectSP ret_val; 597 598 std::string cmd(cmd_cstr); 599 600 if (HasCommands()) 601 { 602 pos = m_command_dict.find(cmd); 603 if (pos != m_command_dict.end()) 604 ret_val = pos->second; 605 } 606 607 if (include_aliases && HasAliases()) 608 { 609 pos = m_alias_dict.find(cmd); 610 if (pos != m_alias_dict.end()) 611 ret_val = pos->second; 612 } 613 614 if (HasUserCommands()) 615 { 616 pos = m_user_dict.find(cmd); 617 if (pos != m_user_dict.end()) 618 ret_val = pos->second; 619 } 620 621 if (!exact && !ret_val) 622 { 623 // We will only get into here if we didn't find any exact matches. 624 625 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp; 626 627 StringList local_matches; 628 if (matches == NULL) 629 matches = &local_matches; 630 631 unsigned int num_cmd_matches = 0; 632 unsigned int num_alias_matches = 0; 633 unsigned int num_user_matches = 0; 634 635 // Look through the command dictionaries one by one, and if we get only one match from any of 636 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches. 637 638 if (HasCommands()) 639 { 640 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches); 641 } 642 643 if (num_cmd_matches == 1) 644 { 645 cmd.assign(matches->GetStringAtIndex(0)); 646 pos = m_command_dict.find(cmd); 647 if (pos != m_command_dict.end()) 648 real_match_sp = pos->second; 649 } 650 651 if (include_aliases && HasAliases()) 652 { 653 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches); 654 655 } 656 657 if (num_alias_matches == 1) 658 { 659 cmd.assign(matches->GetStringAtIndex (num_cmd_matches)); 660 pos = m_alias_dict.find(cmd); 661 if (pos != m_alias_dict.end()) 662 alias_match_sp = pos->second; 663 } 664 665 if (HasUserCommands()) 666 { 667 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches); 668 } 669 670 if (num_user_matches == 1) 671 { 672 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches)); 673 674 pos = m_user_dict.find (cmd); 675 if (pos != m_user_dict.end()) 676 user_match_sp = pos->second; 677 } 678 679 // If we got exactly one match, return that, otherwise return the match list. 680 681 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) 682 { 683 if (num_cmd_matches) 684 return real_match_sp; 685 else if (num_alias_matches) 686 return alias_match_sp; 687 else 688 return user_match_sp; 689 } 690 } 691 else if (matches && ret_val) 692 { 693 matches->AppendString (cmd_cstr); 694 } 695 696 697 return ret_val; 698 } 699 700 bool 701 CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace) 702 { 703 if (name && name[0]) 704 { 705 std::string name_sstr(name); 706 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end()); 707 if (found && !can_replace) 708 return false; 709 if (found && m_command_dict[name_sstr]->IsRemovable() == false) 710 return false; 711 m_command_dict[name_sstr] = cmd_sp; 712 return true; 713 } 714 return false; 715 } 716 717 bool 718 CommandInterpreter::AddUserCommand (std::string name, 719 const lldb::CommandObjectSP &cmd_sp, 720 bool can_replace) 721 { 722 if (!name.empty()) 723 { 724 725 const char* name_cstr = name.c_str(); 726 727 // do not allow replacement of internal commands 728 if (CommandExists(name_cstr)) 729 { 730 if (can_replace == false) 731 return false; 732 if (m_command_dict[name]->IsRemovable() == false) 733 return false; 734 } 735 736 if (UserCommandExists(name_cstr)) 737 { 738 if (can_replace == false) 739 return false; 740 if (m_user_dict[name]->IsRemovable() == false) 741 return false; 742 } 743 744 m_user_dict[name] = cmd_sp; 745 return true; 746 } 747 return false; 748 } 749 750 CommandObjectSP 751 CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases) 752 { 753 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command. 754 CommandObjectSP ret_val; // Possibly empty return value. 755 756 if (cmd_cstr == NULL) 757 return ret_val; 758 759 if (cmd_words.GetArgumentCount() == 1) 760 return GetCommandSP(cmd_cstr, include_aliases, true, NULL); 761 else 762 { 763 // We have a multi-word command (seemingly), so we need to do more work. 764 // First, get the cmd_obj_sp for the first word in the command. 765 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL); 766 if (cmd_obj_sp.get() != NULL) 767 { 768 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a 769 // command name), and find the appropriate sub-command SP for each command word.... 770 size_t end = cmd_words.GetArgumentCount(); 771 for (size_t j= 1; j < end; ++j) 772 { 773 if (cmd_obj_sp->IsMultiwordObject()) 774 { 775 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j)); 776 if (cmd_obj_sp.get() == NULL) 777 // The sub-command name was invalid. Fail and return the empty 'ret_val'. 778 return ret_val; 779 } 780 else 781 // We have more words in the command name, but we don't have a multiword object. Fail and return 782 // empty 'ret_val'. 783 return ret_val; 784 } 785 // We successfully looped through all the command words and got valid command objects for them. Assign the 786 // last object retrieved to 'ret_val'. 787 ret_val = cmd_obj_sp; 788 } 789 } 790 return ret_val; 791 } 792 793 CommandObject * 794 CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases) 795 { 796 return GetCommandSPExact (cmd_cstr, include_aliases).get(); 797 } 798 799 CommandObject * 800 CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches) 801 { 802 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get(); 803 804 // If we didn't find an exact match to the command string in the commands, look in 805 // the aliases. 806 807 if (command_obj == NULL) 808 { 809 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get(); 810 } 811 812 // Finally, if there wasn't an exact match among the aliases, look for an inexact match 813 // in both the commands and the aliases. 814 815 if (command_obj == NULL) 816 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get(); 817 818 return command_obj; 819 } 820 821 bool 822 CommandInterpreter::CommandExists (const char *cmd) 823 { 824 return m_command_dict.find(cmd) != m_command_dict.end(); 825 } 826 827 bool 828 CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp, 829 const char *options_args, 830 OptionArgVectorSP &option_arg_vector_sp) 831 { 832 bool success = true; 833 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 834 835 if (!options_args || (strlen (options_args) < 1)) 836 return true; 837 838 std::string options_string (options_args); 839 Args args (options_args); 840 CommandReturnObject result; 841 // Check to see if the command being aliased can take any command options. 842 Options *options = cmd_obj_sp->GetOptions (); 843 if (options) 844 { 845 // See if any options were specified as part of the alias; if so, handle them appropriately. 846 options->NotifyOptionParsingStarting (); 847 args.Unshift ("dummy_arg"); 848 args.ParseAliasOptions (*options, result, option_arg_vector, options_string); 849 args.Shift (); 850 if (result.Succeeded()) 851 options->VerifyPartialOptions (result); 852 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted) 853 { 854 result.AppendError ("Unable to create requested alias.\n"); 855 return false; 856 } 857 } 858 859 if (!options_string.empty()) 860 { 861 if (cmd_obj_sp->WantsRawCommandString ()) 862 option_arg_vector->push_back (OptionArgPair ("<argument>", 863 OptionArgValue (-1, 864 options_string))); 865 else 866 { 867 int argc = args.GetArgumentCount(); 868 for (size_t i = 0; i < argc; ++i) 869 if (strcmp (args.GetArgumentAtIndex (i), "") != 0) 870 option_arg_vector->push_back 871 (OptionArgPair ("<argument>", 872 OptionArgValue (-1, 873 std::string (args.GetArgumentAtIndex (i))))); 874 } 875 } 876 877 return success; 878 } 879 880 bool 881 CommandInterpreter::AliasExists (const char *cmd) 882 { 883 return m_alias_dict.find(cmd) != m_alias_dict.end(); 884 } 885 886 bool 887 CommandInterpreter::UserCommandExists (const char *cmd) 888 { 889 return m_user_dict.find(cmd) != m_user_dict.end(); 890 } 891 892 void 893 CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp) 894 { 895 command_obj_sp->SetIsAlias (true); 896 m_alias_dict[alias_name] = command_obj_sp; 897 } 898 899 bool 900 CommandInterpreter::RemoveAlias (const char *alias_name) 901 { 902 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name); 903 if (pos != m_alias_dict.end()) 904 { 905 m_alias_dict.erase(pos); 906 return true; 907 } 908 return false; 909 } 910 bool 911 CommandInterpreter::RemoveUser (const char *alias_name) 912 { 913 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name); 914 if (pos != m_user_dict.end()) 915 { 916 m_user_dict.erase(pos); 917 return true; 918 } 919 return false; 920 } 921 922 void 923 CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string) 924 { 925 help_string.Printf ("'%s", command_name); 926 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 927 928 if (option_arg_vector_sp) 929 { 930 OptionArgVector *options = option_arg_vector_sp.get(); 931 for (int i = 0; i < options->size(); ++i) 932 { 933 OptionArgPair cur_option = (*options)[i]; 934 std::string opt = cur_option.first; 935 OptionArgValue value_pair = cur_option.second; 936 std::string value = value_pair.second; 937 if (opt.compare("<argument>") == 0) 938 { 939 help_string.Printf (" %s", value.c_str()); 940 } 941 else 942 { 943 help_string.Printf (" %s", opt.c_str()); 944 if ((value.compare ("<no-argument>") != 0) 945 && (value.compare ("<need-argument") != 0)) 946 { 947 help_string.Printf (" %s", value.c_str()); 948 } 949 } 950 } 951 } 952 953 help_string.Printf ("'"); 954 } 955 956 size_t 957 CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict) 958 { 959 CommandObject::CommandMap::const_iterator pos; 960 CommandObject::CommandMap::const_iterator end = dict.end(); 961 size_t max_len = 0; 962 963 for (pos = dict.begin(); pos != end; ++pos) 964 { 965 size_t len = pos->first.size(); 966 if (max_len < len) 967 max_len = len; 968 } 969 return max_len; 970 } 971 972 void 973 CommandInterpreter::GetHelp (CommandReturnObject &result, 974 uint32_t cmd_types) 975 { 976 CommandObject::CommandMap::const_iterator pos; 977 uint32_t max_len = FindLongestCommandWord (m_command_dict); 978 979 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin ) 980 { 981 982 result.AppendMessage("The following is a list of built-in, permanent debugger commands:"); 983 result.AppendMessage(""); 984 985 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) 986 { 987 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(), 988 max_len); 989 } 990 result.AppendMessage(""); 991 992 } 993 994 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases )) 995 { 996 result.AppendMessage("The following is a list of your current command abbreviations " 997 "(see 'help command alias' for more info):"); 998 result.AppendMessage(""); 999 max_len = FindLongestCommandWord (m_alias_dict); 1000 1001 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos) 1002 { 1003 StreamString sstr; 1004 StreamString translation_and_help; 1005 std::string entry_name = pos->first; 1006 std::string second_entry = pos->second.get()->GetCommandName(); 1007 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr); 1008 1009 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp()); 1010 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", 1011 translation_and_help.GetData(), max_len); 1012 } 1013 result.AppendMessage(""); 1014 } 1015 1016 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef )) 1017 { 1018 result.AppendMessage ("The following is a list of your current user-defined commands:"); 1019 result.AppendMessage(""); 1020 max_len = FindLongestCommandWord (m_user_dict); 1021 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) 1022 { 1023 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(), 1024 max_len); 1025 } 1026 result.AppendMessage(""); 1027 } 1028 1029 result.AppendMessage("For more information on any particular command, try 'help <command-name>'."); 1030 } 1031 1032 CommandObject * 1033 CommandInterpreter::GetCommandObjectForCommand (std::string &command_string) 1034 { 1035 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will 1036 // eventually be invoked by the given command line. 1037 1038 CommandObject *cmd_obj = NULL; 1039 std::string white_space (" \t\v"); 1040 size_t start = command_string.find_first_not_of (white_space); 1041 size_t end = 0; 1042 bool done = false; 1043 while (!done) 1044 { 1045 if (start != std::string::npos) 1046 { 1047 // Get the next word from command_string. 1048 end = command_string.find_first_of (white_space, start); 1049 if (end == std::string::npos) 1050 end = command_string.size(); 1051 std::string cmd_word = command_string.substr (start, end - start); 1052 1053 if (cmd_obj == NULL) 1054 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid 1055 // command or alias. 1056 cmd_obj = GetCommandObject (cmd_word.c_str()); 1057 else if (cmd_obj->IsMultiwordObject ()) 1058 { 1059 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object. 1060 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str()); 1061 if (sub_cmd_obj) 1062 cmd_obj = sub_cmd_obj; 1063 else // cmd_word was not a valid sub-command word, so we are donee 1064 done = true; 1065 } 1066 else 1067 // We have a cmd_obj and it is not a multi-word object, so we are done. 1068 done = true; 1069 1070 // If we didn't find a valid command object, or our command object is not a multi-word object, or 1071 // we are at the end of the command_string, then we are done. Otherwise, find the start of the 1072 // next word. 1073 1074 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size()) 1075 done = true; 1076 else 1077 start = command_string.find_first_not_of (white_space, end); 1078 } 1079 else 1080 // Unable to find any more words. 1081 done = true; 1082 } 1083 1084 if (end == command_string.size()) 1085 command_string.clear(); 1086 else 1087 command_string = command_string.substr(end); 1088 1089 return cmd_obj; 1090 } 1091 1092 static const char *k_white_space = " \t\v"; 1093 static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"; 1094 static void 1095 StripLeadingSpaces (std::string &s) 1096 { 1097 if (!s.empty()) 1098 { 1099 size_t pos = s.find_first_not_of (k_white_space); 1100 if (pos == std::string::npos) 1101 s.clear(); 1102 else if (pos == 0) 1103 return; 1104 s.erase (0, pos); 1105 } 1106 } 1107 1108 static size_t 1109 FindArgumentTerminator (const std::string &s) 1110 { 1111 const size_t s_len = s.size(); 1112 size_t offset = 0; 1113 while (offset < s_len) 1114 { 1115 size_t pos = s.find ("--", offset); 1116 if (pos == std::string::npos) 1117 break; 1118 if (pos > 0) 1119 { 1120 if (isspace(s[pos-1])) 1121 { 1122 // Check if the string ends "\s--" (where \s is a space character) 1123 // or if we have "\s--\s". 1124 if ((pos + 2 >= s_len) || isspace(s[pos+2])) 1125 { 1126 return pos; 1127 } 1128 } 1129 } 1130 offset = pos + 2; 1131 } 1132 return std::string::npos; 1133 } 1134 1135 static bool 1136 ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char "e_char) 1137 { 1138 command.clear(); 1139 suffix.clear(); 1140 StripLeadingSpaces (command_string); 1141 1142 bool result = false; 1143 quote_char = '\0'; 1144 1145 if (!command_string.empty()) 1146 { 1147 const char first_char = command_string[0]; 1148 if (first_char == '\'' || first_char == '"') 1149 { 1150 quote_char = first_char; 1151 const size_t end_quote_pos = command_string.find (quote_char, 1); 1152 if (end_quote_pos == std::string::npos) 1153 { 1154 command.swap (command_string); 1155 command_string.erase (); 1156 } 1157 else 1158 { 1159 command.assign (command_string, 1, end_quote_pos - 1); 1160 if (end_quote_pos + 1 < command_string.size()) 1161 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1)); 1162 else 1163 command_string.erase (); 1164 } 1165 } 1166 else 1167 { 1168 const size_t first_space_pos = command_string.find_first_of (k_white_space); 1169 if (first_space_pos == std::string::npos) 1170 { 1171 command.swap (command_string); 1172 command_string.erase(); 1173 } 1174 else 1175 { 1176 command.assign (command_string, 0, first_space_pos); 1177 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos)); 1178 } 1179 } 1180 result = true; 1181 } 1182 1183 1184 if (!command.empty()) 1185 { 1186 // actual commands can't start with '-' or '_' 1187 if (command[0] != '-' && command[0] != '_') 1188 { 1189 size_t pos = command.find_first_not_of(k_valid_command_chars); 1190 if (pos > 0 && pos != std::string::npos) 1191 { 1192 suffix.assign (command.begin() + pos, command.end()); 1193 command.erase (pos); 1194 } 1195 } 1196 } 1197 1198 return result; 1199 } 1200 1201 CommandObject * 1202 CommandInterpreter::BuildAliasResult (const char *alias_name, 1203 std::string &raw_input_string, 1204 std::string &alias_result, 1205 CommandReturnObject &result) 1206 { 1207 CommandObject *alias_cmd_obj = NULL; 1208 Args cmd_args (raw_input_string.c_str()); 1209 alias_cmd_obj = GetCommandObject (alias_name); 1210 StreamString result_str; 1211 1212 if (alias_cmd_obj) 1213 { 1214 std::string alias_name_str = alias_name; 1215 if ((cmd_args.GetArgumentCount() == 0) 1216 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)) 1217 cmd_args.Unshift (alias_name); 1218 1219 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ()); 1220 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 1221 1222 if (option_arg_vector_sp.get()) 1223 { 1224 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 1225 1226 for (int i = 0; i < option_arg_vector->size(); ++i) 1227 { 1228 OptionArgPair option_pair = (*option_arg_vector)[i]; 1229 OptionArgValue value_pair = option_pair.second; 1230 int value_type = value_pair.first; 1231 std::string option = option_pair.first; 1232 std::string value = value_pair.second; 1233 if (option.compare ("<argument>") == 0) 1234 result_str.Printf (" %s", value.c_str()); 1235 else 1236 { 1237 result_str.Printf (" %s", option.c_str()); 1238 if (value_type != optional_argument) 1239 result_str.Printf (" "); 1240 if (value.compare ("<no_argument>") != 0) 1241 { 1242 int index = GetOptionArgumentPosition (value.c_str()); 1243 if (index == 0) 1244 result_str.Printf ("%s", value.c_str()); 1245 else if (index >= cmd_args.GetArgumentCount()) 1246 { 1247 1248 result.AppendErrorWithFormat 1249 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n", 1250 index); 1251 result.SetStatus (eReturnStatusFailed); 1252 return alias_cmd_obj; 1253 } 1254 else 1255 { 1256 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index)); 1257 if (strpos != std::string::npos) 1258 raw_input_string = raw_input_string.erase (strpos, 1259 strlen (cmd_args.GetArgumentAtIndex (index))); 1260 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index)); 1261 } 1262 } 1263 } 1264 } 1265 } 1266 1267 alias_result = result_str.GetData(); 1268 } 1269 return alias_cmd_obj; 1270 } 1271 1272 Error 1273 CommandInterpreter::PreprocessCommand (std::string &command) 1274 { 1275 // The command preprocessor needs to do things to the command 1276 // line before any parsing of arguments or anything else is done. 1277 // The only current stuff that gets proprocessed is anyting enclosed 1278 // in backtick ('`') characters is evaluated as an expression and 1279 // the result of the expression must be a scalar that can be substituted 1280 // into the command. An example would be: 1281 // (lldb) memory read `$rsp + 20` 1282 Error error; // Error for any expressions that might not evaluate 1283 size_t start_backtick; 1284 size_t pos = 0; 1285 while ((start_backtick = command.find ('`', pos)) != std::string::npos) 1286 { 1287 if (start_backtick > 0 && command[start_backtick-1] == '\\') 1288 { 1289 // The backtick was preceeded by a '\' character, remove the slash 1290 // and don't treat the backtick as the start of an expression 1291 command.erase(start_backtick-1, 1); 1292 // No need to add one to start_backtick since we just deleted a char 1293 pos = start_backtick; 1294 } 1295 else 1296 { 1297 const size_t expr_content_start = start_backtick + 1; 1298 const size_t end_backtick = command.find ('`', expr_content_start); 1299 if (end_backtick == std::string::npos) 1300 return error; 1301 else if (end_backtick == expr_content_start) 1302 { 1303 // Empty expression (two backticks in a row) 1304 command.erase (start_backtick, 2); 1305 } 1306 else 1307 { 1308 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start); 1309 1310 ExecutionContext exe_ctx(GetExecutionContext()); 1311 Target *target = exe_ctx.GetTargetPtr(); 1312 // Get a dummy target to allow for calculator mode while processing backticks. 1313 // This also helps break the infinite loop caused when target is null. 1314 if (!target) 1315 target = Host::GetDummyTarget(GetDebugger()).get(); 1316 if (target) 1317 { 1318 ValueObjectSP expr_result_valobj_sp; 1319 1320 EvaluateExpressionOptions options; 1321 options.SetCoerceToId(false) 1322 .SetUnwindOnError(true) 1323 .SetKeepInMemory(false) 1324 .SetRunOthers(true) 1325 .SetTimeoutUsec(0); 1326 1327 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(), 1328 exe_ctx.GetFramePtr(), 1329 expr_result_valobj_sp, 1330 options); 1331 1332 if (expr_result == eExecutionCompleted) 1333 { 1334 Scalar scalar; 1335 if (expr_result_valobj_sp->ResolveValue (scalar)) 1336 { 1337 command.erase (start_backtick, end_backtick - start_backtick + 1); 1338 StreamString value_strm; 1339 const bool show_type = false; 1340 scalar.GetValue (&value_strm, show_type); 1341 size_t value_string_size = value_strm.GetSize(); 1342 if (value_string_size) 1343 { 1344 command.insert (start_backtick, value_strm.GetData(), value_string_size); 1345 pos = start_backtick + value_string_size; 1346 continue; 1347 } 1348 else 1349 { 1350 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str()); 1351 } 1352 } 1353 else 1354 { 1355 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str()); 1356 } 1357 } 1358 else 1359 { 1360 if (expr_result_valobj_sp) 1361 error = expr_result_valobj_sp->GetError(); 1362 if (error.Success()) 1363 { 1364 1365 switch (expr_result) 1366 { 1367 case eExecutionSetupError: 1368 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str()); 1369 break; 1370 case eExecutionCompleted: 1371 break; 1372 case eExecutionDiscarded: 1373 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str()); 1374 break; 1375 case eExecutionInterrupted: 1376 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str()); 1377 break; 1378 case eExecutionTimedOut: 1379 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str()); 1380 break; 1381 } 1382 } 1383 } 1384 } 1385 } 1386 if (error.Fail()) 1387 break; 1388 } 1389 } 1390 return error; 1391 } 1392 1393 1394 bool 1395 CommandInterpreter::HandleCommand (const char *command_line, 1396 LazyBool lazy_add_to_history, 1397 CommandReturnObject &result, 1398 ExecutionContext *override_context, 1399 bool repeat_on_empty_command, 1400 bool no_context_switching) 1401 1402 { 1403 1404 bool done = false; 1405 CommandObject *cmd_obj = NULL; 1406 bool wants_raw_input = false; 1407 std::string command_string (command_line); 1408 std::string original_command_string (command_line); 1409 1410 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS)); 1411 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line); 1412 1413 // Make a scoped cleanup object that will clear the crash description string 1414 // on exit of this function. 1415 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription); 1416 1417 if (log) 1418 log->Printf ("Processing command: %s", command_line); 1419 1420 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line); 1421 1422 if (!no_context_switching) 1423 UpdateExecutionContext (override_context); 1424 1425 // <rdar://problem/11328896> 1426 bool add_to_history; 1427 if (lazy_add_to_history == eLazyBoolCalculate) 1428 add_to_history = (m_command_source_depth == 0); 1429 else 1430 add_to_history = (lazy_add_to_history == eLazyBoolYes); 1431 1432 bool empty_command = false; 1433 bool comment_command = false; 1434 if (command_string.empty()) 1435 empty_command = true; 1436 else 1437 { 1438 const char *k_space_characters = "\t\n\v\f\r "; 1439 1440 size_t non_space = command_string.find_first_not_of (k_space_characters); 1441 // Check for empty line or comment line (lines whose first 1442 // non-space character is the comment character for this interpreter) 1443 if (non_space == std::string::npos) 1444 empty_command = true; 1445 else if (command_string[non_space] == m_comment_char) 1446 comment_command = true; 1447 else if (command_string[non_space] == m_repeat_char) 1448 { 1449 const char *history_string = FindHistoryString (command_string.c_str() + non_space); 1450 if (history_string == NULL) 1451 { 1452 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str()); 1453 result.SetStatus(eReturnStatusFailed); 1454 return false; 1455 } 1456 add_to_history = false; 1457 command_string = history_string; 1458 original_command_string = history_string; 1459 } 1460 } 1461 1462 if (empty_command) 1463 { 1464 if (repeat_on_empty_command) 1465 { 1466 if (m_command_history.empty()) 1467 { 1468 result.AppendError ("empty command"); 1469 result.SetStatus(eReturnStatusFailed); 1470 return false; 1471 } 1472 else 1473 { 1474 command_line = m_repeat_command.c_str(); 1475 command_string = command_line; 1476 original_command_string = command_line; 1477 if (m_repeat_command.empty()) 1478 { 1479 result.AppendErrorWithFormat("No auto repeat.\n"); 1480 result.SetStatus (eReturnStatusFailed); 1481 return false; 1482 } 1483 } 1484 add_to_history = false; 1485 } 1486 else 1487 { 1488 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1489 return true; 1490 } 1491 } 1492 else if (comment_command) 1493 { 1494 result.SetStatus (eReturnStatusSuccessFinishNoResult); 1495 return true; 1496 } 1497 1498 1499 Error error (PreprocessCommand (command_string)); 1500 1501 if (error.Fail()) 1502 { 1503 result.AppendError (error.AsCString()); 1504 result.SetStatus(eReturnStatusFailed); 1505 return false; 1506 } 1507 // Phase 1. 1508 1509 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object 1510 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that 1511 // the user could have specified an alias, and in translating the alias there may also be command options and/or 1512 // even data (including raw text strings) that need to be found and inserted into the command line as part of 1513 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command 1514 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions & 1515 // replacements taken care of; 3). whether or not the Execute function wants raw input or not. 1516 1517 StreamString revised_command_line; 1518 size_t actual_cmd_name_len = 0; 1519 std::string next_word; 1520 StringList matches; 1521 while (!done) 1522 { 1523 char quote_char = '\0'; 1524 std::string suffix; 1525 ExtractCommand (command_string, next_word, suffix, quote_char); 1526 if (cmd_obj == NULL) 1527 { 1528 if (AliasExists (next_word.c_str())) 1529 { 1530 std::string alias_result; 1531 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result); 1532 revised_command_line.Printf ("%s", alias_result.c_str()); 1533 if (cmd_obj) 1534 { 1535 wants_raw_input = cmd_obj->WantsRawCommandString (); 1536 actual_cmd_name_len = strlen (cmd_obj->GetCommandName()); 1537 } 1538 } 1539 else 1540 { 1541 cmd_obj = GetCommandObject (next_word.c_str(), &matches); 1542 if (cmd_obj) 1543 { 1544 actual_cmd_name_len += next_word.length(); 1545 revised_command_line.Printf ("%s", next_word.c_str()); 1546 wants_raw_input = cmd_obj->WantsRawCommandString (); 1547 } 1548 else 1549 { 1550 revised_command_line.Printf ("%s", next_word.c_str()); 1551 } 1552 } 1553 } 1554 else 1555 { 1556 if (cmd_obj->IsMultiwordObject ()) 1557 { 1558 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str()); 1559 if (sub_cmd_obj) 1560 { 1561 actual_cmd_name_len += next_word.length() + 1; 1562 revised_command_line.Printf (" %s", next_word.c_str()); 1563 cmd_obj = sub_cmd_obj; 1564 wants_raw_input = cmd_obj->WantsRawCommandString (); 1565 } 1566 else 1567 { 1568 if (quote_char) 1569 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char); 1570 else 1571 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str()); 1572 done = true; 1573 } 1574 } 1575 else 1576 { 1577 if (quote_char) 1578 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char); 1579 else 1580 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str()); 1581 done = true; 1582 } 1583 } 1584 1585 if (cmd_obj == NULL) 1586 { 1587 uint32_t num_matches = matches.GetSize(); 1588 if (matches.GetSize() > 1) { 1589 std::string error_msg; 1590 error_msg.assign ("Ambiguous command '"); 1591 error_msg.append(next_word.c_str()); 1592 error_msg.append ("'."); 1593 1594 error_msg.append (" Possible matches:"); 1595 1596 for (uint32_t i = 0; i < num_matches; ++i) { 1597 error_msg.append ("\n\t"); 1598 error_msg.append (matches.GetStringAtIndex(i)); 1599 } 1600 error_msg.append ("\n"); 1601 result.AppendRawError (error_msg.c_str(), error_msg.size()); 1602 } else { 1603 // We didn't have only one match, otherwise we wouldn't get here. 1604 assert(num_matches == 0); 1605 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str()); 1606 } 1607 result.SetStatus (eReturnStatusFailed); 1608 return false; 1609 } 1610 1611 if (cmd_obj->IsMultiwordObject ()) 1612 { 1613 if (!suffix.empty()) 1614 { 1615 1616 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n", 1617 next_word.c_str(), 1618 suffix.c_str()); 1619 result.SetStatus (eReturnStatusFailed); 1620 return false; 1621 } 1622 } 1623 else 1624 { 1625 // If we found a normal command, we are done 1626 done = true; 1627 if (!suffix.empty()) 1628 { 1629 switch (suffix[0]) 1630 { 1631 case '/': 1632 // GDB format suffixes 1633 { 1634 Options *command_options = cmd_obj->GetOptions(); 1635 if (command_options && command_options->SupportsLongOption("gdb-format")) 1636 { 1637 std::string gdb_format_option ("--gdb-format="); 1638 gdb_format_option += (suffix.c_str() + 1); 1639 1640 bool inserted = false; 1641 std::string &cmd = revised_command_line.GetString(); 1642 size_t arg_terminator_idx = FindArgumentTerminator (cmd); 1643 if (arg_terminator_idx != std::string::npos) 1644 { 1645 // Insert the gdb format option before the "--" that terminates options 1646 gdb_format_option.append(1,' '); 1647 cmd.insert(arg_terminator_idx, gdb_format_option); 1648 inserted = true; 1649 } 1650 1651 if (!inserted) 1652 revised_command_line.Printf (" %s", gdb_format_option.c_str()); 1653 1654 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos) 1655 revised_command_line.PutCString (" --"); 1656 } 1657 else 1658 { 1659 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n", 1660 cmd_obj->GetCommandName()); 1661 result.SetStatus (eReturnStatusFailed); 1662 return false; 1663 } 1664 } 1665 break; 1666 1667 default: 1668 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n", 1669 suffix.c_str()); 1670 result.SetStatus (eReturnStatusFailed); 1671 return false; 1672 1673 } 1674 } 1675 } 1676 if (command_string.length() == 0) 1677 done = true; 1678 1679 } 1680 1681 if (!command_string.empty()) 1682 revised_command_line.Printf (" %s", command_string.c_str()); 1683 1684 // End of Phase 1. 1685 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command 1686 // specified was valid; revised_command_line contains the complete command line (including command name(s)), 1687 // fully translated with all substitutions & translations taken care of (still in raw text format); and 1688 // wants_raw_input specifies whether the Execute method expects raw input or not. 1689 1690 1691 if (log) 1692 { 1693 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>"); 1694 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData()); 1695 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False"); 1696 } 1697 1698 // Phase 2. 1699 // Take care of things like setting up the history command & calling the appropriate Execute method on the 1700 // CommandObject, with the appropriate arguments. 1701 1702 if (cmd_obj != NULL) 1703 { 1704 if (add_to_history) 1705 { 1706 Args command_args (revised_command_line.GetData()); 1707 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0); 1708 if (repeat_command != NULL) 1709 m_repeat_command.assign(repeat_command); 1710 else 1711 m_repeat_command.assign(original_command_string.c_str()); 1712 1713 // Don't keep pushing the same command onto the history... 1714 if (m_command_history.empty() || m_command_history.back() != original_command_string) 1715 m_command_history.push_back (original_command_string); 1716 } 1717 1718 command_string = revised_command_line.GetData(); 1719 std::string command_name (cmd_obj->GetCommandName()); 1720 std::string remainder; 1721 if (actual_cmd_name_len < command_string.length()) 1722 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter 1723 // than cmd_obj->GetCommandName(), because name completion 1724 // allows users to enter short versions of the names, 1725 // e.g. 'br s' for 'breakpoint set'. 1726 1727 // Remove any initial spaces 1728 std::string white_space (" \t\v"); 1729 size_t pos = remainder.find_first_not_of (white_space); 1730 if (pos != 0 && pos != std::string::npos) 1731 remainder.erase(0, pos); 1732 1733 if (log) 1734 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str()); 1735 1736 cmd_obj->Execute (remainder.c_str(), result); 1737 } 1738 else 1739 { 1740 // We didn't find the first command object, so complete the first argument. 1741 Args command_args (revised_command_line.GetData()); 1742 StringList matches; 1743 int num_matches; 1744 int cursor_index = 0; 1745 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0)); 1746 bool word_complete; 1747 num_matches = HandleCompletionMatches (command_args, 1748 cursor_index, 1749 cursor_char_position, 1750 0, 1751 -1, 1752 word_complete, 1753 matches); 1754 1755 if (num_matches > 0) 1756 { 1757 std::string error_msg; 1758 error_msg.assign ("ambiguous command '"); 1759 error_msg.append(command_args.GetArgumentAtIndex(0)); 1760 error_msg.append ("'."); 1761 1762 error_msg.append (" Possible completions:"); 1763 for (int i = 0; i < num_matches; i++) 1764 { 1765 error_msg.append ("\n\t"); 1766 error_msg.append (matches.GetStringAtIndex (i)); 1767 } 1768 error_msg.append ("\n"); 1769 result.AppendRawError (error_msg.c_str(), error_msg.size()); 1770 } 1771 else 1772 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0)); 1773 1774 result.SetStatus (eReturnStatusFailed); 1775 } 1776 1777 if (log) 1778 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed")); 1779 1780 return result.Succeeded(); 1781 } 1782 1783 int 1784 CommandInterpreter::HandleCompletionMatches (Args &parsed_line, 1785 int &cursor_index, 1786 int &cursor_char_position, 1787 int match_start_point, 1788 int max_return_elements, 1789 bool &word_complete, 1790 StringList &matches) 1791 { 1792 int num_command_matches = 0; 1793 bool look_for_subcommand = false; 1794 1795 // For any of the command completions a unique match will be a complete word. 1796 word_complete = true; 1797 1798 if (cursor_index == -1) 1799 { 1800 // We got nothing on the command line, so return the list of commands 1801 bool include_aliases = true; 1802 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches); 1803 } 1804 else if (cursor_index == 0) 1805 { 1806 // The cursor is in the first argument, so just do a lookup in the dictionary. 1807 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches); 1808 num_command_matches = matches.GetSize(); 1809 1810 if (num_command_matches == 1 1811 && cmd_obj && cmd_obj->IsMultiwordObject() 1812 && matches.GetStringAtIndex(0) != NULL 1813 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0) 1814 { 1815 look_for_subcommand = true; 1816 num_command_matches = 0; 1817 matches.DeleteStringAtIndex(0); 1818 parsed_line.AppendArgument (""); 1819 cursor_index++; 1820 cursor_char_position = 0; 1821 } 1822 } 1823 1824 if (cursor_index > 0 || look_for_subcommand) 1825 { 1826 // We are completing further on into a commands arguments, so find the command and tell it 1827 // to complete the command. 1828 // First see if there is a matching initial command: 1829 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0)); 1830 if (command_object == NULL) 1831 { 1832 return 0; 1833 } 1834 else 1835 { 1836 parsed_line.Shift(); 1837 cursor_index--; 1838 num_command_matches = command_object->HandleCompletion (parsed_line, 1839 cursor_index, 1840 cursor_char_position, 1841 match_start_point, 1842 max_return_elements, 1843 word_complete, 1844 matches); 1845 } 1846 } 1847 1848 return num_command_matches; 1849 1850 } 1851 1852 int 1853 CommandInterpreter::HandleCompletion (const char *current_line, 1854 const char *cursor, 1855 const char *last_char, 1856 int match_start_point, 1857 int max_return_elements, 1858 StringList &matches) 1859 { 1860 // We parse the argument up to the cursor, so the last argument in parsed_line is 1861 // the one containing the cursor, and the cursor is after the last character. 1862 1863 Args parsed_line(current_line, last_char - current_line); 1864 Args partial_parsed_line(current_line, cursor - current_line); 1865 1866 // Don't complete comments, and if the line we are completing is just the history repeat character, 1867 // substitute the appropriate history line. 1868 const char *first_arg = parsed_line.GetArgumentAtIndex(0); 1869 if (first_arg) 1870 { 1871 if (first_arg[0] == m_comment_char) 1872 return 0; 1873 else if (first_arg[0] == m_repeat_char) 1874 { 1875 const char *history_string = FindHistoryString (first_arg); 1876 if (history_string != NULL) 1877 { 1878 matches.Clear(); 1879 matches.InsertStringAtIndex(0, history_string); 1880 return -2; 1881 } 1882 else 1883 return 0; 1884 1885 } 1886 } 1887 1888 1889 int num_args = partial_parsed_line.GetArgumentCount(); 1890 int cursor_index = partial_parsed_line.GetArgumentCount() - 1; 1891 int cursor_char_position; 1892 1893 if (cursor_index == -1) 1894 cursor_char_position = 0; 1895 else 1896 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index)); 1897 1898 if (cursor > current_line && cursor[-1] == ' ') 1899 { 1900 // We are just after a space. If we are in an argument, then we will continue 1901 // parsing, but if we are between arguments, then we have to complete whatever the next 1902 // element would be. 1903 // We can distinguish the two cases because if we are in an argument (e.g. because the space is 1904 // protected by a quote) then the space will also be in the parsed argument... 1905 1906 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index); 1907 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ') 1908 { 1909 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"'); 1910 cursor_index++; 1911 cursor_char_position = 0; 1912 } 1913 } 1914 1915 int num_command_matches; 1916 1917 matches.Clear(); 1918 1919 // Only max_return_elements == -1 is supported at present: 1920 assert (max_return_elements == -1); 1921 bool word_complete; 1922 num_command_matches = HandleCompletionMatches (parsed_line, 1923 cursor_index, 1924 cursor_char_position, 1925 match_start_point, 1926 max_return_elements, 1927 word_complete, 1928 matches); 1929 1930 if (num_command_matches <= 0) 1931 return num_command_matches; 1932 1933 if (num_args == 0) 1934 { 1935 // If we got an empty string, insert nothing. 1936 matches.InsertStringAtIndex(0, ""); 1937 } 1938 else 1939 { 1940 // Now figure out if there is a common substring, and if so put that in element 0, otherwise 1941 // put an empty string in element 0. 1942 std::string command_partial_str; 1943 if (cursor_index >= 0) 1944 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), 1945 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position); 1946 1947 std::string common_prefix; 1948 matches.LongestCommonPrefix (common_prefix); 1949 int partial_name_len = command_partial_str.size(); 1950 1951 // If we matched a unique single command, add a space... 1952 // Only do this if the completer told us this was a complete word, however... 1953 if (num_command_matches == 1 && word_complete) 1954 { 1955 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index); 1956 if (quote_char != '\0') 1957 common_prefix.push_back(quote_char); 1958 1959 common_prefix.push_back(' '); 1960 } 1961 common_prefix.erase (0, partial_name_len); 1962 matches.InsertStringAtIndex(0, common_prefix.c_str()); 1963 } 1964 return num_command_matches; 1965 } 1966 1967 1968 CommandInterpreter::~CommandInterpreter () 1969 { 1970 } 1971 1972 const char * 1973 CommandInterpreter::GetPrompt () 1974 { 1975 return m_debugger.GetPrompt(); 1976 } 1977 1978 void 1979 CommandInterpreter::SetPrompt (const char *new_prompt) 1980 { 1981 m_debugger.SetPrompt (new_prompt); 1982 } 1983 1984 size_t 1985 CommandInterpreter::GetConfirmationInputReaderCallback 1986 ( 1987 void *baton, 1988 InputReader &reader, 1989 lldb::InputReaderAction action, 1990 const char *bytes, 1991 size_t bytes_len 1992 ) 1993 { 1994 File &out_file = reader.GetDebugger().GetOutputFile(); 1995 bool *response_ptr = (bool *) baton; 1996 1997 switch (action) 1998 { 1999 case eInputReaderActivate: 2000 if (out_file.IsValid()) 2001 { 2002 if (reader.GetPrompt()) 2003 { 2004 out_file.Printf ("%s", reader.GetPrompt()); 2005 out_file.Flush (); 2006 } 2007 } 2008 break; 2009 2010 case eInputReaderDeactivate: 2011 break; 2012 2013 case eInputReaderReactivate: 2014 if (out_file.IsValid() && reader.GetPrompt()) 2015 { 2016 out_file.Printf ("%s", reader.GetPrompt()); 2017 out_file.Flush (); 2018 } 2019 break; 2020 2021 case eInputReaderAsynchronousOutputWritten: 2022 break; 2023 2024 case eInputReaderGotToken: 2025 if (bytes_len == 0) 2026 { 2027 reader.SetIsDone(true); 2028 } 2029 else if (bytes[0] == 'y' || bytes[0] == 'Y') 2030 { 2031 *response_ptr = true; 2032 reader.SetIsDone(true); 2033 } 2034 else if (bytes[0] == 'n' || bytes[0] == 'N') 2035 { 2036 *response_ptr = false; 2037 reader.SetIsDone(true); 2038 } 2039 else 2040 { 2041 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt()) 2042 { 2043 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt()); 2044 out_file.Flush (); 2045 } 2046 } 2047 break; 2048 2049 case eInputReaderInterrupt: 2050 case eInputReaderEndOfFile: 2051 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action 2052 reader.SetIsDone (true); 2053 break; 2054 2055 case eInputReaderDone: 2056 break; 2057 } 2058 2059 return bytes_len; 2060 2061 } 2062 2063 bool 2064 CommandInterpreter::Confirm (const char *message, bool default_answer) 2065 { 2066 // Check AutoConfirm first: 2067 if (m_debugger.GetAutoConfirm()) 2068 return default_answer; 2069 2070 InputReaderSP reader_sp (new InputReader(GetDebugger())); 2071 bool response = default_answer; 2072 if (reader_sp) 2073 { 2074 std::string prompt(message); 2075 prompt.append(": ["); 2076 if (default_answer) 2077 prompt.append ("Y/n] "); 2078 else 2079 prompt.append ("y/N] "); 2080 2081 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback, 2082 &response, // baton 2083 eInputReaderGranularityLine, // token size, to pass to callback function 2084 NULL, // end token 2085 prompt.c_str(), // prompt 2086 true)); // echo input 2087 if (err.Success()) 2088 { 2089 GetDebugger().PushInputReader (reader_sp); 2090 } 2091 reader_sp->WaitOnReaderIsDone(); 2092 } 2093 return response; 2094 } 2095 2096 2097 void 2098 CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type) 2099 { 2100 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true); 2101 2102 if (cmd_obj_sp) 2103 { 2104 CommandObject *cmd_obj = cmd_obj_sp.get(); 2105 if (cmd_obj->IsCrossRefObject ()) 2106 cmd_obj->AddObject (object_type); 2107 } 2108 } 2109 2110 OptionArgVectorSP 2111 CommandInterpreter::GetAliasOptions (const char *alias_name) 2112 { 2113 OptionArgMap::iterator pos; 2114 OptionArgVectorSP ret_val; 2115 2116 std::string alias (alias_name); 2117 2118 if (HasAliasOptions()) 2119 { 2120 pos = m_alias_options.find (alias); 2121 if (pos != m_alias_options.end()) 2122 ret_val = pos->second; 2123 } 2124 2125 return ret_val; 2126 } 2127 2128 void 2129 CommandInterpreter::RemoveAliasOptions (const char *alias_name) 2130 { 2131 OptionArgMap::iterator pos = m_alias_options.find(alias_name); 2132 if (pos != m_alias_options.end()) 2133 { 2134 m_alias_options.erase (pos); 2135 } 2136 } 2137 2138 void 2139 CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp) 2140 { 2141 m_alias_options[alias_name] = option_arg_vector_sp; 2142 } 2143 2144 bool 2145 CommandInterpreter::HasCommands () 2146 { 2147 return (!m_command_dict.empty()); 2148 } 2149 2150 bool 2151 CommandInterpreter::HasAliases () 2152 { 2153 return (!m_alias_dict.empty()); 2154 } 2155 2156 bool 2157 CommandInterpreter::HasUserCommands () 2158 { 2159 return (!m_user_dict.empty()); 2160 } 2161 2162 bool 2163 CommandInterpreter::HasAliasOptions () 2164 { 2165 return (!m_alias_options.empty()); 2166 } 2167 2168 void 2169 CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj, 2170 const char *alias_name, 2171 Args &cmd_args, 2172 std::string &raw_input_string, 2173 CommandReturnObject &result) 2174 { 2175 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); 2176 2177 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString(); 2178 2179 // Make sure that the alias name is the 0th element in cmd_args 2180 std::string alias_name_str = alias_name; 2181 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0) 2182 cmd_args.Unshift (alias_name); 2183 2184 Args new_args (alias_cmd_obj->GetCommandName()); 2185 if (new_args.GetArgumentCount() == 2) 2186 new_args.Shift(); 2187 2188 if (option_arg_vector_sp.get()) 2189 { 2190 if (wants_raw_input) 2191 { 2192 // We have a command that both has command options and takes raw input. Make *sure* it has a 2193 // " -- " in the right place in the raw_input_string. 2194 size_t pos = raw_input_string.find(" -- "); 2195 if (pos == std::string::npos) 2196 { 2197 // None found; assume it goes at the beginning of the raw input string 2198 raw_input_string.insert (0, " -- "); 2199 } 2200 } 2201 2202 OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); 2203 int old_size = cmd_args.GetArgumentCount(); 2204 std::vector<bool> used (old_size + 1, false); 2205 2206 used[0] = true; 2207 2208 for (int i = 0; i < option_arg_vector->size(); ++i) 2209 { 2210 OptionArgPair option_pair = (*option_arg_vector)[i]; 2211 OptionArgValue value_pair = option_pair.second; 2212 int value_type = value_pair.first; 2213 std::string option = option_pair.first; 2214 std::string value = value_pair.second; 2215 if (option.compare ("<argument>") == 0) 2216 { 2217 if (!wants_raw_input 2218 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice 2219 new_args.AppendArgument (value.c_str()); 2220 } 2221 else 2222 { 2223 if (value_type != optional_argument) 2224 new_args.AppendArgument (option.c_str()); 2225 if (value.compare ("<no-argument>") != 0) 2226 { 2227 int index = GetOptionArgumentPosition (value.c_str()); 2228 if (index == 0) 2229 { 2230 // value was NOT a positional argument; must be a real value 2231 if (value_type != optional_argument) 2232 new_args.AppendArgument (value.c_str()); 2233 else 2234 { 2235 char buffer[255]; 2236 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str()); 2237 new_args.AppendArgument (buffer); 2238 } 2239 2240 } 2241 else if (index >= cmd_args.GetArgumentCount()) 2242 { 2243 result.AppendErrorWithFormat 2244 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n", 2245 index); 2246 result.SetStatus (eReturnStatusFailed); 2247 return; 2248 } 2249 else 2250 { 2251 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string 2252 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index)); 2253 if (strpos != std::string::npos) 2254 { 2255 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index))); 2256 } 2257 2258 if (value_type != optional_argument) 2259 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index)); 2260 else 2261 { 2262 char buffer[255]; 2263 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(), 2264 cmd_args.GetArgumentAtIndex (index)); 2265 new_args.AppendArgument (buffer); 2266 } 2267 used[index] = true; 2268 } 2269 } 2270 } 2271 } 2272 2273 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j) 2274 { 2275 if (!used[j] && !wants_raw_input) 2276 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j)); 2277 } 2278 2279 cmd_args.Clear(); 2280 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector()); 2281 } 2282 else 2283 { 2284 result.SetStatus (eReturnStatusSuccessFinishNoResult); 2285 // This alias was not created with any options; nothing further needs to be done, unless it is a command that 2286 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw 2287 // input string. 2288 if (wants_raw_input) 2289 { 2290 cmd_args.Clear(); 2291 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector()); 2292 } 2293 return; 2294 } 2295 2296 result.SetStatus (eReturnStatusSuccessFinishNoResult); 2297 return; 2298 } 2299 2300 2301 int 2302 CommandInterpreter::GetOptionArgumentPosition (const char *in_string) 2303 { 2304 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position 2305 // of zero. 2306 2307 char *cptr = (char *) in_string; 2308 2309 // Does it start with '%' 2310 if (cptr[0] == '%') 2311 { 2312 ++cptr; 2313 2314 // Is the rest of it entirely digits? 2315 if (isdigit (cptr[0])) 2316 { 2317 const char *start = cptr; 2318 while (isdigit (cptr[0])) 2319 ++cptr; 2320 2321 // We've gotten to the end of the digits; are we at the end of the string? 2322 if (cptr[0] == '\0') 2323 position = atoi (start); 2324 } 2325 } 2326 2327 return position; 2328 } 2329 2330 void 2331 CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result) 2332 { 2333 FileSpec init_file; 2334 if (in_cwd) 2335 { 2336 // In the current working directory we don't load any program specific 2337 // .lldbinit files, we only look for a "./.lldbinit" file. 2338 if (m_skip_lldbinit_files) 2339 return; 2340 2341 init_file.SetFile ("./.lldbinit", true); 2342 } 2343 else 2344 { 2345 // If we aren't looking in the current working directory we are looking 2346 // in the home directory. We will first see if there is an application 2347 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a 2348 // "-" and the name of the program. If this file doesn't exist, we fall 2349 // back to just the "~/.lldbinit" file. We also obey any requests to not 2350 // load the init files. 2351 const char *init_file_path = "~/.lldbinit"; 2352 2353 if (m_skip_app_init_files == false) 2354 { 2355 FileSpec program_file_spec (Host::GetProgramFileSpec()); 2356 const char *program_name = program_file_spec.GetFilename().AsCString(); 2357 2358 if (program_name) 2359 { 2360 char program_init_file_name[PATH_MAX]; 2361 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name); 2362 init_file.SetFile (program_init_file_name, true); 2363 if (!init_file.Exists()) 2364 init_file.Clear(); 2365 } 2366 } 2367 2368 if (!init_file && !m_skip_lldbinit_files) 2369 init_file.SetFile (init_file_path, true); 2370 } 2371 2372 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting 2373 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details). 2374 2375 if (init_file.Exists()) 2376 { 2377 ExecutionContext *exe_ctx = NULL; // We don't have any context yet. 2378 bool stop_on_continue = true; 2379 bool stop_on_error = false; 2380 bool echo_commands = false; 2381 bool print_results = false; 2382 2383 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result); 2384 } 2385 else 2386 { 2387 // nothing to be done if the file doesn't exist 2388 result.SetStatus(eReturnStatusSuccessFinishNoResult); 2389 } 2390 } 2391 2392 PlatformSP 2393 CommandInterpreter::GetPlatform (bool prefer_target_platform) 2394 { 2395 PlatformSP platform_sp; 2396 if (prefer_target_platform) 2397 { 2398 ExecutionContext exe_ctx(GetExecutionContext()); 2399 Target *target = exe_ctx.GetTargetPtr(); 2400 if (target) 2401 platform_sp = target->GetPlatform(); 2402 } 2403 2404 if (!platform_sp) 2405 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform(); 2406 return platform_sp; 2407 } 2408 2409 void 2410 CommandInterpreter::HandleCommands (const StringList &commands, 2411 ExecutionContext *override_context, 2412 bool stop_on_continue, 2413 bool stop_on_error, 2414 bool echo_commands, 2415 bool print_results, 2416 LazyBool add_to_history, 2417 CommandReturnObject &result) 2418 { 2419 size_t num_lines = commands.GetSize(); 2420 2421 // If we are going to continue past a "continue" then we need to run the commands synchronously. 2422 // Make sure you reset this value anywhere you return from the function. 2423 2424 bool old_async_execution = m_debugger.GetAsyncExecution(); 2425 2426 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will 2427 // cause series of commands that change the context, then do an operation that relies on that context to fail. 2428 2429 if (override_context != NULL) 2430 UpdateExecutionContext (override_context); 2431 2432 if (!stop_on_continue) 2433 { 2434 m_debugger.SetAsyncExecution (false); 2435 } 2436 2437 for (int idx = 0; idx < num_lines; idx++) 2438 { 2439 const char *cmd = commands.GetStringAtIndex(idx); 2440 if (cmd[0] == '\0') 2441 continue; 2442 2443 if (echo_commands) 2444 { 2445 result.AppendMessageWithFormat ("%s %s\n", 2446 GetPrompt(), 2447 cmd); 2448 } 2449 2450 CommandReturnObject tmp_result; 2451 // If override_context is not NULL, pass no_context_switching = true for 2452 // HandleCommand() since we updated our context already. 2453 bool success = HandleCommand(cmd, add_to_history, tmp_result, 2454 NULL, /* override_context */ 2455 true, /* repeat_on_empty_command */ 2456 override_context != NULL /* no_context_switching */); 2457 2458 if (print_results) 2459 { 2460 if (tmp_result.Succeeded()) 2461 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData()); 2462 } 2463 2464 if (!success || !tmp_result.Succeeded()) 2465 { 2466 const char *error_msg = tmp_result.GetErrorData(); 2467 if (error_msg == NULL || error_msg[0] == '\0') 2468 error_msg = "<unknown error>.\n"; 2469 if (stop_on_error) 2470 { 2471 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s", 2472 idx, cmd, error_msg); 2473 result.SetStatus (eReturnStatusFailed); 2474 m_debugger.SetAsyncExecution (old_async_execution); 2475 return; 2476 } 2477 else if (print_results) 2478 { 2479 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s", 2480 idx + 1, 2481 cmd, 2482 error_msg); 2483 } 2484 } 2485 2486 if (result.GetImmediateOutputStream()) 2487 result.GetImmediateOutputStream()->Flush(); 2488 2489 if (result.GetImmediateErrorStream()) 2490 result.GetImmediateErrorStream()->Flush(); 2491 2492 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution 2493 // could be running (for instance in Breakpoint Commands. 2494 // So we check the return value to see if it is has running in it. 2495 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) 2496 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) 2497 { 2498 if (stop_on_continue) 2499 { 2500 // If we caused the target to proceed, and we're going to stop in that case, set the 2501 // status in our real result before returning. This is an error if the continue was not the 2502 // last command in the set of commands to be run. 2503 if (idx != num_lines - 1) 2504 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n", 2505 idx + 1, cmd); 2506 else 2507 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd); 2508 2509 result.SetStatus(tmp_result.GetStatus()); 2510 m_debugger.SetAsyncExecution (old_async_execution); 2511 2512 return; 2513 } 2514 } 2515 2516 } 2517 2518 result.SetStatus (eReturnStatusSuccessFinishResult); 2519 m_debugger.SetAsyncExecution (old_async_execution); 2520 2521 return; 2522 } 2523 2524 void 2525 CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file, 2526 ExecutionContext *context, 2527 bool stop_on_continue, 2528 bool stop_on_error, 2529 bool echo_command, 2530 bool print_result, 2531 LazyBool add_to_history, 2532 CommandReturnObject &result) 2533 { 2534 if (cmd_file.Exists()) 2535 { 2536 bool success; 2537 StringList commands; 2538 success = commands.ReadFileLines(cmd_file); 2539 if (!success) 2540 { 2541 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString()); 2542 result.SetStatus (eReturnStatusFailed); 2543 return; 2544 } 2545 m_command_source_depth++; 2546 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result); 2547 m_command_source_depth--; 2548 } 2549 else 2550 { 2551 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n", 2552 cmd_file.GetFilename().AsCString()); 2553 result.SetStatus (eReturnStatusFailed); 2554 return; 2555 } 2556 } 2557 2558 ScriptInterpreter * 2559 CommandInterpreter::GetScriptInterpreter (bool can_create) 2560 { 2561 if (m_script_interpreter_ap.get() != NULL) 2562 return m_script_interpreter_ap.get(); 2563 2564 if (!can_create) 2565 return NULL; 2566 2567 // <rdar://problem/11751427> 2568 // we need to protect the initialization of the script interpreter 2569 // otherwise we could end up with two threads both trying to create 2570 // their instance of it, and for some languages (e.g. Python) 2571 // this is a bulletproof recipe for disaster! 2572 // this needs to be a function-level static because multiple Debugger instances living in the same process 2573 // still need to be isolated and not try to initialize Python concurrently 2574 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive); 2575 Mutex::Locker interpreter_lock(g_interpreter_mutex); 2576 2577 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 2578 if (log) 2579 log->Printf("Initializing the ScriptInterpreter now\n"); 2580 2581 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage(); 2582 switch (script_lang) 2583 { 2584 case eScriptLanguagePython: 2585 #ifndef LLDB_DISABLE_PYTHON 2586 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this)); 2587 break; 2588 #else 2589 // Fall through to the None case when python is disabled 2590 #endif 2591 case eScriptLanguageNone: 2592 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this)); 2593 break; 2594 }; 2595 2596 return m_script_interpreter_ap.get(); 2597 } 2598 2599 2600 2601 bool 2602 CommandInterpreter::GetSynchronous () 2603 { 2604 return m_synchronous_execution; 2605 } 2606 2607 void 2608 CommandInterpreter::SetSynchronous (bool value) 2609 { 2610 m_synchronous_execution = value; 2611 } 2612 2613 void 2614 CommandInterpreter::OutputFormattedHelpText (Stream &strm, 2615 const char *word_text, 2616 const char *separator, 2617 const char *help_text, 2618 uint32_t max_word_len) 2619 { 2620 const uint32_t max_columns = m_debugger.GetTerminalWidth(); 2621 2622 int indent_size = max_word_len + strlen (separator) + 2; 2623 2624 strm.IndentMore (indent_size); 2625 2626 StreamString text_strm; 2627 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text); 2628 2629 size_t len = text_strm.GetSize(); 2630 const char *text = text_strm.GetData(); 2631 if (text[len - 1] == '\n') 2632 { 2633 text_strm.EOL(); 2634 len = text_strm.GetSize(); 2635 } 2636 2637 if (len < max_columns) 2638 { 2639 // Output it as a single line. 2640 strm.Printf ("%s", text); 2641 } 2642 else 2643 { 2644 // We need to break it up into multiple lines. 2645 bool first_line = true; 2646 int text_width; 2647 int start = 0; 2648 int end = start; 2649 int final_end = strlen (text); 2650 int sub_len; 2651 2652 while (end < final_end) 2653 { 2654 if (first_line) 2655 text_width = max_columns - 1; 2656 else 2657 text_width = max_columns - indent_size - 1; 2658 2659 // Don't start the 'text' on a space, since we're already outputting the indentation. 2660 if (!first_line) 2661 { 2662 while ((start < final_end) && (text[start] == ' ')) 2663 start++; 2664 } 2665 2666 end = start + text_width; 2667 if (end > final_end) 2668 end = final_end; 2669 else 2670 { 2671 // If we're not at the end of the text, make sure we break the line on white space. 2672 while (end > start 2673 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n') 2674 end--; 2675 assert (end > 0); 2676 } 2677 2678 sub_len = end - start; 2679 if (start != 0) 2680 strm.EOL(); 2681 if (!first_line) 2682 strm.Indent(); 2683 else 2684 first_line = false; 2685 assert (start <= final_end); 2686 assert (start + sub_len <= final_end); 2687 if (sub_len > 0) 2688 strm.Write (text + start, sub_len); 2689 start = end + 1; 2690 } 2691 } 2692 strm.EOL(); 2693 strm.IndentLess(indent_size); 2694 } 2695 2696 void 2697 CommandInterpreter::OutputHelpText (Stream &strm, 2698 const char *word_text, 2699 const char *separator, 2700 const char *help_text, 2701 uint32_t max_word_len) 2702 { 2703 int indent_size = max_word_len + strlen (separator) + 2; 2704 2705 strm.IndentMore (indent_size); 2706 2707 StreamString text_strm; 2708 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text); 2709 2710 const uint32_t max_columns = m_debugger.GetTerminalWidth(); 2711 2712 size_t len = text_strm.GetSize(); 2713 const char *text = text_strm.GetData(); 2714 2715 uint32_t chars_left = max_columns; 2716 2717 for (uint32_t i = 0; i < len; i++) 2718 { 2719 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n') 2720 { 2721 chars_left = max_columns - indent_size; 2722 strm.EOL(); 2723 strm.Indent(); 2724 } 2725 else 2726 { 2727 strm.PutChar(text[i]); 2728 chars_left--; 2729 } 2730 2731 } 2732 2733 strm.EOL(); 2734 strm.IndentLess(indent_size); 2735 } 2736 2737 void 2738 CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found, 2739 StringList &commands_help) 2740 { 2741 CommandObject::CommandMap::const_iterator pos; 2742 2743 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) 2744 { 2745 const char *command_name = pos->first.c_str(); 2746 CommandObject *cmd_obj = pos->second.get(); 2747 2748 if (cmd_obj->HelpTextContainsWord (search_word)) 2749 { 2750 commands_found.AppendString (command_name); 2751 commands_help.AppendString (cmd_obj->GetHelp()); 2752 } 2753 2754 if (cmd_obj->IsMultiwordObject()) 2755 cmd_obj->AproposAllSubCommands (command_name, 2756 search_word, 2757 commands_found, 2758 commands_help); 2759 2760 } 2761 } 2762 2763 2764 void 2765 CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context) 2766 { 2767 if (override_context != NULL) 2768 { 2769 m_exe_ctx_ref = *override_context; 2770 } 2771 else 2772 { 2773 const bool adopt_selected = true; 2774 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected); 2775 } 2776 } 2777 2778 void 2779 CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const 2780 { 2781 DumpHistory (stream, 0, count - 1); 2782 } 2783 2784 void 2785 CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const 2786 { 2787 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1); 2788 for (size_t i = start; i < last_idx; i++) 2789 { 2790 if (!m_command_history[i].empty()) 2791 { 2792 stream.Indent(); 2793 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str()); 2794 } 2795 } 2796 } 2797 2798 const char * 2799 CommandInterpreter::FindHistoryString (const char *input_str) const 2800 { 2801 if (input_str[0] != m_repeat_char) 2802 return NULL; 2803 if (input_str[1] == '-') 2804 { 2805 bool success; 2806 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success); 2807 if (!success) 2808 return NULL; 2809 if (idx > m_command_history.size()) 2810 return NULL; 2811 idx = m_command_history.size() - idx; 2812 return m_command_history[idx].c_str(); 2813 2814 } 2815 else if (input_str[1] == m_repeat_char) 2816 { 2817 if (m_command_history.empty()) 2818 return NULL; 2819 else 2820 return m_command_history.back().c_str(); 2821 } 2822 else 2823 { 2824 bool success; 2825 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success); 2826 if (!success) 2827 return NULL; 2828 if (idx >= m_command_history.size()) 2829 return NULL; 2830 return m_command_history[idx].c_str(); 2831 } 2832 } 2833