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 void
1365 DumpAddress (ExecutionContextScope *exe_scope, const Address &so_addr, bool verbose, Stream &strm)
1366 {
1367     strm.IndentMore();
1368     strm.Indent ("    Address: ");
1369     so_addr.Dump (&strm, exe_scope, Address::DumpStyleModuleWithFileAddress);
1370     strm.PutCString (" (");
1371     so_addr.Dump (&strm, exe_scope, Address::DumpStyleSectionNameOffset);
1372     strm.PutCString (")\n");
1373     strm.Indent ("    Summary: ");
1374     const uint32_t save_indent = strm.GetIndentLevel ();
1375     strm.SetIndentLevel (save_indent + 13);
1376     so_addr.Dump (&strm, exe_scope, Address::DumpStyleResolvedDescription);
1377     strm.SetIndentLevel (save_indent);
1378     // Print out detailed address information when verbose is enabled
1379     if (verbose)
1380     {
1381         strm.EOL();
1382         so_addr.Dump (&strm, exe_scope, Address::DumpStyleDetailedSymbolContext);
1383     }
1384     strm.IndentLess();
1385 }
1386 
1387 static bool
1388 LookupAddressInModule (CommandInterpreter &interpreter,
1389                        Stream &strm,
1390                        Module *module,
1391                        uint32_t resolve_mask,
1392                        lldb::addr_t raw_addr,
1393                        lldb::addr_t offset,
1394                        bool verbose)
1395 {
1396     if (module)
1397     {
1398         lldb::addr_t addr = raw_addr - offset;
1399         Address so_addr;
1400         SymbolContext sc;
1401         Target *target = interpreter.GetExecutionContext().GetTargetPtr();
1402         if (target && !target->GetSectionLoadList().IsEmpty())
1403         {
1404             if (!target->GetSectionLoadList().ResolveLoadAddress (addr, so_addr))
1405                 return false;
1406             else if (so_addr.GetModule().get() != module)
1407                 return false;
1408         }
1409         else
1410         {
1411             if (!module->ResolveFileAddress (addr, so_addr))
1412                 return false;
1413         }
1414 
1415         ExecutionContextScope *exe_scope = interpreter.GetExecutionContext().GetBestExecutionContextScope();
1416         DumpAddress (exe_scope, so_addr, verbose, strm);
1417 //        strm.IndentMore();
1418 //        strm.Indent ("    Address: ");
1419 //        so_addr.Dump (&strm, exe_scope, Address::DumpStyleModuleWithFileAddress);
1420 //        strm.PutCString (" (");
1421 //        so_addr.Dump (&strm, exe_scope, Address::DumpStyleSectionNameOffset);
1422 //        strm.PutCString (")\n");
1423 //        strm.Indent ("    Summary: ");
1424 //        const uint32_t save_indent = strm.GetIndentLevel ();
1425 //        strm.SetIndentLevel (save_indent + 13);
1426 //        so_addr.Dump (&strm, exe_scope, Address::DumpStyleResolvedDescription);
1427 //        strm.SetIndentLevel (save_indent);
1428 //        // Print out detailed address information when verbose is enabled
1429 //        if (verbose)
1430 //        {
1431 //            strm.EOL();
1432 //            so_addr.Dump (&strm, exe_scope, Address::DumpStyleDetailedSymbolContext);
1433 //        }
1434 //        strm.IndentLess();
1435         return true;
1436     }
1437 
1438     return false;
1439 }
1440 
1441 static uint32_t
1442 LookupSymbolInModule (CommandInterpreter &interpreter, Stream &strm, Module *module, const char *name, bool name_is_regex, bool verbose)
1443 {
1444     if (module)
1445     {
1446         SymbolContext sc;
1447 
1448         ObjectFile *objfile = module->GetObjectFile ();
1449         if (objfile)
1450         {
1451             Symtab *symtab = objfile->GetSymtab();
1452             if (symtab)
1453             {
1454                 uint32_t i;
1455                 std::vector<uint32_t> match_indexes;
1456                 ConstString symbol_name (name);
1457                 uint32_t num_matches = 0;
1458                 if (name_is_regex)
1459                 {
1460                     RegularExpression name_regexp(name);
1461                     num_matches = symtab->AppendSymbolIndexesMatchingRegExAndType (name_regexp,
1462                                                                                    eSymbolTypeAny,
1463                                                                                    match_indexes);
1464                 }
1465                 else
1466                 {
1467                     num_matches = symtab->AppendSymbolIndexesWithName (symbol_name, match_indexes);
1468                 }
1469 
1470 
1471                 if (num_matches > 0)
1472                 {
1473                     strm.Indent ();
1474                     strm.Printf("%u symbols match %s'%s' in ", num_matches,
1475                                 name_is_regex ? "the regular expression " : "", name);
1476                     DumpFullpath (strm, &module->GetFileSpec(), 0);
1477                     strm.PutCString(":\n");
1478                     strm.IndentMore ();
1479                     //Symtab::DumpSymbolHeader (&strm);
1480                     for (i=0; i < num_matches; ++i)
1481                     {
1482                         Symbol *symbol = symtab->SymbolAtIndex(match_indexes[i]);
1483                         DumpAddress (interpreter.GetExecutionContext().GetBestExecutionContextScope(),
1484                                      symbol->GetAddress(),
1485                                      verbose,
1486                                      strm);
1487 
1488 //                        strm.Indent ();
1489 //                        symbol->Dump (&strm, interpreter.GetExecutionContext().GetTargetPtr(), i);
1490                     }
1491                     strm.IndentLess ();
1492                     return num_matches;
1493                 }
1494             }
1495         }
1496     }
1497     return 0;
1498 }
1499 
1500 
1501 static void
1502 DumpSymbolContextList (ExecutionContextScope *exe_scope, Stream &strm, SymbolContextList &sc_list, bool verbose)
1503 {
1504     strm.IndentMore ();
1505     uint32_t i;
1506     const uint32_t num_matches = sc_list.GetSize();
1507 
1508     for (i=0; i<num_matches; ++i)
1509     {
1510         SymbolContext sc;
1511         if (sc_list.GetContextAtIndex(i, sc))
1512         {
1513             AddressRange range;
1514 
1515             sc.GetAddressRange(eSymbolContextEverything,
1516                                0,
1517                                true,
1518                                range);
1519 
1520             DumpAddress (exe_scope, range.GetBaseAddress(), verbose, strm);
1521         }
1522     }
1523     strm.IndentLess ();
1524 }
1525 
1526 static uint32_t
1527 LookupFunctionInModule (CommandInterpreter &interpreter,
1528                         Stream &strm,
1529                         Module *module,
1530                         const char *name,
1531                         bool name_is_regex,
1532                         bool include_inlines,
1533                         bool include_symbols,
1534                         bool verbose)
1535 {
1536     if (module && name && name[0])
1537     {
1538         SymbolContextList sc_list;
1539         const bool append = true;
1540         uint32_t num_matches = 0;
1541         if (name_is_regex)
1542         {
1543             RegularExpression function_name_regex (name);
1544             num_matches = module->FindFunctions (function_name_regex,
1545                                                  include_symbols,
1546                                                  include_inlines,
1547                                                  append,
1548                                                  sc_list);
1549         }
1550         else
1551         {
1552             ConstString function_name (name);
1553             num_matches = module->FindFunctions (function_name,
1554                                                  NULL,
1555                                                  eFunctionNameTypeBase | eFunctionNameTypeFull | eFunctionNameTypeMethod | eFunctionNameTypeSelector,
1556                                                  include_symbols,
1557                                                  include_inlines,
1558                                                  append,
1559                                                  sc_list);
1560         }
1561 
1562         if (num_matches)
1563         {
1564             strm.Indent ();
1565             strm.Printf("%u match%s found in ", num_matches, num_matches > 1 ? "es" : "");
1566             DumpFullpath (strm, &module->GetFileSpec(), 0);
1567             strm.PutCString(":\n");
1568             DumpSymbolContextList (interpreter.GetExecutionContext().GetBestExecutionContextScope(), strm, sc_list, verbose);
1569         }
1570         return num_matches;
1571     }
1572     return 0;
1573 }
1574 
1575 static uint32_t
1576 LookupTypeInModule (CommandInterpreter &interpreter,
1577                     Stream &strm,
1578                     Module *module,
1579                     const char *name_cstr,
1580                     bool name_is_regex)
1581 {
1582     if (module && name_cstr && name_cstr[0])
1583     {
1584         TypeList type_list;
1585         const uint32_t max_num_matches = UINT32_MAX;
1586         uint32_t num_matches = 0;
1587         bool name_is_fully_qualified = false;
1588         SymbolContext sc;
1589 
1590         ConstString name(name_cstr);
1591         num_matches = module->FindTypes(sc, name, name_is_fully_qualified, max_num_matches, type_list);
1592 
1593         if (num_matches)
1594         {
1595             strm.Indent ();
1596             strm.Printf("%u match%s found in ", num_matches, num_matches > 1 ? "es" : "");
1597             DumpFullpath (strm, &module->GetFileSpec(), 0);
1598             strm.PutCString(":\n");
1599             const uint32_t num_types = type_list.GetSize();
1600             for (uint32_t i=0; i<num_types; ++i)
1601             {
1602                 TypeSP type_sp (type_list.GetTypeAtIndex(i));
1603                 if (type_sp)
1604                 {
1605                     // Resolve the clang type so that any forward references
1606                     // to types that haven't yet been parsed will get parsed.
1607                     type_sp->GetClangFullType ();
1608                     type_sp->GetDescription (&strm, eDescriptionLevelFull, true);
1609                     // Print all typedef chains
1610                     TypeSP typedef_type_sp (type_sp);
1611                     TypeSP typedefed_type_sp (typedef_type_sp->GetTypedefType());
1612                     while (typedefed_type_sp)
1613                     {
1614                         strm.EOL();
1615                         strm.Printf("     typedef '%s': ", typedef_type_sp->GetName().GetCString());
1616                         typedefed_type_sp->GetClangFullType ();
1617                         typedefed_type_sp->GetDescription (&strm, eDescriptionLevelFull, true);
1618                         typedef_type_sp = typedefed_type_sp;
1619                         typedefed_type_sp = typedef_type_sp->GetTypedefType();
1620                     }
1621                 }
1622                 strm.EOL();
1623             }
1624         }
1625         return num_matches;
1626     }
1627     return 0;
1628 }
1629 
1630 static uint32_t
1631 LookupFileAndLineInModule (CommandInterpreter &interpreter,
1632                            Stream &strm,
1633                            Module *module,
1634                            const FileSpec &file_spec,
1635                            uint32_t line,
1636                            bool check_inlines,
1637                            bool verbose)
1638 {
1639     if (module && file_spec)
1640     {
1641         SymbolContextList sc_list;
1642         const uint32_t num_matches = module->ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines,
1643                                                                               eSymbolContextEverything, sc_list);
1644         if (num_matches > 0)
1645         {
1646             strm.Indent ();
1647             strm.Printf("%u match%s found in ", num_matches, num_matches > 1 ? "es" : "");
1648             strm << file_spec;
1649             if (line > 0)
1650                 strm.Printf (":%u", line);
1651             strm << " in ";
1652             DumpFullpath (strm, &module->GetFileSpec(), 0);
1653             strm.PutCString(":\n");
1654             DumpSymbolContextList (interpreter.GetExecutionContext().GetBestExecutionContextScope(), strm, sc_list, verbose);
1655             return num_matches;
1656         }
1657     }
1658     return 0;
1659 
1660 }
1661 
1662 
1663 static size_t
1664 FindModulesByName (Target *target,
1665                    const char *module_name,
1666                    ModuleList &module_list,
1667                    bool check_global_list)
1668 {
1669 // Dump specified images (by basename or fullpath)
1670     FileSpec module_file_spec(module_name, false);
1671     ModuleSpec module_spec (module_file_spec);
1672 
1673     const size_t initial_size = module_list.GetSize ();
1674 
1675     size_t num_matches = 0;
1676 
1677     if (target)
1678     {
1679         num_matches = target->GetImages().FindModules (module_spec, module_list);
1680 
1681         // Not found in our module list for our target, check the main
1682         // shared module list in case it is a extra file used somewhere
1683         // else
1684         if (num_matches == 0)
1685         {
1686             module_spec.GetArchitecture() = target->GetArchitecture();
1687             num_matches = ModuleList::FindSharedModules (module_spec, module_list);
1688         }
1689     }
1690     else
1691     {
1692         num_matches = ModuleList::FindSharedModules (module_spec,module_list);
1693     }
1694 
1695     if (check_global_list && num_matches == 0)
1696     {
1697         // Check the global list
1698         Mutex::Locker locker(Module::GetAllocationModuleCollectionMutex());
1699         const uint32_t num_modules = Module::GetNumberAllocatedModules();
1700         ModuleSP module_sp;
1701         for (uint32_t image_idx = 0; image_idx<num_modules; ++image_idx)
1702         {
1703             Module *module = Module::GetAllocatedModuleAtIndex(image_idx);
1704 
1705             if (module)
1706             {
1707                 if (module->MatchesModuleSpec (module_spec))
1708                 {
1709                     module_sp = module->shared_from_this();
1710                     module_list.AppendIfNeeded(module_sp);
1711                 }
1712             }
1713         }
1714     }
1715     return module_list.GetSize () - initial_size;
1716 }
1717 
1718 #pragma mark CommandObjectTargetModulesModuleAutoComplete
1719 
1720 //----------------------------------------------------------------------
1721 // A base command object class that can auto complete with module file
1722 // paths
1723 //----------------------------------------------------------------------
1724 
1725 class CommandObjectTargetModulesModuleAutoComplete : public CommandObject
1726 {
1727 public:
1728 
1729     CommandObjectTargetModulesModuleAutoComplete (CommandInterpreter &interpreter,
1730                                       const char *name,
1731                                       const char *help,
1732                                       const char *syntax) :
1733     CommandObject (interpreter, name, help, syntax)
1734     {
1735         CommandArgumentEntry arg;
1736         CommandArgumentData file_arg;
1737 
1738         // Define the first (and only) variant of this arg.
1739         file_arg.arg_type = eArgTypeFilename;
1740         file_arg.arg_repetition = eArgRepeatStar;
1741 
1742         // There is only one variant this argument could be; put it into the argument entry.
1743         arg.push_back (file_arg);
1744 
1745         // Push the data for the first argument into the m_arguments vector.
1746         m_arguments.push_back (arg);
1747     }
1748 
1749     virtual
1750     ~CommandObjectTargetModulesModuleAutoComplete ()
1751     {
1752     }
1753 
1754     virtual int
1755     HandleArgumentCompletion (Args &input,
1756                               int &cursor_index,
1757                               int &cursor_char_position,
1758                               OptionElementVector &opt_element_vector,
1759                               int match_start_point,
1760                               int max_return_elements,
1761                               bool &word_complete,
1762                               StringList &matches)
1763     {
1764         // Arguments are the standard module completer.
1765         std::string completion_str (input.GetArgumentAtIndex(cursor_index));
1766         completion_str.erase (cursor_char_position);
1767 
1768         CommandCompletions::InvokeCommonCompletionCallbacks (m_interpreter,
1769                                                              CommandCompletions::eModuleCompletion,
1770                                                              completion_str.c_str(),
1771                                                              match_start_point,
1772                                                              max_return_elements,
1773                                                              NULL,
1774                                                              word_complete,
1775                                                              matches);
1776         return matches.GetSize();
1777     }
1778 };
1779 
1780 #pragma mark CommandObjectTargetModulesSourceFileAutoComplete
1781 
1782 //----------------------------------------------------------------------
1783 // A base command object class that can auto complete with module source
1784 // file paths
1785 //----------------------------------------------------------------------
1786 
1787 class CommandObjectTargetModulesSourceFileAutoComplete : public CommandObject
1788 {
1789 public:
1790 
1791     CommandObjectTargetModulesSourceFileAutoComplete (CommandInterpreter &interpreter,
1792                                           const char *name,
1793                                           const char *help,
1794                                           const char *syntax) :
1795     CommandObject (interpreter, name, help, syntax)
1796     {
1797         CommandArgumentEntry arg;
1798         CommandArgumentData source_file_arg;
1799 
1800         // Define the first (and only) variant of this arg.
1801         source_file_arg.arg_type = eArgTypeSourceFile;
1802         source_file_arg.arg_repetition = eArgRepeatPlus;
1803 
1804         // There is only one variant this argument could be; put it into the argument entry.
1805         arg.push_back (source_file_arg);
1806 
1807         // Push the data for the first argument into the m_arguments vector.
1808         m_arguments.push_back (arg);
1809     }
1810 
1811     virtual
1812     ~CommandObjectTargetModulesSourceFileAutoComplete ()
1813     {
1814     }
1815 
1816     virtual int
1817     HandleArgumentCompletion (Args &input,
1818                               int &cursor_index,
1819                               int &cursor_char_position,
1820                               OptionElementVector &opt_element_vector,
1821                               int match_start_point,
1822                               int max_return_elements,
1823                               bool &word_complete,
1824                               StringList &matches)
1825     {
1826         // Arguments are the standard source file completer.
1827         std::string completion_str (input.GetArgumentAtIndex(cursor_index));
1828         completion_str.erase (cursor_char_position);
1829 
1830         CommandCompletions::InvokeCommonCompletionCallbacks (m_interpreter,
1831                                                              CommandCompletions::eSourceFileCompletion,
1832                                                              completion_str.c_str(),
1833                                                              match_start_point,
1834                                                              max_return_elements,
1835                                                              NULL,
1836                                                              word_complete,
1837                                                              matches);
1838         return matches.GetSize();
1839     }
1840 };
1841 
1842 
1843 #pragma mark CommandObjectTargetModulesDumpSymtab
1844 
1845 
1846 class CommandObjectTargetModulesDumpSymtab : public CommandObjectTargetModulesModuleAutoComplete
1847 {
1848 public:
1849     CommandObjectTargetModulesDumpSymtab (CommandInterpreter &interpreter) :
1850     CommandObjectTargetModulesModuleAutoComplete (interpreter,
1851                                       "target modules dump symtab",
1852                                       "Dump the symbol table from one or more target modules.",
1853                                       NULL),
1854     m_options (interpreter)
1855     {
1856     }
1857 
1858     virtual
1859     ~CommandObjectTargetModulesDumpSymtab ()
1860     {
1861     }
1862 
1863     virtual bool
1864     Execute (Args& command,
1865              CommandReturnObject &result)
1866     {
1867         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1868         if (target == NULL)
1869         {
1870             result.AppendError ("invalid target, create a debug target using the 'target create' command");
1871             result.SetStatus (eReturnStatusFailed);
1872             return false;
1873         }
1874         else
1875         {
1876             uint32_t num_dumped = 0;
1877 
1878             uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
1879             result.GetOutputStream().SetAddressByteSize(addr_byte_size);
1880             result.GetErrorStream().SetAddressByteSize(addr_byte_size);
1881 
1882             if (command.GetArgumentCount() == 0)
1883             {
1884                 // Dump all sections for all modules images
1885                 const uint32_t num_modules = target->GetImages().GetSize();
1886                 if (num_modules > 0)
1887                 {
1888                     result.GetOutputStream().Printf("Dumping symbol table for %u modules.\n", num_modules);
1889                     for (uint32_t image_idx = 0;  image_idx<num_modules; ++image_idx)
1890                     {
1891                         if (num_dumped > 0)
1892                         {
1893                             result.GetOutputStream().EOL();
1894                             result.GetOutputStream().EOL();
1895                         }
1896                         num_dumped++;
1897                         DumpModuleSymtab (m_interpreter, result.GetOutputStream(), target->GetImages().GetModulePointerAtIndex(image_idx), m_options.m_sort_order);
1898                     }
1899                 }
1900                 else
1901                 {
1902                     result.AppendError ("the target has no associated executable images");
1903                     result.SetStatus (eReturnStatusFailed);
1904                     return false;
1905                 }
1906             }
1907             else
1908             {
1909                 // Dump specified images (by basename or fullpath)
1910                 const char *arg_cstr;
1911                 for (int arg_idx = 0; (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != NULL; ++arg_idx)
1912                 {
1913                     ModuleList module_list;
1914                     const size_t num_matches = FindModulesByName (target, arg_cstr, module_list, true);
1915                     if (num_matches > 0)
1916                     {
1917                         for (size_t i=0; i<num_matches; ++i)
1918                         {
1919                             Module *module = module_list.GetModulePointerAtIndex(i);
1920                             if (module)
1921                             {
1922                                 if (num_dumped > 0)
1923                                 {
1924                                     result.GetOutputStream().EOL();
1925                                     result.GetOutputStream().EOL();
1926                                 }
1927                                 num_dumped++;
1928                                 DumpModuleSymtab (m_interpreter, result.GetOutputStream(), module, m_options.m_sort_order);
1929                             }
1930                         }
1931                     }
1932                     else
1933                         result.AppendWarningWithFormat("Unable to find an image that matches '%s'.\n", arg_cstr);
1934                 }
1935             }
1936 
1937             if (num_dumped > 0)
1938                 result.SetStatus (eReturnStatusSuccessFinishResult);
1939             else
1940             {
1941                 result.AppendError ("no matching executable images found");
1942                 result.SetStatus (eReturnStatusFailed);
1943             }
1944         }
1945         return result.Succeeded();
1946     }
1947 
1948     virtual Options *
1949     GetOptions ()
1950     {
1951         return &m_options;
1952     }
1953 
1954     class CommandOptions : public Options
1955     {
1956     public:
1957 
1958         CommandOptions (CommandInterpreter &interpreter) :
1959         Options(interpreter),
1960         m_sort_order (eSortOrderNone)
1961         {
1962         }
1963 
1964         virtual
1965         ~CommandOptions ()
1966         {
1967         }
1968 
1969         virtual Error
1970         SetOptionValue (uint32_t option_idx, const char *option_arg)
1971         {
1972             Error error;
1973             char short_option = (char) m_getopt_table[option_idx].val;
1974 
1975             switch (short_option)
1976             {
1977                 case 's':
1978                     m_sort_order = (SortOrder) Args::StringToOptionEnum (option_arg,
1979                                                                          g_option_table[option_idx].enum_values,
1980                                                                          eSortOrderNone,
1981                                                                          error);
1982                     break;
1983 
1984                 default:
1985                     error.SetErrorStringWithFormat("invalid short option character '%c'", short_option);
1986                     break;
1987 
1988             }
1989             return error;
1990         }
1991 
1992         void
1993         OptionParsingStarting ()
1994         {
1995             m_sort_order = eSortOrderNone;
1996         }
1997 
1998         const OptionDefinition*
1999         GetDefinitions ()
2000         {
2001             return g_option_table;
2002         }
2003 
2004         // Options table: Required for subclasses of Options.
2005         static OptionDefinition g_option_table[];
2006 
2007         SortOrder m_sort_order;
2008     };
2009 
2010 protected:
2011 
2012     CommandOptions m_options;
2013 };
2014 
2015 static OptionEnumValueElement
2016 g_sort_option_enumeration[4] =
2017 {
2018     { eSortOrderNone,       "none",     "No sorting, use the original symbol table order."},
2019     { eSortOrderByAddress,  "address",  "Sort output by symbol address."},
2020     { eSortOrderByName,     "name",     "Sort output by symbol name."},
2021     { 0,                    NULL,       NULL }
2022 };
2023 
2024 
2025 OptionDefinition
2026 CommandObjectTargetModulesDumpSymtab::CommandOptions::g_option_table[] =
2027 {
2028     { LLDB_OPT_SET_1, false, "sort", 's', required_argument, g_sort_option_enumeration, 0, eArgTypeSortOrder, "Supply a sort order when dumping the symbol table."},
2029     { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
2030 };
2031 
2032 #pragma mark CommandObjectTargetModulesDumpSections
2033 
2034 //----------------------------------------------------------------------
2035 // Image section dumping command
2036 //----------------------------------------------------------------------
2037 
2038 class CommandObjectTargetModulesDumpSections : public CommandObjectTargetModulesModuleAutoComplete
2039 {
2040 public:
2041     CommandObjectTargetModulesDumpSections (CommandInterpreter &interpreter) :
2042     CommandObjectTargetModulesModuleAutoComplete (interpreter,
2043                                       "target modules dump sections",
2044                                       "Dump the sections from one or more target modules.",
2045                                       //"target modules dump sections [<file1> ...]")
2046                                       NULL)
2047     {
2048     }
2049 
2050     virtual
2051     ~CommandObjectTargetModulesDumpSections ()
2052     {
2053     }
2054 
2055     virtual bool
2056     Execute (Args& command,
2057              CommandReturnObject &result)
2058     {
2059         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2060         if (target == NULL)
2061         {
2062             result.AppendError ("invalid target, create a debug target using the 'target create' command");
2063             result.SetStatus (eReturnStatusFailed);
2064             return false;
2065         }
2066         else
2067         {
2068             uint32_t num_dumped = 0;
2069 
2070             uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2071             result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2072             result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2073 
2074             if (command.GetArgumentCount() == 0)
2075             {
2076                 // Dump all sections for all modules images
2077                 const uint32_t num_modules = target->GetImages().GetSize();
2078                 if (num_modules > 0)
2079                 {
2080                     result.GetOutputStream().Printf("Dumping sections for %u modules.\n", num_modules);
2081                     for (uint32_t image_idx = 0;  image_idx<num_modules; ++image_idx)
2082                     {
2083                         num_dumped++;
2084                         DumpModuleSections (m_interpreter, result.GetOutputStream(), target->GetImages().GetModulePointerAtIndex(image_idx));
2085                     }
2086                 }
2087                 else
2088                 {
2089                     result.AppendError ("the target has no associated executable images");
2090                     result.SetStatus (eReturnStatusFailed);
2091                     return false;
2092                 }
2093             }
2094             else
2095             {
2096                 // Dump specified images (by basename or fullpath)
2097                 const char *arg_cstr;
2098                 for (int arg_idx = 0; (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != NULL; ++arg_idx)
2099                 {
2100                     ModuleList module_list;
2101                     const size_t num_matches = FindModulesByName (target, arg_cstr, module_list, true);
2102                     if (num_matches > 0)
2103                     {
2104                         for (size_t i=0; i<num_matches; ++i)
2105                         {
2106                             Module *module = module_list.GetModulePointerAtIndex(i);
2107                             if (module)
2108                             {
2109                                 num_dumped++;
2110                                 DumpModuleSections (m_interpreter, result.GetOutputStream(), module);
2111                             }
2112                         }
2113                     }
2114                     else
2115                     {
2116                         // Check the global list
2117                         Mutex::Locker locker(Module::GetAllocationModuleCollectionMutex());
2118 
2119                         result.AppendWarningWithFormat("Unable to find an image that matches '%s'.\n", arg_cstr);
2120                     }
2121                 }
2122             }
2123 
2124             if (num_dumped > 0)
2125                 result.SetStatus (eReturnStatusSuccessFinishResult);
2126             else
2127             {
2128                 result.AppendError ("no matching executable images found");
2129                 result.SetStatus (eReturnStatusFailed);
2130             }
2131         }
2132         return result.Succeeded();
2133     }
2134 };
2135 
2136 
2137 #pragma mark CommandObjectTargetModulesDumpSymfile
2138 
2139 //----------------------------------------------------------------------
2140 // Image debug symbol dumping command
2141 //----------------------------------------------------------------------
2142 
2143 class CommandObjectTargetModulesDumpSymfile : public CommandObjectTargetModulesModuleAutoComplete
2144 {
2145 public:
2146     CommandObjectTargetModulesDumpSymfile (CommandInterpreter &interpreter) :
2147     CommandObjectTargetModulesModuleAutoComplete (interpreter,
2148                                       "target modules dump symfile",
2149                                       "Dump the debug symbol file for one or more target modules.",
2150                                       //"target modules dump symfile [<file1> ...]")
2151                                       NULL)
2152     {
2153     }
2154 
2155     virtual
2156     ~CommandObjectTargetModulesDumpSymfile ()
2157     {
2158     }
2159 
2160     virtual bool
2161     Execute (Args& command,
2162              CommandReturnObject &result)
2163     {
2164         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2165         if (target == NULL)
2166         {
2167             result.AppendError ("invalid target, create a debug target using the 'target create' command");
2168             result.SetStatus (eReturnStatusFailed);
2169             return false;
2170         }
2171         else
2172         {
2173             uint32_t num_dumped = 0;
2174 
2175             uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2176             result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2177             result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2178 
2179             if (command.GetArgumentCount() == 0)
2180             {
2181                 // Dump all sections for all modules images
2182                 const uint32_t num_modules = target->GetImages().GetSize();
2183                 if (num_modules > 0)
2184                 {
2185                     result.GetOutputStream().Printf("Dumping debug symbols for %u modules.\n", num_modules);
2186                     for (uint32_t image_idx = 0;  image_idx<num_modules; ++image_idx)
2187                     {
2188                         if (DumpModuleSymbolVendor (result.GetOutputStream(), target->GetImages().GetModulePointerAtIndex(image_idx)))
2189                             num_dumped++;
2190                     }
2191                 }
2192                 else
2193                 {
2194                     result.AppendError ("the target has no associated executable images");
2195                     result.SetStatus (eReturnStatusFailed);
2196                     return false;
2197                 }
2198             }
2199             else
2200             {
2201                 // Dump specified images (by basename or fullpath)
2202                 const char *arg_cstr;
2203                 for (int arg_idx = 0; (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != NULL; ++arg_idx)
2204                 {
2205                     ModuleList module_list;
2206                     const size_t num_matches = FindModulesByName (target, arg_cstr, module_list, true);
2207                     if (num_matches > 0)
2208                     {
2209                         for (size_t i=0; i<num_matches; ++i)
2210                         {
2211                             Module *module = module_list.GetModulePointerAtIndex(i);
2212                             if (module)
2213                             {
2214                                 if (DumpModuleSymbolVendor (result.GetOutputStream(), module))
2215                                     num_dumped++;
2216                             }
2217                         }
2218                     }
2219                     else
2220                         result.AppendWarningWithFormat("Unable to find an image that matches '%s'.\n", arg_cstr);
2221                 }
2222             }
2223 
2224             if (num_dumped > 0)
2225                 result.SetStatus (eReturnStatusSuccessFinishResult);
2226             else
2227             {
2228                 result.AppendError ("no matching executable images found");
2229                 result.SetStatus (eReturnStatusFailed);
2230             }
2231         }
2232         return result.Succeeded();
2233     }
2234 };
2235 
2236 
2237 #pragma mark CommandObjectTargetModulesDumpLineTable
2238 
2239 //----------------------------------------------------------------------
2240 // Image debug line table dumping command
2241 //----------------------------------------------------------------------
2242 
2243 class CommandObjectTargetModulesDumpLineTable : public CommandObjectTargetModulesSourceFileAutoComplete
2244 {
2245 public:
2246     CommandObjectTargetModulesDumpLineTable (CommandInterpreter &interpreter) :
2247     CommandObjectTargetModulesSourceFileAutoComplete (interpreter,
2248                                           "target modules dump line-table",
2249                                           "Dump the debug symbol file for one or more target modules.",
2250                                           NULL)
2251     {
2252     }
2253 
2254     virtual
2255     ~CommandObjectTargetModulesDumpLineTable ()
2256     {
2257     }
2258 
2259     virtual bool
2260     Execute (Args& command,
2261              CommandReturnObject &result)
2262     {
2263         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2264         if (target == NULL)
2265         {
2266             result.AppendError ("invalid target, create a debug target using the 'target create' command");
2267             result.SetStatus (eReturnStatusFailed);
2268             return false;
2269         }
2270         else
2271         {
2272             ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
2273             uint32_t total_num_dumped = 0;
2274 
2275             uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2276             result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2277             result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2278 
2279             if (command.GetArgumentCount() == 0)
2280             {
2281                 result.AppendErrorWithFormat ("\nSyntax: %s\n", m_cmd_syntax.c_str());
2282                 result.SetStatus (eReturnStatusFailed);
2283             }
2284             else
2285             {
2286                 // Dump specified images (by basename or fullpath)
2287                 const char *arg_cstr;
2288                 for (int arg_idx = 0; (arg_cstr = command.GetArgumentAtIndex(arg_idx)) != NULL; ++arg_idx)
2289                 {
2290                     FileSpec file_spec(arg_cstr, false);
2291                     const uint32_t num_modules = target->GetImages().GetSize();
2292                     if (num_modules > 0)
2293                     {
2294                         uint32_t num_dumped = 0;
2295                         for (uint32_t i = 0; i<num_modules; ++i)
2296                         {
2297                             if (DumpCompileUnitLineTable (m_interpreter,
2298                                                           result.GetOutputStream(),
2299                                                           target->GetImages().GetModulePointerAtIndex(i),
2300                                                           file_spec,
2301                                                           exe_ctx.GetProcessPtr() && exe_ctx.GetProcessRef().IsAlive()))
2302                                 num_dumped++;
2303                         }
2304                         if (num_dumped == 0)
2305                             result.AppendWarningWithFormat ("No source filenames matched '%s'.\n", arg_cstr);
2306                         else
2307                             total_num_dumped += num_dumped;
2308                     }
2309                 }
2310             }
2311 
2312             if (total_num_dumped > 0)
2313                 result.SetStatus (eReturnStatusSuccessFinishResult);
2314             else
2315             {
2316                 result.AppendError ("no source filenames matched any command arguments");
2317                 result.SetStatus (eReturnStatusFailed);
2318             }
2319         }
2320         return result.Succeeded();
2321     }
2322 };
2323 
2324 
2325 #pragma mark CommandObjectTargetModulesDump
2326 
2327 //----------------------------------------------------------------------
2328 // Dump multi-word command for target modules
2329 //----------------------------------------------------------------------
2330 
2331 class CommandObjectTargetModulesDump : public CommandObjectMultiword
2332 {
2333 public:
2334 
2335     //------------------------------------------------------------------
2336     // Constructors and Destructors
2337     //------------------------------------------------------------------
2338     CommandObjectTargetModulesDump(CommandInterpreter &interpreter) :
2339     CommandObjectMultiword (interpreter,
2340                             "target modules dump",
2341                             "A set of commands for dumping information about one or more target modules.",
2342                             "target modules dump [symtab|sections|symfile|line-table] [<file1> <file2> ...]")
2343     {
2344         LoadSubCommand ("symtab",      CommandObjectSP (new CommandObjectTargetModulesDumpSymtab (interpreter)));
2345         LoadSubCommand ("sections",    CommandObjectSP (new CommandObjectTargetModulesDumpSections (interpreter)));
2346         LoadSubCommand ("symfile",     CommandObjectSP (new CommandObjectTargetModulesDumpSymfile (interpreter)));
2347         LoadSubCommand ("line-table",  CommandObjectSP (new CommandObjectTargetModulesDumpLineTable (interpreter)));
2348     }
2349 
2350     virtual
2351     ~CommandObjectTargetModulesDump()
2352     {
2353     }
2354 };
2355 
2356 class CommandObjectTargetModulesAdd : public CommandObject
2357 {
2358 public:
2359     CommandObjectTargetModulesAdd (CommandInterpreter &interpreter) :
2360     CommandObject (interpreter,
2361                    "target modules add",
2362                    "Add a new module to the current target's modules.",
2363                    "target modules add [<module>]")
2364     {
2365     }
2366 
2367     virtual
2368     ~CommandObjectTargetModulesAdd ()
2369     {
2370     }
2371 
2372     virtual bool
2373     Execute (Args& args,
2374              CommandReturnObject &result)
2375     {
2376         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2377         if (target == NULL)
2378         {
2379             result.AppendError ("invalid target, create a debug target using the 'target create' command");
2380             result.SetStatus (eReturnStatusFailed);
2381             return false;
2382         }
2383         else
2384         {
2385             const size_t argc = args.GetArgumentCount();
2386             if (argc == 0)
2387             {
2388                 result.AppendError ("one or more executable image paths must be specified");
2389                 result.SetStatus (eReturnStatusFailed);
2390                 return false;
2391             }
2392             else
2393             {
2394                 for (size_t i=0; i<argc; ++i)
2395                 {
2396                     const char *path = args.GetArgumentAtIndex(i);
2397                     if (path)
2398                     {
2399                         FileSpec file_spec(path, true);
2400                         if (file_spec.Exists())
2401                         {
2402                             ModuleSpec module_spec (file_spec);
2403                             ModuleSP module_sp (target->GetSharedModule (module_spec));
2404                             if (!module_sp)
2405                             {
2406                                 result.AppendError ("one or more executable image paths must be specified");
2407                                 result.SetStatus (eReturnStatusFailed);
2408                                 return false;
2409                             }
2410                             result.SetStatus (eReturnStatusSuccessFinishResult);
2411                         }
2412                         else
2413                         {
2414                             char resolved_path[PATH_MAX];
2415                             result.SetStatus (eReturnStatusFailed);
2416                             if (file_spec.GetPath (resolved_path, sizeof(resolved_path)))
2417                             {
2418                                 if (strcmp (resolved_path, path) != 0)
2419                                 {
2420                                     result.AppendErrorWithFormat ("invalid module path '%s' with resolved path '%s'\n", path, resolved_path);
2421                                     break;
2422                                 }
2423                             }
2424                             result.AppendErrorWithFormat ("invalid module path '%s'\n", path);
2425                             break;
2426                         }
2427                     }
2428                 }
2429             }
2430         }
2431         return result.Succeeded();
2432     }
2433 
2434     int
2435     HandleArgumentCompletion (Args &input,
2436                               int &cursor_index,
2437                               int &cursor_char_position,
2438                               OptionElementVector &opt_element_vector,
2439                               int match_start_point,
2440                               int max_return_elements,
2441                               bool &word_complete,
2442                               StringList &matches)
2443     {
2444         std::string completion_str (input.GetArgumentAtIndex(cursor_index));
2445         completion_str.erase (cursor_char_position);
2446 
2447         CommandCompletions::InvokeCommonCompletionCallbacks (m_interpreter,
2448                                                              CommandCompletions::eDiskFileCompletion,
2449                                                              completion_str.c_str(),
2450                                                              match_start_point,
2451                                                              max_return_elements,
2452                                                              NULL,
2453                                                              word_complete,
2454                                                              matches);
2455         return matches.GetSize();
2456     }
2457 
2458 };
2459 
2460 class CommandObjectTargetModulesLoad : public CommandObjectTargetModulesModuleAutoComplete
2461 {
2462 public:
2463     CommandObjectTargetModulesLoad (CommandInterpreter &interpreter) :
2464         CommandObjectTargetModulesModuleAutoComplete (interpreter,
2465                                                       "target modules load",
2466                                                       "Set the load addresses for one or more sections in a target module.",
2467                                                       "target modules load [--file <module> --uuid <uuid>] <sect-name> <address> [<sect-name> <address> ....]"),
2468         m_option_group (interpreter),
2469         m_file_option (LLDB_OPT_SET_1, false, "file", 'f', 0, eArgTypePath, "Fullpath or basename for module to load."),
2470         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)
2471     {
2472         m_option_group.Append (&m_uuid_option_group, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2473         m_option_group.Append (&m_file_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2474         m_option_group.Append (&m_slide_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
2475         m_option_group.Finalize();
2476     }
2477 
2478     virtual
2479     ~CommandObjectTargetModulesLoad ()
2480     {
2481     }
2482 
2483     virtual bool
2484     Execute (Args& args,
2485              CommandReturnObject &result)
2486     {
2487         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2488         if (target == NULL)
2489         {
2490             result.AppendError ("invalid target, create a debug target using the 'target create' command");
2491             result.SetStatus (eReturnStatusFailed);
2492             return false;
2493         }
2494         else
2495         {
2496             const size_t argc = args.GetArgumentCount();
2497             ModuleSpec module_spec;
2498             bool search_using_module_spec = false;
2499             if (m_file_option.GetOptionValue().OptionWasSet())
2500             {
2501                 search_using_module_spec = true;
2502                 module_spec.GetFileSpec() = m_file_option.GetOptionValue().GetCurrentValue();
2503             }
2504 
2505             if (m_uuid_option_group.GetOptionValue().OptionWasSet())
2506             {
2507                 search_using_module_spec = true;
2508                 module_spec.GetUUID() = m_uuid_option_group.GetOptionValue().GetCurrentValue();
2509             }
2510 
2511             if (search_using_module_spec)
2512             {
2513 
2514                 ModuleList matching_modules;
2515                 const size_t num_matches = target->GetImages().FindModules (module_spec, matching_modules);
2516 
2517                 char path[PATH_MAX];
2518                 if (num_matches == 1)
2519                 {
2520                     Module *module = matching_modules.GetModulePointerAtIndex(0);
2521                     if (module)
2522                     {
2523                         ObjectFile *objfile = module->GetObjectFile();
2524                         if (objfile)
2525                         {
2526                             SectionList *section_list = objfile->GetSectionList();
2527                             if (section_list)
2528                             {
2529                                 bool changed = false;
2530                                 if (argc == 0)
2531                                 {
2532                                     if (m_slide_option.GetOptionValue().OptionWasSet())
2533                                     {
2534                                         const addr_t slide = m_slide_option.GetOptionValue().GetCurrentValue();
2535                                         module->SetLoadAddress (*target, slide, changed);
2536                                     }
2537                                     else
2538                                     {
2539                                         result.AppendError ("one or more section name + load address pair must be specified");
2540                                         result.SetStatus (eReturnStatusFailed);
2541                                         return false;
2542                                     }
2543                                 }
2544                                 else
2545                                 {
2546                                     if (m_slide_option.GetOptionValue().OptionWasSet())
2547                                     {
2548                                         result.AppendError ("The \"--slide <offset>\" option can't be used in conjunction with setting section load addresses.\n");
2549                                         result.SetStatus (eReturnStatusFailed);
2550                                         return false;
2551                                     }
2552 
2553                                     for (size_t i=0; i<argc; i += 2)
2554                                     {
2555                                         const char *sect_name = args.GetArgumentAtIndex(i);
2556                                         const char *load_addr_cstr = args.GetArgumentAtIndex(i+1);
2557                                         if (sect_name && load_addr_cstr)
2558                                         {
2559                                             ConstString const_sect_name(sect_name);
2560                                             bool success = false;
2561                                             addr_t load_addr = Args::StringToUInt64(load_addr_cstr, LLDB_INVALID_ADDRESS, 0, &success);
2562                                             if (success)
2563                                             {
2564                                                 SectionSP section_sp (section_list->FindSectionByName(const_sect_name));
2565                                                 if (section_sp)
2566                                                 {
2567                                                     if (section_sp->IsThreadSpecific())
2568                                                     {
2569                                                         result.AppendErrorWithFormat ("thread specific sections are not yet supported (section '%s')\n", sect_name);
2570                                                         result.SetStatus (eReturnStatusFailed);
2571                                                         break;
2572                                                     }
2573                                                     else
2574                                                     {
2575                                                         if (target->GetSectionLoadList().SetSectionLoadAddress (section_sp.get(), load_addr))
2576                                                             changed = true;
2577                                                         result.AppendMessageWithFormat("section '%s' loaded at 0x%llx\n", sect_name, load_addr);
2578                                                     }
2579                                                 }
2580                                                 else
2581                                                 {
2582                                                     result.AppendErrorWithFormat ("no section found that matches the section name '%s'\n", sect_name);
2583                                                     result.SetStatus (eReturnStatusFailed);
2584                                                     break;
2585                                                 }
2586                                             }
2587                                             else
2588                                             {
2589                                                 result.AppendErrorWithFormat ("invalid load address string '%s'\n", load_addr_cstr);
2590                                                 result.SetStatus (eReturnStatusFailed);
2591                                                 break;
2592                                             }
2593                                         }
2594                                         else
2595                                         {
2596                                             if (sect_name)
2597                                                 result.AppendError ("section names must be followed by a load address.\n");
2598                                             else
2599                                                 result.AppendError ("one or more section name + load address pair must be specified.\n");
2600                                             result.SetStatus (eReturnStatusFailed);
2601                                             break;
2602                                         }
2603                                     }
2604                                 }
2605 
2606                                 if (changed)
2607                                     target->ModulesDidLoad (matching_modules);
2608                             }
2609                             else
2610                             {
2611                                 module->GetFileSpec().GetPath (path, sizeof(path));
2612                                 result.AppendErrorWithFormat ("no sections in object file '%s'\n", path);
2613                                 result.SetStatus (eReturnStatusFailed);
2614                             }
2615                         }
2616                         else
2617                         {
2618                             module->GetFileSpec().GetPath (path, sizeof(path));
2619                             result.AppendErrorWithFormat ("no object file for module '%s'\n", path);
2620                             result.SetStatus (eReturnStatusFailed);
2621                         }
2622                     }
2623                     else
2624                     {
2625                         module->GetFileSpec().GetPath (path, sizeof(path));
2626                         result.AppendErrorWithFormat ("invalid module '%s'.\n", path);
2627                         result.SetStatus (eReturnStatusFailed);
2628                     }
2629                 }
2630                 else
2631                 {
2632                     char uuid_cstr[64];
2633 
2634                     if (module_spec.GetFileSpec())
2635                         module_spec.GetFileSpec().GetPath (path, sizeof(path));
2636                     else
2637                         path[0] = '\0';
2638 
2639                     if (module_spec.GetUUIDPtr())
2640                         module_spec.GetUUID().GetAsCString(uuid_cstr, sizeof(uuid_cstr));
2641                     else
2642                         uuid_cstr[0] = '\0';
2643                     if (num_matches > 1)
2644                     {
2645                         result.AppendErrorWithFormat ("multiple modules match%s%s%s%s:\n",
2646                                                       path[0] ? " file=" : "",
2647                                                       path,
2648                                                       uuid_cstr[0] ? " uuid=" : "",
2649                                                       uuid_cstr);
2650                         for (size_t i=0; i<num_matches; ++i)
2651                         {
2652                             if (matching_modules.GetModulePointerAtIndex(i)->GetFileSpec().GetPath (path, sizeof(path)))
2653                                 result.AppendMessageWithFormat("%s\n", path);
2654                         }
2655                     }
2656                     else
2657                     {
2658                         result.AppendErrorWithFormat ("no modules were found  that match%s%s%s%s.\n",
2659                                                       path[0] ? " file=" : "",
2660                                                       path,
2661                                                       uuid_cstr[0] ? " uuid=" : "",
2662                                                       uuid_cstr);
2663                     }
2664                     result.SetStatus (eReturnStatusFailed);
2665                 }
2666             }
2667             else
2668             {
2669                 result.AppendError ("either the \"--file <module>\" or the \"--uuid <uuid>\" option must be specified.\n");
2670                 result.SetStatus (eReturnStatusFailed);
2671                 return false;
2672             }
2673         }
2674         return result.Succeeded();
2675     }
2676 
2677     virtual Options *
2678     GetOptions ()
2679     {
2680         return &m_option_group;
2681     }
2682 
2683 protected:
2684     OptionGroupOptions m_option_group;
2685     OptionGroupUUID m_uuid_option_group;
2686     OptionGroupFile m_file_option;
2687     OptionGroupUInt64 m_slide_option;
2688 };
2689 
2690 //----------------------------------------------------------------------
2691 // List images with associated information
2692 //----------------------------------------------------------------------
2693 class CommandObjectTargetModulesList : public CommandObject
2694 {
2695 public:
2696 
2697     class CommandOptions : public Options
2698     {
2699     public:
2700 
2701         CommandOptions (CommandInterpreter &interpreter) :
2702             Options(interpreter),
2703             m_format_array(),
2704             m_use_global_module_list (false),
2705             m_module_addr (LLDB_INVALID_ADDRESS)
2706         {
2707         }
2708 
2709         virtual
2710         ~CommandOptions ()
2711         {
2712         }
2713 
2714         virtual Error
2715         SetOptionValue (uint32_t option_idx, const char *option_arg)
2716         {
2717             char short_option = (char) m_getopt_table[option_idx].val;
2718             if (short_option == 'g')
2719             {
2720                 m_use_global_module_list = true;
2721             }
2722             else if (short_option == 'a')
2723             {
2724                 bool success;
2725                 m_module_addr = Args::StringToAddress(option_arg, LLDB_INVALID_ADDRESS, &success);
2726                 if (!success)
2727                 {
2728                     Error error;
2729                     error.SetErrorStringWithFormat("invalid address: \"%s\"", option_arg);
2730                 }
2731             }
2732             else
2733             {
2734                 uint32_t width = 0;
2735                 if (option_arg)
2736                     width = strtoul (option_arg, NULL, 0);
2737                 m_format_array.push_back(std::make_pair(short_option, width));
2738             }
2739             Error error;
2740             return error;
2741         }
2742 
2743         void
2744         OptionParsingStarting ()
2745         {
2746             m_format_array.clear();
2747             m_use_global_module_list = false;
2748             m_module_addr = LLDB_INVALID_ADDRESS;
2749         }
2750 
2751         const OptionDefinition*
2752         GetDefinitions ()
2753         {
2754             return g_option_table;
2755         }
2756 
2757         // Options table: Required for subclasses of Options.
2758 
2759         static OptionDefinition g_option_table[];
2760 
2761         // Instance variables to hold the values for command options.
2762         typedef std::vector< std::pair<char, uint32_t> > FormatWidthCollection;
2763         FormatWidthCollection m_format_array;
2764         bool m_use_global_module_list;
2765         lldb::addr_t m_module_addr;
2766     };
2767 
2768     CommandObjectTargetModulesList (CommandInterpreter &interpreter) :
2769     CommandObject (interpreter,
2770                    "target modules list",
2771                    "List current executable and dependent shared library images.",
2772                    "target modules list [<cmd-options>]"),
2773         m_options (interpreter)
2774     {
2775     }
2776 
2777     virtual
2778     ~CommandObjectTargetModulesList ()
2779     {
2780     }
2781 
2782     virtual
2783     Options *
2784     GetOptions ()
2785     {
2786         return &m_options;
2787     }
2788 
2789     virtual bool
2790     Execute (Args& command,
2791              CommandReturnObject &result)
2792     {
2793         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2794         const bool use_global_module_list = m_options.m_use_global_module_list;
2795         if (target == NULL && use_global_module_list == false)
2796         {
2797             result.AppendError ("invalid target, create a debug target using the 'target create' command");
2798             result.SetStatus (eReturnStatusFailed);
2799             return false;
2800         }
2801         else
2802         {
2803             if (target)
2804             {
2805                 uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2806                 result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2807                 result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2808             }
2809             // Dump all sections for all modules images
2810             uint32_t num_modules = 0;
2811             Mutex::Locker locker;
2812 
2813             Stream &strm = result.GetOutputStream();
2814 
2815             if (m_options.m_module_addr != LLDB_INVALID_ADDRESS)
2816             {
2817                 if (target)
2818                 {
2819                     Address module_address;
2820                     if (module_address.SetLoadAddress(m_options.m_module_addr, target))
2821                     {
2822                         ModuleSP module_sp (module_address.GetModule());
2823                         if (module_sp)
2824                         {
2825                             PrintModule (target, module_sp.get(), UINT32_MAX, 0, strm);
2826                             result.SetStatus (eReturnStatusSuccessFinishResult);
2827                         }
2828                         else
2829                         {
2830                             result.AppendError ("Couldn't find module matching address: 0x%llx.", m_options.m_module_addr);
2831                             result.SetStatus (eReturnStatusFailed);
2832                         }
2833                     }
2834                     else
2835                     {
2836                         result.AppendError ("Couldn't find module containing address: 0x%llx.", m_options.m_module_addr);
2837                         result.SetStatus (eReturnStatusFailed);
2838                     }
2839                 }
2840                 else
2841                 {
2842                     result.AppendError ("Can only look up modules by address with a valid target.");
2843                     result.SetStatus (eReturnStatusFailed);
2844                 }
2845                 return result.Succeeded();
2846             }
2847 
2848             ModuleList module_list;
2849             ModuleList *module_list_ptr = NULL;
2850             const size_t argc = command.GetArgumentCount();
2851             if (argc == 0)
2852             {
2853                 if (use_global_module_list)
2854                 {
2855                     locker.Lock (Module::GetAllocationModuleCollectionMutex());
2856                     num_modules = Module::GetNumberAllocatedModules();
2857                 }
2858                 else
2859                 {
2860                     module_list_ptr = &target->GetImages();
2861                     num_modules = target->GetImages().GetSize();
2862                 }
2863             }
2864             else
2865             {
2866                 for (size_t i=0; i<argc; ++i)
2867                 {
2868                     // Dump specified images (by basename or fullpath)
2869                     const char *arg_cstr = command.GetArgumentAtIndex(i);
2870                     const size_t num_matches = FindModulesByName (target, arg_cstr, module_list, use_global_module_list);
2871                     if (num_matches == 0)
2872                     {
2873                         if (argc == 1)
2874                         {
2875                             result.AppendErrorWithFormat ("no modules found that match '%s'", arg_cstr);
2876                             result.SetStatus (eReturnStatusFailed);
2877                             return false;
2878                         }
2879                     }
2880                 }
2881 
2882                 num_modules = module_list.GetSize();
2883                 module_list_ptr = &module_list;
2884             }
2885 
2886             if (num_modules > 0)
2887             {
2888                 for (uint32_t image_idx = 0; image_idx<num_modules; ++image_idx)
2889                 {
2890                     ModuleSP module_sp;
2891                     Module *module;
2892                     if (module_list_ptr)
2893                     {
2894                         module_sp = module_list_ptr->GetModuleAtIndex(image_idx);
2895                         module = module_sp.get();
2896                     }
2897                     else
2898                     {
2899                         module = Module::GetAllocatedModuleAtIndex(image_idx);
2900                         module_sp = module->shared_from_this();
2901                     }
2902 
2903                     int indent = strm.Printf("[%3u] ", image_idx);
2904                     PrintModule (target, module, image_idx, indent, strm);
2905 
2906                 }
2907                 result.SetStatus (eReturnStatusSuccessFinishResult);
2908             }
2909             else
2910             {
2911                 if (argc)
2912                 {
2913                     if (use_global_module_list)
2914                         result.AppendError ("the global module list has no matching modules");
2915                     else
2916                         result.AppendError ("the target has no matching modules");
2917                 }
2918                 else
2919                 {
2920                     if (use_global_module_list)
2921                         result.AppendError ("the global module list is empty");
2922                     else
2923                         result.AppendError ("the target has no associated executable images");
2924                 }
2925                 result.SetStatus (eReturnStatusFailed);
2926                 return false;
2927             }
2928         }
2929         return result.Succeeded();
2930     }
2931 protected:
2932 
2933     void
2934     PrintModule (Target *target, Module *module, uint32_t idx, int indent, Stream &strm)
2935     {
2936 
2937         bool dump_object_name = false;
2938         if (m_options.m_format_array.empty())
2939         {
2940             m_options.m_format_array.push_back(std::make_pair('u', 0));
2941             m_options.m_format_array.push_back(std::make_pair('h', 0));
2942             m_options.m_format_array.push_back(std::make_pair('f', 0));
2943             m_options.m_format_array.push_back(std::make_pair('S', 0));
2944         }
2945         const size_t num_entries = m_options.m_format_array.size();
2946         bool print_space = false;
2947         for (size_t i=0; i<num_entries; ++i)
2948         {
2949             if (print_space)
2950                 strm.PutChar(' ');
2951             print_space = true;
2952             const char format_char = m_options.m_format_array[i].first;
2953             uint32_t width = m_options.m_format_array[i].second;
2954             switch (format_char)
2955             {
2956                 case 'A':
2957                     DumpModuleArchitecture (strm, module, false, width);
2958                     break;
2959 
2960                 case 't':
2961                     DumpModuleArchitecture (strm, module, true, width);
2962                     break;
2963 
2964                 case 'f':
2965                     DumpFullpath (strm, &module->GetFileSpec(), width);
2966                     dump_object_name = true;
2967                     break;
2968 
2969                 case 'd':
2970                     DumpDirectory (strm, &module->GetFileSpec(), width);
2971                     break;
2972 
2973                 case 'b':
2974                     DumpBasename (strm, &module->GetFileSpec(), width);
2975                     dump_object_name = true;
2976                     break;
2977 
2978                 case 'h':
2979                 case 'o':
2980                     // Image header address
2981                     {
2982                         uint32_t addr_nibble_width = target ? (target->GetArchitecture().GetAddressByteSize() * 2) : 16;
2983 
2984                         ObjectFile *objfile = module->GetObjectFile ();
2985                         if (objfile)
2986                         {
2987                             Address header_addr(objfile->GetHeaderAddress());
2988                             if (header_addr.IsValid())
2989                             {
2990                                 if (target && !target->GetSectionLoadList().IsEmpty())
2991                                 {
2992                                     lldb::addr_t header_load_addr = header_addr.GetLoadAddress (target);
2993                                     if (header_load_addr == LLDB_INVALID_ADDRESS)
2994                                     {
2995                                         header_addr.Dump (&strm, target, Address::DumpStyleModuleWithFileAddress, Address::DumpStyleFileAddress);
2996                                     }
2997                                     else
2998                                     {
2999                                         if (format_char == 'o')
3000                                         {
3001                                             // Show the offset of slide for the image
3002                                             strm.Printf ("0x%*.*llx", addr_nibble_width, addr_nibble_width, header_load_addr - header_addr.GetFileAddress());
3003                                         }
3004                                         else
3005                                         {
3006                                             // Show the load address of the image
3007                                             strm.Printf ("0x%*.*llx", addr_nibble_width, addr_nibble_width, header_load_addr);
3008                                         }
3009                                     }
3010                                     break;
3011                                 }
3012                                 // The address was valid, but the image isn't loaded, output the address in an appropriate format
3013                                 header_addr.Dump (&strm, target, Address::DumpStyleFileAddress);
3014                                 break;
3015                             }
3016                         }
3017                         strm.Printf ("%*s", addr_nibble_width + 2, "");
3018                     }
3019                     break;
3020                 case 'r':
3021                     {
3022                         uint32_t ref_count = 0;
3023                         ModuleSP module_sp (module->shared_from_this());
3024                         if (module_sp)
3025                         {
3026                             // Take one away to make sure we don't count our local "module_sp"
3027                             ref_count = module_sp.use_count() - 1;
3028                         }
3029                         if (width)
3030                             strm.Printf("{%*u}", width, ref_count);
3031                         else
3032                             strm.Printf("{%u}", ref_count);
3033                     }
3034                     break;
3035 
3036                 case 's':
3037                 case 'S':
3038                     {
3039                         SymbolVendor *symbol_vendor = module->GetSymbolVendor();
3040                         if (symbol_vendor)
3041                         {
3042                             SymbolFile *symbol_file = symbol_vendor->GetSymbolFile();
3043                             if (symbol_file)
3044                             {
3045                                 if (format_char == 'S')
3046                                 {
3047                                     FileSpec &symfile_spec = symbol_file->GetObjectFile()->GetFileSpec();
3048                                     // Dump symbol file only if different from module file
3049                                     if (!symfile_spec || symfile_spec == module->GetFileSpec())
3050                                     {
3051                                         print_space = false;
3052                                         break;
3053                                     }
3054                                     // Add a newline and indent past the index
3055                                     strm.Printf ("\n%*s", indent, "");
3056                                 }
3057                                 DumpFullpath (strm, &symbol_file->GetObjectFile()->GetFileSpec(), width);
3058                                 dump_object_name = true;
3059                                 break;
3060                             }
3061                         }
3062                         strm.Printf("%.*s", width, "<NONE>");
3063                     }
3064                     break;
3065 
3066                 case 'm':
3067                     module->GetModificationTime().Dump(&strm, width);
3068                     break;
3069 
3070                 case 'p':
3071                     strm.Printf("%p", module);
3072                     break;
3073 
3074                 case 'u':
3075                     DumpModuleUUID(strm, module);
3076                     break;
3077 
3078                 default:
3079                     break;
3080             }
3081 
3082         }
3083         if (dump_object_name)
3084         {
3085             const char *object_name = module->GetObjectName().GetCString();
3086             if (object_name)
3087                 strm.Printf ("(%s)", object_name);
3088         }
3089         strm.EOL();
3090     }
3091 
3092     CommandOptions m_options;
3093 };
3094 
3095 OptionDefinition
3096 CommandObjectTargetModulesList::CommandOptions::g_option_table[] =
3097 {
3098     { LLDB_OPT_SET_1, false, "address",    'a', required_argument, NULL, 0, eArgTypeAddress, "Display the image at this address."},
3099     { LLDB_OPT_SET_1, false, "arch",       'A', optional_argument, NULL, 0, eArgTypeWidth,   "Display the architecture when listing images."},
3100     { LLDB_OPT_SET_1, false, "triple",     't', optional_argument, NULL, 0, eArgTypeWidth,   "Display the triple when listing images."},
3101     { 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."},
3102     { 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)."},
3103     { LLDB_OPT_SET_1, false, "uuid",       'u', no_argument,       NULL, 0, eArgTypeNone,    "Display the UUID when listing images."},
3104     { LLDB_OPT_SET_1, false, "fullpath",   'f', optional_argument, NULL, 0, eArgTypeWidth,   "Display the fullpath to the image object file."},
3105     { LLDB_OPT_SET_1, false, "directory",  'd', optional_argument, NULL, 0, eArgTypeWidth,   "Display the directory with optional width for the image object file."},
3106     { LLDB_OPT_SET_1, false, "basename",   'b', optional_argument, NULL, 0, eArgTypeWidth,   "Display the basename with optional width for the image object file."},
3107     { LLDB_OPT_SET_1, false, "symfile",    's', optional_argument, NULL, 0, eArgTypeWidth,   "Display the fullpath to the image symbol file with optional width."},
3108     { 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."},
3109     { LLDB_OPT_SET_1, false, "mod-time",   'm', optional_argument, NULL, 0, eArgTypeWidth,   "Display the modification time with optional width of the module."},
3110     { 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."},
3111     { LLDB_OPT_SET_1, false, "pointer",    'p', optional_argument, NULL, 0, eArgTypeNone,    "Display the module pointer."},
3112     { 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."},
3113     { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
3114 };
3115 
3116 
3117 
3118 //----------------------------------------------------------------------
3119 // Lookup information in images
3120 //----------------------------------------------------------------------
3121 class CommandObjectTargetModulesLookup : public CommandObject
3122 {
3123 public:
3124 
3125     enum
3126     {
3127         eLookupTypeInvalid = -1,
3128         eLookupTypeAddress = 0,
3129         eLookupTypeSymbol,
3130         eLookupTypeFileLine,    // Line is optional
3131         eLookupTypeFunction,
3132         eLookupTypeFunctionOrSymbol,
3133         eLookupTypeType,
3134         kNumLookupTypes
3135     };
3136 
3137     class CommandOptions : public Options
3138     {
3139     public:
3140 
3141         CommandOptions (CommandInterpreter &interpreter) :
3142         Options(interpreter)
3143         {
3144             OptionParsingStarting();
3145         }
3146 
3147         virtual
3148         ~CommandOptions ()
3149         {
3150         }
3151 
3152         virtual Error
3153         SetOptionValue (uint32_t option_idx, const char *option_arg)
3154         {
3155             Error error;
3156 
3157             char short_option = (char) m_getopt_table[option_idx].val;
3158 
3159             switch (short_option)
3160             {
3161                 case 'a':
3162                     m_type = eLookupTypeAddress;
3163                     m_addr = Args::StringToUInt64(option_arg, LLDB_INVALID_ADDRESS);
3164                     if (m_addr == LLDB_INVALID_ADDRESS)
3165                         error.SetErrorStringWithFormat ("invalid address string '%s'", option_arg);
3166                     break;
3167 
3168                 case 'o':
3169                     m_offset = Args::StringToUInt64(option_arg, LLDB_INVALID_ADDRESS);
3170                     if (m_offset == LLDB_INVALID_ADDRESS)
3171                         error.SetErrorStringWithFormat ("invalid offset string '%s'", option_arg);
3172                     break;
3173 
3174                 case 's':
3175                     m_str = option_arg;
3176                     m_type = eLookupTypeSymbol;
3177                     break;
3178 
3179                 case 'f':
3180                     m_file.SetFile (option_arg, false);
3181                     m_type = eLookupTypeFileLine;
3182                     break;
3183 
3184                 case 'i':
3185                     m_include_inlines = false;
3186                     break;
3187 
3188                 case 'l':
3189                     m_line_number = Args::StringToUInt32(option_arg, UINT32_MAX);
3190                     if (m_line_number == UINT32_MAX)
3191                         error.SetErrorStringWithFormat ("invalid line number string '%s'", option_arg);
3192                     else if (m_line_number == 0)
3193                         error.SetErrorString ("zero is an invalid line number");
3194                     m_type = eLookupTypeFileLine;
3195                     break;
3196 
3197                 case 'F':
3198                     m_str = option_arg;
3199                     m_type = eLookupTypeFunction;
3200                     break;
3201 
3202                 case 'n':
3203                     m_str = option_arg;
3204                     m_type = eLookupTypeFunctionOrSymbol;
3205                     break;
3206 
3207                 case 't':
3208                     m_str = option_arg;
3209                     m_type = eLookupTypeType;
3210                     break;
3211 
3212                 case 'v':
3213                     m_verbose = 1;
3214                     break;
3215 
3216                 case 'r':
3217                     m_use_regex = true;
3218                     break;
3219             }
3220 
3221             return error;
3222         }
3223 
3224         void
3225         OptionParsingStarting ()
3226         {
3227             m_type = eLookupTypeInvalid;
3228             m_str.clear();
3229             m_file.Clear();
3230             m_addr = LLDB_INVALID_ADDRESS;
3231             m_offset = 0;
3232             m_line_number = 0;
3233             m_use_regex = false;
3234             m_include_inlines = true;
3235             m_verbose = false;
3236         }
3237 
3238         const OptionDefinition*
3239         GetDefinitions ()
3240         {
3241             return g_option_table;
3242         }
3243 
3244         // Options table: Required for subclasses of Options.
3245 
3246         static OptionDefinition g_option_table[];
3247         int             m_type;         // Should be a eLookupTypeXXX enum after parsing options
3248         std::string     m_str;          // Holds name lookup
3249         FileSpec        m_file;         // Files for file lookups
3250         lldb::addr_t    m_addr;         // Holds the address to lookup
3251         lldb::addr_t    m_offset;       // Subtract this offset from m_addr before doing lookups.
3252         uint32_t        m_line_number;  // Line number for file+line lookups
3253         bool            m_use_regex;    // Name lookups in m_str are regular expressions.
3254         bool            m_include_inlines;// Check for inline entries when looking up by file/line.
3255         bool            m_verbose;      // Enable verbose lookup info
3256 
3257     };
3258 
3259     CommandObjectTargetModulesLookup (CommandInterpreter &interpreter) :
3260     CommandObject (interpreter,
3261                    "target modules lookup",
3262                    "Look up information within executable and dependent shared library images.",
3263                    NULL),
3264     m_options (interpreter)
3265     {
3266         CommandArgumentEntry arg;
3267         CommandArgumentData file_arg;
3268 
3269         // Define the first (and only) variant of this arg.
3270         file_arg.arg_type = eArgTypeFilename;
3271         file_arg.arg_repetition = eArgRepeatStar;
3272 
3273         // There is only one variant this argument could be; put it into the argument entry.
3274         arg.push_back (file_arg);
3275 
3276         // Push the data for the first argument into the m_arguments vector.
3277         m_arguments.push_back (arg);
3278     }
3279 
3280     virtual
3281     ~CommandObjectTargetModulesLookup ()
3282     {
3283     }
3284 
3285     virtual Options *
3286     GetOptions ()
3287     {
3288         return &m_options;
3289     }
3290 
3291 
3292     bool
3293     LookupInModule (CommandInterpreter &interpreter, Module *module, CommandReturnObject &result, bool &syntax_error)
3294     {
3295         switch (m_options.m_type)
3296         {
3297             case eLookupTypeAddress:
3298                 if (m_options.m_addr != LLDB_INVALID_ADDRESS)
3299                 {
3300                     if (LookupAddressInModule (m_interpreter,
3301                                                result.GetOutputStream(),
3302                                                module,
3303                                                eSymbolContextEverything,
3304                                                m_options.m_addr,
3305                                                m_options.m_offset,
3306                                                m_options.m_verbose))
3307                     {
3308                         result.SetStatus(eReturnStatusSuccessFinishResult);
3309                         return true;
3310                     }
3311                 }
3312                 break;
3313 
3314             case eLookupTypeSymbol:
3315                 if (!m_options.m_str.empty())
3316                 {
3317                     if (LookupSymbolInModule (m_interpreter,
3318                                               result.GetOutputStream(),
3319                                               module,
3320                                               m_options.m_str.c_str(),
3321                                               m_options.m_use_regex,
3322                                               m_options.m_verbose))
3323                     {
3324                         result.SetStatus(eReturnStatusSuccessFinishResult);
3325                         return true;
3326                     }
3327                 }
3328                 break;
3329 
3330             case eLookupTypeFileLine:
3331                 if (m_options.m_file)
3332                 {
3333 
3334                     if (LookupFileAndLineInModule (m_interpreter,
3335                                                    result.GetOutputStream(),
3336                                                    module,
3337                                                    m_options.m_file,
3338                                                    m_options.m_line_number,
3339                                                    m_options.m_include_inlines,
3340                                                    m_options.m_verbose))
3341                     {
3342                         result.SetStatus(eReturnStatusSuccessFinishResult);
3343                         return true;
3344                     }
3345                 }
3346                 break;
3347 
3348             case eLookupTypeFunctionOrSymbol:
3349             case eLookupTypeFunction:
3350                 if (!m_options.m_str.empty())
3351                 {
3352                     if (LookupFunctionInModule (m_interpreter,
3353                                                 result.GetOutputStream(),
3354                                                 module,
3355                                                 m_options.m_str.c_str(),
3356                                                 m_options.m_use_regex,
3357                                                 m_options.m_include_inlines,
3358                                                 m_options.m_type == eLookupTypeFunctionOrSymbol, // include symbols
3359                                                 m_options.m_verbose))
3360                     {
3361                         result.SetStatus(eReturnStatusSuccessFinishResult);
3362                         return true;
3363                     }
3364                 }
3365                 break;
3366 
3367 
3368             case eLookupTypeType:
3369                 if (!m_options.m_str.empty())
3370                 {
3371                     if (LookupTypeInModule (m_interpreter,
3372                                             result.GetOutputStream(),
3373                                             module,
3374                                             m_options.m_str.c_str(),
3375                                             m_options.m_use_regex))
3376                     {
3377                         result.SetStatus(eReturnStatusSuccessFinishResult);
3378                         return true;
3379                     }
3380                 }
3381                 break;
3382 
3383             default:
3384                 m_options.GenerateOptionUsage (result.GetErrorStream(), this);
3385                 syntax_error = true;
3386                 break;
3387         }
3388 
3389         result.SetStatus (eReturnStatusFailed);
3390         return false;
3391     }
3392 
3393     virtual bool
3394     Execute (Args& command,
3395              CommandReturnObject &result)
3396     {
3397         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
3398         if (target == NULL)
3399         {
3400             result.AppendError ("invalid target, create a debug target using the 'target create' command");
3401             result.SetStatus (eReturnStatusFailed);
3402             return false;
3403         }
3404         else
3405         {
3406             bool syntax_error = false;
3407             uint32_t i;
3408             uint32_t num_successful_lookups = 0;
3409             uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
3410             result.GetOutputStream().SetAddressByteSize(addr_byte_size);
3411             result.GetErrorStream().SetAddressByteSize(addr_byte_size);
3412             // Dump all sections for all modules images
3413 
3414             if (command.GetArgumentCount() == 0)
3415             {
3416                 // Dump all sections for all modules images
3417                 const uint32_t num_modules = target->GetImages().GetSize();
3418                 if (num_modules > 0)
3419                 {
3420                     for (i = 0; i<num_modules && syntax_error == false; ++i)
3421                     {
3422                         if (LookupInModule (m_interpreter, target->GetImages().GetModulePointerAtIndex(i), result, syntax_error))
3423                         {
3424                             result.GetOutputStream().EOL();
3425                             num_successful_lookups++;
3426                         }
3427                     }
3428                 }
3429                 else
3430                 {
3431                     result.AppendError ("the target has no associated executable images");
3432                     result.SetStatus (eReturnStatusFailed);
3433                     return false;
3434                 }
3435             }
3436             else
3437             {
3438                 // Dump specified images (by basename or fullpath)
3439                 const char *arg_cstr;
3440                 for (i = 0; (arg_cstr = command.GetArgumentAtIndex(i)) != NULL && syntax_error == false; ++i)
3441                 {
3442                     ModuleList module_list;
3443                     const size_t num_matches = FindModulesByName (target, arg_cstr, module_list, false);
3444                     if (num_matches > 0)
3445                     {
3446                         for (size_t i=0; i<num_matches; ++i)
3447                         {
3448                             Module *module = module_list.GetModulePointerAtIndex(i);
3449                             if (module)
3450                             {
3451                                 if (LookupInModule (m_interpreter, module, result, syntax_error))
3452                                 {
3453                                     result.GetOutputStream().EOL();
3454                                     num_successful_lookups++;
3455                                 }
3456                             }
3457                         }
3458                     }
3459                     else
3460                         result.AppendWarningWithFormat("Unable to find an image that matches '%s'.\n", arg_cstr);
3461                 }
3462             }
3463 
3464             if (num_successful_lookups > 0)
3465                 result.SetStatus (eReturnStatusSuccessFinishResult);
3466             else
3467                 result.SetStatus (eReturnStatusFailed);
3468         }
3469         return result.Succeeded();
3470     }
3471 protected:
3472 
3473     CommandOptions m_options;
3474 };
3475 
3476 OptionDefinition
3477 CommandObjectTargetModulesLookup::CommandOptions::g_option_table[] =
3478 {
3479     { LLDB_OPT_SET_1,   true,  "address",    'a', required_argument, NULL, 0, eArgTypeAddress,      "Lookup an address in one or more target modules."},
3480     { 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."},
3481     { LLDB_OPT_SET_2| LLDB_OPT_SET_4 | LLDB_OPT_SET_5
3482       /* FIXME: re-enable this for types when the LookupTypeInModule actually uses the regex option: | LLDB_OPT_SET_6 */ ,
3483                         false, "regex",      'r', no_argument,       NULL, 0, eArgTypeNone,         "The <name> argument for name lookups are regular expressions."},
3484     { 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."},
3485     { 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."},
3486     { 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)."},
3487     { LLDB_OPT_SET_3|
3488       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)."},
3489     { LLDB_OPT_SET_4,   true,  "function",   'F', required_argument, NULL, 0, eArgTypeFunctionName, "Lookup a function by name in the debug symbols in one or more target modules."},
3490     { LLDB_OPT_SET_5,   true,  "name",       'n', required_argument, NULL, 0, eArgTypeFunctionName, "Lookup a function or symbol by name in one or more target modules."},
3491     { LLDB_OPT_SET_6,   true,  "type",       't', required_argument, NULL, 0, eArgTypeName,         "Lookup a type by name in the debug symbols in one or more target modules."},
3492     { LLDB_OPT_SET_ALL, false, "verbose",    'v', no_argument,       NULL, 0, eArgTypeNone,         "Enable verbose lookup information."},
3493     { 0,                false, NULL,           0, 0,                 NULL, 0, eArgTypeNone, NULL }
3494 };
3495 
3496 
3497 #pragma mark CommandObjectMultiwordImageSearchPaths
3498 
3499 //-------------------------------------------------------------------------
3500 // CommandObjectMultiwordImageSearchPaths
3501 //-------------------------------------------------------------------------
3502 
3503 class CommandObjectTargetModulesImageSearchPaths : public CommandObjectMultiword
3504 {
3505 public:
3506 
3507     CommandObjectTargetModulesImageSearchPaths (CommandInterpreter &interpreter) :
3508     CommandObjectMultiword (interpreter,
3509                             "target modules search-paths",
3510                             "A set of commands for operating on debugger target image search paths.",
3511                             "target modules search-paths <subcommand> [<subcommand-options>]")
3512     {
3513         LoadSubCommand ("add",     CommandObjectSP (new CommandObjectTargetModulesSearchPathsAdd (interpreter)));
3514         LoadSubCommand ("clear",   CommandObjectSP (new CommandObjectTargetModulesSearchPathsClear (interpreter)));
3515         LoadSubCommand ("insert",  CommandObjectSP (new CommandObjectTargetModulesSearchPathsInsert (interpreter)));
3516         LoadSubCommand ("list",    CommandObjectSP (new CommandObjectTargetModulesSearchPathsList (interpreter)));
3517         LoadSubCommand ("query",   CommandObjectSP (new CommandObjectTargetModulesSearchPathsQuery (interpreter)));
3518     }
3519 
3520     ~CommandObjectTargetModulesImageSearchPaths()
3521     {
3522     }
3523 };
3524 
3525 
3526 
3527 #pragma mark CommandObjectTargetModules
3528 
3529 //-------------------------------------------------------------------------
3530 // CommandObjectTargetModules
3531 //-------------------------------------------------------------------------
3532 
3533 class CommandObjectTargetModules : public CommandObjectMultiword
3534 {
3535 public:
3536     //------------------------------------------------------------------
3537     // Constructors and Destructors
3538     //------------------------------------------------------------------
3539     CommandObjectTargetModules(CommandInterpreter &interpreter) :
3540         CommandObjectMultiword (interpreter,
3541                                 "target modules",
3542                                 "A set of commands for accessing information for one or more target modules.",
3543                                 "target modules <sub-command> ...")
3544     {
3545         LoadSubCommand ("add",          CommandObjectSP (new CommandObjectTargetModulesAdd (interpreter)));
3546         LoadSubCommand ("load",         CommandObjectSP (new CommandObjectTargetModulesLoad (interpreter)));
3547         //LoadSubCommand ("unload",       CommandObjectSP (new CommandObjectTargetModulesUnload (interpreter)));
3548         LoadSubCommand ("dump",         CommandObjectSP (new CommandObjectTargetModulesDump (interpreter)));
3549         LoadSubCommand ("list",         CommandObjectSP (new CommandObjectTargetModulesList (interpreter)));
3550         LoadSubCommand ("lookup",       CommandObjectSP (new CommandObjectTargetModulesLookup (interpreter)));
3551         LoadSubCommand ("search-paths", CommandObjectSP (new CommandObjectTargetModulesImageSearchPaths (interpreter)));
3552 
3553     }
3554     virtual
3555     ~CommandObjectTargetModules()
3556     {
3557     }
3558 
3559 private:
3560     //------------------------------------------------------------------
3561     // For CommandObjectTargetModules only
3562     //------------------------------------------------------------------
3563     DISALLOW_COPY_AND_ASSIGN (CommandObjectTargetModules);
3564 };
3565 
3566 
3567 
3568 class CommandObjectTargetSymbolsAdd : public CommandObject
3569 {
3570 public:
3571     CommandObjectTargetSymbolsAdd (CommandInterpreter &interpreter) :
3572     CommandObject (interpreter,
3573                    "target symbols add",
3574                    "Add a debug symbol file to one of the target's current modules.",
3575                    "target symbols add [<symfile>]")
3576     {
3577     }
3578 
3579     virtual
3580     ~CommandObjectTargetSymbolsAdd ()
3581     {
3582     }
3583 
3584     virtual bool
3585     Execute (Args& args,
3586              CommandReturnObject &result)
3587     {
3588         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
3589         if (target == NULL)
3590         {
3591             result.AppendError ("invalid target, create a debug target using the 'target create' command");
3592             result.SetStatus (eReturnStatusFailed);
3593             return false;
3594         }
3595         else
3596         {
3597             const size_t argc = args.GetArgumentCount();
3598             if (argc == 0)
3599             {
3600                 result.AppendError ("one or more symbol file paths must be specified");
3601                 result.SetStatus (eReturnStatusFailed);
3602                 return false;
3603             }
3604             else
3605             {
3606                 for (size_t i=0; i<argc; ++i)
3607                 {
3608                     const char *symfile_path = args.GetArgumentAtIndex(i);
3609                     if (symfile_path)
3610                     {
3611                         FileSpec symfile_spec(symfile_path, true);
3612                         ArchSpec arch;
3613                         if (symfile_spec.Exists())
3614                         {
3615                             ModuleSP symfile_module_sp (new Module (symfile_spec, target->GetArchitecture()));
3616                             if (symfile_module_sp)
3617                             {
3618                                 // We now have a module that represents a symbol file
3619                                 // that can be used for a module that might exist in the
3620                                 // current target, so we need to find that module in the
3621                                 // target
3622 
3623                                 ModuleSP old_module_sp (target->GetImages().FindModule (symfile_module_sp->GetUUID()));
3624                                 if (old_module_sp)
3625                                 {
3626                                     // The module has not yet created its symbol vendor, we can just
3627                                     // give the existing target module the symfile path to use for
3628                                     // when it decides to create it!
3629                                     old_module_sp->SetSymbolFileFileSpec (symfile_module_sp->GetFileSpec());
3630 
3631                                     // Let clients know something changed in the module
3632                                     // if it is currently loaded
3633                                     ModuleList module_list;
3634                                     module_list.Append (old_module_sp);
3635                                     target->ModulesDidLoad (module_list);
3636                                 }
3637                             }
3638                             else
3639                             {
3640                                 result.AppendError ("one or more executable image paths must be specified");
3641                                 result.SetStatus (eReturnStatusFailed);
3642                                 return false;
3643                             }
3644                             result.SetStatus (eReturnStatusSuccessFinishResult);
3645                         }
3646                         else
3647                         {
3648                             char resolved_symfile_path[PATH_MAX];
3649                             result.SetStatus (eReturnStatusFailed);
3650                             if (symfile_spec.GetPath (resolved_symfile_path, sizeof(resolved_symfile_path)))
3651                             {
3652                                 if (strcmp (resolved_symfile_path, symfile_path) != 0)
3653                                 {
3654                                     result.AppendErrorWithFormat ("invalid module path '%s' with resolved path '%s'\n", symfile_path, resolved_symfile_path);
3655                                     break;
3656                                 }
3657                             }
3658                             result.AppendErrorWithFormat ("invalid module path '%s'\n", symfile_path);
3659                             break;
3660                         }
3661                     }
3662                 }
3663             }
3664         }
3665         return result.Succeeded();
3666     }
3667 
3668     int
3669     HandleArgumentCompletion (Args &input,
3670                               int &cursor_index,
3671                               int &cursor_char_position,
3672                               OptionElementVector &opt_element_vector,
3673                               int match_start_point,
3674                               int max_return_elements,
3675                               bool &word_complete,
3676                               StringList &matches)
3677     {
3678         std::string completion_str (input.GetArgumentAtIndex(cursor_index));
3679         completion_str.erase (cursor_char_position);
3680 
3681         CommandCompletions::InvokeCommonCompletionCallbacks (m_interpreter,
3682                                                              CommandCompletions::eDiskFileCompletion,
3683                                                              completion_str.c_str(),
3684                                                              match_start_point,
3685                                                              max_return_elements,
3686                                                              NULL,
3687                                                              word_complete,
3688                                                              matches);
3689         return matches.GetSize();
3690     }
3691 
3692 };
3693 
3694 
3695 #pragma mark CommandObjectTargetSymbols
3696 
3697 //-------------------------------------------------------------------------
3698 // CommandObjectTargetSymbols
3699 //-------------------------------------------------------------------------
3700 
3701 class CommandObjectTargetSymbols : public CommandObjectMultiword
3702 {
3703 public:
3704     //------------------------------------------------------------------
3705     // Constructors and Destructors
3706     //------------------------------------------------------------------
3707     CommandObjectTargetSymbols(CommandInterpreter &interpreter) :
3708         CommandObjectMultiword (interpreter,
3709                             "target symbols",
3710                             "A set of commands for adding and managing debug symbol files.",
3711                             "target symbols <sub-command> ...")
3712     {
3713         LoadSubCommand ("add", CommandObjectSP (new CommandObjectTargetSymbolsAdd (interpreter)));
3714 
3715     }
3716     virtual
3717     ~CommandObjectTargetSymbols()
3718     {
3719     }
3720 
3721 private:
3722     //------------------------------------------------------------------
3723     // For CommandObjectTargetModules only
3724     //------------------------------------------------------------------
3725     DISALLOW_COPY_AND_ASSIGN (CommandObjectTargetSymbols);
3726 };
3727 
3728 
3729 #pragma mark CommandObjectTargetStopHookAdd
3730 
3731 //-------------------------------------------------------------------------
3732 // CommandObjectTargetStopHookAdd
3733 //-------------------------------------------------------------------------
3734 
3735 class CommandObjectTargetStopHookAdd : public CommandObject
3736 {
3737 public:
3738 
3739     class CommandOptions : public Options
3740     {
3741     public:
3742         CommandOptions (CommandInterpreter &interpreter) :
3743             Options(interpreter),
3744             m_line_start(0),
3745             m_line_end (UINT_MAX),
3746             m_func_name_type_mask (eFunctionNameTypeAuto),
3747             m_sym_ctx_specified (false),
3748             m_thread_specified (false),
3749             m_use_one_liner (false),
3750             m_one_liner()
3751         {
3752         }
3753 
3754         ~CommandOptions () {}
3755 
3756         const OptionDefinition*
3757         GetDefinitions ()
3758         {
3759             return g_option_table;
3760         }
3761 
3762         virtual Error
3763         SetOptionValue (uint32_t option_idx, const char *option_arg)
3764         {
3765             Error error;
3766             char short_option = (char) m_getopt_table[option_idx].val;
3767             bool success;
3768 
3769             switch (short_option)
3770             {
3771                 case 'c':
3772                     m_class_name = option_arg;
3773                     m_sym_ctx_specified = true;
3774                 break;
3775 
3776                 case 'e':
3777                     m_line_end = Args::StringToUInt32 (option_arg, UINT_MAX, 0, &success);
3778                     if (!success)
3779                     {
3780                         error.SetErrorStringWithFormat ("invalid end line number: \"%s\"", option_arg);
3781                         break;
3782                     }
3783                     m_sym_ctx_specified = true;
3784                 break;
3785 
3786                 case 'l':
3787                     m_line_start = Args::StringToUInt32 (option_arg, 0, 0, &success);
3788                     if (!success)
3789                     {
3790                         error.SetErrorStringWithFormat ("invalid start line number: \"%s\"", option_arg);
3791                         break;
3792                     }
3793                     m_sym_ctx_specified = true;
3794                 break;
3795 
3796                 case 'i':
3797                     m_no_inlines = true;
3798                 break;
3799 
3800                 case 'n':
3801                     m_function_name = option_arg;
3802                     m_func_name_type_mask |= eFunctionNameTypeAuto;
3803                     m_sym_ctx_specified = true;
3804                 break;
3805 
3806                 case 'f':
3807                     m_file_name = option_arg;
3808                     m_sym_ctx_specified = true;
3809                 break;
3810                 case 's':
3811                     m_module_name = option_arg;
3812                     m_sym_ctx_specified = true;
3813                 break;
3814                 case 't' :
3815                 {
3816                     m_thread_id = Args::StringToUInt64(option_arg, LLDB_INVALID_THREAD_ID, 0);
3817                     if (m_thread_id == LLDB_INVALID_THREAD_ID)
3818                        error.SetErrorStringWithFormat ("invalid thread id string '%s'", option_arg);
3819                     m_thread_specified = true;
3820                 }
3821                 break;
3822                 case 'T':
3823                     m_thread_name = option_arg;
3824                     m_thread_specified = true;
3825                 break;
3826                 case 'q':
3827                     m_queue_name = option_arg;
3828                     m_thread_specified = true;
3829                     break;
3830                 case 'x':
3831                 {
3832                     m_thread_index = Args::StringToUInt32(option_arg, UINT32_MAX, 0);
3833                     if (m_thread_id == UINT32_MAX)
3834                        error.SetErrorStringWithFormat ("invalid thread index string '%s'", option_arg);
3835                     m_thread_specified = true;
3836                 }
3837                 break;
3838                 case 'o':
3839                     m_use_one_liner = true;
3840                     m_one_liner = option_arg;
3841                 break;
3842                 default:
3843                     error.SetErrorStringWithFormat ("unrecognized option %c.", short_option);
3844                 break;
3845             }
3846             return error;
3847         }
3848 
3849         void
3850         OptionParsingStarting ()
3851         {
3852             m_class_name.clear();
3853             m_function_name.clear();
3854             m_line_start = 0;
3855             m_line_end = UINT_MAX;
3856             m_file_name.clear();
3857             m_module_name.clear();
3858             m_func_name_type_mask = eFunctionNameTypeAuto;
3859             m_thread_id = LLDB_INVALID_THREAD_ID;
3860             m_thread_index = UINT32_MAX;
3861             m_thread_name.clear();
3862             m_queue_name.clear();
3863 
3864             m_no_inlines = false;
3865             m_sym_ctx_specified = false;
3866             m_thread_specified = false;
3867 
3868             m_use_one_liner = false;
3869             m_one_liner.clear();
3870         }
3871 
3872 
3873         static OptionDefinition g_option_table[];
3874 
3875         std::string m_class_name;
3876         std::string m_function_name;
3877         uint32_t    m_line_start;
3878         uint32_t    m_line_end;
3879         std::string m_file_name;
3880         std::string m_module_name;
3881         uint32_t m_func_name_type_mask;  // A pick from lldb::FunctionNameType.
3882         lldb::tid_t m_thread_id;
3883         uint32_t m_thread_index;
3884         std::string m_thread_name;
3885         std::string m_queue_name;
3886         bool        m_sym_ctx_specified;
3887         bool        m_no_inlines;
3888         bool        m_thread_specified;
3889         // Instance variables to hold the values for one_liner options.
3890         bool m_use_one_liner;
3891         std::string m_one_liner;
3892     };
3893 
3894     Options *
3895     GetOptions ()
3896     {
3897         return &m_options;
3898     }
3899 
3900     CommandObjectTargetStopHookAdd (CommandInterpreter &interpreter) :
3901         CommandObject (interpreter,
3902                        "target stop-hook add ",
3903                        "Add a hook to be executed when the target stops.",
3904                        "target stop-hook add"),
3905         m_options (interpreter)
3906     {
3907     }
3908 
3909     ~CommandObjectTargetStopHookAdd ()
3910     {
3911     }
3912 
3913     static size_t
3914     ReadCommandsCallbackFunction (void *baton,
3915                                   InputReader &reader,
3916                                   lldb::InputReaderAction notification,
3917                                   const char *bytes,
3918                                   size_t bytes_len)
3919     {
3920         StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
3921         Target::StopHook *new_stop_hook = ((Target::StopHook *) baton);
3922         static bool got_interrupted;
3923         bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
3924 
3925         switch (notification)
3926         {
3927         case eInputReaderActivate:
3928             if (!batch_mode)
3929             {
3930                 out_stream->Printf ("%s\n", "Enter your stop hook command(s).  Type 'DONE' to end.");
3931                 if (reader.GetPrompt())
3932                     out_stream->Printf ("%s", reader.GetPrompt());
3933                 out_stream->Flush();
3934             }
3935             got_interrupted = false;
3936             break;
3937 
3938         case eInputReaderDeactivate:
3939             break;
3940 
3941         case eInputReaderReactivate:
3942             if (reader.GetPrompt() && !batch_mode)
3943             {
3944                 out_stream->Printf ("%s", reader.GetPrompt());
3945                 out_stream->Flush();
3946             }
3947             got_interrupted = false;
3948             break;
3949 
3950         case eInputReaderAsynchronousOutputWritten:
3951             break;
3952 
3953         case eInputReaderGotToken:
3954             if (bytes && bytes_len && baton)
3955             {
3956                 StringList *commands = new_stop_hook->GetCommandPointer();
3957                 if (commands)
3958                 {
3959                     commands->AppendString (bytes, bytes_len);
3960                 }
3961             }
3962             if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
3963             {
3964                 out_stream->Printf ("%s", reader.GetPrompt());
3965                 out_stream->Flush();
3966             }
3967             break;
3968 
3969         case eInputReaderInterrupt:
3970             {
3971                 // Finish, and cancel the stop hook.
3972                 new_stop_hook->GetTarget()->RemoveStopHookByID(new_stop_hook->GetID());
3973                 if (!batch_mode)
3974                 {
3975                     out_stream->Printf ("Stop hook cancelled.\n");
3976                     out_stream->Flush();
3977                 }
3978 
3979                 reader.SetIsDone (true);
3980             }
3981             got_interrupted = true;
3982             break;
3983 
3984         case eInputReaderEndOfFile:
3985             reader.SetIsDone (true);
3986             break;
3987 
3988         case eInputReaderDone:
3989             if (!got_interrupted && !batch_mode)
3990             {
3991                 out_stream->Printf ("Stop hook #%llu added.\n", new_stop_hook->GetID());
3992                 out_stream->Flush();
3993             }
3994             break;
3995         }
3996 
3997         return bytes_len;
3998     }
3999 
4000     bool
4001     Execute (Args& command,
4002              CommandReturnObject &result)
4003     {
4004         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
4005         if (target)
4006         {
4007             Target::StopHookSP new_hook_sp;
4008             target->AddStopHook (new_hook_sp);
4009 
4010             //  First step, make the specifier.
4011             std::auto_ptr<SymbolContextSpecifier> specifier_ap;
4012             if (m_options.m_sym_ctx_specified)
4013             {
4014                 specifier_ap.reset(new SymbolContextSpecifier(m_interpreter.GetDebugger().GetSelectedTarget()));
4015 
4016                 if (!m_options.m_module_name.empty())
4017                 {
4018                     specifier_ap->AddSpecification (m_options.m_module_name.c_str(), SymbolContextSpecifier::eModuleSpecified);
4019                 }
4020 
4021                 if (!m_options.m_class_name.empty())
4022                 {
4023                     specifier_ap->AddSpecification (m_options.m_class_name.c_str(), SymbolContextSpecifier::eClassOrNamespaceSpecified);
4024                 }
4025 
4026                 if (!m_options.m_file_name.empty())
4027                 {
4028                     specifier_ap->AddSpecification (m_options.m_file_name.c_str(), SymbolContextSpecifier::eFileSpecified);
4029                 }
4030 
4031                 if (m_options.m_line_start != 0)
4032                 {
4033                     specifier_ap->AddLineSpecification (m_options.m_line_start, SymbolContextSpecifier::eLineStartSpecified);
4034                 }
4035 
4036                 if (m_options.m_line_end != UINT_MAX)
4037                 {
4038                     specifier_ap->AddLineSpecification (m_options.m_line_end, SymbolContextSpecifier::eLineEndSpecified);
4039                 }
4040 
4041                 if (!m_options.m_function_name.empty())
4042                 {
4043                     specifier_ap->AddSpecification (m_options.m_function_name.c_str(), SymbolContextSpecifier::eFunctionSpecified);
4044                 }
4045             }
4046 
4047             if (specifier_ap.get())
4048                 new_hook_sp->SetSpecifier (specifier_ap.release());
4049 
4050             // Next see if any of the thread options have been entered:
4051 
4052             if (m_options.m_thread_specified)
4053             {
4054                 ThreadSpec *thread_spec = new ThreadSpec();
4055 
4056                 if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID)
4057                 {
4058                     thread_spec->SetTID (m_options.m_thread_id);
4059                 }
4060 
4061                 if (m_options.m_thread_index != UINT32_MAX)
4062                     thread_spec->SetIndex (m_options.m_thread_index);
4063 
4064                 if (!m_options.m_thread_name.empty())
4065                     thread_spec->SetName (m_options.m_thread_name.c_str());
4066 
4067                 if (!m_options.m_queue_name.empty())
4068                     thread_spec->SetQueueName (m_options.m_queue_name.c_str());
4069 
4070                 new_hook_sp->SetThreadSpecifier (thread_spec);
4071 
4072             }
4073             if (m_options.m_use_one_liner)
4074             {
4075                 // Use one-liner.
4076                 new_hook_sp->GetCommandPointer()->AppendString (m_options.m_one_liner.c_str());
4077                 result.AppendMessageWithFormat("Stop hook #%llu added.\n", new_hook_sp->GetID());
4078             }
4079             else
4080             {
4081                 // Otherwise gather up the command list, we'll push an input reader and suck the data from that directly into
4082                 // the new stop hook's command string.
4083                 InputReaderSP reader_sp (new InputReader(m_interpreter.GetDebugger()));
4084                 if (!reader_sp)
4085                 {
4086                     result.AppendError("out of memory\n");
4087                     result.SetStatus (eReturnStatusFailed);
4088                     target->RemoveStopHookByID (new_hook_sp->GetID());
4089                     return false;
4090                 }
4091 
4092                 Error err (reader_sp->Initialize (CommandObjectTargetStopHookAdd::ReadCommandsCallbackFunction,
4093                                                   new_hook_sp.get(), // baton
4094                                                   eInputReaderGranularityLine,  // token size, to pass to callback function
4095                                                   "DONE",                       // end token
4096                                                   "> ",                         // prompt
4097                                                   true));                       // echo input
4098                 if (!err.Success())
4099                 {
4100                     result.AppendError (err.AsCString());
4101                     result.SetStatus (eReturnStatusFailed);
4102                     target->RemoveStopHookByID (new_hook_sp->GetID());
4103                     return false;
4104                 }
4105                 m_interpreter.GetDebugger().PushInputReader (reader_sp);
4106             }
4107             result.SetStatus (eReturnStatusSuccessFinishNoResult);
4108         }
4109         else
4110         {
4111             result.AppendError ("invalid target\n");
4112             result.SetStatus (eReturnStatusFailed);
4113         }
4114 
4115         return result.Succeeded();
4116     }
4117 private:
4118     CommandOptions m_options;
4119 };
4120 
4121 OptionDefinition
4122 CommandObjectTargetStopHookAdd::CommandOptions::g_option_table[] =
4123 {
4124     { LLDB_OPT_SET_ALL, false, "one-liner", 'o', required_argument, NULL, NULL, eArgTypeOneLiner,
4125         "Specify a one-line breakpoint command inline. Be sure to surround it with quotes." },
4126     { LLDB_OPT_SET_ALL, false, "shlib", 's', required_argument, NULL, CommandCompletions::eModuleCompletion, eArgTypeShlibName,
4127         "Set the module within which the stop-hook is to be run."},
4128     { LLDB_OPT_SET_ALL, false, "thread-index", 'x', required_argument, NULL, NULL, eArgTypeThreadIndex,
4129         "The stop hook is run only for the thread whose index matches this argument."},
4130     { LLDB_OPT_SET_ALL, false, "thread-id", 't', required_argument, NULL, NULL, eArgTypeThreadID,
4131         "The stop hook is run only for the thread whose TID matches this argument."},
4132     { LLDB_OPT_SET_ALL, false, "thread-name", 'T', required_argument, NULL, NULL, eArgTypeThreadName,
4133         "The stop hook is run only for the thread whose thread name matches this argument."},
4134     { LLDB_OPT_SET_ALL, false, "queue-name", 'q', required_argument, NULL, NULL, eArgTypeQueueName,
4135         "The stop hook is run only for threads in the queue whose name is given by this argument."},
4136     { LLDB_OPT_SET_1, false, "file", 'f', required_argument, NULL, CommandCompletions::eSourceFileCompletion, eArgTypeFilename,
4137         "Specify the source file within which the stop-hook is to be run." },
4138     { LLDB_OPT_SET_1, false, "start-line", 'l', required_argument, NULL, 0, eArgTypeLineNum,
4139         "Set the start of the line range for which the stop-hook is to be run."},
4140     { LLDB_OPT_SET_1, false, "end-line", 'e', required_argument, NULL, 0, eArgTypeLineNum,
4141         "Set the end of the line range for which the stop-hook is to be run."},
4142     { LLDB_OPT_SET_2, false, "classname", 'c', required_argument, NULL, NULL, eArgTypeClassName,
4143         "Specify the class within which the stop-hook is to be run." },
4144     { LLDB_OPT_SET_3, false, "name", 'n', required_argument, NULL, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName,
4145         "Set the function name within which the stop hook will be run." },
4146     { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
4147 };
4148 
4149 #pragma mark CommandObjectTargetStopHookDelete
4150 
4151 //-------------------------------------------------------------------------
4152 // CommandObjectTargetStopHookDelete
4153 //-------------------------------------------------------------------------
4154 
4155 class CommandObjectTargetStopHookDelete : public CommandObject
4156 {
4157 public:
4158 
4159     CommandObjectTargetStopHookDelete (CommandInterpreter &interpreter) :
4160         CommandObject (interpreter,
4161                        "target stop-hook delete",
4162                        "Delete a stop-hook.",
4163                        "target stop-hook delete [<idx>]")
4164     {
4165     }
4166 
4167     ~CommandObjectTargetStopHookDelete ()
4168     {
4169     }
4170 
4171     bool
4172     Execute (Args& command,
4173              CommandReturnObject &result)
4174     {
4175         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
4176         if (target)
4177         {
4178             // FIXME: see if we can use the breakpoint id style parser?
4179             size_t num_args = command.GetArgumentCount();
4180             if (num_args == 0)
4181             {
4182                 if (!m_interpreter.Confirm ("Delete all stop hooks?", true))
4183                 {
4184                     result.SetStatus (eReturnStatusFailed);
4185                     return false;
4186                 }
4187                 else
4188                 {
4189                     target->RemoveAllStopHooks();
4190                 }
4191             }
4192             else
4193             {
4194                 bool success;
4195                 for (size_t i = 0; i < num_args; i++)
4196                 {
4197                     lldb::user_id_t user_id = Args::StringToUInt32 (command.GetArgumentAtIndex(i), 0, 0, &success);
4198                     if (!success)
4199                     {
4200                         result.AppendErrorWithFormat ("invalid stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i));
4201                         result.SetStatus(eReturnStatusFailed);
4202                         return false;
4203                     }
4204                     success = target->RemoveStopHookByID (user_id);
4205                     if (!success)
4206                     {
4207                         result.AppendErrorWithFormat ("unknown stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i));
4208                         result.SetStatus(eReturnStatusFailed);
4209                         return false;
4210                     }
4211                 }
4212             }
4213             result.SetStatus (eReturnStatusSuccessFinishNoResult);
4214         }
4215         else
4216         {
4217             result.AppendError ("invalid target\n");
4218             result.SetStatus (eReturnStatusFailed);
4219         }
4220 
4221         return result.Succeeded();
4222     }
4223 };
4224 #pragma mark CommandObjectTargetStopHookEnableDisable
4225 
4226 //-------------------------------------------------------------------------
4227 // CommandObjectTargetStopHookEnableDisable
4228 //-------------------------------------------------------------------------
4229 
4230 class CommandObjectTargetStopHookEnableDisable : public CommandObject
4231 {
4232 public:
4233 
4234     CommandObjectTargetStopHookEnableDisable (CommandInterpreter &interpreter, bool enable, const char *name, const char *help, const char *syntax) :
4235         CommandObject (interpreter,
4236                        name,
4237                        help,
4238                        syntax),
4239         m_enable (enable)
4240     {
4241     }
4242 
4243     ~CommandObjectTargetStopHookEnableDisable ()
4244     {
4245     }
4246 
4247     bool
4248     Execute (Args& command,
4249              CommandReturnObject &result)
4250     {
4251         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
4252         if (target)
4253         {
4254             // FIXME: see if we can use the breakpoint id style parser?
4255             size_t num_args = command.GetArgumentCount();
4256             bool success;
4257 
4258             if (num_args == 0)
4259             {
4260                 target->SetAllStopHooksActiveState (m_enable);
4261             }
4262             else
4263             {
4264                 for (size_t i = 0; i < num_args; i++)
4265                 {
4266                     lldb::user_id_t user_id = Args::StringToUInt32 (command.GetArgumentAtIndex(i), 0, 0, &success);
4267                     if (!success)
4268                     {
4269                         result.AppendErrorWithFormat ("invalid stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i));
4270                         result.SetStatus(eReturnStatusFailed);
4271                         return false;
4272                     }
4273                     success = target->SetStopHookActiveStateByID (user_id, m_enable);
4274                     if (!success)
4275                     {
4276                         result.AppendErrorWithFormat ("unknown stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i));
4277                         result.SetStatus(eReturnStatusFailed);
4278                         return false;
4279                     }
4280                 }
4281             }
4282             result.SetStatus (eReturnStatusSuccessFinishNoResult);
4283         }
4284         else
4285         {
4286             result.AppendError ("invalid target\n");
4287             result.SetStatus (eReturnStatusFailed);
4288         }
4289         return result.Succeeded();
4290     }
4291 private:
4292     bool m_enable;
4293 };
4294 
4295 #pragma mark CommandObjectTargetStopHookList
4296 
4297 //-------------------------------------------------------------------------
4298 // CommandObjectTargetStopHookList
4299 //-------------------------------------------------------------------------
4300 
4301 class CommandObjectTargetStopHookList : public CommandObject
4302 {
4303 public:
4304 
4305     CommandObjectTargetStopHookList (CommandInterpreter &interpreter) :
4306         CommandObject (interpreter,
4307                        "target stop-hook list",
4308                        "List all stop-hooks.",
4309                        "target stop-hook list [<type>]")
4310     {
4311     }
4312 
4313     ~CommandObjectTargetStopHookList ()
4314     {
4315     }
4316 
4317     bool
4318     Execute (Args& command,
4319              CommandReturnObject &result)
4320     {
4321         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
4322         if (!target)
4323         {
4324             result.AppendError ("invalid target\n");
4325             result.SetStatus (eReturnStatusFailed);
4326             return result.Succeeded();
4327         }
4328 
4329         size_t num_hooks = target->GetNumStopHooks ();
4330         if (num_hooks == 0)
4331         {
4332             result.GetOutputStream().PutCString ("No stop hooks.\n");
4333         }
4334         else
4335         {
4336             for (size_t i = 0; i < num_hooks; i++)
4337             {
4338                 Target::StopHookSP this_hook = target->GetStopHookAtIndex (i);
4339                 if (i > 0)
4340                     result.GetOutputStream().PutCString ("\n");
4341                 this_hook->GetDescription (&(result.GetOutputStream()), eDescriptionLevelFull);
4342             }
4343         }
4344         result.SetStatus (eReturnStatusSuccessFinishResult);
4345         return result.Succeeded();
4346     }
4347 };
4348 
4349 #pragma mark CommandObjectMultiwordTargetStopHooks
4350 //-------------------------------------------------------------------------
4351 // CommandObjectMultiwordTargetStopHooks
4352 //-------------------------------------------------------------------------
4353 
4354 class CommandObjectMultiwordTargetStopHooks : public CommandObjectMultiword
4355 {
4356 public:
4357 
4358     CommandObjectMultiwordTargetStopHooks (CommandInterpreter &interpreter) :
4359         CommandObjectMultiword (interpreter,
4360                                 "target stop-hook",
4361                                 "A set of commands for operating on debugger target stop-hooks.",
4362                                 "target stop-hook <subcommand> [<subcommand-options>]")
4363     {
4364         LoadSubCommand ("add",      CommandObjectSP (new CommandObjectTargetStopHookAdd (interpreter)));
4365         LoadSubCommand ("delete",   CommandObjectSP (new CommandObjectTargetStopHookDelete (interpreter)));
4366         LoadSubCommand ("disable",  CommandObjectSP (new CommandObjectTargetStopHookEnableDisable (interpreter,
4367                                                                                                    false,
4368                                                                                                    "target stop-hook disable [<id>]",
4369                                                                                                    "Disable a stop-hook.",
4370                                                                                                    "target stop-hook disable")));
4371         LoadSubCommand ("enable",   CommandObjectSP (new CommandObjectTargetStopHookEnableDisable (interpreter,
4372                                                                                                    true,
4373                                                                                                    "target stop-hook enable [<id>]",
4374                                                                                                    "Enable a stop-hook.",
4375                                                                                                    "target stop-hook enable")));
4376         LoadSubCommand ("list",     CommandObjectSP (new CommandObjectTargetStopHookList (interpreter)));
4377     }
4378 
4379     ~CommandObjectMultiwordTargetStopHooks()
4380     {
4381     }
4382 };
4383 
4384 
4385 
4386 #pragma mark CommandObjectMultiwordTarget
4387 
4388 //-------------------------------------------------------------------------
4389 // CommandObjectMultiwordTarget
4390 //-------------------------------------------------------------------------
4391 
4392 CommandObjectMultiwordTarget::CommandObjectMultiwordTarget (CommandInterpreter &interpreter) :
4393     CommandObjectMultiword (interpreter,
4394                             "target",
4395                             "A set of commands for operating on debugger targets.",
4396                             "target <subcommand> [<subcommand-options>]")
4397 {
4398 
4399     LoadSubCommand ("create",    CommandObjectSP (new CommandObjectTargetCreate (interpreter)));
4400     LoadSubCommand ("delete",    CommandObjectSP (new CommandObjectTargetDelete (interpreter)));
4401     LoadSubCommand ("list",      CommandObjectSP (new CommandObjectTargetList   (interpreter)));
4402     LoadSubCommand ("select",    CommandObjectSP (new CommandObjectTargetSelect (interpreter)));
4403     LoadSubCommand ("stop-hook", CommandObjectSP (new CommandObjectMultiwordTargetStopHooks (interpreter)));
4404     LoadSubCommand ("modules",   CommandObjectSP (new CommandObjectTargetModules (interpreter)));
4405     LoadSubCommand ("symbols",   CommandObjectSP (new CommandObjectTargetSymbols (interpreter)));
4406     LoadSubCommand ("variable",  CommandObjectSP (new CommandObjectTargetVariable (interpreter)));
4407 }
4408 
4409 CommandObjectMultiwordTarget::~CommandObjectMultiwordTarget ()
4410 {
4411 }
4412 
4413 
4414