1 //===-- AppleObjCDeclVendor.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 "AppleObjCDeclVendor.h"
11 
12 #include "Plugins/ExpressionParser/Clang/ASTDumper.h"
13 #include "lldb/Core/Log.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
16 #include "lldb/Symbol/ClangUtil.h"
17 #include "lldb/Target/ObjCLanguageRuntime.h"
18 #include "lldb/Target/Process.h"
19 #include "lldb/Target/Target.h"
20 
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/DeclObjC.h"
23 
24 using namespace lldb_private;
25 
26 class lldb_private::AppleObjCExternalASTSource : public ClangExternalASTSourceCommon
27 {
28 public:
29     AppleObjCExternalASTSource (AppleObjCDeclVendor &decl_vendor) :
30         m_decl_vendor(decl_vendor)
31     {
32     }
33 
34     bool
35     FindExternalVisibleDeclsByName(const clang::DeclContext *decl_ctx, clang::DeclarationName name) override
36     {
37         static unsigned int invocation_id = 0;
38         unsigned int current_id = invocation_id++;
39 
40         Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));  // FIXME - a more appropriate log channel?
41 
42         if (log)
43         {
44             log->Printf("AppleObjCExternalASTSource::FindExternalVisibleDeclsByName[%u] on (ASTContext*)%p Looking for %s in (%sDecl*)%p",
45                         current_id,
46                         static_cast<void*>(&decl_ctx->getParentASTContext()),
47                         name.getAsString().c_str(), decl_ctx->getDeclKindName(),
48                         static_cast<const void*>(decl_ctx));
49         }
50 
51         do
52         {
53             const clang::ObjCInterfaceDecl *interface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl_ctx);
54 
55             if (!interface_decl)
56                 break;
57 
58             clang::ObjCInterfaceDecl *non_const_interface_decl = const_cast<clang::ObjCInterfaceDecl*>(interface_decl);
59 
60             if (!m_decl_vendor.FinishDecl(non_const_interface_decl))
61                 break;
62 
63             clang::DeclContext::lookup_result result = non_const_interface_decl->lookup(name);
64 
65             return (result.size() != 0);
66         }
67         while(0);
68 
69         SetNoExternalVisibleDeclsForName(decl_ctx, name);
70         return false;
71     }
72 
73     void
74     CompleteType(clang::TagDecl *tag_decl) override
75     {
76         static unsigned int invocation_id = 0;
77         unsigned int current_id = invocation_id++;
78 
79         Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));  // FIXME - a more appropriate log channel?
80 
81         if (log)
82         {
83             log->Printf("AppleObjCExternalASTSource::CompleteType[%u] on (ASTContext*)%p Completing (TagDecl*)%p named %s",
84                         current_id,
85                         static_cast<void*>(&tag_decl->getASTContext()),
86                         static_cast<void*>(tag_decl),
87                         tag_decl->getName().str().c_str());
88 
89             log->Printf("  AOEAS::CT[%u] Before:", current_id);
90             ASTDumper dumper((clang::Decl*)tag_decl);
91             dumper.ToLog(log, "    [CT] ");
92         }
93 
94         if (log)
95         {
96             log->Printf("  AOEAS::CT[%u] After:", current_id);
97             ASTDumper dumper((clang::Decl*)tag_decl);
98             dumper.ToLog(log, "    [CT] ");
99         }
100         return;
101     }
102 
103     void
104     CompleteType(clang::ObjCInterfaceDecl *interface_decl) override
105     {
106         static unsigned int invocation_id = 0;
107         unsigned int current_id = invocation_id++;
108 
109         Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));  // FIXME - a more appropriate log channel?
110 
111         if (log)
112         {
113             log->Printf("AppleObjCExternalASTSource::CompleteType[%u] on (ASTContext*)%p Completing (ObjCInterfaceDecl*)%p named %s",
114                         current_id,
115                         static_cast<void*>(&interface_decl->getASTContext()),
116                         static_cast<void*>(interface_decl),
117                         interface_decl->getName().str().c_str());
118 
119             log->Printf("  AOEAS::CT[%u] Before:", current_id);
120             ASTDumper dumper((clang::Decl*)interface_decl);
121             dumper.ToLog(log, "    [CT] ");
122         }
123 
124         m_decl_vendor.FinishDecl(interface_decl);
125 
126         if (log)
127         {
128             log->Printf("  [CT] After:");
129             ASTDumper dumper((clang::Decl*)interface_decl);
130             dumper.ToLog(log, "    [CT] ");
131         }
132         return;
133     }
134 
135     bool
136     layoutRecordType(const clang::RecordDecl *Record, uint64_t &Size, uint64_t &Alignment,
137                      llvm::DenseMap<const clang::FieldDecl *, uint64_t> &FieldOffsets,
138                      llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> &BaseOffsets,
139                      llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> &VirtualBaseOffsets) override
140     {
141         return false;
142     }
143 
144     void
145     StartTranslationUnit(clang::ASTConsumer *Consumer) override
146     {
147         clang::TranslationUnitDecl *translation_unit_decl = m_decl_vendor.m_ast_ctx.getASTContext()->getTranslationUnitDecl();
148         translation_unit_decl->setHasExternalVisibleStorage();
149         translation_unit_decl->setHasExternalLexicalStorage();
150     }
151 private:
152     AppleObjCDeclVendor                                    &m_decl_vendor;
153 };
154 
155 AppleObjCDeclVendor::AppleObjCDeclVendor(ObjCLanguageRuntime &runtime) :
156     DeclVendor(),
157     m_runtime(runtime),
158     m_ast_ctx(runtime.GetProcess()->GetTarget().GetArchitecture().GetTriple().getTriple().c_str()),
159     m_type_realizer_sp(m_runtime.GetEncodingToType())
160 {
161     m_external_source = new AppleObjCExternalASTSource (*this);
162     llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> external_source_owning_ptr (m_external_source);
163     m_ast_ctx.getASTContext()->setExternalSource(external_source_owning_ptr);
164 }
165 
166 clang::ObjCInterfaceDecl*
167 AppleObjCDeclVendor::GetDeclForISA(ObjCLanguageRuntime::ObjCISA isa)
168 {
169     ISAToInterfaceMap::const_iterator iter = m_isa_to_interface.find(isa);
170 
171     if (iter != m_isa_to_interface.end())
172         return iter->second;
173 
174     clang::ASTContext *ast_ctx = m_ast_ctx.getASTContext();
175 
176     ObjCLanguageRuntime::ClassDescriptorSP descriptor = m_runtime.GetClassDescriptorFromISA(isa);
177 
178     if (!descriptor)
179         return NULL;
180 
181     const ConstString &name(descriptor->GetClassName());
182 
183     clang::IdentifierInfo &identifier_info = ast_ctx->Idents.get(name.GetStringRef());
184 
185     clang::ObjCInterfaceDecl *new_iface_decl = clang::ObjCInterfaceDecl::Create(*ast_ctx,
186                                                                                 ast_ctx->getTranslationUnitDecl(),
187                                                                                 clang::SourceLocation(),
188                                                                                 &identifier_info,
189                                                                                 nullptr,
190                                                                                 nullptr);
191 
192     ClangASTMetadata meta_data;
193     meta_data.SetISAPtr(isa);
194     m_external_source->SetMetadata(new_iface_decl, meta_data);
195 
196     new_iface_decl->setHasExternalVisibleStorage();
197     new_iface_decl->setHasExternalLexicalStorage();
198 
199     ast_ctx->getTranslationUnitDecl()->addDecl(new_iface_decl);
200 
201     m_isa_to_interface[isa] = new_iface_decl;
202 
203     return new_iface_decl;
204 }
205 
206 class ObjCRuntimeMethodType
207 {
208 public:
209     ObjCRuntimeMethodType (const char *types) : m_is_valid(false)
210     {
211         const char *cursor = types;
212         enum ParserState {
213             Start = 0,
214             InType,
215             InPos
216         } state = Start;
217         const char *type = NULL;
218         int brace_depth = 0;
219 
220         uint32_t stepsLeft = 256;
221 
222         while (1)
223         {
224             if (--stepsLeft == 0)
225             {
226                 m_is_valid = false;
227                 return;
228             }
229 
230             switch (state)
231             {
232             case Start:
233                 {
234                     switch (*cursor)
235                     {
236                     default:
237                         state = InType;
238                         type = cursor;
239                         break;
240                     case '\0':
241                         m_is_valid = true;
242                         return;
243                     case '0': case '1': case '2': case '3': case '4':
244                     case '5': case '6': case '7': case '8': case '9':
245                         m_is_valid = false;
246                         return;
247                     }
248                 }
249                 break;
250             case InType:
251                 {
252                     switch (*cursor)
253                     {
254                     default:
255                         ++cursor;
256                         break;
257                     case '0': case '1': case '2': case '3': case '4':
258                     case '5': case '6': case '7': case '8': case '9':
259                         if (!brace_depth)
260                         {
261                             state = InPos;
262                             if (type)
263                             {
264                                 m_type_vector.push_back(std::string(type, (cursor - type)));
265                             }
266                             else
267                             {
268                                 m_is_valid = false;
269                                 return;
270                             }
271                             type = NULL;
272                         }
273                         else
274                         {
275                             ++cursor;
276                         }
277                         break;
278                     case '[': case '{': case '(':
279                         ++brace_depth;
280                         ++cursor;
281                         break;
282                     case ']': case '}': case ')':
283                         if (!brace_depth)
284                         {
285                             m_is_valid = false;
286                             return;
287                         }
288                         --brace_depth;
289                         ++cursor;
290                         break;
291                     case '\0':
292                         m_is_valid = false;
293                         return;
294                     }
295                 }
296                 break;
297             case InPos:
298                 {
299                     switch (*cursor)
300                     {
301                     default:
302                         state = InType;
303                         type = cursor;
304                         break;
305                     case '0': case '1': case '2': case '3': case '4':
306                     case '5': case '6': case '7': case '8': case '9':
307                         ++cursor;
308                         break;
309                     case '\0':
310                         m_is_valid = true;
311                         return;
312                     }
313                 }
314                 break;
315             }
316         }
317     }
318 
319     clang::ObjCMethodDecl *BuildMethod (clang::ObjCInterfaceDecl *interface_decl, const char *name, bool instance, ObjCLanguageRuntime::EncodingToTypeSP type_realizer_sp)
320     {
321         if (!m_is_valid || m_type_vector.size() < 3)
322             return NULL;
323 
324         clang::ASTContext &ast_ctx(interface_decl->getASTContext());
325 
326         clang::QualType return_qual_type;
327 
328         const bool isInstance = instance;
329         const bool isVariadic = false;
330         const bool isSynthesized = false;
331         const bool isImplicitlyDeclared = true;
332         const bool isDefined = false;
333         const clang::ObjCMethodDecl::ImplementationControl impControl = clang::ObjCMethodDecl::None;
334         const bool HasRelatedResultType = false;
335         const bool for_expression = true;
336 
337         std::vector <clang::IdentifierInfo *> selector_components;
338 
339         const char *name_cursor = name;
340         bool is_zero_argument = true;
341 
342 
343         while (*name_cursor != '\0')
344         {
345             const char *colon_loc = strchr(name_cursor, ':');
346             if (!colon_loc)
347             {
348                 selector_components.push_back(&ast_ctx.Idents.get(llvm::StringRef(name_cursor)));
349                 break;
350             }
351             else
352             {
353                 is_zero_argument = false;
354                 selector_components.push_back(&ast_ctx.Idents.get(llvm::StringRef(name_cursor, colon_loc - name_cursor)));
355                 name_cursor = colon_loc + 1;
356             }
357         }
358 
359         clang::Selector sel = ast_ctx.Selectors.getSelector(is_zero_argument ? 0 : selector_components.size(), selector_components.data());
360 
361         clang::QualType ret_type = ClangUtil::GetQualType(
362             type_realizer_sp->RealizeType(interface_decl->getASTContext(), m_type_vector[0].c_str(), for_expression));
363 
364         if (ret_type.isNull())
365             return NULL;
366 
367         clang::ObjCMethodDecl *ret = clang::ObjCMethodDecl::Create(ast_ctx,
368                                                                    clang::SourceLocation(),
369                                                                    clang::SourceLocation(),
370                                                                    sel,
371                                                                    ret_type,
372                                                                    NULL,
373                                                                    interface_decl,
374                                                                    isInstance,
375                                                                    isVariadic,
376                                                                    isSynthesized,
377                                                                    isImplicitlyDeclared,
378                                                                    isDefined,
379                                                                    impControl,
380                                                                    HasRelatedResultType);
381 
382         std::vector <clang::ParmVarDecl*> parm_vars;
383 
384         for (size_t ai = 3, ae = m_type_vector.size();
385              ai != ae;
386              ++ai)
387         {
388             const bool for_expression = true;
389             clang::QualType arg_type = ClangUtil::GetQualType(
390                 type_realizer_sp->RealizeType(ast_ctx, m_type_vector[ai].c_str(), for_expression));
391 
392             if (arg_type.isNull())
393                 return NULL; // well, we just wasted a bunch of time.  Wish we could delete the stuff we'd just made!
394 
395             parm_vars.push_back(clang::ParmVarDecl::Create(ast_ctx,
396                                                            ret,
397                                                            clang::SourceLocation(),
398                                                            clang::SourceLocation(),
399                                                            NULL,
400                                                            arg_type,
401                                                            NULL,
402                                                            clang::SC_None,
403                                                            NULL));
404         }
405 
406         ret->setMethodParams(ast_ctx, llvm::ArrayRef<clang::ParmVarDecl*>(parm_vars), llvm::ArrayRef<clang::SourceLocation>());
407 
408         return ret;
409     }
410 
411     explicit operator bool ()
412     {
413         return m_is_valid;
414     }
415 
416     size_t
417     GetNumTypes ()
418     {
419         return m_type_vector.size();
420     }
421 
422     const char*
423     GetTypeAtIndex (size_t idx)
424     {
425         return m_type_vector[idx].c_str();
426     }
427 
428 private:
429     typedef std::vector <std::string> TypeVector;
430 
431     TypeVector  m_type_vector;
432     bool        m_is_valid;
433 };
434 
435 bool
436 AppleObjCDeclVendor::FinishDecl(clang::ObjCInterfaceDecl *interface_decl)
437 {
438     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));  // FIXME - a more appropriate log channel?
439 
440     ClangASTMetadata *metadata = m_external_source->GetMetadata(interface_decl);
441     ObjCLanguageRuntime::ObjCISA objc_isa = 0;
442     if (metadata)
443      objc_isa = metadata->GetISAPtr();
444 
445     if (!objc_isa)
446         return false;
447 
448     if (!interface_decl->hasExternalVisibleStorage())
449         return true;
450 
451     interface_decl->startDefinition();
452 
453     interface_decl->setHasExternalVisibleStorage(false);
454     interface_decl->setHasExternalLexicalStorage(false);
455 
456     ObjCLanguageRuntime::ClassDescriptorSP descriptor = m_runtime.GetClassDescriptorFromISA(objc_isa);
457 
458     if (!descriptor)
459         return false;
460 
461     auto superclass_func = [interface_decl, this](ObjCLanguageRuntime::ObjCISA isa)
462     {
463         clang::ObjCInterfaceDecl *superclass_decl = GetDeclForISA(isa);
464 
465         if (!superclass_decl)
466             return;
467 
468         FinishDecl(superclass_decl);
469         clang::ASTContext *context = m_ast_ctx.getASTContext();
470         interface_decl->setSuperClass(
471                 context->getTrivialTypeSourceInfo(context->getObjCInterfaceType(superclass_decl)));
472     };
473 
474     auto instance_method_func = [log, interface_decl, this](const char *name, const char *types) -> bool
475     {
476         if (!name || !types)
477             return false; // skip this one
478 
479         ObjCRuntimeMethodType method_type(types);
480 
481         clang::ObjCMethodDecl *method_decl = method_type.BuildMethod (interface_decl, name, true, m_type_realizer_sp);
482 
483         if (log)
484             log->Printf("[  AOTV::FD] Instance method [%s] [%s]", name, types);
485 
486         if (method_decl)
487             interface_decl->addDecl(method_decl);
488 
489         return false;
490     };
491 
492     auto class_method_func = [log, interface_decl, this](const char *name, const char *types) -> bool
493     {
494         if (!name || !types)
495             return false; // skip this one
496 
497         ObjCRuntimeMethodType method_type(types);
498 
499         clang::ObjCMethodDecl *method_decl = method_type.BuildMethod (interface_decl, name, false, m_type_realizer_sp);
500 
501         if (log)
502             log->Printf("[  AOTV::FD] Class method [%s] [%s]", name, types);
503 
504         if (method_decl)
505             interface_decl->addDecl(method_decl);
506 
507         return false;
508     };
509 
510     auto ivar_func = [log, interface_decl, this](const char *name, const char *type, lldb::addr_t offset_ptr, uint64_t size) -> bool
511     {
512         if (!name || !type)
513             return false;
514 
515         const bool for_expression = false;
516 
517         if (log)
518             log->Printf("[  AOTV::FD] Instance variable [%s] [%s], offset at %" PRIx64, name, type, offset_ptr);
519 
520         CompilerType ivar_type = m_runtime.GetEncodingToType()->RealizeType(m_ast_ctx, type, for_expression);
521 
522         if (ivar_type.IsValid())
523         {
524             clang::TypeSourceInfo * const type_source_info = nullptr;
525             const bool is_synthesized = false;
526             clang::ObjCIvarDecl *ivar_decl = clang::ObjCIvarDecl::Create(
527                 *m_ast_ctx.getASTContext(), interface_decl, clang::SourceLocation(), clang::SourceLocation(),
528                 &m_ast_ctx.getASTContext()->Idents.get(name), ClangUtil::GetQualType(ivar_type),
529                 type_source_info, // TypeSourceInfo *
530                 clang::ObjCIvarDecl::Public, 0, is_synthesized);
531 
532             if (ivar_decl)
533             {
534                 interface_decl->addDecl(ivar_decl);
535             }
536         }
537 
538         return false;
539     };
540 
541     if (log)
542     {
543         ASTDumper method_dumper ((clang::Decl*)interface_decl);
544 
545         log->Printf("[AppleObjCDeclVendor::FinishDecl] Finishing Objective-C interface for %s", descriptor->GetClassName().AsCString());
546     }
547 
548 
549     if (!descriptor->Describe(superclass_func,
550                               instance_method_func,
551                               class_method_func,
552                               ivar_func))
553         return false;
554 
555     if (log)
556     {
557         ASTDumper method_dumper ((clang::Decl*)interface_decl);
558 
559         log->Printf("[AppleObjCDeclVendor::FinishDecl] Finished Objective-C interface");
560 
561         method_dumper.ToLog(log, "  [AOTV::FD] ");
562     }
563 
564     return true;
565 }
566 
567 uint32_t
568 AppleObjCDeclVendor::FindDecls (const ConstString &name,
569                                 bool append,
570                                 uint32_t max_matches,
571                                 std::vector <clang::NamedDecl *> &decls)
572 {
573     static unsigned int invocation_id = 0;
574     unsigned int current_id = invocation_id++;
575 
576     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));  // FIXME - a more appropriate log channel?
577 
578     if (log)
579         log->Printf("AppleObjCDeclVendor::FindTypes [%u] ('%s', %s, %u, )",
580                     current_id,
581                     (const char*)name.AsCString(),
582                     append ? "true" : "false",
583                     max_matches);
584 
585     if (!append)
586         decls.clear();
587 
588     uint32_t ret = 0;
589 
590     do
591     {
592         // See if the type is already in our ASTContext.
593 
594         clang::ASTContext *ast_ctx = m_ast_ctx.getASTContext();
595 
596         clang::IdentifierInfo &identifier_info = ast_ctx->Idents.get(name.GetStringRef());
597         clang::DeclarationName decl_name = ast_ctx->DeclarationNames.getIdentifier(&identifier_info);
598 
599         clang::DeclContext::lookup_result lookup_result = ast_ctx->getTranslationUnitDecl()->lookup(decl_name);
600 
601         if (!lookup_result.empty())
602         {
603             if (clang::ObjCInterfaceDecl *result_iface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(lookup_result[0]))
604             {
605                 if (log)
606                 {
607                     clang::QualType result_iface_type = ast_ctx->getObjCInterfaceType(result_iface_decl);
608                     ASTDumper dumper(result_iface_type);
609 
610                     uint64_t isa_value = LLDB_INVALID_ADDRESS;
611                     ClangASTMetadata *metadata = m_external_source->GetMetadata(result_iface_decl);
612                     if (metadata)
613                         isa_value = metadata->GetISAPtr();
614 
615                     log->Printf("AOCTV::FT [%u] Found %s (isa 0x%" PRIx64 ") in the ASTContext",
616                                 current_id,
617                                 dumper.GetCString(),
618                                 isa_value);
619                 }
620 
621                 decls.push_back(result_iface_decl);
622                 ret++;
623                 break;
624             }
625             else
626             {
627                 if (log)
628                     log->Printf("AOCTV::FT [%u] There's something in the ASTContext, but it's not something we know about",
629                                 current_id);
630                 break;
631             }
632         }
633         else if(log)
634         {
635             log->Printf("AOCTV::FT [%u] Couldn't find %s in the ASTContext",
636                         current_id,
637                         name.AsCString());
638         }
639 
640         // It's not.  If it exists, we have to put it into our ASTContext.
641 
642         ObjCLanguageRuntime::ObjCISA isa = m_runtime.GetISA(name);
643 
644         if (!isa)
645         {
646             if (log)
647                 log->Printf("AOCTV::FT [%u] Couldn't find the isa",
648                             current_id);
649 
650             break;
651         }
652 
653         clang::ObjCInterfaceDecl *iface_decl = GetDeclForISA(isa);
654 
655         if (!iface_decl)
656         {
657             if (log)
658                 log->Printf("AOCTV::FT [%u] Couldn't get the Objective-C interface for isa 0x%" PRIx64,
659                             current_id,
660                             (uint64_t)isa);
661 
662             break;
663         }
664 
665         if (log)
666         {
667             clang::QualType new_iface_type = ast_ctx->getObjCInterfaceType(iface_decl);
668             ASTDumper dumper(new_iface_type);
669             log->Printf("AOCTV::FT [%u] Created %s (isa 0x%" PRIx64 ")",
670                         current_id,
671                         dumper.GetCString(),
672                         (uint64_t)isa);
673         }
674 
675         decls.push_back(iface_decl);
676         ret++;
677         break;
678     } while (0);
679 
680     return ret;
681 }
682