1 //===-- ItaniumABILanguageRuntime.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 "ItaniumABILanguageRuntime.h"
11 
12 #include "lldb/Breakpoint/BreakpointLocation.h"
13 #include "lldb/Core/ConstString.h"
14 #include "lldb/Core/Error.h"
15 #include "lldb/Core/Log.h"
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Core/Scalar.h"
19 #include "lldb/Core/ValueObject.h"
20 #include "lldb/Core/ValueObjectMemory.h"
21 #include "lldb/Symbol/ClangASTContext.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Target/RegisterContext.h"
24 #include "lldb/Target/StopInfo.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Target/Thread.h"
27 
28 #include <vector>
29 
30 using namespace lldb;
31 using namespace lldb_private;
32 
33 static const char *pluginName = "ItaniumABILanguageRuntime";
34 static const char *pluginDesc = "Itanium ABI for the C++ language";
35 static const char *pluginShort = "language.itanium";
36 static const char *vtable_demangled_prefix = "vtable for ";
37 
38 bool
39 ItaniumABILanguageRuntime::CouldHaveDynamicValue (ValueObject &in_value)
40 {
41     return ClangASTContext::IsPossibleDynamicType(in_value.GetClangAST(), in_value.GetClangType(), NULL,
42                                                   true, // check for C++
43                                                   false); // do not check for ObjC
44 }
45 
46 bool
47 ItaniumABILanguageRuntime::GetDynamicTypeAndAddress (ValueObject &in_value,
48                                                      lldb::DynamicValueType use_dynamic,
49                                                      TypeAndOrName &class_type_or_name,
50                                                      Address &dynamic_address)
51 {
52     // For Itanium, if the type has a vtable pointer in the object, it will be at offset 0
53     // in the object.  That will point to the "address point" within the vtable (not the beginning of the
54     // vtable.)  We can then look up the symbol containing this "address point" and that symbol's name
55     // demangled will contain the full class name.
56     // The second pointer above the "address point" is the "offset_to_top".  We'll use that to get the
57     // start of the value object which holds the dynamic type.
58     //
59 
60     // Only a pointer or reference type can have a different dynamic and static type:
61     if (CouldHaveDynamicValue (in_value))
62     {
63         // First job, pull out the address at 0 offset from the object.
64         AddressType address_type;
65         lldb::addr_t original_ptr = in_value.GetPointerValue(&address_type);
66         if (original_ptr == LLDB_INVALID_ADDRESS)
67             return false;
68 
69         ExecutionContext exe_ctx (in_value.GetExecutionContextRef());
70 
71         Target *target = exe_ctx.GetTargetPtr();
72         Process *process = exe_ctx.GetProcessPtr();
73 
74         char memory_buffer[16];
75         DataExtractor data(memory_buffer, sizeof(memory_buffer),
76                            process->GetByteOrder(),
77                            process->GetAddressByteSize());
78         size_t address_byte_size = process->GetAddressByteSize();
79         Error error;
80         size_t bytes_read = process->ReadMemory (original_ptr,
81                                                  memory_buffer,
82                                                  address_byte_size,
83                                                  error);
84         if (!error.Success() || (bytes_read != address_byte_size))
85         {
86             return false;
87         }
88 
89         uint32_t offset_ptr = 0;
90         lldb::addr_t vtable_address_point = data.GetAddress (&offset_ptr);
91 
92         if (offset_ptr == 0)
93             return false;
94 
95         // Now find the symbol that contains this address:
96 
97         SymbolContext sc;
98         Address address_point_address;
99         if (target && !target->GetSectionLoadList().IsEmpty())
100         {
101             if (target->GetSectionLoadList().ResolveLoadAddress (vtable_address_point, address_point_address))
102             {
103                 target->GetImages().ResolveSymbolContextForAddress (address_point_address, eSymbolContextSymbol, sc);
104                 Symbol *symbol = sc.symbol;
105                 if (symbol != NULL)
106                 {
107                     const char *name = symbol->GetMangled().GetDemangledName().AsCString();
108                     if (strstr(name, vtable_demangled_prefix) == name)
109                     {
110                         LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
111                         if (log)
112                             log->Printf ("0x%16.16llx: static-type = '%s' has vtable symbol '%s'\n",
113                                          original_ptr,
114                                          in_value.GetTypeName().GetCString(),
115                                          name);
116                         // We are a C++ class, that's good.  Get the class name and look it up:
117                         const char *class_name = name + strlen(vtable_demangled_prefix);
118                         class_type_or_name.SetName (class_name);
119                         const bool exact_match = true;
120                         TypeList class_types;
121 
122                         uint32_t num_matches = 0;
123                         // First look in the module that the vtable symbol came from
124                         // and look for a single exact match.
125                         if (sc.module_sp)
126                         {
127                             num_matches = sc.module_sp->FindTypes (sc,
128                                                                    ConstString(class_name),
129                                                                    exact_match,
130                                                                    1,
131                                                                    class_types);
132                         }
133 
134                         // If we didn't find a symbol, then move on to the entire
135                         // module list in the target and get as many unique matches
136                         // as possible
137                         if (num_matches == 0)
138                         {
139                             num_matches = target->GetImages().FindTypes (sc,
140                                                                          ConstString(class_name),
141                                                                          exact_match,
142                                                                          UINT32_MAX,
143                                                                          class_types);
144                         }
145 
146                         lldb::TypeSP type_sp;
147                         if (num_matches == 0)
148                         {
149                             if (log)
150                                 log->Printf("0x%16.16llx: is not dynamic\n", original_ptr);
151                             return false;
152                         }
153                         if (num_matches == 1)
154                         {
155                             type_sp = class_types.GetTypeAtIndex(0);
156                             if (log)
157                                 log->Printf ("0x%16.16llx: static-type = '%s' has dynamic type: uid={0x%llx}, type-name='%s'\n",
158                                              original_ptr,
159                                              in_value.GetTypeName().AsCString(),
160                                              type_sp->GetID(),
161                                              type_sp->GetName().GetCString());
162 
163                             class_type_or_name.SetTypeSP(class_types.GetTypeAtIndex(0));
164                         }
165                         else if (num_matches > 1)
166                         {
167                             size_t i;
168                             if (log)
169                             {
170                                 for (i = 0; i < num_matches; i++)
171                                 {
172                                     type_sp = class_types.GetTypeAtIndex(i);
173                                     if (type_sp)
174                                     {
175                                         if (log)
176                                             log->Printf ("0x%16.16llx: static-type = '%s' has multiple matching dynamic types: uid={0x%llx}, type-name='%s'\n",
177                                                          original_ptr,
178                                                          in_value.GetTypeName().AsCString(),
179                                                          type_sp->GetID(),
180                                                          type_sp->GetName().GetCString());
181                                     }
182                                 }
183                             }
184 
185                             for (i = 0; i < num_matches; i++)
186                             {
187                                 type_sp = class_types.GetTypeAtIndex(i);
188                                 if (type_sp)
189                                 {
190                                     if (ClangASTContext::IsCXXClassType(type_sp->GetClangFullType()))
191                                     {
192                                         if (log)
193                                             log->Printf ("0x%16.16llx: static-type = '%s' has multiple matching dynamic types, picking this one: uid={0x%llx}, type-name='%s'\n",
194                                                          original_ptr,
195                                                          in_value.GetTypeName().AsCString(),
196                                                          type_sp->GetID(),
197                                                          type_sp->GetName().GetCString());
198                                         class_type_or_name.SetTypeSP(type_sp);
199                                         break;
200                                     }
201                                 }
202                             }
203 
204                             if (i == num_matches)
205                             {
206                                 if (log)
207                                     log->Printf ("0x%16.16llx: static-type = '%s' has multiple matching dynamic types, didn't find a C++ match\n",
208                                                  original_ptr,
209                                                  in_value.GetTypeName().AsCString());
210                                 return false;
211                             }
212                         }
213 
214                         // There can only be one type with a given name,
215                         // so we've just found duplicate definitions, and this
216                         // one will do as well as any other.
217                         // We don't consider something to have a dynamic type if
218                         // it is the same as the static type.  So compare against
219                         // the value we were handed.
220                         if (type_sp)
221                         {
222                             clang::ASTContext *in_ast_ctx = in_value.GetClangAST ();
223                             clang::ASTContext *this_ast_ctx = type_sp->GetClangAST ();
224                             if (in_ast_ctx == this_ast_ctx)
225                             {
226                                 if (ClangASTContext::AreTypesSame (in_ast_ctx,
227                                                                    in_value.GetClangType(),
228                                                                    type_sp->GetClangFullType()))
229                                 {
230                                     // The dynamic type we found was the same type,
231                                     // so we don't have a dynamic type here...
232                                     return false;
233                                 }
234                             }
235 
236                             // The offset_to_top is two pointers above the address.
237                             Address offset_to_top_address = address_point_address;
238                             int64_t slide = -2 * ((int64_t) target->GetArchitecture().GetAddressByteSize());
239                             offset_to_top_address.Slide (slide);
240 
241                             Error error;
242                             lldb::addr_t offset_to_top_location = offset_to_top_address.GetLoadAddress(target);
243 
244                             size_t bytes_read = process->ReadMemory (offset_to_top_location,
245                                                                      memory_buffer,
246                                                                      address_byte_size,
247                                                                      error);
248 
249                             if (!error.Success() || (bytes_read != address_byte_size))
250                             {
251                                 return false;
252                             }
253 
254                             offset_ptr = 0;
255                             int64_t offset_to_top = data.GetMaxS64(&offset_ptr, process->GetAddressByteSize());
256 
257                             // So the dynamic type is a value that starts at offset_to_top
258                             // above the original address.
259                             lldb::addr_t dynamic_addr = original_ptr + offset_to_top;
260                             if (!target->GetSectionLoadList().ResolveLoadAddress (dynamic_addr, dynamic_address))
261                             {
262                                 dynamic_address.SetRawAddress(dynamic_addr);
263                             }
264                             return true;
265                         }
266                     }
267                 }
268             }
269         }
270     }
271 
272     return false;
273 }
274 
275 bool
276 ItaniumABILanguageRuntime::IsVTableName (const char *name)
277 {
278     if (name == NULL)
279         return false;
280 
281     // Can we maybe ask Clang about this?
282     if (strstr (name, "_vptr$") == name)
283         return true;
284     else
285         return false;
286 }
287 
288 //------------------------------------------------------------------
289 // Static Functions
290 //------------------------------------------------------------------
291 LanguageRuntime *
292 ItaniumABILanguageRuntime::CreateInstance (Process *process, lldb::LanguageType language)
293 {
294     // FIXME: We have to check the process and make sure we actually know that this process supports
295     // the Itanium ABI.
296     if (language == eLanguageTypeC_plus_plus)
297         return new ItaniumABILanguageRuntime (process);
298     else
299         return NULL;
300 }
301 
302 void
303 ItaniumABILanguageRuntime::Initialize()
304 {
305     PluginManager::RegisterPlugin (pluginName,
306                                    pluginDesc,
307                                    CreateInstance);
308 }
309 
310 void
311 ItaniumABILanguageRuntime::Terminate()
312 {
313     PluginManager::UnregisterPlugin (CreateInstance);
314 }
315 
316 //------------------------------------------------------------------
317 // PluginInterface protocol
318 //------------------------------------------------------------------
319 const char *
320 ItaniumABILanguageRuntime::GetPluginName()
321 {
322     return pluginName;
323 }
324 
325 const char *
326 ItaniumABILanguageRuntime::GetShortPluginName()
327 {
328     return pluginShort;
329 }
330 
331 uint32_t
332 ItaniumABILanguageRuntime::GetPluginVersion()
333 {
334     return 1;
335 }
336 
337 static const char *exception_names[] = { "__cxa_begin_catch", "__cxa_throw", "__cxa_rethrow", "__cxa_allocate_exception"};
338 static const int num_throw_names = 3;
339 static const int num_expression_throw_names = 1;
340 
341 BreakpointResolverSP
342 ItaniumABILanguageRuntime::CreateExceptionResolver (Breakpoint *bkpt, bool catch_bp, bool throw_bp)
343 {
344     return CreateExceptionResolver (bkpt, catch_bp, throw_bp, false);
345 }
346 
347 BreakpointResolverSP
348 ItaniumABILanguageRuntime::CreateExceptionResolver (Breakpoint *bkpt, bool catch_bp, bool throw_bp, bool for_expressions)
349 {
350     BreakpointResolverSP resolver_sp;
351     static const int total_expressions = sizeof (exception_names)/sizeof (char *);
352 
353     // One complication here is that most users DON'T want to stop at __cxa_allocate_expression, but until we can do
354     // anything better with predicting unwinding the expression parser does.  So we have two forms of the exception
355     // breakpoints, one for expressions that leaves out __cxa_allocate_exception, and one that includes it.
356     // The SetExceptionBreakpoints does the latter, the CreateExceptionBreakpoint in the runtime the former.
357 
358     uint32_t num_expressions;
359     if (catch_bp && throw_bp)
360     {
361         if (for_expressions)
362             num_expressions = total_expressions;
363         else
364             num_expressions = total_expressions - num_expression_throw_names;
365 
366         resolver_sp.reset (new BreakpointResolverName (bkpt,
367                                                        exception_names,
368                                                        num_expressions,
369                                                        eFunctionNameTypeBase,
370                                                        eLazyBoolNo));
371     }
372     else if (throw_bp)
373     {
374         if (for_expressions)
375             num_expressions = num_throw_names - num_expression_throw_names;
376         else
377             num_expressions = num_throw_names;
378 
379         resolver_sp.reset (new BreakpointResolverName (bkpt,
380                                                        exception_names + 1,
381                                                        num_expressions,
382                                                        eFunctionNameTypeBase,
383                                                        eLazyBoolNo));
384     }
385     else if (catch_bp)
386         resolver_sp.reset (new BreakpointResolverName (bkpt,
387                                                        exception_names,
388                                                        total_expressions - num_throw_names,
389                                                        eFunctionNameTypeBase,
390                                                        eLazyBoolNo));
391 
392     return resolver_sp;
393 }
394 
395 void
396 ItaniumABILanguageRuntime::SetExceptionBreakpoints ()
397 {
398     if (!m_process)
399         return;
400 
401     const bool catch_bp = false;
402     const bool throw_bp = true;
403     const bool is_internal = true;
404     const bool for_expressions = true;
405 
406     // For the exception breakpoints set by the Expression parser, we'll be a little more aggressive and
407     // stop at exception allocation as well.
408 
409     if (!m_cxx_exception_bp_sp)
410     {
411         Target &target = m_process->GetTarget();
412 
413         BreakpointResolverSP exception_resolver_sp = CreateExceptionResolver (NULL, catch_bp, throw_bp, for_expressions);
414         SearchFilterSP filter_sp = target.GetSearchFilterForModule(NULL);
415 
416         m_cxx_exception_bp_sp = target.CreateBreakpoint (filter_sp, exception_resolver_sp, is_internal);
417     }
418     else
419         m_cxx_exception_bp_sp->SetEnabled (true);
420 
421 }
422 
423 void
424 ItaniumABILanguageRuntime::ClearExceptionBreakpoints ()
425 {
426     if (!m_process)
427         return;
428 
429     if (m_cxx_exception_bp_sp.get())
430     {
431         m_cxx_exception_bp_sp->SetEnabled (false);
432     }
433 }
434 
435 bool
436 ItaniumABILanguageRuntime::ExceptionBreakpointsExplainStop (lldb::StopInfoSP stop_reason)
437 {
438     if (!m_process)
439         return false;
440 
441     if (!stop_reason ||
442         stop_reason->GetStopReason() != eStopReasonBreakpoint)
443         return false;
444 
445     uint64_t break_site_id = stop_reason->GetValue();
446     return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint(break_site_id,
447                                                                                m_cxx_exception_bp_sp->GetID());
448 
449 }
450