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