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