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.use_synth,
492                                       false,
493                                       m_varobj_options.flat_output,
494                                       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             uint32_t width = 0;
2485             if (option_arg)
2486                 width = strtoul (option_arg, NULL, 0);
2487             m_format_array.push_back(std::make_pair(short_option, width));
2488             Error error;
2489             return error;
2490         }
2491 
2492         void
2493         OptionParsingStarting ()
2494         {
2495             m_format_array.clear();
2496         }
2497 
2498         const OptionDefinition*
2499         GetDefinitions ()
2500         {
2501             return g_option_table;
2502         }
2503 
2504         // Options table: Required for subclasses of Options.
2505 
2506         static OptionDefinition g_option_table[];
2507 
2508         // Instance variables to hold the values for command options.
2509         typedef std::vector< std::pair<char, uint32_t> > FormatWidthCollection;
2510         FormatWidthCollection m_format_array;
2511     };
2512 
2513     CommandObjectTargetModulesList (CommandInterpreter &interpreter) :
2514     CommandObject (interpreter,
2515                    "target modules list",
2516                    "List current executable and dependent shared library images.",
2517                    "target modules list [<cmd-options>]"),
2518         m_options (interpreter)
2519     {
2520     }
2521 
2522     virtual
2523     ~CommandObjectTargetModulesList ()
2524     {
2525     }
2526 
2527     virtual
2528     Options *
2529     GetOptions ()
2530     {
2531         return &m_options;
2532     }
2533 
2534     virtual bool
2535     Execute (Args& command,
2536              CommandReturnObject &result)
2537     {
2538         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2539         if (target == NULL)
2540         {
2541             result.AppendError ("invalid target, create a debug target using the 'target create' command");
2542             result.SetStatus (eReturnStatusFailed);
2543             return false;
2544         }
2545         else
2546         {
2547             uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2548             result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2549             result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2550             // Dump all sections for all modules images
2551             const uint32_t num_modules = target->GetImages().GetSize();
2552             if (num_modules > 0)
2553             {
2554                 Stream &strm = result.GetOutputStream();
2555 
2556                 for (uint32_t image_idx = 0; image_idx<num_modules; ++image_idx)
2557                 {
2558                     Module *module = target->GetImages().GetModulePointerAtIndex(image_idx);
2559                     strm.Printf("[%3u] ", image_idx);
2560 
2561                     bool dump_object_name = false;
2562                     if (m_options.m_format_array.empty())
2563                     {
2564                         DumpFullpath(strm, &module->GetFileSpec(), 0);
2565                         dump_object_name = true;
2566                     }
2567                     else
2568                     {
2569                         const size_t num_entries = m_options.m_format_array.size();
2570                         for (size_t i=0; i<num_entries; ++i)
2571                         {
2572                             if (i > 0)
2573                                 strm.PutChar(' ');
2574                             char format_char = m_options.m_format_array[i].first;
2575                             uint32_t width = m_options.m_format_array[i].second;
2576                             switch (format_char)
2577                             {
2578                                 case 'a':
2579                                     DumpModuleArchitecture (strm, module, false, width);
2580                                     break;
2581 
2582                                 case 't':
2583                                     DumpModuleArchitecture (strm, module, true, width);
2584                                     break;
2585 
2586                                 case 'f':
2587                                     DumpFullpath (strm, &module->GetFileSpec(), width);
2588                                     dump_object_name = true;
2589                                     break;
2590 
2591                                 case 'd':
2592                                     DumpDirectory (strm, &module->GetFileSpec(), width);
2593                                     break;
2594 
2595                                 case 'b':
2596                                     DumpBasename (strm, &module->GetFileSpec(), width);
2597                                     dump_object_name = true;
2598                                     break;
2599 
2600                                 case 's':
2601                                 case 'S':
2602                                 {
2603                                     SymbolVendor *symbol_vendor = module->GetSymbolVendor();
2604                                     if (symbol_vendor)
2605                                     {
2606                                         SymbolFile *symbol_file = symbol_vendor->GetSymbolFile();
2607                                         if (symbol_file)
2608                                         {
2609                                             if (format_char == 'S')
2610                                                 DumpBasename(strm, &symbol_file->GetObjectFile()->GetFileSpec(), width);
2611                                             else
2612                                                 DumpFullpath (strm, &symbol_file->GetObjectFile()->GetFileSpec(), width);
2613                                             dump_object_name = true;
2614                                             break;
2615                                         }
2616                                     }
2617                                     strm.Printf("%.*s", width, "<NONE>");
2618                                 }
2619                                     break;
2620 
2621                                 case 'u':
2622                                     DumpModuleUUID(strm, module);
2623                                     break;
2624 
2625                                 default:
2626                                     break;
2627                             }
2628 
2629                         }
2630                     }
2631                     if (dump_object_name)
2632                     {
2633                         const char *object_name = module->GetObjectName().GetCString();
2634                         if (object_name)
2635                             strm.Printf ("(%s)", object_name);
2636                     }
2637                     strm.EOL();
2638                 }
2639                 result.SetStatus (eReturnStatusSuccessFinishResult);
2640             }
2641             else
2642             {
2643                 result.AppendError ("the target has no associated executable images");
2644                 result.SetStatus (eReturnStatusFailed);
2645                 return false;
2646             }
2647         }
2648         return result.Succeeded();
2649     }
2650 protected:
2651 
2652     CommandOptions m_options;
2653 };
2654 
2655 OptionDefinition
2656 CommandObjectTargetModulesList::CommandOptions::g_option_table[] =
2657 {
2658     { LLDB_OPT_SET_1, false, "arch",       'a', optional_argument, NULL, 0, eArgTypeWidth,   "Display the architecture when listing images."},
2659     { LLDB_OPT_SET_1, false, "triple",     't', optional_argument, NULL, 0, eArgTypeWidth,   "Display the triple when listing images."},
2660     { LLDB_OPT_SET_1, false, "uuid",       'u', no_argument,       NULL, 0, eArgTypeNone,    "Display the UUID when listing images."},
2661     { LLDB_OPT_SET_1, false, "fullpath",   'f', optional_argument, NULL, 0, eArgTypeWidth,   "Display the fullpath to the image object file."},
2662     { LLDB_OPT_SET_1, false, "directory",  'd', optional_argument, NULL, 0, eArgTypeWidth,   "Display the directory with optional width for the image object file."},
2663     { LLDB_OPT_SET_1, false, "basename",   'b', optional_argument, NULL, 0, eArgTypeWidth,   "Display the basename with optional width for the image object file."},
2664     { LLDB_OPT_SET_1, false, "symfile",    's', optional_argument, NULL, 0, eArgTypeWidth,   "Display the fullpath to the image symbol file with optional width."},
2665     { LLDB_OPT_SET_1, false, "symfile-basename", 'S', optional_argument, NULL, 0, eArgTypeWidth,   "Display the basename to the image symbol file with optional width."},
2666     { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
2667 };
2668 
2669 
2670 
2671 //----------------------------------------------------------------------
2672 // Lookup information in images
2673 //----------------------------------------------------------------------
2674 class CommandObjectTargetModulesLookup : public CommandObject
2675 {
2676 public:
2677 
2678     enum
2679     {
2680         eLookupTypeInvalid = -1,
2681         eLookupTypeAddress = 0,
2682         eLookupTypeSymbol,
2683         eLookupTypeFileLine,    // Line is optional
2684         eLookupTypeFunction,
2685         eLookupTypeType,
2686         kNumLookupTypes
2687     };
2688 
2689     class CommandOptions : public Options
2690     {
2691     public:
2692 
2693         CommandOptions (CommandInterpreter &interpreter) :
2694         Options(interpreter)
2695         {
2696             OptionParsingStarting();
2697         }
2698 
2699         virtual
2700         ~CommandOptions ()
2701         {
2702         }
2703 
2704         virtual Error
2705         SetOptionValue (uint32_t option_idx, const char *option_arg)
2706         {
2707             Error error;
2708 
2709             char short_option = (char) m_getopt_table[option_idx].val;
2710 
2711             switch (short_option)
2712             {
2713                 case 'a':
2714                     m_type = eLookupTypeAddress;
2715                     m_addr = Args::StringToUInt64(option_arg, LLDB_INVALID_ADDRESS);
2716                     if (m_addr == LLDB_INVALID_ADDRESS)
2717                         error.SetErrorStringWithFormat ("Invalid address string '%s'.\n", option_arg);
2718                     break;
2719 
2720                 case 'o':
2721                     m_offset = Args::StringToUInt64(option_arg, LLDB_INVALID_ADDRESS);
2722                     if (m_offset == LLDB_INVALID_ADDRESS)
2723                         error.SetErrorStringWithFormat ("Invalid offset string '%s'.\n", option_arg);
2724                     break;
2725 
2726                 case 's':
2727                     m_str = option_arg;
2728                     m_type = eLookupTypeSymbol;
2729                     break;
2730 
2731                 case 'f':
2732                     m_file.SetFile (option_arg, false);
2733                     m_type = eLookupTypeFileLine;
2734                     break;
2735 
2736                 case 'i':
2737                     m_check_inlines = false;
2738                     break;
2739 
2740                 case 'l':
2741                     m_line_number = Args::StringToUInt32(option_arg, UINT32_MAX);
2742                     if (m_line_number == UINT32_MAX)
2743                         error.SetErrorStringWithFormat ("Invalid line number string '%s'.\n", option_arg);
2744                     else if (m_line_number == 0)
2745                         error.SetErrorString ("Zero is an invalid line number.");
2746                     m_type = eLookupTypeFileLine;
2747                     break;
2748 
2749                 case 'n':
2750                     m_str = option_arg;
2751                     m_type = eLookupTypeFunction;
2752                     break;
2753 
2754                 case 't':
2755                     m_str = option_arg;
2756                     m_type = eLookupTypeType;
2757                     break;
2758 
2759                 case 'v':
2760                     m_verbose = 1;
2761                     break;
2762 
2763                 case 'r':
2764                     m_use_regex = true;
2765                     break;
2766             }
2767 
2768             return error;
2769         }
2770 
2771         void
2772         OptionParsingStarting ()
2773         {
2774             m_type = eLookupTypeInvalid;
2775             m_str.clear();
2776             m_file.Clear();
2777             m_addr = LLDB_INVALID_ADDRESS;
2778             m_offset = 0;
2779             m_line_number = 0;
2780             m_use_regex = false;
2781             m_check_inlines = true;
2782             m_verbose = false;
2783         }
2784 
2785         const OptionDefinition*
2786         GetDefinitions ()
2787         {
2788             return g_option_table;
2789         }
2790 
2791         // Options table: Required for subclasses of Options.
2792 
2793         static OptionDefinition g_option_table[];
2794         int             m_type;         // Should be a eLookupTypeXXX enum after parsing options
2795         std::string     m_str;          // Holds name lookup
2796         FileSpec        m_file;         // Files for file lookups
2797         lldb::addr_t    m_addr;         // Holds the address to lookup
2798         lldb::addr_t    m_offset;       // Subtract this offset from m_addr before doing lookups.
2799         uint32_t        m_line_number;  // Line number for file+line lookups
2800         bool            m_use_regex;    // Name lookups in m_str are regular expressions.
2801         bool            m_check_inlines;// Check for inline entries when looking up by file/line.
2802         bool            m_verbose;      // Enable verbose lookup info
2803 
2804     };
2805 
2806     CommandObjectTargetModulesLookup (CommandInterpreter &interpreter) :
2807     CommandObject (interpreter,
2808                    "target modules lookup",
2809                    "Look up information within executable and dependent shared library images.",
2810                    NULL),
2811     m_options (interpreter)
2812     {
2813         CommandArgumentEntry arg;
2814         CommandArgumentData file_arg;
2815 
2816         // Define the first (and only) variant of this arg.
2817         file_arg.arg_type = eArgTypeFilename;
2818         file_arg.arg_repetition = eArgRepeatStar;
2819 
2820         // There is only one variant this argument could be; put it into the argument entry.
2821         arg.push_back (file_arg);
2822 
2823         // Push the data for the first argument into the m_arguments vector.
2824         m_arguments.push_back (arg);
2825     }
2826 
2827     virtual
2828     ~CommandObjectTargetModulesLookup ()
2829     {
2830     }
2831 
2832     virtual Options *
2833     GetOptions ()
2834     {
2835         return &m_options;
2836     }
2837 
2838 
2839     bool
2840     LookupInModule (CommandInterpreter &interpreter, Module *module, CommandReturnObject &result, bool &syntax_error)
2841     {
2842         switch (m_options.m_type)
2843         {
2844             case eLookupTypeAddress:
2845                 if (m_options.m_addr != LLDB_INVALID_ADDRESS)
2846                 {
2847                     if (LookupAddressInModule (m_interpreter,
2848                                                result.GetOutputStream(),
2849                                                module,
2850                                                eSymbolContextEverything,
2851                                                m_options.m_addr,
2852                                                m_options.m_offset,
2853                                                m_options.m_verbose))
2854                     {
2855                         result.SetStatus(eReturnStatusSuccessFinishResult);
2856                         return true;
2857                     }
2858                 }
2859                 break;
2860 
2861             case eLookupTypeSymbol:
2862                 if (!m_options.m_str.empty())
2863                 {
2864                     if (LookupSymbolInModule (m_interpreter, result.GetOutputStream(), module, m_options.m_str.c_str(), m_options.m_use_regex))
2865                     {
2866                         result.SetStatus(eReturnStatusSuccessFinishResult);
2867                         return true;
2868                     }
2869                 }
2870                 break;
2871 
2872             case eLookupTypeFileLine:
2873                 if (m_options.m_file)
2874                 {
2875 
2876                     if (LookupFileAndLineInModule (m_interpreter,
2877                                                    result.GetOutputStream(),
2878                                                    module,
2879                                                    m_options.m_file,
2880                                                    m_options.m_line_number,
2881                                                    m_options.m_check_inlines,
2882                                                    m_options.m_verbose))
2883                     {
2884                         result.SetStatus(eReturnStatusSuccessFinishResult);
2885                         return true;
2886                     }
2887                 }
2888                 break;
2889 
2890             case eLookupTypeFunction:
2891                 if (!m_options.m_str.empty())
2892                 {
2893                     if (LookupFunctionInModule (m_interpreter,
2894                                                 result.GetOutputStream(),
2895                                                 module,
2896                                                 m_options.m_str.c_str(),
2897                                                 m_options.m_use_regex,
2898                                                 m_options.m_verbose))
2899                     {
2900                         result.SetStatus(eReturnStatusSuccessFinishResult);
2901                         return true;
2902                     }
2903                 }
2904                 break;
2905 
2906             case eLookupTypeType:
2907                 if (!m_options.m_str.empty())
2908                 {
2909                     if (LookupTypeInModule (m_interpreter,
2910                                             result.GetOutputStream(),
2911                                             module,
2912                                             m_options.m_str.c_str(),
2913                                             m_options.m_use_regex))
2914                     {
2915                         result.SetStatus(eReturnStatusSuccessFinishResult);
2916                         return true;
2917                     }
2918                 }
2919                 break;
2920 
2921             default:
2922                 m_options.GenerateOptionUsage (result.GetErrorStream(), this);
2923                 syntax_error = true;
2924                 break;
2925         }
2926 
2927         result.SetStatus (eReturnStatusFailed);
2928         return false;
2929     }
2930 
2931     virtual bool
2932     Execute (Args& command,
2933              CommandReturnObject &result)
2934     {
2935         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
2936         if (target == NULL)
2937         {
2938             result.AppendError ("invalid target, create a debug target using the 'target create' command");
2939             result.SetStatus (eReturnStatusFailed);
2940             return false;
2941         }
2942         else
2943         {
2944             bool syntax_error = false;
2945             uint32_t i;
2946             uint32_t num_successful_lookups = 0;
2947             uint32_t addr_byte_size = target->GetArchitecture().GetAddressByteSize();
2948             result.GetOutputStream().SetAddressByteSize(addr_byte_size);
2949             result.GetErrorStream().SetAddressByteSize(addr_byte_size);
2950             // Dump all sections for all modules images
2951 
2952             if (command.GetArgumentCount() == 0)
2953             {
2954                 // Dump all sections for all modules images
2955                 const uint32_t num_modules = target->GetImages().GetSize();
2956                 if (num_modules > 0)
2957                 {
2958                     for (i = 0; i<num_modules && syntax_error == false; ++i)
2959                     {
2960                         if (LookupInModule (m_interpreter, target->GetImages().GetModulePointerAtIndex(i), result, syntax_error))
2961                         {
2962                             result.GetOutputStream().EOL();
2963                             num_successful_lookups++;
2964                         }
2965                     }
2966                 }
2967                 else
2968                 {
2969                     result.AppendError ("the target has no associated executable images");
2970                     result.SetStatus (eReturnStatusFailed);
2971                     return false;
2972                 }
2973             }
2974             else
2975             {
2976                 // Dump specified images (by basename or fullpath)
2977                 const char *arg_cstr;
2978                 for (i = 0; (arg_cstr = command.GetArgumentAtIndex(i)) != NULL && syntax_error == false; ++i)
2979                 {
2980                     FileSpec image_file(arg_cstr, false);
2981                     ModuleList matching_modules;
2982                     size_t num_matching_modules = target->GetImages().FindModules(&image_file, NULL, NULL, NULL, matching_modules);
2983 
2984                     // Not found in our module list for our target, check the main
2985                     // shared module list in case it is a extra file used somewhere
2986                     // else
2987                     if (num_matching_modules == 0)
2988                         num_matching_modules = ModuleList::FindSharedModules (image_file,
2989                                                                               target->GetArchitecture(),
2990                                                                               NULL,
2991                                                                               NULL,
2992                                                                               matching_modules);
2993 
2994                     if (num_matching_modules > 0)
2995                     {
2996                         for (size_t j=0; j<num_matching_modules; ++j)
2997                         {
2998                             Module * image_module = matching_modules.GetModulePointerAtIndex(j);
2999                             if (image_module)
3000                             {
3001                                 if (LookupInModule (m_interpreter, image_module, result, syntax_error))
3002                                 {
3003                                     result.GetOutputStream().EOL();
3004                                     num_successful_lookups++;
3005                                 }
3006                             }
3007                         }
3008                     }
3009                     else
3010                         result.AppendWarningWithFormat("Unable to find an image that matches '%s'.\n", arg_cstr);
3011                 }
3012             }
3013 
3014             if (num_successful_lookups > 0)
3015                 result.SetStatus (eReturnStatusSuccessFinishResult);
3016             else
3017                 result.SetStatus (eReturnStatusFailed);
3018         }
3019         return result.Succeeded();
3020     }
3021 protected:
3022 
3023     CommandOptions m_options;
3024 };
3025 
3026 OptionDefinition
3027 CommandObjectTargetModulesLookup::CommandOptions::g_option_table[] =
3028 {
3029     { LLDB_OPT_SET_1,   true,  "address",    'a', required_argument, NULL, 0, eArgTypeAddress,      "Lookup an address in one or more target modules."},
3030     { 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."},
3031     { LLDB_OPT_SET_2| LLDB_OPT_SET_4
3032       /* FIXME: re-enable this for types when the LookupTypeInModule actually uses the regex option: | LLDB_OPT_SET_5 */ ,
3033                         false, "regex",      'r', no_argument,       NULL, 0, eArgTypeNone,         "The <name> argument for name lookups are regular expressions."},
3034     { 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."},
3035     { 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."},
3036     { 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)."},
3037     { LLDB_OPT_SET_3,   false, "no-inlines", 'i', no_argument,       NULL, 0, eArgTypeNone,         "Check inline line entries (must be used in conjunction with --file)."},
3038     { 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."},
3039     { 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."},
3040     { LLDB_OPT_SET_ALL, false, "verbose",    'v', no_argument,       NULL, 0, eArgTypeNone,         "Enable verbose lookup information."},
3041     { 0, false, NULL,           0, 0,                 NULL, 0, eArgTypeNone, NULL }
3042 };
3043 
3044 
3045 #pragma mark CommandObjectMultiwordImageSearchPaths
3046 
3047 //-------------------------------------------------------------------------
3048 // CommandObjectMultiwordImageSearchPaths
3049 //-------------------------------------------------------------------------
3050 
3051 class CommandObjectTargetModulesImageSearchPaths : public CommandObjectMultiword
3052 {
3053 public:
3054 
3055     CommandObjectTargetModulesImageSearchPaths (CommandInterpreter &interpreter) :
3056     CommandObjectMultiword (interpreter,
3057                             "target modules search-paths",
3058                             "A set of commands for operating on debugger target image search paths.",
3059                             "target modules search-paths <subcommand> [<subcommand-options>]")
3060     {
3061         LoadSubCommand ("add",     CommandObjectSP (new CommandObjectTargetModulesSearchPathsAdd (interpreter)));
3062         LoadSubCommand ("clear",   CommandObjectSP (new CommandObjectTargetModulesSearchPathsClear (interpreter)));
3063         LoadSubCommand ("insert",  CommandObjectSP (new CommandObjectTargetModulesSearchPathsInsert (interpreter)));
3064         LoadSubCommand ("list",    CommandObjectSP (new CommandObjectTargetModulesSearchPathsList (interpreter)));
3065         LoadSubCommand ("query",   CommandObjectSP (new CommandObjectTargetModulesSearchPathsQuery (interpreter)));
3066     }
3067 
3068     ~CommandObjectTargetModulesImageSearchPaths()
3069     {
3070     }
3071 };
3072 
3073 
3074 
3075 #pragma mark CommandObjectTargetModules
3076 
3077 //-------------------------------------------------------------------------
3078 // CommandObjectTargetModules
3079 //-------------------------------------------------------------------------
3080 
3081 class CommandObjectTargetModules : public CommandObjectMultiword
3082 {
3083 public:
3084     //------------------------------------------------------------------
3085     // Constructors and Destructors
3086     //------------------------------------------------------------------
3087     CommandObjectTargetModules(CommandInterpreter &interpreter) :
3088         CommandObjectMultiword (interpreter,
3089                                 "target modules",
3090                                 "A set of commands for accessing information for one or more target modules.",
3091                                 "target modules <sub-command> ...")
3092     {
3093         LoadSubCommand ("add",          CommandObjectSP (new CommandObjectTargetModulesAdd (interpreter)));
3094         LoadSubCommand ("load",         CommandObjectSP (new CommandObjectTargetModulesLoad (interpreter)));
3095         //LoadSubCommand ("unload",       CommandObjectSP (new CommandObjectTargetModulesUnload (interpreter)));
3096         LoadSubCommand ("dump",         CommandObjectSP (new CommandObjectTargetModulesDump (interpreter)));
3097         LoadSubCommand ("list",         CommandObjectSP (new CommandObjectTargetModulesList (interpreter)));
3098         LoadSubCommand ("lookup",       CommandObjectSP (new CommandObjectTargetModulesLookup (interpreter)));
3099         LoadSubCommand ("search-paths", CommandObjectSP (new CommandObjectTargetModulesImageSearchPaths (interpreter)));
3100 
3101     }
3102     virtual
3103     ~CommandObjectTargetModules()
3104     {
3105     }
3106 
3107 private:
3108     //------------------------------------------------------------------
3109     // For CommandObjectTargetModules only
3110     //------------------------------------------------------------------
3111     DISALLOW_COPY_AND_ASSIGN (CommandObjectTargetModules);
3112 };
3113 
3114 
3115 #pragma mark CommandObjectTargetStopHookAdd
3116 
3117 //-------------------------------------------------------------------------
3118 // CommandObjectTargetStopHookAdd
3119 //-------------------------------------------------------------------------
3120 
3121 class CommandObjectTargetStopHookAdd : public CommandObject
3122 {
3123 public:
3124 
3125     class CommandOptions : public Options
3126     {
3127     public:
3128         CommandOptions (CommandInterpreter &interpreter) :
3129             Options(interpreter),
3130             m_line_start(0),
3131             m_line_end (UINT_MAX),
3132             m_func_name_type_mask (eFunctionNameTypeAuto),
3133             m_sym_ctx_specified (false),
3134             m_thread_specified (false),
3135             m_use_one_liner (false),
3136             m_one_liner()
3137         {
3138         }
3139 
3140         ~CommandOptions () {}
3141 
3142         const OptionDefinition*
3143         GetDefinitions ()
3144         {
3145             return g_option_table;
3146         }
3147 
3148         virtual Error
3149         SetOptionValue (uint32_t option_idx, const char *option_arg)
3150         {
3151             Error error;
3152             char short_option = (char) m_getopt_table[option_idx].val;
3153             bool success;
3154 
3155             switch (short_option)
3156             {
3157                 case 'c':
3158                     m_class_name = option_arg;
3159                     m_sym_ctx_specified = true;
3160                 break;
3161 
3162                 case 'e':
3163                     m_line_end = Args::StringToUInt32 (option_arg, UINT_MAX, 0, &success);
3164                     if (!success)
3165                     {
3166                         error.SetErrorStringWithFormat ("Invalid end line number: \"%s\".", option_arg);
3167                         break;
3168                     }
3169                     m_sym_ctx_specified = true;
3170                 break;
3171 
3172                 case 'l':
3173                     m_line_start = Args::StringToUInt32 (option_arg, 0, 0, &success);
3174                     if (!success)
3175                     {
3176                         error.SetErrorStringWithFormat ("Invalid start line number: \"%s\".", option_arg);
3177                         break;
3178                     }
3179                     m_sym_ctx_specified = true;
3180                 break;
3181 
3182                 case 'n':
3183                     m_function_name = option_arg;
3184                     m_func_name_type_mask |= eFunctionNameTypeAuto;
3185                     m_sym_ctx_specified = true;
3186                 break;
3187 
3188                 case 'f':
3189                     m_file_name = option_arg;
3190                     m_sym_ctx_specified = true;
3191                 break;
3192                 case 's':
3193                     m_module_name = option_arg;
3194                     m_sym_ctx_specified = true;
3195                 break;
3196                 case 't' :
3197                 {
3198                     m_thread_id = Args::StringToUInt64(option_arg, LLDB_INVALID_THREAD_ID, 0);
3199                     if (m_thread_id == LLDB_INVALID_THREAD_ID)
3200                        error.SetErrorStringWithFormat ("Invalid thread id string '%s'.\n", option_arg);
3201                     m_thread_specified = true;
3202                 }
3203                 break;
3204                 case 'T':
3205                     m_thread_name = option_arg;
3206                     m_thread_specified = true;
3207                 break;
3208                 case 'q':
3209                     m_queue_name = option_arg;
3210                     m_thread_specified = true;
3211                     break;
3212                 case 'x':
3213                 {
3214                     m_thread_index = Args::StringToUInt32(option_arg, UINT32_MAX, 0);
3215                     if (m_thread_id == UINT32_MAX)
3216                        error.SetErrorStringWithFormat ("Invalid thread index string '%s'.\n", option_arg);
3217                     m_thread_specified = true;
3218                 }
3219                 break;
3220                 case 'o':
3221                     m_use_one_liner = true;
3222                     m_one_liner = option_arg;
3223                 break;
3224                 default:
3225                     error.SetErrorStringWithFormat ("Unrecognized option %c.");
3226                 break;
3227             }
3228             return error;
3229         }
3230 
3231         void
3232         OptionParsingStarting ()
3233         {
3234             m_class_name.clear();
3235             m_function_name.clear();
3236             m_line_start = 0;
3237             m_line_end = UINT_MAX;
3238             m_file_name.clear();
3239             m_module_name.clear();
3240             m_func_name_type_mask = eFunctionNameTypeAuto;
3241             m_thread_id = LLDB_INVALID_THREAD_ID;
3242             m_thread_index = UINT32_MAX;
3243             m_thread_name.clear();
3244             m_queue_name.clear();
3245 
3246             m_sym_ctx_specified = false;
3247             m_thread_specified = false;
3248 
3249             m_use_one_liner = false;
3250             m_one_liner.clear();
3251         }
3252 
3253 
3254         static OptionDefinition g_option_table[];
3255 
3256         std::string m_class_name;
3257         std::string m_function_name;
3258         uint32_t    m_line_start;
3259         uint32_t    m_line_end;
3260         std::string m_file_name;
3261         std::string m_module_name;
3262         uint32_t m_func_name_type_mask;  // A pick from lldb::FunctionNameType.
3263         lldb::tid_t m_thread_id;
3264         uint32_t m_thread_index;
3265         std::string m_thread_name;
3266         std::string m_queue_name;
3267         bool        m_sym_ctx_specified;
3268         bool        m_thread_specified;
3269         // Instance variables to hold the values for one_liner options.
3270         bool m_use_one_liner;
3271         std::string m_one_liner;
3272     };
3273 
3274     Options *
3275     GetOptions ()
3276     {
3277         return &m_options;
3278     }
3279 
3280     CommandObjectTargetStopHookAdd (CommandInterpreter &interpreter) :
3281         CommandObject (interpreter,
3282                        "target stop-hook add ",
3283                        "Add a hook to be executed when the target stops.",
3284                        "target stop-hook add"),
3285         m_options (interpreter)
3286     {
3287     }
3288 
3289     ~CommandObjectTargetStopHookAdd ()
3290     {
3291     }
3292 
3293     static size_t
3294     ReadCommandsCallbackFunction (void *baton,
3295                                   InputReader &reader,
3296                                   lldb::InputReaderAction notification,
3297                                   const char *bytes,
3298                                   size_t bytes_len)
3299     {
3300         StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
3301         Target::StopHook *new_stop_hook = ((Target::StopHook *) baton);
3302         static bool got_interrupted;
3303         bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
3304 
3305         switch (notification)
3306         {
3307         case eInputReaderActivate:
3308             if (!batch_mode)
3309             {
3310                 out_stream->Printf ("%s\n", "Enter your stop hook command(s).  Type 'DONE' to end.");
3311                 if (reader.GetPrompt())
3312                     out_stream->Printf ("%s", reader.GetPrompt());
3313                 out_stream->Flush();
3314             }
3315             got_interrupted = false;
3316             break;
3317 
3318         case eInputReaderDeactivate:
3319             break;
3320 
3321         case eInputReaderReactivate:
3322             if (reader.GetPrompt() && !batch_mode)
3323             {
3324                 out_stream->Printf ("%s", reader.GetPrompt());
3325                 out_stream->Flush();
3326             }
3327             got_interrupted = false;
3328             break;
3329 
3330         case eInputReaderAsynchronousOutputWritten:
3331             break;
3332 
3333         case eInputReaderGotToken:
3334             if (bytes && bytes_len && baton)
3335             {
3336                 StringList *commands = new_stop_hook->GetCommandPointer();
3337                 if (commands)
3338                 {
3339                     commands->AppendString (bytes, bytes_len);
3340                 }
3341             }
3342             if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
3343             {
3344                 out_stream->Printf ("%s", reader.GetPrompt());
3345                 out_stream->Flush();
3346             }
3347             break;
3348 
3349         case eInputReaderInterrupt:
3350             {
3351                 // Finish, and cancel the stop hook.
3352                 new_stop_hook->GetTarget()->RemoveStopHookByID(new_stop_hook->GetID());
3353                 if (!batch_mode)
3354                 {
3355                     out_stream->Printf ("Stop hook cancelled.\n");
3356                     out_stream->Flush();
3357                 }
3358 
3359                 reader.SetIsDone (true);
3360             }
3361             got_interrupted = true;
3362             break;
3363 
3364         case eInputReaderEndOfFile:
3365             reader.SetIsDone (true);
3366             break;
3367 
3368         case eInputReaderDone:
3369             if (!got_interrupted && !batch_mode)
3370             {
3371                 out_stream->Printf ("Stop hook #%d added.\n", new_stop_hook->GetID());
3372                 out_stream->Flush();
3373             }
3374             break;
3375         }
3376 
3377         return bytes_len;
3378     }
3379 
3380     bool
3381     Execute (Args& command,
3382              CommandReturnObject &result)
3383     {
3384         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
3385         if (target)
3386         {
3387             Target::StopHookSP new_hook_sp;
3388             target->AddStopHook (new_hook_sp);
3389 
3390             //  First step, make the specifier.
3391             std::auto_ptr<SymbolContextSpecifier> specifier_ap;
3392             if (m_options.m_sym_ctx_specified)
3393             {
3394                 specifier_ap.reset(new SymbolContextSpecifier(m_interpreter.GetDebugger().GetSelectedTarget()));
3395 
3396                 if (!m_options.m_module_name.empty())
3397                 {
3398                     specifier_ap->AddSpecification (m_options.m_module_name.c_str(), SymbolContextSpecifier::eModuleSpecified);
3399                 }
3400 
3401                 if (!m_options.m_class_name.empty())
3402                 {
3403                     specifier_ap->AddSpecification (m_options.m_class_name.c_str(), SymbolContextSpecifier::eClassOrNamespaceSpecified);
3404                 }
3405 
3406                 if (!m_options.m_file_name.empty())
3407                 {
3408                     specifier_ap->AddSpecification (m_options.m_file_name.c_str(), SymbolContextSpecifier::eFileSpecified);
3409                 }
3410 
3411                 if (m_options.m_line_start != 0)
3412                 {
3413                     specifier_ap->AddLineSpecification (m_options.m_line_start, SymbolContextSpecifier::eLineStartSpecified);
3414                 }
3415 
3416                 if (m_options.m_line_end != UINT_MAX)
3417                 {
3418                     specifier_ap->AddLineSpecification (m_options.m_line_end, SymbolContextSpecifier::eLineEndSpecified);
3419                 }
3420 
3421                 if (!m_options.m_function_name.empty())
3422                 {
3423                     specifier_ap->AddSpecification (m_options.m_function_name.c_str(), SymbolContextSpecifier::eFunctionSpecified);
3424                 }
3425             }
3426 
3427             if (specifier_ap.get())
3428                 new_hook_sp->SetSpecifier (specifier_ap.release());
3429 
3430             // Next see if any of the thread options have been entered:
3431 
3432             if (m_options.m_thread_specified)
3433             {
3434                 ThreadSpec *thread_spec = new ThreadSpec();
3435 
3436                 if (m_options.m_thread_id != LLDB_INVALID_THREAD_ID)
3437                 {
3438                     thread_spec->SetTID (m_options.m_thread_id);
3439                 }
3440 
3441                 if (m_options.m_thread_index != UINT32_MAX)
3442                     thread_spec->SetIndex (m_options.m_thread_index);
3443 
3444                 if (!m_options.m_thread_name.empty())
3445                     thread_spec->SetName (m_options.m_thread_name.c_str());
3446 
3447                 if (!m_options.m_queue_name.empty())
3448                     thread_spec->SetQueueName (m_options.m_queue_name.c_str());
3449 
3450                 new_hook_sp->SetThreadSpecifier (thread_spec);
3451 
3452             }
3453             if (m_options.m_use_one_liner)
3454             {
3455                 // Use one-liner.
3456                 new_hook_sp->GetCommandPointer()->AppendString (m_options.m_one_liner.c_str());
3457                 result.AppendMessageWithFormat("Stop hook #%d added.\n", new_hook_sp->GetID());
3458             }
3459             else
3460             {
3461                 // Otherwise gather up the command list, we'll push an input reader and suck the data from that directly into
3462                 // the new stop hook's command string.
3463                 InputReaderSP reader_sp (new InputReader(m_interpreter.GetDebugger()));
3464                 if (!reader_sp)
3465                 {
3466                     result.AppendError("out of memory\n");
3467                     result.SetStatus (eReturnStatusFailed);
3468                     target->RemoveStopHookByID (new_hook_sp->GetID());
3469                     return false;
3470                 }
3471 
3472                 Error err (reader_sp->Initialize (CommandObjectTargetStopHookAdd::ReadCommandsCallbackFunction,
3473                                                   new_hook_sp.get(), // baton
3474                                                   eInputReaderGranularityLine,  // token size, to pass to callback function
3475                                                   "DONE",                       // end token
3476                                                   "> ",                         // prompt
3477                                                   true));                       // echo input
3478                 if (!err.Success())
3479                 {
3480                     result.AppendError (err.AsCString());
3481                     result.SetStatus (eReturnStatusFailed);
3482                     target->RemoveStopHookByID (new_hook_sp->GetID());
3483                     return false;
3484                 }
3485                 m_interpreter.GetDebugger().PushInputReader (reader_sp);
3486             }
3487             result.SetStatus (eReturnStatusSuccessFinishNoResult);
3488         }
3489         else
3490         {
3491             result.AppendError ("invalid target\n");
3492             result.SetStatus (eReturnStatusFailed);
3493         }
3494 
3495         return result.Succeeded();
3496     }
3497 private:
3498     CommandOptions m_options;
3499 };
3500 
3501 OptionDefinition
3502 CommandObjectTargetStopHookAdd::CommandOptions::g_option_table[] =
3503 {
3504     { LLDB_OPT_SET_ALL, false, "one-liner", 'o', required_argument, NULL, NULL, eArgTypeOneLiner,
3505         "Specify a one-line breakpoint command inline. Be sure to surround it with quotes." },
3506     { LLDB_OPT_SET_ALL, false, "shlib", 's', required_argument, NULL, CommandCompletions::eModuleCompletion, eArgTypeShlibName,
3507         "Set the module within which the stop-hook is to be run."},
3508     { LLDB_OPT_SET_ALL, false, "thread-index", 'x', required_argument, NULL, NULL, eArgTypeThreadIndex,
3509         "The stop hook is run only for the thread whose index matches this argument."},
3510     { LLDB_OPT_SET_ALL, false, "thread-id", 't', required_argument, NULL, NULL, eArgTypeThreadID,
3511         "The stop hook is run only for the thread whose TID matches this argument."},
3512     { LLDB_OPT_SET_ALL, false, "thread-name", 'T', required_argument, NULL, NULL, eArgTypeThreadName,
3513         "The stop hook is run only for the thread whose thread name matches this argument."},
3514     { LLDB_OPT_SET_ALL, false, "queue-name", 'q', required_argument, NULL, NULL, eArgTypeQueueName,
3515         "The stop hook is run only for threads in the queue whose name is given by this argument."},
3516     { LLDB_OPT_SET_1, false, "file", 'f', required_argument, NULL, CommandCompletions::eSourceFileCompletion, eArgTypeFilename,
3517         "Specify the source file within which the stop-hook is to be run." },
3518     { LLDB_OPT_SET_1, false, "start-line", 'l', required_argument, NULL, 0, eArgTypeLineNum,
3519         "Set the start of the line range for which the stop-hook is to be run."},
3520     { LLDB_OPT_SET_1, false, "end-line", 'e', required_argument, NULL, 0, eArgTypeLineNum,
3521         "Set the end of the line range for which the stop-hook is to be run."},
3522     { LLDB_OPT_SET_2, false, "classname", 'c', required_argument, NULL, NULL, eArgTypeClassName,
3523         "Specify the class within which the stop-hook is to be run." },
3524     { LLDB_OPT_SET_3, false, "name", 'n', required_argument, NULL, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName,
3525         "Set the function name within which the stop hook will be run." },
3526     { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
3527 };
3528 
3529 #pragma mark CommandObjectTargetStopHookDelete
3530 
3531 //-------------------------------------------------------------------------
3532 // CommandObjectTargetStopHookDelete
3533 //-------------------------------------------------------------------------
3534 
3535 class CommandObjectTargetStopHookDelete : public CommandObject
3536 {
3537 public:
3538 
3539     CommandObjectTargetStopHookDelete (CommandInterpreter &interpreter) :
3540         CommandObject (interpreter,
3541                        "target stop-hook delete [<id>]",
3542                        "Delete a stop-hook.",
3543                        "target stop-hook delete")
3544     {
3545     }
3546 
3547     ~CommandObjectTargetStopHookDelete ()
3548     {
3549     }
3550 
3551     bool
3552     Execute (Args& command,
3553              CommandReturnObject &result)
3554     {
3555         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
3556         if (target)
3557         {
3558             // FIXME: see if we can use the breakpoint id style parser?
3559             size_t num_args = command.GetArgumentCount();
3560             if (num_args == 0)
3561             {
3562                 if (!m_interpreter.Confirm ("Delete all stop hooks?", true))
3563                 {
3564                     result.SetStatus (eReturnStatusFailed);
3565                     return false;
3566                 }
3567                 else
3568                 {
3569                     target->RemoveAllStopHooks();
3570                 }
3571             }
3572             else
3573             {
3574                 bool success;
3575                 for (size_t i = 0; i < num_args; i++)
3576                 {
3577                     lldb::user_id_t user_id = Args::StringToUInt32 (command.GetArgumentAtIndex(i), 0, 0, &success);
3578                     if (!success)
3579                     {
3580                         result.AppendErrorWithFormat ("invalid stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i));
3581                         result.SetStatus(eReturnStatusFailed);
3582                         return false;
3583                     }
3584                     success = target->RemoveStopHookByID (user_id);
3585                     if (!success)
3586                     {
3587                         result.AppendErrorWithFormat ("unknown stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i));
3588                         result.SetStatus(eReturnStatusFailed);
3589                         return false;
3590                     }
3591                 }
3592             }
3593             result.SetStatus (eReturnStatusSuccessFinishNoResult);
3594         }
3595         else
3596         {
3597             result.AppendError ("invalid target\n");
3598             result.SetStatus (eReturnStatusFailed);
3599         }
3600 
3601         return result.Succeeded();
3602     }
3603 };
3604 #pragma mark CommandObjectTargetStopHookEnableDisable
3605 
3606 //-------------------------------------------------------------------------
3607 // CommandObjectTargetStopHookEnableDisable
3608 //-------------------------------------------------------------------------
3609 
3610 class CommandObjectTargetStopHookEnableDisable : public CommandObject
3611 {
3612 public:
3613 
3614     CommandObjectTargetStopHookEnableDisable (CommandInterpreter &interpreter, bool enable, const char *name, const char *help, const char *syntax) :
3615         CommandObject (interpreter,
3616                        name,
3617                        help,
3618                        syntax),
3619         m_enable (enable)
3620     {
3621     }
3622 
3623     ~CommandObjectTargetStopHookEnableDisable ()
3624     {
3625     }
3626 
3627     bool
3628     Execute (Args& command,
3629              CommandReturnObject &result)
3630     {
3631         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
3632         if (target)
3633         {
3634             // FIXME: see if we can use the breakpoint id style parser?
3635             size_t num_args = command.GetArgumentCount();
3636             bool success;
3637 
3638             if (num_args == 0)
3639             {
3640                 target->SetAllStopHooksActiveState (m_enable);
3641             }
3642             else
3643             {
3644                 for (size_t i = 0; i < num_args; i++)
3645                 {
3646                     lldb::user_id_t user_id = Args::StringToUInt32 (command.GetArgumentAtIndex(i), 0, 0, &success);
3647                     if (!success)
3648                     {
3649                         result.AppendErrorWithFormat ("invalid stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i));
3650                         result.SetStatus(eReturnStatusFailed);
3651                         return false;
3652                     }
3653                     success = target->SetStopHookActiveStateByID (user_id, m_enable);
3654                     if (!success)
3655                     {
3656                         result.AppendErrorWithFormat ("unknown stop hook id: \"%s\".\n", command.GetArgumentAtIndex(i));
3657                         result.SetStatus(eReturnStatusFailed);
3658                         return false;
3659                     }
3660                 }
3661             }
3662             result.SetStatus (eReturnStatusSuccessFinishNoResult);
3663         }
3664         else
3665         {
3666             result.AppendError ("invalid target\n");
3667             result.SetStatus (eReturnStatusFailed);
3668         }
3669         return result.Succeeded();
3670     }
3671 private:
3672     bool m_enable;
3673 };
3674 
3675 #pragma mark CommandObjectTargetStopHookList
3676 
3677 //-------------------------------------------------------------------------
3678 // CommandObjectTargetStopHookList
3679 //-------------------------------------------------------------------------
3680 
3681 class CommandObjectTargetStopHookList : public CommandObject
3682 {
3683 public:
3684 
3685     CommandObjectTargetStopHookList (CommandInterpreter &interpreter) :
3686         CommandObject (interpreter,
3687                        "target stop-hook list [<type>]",
3688                        "List all stop-hooks.",
3689                        "target stop-hook list")
3690     {
3691     }
3692 
3693     ~CommandObjectTargetStopHookList ()
3694     {
3695     }
3696 
3697     bool
3698     Execute (Args& command,
3699              CommandReturnObject &result)
3700     {
3701         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
3702         if (target)
3703         {
3704             bool notify = true;
3705             target->GetImageSearchPathList().Clear(notify);
3706             result.SetStatus (eReturnStatusSuccessFinishNoResult);
3707         }
3708         else
3709         {
3710             result.AppendError ("invalid target\n");
3711             result.SetStatus (eReturnStatusFailed);
3712         }
3713 
3714         size_t num_hooks = target->GetNumStopHooks ();
3715         if (num_hooks == 0)
3716         {
3717             result.GetOutputStream().PutCString ("No stop hooks.\n");
3718         }
3719         else
3720         {
3721             for (size_t i = 0; i < num_hooks; i++)
3722             {
3723                 Target::StopHookSP this_hook = target->GetStopHookAtIndex (i);
3724                 if (i > 0)
3725                     result.GetOutputStream().PutCString ("\n");
3726                 this_hook->GetDescription (&(result.GetOutputStream()), eDescriptionLevelFull);
3727             }
3728         }
3729         return result.Succeeded();
3730     }
3731 };
3732 
3733 #pragma mark CommandObjectMultiwordTargetStopHooks
3734 //-------------------------------------------------------------------------
3735 // CommandObjectMultiwordTargetStopHooks
3736 //-------------------------------------------------------------------------
3737 
3738 class CommandObjectMultiwordTargetStopHooks : public CommandObjectMultiword
3739 {
3740 public:
3741 
3742     CommandObjectMultiwordTargetStopHooks (CommandInterpreter &interpreter) :
3743         CommandObjectMultiword (interpreter,
3744                                 "target stop-hook",
3745                                 "A set of commands for operating on debugger target stop-hooks.",
3746                                 "target stop-hook <subcommand> [<subcommand-options>]")
3747     {
3748         LoadSubCommand ("add",      CommandObjectSP (new CommandObjectTargetStopHookAdd (interpreter)));
3749         LoadSubCommand ("delete",   CommandObjectSP (new CommandObjectTargetStopHookDelete (interpreter)));
3750         LoadSubCommand ("disable",  CommandObjectSP (new CommandObjectTargetStopHookEnableDisable (interpreter,
3751                                                                                                    false,
3752                                                                                                    "target stop-hook disable [<id>]",
3753                                                                                                    "Disable a stop-hook.",
3754                                                                                                    "target stop-hook disable")));
3755         LoadSubCommand ("enable",   CommandObjectSP (new CommandObjectTargetStopHookEnableDisable (interpreter,
3756                                                                                                    true,
3757                                                                                                    "target stop-hook enable [<id>]",
3758                                                                                                    "Enable a stop-hook.",
3759                                                                                                    "target stop-hook enable")));
3760         LoadSubCommand ("list",     CommandObjectSP (new CommandObjectTargetStopHookList (interpreter)));
3761     }
3762 
3763     ~CommandObjectMultiwordTargetStopHooks()
3764     {
3765     }
3766 };
3767 
3768 
3769 
3770 #pragma mark CommandObjectMultiwordTarget
3771 
3772 //-------------------------------------------------------------------------
3773 // CommandObjectMultiwordTarget
3774 //-------------------------------------------------------------------------
3775 
3776 CommandObjectMultiwordTarget::CommandObjectMultiwordTarget (CommandInterpreter &interpreter) :
3777     CommandObjectMultiword (interpreter,
3778                             "target",
3779                             "A set of commands for operating on debugger targets.",
3780                             "target <subcommand> [<subcommand-options>]")
3781 {
3782 
3783     LoadSubCommand ("create",    CommandObjectSP (new CommandObjectTargetCreate (interpreter)));
3784     LoadSubCommand ("list",      CommandObjectSP (new CommandObjectTargetList   (interpreter)));
3785     LoadSubCommand ("select",    CommandObjectSP (new CommandObjectTargetSelect (interpreter)));
3786     LoadSubCommand ("stop-hook", CommandObjectSP (new CommandObjectMultiwordTargetStopHooks (interpreter)));
3787     LoadSubCommand ("modules",   CommandObjectSP (new CommandObjectTargetModules (interpreter)));
3788     LoadSubCommand ("variable",  CommandObjectSP (new CommandObjectTargetVariable (interpreter)));
3789 }
3790 
3791 CommandObjectMultiwordTarget::~CommandObjectMultiwordTarget ()
3792 {
3793 }
3794 
3795 
3796