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