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