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