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