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