1 //===-- CommandObjectTarget.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 "CommandObjectTarget.h"
11 
12 // C Includes
13 #include <errno.h>
14 
15 // C++ Includes
16 // Other libraries and framework includes
17 // Project includes
18 #include "lldb/Interpreter/Args.h"
19 #include "lldb/Core/Debugger.h"
20 #include "lldb/Core/InputReader.h"
21 #include "lldb/Core/Section.h"
22 #include "lldb/Core/State.h"
23 #include "lldb/Core/Timer.h"
24 #include "lldb/Core/ValueObjectVariable.h"
25 #include "lldb/Interpreter/CommandInterpreter.h"
26 #include "lldb/Interpreter/CommandReturnObject.h"
27 #include "lldb/Interpreter/Options.h"
28 #include "lldb/Interpreter/OptionGroupArchitecture.h"
29 #include "lldb/Interpreter/OptionGroupFile.h"
30 #include "lldb/Interpreter/OptionGroupVariable.h"
31 #include "lldb/Interpreter/OptionGroupPlatform.h"
32 #include "lldb/Interpreter/OptionGroupUInt64.h"
33 #include "lldb/Interpreter/OptionGroupUUID.h"
34 #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"
35 #include "lldb/Symbol/LineTable.h"
36 #include "lldb/Symbol/ObjectFile.h"
37 #include "lldb/Symbol/SymbolFile.h"
38 #include "lldb/Symbol/SymbolVendor.h"
39 #include "lldb/Symbol/VariableList.h"
40 #include "lldb/Target/Process.h"
41 #include "lldb/Target/StackFrame.h"
42 #include "lldb/Target/Thread.h"
43 #include "lldb/Target/ThreadSpec.h"
44 
45 using namespace lldb;
46 using namespace lldb_private;
47 
48 
49 
50 static void
51 DumpTargetInfo (uint32_t target_idx, Target *target, const char *prefix_cstr, bool show_stopped_process_status, Stream &strm)
52 {
53     const ArchSpec &target_arch = target->GetArchitecture();
54 
55     ModuleSP exe_module_sp (target->GetExecutableModule ());
56     char exe_path[PATH_MAX];
57     bool exe_valid = false;
58     if (exe_module_sp)
59         exe_valid = exe_module_sp->GetFileSpec().GetPath (exe_path, sizeof(exe_path));
60 
61     if (!exe_valid)
62         ::strcpy (exe_path, "<none>");
63 
64     strm.Printf ("%starget #%u: %s", prefix_cstr ? prefix_cstr : "", target_idx, exe_path);
65 
66     uint32_t properties = 0;
67     if (target_arch.IsValid())
68     {
69         strm.Printf ("%sarch=%s", properties++ > 0 ? ", " : " ( ", target_arch.GetTriple().str().c_str());
70         properties++;
71     }
72     PlatformSP platform_sp (target->GetPlatform());
73     if (platform_sp)
74         strm.Printf ("%splatform=%s", properties++ > 0 ? ", " : " ( ", platform_sp->GetName());
75 
76     ProcessSP process_sp (target->GetProcessSP());
77     bool show_process_status = false;
78     if (process_sp)
79     {
80         lldb::pid_t pid = process_sp->GetID();
81         StateType state = process_sp->GetState();
82         if (show_stopped_process_status)
83             show_process_status = StateIsStoppedState(state);
84         const char *state_cstr = StateAsCString (state);
85         if (pid != LLDB_INVALID_PROCESS_ID)
86             strm.Printf ("%spid=%i", properties++ > 0 ? ", " : " ( ", pid);
87         strm.Printf ("%sstate=%s", properties++ > 0 ? ", " : " ( ", state_cstr);
88     }
89     if (properties > 0)
90         strm.PutCString (" )\n");
91     else
92         strm.EOL();
93     if (show_process_status)
94     {
95         const bool only_threads_with_stop_reason = true;
96         const uint32_t start_frame = 0;
97         const uint32_t num_frames = 1;
98         const uint32_t num_frames_with_source = 1;
99         process_sp->GetStatus (strm);
100         process_sp->GetThreadStatus (strm,
101                                      only_threads_with_stop_reason,
102                                      start_frame,
103                                      num_frames,
104                                      num_frames_with_source);
105 
106     }
107 }
108 
109 static uint32_t
110 DumpTargetList (TargetList &target_list, bool show_stopped_process_status, Stream &strm)
111 {
112     const uint32_t num_targets = target_list.GetNumTargets();
113     if (num_targets)
114     {
115         TargetSP selected_target_sp (target_list.GetSelectedTarget());
116         strm.PutCString ("Current targets:\n");
117         for (uint32_t i=0; i<num_targets; ++i)
118         {
119             TargetSP target_sp (target_list.GetTargetAtIndex (i));
120             if (target_sp)
121             {
122                 bool is_selected = target_sp.get() == selected_target_sp.get();
123                 DumpTargetInfo (i,
124                                 target_sp.get(),
125                                 is_selected ? "* " : "  ",
126                                 show_stopped_process_status,
127                                 strm);
128             }
129         }
130     }
131     return num_targets;
132 }
133 #pragma mark CommandObjectTargetCreate
134 
135 //-------------------------------------------------------------------------
136 // "target create"
137 //-------------------------------------------------------------------------
138 
139 class CommandObjectTargetCreate : public CommandObject
140 {
141 public:
142     CommandObjectTargetCreate(CommandInterpreter &interpreter) :
143         CommandObject (interpreter,
144                        "target create",
145                        "Create a target using the argument as the main executable.",
146                        NULL),
147         m_option_group (interpreter),
148         m_arch_option (),
149         m_platform_options(true) // Do include the "--platform" option in the platform settings by passing true
150     {
151         CommandArgumentEntry arg;
152         CommandArgumentData file_arg;
153 
154         // Define the first (and only) variant of this arg.
155             file_arg.arg_type = eArgTypeFilename;
156         file_arg.arg_repetition = eArgRepeatPlain;
157 
158         // There is only one variant this argument could be; put it into the argument entry.
159         arg.push_back (file_arg);
160 
161         // Push the data for the first argument into the m_arguments vector.
162         m_arguments.push_back (arg);
163 
164         m_option_group.Append (&m_arch_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
165         m_option_group.Append (&m_platform_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
166         m_option_group.Finalize();
167     }
168 
169     ~CommandObjectTargetCreate ()
170     {
171     }
172 
173     Options *
174     GetOptions ()
175     {
176         return &m_option_group;
177     }
178 
179     bool
180     Execute (Args& command, CommandReturnObject &result)
181     {
182         const int argc = command.GetArgumentCount();
183         if (argc == 1)
184         {
185             const char *file_path = command.GetArgumentAtIndex(0);
186             Timer scoped_timer(__PRETTY_FUNCTION__, "(lldb) target create '%s'", file_path);
187             FileSpec file_spec (file_path, true);
188 
189             bool select = true;
190             PlatformSP platform_sp;
191 
192             Error error;
193 
194             if (m_platform_options.PlatformWasSpecified ())
195             {
196                 platform_sp = m_platform_options.CreatePlatformWithOptions(m_interpreter, select, error);
197                 if (!platform_sp)
198                 {
199                     result.AppendError(error.AsCString());
200                     result.SetStatus (eReturnStatusFailed);
201                     return false;
202                 }
203             }
204             ArchSpec file_arch;
205 
206             const char *arch_cstr = m_arch_option.GetArchitectureName();
207             if (arch_cstr)
208             {
209                 if (!platform_sp)
210                     platform_sp = m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform();
211                 if (!m_arch_option.GetArchitecture(platform_sp.get(), file_arch))
212                 {
213                     result.AppendErrorWithFormat("invalid architecture '%s'\n", arch_cstr);
214                     result.SetStatus (eReturnStatusFailed);
215                     return false;
216                 }
217             }
218 
219             if (! file_spec.Exists() && !file_spec.ResolveExecutableLocation())
220             {
221                 result.AppendErrorWithFormat ("File '%s' does not exist.\n", file_path);
222                 result.SetStatus (eReturnStatusFailed);
223                 return false;
224             }
225 
226             TargetSP target_sp;
227             Debugger &debugger = m_interpreter.GetDebugger();
228             error = debugger.GetTargetList().CreateTarget (debugger, file_spec, file_arch, true, target_sp);
229 
230             if (target_sp)
231             {
232                 debugger.GetTargetList().SetSelectedTarget(target_sp.get());
233                 result.AppendMessageWithFormat ("Current executable set to '%s' (%s).\n", file_path, target_sp->GetArchitecture().GetArchitectureName());
234                 result.SetStatus (eReturnStatusSuccessFinishNoResult);
235             }
236             else
237             {
238                 result.AppendError(error.AsCString());
239                 result.SetStatus (eReturnStatusFailed);
240             }
241         }
242         else
243         {
244             result.AppendErrorWithFormat("'%s' takes exactly one executable path argument.\n", m_cmd_name.c_str());
245             result.SetStatus (eReturnStatusFailed);
246         }
247         return result.Succeeded();
248 
249     }
250 
251     int
252     HandleArgumentCompletion (Args &input,
253                               int &cursor_index,
254                               int &cursor_char_position,
255                               OptionElementVector &opt_element_vector,
256                               int match_start_point,
257                               int max_return_elements,
258                               bool &word_complete,
259                               StringList &matches)
260     {
261         std::string completion_str (input.GetArgumentAtIndex(cursor_index));
262         completion_str.erase (cursor_char_position);
263 
264         CommandCompletions::InvokeCommonCompletionCallbacks (m_interpreter,
265                                                              CommandCompletions::eDiskFileCompletion,
266                                                              completion_str.c_str(),
267                                                              match_start_point,
268                                                              max_return_elements,
269                                                              NULL,
270                                                              word_complete,
271                                                              matches);
272         return matches.GetSize();
273     }
274 private:
275     OptionGroupOptions m_option_group;
276     OptionGroupArchitecture m_arch_option;
277     OptionGroupPlatform m_platform_options;
278 
279 };
280 
281 #pragma mark CommandObjectTargetList
282 
283 //----------------------------------------------------------------------
284 // "target list"
285 //----------------------------------------------------------------------
286 
287 class CommandObjectTargetList : public CommandObject
288 {
289 public:
290     CommandObjectTargetList (CommandInterpreter &interpreter) :
291         CommandObject (interpreter,
292                        "target list",
293                        "List all current targets in the current debug session.",
294                        NULL,
295                        0)
296     {
297     }
298 
299     virtual
300     ~CommandObjectTargetList ()
301     {
302     }
303 
304     virtual bool
305     Execute (Args& args, CommandReturnObject &result)
306     {
307         if (args.GetArgumentCount() == 0)
308         {
309             Stream &strm = result.GetOutputStream();
310 
311             bool show_stopped_process_status = false;
312             if (DumpTargetList (m_interpreter.GetDebugger().GetTargetList(), show_stopped_process_status, strm) == 0)
313             {
314                 strm.PutCString ("No targets.\n");
315             }
316             result.SetStatus (eReturnStatusSuccessFinishResult);
317         }
318         else
319         {
320             result.AppendError ("the 'target list' command takes no arguments\n");
321             result.SetStatus (eReturnStatusFailed);
322         }
323         return result.Succeeded();
324     }
325 };
326 
327 
328 #pragma mark CommandObjectTargetSelect
329 
330 //----------------------------------------------------------------------
331 // "target select"
332 //----------------------------------------------------------------------
333 
334 class CommandObjectTargetSelect : public CommandObject
335 {
336 public:
337     CommandObjectTargetSelect (CommandInterpreter &interpreter) :
338         CommandObject (interpreter,
339                        "target select",
340                        "Select a target as the current target by target index.",
341                        NULL,
342                        0)
343     {
344     }
345 
346     virtual
347     ~CommandObjectTargetSelect ()
348     {
349     }
350 
351     virtual bool
352     Execute (Args& args, CommandReturnObject &result)
353     {
354         if (args.GetArgumentCount() == 1)
355         {
356             bool success = false;
357             const char *target_idx_arg = args.GetArgumentAtIndex(0);
358             uint32_t target_idx = Args::StringToUInt32 (target_idx_arg, UINT32_MAX, 0, &success);
359             if (success)
360             {
361                 TargetList &target_list = m_interpreter.GetDebugger().GetTargetList();
362                 const uint32_t num_targets = target_list.GetNumTargets();
363                 if (target_idx < num_targets)
364                 {
365                     TargetSP target_sp (target_list.GetTargetAtIndex (target_idx));
366                     if (target_sp)
367                     {
368                         Stream &strm = result.GetOutputStream();
369                         target_list.SetSelectedTarget (target_sp.get());
370                         bool show_stopped_process_status = false;
371                         DumpTargetList (target_list, show_stopped_process_status, strm);
372                         result.SetStatus (eReturnStatusSuccessFinishResult);
373                     }
374                     else
375                     {
376                         result.AppendErrorWithFormat ("target #%u is NULL in target list\n", target_idx);
377                         result.SetStatus (eReturnStatusFailed);
378                     }
379                 }
380                 else
381                 {
382                     result.AppendErrorWithFormat ("index %u is out of range, valid target indexes are 0 - %u\n",
383                                                   target_idx,
384                                                   num_targets - 1);
385                     result.SetStatus (eReturnStatusFailed);
386                 }
387             }
388             else
389             {
390                 result.AppendErrorWithFormat("invalid index string value '%s'\n", target_idx_arg);
391                 result.SetStatus (eReturnStatusFailed);
392             }
393         }
394         else
395         {
396             result.AppendError ("'target select' takes a single argument: a target index\n");
397             result.SetStatus (eReturnStatusFailed);
398         }
399         return result.Succeeded();
400     }
401 };
402 
403 
404 #pragma mark CommandObjectTargetVariable
405 
406 //----------------------------------------------------------------------
407 // "target variable"
408 //----------------------------------------------------------------------
409 
410 class CommandObjectTargetVariable : public CommandObject
411 {
412 public:
413     CommandObjectTargetVariable (CommandInterpreter &interpreter) :
414         CommandObject (interpreter,
415                        "target variable",
416                        "Read global variable(s) prior to running your binary.",
417                        NULL,
418                        0),
419         m_option_group (interpreter),
420         m_option_variable (false), // Don't include frame options
421         m_option_compile_units    (LLDB_OPT_SET_1, false, "file", 'f', 0, eArgTypePath, "A basename or fullpath to a file that contains global variables. This option can be specified multiple times."),
422         m_option_shared_libraries (LLDB_OPT_SET_1, false, "shlib",'s', 0, eArgTypePath, "A basename or fullpath to a shared library to use in the search for global variables. This option can be specified multiple times."),
423         m_varobj_options()
424     {
425         m_option_group.Append (&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
426         m_option_group.Append (&m_option_variable, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
427         m_option_group.Append (&m_option_compile_units, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
428         m_option_group.Append (&m_option_shared_libraries, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
429         m_option_group.Finalize();
430     }
431 
432     virtual
433     ~CommandObjectTargetVariable ()
434     {
435     }
436 
437     void
438     DumpValueObject (Stream &s, VariableSP &var_sp, ValueObjectSP &valobj_sp, const char *root_name)
439     {
440         if (m_option_variable.format != eFormatDefault)
441             valobj_sp->SetFormat (m_option_variable.format);
442 
443         switch (var_sp->GetScope())
444         {
445             case eValueTypeVariableGlobal:
446                 if (m_option_variable.show_scope)
447                     s.PutCString("GLOBAL: ");
448                 break;
449 
450             case eValueTypeVariableStatic:
451                 if (m_option_variable.show_scope)
452                     s.PutCString("STATIC: ");
453                 break;
454 
455             case eValueTypeVariableArgument:
456                 if (m_option_variable.show_scope)
457                     s.PutCString("   ARG: ");
458                 break;
459 
460             case eValueTypeVariableLocal:
461                 if (m_option_variable.show_scope)
462                     s.PutCString(" LOCAL: ");
463                 break;
464 
465             default:
466                 break;
467         }
468 
469         if (m_option_variable.show_decl)
470         {
471             bool show_fullpaths = false;
472             bool show_module = true;
473             if (var_sp->DumpDeclaration(&s, show_fullpaths, show_module))
474                 s.PutCString (": ");
475         }
476 
477         const Format format = m_option_variable.format;
478         if (format != eFormatDefault)
479             valobj_sp->SetFormat (format);
480 
481         ValueObject::DumpValueObject (s,
482                                       valobj_sp.get(),
483                                       root_name,
484                                       m_varobj_options.ptr_depth,
485                                       0,
486                                       m_varobj_options.max_depth,
487                                       m_varobj_options.show_types,
488                                       m_varobj_options.show_location,
489                                       m_varobj_options.use_objc,
490                                       m_varobj_options.use_dynamic,
491                                       m_varobj_options.use_synth,
492                                       false,
493                                       m_varobj_options.flat_output,
494                                       m_varobj_options.no_summary_depth);
495 
496     }
497 
498 
499     static uint32_t GetVariableCallback (void *baton,
500                                          const char *name,
501                                          VariableList &variable_list)
502     {
503         Target *target = static_cast<Target *>(baton);
504         if (target)
505         {
506             return target->GetImages().FindGlobalVariables (ConstString(name),
507                                                             true,
508                                                             UINT32_MAX,
509                                                             variable_list);
510         }
511         return 0;
512     }
513 
514 
515 
516     virtual bool
517     Execute (Args& args, CommandReturnObject &result)
518     {
519         ExecutionContext exe_ctx (m_interpreter.GetExecutionContext());
520 
521         if (exe_ctx.target)
522         {
523             const size_t argc = args.GetArgumentCount();
524             if (argc > 0)
525             {
526                 Stream &s = result.GetOutputStream();
527 
528                 for (size_t idx = 0; idx < argc; ++idx)
529                 {
530                     VariableList variable_list;
531                     ValueObjectList valobj_list;
532 
533                     const char *arg = args.GetArgumentAtIndex(idx);
534                     uint32_t matches = 0;
535                     bool use_var_name = false;
536                     if (m_option_variable.use_regex)
537                     {
538                         RegularExpression regex(arg);
539                         if (!regex.IsValid ())
540                         {
541                             result.GetErrorStream().Printf ("error: invalid regular expression: '%s'\n", arg);
542                             result.SetStatus (eReturnStatusFailed);
543                             return false;
544                         }
545                         use_var_name = true;
546                         matches = exe_ctx.target->GetImages().FindGlobalVariables (regex,
547                                                                                    true,
548                                                                                    UINT32_MAX,
549                                                                                    variable_list);
550                     }
551                     else
552                     {
553                         Error error (Variable::GetValuesForVariableExpressionPath (arg,
554                                                                                    exe_ctx.GetBestExecutionContextScope(),
555                                                                                    GetVariableCallback,
556                                                                                    exe_ctx.target,
557                                                                                    variable_list,
558                                                                                    valobj_list));
559 
560 //                        matches = exe_ctx.target->GetImages().FindGlobalVariables (ConstString(arg),
561 //                                                                                   true,
562 //                                                                                   UINT32_MAX,
563 //                                                                                   variable_list);
564                         matches = variable_list.GetSize();
565                     }
566 
567                     if (matches == 0)
568                     {
569                         result.GetErrorStream().Printf ("error: can't find global variable '%s'\n", arg);
570                         result.SetStatus (eReturnStatusFailed);
571                         return false;
572                     }
573                     else
574                     {
575                         for (uint32_t global_idx=0; global_idx<matches; ++global_idx)
576                         {
577                             VariableSP var_sp (variable_list.GetVariableAtIndex(global_idx));
578                             if (var_sp)
579                             {
580                                 ValueObjectSP valobj_sp (valobj_list.GetValueObjectAtIndex(global_idx));
581                                 if (!valobj_sp)
582                                     valobj_sp = ValueObjectVariable::Create (exe_ctx.GetBestExecutionContextScope(), var_sp);
583 
584                                 if (valobj_sp)
585                                     DumpValueObject (s, var_sp, valobj_sp, use_var_name ? var_sp->GetName().GetCString() : arg);
586                             }
587                         }
588                     }
589                 }
590             }
591             else
592             {
593                 result.AppendError ("'target variable' takes one or more global variable names as arguments\n");
594                 result.SetStatus (eReturnStatusFailed);
595             }
596         }
597         else
598         {
599             result.AppendError ("invalid target, create a debug target using the 'target create' command");
600             result.SetStatus (eReturnStatusFailed);
601             return false;
602         }
603         return result.Succeeded();
604     }
605 
606     Options *
607     GetOptions ()
608     {
609         return &m_option_group;
610     }
611 
612 protected:
613     OptionGroupOptions m_option_group;
614     OptionGroupVariable m_option_variable;
615     OptionGroupFileList m_option_compile_units;
616     OptionGroupFileList m_option_shared_libraries;
617     OptionGroupValueObjectDisplay m_varobj_options;
618 
619 };
620 
621 
622 #pragma mark CommandObjectTargetModulesSearchPathsAdd
623 
624 class CommandObjectTargetModulesSearchPathsAdd : public CommandObject
625 {
626 public:
627 
628     CommandObjectTargetModulesSearchPathsAdd (CommandInterpreter &interpreter) :
629         CommandObject (interpreter,
630                        "target modules search-paths add",
631                        "Add new image search paths substitution pairs to the current target.",
632                        NULL)
633     {
634         CommandArgumentEntry arg;
635         CommandArgumentData old_prefix_arg;
636         CommandArgumentData new_prefix_arg;
637 
638         // Define the first variant of this arg pair.
639         old_prefix_arg.arg_type = eArgTypeOldPathPrefix;
640         old_prefix_arg.arg_repetition = eArgRepeatPairPlus;
641 
642         // Define the first variant of this arg pair.
643         new_prefix_arg.arg_type = eArgTypeNewPathPrefix;
644         new_prefix_arg.arg_repetition = eArgRepeatPairPlus;
645 
646         // There are two required arguments that must always occur together, i.e. an argument "pair".  Because they
647         // must always occur together, they are treated as two variants of one argument rather than two independent
648         // arguments.  Push them both into the first argument position for m_arguments...
649 
650         arg.push_back (old_prefix_arg);
651         arg.push_back (new_prefix_arg);
652 
653         m_arguments.push_back (arg);
654     }
655 
656     ~CommandObjectTargetModulesSearchPathsAdd ()
657     {
658     }
659 
660     bool
661     Execute (Args& command,
662              CommandReturnObject &result)
663     {
664         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
665         if (target)
666         {
667             uint32_t argc = command.GetArgumentCount();
668             if (argc & 1)
669             {
670                 result.AppendError ("add requires an even number of arguments\n");
671                 result.SetStatus (eReturnStatusFailed);
672             }
673             else
674             {
675                 for (uint32_t i=0; i<argc; i+=2)
676                 {
677                     const char *from = command.GetArgumentAtIndex(i);
678                     const char *to = command.GetArgumentAtIndex(i+1);
679 
680                     if (from[0] && to[0])
681                     {
682                         bool last_pair = ((argc - i) == 2);
683                         target->GetImageSearchPathList().Append (ConstString(from),
684                                                                  ConstString(to),
685                                                                  last_pair); // Notify if this is the last pair
686                         result.SetStatus (eReturnStatusSuccessFinishNoResult);
687                     }
688                     else
689                     {
690                         if (from[0])
691                             result.AppendError ("<path-prefix> can't be empty\n");
692                         else
693                             result.AppendError ("<new-path-prefix> can't be empty\n");
694                         result.SetStatus (eReturnStatusFailed);
695                     }
696                 }
697             }
698         }
699         else
700         {
701             result.AppendError ("invalid target\n");
702             result.SetStatus (eReturnStatusFailed);
703         }
704         return result.Succeeded();
705     }
706 };
707 
708 #pragma mark CommandObjectTargetModulesSearchPathsClear
709 
710 class CommandObjectTargetModulesSearchPathsClear : public CommandObject
711 {
712 public:
713 
714     CommandObjectTargetModulesSearchPathsClear (CommandInterpreter &interpreter) :
715         CommandObject (interpreter,
716                        "target modules search-paths clear",
717                        "Clear all current image search path substitution pairs from the current target.",
718                        "target modules search-paths clear")
719     {
720     }
721 
722     ~CommandObjectTargetModulesSearchPathsClear ()
723     {
724     }
725 
726     bool
727     Execute (Args& command,
728              CommandReturnObject &result)
729     {
730         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
731         if (target)
732         {
733             bool notify = true;
734             target->GetImageSearchPathList().Clear(notify);
735             result.SetStatus (eReturnStatusSuccessFinishNoResult);
736         }
737         else
738         {
739             result.AppendError ("invalid target\n");
740             result.SetStatus (eReturnStatusFailed);
741         }
742         return result.Succeeded();
743     }
744 };
745 
746 #pragma mark CommandObjectTargetModulesSearchPathsInsert
747 
748 class CommandObjectTargetModulesSearchPathsInsert : public CommandObject
749 {
750 public:
751 
752     CommandObjectTargetModulesSearchPathsInsert (CommandInterpreter &interpreter) :
753         CommandObject (interpreter,
754                        "target modules search-paths insert",
755                        "Insert a new image search path substitution pair into the current target at the specified index.",
756                        NULL)
757     {
758         CommandArgumentEntry arg1;
759         CommandArgumentEntry arg2;
760         CommandArgumentData index_arg;
761         CommandArgumentData old_prefix_arg;
762         CommandArgumentData new_prefix_arg;
763 
764         // Define the first and only variant of this arg.
765         index_arg.arg_type = eArgTypeIndex;
766         index_arg.arg_repetition = eArgRepeatPlain;
767 
768         // Put the one and only variant into the first arg for m_arguments:
769         arg1.push_back (index_arg);
770 
771         // Define the first variant of this arg pair.
772         old_prefix_arg.arg_type = eArgTypeOldPathPrefix;
773         old_prefix_arg.arg_repetition = eArgRepeatPairPlus;
774 
775         // Define the first variant of this arg pair.
776         new_prefix_arg.arg_type = eArgTypeNewPathPrefix;
777         new_prefix_arg.arg_repetition = eArgRepeatPairPlus;
778 
779         // There are two required arguments that must always occur together, i.e. an argument "pair".  Because they
780         // must always occur together, they are treated as two variants of one argument rather than two independent
781         // arguments.  Push them both into the same argument position for m_arguments...
782 
783         arg2.push_back (old_prefix_arg);
784         arg2.push_back (new_prefix_arg);
785 
786         // Add arguments to m_arguments.
787         m_arguments.push_back (arg1);
788         m_arguments.push_back (arg2);
789     }
790 
791     ~CommandObjectTargetModulesSearchPathsInsert ()
792     {
793     }
794 
795     bool
796     Execute (Args& command,
797              CommandReturnObject &result)
798     {
799         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
800         if (target)
801         {
802             uint32_t argc = command.GetArgumentCount();
803             // check for at least 3 arguments and an odd nubmer of parameters
804             if (argc >= 3 && argc & 1)
805             {
806                 bool success = false;
807 
808                 uint32_t insert_idx = Args::StringToUInt32(command.GetArgumentAtIndex(0), UINT32_MAX, 0, &success);
809 
810                 if (!success)
811                 {
812                     result.AppendErrorWithFormat("<index> parameter is not an integer: '%s'.\n", command.GetArgumentAtIndex(0));
813                     result.SetStatus (eReturnStatusFailed);
814                     return result.Succeeded();
815                 }
816 
817                 // shift off the index
818                 command.Shift();
819                 argc = command.GetArgumentCount();
820 
821                 for (uint32_t i=0; i<argc; i+=2, ++insert_idx)
822                 {
823                     const char *from = command.GetArgumentAtIndex(i);
824                     const char *to = command.GetArgumentAtIndex(i+1);
825 
826                     if (from[0] && to[0])
827                     {
828                         bool last_pair = ((argc - i) == 2);
829                         target->GetImageSearchPathList().Insert (ConstString(from),
830                                                                  ConstString(to),
831                                                                  insert_idx,
832                                                                  last_pair);
833                         result.SetStatus (eReturnStatusSuccessFinishNoResult);
834                     }
835                     else
836                     {
837                         if (from[0])
838                             result.AppendError ("<path-prefix> can't be empty\n");
839                         else
840                             result.AppendError ("<new-path-prefix> can't be empty\n");
841                         result.SetStatus (eReturnStatusFailed);
842                         return false;
843                     }
844                 }
845             }
846             else
847             {
848                 result.AppendError ("insert requires at least three arguments\n");
849                 result.SetStatus (eReturnStatusFailed);
850                 return result.Succeeded();
851             }
852 
853         }
854         else
855         {
856             result.AppendError ("invalid target\n");
857             result.SetStatus (eReturnStatusFailed);
858         }
859         return result.Succeeded();
860     }
861 };
862 
863 
864 #pragma mark CommandObjectTargetModulesSearchPathsList
865 
866 
867 class CommandObjectTargetModulesSearchPathsList : public CommandObject
868 {
869 public:
870 
871     CommandObjectTargetModulesSearchPathsList (CommandInterpreter &interpreter) :
872         CommandObject (interpreter,
873                        "target modules search-paths list",
874                        "List all current image search path substitution pairs in the current target.",
875                        "target modules search-paths list")
876     {
877     }
878 
879     ~CommandObjectTargetModulesSearchPathsList ()
880     {
881     }
882 
883     bool
884     Execute (Args& command,
885              CommandReturnObject &result)
886     {
887         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
888         if (target)
889         {
890             if (command.GetArgumentCount() != 0)
891             {
892                 result.AppendError ("list takes no arguments\n");
893                 result.SetStatus (eReturnStatusFailed);
894                 return result.Succeeded();
895             }
896 
897             target->GetImageSearchPathList().Dump(&result.GetOutputStream());
898             result.SetStatus (eReturnStatusSuccessFinishResult);
899         }
900         else
901         {
902             result.AppendError ("invalid target\n");
903             result.SetStatus (eReturnStatusFailed);
904         }
905         return result.Succeeded();
906     }
907 };
908 
909 #pragma mark CommandObjectTargetModulesSearchPathsQuery
910 
911 class CommandObjectTargetModulesSearchPathsQuery : public CommandObject
912 {
913 public:
914 
915     CommandObjectTargetModulesSearchPathsQuery (CommandInterpreter &interpreter) :
916     CommandObject (interpreter,
917                    "target modules search-paths query",
918                    "Transform a path using the first applicable image search path.",
919                    NULL)
920     {
921         CommandArgumentEntry arg;
922         CommandArgumentData path_arg;
923 
924         // Define the first (and only) variant of this arg.
925         path_arg.arg_type = eArgTypePath;
926         path_arg.arg_repetition = eArgRepeatPlain;
927 
928         // There is only one variant this argument could be; put it into the argument entry.
929         arg.push_back (path_arg);
930 
931         // Push the data for the first argument into the m_arguments vector.
932         m_arguments.push_back (arg);
933     }
934 
935     ~CommandObjectTargetModulesSearchPathsQuery ()
936     {
937     }
938 
939     bool
940     Execute (Args& command,
941              CommandReturnObject &result)
942     {
943         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
944         if (target)
945         {
946             if (command.GetArgumentCount() != 1)
947             {
948                 result.AppendError ("query requires one argument\n");
949                 result.SetStatus (eReturnStatusFailed);
950                 return result.Succeeded();
951             }
952 
953             ConstString orig(command.GetArgumentAtIndex(0));
954             ConstString transformed;
955             if (target->GetImageSearchPathList().RemapPath(orig, transformed))
956                 result.GetOutputStream().Printf("%s\n", transformed.GetCString());
957             else
958                 result.GetOutputStream().Printf("%s\n", orig.GetCString());
959 
960             result.SetStatus (eReturnStatusSuccessFinishResult);
961         }
962         else
963         {
964             result.AppendError ("invalid target\n");
965             result.SetStatus (eReturnStatusFailed);
966         }
967         return result.Succeeded();
968     }
969 };
970 
971 //----------------------------------------------------------------------
972 // Static Helper functions
973 //----------------------------------------------------------------------
974 static void
975 DumpModuleArchitecture (Stream &strm, Module *module, bool full_triple, uint32_t width)
976 {
977     if (module)
978     {
979         const char *arch_cstr;
980         if (full_triple)
981             arch_cstr = module->GetArchitecture().GetTriple().str().c_str();
982         else
983             arch_cstr = module->GetArchitecture().GetArchitectureName();
984         if (width)
985             strm.Printf("%-*s", width, arch_cstr);
986         else
987             strm.PutCString(arch_cstr);
988     }
989 }
990 
991 static void
992 DumpModuleUUID (Stream &strm, Module *module)
993 {
994     module->GetUUID().Dump (&strm);
995 }
996 
997 static uint32_t
998 DumpCompileUnitLineTable
999 (
1000  CommandInterpreter &interpreter,
1001  Stream &strm,
1002  Module *module,
1003  const FileSpec &file_spec,
1004  bool load_addresses
1005  )
1006 {
1007     uint32_t num_matches = 0;
1008     if (module)
1009     {
1010         SymbolContextList sc_list;
1011         num_matches = module->ResolveSymbolContextsForFileSpec (file_spec,
1012                                                                 0,
1013                                                                 false,
1014                                                                 eSymbolContextCompUnit,
1015                                                                 sc_list);
1016 
1017         for (uint32_t i=0; i<num_matches; ++i)
1018         {
1019             SymbolContext sc;
1020             if (sc_list.GetContextAtIndex(i, sc))
1021             {
1022                 if (i > 0)
1023                     strm << "\n\n";
1024 
1025                 strm << "Line table for " << *static_cast<FileSpec*> (sc.comp_unit) << " in `"
1026                 << module->GetFileSpec().GetFilename() << "\n";
1027                 LineTable *line_table = sc.comp_unit->GetLineTable();
1028                 if (line_table)
1029                     line_table->GetDescription (&strm,
1030                                                 interpreter.GetExecutionContext().target,
1031                                                 lldb::eDescriptionLevelBrief);
1032                 else
1033                     strm << "No line table";
1034             }
1035         }
1036     }
1037     return num_matches;
1038 }
1039 
1040 static void
1041 DumpFullpath (Stream &strm, const FileSpec *file_spec_ptr, uint32_t width)
1042 {
1043     if (file_spec_ptr)
1044     {
1045         if (width > 0)
1046         {
1047             char fullpath[PATH_MAX];
1048             if (file_spec_ptr->GetPath(fullpath, sizeof(fullpath)))
1049             {
1050                 strm.Printf("%-*s", width, fullpath);
1051                 return;
1052             }
1053         }
1054         else
1055         {
1056             file_spec_ptr->Dump(&strm);
1057             return;
1058         }
1059     }
1060     // Keep the width spacing correct if things go wrong...
1061     if (width > 0)
1062         strm.Printf("%-*s", width, "");
1063 }
1064 
1065 static void
1066 DumpDirectory (Stream &strm, const FileSpec *file_spec_ptr, uint32_t width)
1067 {
1068     if (file_spec_ptr)
1069     {
1070         if (width > 0)
1071             strm.Printf("%-*s", width, file_spec_ptr->GetDirectory().AsCString(""));
1072         else
1073             file_spec_ptr->GetDirectory().Dump(&strm);
1074         return;
1075     }
1076     // Keep the width spacing correct if things go wrong...
1077     if (width > 0)
1078         strm.Printf("%-*s", width, "");
1079 }
1080 
1081 static void
1082 DumpBasename (Stream &strm, const FileSpec *file_spec_ptr, uint32_t width)
1083 {
1084     if (file_spec_ptr)
1085     {
1086         if (width > 0)
1087             strm.Printf("%-*s", width, file_spec_ptr->GetFilename().AsCString(""));
1088         else
1089             file_spec_ptr->GetFilename().Dump(&strm);
1090         return;
1091     }
1092     // Keep the width spacing correct if things go wrong...
1093     if (width > 0)
1094         strm.Printf("%-*s", width, "");
1095 }
1096 
1097 
1098 static void
1099 DumpModuleSymtab (CommandInterpreter &interpreter, Stream &strm, Module *module, SortOrder sort_order)
1100 {
1101     if (module)
1102     {
1103         ObjectFile *objfile = module->GetObjectFile ();
1104         if (objfile)
1105         {
1106             Symtab *symtab = objfile->GetSymtab();
1107             if (symtab)
1108                 symtab->Dump(&strm, interpreter.GetExecutionContext().target, sort_order);
1109         }
1110     }
1111 }
1112 
1113 static void
1114 DumpModuleSections (CommandInterpreter &interpreter, Stream &strm, Module *module)
1115 {
1116     if (module)
1117     {
1118         ObjectFile *objfile = module->GetObjectFile ();
1119         if (objfile)
1120         {
1121             SectionList *section_list = objfile->GetSectionList();
1122             if (section_list)
1123             {
1124                 strm.PutCString ("Sections for '");
1125                 strm << module->GetFileSpec();
1126                 if (module->GetObjectName())
1127                     strm << '(' << module->GetObjectName() << ')';
1128                 strm.Printf ("' (%s):\n", module->GetArchitecture().GetArchitectureName());
1129                 strm.IndentMore();
1130                 section_list->Dump(&strm, interpreter.GetExecutionContext().target, true, UINT32_MAX);
1131                 strm.IndentLess();
1132             }
1133         }
1134     }
1135 }
1136 
1137 static bool
1138 DumpModuleSymbolVendor (Stream &strm, Module *module)
1139 {
1140     if (module)
1141     {
1142         SymbolVendor *symbol_vendor = module->GetSymbolVendor(true);
1143         if (symbol_vendor)
1144         {
1145             symbol_vendor->Dump(&strm);
1146             return true;
1147         }
1148     }
1149     return false;
1150 }
1151 
1152 static bool
1153 LookupAddressInModule
1154 (
1155  CommandInterpreter &interpreter,
1156  Stream &strm,
1157  Module *module,
1158  uint32_t resolve_mask,
1159  lldb::addr_t raw_addr,
1160  lldb::addr_t offset,
1161  bool verbose
1162  )
1163 {
1164     if (module)
1165     {
1166         lldb::addr_t addr = raw_addr - offset;
1167         Address so_addr;
1168         SymbolContext sc;
1169         Target *target = interpreter.GetExecutionContext().target;
1170         if (target && !target->GetSectionLoadList().IsEmpty())
1171         {
1172             if (!target->GetSectionLoadList().ResolveLoadAddress (addr, so_addr))
1173                 return false;
1174             else if (so_addr.GetModule() != module)
1175                 return false;
1176         }
1177         else
1178         {
1179             if (!module->ResolveFileAddress (addr, so_addr))
1180                 return false;
1181         }
1182 
1183         // If an offset was given, print out the address we ended up looking up
1184         if (offset)
1185             strm.Printf("File Address: 0x%llx\n", addr);
1186 
1187         ExecutionContextScope *exe_scope = interpreter.GetExecutionContext().GetBestExecutionContextScope();
1188         strm.IndentMore();
1189         strm.Indent ("    Address: ");
1190         so_addr.Dump (&strm, exe_scope, Address::DumpStyleSectionNameOffset);
1191         strm.EOL();
1192         strm.Indent ("    Summary: ");
1193         const uint32_t save_indent = strm.GetIndentLevel ();
1194         strm.SetIndentLevel (save_indent + 11);
1195         so_addr.Dump (&strm, exe_scope, Address::DumpStyleResolvedDescription);
1196         strm.SetIndentLevel (save_indent);
1197         strm.EOL();
1198         // Print out detailed address information when verbose is enabled
1199         if (verbose)
1200         {
1201             if (so_addr.Dump (&strm, exe_scope, Address::DumpStyleDetailedSymbolContext))
1202                 strm.EOL();
1203         }
1204         strm.IndentLess();
1205         return true;
1206     }
1207 
1208     return false;
1209 }
1210 
1211 static uint32_t
1212 LookupSymbolInModule (CommandInterpreter &interpreter, Stream &strm, Module *module, const char *name, bool name_is_regex)
1213 {
1214     if (module)
1215     {
1216         SymbolContext sc;
1217 
1218         ObjectFile *objfile = module->GetObjectFile ();
1219         if (objfile)
1220         {
1221             Symtab *symtab = objfile->GetSymtab();
1222             if (symtab)
1223             {
1224                 uint32_t i;
1225                 std::vector<uint32_t> match_indexes;
1226                 ConstString symbol_name (name);
1227                 uint32_t num_matches = 0;
1228                 if (name_is_regex)
1229                 {
1230                     RegularExpression name_regexp(name);
1231                     num_matches = symtab->AppendSymbolIndexesMatchingRegExAndType (name_regexp,
1232                                                                                    eSymbolTypeAny,
1233                                                                                    match_indexes);
1234                 }
1235                 else
1236                 {
1237                     num_matches = symtab->AppendSymbolIndexesWithName (symbol_name, match_indexes);
1238                 }
1239 
1240 
1241                 if (num_matches > 0)
1242                 {
1243                     strm.Indent ();
1244                     strm.Printf("%u symbols match %s'%s' in ", num_matches,
1245                                 name_is_regex ? "the regular expression " : "", name);
1246                     DumpFullpath (strm, &module->GetFileSpec(), 0);
1247                     strm.PutCString(":\n");
1248                     strm.IndentMore ();
1249                     Symtab::DumpSymbolHeader (&strm);
1250                     for (i=0; i < num_matches; ++i)
1251                     {
1252                         Symbol *symbol = symtab->SymbolAtIndex(match_indexes[i]);
1253                         strm.Indent ();
1254                         symbol->Dump (&strm, interpreter.GetExecutionContext().target, i);
1255                     }
1256                     strm.IndentLess ();
1257                     return num_matches;
1258                 }
1259             }
1260         }
1261     }
1262     return 0;
1263 }
1264 
1265 
1266 static void
1267 DumpSymbolContextList (CommandInterpreter &interpreter, Stream &strm, SymbolContextList &sc_list, bool prepend_addr, bool verbose)
1268 {
1269     strm.IndentMore ();
1270     uint32_t i;
1271     const uint32_t num_matches = sc_list.GetSize();
1272 
1273     for (i=0; i<num_matches; ++i)
1274     {
1275         SymbolContext sc;
1276         if (sc_list.GetContextAtIndex(i, sc))
1277         {
1278             strm.Indent();
1279             ExecutionContextScope *exe_scope = interpreter.GetExecutionContext().GetBestExecutionContextScope ();
1280 
1281             if (prepend_addr)
1282             {
1283                 if (sc.line_entry.range.GetBaseAddress().IsValid())
1284                 {
1285                     sc.line_entry.range.GetBaseAddress().Dump (&strm,
1286                                                                exe_scope,
1287                                                                Address::DumpStyleLoadAddress,
1288                                                                Address::DumpStyleModuleWithFileAddress);
1289                     strm.PutCString(" in ");
1290                 }
1291             }
1292             sc.DumpStopContext(&strm,
1293                                exe_scope,
1294                                sc.line_entry.range.GetBaseAddress(),
1295                                true,
1296                                true,
1297                                false);
1298             strm.EOL();
1299             if (verbose)
1300             {
1301                 if (sc.line_entry.range.GetBaseAddress().IsValid())
1302                 {
1303                     if (sc.line_entry.range.GetBaseAddress().Dump (&strm,
1304                                                                    exe_scope,
1305                                                                    Address::DumpStyleDetailedSymbolContext))
1306                         strm.PutCString("\n\n");
1307                 }
1308                 else if (sc.function->GetAddressRange().GetBaseAddress().IsValid())
1309                 {
1310                     if (sc.function->GetAddressRange().GetBaseAddress().Dump (&strm,
1311                                                                               exe_scope,
1312                                                                               Address::DumpStyleDetailedSymbolContext))
1313                         strm.PutCString("\n\n");
1314                 }
1315             }
1316         }
1317     }
1318     strm.IndentLess ();
1319 }
1320 
1321 static uint32_t
1322 LookupFunctionInModule (CommandInterpreter &interpreter, Stream &strm, Module *module, const char *name, bool name_is_regex, bool verbose)
1323 {
1324     if (module && name && name[0])
1325     {
1326         SymbolContextList sc_list;
1327         const bool include_symbols = false;
1328         const bool append = true;
1329         uint32_t num_matches = 0;
1330         if (name_is_regex)
1331         {
1332             RegularExpression function_name_regex (name);
1333             num_matches = module->FindFunctions (function_name_regex,
1334                                                  include_symbols,
1335                                                  append,
1336                                                  sc_list);
1337         }
1338         else
1339         {
1340             ConstString function_name (name);
1341             num_matches = module->FindFunctions (function_name,
1342                                                  eFunctionNameTypeBase | eFunctionNameTypeFull | eFunctionNameTypeMethod | eFunctionNameTypeSelector,
1343                                                  include_symbols,
1344                                                  append,
1345                                                  sc_list);
1346         }
1347 
1348         if (num_matches)
1349         {
1350             strm.Indent ();
1351             strm.Printf("%u match%s found in ", num_matches, num_matches > 1 ? "es" : "");
1352             DumpFullpath (strm, &module->GetFileSpec(), 0);
1353             strm.PutCString(":\n");
1354             DumpSymbolContextList (interpreter, strm, sc_list, true, verbose);
1355         }
1356         return num_matches;
1357     }
1358     return 0;
1359 }
1360 
1361 static uint32_t
1362 LookupTypeInModule (CommandInterpreter &interpreter,
1363                     Stream &strm,
1364                     Module *module,
1365                     const char *name_cstr,
1366                     bool name_is_regex)
1367 {
1368     if (module && name_cstr && name_cstr[0])
1369     {
1370         /*SymbolContextList sc_list;
1371 
1372         SymbolVendor *symbol_vendor = module->GetSymbolVendor();
1373         if (symbol_vendor)
1374         {*/
1375             TypeList type_list;
1376             uint32_t num_matches = 0;
1377             SymbolContext sc;
1378             //            if (name_is_regex)
1379             //            {
1380             //                RegularExpression name_regex (name_cstr);
1381             //                num_matches = symbol_vendor->FindFunctions(sc, name_regex, true, UINT32_MAX, type_list);
1382             //            }
1383             //            else
1384             //            {
1385             ConstString name(name_cstr);
1386             num_matches = module->FindTypes(sc, name, true, UINT32_MAX, type_list);
1387             //            }
1388 
1389             if (num_matches)
1390             {
1391                 strm.Indent ();
1392                 strm.Printf("%u match%s found in ", num_matches, num_matches > 1 ? "es" : "");
1393                 DumpFullpath (strm, &module->GetFileSpec(), 0);
1394                 strm.PutCString(":\n");
1395                 const uint32_t num_types = type_list.GetSize();
1396                 for (uint32_t i=0; i<num_types; ++i)
1397                 {
1398                     TypeSP type_sp (type_list.GetTypeAtIndex(i));
1399                     if (type_sp)
1400                     {
1401                         // Resolve the clang type so that any forward references
1402                         // to types that haven't yet been parsed will get parsed.
1403                         type_sp->GetClangFullType ();
1404                         type_sp->GetDescription (&strm, eDescriptionLevelFull, true);
1405                     }
1406                     strm.EOL();
1407                 }
1408             }
1409             return num_matches;
1410         //}
1411     }
1412     return 0;
1413 }
1414 
1415 static uint32_t
1416 LookupFileAndLineInModule (CommandInterpreter &interpreter,
1417                            Stream &strm,
1418                            Module *module,
1419                            const FileSpec &file_spec,
1420                            uint32_t line,
1421                            bool check_inlines,
1422                            bool verbose)
1423 {
1424     if (module && file_spec)
1425     {
1426         SymbolContextList sc_list;
1427         const uint32_t num_matches = module->ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines,
1428                                                                               eSymbolContextEverything, sc_list);
1429         if (num_matches > 0)
1430         {
1431             strm.Indent ();
1432             strm.Printf("%u match%s found in ", num_matches, num_matches > 1 ? "es" : "");
1433             strm << file_spec;
1434             if (line > 0)
1435                 strm.Printf (":%u", line);
1436             strm << " in ";
1437             DumpFullpath (strm, &module->GetFileSpec(), 0);
1438             strm.PutCString(":\n");
1439             DumpSymbolContextList (interpreter, strm, sc_list, true, verbose);
1440             return num_matches;
1441         }
1442     }
1443     return 0;
1444 
1445 }
1446 
1447 #pragma mark CommandObjectTargetModulesModuleAutoComplete
1448 
1449 //----------------------------------------------------------------------
1450 // A base command object class that can auto complete with module file
1451 // paths
1452 //----------------------------------------------------------------------
1453 
1454 class CommandObjectTargetModulesModuleAutoComplete : public CommandObject
1455 {
1456 public:
1457 
1458     CommandObjectTargetModulesModuleAutoComplete (CommandInterpreter &interpreter,
1459                                       const char *name,
1460                                       const char *help,
1461                                       const char *syntax) :
1462     CommandObject (interpreter, name, help, syntax)
1463     {
1464         CommandArgumentEntry arg;
1465         CommandArgumentData file_arg;
1466 
1467         // Define the first (and only) variant of this arg.
1468         file_arg.arg_type = eArgTypeFilename;
1469         file_arg.arg_repetition = eArgRepeatStar;
1470 
1471         // There is only one variant this argument could be; put it into the argument entry.
1472         arg.push_back (file_arg);
1473 
1474         // Push the data for the first argument into the m_arguments vector.
1475         m_arguments.push_back (arg);
1476     }
1477 
1478     virtual
1479     ~CommandObjectTargetModulesModuleAutoComplete ()
1480     {
1481     }
1482 
1483     virtual int
1484     HandleArgumentCompletion (Args &input,
1485                               int &cursor_index,
1486                               int &cursor_char_position,
1487                               OptionElementVector &opt_element_vector,
1488                               int match_start_point,
1489                               int max_return_elements,
1490                               bool &word_complete,
1491                               StringList &matches)
1492     {
1493         // Arguments are the standard module completer.
1494         std::string completion_str (input.GetArgumentAtIndex(cursor_index));
1495         completion_str.erase (cursor_char_position);
1496 
1497         CommandCompletions::InvokeCommonCompletionCallbacks (m_interpreter,
1498                                                              CommandCompletions::eModuleCompletion,
1499                                                              completion_str.c_str(),
1500                                                              match_start_point,
1501                                                              max_return_elements,
1502                                                              NULL,
1503                                                              word_complete,
1504                                                              matches);
1505         return matches.GetSize();
1506     }
1507 };
1508 
1509 #pragma mark CommandObjectTargetModulesSourceFileAutoComplete
1510 
1511 //----------------------------------------------------------------------
1512 // A base command object class that can auto complete with module source
1513 // file paths
1514 //----------------------------------------------------------------------
1515 
1516 class CommandObjectTargetModulesSourceFileAutoComplete : public CommandObject
1517 {
1518 public:
1519 
1520     CommandObjectTargetModulesSourceFileAutoComplete (CommandInterpreter &interpreter,
1521                                           const char *name,
1522                                           const char *help,
1523                                           const char *syntax) :
1524     CommandObject (interpreter, name, help, syntax)
1525     {
1526         CommandArgumentEntry arg;
1527         CommandArgumentData source_file_arg;
1528 
1529         // Define the first (and only) variant of this arg.
1530         source_file_arg.arg_type = eArgTypeSourceFile;
1531         source_file_arg.arg_repetition = eArgRepeatPlus;
1532 
1533         // There is only one variant this argument could be; put it into the argument entry.
1534         arg.push_back (source_file_arg);
1535 
1536         // Push the data for the first argument into the m_arguments vector.
1537         m_arguments.push_back (arg);
1538     }
1539 
1540     virtual
1541     ~CommandObjectTargetModulesSourceFileAutoComplete ()
1542     {
1543     }
1544 
1545     virtual int
1546     HandleArgumentCompletion (Args &input,
1547                               int &cursor_index,
1548                               int &cursor_char_position,
1549                               OptionElementVector &opt_element_vector,
1550                               int match_start_point,
1551                               int max_return_elements,
1552                               bool &word_complete,
1553                               StringList &matches)
1554     {
1555         // Arguments are the standard source file completer.
1556         std::string completion_str (input.GetArgumentAtIndex(cursor_index));
1557         completion_str.erase (cursor_char_position);
1558 
1559         CommandCompletions::InvokeCommonCompletionCallbacks (m_interpreter,
1560                                                              CommandCompletions::eSourceFileCompletion,
1561                                                              completion_str.c_str(),
1562                                                              match_start_point,
1563                                                              max_return_elements,
1564                                                              NULL,
1565                                                              word_complete,
1566                                                              matches);
1567         return matches.GetSize();
1568     }
1569 };
1570 
1571 
1572 #pragma mark CommandObjectTargetModulesDumpSymtab
1573 
1574 
1575 class CommandObjectTargetModulesDumpSymtab : public CommandObjectTargetModulesModuleAutoComplete
1576 {
1577 public:
1578     CommandObjectTargetModulesDumpSymtab (CommandInterpreter &interpreter) :
1579     CommandObjectTargetModulesModuleAutoComplete (interpreter,
1580                                       "target modules dump symtab",
1581                                       "Dump the symbol table from one or more target modules.",
1582                                       NULL),
1583     m_options (interpreter)
1584     {
1585     }
1586 
1587     virtual
1588     ~CommandObjectTargetModulesDumpSymtab ()
1589     {
1590     }
1591 
1592     virtual bool
1593     Execute (Args& command,
1594              CommandReturnObject &result)
1595     {
1596         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1597         if (target == NULL)
1598         {
1599             result.AppendError ("invalid target, create a debug target using the 'target create' command");
1600             result.SetStatus (eReturnStatusFailed);
1601             return false;
1602         }
1603         else
1604         {
1605             uint32_t num_dumped = 0;
1606 
1607             uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
1608             result.GetOutputStream().SetAddressByteSize(addr_byte_size);
1609             result.GetErrorStream().SetAddressByteSize(addr_byte_size);
1610 
1611             if (command.GetArgumentCount() == 0)
1612             {
1613                 // Dump all sections for all modules images
1614                 const uint32_t num_modules = target->GetImages().GetSize();
1615                 if (num_modules > 0)
1616                 {
1617                     result.GetOutputStream().Printf("Dumping symbol table for %u modules.\n", num_modules);
1618                     for (uint32_t image_idx = 0;  image_idx<num_modules; ++image_idx)
1619                     {
1620                         if (num_dumped > 0)
1621                         {
1622                             result.GetOutputStream().EOL();
1623                             result.GetOutputStream().EOL();
1624                         }
1625                         num_dumped++;
1626                         DumpModuleSymtab (m_interpreter, result.GetOutputStream(), target->GetImages().GetModulePointerAtIndex(image_idx), m_options.m_sort_order);
1627                     }
1628                 }
1629                 else
1630                 {
1631                     result.AppendError ("the target has no associated executable images");
1632                     result.SetStatus (eReturnStatusFailed);
1633                     return false;
1634                 }
1635             }
1636             else
1637             {
1638                 // Dump specified images (by basename or fullpath)
1639                 const char *arg_cstr;
1640                 for (int arg_idx = 0; (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != NULL; ++arg_idx)
1641                 {
1642                     FileSpec image_file(arg_cstr, false);
1643                     ModuleList matching_modules;
1644                     size_t num_matching_modules = target->GetImages().FindModules(&image_file, NULL, NULL, NULL, matching_modules);
1645 
1646                     // Not found in our module list for our target, check the main
1647                     // shared module list in case it is a extra file used somewhere
1648                     // else
1649                     if (num_matching_modules == 0)
1650                         num_matching_modules = ModuleList::FindSharedModules (image_file,
1651                                                                               target->GetArchitecture(),
1652                                                                               NULL,
1653                                                                               NULL,
1654                                                                               matching_modules);
1655 
1656                     if (num_matching_modules > 0)
1657                     {
1658                         for (size_t i=0; i<num_matching_modules; ++i)
1659                         {
1660                             Module *image_module = matching_modules.GetModulePointerAtIndex(i);
1661                             if (image_module)
1662                             {
1663                                 if (num_dumped > 0)
1664                                 {
1665                                     result.GetOutputStream().EOL();
1666                                     result.GetOutputStream().EOL();
1667                                 }
1668                                 num_dumped++;
1669                                 DumpModuleSymtab (m_interpreter, result.GetOutputStream(), image_module, m_options.m_sort_order);
1670                             }
1671                         }
1672                     }
1673                     else
1674                         result.AppendWarningWithFormat("Unable to find an image that matches '%s'.\n", arg_cstr);
1675                 }
1676             }
1677 
1678             if (num_dumped > 0)
1679                 result.SetStatus (eReturnStatusSuccessFinishResult);
1680             else
1681             {
1682                 result.AppendError ("no matching executable images found");
1683                 result.SetStatus (eReturnStatusFailed);
1684             }
1685         }
1686         return result.Succeeded();
1687     }
1688 
1689     virtual Options *
1690     GetOptions ()
1691     {
1692         return &m_options;
1693     }
1694 
1695     class CommandOptions : public Options
1696     {
1697     public:
1698 
1699         CommandOptions (CommandInterpreter &interpreter) :
1700         Options(interpreter),
1701         m_sort_order (eSortOrderNone)
1702         {
1703         }
1704 
1705         virtual
1706         ~CommandOptions ()
1707         {
1708         }
1709 
1710         virtual Error
1711         SetOptionValue (uint32_t option_idx, const char *option_arg)
1712         {
1713             Error error;
1714             char short_option = (char) m_getopt_table[option_idx].val;
1715 
1716             switch (short_option)
1717             {
1718                 case 's':
1719                 {
1720                     bool found_one = false;
1721                     m_sort_order = (SortOrder) Args::StringToOptionEnum (option_arg,
1722                                                                          g_option_table[option_idx].enum_values,
1723                                                                          eSortOrderNone,
1724                                                                          &found_one);
1725                     if (!found_one)
1726                         error.SetErrorStringWithFormat("Invalid enumeration value '%s' for option '%c'.\n",
1727                                                        option_arg,
1728                                                        short_option);
1729                 }
1730                     break;
1731 
1732                 default:
1733                     error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
1734                     break;
1735 
1736             }
1737             return error;
1738         }
1739 
1740         void
1741         OptionParsingStarting ()
1742         {
1743             m_sort_order = eSortOrderNone;
1744         }
1745 
1746         const OptionDefinition*
1747         GetDefinitions ()
1748         {
1749             return g_option_table;
1750         }
1751 
1752         // Options table: Required for subclasses of Options.
1753         static OptionDefinition g_option_table[];
1754 
1755         SortOrder m_sort_order;
1756     };
1757 
1758 protected:
1759 
1760     CommandOptions m_options;
1761 };
1762 
1763 static OptionEnumValueElement
1764 g_sort_option_enumeration[4] =
1765 {
1766     { eSortOrderNone,       "none",     "No sorting, use the original symbol table order."},
1767     { eSortOrderByAddress,  "address",  "Sort output by symbol address."},
1768     { eSortOrderByName,     "name",     "Sort output by symbol name."},
1769     { 0,                    NULL,       NULL }
1770 };
1771 
1772 
1773 OptionDefinition
1774 CommandObjectTargetModulesDumpSymtab::CommandOptions::g_option_table[] =
1775 {
1776     { LLDB_OPT_SET_1, false, "sort", 's', required_argument, g_sort_option_enumeration, 0, eArgTypeSortOrder, "Supply a sort order when dumping the symbol table."},
1777     { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
1778 };
1779 
1780 #pragma mark CommandObjectTargetModulesDumpSections
1781 
1782 //----------------------------------------------------------------------
1783 // Image section dumping command
1784 //----------------------------------------------------------------------
1785 
1786 class CommandObjectTargetModulesDumpSections : public CommandObjectTargetModulesModuleAutoComplete
1787 {
1788 public:
1789     CommandObjectTargetModulesDumpSections (CommandInterpreter &interpreter) :
1790     CommandObjectTargetModulesModuleAutoComplete (interpreter,
1791                                       "target modules dump sections",
1792                                       "Dump the sections from one or more target modules.",
1793                                       //"target modules dump sections [<file1> ...]")
1794                                       NULL)
1795     {
1796     }
1797 
1798     virtual
1799     ~CommandObjectTargetModulesDumpSections ()
1800     {
1801     }
1802 
1803     virtual bool
1804     Execute (Args& command,
1805              CommandReturnObject &result)
1806     {
1807         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1808         if (target == NULL)
1809         {
1810             result.AppendError ("invalid target, create a debug target using the 'target create' command");
1811             result.SetStatus (eReturnStatusFailed);
1812             return false;
1813         }
1814         else
1815         {
1816             uint32_t num_dumped = 0;
1817 
1818             uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
1819             result.GetOutputStream().SetAddressByteSize(addr_byte_size);
1820             result.GetErrorStream().SetAddressByteSize(addr_byte_size);
1821 
1822             if (command.GetArgumentCount() == 0)
1823             {
1824                 // Dump all sections for all modules images
1825                 const uint32_t num_modules = target->GetImages().GetSize();
1826                 if (num_modules > 0)
1827                 {
1828                     result.GetOutputStream().Printf("Dumping sections for %u modules.\n", num_modules);
1829                     for (uint32_t image_idx = 0;  image_idx<num_modules; ++image_idx)
1830                     {
1831                         num_dumped++;
1832                         DumpModuleSections (m_interpreter, result.GetOutputStream(), target->GetImages().GetModulePointerAtIndex(image_idx));
1833                     }
1834                 }
1835                 else
1836                 {
1837                     result.AppendError ("the target has no associated executable images");
1838                     result.SetStatus (eReturnStatusFailed);
1839                     return false;
1840                 }
1841             }
1842             else
1843             {
1844                 // Dump specified images (by basename or fullpath)
1845                 const char *arg_cstr;
1846                 for (int arg_idx = 0; (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != NULL; ++arg_idx)
1847                 {
1848                     FileSpec image_file(arg_cstr, false);
1849                     ModuleList matching_modules;
1850                     size_t num_matching_modules = target->GetImages().FindModules(&image_file, NULL, NULL, NULL, matching_modules);
1851 
1852                     // Not found in our module list for our target, check the main
1853                     // shared module list in case it is a extra file used somewhere
1854                     // else
1855                     if (num_matching_modules == 0)
1856                         num_matching_modules = ModuleList::FindSharedModules (image_file,
1857                                                                               target->GetArchitecture(),
1858                                                                               NULL,
1859                                                                               NULL,
1860                                                                               matching_modules);
1861 
1862                     if (num_matching_modules > 0)
1863                     {
1864                         for (size_t i=0; i<num_matching_modules; ++i)
1865                         {
1866                             Module * image_module = matching_modules.GetModulePointerAtIndex(i);
1867                             if (image_module)
1868                             {
1869                                 num_dumped++;
1870                                 DumpModuleSections (m_interpreter, result.GetOutputStream(), image_module);
1871                             }
1872                         }
1873                     }
1874                     else
1875                         result.AppendWarningWithFormat("Unable to find an image that matches '%s'.\n", arg_cstr);
1876                 }
1877             }
1878 
1879             if (num_dumped > 0)
1880                 result.SetStatus (eReturnStatusSuccessFinishResult);
1881             else
1882             {
1883                 result.AppendError ("no matching executable images found");
1884                 result.SetStatus (eReturnStatusFailed);
1885             }
1886         }
1887         return result.Succeeded();
1888     }
1889 };
1890 
1891 
1892 #pragma mark CommandObjectTargetModulesDumpSymfile
1893 
1894 //----------------------------------------------------------------------
1895 // Image debug symbol dumping command
1896 //----------------------------------------------------------------------
1897 
1898 class CommandObjectTargetModulesDumpSymfile : public CommandObjectTargetModulesModuleAutoComplete
1899 {
1900 public:
1901     CommandObjectTargetModulesDumpSymfile (CommandInterpreter &interpreter) :
1902     CommandObjectTargetModulesModuleAutoComplete (interpreter,
1903                                       "target modules dump symfile",
1904                                       "Dump the debug symbol file for one or more target modules.",
1905                                       //"target modules dump symfile [<file1> ...]")
1906                                       NULL)
1907     {
1908     }
1909 
1910     virtual
1911     ~CommandObjectTargetModulesDumpSymfile ()
1912     {
1913     }
1914 
1915     virtual bool
1916     Execute (Args& command,
1917              CommandReturnObject &result)
1918     {
1919         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1920         if (target == NULL)
1921         {
1922             result.AppendError ("invalid target, create a debug target using the 'target create' command");
1923             result.SetStatus (eReturnStatusFailed);
1924             return false;
1925         }
1926         else
1927         {
1928             uint32_t num_dumped = 0;
1929 
1930             uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
1931             result.GetOutputStream().SetAddressByteSize(addr_byte_size);
1932             result.GetErrorStream().SetAddressByteSize(addr_byte_size);
1933 
1934             if (command.GetArgumentCount() == 0)
1935             {
1936                 // Dump all sections for all modules images
1937                 const uint32_t num_modules = target->GetImages().GetSize();
1938                 if (num_modules > 0)
1939                 {
1940                     result.GetOutputStream().Printf("Dumping debug symbols for %u modules.\n", num_modules);
1941                     for (uint32_t image_idx = 0;  image_idx<num_modules; ++image_idx)
1942                     {
1943                         if (DumpModuleSymbolVendor (result.GetOutputStream(), target->GetImages().GetModulePointerAtIndex(image_idx)))
1944                             num_dumped++;
1945                     }
1946                 }
1947                 else
1948                 {
1949                     result.AppendError ("the target has no associated executable images");
1950                     result.SetStatus (eReturnStatusFailed);
1951                     return false;
1952                 }
1953             }
1954             else
1955             {
1956                 // Dump specified images (by basename or fullpath)
1957                 const char *arg_cstr;
1958                 for (int arg_idx = 0; (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != NULL; ++arg_idx)
1959                 {
1960                     FileSpec image_file(arg_cstr, false);
1961                     ModuleList matching_modules;
1962                     size_t num_matching_modules = target->GetImages().FindModules(&image_file, NULL, NULL, NULL, matching_modules);
1963 
1964                     // Not found in our module list for our target, check the main
1965                     // shared module list in case it is a extra file used somewhere
1966                     // else
1967                     if (num_matching_modules == 0)
1968                         num_matching_modules = ModuleList::FindSharedModules (image_file,
1969                                                                               target->GetArchitecture(),
1970                                                                               NULL,
1971                                                                               NULL,
1972                                                                               matching_modules);
1973 
1974                     if (num_matching_modules > 0)
1975                     {
1976                         for (size_t i=0; i<num_matching_modules; ++i)
1977                         {
1978                             Module * image_module = matching_modules.GetModulePointerAtIndex(i);
1979                             if (image_module)
1980                             {
1981                                 if (DumpModuleSymbolVendor (result.GetOutputStream(), image_module))
1982                                     num_dumped++;
1983                             }
1984                         }
1985                     }
1986                     else
1987                         result.AppendWarningWithFormat("Unable to find an image that matches '%s'.\n", arg_cstr);
1988                 }
1989             }
1990 
1991             if (num_dumped > 0)
1992                 result.SetStatus (eReturnStatusSuccessFinishResult);
1993             else
1994             {
1995                 result.AppendError ("no matching executable images found");
1996                 result.SetStatus (eReturnStatusFailed);
1997             }
1998         }
1999         return result.Succeeded();
2000     }
2001 };
2002 
2003 
2004 #pragma mark CommandObjectTargetModulesDumpLineTable
2005 
2006 //----------------------------------------------------------------------
2007 // Image debug line table dumping command
2008 //----------------------------------------------------------------------
2009 
2010 class CommandObjectTargetModulesDumpLineTable : public CommandObjectTargetModulesSourceFileAutoComplete
2011 {
2012 public:
2013     CommandObjectTargetModulesDumpLineTable (CommandInterpreter &interpreter) :
2014     CommandObjectTargetModulesSourceFileAutoComplete (interpreter,
2015                                           "target modules dump line-table",
2016                                           "Dump the debug symbol file for one or more target modules.",
2017                                           NULL)
2018     {
2019     }
2020 
2021     virtual
2022     ~CommandObjectTargetModulesDumpLineTable ()
2023     {
2024     }
2025 
2026     virtual bool
2027     Execute (Args& command,
2028              CommandReturnObject &result)
2029     {
2030         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2031         if (target == NULL)
2032         {
2033             result.AppendError ("invalid target, create a debug target using the 'target create' command");
2034             result.SetStatus (eReturnStatusFailed);
2035             return false;
2036         }
2037         else
2038         {
2039             ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
2040             uint32_t total_num_dumped = 0;
2041 
2042             uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2043             result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2044             result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2045 
2046             if (command.GetArgumentCount() == 0)
2047             {
2048                 result.AppendErrorWithFormat ("\nSyntax: %s\n", m_cmd_syntax.c_str());
2049                 result.SetStatus (eReturnStatusFailed);
2050             }
2051             else
2052             {
2053                 // Dump specified images (by basename or fullpath)
2054                 const char *arg_cstr;
2055                 for (int arg_idx = 0; (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != NULL; ++arg_idx)
2056                 {
2057                     FileSpec file_spec(arg_cstr, false);
2058                     const uint32_t num_modules = target->GetImages().GetSize();
2059                     if (num_modules > 0)
2060                     {
2061                         uint32_t num_dumped = 0;
2062                         for (uint32_t i = 0; i<num_modules; ++i)
2063                         {
2064                             if (DumpCompileUnitLineTable (m_interpreter,
2065                                                           result.GetOutputStream(),
2066                                                           target->GetImages().GetModulePointerAtIndex(i),
2067                                                           file_spec,
2068                                                           exe_ctx.process != NULL && exe_ctx.process->IsAlive()))
2069                                 num_dumped++;
2070                         }
2071                         if (num_dumped == 0)
2072                             result.AppendWarningWithFormat ("No source filenames matched '%s'.\n", arg_cstr);
2073                         else
2074                             total_num_dumped += num_dumped;
2075                     }
2076                 }
2077             }
2078 
2079             if (total_num_dumped > 0)
2080                 result.SetStatus (eReturnStatusSuccessFinishResult);
2081             else
2082             {
2083                 result.AppendError ("no source filenames matched any command arguments");
2084                 result.SetStatus (eReturnStatusFailed);
2085             }
2086         }
2087         return result.Succeeded();
2088     }
2089 };
2090 
2091 
2092 #pragma mark CommandObjectTargetModulesDump
2093 
2094 //----------------------------------------------------------------------
2095 // Dump multi-word command for target modules
2096 //----------------------------------------------------------------------
2097 
2098 class CommandObjectTargetModulesDump : public CommandObjectMultiword
2099 {
2100 public:
2101 
2102     //------------------------------------------------------------------
2103     // Constructors and Destructors
2104     //------------------------------------------------------------------
2105     CommandObjectTargetModulesDump(CommandInterpreter &interpreter) :
2106     CommandObjectMultiword (interpreter,
2107                             "target modules dump",
2108                             "A set of commands for dumping information about one or more target modules.",
2109                             "target modules dump [symtab|sections|symfile|line-table] [<file1> <file2> ...]")
2110     {
2111         LoadSubCommand ("symtab",      CommandObjectSP (new CommandObjectTargetModulesDumpSymtab (interpreter)));
2112         LoadSubCommand ("sections",    CommandObjectSP (new CommandObjectTargetModulesDumpSections (interpreter)));
2113         LoadSubCommand ("symfile",     CommandObjectSP (new CommandObjectTargetModulesDumpSymfile (interpreter)));
2114         LoadSubCommand ("line-table",  CommandObjectSP (new CommandObjectTargetModulesDumpLineTable (interpreter)));
2115     }
2116 
2117     virtual
2118     ~CommandObjectTargetModulesDump()
2119     {
2120     }
2121 };
2122 
2123 class CommandObjectTargetModulesAdd : public CommandObject
2124 {
2125 public:
2126     CommandObjectTargetModulesAdd (CommandInterpreter &interpreter) :
2127     CommandObject (interpreter,
2128                    "target modules add",
2129                    "Add a new module to the current target's modules.",
2130                    "target modules add [<module>]")
2131     {
2132     }
2133 
2134     virtual
2135     ~CommandObjectTargetModulesAdd ()
2136     {
2137     }
2138 
2139     virtual bool
2140     Execute (Args& args,
2141              CommandReturnObject &result)
2142     {
2143         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2144         if (target == NULL)
2145         {
2146             result.AppendError ("invalid target, create a debug target using the 'target create' command");
2147             result.SetStatus (eReturnStatusFailed);
2148             return false;
2149         }
2150         else
2151         {
2152             const size_t argc = args.GetArgumentCount();
2153             if (argc == 0)
2154             {
2155                 result.AppendError ("one or more executable image paths must be specified");
2156                 result.SetStatus (eReturnStatusFailed);
2157                 return false;
2158             }
2159             else
2160             {
2161                 for (size_t i=0; i<argc; ++i)
2162                 {
2163                     const char *path = args.GetArgumentAtIndex(i);
2164                     if (path)
2165                     {
2166                         FileSpec file_spec(path, true);
2167                         ArchSpec arch;
2168                         if (file_spec.Exists())
2169                         {
2170                             ModuleSP module_sp (target->GetSharedModule(file_spec, arch));
2171                             if (!module_sp)
2172                             {
2173                                 result.AppendError ("one or more executable image paths must be specified");
2174                                 result.SetStatus (eReturnStatusFailed);
2175                                 return false;
2176                             }
2177                         }
2178                         else
2179                         {
2180                             char resolved_path[PATH_MAX];
2181                             result.SetStatus (eReturnStatusFailed);
2182                             if (file_spec.GetPath (resolved_path, sizeof(resolved_path)))
2183                             {
2184                                 if (strcmp (resolved_path, path) != 0)
2185                                 {
2186                                     result.AppendErrorWithFormat ("invalid module path '%s' with resolved path '%s'\n", path, resolved_path);
2187                                     break;
2188                                 }
2189                             }
2190                             result.AppendErrorWithFormat ("invalid module path '%s'\n", path);
2191                             break;
2192                         }
2193                     }
2194                 }
2195             }
2196         }
2197         return result.Succeeded();
2198     }
2199 
2200     int
2201     HandleArgumentCompletion (Args &input,
2202                               int &cursor_index,
2203                               int &cursor_char_position,
2204                               OptionElementVector &opt_element_vector,
2205                               int match_start_point,
2206                               int max_return_elements,
2207                               bool &word_complete,
2208                               StringList &matches)
2209     {
2210         std::string completion_str (input.GetArgumentAtIndex(cursor_index));
2211         completion_str.erase (cursor_char_position);
2212 
2213         CommandCompletions::InvokeCommonCompletionCallbacks (m_interpreter,
2214                                                              CommandCompletions::eDiskFileCompletion,
2215                                                              completion_str.c_str(),
2216                                                              match_start_point,
2217                                                              max_return_elements,
2218                                                              NULL,
2219                                                              word_complete,
2220                                                              matches);
2221         return matches.GetSize();
2222     }
2223 
2224 };
2225 
2226 class CommandObjectTargetModulesLoad : public CommandObjectTargetModulesModuleAutoComplete
2227 {
2228 public:
2229     CommandObjectTargetModulesLoad (CommandInterpreter &interpreter) :
2230         CommandObjectTargetModulesModuleAutoComplete (interpreter,
2231                                                       "target modules load",
2232                                                       "Set the load addresses for one or more sections in a target module.",
2233                                                       "target modules load [--file <module> --uuid <uuid>] <sect-name> <address> [<sect-name> <address> ....]"),
2234         m_option_group (interpreter),
2235         m_file_option (LLDB_OPT_SET_1, false, "file", 'f', 0, eArgTypePath, "Fullpath or basename for module to load."),
2236         m_slide_option(LLDB_OPT_SET_1, false, "slide", 's', 0, eArgTypeOffset, "Set the load address for all sections to be the virtual address in the file plus the offset.", 0)
2237     {
2238         m_option_group.Append (&m_uuid_option_group, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2239         m_option_group.Append (&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2240         m_option_group.Append (&m_slide_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2241         m_option_group.Finalize();
2242     }
2243 
2244     virtual
2245     ~CommandObjectTargetModulesLoad ()
2246     {
2247     }
2248 
2249     virtual bool
2250     Execute (Args& args,
2251              CommandReturnObject &result)
2252     {
2253         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2254         if (target == NULL)
2255         {
2256             result.AppendError ("invalid target, create a debug target using the 'target create' command");
2257             result.SetStatus (eReturnStatusFailed);
2258             return false;
2259         }
2260         else
2261         {
2262             const size_t argc = args.GetArgumentCount();
2263             const FileSpec *file_ptr = NULL;
2264             const UUID *uuid_ptr = NULL;
2265             if (m_file_option.GetOptionValue().OptionWasSet())
2266                 file_ptr = &m_file_option.GetOptionValue().GetCurrentValue();
2267 
2268             if (m_uuid_option_group.GetOptionValue().OptionWasSet())
2269                 uuid_ptr = &m_uuid_option_group.GetOptionValue().GetCurrentValue();
2270 
2271             if (file_ptr || uuid_ptr)
2272             {
2273 
2274                 ModuleList matching_modules;
2275                 const size_t num_matches = target->GetImages().FindModules (file_ptr,   // File spec to match (can be NULL to match by UUID only)
2276                                                                             NULL,       // Architecture
2277                                                                             uuid_ptr,   // UUID to match (can be NULL to not match on UUID)
2278                                                                             NULL,       // Object name
2279                                                                             matching_modules);
2280 
2281                 char path[PATH_MAX];
2282                 if (num_matches == 1)
2283                 {
2284                     Module *module = matching_modules.GetModulePointerAtIndex(0);
2285                     if (module)
2286                     {
2287                         ObjectFile *objfile = module->GetObjectFile();
2288                         if (objfile)
2289                         {
2290                             SectionList *section_list = objfile->GetSectionList();
2291                             if (section_list)
2292                             {
2293                                 if (argc == 0)
2294                                 {
2295                                     if (m_slide_option.GetOptionValue().OptionWasSet())
2296                                     {
2297                                         Module *module = matching_modules.GetModulePointerAtIndex(0);
2298                                         if (module)
2299                                         {
2300                                             ObjectFile *objfile = module->GetObjectFile();
2301                                             if (objfile)
2302                                             {
2303                                                 SectionList *section_list = objfile->GetSectionList();
2304                                                 if (section_list)
2305                                                 {
2306                                                     const size_t num_sections = section_list->GetSize();
2307                                                     const addr_t slide = m_slide_option.GetOptionValue().GetCurrentValue();
2308                                                     for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx)
2309                                                     {
2310                                                         SectionSP section_sp (section_list->GetSectionAtIndex(sect_idx));
2311                                                         if (section_sp)
2312                                                             target->GetSectionLoadList().SetSectionLoadAddress (section_sp.get(), section_sp->GetFileAddress() + slide);
2313                                                     }
2314                                                 }
2315                                             }
2316                                         }
2317                                     }
2318                                     else
2319                                     {
2320                                         result.AppendError ("one or more section name + load address pair must be specified");
2321                                         result.SetStatus (eReturnStatusFailed);
2322                                         return false;
2323                                     }
2324                                 }
2325                                 else
2326                                 {
2327                                     if (m_slide_option.GetOptionValue().OptionWasSet())
2328                                     {
2329                                         result.AppendError ("The \"--slide <offset>\" option can't be used in conjunction with setting section load addresses.\n");
2330                                         result.SetStatus (eReturnStatusFailed);
2331                                         return false;
2332                                     }
2333 
2334                                     for (size_t i=0; i<argc; i += 2)
2335                                     {
2336                                         const char *sect_name = args.GetArgumentAtIndex(i);
2337                                         const char *load_addr_cstr = args.GetArgumentAtIndex(i+1);
2338                                         if (sect_name && load_addr_cstr)
2339                                         {
2340                                             ConstString const_sect_name(sect_name);
2341                                             bool success = false;
2342                                             addr_t load_addr = Args::StringToUInt64(load_addr_cstr, LLDB_INVALID_ADDRESS, 0, &success);
2343                                             if (success)
2344                                             {
2345                                                 SectionSP section_sp (section_list->FindSectionByName(const_sect_name));
2346                                                 if (section_sp)
2347                                                 {
2348                                                     target->GetSectionLoadList().SetSectionLoadAddress (section_sp.get(), load_addr);
2349                                                     result.AppendMessageWithFormat("section '%s' loaded at 0x%llx\n", sect_name, load_addr);
2350                                                 }
2351                                                 else
2352                                                 {
2353                                                     result.AppendErrorWithFormat ("no section found that matches the section name '%s'\n", sect_name);
2354                                                     result.SetStatus (eReturnStatusFailed);
2355                                                     break;
2356                                                 }
2357                                             }
2358                                             else
2359                                             {
2360                                                 result.AppendErrorWithFormat ("invalid load address string '%s'\n", load_addr_cstr);
2361                                                 result.SetStatus (eReturnStatusFailed);
2362                                                 break;
2363                                             }
2364                                         }
2365                                         else
2366                                         {
2367                                             if (sect_name)
2368                                                 result.AppendError ("section names must be followed by a load address.\n");
2369                                             else
2370                                                 result.AppendError ("one or more section name + load address pair must be specified.\n");
2371                                             result.SetStatus (eReturnStatusFailed);
2372                                             break;
2373                                         }
2374                                     }
2375                                 }
2376                             }
2377                             else
2378                             {
2379                                 module->GetFileSpec().GetPath (path, sizeof(path));
2380                                 result.AppendErrorWithFormat ("no sections in object file '%s'\n", path);
2381                                 result.SetStatus (eReturnStatusFailed);
2382                             }
2383                         }
2384                         else
2385                         {
2386                             module->GetFileSpec().GetPath (path, sizeof(path));
2387                             result.AppendErrorWithFormat ("no object file for module '%s'\n", path);
2388                             result.SetStatus (eReturnStatusFailed);
2389                         }
2390                     }
2391                     else
2392                     {
2393                         module->GetFileSpec().GetPath (path, sizeof(path));
2394                         result.AppendErrorWithFormat ("invalid module '%s'.\n", path);
2395                         result.SetStatus (eReturnStatusFailed);
2396                     }
2397                 }
2398                 else
2399                 {
2400                     char uuid_cstr[64];
2401                     if (file_ptr)
2402                         file_ptr->GetPath (path, sizeof(path));
2403                     else
2404                         path[0] = '\0';
2405 
2406                     if (uuid_ptr)
2407                         uuid_ptr->GetAsCString(uuid_cstr, sizeof(uuid_cstr));
2408                     else
2409                         uuid_cstr[0] = '\0';
2410                     if (num_matches > 1)
2411                     {
2412                         result.AppendErrorWithFormat ("multiple modules match%s%s%s%s:\n",
2413                                                       path[0] ? " file=" : "",
2414                                                       path,
2415                                                       uuid_cstr[0] ? " uuid=" : "",
2416                                                       uuid_cstr);
2417                         for (size_t i=0; i<num_matches; ++i)
2418                         {
2419                             if (matching_modules.GetModulePointerAtIndex(i)->GetFileSpec().GetPath (path, sizeof(path)))
2420                                 result.AppendMessageWithFormat("%s\n", path);
2421                         }
2422                     }
2423                     else
2424                     {
2425                         result.AppendErrorWithFormat ("no modules were found  that match%s%s%s%s.\n",
2426                                                       path[0] ? " file=" : "",
2427                                                       path,
2428                                                       uuid_cstr[0] ? " uuid=" : "",
2429                                                       uuid_cstr);
2430                     }
2431                     result.SetStatus (eReturnStatusFailed);
2432                 }
2433             }
2434             else
2435             {
2436                 result.AppendError ("either the \"--file <module>\" or the \"--uuid <uuid>\" option must be specified.\n");
2437                 result.SetStatus (eReturnStatusFailed);
2438                 return false;
2439             }
2440         }
2441         return result.Succeeded();
2442     }
2443 
2444     virtual Options *
2445     GetOptions ()
2446     {
2447         return &m_option_group;
2448     }
2449 
2450 protected:
2451     OptionGroupOptions m_option_group;
2452     OptionGroupUUID m_uuid_option_group;
2453     OptionGroupFile m_file_option;
2454     OptionGroupUInt64 m_slide_option;
2455 };
2456 
2457 //----------------------------------------------------------------------
2458 // List images with associated information
2459 //----------------------------------------------------------------------
2460 class CommandObjectTargetModulesList : public CommandObject
2461 {
2462 public:
2463 
2464     class CommandOptions : public Options
2465     {
2466     public:
2467 
2468         CommandOptions (CommandInterpreter &interpreter) :
2469         Options(interpreter),
2470         m_format_array()
2471         {
2472         }
2473 
2474         virtual
2475         ~CommandOptions ()
2476         {
2477         }
2478 
2479         virtual Error
2480         SetOptionValue (uint32_t option_idx, const char *option_arg)
2481         {
2482             char short_option = (char) m_getopt_table[option_idx].val;
2483             uint32_t width = 0;
2484             if (option_arg)
2485                 width = strtoul (option_arg, NULL, 0);
2486             m_format_array.push_back(std::make_pair(short_option, width));
2487             Error error;
2488             return error;
2489         }
2490 
2491         void
2492         OptionParsingStarting ()
2493         {
2494             m_format_array.clear();
2495         }
2496 
2497         const OptionDefinition*
2498         GetDefinitions ()
2499         {
2500             return g_option_table;
2501         }
2502 
2503         // Options table: Required for subclasses of Options.
2504 
2505         static OptionDefinition g_option_table[];
2506 
2507         // Instance variables to hold the values for command options.
2508         typedef std::vector< std::pair<char, uint32_t> > FormatWidthCollection;
2509         FormatWidthCollection m_format_array;
2510     };
2511 
2512     CommandObjectTargetModulesList (CommandInterpreter &interpreter) :
2513     CommandObject (interpreter,
2514                    "target modules list",
2515                    "List current executable and dependent shared library images.",
2516                    "target modules list [<cmd-options>]"),
2517         m_options (interpreter)
2518     {
2519     }
2520 
2521     virtual
2522     ~CommandObjectTargetModulesList ()
2523     {
2524     }
2525 
2526     virtual
2527     Options *
2528     GetOptions ()
2529     {
2530         return &m_options;
2531     }
2532 
2533     virtual bool
2534     Execute (Args& command,
2535              CommandReturnObject &result)
2536     {
2537         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2538         if (target == NULL)
2539         {
2540             result.AppendError ("invalid target, create a debug target using the 'target create' command");
2541             result.SetStatus (eReturnStatusFailed);
2542             return false;
2543         }
2544         else
2545         {
2546             uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2547             result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2548             result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2549             // Dump all sections for all modules images
2550             const uint32_t num_modules = target->GetImages().GetSize();
2551             if (num_modules > 0)
2552             {
2553                 Stream &strm = result.GetOutputStream();
2554 
2555                 for (uint32_t image_idx = 0; image_idx<num_modules; ++image_idx)
2556                 {
2557                     Module *module = target->GetImages().GetModulePointerAtIndex(image_idx);
2558                     strm.Printf("[%3u] ", image_idx);
2559 
2560                     bool dump_object_name = false;
2561                     if (m_options.m_format_array.empty())
2562                     {
2563                         DumpFullpath(strm, &module->GetFileSpec(), 0);
2564                         dump_object_name = true;
2565                     }
2566                     else
2567                     {
2568                         const size_t num_entries = m_options.m_format_array.size();
2569                         for (size_t i=0; i<num_entries; ++i)
2570                         {
2571                             if (i > 0)
2572                                 strm.PutChar(' ');
2573                             char format_char = m_options.m_format_array[i].first;
2574                             uint32_t width = m_options.m_format_array[i].second;
2575                             switch (format_char)
2576                             {
2577                                 case 'a':
2578                                     DumpModuleArchitecture (strm, module, false, width);
2579                                     break;
2580 
2581                                 case 't':
2582                                     DumpModuleArchitecture (strm, module, true, width);
2583                                     break;
2584 
2585                                 case 'f':
2586                                     DumpFullpath (strm, &module->GetFileSpec(), width);
2587                                     dump_object_name = true;
2588                                     break;
2589 
2590                                 case 'd':
2591                                     DumpDirectory (strm, &module->GetFileSpec(), width);
2592                                     break;
2593 
2594                                 case 'b':
2595                                     DumpBasename (strm, &module->GetFileSpec(), width);
2596                                     dump_object_name = true;
2597                                     break;
2598 
2599                                 case 's':
2600                                 case 'S':
2601                                 {
2602                                     SymbolVendor *symbol_vendor = module->GetSymbolVendor();
2603                                     if (symbol_vendor)
2604                                     {
2605                                         SymbolFile *symbol_file = symbol_vendor->GetSymbolFile();
2606                                         if (symbol_file)
2607                                         {
2608                                             if (format_char == 'S')
2609                                                 DumpBasename(strm, &symbol_file->GetObjectFile()->GetFileSpec(), width);
2610                                             else
2611                                                 DumpFullpath (strm, &symbol_file->GetObjectFile()->GetFileSpec(), width);
2612                                             dump_object_name = true;
2613                                             break;
2614                                         }
2615                                     }
2616                                     strm.Printf("%.*s", width, "<NONE>");
2617                                 }
2618                                     break;
2619 
2620                                 case 'u':
2621                                     DumpModuleUUID(strm, module);
2622                                     break;
2623 
2624                                 default:
2625                                     break;
2626                             }
2627 
2628                         }
2629                     }
2630                     if (dump_object_name)
2631                     {
2632                         const char *object_name = module->GetObjectName().GetCString();
2633                         if (object_name)
2634                             strm.Printf ("(%s)", object_name);
2635                     }
2636                     strm.EOL();
2637                 }
2638                 result.SetStatus (eReturnStatusSuccessFinishResult);
2639             }
2640             else
2641             {
2642                 result.AppendError ("the target has no associated executable images");
2643                 result.SetStatus (eReturnStatusFailed);
2644                 return false;
2645             }
2646         }
2647         return result.Succeeded();
2648     }
2649 protected:
2650 
2651     CommandOptions m_options;
2652 };
2653 
2654 OptionDefinition
2655 CommandObjectTargetModulesList::CommandOptions::g_option_table[] =
2656 {
2657     { LLDB_OPT_SET_1, false, "arch",       'a', optional_argument, NULL, 0, eArgTypeWidth,   "Display the architecture when listing images."},
2658     { LLDB_OPT_SET_1, false, "triple",     't', optional_argument, NULL, 0, eArgTypeWidth,   "Display the triple when listing images."},
2659     { LLDB_OPT_SET_1, false, "uuid",       'u', no_argument,       NULL, 0, eArgTypeNone,    "Display the UUID when listing images."},
2660     { LLDB_OPT_SET_1, false, "fullpath",   'f', optional_argument, NULL, 0, eArgTypeWidth,   "Display the fullpath to the image object file."},
2661     { LLDB_OPT_SET_1, false, "directory",  'd', optional_argument, NULL, 0, eArgTypeWidth,   "Display the directory with optional width for the image object file."},
2662     { LLDB_OPT_SET_1, false, "basename",   'b', optional_argument, NULL, 0, eArgTypeWidth,   "Display the basename with optional width for the image object file."},
2663     { LLDB_OPT_SET_1, false, "symfile",    's', optional_argument, NULL, 0, eArgTypeWidth,   "Display the fullpath to the image symbol file with optional width."},
2664     { LLDB_OPT_SET_1, false, "symfile-basename", 'S', optional_argument, NULL, 0, eArgTypeWidth,   "Display the basename to the image symbol file with optional width."},
2665     { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
2666 };
2667 
2668 
2669 
2670 //----------------------------------------------------------------------
2671 // Lookup information in images
2672 //----------------------------------------------------------------------
2673 class CommandObjectTargetModulesLookup : public CommandObject
2674 {
2675 public:
2676 
2677     enum
2678     {
2679         eLookupTypeInvalid = -1,
2680         eLookupTypeAddress = 0,
2681         eLookupTypeSymbol,
2682         eLookupTypeFileLine,    // Line is optional
2683         eLookupTypeFunction,
2684         eLookupTypeType,
2685         kNumLookupTypes
2686     };
2687 
2688     class CommandOptions : public Options
2689     {
2690     public:
2691 
2692         CommandOptions (CommandInterpreter &interpreter) :
2693         Options(interpreter)
2694         {
2695             OptionParsingStarting();
2696         }
2697 
2698         virtual
2699         ~CommandOptions ()
2700         {
2701         }
2702 
2703         virtual Error
2704         SetOptionValue (uint32_t option_idx, const char *option_arg)
2705         {
2706             Error error;
2707 
2708             char short_option = (char) m_getopt_table[option_idx].val;
2709 
2710             switch (short_option)
2711             {
2712                 case 'a':
2713                     m_type = eLookupTypeAddress;
2714                     m_addr = Args::StringToUInt64(option_arg, LLDB_INVALID_ADDRESS);
2715                     if (m_addr == LLDB_INVALID_ADDRESS)
2716                         error.SetErrorStringWithFormat ("Invalid address string '%s'.\n", option_arg);
2717                     break;
2718 
2719                 case 'o':
2720                     m_offset = Args::StringToUInt64(option_arg, LLDB_INVALID_ADDRESS);
2721                     if (m_offset == LLDB_INVALID_ADDRESS)
2722                         error.SetErrorStringWithFormat ("Invalid offset string '%s'.\n", option_arg);
2723                     break;
2724 
2725                 case 's':
2726                     m_str = option_arg;
2727                     m_type = eLookupTypeSymbol;
2728                     break;
2729 
2730                 case 'f':
2731                     m_file.SetFile (option_arg, false);
2732                     m_type = eLookupTypeFileLine;
2733                     break;
2734 
2735                 case 'i':
2736                     m_check_inlines = false;
2737                     break;
2738 
2739                 case 'l':
2740                     m_line_number = Args::StringToUInt32(option_arg, UINT32_MAX);
2741                     if (m_line_number == UINT32_MAX)
2742                         error.SetErrorStringWithFormat ("Invalid line number string '%s'.\n", option_arg);
2743                     else if (m_line_number == 0)
2744                         error.SetErrorString ("Zero is an invalid line number.");
2745                     m_type = eLookupTypeFileLine;
2746                     break;
2747 
2748                 case 'n':
2749                     m_str = option_arg;
2750                     m_type = eLookupTypeFunction;
2751                     break;
2752 
2753                 case 't':
2754                     m_str = option_arg;
2755                     m_type = eLookupTypeType;
2756                     break;
2757 
2758                 case 'v':
2759                     m_verbose = 1;
2760                     break;
2761 
2762                 case 'r':
2763                     m_use_regex = true;
2764                     break;
2765             }
2766 
2767             return error;
2768         }
2769 
2770         void
2771         OptionParsingStarting ()
2772         {
2773             m_type = eLookupTypeInvalid;
2774             m_str.clear();
2775             m_file.Clear();
2776             m_addr = LLDB_INVALID_ADDRESS;
2777             m_offset = 0;
2778             m_line_number = 0;
2779             m_use_regex = false;
2780             m_check_inlines = true;
2781             m_verbose = false;
2782         }
2783 
2784         const OptionDefinition*
2785         GetDefinitions ()
2786         {
2787             return g_option_table;
2788         }
2789 
2790         // Options table: Required for subclasses of Options.
2791 
2792         static OptionDefinition g_option_table[];
2793         int             m_type;         // Should be a eLookupTypeXXX enum after parsing options
2794         std::string     m_str;          // Holds name lookup
2795         FileSpec        m_file;         // Files for file lookups
2796         lldb::addr_t    m_addr;         // Holds the address to lookup
2797         lldb::addr_t    m_offset;       // Subtract this offset from m_addr before doing lookups.
2798         uint32_t        m_line_number;  // Line number for file+line lookups
2799         bool            m_use_regex;    // Name lookups in m_str are regular expressions.
2800         bool            m_check_inlines;// Check for inline entries when looking up by file/line.
2801         bool            m_verbose;      // Enable verbose lookup info
2802 
2803     };
2804 
2805     CommandObjectTargetModulesLookup (CommandInterpreter &interpreter) :
2806     CommandObject (interpreter,
2807                    "target modules lookup",
2808                    "Look up information within executable and dependent shared library images.",
2809                    NULL),
2810     m_options (interpreter)
2811     {
2812         CommandArgumentEntry arg;
2813         CommandArgumentData file_arg;
2814 
2815         // Define the first (and only) variant of this arg.
2816         file_arg.arg_type = eArgTypeFilename;
2817         file_arg.arg_repetition = eArgRepeatStar;
2818 
2819         // There is only one variant this argument could be; put it into the argument entry.
2820         arg.push_back (file_arg);
2821 
2822         // Push the data for the first argument into the m_arguments vector.
2823         m_arguments.push_back (arg);
2824     }
2825 
2826     virtual
2827     ~CommandObjectTargetModulesLookup ()
2828     {
2829     }
2830 
2831     virtual Options *
2832     GetOptions ()
2833     {
2834         return &m_options;
2835     }
2836 
2837 
2838     bool
2839     LookupInModule (CommandInterpreter &interpreter, Module *module, CommandReturnObject &result, bool &syntax_error)
2840     {
2841         switch (m_options.m_type)
2842         {
2843             case eLookupTypeAddress:
2844                 if (m_options.m_addr != LLDB_INVALID_ADDRESS)
2845                 {
2846                     if (LookupAddressInModule (m_interpreter,
2847                                                result.GetOutputStream(),
2848                                                module,
2849                                                eSymbolContextEverything,
2850                                                m_options.m_addr,
2851                                                m_options.m_offset,
2852                                                m_options.m_verbose))
2853                     {
2854                         result.SetStatus(eReturnStatusSuccessFinishResult);
2855                         return true;
2856                     }
2857                 }
2858                 break;
2859 
2860             case eLookupTypeSymbol:
2861                 if (!m_options.m_str.empty())
2862                 {
2863                     if (LookupSymbolInModule (m_interpreter, result.GetOutputStream(), module, m_options.m_str.c_str(), m_options.m_use_regex))
2864                     {
2865                         result.SetStatus(eReturnStatusSuccessFinishResult);
2866                         return true;
2867                     }
2868                 }
2869                 break;
2870 
2871             case eLookupTypeFileLine:
2872                 if (m_options.m_file)
2873                 {
2874 
2875                     if (LookupFileAndLineInModule (m_interpreter,
2876                                                    result.GetOutputStream(),
2877                                                    module,
2878                                                    m_options.m_file,
2879                                                    m_options.m_line_number,
2880                                                    m_options.m_check_inlines,
2881                                                    m_options.m_verbose))
2882                     {
2883                         result.SetStatus(eReturnStatusSuccessFinishResult);
2884                         return true;
2885                     }
2886                 }
2887                 break;
2888 
2889             case eLookupTypeFunction:
2890                 if (!m_options.m_str.empty())
2891                 {
2892                     if (LookupFunctionInModule (m_interpreter,
2893                                                 result.GetOutputStream(),
2894                                                 module,
2895                                                 m_options.m_str.c_str(),
2896                                                 m_options.m_use_regex,
2897                                                 m_options.m_verbose))
2898                     {
2899                         result.SetStatus(eReturnStatusSuccessFinishResult);
2900                         return true;
2901                     }
2902                 }
2903                 break;
2904 
2905             case eLookupTypeType:
2906                 if (!m_options.m_str.empty())
2907                 {
2908                     if (LookupTypeInModule (m_interpreter,
2909                                             result.GetOutputStream(),
2910                                             module,
2911                                             m_options.m_str.c_str(),
2912                                             m_options.m_use_regex))
2913                     {
2914                         result.SetStatus(eReturnStatusSuccessFinishResult);
2915                         return true;
2916                     }
2917                 }
2918                 break;
2919 
2920             default:
2921                 m_options.GenerateOptionUsage (result.GetErrorStream(), this);
2922                 syntax_error = true;
2923                 break;
2924         }
2925 
2926         result.SetStatus (eReturnStatusFailed);
2927         return false;
2928     }
2929 
2930     virtual bool
2931     Execute (Args& command,
2932              CommandReturnObject &result)
2933     {
2934         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2935         if (target == NULL)
2936         {
2937             result.AppendError ("invalid target, create a debug target using the 'target create' command");
2938             result.SetStatus (eReturnStatusFailed);
2939             return false;
2940         }
2941         else
2942         {
2943             bool syntax_error = false;
2944             uint32_t i;
2945             uint32_t num_successful_lookups = 0;
2946             uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2947             result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2948             result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2949             // Dump all sections for all modules images
2950 
2951             if (command.GetArgumentCount() == 0)
2952             {
2953                 // Dump all sections for all modules images
2954                 const uint32_t num_modules = target->GetImages().GetSize();
2955                 if (num_modules > 0)
2956                 {
2957                     for (i = 0; i<num_modules && syntax_error == false; ++i)
2958                     {
2959                         if (LookupInModule (m_interpreter, target->GetImages().GetModulePointerAtIndex(i), result, syntax_error))
2960                         {
2961                             result.GetOutputStream().EOL();
2962                             num_successful_lookups++;
2963                         }
2964                     }
2965                 }
2966                 else
2967                 {
2968                     result.AppendError ("the target has no associated executable images");
2969                     result.SetStatus (eReturnStatusFailed);
2970                     return false;
2971                 }
2972             }
2973             else
2974             {
2975                 // Dump specified images (by basename or fullpath)
2976                 const char *arg_cstr;
2977                 for (i = 0; (arg_cstr = command.GetArgumentAtIndex(i)) != NULL && syntax_error == false; ++i)
2978                 {
2979                     FileSpec image_file(arg_cstr, false);
2980                     ModuleList matching_modules;
2981                     size_t num_matching_modules = target->GetImages().FindModules(&image_file, NULL, NULL, NULL, matching_modules);
2982 
2983                     // Not found in our module list for our target, check the main
2984                     // shared module list in case it is a extra file used somewhere
2985                     // else
2986                     if (num_matching_modules == 0)
2987                         num_matching_modules = ModuleList::FindSharedModules (image_file,
2988                                                                               target->GetArchitecture(),
2989                                                                               NULL,
2990                                                                               NULL,
2991                                                                               matching_modules);
2992 
2993                     if (num_matching_modules > 0)
2994                     {
2995                         for (size_t j=0; j<num_matching_modules; ++j)
2996                         {
2997                             Module * image_module = matching_modules.GetModulePointerAtIndex(j);
2998                             if (image_module)
2999                             {
3000                                 if (LookupInModule (m_interpreter, image_module, result, syntax_error))
3001                                 {
3002                                     result.GetOutputStream().EOL();
3003                                     num_successful_lookups++;
3004                                 }
3005                             }
3006                         }
3007                     }
3008                     else
3009                         result.AppendWarningWithFormat("Unable to find an image that matches '%s'.\n", arg_cstr);
3010                 }
3011             }
3012 
3013             if (num_successful_lookups > 0)
3014                 result.SetStatus (eReturnStatusSuccessFinishResult);
3015             else
3016                 result.SetStatus (eReturnStatusFailed);
3017         }
3018         return result.Succeeded();
3019     }
3020 protected:
3021 
3022     CommandOptions m_options;
3023 };
3024 
3025 OptionDefinition
3026 CommandObjectTargetModulesLookup::CommandOptions::g_option_table[] =
3027 {
3028     { LLDB_OPT_SET_1,   true,  "address",    'a', required_argument, NULL, 0, eArgTypeAddress,      "Lookup an address in one or more target modules."},
3029     { LLDB_OPT_SET_1,   false, "offset",     'o', required_argument, NULL, 0, eArgTypeOffset,       "When looking up an address subtract <offset> from any addresses before doing the lookup."},
3030     { LLDB_OPT_SET_2| LLDB_OPT_SET_4
3031       /* FIXME: re-enable this for types when the LookupTypeInModule actually uses the regex option: | LLDB_OPT_SET_5 */ ,
3032                         false, "regex",      'r', no_argument,       NULL, 0, eArgTypeNone,         "The <name> argument for name lookups are regular expressions."},
3033     { LLDB_OPT_SET_2,   true,  "symbol",     's', required_argument, NULL, 0, eArgTypeSymbol,       "Lookup a symbol by name in the symbol tables in one or more target modules."},
3034     { LLDB_OPT_SET_3,   true,  "file",       'f', required_argument, NULL, 0, eArgTypeFilename,     "Lookup a file by fullpath or basename in one or more target modules."},
3035     { LLDB_OPT_SET_3,   false, "line",       'l', required_argument, NULL, 0, eArgTypeLineNum,      "Lookup a line number in a file (must be used in conjunction with --file)."},
3036     { LLDB_OPT_SET_3,   false, "no-inlines", 'i', no_argument,       NULL, 0, eArgTypeNone,         "Check inline line entries (must be used in conjunction with --file)."},
3037     { LLDB_OPT_SET_4,   true,  "function",   'n', required_argument, NULL, 0, eArgTypeFunctionName, "Lookup a function by name in the debug symbols in one or more target modules."},
3038     { LLDB_OPT_SET_5,   true,  "type",       't', required_argument, NULL, 0, eArgTypeName,         "Lookup a type by name in the debug symbols in one or more target modules."},
3039     { LLDB_OPT_SET_ALL, false, "verbose",    'v', no_argument,       NULL, 0, eArgTypeNone,         "Enable verbose lookup information."},
3040     { 0, false, NULL,           0, 0,                 NULL, 0, eArgTypeNone, NULL }
3041 };
3042 
3043 
3044 #pragma mark CommandObjectMultiwordImageSearchPaths
3045 
3046 //-------------------------------------------------------------------------
3047 // CommandObjectMultiwordImageSearchPaths
3048 //-------------------------------------------------------------------------
3049 
3050 class CommandObjectTargetModulesImageSearchPaths : public CommandObjectMultiword
3051 {
3052 public:
3053 
3054     CommandObjectTargetModulesImageSearchPaths (CommandInterpreter &interpreter) :
3055     CommandObjectMultiword (interpreter,
3056                             "target modules search-paths",
3057                             "A set of commands for operating on debugger target image search paths.",
3058                             "target modules search-paths <subcommand> [<subcommand-options>]")
3059     {
3060         LoadSubCommand ("add",     CommandObjectSP (new CommandObjectTargetModulesSearchPathsAdd (interpreter)));
3061         LoadSubCommand ("clear",   CommandObjectSP (new CommandObjectTargetModulesSearchPathsClear (interpreter)));
3062         LoadSubCommand ("insert",  CommandObjectSP (new CommandObjectTargetModulesSearchPathsInsert (interpreter)));
3063         LoadSubCommand ("list",    CommandObjectSP (new CommandObjectTargetModulesSearchPathsList (interpreter)));
3064         LoadSubCommand ("query",   CommandObjectSP (new CommandObjectTargetModulesSearchPathsQuery (interpreter)));
3065     }
3066 
3067     ~CommandObjectTargetModulesImageSearchPaths()
3068     {
3069     }
3070 };
3071 
3072 
3073 
3074 #pragma mark CommandObjectTargetModules
3075 
3076 //-------------------------------------------------------------------------
3077 // CommandObjectTargetModules
3078 //-------------------------------------------------------------------------
3079 
3080 class CommandObjectTargetModules : public CommandObjectMultiword
3081 {
3082 public:
3083     //------------------------------------------------------------------
3084     // Constructors and Destructors
3085     //------------------------------------------------------------------
3086     CommandObjectTargetModules(CommandInterpreter &interpreter) :
3087         CommandObjectMultiword (interpreter,
3088                                 "target modules",
3089                                 "A set of commands for accessing information for one or more target modules.",
3090                                 "target modules <sub-command> ...")
3091     {
3092         LoadSubCommand ("add",          CommandObjectSP (new CommandObjectTargetModulesAdd (interpreter)));
3093         LoadSubCommand ("load",         CommandObjectSP (new CommandObjectTargetModulesLoad (interpreter)));
3094         //LoadSubCommand ("unload",       CommandObjectSP (new CommandObjectTargetModulesUnload (interpreter)));
3095         LoadSubCommand ("dump",         CommandObjectSP (new CommandObjectTargetModulesDump (interpreter)));
3096         LoadSubCommand ("list",         CommandObjectSP (new CommandObjectTargetModulesList (interpreter)));
3097         LoadSubCommand ("lookup",       CommandObjectSP (new CommandObjectTargetModulesLookup (interpreter)));
3098         LoadSubCommand ("search-paths", CommandObjectSP (new CommandObjectTargetModulesImageSearchPaths (interpreter)));
3099 
3100     }
3101     virtual
3102     ~CommandObjectTargetModules()
3103     {
3104     }
3105 
3106 private:
3107     //------------------------------------------------------------------
3108     // For CommandObjectTargetModules only
3109     //------------------------------------------------------------------
3110     DISALLOW_COPY_AND_ASSIGN (CommandObjectTargetModules);
3111 };
3112 
3113 
3114 #pragma mark CommandObjectTargetStopHookAdd
3115 
3116 //-------------------------------------------------------------------------
3117 // CommandObjectTargetStopHookAdd
3118 //-------------------------------------------------------------------------
3119 
3120 class CommandObjectTargetStopHookAdd : public CommandObject
3121 {
3122 public:
3123 
3124     class CommandOptions : public Options
3125     {
3126     public:
3127         CommandOptions (CommandInterpreter &interpreter) :
3128             Options(interpreter),
3129             m_line_start(0),
3130             m_line_end (UINT_MAX),
3131             m_func_name_type_mask (eFunctionNameTypeAuto),
3132             m_sym_ctx_specified (false),
3133             m_thread_specified (false),
3134             m_use_one_liner (false),
3135             m_one_liner()
3136         {
3137         }
3138 
3139         ~CommandOptions () {}
3140 
3141         const OptionDefinition*
3142         GetDefinitions ()
3143         {
3144             return g_option_table;
3145         }
3146 
3147         virtual Error
3148         SetOptionValue (uint32_t option_idx, const char *option_arg)
3149         {
3150             Error error;
3151             char short_option = (char) m_getopt_table[option_idx].val;
3152             bool success;
3153 
3154             switch (short_option)
3155             {
3156                 case 'c':
3157                     m_class_name = option_arg;
3158                     m_sym_ctx_specified = true;
3159                 break;
3160 
3161                 case 'e':
3162                     m_line_end = Args::StringToUInt32 (option_arg, UINT_MAX, 0, &success);
3163                     if (!success)
3164                     {
3165                         error.SetErrorStringWithFormat ("Invalid end line number: \"%s\".", option_arg);
3166                         break;
3167                     }
3168                     m_sym_ctx_specified = true;
3169                 break;
3170 
3171                 case 'l':
3172                     m_line_start = Args::StringToUInt32 (option_arg, 0, 0, &success);
3173                     if (!success)
3174                     {
3175                         error.SetErrorStringWithFormat ("Invalid start line number: \"%s\".", option_arg);
3176                         break;
3177                     }
3178                     m_sym_ctx_specified = true;
3179                 break;
3180 
3181                 case 'n':
3182                     m_function_name = option_arg;
3183                     m_func_name_type_mask |= eFunctionNameTypeAuto;
3184                     m_sym_ctx_specified = true;
3185                 break;
3186 
3187                 case 'f':
3188                     m_file_name = option_arg;
3189                     m_sym_ctx_specified = true;
3190                 break;
3191                 case 's':
3192                     m_module_name = option_arg;
3193                     m_sym_ctx_specified = true;
3194                 break;
3195                 case 't' :
3196                 {
3197                     m_thread_id = Args::StringToUInt64(option_arg, LLDB_INVALID_THREAD_ID, 0);
3198                     if (m_thread_id == LLDB_INVALID_THREAD_ID)
3199                        error.SetErrorStringWithFormat ("Invalid thread id string '%s'.\n", option_arg);
3200                     m_thread_specified = true;
3201                 }
3202                 break;
3203                 case 'T':
3204                     m_thread_name = option_arg;
3205                     m_thread_specified = true;
3206                 break;
3207                 case 'q':
3208                     m_queue_name = option_arg;
3209                     m_thread_specified = true;
3210                     break;
3211                 case 'x':
3212                 {
3213                     m_thread_index = Args::StringToUInt32(option_arg, UINT32_MAX, 0);
3214                     if (m_thread_id == UINT32_MAX)
3215                        error.SetErrorStringWithFormat ("Invalid thread index string '%s'.\n", option_arg);
3216                     m_thread_specified = true;
3217                 }
3218                 break;
3219                 case 'o':
3220                     m_use_one_liner = true;
3221                     m_one_liner = option_arg;
3222                 break;
3223                 default:
3224                     error.SetErrorStringWithFormat ("Unrecognized option %c.");
3225                 break;
3226             }
3227             return error;
3228         }
3229 
3230         void
3231         OptionParsingStarting ()
3232         {
3233             m_class_name.clear();
3234             m_function_name.clear();
3235             m_line_start = 0;
3236             m_line_end = UINT_MAX;
3237             m_file_name.clear();
3238             m_module_name.clear();
3239             m_func_name_type_mask = eFunctionNameTypeAuto;
3240             m_thread_id = LLDB_INVALID_THREAD_ID;
3241             m_thread_index = UINT32_MAX;
3242             m_thread_name.clear();
3243             m_queue_name.clear();
3244 
3245             m_sym_ctx_specified = false;
3246             m_thread_specified = false;
3247 
3248             m_use_one_liner = false;
3249             m_one_liner.clear();
3250         }
3251 
3252 
3253         static OptionDefinition g_option_table[];
3254 
3255         std::string m_class_name;
3256         std::string m_function_name;
3257         uint32_t    m_line_start;
3258         uint32_t    m_line_end;
3259         std::string m_file_name;
3260         std::string m_module_name;
3261         uint32_t m_func_name_type_mask;  // A pick from lldb::FunctionNameType.
3262         lldb::tid_t m_thread_id;
3263         uint32_t m_thread_index;
3264         std::string m_thread_name;
3265         std::string m_queue_name;
3266         bool        m_sym_ctx_specified;
3267         bool        m_thread_specified;
3268         // Instance variables to hold the values for one_liner options.
3269         bool m_use_one_liner;
3270         std::string m_one_liner;
3271     };
3272 
3273     Options *
3274     GetOptions ()
3275     {
3276         return &m_options;
3277     }
3278 
3279     CommandObjectTargetStopHookAdd (CommandInterpreter &interpreter) :
3280         CommandObject (interpreter,
3281                        "target stop-hook add ",
3282                        "Add a hook to be executed when the target stops.",
3283                        "target stop-hook add"),
3284         m_options (interpreter)
3285     {
3286     }
3287 
3288     ~CommandObjectTargetStopHookAdd ()
3289     {
3290     }
3291 
3292     static size_t
3293     ReadCommandsCallbackFunction (void *baton,
3294                                   InputReader &reader,
3295                                   lldb::InputReaderAction notification,
3296                                   const char *bytes,
3297                                   size_t bytes_len)
3298     {
3299         StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
3300         Target::StopHook *new_stop_hook = ((Target::StopHook *) baton);
3301         static bool got_interrupted;
3302         bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
3303 
3304         switch (notification)
3305         {
3306         case eInputReaderActivate:
3307             if (!batch_mode)
3308             {
3309                 out_stream->Printf ("%s\n", "Enter your stop hook command(s).  Type 'DONE' to end.");
3310                 if (reader.GetPrompt())
3311                     out_stream->Printf ("%s", reader.GetPrompt());
3312                 out_stream->Flush();
3313             }
3314             got_interrupted = false;
3315             break;
3316 
3317         case eInputReaderDeactivate:
3318             break;
3319 
3320         case eInputReaderReactivate:
3321             if (reader.GetPrompt() && !batch_mode)
3322             {
3323                 out_stream->Printf ("%s", reader.GetPrompt());
3324                 out_stream->Flush();
3325             }
3326             got_interrupted = false;
3327             break;
3328 
3329         case eInputReaderAsynchronousOutputWritten:
3330             break;
3331 
3332         case eInputReaderGotToken:
3333             if (bytes && bytes_len && baton)
3334             {
3335                 StringList *commands = new_stop_hook->GetCommandPointer();
3336                 if (commands)
3337                 {
3338                     commands->AppendString (bytes, bytes_len);
3339                 }
3340             }
3341             if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
3342             {
3343                 out_stream->Printf ("%s", reader.GetPrompt());
3344                 out_stream->Flush();
3345             }
3346             break;
3347 
3348         case eInputReaderInterrupt:
3349             {
3350                 // Finish, and cancel the stop hook.
3351                 new_stop_hook->GetTarget()->RemoveStopHookByID(new_stop_hook->GetID());
3352                 if (!batch_mode)
3353                 {
3354                     out_stream->Printf ("Stop hook cancelled.\n");
3355                     out_stream->Flush();
3356                 }
3357 
3358                 reader.SetIsDone (true);
3359             }
3360             got_interrupted = true;
3361             break;
3362 
3363         case eInputReaderEndOfFile:
3364             reader.SetIsDone (true);
3365             break;
3366 
3367         case eInputReaderDone:
3368             if (!got_interrupted && !batch_mode)
3369             {
3370                 out_stream->Printf ("Stop hook #%d added.\n", new_stop_hook->GetID());
3371                 out_stream->Flush();
3372             }
3373             break;
3374         }
3375 
3376         return bytes_len;
3377     }
3378 
3379     bool
3380     Execute (Args& command,
3381              CommandReturnObject &result)
3382     {
3383         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
3384         if (target)
3385         {
3386             Target::StopHookSP new_hook_sp;
3387             target->AddStopHook (new_hook_sp);
3388 
3389             //  First step, make the specifier.
3390             std::auto_ptr<SymbolContextSpecifier> specifier_ap;
3391             if (m_options.m_sym_ctx_specified)
3392             {
3393                 specifier_ap.reset(new SymbolContextSpecifier(m_interpreter.GetDebugger().GetSelectedTarget()));
3394 
3395                 if (!m_options.m_module_name.empty())
3396                 {
3397                     specifier_ap->AddSpecification (m_options.m_module_name.c_str(), SymbolContextSpecifier::eModuleSpecified);
3398                 }
3399 
3400                 if (!m_options.m_class_name.empty())
3401                 {
3402                     specifier_ap->AddSpecification (m_options.m_class_name.c_str(), SymbolContextSpecifier::eClassOrNamespaceSpecified);
3403                 }
3404 
3405                 if (!m_options.m_file_name.empty())
3406                 {
3407                     specifier_ap->AddSpecification (m_options.m_file_name.c_str(), SymbolContextSpecifier::eFileSpecified);
3408                 }
3409 
3410                 if (m_options.m_line_start != 0)
3411                 {
3412                     specifier_ap->AddLineSpecification (m_options.m_line_start, SymbolContextSpecifier::eLineStartSpecified);
3413                 }
3414 
3415                 if (m_options.m_line_end != UINT_MAX)
3416                 {
3417                     specifier_ap->AddLineSpecification (m_options.m_line_end, SymbolContextSpecifier::eLineEndSpecified);
3418                 }
3419 
3420                 if (!m_options.m_function_name.empty())
3421                 {
3422                     specifier_ap->AddSpecification (m_options.m_function_name.c_str(), SymbolContextSpecifier::eFunctionSpecified);
3423                 }
3424             }
3425 
3426             if (specifier_ap.get())
3427                 new_hook_sp->SetSpecifier (specifier_ap.release());
3428 
3429             // Next see if any of the thread options have been entered:
3430 
3431             if (m_options.m_thread_specified)
3432             {
3433                 ThreadSpec *thread_spec = new ThreadSpec();
3434 
3435                 if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID)
3436                 {
3437                     thread_spec->SetTID (m_options.m_thread_id);
3438                 }
3439 
3440                 if (m_options.m_thread_index != UINT32_MAX)
3441                     thread_spec->SetIndex (m_options.m_thread_index);
3442 
3443                 if (!m_options.m_thread_name.empty())
3444                     thread_spec->SetName (m_options.m_thread_name.c_str());
3445 
3446                 if (!m_options.m_queue_name.empty())
3447                     thread_spec->SetQueueName (m_options.m_queue_name.c_str());
3448 
3449                 new_hook_sp->SetThreadSpecifier (thread_spec);
3450 
3451             }
3452             if (m_options.m_use_one_liner)
3453             {
3454                 // Use one-liner.
3455                 new_hook_sp->GetCommandPointer()->AppendString (m_options.m_one_liner.c_str());
3456                 result.AppendMessageWithFormat("Stop hook #%d added.\n", new_hook_sp->GetID());
3457             }
3458             else
3459             {
3460                 // Otherwise gather up the command list, we'll push an input reader and suck the data from that directly into
3461                 // the new stop hook's command string.
3462                 InputReaderSP reader_sp (new InputReader(m_interpreter.GetDebugger()));
3463                 if (!reader_sp)
3464                 {
3465                     result.AppendError("out of memory\n");
3466                     result.SetStatus (eReturnStatusFailed);
3467                     target->RemoveStopHookByID (new_hook_sp->GetID());
3468                     return false;
3469                 }
3470 
3471                 Error err (reader_sp->Initialize (CommandObjectTargetStopHookAdd::ReadCommandsCallbackFunction,
3472                                                   new_hook_sp.get(), // baton
3473                                                   eInputReaderGranularityLine,  // token size, to pass to callback function
3474                                                   "DONE",                       // end token
3475                                                   "> ",                         // prompt
3476                                                   true));                       // echo input
3477                 if (!err.Success())
3478                 {
3479                     result.AppendError (err.AsCString());
3480                     result.SetStatus (eReturnStatusFailed);
3481                     target->RemoveStopHookByID (new_hook_sp->GetID());
3482                     return false;
3483                 }
3484                 m_interpreter.GetDebugger().PushInputReader (reader_sp);
3485             }
3486             result.SetStatus (eReturnStatusSuccessFinishNoResult);
3487         }
3488         else
3489         {
3490             result.AppendError ("invalid target\n");
3491             result.SetStatus (eReturnStatusFailed);
3492         }
3493 
3494         return result.Succeeded();
3495     }
3496 private:
3497     CommandOptions m_options;
3498 };
3499 
3500 OptionDefinition
3501 CommandObjectTargetStopHookAdd::CommandOptions::g_option_table[] =
3502 {
3503     { LLDB_OPT_SET_ALL, false, "one-liner", 'o', required_argument, NULL, NULL, eArgTypeOneLiner,
3504         "Specify a one-line breakpoint command inline. Be sure to surround it with quotes." },
3505     { LLDB_OPT_SET_ALL, false, "shlib", 's', required_argument, NULL, CommandCompletions::eModuleCompletion, eArgTypeShlibName,
3506         "Set the module within which the stop-hook is to be run."},
3507     { LLDB_OPT_SET_ALL, false, "thread-index", 'x', required_argument, NULL, NULL, eArgTypeThreadIndex,
3508         "The stop hook is run only for the thread whose index matches this argument."},
3509     { LLDB_OPT_SET_ALL, false, "thread-id", 't', required_argument, NULL, NULL, eArgTypeThreadID,
3510         "The stop hook is run only for the thread whose TID matches this argument."},
3511     { LLDB_OPT_SET_ALL, false, "thread-name", 'T', required_argument, NULL, NULL, eArgTypeThreadName,
3512         "The stop hook is run only for the thread whose thread name matches this argument."},
3513     { LLDB_OPT_SET_ALL, false, "queue-name", 'q', required_argument, NULL, NULL, eArgTypeQueueName,
3514         "The stop hook is run only for threads in the queue whose name is given by this argument."},
3515     { LLDB_OPT_SET_1, false, "file", 'f', required_argument, NULL, CommandCompletions::eSourceFileCompletion, eArgTypeFilename,
3516         "Specify the source file within which the stop-hook is to be run." },
3517     { LLDB_OPT_SET_1, false, "start-line", 'l', required_argument, NULL, 0, eArgTypeLineNum,
3518         "Set the start of the line range for which the stop-hook is to be run."},
3519     { LLDB_OPT_SET_1, false, "end-line", 'e', required_argument, NULL, 0, eArgTypeLineNum,
3520         "Set the end of the line range for which the stop-hook is to be run."},
3521     { LLDB_OPT_SET_2, false, "classname", 'c', required_argument, NULL, NULL, eArgTypeClassName,
3522         "Specify the class within which the stop-hook is to be run." },
3523     { LLDB_OPT_SET_3, false, "name", 'n', required_argument, NULL, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName,
3524         "Set the function name within which the stop hook will be run." },
3525     { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
3526 };
3527 
3528 #pragma mark CommandObjectTargetStopHookDelete
3529 
3530 //-------------------------------------------------------------------------
3531 // CommandObjectTargetStopHookDelete
3532 //-------------------------------------------------------------------------
3533 
3534 class CommandObjectTargetStopHookDelete : public CommandObject
3535 {
3536 public:
3537 
3538     CommandObjectTargetStopHookDelete (CommandInterpreter &interpreter) :
3539         CommandObject (interpreter,
3540                        "target stop-hook delete [<id>]",
3541                        "Delete a stop-hook.",
3542                        "target stop-hook delete")
3543     {
3544     }
3545 
3546     ~CommandObjectTargetStopHookDelete ()
3547     {
3548     }
3549 
3550     bool
3551     Execute (Args& command,
3552              CommandReturnObject &result)
3553     {
3554         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
3555         if (target)
3556         {
3557             // FIXME: see if we can use the breakpoint id style parser?
3558             size_t num_args = command.GetArgumentCount();
3559             if (num_args == 0)
3560             {
3561                 if (!m_interpreter.Confirm ("Delete all stop hooks?", true))
3562                 {
3563                     result.SetStatus (eReturnStatusFailed);
3564                     return false;
3565                 }
3566                 else
3567                 {
3568                     target->RemoveAllStopHooks();
3569                 }
3570             }
3571             else
3572             {
3573                 bool success;
3574                 for (size_t i = 0; i < num_args; i++)
3575                 {
3576                     lldb::user_id_t user_id = Args::StringToUInt32 (command.GetArgumentAtIndex(i), 0, 0, &success);
3577                     if (!success)
3578                     {
3579                         result.AppendErrorWithFormat ("invalid stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i));
3580                         result.SetStatus(eReturnStatusFailed);
3581                         return false;
3582                     }
3583                     success = target->RemoveStopHookByID (user_id);
3584                     if (!success)
3585                     {
3586                         result.AppendErrorWithFormat ("unknown stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i));
3587                         result.SetStatus(eReturnStatusFailed);
3588                         return false;
3589                     }
3590                 }
3591             }
3592             result.SetStatus (eReturnStatusSuccessFinishNoResult);
3593         }
3594         else
3595         {
3596             result.AppendError ("invalid target\n");
3597             result.SetStatus (eReturnStatusFailed);
3598         }
3599 
3600         return result.Succeeded();
3601     }
3602 };
3603 #pragma mark CommandObjectTargetStopHookEnableDisable
3604 
3605 //-------------------------------------------------------------------------
3606 // CommandObjectTargetStopHookEnableDisable
3607 //-------------------------------------------------------------------------
3608 
3609 class CommandObjectTargetStopHookEnableDisable : public CommandObject
3610 {
3611 public:
3612 
3613     CommandObjectTargetStopHookEnableDisable (CommandInterpreter &interpreter, bool enable, const char *name, const char *help, const char *syntax) :
3614         CommandObject (interpreter,
3615                        name,
3616                        help,
3617                        syntax),
3618         m_enable (enable)
3619     {
3620     }
3621 
3622     ~CommandObjectTargetStopHookEnableDisable ()
3623     {
3624     }
3625 
3626     bool
3627     Execute (Args& command,
3628              CommandReturnObject &result)
3629     {
3630         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
3631         if (target)
3632         {
3633             // FIXME: see if we can use the breakpoint id style parser?
3634             size_t num_args = command.GetArgumentCount();
3635             bool success;
3636 
3637             if (num_args == 0)
3638             {
3639                 target->SetAllStopHooksActiveState (m_enable);
3640             }
3641             else
3642             {
3643                 for (size_t i = 0; i < num_args; i++)
3644                 {
3645                     lldb::user_id_t user_id = Args::StringToUInt32 (command.GetArgumentAtIndex(i), 0, 0, &success);
3646                     if (!success)
3647                     {
3648                         result.AppendErrorWithFormat ("invalid stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i));
3649                         result.SetStatus(eReturnStatusFailed);
3650                         return false;
3651                     }
3652                     success = target->SetStopHookActiveStateByID (user_id, m_enable);
3653                     if (!success)
3654                     {
3655                         result.AppendErrorWithFormat ("unknown stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i));
3656                         result.SetStatus(eReturnStatusFailed);
3657                         return false;
3658                     }
3659                 }
3660             }
3661             result.SetStatus (eReturnStatusSuccessFinishNoResult);
3662         }
3663         else
3664         {
3665             result.AppendError ("invalid target\n");
3666             result.SetStatus (eReturnStatusFailed);
3667         }
3668         return result.Succeeded();
3669     }
3670 private:
3671     bool m_enable;
3672 };
3673 
3674 #pragma mark CommandObjectTargetStopHookList
3675 
3676 //-------------------------------------------------------------------------
3677 // CommandObjectTargetStopHookList
3678 //-------------------------------------------------------------------------
3679 
3680 class CommandObjectTargetStopHookList : public CommandObject
3681 {
3682 public:
3683 
3684     CommandObjectTargetStopHookList (CommandInterpreter &interpreter) :
3685         CommandObject (interpreter,
3686                        "target stop-hook list [<type>]",
3687                        "List all stop-hooks.",
3688                        "target stop-hook list")
3689     {
3690     }
3691 
3692     ~CommandObjectTargetStopHookList ()
3693     {
3694     }
3695 
3696     bool
3697     Execute (Args& command,
3698              CommandReturnObject &result)
3699     {
3700         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
3701         if (target)
3702         {
3703             bool notify = true;
3704             target->GetImageSearchPathList().Clear(notify);
3705             result.SetStatus (eReturnStatusSuccessFinishNoResult);
3706         }
3707         else
3708         {
3709             result.AppendError ("invalid target\n");
3710             result.SetStatus (eReturnStatusFailed);
3711         }
3712 
3713         size_t num_hooks = target->GetNumStopHooks ();
3714         if (num_hooks == 0)
3715         {
3716             result.GetOutputStream().PutCString ("No stop hooks.\n");
3717         }
3718         else
3719         {
3720             for (size_t i = 0; i < num_hooks; i++)
3721             {
3722                 Target::StopHookSP this_hook = target->GetStopHookAtIndex (i);
3723                 if (i > 0)
3724                     result.GetOutputStream().PutCString ("\n");
3725                 this_hook->GetDescription (&(result.GetOutputStream()), eDescriptionLevelFull);
3726             }
3727         }
3728         return result.Succeeded();
3729     }
3730 };
3731 
3732 #pragma mark CommandObjectMultiwordTargetStopHooks
3733 //-------------------------------------------------------------------------
3734 // CommandObjectMultiwordTargetStopHooks
3735 //-------------------------------------------------------------------------
3736 
3737 class CommandObjectMultiwordTargetStopHooks : public CommandObjectMultiword
3738 {
3739 public:
3740 
3741     CommandObjectMultiwordTargetStopHooks (CommandInterpreter &interpreter) :
3742         CommandObjectMultiword (interpreter,
3743                                 "target stop-hook",
3744                                 "A set of commands for operating on debugger target stop-hooks.",
3745                                 "target stop-hook <subcommand> [<subcommand-options>]")
3746     {
3747         LoadSubCommand ("add",      CommandObjectSP (new CommandObjectTargetStopHookAdd (interpreter)));
3748         LoadSubCommand ("delete",   CommandObjectSP (new CommandObjectTargetStopHookDelete (interpreter)));
3749         LoadSubCommand ("disable",  CommandObjectSP (new CommandObjectTargetStopHookEnableDisable (interpreter,
3750                                                                                                    false,
3751                                                                                                    "target stop-hook disable [<id>]",
3752                                                                                                    "Disable a stop-hook.",
3753                                                                                                    "target stop-hook disable")));
3754         LoadSubCommand ("enable",   CommandObjectSP (new CommandObjectTargetStopHookEnableDisable (interpreter,
3755                                                                                                    true,
3756                                                                                                    "target stop-hook enable [<id>]",
3757                                                                                                    "Enable a stop-hook.",
3758                                                                                                    "target stop-hook enable")));
3759         LoadSubCommand ("list",     CommandObjectSP (new CommandObjectTargetStopHookList (interpreter)));
3760     }
3761 
3762     ~CommandObjectMultiwordTargetStopHooks()
3763     {
3764     }
3765 };
3766 
3767 
3768 
3769 #pragma mark CommandObjectMultiwordTarget
3770 
3771 //-------------------------------------------------------------------------
3772 // CommandObjectMultiwordTarget
3773 //-------------------------------------------------------------------------
3774 
3775 CommandObjectMultiwordTarget::CommandObjectMultiwordTarget (CommandInterpreter &interpreter) :
3776     CommandObjectMultiword (interpreter,
3777                             "target",
3778                             "A set of commands for operating on debugger targets.",
3779                             "target <subcommand> [<subcommand-options>]")
3780 {
3781 
3782     LoadSubCommand ("create",    CommandObjectSP (new CommandObjectTargetCreate (interpreter)));
3783     LoadSubCommand ("list",      CommandObjectSP (new CommandObjectTargetList   (interpreter)));
3784     LoadSubCommand ("select",    CommandObjectSP (new CommandObjectTargetSelect (interpreter)));
3785     LoadSubCommand ("stop-hook", CommandObjectSP (new CommandObjectMultiwordTargetStopHooks (interpreter)));
3786     LoadSubCommand ("modules",   CommandObjectSP (new CommandObjectTargetModules (interpreter)));
3787     LoadSubCommand ("variable",  CommandObjectSP (new CommandObjectTargetVariable (interpreter)));
3788 }
3789 
3790 CommandObjectMultiwordTarget::~CommandObjectMultiwordTarget ()
3791 {
3792 }
3793 
3794 
3795