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