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