Logo ROOT  
Reference Guide
TClingCallbacks.cxx
Go to the documentation of this file.
1// @(#)root/core/meta:$Id$
2// Author: Vassil Vassilev 7/10/2012
3
4/*************************************************************************
5 * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12#include "TClingCallbacks.h"
13
14#include "cling/Interpreter/DynamicLibraryManager.h"
15#include "cling/Interpreter/Interpreter.h"
16#include "cling/Interpreter/InterpreterCallbacks.h"
17#include "cling/Interpreter/Transaction.h"
18#include "cling/Utils/AST.h"
19
20#include "clang/AST/ASTConsumer.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/GlobalDecl.h"
25#include "clang/Frontend/CompilerInstance.h"
26#include "clang/Lex/HeaderSearch.h"
27#include "clang/Lex/PPCallbacks.h"
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Parse/Parser.h"
30#include "clang/Sema/Lookup.h"
31#include "clang/Sema/Scope.h"
32
33#include "llvm/Object/ELFObjectFile.h"
34#include "llvm/Object/ObjectFile.h"
35#include "llvm/Support/FileSystem.h"
36#include "llvm/Support/Path.h"
37
38#include "TClingUtils.h"
39#include "ClingRAII.h"
40
41using namespace clang;
42using namespace cling;
43using namespace ROOT::Internal;
44
46class TObject;
47
48// Functions used to forward calls from code compiled with no-rtti to code
49// compiled with rtti.
50extern "C" {
51 void TCling__UpdateListsOnCommitted(const cling::Transaction&, Interpreter*);
52 void TCling__UpdateListsOnUnloaded(const cling::Transaction&);
53 void TCling__InvalidateGlobal(const clang::Decl*);
54 void TCling__TransactionRollback(const cling::Transaction&);
55 void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt*&);
56 TObject* TCling__GetObjectAddress(const char *Name, void *&LookupCtx);
58 int TCling__AutoLoadCallback(const char* className);
59 int TCling__AutoParseCallback(const char* className);
60 const char* TCling__GetClassSharedLibs(const char* className);
61 int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl* name);
62 int TCling__CompileMacro(const char *fileName, const char *options);
63 void TCling__SplitAclicMode(const char* fileName, std::string &mode,
64 std::string &args, std::string &io, std::string &fname);
65 bool TCling__LibraryLoadingFailed(const std::string&, const std::string&, bool, bool);
66 void TCling__LibraryLoadedRTTI(const void* dyLibHandle,
67 llvm::StringRef canonicalName);
68 void TCling__LibraryUnloadedRTTI(const void* dyLibHandle,
69 llvm::StringRef canonicalName);
72 void TCling__RestoreInterpreterMutex(void *state);
75 void TCling__FindLoadedLibraries(std::vector<std::pair<uint32_t, std::string>> &sLibraries,
76 std::vector<std::string> &sPaths,
77 cling::Interpreter &interpreter, bool searchSystem);
78}
79
80TClingCallbacks::TClingCallbacks(cling::Interpreter* interp, bool hasCodeGen)
81 : InterpreterCallbacks(interp),
82 fLastLookupCtx(0), fROOTSpecialNamespace(0),
83 fFirstRun(true), fIsAutoloading(false), fIsAutoloadingRecursively(false),
84 fIsAutoParsingSuspended(false), fPPOldFlag(false), fPPChanged(false) {
85 if (hasCodeGen) {
86 Transaction* T = 0;
87 m_Interpreter->declare("namespace __ROOT_SpecialObjects{}", &T);
88 fROOTSpecialNamespace = dyn_cast<NamespaceDecl>(T->getFirstDecl().getSingleDecl());
89 }
90}
91
92//pin the vtable here
94
95void TClingCallbacks::InclusionDirective(clang::SourceLocation sLoc/*HashLoc*/,
96 const clang::Token &/*IncludeTok*/,
97 llvm::StringRef FileName,
98 bool /*IsAngled*/,
99 clang::CharSourceRange /*FilenameRange*/,
100 const clang::FileEntry *FE,
101 llvm::StringRef /*SearchPath*/,
102 llvm::StringRef /*RelativePath*/,
103 const clang::Module * Imported) {
104 // We found a module. Do not try to do anything else.
105 Sema &SemaR = m_Interpreter->getSema();
106 if (Imported) {
107 // FIXME: We should make the module visible at that point.
108 if (!SemaR.isModuleVisible(Imported))
109 ROOT::TMetaUtils::Info("TClingCallbacks::InclusionDirective",
110 "Module %s resolved but not visible!", Imported->Name.c_str());
111 else
112 return;
113 }
114
115 // Method called via Callbacks->InclusionDirective()
116 // in Preprocessor::HandleIncludeDirective(), invoked whenever an
117 // inclusion directive has been processed, and allowing us to try
118 // to autoload libraries using their header file name.
119 // Two strategies are tried:
120 // 1) The header name is looked for in the list of autoload keys
121 // 2) Heurists are applied to the header name to distill a classname.
122 // For example try to autoload TGClient (libGui) when seeing #include "TGClient.h"
123 // or TH1F in presence of TH1F.h.
124 // Strategy 2) is tried only if 1) fails.
125
126 bool isHeaderFile = FileName.endswith(".h") || FileName.endswith(".hxx") || FileName.endswith(".hpp");
127 if (!IsAutoloadingEnabled() || fIsAutoloadingRecursively || !isHeaderFile)
128 return;
129
130 std::string localString(FileName.str());
131
132 DeclarationName Name = &SemaR.getASTContext().Idents.get(localString.c_str());
133 LookupResult RHeader(SemaR, Name, sLoc, Sema::LookupOrdinaryName);
134
135 tryAutoParseInternal(localString, RHeader, SemaR.getCurScope(), FE);
136}
137
138// TCling__LibraryLoadingFailed is a function in TCling which handles errmessage
139bool TClingCallbacks::LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem,
140 bool permanent, bool resolved) {
141 return TCling__LibraryLoadingFailed(errmessage, libStem, permanent, resolved);
142}
143
144// Preprocessor callbacks used to handle special cases like for example:
145// #include "myMacro.C+"
146//
147bool TClingCallbacks::FileNotFound(llvm::StringRef FileName,
148 llvm::SmallVectorImpl<char> &RecoveryPath) {
149 // Method called via Callbacks->FileNotFound(Filename, RecoveryPath)
150 // in Preprocessor::HandleIncludeDirective(), initially allowing to
151 // change the include path, and allowing us to compile code via ACLiC
152 // when specifying #include "myfile.C+", and suppressing the preprocessor
153 // error message:
154 // input_line_23:1:10: fatal error: 'myfile.C+' file not found
155
156 Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
157
158 // remove any trailing "\n
159 std::string filename(FileName.str().substr(0,FileName.str().find_last_of('"')));
160 std::string fname, mode, arguments, io;
161 // extract the filename and ACliC mode
162 TCling__SplitAclicMode(filename.c_str(), mode, arguments, io, fname);
163 if (mode.length() > 0) {
164 if (llvm::sys::fs::exists(fname)) {
165 // format the CompileMacro() option string
166 std::string options = "k";
167 if (mode.find("++") != std::string::npos) options += "f";
168 if (mode.find("g") != std::string::npos) options += "g";
169 if (mode.find("O") != std::string::npos) options += "O";
170
171 // Save state of the preprocessor
172 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
173 Parser& P = const_cast<Parser&>(m_Interpreter->getParser());
174 // After we have saved the token reset the current one to
175 // something which is safe (semi colon usually means empty decl)
176 Token& Tok = const_cast<Token&>(P.getCurToken());
177 // We parsed 'include' token. We don't need to restore it, because
178 // we provide our own way of handling the entire #include "file.c+"
179 // Thus if we reverted the token back to the parser, we are in
180 // a trouble.
181 Tok.setKind(tok::semi);
182 // We can't PushDeclContext, because we go up and the routine that pops
183 // the DeclContext assumes that we drill down always.
184 // We have to be on the global context. At that point we are in a
185 // wrapper function so the parent context must be the global.
186 // This is needed to solve potential issues when using #include "myFile.C+"
187 // after a scope declaration like:
188 // void Check(TObject* obj) {
189 // if (obj) cout << "Found the referenced object\n";
190 // else cout << "Error: Could not find the referenced object\n";
191 // }
192 // #include "A.C+"
193 Sema& SemaR = m_Interpreter->getSema();
194 ASTContext& C = SemaR.getASTContext();
195 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(),
196 SemaR.TUScope);
197 int retcode = TCling__CompileMacro(fname.c_str(), options.c_str());
198 if (retcode) {
199 // compilation was successful, let's remember the original
200 // preprocessor "include not found" error suppression flag
201 if (!fPPChanged)
202 fPPOldFlag = PP.GetSuppressIncludeNotFoundError();
203 PP.SetSuppressIncludeNotFoundError(true);
204 fPPChanged = true;
205 }
206 return false;
207 }
208 }
209 if (fPPChanged) {
210 // restore the original preprocessor "include not found" error
211 // suppression flag
212 PP.SetSuppressIncludeNotFoundError(fPPOldFlag);
213 fPPChanged = false;
214 }
215 return false;
216}
217
218
219static bool topmostDCIsFunction(Scope* S) {
220 if (!S)
221 return false;
222
223 DeclContext* DC = S->getEntity();
224 // For DeclContext-less scopes like if (dyn_expr) {}
225 // Find the DC enclosing S.
226 while (!DC) {
227 S = S->getParent();
228 DC = S->getEntity();
229 }
230
231 // DynamicLookup only happens inside topmost functions:
232 clang::DeclContext* MaybeTU = DC;
233 while (MaybeTU && !isa<TranslationUnitDecl>(MaybeTU)) {
234 DC = MaybeTU;
235 MaybeTU = MaybeTU->getParent();
236 }
237 return isa<FunctionDecl>(DC);
238}
239
240// On a failed lookup we have to try to more things before issuing an error.
241// The symbol might need to be loaded by ROOT's autoloading mechanism or
242// it might be a ROOT special object.
243//
244// Try those first and if still failing issue the diagnostics.
245//
246// returns true when a declaration is found and no error should be emitted.
247//
248bool TClingCallbacks::LookupObject(LookupResult &R, Scope *S) {
250 // init error or rootcling
251 return false;
252 }
253
254 // Don't do any extra work if an error that is not still recovered occurred.
255 if (m_Interpreter->getSema().getDiagnostics().hasErrorOccurred())
256 return false;
257
258 if (tryAutoParseInternal(R.getLookupName().getAsString(), R, S))
259 return true; // happiness.
260
261 // The remaining lookup routines only work on global scope functions
262 // ("macros"), not in classes, namespaces etc - anything that looks like
263 // it has seen any trace of software development.
265 return false;
266
267 // If the autoload wasn't successful try ROOT specials.
269 return true;
270
271 // For backward-compatibility with CINT we must support stmts like:
272 // x = 4; y = new MyClass();
273 // I.e we should "inject" a C++11 auto keyword in front of "x" and "y"
274 // This has to have higher precedence than the dynamic scopes. It is claimed
275 // that if one assigns to a name and the lookup of that name fails if *must*
276 // auto keyword must be injected and the stmt evaluation must not be delayed
277 // until runtime.
278 // For now supported only at the prompt.
280 return true;
281 }
282
284 return false;
285
286 // Finally try to resolve this name as a dynamic name, i.e delay its
287 // resolution for runtime.
289}
290
291bool TClingCallbacks::LookupObject(const DeclContext* DC, DeclarationName Name) {
293 // init error or rootcling
294 return false;
295 }
296
297 if (!IsAutoloadingEnabled() || fIsAutoloadingRecursively) return false;
298
299 if (Name.getNameKind() != DeclarationName::Identifier) return false;
300
301
302
303 // Get the 'lookup' decl context.
304 // We need to cast away the constness because we will lookup items of this
305 // namespace/DeclContext
306 NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(const_cast<DeclContext*>(DC));
307 if (!NSD)
308 return false;
309
311 return false;
312
313 const DeclContext* primaryDC = NSD->getPrimaryContext();
314 if (primaryDC != DC)
315 return false;
316
317 Sema &SemaR = m_Interpreter->getSema();
318 LookupResult R(SemaR, Name, SourceLocation(), Sema::LookupOrdinaryName);
319 R.suppressDiagnostics();
320 // We need the qualified name for TCling to find the right library.
321 std::string qualName
322 = NSD->getQualifiedNameAsString() + "::" + Name.getAsString();
323
324
325 // We want to avoid qualified lookups, because they are expensive and
326 // difficult to construct. This is why we *artificially* push a scope and
327 // a decl context, where Sema should do the lookup.
328 clang::Scope S(SemaR.TUScope, clang::Scope::DeclScope, SemaR.getDiagnostics());
329 S.setEntity(const_cast<DeclContext*>(DC));
330 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, const_cast<DeclContext*>(DC), &S);
331
332 if (tryAutoParseInternal(qualName, R, SemaR.getCurScope())) {
333 llvm::SmallVector<NamedDecl*, 4> lookupResults;
334 for(LookupResult::iterator I = R.begin(), E = R.end(); I < E; ++I)
335 lookupResults.push_back(*I);
336 UpdateWithNewDecls(DC, Name, llvm::makeArrayRef(lookupResults.data(),
337 lookupResults.size()));
338 return true;
339 }
340 return false;
341}
342
343bool TClingCallbacks::LookupObject(clang::TagDecl* Tag) {
345 // init error or rootcling
346 return false;
347 }
348
349 // Clang needs Tag's complete definition. Can we parse it?
351
352 Sema &SemaR = m_Interpreter->getSema();
353
354 SourceLocation Loc = Tag->getLocation();
355 if (SemaR.getSourceManager().isInSystemHeader(Loc)) {
356 // We will not help the system headers, sorry.
357 return false;
358 }
359
360 for (auto ReRD: Tag->redecls()) {
361 // Don't autoparse a TagDecl while we are parsing its definition!
362 if (ReRD->isBeingDefined())
363 return false;
364 }
365
366
367 if (RecordDecl* RD = dyn_cast<RecordDecl>(Tag)) {
368 ASTContext& C = SemaR.getASTContext();
369 Parser& P = const_cast<Parser&>(m_Interpreter->getParser());
370
371 ParsingStateRAII raii(P,SemaR);
372
373 // Use the Normalized name for the autoload
374 std::string Name;
375 const ROOT::TMetaUtils::TNormalizedCtxt* tNormCtxt = NULL;
378 C.getTypeDeclType(RD),
379 *m_Interpreter,
380 *tNormCtxt);
381 // Autoparse implies autoload
382 if (TCling__AutoParseCallback(Name.c_str())) {
383 // We have read it; remember that.
384 Tag->setHasExternalLexicalStorage(false);
385 return true;
386 }
387 }
388 return false;
389}
390
391
392// The symbol might be defined in the ROOT class autoloading map so we have to
393// try to autoload it first and do secondary lookup to try to find it.
394//
395// returns true when a declaration is found and no error should be emitted.
396// If FileEntry, this is a reacting on a #include and Name is the included
397// filename.
398//
399bool TClingCallbacks::tryAutoParseInternal(llvm::StringRef Name, LookupResult &R,
400 Scope *S, const FileEntry* FE /*=0*/) {
402 // init error or rootcling
403 return false;
404 }
405
406 Sema &SemaR = m_Interpreter->getSema();
407
408 // Try to autoload first if autoloading is enabled
409 if (IsAutoloadingEnabled()) {
410 // Avoid tail chasing.
412 return false;
413
414 // We should try autoload only for special lookup failures.
415 Sema::LookupNameKind kind = R.getLookupKind();
416 if (!(kind == Sema::LookupTagName || kind == Sema::LookupOrdinaryName
417 || kind == Sema::LookupNestedNameSpecifierName
418 || kind == Sema::LookupNamespaceName))
419 return false;
420
422
423 bool lookupSuccess = false;
424 // Save state of the PP
425 Parser &P = const_cast<Parser &>(m_Interpreter->getParser());
426
427 ParsingStateRAII raii(P, SemaR);
428
429 // First see whether we have a fwd decl of this name.
430 // We shall only do that if lookup makes sense for it (!FE).
431 if (!FE) {
432 lookupSuccess = SemaR.LookupName(R, S);
433 if (lookupSuccess) {
434 if (R.isSingleResult()) {
435 if (isa<clang::RecordDecl>(R.getFoundDecl())) {
436 // Good enough; RequireCompleteType() will tell us if we
437 // need to auto parse.
438 // But we might need to auto-load.
441 return true;
442 }
443 }
444 }
445 }
446
447 if (TCling__AutoParseCallback(Name.str().c_str())) {
448 // Shouldn't we pop more?
449 raii.fPushedDCAndS.pop();
450 raii.fCleanupRAII.pop();
451 lookupSuccess = FE || SemaR.LookupName(R, S);
452 } else if (FE && TCling__GetClassSharedLibs(Name.str().c_str())) {
453 // We are "autoparsing" a header, and the header was not parsed.
454 // But its library is known - so we do know about that header.
455 // Do the parsing explicitly here, while recursive autoloading is
456 // disabled.
457 std::string incl = "#include \"";
458 incl += FE->getName();
459 incl += '"';
460 m_Interpreter->declare(incl);
461 }
462
464
465 if (lookupSuccess)
466 return true;
467 }
468
469 return false;
470}
471
472// If cling cannot find a name it should ask ROOT before it issues an error.
473// If ROOT knows the name then it has to create a new variable with that name
474// and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).
475// For example if the interpreter is looking for h in h-Draw(), this routine
476// will create
477// namespace __ROOT_SpecialObjects {
478// THist* h = (THist*) the_address;
479// }
480//
481// Later if h is called again it again won't be found by the standart lookup
482// because it is in our hidden namespace (nobody should do using namespace
483// __ROOT_SpecialObjects). It caches the variable declarations and their
484// last address. If the newly found decl with the same name (h) has different
485// address than the cached one it goes directly at the address and updates it.
486//
487// returns true when declaration is found and no error should be emitted.
488//
491 // init error or rootcling
492 return false;
493 }
494
495 // User must be able to redefine the names that come from a file.
496 if (R.isForRedeclaration())
497 return false;
498 // If there is a result abort.
499 if (!R.empty())
500 return false;
501 const Sema::LookupNameKind LookupKind = R.getLookupKind();
502 if (LookupKind != Sema::LookupOrdinaryName)
503 return false;
504
505
506 Sema &SemaR = m_Interpreter->getSema();
507 ASTContext& C = SemaR.getASTContext();
508 Preprocessor &PP = SemaR.getPreprocessor();
509 DeclContext *CurDC = SemaR.CurContext;
510 DeclarationName Name = R.getLookupName();
511
512 // Make sure that the failed lookup comes from a function body.
513 if(!CurDC || !CurDC->isFunctionOrMethod())
514 return false;
515
516 // Save state of the PP, because TCling__GetObjectAddress may induce nested
517 // lookup.
518 Preprocessor::CleanupAndRestoreCacheRAII cleanupPPRAII(PP);
519 TObject *obj = TCling__GetObjectAddress(Name.getAsString().c_str(),
521 cleanupPPRAII.pop(); // force restoring the cache
522
523 if (obj) {
524
525#if defined(R__MUST_REVISIT)
526#if R__MUST_REVISIT(6,2)
527 // Register the address in TCling::fgSetOfSpecials
528 // to speed-up the execution of TCling::RecursiveRemove when
529 // the object is not a special.
530 // See http://root.cern.ch/viewvc/trunk/core/meta/src/TCint.cxx?view=log#rev18109
531 if (!fgSetOfSpecials) {
532 fgSetOfSpecials = new std::set<TObject*>;
533 }
534 ((std::set<TObject*>*)fgSetOfSpecials)->insert((TObject*)*obj);
535#endif
536#endif
537
538 VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR, Name,
540 if (VD) {
541 //TODO: Check for same types.
542 GlobalDecl GD(VD);
543 TObject **address = (TObject**)m_Interpreter->getAddressOfGlobal(GD);
544 // Since code was generated already we cannot rely on the initializer
545 // of the decl in the AST, however we will update that init so that it
546 // will be easier while debugging.
547 CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit());
548 Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj);
549 CStyleCast->setSubExpr(newInit);
550
551 // The actual update happens here, directly in memory.
552 *address = obj;
553 }
554 else {
555 // Save state of the PP
556 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
557
558 const Decl *TD = TCling__GetObjectDecl(obj);
559 // We will declare the variable as pointer.
560 QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD)));
561
562 VD = VarDecl::Create(C, fROOTSpecialNamespace, SourceLocation(),
563 SourceLocation(), Name.getAsIdentifierInfo(), QT,
564 /*TypeSourceInfo*/0, SC_None);
565 // Build an initializer
566 Expr* Init
567 = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);
568 // Register the decl in our hidden special namespace
569 VD->setInit(Init);
570 fROOTSpecialNamespace->addDecl(VD);
571
572 cling::CompilationOptions CO;
573 CO.DeclarationExtraction = 0;
574 CO.ValuePrinting = CompilationOptions::VPDisabled;
575 CO.ResultEvaluation = 0;
576 CO.DynamicScoping = 0;
577 CO.Debug = 0;
578 CO.CodeGeneration = 1;
579
580 cling::Transaction* T = new cling::Transaction(CO, SemaR);
581 T->append(VD);
582 T->setState(cling::Transaction::kCompleted);
583
584 m_Interpreter->emitAllDecls(T);
585 }
586 assert(VD && "Cannot be null!");
587 R.addDecl(VD);
588 return true;
589 }
590
591 return false;
592}
593
596 // init error or rootcling
597 return false;
598 }
599
601 return false;
602
603 DeclarationName Name = R.getLookupName();
604 IdentifierInfo* II = Name.getAsIdentifierInfo();
605 SourceLocation Loc = R.getNameLoc();
606 Sema& SemaRef = R.getSema();
607 ASTContext& C = SemaRef.getASTContext();
608 DeclContext* TU = C.getTranslationUnitDecl();
609 assert(TU && "Must not be null.");
610
611 // DynamicLookup only happens inside wrapper functions:
612 clang::FunctionDecl* Wrapper = nullptr;
613 Scope* Cursor = S;
614 do {
615 DeclContext* DCCursor = Cursor->getEntity();
616 if (DCCursor == TU)
617 return false;
618 Wrapper = dyn_cast_or_null<FunctionDecl>(DCCursor);
619 if (Wrapper) {
620 if (utils::Analyze::IsWrapper(Wrapper)) {
621 break;
622 } else {
623 // Can't have a function inside the wrapper:
624 return false;
625 }
626 }
627 } while ((Cursor = Cursor->getParent()));
628
629 if (!Wrapper) {
630 // The parent of S wasn't the TU?!
631 return false;
632 }
633
634 VarDecl* Result = VarDecl::Create(C, TU, Loc, Loc, II, C.DependentTy,
635 /*TypeSourceInfo*/0, SC_None);
636
637 if (!Result) {
638 // We cannot handle the situation. Give up
639 return false;
640 }
641
642 // Annotate the decl to give a hint in cling. FIXME: Current implementation
643 // is a gross hack, because TClingCallbacks shouldn't know about
644 // EvaluateTSynthesizer at all!
645
646 SourceRange invalidRange;
647 Wrapper->addAttr(new (C) AnnotateAttr(invalidRange, C, "__ResolveAtRuntime", 0));
648
649 // Here we have the scope but we cannot do Sema::PushDeclContext, because
650 // on pop it will try to go one level up, which we don't want.
651 Sema::ContextRAII pushedDC(SemaRef, TU);
652 R.addDecl(Result);
653 //SemaRef.PushOnScopeChains(Result, SemaRef.TUScope, /*Add to ctx*/true);
654 // Say that we can handle the situation. Clang should try to recover
655 return true;
656}
657
658bool TClingCallbacks::shouldResolveAtRuntime(LookupResult& R, Scope* S) {
659 if (m_IsRuntime)
660 return false;
661
662 if (R.getLookupKind() != Sema::LookupOrdinaryName)
663 return false;
664
665 if (R.isForRedeclaration())
666 return false;
667
668 if (!R.empty())
669 return false;
670
671 const Transaction* T = getInterpreter()->getCurrentTransaction();
672 if (!T)
673 return false;
674 const cling::CompilationOptions& COpts = T->getCompilationOpts();
675 if (!COpts.DynamicScoping)
676 return false;
677
678 // FIXME: Figure out better way to handle:
679 // C++ [basic.lookup.classref]p1:
680 // In a class member access expression (5.2.5), if the . or -> token is
681 // immediately followed by an identifier followed by a <, the
682 // identifier must be looked up to determine whether the < is the
683 // beginning of a template argument list (14.2) or a less-than operator.
684 // The identifier is first looked up in the class of the object
685 // expression. If the identifier is not found, it is then looked up in
686 // the context of the entire postfix-expression and shall name a class
687 // or function template.
688 //
689 // We want to ignore object(.|->)member<template>
690 //if (R.getSema().PP.LookAhead(0).getKind() == tok::less)
691 // TODO: check for . or -> in the cached token stream
692 // return false;
693
694 for (Scope* DepScope = S; DepScope; DepScope = DepScope->getParent()) {
695 if (DeclContext* Ctx = static_cast<DeclContext*>(DepScope->getEntity())) {
696 if (!Ctx->isDependentContext())
697 // For now we support only the prompt.
698 if (isa<FunctionDecl>(Ctx))
699 return true;
700 }
701 }
702
703 return false;
704}
705
708 // init error or rootcling
709 return false;
710 }
711
712 // Should be disabled with the dynamic scopes.
713 if (m_IsRuntime)
714 return false;
715
716 if (R.isForRedeclaration())
717 return false;
718
719 if (R.getLookupKind() != Sema::LookupOrdinaryName)
720 return false;
721
722 if (!isa<FunctionDecl>(R.getSema().CurContext))
723 return false;
724
725 {
726 // ROOT-8538: only top-most (function-level) scope is supported.
727 DeclContext* ScopeDC = S->getEntity();
728 if (!ScopeDC || !llvm::isa<FunctionDecl>(ScopeDC))
729 return false;
730
731 // Make sure that the failed lookup comes the prompt. Currently, we
732 // support only the prompt.
733 Scope* FnScope = S->getFnParent();
734 if (!FnScope)
735 return false;
736 auto FD = dyn_cast_or_null<FunctionDecl>(FnScope->getEntity());
737 if (!FD || !utils::Analyze::IsWrapper(FD))
738 return false;
739 }
740
741 Sema& SemaRef = R.getSema();
742 ASTContext& C = SemaRef.getASTContext();
743 DeclContext* DC = SemaRef.CurContext;
744 assert(DC && "Must not be null.");
745
746
747 Preprocessor& PP = R.getSema().getPreprocessor();
748 //Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
749 //PP.EnableBacktrackAtThisPos();
750 if (PP.LookAhead(0).isNot(tok::equal)) {
751 //PP.Backtrack();
752 return false;
753 }
754 //PP.CommitBacktrackedTokens();
755 //cleanupRAII.pop();
756 DeclarationName Name = R.getLookupName();
757 IdentifierInfo* II = Name.getAsIdentifierInfo();
758 SourceLocation Loc = R.getNameLoc();
759 VarDecl* Result = VarDecl::Create(C, DC, Loc, Loc, II,
760 C.getAutoType(QualType(),
761 clang::AutoTypeKeyword::Auto,
762 /*IsDependent*/false),
763 /*TypeSourceInfo*/0, SC_None);
764
765 if (!Result) {
766 ROOT::TMetaUtils::Error("TClingCallbacks::tryInjectImplicitAutoKeyword",
767 "Cannot create VarDecl");
768 return false;
769 }
770
771 // Annotate the decl to give a hint in cling.
772 // FIXME: We should move this in cling, when we implement turning it on
773 // and off.
774 SourceRange invalidRange;
775 Result->addAttr(new (C) AnnotateAttr(invalidRange, C, "__Auto", 0));
776
777 R.addDecl(Result);
778 // Say that we can handle the situation. Clang should try to recover
779 return true;
780}
781
783 // Replay existing decls from the AST.
784 if (fFirstRun) {
785 // Before setting up the callbacks register what cling have seen during init.
786 Sema& SemaR = m_Interpreter->getSema();
787 cling::Transaction TPrev((cling::CompilationOptions(), SemaR));
788 TPrev.append(SemaR.getASTContext().getTranslationUnitDecl());
789 TCling__UpdateListsOnCommitted(TPrev, m_Interpreter);
790
791 fFirstRun = false;
792 }
793}
794
795// The callback is used to update the list of globals in ROOT.
796//
797void TClingCallbacks::TransactionCommitted(const Transaction &T) {
798 if (fFirstRun && T.empty())
799 Initialize();
800
801 TCling__UpdateListsOnCommitted(T, m_Interpreter);
802}
803
804// The callback is used to update the list of globals in ROOT.
805//
806void TClingCallbacks::TransactionUnloaded(const Transaction &T) {
807 if (T.empty())
808 return;
809
811}
812
813// The callback is used to clear the autoparsing caches.
814//
815void TClingCallbacks::TransactionRollback(const Transaction &T) {
816 if (T.empty())
817 return;
818
820}
821
822void TClingCallbacks::DefinitionShadowed(const clang::NamedDecl *D) {
824}
825
826void TClingCallbacks::DeclDeserialized(const clang::Decl* D) {
827 if (const RecordDecl* RD = dyn_cast<RecordDecl>(D)) {
828 // FIXME: Our autoloading doesn't work (load the library) when the looked
829 // up decl is found in the PCH/PCM. We have to do that extra step, which
830 // loads the corresponding library when a decl was deserialized.
831 //
832 // Unfortunately we cannot do that with the current implementation,
833 // because the library load will pull in the header files of the library
834 // as well, even though they are in the PCH/PCM and available.
835 (void)RD;//TCling__AutoLoadCallback(RD->getNameAsString().c_str());
836 }
837}
838
839void TClingCallbacks::LibraryLoaded(const void* dyLibHandle,
840 llvm::StringRef canonicalName) {
841 TCling__LibraryLoadedRTTI(dyLibHandle, canonicalName);
842}
843
844void TClingCallbacks::LibraryUnloaded(const void* dyLibHandle,
845 llvm::StringRef canonicalName) {
846 TCling__LibraryUnloadedRTTI(dyLibHandle, canonicalName);
847}
848
851}
852
854{
855 // We can safely assume that if the lock exist already when we are in Cling code,
856 // then the lock has (or should been taken) already. Any action (that caused callers
857 // to take the lock) is halted during ProcessLine. So it is fair to unlock it.
859}
860
862{
864}
865
867{
869}
870
872{
874}
875
876static bool shouldIgnore(const std::string& FileName,
877 const cling::DynamicLibraryManager& dyLibManager) {
878 if (llvm::sys::fs::is_directory(FileName))
879 return true;
880
881 if (!cling::DynamicLibraryManager::isSharedLibrary(FileName))
882 return true;
883
884 // No need to check linked libraries, as this function is only invoked
885 // for symbols that cannot be found (neither by dlsym nor in the JIT).
886 if (dyLibManager.isLibraryLoaded(FileName.c_str()))
887 return true;
888
889
890 auto ObjF = llvm::object::ObjectFile::createObjectFile(FileName);
891 if (!ObjF) {
892 if (gDebug > 1)
893 ROOT::TMetaUtils::Warning("[DyLD]", "Failed to read object file %s",
894 FileName.c_str());
895 return true;
896 }
897
898 llvm::object::ObjectFile *file = ObjF.get().getBinary();
899
900 if (isa<llvm::object::ELFObjectFileBase>(*file)) {
901 for (auto S : file->sections()) {
902 StringRef name;
903 S.getName(name);
904 if (name == ".text") {
905 // Check if the library has only debug symbols, usually when
906 // stripped with objcopy --only-keep-debug. This check is done by
907 // reading the manual of objcopy and inspection of stripped with
908 // objcopy libraries.
909 auto SecRef = static_cast<llvm::object::ELFSectionRef&>(S);
910 if (SecRef.getType() == llvm::ELF::SHT_NOBITS)
911 return true;
912
913 return (SecRef.getFlags() & llvm::ELF::SHF_ALLOC) == 0;
914 }
915 }
916 return true;
917 }
918 //FIXME: Handle osx using isStripped after upgrading to llvm9.
919
920 llvm::StringRef fileStem = llvm::sys::path::stem(FileName);
921 return fileStem.startswith("libNew");
922}
923
924static void SearchAndAddPath(const std::string& Path,
925 std::vector<std::pair<uint32_t, std::string>> &sLibraries, std::vector<std::string> &sPaths,
926 std::unordered_set<std::string>& alreadyLookedPath, cling::DynamicLibraryManager* dyLibManager)
927{
928 // Already searched?
929 auto it = alreadyLookedPath.insert(Path);
930 if (!it.second)
931 return;
932 StringRef DirPath(Path);
933 if (!llvm::sys::fs::is_directory(DirPath))
934 return;
935
936 bool flag = false;
937 std::error_code EC;
938 for (llvm::sys::fs::directory_iterator DirIt(DirPath, EC), DirEnd;
939 DirIt != DirEnd && !EC; DirIt.increment(EC)) {
940
941 std::string FileName(DirIt->path());
942 if (shouldIgnore(FileName, *dyLibManager))
943 continue;
944
945 sLibraries.push_back(std::make_pair(sPaths.size(), llvm::sys::path::filename(FileName)));
946 flag = true;
947 }
948
949 if (flag)
950 sPaths.push_back(Path);
951}
952
953// Extracted here to circumvent ODR clash between
954// std::Sp_counted_ptr_inplace<llvm::sys::fs::detail::DirIterState, std::allocator<llvm::sys::fs::detail::DirIterState>, (_gnu_cxx::_Lock_policy)2>::_M_get_deleter(std::type_info const&)
955// coming from a no-rtti and a rtti build in libstdc++ from GCC >= 8.1.
956// In its function body, rtti uses `arg0 == typeid(...)` protected by #ifdef __cpp_rtti. Depending
957// on which symbol (with or without rtti) the linker picks up, the argument `arg0` is a valid
958// type_info - or not, in which case this comparison crashes.
959// Circumvent this by removing the rtti-use of this function:
960void TCling__FindLoadedLibraries(std::vector<std::pair<uint32_t, std::string>> &sLibraries,
961 std::vector<std::string> &sPaths,
962 cling::Interpreter &interpreter, bool searchSystem)
963{
964 // Store the information of path so that we don't have to iterate over the same path again and again.
965 static std::unordered_set<std::string> alreadyLookedPath;
966 cling::DynamicLibraryManager* dyLibManager = interpreter.getDynamicLibraryManager();
967
968 const auto &searchPaths = dyLibManager->getSearchPath();
969 for (const cling::DynamicLibraryManager::SearchPathInfo &Info : searchPaths) {
970 if (!Info.IsUser && !searchSystem)
971 continue;
972 SearchAndAddPath(Info.Path, sLibraries, sPaths, alreadyLookedPath, dyLibManager);
973 }
974}
#define R__EXTERN
Definition: DllImport.h:27
#define R(a, b, c, d, e, f, g, h, i)
Definition: RSha256.hxx:110
bool TCling__LibraryLoadingFailed(const std::string &, const std::string &, bool, bool)
Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name, which is extracted by er...
Definition: TCling.cxx:346
static void SearchAndAddPath(const std::string &Path, std::vector< std::pair< uint32_t, std::string > > &sLibraries, std::vector< std::string > &sPaths, std::unordered_set< std::string > &alreadyLookedPath, cling::DynamicLibraryManager *dyLibManager)
void TCling__FindLoadedLibraries(std::vector< std::pair< uint32_t, std::string > > &sLibraries, std::vector< std::string > &sPaths, cling::Interpreter &interpreter, bool searchSystem)
static bool shouldIgnore(const std::string &FileName, const cling::DynamicLibraryManager &dyLibManager)
void * TCling__LockCompilationDuringUserCodeExecution()
Lock the interpreter.
Definition: TCling.cxx:363
void TCling__UpdateListsOnCommitted(const cling::Transaction &, Interpreter *)
void TCling__SplitAclicMode(const char *fileName, std::string &mode, std::string &args, std::string &io, std::string &fname)
Definition: TCling.cxx:645
void TCling__TransactionRollback(const cling::Transaction &)
Definition: TCling.cxx:574
const char * TCling__GetClassSharedLibs(const char *className)
Definition: TCling.cxx:627
int TCling__AutoParseCallback(const char *className)
Definition: TCling.cxx:622
Decl * TCling__GetObjectDecl(TObject *obj)
Definition: TCling.cxx:599
R__EXTERN int gDebug
void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt *&)
Definition: TCling.cxx:552
void TCling__RestoreInterpreterMutex(void *state)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
Definition: TCling.cxx:336
int TCling__CompileMacro(const char *fileName, const char *options)
Definition: TCling.cxx:638
void * TCling__ResetInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition: TCling.cxx:355
int TCling__AutoLoadCallback(const char *className)
Definition: TCling.cxx:617
void TCling__LibraryUnloadedRTTI(const void *dyLibHandle, llvm::StringRef canonicalName)
void TCling__PrintStackTrace()
Print a StackTrace!
Definition: TCling.cxx:329
int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *name)
Definition: TCling.cxx:633
void TCling__UpdateListsOnUnloaded(const cling::Transaction &)
Definition: TCling.cxx:564
void TCling__UnlockCompilationDuringUserCodeExecution(void *state)
Unlock the interpreter.
Definition: TCling.cxx:374
static bool topmostDCIsFunction(Scope *S)
void TCling__InvalidateGlobal(const clang::Decl *)
Definition: TCling.cxx:569
void TCling__LibraryLoadedRTTI(const void *dyLibHandle, llvm::StringRef canonicalName)
TObject * TCling__GetObjectAddress(const char *Name, void *&LookupCtx)
Definition: TCling.cxx:595
void Info(const char *location, const char *msgfmt,...)
void Error(const char *location, const char *msgfmt,...)
void Warning(const char *location, const char *msgfmt,...)
char name[80]
Definition: TGX11.cxx:109
XID Cursor
Definition: TGX11.h:37
typedef void((*Func_t)())
virtual void LibraryUnloaded(const void *dyLibHandle, llvm::StringRef canonicalName)
virtual void * LockCompilationDuringUserCodeExecution()
bool tryAutoParseInternal(llvm::StringRef Name, clang::LookupResult &R, clang::Scope *S, const clang::FileEntry *FE=0)
bool tryFindROOTSpecialInternal(clang::LookupResult &R, clang::Scope *S)
virtual bool LookupObject(clang::LookupResult &R, clang::Scope *S)
bool fIsAutoParsingSuspended
bool tryResolveAtRuntimeInternal(clang::LookupResult &R, clang::Scope *S)
virtual bool LibraryLoadingFailed(const std::string &, const std::string &, bool, bool)
virtual void LibraryLoaded(const void *dyLibHandle, llvm::StringRef canonicalName)
virtual void DeclDeserialized(const clang::Decl *D)
virtual void ReturnedFromUserCode(void *stateInfo)
bool tryInjectImplicitAutoKeyword(clang::LookupResult &R, clang::Scope *S)
clang::NamespaceDecl * fROOTSpecialNamespace
virtual void InclusionDirective(clang::SourceLocation, const clang::Token &, llvm::StringRef FileName, bool, clang::CharSourceRange, const clang::FileEntry *, llvm::StringRef, llvm::StringRef, const clang::Module *)
virtual void UnlockCompilationDuringUserCodeExecution(void *StateInfo)
TClingCallbacks(cling::Interpreter *interp, bool hasCodeGen)
virtual void TransactionRollback(const cling::Transaction &T)
virtual void TransactionUnloaded(const cling::Transaction &T)
virtual void PrintStackTrace()
bool IsAutoloadingEnabled()
virtual bool FileNotFound(llvm::StringRef FileName, llvm::SmallVectorImpl< char > &RecoveryPath)
virtual void * EnteringUserCode()
virtual void TransactionCommitted(const cling::Transaction &T)
bool fIsAutoloadingRecursively
bool shouldResolveAtRuntime(clang::LookupResult &R, clang::Scope *S)
virtual void DefinitionShadowed(const clang::NamedDecl *D)
A previous definition has been shadowed; invalidate TCling' stored data about the old (global) decl.
Mother of all ROOT objects.
Definition: TObject.h:37
#define I(x, y, z)
static double P[]
static double C[]
double T(double x)
Definition: ChebyshevPol.h:34
RooArgSet S(const RooAbsArg &v1)
void Init(TClassEdit::TInterpreterLookupHelper *helper)
Definition: TClassEdit.cxx:155
void GetNormalizedName(std::string &norm_name, std::string_view name)
Return the normalized name.
Definition: TClassEdit.cxx:832
constexpr Double_t E()
Base of natural log:
Definition: TMath.h:97
Definition: file.py:1
const char * Name
Definition: TXMLSetup.cxx:66
RAII used to store Parser, Sema, Preprocessor state for recursive parsing.
Definition: ClingRAII.h:22
clang::Preprocessor::CleanupAndRestoreCacheRAII fCleanupRAII
Definition: ClingRAII.h:60
clang::Sema::ContextAndScopeRAII fPushedDCAndS
Definition: ClingRAII.h:73