Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TCling.cxx
Go to the documentation of this file.
1// @(#)root/meta:$Id$
2// vim: sw=3 ts=3 expandtab foldmethod=indent
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/** \class TCling
13
14This class defines an interface to the cling C++ interpreter.
15
16Cling is a full ANSI compliant C++-11 interpreter based on
17clang/LLVM technology.
18*/
19
20#include "TCling.h"
21
23
24#include "TClingBaseClassInfo.h"
25#include "TClingCallFunc.h"
26#include "TClingClassInfo.h"
28#include "TClingMethodArgInfo.h"
29#include "TClingMethodInfo.h"
31#include "TClingTypedefInfo.h"
32#include "TClingTypeInfo.h"
33#include "TClingValue.h"
34
35#include "TROOT.h"
36#include "TApplication.h"
37#include "TGlobal.h"
38#include "TDataType.h"
39#include "TClass.h"
40#include "TClassEdit.h"
41#include "TClassTable.h"
42#include "TClingCallbacks.h"
43#include "TClingDiagnostics.h"
44#include "TBaseClass.h"
45#include "TDataMember.h"
46#include "TMemberInspector.h"
47#include "TMethod.h"
48#include "TMethodArg.h"
49#include "TFunctionTemplate.h"
50#include "TObjArray.h"
51#include "TObjString.h"
52#include "TString.h"
53#include "THashList.h"
54#include "TVirtualPad.h"
55#include "TSystem.h"
56#include "TVirtualMutex.h"
57#include "TError.h"
58#include "TEnv.h"
59#include "TEnum.h"
60#include "TEnumConstant.h"
61#include "THashTable.h"
63#include "RConfigure.h"
64#include "compiledata.h"
65#include "strlcpy.h"
66#include "snprintf.h"
67#include "TClingUtils.h"
70#include "TListOfDataMembers.h"
71#include "TListOfEnums.h"
73#include "TListOfFunctions.h"
75#include "TMemFile.h"
76#include "TProtoClass.h"
77#include "TStreamerInfo.h" // This is here to avoid to use the plugin manager
78#include "ThreadLocalStorage.h"
79#include "TFile.h"
80#include "TKey.h"
81#include "ClingRAII.h"
82
83#include "clang/AST/ASTContext.h"
84#include "clang/AST/Decl.h"
85#include "clang/AST/DeclarationName.h"
86#include "clang/AST/GlobalDecl.h"
87#include "clang/AST/RecordLayout.h"
88#include "clang/AST/DeclVisitor.h"
89#include "clang/AST/RecursiveASTVisitor.h"
90#include "clang/AST/Type.h"
91#include "clang/Basic/SourceLocation.h"
92#include "clang/Basic/Specifiers.h"
93#include "clang/Basic/TargetInfo.h"
94#include "clang/CodeGen/ModuleBuilder.h"
95#include "clang/Frontend/CompilerInstance.h"
96#include "clang/Frontend/FrontendDiagnostic.h"
97#include "clang/Lex/HeaderSearch.h"
98#include "clang/Lex/Preprocessor.h"
99#include "clang/Lex/PreprocessorOptions.h"
100#include "clang/Parse/Parser.h"
101#include "clang/Sema/Lookup.h"
102#include "clang/Sema/Sema.h"
103#include "clang/Serialization/ASTReader.h"
104#include "clang/Serialization/GlobalModuleIndex.h"
105
106#include "cling/Interpreter/ClangInternalState.h"
107#include "cling/Interpreter/DynamicLibraryManager.h"
108#include "cling/Interpreter/Interpreter.h"
109#include "cling/Interpreter/LookupHelper.h"
110#include "cling/Interpreter/Value.h"
111#include "cling/Interpreter/Transaction.h"
112#include "cling/MetaProcessor/MetaProcessor.h"
113#include "cling/Utils/AST.h"
114#include "cling/Utils/ParserStateRAII.h"
115#include "cling/Utils/SourceNormalization.h"
116#include "cling/Interpreter/Exception.h"
117
118#include <CppInterOp/CppInterOp.h>
119
120#include "llvm/IR/GlobalValue.h"
121#include "llvm/IR/Module.h"
122
123#include "llvm/Support/DynamicLibrary.h"
124#include "llvm/Support/raw_ostream.h"
125#include "llvm/Support/Path.h"
126#include "llvm/Support/Process.h"
127#include "llvm/Object/ELFObjectFile.h"
128#include "llvm/Object/ObjectFile.h"
129#include "llvm/Object/SymbolicFile.h"
130#include "llvm/Support/FileSystem.h"
131
132#include <algorithm>
133#include <iostream>
134#include <cassert>
135#include <map>
136#include <set>
137#include <stdexcept>
138#include <cstdint>
139#include <fstream>
140#include <sstream>
141#include <string>
142#include <tuple>
143#include <typeinfo>
144#include <unordered_map>
145#include <unordered_set>
146#include <utility>
147#include <vector>
148#include <functional>
149#include <optional>
150
151#ifndef R__WIN32
152#include <cxxabi.h>
153#define R__DLLEXPORT __attribute__ ((visibility ("default")))
154#include <sys/stat.h>
155#endif
156#include <climits>
157#include <cstdio>
158
159#ifdef __APPLE__
160#include <dlfcn.h>
161#include <mach-o/dyld.h>
162#include <mach-o/loader.h>
163#endif // __APPLE__
164
165#ifdef R__UNIX
166#include <dlfcn.h>
167#endif
168
169#if defined(R__LINUX) || defined(R__FBSD)
170# ifndef _GNU_SOURCE
171# define _GNU_SOURCE
172# endif
173# include <link.h> // dl_iterate_phdr()
174#endif
175
176#if defined(__CYGWIN__)
177#include <sys/cygwin.h>
178#define HMODULE void *
179extern "C" {
181 __declspec(dllimport) bool __stdcall EnumProcessModules(void *, void **, unsigned long, unsigned long *);
182 __declspec(dllimport) unsigned long __stdcall GetModuleFileNameExW(void *, void *, wchar_t *, unsigned long);
183}
184#endif
185
186// Fragment copied from LLVM's raw_ostream.cpp
187#if defined(_MSC_VER)
188#ifndef STDIN_FILENO
189# define STDIN_FILENO 0
190#endif
191#ifndef STDOUT_FILENO
192# define STDOUT_FILENO 1
193#endif
194#ifndef STDERR_FILENO
195# define STDERR_FILENO 2
196#endif
197#ifndef R__WIN32
198//#if defined(HAVE_UNISTD_H)
199# include <unistd.h>
200//#endif
201#else
202#include "Windows4Root.h"
203#include <Psapi.h>
204#include <direct.h>
205#undef GetModuleFileName
206#define RTLD_DEFAULT ((void *)::GetModuleHandle(NULL))
207#define dlsym(library, function_name) ::GetProcAddress((HMODULE)library, function_name)
208#define dlopen(library_name, flags) ::LoadLibraryA(library_name)
209#define dlclose(library) ::FreeLibrary((HMODULE)library)
210#define R__DLLEXPORT __declspec(dllexport)
211#endif
212#endif
213
214//______________________________________________________________________________
215// These functions are helpers for debugging issues with non-LLVMDEV builds.
216//
217R__DLLEXPORT clang::DeclContext* TCling__DEBUG__getDeclContext(clang::Decl* D) {
218 return D->getDeclContext();
219}
220R__DLLEXPORT clang::NamespaceDecl* TCling__DEBUG__DCtoNamespace(clang::DeclContext* DC) {
221 return llvm::dyn_cast<clang::NamespaceDecl>(DC);
222}
223R__DLLEXPORT clang::RecordDecl* TCling__DEBUG__DCtoRecordDecl(clang::DeclContext* DC) {
224 return llvm::dyn_cast<clang::RecordDecl>(DC);
225}
226R__DLLEXPORT void TCling__DEBUG__dump(clang::DeclContext* DC) {
227 return DC->dumpDeclContext();
228}
229R__DLLEXPORT void TCling__DEBUG__dump(clang::Decl* D) {
230 return D->dump();
231}
232R__DLLEXPORT void TCling__DEBUG__dump(clang::FunctionDecl* FD) {
233 return FD->dump();
234}
236 return ((clang::Decl*)D)->dump();
237}
239 if (clang::NamedDecl* ND = llvm::dyn_cast<clang::NamedDecl>(D)) {
240 std::string name;
241 {
242 llvm::raw_string_ostream OS(name);
243 ND->getNameForDiagnostic(OS, D->getASTContext().getPrintingPolicy(),
244 true /*Qualified*/);
245 }
246 printf("%s\n", name.c_str());
247 }
248}
249//______________________________________________________________________________
250// These functions are helpers for testing issues directly rather than
251// relying on side effects.
252// This is used for the test for ROOT-7462/ROOT-6070
254 return D->isInvalidDecl();
255}
258 assert(info && info->IsValid());
259 return info->GetDecl()->isInvalidDecl();
260}
261
262using std::string, std::vector;
263using namespace clang;
264using namespace ROOT;
265
266namespace {
267 static const std::string gInterpreterClassDef = R"ICF(
268#undef ClassDef
269#define ClassDef(name, id) \
270_ClassDefInterp_(name,id,virtual,) \
271static int DeclFileLine() { return __LINE__; }
272#undef ClassDefNV
273#define ClassDefNV(name, id) \
274_ClassDefInterp_(name,id,,) \
275static int DeclFileLine() { return __LINE__; }
276#undef ClassDefOverride
277#define ClassDefOverride(name, id) \
278_ClassDefInterp_(name,id,,override) \
279static int DeclFileLine() { return __LINE__; }
280)ICF";
281
282 static const std::string gNonInterpreterClassDef = R"ICF(
283#define __ROOTCLING__ 1
284#undef ClassDef
285#define ClassDef(name,id) \
286_ClassDefOutline_(name,id,virtual,) \
287static int DeclFileLine() { return __LINE__; }
288#undef ClassDefNV
289#define ClassDefNV(name, id)\
290_ClassDefOutline_(name,id,,)\
291static int DeclFileLine() { return __LINE__; }
292#undef ClassDefOverride
293#define ClassDefOverride(name, id)\
294_ClassDefOutline_(name,id,,override)\
295static int DeclFileLine() { return __LINE__; }
296)ICF";
297
298// The macros below use ::Error, so let's ensure it is included
299 static const std::string gClassDefInterpMacro = R"ICF(
300#include "TError.h"
301
302#define _ClassDefInterp_(name,id,virtual_keyword, overrd) \
303private: \
304public: \
305 static TClass *Class() { static TClass* sIsA = 0; if (!sIsA) sIsA = TClass::GetClass(#name); return sIsA; } \
306 static const char *Class_Name() { return #name; } \
307 virtual_keyword Bool_t CheckTObjectHashConsistency() const overrd { \
308 static std::atomic<UChar_t> recurseBlocker(0); \
309 if (R__likely(recurseBlocker >= 2)) { \
310 return ::ROOT::Internal::THashConsistencyHolder<decltype(*this)>::fgHashConsistency; \
311 } else if (recurseBlocker == 1) { \
312 return false; \
313 } else if (recurseBlocker++ == 0) { \
314 ::ROOT::Internal::THashConsistencyHolder<decltype(*this)>::fgHashConsistency = \
315 ::ROOT::Internal::HasConsistentHashMember(_QUOTE_(name)) || \
316 ::ROOT::Internal::HasConsistentHashMember(*IsA()); \
317 ++recurseBlocker; \
318 return ::ROOT::Internal::THashConsistencyHolder<decltype(*this)>::fgHashConsistency; \
319 } \
320 return false; /* unreachable */ \
321 } \
322 static Version_t Class_Version() { return id; } \
323 static TClass *Dictionary() { return 0; } \
324 virtual_keyword TClass *IsA() const overrd { return name::Class(); } \
325 virtual_keyword void ShowMembers(TMemberInspector&insp) const overrd { ::ROOT::Class_ShowMembers(name::Class(), this, insp); } \
326 virtual_keyword void Streamer(TBuffer&) overrd { ::Error("Streamer", "Cannot stream interpreted class."); } \
327 void StreamerNVirtual(TBuffer&ClassDef_StreamerNVirtual_b) { name::Streamer(ClassDef_StreamerNVirtual_b); } \
328 static const char *DeclFileName() { return __FILE__; } \
329 static int ImplFileLine() { return 0; } \
330 static const char *ImplFileName() { return __FILE__; }
331)ICF";
332}
334
335// The functions are used to bridge cling/clang/llvm compiled with no-rtti and
336// ROOT (which uses rtti)
337
338////////////////////////////////////////////////////////////////////////////////
339/// Print a StackTrace!
340
341extern "C"
345
346////////////////////////////////////////////////////////////////////////////////
347/// Load a library.
348
349extern "C" int TCling__LoadLibrary(const char *library)
350{
351 return gSystem->Load(library, "", false);
352}
353
354////////////////////////////////////////////////////////////////////////////////
355/// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
356
357extern "C" void TCling__RestoreInterpreterMutex(void *delta)
358{
359 ((TCling*)gCling)->ApplyToInterpreterMutex(delta);
360}
361
362////////////////////////////////////////////////////////////////////////////////
363/// Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name,
364/// which is extracted by error messages we get from callback from cling. Return true
365/// when the missing library was autoloaded.
366
367extern "C" bool TCling__LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
368{
369 return ((TCling*)gCling)->LibraryLoadingFailed(errmessage, libStem, permanent, resolved);
370}
371
372////////////////////////////////////////////////////////////////////////////////
373/// Reset the interpreter lock to the state it had before interpreter-related
374/// calls happened.
375
377{
378 return ((TCling*)gCling)->RewindInterpreterMutex();
379}
380
381////////////////////////////////////////////////////////////////////////////////
382/// Lock the interpreter.
383
385{
386 if (gInterpreterMutex) {
388 }
389 return nullptr;
390}
391
392////////////////////////////////////////////////////////////////////////////////
393/// Unlock the interpreter.
394
396{
397 if (gInterpreterMutex) {
399 }
400}
401
402////////////////////////////////////////////////////////////////////////////////
403/// Update TClingClassInfo for a class (e.g. upon seeing a definition).
404
406{
407 static Bool_t entered = kFALSE;
410
411 if (entered) topLevel = kFALSE;
412 else {
413 entered = kTRUE;
414 topLevel = kTRUE;
415 }
416 if (topLevel) {
417 ((TCling*)gInterpreter)->UpdateClassInfoWithDecl(TD);
418 } else {
419 // If we are called indirectly from within another call to
420 // TCling::UpdateClassInfo, we delay the update until the dictionary loading
421 // is finished (i.e. when we return to the top level TCling::UpdateClassInfo).
422 // This allows for the dictionary to be fully populated when we actually
423 // update the TClass object. The updating of the TClass sometimes
424 // (STL containers and when there is an emulated class) forces the building
425 // of the TClass object's real data (which needs the dictionary info).
426 updateList.push_back(TD);
427 }
428 if (topLevel) {
429 while (!updateList.empty()) {
430 ((TCling*)gInterpreter)->UpdateClassInfoWithDecl(updateList.back());
431 updateList.pop_back();
432 }
433 entered = kFALSE;
434 }
435}
436
438 const clang::Decl* D = static_cast<const clang::Decl*>(enumObj->GetDeclId());
439 if(const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(D)) {
440 // Add the constants to the enum type.
441 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(),
442 EDE = ED->enumerator_end(); EDI != EDE; ++EDI) {
443 // Get name of the enum type.
444 std::string constbuf;
445 if (const NamedDecl* END = llvm::dyn_cast<NamedDecl>(*EDI)) {
446 PrintingPolicy Policy((*EDI)->getASTContext().getPrintingPolicy());
447 llvm::raw_string_ostream stream(constbuf);
448 // Don't trigger fopen of the source file to count lines:
449 Policy.AnonymousTagLocations = false;
450 (END)->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
451 }
452 const char* constantName = constbuf.c_str();
453
454 // Get value of the constant.
456 const llvm::APSInt valAPSInt = (*EDI)->getInitVal();
457 if (valAPSInt.isSigned()) {
458 value = valAPSInt.getSExtValue();
459 } else {
460 value = valAPSInt.getZExtValue();
461 }
462
463 // Create the TEnumConstant or update it if existing
464 TEnumConstant* enumConstant = nullptr;
465 TClingClassInfo* tcCInfo = (TClingClassInfo*)(cl ? cl->GetClassInfo() : nullptr);
468 if (TObject* encAsTObj = enumObj->GetConstants()->FindObject(constantName)){
469 ((TEnumConstant*)encAsTObj)->Update(dmInfo);
470 } else {
472 }
473
474 // Add the global constants to the list of Globals.
475 if (!cl) {
476 TCollection* globals = gROOT->GetListOfGlobals(false);
477 if (!globals->FindObject(constantName)) {
478 globals->Add(enumConstant);
479 }
480 }
481 }
482 }
483}
484
486{
487 // Handle new enum declaration for either global and nested enums.
488
489 // Create the enum type.
490 TEnum* enumType = nullptr;
491 const clang::Decl* D = static_cast<const clang::Decl*>(VD);
492 std::string buf;
493 if (const EnumDecl* ED = llvm::dyn_cast<EnumDecl>(D)) {
494 // Get name of the enum type.
495 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
496 llvm::raw_string_ostream stream(buf);
497 // Don't trigger fopen of the source file to count lines:
498 Policy.AnonymousTagLocations = false;
499 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
500 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
501 }
502 if (buf.empty()) {
503 return nullptr;
504 }
505 const char* name = buf.c_str();
506 enumType = new TEnum(name, VD, cl);
508
509 return enumType;
510}
511
512void TCling::HandleNewDecl(const void* DV, bool isDeserialized, std::set<TClass*> &modifiedTClasses) {
513 // Handle new declaration.
514 // Record the modified class, struct and namespaces in 'modifiedTClasses'.
515
516 const clang::Decl* D = static_cast<const clang::Decl*>(DV);
517
518 if (!D->isCanonicalDecl() && !isa<clang::NamespaceDecl>(D)
519 && !dyn_cast<clang::RecordDecl>(D)) return;
520
521 if (isa<clang::FunctionDecl>(D->getDeclContext())
522 || isa<clang::TagDecl>(D->getDeclContext()))
523 return;
524
525 // Don't list templates.
526 if (const clang::CXXRecordDecl* RD = dyn_cast<clang::CXXRecordDecl>(D)) {
527 if (RD->getDescribedClassTemplate())
528 return;
529 } else if (const clang::FunctionDecl* FD = dyn_cast<clang::FunctionDecl>(D)) {
530 if (FD->getDescribedFunctionTemplate())
531 return;
532 }
533
534 if (const RecordDecl *TD = dyn_cast<RecordDecl>(D)) {
535 if (TD->isCanonicalDecl() || TD->isThisDeclarationADefinition())
537 }
538 else if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
539
540 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
541 // Mostly just for EnumDecl (the other TagDecl are handled
542 // by the 'RecordDecl' if statement.
544 } else if (const NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(D)) {
546 }
547
548 // We care about declarations on the global scope.
549 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
550 return;
551
552 // Enums are lazyly created, thus we don not need to handle them here.
553 if (isa<EnumDecl>(ND))
554 return;
555
556 // ROOT says that global is enum(lazylycreated)/var/field declared on the global
557 // scope.
558 if (!(isa<VarDecl>(ND)))
559 return;
560
561 // Skip if already in the list.
562 if (gROOT->GetListOfGlobals()->FindObject(ND->getNameAsString().c_str()))
563 return;
564
565 // Put the global constants and global enums in the corresponding lists.
566 gROOT->GetListOfGlobals()->Add(new TGlobal((DataMemberInfo_t *)
568 cast<ValueDecl>(ND), nullptr)));
569 }
570}
571
572extern "C"
574{
575 // We are sure in this context of the type of the interpreter
576 normCtxt = &( (TCling*) gInterpreter)->GetNormalizedContext();
577}
578
579extern "C"
580void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter*) {
581 ((TCling*)gCling)->UpdateListsOnCommitted(T);
582}
583
584extern "C"
585void TCling__UpdateListsOnUnloaded(const cling::Transaction &T) {
586 ((TCling*)gCling)->UpdateListsOnUnloaded(T);
587}
588
589extern "C"
590void TCling__InvalidateGlobal(const clang::Decl *D) {
591 ((TCling*)gCling)->InvalidateGlobal(D);
592}
593
594extern "C"
595void TCling__TransactionRollback(const cling::Transaction &T) {
596 ((TCling*)gCling)->TransactionRollback(T);
597}
598
599extern "C" void TCling__LibraryLoadedRTTI(const void* dyLibHandle,
600 const char* canonicalName) {
601 ((TCling*)gCling)->LibraryLoaded(dyLibHandle, canonicalName);
602}
603
604extern "C" void TCling__RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
605{
606 ((TCling *)gCling)->RegisterRdictForLoadPCM(pcmFileNameFullPath, pcmContent);
607}
608
609extern "C" void TCling__LibraryUnloadedRTTI(const void* dyLibHandle,
610 const char* canonicalName) {
611 ((TCling*)gCling)->LibraryUnloaded(dyLibHandle, canonicalName);
612}
613
614
615extern "C"
616TObject* TCling__GetObjectAddress(const char *Name, void *&LookupCtx) {
617 return ((TCling*)gCling)->GetObjectAddress(Name, LookupCtx);
618}
619
620extern "C" const Decl* TCling__GetObjectDecl(TObject *obj) {
621 return ((TClingClassInfo*)obj->IsA()->GetClassInfo())->GetDecl();
622}
623
625 const char* argv[])
626{
627 auto tcling = new TCling("C++", "cling C++ Interpreter", argv, interpLibHandle);
628
629 return tcling;
630}
631
633{
634 delete interp;
635}
636
637// Load library containing specified class. Returns 0 in case of error
638// and 1 in case if success.
639extern "C" int TCling__AutoLoadCallback(const char* className)
640{
641 return ((TCling*)gCling)->AutoLoad(className);
642}
643
644extern "C" int TCling__AutoParseCallback(const char* className)
645{
646 return ((TCling*)gCling)->AutoParse(className);
647}
648
649extern "C" const char* TCling__GetClassSharedLibs(const char* className, bool skipCore)
650{
651 return ((TCling*)gCling)->GetClassSharedLibs(className, skipCore);
652}
653
654// Returns 0 for failure 1 for success
655extern "C" int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl* nsDecl)
656{
657 return ((TCling*)gCling)->IsAutoLoadNamespaceCandidate(nsDecl);
658}
659
660extern "C" int TCling__CompileMacro(const char *fileName, const char *options)
661{
662 string file(fileName);
663 string opt(options);
664 return gSystem->CompileMacro(file.c_str(), opt.c_str());
665}
666
667extern "C" void TCling__SplitAclicMode(const char* fileName, string &mode,
668 string &args, string &io, string &fname)
669{
670 string file(fileName);
671 TString f, amode, arguments, aclicio;
672 f = gSystem->SplitAclicMode(file.c_str(), amode, arguments, aclicio);
673 mode = amode.Data(); args = arguments.Data();
674 io = aclicio.Data(); fname = f.Data();
675}
676
677//______________________________________________________________________________
678//
679//
680//
681
682#ifdef R__WIN32
683extern "C" {
684 char *__unDName(char *demangled, const char *mangled, int out_len,
685 void * (* pAlloc )(size_t), void (* pFree )(void *),
686 unsigned short int flags);
687}
688#endif
689
690////////////////////////////////////////////////////////////////////////////////
691/// Find a template decl within N nested namespaces, 0<=N<inf
692/// Assumes 1 and only 1 template present and 1 and only 1 entity contained
693/// by the namespace. Example: `ns1::ns2::..::%nsN::%myTemplate`
694/// Returns nullptr in case of error
695
696static clang::ClassTemplateDecl* FindTemplateInNamespace(clang::Decl* decl)
697{
698 using namespace clang;
699 if (NamespaceDecl* nsd = llvm::dyn_cast<NamespaceDecl>(decl)){
700 return FindTemplateInNamespace(*nsd->decls_begin());
701 }
702
703 if (ClassTemplateDecl* ctd = llvm::dyn_cast<ClassTemplateDecl>(decl)){
704 return ctd;
705 }
706
707 return nullptr; // something went wrong.
708}
709
710//______________________________________________________________________________
711//
712//
713//
714
715int TCling_GenerateDictionary(const std::vector<std::string> &classes,
716 const std::vector<std::string> &headers,
717 const std::vector<std::string> &fwdDecls,
718 const std::vector<std::string> &unknown)
719{
720 //This function automatically creates the "LinkDef.h" file for templated
721 //classes then executes CompileMacro on it.
722 //The name of the file depends on the class name, and it's not generated again
723 //if the file exist.
724 if (classes.empty()) {
725 return 0;
726 }
727 // Use the name of the first class as the main name.
728 const std::string& className = classes[0];
729 //(0) prepare file name
730 TString fileName = "AutoDict_";
731 std::string::const_iterator sIt;
732 for (sIt = className.begin(); sIt != className.end(); ++sIt) {
733 if (*sIt == '<' || *sIt == '>' ||
734 *sIt == ' ' || *sIt == '*' ||
735 *sIt == ',' || *sIt == '&' ||
736 *sIt == ':') {
737 fileName += '_';
738 }
739 else {
740 fileName += *sIt;
741 }
742 }
743 if (classes.size() > 1) {
744 Int_t chk = 0;
745 std::vector<std::string>::const_iterator it = classes.begin();
746 while ((++it) != classes.end()) {
747 for (UInt_t cursor = 0; cursor != it->length(); ++cursor) {
748 chk = chk * 3 + it->at(cursor);
749 }
750 }
751 fileName += TString::Format("_%u", chk);
752 }
753 fileName += ".cxx";
754 if (gSystem->AccessPathName(fileName) != 0) {
755 //file does not exist
756 //(1) prepare file data
757 // If STL, also request iterators' operators.
758 // vector is special: we need to check whether
759 // vector::iterator is a typedef to pointer or a
760 // class.
761 static const std::set<std::string> sSTLTypes {
762 "vector","list","forward_list","deque","map","unordered_map","multimap",
763 "unordered_multimap","set","unordered_set","multiset","unordered_multiset",
764 "queue","priority_queue","stack","iterator"};
765 std::vector<std::string>::const_iterator it;
766 std::string fileContent("");
767 for (it = headers.begin(); it != headers.end(); ++it) {
768 fileContent += "#include \"" + *it + "\"\n";
769 }
770 for (it = unknown.begin(); it != unknown.end(); ++it) {
771 TClass* cl = TClass::GetClass(it->c_str());
772 if (cl && cl->GetDeclFileName()) {
773 TString header = gSystem->BaseName(cl->GetDeclFileName());
776 while (dirbase.Length() && dirbase != "."
777 && dirbase != "include" && dirbase != "inc"
778 && dirbase != "prec_stl") {
780 dir = gSystem->GetDirName(dir);
781 }
782 fileContent += TString("#include \"") + header + "\"\n";
783 }
784 }
785 for (it = fwdDecls.begin(); it != fwdDecls.end(); ++it) {
786 fileContent += "class " + *it + ";\n";
787 }
788 fileContent += "#ifdef __CLING__ \n";
789 fileContent += "#pragma link C++ nestedclasses;\n";
790 fileContent += "#pragma link C++ nestedtypedefs;\n";
791 for (it = classes.begin(); it != classes.end(); ++it) {
792 std::string n(*it);
793 size_t posTemplate = n.find('<');
794 std::set<std::string>::const_iterator iSTLType = sSTLTypes.end();
795 if (posTemplate != std::string::npos) {
796 n.erase(posTemplate, std::string::npos);
797 if (n.compare(0, 5, "std::") == 0) {
798 n.erase(0, 5);
799 }
800 iSTLType = sSTLTypes.find(n);
801 }
802 fileContent += "#pragma link C++ class ";
803 fileContent += *it + "+;\n" ;
804 if (iSTLType == sSTLTypes.end()) {
805 // Not an STL class; we need to allow the I/O of contained
806 // classes (now that we have a dictionary for them).
807 fileContent += "#pragma link C++ class " + *it + "::*+;\n" ;
808 }
809 }
810 fileContent += "#endif\n";
811 //end(1)
812 //(2) prepare the file
814 filePointer = fopen(fileName, "w");
815 if (filePointer == nullptr) {
816 //can't open a file
817 return 1;
818 }
819 //end(2)
820 //write data into the file
821 fprintf(filePointer, "%s", fileContent.c_str());
823 }
824 //(3) checking if we can compile a macro, if not then cleaning
826 gErrorIgnoreLevel = kWarning; // no "Info: creating library..."
827 Int_t ret = gSystem->CompileMacro(fileName, "k");
829 if (ret == 0) { //can't compile a macro
830 return 2;
831 }
832 //end(3)
833 return 0;
834}
835
836int TCling_GenerateDictionary(const std::string& className,
837 const std::vector<std::string> &headers,
838 const std::vector<std::string> &fwdDecls,
839 const std::vector<std::string> &unknown)
840{
841 //This function automatically creates the "LinkDef.h" file for templated
842 //classes then executes CompileMacro on it.
843 //The name of the file depends on the class name, and it's not generated again
844 //if the file exist.
845 std::vector<std::string> classes;
846 classes.push_back(className);
848}
849
850//______________________________________________________________________________
851//
852//
853//
854
855// It is a "fantom" method to synchronize user keyboard input
856// and ROOT prompt line (for WIN32)
857const char* fantomline = "TRint::EndOfLineAction();";
858
859//______________________________________________________________________________
860//
861//
862//
863
864void* TCling::fgSetOfSpecials = nullptr;
865
866//______________________________________________________________________________
867//
868// llvm error handler through exceptions; see also cling/UserInterface
869//
870namespace {
871 // Handle fatal llvm errors by throwing an exception.
872 // Yes, throwing exceptions in error handlers is bad.
873 // Doing nothing is pretty terrible, too.
874 void exceptionErrorHandler(void * /*user_data*/,
875 const char *reason,
876 bool /*gen_crash_diag*/) {
877 throw std::runtime_error(std::string(">>> Interpreter compilation error:\n") + reason);
878 }
879}
880
881//______________________________________________________________________________
882//
883//
884//
885
886////////////////////////////////////////////////////////////////////////////////
887
888namespace{
889 // An instance of this class causes the diagnostics of clang to be suppressed
890 // during its lifetime
891 class clangDiagSuppr {
892 public:
893 clangDiagSuppr(clang::DiagnosticsEngine& diag): fDiagEngine(diag){
894 fOldDiagValue = fDiagEngine.getIgnoreAllWarnings();
895 fDiagEngine.setIgnoreAllWarnings(true);
896 }
897
899 fDiagEngine.setIgnoreAllWarnings(fOldDiagValue);
900 }
901 private:
902 clang::DiagnosticsEngine& fDiagEngine;
903 bool fOldDiagValue;
904 };
905
906}
907
908////////////////////////////////////////////////////////////////////////////////
909/// Allow calling autoparsing from TMetaUtils
911{
912 return gCling->AutoParse(cname);
913}
914
915////////////////////////////////////////////////////////////////////////////////
916/// Try hard to avoid looking up in the Cling database as this could enduce
917/// an unwanted autoparsing.
918
920 std::string &result)
921{
922 result.clear();
923
924 unsigned long offset = 0;
925 if (strncmp(tname.c_str(), "const ", 6) == 0) {
926 offset = 6;
927 }
928 unsigned long end = tname.length();
929 while( end && (tname[end-1]=='&' || tname[end-1]=='*' || tname[end-1]==']') ) {
930 if ( tname[end-1]==']' ) {
931 --end;
932 while ( end && tname[end-1]!='[' ) --end;
933 }
934 --end;
935 }
936 std::string innerbuf;
937 const char *inner;
938 if (end != tname.length()) {
939 innerbuf = tname.substr(offset,end-offset);
940 inner = innerbuf.c_str();
941 } else {
942 inner = tname.c_str()+offset;
943 }
944
945 //if (strchr(tname.c_str(),'[')!=0) fprintf(stderr,"DEBUG: checking on %s vs %s %lu %lu\n",tname.c_str(),inner,offset,end);
946 if (gROOT->GetListOfClasses()->FindObject(inner)
948 // This is a known class.
949 return true;
950 }
951
952 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
953 TDataType *type = (TDataType *)typeTable->THashTable::FindObject( inner );
954 if (type) {
955 // This is a raw type and an already loaded typedef.
956 const char *newname = type->GetFullTypeName();
957 if (type->GetType() == kLong64_t) {
958 newname = "Long64_t";
959 } else if (type->GetType() == kULong64_t) {
960 newname = "ULong64_t";
961 }
962 if (strcmp(inner,newname) == 0) {
963 return true;
964 }
965 if (offset) result = "const ";
966 result += newname;
967 if ( end != tname.length() ) {
968 result += tname.substr(end,tname.length()-end);
969 }
970 if (result == tname) result.clear();
971 return true;
972 }
973
974 // Check if the name is an enumerator
976 if (lastPos != inner) // Main switch: case 1 - scoped enum, case 2 global enum
977 {
978 // We have a scope
979 const auto enName = lastPos;
980 const auto scopeNameSize = (lastPos - inner) / sizeof(decltype(*lastPos)) - 2;
981 std::string scopeName{inner, scopeNameSize};
982 // Check if the scope is in the list of classes
983 if (auto scope = static_cast<TClass *>(gROOT->GetListOfClasses()->FindObject(scopeName.c_str()))) {
984 auto enumTable = dynamic_cast<const THashList *>(scope->GetListOfEnums(false));
985 if (enumTable && enumTable->THashList::FindObject(enName))
986 return true;
987 }
988 // It may still be in one of the loaded protoclasses
989 else if (auto scope = static_cast<TProtoClass *>(gClassTable->GetProtoNorm(scopeName.c_str()))) {
990 auto listOfEnums = scope->GetListOfEnums();
991 if (listOfEnums) { // it could be null: no enumerators in the protoclass
992 auto enumTable = dynamic_cast<const THashList *>(listOfEnums);
993 if (enumTable && enumTable->THashList::FindObject(enName))
994 return true;
995 }
996 }
997 } else
998 {
999 // We don't have any scope: this could only be a global enum
1000 auto enumTable = dynamic_cast<const THashList *>(gROOT->GetListOfEnums());
1001 if (enumTable && enumTable->THashList::FindObject(inner)) return true;
1002 }
1003
1005 {
1006 // This is a class name.
1007 return true;
1008 }
1009
1010 return false;
1011}
1012
1013////////////////////////////////////////////////////////////////////////////////
1014/// Check if the class name is present in TClassTable.
1015///
1016/// \param[in] tname class name to check.
1017/// \param[out] result If a class name has an alternative name registered in
1018/// TClassTable, it will be copied into this string.
1019bool TClingLookupHelper__CheckInClassTable(const std::string &tname, std::string &result)
1020{
1021 result.clear();
1022
1023 if (gROOT->GetListOfClasses()->FindObject(tname.c_str()) || TClassTable::Check(tname.c_str(), result)) {
1024 // This is a known class.
1025 return true;
1026 }
1027
1028 return false;
1029}
1030
1031////////////////////////////////////////////////////////////////////////////////
1032
1037
1038////////////////////////////////////////////////////////////////////////////////
1039
1041{
1042 return fContent.c_str();
1043}
1044
1045////////////////////////////////////////////////////////////////////////////////
1046/// Append string to the storage if not added already.
1047
1048inline bool TCling::TUniqueString::Append(const std::string& str)
1049{
1050 bool notPresent = fLinesHashSet.emplace(fHashFunc(str)).second;
1051 if (notPresent){
1052 fContent+=str;
1053 }
1054 return notPresent;
1055}
1056
1057std::string TCling::ToString(const char* type, void* obj)
1058{
1059 return fInterpreter->toString(type, obj);
1060}
1061
1062////////////////////////////////////////////////////////////////////////////////
1063///\returns true if the module was loaded.
1064static bool LoadModule(const std::string &ModuleName, cling::Interpreter &interp)
1065{
1066 // When starting up ROOT, cling would load all modulemap files on the include
1067 // paths. However, in a ROOT session, it is very common to run aclic which
1068 // will invoke rootcling and possibly produce a modulemap and a module in
1069 // the current folder.
1070 //
1071 // Before failing, try loading the modulemap in the current folder and try
1072 // loading the requested module from it.
1073 std::string currentDir = gSystem->WorkingDirectory();
1074 assert(!currentDir.empty());
1076 if (gDebug > 2)
1077 ::Info("TCling::__LoadModule", "Preloading module %s. \n",
1078 ModuleName.c_str());
1079
1080 return interp.loadModule(ModuleName, /*Complain=*/true);
1081}
1082
1083////////////////////////////////////////////////////////////////////////////////
1084/// Loads the C++ modules that we require to run any ROOT program. This is just
1085/// supposed to make a C++ module from a modulemap available to the interpreter.
1086static void LoadModules(const std::vector<std::string> &modules, cling::Interpreter &interp)
1087{
1088 for (const auto &modName : modules)
1090}
1091
1092static bool IsFromRootCling() {
1093 // rootcling also uses TCling for generating the dictionary ROOT files.
1094 const static bool foundSymbol = dlsym(RTLD_DEFAULT, "usedToIdentifyRootClingByDlSym");
1095 return foundSymbol;
1096}
1097
1098/// Checks if there is an ASTFile on disk for the given module \c M.
1099static bool HasASTFileOnDisk(clang::Module *M, const clang::Preprocessor &PP, std::string *FullFileName = nullptr)
1100{
1101 const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1102
1103 std::string ModuleFileName;
1104 if (!HSOpts.PrebuiltModulePaths.empty())
1105 // Load the module from *only* in the prebuilt module path.
1106 ModuleFileName = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(M->Name);
1107 if (FullFileName)
1109
1110 return !ModuleFileName.empty();
1111}
1112
1113static bool HaveFullGlobalModuleIndex = false;
1115{
1116 CompilerInstance &CI = *interp.getCI();
1117 Preprocessor &PP = CI.getPreprocessor();
1118 auto ModuleManager = CI.getASTReader();
1120 // StringRef ModuleIndexPath = HSI.getModuleCachePath();
1121 // HeaderSearch& HSI = PP.getHeaderSearchInfo();
1122 // HSI.setModuleCachePath(TROOT::GetSharedLibDir().Data());
1123 std::string ModuleIndexPath = TROOT::GetSharedLibDir().Data();
1124 if (ModuleIndexPath.empty())
1125 return nullptr;
1126 // Get an existing global index. This loads it if not already loaded.
1127 ModuleManager->resetForReload();
1128 ModuleManager->loadGlobalIndex();
1129 GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1130
1131 // For finding modules needing to be imported for fixit messages,
1132 // we need to make the global index cover all modules, so we do that here.
1134 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1135 bool RecreateIndex = false;
1136 for (ModuleMap::module_iterator I = MMap.module_begin(), E = MMap.module_end(); I != E; ++I) {
1137 Module *TheModule = I->second;
1138 // We want the index only of the prebuilt modules.
1140 continue;
1141 LoadModule(TheModule->Name, interp);
1142 RecreateIndex = true;
1143 }
1144 if (RecreateIndex) {
1145 cling::Interpreter::PushTransactionRAII deserRAII(&interp);
1146 clang::GlobalModuleIndex::UserDefinedInterestingIDs IDs;
1147
1148 struct DefinitionFinder : public RecursiveASTVisitor<DefinitionFinder> {
1149 DefinitionFinder(clang::GlobalModuleIndex::UserDefinedInterestingIDs& IDs,
1150 clang::TranslationUnitDecl* TU) : DefinitionIDs(IDs) {
1152 }
1153 bool VisitNamedDecl(NamedDecl *ND) {
1154 if (!ND->isFromASTFile())
1155 return true;
1156 if (!ND->getIdentifier())
1157 return true;
1158
1159 if (ND->getAccess() == AS_protected || ND->getAccess() == AS_private)
1160 return true;
1161
1162 if (TagDecl *TD = llvm::dyn_cast<TagDecl>(ND)) {
1163 if (TD->isCompleteDefinition())
1164 Register(TD);
1165 } else if (NamespaceDecl *NSD = llvm::dyn_cast<NamespaceDecl>(ND)) {
1166 Register(NSD, /*AddSingleEntry=*/ false);
1167 }
1169 Register(TND);
1170 // FIXME: Add the rest...
1171 return true; // continue decending
1172 }
1173 private:
1174 clang::GlobalModuleIndex::UserDefinedInterestingIDs &DefinitionIDs;
1175 void Register(const NamedDecl* ND, bool AddSingleEntry = true) {
1176 assert(ND->isFromASTFile());
1177 // FIXME: All decls should have an owning module once rootcling
1178 // updates its generated decls from within the LookupHelper & co.
1179 if (!ND->hasOwningModule()) {
1180#ifndef NDEBUG
1181 SourceManager &SM = ND->getASTContext().getSourceManager();
1182 SourceLocation Loc = ND->getLocation();
1183 OptionalFileEntryRef FE = SM.getFileEntryRefForID(SM.getFileID(Loc));
1184 (void)FE;
1185 assert(FE->getName().contains("input_line_"));
1186#endif
1187 return;
1188 }
1189
1190 Module *OwningModule = ND->getOwningModule()->getTopLevelModule();
1192 assert(!ND->getName().empty() && "Empty name");
1193 if (AddSingleEntry && DefinitionIDs.count(ND->getName()))
1194 return;
1195 // FIXME: The FileEntry in not stable to serialize.
1196 // FIXME: We might end up with many times with the same module.
1197 // FIXME: We might end up two modules containing a definition.
1198 // FIXME: What do we do if no definition is found.
1199 DefinitionIDs[ND->getName()].push_back(OwningModule->getASTFile());
1200 }
1201 };
1202 DefinitionFinder defFinder(IDs, CI.getASTContext().getTranslationUnitDecl());
1203
1204 llvm::cantFail(GlobalModuleIndex::writeIndex(CI.getFileManager(),
1205 CI.getPCHContainerReader(),
1207 &IDs));
1208 ModuleManager->resetForReload();
1209 ModuleManager->loadGlobalIndex();
1210 GlobalIndex = ModuleManager->getGlobalIndex();
1211 }
1213 }
1214 return GlobalIndex;
1215}
1216
1217static void RegisterCxxModules(cling::Interpreter &clingInterp)
1218{
1219 if (!clingInterp.getCI()->getLangOpts().Modules)
1220 return;
1221
1222 // Loading of a module might deserialize.
1223 cling::Interpreter::PushTransactionRAII deserRAII(&clingInterp);
1224
1225 // Setup core C++ modules if we have any to setup.
1226
1227 // Load libc and stl first.
1228 // Load vcruntime module for windows
1229#ifdef R__WIN32
1230 LoadModule("vcruntime", clingInterp);
1231 LoadModule("services", clingInterp);
1232#endif
1233
1234#ifdef R__MACOSX
1235 LoadModule("Darwin", clingInterp);
1236#else
1237 LoadModule("libc", clingInterp);
1238#endif
1239 LoadModule("std", clingInterp);
1240
1241 LoadModule("_Builtin_intrinsics", clingInterp);
1242
1243 // Load core modules
1244 // This should be vector in order to be able to pass it to LoadModules
1245 std::vector<std::string> CoreModules = {"ROOT_Foundation_C",
1246 "ROOT_Config",
1247 "ROOT_Rtypes",
1248 "ROOT_Foundation_Stage1_NoRTTI",
1249 "Core",
1250 "Rint",
1251 "RIO"};
1252
1254
1255 // Take this branch only from ROOT because we don't need to preload modules in rootcling
1256 if (!IsFromRootCling()) {
1257 std::vector<std::string> CommonModules = {"MathCore"};
1259
1260 // These modules should not be preloaded but they fix issues.
1261 // FIXME: Hist is not a core module but is very entangled to MathCore and
1262 // causes issues.
1263 std::vector<std::string> FIXMEModules = {"Hist"};
1264 clang::CompilerInstance &CI = *clingInterp.getCI();
1265 clang::Preprocessor &PP = CI.getPreprocessor();
1266 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1267 if (MMap.findModule("RInterface"))
1268 FIXMEModules.push_back("RInterface");
1269
1271
1272 GlobalModuleIndex *GlobalIndex = nullptr;
1274 // FIXME: The ASTReader still calls loadGlobalIndex and loads the file
1275 // We should investigate how to suppress it completely.
1276 GlobalIndex = CI.getASTReader()->getGlobalIndex();
1277
1278 llvm::StringSet<> KnownModuleFileNames;
1279 if (GlobalIndex)
1280 GlobalIndex->getKnownModuleFileNames(KnownModuleFileNames);
1281
1282 std::vector<std::string> PendingModules;
1283 PendingModules.reserve(256);
1284 for (auto I = MMap.module_begin(), E = MMap.module_end(); I != E; ++I) {
1285 clang::Module *M = I->second;
1286 assert(M);
1287
1288 // We want to load only already created modules.
1289 std::string FullASTFilePath;
1291 continue;
1292
1294 continue;
1295
1296 if (M->IsUnimportable)
1297 continue;
1298
1299 if (GlobalIndex)
1300 LoadModule(M->Name, clingInterp);
1301 else {
1302 // FIXME: We may be able to remove those checks as cling::loadModule
1303 // checks if a module was alredy loaded.
1304 if (std::find(CoreModules.begin(), CoreModules.end(), M->Name) != CoreModules.end())
1305 continue; // This is a core module which was already loaded.
1306
1307 // Load system modules now and delay the other modules after we have
1308 // loaded all system ones.
1309 if (M->IsSystem)
1310 LoadModule(M->Name, clingInterp);
1311 else
1312 PendingModules.push_back(M->Name);
1313 }
1314 }
1316 }
1317
1318 // Check that the gROOT macro was exported by any core module.
1319 assert(clingInterp.getMacro("gROOT") && "Couldn't load gROOT macro?");
1320
1321 // `ERROR` and `PI` are from loading R related modules, which conflict with
1322 // user's code.
1323 clingInterp.declare(R"CODE(
1324#ifdef PI
1325# undef PI
1326#endif
1327#ifdef ERROR
1328# undef ERROR
1329#endif
1330 )CODE");
1331}
1332
1333static void RegisterPreIncludedHeaders(cling::Interpreter &clingInterp)
1334{
1335 std::string PreIncludes;
1336 bool hasCxxModules = clingInterp.getCI()->getLangOpts().Modules;
1337
1338 // For the list to also include string, we have to include it now.
1339 // rootcling does parts already if needed, e.g. genreflex does not want using
1340 // namespace std.
1341 if (IsFromRootCling()) {
1342 PreIncludes += "#include \"RtypesCore.h\"\n";
1343 } else {
1344 if (!hasCxxModules)
1345 PreIncludes += "#include \"Rtypes.h\"\n";
1346
1348 + gInterpreterClassDef + "\n"
1349 "#undef ClassImp\n" // bw compatibility
1350 "#define ClassImp(X);\n"; // bw compatibility
1351 }
1352 if (!hasCxxModules)
1353 PreIncludes += "#include <string>\n";
1354
1355 // We must include it even when we have modules because it is marked as
1356 // textual in the modulemap due to the nature of the assert header.
1357#ifndef R__WIN32
1358 PreIncludes += "#include <cassert>\n";
1359#endif
1360 PreIncludes += "using namespace std;\n";
1361 clingInterp.declare(PreIncludes);
1362}
1363
1364////////////////////////////////////////////////////////////////////////////////
1365/// Initialize the cling interpreter interface.
1366/// \param name name for TInterpreter
1367/// \param title title for TInterpreter
1368/// \param argv - array of arguments passed to the cling::Interpreter constructor
1369/// e.g. `-DFOO=bar`. The last element of the array must be `nullptr`.
1370/// \param interpLibHandle handle to interpreter library
1371
1372TCling::TCling(const char *name, const char *title, const char* const argv[], void *interpLibHandle)
1373: TInterpreter(name, title), fGlobalsListSerial(-1), fMapfile(nullptr),
1374 fRootmapFiles(nullptr), fLockProcessLine(true), fNormalizedCtxt(nullptr), fLookupHelper(nullptr),
1375 fPrevLoadedDynLibInfo(nullptr), fClingCallbacks(nullptr), fAutoLoadCallBack(nullptr),
1377{
1378 fPrompt[0] = 0;
1379 const bool fromRootCling = IsFromRootCling();
1380
1381 fCxxModulesEnabled = false;
1382#ifdef R__USE_CXXMODULES
1383 fCxxModulesEnabled = true;
1384#endif
1385
1386 llvm::install_fatal_error_handler(&exceptionErrorHandler);
1387
1388 fTemporaries = new std::vector<cling::Value>();
1389
1390 std::vector<std::string> clingArgsStorage;
1391 clingArgsStorage.push_back("cling4root");
1392 for (const char* const* arg = argv; *arg; ++arg)
1393 clingArgsStorage.push_back(*arg);
1394
1395 // rootcling sets its arguments through TROOT::GetExtraInterpreterArgs().
1396 if (!fromRootCling) {
1398
1399 // Add -I early so ASTReader can find the headers.
1400 std::string interpInclude(TROOT::GetEtcDir().Data());
1401 clingArgsStorage.push_back("-I" + interpInclude);
1402
1403 // Add include path to etc/cling.
1404 clingArgsStorage.push_back("-I" + interpInclude + "/cling");
1405
1406 // Add include path to etc/cling.
1407 clingArgsStorage.push_back("-I" + interpInclude + "/cling/plugins/include");
1408
1409 // Add the root include directory and etc/ to list searched by default.
1410 clingArgsStorage.push_back(std::string(("-I" + TROOT::GetIncludeDir()).Data()));
1411
1412 // Add the current path to the include path
1413 // TCling::AddIncludePath(".");
1414
1415 // Attach the PCH (unless we have C++ modules enabled which provide the
1416 // same functionality).
1417 if (!fCxxModulesEnabled) {
1418 std::string pchFilename = interpInclude + "/allDict.cxx.pch";
1419 if (gSystem->Getenv("ROOT_PCH")) {
1420 pchFilename = gSystem->Getenv("ROOT_PCH");
1421 }
1422
1423 clingArgsStorage.push_back("-include-pch");
1424 clingArgsStorage.push_back(pchFilename);
1425 }
1426
1427 clingArgsStorage.push_back("-Wno-undefined-inline");
1428 clingArgsStorage.push_back("-fsigned-char");
1429 clingArgsStorage.push_back("-fsized-deallocation");
1430 // The -O1 optimization flag has nasty side effects on Windows (32 and 64 bit)
1431 // See the GitHub issues #9809 and #9944
1432 // TODO: to be reviewed after the upgrade of LLVM & Clang
1433#ifndef _MSC_VER
1434 clingArgsStorage.push_back("-O1");
1435 // Disable optimized register allocation which is turned on automatically
1436 // by -O1, but seems to require -O2 to not explode in run time.
1437 clingArgsStorage.push_back("-mllvm");
1438 clingArgsStorage.push_back("-optimize-regalloc=0");
1439#endif
1440
1441#ifdef CLING_WITH_ADAPTIVECPP
1442 std::string acppInclude(TROOT::GetIncludeDir() + "/AdaptiveCpp");
1443
1444 clingArgsStorage.push_back("-isystem");
1445 clingArgsStorage.push_back(acppInclude);
1446 clingArgsStorage.push_back("-mllvm");
1447 clingArgsStorage.push_back("-acpp-sscp");
1448#endif
1449 }
1450
1451 // Process externally passed arguments if present.
1452 std::optional<std::string> EnvOpt = llvm::sys::Process::GetEnv("EXTRA_CLING_ARGS");
1453 if (EnvOpt.has_value()) {
1455 while (!Env.empty()) {
1456 StringRef Arg;
1457 std::tie(Arg, Env) = Env.split(' ');
1458 clingArgsStorage.push_back(Arg.str());
1459 }
1460 }
1461
1462 auto GetEnvVarPath = [](const std::string &EnvVar, std::vector<std::string> &Paths) {
1463 std::optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(EnvVar);
1464 if (EnvOpt.has_value()) {
1466 while (!Env.empty()) {
1467 StringRef Arg;
1468 std::tie(Arg, Env) = Env.split(ROOT::FoundationUtils::GetEnvPathSeparator());
1469 if (std::find(Paths.begin(), Paths.end(), Arg.str()) == Paths.end())
1470 Paths.push_back(Arg.str());
1471 }
1472 }
1473 };
1474
1475 if (fCxxModulesEnabled) {
1476 std::vector<std::string> Paths;
1477 // ROOT usually knows better where its libraries are. This way we can
1478 // discover modules without having to should thisroot.sh and should fix
1479 // gnuinstall.
1480 Paths.push_back(TROOT::GetSharedLibDir().Data());
1481 GetEnvVarPath("CLING_PREBUILT_MODULE_PATH", Paths);
1482 std::string EnvVarPath;
1483 for (const std::string& P : Paths)
1485 // FIXME: We should make cling -fprebuilt-module-path work.
1486 gSystem->Setenv("CLING_PREBUILT_MODULE_PATH", EnvVarPath.c_str());
1487 }
1488
1489 // FIXME: This only will enable frontend timing reports.
1490 EnvOpt = llvm::sys::Process::GetEnv("ROOT_CLING_TIMING");
1491 if (EnvOpt.has_value())
1492 clingArgsStorage.push_back("-ftime-report");
1493
1494 // Add the overlay file. Note that we cannot factor it out for both root
1495 // and rootcling because rootcling activates modules only if -cxxmodule
1496 // flag is passed.
1498 // For now we prefer rootcling to enumerate explicitly its modulemaps.
1499 std::vector<std::string> ModuleMaps;
1500 std::string ModuleMapSuffix = ROOT::FoundationUtils::GetPathSeparator() + "ROOT.modulemap";
1501 ModuleMaps.push_back(TROOT::GetIncludeDir().Data() + ModuleMapSuffix);
1502 GetEnvVarPath("CLING_MODULEMAP_FILES", ModuleMaps);
1503
1504 std::string cwd = gSystem->WorkingDirectory();
1505 // Give highest precedence of the modulemap in the cwd if any.
1506 if (llvm::sys::fs::exists(cwd + ModuleMapSuffix))
1507 ModuleMaps.push_back(cwd + ModuleMapSuffix);
1508
1509 for (const std::string& M : ModuleMaps)
1510 clingArgsStorage.push_back("-fmodule-map-file=" + M);
1511
1512 std::string ModulesCachePath;
1513 EnvOpt = llvm::sys::Process::GetEnv("CLING_MODULES_CACHE_PATH");
1514 if (EnvOpt.has_value()){
1516 assert(llvm::sys::fs::exists(Env) && "Path does not exist!");
1517 ModulesCachePath = Env.str();
1518 } else {
1520 }
1521
1522 clingArgsStorage.push_back("-fmodules-cache-path=" + ModulesCachePath);
1523 }
1524
1525 std::vector<const char*> interpArgs;
1526 for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1528 interpArgs.push_back(iArg->c_str());
1529
1530 // Activate C++ modules support. If we are running within rootcling, it's up
1531 // to rootcling to set this flag depending on whether it wants to produce
1532 // C++ modules.
1534 if (fCxxModulesEnabled) {
1535 if (!fromRootCling) {
1536 // We only set this flag, rest is done by the CIFactory.
1537 interpArgs.push_back("-fmodules");
1538 interpArgs.push_back("-fno-implicit-module-maps");
1539 // We should never build modules during runtime, so let's enable the
1540 // module build remarks from clang to make it easier to spot when we do
1541 // this by accident.
1542 interpArgs.push_back("-Rmodule-build");
1543 }
1544 // ROOT implements its AutoLoading upon module's link directives. We
1545 // generate module A { header "A.h" link "A.so" export * } where ROOT's
1546 // facilities use the link directive to dynamically load the relevant
1547 // library. So, we need to suppress clang's default autolink behavior.
1548 interpArgs.push_back("-fno-autolink");
1549 }
1550
1551#ifdef R__FAST_MATH
1552 // Same setting as in rootcling_impl.cxx.
1553 interpArgs.push_back("-ffast-math");
1554#endif
1555
1557 // Add statically injected extra arguments, usually coming from rootcling.
1558 for (const char** extraArgs = TROOT::GetExtraInterpreterArgs();
1559 extraArgs && *extraArgs; ++extraArgs) {
1560 if (!strcmp(*extraArgs, "-resource-dir")) {
1561 // Take the next arg as the llvm resource directory.
1563 } else {
1564 interpArgs.push_back(*extraArgs);
1565 }
1566 }
1567
1568 std::vector<std::string> _empty;
1570 for (const auto &arg: args)
1571 interpArgs.emplace_back(arg.c_str());
1572
1573 // Add the Rdict module file extension.
1574 cling::Interpreter::ModuleFileExtensions extensions;
1575 EnvOpt = llvm::sys::Process::GetEnv("ROOTDEBUG_RDICT");
1576 if (!EnvOpt.has_value())
1577 extensions.push_back(std::make_shared<TClingRdictModuleFileExtension>());
1578
1579 fInterpreter = std::make_unique<cling::Interpreter>(interpArgs.size(),
1580 &(interpArgs[0]),
1583
1584 if (!fInterpreter->getCI()) { // Compiler instance could not be created. See https://its.cern.ch/jira/browse/ROOT-10239
1585 return;
1586 }
1587
1588 // Tell CppInterOp that the cling::Interpreter instance is managed externally by ROOT
1589 // Sets the interpreter by passing the fInterpreter handle as soon as TCling is initialized
1590 Cpp::UseExternalInterpreter((Cpp::TInterp_t*)fInterpreter.get());
1591
1592 // Don't check whether modules' files exist.
1593 fInterpreter->getCI()->getPreprocessorOpts().DisablePCHOrModuleValidation =
1594 DisableValidationForModuleKind::All;
1595
1596 // Until we can disable AutoLoading during Sema::CorrectTypo() we have
1597 // to disable spell checking.
1598 fInterpreter->getCI()->getLangOpts().SpellChecking = false;
1599
1600 // Sync modules on/off between clang and us: clang turns it on for C++ >= 20.
1601 auto isModulesArg = [](const char* arg) { return !strcmp(arg, "-fmodules"); };
1602 bool hasModulesArg = std::find_if(interpArgs.begin(), interpArgs.end(), isModulesArg) != interpArgs.end();
1603 fInterpreter->getCI()->getLangOpts().Modules = hasModulesArg;
1604
1605 // We need stream that doesn't close its file descriptor, thus we are not
1606 // using llvm::outs. Keeping file descriptor open we will be able to use
1607 // the results in pipes (Savannah #99234).
1608 static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO, /*ShouldClose*/false);
1609 fMetaProcessor = std::make_unique<cling::MetaProcessor>(*fInterpreter, fMPOuts);
1610
1613
1614 // We are now ready (enough is loaded) to init the list of opaque typedefs.
1620
1621 // Disallow auto-parsing in rootcling
1623
1624 ResetAll();
1625
1626 // Enable dynamic lookup
1627 if (!fromRootCling) {
1628 fInterpreter->enableDynamicLookup();
1629 }
1630
1631 // Enable ClinG's DefinitionShadower for ROOT.
1632 fInterpreter->getRuntimeOptions().AllowRedefinition = 1;
1633 auto &Policy = const_cast<clang::PrintingPolicy &>(fInterpreter->getCI()->getASTContext().getPrintingPolicy());
1634 // Print 'a<b<c> >' rather than 'a<b<c>>'.
1635 // FIXME: We should probably switch to the default printing policy setting
1636 // after adjusting tons of reference files.
1637 Policy.SplitTemplateClosers = true;
1638 // Keep default templare arguments, required for dictionary generation.
1639 Policy.SuppressDefaultTemplateArgs = false;
1640
1641
1642 // Attach cling callbacks last; they might need TROOT::fInterpreter
1643 // and should thus not be triggered during the equivalent of
1644 // TROOT::fInterpreter = new TCling;
1645 std::unique_ptr<TClingCallbacks>
1649 fInterpreter->setCallbacks(std::move(clingCallbacks));
1650
1651 if (!fromRootCling) {
1652 cling::DynamicLibraryManager& DLM = *fInterpreter->getDynamicLibraryManager();
1653 // Make sure cling looks into ROOT's libdir, even if not part of LD_LIBRARY_PATH
1654 // e.g. because of an RPATH build.
1655 DLM.addSearchPath(TROOT::GetSharedLibDir().Data(), /*isUser=*/true,
1656 /*prepend=*/true);
1657 auto ShouldPermanentlyIgnore = [](llvm::StringRef FileName) -> bool{
1658 llvm::StringRef stem = llvm::sys::path::stem(FileName);
1659 return stem.starts_with("libNew") || stem.starts_with("libcppyy_backend");
1660 };
1661 // Initialize the dyld for AutoloadLibraryGenerator.
1662 DLM.initializeDyld(ShouldPermanentlyIgnore);
1663 }
1664}
1665
1666
1667////////////////////////////////////////////////////////////////////////////////
1668/// Destroy the interpreter interface.
1669
1671{
1672 // ROOT's atexit functions require the interepreter to be available.
1673 // Run them before shutting down.
1674 if (!IsFromRootCling())
1675 GetInterpreterImpl()->runAtExitFuncs();
1676 fIsShuttingDown = true;
1677 delete fMapfile;
1678 delete fRootmapFiles;
1679 delete fTemporaries;
1680 delete fNormalizedCtxt;
1681 delete fLookupHelper;
1682 gCling = nullptr;
1683}
1684
1685////////////////////////////////////////////////////////////////////////////////
1686/// Initialize the interpreter, once TROOT::fInterpreter is set.
1687
1689{
1690 if (!fClingCallbacks) // Compiler instance could not be created. See https://its.cern.ch/jira/browse/ROOT-10239
1691 return;
1693
1694 // We are set up. Enable ROOT's AutoLoading.
1695 if (IsFromRootCling())
1696 return;
1697
1698 // Read the rules before enabling the auto loading to not inadvertently
1699 // load the libraries for the classes concerned even-though the user is
1700 // *not* using them.
1701 // Note this call must happen before the first call to LoadLibraryMap.
1702 assert(GetRootMapFiles() == nullptr && "Must be called before LoadLibraryMap!");
1703 TClass::ReadRules(); // Read the default customization rules ...
1704
1706 SetClassAutoLoading(true);
1707}
1708
1710{
1711 fIsShuttingDown = true;
1712 ResetGlobals();
1713}
1714
1715////////////////////////////////////////////////////////////////////////////////
1716/// Helper to initialize TVirtualStreamerInfo's factor early.
1717/// Use static initialization to insure only one TStreamerInfo is created.
1719{
1720 // Use lambda since SetFactory return void.
1721 auto setFactory = []() {
1723 return kTRUE;
1724 };
1725 static bool doneFactory = setFactory();
1726 return doneFactory; // avoid unused variable warning.
1727}
1728
1729////////////////////////////////////////////////////////////////////////////////
1730/// Register Rdict data for future loading by LoadPCM;
1731
1732void TCling::RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
1733{
1734 if (IsFromRootCling())
1735 return;
1736
1737 if (llvm::sys::fs::exists(pcmFileNameFullPath)) {
1738 ::Error("TCling::RegisterRdictForLoadPCM", "Rdict '%s' is both in Module extension and in File system.", pcmFileNameFullPath.c_str());
1739 return;
1740 }
1741
1742 // The pcmFileNameFullPath must be resolved already because we cannot resolve
1743 // a link to a non-existent file.
1745}
1746
1747////////////////////////////////////////////////////////////////////////////////
1748/// Tries to load a PCM from TFile; returns true on success.
1749/// The caller of this function should be holding the ROOT Write lock.
1750
1752{
1753 auto listOfKeys = pcmFile.GetListOfKeys();
1754
1755 // This is an empty pcm
1756 if (listOfKeys && ((listOfKeys->GetSize() == 0) || // Nothing here, or
1757 ((listOfKeys->GetSize() == 1) && // only one, and
1758 !strcmp(((TKey *)listOfKeys->At(0))->GetName(), "EMPTY") // name is EMPTY
1759 ))) {
1760 return;
1761 }
1762
1764 if (gDebug > 1)
1765 ::Info("TCling::LoadPCMImpl", "reading protoclasses for %s \n", pcmFile.GetName());
1766
1768 pcmFile.GetObject("__Enums", enums);
1769 if (enums) {
1770 // Cache the pointers
1771 auto listOfGlobals = gROOT->GetListOfGlobals();
1772 auto listOfEnums = dynamic_cast<THashList *>(gROOT->GetListOfEnums());
1773 // Loop on enums and then on enum constants
1774 for (auto selEnum : *enums) {
1775 const char *enumScope = selEnum->GetTitle();
1776 const char *enumName = selEnum->GetName();
1777 if (strcmp(enumScope, "") == 0) {
1778 // This is a global enum and is added to the
1779 // list of enums and its constants to the list of globals
1780 if (!listOfEnums->THashList::FindObject(enumName)) {
1781 ((TEnum *)selEnum)->SetClass(nullptr);
1782 listOfEnums->Add(selEnum);
1783 }
1784 for (auto enumConstant : *static_cast<TEnum *>(selEnum)->GetConstants()) {
1785 if (!listOfGlobals->FindObject(enumConstant)) {
1787 }
1788 }
1789 } else {
1790 // This enum is in a namespace. A TClass entry is bootstrapped if
1791 // none exists yet and the enum is added to it
1793 if (!nsTClassEntry) {
1795 }
1796 auto listOfEnums = nsTClassEntry->fEnums.load();
1797 if (!listOfEnums) {
1798 if ((kIsClass | kIsStruct | kIsUnion) & nsTClassEntry->Property()) {
1799 // For this case, the list will be immutable once constructed
1800 // (i.e. in this case, by the end of this routine).
1802 } else {
1803 // namespaces can have enums added to them
1805 }
1806 }
1807 if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)) {
1808 ((TEnum *)selEnum)->SetClass(nsTClassEntry);
1809 listOfEnums->Add(selEnum);
1810 }
1811 }
1812 }
1813 enums->Clear();
1814 delete enums;
1815 }
1816
1817 pcmFile.GetObject("__ProtoClasses", protoClasses);
1818
1819 if (protoClasses) {
1820 for (auto obj : *protoClasses) {
1821 TProtoClass *proto = (TProtoClass *)obj;
1823 }
1824 // Now that all TClass-es know how to set them up we can update
1825 // existing TClasses, which might cause the creation of e.g. TBaseClass
1826 // objects which in turn requires the creation of TClasses, that could
1827 // come from the PCH, but maybe later in the loop. Instead of resolving
1828 // a dependency graph the addition to the TClassTable above allows us
1829 // to create these dependent TClasses as needed below.
1830 for (auto proto : *protoClasses) {
1831 if (TClass *existingCl = (TClass *)gROOT->GetListOfClasses()->FindObject(proto->GetName())) {
1832 // We have an existing TClass object. It might be emulated
1833 // or interpreted; we now have more information available.
1834 // Make that available.
1835 if (existingCl->GetState() != TClass::kHasTClassInit) {
1836 DictFuncPtr_t dict = gClassTable->GetDict(proto->GetName());
1837 if (!dict) {
1838 ::Error("TCling::LoadPCM", "Inconsistent TClassTable for %s", proto->GetName());
1839 } else {
1840 // This will replace the existing TClass.
1841 TClass *ncl = (*dict)();
1842 if (ncl)
1843 ncl->PostLoadCheck();
1844 }
1845 }
1846 }
1847 }
1848
1849 protoClasses->Clear(); // Ownership was transferred to TClassTable.
1850 delete protoClasses;
1851 }
1852
1854 pcmFile.GetObject("__Typedefs", dataTypes);
1855 if (dataTypes) {
1856 for (auto typedf : *dataTypes)
1857 gROOT->GetListOfTypes()->Add(typedf);
1858 dataTypes->Clear(); // Ownership was transferred to TListOfTypes.
1859 delete dataTypes;
1860 }
1861}
1862
1863////////////////////////////////////////////////////////////////////////////////
1864/// Tries to load a rdict PCM, issues diagnostics if it fails.
1865/// The caller of this function should be holding the ROOT Write lock.
1866
1868{
1871 assert(!pcmFileNameFullPath.empty());
1872 assert(llvm::sys::path::is_absolute(pcmFileNameFullPath));
1873
1874 // Easier to work with the ROOT interfaces.
1876
1877 // Prevent the ROOT-PCMs hitting this during auto-load during
1878 // JITting - which will cause recursive compilation.
1879 // Avoid to call the plugin manager at all.
1881
1883 llvm::SaveAndRestore<Int_t> SaveGDebug(gDebug);
1884 if (gDebug > 5) {
1885 gDebug -= 5;
1886 ::Info("TCling::LoadPCM", "Loading ROOT PCM %s", pcmFileName.Data());
1887 } else {
1888 gDebug = 0;
1889 }
1890
1891 if (llvm::sys::fs::is_symlink_file(pcmFileNameFullPath))
1893
1895 if (pendingRdict != fPendingRdicts.end()) {
1896 llvm::StringRef pcmContent = pendingRdict->second;
1898 std::string RDictFileOpts = pcmFileNameFullPath + "?filetype=pcm";
1900
1901 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
1903 // Currently the module file are never unloaded (even if the library is
1904 // unloaded) and, of course, never reloaded.
1905 // Consequently, we must NOT remove the `pendingRdict` from the list
1906 // of pending dictionary, otherwise if a library is unloaded and then
1907 // reload we will be unable to update properly the TClass object
1908 // (because we wont be able to load the rootpcm file by executing the
1909 // above lines)
1910
1911 return;
1912 }
1913
1914 if (!llvm::sys::fs::exists(pcmFileNameFullPath)) {
1915 ::Error("TCling::LoadPCM", "ROOT PCM %s file does not exist",
1916 pcmFileNameFullPath.data());
1917 if (!fPendingRdicts.empty())
1918 for (const auto &rdict : fPendingRdicts)
1919 ::Info("TCling::LoadPCM", "In-memory ROOT PCM candidate %s\n",
1920 rdict.first.c_str());
1921 return;
1922 }
1923
1924 if (!gROOT->IsRootFile(pcmFileName)) {
1925 Fatal("LoadPCM", "The file %s is not a ROOT as was expected\n", pcmFileName.Data());
1926 return;
1927 }
1928 TFile pcmFile(pcmFileName + "?filetype=pcm", "READ");
1930}
1931
1932//______________________________________________________________________________
1933
1934namespace {
1935 using namespace clang;
1936
1937 class ExtLexicalStorageAdder: public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1938 // This class is to be considered an helper for autoparsing.
1939 // It visits the AST and marks all classes (in all of their redeclarations)
1940 // with the setHasExternalLexicalStorage method.
1941 public:
1942 bool VisitRecordDecl(clang::RecordDecl* rcd){
1943 if (gDebug > 2)
1944 Info("ExtLexicalStorageAdder",
1945 "Adding external lexical storage to class %s",
1946 rcd->getNameAsString().c_str());
1947 auto reDeclPtr = rcd->getMostRecentDecl();
1948 do {
1949 reDeclPtr->setHasExternalLexicalStorage();
1950 } while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1951
1952 return false;
1953 }
1954 };
1955
1956
1957}
1958
1959////////////////////////////////////////////////////////////////////////////////
1960///\returns true if the module map was loaded, false on error or if the map was
1961/// already loaded.
1963 const std::string &ModuleMapName /*= "module.modulemap"*/) const
1964{
1965 assert(llvm::sys::path::is_absolute(FullPath));
1966 Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
1967 FileManager &FM = PP.getFileManager();
1968 // FIXME: In a ROOT session we can add an include path (through .I /inc/path)
1969 // We should look for modulemap files there too.
1970 if (auto DE = FM.getOptionalDirectoryRef(FullPath)) {
1971 HeaderSearch &HS = PP.getHeaderSearchInfo();
1972 HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1973 const auto &ModPaths = HSOpts.PrebuiltModulePaths;
1974 bool pathExists = std::find(ModPaths.begin(), ModPaths.end(), FullPath) != ModPaths.end();
1975 if (!pathExists)
1976 HSOpts.AddPrebuiltModulePath(FullPath);
1977 // We cannot use HS.lookupModuleMapFile(DE, /*IsFramework*/ false);
1978 // because its internal call to getFile has CacheFailure set to true.
1979 // In our case, modulemaps can appear any time due to ACLiC.
1980 // Code copied from HS.lookupModuleMapFile.
1981 llvm::SmallString<256> ModuleMapFileName(DE->getName());
1982 llvm::sys::path::append(ModuleMapFileName, ModuleMapName);
1983 if (auto FE = FM.getOptionalFileRef(ModuleMapFileName, /*openFile*/ false,
1984 /*CacheFailure*/ false)) {
1985 if (!HS.loadModuleMapFile(*FE, /*IsSystem*/ false))
1986 return true;
1987 Error("RegisterPrebuiltModulePath", "Could not load modulemap in %s", ModuleMapFileName.c_str());
1988 }
1989 }
1990 return false;
1991}
1992
1993////////////////////////////////////////////////////////////////////////////////
1994/// List of dicts that have the PCM information already in the PCH.
1995static const std::unordered_set<std::string> gIgnoredPCMNames = {"libCore",
1996 "libRint",
1997 "libThread",
1998 "libRIO",
1999 "libImt",
2000 "libMultiProc",
2001 "libcomplexDict",
2002 "libdequeDict",
2003 "liblistDict",
2004 "libforward_listDict",
2005 "libvectorDict",
2006 "libmapDict",
2007 "libmultimap2Dict",
2008 "libmap2Dict",
2009 "libmultimapDict",
2010 "libsetDict",
2011 "libmultisetDict",
2012 "libunordered_setDict",
2013 "libunordered_multisetDict",
2014 "libunordered_mapDict",
2015 "libunordered_multimapDict",
2016 "libvalarrayDict",
2017 "G__GenVector32",
2018 "G__Smatrix32"};
2019
2020static void PrintDlError(const char *dyLibName, const char *modulename)
2021{
2022#ifdef R__WIN32
2023 char dyLibError[1000];
2025 dyLibError, sizeof(dyLibError), NULL);
2026#else
2027 const char *dyLibError = dlerror();
2028#endif
2029 ::Error("TCling::RegisterModule", "Cannot open shared library %s for dictionary %s:\n %s", dyLibName, modulename,
2030 (dyLibError) ? dyLibError : "");
2031}
2032
2033////////////////////////////////////////////////////////////////////////////////
2034// Update all the TClass registered in fClassesToUpdate
2035
2037{
2038 while (!fClassesToUpdate.empty()) {
2039 TClass *oldcl = fClassesToUpdate.back().first;
2040 // If somehow the TClass has already been loaded (maybe it was registered several time),
2041 // we skip it. Otherwise, the existing TClass is in mode kInterpreted, kEmulated or
2042 // maybe even kForwardDeclared and needs to replaced.
2043 if (oldcl->GetState() != TClass::kHasTClassInit) {
2044 // if (gDebug > 2) Info("RegisterModule", "Forcing TClass init for %s", oldcl->GetName());
2045 DictFuncPtr_t dict = fClassesToUpdate.back().second;
2046 fClassesToUpdate.pop_back();
2047 // Calling func could manipulate the list so, let maintain the list
2048 // then call the dictionary function.
2049 TClass *ncl = dict();
2050 if (ncl) ncl->PostLoadCheck();
2051 } else {
2052 fClassesToUpdate.pop_back();
2053 }
2054 }
2055}
2056////////////////////////////////////////////////////////////////////////////////
2057/// Inject the module named "modulename" into cling; load all headers.
2058/// headers is a 0-terminated array of header files to `#include` after
2059/// loading the module. The module is searched for in all $LD_LIBRARY_PATH
2060/// entries (or %PATH% on Windows).
2061/// This function gets called by the static initialization of dictionary
2062/// libraries.
2063/// The payload code is injected "as is" in the interpreter.
2064/// The value of 'triggerFunc' is used to find the shared library location.
2065/// The caller of this function should be holding the ROOT Write lock.
2066
2068 const char** headers,
2069 const char** includePaths,
2070 const char* payloadCode,
2071 const char* fwdDeclsCode,
2072 void (*triggerFunc)(),
2074 const char** classesHeaders,
2075 Bool_t lateRegistration /*=false*/,
2076 Bool_t hasCxxModule /*=false*/)
2077{
2078 const bool fromRootCling = IsFromRootCling();
2079 // We need the dictionary initialization but we don't want to inject the
2080 // declarations into the interpreter, except for those we really need for
2081 // I/O; see rootcling.cxx after the call to TCling__GetInterpreter().
2082 if (fromRootCling) return;
2083
2084 // When we cannot provide a module for the library we should enable header
2085 // parsing. This 'mixed' mode ensures gradual migration to modules.
2086 llvm::SaveAndRestore<bool> SaveHeaderParsing(fHeaderParsingOnDemand);
2088
2089 // Treat Aclic Libs in a special way. Do not delay the parsing.
2091 bool isACLiC = strstr(modulename, "_ACLiC_dict") != nullptr;
2093 if (gDebug>1)
2094 Info("TCling::RegisterModule",
2095 "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
2097 }
2098
2099
2100 // Make sure we relookup symbols that were search for before we loaded
2101 // their autoparse information. We could be more subtil and remove only
2102 // the failed one or only the one in this module, but for now this is
2103 // better than nothing.
2104 fLookedUpClasses.clear();
2105
2106 // Make sure we do not set off AutoLoading or autoparsing during the
2107 // module registration!
2109
2110 for (const char** inclPath = includePaths; *inclPath; ++inclPath) {
2112 }
2113 cling::Transaction* T = nullptr;
2114 // Put the template decls and the number of arguments to skip in the TNormalizedCtxt
2116 const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
2117 const int nArgsToSkip = fwdDeclArgToSkipPair.second;
2118 auto compRes = fInterpreter->declare(fwdDecl.c_str(), &T);
2119 assert(cling::Interpreter::kSuccess == compRes &&
2120 "A fwd declaration could not be compiled");
2121 if (compRes!=cling::Interpreter::kSuccess){
2122 Warning("TCling::RegisterModule",
2123 "Problems in declaring string '%s' were encountered.",
2124 fwdDecl.c_str()) ;
2125 continue;
2126 }
2127
2128 // Drill through namespaces recursively until the template is found
2129 if(ClassTemplateDecl* TD = FindTemplateInNamespace(T->getFirstDecl().getSingleDecl())){
2131 }
2132
2133 }
2134
2135 // FIXME: Remove #define __ROOTCLING__ once PCMs are there.
2136 // This is used to give Sema the same view on ACLiC'ed files (which
2137 // are then #included through the dictionary) as rootcling had.
2139 if (payloadCode)
2140 code += payloadCode;
2141
2142 std::string dyLibName = cling::DynamicLibraryManager::getSymbolLocation(triggerFunc);
2143 assert(!llvm::sys::fs::is_symlink_file(dyLibName));
2144
2145 if (dyLibName.empty()) {
2146 ::Error("TCling::RegisterModule", "Dictionary trigger function for %s not found", modulename);
2147 return;
2148 }
2149
2150 // The triggerFunc may not be in a shared object but in an executable.
2151 bool isSharedLib = cling::DynamicLibraryManager::isSharedLibrary(dyLibName);
2152
2153 bool wasDlopened = false;
2154
2155 // If this call happens after dlopen has finished (i.e. late registration)
2156 // there is no need to dlopen the library recursively. See ROOT-8437 where
2157 // the dyLibName would correspond to the binary.
2158 if (!lateRegistration) {
2159
2160 if (isSharedLib) {
2161 // We need to open the dictionary shared library, to resolve symbols
2162 // requested by the JIT from it: as the library is currently being dlopen'ed,
2163 // its symbols are not yet reachable from the process.
2164 // Recursive dlopen seems to work just fine.
2165 void* dyLibHandle = dlopen(dyLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
2166 if (dyLibHandle) {
2168 wasDlopened = true;
2169 } else {
2171 }
2172 }
2173 } // if (!lateRegistration)
2174
2176 // We now parse the forward declarations. All the classes are then modified
2177 // in order for them to have an external lexical storage.
2178 std::string fwdDeclsCodeLessEnums;
2179 {
2180 // Search for enum forward decls and only declare them if no
2181 // declaration exists yet.
2182 std::string fwdDeclsLine;
2183 std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
2184 std::vector<std::string> scopes;
2185 while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
2186 const auto enumPos = fwdDeclsLine.find("enum __attribute__((annotate(\"");
2187 // We check if the line contains a fwd declaration of an enum
2188 if (enumPos != std::string::npos) {
2189 // We clear the scopes which we may have carried from a previous iteration
2190 scopes.clear();
2191 // We check if the enum is not in a scope. If yes, save its name
2192 // and the names of the enclosing scopes.
2193 if (enumPos != 0) {
2194 // it's enclosed in namespaces. We need to understand what they are
2195 auto nsPos = fwdDeclsLine.find("namespace");
2196 R__ASSERT(nsPos < enumPos && "Inconsistent enum and enclosing scope parsing!");
2197 while (nsPos < enumPos && nsPos != std::string::npos) {
2198 // we have a namespace, let's put it in the collection of scopes
2199 const auto nsNameStart = nsPos + 10;
2200 const auto nsNameEnd = fwdDeclsLine.find('{', nsNameStart);
2201 const auto nsName = fwdDeclsLine.substr(nsNameStart, nsNameEnd - nsNameStart);
2202 scopes.push_back(nsName);
2203 nsPos = fwdDeclsLine.find("namespace", nsNameEnd);
2204 }
2205 }
2206 clang::DeclContext* DC = nullptr;
2207 for (auto &&aScope: scopes) {
2208 DC = cling::utils::Lookup::Namespace(&fInterpreter->getSema(), aScope.c_str(), DC);
2209 if (!DC) {
2210 // No decl context means we have to fwd declare the enum.
2211 break;
2212 }
2213 }
2214 if (scopes.empty() || DC) {
2215 // We know the scope; let's look for the enum. For that, look
2216 // for the *last* closing parentheses of an attribute because
2217 // there can be multiple.
2218 size_t posEnumName = fwdDeclsLine.rfind("\"))) ");
2219 R__ASSERT(posEnumName != std::string::npos && "Inconsistent enum fwd decl!");
2220 posEnumName += 5; // skip "\"))) "
2222 ++posEnumName;
2223 size_t posEnumNameEnd = fwdDeclsLine.find(" : ", posEnumName);
2224 R__ASSERT(posEnumNameEnd != std::string::npos && "Inconsistent enum fwd decl (end)!");
2227 // posEnumNameEnd now points to the last character of the name.
2228
2229 std::string enumName = fwdDeclsLine.substr(posEnumName,
2231
2232 if (clang::NamedDecl* enumDecl
2233 = cling::utils::Lookup::Named(&fInterpreter->getSema(),
2234 enumName.c_str(), DC)) {
2235 // We have an existing enum decl (forward or definition);
2236 // skip this.
2237 R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) && "not an enum decl!");
2238 (void)enumDecl;
2239 continue;
2240 }
2241 }
2242 }
2243
2245 }
2246 }
2247
2248 if (!fwdDeclsCodeLessEnums.empty()){ // Avoid the overhead if nothing is to be declared
2249 auto compRes = fInterpreter->declare(fwdDeclsCodeLessEnums, &T);
2250 assert(cling::Interpreter::kSuccess == compRes &&
2251 "The forward declarations could not be compiled");
2252 if (compRes!=cling::Interpreter::kSuccess){
2253 Warning("TCling::RegisterModule",
2254 "Problems in compiling forward declarations for module %s: '%s'",
2256 }
2257 else if (T){
2258 // Loop over all decls in the transaction and go through them all
2259 // to mark them properly.
2260 // In order to do that, we first iterate over all the DelayedCallInfos
2261 // within the transaction. Then we loop over all Decls in the DeclGroupRef
2262 // contained in the DelayedCallInfos. For each decl, we traverse.
2263 ExtLexicalStorageAdder elsa;
2264 for (auto dciIt = T->decls_begin();dciIt!=T->decls_end();dciIt++){
2265 cling::Transaction::DelayCallInfo& dci = *dciIt;
2266 for(auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
2267 clang::Decl* declPtr = *dit;
2268 elsa.TraverseDecl(declPtr);
2269 }
2270 }
2271 }
2272 }
2273
2274 // Now we register all the headers necessary for the class
2275 // Typical format of the array:
2276 // {"A", "classes.h", "@",
2277 // "vector<A>", "vector", "@",
2278 // "myClass", payloadCode, "@",
2279 // nullptr};
2280
2281 std::string temp;
2282 for (const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
2283 temp=*classesHeader;
2284
2285 size_t theTemplateHash = 0;
2286 bool addTemplate = false;
2287 size_t posTemplate = temp.find('<');
2288 if (posTemplate != std::string::npos) {
2289 // Add an entry for the template itself.
2290 std::string templateName = temp.substr(0, posTemplate);
2292 addTemplate = true;
2293 }
2294 size_t theHash = fStringHashFunction(temp);
2295 classesHeader++;
2297 // This is done in order to distinguish headers from files and from the payloadCode
2299 fPayloads.insert(theHash);
2301 }
2302 if (gDebug > 2)
2303 Info("TCling::RegisterModule",
2304 "Adding a header for %s", temp.c_str());
2306 if (addTemplate) {
2309 }
2310 addTemplate = false;
2311 }
2312 }
2313 }
2314 }
2315
2316 clang::Sema &TheSema = fInterpreter->getSema();
2317
2318 bool ModuleWasSuccessfullyLoaded = false;
2319 if (hasCxxModule) {
2320 std::string ModuleName = modulename;
2321 if (llvm::StringRef(modulename).starts_with("lib"))
2322 ModuleName = llvm::StringRef(modulename).substr(3).str();
2323
2324 // In case we are directly loading the library via gSystem->Load() without
2325 // specifying the relevant include paths we should try loading the
2326 // modulemap next to the library location.
2327 clang::Preprocessor &PP = TheSema.getPreprocessor();
2328 std::string ModuleMapName;
2329 if (isACLiC)
2330 ModuleMapName = ModuleName + ".modulemap";
2331 else
2332 ModuleMapName = "module.modulemap";
2333 RegisterPrebuiltModulePath(llvm::sys::path::parent_path(dyLibName).str(),
2335
2336 // FIXME: We should only complain for modules which we know to exist. For example, we should not complain about
2337 // modules such as GenVector32 because it needs to fall back to GenVector.
2338 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2341 // Only report if we found the module in the modulemap.
2342 clang::HeaderSearch &headerSearch = PP.getHeaderSearchInfo();
2343 clang::ModuleMap &moduleMap = headerSearch.getModuleMap();
2344 if (moduleMap.findModule(ModuleName))
2345 Info("TCling::RegisterModule", "Module %s in modulemap failed to load.", ModuleName.c_str());
2346 }
2347 }
2348
2350 llvm::SmallString<256> pcmFileNameFullPath(dyLibName);
2351 // The path dyLibName might not be absolute. This can happen if dyLibName
2352 // is linked to an executable in the same folder.
2353 llvm::sys::fs::make_absolute(pcmFileNameFullPath);
2354 llvm::sys::path::remove_filename(pcmFileNameFullPath);
2355 llvm::sys::path::append(pcmFileNameFullPath,
2357 LoadPCM(pcmFileNameFullPath.str().str());
2358 }
2359
2360 { // scope within which diagnostics are de-activated
2361 // For now we disable diagnostics because we saw them already at
2362 // dictionary generation time. That won't be an issue with the PCMs.
2363
2364 clangDiagSuppr diagSuppr(TheSema.getDiagnostics());
2365
2366#if defined(R__MUST_REVISIT)
2367#if R__MUST_REVISIT(6,2)
2368 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
2369#endif
2370#endif
2371
2374
2375 const cling::Transaction* watermark = fInterpreter->getLastTransaction();
2376 cling::Interpreter::CompilationResult compRes = fInterpreter->parseForModule(code.Data());
2377 if (isACLiC) {
2378 // Register an unload point.
2379 fMetaProcessor->registerUnloadPoint(watermark, headers[0]);
2380 }
2381
2382 assert(cling::Interpreter::kSuccess == compRes &&
2383 "Payload code of a dictionary could not be parsed correctly.");
2384 if (compRes!=cling::Interpreter::kSuccess) {
2385 Warning("TCling::RegisterModule",
2386 "Problems declaring payload for module %s.", modulename) ;
2387 }
2388 }
2389 }
2390
2391 // Now that all the header have been registered/compiled, let's
2392 // make sure to 'reset' the TClass that have a class init in this module
2393 // but already had their type information available (using information/header
2394 // loaded from other modules or from class rules or from opening a TFile
2395 // or from loading header in a way that did not provoke the loading of
2396 // the library we just loaded).
2398
2400 // __ROOTCLING__ might be pulled in through PCH
2401 fInterpreter->declare("#ifdef __ROOTCLING__\n"
2402 "#undef __ROOTCLING__\n"
2404 "#endif");
2405 }
2406
2407 if (wasDlopened) {
2409 void* dyLibHandle = fRegisterModuleDyLibs.back();
2410 fRegisterModuleDyLibs.pop_back();
2412 }
2413}
2414
2416 clang::CompilerInstance& CI = *GetInterpreterImpl()->getCI();
2417 ASTContext &C = CI.getASTContext();
2418
2419 // Do not do anything if we have no global module index.
2420 // FIXME: This is mostly to real with false positives in the TTabCom
2421 // interface for non-modules.
2422 if (!fCxxModulesEnabled)
2423 return;
2424
2425 if (IdentifierInfoLookup *External = C.Idents.getExternalIdentifierLookup()) {
2426 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
2427 for (llvm::StringRef Ident = Iter->Next(); !Ident.empty(); Ident = Iter->Next()) {
2428 std::string I = Ident.str();
2429 if (!Idents.Contains(I.data()))
2430 Idents.Add(new TObjString(I.c_str()));
2431 }
2432 }
2433}
2434
2435
2436////////////////////////////////////////////////////////////////////////////////
2437/// Register classes that already existed prior to their dictionary loading
2438/// and that already had a ClassInfo (and thus would not be refresh via
2439/// UpdateClassInfo.
2440
2442{
2443 fClassesToUpdate.push_back(std::make_pair(oldcl,dict));
2444}
2445
2446////////////////////////////////////////////////////////////////////////////////
2447/// If the dictionary is loaded, we can remove the class from the list
2448/// (otherwise the class might be loaded twice).
2449
2451{
2452 typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
2453 iterator stop = fClassesToUpdate.end();
2454 for(iterator i = fClassesToUpdate.begin();
2455 i != stop;
2456 ++i)
2457 {
2458 if ( i->first == oldcl ) {
2459 fClassesToUpdate.erase(i);
2460 return;
2461 }
2462 }
2463}
2464
2465
2466////////////////////////////////////////////////////////////////////////////////
2467/// Let cling process a command line.
2468///
2469/// If the command is executed and the error is 0, then the return value
2470/// is the int value corresponding to the result of the executed command
2471/// (float and double return values will be truncated).
2472///
2473
2474// Method for handling the interpreter exceptions.
2475// the MetaProcessor is passing in as argument to teh function, because
2476// cling::Interpreter::CompilationResult is a nested class and it cannot be
2477// forward declared, thus this method cannot be a static member function
2478// of TCling.
2479
2480static int HandleInterpreterException(cling::MetaProcessor* metaProcessor,
2481 const char* input_line,
2482 cling::Interpreter::CompilationResult& compRes,
2483 cling::Value* result)
2484{
2485 try {
2486 return metaProcessor->process(input_line, compRes, result);
2487 }
2488 catch (cling::InterpreterException& ex)
2489 {
2490 Error("HandleInterpreterException", "%s\n%s", ex.what(), "Execution of your code was aborted.");
2491 ex.diagnose();
2492 compRes = cling::Interpreter::kFailure;
2493 }
2494 return 0;
2495}
2496
2497////////////////////////////////////////////////////////////////////////////////
2498
2499bool TCling::DiagnoseIfInterpreterException(const std::exception &e) const
2500{
2501 if (auto ie = dynamic_cast<const cling::InterpreterException*>(&e)) {
2502 ie->diagnose();
2503 return true;
2504 }
2505 return false;
2506}
2507
2508////////////////////////////////////////////////////////////////////////////////
2509
2511{
2512 // Copy the passed line, it comes from a static buffer in TApplication
2513 // which can be reentered through the Cling evaluation routines,
2514 // which would overwrite the static buffer and we would forget what we
2515 // were doing.
2516 //
2518 if (strstr(line,fantomline)) {
2519 // End-Of-Line action
2520 // See the comment (copied from above):
2521 // It is a "fantom" method to synchronize user keyboard input
2522 // and ROOT prompt line (for WIN32)
2523 // and is implemented by
2524 if (gApplication) {
2525 if (gApplication->IsCmdThread()) {
2527 gROOT->SetLineIsProcessing();
2528
2530
2531 gROOT->SetLineHasBeenProcessed();
2532 }
2533 }
2534 return 0;
2535 }
2536
2538 gGlobalMutex->Lock();
2539 if (!gInterpreterMutex)
2542 }
2544 gROOT->SetLineIsProcessing();
2545
2546 struct InterpreterFlagsRAII {
2547 cling::Interpreter* fInterpreter;
2549
2550 InterpreterFlagsRAII(cling::Interpreter* interp):
2551 fInterpreter(interp),
2552 fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
2553 {
2554 fInterpreter->enableDynamicLookup(true);
2555 }
2557 fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
2558 gROOT->SetLineHasBeenProcessed();
2559 }
2561
2562 // A non-zero returned value means the given line was
2563 // not a complete statement.
2564 int indent = 0;
2565 // This will hold the resulting value of the evaluation the given line.
2566 cling::Value result;
2567 cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
2568 if (!strncmp(sLine.Data(), ".L", 2) || !strncmp(sLine.Data(), ".x", 2) ||
2569 !strncmp(sLine.Data(), ".X", 2)) {
2570 // If there was a trailing "+", then CINT compiled the code above,
2571 // and we will need to strip the "+" before passing the line to cling.
2574 TString arguments;
2575 TString io;
2577 aclicMode, arguments, io);
2578 if (aclicMode.Length()) {
2579 // Remove the leading '+'
2580 R__ASSERT(aclicMode[0]=='+' && "ACLiC mode must start with a +");
2581 aclicMode[0]='k'; // We always want to keep the .so around.
2582 if (aclicMode[1]=='+') {
2583 // We have a 2nd +
2584 aclicMode[1]='f'; // We want to force the recompilation.
2585 }
2587 // ACLiC failed.
2588 compRes = cling::Interpreter::kFailure;
2589 } else {
2590 if (strncmp(sLine.Data(), ".L", 2) != 0) {
2591 // if execution was requested.
2592
2593 if (arguments.Length() == 0) {
2594 arguments = "()";
2595 }
2596 // We need to remove the extension.
2597 Ssiz_t ext = fname.Last('.');
2598 if (ext != kNPOS) {
2599 fname.Remove(ext);
2600 }
2601 const char *function = gSystem->BaseName(fname);
2602 mod_line = function + arguments + io;
2604 }
2605 }
2606 } else if (cling::DynamicLibraryManager::isSharedLibrary(fname.Data()) &&
2607 strncmp(sLine.Data(), ".L", 2) != 0) { // .x *.so or *.dll
2608 if (gSystem->Load(fname) < 0) {
2609 // Loading failed.
2610 compRes = cling::Interpreter::kFailure;
2611 } else {
2612 if (arguments.Length() == 0) {
2613 arguments = "()";
2614 }
2615 // We need to remove the extension. (*.so or *.dll)
2616 Ssiz_t ext = fname.Last('.');
2617 if (ext != kNPOS) {
2618 fname.Remove(ext);
2619 }
2620 // Now we try to find the 'main' function to run within this shared library
2621 // We distinguish two cases: a library.so with a function library(args),
2622 // or a precompiled ACLiC macro (macro_C.so) with a function macro(args).
2623 // Only in the second case, we need to strip the suffix _C or _cpp from fname.
2624 if (!gInterpreter->GetFunction(nullptr, gSystem->BaseName(fname))) { // AcLiC macro
2625 // We need to remove the automatically appended _ extension when compiling (macro_C from macro.C)
2626 ext = fname.Last('_');
2627 if (ext != kNPOS) {
2628 fname.Remove(ext);
2629 }
2630 }
2631 const char *function = gSystem->BaseName(fname);
2632 mod_line = function + arguments + io;
2634 }
2635 } else {
2636 // neither ACLiC nor run shared-library (.x)
2637 size_t unnamedMacroOpenCurly;
2638 {
2639 std::string code;
2640 std::string codeline;
2641 // Windows requires std::ifstream::binary to properly handle
2642 // CRLF and LF line endings
2643 std::ifstream in(fname, std::ifstream::binary);
2644 while (in) {
2645 std::getline(in, codeline);
2646 code += codeline + "\n";
2647 }
2649 = cling::utils::isUnnamedMacro(code, fInterpreter->getCI()->getLangOpts());
2650 }
2651
2652 fCurExecutingMacros.push_back(fname);
2653 if (unnamedMacroOpenCurly != std::string::npos) {
2654 compRes = fMetaProcessor->readInputFromFile(fname.Data(), &result,
2656 } else {
2657 // No DynLookup for .x, .L of named macros.
2658 fInterpreter->enableDynamicLookup(false);
2660 }
2661 fCurExecutingMacros.pop_back();
2662 }
2663 } // .L / .X / .x
2664 else {
2665 if (0!=strncmp(sLine.Data(), ".autodict ",10) && sLine != ".autodict") {
2666 // explicitly ignore .autodict without having to support it
2667 // in cling.
2668
2669 // Turn off autoparsing if this is an include directive
2670 bool isInclusionDirective = sLine.Contains("\n#include") || sLine.BeginsWith("#include");
2674 } else {
2676 }
2677 }
2678 }
2679 if (result.isValid())
2681 if (indent) {
2682 if (error)
2683 *error = kProcessing;
2684 return 0;
2685 }
2686 if (error) {
2687 switch (compRes) {
2688 case cling::Interpreter::kSuccess: *error = kNoError; break;
2689 case cling::Interpreter::kFailure: *error = kRecoverable; break;
2690 case cling::Interpreter::kMoreInputExpected: *error = kProcessing; break;
2691 }
2692 }
2693 if (compRes == cling::Interpreter::kSuccess
2694 && result.isValid()
2695 && !result.isVoid())
2696 {
2697 return result.castAs<Longptr_t>();
2698 }
2699 return 0;
2700}
2701
2702////////////////////////////////////////////////////////////////////////////////
2703/// No-op; see TRint instead.
2704
2706{
2707}
2708
2709////////////////////////////////////////////////////////////////////////////////
2710/// \brief Add a directory to the list of directories in which the
2711/// interpreter looks for include files.
2712/// \param[in] path The path to the directory.
2713/// \note Only one path item can be specified at a time, i.e. "path1:path2" is
2714/// \b NOT supported.
2715/// \warning Only the path to the directory should be specified, without
2716/// prepending the \c -I prefix, i.e.
2717/// <tt>gCling->AddIncludePath("/path/to/my/includes")</tt>. If the
2718/// \c -I prefix is used it will be ignored.
2719void TCling::AddIncludePath(const char *path)
2720{
2722 // Favorite source of annoyance: gSystem->AddIncludePath() needs "-I",
2723 // gCling->AddIncludePath() does not! Work around that inconsistency:
2724 if (path[0] == '-' && path[1] == 'I')
2725 path += 2;
2726 TString sPath(path);
2728#ifdef _MSC_VER
2729 if (sPath.BeginsWith("/")) {
2730 char drive[3];
2731 snprintf(drive, 3, "%c:", _getdrive() + 'A' - 1);
2732 sPath.Prepend(drive);
2733 }
2734#endif
2735 fInterpreter->AddIncludePath(sPath.Data());
2736}
2737
2738////////////////////////////////////////////////////////////////////////////////
2739/// Visit all members over members, recursing over base classes.
2740
2742 const TClass* cl, Bool_t isTransient)
2743{
2744 if (insp.GetObjectValidity() == TMemberInspector::kUnset) {
2745 insp.SetObjectValidity(obj ? TMemberInspector::kValidObjectGiven
2747 }
2748
2749 if (!cl || cl->GetCollectionProxy()) {
2750 // We do not need to investigate the content of the STL
2751 // collection, they are opaque to us (and details are
2752 // uninteresting).
2753 return;
2754 }
2755
2756 static const TClassRef clRefString("std::string");
2757 if (clRefString == cl) {
2758 // We stream std::string without going through members..
2759 return;
2760 }
2761
2762 if (TClassEdit::IsStdArray(cl->GetName())) {
2763 // We treat std arrays as C arrays
2764 return;
2765 }
2766
2767 const char* cobj = (const char*) obj; // for ptr arithmetics
2768
2769 // Treat the case of std::complex in a special manner. We want to enforce
2770 // the layout of a stl implementation independent class, which is the
2771 // complex as implemented in ROOT5.
2772
2773 // A simple lambda to simplify the code
2774 auto inspInspect = [&] (ptrdiff_t offset){
2775 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_real", cobj, isTransient);
2776 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_imag", cobj + offset, isTransient);
2777 };
2778
2780 switch(complexType) {
2782 {
2783 break;
2784 }
2786 {
2787 inspInspect(sizeof(float));
2788 return;
2789 }
2791 {
2792 inspInspect(sizeof(double));
2793 return;
2794 }
2796 {
2797 inspInspect(sizeof(int));
2798 return;
2799 }
2801 {
2802 inspInspect(sizeof(long));
2803 return;
2804 }
2805 }
2806
2807 static clang::PrintingPolicy
2808 printPol(fInterpreter->getCI()->getLangOpts());
2809 if (printPol.Indentation) {
2810 // not yet initialized
2811 printPol.Indentation = 0;
2812 printPol.SuppressInitializers = true;
2813 }
2814
2815 const char* clname = cl->GetName();
2816 // Printf("Inspecting class %s\n", clname);
2817
2818 const clang::ASTContext& astContext = fInterpreter->getCI()->getASTContext();
2819 const clang::Decl *scopeDecl = nullptr;
2820 const clang::Type *recordType = nullptr;
2821
2822 if (cl->GetClassInfo()) {
2824 scopeDecl = clingCI->GetDecl();
2825 recordType = clingCI->GetType();
2826 } else {
2827 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
2828 // Diags will complain about private classes:
2829 scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2830 &recordType);
2831 }
2832 if (!scopeDecl) {
2833 Error("InspectMembers", "Cannot find Decl for class %s", clname);
2834 return;
2835 }
2836 const clang::CXXRecordDecl* recordDecl
2837 = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2838 if (!recordDecl) {
2839 Error("InspectMembers", "Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2840 return;
2841 }
2842
2843 {
2844 // Force possible deserializations first. We need to have no pending
2845 // Transaction when passing control flow to the inspector below (ROOT-7779).
2846 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2847
2848 astContext.getASTRecordLayout(recordDecl);
2849
2850 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2851 eField = recordDecl->field_end(); iField != eField; ++iField) {}
2852 }
2853
2854 const clang::ASTRecordLayout& recLayout
2855 = astContext.getASTRecordLayout(recordDecl);
2856
2857 // TVirtualCollectionProxy *proxy = cl->GetCollectionProxy();
2858 // if (proxy && ( proxy->GetProperties() & TVirtualCollectionProxy::kIsEmulated ) ) {
2859 // Error("InspectMembers","The TClass for %s has an emulated proxy but we are looking at a compiled version of the collection!\n",
2860 // cl->GetName());
2861 // }
2862 if (cl->Size() != recLayout.getSize().getQuantity()) {
2863 Error("InspectMembers","TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2864 cl->GetName(),cl->Size(),(Long64_t)recLayout.getSize().getQuantity());
2865 }
2866
2867 unsigned iNField = 0;
2868 // iterate over fields
2869 // FieldDecls are non-static, else it would be a VarDecl.
2870 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2871 eField = recordDecl->field_end(); iField != eField;
2872 ++iField, ++iNField) {
2873
2874
2875 clang::QualType memberQT = iField->getType();
2876 if (recordType) {
2877 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2879 }
2880 memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2881 if (memberQT.isNull()) {
2882 std::string memberName;
2883 llvm::raw_string_ostream stream(memberName);
2884 // Don't trigger fopen of the source file to count lines:
2885 printPol.AnonymousTagLocations = false;
2886 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2887 stream.flush();
2888 Error("InspectMembers",
2889 "Cannot retrieve QualType for member %s while inspecting class %s",
2890 memberName.c_str(), clname);
2891 continue; // skip member
2892 }
2893 const clang::Type* memType = memberQT.getTypePtr();
2894 if (!memType) {
2895 std::string memberName;
2896 llvm::raw_string_ostream stream(memberName);
2897 // Don't trigger fopen of the source file to count lines:
2898 printPol.AnonymousTagLocations = false;
2899 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2900 stream.flush();
2901 Error("InspectMembers",
2902 "Cannot retrieve Type for member %s while inspecting class %s",
2903 memberName.c_str(), clname);
2904 continue; // skip member
2905 }
2906
2907 const clang::Type* memNonPtrType = memType;
2908 Bool_t ispointer = false;
2909 if (memNonPtrType->isPointerType()) {
2910 ispointer = true;
2911 clang::QualType ptrQT
2912 = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2913 if (recordType) {
2914 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2916 }
2917 ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2918 if (ptrQT.isNull()) {
2919 std::string memberName;
2920 llvm::raw_string_ostream stream(memberName);
2921 // Don't trigger fopen of the source file to count lines:
2922 printPol.AnonymousTagLocations = false;
2923 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2924 stream.flush();
2925 Error("InspectMembers",
2926 "Cannot retrieve pointee Type for member %s while inspecting class %s",
2927 memberName.c_str(), clname);
2928 continue; // skip member
2929 }
2930 memNonPtrType = ptrQT.getTypePtr();
2931 }
2932
2933 // assemble array size(s): "[12][4][]"
2934 llvm::SmallString<8> arraySize;
2935 const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2936 unsigned arrLevel = 0;
2937 bool haveErrorDueToArray = false;
2938 while (arrType) {
2939 ++arrLevel;
2940 arraySize += '[';
2941 const clang::ConstantArrayType* constArrType =
2942 clang::dyn_cast<clang::ConstantArrayType>(arrType);
2943 if (constArrType) {
2944 constArrType->getSize().toStringUnsigned(arraySize);
2945 }
2946 arraySize += ']';
2947 clang::QualType subArrQT = arrType->getElementType();
2948 if (subArrQT.isNull()) {
2949 std::string memberName;
2950 llvm::raw_string_ostream stream(memberName);
2951 // Don't trigger fopen of the source file to count lines:
2952 printPol.AnonymousTagLocations = false;
2953 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2954 stream.flush();
2955 Error("InspectMembers",
2956 "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2957 arrLevel, subArrQT.getAsString(printPol).c_str(),
2958 memberName.c_str(), clname);
2959 haveErrorDueToArray = true;
2960 break;
2961 }
2962 arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2963 }
2964 if (haveErrorDueToArray) {
2965 continue; // skip member
2966 }
2967
2968 // construct member name
2969 std::string fieldName;
2970 if (memType->isPointerType()) {
2971 fieldName = "*";
2972 }
2973
2974 // Check if this field has a custom ioname, if not, just use the one of the decl
2975 std::string ioname(iField->getName());
2977 fieldName += ioname;
2978 fieldName += arraySize;
2979
2980 // get member offset
2981 // NOTE currently we do not support bitfield and do not support
2982 // member that are not aligned on 'bit' boundaries.
2983 clang::CharUnits offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2984 ptrdiff_t fieldOffset = offset.getQuantity();
2985
2986 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fBits[2]", fBits);
2987 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fName", &fName);
2988 // R__insp.InspectMember(fName, "fName.");
2989 // R__insp.Inspect(R__cl, R__insp.GetParent(), "*fClass", &fClass);
2990
2991 // If the class has a custom streamer and the type of the filed is a
2992 // private enum, struct or class, skip it.
2993 if (!insp.IsTreatingNonAccessibleTypes()){
2994 auto iFiledQtype = iField->getType();
2995 if (auto tagDecl = iFiledQtype->getAsTagDecl()){
2996 auto declAccess = tagDecl->getAccess();
2998 continue;
2999 }
3000 }
3001 }
3002
3003 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
3004
3005 if (!ispointer) {
3006 const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
3007 if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
3008 // nested objects get an extra call to InspectMember
3009 // R__insp.InspectMember("FileStat_t", (void*)&fFileStat, "fFileStat.", false);
3010 std::string sFieldRecName;
3013 clang::QualType(memNonPtrType,0),
3014 *fInterpreter,
3016 }
3017
3018 TDataMember* mbr = cl->GetDataMember(ioname.c_str());
3019 // if we can not find the member (which should not really happen),
3020 // let's consider it transient.
3021 Bool_t transient = isTransient || !mbr || !mbr->IsPersistent();
3022 if (!mbr || !mbr->IsPersistent())
3023 insp.IncrementNestedTransient();
3024 insp.InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
3025 (fieldName + '.').c_str(), transient);
3026 if (!mbr || !mbr->IsPersistent())
3027 insp.DecrementNestedTransient();
3028
3029 }
3030 }
3031 } // loop over fields
3032
3033 // inspect bases
3034 // TNamed::ShowMembers(R__insp);
3035 unsigned iNBase = 0;
3036 for (clang::CXXRecordDecl::base_class_const_iterator iBase
3037 = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
3038 iBase != eBase; ++iBase, ++iNBase) {
3039 clang::QualType baseQT = iBase->getType();
3040 if (baseQT.isNull()) {
3041 Error("InspectMembers",
3042 "Cannot find QualType for base number %d while inspecting class %s",
3043 iNBase, clname);
3044 continue;
3045 }
3046 const clang::CXXRecordDecl* baseDecl
3047 = baseQT->getAsCXXRecordDecl();
3048 if (!baseDecl) {
3049 Error("InspectMembers",
3050 "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
3051 iNBase, clname);
3052 continue;
3053 }
3054 TClass* baseCl=nullptr;
3055 std::string sBaseName;
3056 // Try with the DeclId
3057 std::vector<TClass*> foundClasses;
3059 if (foundClasses.size()==1){
3061 } else {
3062 // Try with the normalised Name, as a fallback
3063 if (!baseCl){
3065 baseQT,
3066 *fInterpreter,
3069 }
3070 }
3071
3072 if (!baseCl){
3073 std::string qualNameForDiag;
3075 Error("InspectMembers",
3076 "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
3077 continue;
3078 }
3079
3080 int64_t baseOffset;
3081 if (iBase->isVirtual()) {
3082 if (insp.GetObjectValidity() == TMemberInspector::kNoObjectGiven) {
3083 if (!isTransient) {
3084 Error("InspectMembers",
3085 "Base %s of class %s is virtual but no object provided",
3086 sBaseName.c_str(), clname);
3087 }
3089 } else {
3090 // We have an object to determine the vbase offset.
3092 TClingClassInfo* baseCi = (TClingClassInfo*)baseCl->GetClassInfo();
3093 if (ci && baseCi) {
3094 baseOffset = ci->GetBaseOffset(baseCi, const_cast<void*>(obj),
3095 true /*isDerivedObj*/);
3096 if (baseOffset == -1) {
3097 Error("InspectMembers",
3098 "Error calculating offset of virtual base %s of class %s",
3099 sBaseName.c_str(), clname);
3100 }
3101 } else {
3102 Error("InspectMembers",
3103 "Cannot calculate offset of virtual base %s of class %s",
3104 sBaseName.c_str(), clname);
3105 continue;
3106 }
3107 }
3108 } else {
3109 baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
3110 }
3111 // TOFIX: baseCl can be null here!
3112 if (baseCl->IsLoaded()) {
3113 // For loaded class, CallShowMember will (especially for TObject)
3114 // call the virtual ShowMember rather than the class specific version
3115 // resulting in an infinite recursion.
3117 } else {
3118 baseCl->CallShowMembers(cobj + baseOffset,
3119 insp, isTransient);
3120 }
3121 } // loop over bases
3122}
3123
3124////////////////////////////////////////////////////////////////////////////////
3125/// Check if constructor exited correctly, ie the instance is in a valid state
3126/// \return true if there is a compiler instance available, false otherwise
3128{
3129 return fInterpreter->getCI() != nullptr;
3130}
3131
3132////////////////////////////////////////////////////////////////////////////////
3133/// Reset the interpreter internal state in case a previous action was not correctly
3134/// terminated.
3135
3137{
3138 // No-op there is not equivalent state (to be cleared) in Cling.
3139}
3140
3141////////////////////////////////////////////////////////////////////////////////
3142/// Delete existing temporary values.
3143
3145{
3146 // No-op for cling due to cling::Value.
3147}
3148
3149////////////////////////////////////////////////////////////////////////////////
3150/// Declare code to the interpreter, without any of the interpreter actions
3151/// that could trigger a re-interpretation of the code. I.e. make cling
3152/// behave like a compiler: no dynamic lookup, no input wrapping for
3153/// subsequent execution, no automatic provision of declarations but just a
3154/// plain `#include`.
3155/// Returns true on success, false on failure.
3156
3157bool TCling::Declare(const char* code)
3158{
3160
3163
3164 bool oldDynLookup = fInterpreter->isDynamicLookupEnabled();
3165 fInterpreter->enableDynamicLookup(false);
3166 bool oldRawInput = fInterpreter->isRawInputEnabled();
3167 fInterpreter->enableRawInput(true);
3168
3169 Bool_t ret = LoadText(code);
3170
3171 fInterpreter->enableRawInput(oldRawInput);
3172 fInterpreter->enableDynamicLookup(oldDynLookup);
3173 return ret;
3174}
3175
3176////////////////////////////////////////////////////////////////////////////////
3177/// It calls a "fantom" method to synchronize user keyboard input
3178/// and ROOT prompt line.
3179
3184
3185// This static function is a hop of TCling::IsLibraryLoaded, which is taking a lock and calling
3186// into this function. This is because we wanted to avoid a duplication in TCling::IsLoaded, which
3187// was already taking a lock.
3188static Bool_t s_IsLibraryLoaded(const char* libname, cling::Interpreter* fInterpreter)
3189{
3190 // Check shared library.
3193 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.Data());
3194 return false;
3195}
3196
3202
3203////////////////////////////////////////////////////////////////////////////////
3204/// Return true if ROOT has cxxmodules pcm for a given library name.
3205// FIXME: We need to be able to support lazy loading of pcm generated by ACLiC.
3207{
3208 llvm::StringRef ModuleName(libname);
3209 ModuleName = llvm::sys::path::stem(ModuleName);
3210 ModuleName.consume_front("lib");
3211
3212 // FIXME: In case when the modulemap is not yet loaded we will return the
3213 // wrong result. Consider a call to HasPCMForLibrary(../test/libEvent.so)
3214 // We will only load the modulemap for libEvent.so after we dlopen libEvent
3215 // which may happen after calling this interface. Maybe we should also check
3216 // if there is a Event.pcm file and a module.modulemap, load it and return
3217 // true.
3218 clang::ModuleMap &moduleMap = fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
3219 clang::Module *M = moduleMap.findModule(ModuleName);
3220 return M && !M->IsUnimportable && M->getASTFile();
3221}
3222
3223////////////////////////////////////////////////////////////////////////////////
3224/// Return true if the file has already been loaded by cint.
3225/// We will try in this order:
3226/// actual filename
3227/// filename as a path relative to
3228/// the include path
3229/// the shared library path
3230
3232{
3234
3235 //FIXME: if we use llvm::sys::fs::make_absolute all this can go away. See
3236 // cling::DynamicLibraryManager.
3237
3238 std::string file_name = filename;
3239 size_t at = std::string::npos;
3240 while ((at = file_name.find("/./")) != std::string::npos)
3241 file_name.replace(at, 3, "/");
3242
3243 std::string filesStr = "";
3244 llvm::raw_string_ostream filesOS(filesStr);
3245 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3246 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3247 filesOS.flush();
3248
3249 llvm::SmallVector<llvm::StringRef, 100> files;
3250 llvm::StringRef(filesStr).split(files, "\n");
3251
3252 std::set<std::string> fileMap;
3253 llvm::StringRef file_name_ref(file_name);
3254 // Fill fileMap; return early on exact match.
3256 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3257 if ((*iF) == file_name_ref) return kTRUE; // exact match
3258 fileMap.insert(iF->str());
3259 }
3260
3261 if (fileMap.empty()) return kFALSE;
3262
3263 // Check MacroPath.
3264 TString sFilename(file_name.c_str());
3266 && fileMap.count(sFilename.Data())) {
3267 return kTRUE;
3268 }
3269
3270 // Check IncludePath.
3271 TString incPath = gSystem->GetIncludePath(); // of the form -Idir1 -Idir2 -Idir3
3272 incPath.Append(":").Prepend(" "); // to match " -I" (note leading ' ')
3273 incPath.ReplaceAll(" -I", ":"); // of form :dir1 :dir2:dir3
3274 while (incPath.Index(" :") != -1) {
3275 incPath.ReplaceAll(" :", ":");
3276 }
3277 incPath.Prepend(".:");
3278 sFilename = file_name.c_str();
3280 && fileMap.count(sFilename.Data())) {
3281 return kTRUE;
3282 }
3283
3284 // Check shared library.
3285 if (s_IsLibraryLoaded(file_name.c_str(), GetInterpreterImpl()))
3286 return kTRUE;
3287
3288 //FIXME: We must use the cling::Interpreter::lookupFileOrLibrary iface.
3289 clang::ConstSearchDirIterator *CurDir = nullptr;
3290 clang::Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
3291 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3292 auto FE = HS.LookupFile(file_name.c_str(),
3293 clang::SourceLocation(),
3294 /*isAngled*/ false,
3295 /*FromDir*/ nullptr, CurDir,
3296 clang::ArrayRef<std::pair<clang::OptionalFileEntryRef,
3297 clang::DirectoryEntryRef>>(),
3298 /*SearchPath*/ nullptr,
3299 /*RelativePath*/ nullptr,
3300 /*RequestingModule*/ nullptr,
3301 /*SuggestedModule*/ nullptr,
3302 /*IsMapped*/ nullptr,
3303 /*IsFrameworkFound*/ nullptr,
3304 /*SkipCache*/ false,
3305 /*BuildSystemModule*/ false,
3306 /*OpenFile*/ false,
3307 /*CacheFail*/ false);
3308 if (FE) {
3309 // check in the source manager if the file is actually loaded
3310 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3311 // this works only with header (and source) files...
3312 clang::FileID FID = SM.translateFile(*FE);
3313 if (!FID.isInvalid() && FID.getHashValue() == 0)
3314 return kFALSE;
3315 else {
3316 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3317 if (SLocE.isFile() && !SLocE.getFile().getContentCache().getBufferIfLoaded())
3318 return kFALSE;
3319 if (!FID.isInvalid())
3320 return kTRUE;
3321 }
3322 // ...then check shared library again, but with full path now
3323 sFilename = FE->getName().str();
3325 && fileMap.count(sFilename.Data())) {
3326 return kTRUE;
3327 }
3328 }
3329 return kFALSE;
3330}
3331
3332
3333#if defined(R__MACOSX)
3334
3335////////////////////////////////////////////////////////////////////////////////
3336/// Check if lib is in the dynamic linker cache, returns true if it is, and if so,
3337/// modifies the library file name parameter `lib` from `/usr/lib/libFOO.dylib`
3338/// to `-lFOO` such that it can be passed to the linker.
3339/// This is a unique feature of macOS 11.
3340
3341static bool R__UpdateLibFileForLinking(TString &lib)
3342{
3343 const char *mapfile = nullptr;
3344#if __x86_64__
3345 mapfile = "/System/Library/dyld/dyld_shared_cache_x86_64.map";
3346#elif __arm64__
3347 mapfile = "/System/Library/dyld/dyld_shared_cache_arm64e.map";
3348#else
3349 #error unsupported architecture
3350#endif
3351 if (std::ifstream cacheMap{mapfile}) {
3352 std::string line;
3353 while (getline(cacheMap, line)) {
3354 if (line.find(lib) != std::string::npos) {
3355 lib.ReplaceAll("/usr/lib/lib","-l");
3356 lib.ReplaceAll(".dylib","");
3357 return true;
3358 }
3359 }
3360 return false;
3361 }
3362 return false;
3363}
3364#endif // R__MACOSX
3365
3366#if defined (R__LINUX) || defined (R__FBSD)
3367
3368////////////////////////////////////////////////////////////////////////////////
3369/// Callback for dl_iterate_phdr(), see `man dl_iterate_phdr`.
3370/// Collects opened libraries.
3371
3372static int callback_for_dl_iterate_phdr(struct dl_phdr_info *info, size_t size, void *data)
3373{
3374 // This function is called through UpdateListOfLoadedSharedLibraries() which is locked.
3375 static std::unordered_set<decltype(info->dlpi_addr)> sKnownLoadedLibBaseAddrs;
3376
3377 auto newLibs = static_cast<std::vector<std::string>*>(data);
3378 if (!sKnownLoadedLibBaseAddrs.count(info->dlpi_addr)) {
3379 // Skip \0, "", and kernel pseudo-libs linux-vdso.so.1 or linux-gate.so.1
3380 if (info->dlpi_name && info->dlpi_name[0]
3381#if defined(R__FBSD)
3382 //skip the executable (with null addr)
3383 && info->dlpi_addr
3384 //has no path
3385 && strncmp(info->dlpi_name, "[vdso]", 6)
3386 //the linker does not like to be mmapped
3387 //causes a crash in cling::DynamicLibraryManager::loadLibrary())
3388 //with error message "mmap of entire address space failed: Cannot allocate memory"
3389 && strncmp(info->dlpi_name, "/libexec/ld-elf.so.1", 20)
3390#endif
3391 && strncmp(info->dlpi_name, "linux-vdso.so", 13)
3392 && strncmp(info->dlpi_name, "linux-vdso32.so", 15)
3393 && strncmp(info->dlpi_name, "linux-vdso64.so", 15)
3394 && strncmp(info->dlpi_name, "linux-gate.so", 13))
3395 newLibs->emplace_back(info->dlpi_name);
3396 sKnownLoadedLibBaseAddrs.insert(info->dlpi_addr);
3397 }
3398 // No matter what the doc says, return != 0 means "stop the iteration".
3399 return 0;
3400}
3401
3402#endif // R__LINUX || R__FBSD
3403
3404
3405////////////////////////////////////////////////////////////////////////////////
3406
3408{
3409#if defined(R__WIN32) || defined(__CYGWIN__)
3410 HMODULE hModules[1024];
3411 void *hProcess;
3412 unsigned long cbModules;
3413 unsigned int i;
3414 hProcess = (void *)::GetCurrentProcess();
3416 // start at 1 to skip the executable itself
3417 for (i = 1; i < (cbModules / sizeof(void *)); i++) {
3418 static const int bufsize = 260;
3419 wchar_t winname[bufsize];
3420 char posixname[bufsize];
3422#if defined(__CYGWIN__)
3424#else
3425 std::wstring wpath = winname;
3426 std::replace(wpath.begin(), wpath.end(), '\\', '/');
3427 string path(wpath.begin(), wpath.end());
3428 strncpy(posixname, path.c_str(), bufsize);
3429#endif
3432 }
3433 }
3434#elif defined(R__MACOSX)
3435 // fPrevLoadedDynLibInfo stores the *next* image index to look at
3436 uint32_t imageIndex = (uint32_t) (size_t) fPrevLoadedDynLibInfo;
3437
3439 // Skip non-dylibs
3440 if (mh->filetype == MH_DYLIB) {
3441 if (const char* imageName = _dyld_get_image_name(imageIndex)) {
3443 }
3444 }
3445
3446 ++imageIndex;
3447 }
3448 fPrevLoadedDynLibInfo = (void*)(size_t)imageIndex;
3449#elif defined(R__LINUX) || defined(R__FBSD)
3450 // fPrevLoadedDynLibInfo is unused on Linux.
3451 (void) fPrevLoadedDynLibInfo;
3452
3453 std::vector<std::string> newLibs;
3455 for (auto &&lib: newLibs)
3456 RegisterLoadedSharedLibrary(lib.c_str());
3457#else
3458 Error("TCling::UpdateListOfLoadedSharedLibraries",
3459 "Platform not supported!");
3460#endif
3461}
3462
3463namespace {
3464template <int N>
3465static bool StartsWithStrLit(const char *haystack, const char (&needle)[N]) {
3466 return !strncmp(haystack, needle, N - 1);
3467}
3468}
3469
3470////////////////////////////////////////////////////////////////////////////////
3471/// Register a new shared library name with the interpreter; add it to
3472/// fSharedLibs.
3473
3475{
3476 // Ignore NULL filenames, aka "the process".
3477 if (!filename) return;
3478
3479 // Tell the interpreter that this library is available; all libraries can be
3480 // used to resolve symbols.
3481 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3482 if (!DLM->isLibraryLoaded(filename)) {
3483 DLM->loadLibrary(filename, true /*permanent*/, true /*resolved*/);
3484 }
3485
3486#if defined(R__MACOSX)
3487 // Check that this is not a system library that does not exist on disk.
3488 auto lenFilename = strlen(filename);
3489 auto isInMacOSSystemDir = [](const char *fn) {
3490 return StartsWithStrLit(fn, "/usr/lib/") || StartsWithStrLit(fn, "/System/Library/");
3491 };
3492 if (!strcmp(filename, "cl_kernels") // yepp, no directory
3493
3494 // These we should not link with (e.g. because they forward to .tbd):
3495 || StartsWithStrLit(filename, "/usr/lib/system/")
3496 || StartsWithStrLit(filename, "/usr/lib/libc++")
3497 || StartsWithStrLit(filename, "/System/Library/Frameworks/")
3498 || StartsWithStrLit(filename, "/System/Library/PrivateFrameworks/")
3499 || StartsWithStrLit(filename, "/System/Library/CoreServices/")
3500 || StartsWithStrLit(filename, "/usr/lib/libSystem")
3501 || StartsWithStrLit(filename, "/usr/lib/libstdc++")
3502 || StartsWithStrLit(filename, "/usr/lib/libicucore")
3503 || StartsWithStrLit(filename, "/usr/lib/libbsm")
3504 || StartsWithStrLit(filename, "/usr/lib/libobjc")
3505 || StartsWithStrLit(filename, "/usr/lib/libresolv")
3506 || StartsWithStrLit(filename, "/usr/lib/libauto")
3507 || StartsWithStrLit(filename, "/usr/lib/libcups")
3508 || StartsWithStrLit(filename, "/usr/lib/libDiagnosticMessagesClient")
3509 || StartsWithStrLit(filename, "/usr/lib/liblangid")
3510 || StartsWithStrLit(filename, "/usr/lib/libCRFSuite")
3511 || StartsWithStrLit(filename, "/usr/lib/libpam")
3512 || StartsWithStrLit(filename, "/usr/lib/libOpenScriptingUtil")
3513 || StartsWithStrLit(filename, "/usr/lib/libextension")
3514 || StartsWithStrLit(filename, "/usr/lib/libAudioToolboxUtility")
3515 || StartsWithStrLit(filename, "/usr/lib/liboah")
3516 || StartsWithStrLit(filename, "/usr/lib/libRosetta")
3517 || StartsWithStrLit(filename, "/usr/lib/libCoreEntitlements")
3518 || StartsWithStrLit(filename, "/usr/lib/libssl.")
3519 || StartsWithStrLit(filename, "/usr/lib/libcrypto.")
3520
3521 // The system lib is likely in macOS's blob.
3523
3524 // "Link against the umbrella framework 'System.framework' instead"
3525 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_kernel")
3526 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_platform")
3527 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_pthread")
3528
3529 // "cannot link directly with dylib/framework, your binary is not an allowed client of
3530 // /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/
3531 // SDKs/MacOSX.sdk/usr/lib/libAudioToolboxUtility.tbd for architecture x86_64
3532 || (lenFilename > 4 && !strcmp(filename + lenFilename - 4, ".tbd")))
3533 return;
3536 filename = sFileName.Data();
3537#elif defined(__CYGWIN__)
3538 // Check that this is not a system library
3539 static const int bufsize = 260;
3540 char posixwindir[bufsize];
3541 char *windir = std::getenv("WINDIR");
3542 if (windir)
3544 else
3545 snprintf(posixwindir, sizeof(posixwindir), "/Windows/");
3546 if (strstr(filename, posixwindir) ||
3547 strstr(filename, "/usr/bin/cyg"))
3548 return;
3549#elif defined(R__WIN32)
3550 if (strstr(filename, "/Windows/"))
3551 return;
3552#elif defined (R__LINUX)
3553 if (strstr(filename, "/ld-linux")
3554 || strstr(filename, "linux-gnu/")
3555 || strstr(filename, "/libstdc++.")
3556 || strstr(filename, "/libgcc")
3557 || strstr(filename, "/libc.")
3558 || strstr(filename, "/libdl.")
3559 || strstr(filename, "/libm."))
3560 return;
3561#endif
3562 // Update string of available libraries.
3563 if (!fSharedLibs.IsNull()) {
3564 fSharedLibs.Append(" ");
3565 }
3567}
3568
3569////////////////////////////////////////////////////////////////////////////////
3570/// Load a library file in cling's memory.
3571/// if 'system' is true, the library is never unloaded.
3572/// Return 0 on success, -1 on failure.
3573
3575{
3576 assert(!IsFromRootCling() && "Trying to load library from rootcling!");
3577
3578 // Used to return 0 on success, 1 on duplicate, -1 on failure, -2 on "fatal".
3580 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3581 std::string canonLib = DLM->lookupLibrary(filename);
3582 cling::DynamicLibraryManager::LoadLibResult res
3583 = cling::DynamicLibraryManager::kLoadLibNotFound;
3584 if (!canonLib.empty()) {
3585 if (system)
3586 res = DLM->loadLibrary(filename, system, true);
3587 else {
3588 // For the non system libs, we'd like to be able to unload them.
3589 // FIXME: Here we lose the information about kLoadLibAlreadyLoaded case.
3590 cling::Interpreter::CompilationResult compRes;
3591 HandleInterpreterException(GetMetaProcessorImpl(), Form(".L %s", canonLib.c_str()), compRes, /*cling::Value*/nullptr);
3592 if (compRes == cling::Interpreter::kSuccess)
3593 res = cling::DynamicLibraryManager::kLoadLibSuccess;
3594 }
3595 }
3596
3597 if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3599 }
3600 switch (res) {
3601 case cling::DynamicLibraryManager::kLoadLibSuccess: return 0;
3602 case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded: return 1;
3603 default: break;
3604 };
3605 return -1;
3606}
3607
3608////////////////////////////////////////////////////////////////////////////////
3609/// Load a macro file in cling's memory.
3610
3611void TCling::LoadMacro(const char* filename, EErrorCode* error)
3612{
3613 ProcessLine(Form(".L %s", filename), error);
3614}
3615
3616////////////////////////////////////////////////////////////////////////////////
3617/// Let cling process a command line asynch.
3618
3620{
3621 return ProcessLine(line, error);
3622}
3623
3624////////////////////////////////////////////////////////////////////////////////
3625/// Let cling process a command line synchronously, i.e we are waiting
3626/// it will be finished.
3627
3629{
3631 if (gApplication) {
3632 if (gApplication->IsCmdThread()) {
3633 return ProcessLine(line, error);
3634 }
3635 return 0;
3636 }
3637 return ProcessLine(line, error);
3638}
3639
3640////////////////////////////////////////////////////////////////////////////////
3641/// Directly execute an executable statement (e.g. "func()", "3+5", etc.
3642/// however not declarations, like "Int_t x;").
3643
3645{
3646#ifdef R__WIN32
3647 // Test on ApplicationImp not being 0 is needed because only at end of
3648 // TApplication ctor the IsLineProcessing flag is set to 0, so before
3649 // we can not use it.
3651 while (gROOT->IsLineProcessing() && !gApplication) {
3652 Warning("Calc", "waiting for cling thread to free");
3653 gSystem->Sleep(500);
3654 }
3655 gROOT->SetLineIsProcessing();
3656 }
3657#endif // R__WIN32
3659 if (error) {
3660 *error = TInterpreter::kNoError;
3661 }
3662 cling::Value valRef;
3663 cling::Interpreter::CompilationResult cr = cling::Interpreter::kFailure;
3664 try {
3665 cr = fInterpreter->evaluate(line, valRef);
3666 }
3667 catch (cling::InterpreterException& ex)
3668 {
3669 Error("Calc", "%s.\n%s", ex.what(), "Evaluation of your expression was aborted.");
3670 ex.diagnose();
3671 cr = cling::Interpreter::kFailure;
3672 }
3673
3674 if (cr != cling::Interpreter::kSuccess) {
3675 // Failure in compilation.
3676 if (error) {
3677 // Note: Yes these codes are weird.
3679 }
3680 return 0L;
3681 }
3682 if (!valRef.isValid()) {
3683 // Failure at runtime.
3684 if (error) {
3685 // Note: Yes these codes are weird.
3686 *error = TInterpreter::kDangerous;
3687 }
3688 return 0L;
3689 }
3690
3691 if (valRef.isVoid()) {
3692 return 0;
3693 }
3694
3696#ifdef R__WIN32
3698 gROOT->SetLineHasBeenProcessed();
3699 }
3700#endif // R__WIN32
3701 return valRef.castAs<Longptr_t>();
3702}
3703
3704////////////////////////////////////////////////////////////////////////////////
3705/// Set a getline function to call when input is needed.
3706
3707void TCling::SetGetline(const char * (*getlineFunc)(const char* prompt),
3708 void (*histaddFunc)(const char* line))
3709{
3710 // If cling offers a replacement for G__pause(), it would need to
3711 // also offer a way to customize at least the history recording.
3712
3713#if defined(R__MUST_REVISIT)
3714#if R__MUST_REVISIT(6,2)
3715 Warning("SetGetline","Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3716#endif
3717#endif
3718}
3719
3720////////////////////////////////////////////////////////////////////////////////
3721/// Helper function to increase the internal Cling count of transactions
3722/// that change the AST.
3723
3724Bool_t TCling::HandleNewTransaction(const cling::Transaction &T)
3725{
3727
3728 if ((std::distance(T.decls_begin(), T.decls_end()) != 1)
3729 || T.deserialized_decls_begin() != T.deserialized_decls_end()
3730 || T.macros_begin() != T.macros_end()
3731 || ((!T.getFirstDecl().isNull()) && ((*T.getFirstDecl().begin()) != T.getWrapperFD()))) {
3733 return true;
3734 }
3735 return false;
3736}
3737
3738////////////////////////////////////////////////////////////////////////////////
3739/// Delete object from cling symbol table so it can not be used anymore.
3740/// cling objects are always on the heap.
3741
3743{
3744 // NOTE: When replacing the mutex by a ReadWrite mutex, we **must**
3745 // put in place the Read/Write part here. Keeping the write lock
3746 // here is 'catasptrophic' for scaling as it means that ALL calls
3747 // to RecursiveRemove will take the write lock and performance
3748 // of many threads trying to access the write lock at the same
3749 // time is relatively bad.
3751 // Note that fgSetOfSpecials is supposed to be updated by TClingCallbacks::tryFindROOTSpecialInternal
3752 // (but isn't at the moment).
3753 if (obj->IsOnHeap() && fgSetOfSpecials && !((std::set<TObject*>*)fgSetOfSpecials)->empty()) {
3754 std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)fgSetOfSpecials)->find(obj);
3755 if (iSpecial != ((std::set<TObject*>*)fgSetOfSpecials)->end()) {
3757 DeleteGlobal(obj);
3758 ((std::set<TObject*>*)fgSetOfSpecials)->erase(iSpecial);
3759 }
3760 }
3761}
3762
3763////////////////////////////////////////////////////////////////////////////////
3764/// Pressing Ctrl+C should forward here. In the case where we have had
3765/// continuation requested we must reset it.
3766
3768{
3769 fMetaProcessor->cancelContinuation();
3770 // Reset the Cling state to the state saved by the last call to
3771 // TCling::SaveContext().
3772#if defined(R__MUST_REVISIT)
3773#if R__MUST_REVISIT(6,2)
3775 Warning("Reset","Cling should support the equivalent of scratch_upto(&fDictPos)");
3776#endif
3777#endif
3778}
3779
3780////////////////////////////////////////////////////////////////////////////////
3781/// Reset the Cling state to its initial state.
3782
3784{
3785#if defined(R__MUST_REVISIT)
3786#if R__MUST_REVISIT(6,2)
3788 Warning("ResetAll","Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3789#endif
3790#endif
3791}
3792
3793////////////////////////////////////////////////////////////////////////////////
3794/// Reset in Cling the list of global variables to the state saved by the last
3795/// call to TCling::SaveGlobalsContext().
3796///
3797/// Note: Right now, all we do is run the global destructors.
3798
3800{
3802 // TODO:
3803 // Here we should iterate over the transactions (N-3) and revert.
3804 // N-3 because the first three internal to cling.
3805
3806 fInterpreter->runAndRemoveStaticDestructors();
3807}
3808
3809////////////////////////////////////////////////////////////////////////////////
3810/// Reset the Cling 'user' global objects/variables state to the state saved by the last
3811/// call to TCling::SaveGlobalsContext().
3812
3814{
3815#if defined(R__MUST_REVISIT)
3816#if R__MUST_REVISIT(6,2)
3818 Warning("ResetGlobalVar","Cling should support the equivalent of resetglobalvar(obj)");
3819#endif
3820#endif
3821}
3822
3823////////////////////////////////////////////////////////////////////////////////
3824/// Rewind Cling dictionary to the point where it was before executing
3825/// the current macro. This function is typically called after SEGV or
3826/// ctlr-C after doing a longjmp back to the prompt.
3827
3829{
3830#if defined(R__MUST_REVISIT)
3831#if R__MUST_REVISIT(6,2)
3833 Warning("RewindDictionary","Cling should provide a way to revert transaction similar to rewinddictionary()");
3834#endif
3835#endif
3836}
3837
3838////////////////////////////////////////////////////////////////////////////////
3839/// Delete obj from Cling symbol table so it cannot be accessed anymore.
3840/// Returns 1 in case of success and 0 in case object was not in table.
3841
3843{
3844#if defined(R__MUST_REVISIT)
3845#if R__MUST_REVISIT(6,2)
3847 Warning("DeleteGlobal","Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3848#endif
3849#endif
3850 return 0;
3851}
3852
3853////////////////////////////////////////////////////////////////////////////////
3854/// Undeclare obj called name.
3855/// Returns 1 in case of success, 0 for failure.
3856
3858{
3859#if defined(R__MUST_REVISIT)
3860#if R__MUST_REVISIT(6,2)
3861 Warning("DeleteVariable","should do more that just reseting the value to zero");
3862#endif
3863#endif
3864
3866 llvm::StringRef srName(name);
3867 const char* unscopedName = name;
3868 llvm::StringRef::size_type posScope = srName.rfind("::");
3869 const clang::DeclContext* declCtx = nullptr;
3870 if (posScope != llvm::StringRef::npos) {
3871 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3872 const clang::Decl* scopeDecl
3873 = lh.findScope(srName.substr(0, posScope),
3874 cling::LookupHelper::WithDiagnostics);
3875 if (!scopeDecl) {
3876 Error("DeleteVariable", "Cannot find enclosing scope for variable %s",
3877 name);
3878 return 0;
3879 }
3880 declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3881 if (!declCtx) {
3882 Error("DeleteVariable",
3883 "Enclosing scope for variable %s is not a declaration context",
3884 name);
3885 return 0;
3886 }
3887 unscopedName += posScope + 2;
3888 }
3889 // Could trigger deserialization of decls.
3890 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
3891 clang::NamedDecl* nVarDecl
3892 = cling::utils::Lookup::Named(&fInterpreter->getSema(), unscopedName, declCtx);
3893 if (!nVarDecl) {
3894 Error("DeleteVariable", "Unknown variable %s", name);
3895 return 0;
3896 }
3897 clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3898 if (!varDecl) {
3899 Error("DeleteVariable", "Entity %s is not a variable", name);
3900 return 0;
3901 }
3902
3903 clang::QualType qType = varDecl->getType();
3904 const clang::Type* type = qType->getUnqualifiedDesugaredType();
3905 // Cannot set a reference's address to nullptr; the JIT can place it
3906 // into read-only memory (ROOT-7100).
3907 if (type->isPointerType()) {
3908 int** ppInt = (int**)fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3909 // set pointer to invalid.
3910 if (ppInt) *ppInt = nullptr;
3911 }
3912 return 1;
3913}
3914
3915////////////////////////////////////////////////////////////////////////////////
3916/// Save the current Cling state.
3917
3919{
3920#if defined(R__MUST_REVISIT)
3921#if R__MUST_REVISIT(6,2)
3923 Warning("SaveContext","Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3924#endif
3925#endif
3926}
3927
3928////////////////////////////////////////////////////////////////////////////////
3929/// Save the current Cling state of global objects.
3930
3932{
3933#if defined(R__MUST_REVISIT)
3934#if R__MUST_REVISIT(6,2)
3936 Warning("SaveGlobalsContext","Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3937#endif
3938#endif
3939}
3940
3941////////////////////////////////////////////////////////////////////////////////
3942/// No op: see TClingCallbacks (used to update the list of globals)
3943
3947
3948////////////////////////////////////////////////////////////////////////////////
3949/// No op: see TClingCallbacks (used to update the list of global functions)
3950
3954
3955////////////////////////////////////////////////////////////////////////////////
3956/// No op: see TClingCallbacks (used to update the list of types)
3957
3959{
3960}
3961
3962////////////////////////////////////////////////////////////////////////////////
3963/// Check in what order the member of a tuple are layout.
3964enum class ETupleOrdering {
3965 kAscending,
3968};
3969
3975
3981
3983{
3984 std::tuple<int,double> value;
3987
3988 size_t offset0 = ((char*)&(std::get<0>(value))) - ((char*)&value);
3989 size_t offset1 = ((char*)&(std::get<1>(value))) - ((char*)&value);
3990
3991 size_t ascOffset0 = ((char*)&(asc._0)) - ((char*)&asc);
3992 size_t ascOffset1 = ((char*)&(asc._1)) - ((char*)&asc);
3993
3994 size_t desOffset0 = ((char*)&(des._0)) - ((char*)&des);
3995 size_t desOffset1 = ((char*)&(des._1)) - ((char*)&des);
3996
3997 if (offset0 == ascOffset0 && offset1 == ascOffset1) {
3999 } else if (offset0 == desOffset0 && offset1 == desOffset1) {
4001 } else {
4003 }
4004}
4005
4006static std::string AlternateTuple(const char *classname, const cling::LookupHelper& lh, Bool_t silent)
4007{
4009 std::string alternateName = "TEmulatedTuple";
4010 alternateName.append( classname + 5 );
4011
4012 std::string fullname = "ROOT::Internal::" + alternateName;
4013 if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
4014 /*resultType*/nullptr, /* intantiateTemplate= */ false))
4015 return fullname;
4016
4017 {
4018 // Check if we can produce the tuple
4019 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
4020 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
4021 auto deleter = [](TypeInfo_t *type) {
4022 gInterpreter->TypeInfo_Delete(type);
4023 };
4024 std::unique_ptr<TypeInfo_t, decltype(deleter)> type{ gInterpreter->TypeInfo_Factory(), deleter };
4025 while (iter != theEnd) {
4026 gInterpreter->TypeInfo_Init(type.get(), iter->c_str());
4027 if (gInterpreter->TypeInfo_Property(type.get()) & kIsNotReacheable) {
4028 if (!silent)
4029 Error("Load","Could not declare alternate type for %s since %s (or one of its context) is private or protected",
4030 classname, iter->c_str());
4031 return "";
4032 }
4033 ++iter;
4034 }
4035 }
4036
4037 std::string guard_name;
4039 std::ostringstream guard;
4040 guard << "ROOT_INTERNAL_TEmulated_";
4041 guard << guard_name;
4042
4043 std::ostringstream alternateTuple;
4044 alternateTuple << "#ifndef " << guard.str() << "\n";
4045 alternateTuple << "#define " << guard.str() << "\n";
4046 alternateTuple << "namespace ROOT { namespace Internal {\n";
4047 alternateTuple << "template <class... Types> struct TEmulatedTuple;\n";
4048 alternateTuple << "template <> struct " << alternateName << " {\n";
4049
4050 // This could also be a compile time choice ...
4051 switch(IsTupleAscending()) {
4053 unsigned int nMember = 0;
4054 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
4055 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
4056 while (iter != theEnd) {
4057 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4058 ++iter;
4059 ++nMember;
4060 }
4061 break;
4062 }
4064 unsigned int nMember = tupleContent.fElements.size() - 3;
4065 auto iter = tupleContent.fElements.rbegin() + 1; // skip the 'stars'.
4066 auto theEnd = tupleContent.fElements.rend() - 1; // Skip the template name (tuple).
4067 while (iter != theEnd) {
4068 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4069 ++iter;
4070 --nMember;
4071 }
4072 break;
4073 }
4075 Fatal("TCling::SetClassInfo::AlternateTuple",
4076 "Layout of std::tuple on this platform is unexpected.");
4077 break;
4078 }
4079 }
4080
4081 alternateTuple << "};\n";
4082 alternateTuple << "}}\n";
4083 alternateTuple << "#endif\n";
4084 if (!gCling->Declare(alternateTuple.str().c_str()))
4085 {
4086 // Declare is not silent (yet?), so add an explicit error message
4087 // to indicate the consequence of the syntax errors.
4088 Error("Load","Could not declare %s",alternateName.c_str());
4089 return "";
4090 }
4091 alternateName = "ROOT::Internal::" + alternateName;
4092 return alternateName;
4093}
4094
4095////////////////////////////////////////////////////////////////////////////////
4096/// Set pointer to the TClingClassInfo in TClass.
4097/// If 'reload' is true, (attempt to) generate a new ClassInfo even if we
4098/// already have one.
4099
4101{
4102 // We are shutting down, there is no point in reloading, it only triggers
4103 // redundant deserializations.
4104 if (fIsShuttingDown) {
4105 // Remove the decl_id from the DeclIdToTClass map
4106 if (cl->fClassInfo) {
4109 // Test again as another thread may have set fClassInfo to nullptr.
4110 if (TClinginfo) {
4112 }
4113 delete TClinginfo;
4114 cl->fClassInfo = nullptr;
4115 }
4116 return;
4117 }
4118
4120 if (cl->fClassInfo && !reload) {
4121 return;
4122 }
4123 //Remove the decl_id from the DeclIdToTClass map
4125 if (TClinginfo) {
4127 }
4128 delete TClinginfo;
4129 cl->fClassInfo = nullptr;
4130 std::string name(cl->GetName());
4131
4132 auto SetWithoutClassInfoState = [](TClass *cl)
4133 {
4134 if (cl->fState != TClass::kHasTClassInit) {
4135 if (cl->fStreamerInfo->GetEntries() != 0) {
4137 } else {
4139 }
4140 }
4141 };
4142 // Handle the special case of 'tuple' where we ignore the real implementation
4143 // details and just overlay a 'simpler'/'simplistic' version that is easy
4144 // for the I/O to understand and handle.
4145 if (strncmp(cl->GetName(),"tuple<",std::char_traits<char>::length("tuple<"))==0) {
4146 if (!reload)
4147 name = AlternateTuple(cl->GetName(), fInterpreter->getLookupHelper(), silent);
4148 if (reload || name.empty()) {
4149 // We could not generate the alternate
4151 return;
4152 }
4153 }
4154
4156 // FIXME: Rather than adding an option to the TClingClassInfo, we should consider combining code
4157 // that is currently in the caller (like SetUnloaded) that disable AutoLoading and AutoParsing and
4158 // code is in the callee (disabling template instantiation) and end up with a more explicit class:
4159 // TClingClassInfoReadOnly.
4161 if (!info->IsValid()) {
4163 delete info;
4164 return;
4165 }
4166 cl->fClassInfo = (ClassInfo_t*)info; // Note: We are transferring ownership here.
4167 // In case a class contains an external enum, the enum will be seen as a
4168 // class. We must detect this special case and make the class a Zombie.
4169 // Here we assume that a class has at least one method.
4170 // We can NOT call TClass::Property from here, because this method
4171 // assumes that the TClass is well formed to do a lot of information
4172 // caching. The method SetClassInfo (i.e. here) is usually called during
4173 // the building phase of the TClass, hence it is NOT well formed yet.
4175 if (
4176 info->IsValid() &&
4177 !(info->Property() & (kIsClass | kIsStruct | kIsNamespace))
4178 ) {
4180 }
4181 if (!info->IsLoaded()) {
4182 if (info->Property() & (kIsNamespace)) {
4183 // Namespaces can have info but no corresponding CINT dictionary
4184 // because they are auto-created if one of their contained
4185 // classes has a dictionary.
4187 }
4188 // this happens when no dictionary is available
4189 delete info;
4190 cl->fClassInfo = nullptr;
4191 }
4192 if (zombieCandidate && !cl->GetCollectionType()) {
4193 cl->MakeZombie();
4194 }
4195 // If we reach here, the info was valid (See early returns).
4196 if (cl->fState != TClass::kHasTClassInit) {
4197 if (cl->fClassInfo) {
4199 } else {
4200// if (TClassEdit::IsSTLCont(cl->GetName()) {
4201// There will be an emulated collection proxy, is that the same?
4202// cl->fState = TClass::kEmulated;
4203// } else {
4204 if (cl->fStreamerInfo->GetEntries() != 0) {
4206 } else {
4208 }
4209// }
4210 }
4211 }
4212 if (cl->fClassInfo) {
4213 TClass::AddClassToDeclIdMap(((TClingClassInfo*)cl->fClassInfo)->GetDeclId(), cl);
4214 }
4215}
4216
4217////////////////////////////////////////////////////////////////////////////////
4218/// Checks if an entity with the specified name is defined in Cling.
4219/// Returns kUnknown if the entity is not defined.
4220/// Returns kWithClassDefInline if the entity exists and has a ClassDefInline
4221/// Returns kKnown if the entity is defined.
4222///
4223/// By default, structs, namespaces, classes, enums and unions are looked for.
4224/// If the flag isClassOrNamespaceOnly is true, classes, structs and
4225/// namespaces only are considered. I.e. if the name is an enum or a union,
4226/// the returned value is false.
4227///
4228/// In the case where the class is not loaded and belongs to a namespace
4229/// or is nested, looking for the full class name is outputting a lots of
4230/// (expected) error messages. Currently the only way to avoid this is to
4231/// specifically check that each level of nesting is already loaded.
4232/// In case of templates the idea is that everything between the outer
4233/// '<' and '>' has to be skipped, e.g.: `aap<pippo<noot>::klaas>::a_class`
4234
4237{
4239 static const char *anonEnum = "anonymous enum ";
4240 static const int cmplen = strlen(anonEnum);
4241
4242 if (fIsShuttingDown || 0 == strncmp(name, anonEnum, cmplen)) {
4243 return kUnknown;
4244 }
4245
4246 // Do not turn on the AutoLoading if it is globally off.
4248
4249 // Avoid the double search below in case the name is a fundamental type
4250 // or typedef to a fundamental type.
4251 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
4252 TDataType *fundType = (TDataType *)typeTable->THashTable::FindObject( name );
4253
4255 && fundType->GetType() > 0) {
4256 // Fundamental type, no a class.
4257 return kUnknown;
4258 }
4259
4260 // Migrated from within TClass::GetClass
4261 // If we want to know if a class or a namespace with this name exists in the
4262 // interpreter and this is an enum in the type system, before or after loading
4263 // according to the autoload function argument, return kUnknown.
4265 return kUnknown;
4266
4267 const char *classname = name;
4268
4269 // RAII to suspend and restore auto-loading and auto-parsing based on some external conditions.
4271 int fStoreAutoLoad = 0;
4272 int fStoreAutoParse = 0;
4273 bool fSuspendedAutoParse = false;
4274 public:
4276 fStoreAutoLoad = ((TCling*)gCling)->SetClassAutoLoading(autoload);
4277 }
4278
4279 void SuspendAutoParsing() {
4280 fSuspendedAutoParse = true;
4281 fStoreAutoParse = ((TCling*)gCling)->SetSuspendAutoParsing(true);
4282 }
4283
4286 ((TCling*)gCling)->SetSuspendAutoParsing(fStoreAutoParse);
4287 ((TCling*)gCling)->SetClassAutoLoading(fStoreAutoLoad);
4288 }
4289 };
4290
4292 if (TClassEdit::IsStdPair(classname) || TClassEdit::IsStdPairBase(classname))
4293 autoLoadParseRAII.SuspendAutoParsing();
4294
4295 // First we want to check whether the decl exist, but _without_
4296 // generating any template instantiation. However, the lookup
4297 // still will create a forward declaration of the class template instance
4298 // if it exist. In this case, the return value of findScope will still
4299 // be zero but the type will be initialized.
4300 // Note in the corresponding code in ROOT 5, CINT was not instantiating
4301 // this forward declaration.
4302 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4303 const clang::Type *type = nullptr;
4304 const clang::Decl *decl
4305 = lh.findScope(classname,
4306 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4307 : cling::LookupHelper::NoDiagnostics,
4308 &type, /* intantiateTemplate= */ false );
4309 if (!decl) {
4310 std::string buf = TClassEdit::InsertStd(classname);
4311 decl = lh.findScope(buf,
4312 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4313 : cling::LookupHelper::NoDiagnostics,
4314 &type,false);
4315 }
4316
4317 if (type) {
4318 // If decl==0 and the type is valid, then we have a forward declaration.
4319 if (!decl) {
4320 // If we have a forward declaration for a class template instantiation,
4321 // we want to ignore it if it was produced/induced by the call to
4322 // findScope, however we can not distinguish those from the
4323 // instantiation induce by 'soft' use (and thus also induce by the
4324 // same underlying code paths)
4325 // ['soft' use = use not requiring a complete definition]
4326 // So to reduce the amount of disruption to the existing code we
4327 // would just ignore those for STL collection, for which we really
4328 // need to have the compiled collection proxy (and thus the TClass
4329 // bootstrap).
4330 clang::ClassTemplateSpecializationDecl *tmpltDecl =
4331 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
4332 (type->getAsCXXRecordDecl());
4333 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4334 // Since the point of instantiation is invalid, we 'guess' that
4335 // the 'instantiation' of the forwarded type appended in
4336 // findscope.
4338 // For STL Collection we return kUnknown.
4339 return kUnknown;
4340 }
4341 }
4342 }
4344 if (!tci.IsValid()) {
4345 return kUnknown;
4346 }
4349
4350 if (tci.Property() & propertiesMask) {
4351 bool hasClassDefInline = false;
4353 // We do not need to check for ClassDefInline when this is called from
4354 // TClass::Init, we only do it for the call from TClass::GetClass.
4355 auto hasDictionary = tci.GetMethod("Dictionary", "", false, nullptr, ROOT::kExactMatch);
4356 auto implLineFunc = tci.GetMethod("ImplFileLine", "", false, nullptr, ROOT::kExactMatch);
4357
4358 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4359 int lineNumber = 0;
4360 bool success = false;
4361 std::tie(success, lineNumber) =
4364 }
4365 }
4366
4367 // fprintf(stderr,"CheckClassInfo: %s had dict=%d inline=%d\n",name,hasDictionary.IsValid()
4368 // , hasClassDefInline);
4369
4370 // We are now sure that the entry is not in fact an autoload entry.
4372 return kWithClassDefInline;
4373 else
4374 return kKnown;
4375 } else {
4376 // We are now sure that the entry is not in fact an autoload entry.
4377 return kUnknown;
4378 }
4379 }
4380
4381 if (decl)
4382 return kKnown;
4383 else
4384 return kUnknown;
4385
4386 // Setting up iterator part of TClingTypedefInfo is too slow.
4387 // Copy the lookup code instead:
4388 /*
4389 TClingTypedefInfo t(fInterpreter, name);
4390 if (t.IsValid() && !(t.Property() & kIsFundamental)) {
4391 delete[] classname;
4392 return kTRUE;
4393 }
4394 */
4395
4396// const clang::Decl *decl = lh.findScope(name);
4397// if (!decl) {
4398// std::string buf = TClassEdit::InsertStd(name);
4399// decl = lh.findScope(buf);
4400// }
4401
4402// return (decl);
4403}
4404
4405////////////////////////////////////////////////////////////////////////////////
4406/// Return true if there is a class template by the given name ...
4407
4409{
4410 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4411 // Interpreter transaction ahead, needs locking
4413 const clang::Decl *decl
4414 = lh.findClassTemplate(name,
4415 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4416 : cling::LookupHelper::NoDiagnostics);
4417 if (!decl) {
4418 std::string strname = "std::";
4419 strname += name;
4420 decl = lh.findClassTemplate(strname,
4421 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4422 : cling::LookupHelper::NoDiagnostics);
4423 }
4424 return nullptr != decl;
4425}
4426
4427////////////////////////////////////////////////////////////////////////////////
4428/// Create list of pointers to base class(es) for TClass cl.
4429
4431{
4433 if (cl->fBase) {
4434 return;
4435 }
4436 // Ignore the base class (e.g. `std::_Complex_base` on Windows)
4438 cl->fBase = new TList();
4439 return;
4440 }
4442 if (!tci) return;
4444 TList *listOfBase = new TList;
4445 while (t.Next()) {
4446 // if name cannot be obtained no use to put in list
4447 if (t.IsValid() && t.Name()) {
4449 listOfBase->Add(new TBaseClass((BaseClassInfo_t *)a, cl));
4450 }
4451 }
4452 // Now that is complete, publish it.
4453 cl->fBase = listOfBase;
4454}
4455
4456////////////////////////////////////////////////////////////////////////////////
4457/// Create list of pointers to enums for TClass cl.
4458
4460{
4462
4463 const Decl * D;
4464 TClass* cl = enumList.GetClass();
4465 if (cl) {
4466 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4467 }
4468 else {
4469 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4470 }
4471 // Iterate on the decl of the class and get the enums.
4472 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4473 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4474 // Collect all contexts of the namespace.
4475 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4476 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4478 declIter != declEnd; ++declIter) {
4479 // Iterate on all decls for each context.
4480 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4481 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4482 if (const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4483 // Get name of the enum type.
4484 std::string buf;
4485 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4486 llvm::raw_string_ostream stream(buf);
4487 // Don't trigger fopen of the source file to count lines:
4488 Policy.AnonymousTagLocations = false;
4489 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
4490 stream.flush();
4491 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
4492 if (!buf.empty()) {
4493 const char* name = buf.c_str();
4494 // Add the enum to the list of loaded enums.
4495 enumList.Get(ED, name);
4496 }
4497 }
4498 }
4499 }
4500 }
4501}
4502
4503////////////////////////////////////////////////////////////////////////////////
4504/// Create list of pointers to function templates for TClass cl.
4505
4507{
4509
4510 const Decl * D;
4512 if (cl) {
4513 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4515 }
4516 else {
4517 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4518 funcTempList = (TListOfFunctionTemplates*)gROOT->GetListOfFunctionTemplates();
4519 }
4520 // Iterate on the decl of the class and get the enums.
4521 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4522 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4523 // Collect all contexts of the namespace.
4524 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4525 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4528 // Iterate on all decls for each context.
4529 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4530 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4531 if (const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4532 funcTempList->Get(FTD);
4533 }
4534 }
4535 }
4536 }
4537}
4538
4539////////////////////////////////////////////////////////////////////////////////
4540/// Get the scopes representing using declarations of namespace
4541
4542std::vector<std::string> TCling::GetUsingNamespaces(ClassInfo_t *cl) const
4543{
4545 return ci->GetUsingNamespaces();
4546}
4547
4548////////////////////////////////////////////////////////////////////////////////
4549/// Create list of pointers to data members for TClass cl.
4550/// This is now a nop. The creation and updating is handled in
4551/// TListOfDataMembers.
4552
4554{
4555}
4556
4557////////////////////////////////////////////////////////////////////////////////
4558/// Create list of pointers to methods for TClass cl.
4559/// This is now a nop. The creation and updating is handled in
4560/// TListOfFunctions.
4561
4563{
4564}
4565
4566////////////////////////////////////////////////////////////////////////////////
4567/// Update the list of pointers to method for TClass cl
4568/// This is now a nop. The creation and updating is handled in
4569/// TListOfFunctions.
4570
4572{
4573}
4574
4575////////////////////////////////////////////////////////////////////////////////
4576/// Update the list of pointers to data members for TClass cl
4577/// This is now a nop. The creation and updating is handled in
4578/// TListOfDataMembers.
4579
4581{
4582}
4583
4584////////////////////////////////////////////////////////////////////////////////
4585/// Create list of pointers to method arguments for TMethod m.
4586
4588{
4590 if (m->fMethodArgs) {
4591 return;
4592 }
4593 TList *arglist = new TList;
4595 while (t.Next()) {
4596 if (t.IsValid()) {
4598 arglist->Add(new TMethodArg((MethodArgInfo_t*)a, m));
4599 }
4600 }
4601 m->fMethodArgs = arglist;
4602}
4603
4604////////////////////////////////////////////////////////////////////////////////
4605/// Return whether we are waiting for more input either because the collected
4606/// input contains unbalanced braces or last seen token was a `\` (backslash-newline)
4607
4609{
4610 return fMetaProcessor->awaitingMoreInput();
4611}
4612
4613////////////////////////////////////////////////////////////////////////////////
4614/// Generate a TClass for the given class.
4615/// Since the caller has already check the ClassInfo, let it give use the
4616/// result (via the value of emulation) rather than recalculate it.
4617
4618TClass *TCling::GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent /* = kFALSE */)
4619{
4620// For now the following line would lead to the (unwanted) instantiation
4621// of class template. This could/would need to be resurrected only if
4622// we re-introduce so sort of automatic instantiation. However this would
4623// have to include carefull look at the template parameter to avoid
4624// creating instance we can not really use (if the parameter are only forward
4625// declaration or do not have all the necessary interfaces).
4626
4627 // TClingClassInfo tci(fInterpreter, classname);
4628 // if (1 || !tci.IsValid()) {
4629
4630 Version_t version = 1;
4631 if (TClassEdit::IsSTLCont(classname)) {
4632 version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4633 }
4635 TClass *cl = new TClass(classname, version, silent);
4636 if (!emulation) {
4637 // Set the class version if the class is versioned.
4638 // Note that we cannot just call CLASS::Class_Version() as we might not have
4639 // an execution engine (when invoked from rootcling).
4640
4641 // Do not call cl->GetClassVersion(), it has side effects!
4643 if (oldvers == version && cl->GetClassInfo()) {
4644 // We have a version and it might need an update.
4646 if (llvm::isa<clang::NamespaceDecl>(cli->GetDecl())) {
4647 // Namespaces don't have class versions.
4648 return cl;
4649 }
4650 TClingMethodInfo mi = cli->GetMethod("Class_Version", "", nullptr /*poffset*/,
4653 if (!mi.IsValid()) {
4654 if (cl->TestBit(TClass::kIsTObject)) {
4655 Error("GenerateTClass",
4656 "Cannot find %s::Class_Version()! Class version might be wrong.",
4657 cl->GetName());
4658 }
4659 return cl;
4660 }
4661 Version_t newvers = ROOT::TMetaUtils::GetClassVersion(llvm::dyn_cast<clang::RecordDecl>(cli->GetDecl()),
4662 *fInterpreter);
4663 if (newvers == -1) {
4664 // Didn't manage to determine the class version from the AST.
4665 // Use runtime instead.
4666 if ((mi.Property() & kIsStatic)
4667 && !fInterpreter->isInSyntaxOnlyMode()) {
4668 // This better be a static function.
4670 callfunc.SetFunc(&mi);
4671 newvers = callfunc.ExecInt(nullptr);
4672 } else {
4673 Error("GenerateTClass",
4674 "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4675 cl->GetName());
4676 }
4677 }
4678 if (newvers != oldvers) {
4679 cl->fClassVersion = newvers;
4680 cl->fStreamerInfo->Expand(newvers + 2 + 10);
4681 }
4682 }
4683 }
4684
4685 return cl;
4686
4687// } else {
4688// return GenerateTClass(&tci,silent);
4689// }
4690}
4691
4692#if 0
4693////////////////////////////////////////////////////////////////////////////////
4694
4696{
4697 includes += info->FileName();
4698
4699 const clang::ClassTemplateSpecializationDecl *templateCl
4700 = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->GetDecl());
4701 if (templateCl) {
4702 for(unsigned int i=0; i < templateCl->getTemplateArgs().size(); ++i) {
4703 const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4704 if (arg.getKind() == clang::TemplateArgument::Type) {
4705 const clang::Type *uType = ROOT::TMetaUtils::GetUnderlyingType( arg.getAsType() );
4706
4707 if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4708 // We really need a header file.
4709 const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4710 if (argdecl) {
4711 includes += ";";
4712 TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4714 } else {
4715 std::string Result;
4716 llvm::raw_string_ostream OS(Result);
4717 arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4718 Warning("TCling::GenerateTClass","Missing header file for %s",OS.str().c_str());
4719 }
4720 }
4721 }
4722 }
4723 }
4724}
4725#endif
4726
4727////////////////////////////////////////////////////////////////////////////////
4728/// Generate a TClass for the given class.
4729
4731{
4733 if (!info || !info->IsValid()) {
4734 Fatal("GenerateTClass","Requires a valid ClassInfo object");
4735 return nullptr;
4736 }
4737 // We are in the case where we have AST nodes for this class.
4738 TClass *cl = nullptr;
4739 std::string classname;
4740 info->FullName(classname,*fNormalizedCtxt); // Could we use Name()?
4741 if (TClassEdit::IsSTLCont(classname)) {
4742#if 0
4743 Info("GenerateTClass","Will (try to) generate the compiled TClass for %s.",classname.c_str());
4744 // We need to build up the list of required headers, by
4745 // looking at each template arguments.
4748
4749 if (0 == GenerateDictionary(classname.c_str(),includes)) {
4750 // 0 means success.
4751 cl = TClass::LoadClass(classnam.c_str(), silent);
4752 if (cl == 0) {
4753 Error("GenerateTClass","Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4754 }
4755 }
4756#endif
4757 if (cl == nullptr) {
4758 int version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4759 cl = new TClass(classinfo, version, nullptr, nullptr, -1, -1, silent);
4760 }
4761 } else {
4762 // For regular class, just create a TClass on the fly ...
4763 // Not quite useful yet, but that what CINT used to do anyway.
4764 cl = new TClass(classinfo, 1, nullptr, nullptr, -1, -1, silent);
4765 }
4766 // Add the new TClass to the map of declid and TClass*.
4767 if (cl) {
4769 }
4770 return cl;
4771}
4772
4773////////////////////////////////////////////////////////////////////////////////
4774/// Generate the dictionary for the C++ classes listed in the first
4775/// argument (in a semi-colon separated list).
4776/// 'includes' contains a semi-colon separated list of file to
4777/// `#include` in the dictionary.
4778/// For example:
4779/// ~~~ {.cpp}
4780/// gInterpreter->GenerateDictionary("vector<vector<float> >;list<vector<float> >","list;vector");
4781/// ~~~
4782/// or
4783/// ~~~ {.cpp}
4784/// gInterpreter->GenerateDictionary("myclass","myclass.h;myhelper.h");
4785/// ~~~
4786
4787Int_t TCling::GenerateDictionary(const char* classes, const char* includes /* = "" */, const char* /* options = 0 */)
4788{
4789 if (classes == nullptr || classes[0] == 0) {
4790 Error("TCling::GenerateDictionary", "Cannot generate dictionary without passing classes.");
4791 return 0;
4792 }
4793 // Split the input list
4794 std::vector<std::string> listClasses;
4795 for (
4796 const char* current = classes, *prev = classes;
4797 *current != 0;
4798 ++current
4799 ) {
4800 if (*current == ';') {
4801 listClasses.push_back(std::string(prev, current - prev));
4802 prev = current + 1;
4803 }
4804 else if (*(current + 1) == 0) {
4805 listClasses.push_back(std::string(prev, current + 1 - prev));
4806 prev = current + 1;
4807 }
4808 }
4809 std::vector<std::string> listIncludes;
4810 if (!includes)
4811 includes = "";
4812 for (
4813 const char* current = includes, *prev = includes;
4814 *current != 0;
4815 ++current
4816 ) {
4817 if (*current == ';') {
4818 listIncludes.push_back(std::string(prev, current - prev));
4819 prev = current + 1;
4820 }
4821 else if (*(current + 1) == 0) {
4822 listIncludes.push_back(std::string(prev, current + 1 - prev));
4823 prev = current + 1;
4824 }
4825 }
4826 // Generate the temporary dictionary file
4828 std::vector<std::string>(), std::vector<std::string>());
4829}
4830
4831////////////////////////////////////////////////////////////////////////////////
4832/// Return pointer to cling Decl of global/static variable that is located
4833/// at the address given by addr.
4834
4836{
4838 DeclId_t d;
4840
4841 // Could trigger deserialization of decls.
4842 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4843
4844 if (cl) {
4845 d = cl->GetDataMember(name);
4846 // We check if the decl of the data member has an annotation which indicates
4847 // an ioname.
4848 // In case this is true, if the name requested is not the ioname, we
4849 // return 0, as if the member did not exist. In some sense we override
4850 // the information in the TClassInfo instance, isolating the typesystem in
4851 // TClass from the one in the AST.
4852 if (const ValueDecl* decl = (const ValueDecl*) d){
4853 std::string ioName;
4855 if (hasIoName && ioName != name) return nullptr;
4856 }
4857 return d;
4858 }
4859 // We are looking up for something on the TU scope.
4860 // FIXME: We do not want to go through TClingClassInfo(fInterpreter) because of redundant deserializations. That
4861 // interface will actually construct iterators and walk over the decls on the global scope. In would return the first
4862 // occurrence of a decl with the looked up name. However, that's not what C++ lookup would do: if we want to switch
4863 // to a more complete C++ lookup interface we need sift through the found names and pick up the declarations which
4864 // are only fulfilling ROOT's understanding for a Data Member.
4865 // FIXME: We should probably deprecate the TClingClassInfo(fInterpreter) interface and replace it withe something
4866 // similar as below.
4867 using namespace clang;
4868 Sema& SemaR = fInterpreter->getSema();
4869 DeclarationName DName = &SemaR.Context.Idents.get(name);
4870
4871 LookupResult R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4872 RedeclarationKind::ForExternalRedeclaration);
4873
4874 cling::utils::Lookup::Named(&SemaR, R);
4875
4876 LookupResult::Filter F = R.makeFilter();
4877 // Filter the data-member looking decls.
4878 while (F.hasNext()) {
4879 NamedDecl *D = F.next();
4882 continue;
4883 F.erase();
4884 }
4885 F.done();
4886
4887 if (R.isSingleResult())
4888 return R.getFoundDecl();
4889 return nullptr;
4890}
4891
4892////////////////////////////////////////////////////////////////////////////////
4893/// Return pointer to cling Decl of global/static variable that is located
4894/// at the address given by addr.
4895
4897{
4899
4900 const clang::Decl* possibleEnum = nullptr;
4901 // FInd the context of the decl.
4902 if (cl) {
4904 if (cci) {
4905 const clang::DeclContext* dc = nullptr;
4906 if (const clang::Decl* D = cci->GetDecl()) {
4907 if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
4909 }
4910 }
4911 if (dc) {
4912 // If it is a data member enum.
4913 // Could trigger deserialization of decls.
4914 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4915 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name, dc);
4916 } else {
4917 Error("TCling::GetEnum", "DeclContext not found for %s .\n", name);
4918 }
4919 }
4920 } else {
4921 // If it is a global enum.
4922 // Could trigger deserialization of decls.
4923 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4924 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name);
4925 }
4926 if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
4928 return possibleEnum;
4929 }
4930 return nullptr;
4931}
4932
4933////////////////////////////////////////////////////////////////////////////////
4934/// Return pointer to cling DeclId for a global value
4935
4936TInterpreter::DeclId_t TCling::GetDeclId( const llvm::GlobalValue *gv ) const
4937{
4938 if (!gv) return nullptr;
4939
4940 llvm::StringRef mangled_name = gv->getName();
4941
4942 int err = 0;
4943 char* demangled_name_c = TClassEdit::DemangleName(mangled_name.str().c_str(), err);
4944 if (err) {
4945 if (err == -2) {
4946 // It might simply be an unmangled global name.
4947 DeclId_t d;
4949 d = gcl.GetDataMember(mangled_name.str().c_str());
4950 return d;
4951 }
4952 return nullptr;
4953 }
4954
4955 std::string scopename(demangled_name_c);
4957
4958 //
4959 // Separate out the class or namespace part of the
4960 // function name.
4961 //
4962 std::string dataname;
4963
4964 if (!strncmp(scopename.c_str(), "typeinfo for ", sizeof("typeinfo for ")-1)) {
4965 scopename.erase(0, sizeof("typeinfo for ")-1);
4966 } else if (!strncmp(scopename.c_str(), "vtable for ", sizeof("vtable for ")-1)) {
4967 scopename.erase(0, sizeof("vtable for ")-1);
4968 } else {
4969 // See if it is a function
4970 std::string::size_type pos = scopename.rfind('(');
4971 if (pos != std::string::npos) {
4972 return nullptr;
4973 }
4974 // Separate the scope and member name
4975 pos = scopename.rfind(':');
4976 if (pos != std::string::npos) {
4977 if ((pos != 0) && (scopename[pos-1] == ':')) {
4978 dataname = scopename.substr(pos+1);
4979 scopename.erase(pos-1);
4980 }
4981 } else {
4982 scopename.clear();
4984 }
4985 }
4986 //fprintf(stderr, "name: '%s'\n", name.c_str());
4987 // Now we have the class or namespace name, so do the lookup.
4988
4989
4990 DeclId_t d;
4991 if (scopename.size()) {
4993 d = cl.GetDataMember(dataname.c_str());
4994 }
4995 else {
4997 d = gcl.GetDataMember(dataname.c_str());
4998 }
4999 return d;
5000}
5001
5002////////////////////////////////////////////////////////////////////////////////
5003/// NOT IMPLEMENTED.
5004
5006{
5007 Error("GetDataMemberWithValue()", "not implemented");
5008 return nullptr;
5009}
5010
5011////////////////////////////////////////////////////////////////////////////////
5012/// Return pointer to cling DeclId for a data member with a given name.
5013
5015{
5016 // NOT IMPLEMENTED.
5017 Error("GetDataMemberAtAddr()", "not implemented");
5018 return nullptr;
5019}
5020
5021////////////////////////////////////////////////////////////////////////////////
5022/// Return the cling mangled name for a method of a class with parameters
5023/// params (params is a string of actual arguments, not formal ones). If the
5024/// class is 0 the global function list will be searched.
5025
5027 const char* params, Bool_t objectIsConst /* = kFALSE */)
5028{
5031 if (cl) {
5034 &offset);
5035 }
5036 else {
5039 func.SetFunc(&gcl, method, params, &offset);
5040 }
5042 if (!mi) return "";
5043 TString mangled_name( mi->GetMangledName() );
5044 delete mi;
5045 return mangled_name;
5046}
5047
5048////////////////////////////////////////////////////////////////////////////////
5049/// Return the cling mangled name for a method of a class with a certain
5050/// prototype, i.e. "char*,int,float". If the class is 0 the global function
5051/// list will be searched.
5052
5054 const char* proto, Bool_t objectIsConst /* = kFALSE */,
5055 EFunctionMatchMode mode /* = kConversionMatch */)
5056{
5058 if (cl) {
5059 return ((TClingClassInfo*)cl->GetClassInfo())->
5060 GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetMangledName();
5061 }
5063 return gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetMangledName();
5064}
5065
5066////////////////////////////////////////////////////////////////////////////////
5067/// Return pointer to cling interface function for a method of a class with
5068/// parameters params (params is a string of actual arguments, not formal
5069/// ones). If the class is 0 the global function list will be searched.
5070
5072 const char* params, Bool_t objectIsConst /* = kFALSE */)
5073{
5076 if (cl) {
5079 &offset);
5080 }
5081 else {
5084 func.SetFunc(&gcl, method, params, &offset);
5085 }
5086 return (void*) func.InterfaceMethod();
5087}
5088
5089////////////////////////////////////////////////////////////////////////////////
5090/// Return pointer to cling interface function for a method of a class with
5091/// a certain name.
5092
5094{
5096 DeclId_t f;
5098 if (cl) {
5099 f = cl->GetMethod(method).GetDeclId();
5100 }
5101 else {
5103 f = gcl.GetMethod(method).GetDeclId();
5104 }
5105 return f;
5106
5107}
5108
5109////////////////////////////////////////////////////////////////////////////////
5110/// Insert overloads of name in cl to res.
5111
5113 std::vector<DeclId_t>& res) const
5114{
5115 clang::Sema& S = fInterpreter->getSema();
5116 clang::ASTContext& Ctx = S.Context;
5117 const clang::Decl* CtxDecl
5118 = cl ? (const clang::Decl*)((TClingClassInfo*)cl)->GetDeclId():
5119 Ctx.getTranslationUnitDecl();
5120 auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
5121 const clang::DeclContext* DeclCtx = RecDecl;
5122
5123 if (!DeclCtx)
5125 if (!DeclCtx) return;
5126
5127 clang::DeclarationName DName;
5128 // The DeclarationName is funcname, unless it's a ctor or dtor.
5129 // FIXME: or operator or conversion! See enum clang::DeclarationName::NameKind.
5130
5131 if (RecDecl) {
5132 if (RecDecl->getNameAsString() == funcname) {
5133 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5134 DName = Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalType(QT));
5135 } else if (funcname[0] == '~' && RecDecl->getNameAsString() == funcname + 1) {
5136 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5137 DName = Ctx.DeclarationNames.getCXXDestructorName(Ctx.getCanonicalType(QT));
5138 } else {
5139 DName = &Ctx.Idents.get(funcname);
5140 }
5141 } else {
5142 DName = &Ctx.Idents.get(funcname);
5143 }
5144
5145 // NotForRedeclaration: we want to find names in inline namespaces etc.
5146 clang::LookupResult R(S, DName, clang::SourceLocation(), Sema::LookupOrdinaryName,
5147 RedeclarationKind::NotForRedeclaration);
5148 R.suppressDiagnostics(); // else lookup with NotForRedeclaration will check access etc
5149 S.LookupQualifiedName(R, const_cast<DeclContext*>(DeclCtx));
5150 if (R.empty()) return;
5151 R.resolveKind();
5152 res.reserve(res.size() + (R.end() - R.begin()));
5153 for (clang::LookupResult::iterator IR = R.begin(), ER = R.end();
5154 IR != ER; ++IR) {
5155 if (const clang::FunctionDecl* FD
5156 = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
5157 if (!FD->getDescribedFunctionTemplate()) {
5158 res.push_back(FD);
5159 }
5160 } else if (const auto *USD = llvm::dyn_cast<const clang::UsingShadowDecl>(*IR)) {
5161 // FIXME: multi-level using
5162 if (llvm::isa<clang::FunctionDecl>(USD->getTargetDecl())) {
5163 res.push_back(USD);
5164 }
5165 }
5166 }
5167}
5168
5169////////////////////////////////////////////////////////////////////////////////
5170/// Return pointer to cling interface function for a method of a class with
5171/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5172/// function list will be searched.
5173
5175 const char* proto,
5176 Bool_t objectIsConst /* = kFALSE */,
5177 EFunctionMatchMode mode /* = kConversionMatch */)
5178{
5180 void* f;
5181 if (cl) {
5182 f = ((TClingClassInfo*)cl->GetClassInfo())->
5183 GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).InterfaceMethod();
5184 }
5185 else {
5187 f = gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).InterfaceMethod();
5188 }
5189 return f;
5190}
5191
5192////////////////////////////////////////////////////////////////////////////////
5193/// Return pointer to cling DeclId for a method of a class with
5194/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5195/// function list will be searched.
5196
5198 const char* params,
5199 Bool_t objectIsConst /* = kFALSE */)
5200{
5202 DeclId_t f;
5204 if (cl) {
5205 f = cl->GetMethodWithArgs(method, params, objectIsConst, nullptr /*poffset*/).GetDeclId();
5206 }
5207 else {
5209 f = gcl.GetMethod(method, params, objectIsConst, nullptr /*poffset*/).GetDeclId();
5210 }
5211 return f;
5212}
5213
5214////////////////////////////////////////////////////////////////////////////////
5215/// Return pointer to cling interface function for a method of a class with
5216/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5217/// function list will be searched.
5218
5220 const char* proto,
5221 Bool_t objectIsConst /* = kFALSE */,
5222 EFunctionMatchMode mode /* = kConversionMatch */)
5223{
5225 DeclId_t f;
5227 if (cl) {
5228 f = cl->GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetDeclId();
5229 }
5230 else {
5232 f = gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetDeclId();
5233 }
5234 return f;
5235}
5236
5237////////////////////////////////////////////////////////////////////////////////
5238/// Return pointer to cling interface function for a method of a class with
5239/// a certain name.
5240
5242{
5244 DeclId_t f;
5246 if (cl) {
5247 f = cl->GetFunctionTemplate(name);
5248 }
5249 else {
5251 f = gcl.GetFunctionTemplate(name);
5252 }
5253 return f;
5254
5255}
5256
5257////////////////////////////////////////////////////////////////////////////////
5258/// The 'name' is known to the interpreter, this function returns
5259/// the internal version of this name (usually just resolving typedefs)
5260/// This is used in particular to synchronize between the name used
5261/// by rootcling and by the run-time environment (TClass)
5262/// Return 0 if the name is not known.
5263
5264void TCling::GetInterpreterTypeName(const char* name, std::string &output, Bool_t full)
5265{
5266 output.clear();
5267
5269
5271 if (!cl.IsValid()) {
5272 return ;
5273 }
5274 if (full) {
5276 return;
5277 }
5278 // Well well well, for backward compatibility we need to act a bit too
5279 // much like CINT.
5282
5283 return;
5284}
5285
5286////////////////////////////////////////////////////////////////////////////////
5287/// Execute a global function with arguments params.
5288///
5289/// FIXME: The cint-based version of this code does not check if the
5290/// SetFunc() call works, and does not do any real checking
5291/// for errors from the Exec() call. It did fetch the most
5292/// recent cint security error and return that in error, but
5293/// this does not really translate well to cling/clang. We
5294/// should enhance these interfaces so that we can report
5295/// compilation and runtime errors properly.
5296
5297void TCling::Execute(const char* function, const char* params, int* error)
5298{
5300 if (error) {
5301 *error = TInterpreter::kNoError;
5302 }
5304 Longptr_t offset = 0L;
5306 func.SetFunc(&cl, function, params, &offset);
5307 func.Exec(nullptr);
5308}
5309
5310////////////////////////////////////////////////////////////////////////////////
5311/// Execute a method from class cl with arguments params.
5312///
5313/// FIXME: The cint-based version of this code does not check if the
5314/// SetFunc() call works, and does not do any real checking
5315/// for errors from the Exec() call. It did fetch the most
5316/// recent cint security error and return that in error, but
5317/// this does not really translate well to cling/clang. We
5318/// should enhance these interfaces so that we can report
5319/// compilation and runtime errors properly.
5320
5321void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5322 const char* params, Bool_t objectIsConst, int* error)
5323{
5325 if (error) {
5326 *error = TInterpreter::kNoError;
5327 }
5328 // If the actual class of this object inherits 2nd (or more) from TObject,
5329 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5330 // hence gInterpreter->Execute will improperly correct the offset.
5331 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5332 Longptr_t offset = 0L;
5335 void* address = (void*)((Longptr_t)addr + offset);
5336 func.Exec(address);
5337}
5338
5339////////////////////////////////////////////////////////////////////////////////
5340
5341void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5342 const char* params, int* error)
5343{
5344 Execute(obj,cl,method,params,false,error);
5345}
5346
5347////////////////////////////////////////////////////////////////////////////////
5348/// Execute a method from class cl with the arguments in array params
5349/// (params[0] ... params[n] = array of TObjString parameters).
5350/// Convert the TObjArray array of TObjString parameters to a character
5351/// string of comma separated parameters.
5352/// The parameters of type 'char' are enclosed in double quotes and all
5353/// internal quotes are escaped.
5354
5356 TObjArray* params, int* error)
5357{
5358 if (!method) {
5359 Error("Execute", "No method was defined");
5360 return;
5361 }
5362 TList* argList = method->GetListOfMethodArgs();
5363 // Check number of actual parameters against of expected formal ones
5364
5365 Int_t nparms = argList->LastIndex() + 1;
5366 Int_t argc = params ? params->GetEntries() : 0;
5367
5368 if (argc > nparms) {
5369 Error("Execute","Too many parameters to call %s, got %d but expected at most %d.",method->GetName(),argc,nparms);
5370 return;
5371 }
5372 if (nparms != argc) {
5373 // Let's see if the 'missing' argument are all defaulted.
5374 // if nparms==0 then either we stopped earlier either argc is also zero and we can't reach here.
5375 assert(nparms > 0);
5376
5377 TMethodArg *arg = (TMethodArg *) argList->At( 0 );
5378 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5379 // There is a default value for the first missing
5380 // argument, so we are fine.
5381 } else {
5382 Int_t firstDefault = -1;
5383 for (Int_t i = 0; i < nparms; i ++) {
5384 arg = (TMethodArg *) argList->At( i );
5385 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5386 firstDefault = i;
5387 break;
5388 }
5389 }
5390 if (firstDefault >= 0) {
5391 Error("Execute","Too few arguments to call %s, got only %d but expected at least %d and at most %d.",method->GetName(),argc,firstDefault,nparms);
5392 } else {
5393 Error("Execute","Too few arguments to call %s, got only %d but expected %d.",method->GetName(),argc,nparms);
5394 }
5395 return;
5396 }
5397 }
5398
5399 const char* listpar = "";
5400 TString complete(10);
5401 if (params) {
5402 // Create a character string of parameters from TObjArray
5403 TIter next(params);
5404 for (Int_t i = 0; i < argc; i ++) {
5405 TMethodArg* arg = (TMethodArg*) argList->At(i);
5407 TObjString* nxtpar = (TObjString*) next();
5408 if (i) {
5409 complete += ',';
5410 }
5411 if (strstr(type.TrueName(*fNormalizedCtxt), "char")) {
5412 TString chpar('\"');
5413 chpar += (nxtpar->String()).ReplaceAll("\"", "\\\"");
5414 // At this point we have to check if string contains \\"
5415 // and apply some more sophisticated parser. Not implemented yet!
5416 complete += chpar;
5417 complete += '\"';
5418 }
5419 else {
5420 complete += nxtpar->String();
5421 }
5422 }
5423 listpar = complete.Data();
5424 }
5425
5426 // And now execute it.
5428 if (error) {
5429 *error = TInterpreter::kNoError;
5430 }
5431 // If the actual class of this object inherits 2nd (or more) from TObject,
5432 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5433 // hence gInterpreter->Execute will improperly correct the offset.
5434 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5437 func.Init(*minfo);
5438 func.SetArgs(listpar);
5439 // Now calculate the 'this' pointer offset for the method
5440 // when starting from the class described by cl.
5441 const CXXMethodDecl * mdecl = dyn_cast<CXXMethodDecl>(minfo->GetTargetFunctionDecl());
5442 Longptr_t offset = ((TClingClassInfo*)cl->GetClassInfo())->GetOffset(mdecl);
5443 void* address = (void*)((Longptr_t)addr + offset);
5444 func.Exec(address);
5445}
5446
5447////////////////////////////////////////////////////////////////////////////////
5448
5450 const void* args[] /*=0*/,
5451 int nargs /*=0*/,
5452 void* ret/*= 0*/) const
5453{
5454 if (!method) {
5455 Error("ExecuteWithArgsAndReturn", "No method was defined");
5456 return;
5457 }
5458
5460 TClingCallFunc func(*minfo);
5461 func.ExecWithArgsAndReturn(address, args, nargs, ret);
5462}
5463
5464////////////////////////////////////////////////////////////////////////////////
5465/// Execute a cling macro.
5466
5468{
5470 fCurExecutingMacros.push_back(filename);
5472 fCurExecutingMacros.pop_back();
5473 return result;
5474}
5475
5476////////////////////////////////////////////////////////////////////////////////
5477/// Return the file name of the current un-included interpreted file.
5478/// See the documentation for GetCurrentMacroName().
5479
5481{
5482 Warning("GetTopLevelMacroName", "Must change return type!");
5483 return fCurExecutingMacros.empty() ? nullptr : fCurExecutingMacros.back();
5484}
5485
5486////////////////////////////////////////////////////////////////////////////////
5487/// Return the file name of the currently interpreted file,
5488/// included or not. Example to illustrate the difference between
5489/// GetCurrentMacroName() and GetTopLevelMacroName():
5490/// ~~~ {.cpp}
5491/// void inclfile() {
5492/// std::cout << "In inclfile.C" << std::endl;
5493/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5494/// TCling::GetCurrentMacroName() << std::endl;
5495/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5496/// TCling::GetTopLevelMacroName() << std::endl;
5497/// }
5498/// ~~~
5499/// ~~~ {.cpp}
5500/// void mymacro() {
5501/// std::cout << "In mymacro.C" << std::endl;
5502/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5503/// TCling::GetCurrentMacroName() << std::endl;
5504/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5505/// TCling::GetTopLevelMacroName() << std::endl;
5506/// std::cout << " Now calling inclfile..." << std::endl;
5507/// gInterpreter->ProcessLine(".x inclfile.C");
5508/// }
5509/// ~~~
5510/// Running mymacro.C will print:
5511///
5512/// ~~~ {.cpp}
5513/// root [0] .x mymacro.C
5514/// ~~~
5515/// In mymacro.C
5516/// ~~~ {.cpp}
5517/// TCling::GetCurrentMacroName() returns ./mymacro.C
5518/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5519/// ~~~
5520/// Now calling inclfile...
5521/// In inclfile.h
5522/// ~~~ {.cpp}
5523/// TCling::GetCurrentMacroName() returns inclfile.C
5524/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5525/// ~~~
5526
5528{
5529#if defined(R__MUST_REVISIT)
5530#if R__MUST_REVISIT(6,0)
5531 Warning("GetCurrentMacroName", "Must change return type!");
5532#endif
5533#endif
5534 return fCurExecutingMacros.empty() ? nullptr : fCurExecutingMacros.back();
5535}
5536
5537////////////////////////////////////////////////////////////////////////////////
5538/// Return the absolute type of typeDesc.
5539/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
5540/// You need to use the result immediately before it is being overwritten.
5541
5542const char* TCling::TypeName(const char* typeDesc)
5543{
5544 TTHREAD_TLS_DECL(std::string,t);
5545
5546 if (!strstr(typeDesc, "(*)(")) {
5547 const char *s = strchr(typeDesc, ' ');
5548 const char *template_start = strchr(typeDesc, '<');
5549 if (!strcmp(typeDesc, "long long")) {
5550 t = typeDesc;
5551 }
5552 else if (!strncmp(typeDesc, "unsigned ", s + 1 - typeDesc)) {
5553 t = typeDesc;
5554 }
5555 // s is the position of the second 'word' (if any)
5556 // except in the case of templates where there will be a space
5557 // just before any closing '>': eg.
5558 // TObj<std::vector<UShort_t,__malloc_alloc_template<0> > >*
5559 else if (s && (template_start == nullptr || (s < template_start))) {
5560 t = s + 1;
5561 }
5562 else {
5563 t = typeDesc;
5564 }
5565 }
5566 else {
5567 t = typeDesc;
5568 }
5569 auto l = t.length();
5570 while (l > 0 && (t[l - 1] == '*' || t[l - 1] == '&'))
5571 --l;
5572 t.resize(l);
5573 return t.c_str(); // NOLINT
5574}
5575
5576static bool requiresRootMap(const char* rootmapfile)
5577{
5579
5580 llvm::StringRef libName = llvm::sys::path::filename(rootmapfile);
5581 libName.consume_back(".rootmap");
5582
5583 return !gInterpreter->HasPCMForLibrary(libName.str().c_str());
5584}
5585
5586////////////////////////////////////////////////////////////////////////////////
5587/// Read and parse a rootmapfile in its new format, and return 0 in case of
5588/// success, -1 if the file has already been read, and -3 in case its format
5589/// is the old one (e.g. containing "Library.ClassName"), -4 in case of syntax
5590/// error.
5591
5593{
5594 if (!(rootmapfile && *rootmapfile))
5595 return 0;
5596
5598 return 0; // success
5599
5600 // For "class ", "namespace ", "typedef ", "header ", "enum ", "var " respectively
5601 const std::map<char, unsigned int> keyLenMap = {{'c',6},{'n',10},{'t',8},{'h',7},{'e',5},{'v',4}};
5602
5604#ifdef _MSC_VER
5605 std::replace(rootmapfileNoBackslash.begin(), rootmapfileNoBackslash.end(), '\\', '/');
5606#endif
5607 // Add content of a specific rootmap file
5609 return -1;
5610
5611 // Line 1 is `{ decls }`
5612 std::string lineDirective = std::string("\n#line 2 \"Forward declarations from ") + rootmapfileNoBackslash + "\"\n";
5613
5614 std::ifstream file(rootmapfileNoBackslash);
5615 std::string line;
5616 line.reserve(200);
5617 std::string lib_name;
5618 line.reserve(100);
5619 bool newFormat = false;
5620 while (getline(file, line, '\n')) {
5621 if (!newFormat && (line.compare(0, 8, "Library.") == 0 || line.compare(0, 8, "Declare.") == 0)) {
5622 file.close();
5623 return -3; // old format
5624 }
5625 newFormat = true;
5626
5627 if (line.compare(0, 9, "{ decls }") == 0) {
5628 // forward declarations
5629
5630 while (getline(file, line, '\n')) {
5631 if (line[0] == '[')
5632 break;
5633 if (!uniqueString) {
5634 Error("ReadRootmapFile", "Cannot handle \"{ decls }\" sections in custom rootmap file %s",
5635 rootmapfileNoBackslash.c_str());
5636 return -4;
5637 }
5638 if (!lineDirective.empty())
5639 uniqueString->Append(lineDirective);
5640 uniqueString->Append(line + '\n');
5641 }
5642 }
5643 const char firstChar = line[0];
5644 if (firstChar == '[') {
5645 // new section (library)
5646 auto brpos = line.find(']');
5647 if (brpos == string::npos)
5648 continue;
5649 lib_name = line.substr(1, brpos - 1);
5650 // Remove spaces at the beginning and at the end of the library name
5651 lib_name.erase(lib_name.find_last_not_of(' ') + 1);
5652 lib_name.erase(0, lib_name.find_first_not_of(' '));
5653 if (gDebug > 3) {
5654 TString lib_nameTstr(lib_name.c_str());
5655 TObjArray *tokens = lib_nameTstr.Tokenize(" ");
5656 const char *lib = ((TObjString *)tokens->At(0))->GetName();
5657 const char *wlib = gSystem->DynamicPathName(lib, kTRUE);
5658 if (wlib) {
5659 Info("ReadRootmapFile", "%s: New section for %s", rootmapfile, lib_nameTstr.Data());
5660 } else {
5661 Info("ReadRootmapFile", "%s: Section for %s (library does not exist)", rootmapfile, lib_nameTstr.Data());
5662 }
5663 delete[] wlib;
5664 delete tokens;
5665 }
5666 } else {
5667 auto keyLenIt = keyLenMap.find(firstChar);
5668 if (keyLenIt == keyLenMap.end())
5669 continue;
5670 unsigned int keyLen = keyLenIt->second;
5671 // Do not make a copy, just start after the key
5672 const char *keyname = line.c_str() + keyLen;
5673 if (gDebug > 6)
5674 Info("ReadRootmapFile", "%s: class %s in %s", rootmapfile, keyname, lib_name.c_str());
5676 if (isThere) {
5677 if (lib_name != isThere->GetValue()) { // the same key for two different libs
5678 if (firstChar == 'n') {
5679 if (gDebug > 3)
5680 Info("ReadRootmapFile",
5681 "While processing %s, namespace %s was found to be associated to %s although it is already "
5682 "associated to %s",
5683 rootmapfile, keyname, lib_name.c_str(), isThere->GetValue());
5684 } else if (firstChar == 'h') { // it is a header: add the libname to the list of libs to be loaded.
5685 lib_name += " ";
5686 lib_name += isThere->GetValue();
5687 fMapfile->SetValue(keyname, lib_name.c_str());
5688 } else if (!TClassEdit::IsSTLCont(keyname)) {
5689 Warning("ReadRootmapFile",
5690 "While processing %s, %s %s was found to be associated to %s although it is already "
5691 "associated to %s",
5692 rootmapfile, line.substr(0, keyLen - 1).c_str(), keyname, lib_name.c_str(),
5693 isThere->GetValue());
5694 }
5695 } else { // the same key for the same lib
5696 if (gDebug > 3)
5697 Info("ReadRootmapFile", "While processing %s, key %s was found to be already defined for %s",
5698 rootmapfile, keyname, lib_name.c_str());
5699 }
5700 } else {
5701 fMapfile->SetValue(keyname, lib_name.c_str());
5702 }
5703 }
5704 }
5705 file.close();
5706 return 0;
5707}
5708
5709////////////////////////////////////////////////////////////////////////////////
5710/// Create a resource table and read the (possibly) three resource files,
5711/// i.e. `$ROOTSYS/etc/system<name>` (or `ROOTETCDIR/system<name>`), `$HOME/<name>`
5712/// and `$PWD/<name>`. ROOT always reads ".rootrc" (in TROOT::InitSystem()). You
5713/// can read additional user defined resource files by creating additional TEnv
5714/// objects. By setting the shell variable ROOTENV_NO_HOME=1 the reading of
5715/// the `$HOME/<name>` resource file will be skipped. This might be useful in
5716/// case the home directory resides on an automounted remote file system
5717/// and one wants to avoid the file system from being mounted.
5718
5720{
5721 assert(requiresRootMap(name) && "We have a module!");
5722
5723 if (!requiresRootMap(name))
5724 return;
5725
5727
5729
5730 TString sname = "system";
5731 sname += name;
5734
5736 if (ret == -3) // old format
5738 if (!gSystem->Getenv("ROOTENV_NO_HOME")) {
5742 if (ret == -3) // old format
5746 if (ret == -3) // old format
5748 }
5749 } else {
5751 if (ret == -3) // old format
5753 }
5755}
5756
5757
5758namespace {
5759 using namespace clang;
5760
5761 class ExtVisibleStorageAdder: public RecursiveASTVisitor<ExtVisibleStorageAdder>{
5762 // This class is to be considered an helper for AutoLoading.
5763 // It is a recursive visitor is used to inspect namespaces and specializations
5764 // coming from forward declarations in rootmaps and to set the external visible
5765 // storage flag for them.
5766 public:
5767 ExtVisibleStorageAdder(std::unordered_set<const NamespaceDecl*>& nsSet): fNSSet(nsSet) {};
5768 bool VisitNamespaceDecl(NamespaceDecl* nsDecl) {
5769 // We want to enable the external lookup for this namespace
5770 // because it may shadow the lookup of other names contained
5771 // in that namespace
5772
5773 nsDecl->setHasExternalVisibleStorage();
5774 fNSSet.insert(nsDecl);
5775 return true;
5776 }
5778 // We want to enable the external lookup for this specialization
5779 // because we can provide a definition for it!
5780 if (specDecl->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
5781 //SpecSet.insert(specDecl);
5782 specDecl->setHasExternalLexicalStorage();
5783
5784 // No need to recurse. On the contrary, recursing is actively harmful:
5785 // NOTE: must not recurse to prevent this visitor from triggering loading from
5786 // the external AST source (i.e. autoloading). This would be triggered right here,
5787 // before autoloading is even set up, as rootmap file parsing happens before that.
5788 // Even if autoloading is off and has no effect, triggering loading from external
5789 // AST source resets the flag setHasExternalLexicalStorage(), hiding this specialization
5790 // from subsequent autoloads!
5791 return false;
5792 }
5793 private:
5794 std::unordered_set<const NamespaceDecl*>& fNSSet;
5795 };
5796}
5797
5798////////////////////////////////////////////////////////////////////////////////
5799/// Load map between class and library. If rootmapfile is specified a
5800/// specific rootmap file can be added (typically used by ACLiC).
5801/// In case of error -1 is returned, 0 otherwise.
5802/// The interpreter uses this information to automatically load the shared
5803/// library for a class (autoload mechanism), see the AutoLoad() methods below.
5804
5806{
5808 return 0;
5809
5811
5812 // open the [system].rootmap files
5813 if (!fMapfile) {
5814 fMapfile = new TEnv();
5818 InitRootmapFile(".rootmap");
5819 }
5820
5821 // Prepare a list of all forward declarations for cling
5822 // For some experiments it is easily as big as 500k characters. To be on the
5823 // safe side, we go for 1M.
5824 TUniqueString uniqueString(1048576);
5825
5826 // Load all rootmap files in the dynamic load path ((DY)LD_LIBRARY_PATH, etc.).
5827 // A rootmap file must end with the string ".rootmap".
5829 if (ldpath != fRootmapLoadPath) {
5831#ifdef WIN32
5832 TObjArray* paths = ldpath.Tokenize(";");
5833#else
5834 TObjArray* paths = ldpath.Tokenize(":");
5835#endif
5836 TString d;
5837 for (Int_t i = 0; i < paths->GetEntriesFast(); i++) {
5838 d = ((TObjString *)paths->At(i))->GetString();
5839 // check if directory already scanned
5840 Int_t skip = 0;
5841 for (Int_t j = 0; j < i; j++) {
5842 TString pd = ((TObjString *)paths->At(j))->GetString();
5843 if (pd == d) {
5844 skip++;
5845 break;
5846 }
5847 }
5848 if (!skip) {
5849 void* dirp = gSystem->OpenDirectory(d);
5850 if (dirp) {
5851 if (gDebug > 3) {
5852 Info("LoadLibraryMap", "%s", d.Data());
5853 }
5854 const char* f1;
5855 while ((f1 = gSystem->GetDirEntry(dirp))) {
5856 TString f = f1;
5857 if (f.EndsWith(".rootmap")) {
5858 TString p;
5859 p = d + "/" + f;
5861 if (!fRootmapFiles->FindObject(f) && f != ".rootmap") {
5862 if (gDebug > 4) {
5863 Info("LoadLibraryMap", " rootmap file: %s", p.Data());
5864 }
5866
5867 if (ret == 0)
5868 fRootmapFiles->Add(new TNamed(gSystem->BaseName(f), p.Data()));
5869 if (ret == -3) {
5870 // old format
5872 fRootmapFiles->Add(new TNamed(f, p));
5873 }
5874 }
5875 // else {
5876 // fprintf(stderr,"Reject %s because %s is already there\n",p.Data(),f.Data());
5877 // fRootmapFiles->FindObject(f)->ls();
5878 // }
5879 }
5880 }
5881 if (f.BeginsWith("rootmap")) {
5882 TString p;
5883 p = d + "/" + f;
5884 FileStat_t stat;
5885 if (gSystem->GetPathInfo(p, stat) == 0 && R_ISREG(stat.fMode)) {
5886 Warning("LoadLibraryMap", "please rename %s to end with \".rootmap\"", p.Data());
5887 }
5888 }
5889 }
5890 }
5892 }
5893 }
5894 delete paths;
5895 if (fMapfile->GetTable() && !fMapfile->GetTable()->GetEntries()) {
5896 return -1;
5897 }
5898 }
5899 if (rootmapfile && *rootmapfile) {
5901 if (res == 0) {
5902 //TString p = gSystem->ConcatFileName(gSystem->pwd(), rootmapfile);
5903 //fRootmapFiles->Add(new TNamed(gSystem->BaseName(rootmapfile), p.Data()));
5905 }
5906 else if (res == -3) {
5907 // old format
5912 }
5913 }
5914 TEnvRec* rec;
5915 TIter next(fMapfile->GetTable());
5916 while ((rec = (TEnvRec*) next())) {
5917 TString cls = rec->GetName();
5918 if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
5919 // get the first lib from the list of lib and dependent libs
5920 TString libs = rec->GetValue();
5921 if (libs == "") {
5922 continue;
5923 }
5924 TString delim(" ");
5925 TObjArray* tokens = libs.Tokenize(delim);
5926 const char* lib = ((TObjString*)tokens->At(0))->GetName();
5927 // convert "@@" to "::", we used "@@" because TEnv
5928 // considers "::" a terminator
5929 cls.Remove(0, 8);
5930 cls.ReplaceAll("@@", "::");
5931 // convert "-" to " ", since class names may have
5932 // blanks and TEnv considers a blank a terminator
5933 cls.ReplaceAll("-", " ");
5934 if (gDebug > 6) {
5935 const char* wlib = gSystem->DynamicPathName(lib, kTRUE);
5936 if (wlib) {
5937 Info("LoadLibraryMap", "class %s in %s", cls.Data(), wlib);
5938 }
5939 else {
5940 Info("LoadLibraryMap", "class %s in %s (library does not exist)", cls.Data(), lib);
5941 }
5942 delete[] wlib;
5943 }
5944 delete tokens;
5945 }
5946 else if (!strncmp(cls.Data(), "Declare.", 8) && cls.Length() > 8) {
5947 cls.Remove(0, 8);
5948 // convert "-" to " ", since class names may have
5949 // blanks and TEnv considers a blank a terminator
5950 cls.ReplaceAll("-", " ");
5951 fInterpreter->declare(cls.Data());
5952 }
5953 }
5954
5955 // Process the forward declarations collected
5956 cling::Transaction* T = nullptr;
5957 auto compRes= fInterpreter->declare(uniqueString.Data(), &T);
5958 assert(cling::Interpreter::kSuccess == compRes && "A declaration in a rootmap could not be compiled");
5959
5960 if (compRes!=cling::Interpreter::kSuccess){
5961 Warning("LoadLibraryMap",
5962 "Problems in %s declaring '%s' were encountered.", rootmapfile, uniqueString.Data()) ;
5963 }
5964
5965 if (T) {
5966 ExtVisibleStorageAdder evsAdder(fNSFromRootmaps);
5967 for (auto declIt = T->decls_begin(); declIt < T->decls_end(); ++declIt) {
5968 if (declIt->m_DGR.isSingleDecl()) {
5969 if (Decl* D = declIt->m_DGR.getSingleDecl()) {
5970 if (clang::isa<TagDecl>(D) || clang::isa<NamespaceDecl>(D)) {
5971 evsAdder.TraverseDecl(D);
5972 }
5973 }
5974 }
5975 }
5976 }
5977
5978 // clear duplicates
5979
5980 return 0;
5981}
5982
5983////////////////////////////////////////////////////////////////////////////////
5984/// Scan again along the dynamic path for library maps. Entries for the loaded
5985/// shared libraries are unloaded first. This can be useful after reseting
5986/// the dynamic path through TSystem::SetDynamicPath()
5987/// In case of error -1 is returned, 0 otherwise.
5988
5995
5996////////////////////////////////////////////////////////////////////////////////
5997/// Reload the library map entries coming from all the loaded shared libraries,
5998/// after first unloading the current ones.
5999/// In case of error -1 is returned, 0 otherwise.
6000
6002{
6004 const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
6005 const Int_t nrSharedLibs = sharedLibL->GetEntriesFast();
6006 for (Int_t ilib = 0; ilib < nrSharedLibs; ilib++) {
6007 const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
6010 if (ret < 0) {
6011 continue;
6012 }
6014 if (sharedLibBaseStr.EndsWith(".dll")) {
6015 rootMapBaseStr.ReplaceAll(".dll", "");
6016 }
6017 else if (sharedLibBaseStr.EndsWith(".DLL")) {
6018 rootMapBaseStr.ReplaceAll(".DLL", "");
6019 }
6020 else if (sharedLibBaseStr.EndsWith(".so")) {
6021 rootMapBaseStr.ReplaceAll(".so", "");
6022 }
6023 else if (sharedLibBaseStr.EndsWith(".sl")) {
6024 rootMapBaseStr.ReplaceAll(".sl", "");
6025 }
6026 else if (sharedLibBaseStr.EndsWith(".dl")) {
6027 rootMapBaseStr.ReplaceAll(".dl", "");
6028 }
6029 else if (sharedLibBaseStr.EndsWith(".a")) {
6030 rootMapBaseStr.ReplaceAll(".a", "");
6031 }
6032 else {
6033 Error("ReloadAllSharedLibraryMaps", "Unknown library type %s", sharedLibBaseStr.Data());
6034 delete sharedLibL;
6035 return -1;
6036 }
6037 rootMapBaseStr += ".rootmap";
6039 if (!rootMap) {
6040 Error("ReloadAllSharedLibraryMaps", "Could not find rootmap %s in path", rootMapBaseStr.Data());
6041 delete[] rootMap;
6042 delete sharedLibL;
6043 return -1;
6044 }
6045 const Int_t status = LoadLibraryMap(rootMap);
6046 if (status < 0) {
6047 Error("ReloadAllSharedLibraryMaps", "Error loading map %s", rootMap);
6048 delete[] rootMap;
6049 delete sharedLibL;
6050 return -1;
6051 }
6052 delete[] rootMap;
6053 }
6054 delete sharedLibL;
6055 return 0;
6056}
6057
6058////////////////////////////////////////////////////////////////////////////////
6059/// Unload the library map entries coming from all the loaded shared libraries.
6060/// Returns 0 if succesful
6061
6063{
6065 const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
6066 for (Int_t ilib = 0; ilib < sharedLibL->GetEntriesFast(); ilib++) {
6067 const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
6070 }
6071 delete sharedLibL;
6072 return 0;
6073}
6074
6075////////////////////////////////////////////////////////////////////////////////
6076/// Unload library map entries coming from the specified library.
6077/// Returns -1 in case no entries for the specified library were found,
6078/// 0 otherwise.
6079
6081{
6082 if (!fMapfile || !library || !*library) {
6083 return 0;
6084 }
6086 Ssiz_t idx = libname.Last('.');
6087 if (idx != kNPOS) {
6088 libname.Remove(idx);
6089 }
6090 size_t len = libname.Length();
6091 TEnvRec *rec;
6092 TIter next(fMapfile->GetTable());
6094 Int_t ret = 0;
6095 while ((rec = (TEnvRec *) next())) {
6096 TString cls = rec->GetName();
6097 if (cls.Length() > 2) {
6098 // get the first lib from the list of lib and dependent libs
6099 TString libs = rec->GetValue();
6100 if (libs == "") {
6101 continue;
6102 }
6103 TString delim(" ");
6104 TObjArray* tokens = libs.Tokenize(delim);
6105 const char* lib = ((TObjString *)tokens->At(0))->GetName();
6106 if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
6107 // convert "@@" to "::", we used "@@" because TEnv
6108 // considers "::" a terminator
6109 cls.Remove(0, 8);
6110 cls.ReplaceAll("@@", "::");
6111 // convert "-" to " ", since class names may have
6112 // blanks and TEnv considers a blank a terminator
6113 cls.ReplaceAll("-", " ");
6114 }
6115 if (!strncmp(lib, libname.Data(), len)) {
6116 if (fMapfile->GetTable()->Remove(rec) == nullptr) {
6117 Error("UnloadLibraryMap", "entry for <%s, %s> not found in library map table", cls.Data(), lib);
6118 ret = -1;
6119 }
6120 }
6121 delete tokens;
6122 }
6123 }
6124 if (ret >= 0) {
6126 if (!library_rootmap.EndsWith(".rootmap"))
6127 library_rootmap.Append(".rootmap");
6128 TNamed* mfile = nullptr;
6131 delete mfile;
6132 }
6134 }
6135 return ret;
6136}
6137
6138////////////////////////////////////////////////////////////////////////////////
6139/// Register the AutoLoading information for a class.
6140/// libs is a space separated list of libraries.
6141
6142Int_t TCling::SetClassSharedLibs(const char *cls, const char *libs)
6143{
6144 if (!cls || !*cls)
6145 return 0;
6146
6147 TString key = TString("Library.") + cls;
6148 // convert "::" to "@@", we used "@@" because TEnv
6149 // considers "::" a terminator
6150 key.ReplaceAll("::", "@@");
6151 // convert "-" to " ", since class names may have
6152 // blanks and TEnv considers a blank a terminator
6153 key.ReplaceAll(" ", "-");
6154
6156 if (!fMapfile) {
6157 fMapfile = new TEnv();
6159
6162
6163 InitRootmapFile(".rootmap");
6164 }
6165 //fMapfile->SetValue(key, libs);
6167 return 1;
6168}
6169
6170////////////////////////////////////////////////////////////////////////////////
6171/// Demangle the name (from the typeinfo) and then request the class
6172/// via the usual name based interface (TClass::GetClass).
6173
6174TClass *TCling::GetClass(const std::type_info& typeinfo, Bool_t load) const
6175{
6176 int err = 0;
6178 if (err) return nullptr;
6181 return theClass;
6182}
6183
6184////////////////////////////////////////////////////////////////////////////////
6185/// Load library containing the specified class. Returns 0 in case of error
6186/// and 1 in case if success.
6187
6188Int_t TCling::AutoLoad(const std::type_info& typeinfo, Bool_t knowDictNotLoaded /* = kFALSE */)
6189{
6190 assert(IsClassAutoLoadingEnabled() && "Calling when AutoLoading is off!");
6191
6192 int err = 0;
6194 if (err) {
6195 return 0;
6196 }
6197
6198 std::string demangled_name(demangled_name_c);
6200
6201 // AutoLoad expects (because TClass::GetClass already prepares it that way) a
6202 // shortened name.
6205
6206 // No need to worry about typedef, they aren't any ... but there are
6207 // inlined namespaces ...
6208
6210 if (result == 0) {
6213 }
6214
6215 return result;
6216}
6217
6218////////////////////////////////////////////////////////////////////////////////
6219// Get the list of 'published'/'known' library for the class and load them.
6221{
6222 Int_t status = 0;
6223
6224 // lookup class to find list of dependent libraries
6226 if (!deplibs.IsNull()) {
6227 TString delim(" ");
6228 TObjArray* tokens = deplibs.Tokenize(delim);
6229 for (Int_t i = (tokens->GetEntriesFast() - 1); i > 0; --i) {
6230 const char* deplib = ((TObjString*)tokens->At(i))->GetName();
6231 if (gROOT->LoadClass(cls, deplib) == 0) {
6232 if (gDebug > 0) {
6233 gCling->Info("TCling::AutoLoad",
6234 "loaded dependent library %s for %s", deplib, cls);
6235 }
6236 }
6237 else {
6238 gCling->Error("TCling::AutoLoad",
6239 "failure loading dependent library %s for %s",
6240 deplib, cls);
6241 }
6242 }
6243 const char* lib = ((TObjString*)tokens->At(0))->GetName();
6244 if (lib && lib[0]) {
6245 if (gROOT->LoadClass(cls, lib) == 0) {
6246 if (gDebug > 0) {
6247 gCling->Info("TCling::AutoLoad",
6248 "loaded library %s for %s", lib, cls);
6249 }
6250 status = 1;
6251 }
6252 else {
6253 gCling->Error("TCling::AutoLoad",
6254 "failure loading library %s for %s", lib, cls);
6255 }
6256 }
6257 delete tokens;
6258 }
6259
6260 return status;
6261}
6262
6263////////////////////////////////////////////////////////////////////////////////
6264// Iterate through the data member of the class (either through the TProtoClass
6265// or through Cling) and trigger, recursively, the loading the necessary libraries.
6266// \note `cls` is expected to be already normalized!
6267// \returns 1 on success.
6268Int_t TCling::DeepAutoLoadImpl(const char *cls, std::unordered_set<std::string> &visited,
6269 bool nameIsNormalized)
6270{
6271 // Try to insert; if insertion failed because the entry existed, DeepAutoLoadImpl()
6272 // has previously (within the same call to `AutoLoad()`) tried to load this class
6273 // and we are done, whether success or not, as it won't work better now than before,
6274 // because there is no additional information now compared to before.
6275 if (!visited.insert(std::string(cls)).second)
6276 return 1;
6277
6278 if (ShallowAutoLoadImpl(cls) == 0) {
6279 // If ShallowAutoLoadImpl() has an error, we have an error.
6280 return 0;
6281 }
6282
6283 // Now look through the TProtoClass to load the required library/dictionary
6285 for (auto element : proto->GetData()) {
6286 if (element->IsBasic())
6287 continue;
6288 const char *subtypename = element->GetTypeName();
6290 // Failure to load a dictionary is not (quite) a failure load
6291 // the top-level library. If we return false here, then
6292 // we would end up in a situation where the library and thus
6293 // the dictionary is loaded for "cls" but the TClass is
6294 // not created and/or marked as unavailable (in case where
6295 // AutoLoad is called from TClass::GetClass).
6296 DeepAutoLoadImpl(subtypename, visited, true /*normalized*/);
6297 }
6298 }
6299 return 1;
6300 }
6301
6302 // We found no TProtoClass for cls.
6303 auto classinfo = gInterpreter->ClassInfo_Factory(cls);
6304 if (classinfo && gInterpreter->ClassInfo_IsValid(classinfo)
6305 && !(gInterpreter->ClassInfo_Property(classinfo) & kIsEnum))
6306 {
6308 while (gInterpreter->DataMemberInfo_Next(memberinfo)) {
6309 if (gInterpreter->DataMemberInfo_TypeProperty(memberinfo) & ::kIsFundamental)
6310 continue;
6311 auto membertypename = TClassEdit::GetLong64_Name(gInterpreter->TypeName(gInterpreter->DataMemberInfo_TypeTrueName(memberinfo)));
6313 // Failure to load a dictionary is not (quite) a failure load
6314 // the top-level library. See detailed comment in the TProtoClass
6315 // branch (above).
6316 (void)DeepAutoLoadImpl(membertypename.c_str(), visited, true /*normalized*/);
6317 }
6318 }
6319 gInterpreter->DataMemberInfo_Delete(memberinfo);
6320 }
6321 gInterpreter->ClassInfo_Delete(classinfo);
6322 return 1;
6323}
6324
6325////////////////////////////////////////////////////////////////////////////////
6326/// Load library containing the specified class. Returns 0 in case of error
6327/// and 1 in case if success.
6328
6330{
6331 // Prevent update to IsClassAutoloading between our check and our actions.
6333
6334 // TClass::GetClass explicitly calls gInterpreter->AutoLoad. When called from
6335 // rootcling (in *_rdict.pcm file generation) it is a no op.
6336 // FIXME: We should avoid calling autoload when we know we are not supposed
6337 // to and transform this check into an assert.
6339 // Never load any library from rootcling/genreflex.
6340 if (gDebug > 2) {
6341 Info("TCling::AutoLoad", "Explicitly disabled (the class name is %s)", cls);
6342 }
6343 return 0;
6344 }
6345
6346 assert(IsClassAutoLoadingEnabled() && "Calling when AutoLoading is off!");
6347
6349
6351 // The library is already loaded as the class's dictionary is known.
6352 // Return success.
6353 // Note: the name (cls) is expected to be normalized as it comes either
6354 // from a callbacks (that can/should calculate the normalized name from the
6355 // decl) or from TClass::GetClass (which does also calculate the normalized
6356 // name).
6357 return 1;
6358 }
6359
6360 if (gDebug > 2) {
6361 Info("TCling::AutoLoad",
6362 "Trying to autoload for %s", cls);
6363 }
6364
6365 if (!gROOT || !gInterpreter || gROOT->TestBit(TObject::kInvalidObject)) {
6366 if (gDebug > 2) {
6367 Info("TCling::AutoLoad",
6368 "Disabled due to gROOT or gInterpreter being invalid/not ready (the class name is %s)", cls);
6369 }
6370 return 0;
6371 }
6372 // Prevent the recursion when the library dictionary are loaded.
6374 // Try using externally provided callback first.
6375 if (fAutoLoadCallBack) {
6377 if (success)
6378 return success;
6379 }
6380
6381 // During the 'Deep' part of the search we will call GetClassSharedLibsForModule
6382 // (when module are enabled) which might end up calling AutoParsing but
6383 // that should only be for the cases where the library has no generated pcm
6384 // and in that case a rootmap should be available.
6385 // This avoids a very costly operation (for generally no gain) but reduce the
6386 // quality of the search (i.e. bad in case of library with no pcm and no rootmap
6387 // file).
6389 std::unordered_set<std::string> visited;
6390 return DeepAutoLoadImpl(cls, visited, false /*normalized*/);
6391}
6392
6393////////////////////////////////////////////////////////////////////////////////
6394/// Parse the payload or header.
6395
6396static cling::Interpreter::CompilationResult ExecAutoParse(const char *what,
6397 Bool_t header,
6398 cling::Interpreter *interpreter)
6399{
6400 std::string code = gNonInterpreterClassDef ;
6401 if (!header) {
6402 // This is the complete header file content and not the
6403 // name of a header.
6404 code += what;
6405
6406 } else {
6407 code += ("#include \"");
6408 code += what;
6409 code += "\"\n";
6410 }
6411 code += ("#ifdef __ROOTCLING__\n"
6412 "#undef __ROOTCLING__\n"
6414 "#endif");
6415
6416 cling::Interpreter::CompilationResult cr;
6417 {
6418 // scope within which diagnostics are de-activated
6419 // For now we disable diagnostics because we saw them already at
6420 // dictionary generation time. That won't be an issue with the PCMs.
6421
6422 Sema &SemaR = interpreter->getSema();
6424 clangDiagSuppr diagSuppr(SemaR.getDiagnostics());
6425
6426 #if defined(R__MUST_REVISIT)
6427 #if R__MUST_REVISIT(6,2)
6428 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
6429 #endif
6430 #endif
6431
6432 cr = interpreter->parseForModule(code);
6433 }
6434 return cr;
6435}
6436
6437////////////////////////////////////////////////////////////////////////////////
6438/// Helper routine for TCling::AutoParse implementing the actual call to the
6439/// parser and looping over template parameters (if
6440/// any) and when they don't have a registered header to autoparse,
6441/// recurse over their template parameters.
6442///
6443/// Returns the number of header parsed.
6444
6446{
6447 // We assume the lock has already been taken.
6448 // R__LOCKGUARD(gInterpreterMutex);
6449
6451 unsigned long offset = 0;
6452 if (strncmp(cls, "const ", 6) == 0) {
6453 offset = 6;
6454 }
6455
6456 // Loop on the possible autoparse keys
6457 bool skipFirstEntry = false;
6458 std::vector<std::string> autoparseKeys;
6459 if (strchr(cls, '<')) {
6460 int nestedLoc = 0;
6462 // Check if we can skip the name of the template in the autoparses
6463 // Take all the scopes one by one. If all of them are in the AST, we do not
6464 // need to autoparse for that particular template.
6465 if (!autoparseKeys.empty() && !autoparseKeys[0].empty()) {
6466 // autoparseKeys[0] is empty when the input is not a template instance.
6467 // The case strchr(cls, '<') != 0 but still not a template instance can
6468 // happens 'just' for string (GetSplit replaces the template by the short name
6469 // and then use that for thew splitting)
6471 auto tokens = templateName.Tokenize("::");
6472 clang::NamedDecl* previousScopeAsNamedDecl = nullptr;
6473 clang::DeclContext* previousScopeAsContext = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
6475 previousScopeAsContext = fInterpreter->getSema().getStdNamespace();
6476 auto nTokens = tokens->GetEntriesFast();
6477 for (Int_t tk = 0; tk < nTokens; ++tk) {
6478 auto scopeObj = tokens->UncheckedAt(tk);
6479 auto scopeName = ((TObjString*) scopeObj)->String().Data();
6480 previousScopeAsNamedDecl = cling::utils::Lookup::Named(&fInterpreter->getSema(), scopeName, previousScopeAsContext);
6481 // Check if we have multiple nodes in the AST with this name
6482 if ((clang::NamedDecl*)-1 == previousScopeAsNamedDecl) break;
6483 previousScopeAsContext = llvm::dyn_cast_or_null<clang::DeclContext>(previousScopeAsNamedDecl);
6484 if (!previousScopeAsContext) break; // this is not a context
6485 }
6486 delete tokens;
6487 // Now, let's check if the last scope, the template, has a definition, i.e. it's not a fwd decl
6488 if ((clang::NamedDecl*)-1 != previousScopeAsNamedDecl) {
6489 if (auto templateDecl = llvm::dyn_cast_or_null<clang::ClassTemplateDecl>(previousScopeAsNamedDecl)) {
6490 if (auto templatedDecl = templateDecl->getTemplatedDecl()) {
6491 skipFirstEntry = templatedDecl->hasDefinition();
6492 }
6493 }
6494 }
6495
6496 }
6497 }
6498 if (topLevel) autoparseKeys.emplace_back(cls);
6499
6500 for (const auto & apKeyStr : autoparseKeys) {
6501 if (skipFirstEntry) {
6502 skipFirstEntry=false;
6503 continue;
6504 }
6505 if (apKeyStr.empty()) continue;
6506 const char *apKey = apKeyStr.c_str();
6508 // If the class was not looked up
6509 if (gDebug > 1) {
6510 Info("TCling::AutoParse",
6511 "Starting autoparse for %s\n", apKey);
6512 }
6513 if (fLookedUpClasses.insert(normNameHash).second) {
6514 auto const &iter = fClassesHeadersMap.find(normNameHash);
6515 if (iter != fClassesHeadersMap.end()) {
6516 const cling::Transaction *T = fInterpreter->getCurrentTransaction();
6518 auto const &hNamesPtrs = iter->second;
6519 if (gDebug > 1) {
6520 Info("TCling::AutoParse",
6521 "We can proceed for %s. We have %s headers.", apKey, std::to_string(hNamesPtrs.size()).c_str());
6522 }
6523 for (auto & hName : hNamesPtrs) {
6524 if (fParsedPayloadsAddresses.count(hName) == 1) continue;
6525 if (0 != fPayloads.count(normNameHash)) {
6526 float initRSSval=0.f, initVSIZEval=0.f;
6527 (void) initRSSval; // Avoid unused var warning
6528 (void) initVSIZEval;
6529 if (gDebug > 0) {
6530 Info("AutoParse",
6531 "Parsing full payload for %s", apKey);
6534 initRSSval = 1e-3*info.fMemResident;
6535 initVSIZEval = 1e-3*info.fMemVirtual;
6536 }
6538 if (cRes != cling::Interpreter::kSuccess) {
6539 if (hName[0] == '\n')
6540 Error("AutoParse", "Error parsing payload code for class %s with content:\n%s", apKey, hName);
6541 } else {
6544 if (gDebug > 0){
6547 float endRSSval = 1e-3*info.fMemResident;
6548 float endVSIZEval = 1e-3*info.fMemVirtual;
6549 Info("Autoparse", ">>> RSS key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initRSSval, endRSSval, endRSSval-initRSSval);
6550 Info("Autoparse", ">>> VSIZE key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initVSIZEval, endVSIZEval, endVSIZEval-initVSIZEval);
6551 }
6552 }
6553 } else if (!IsLoaded(hName)) {
6554 if (gDebug > 0) {
6555 Info("AutoParse",
6556 "Parsing single header %s", hName);
6557 }
6559 if (cRes != cling::Interpreter::kSuccess) {
6560 Error("AutoParse", "Error parsing headerfile %s for class %s.", hName, apKey);
6561 } else {
6563 }
6564 }
6565 }
6566 }
6567 else {
6568 // There is no header registered for this class, if this a
6569 // template, it will be instantiated if/when it is requested
6570 // and if we do no load/parse its components we might end up
6571 // not using an eventual specialization.
6572 if (strchr(apKey, '<')) {
6574 }
6575 }
6576 }
6577 }
6578
6579 return nHheadersParsed;
6580
6581}
6582
6583////////////////////////////////////////////////////////////////////////////////
6584/// Parse the headers relative to the class
6585/// Returns 1 in case of success, 0 in case of failure
6586
6588{
6589 if (llvm::StringRef(cls).contains("(lambda)"))
6590 return 0;
6591
6594 return AutoLoad(cls);
6595 } else {
6596 return 0;
6597 }
6598 }
6599
6601
6602 if (gDebug > 1) {
6603 Info("TCling::AutoParse",
6604 "Trying to autoparse for %s", cls);
6605 }
6606
6607 // The catalogue of headers is in the dictionary
6609 && !gClassTable->GetDictNorm(cls)) {
6610 // Need RAII against recursive (dictionary payload) parsing (ROOT-8445).
6612 fInterpreter->getSema());
6613 AutoLoad(cls, true /*knowDictNotLoaded*/);
6614 }
6615
6616 // Prevent the recursion when the library dictionary are loaded.
6618
6619 // No recursive header parsing on demand; we require headers to be standalone.
6621
6622 Int_t nHheadersParsed = AutoParseImplRecurse(cls,/*topLevel=*/ true);
6623
6625
6626 return nHheadersParsed > 0 ? 1 : 0;
6627}
6628
6629// This is a function which gets callback from cling when DynamicLibraryManager->loadLibrary failed for some reason.
6630// Try to solve the problem by AutoLoading. Return true when AutoLoading success, return
6631// false if not.
6632bool TCling::LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
6633{
6635 if (errMsg.contains("undefined symbol: ")) {
6636 // This branch is taken when the callback was from DynamicLibraryManager::loadLibrary
6637 std::string mangled_name = std::string(errMsg.split("undefined symbol: ").second);
6638 void* res = ((TCling*)gCling)->LazyFunctionCreatorAutoload(mangled_name);
6639 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
6640 if (res && DLM && (DLM->loadLibrary(libStem, permanent, resolved) == cling::DynamicLibraryManager::kLoadLibSuccess))
6641 // Return success when LazyFunctionCreatorAutoload could find mangled_name
6642 return true;
6643 } else {
6644 // The callback is from IncrementalExecutor::diagnoseUnresolvedSymbols
6646 return true;
6647 }
6648
6649 return false;
6650}
6651
6652////////////////////////////////////////////////////////////////////////////////
6653/// Autoload a library based on a missing symbol.
6654
6657
6658 // We have already loaded the library.
6659 if (void* Addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(dlsym_mangled_name))
6660 return Addr;
6661
6662 const cling::DynamicLibraryManager &DLM = *GetInterpreterImpl()->getDynamicLibraryManager();
6664
6665 auto LibLoader = [](const std::string& LibName) -> bool {
6666 if (gSystem->Load(LibName.c_str(), "", false) < 0) {
6667 ::Error("TCling__LazyFunctionCreatorAutoloadForModule",
6668 "Failed to load library %s", LibName.c_str());
6669 return false;
6670 }
6671 return true; //success.
6672 };
6673
6674 std::string libName = DLM.searchLibrariesForSymbol(mangled_name,
6675 /*searchSystem=*/ true);
6676
6677 assert(!llvm::StringRef(libName).starts_with("libNew") && "We must not resolve symbols from libNew!");
6678
6679 if (libName.empty())
6680 return nullptr;
6681
6682 if (!LibLoader(libName))
6683 return nullptr;
6684
6685 return llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(dlsym_mangled_name);
6686}
6687
6688////////////////////////////////////////////////////////////////////////////////
6689
6691{
6692 return fNSFromRootmaps.count(nsDecl) != 0;
6693}
6694
6695////////////////////////////////////////////////////////////////////////////////
6696/// Internal function. Actually do the update of the ClassInfo when seeing
6697// new TagDecl or NamespaceDecl.
6698void TCling::RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
6699{
6700
6702 if (cci) {
6703 // If we only had a forward declaration then update the
6704 // TClingClassInfo with the definition if we have it now.
6705 const NamedDecl *oldDef = llvm::dyn_cast_or_null<NamedDecl>(cci->GetDecl());
6706 if (!oldDef || (def && def != oldDef)) {
6707 cl->ResetCaches();
6708 TClass::RemoveClassDeclId(cci->GetDeclId());
6709 if (def) {
6710 if (cci->GetType()) {
6711 // It's a tag decl, not a namespace decl.
6712 cci->Init(*cci->GetType());
6713 TClass::AddClassToDeclIdMap(cci->GetDeclId(), cl);
6714 } else {
6715 Error("RefreshClassInfo", "Should not need to update the classInfo a non type decl: %s", oldDef->getNameAsString().c_str());
6716 }
6717 }
6718 }
6719 } else if (!cl->TestBit(TClass::kLoading) && !cl->fHasRootPcmInfo) {
6720 cl->ResetCaches();
6721 if (strncmp(cl->GetName(),"tuple<",strlen("tuple<"))==0) {
6722 // We need to use the Emulated Tuple but we should not trigger parsing
6723 // yet, so delay the creation of the ClassInfo
6724 delete ((TClingClassInfo *)cl->fClassInfo);
6725 cl->fClassInfo = nullptr;
6726 cl->fCanLoadClassInfo = true;
6728 if (cl->fState != TClass::kHasTClassInit) {
6730 }
6731 return;
6732 }
6733 // yes, this is almost a waste of time, but we do need to lookup
6734 // the 'type' corresponding to the TClass anyway in order to
6735 // preserve the opaque typedefs (Double32_t)
6736 if (!alias && def != nullptr)
6738 else
6740 if (((TClingClassInfo *)cl->fClassInfo)->IsValid()) {
6741 // We now need to update the state and bits.
6742 if (cl->fState != TClass::kHasTClassInit) {
6743 // if (!cl->fClassInfo->IsValid()) cl->fState = TClass::kForwardDeclared; else
6745 }
6746 TClass::AddClassToDeclIdMap(((TClingClassInfo *)(cl->fClassInfo))->GetDeclId(), cl);
6747 } else {
6748 delete ((TClingClassInfo *)cl->fClassInfo);
6749 cl->fClassInfo = nullptr;
6750 }
6751 }
6752}
6753
6754////////////////////////////////////////////////////////////////////////////////
6755/// Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
6757{
6758 const TagDecl *td = dyn_cast<TagDecl>(ND);
6760 const NamedDecl *canon = nullptr;
6761
6762 std::string name;
6763 TagDecl* tdDef = nullptr;
6764 if (td) {
6765 canon = tdDef = td->getDefinition();
6766 // Let's pass the decl to the TClass only if it has a definition.
6767 if (!tdDef) return;
6768
6769 if (!tdDef->isCompleteDefinition() || llvm::isa<clang::FunctionDecl>(tdDef->getDeclContext())) {
6770 // Ignore incomplete definition.
6771 // Ignore declaration within a function.
6772 return;
6773 }
6774
6775 auto declName = tdDef->getNameAsString();
6776 // Check if we have registered the unqualified name into the list
6777 // of TClass that are in kNoInfo, kEmulated or kFwdDeclaredState.
6778 // Since this is used as heureutistic to avoid spurrious calls to GetNormalizedName
6779 // the unqualified name is sufficient (and the fully qualified name might be
6780 // 'wrong' if there is difference in spelling in the template paramters (for example)
6782 // fprintf (stderr,"WARNING: Impossible to find a TClassEntry in kNoInfo or kEmulated the decl of which would be called %s. Skip w/o building the normalized name.\n",declName.c_str() );
6783 return;
6784 }
6785
6786 clang::QualType type(tdDef->getTypeForDecl(), 0);
6788 } else if (ns) {
6789 canon = ns->getCanonicalDecl();
6790 name = ND->getQualifiedNameAsString();
6791 } else {
6792 name = ND->getQualifiedNameAsString();
6793 }
6794
6795 // Supposedly we are being called while something is being
6796 // loaded ... let's now tell the autoloader to do the work
6797 // yet another time.
6799 // FIXME: There can be more than one TClass for a single decl.
6800 // for example vector<double> and vector<Double32_t>
6801 TClass* cl = (TClass*)gROOT->GetListOfClasses()->FindObject(name.c_str());
6802 if (cl && GetModTClasses().find(cl) == GetModTClasses().end()) {
6803 RefreshClassInfo(cl, canon, false);
6804 }
6805 // And here we should find the other 'aliases' (eg. vector<Double32_t>)
6806 // and update them too:
6807 // foreach(aliascl in gROOT->GetListOfClasses()->FindAliasesOf(name.c_str()))
6808 // RefreshClassInfo(cl, tdDef, true);
6809}
6810
6811////////////////////////////////////////////////////////////////////////////////
6812/// No op: see TClingCallbacks
6813
6817
6818//______________________________________________________________________________
6819//FIXME: Factor out that function in TClass, because TClass does it already twice
6821{
6822 // This is a no-op as part of the API.
6823 // TCling uses UpdateClassInfoWithDecl() instead.
6824}
6825
6826////////////////////////////////////////////////////////////////////////////////
6827/// Update all canvases at end the terminal input command.
6828
6830{
6831 TIter next(gROOT->GetListOfCanvases());
6832 TVirtualPad* canvas;
6833 while ((canvas = (TVirtualPad*)next())) {
6834 canvas->Update();
6835 }
6836}
6837
6838////////////////////////////////////////////////////////////////////////////////
6839
6840void TCling::UpdateListsOnCommitted(const cling::Transaction &T) {
6841 std::set<TClass*> modifiedTClasses; // TClasses that require update after this transaction
6842
6843 // If the transaction does not contain anything we can return earlier.
6844 if (!HandleNewTransaction(T)) return;
6845
6846 bool isTUTransaction = false;
6847 if (!T.empty() && T.decls_begin() + 1 == T.decls_end() && !T.hasNestedTransactions()) {
6848 clang::Decl* FirstDecl = *(T.decls_begin()->m_DGR.begin());
6849 if (llvm::isa<clang::TranslationUnitDecl>(FirstDecl)) {
6850 // The is the first transaction, we have to expose to meta
6851 // what's already in the AST.
6852 isTUTransaction = true;
6853 }
6854 }
6855
6856 std::set<const void*> TransactionDeclSet;
6857 if (!isTUTransaction && T.decls_end() - T.decls_begin()) {
6858 const clang::Decl* WrapperFD = T.getWrapperFD();
6859 for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
6860 I != E; ++I) {
6861 if (I->m_Call != cling::Transaction::kCCIHandleTopLevelDecl
6862 && I->m_Call != cling::Transaction::kCCIHandleTagDeclDefinition)
6863 continue;
6864
6865 for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6866 DE = I->m_DGR.end(); DI != DE; ++DI) {
6867 if (*DI == WrapperFD)
6868 continue;
6869 TransactionDeclSet.insert(*DI);
6870 ((TCling*)gCling)->HandleNewDecl(*DI, false, modifiedTClasses);
6871 }
6872 }
6873 }
6874
6875 // The above might trigger more decls to be deserialized.
6876 // Thus the iteration over the deserialized decls must be last.
6877 for (cling::Transaction::const_iterator I = T.deserialized_decls_begin(),
6878 E = T.deserialized_decls_end(); I != E; ++I) {
6879 for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6880 DE = I->m_DGR.end(); DI != DE; ++DI)
6881 if (TransactionDeclSet.find(*DI) == TransactionDeclSet.end()) {
6882 //FIXME: HandleNewDecl should take DeclGroupRef
6883 ((TCling*)gCling)->HandleNewDecl(*DI, /*isDeserialized*/true,
6885 }
6886 }
6887
6888
6889 // When fully building the reflection info in TClass, a deserialization
6890 // could be triggered, which may result in request for building the
6891 // reflection info for the same TClass. This in turn will clear the caches
6892 // for the TClass in-flight and cause null ptr derefs.
6893 // FIXME: This is a quick fix, solving most of the issues. The actual
6894 // question is: Shouldn't TClass provide a lock mechanism on update or lock
6895 // itself until the update is done.
6896 //
6897 std::vector<TClass*> modifiedTClassesDiff(modifiedTClasses.size());
6898 std::vector<TClass*>::iterator it;
6900 ((TCling*)gCling)->GetModTClasses().begin(),
6901 ((TCling*)gCling)->GetModTClasses().end(),
6904
6905 // Lock the TClass for updates
6906 ((TCling*)gCling)->GetModTClasses().insert(modifiedTClassesDiff.begin(),
6908 for (std::vector<TClass*>::const_iterator I = modifiedTClassesDiff.begin(),
6909 E = modifiedTClassesDiff.end(); I != E; ++I) {
6910 // Make sure the TClass has not been deleted.
6911 if (!gROOT->GetListOfClasses()->FindObject(*I)) {
6912 continue;
6913 }
6914 // Could trigger deserialization of decls.
6915 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
6916 // Unlock the TClass for updates
6917 ((TCling*)gCling)->GetModTClasses().erase(*I);
6918
6919 }
6920}
6921
6922///\brief Invalidate stored TCling state for declarations included in transaction `T'.
6923///
6924void TCling::UpdateListsOnUnloaded(const cling::Transaction &T)
6925{
6927
6928 auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
6929 (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
6930 (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
6931 (TListOfEnums *)gROOT->GetListOfEnums());
6932
6933 cling::Transaction::const_nested_iterator iNested = T.nested_begin();
6934 for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
6935 I != E; ++I) {
6936 if (I->m_Call == cling::Transaction::kCCIHandleVTable)
6937 continue;
6938 if (I->m_Call == cling::Transaction::kCCINone) {
6940 ++iNested;
6941 continue;
6942 }
6943
6944 for (auto &D : I->m_DGR)
6946 }
6947}
6948
6949///\brief Invalidate cached TCling information for the given global declaration.
6950///
6952 auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
6953 (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
6954 (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
6955 (TListOfEnums *)gROOT->GetListOfEnums());
6957}
6958
6959///\brief Invalidate cached TCling information for the given declaration, and
6960/// removed it from the appropriate object list.
6961///\param[in] Lists - std::tuple<TListOfDataMembers&, TListOfFunctions&,
6962/// TListOfFunctionTemplates&, TListOfEnums&>
6963/// of pointers to the (global/class) object lists.
6964///\param[in] D - Decl to discard.
6965///
6969 TListOfEnums*> &Lists, const Decl *D) {
6970 if (D->isFromASTFile()) // `D' came from the PCH; ignore
6971 return;
6972
6973 TListOfDataMembers &LODM = *(std::get<0>(Lists));
6974 TListOfFunctions &LOF = *(std::get<1>(Lists));
6975 TListOfFunctionTemplates &LOFT = *(std::get<2>(Lists));
6976 TListOfEnums &LOE = *(std::get<3>(Lists));
6977
6979 TObject *O = LODM.Find((TDictionary::DeclId_t)D);
6980 if (LODM.GetClass())
6981 RemoveAndInvalidateObject(LODM, static_cast<TDataMember *>(O));
6982 else
6983 RemoveAndInvalidateObject(LODM, static_cast<TGlobal *>(O));
6984 } else if (isa<FunctionDecl>(D)) {
6986 } else if (isa<FunctionTemplateDecl>(D)) {
6988 } else if (isa<EnumDecl>(D)) {
6989 TEnum *E = LOE.Find((TDictionary::DeclId_t)D);
6990 if (!E)
6991 return;
6992
6993 // Try to invalidate enumerators (for unscoped enumerations).
6994 for (TIter I = E->GetConstants(); auto EC = (TEnumConstant *)I(); )
6996 (TEnumConstant *)LODM.FindObject(EC->GetName()));
6997
6999 } else if (isa<RecordDecl>(D) || isa<NamespaceDecl>(D)) {
7001 return;
7002
7003 std::vector<TClass *> Classes;
7004 if (!TClass::GetClass(D->getCanonicalDecl(), Classes))
7005 return;
7006 for (auto &C : Classes) {
7007 auto Lists = std::make_tuple((TListOfDataMembers *)C->GetListOfDataMembers(),
7008 (TListOfFunctions *)C->GetListOfMethods(),
7009 (TListOfFunctionTemplates *)C->GetListOfFunctionTemplates(),
7010 (TListOfEnums *)C->GetListOfEnums());
7011 for (auto &I : cast<DeclContext>(D)->decls())
7013
7014 // For NamespaceDecl (redeclarable), only invalidate this redecl.
7015 if (D->getKind() != Decl::Namespace || cast<NamespaceDecl>(D)->isFirstDecl())
7016 C->ResetClassInfo();
7017 }
7018 }
7019}
7020
7021////////////////////////////////////////////////////////////////////////////////
7022// If an autoparse was done during a transaction and that it is rolled back,
7023// we need to make sure the next request for the same autoparse will be
7024// honored.
7025void TCling::TransactionRollback(const cling::Transaction &T) {
7026 auto const &triter = fTransactionHeadersMap.find(&T);
7027 if (triter != fTransactionHeadersMap.end()) {
7028 std::size_t normNameHash = triter->second;
7029
7031
7032 auto const &iter = fClassesHeadersMap.find(normNameHash);
7033 if (iter != fClassesHeadersMap.end()) {
7034 auto const &hNamesPtrs = iter->second;
7035 for (auto &hName : hNamesPtrs) {
7036 if (gDebug > 0) {
7037 Info("TransactionRollback",
7038 "Restoring ability to autoaparse: %s", hName);
7039 }
7041 }
7042 }
7043 }
7044}
7045
7046////////////////////////////////////////////////////////////////////////////////
7047
7048void TCling::LibraryLoaded(const void* dyLibHandle, const char* canonicalName) {
7049// R__LOCKGUARD_CLING(gInterpreterMutex);
7050// UpdateListOfLoadedSharedLibraries();
7051}
7052
7053////////////////////////////////////////////////////////////////////////////////
7054
7055void TCling::LibraryUnloaded(const void* dyLibHandle, const char* canonicalName) {
7056 fPrevLoadedDynLibInfo = nullptr;
7057 fSharedLibs = "";
7058}
7059
7060////////////////////////////////////////////////////////////////////////////////
7061/// Return the list of shared libraries loaded into the process.
7062
7069
7070static std::string GetClassSharedLibsForModule(const char *cls, cling::LookupHelper &LH, bool skipCore)
7071{
7072 if (!cls || !*cls)
7073 return {};
7074
7075 using namespace clang;
7076 if (const Decl *D = LH.findScope(cls, cling::LookupHelper::NoDiagnostics,
7077 /*type*/ nullptr, /*instantiate*/ false)) {
7078 if (!D->isFromASTFile()) {
7079 if (gDebug > 5)
7080 Warning("GetClassSharedLibsForModule", "Decl found for %s is not part of a module", cls);
7081 return {};
7082 }
7083 class ModuleCollector : public ConstDeclVisitor<ModuleCollector> {
7084 llvm::DenseSet<Module *> &m_TopLevelModules;
7085
7086 public:
7087 ModuleCollector(llvm::DenseSet<Module *> &TopLevelModules) : m_TopLevelModules(TopLevelModules) {}
7088 void Collect(const Decl *D) { Visit(D); }
7089
7090 void VisitDecl(const Decl *D)
7091 {
7092 // FIXME: Such case is described ROOT-7765 where
7093 // ROOT_GENERATE_DICTIONARY does not contain the list of headers.
7094 // They are specified as #includes in the LinkDef file. This leads to
7095 // generation of incomplete modulemap files and this logic fails to
7096 // compute the corresponding module of D.
7097 // FIXME: If we want to support such a case, we should not rely on
7098 // the contents of the modulemap but mangle D and look it up in the
7099 // .so files.
7100 if (!D->hasOwningModule())
7101 return;
7102 if (Module *M = D->getOwningModule()->getTopLevelModule())
7103 m_TopLevelModules.insert(M);
7104 }
7105
7107 {
7108 switch (TA.getKind()) {
7109 case TemplateArgument::Null:
7110 case TemplateArgument::Integral:
7111 case TemplateArgument::Pack:
7112 case TemplateArgument::NullPtr:
7113 case TemplateArgument::StructuralValue:
7114 case TemplateArgument::Expression:
7115 case TemplateArgument::Template:
7116 case TemplateArgument::TemplateExpansion: return;
7117 case TemplateArgument::Type:
7118 if (const TagType *TagTy = dyn_cast<TagType>(TA.getAsType()))
7119 return Visit(TagTy->getDecl());
7120 return;
7121 case TemplateArgument::Declaration: return Visit(TA.getAsDecl());
7122 }
7123 llvm_unreachable("Invalid TemplateArgument::Kind!");
7124 }
7125
7127 {
7128 if (CTSD->getOwningModule())
7129 VisitDecl(CTSD);
7130 else
7131 VisitDecl(CTSD->getSpecializedTemplate());
7132 const TemplateArgumentList &ArgList = CTSD->getTemplateArgs();
7133 for (const TemplateArgument *Arg = ArgList.data(), *ArgEnd = Arg + ArgList.size(); Arg != ArgEnd; ++Arg) {
7135 }
7136 }
7137 };
7138
7139 llvm::DenseSet<Module *> TopLevelModules;
7141 m.Collect(D);
7142 std::string result;
7143 for (auto M : TopLevelModules) {
7144 // ROOT-unaware modules (i.e. not processed by rootcling) do not have a
7145 // link declaration.
7146 if (!M->LinkLibraries.size())
7147 continue;
7148 // We have preloaded the Core module thus libCore.so
7149 if (M->Name == "Core" && skipCore)
7150 continue;
7151 assert(M->LinkLibraries.size() == 1);
7152 if (!result.empty())
7153 result += ' ';
7154 result += M->LinkLibraries[0].Library;
7155 }
7156 return result;
7157 }
7158 return {};
7159}
7160
7161////////////////////////////////////////////////////////////////////////////////
7162/// Get the list of shared libraries containing the code for class cls.
7163/// The first library in the list is the one containing the class, the
7164/// others are the libraries the first one depends on. Returns 0
7165/// in case the library is not found.
7166/// \param cls the name of the class
7167/// \param skipCore if true (default), remove "Core" from the returned list
7168
7169const char* TCling::GetClassSharedLibs(const char* cls, bool skipCore)
7170{
7171 if (fCxxModulesEnabled) {
7172 // Lock the interpreter mutex before interacting with cling.
7173 // TODO: Can we move this further deep? In principle the lock should be in
7174 // GetClassSharedLibsForModule, but it might be needed also for
7175 // getLookupHelper?
7177 llvm::StringRef className = cls;
7178 // If we get a class name containing lambda, we cannot parse it and we
7179 // can exit early.
7180 // FIXME: This works around a bug when we are instantiating a template
7181 // make_unique and the substitution fails. Seen in most of the dataframe
7182 // tests.
7183 if (className.contains("(lambda)"))
7184 return nullptr;
7185 // Limit the recursion which can be induced by GetClassSharedLibsForModule.
7187 cling::LookupHelper &LH = fInterpreter->getLookupHelper();
7189 if (!libs.empty()) {
7190 fAutoLoadLibStorage.push_back(libs);
7191 return fAutoLoadLibStorage.back().c_str();
7192 }
7193 }
7194
7195 if (!cls || !*cls) {
7196 return nullptr;
7197 }
7198 // lookup class to find list of libraries
7199 if (fMapfile) {
7200 TEnvRec* libs_record = nullptr;
7202 if (libs_record) {
7203 const char* libs = libs_record->GetValue();
7204 return (*libs) ? libs : nullptr;
7205 }
7206 else {
7207 // Try the old format...
7208 TString c = TString("Library.") + cls;
7209 // convert "::" to "@@", we used "@@" because TEnv
7210 // considers "::" a terminator
7211 c.ReplaceAll("::", "@@");
7212 // convert "-" to " ", since class names may have
7213 // blanks and TEnv considers a blank a terminator
7214 c.ReplaceAll(" ", "-");
7215 // Use TEnv::Lookup here as the rootmap file must start with Library.
7216 // and do not support using any stars (so we do not need to waste time
7217 // with the search made by TEnv::GetValue).
7218 TEnvRec* libs_record = nullptr;
7220 if (libs_record) {
7221 const char* libs = libs_record->GetValue();
7222 return (*libs) ? libs : nullptr;
7223 }
7224 }
7225 }
7226 return nullptr;
7227}
7228
7229/// This interface returns a list of dependent libraries in the form:
7230/// lib libA.so libB.so libC.so. The first library is the library we are
7231/// searching dependencies for.
7232/// Note: In order to speed up the search, we display the dependencies of the
7233/// libraries which are not yet loaded. For instance, if libB.so was already
7234/// loaded the list would contain: lib libA.so libC.so.
7235static std::string GetSharedLibImmediateDepsSlow(std::string lib,
7236 cling::Interpreter *interp,
7237 bool skipLoadedLibs = true)
7238{
7239 TString LibFullPath(lib);
7240 if (!llvm::sys::path::is_absolute(lib)) {
7241 if (!gSystem->FindDynamicLibrary(LibFullPath, /*quiet=*/true)) {
7242 Error("TCling__GetSharedLibImmediateDepsSlow", "Cannot find library '%s'", lib.c_str());
7243 return "";
7244 }
7245 } else {
7246 assert(llvm::sys::fs::exists(lib) && "Must exist!");
7247 lib = llvm::sys::path::filename(lib).str();
7248 }
7249
7250 auto ObjF = llvm::object::ObjectFile::createObjectFile(LibFullPath.Data());
7251 if (!ObjF) {
7252 Warning("TCling__GetSharedLibImmediateDepsSlow", "Failed to read object file %s", lib.c_str());
7253 return "";
7254 }
7255
7256 llvm::object::ObjectFile *BinObjFile = ObjF.get().getBinary();
7257
7258 std::set<string> DedupSet;
7259 std::string Result = lib + ' ';
7260 for (const auto &S : BinObjFile->symbols()) {
7261 uint32_t Flags = llvm::cantFail(S.getFlags());
7262 // Skip defined symbols: we have them.
7263 if (!(Flags & llvm::object::SymbolRef::SF_Undefined))
7264 continue;
7265 // Skip undefined weak symbols: if we don't have them we won't need them.
7266 // `__gmon_start__` being a typical example.
7267 if (Flags & llvm::object::SymbolRef::SF_Weak)
7268 continue;
7269 llvm::Expected<StringRef> SymNameErr = S.getName();
7270 if (!SymNameErr) {
7271 Warning("GetSharedLibDepsForModule", "Failed to read symbol");
7272 continue;
7273 }
7274 llvm::StringRef SymName = SymNameErr.get();
7275 if (SymName.empty())
7276 continue;
7277
7278 if (BinObjFile->isELF()) {
7279 // Skip the symbols which are part of the C/C++ runtime and have a
7280 // fixed library version. See binutils ld VERSION. Those reside in
7281 // 'system' libraries, which we avoid in FindLibraryForSymbol.
7282 if (SymName.contains("@GLIBCXX") || SymName.contains("@CXXABI") ||
7283 SymName.contains("@GLIBC") || SymName.contains("@GCC"))
7284 continue;
7285
7286 // Those are 'weak undefined' symbols produced by gcc. We can
7287 // ignore them.
7288 // FIXME: It is unclear whether we can ignore all weak undefined
7289 // symbols:
7290 // http://lists.llvm.org/pipermail/llvm-dev/2017-October/118177.html
7291 static constexpr llvm::StringRef RegisterClasses("_Jv_RegisterClasses");
7292 static constexpr llvm::StringRef RegisterCloneTable("_ITM_registerTMCloneTable");
7293 static constexpr llvm::StringRef DeregisterCloneTable("_ITM_deregisterTMCloneTable");
7294 if (SymName == RegisterClasses ||
7297 continue;
7298 }
7299
7300 // If we can find the address of the symbol, we have loaded it. Skip.
7301 if (skipLoadedLibs) {
7303 if (llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(SymNameForDlsym))
7304 continue;
7305 }
7306
7308 std::string found = interp->getDynamicLibraryManager()->searchLibrariesForSymbol(SymName, /*searchSystem*/false);
7309 // The expected output is just filename without the full path, which
7310 // is not very accurate, because our Dyld implementation might find
7311 // a match in location a/b/c.so and if we return just c.so ROOT might
7312 // resolve it to y/z/c.so and there we might not be ABI compatible.
7313 // FIXME: Teach the users of GetSharedLibDeps to work with full paths.
7314 if (!found.empty()) {
7315 std::string cand = llvm::sys::path::filename(found).str();
7316 if (!DedupSet.insert(cand).second)
7317 continue;
7318
7319 Result += cand + ' ';
7320 }
7321 }
7322
7323 return Result;
7324}
7325
7326static bool hasParsedRootmapForLibrary(llvm::StringRef lib)
7327{
7328 // Check if we have parsed a rootmap file.
7329 llvm::SmallString<256> rootmapName;
7330 if (!lib.starts_with("lib"))
7331 rootmapName.append("lib");
7332
7333 rootmapName.append(llvm::sys::path::filename(lib));
7334 llvm::sys::path::replace_extension(rootmapName, "rootmap");
7335
7336 if (gCling->GetRootMapFiles()->FindObject(rootmapName.c_str()))
7337 return true;
7338
7339 // Perform a last resort by dropping the lib prefix.
7340 llvm::StringRef rootmapNameNoLib = rootmapName.str();
7341 if (rootmapNameNoLib.consume_front("lib"))
7342 return gCling->GetRootMapFiles()->FindObject(rootmapNameNoLib.data());
7343
7344 return false;
7345}
7346
7347static bool hasPrecomputedLibraryDeps(llvm::StringRef lib)
7348{
7349 if (gCling->HasPCMForLibrary(lib.data()))
7350 return true;
7351
7352 return hasParsedRootmapForLibrary(lib);
7353}
7354
7355////////////////////////////////////////////////////////////////////////////////
7356/// Get the list a libraries on which the specified lib depends. The
7357/// returned string contains as first element the lib itself.
7358/// Returns 0 in case the lib does not exist or does not have
7359/// any dependencies. If useDyld is true, we iterate through all available
7360/// libraries and try to construct the dependency chain by resolving each
7361/// symbol.
7362
7363const char* TCling::GetSharedLibDeps(const char* lib, bool useDyld/* = false*/)
7364{
7365 if (llvm::sys::path::is_absolute(lib) && !llvm::sys::fs::exists(lib))
7366 return nullptr;
7367
7368 if (!hasParsedRootmapForLibrary(lib)) {
7369 llvm::SmallString<512> rootmapName(lib);
7370 llvm::sys::path::replace_extension(rootmapName, "rootmap");
7371 if (llvm::sys::fs::exists(rootmapName)) {
7372 if (gDebug > 0)
7373 Info("Load", "loading %s", rootmapName.c_str());
7374 gInterpreter->LoadLibraryMap(rootmapName.c_str());
7375 }
7376 }
7377
7378 if (hasPrecomputedLibraryDeps(lib) && useDyld) {
7379 if (gDebug > 0)
7380 Warning("TCling::GetSharedLibDeps", "Precomputed dependencies available but scanning '%s'", lib);
7381 }
7382
7383 if (useDyld) {
7385 if (!libs.empty()) {
7386 fAutoLoadLibStorage.push_back(libs);
7387 return fAutoLoadLibStorage.back().c_str();
7388 }
7389 }
7390
7391 if (!fMapfile || !lib || !lib[0]) {
7392 return nullptr;
7393 }
7394 TString libname(lib);
7395 Ssiz_t idx = libname.Last('.');
7396 if (idx != kNPOS) {
7397 libname.Remove(idx);
7398 }
7399 TEnvRec* rec;
7400 TIter next(fMapfile->GetTable());
7401 size_t len = libname.Length();
7402 while ((rec = (TEnvRec*) next())) {
7403 const char* libs = rec->GetValue();
7404 if (!strncmp(libs, libname.Data(), len) && strlen(libs) >= len
7405 && (!libs[len] || libs[len] == ' ' || libs[len] == '.')) {
7406 return libs;
7407 }
7408 }
7409 return nullptr;
7410}
7411
7412////////////////////////////////////////////////////////////////////////////////
7413/// If error messages are disabled, the interpreter should suppress its
7414/// failures and warning messages from stdout.
7415
7417{
7418#if defined(R__MUST_REVISIT)
7419#if R__MUST_REVISIT(6,2)
7420 Warning("IsErrorMessagesEnabled", "Interface not available yet.");
7421#endif
7422#endif
7423 return kTRUE;
7424}
7425
7426////////////////////////////////////////////////////////////////////////////////
7427/// If error messages are disabled, the interpreter should suppress its
7428/// failures and warning messages from stdout. Return the previous state.
7429
7431{
7432#if defined(R__MUST_REVISIT)
7433#if R__MUST_REVISIT(6,2)
7434 Warning("SetErrorMessages", "Interface not available yet.");
7435#endif
7436#endif
7438}
7439
7440////////////////////////////////////////////////////////////////////////////////
7441/// Refresh the list of include paths known to the interpreter and return it
7442/// with -I prepended.
7443
7445{
7447
7448 fIncludePath = "";
7449
7450 llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7451 //false - no system header, true - with flags.
7452 fInterpreter->GetIncludePaths(includePaths, false, true);
7453 if (const size_t nPaths = includePaths.size()) {
7454 assert(!(nPaths & 1) && "GetIncludePath, number of paths and options is not equal");
7455
7456 for (size_t i = 0; i < nPaths; i += 2) {
7457 if (i)
7458 fIncludePath.Append(' ');
7459 fIncludePath.Append(includePaths[i].c_str());
7460
7461 if (includePaths[i] != "-I")
7462 fIncludePath.Append(' ');
7463 fIncludePath.Append('"');
7465 fIncludePath.Append('"');
7466 }
7467 }
7468
7469 return fIncludePath;
7470}
7471
7472////////////////////////////////////////////////////////////////////////////////
7473/// Return the directory containing CINT's stl cintdlls.
7474
7475const char* TCling::GetSTLIncludePath() const
7476{
7477 return "";
7478}
7479
7480//______________________________________________________________________________
7481// M I S C
7482//______________________________________________________________________________
7483
7484int TCling::DisplayClass(FILE* /*fout*/, const char* /*name*/, int /*base*/, int /*start*/) const
7485{
7486 // Interface to cling function
7487 return 0;
7488}
7489
7490////////////////////////////////////////////////////////////////////////////////
7491/// Interface to cling function
7492
7494{
7495 assert(fout != nullptr && "DisplayIncludePath, 'fout' parameter is null");
7496
7497 llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7498 //false - no system header, true - with flags.
7499 fInterpreter->GetIncludePaths(includePaths, false, true);
7500 if (const size_t nPaths = includePaths.size()) {
7501 assert(!(nPaths & 1) && "DisplayIncludePath, number of paths and options is not equal");
7502
7503 std::string allIncludes("include path:");
7504 for (size_t i = 0; i < nPaths; i += 2) {
7505 allIncludes += ' ';
7507
7508 if (includePaths[i] != "-I")
7509 allIncludes += ' ';
7510 allIncludes += includePaths[i + 1];
7511 }
7512
7513 fprintf(fout, "%s\n", allIncludes.c_str());
7514 }
7515
7516 return 0;
7517}
7518
7519////////////////////////////////////////////////////////////////////////////////
7520/// Interface to cling function
7521
7522void* TCling::FindSym(const char* entry) const
7523{
7525 return fInterpreter->getAddressOfGlobal(entry);
7526}
7527
7528////////////////////////////////////////////////////////////////////////////////
7529/// Let the interpreter issue a generic error, and set its error state.
7530
7531void TCling::GenericError(const char* error) const
7532{
7533#if defined(R__MUST_REVISIT)
7534#if R__MUST_REVISIT(6,2)
7535 Warning("GenericError","Interface not available yet.");
7536#endif
7537#endif
7538}
7539
7540////////////////////////////////////////////////////////////////////////////////
7541/// This routines used to return the address of the internal wrapper
7542/// function (of the interpreter) that was used to call *all* the
7543/// interpreted functions that were bytecode compiled (no longer
7544/// interpreted line by line). In Cling, there is no such
7545/// wrapper function.
7546/// In practice this routines was use to decipher whether the
7547/// pointer returns by InterfaceMethod could be used to uniquely
7548/// represent the function. In Cling if the function is in a
7549/// useable state (its compiled version is available), this is
7550/// always the case.
7551/// See TClass::GetMethod.
7552
7554{
7555 return 0;
7556}
7557
7558////////////////////////////////////////////////////////////////////////////////
7559/// Interface to cling function
7560
7562{
7563#if defined(R__MUST_REVISIT)
7564#if R__MUST_REVISIT(6,2)
7565 Warning("GetSecurityError", "Interface not available yet.");
7566#endif
7567#endif
7568 return 0;
7569}
7570
7571////////////////////////////////////////////////////////////////////////////////
7572/// Load a source file or library called path into the interpreter.
7573
7574int TCling::LoadFile(const char* path) const
7575{
7576 // Modifying the interpreter state needs locking.
7578 cling::Interpreter::CompilationResult compRes;
7579 HandleInterpreterException(GetMetaProcessorImpl(), TString::Format(".L %s", path), compRes, /*cling::Value*/nullptr);
7580 return compRes == cling::Interpreter::kFailure;
7581}
7582
7583////////////////////////////////////////////////////////////////////////////////
7584/// Load the declarations from text into the interpreter.
7585/// Note that this cannot be (top level) statements; text must contain
7586/// top level declarations.
7587/// Returns true on success, false on failure.
7588
7589Bool_t TCling::LoadText(const char* text) const
7590{
7591 return (fInterpreter->declare(text) == cling::Interpreter::kSuccess);
7592}
7593
7594////////////////////////////////////////////////////////////////////////////////
7595/// Interface to cling function
7596
7597const char* TCling::MapCppName(const char* name) const
7598{
7599 TTHREAD_TLS_DECL(std::string,buffer);
7601 return buffer.c_str(); // NOLINT
7602}
7603
7604////////////////////////////////////////////////////////////////////////////////
7605/// [Place holder for Mutex Lock]
7606/// Provide the interpreter with a way to
7607/// acquire a lock used to protect critical section
7608/// of its code (non-thread safe parts).
7609
7610void TCling::SetAlloclockfunc(void (* /* p */ )()) const
7611{
7612 // nothing to do for now.
7613}
7614
7615////////////////////////////////////////////////////////////////////////////////
7616/// [Place holder for Mutex Unlock] Provide the interpreter with a way to
7617/// release a lock used to protect critical section
7618/// of its code (non-thread safe parts).
7619
7620void TCling::SetAllocunlockfunc(void (* /* p */ )()) const
7621{
7622 // nothing to do for now.
7623}
7624
7625////////////////////////////////////////////////////////////////////////////////
7626/// Returns if class AutoLoading is currently enabled.
7627
7629{
7630 if (IsFromRootCling())
7631 return false;
7632 if (!fClingCallbacks)
7633 return false;
7635}
7636
7637////////////////////////////////////////////////////////////////////////////////
7638/// Enable/Disable the AutoLoading of libraries.
7639/// Returns the old value, i.e whether it was enabled or not.
7640
7642{
7643 // If no state change is required, exit early.
7644 // FIXME: In future we probably want to complain if we made a request which
7645 // was with the same state as before in order to catch programming errors.
7646 if ((bool) autoload == IsClassAutoLoadingEnabled())
7647 return autoload;
7648
7649 assert(fClingCallbacks && "We must have callbacks!");
7652 return oldVal;
7653}
7654
7655////////////////////////////////////////////////////////////////////////////////
7656/// Enable/Disable the Autoparsing of headers.
7657/// Returns the old value, i.e whether it was enabled or not.
7658
7665
7666////////////////////////////////////////////////////////////////////////////////
7667/// Suspend the Autoparsing of headers.
7668/// Returns the old value, i.e whether it was suspended or not.
7669
7676
7677////////////////////////////////////////////////////////////////////////////////
7678/// Set a callback to receive error messages.
7679
7681{
7682#if defined(R__MUST_REVISIT)
7683#if R__MUST_REVISIT(6,2)
7684 Warning("SetErrmsgcallback", "Interface not available yet.");
7685#endif
7686#endif
7687}
7688
7690{
7691 if (enable) {
7693 &fInterpreter->getDiagnostics().getDiagnosticOptions(),
7694 fInterpreter->getCI()->getLangOpts(),
7695 [] (clang::DiagnosticsEngine::Level Level, const std::string &Info) {
7696 if (Level == clang::DiagnosticsEngine::Warning) {
7697 ::Warning("cling", "%s", Info.c_str());
7698 } else if (Level == clang::DiagnosticsEngine::Error
7699 || Level == clang::DiagnosticsEngine::Fatal) {
7700 ::Error("cling", "%s", Info.c_str());
7701 } else {
7702 ::Info("cling", "%s", Info.c_str());
7703 }
7704 });
7705 fInterpreter->replaceDiagnosticConsumer(consumer, /*Own=*/true);
7706 } else {
7707 fInterpreter->replaceDiagnosticConsumer(nullptr);
7708 }
7709}
7710
7711
7712////////////////////////////////////////////////////////////////////////////////
7713/// Create / close a scope for temporaries. No-op for cling; use
7714/// cling::Value instead.
7715
7716void TCling::SetTempLevel(int val) const
7717{
7718}
7719
7720////////////////////////////////////////////////////////////////////////////////
7721
7722int TCling::UnloadFile(const char* path) const
7723{
7724 // Modifying the interpreter state needs locking.
7726 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
7727 std::string canonical = DLM->lookupLibrary(path);
7728 if (canonical.empty()) {
7729 canonical = path;
7730 }
7731 // Unload a shared library or a source file.
7732 cling::Interpreter::CompilationResult compRes;
7733 HandleInterpreterException(GetMetaProcessorImpl(), Form(".U %s", canonical.c_str()), compRes, /*cling::Value*/nullptr);
7734 return compRes == cling::Interpreter::kFailure;
7735}
7736
7737std::unique_ptr<TInterpreterValue> TCling::MakeInterpreterValue() const {
7738 return std::unique_ptr<TInterpreterValue>(new TClingValue);
7739}
7740
7741////////////////////////////////////////////////////////////////////////////////
7742/// The call to Cling's tab complition.
7743
7744void TCling::CodeComplete(const std::string& line, size_t& cursor,
7745 std::vector<std::string>& completions)
7746{
7747 fInterpreter->codeComplete(line, cursor, completions);
7748}
7749
7750////////////////////////////////////////////////////////////////////////////////
7751/// Get the interpreter value corresponding to the statement.
7753{
7755
7756 auto V = reinterpret_cast<cling::Value*>(value.GetValAddr());
7757 auto compRes = fInterpreter->evaluate(code, *V);
7758 return compRes!=cling::Interpreter::kSuccess ? 0 : 1 ;
7759}
7760
7761////////////////////////////////////////////////////////////////////////////////
7762
7764{
7765 using namespace cling;
7766 const Value* V = reinterpret_cast<const Value*>(value.GetValAddr());
7768}
7769
7770////////////////////////////////////////////////////////////////////////////////
7771/// Register value as a temporary, extending its lifetime to that of the
7772/// interpreter. This is needed for TCling's compatibility interfaces
7773/// returning long - the address of the temporary objects.
7774/// As such, "simple" types don't need to be stored; they are returned by
7775/// value; only pointers / references / objects need to be stored.
7776
7777void TCling::RegisterTemporary(const cling::Value& value)
7778{
7779 if (value.isValid() && value.needsManagedAllocation()) {
7781 fTemporaries->push_back(value);
7782 }
7783}
7784
7785////////////////////////////////////////////////////////////////////////////////
7786/// If the interpreter encounters Name, check whether that is an object ROOT
7787/// could retrieve. To not re-read objects from disk, cache the name/object
7788/// pair for a given LookupCtx.
7789
7791{
7792 // The call to FindSpecialObject might induces any kind of use
7793 // of the interpreter ... (library loading, function calling, etc.)
7794 // ... and we _know_ we are in the middle of parsing, so let's make
7795 // sure to save the state and then restore it.
7796
7797 if (gDirectory) {
7799 if (iSpecObjMap != fSpecialObjectMaps.end()) {
7800 auto iSpecObj = iSpecObjMap->second.find(Name);
7801 if (iSpecObj != iSpecObjMap->second.end()) {
7803 return iSpecObj->second;
7804 }
7805 }
7806 }
7807
7808 // Save state of the PP
7809 Sema &SemaR = fInterpreter->getSema();
7810 ASTContext& C = SemaR.getASTContext();
7811 Preprocessor &PP = SemaR.getPreprocessor();
7812 Parser& P = const_cast<Parser&>(fInterpreter->getParser());
7813 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
7814 Parser::ParserCurTokRestoreRAII savedCurToken(P);
7815 // After we have saved the token reset the current one to something which
7816 // is safe (semi colon usually means empty decl)
7817 Token& Tok = const_cast<Token&>(P.getCurToken());
7818 Tok.setKind(tok::semi);
7819
7820 // We can't PushDeclContext, because we go up and the routine that pops
7821 // the DeclContext assumes that we drill down always.
7822 // We have to be on the global context. At that point we are in a
7823 // wrapper function so the parent context must be the global.
7824 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(),
7825 SemaR.TUScope);
7826
7827 TObject* specObj = gROOT->FindSpecialObject(Name, LookupCtx);
7828 if (specObj) {
7829 if (!LookupCtx) {
7830 Error("GetObjectAddress", "Got a special object without LookupCtx!");
7831 } else {
7833 }
7834 }
7835 return specObj;
7836}
7837
7838////////////////////////////////////////////////////////////////////////////////
7839/// Inject function as a friend into klass.
7840/// With function being f in void f() {new N::PrivKlass(); } this enables
7841/// I/O of non-public classes.
7842
7843void TCling::AddFriendToClass(clang::FunctionDecl* function,
7844 clang::CXXRecordDecl* klass) const
7845{
7846 using namespace clang;
7847 ASTContext& Ctx = klass->getASTContext();
7848 FriendDecl::FriendUnion friendUnion(function);
7849 // one dummy object for the source location
7851 FriendDecl* friendDecl = FriendDecl::Create(Ctx, klass, sl, friendUnion, sl);
7852 klass->pushFriendDecl(friendDecl);
7853}
7854
7855//______________________________________________________________________________
7856//
7857// DeclId getter.
7858//
7859
7860////////////////////////////////////////////////////////////////////////////////
7861/// Return a unique identifier of the declaration represented by the
7862/// CallFunc
7863
7865{
7866 if (func) return ((TClingCallFunc*)func)->GetDecl()->getCanonicalDecl();
7867 return nullptr;
7868}
7869
7870////////////////////////////////////////////////////////////////////////////////
7871/// Return a (almost) unique identifier of the declaration represented by the
7872/// ClassInfo. In ROOT, this identifier can point to more than one TClass
7873/// when the underlying class is a template instance involving one of the
7874/// opaque typedef.
7875
7877{
7878 if (cinfo) return ((TClingClassInfo*)cinfo)->GetDeclId();
7879 return nullptr;
7880}
7881
7882////////////////////////////////////////////////////////////////////////////////
7883/// Return a unique identifier of the declaration represented by the
7884/// MethodInfo
7885
7887{
7888 if (data) return ((TClingDataMemberInfo*)data)->GetDeclId();
7889 return nullptr;
7890}
7891
7892////////////////////////////////////////////////////////////////////////////////
7893/// Return a unique identifier of the declaration represented by the
7894/// MethodInfo
7895
7897{
7898 if (method) return ((TClingMethodInfo*)method)->GetDeclId();
7899 return nullptr;
7900}
7901
7902////////////////////////////////////////////////////////////////////////////////
7903/// Return a unique identifier of the declaration represented by the
7904/// TypedefInfo
7905
7907{
7908 if (tinfo) return ((TClingTypedefInfo*)tinfo)->GetDecl()->getCanonicalDecl();
7909 return nullptr;
7910}
7911
7912//______________________________________________________________________________
7913//
7914// CallFunc interface
7915//
7916
7917////////////////////////////////////////////////////////////////////////////////
7918
7920{
7921 delete (TClingCallFunc*) func;
7922}
7923
7924////////////////////////////////////////////////////////////////////////////////
7925
7926void TCling::CallFunc_Exec(CallFunc_t* func, void* address) const
7927{
7928 TClingCallFunc* f = (TClingCallFunc*) func;
7929 f->Exec(address);
7930}
7931
7932////////////////////////////////////////////////////////////////////////////////
7933
7934void TCling::CallFunc_Exec(CallFunc_t* func, void* address, TInterpreterValue& val) const
7935{
7936 TClingCallFunc* f = (TClingCallFunc*) func;
7937 f->Exec(address, &val);
7938}
7939
7940////////////////////////////////////////////////////////////////////////////////
7941
7942void TCling::CallFunc_ExecWithReturn(CallFunc_t* func, void* address, void* ret) const
7943{
7944 TClingCallFunc* f = (TClingCallFunc*) func;
7945 f->ExecWithReturn(address, ret);
7946}
7947
7948////////////////////////////////////////////////////////////////////////////////
7949
7951 const void* args[] /*=0*/,
7952 int nargs /*=0*/,
7953 void* ret/*=0*/) const
7954{
7955 TClingCallFunc* f = (TClingCallFunc*) func;
7956 f->ExecWithArgsAndReturn(address, args, nargs, ret);
7957}
7958
7959////////////////////////////////////////////////////////////////////////////////
7960
7962{
7963 TClingCallFunc* f = (TClingCallFunc*) func;
7964 return f->ExecInt(address);
7965}
7966
7967////////////////////////////////////////////////////////////////////////////////
7968
7970{
7971 TClingCallFunc* f = (TClingCallFunc*) func;
7972 return f->ExecInt64(address);
7973}
7974
7975////////////////////////////////////////////////////////////////////////////////
7976
7978{
7979 TClingCallFunc* f = (TClingCallFunc*) func;
7980 return f->ExecDouble(address);
7981}
7982
7983////////////////////////////////////////////////////////////////////////////////
7984
7990
7991////////////////////////////////////////////////////////////////////////////////
7992
7994{
7995 return (CallFunc_t*) new TClingCallFunc(*(TClingCallFunc*)func);
7996}
7997
7998////////////////////////////////////////////////////////////////////////////////
7999
8001{
8002 TClingCallFunc* f = (TClingCallFunc*) func;
8003 return (MethodInfo_t*) f->FactoryMethod();
8004}
8005
8006////////////////////////////////////////////////////////////////////////////////
8007
8009{
8010 TClingCallFunc* f = (TClingCallFunc*) func;
8011 f->IgnoreExtraArgs(ignore);
8012}
8013
8014////////////////////////////////////////////////////////////////////////////////
8015
8017{
8019 TClingCallFunc* f = (TClingCallFunc*) func;
8020 f->Init();
8021}
8022
8023////////////////////////////////////////////////////////////////////////////////
8024
8026{
8027 TClingCallFunc* f = (TClingCallFunc*) func;
8028 return f->IsValid();
8029}
8030
8031////////////////////////////////////////////////////////////////////////////////
8032
8035{
8036 TClingCallFunc* f = (TClingCallFunc*) func;
8037 return f->IFacePtr();
8038}
8039
8040////////////////////////////////////////////////////////////////////////////////
8041
8043{
8044 TClingCallFunc* f = (TClingCallFunc*) func;
8045 f->ResetArg();
8046}
8047
8048////////////////////////////////////////////////////////////////////////////////
8049
8051{
8052 TClingCallFunc* f = (TClingCallFunc*) func;
8053 f->SetArg(param);
8054}
8055
8056////////////////////////////////////////////////////////////////////////////////
8057
8059{
8060 TClingCallFunc* f = (TClingCallFunc*) func;
8061 f->SetArg(param);
8062}
8063
8064////////////////////////////////////////////////////////////////////////////////
8065
8067{
8068 TClingCallFunc* f = (TClingCallFunc*) func;
8069 f->SetArg(param);
8070}
8071
8072////////////////////////////////////////////////////////////////////////////////
8073
8075{
8076 TClingCallFunc* f = (TClingCallFunc*) func;
8077 f->SetArg(param);
8078}
8079
8080////////////////////////////////////////////////////////////////////////////////
8081
8083{
8084 TClingCallFunc* f = (TClingCallFunc*) func;
8085 f->SetArg(param);
8086}
8087
8088////////////////////////////////////////////////////////////////////////////////
8089
8091{
8092 TClingCallFunc* f = (TClingCallFunc*) func;
8093 f->SetArg(param);
8094}
8095
8096////////////////////////////////////////////////////////////////////////////////
8097
8099{
8100 TClingCallFunc* f = (TClingCallFunc*) func;
8101 f->SetArgArray(paramArr, nparam);
8102}
8103
8104////////////////////////////////////////////////////////////////////////////////
8105
8106void TCling::CallFunc_SetArgs(CallFunc_t* func, const char* param) const
8107{
8108 TClingCallFunc* f = (TClingCallFunc*) func;
8109 f->SetArgs(param);
8110}
8111
8112////////////////////////////////////////////////////////////////////////////////
8113
8114void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, Longptr_t* offset) const
8115{
8116 TClingCallFunc* f = (TClingCallFunc*) func;
8118 f->SetFunc(ci, method, params, offset);
8119}
8120
8121////////////////////////////////////////////////////////////////////////////////
8122
8123void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, bool objectIsConst, Longptr_t* offset) const
8124{
8125 TClingCallFunc* f = (TClingCallFunc*) func;
8127 f->SetFunc(ci, method, params, objectIsConst, offset);
8128}
8129////////////////////////////////////////////////////////////////////////////////
8130
8131void TCling::CallFunc_SetFunc(CallFunc_t* func, MethodInfo_t* info) const
8132{
8133 TClingCallFunc* f = (TClingCallFunc*) func;
8135 f->SetFunc(minfo);
8136}
8137
8138////////////////////////////////////////////////////////////////////////////////
8139/// Interface to cling function
8140
8141void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8142{
8143 TClingCallFunc* f = (TClingCallFunc*) func;
8145 f->SetFuncProto(ci, method, proto, offset, mode);
8146}
8147
8148////////////////////////////////////////////////////////////////////////////////
8149/// Interface to cling function
8150
8151void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, bool objectIsConst, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8152{
8153 TClingCallFunc* f = (TClingCallFunc*) func;
8155 f->SetFuncProto(ci, method, proto, objectIsConst, offset, mode);
8156}
8157
8158////////////////////////////////////////////////////////////////////////////////
8159/// Interface to cling function
8160
8161void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const std::vector<TypeInfo_t*> &proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8162{
8163 TClingCallFunc* f = (TClingCallFunc*) func;
8165 llvm::SmallVector<clang::QualType, 4> funcProto;
8166 for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
8167 iter != end; ++iter) {
8168 funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
8169 }
8170 f->SetFuncProto(ci, method, funcProto, offset, mode);
8171}
8172
8173////////////////////////////////////////////////////////////////////////////////
8174/// Interface to cling function
8175
8176void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const std::vector<TypeInfo_t*> &proto, bool objectIsConst, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8177{
8178 TClingCallFunc* f = (TClingCallFunc*) func;
8180 llvm::SmallVector<clang::QualType, 4> funcProto;
8181 for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
8182 iter != end; ++iter) {
8183 funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
8184 }
8185 f->SetFuncProto(ci, method, funcProto, objectIsConst, offset, mode);
8186}
8187
8189{
8190 TClingCallFunc *f = (TClingCallFunc *)func;
8191 std::string wrapper_name;
8192 std::string wrapper;
8193 f->get_wrapper_code(wrapper_name, wrapper);
8194 return wrapper;
8195}
8196
8197//______________________________________________________________________________
8198//
8199// ClassInfo interface
8200//
8201
8202////////////////////////////////////////////////////////////////////////////////
8203/// Return true if the entity pointed to by 'declid' is declared in
8204/// the context described by 'info'. If info is null, look into the
8205/// global scope (translation unit scope).
8206
8208{
8209 if (!declid)
8210 return kFALSE;
8211
8212 const clang::DeclContext *ctxt = nullptr;
8213 if (info) {
8214 ctxt = clang::Decl::castToDeclContext(((TClingClassInfo*)info)->GetDecl());
8215 } else {
8216 ctxt = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
8217 }
8218 if (!ctxt)
8219 return kFALSE;
8220
8221 const clang::Decl *decl = reinterpret_cast<const clang::Decl*>(declid);
8222 if (!decl)
8223 return kFALSE;
8224
8225 const clang::DeclContext *declDC = decl->getDeclContext();
8226 // ClassInfo_t-s are always "spellable" scopes, never unnamed or inline ones.
8227 while (true) {
8228 if (declDC->isTransparentContext()) {
8229 declDC = declDC->getParent();
8230 continue;
8231 }
8232 if (const auto *declRD = llvm::dyn_cast<clang::RecordDecl>(declDC)) {
8233 if (declRD->isAnonymousStructOrUnion()) {
8234 declDC = declRD->getParent();
8235 continue;
8236 }
8237 }
8238 if (const auto *declNS = llvm::dyn_cast<clang::NamespaceDecl>(declDC)) {
8239 if (declNS->isAnonymousNamespace() || declNS->isInlineNamespace()) {
8240 declDC = declNS->getParent();
8241 continue;
8242 }
8243 }
8244 break;
8245 }
8246
8247 return declDC->Equals(ctxt);
8248}
8249
8250////////////////////////////////////////////////////////////////////////////////
8251
8257
8258////////////////////////////////////////////////////////////////////////////////
8259
8261{
8262 delete (TClingClassInfo*) cinfo;
8263}
8264
8265////////////////////////////////////////////////////////////////////////////////
8266
8272
8273////////////////////////////////////////////////////////////////////////////////
8274
8280
8281////////////////////////////////////////////////////////////////////////////////
8282
8288
8289////////////////////////////////////////////////////////////////////////////////
8290
8296
8297////////////////////////////////////////////////////////////////////////////////
8298
8303
8304////////////////////////////////////////////////////////////////////////////////
8305
8311
8317
8318
8319////////////////////////////////////////////////////////////////////////////////
8320
8321int TCling::ClassInfo_GetMethodNArg(ClassInfo_t* cinfo, const char* method, const char* proto, Bool_t objectIsConst /* = false */, EFunctionMatchMode mode /* = kConversionMatch */) const
8322{
8324 return TClinginfo->GetMethodNArg(method, proto, objectIsConst, mode);
8325}
8326
8327////////////////////////////////////////////////////////////////////////////////
8328
8334
8335////////////////////////////////////////////////////////////////////////////////
8336
8338{
8340 return TClinginfo->HasMethod(name);
8341}
8342
8343////////////////////////////////////////////////////////////////////////////////
8344
8351
8352////////////////////////////////////////////////////////////////////////////////
8353
8360
8361////////////////////////////////////////////////////////////////////////////////
8362
8364{
8366 return TClinginfo->IsBase(name);
8367}
8368
8369////////////////////////////////////////////////////////////////////////////////
8370
8371bool TCling::ClassInfo_IsEnum(const char* name) const
8372{
8374}
8375
8376////////////////////////////////////////////////////////////////////////////////
8377
8383
8384
8385////////////////////////////////////////////////////////////////////////////////
8386
8392
8393
8394////////////////////////////////////////////////////////////////////////////////
8395
8397{
8399 return TClinginfo->IsLoaded();
8400}
8401
8402////////////////////////////////////////////////////////////////////////////////
8403
8405{
8407 return TClinginfo->IsValid();
8408}
8409
8410////////////////////////////////////////////////////////////////////////////////
8411
8412bool TCling::ClassInfo_IsValidMethod(ClassInfo_t* cinfo, const char* method, const char* proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8413{
8415 return TClinginfo->IsValidMethod(method, proto, false, offset, mode);
8416}
8417
8418////////////////////////////////////////////////////////////////////////////////
8419
8421{
8423 return TClinginfo->IsValidMethod(method, proto, objectIsConst, offset, mode);
8424}
8425
8426////////////////////////////////////////////////////////////////////////////////
8427
8433
8434////////////////////////////////////////////////////////////////////////////////
8435
8441
8442////////////////////////////////////////////////////////////////////////////////
8443
8449
8450////////////////////////////////////////////////////////////////////////////////
8451
8453{
8455 return TClinginfo->New(n, arena,*fNormalizedCtxt);
8456}
8457
8458////////////////////////////////////////////////////////////////////////////////
8459
8465
8466////////////////////////////////////////////////////////////////////////////////
8467
8473
8474////////////////////////////////////////////////////////////////////////////////
8475
8481
8482////////////////////////////////////////////////////////////////////////////////
8483
8489
8490////////////////////////////////////////////////////////////////////////////////
8491
8493{
8495 return TClinginfo->FileName();
8496}
8497
8498////////////////////////////////////////////////////////////////////////////////
8499
8501{
8503 TTHREAD_TLS_DECL(std::string,output);
8504 TClinginfo->FullName(output,*fNormalizedCtxt);
8505 return output.c_str(); // NOLINT
8506}
8507
8508////////////////////////////////////////////////////////////////////////////////
8509
8511{
8513 return TClinginfo->Name();
8514}
8515
8516////////////////////////////////////////////////////////////////////////////////
8517
8519{
8521 return TClinginfo->Title();
8522}
8523
8524////////////////////////////////////////////////////////////////////////////////
8525
8527{
8529 return TClinginfo->TmpltName();
8530}
8531
8532
8533
8534//______________________________________________________________________________
8535//
8536// BaseClassInfo interface
8537//
8538
8539////////////////////////////////////////////////////////////////////////////////
8540
8545
8546////////////////////////////////////////////////////////////////////////////////
8547
8554
8555////////////////////////////////////////////////////////////////////////////////
8556
8565
8566////////////////////////////////////////////////////////////////////////////////
8567
8573
8574////////////////////////////////////////////////////////////////////////////////
8575
8581
8582////////////////////////////////////////////////////////////////////////////////
8583
8589
8590////////////////////////////////////////////////////////////////////////////////
8591
8593{
8596 // Offset to the class itself.
8597 if (TClinginfo->GetDecl() == TClinginfoBase->GetDecl()) {
8598 return 0;
8599 }
8600 return TClinginfo->GetBaseOffset(TClinginfoBase, address, isDerivedObject);
8601}
8602
8603////////////////////////////////////////////////////////////////////////////////
8604
8610
8611////////////////////////////////////////////////////////////////////////////////
8612
8618
8619////////////////////////////////////////////////////////////////////////////////
8620
8626
8627////////////////////////////////////////////////////////////////////////////////
8628
8630{
8632 TTHREAD_TLS_DECL(std::string,output);
8633 TClinginfo->FullName(output,*fNormalizedCtxt);
8634 return output.c_str(); // NOLINT
8635}
8636
8637////////////////////////////////////////////////////////////////////////////////
8638
8644
8645////////////////////////////////////////////////////////////////////////////////
8646
8652
8653//______________________________________________________________________________
8654//
8655// DataMemberInfo interface
8656//
8657
8658////////////////////////////////////////////////////////////////////////////////
8659
8665
8666////////////////////////////////////////////////////////////////////////////////
8667
8672
8673////////////////////////////////////////////////////////////////////////////////
8674
8681
8682////////////////////////////////////////////////////////////////////////////////
8683
8685{
8687 const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
8688 const clang::ValueDecl* vd = llvm::dyn_cast_or_null<clang::ValueDecl>(decl);
8690}
8691
8692////////////////////////////////////////////////////////////////////////////////
8693
8699
8700////////////////////////////////////////////////////////////////////////////////
8701
8707
8708////////////////////////////////////////////////////////////////////////////////
8709
8715
8716////////////////////////////////////////////////////////////////////////////////
8717
8723
8724////////////////////////////////////////////////////////////////////////////////
8725
8731
8732////////////////////////////////////////////////////////////////////////////////
8733
8739
8740////////////////////////////////////////////////////////////////////////////////
8741
8747
8748////////////////////////////////////////////////////////////////////////////////
8749
8755
8756////////////////////////////////////////////////////////////////////////////////
8757
8763
8764////////////////////////////////////////////////////////////////////////////////
8765
8771
8772////////////////////////////////////////////////////////////////////////////////
8773
8779
8780////////////////////////////////////////////////////////////////////////////////
8781
8787
8788////////////////////////////////////////////////////////////////////////////////
8789
8791{
8792 TTHREAD_TLS_DECL(std::string,result);
8793
8795 result = TClinginfo->ValidArrayIndex().str();
8796 return result.c_str(); // NOLINT
8797}
8798
8799////////////////////////////////////////////////////////////////////////////////
8800
8802{
8803 Decl* decl = static_cast<Decl*>(const_cast<void*>(declId));
8804 ASTContext &C = decl->getASTContext();
8805 decl->addAttr(AnnotateAttr::CreateImplicit(C, attribute, nullptr, 0));
8806}
8807
8808//______________________________________________________________________________
8809//
8810// Function Template interface
8811//
8812
8813////////////////////////////////////////////////////////////////////////////////
8814
8815static void ConstructorName(std::string &name, const clang::Decl *decl,
8816 cling::Interpreter &interp,
8818{
8819 const clang::TypeDecl* td = llvm::dyn_cast<clang::TypeDecl>(decl->getDeclContext());
8820 if (!td) return;
8821
8822 clang::QualType qualType(td->getTypeForDecl(),0);
8824 unsigned int level = 0;
8825 for(size_t cursor = name.length()-1; cursor != 0; --cursor) {
8826 if (name[cursor] == '>') ++level;
8827 else if (name[cursor] == '<' && level) --level;
8828 else if (level == 0 && name[cursor] == ':') {
8829 name.erase(0,cursor+1);
8830 break;
8831 }
8832 }
8833}
8834
8835////////////////////////////////////////////////////////////////////////////////
8836
8837void TCling::GetFunctionName(const clang::Decl *decl, std::string &output) const
8838{
8839 output.clear();
8840
8841 const auto *FD = llvm::dyn_cast<clang::FunctionDecl>(decl);
8842 if (const auto *USD = llvm::dyn_cast<clang::UsingShadowDecl>(decl)) {
8843 FD = llvm::dyn_cast<clang::FunctionDecl>(USD->getTargetDecl());
8844 }
8845 if (!FD) {
8846 Error("GetFunctionName", "NULL Decl!");
8847 return;
8848 }
8849
8850 // For using-decls, show "Derived", not "Base", i.e. use the
8851 // name of the decl context of the UsingShadowDecl (aka `decl`)
8852 // not the name of FD's decl context.
8853 if (llvm::isa<clang::CXXConstructorDecl>(FD))
8854 {
8856
8857 } else if (llvm::isa<clang::CXXDestructorDecl>(decl))
8858 {
8860 output.insert(output.begin(), '~');
8861 } else {
8862 llvm::raw_string_ostream stream(output);
8863 auto printPolicy = decl->getASTContext().getPrintingPolicy();
8864 // Don't trigger fopen of the source file to count lines:
8865 printPolicy.AnonymousTagLocations = false;
8866 FD->getNameForDiagnostic(stream, printPolicy, /*Qualified=*/false);
8867 }
8868}
8869
8870////////////////////////////////////////////////////////////////////////////////
8871/// Return a unique identifier of the declaration represented by the
8872/// FuncTempInfo
8873
8878
8879////////////////////////////////////////////////////////////////////////////////
8880/// Delete the FuncTempInfo_t
8881
8883{
8884 // Currently the address of ft_info is actually the decl itself,
8885 // so we have nothing to do.
8886}
8887
8888////////////////////////////////////////////////////////////////////////////////
8889/// Construct a FuncTempInfo_t
8890
8892{
8893 // Currently the address of ft_info is actually the decl itself,
8894 // so we have nothing to do.
8895
8896 return (FuncTempInfo_t*)const_cast<void*>(declid);
8897}
8898
8899////////////////////////////////////////////////////////////////////////////////
8900/// Construct a FuncTempInfo_t
8901
8903{
8904 // Currently the address of ft_info is actually the decl itself,
8905 // so we have nothing to do.
8906
8907 return (FuncTempInfo_t*)ft_info;
8908}
8909
8910////////////////////////////////////////////////////////////////////////////////
8911/// Check validity of a FuncTempInfo_t
8912
8914{
8915 // Currently the address of ft_info is actually the decl itself,
8916 // so we have nothing to do.
8917
8918 return t_info != nullptr;
8919}
8920
8921////////////////////////////////////////////////////////////////////////////////
8922/// Return the maximum number of template arguments of the
8923/// function template described by ft_info.
8924
8926{
8927 if (!ft_info) return 0;
8928 const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
8929 return ft->getTemplateParameters()->size();
8930}
8931
8932////////////////////////////////////////////////////////////////////////////////
8933/// Return the number of required template arguments of the
8934/// function template described by ft_info.
8935
8937{
8938 if (!ft_info) return 0;
8939 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8940 return ft->getTemplateParameters()->getMinRequiredArguments();
8941}
8942
8943////////////////////////////////////////////////////////////////////////////////
8944/// Return the property of the function template.
8945
8947{
8948 if (!ft_info) return 0;
8949
8950 long property = 0L;
8951 property |= kIsCompiled;
8952
8953 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8954
8955 switch (ft->getAccess()) {
8956 case clang::AS_public:
8957 property |= kIsPublic;
8958 break;
8959 case clang::AS_protected:
8960 property |= kIsProtected;
8961 break;
8962 case clang::AS_private:
8963 property |= kIsPrivate;
8964 break;
8965 case clang::AS_none:
8966 if (ft->getDeclContext()->isNamespace())
8968 break;
8969 default:
8970 // IMPOSSIBLE
8971 assert(false && "Unexpected value for the access property value in Clang");
8972 break;
8973 }
8974
8975 const clang::FunctionDecl *fd = ft->getTemplatedDecl();
8976
8977 if (fd && fd->getStorageClass() == clang::SC_Static)
8978 property |= kIsStatic;
8979
8980 if (const clang::CXXMethodDecl *md =
8981 llvm::dyn_cast<clang::CXXMethodDecl>(fd)) {
8982 if (md->getMethodQualifiers().hasConst()) {
8983 property |= kIsConstant | kIsConstMethod;
8984 }
8985 if (md->isVirtual()) {
8986 property |= kIsVirtual;
8987 }
8988 if (md->isPureVirtual()) {
8989 property |= kIsPureVirtual;
8990 }
8991 if (const clang::CXXConstructorDecl *cd =
8992 llvm::dyn_cast<clang::CXXConstructorDecl>(md)) {
8993 if (cd->isExplicit()) {
8994 property |= kIsExplicit;
8995 }
8996 }
8997 else if (const clang::CXXConversionDecl *cd =
8998 llvm::dyn_cast<clang::CXXConversionDecl>(md)) {
8999 if (cd->isExplicit()) {
9000 property |= kIsExplicit;
9001 }
9002 }
9003 }
9004 return property;
9005}
9006
9007////////////////////////////////////////////////////////////////////////////////
9008/// Return the property not already defined in Property
9009/// See TDictionary's EFunctionProperty
9010
9012{
9013 if (!ft_info) return 0;
9014
9015 long property = 0L;
9016 property |= kIsCompiled;
9017
9018 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9019 const clang::FunctionDecl *fd = ft->getTemplatedDecl();
9020
9021 if (fd->isOverloadedOperator())
9023 if (llvm::isa<clang::CXXConversionDecl>(fd))
9025 if (llvm::isa<clang::CXXConstructorDecl>(fd))
9027 if (llvm::isa<clang::CXXDestructorDecl>(fd))
9029 if (fd->isInlined())
9031 return property;
9032}
9033
9034////////////////////////////////////////////////////////////////////////////////
9035/// Return the name of this function template.
9036
9038{
9039 output.Clear();
9040 if (!ft_info) return;
9041 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9042 std::string buf;
9043 GetFunctionName(ft->getTemplatedDecl(), buf);
9044 output = buf;
9045}
9046
9047////////////////////////////////////////////////////////////////////////////////
9048/// Return the comments associates with this function template.
9049
9051{
9052 output.Clear();
9053 if (!ft_info) return;
9054 const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
9055
9056 // Iterate over the redeclarations, we can have multiple definitions in the
9057 // redecl chain (came from merging of pcms).
9060 if (AnnotateAttr *A = AnnotFD->getAttr<AnnotateAttr>()) {
9061 output = A->getAnnotation().str();
9062 return;
9063 }
9064 }
9065 if (!ft->isFromASTFile()) {
9066 // Try to get the comment from the header file if present
9067 // but not for decls from AST file, where rootcling would have
9068 // created an annotation
9070 }
9071}
9072
9073
9074//______________________________________________________________________________
9075//
9076// MethodInfo interface
9077//
9078
9079////////////////////////////////////////////////////////////////////////////////
9080/// Interface to cling function
9081
9082void TCling::MethodInfo_Delete(MethodInfo_t* minfo) const
9083{
9084 delete(TClingMethodInfo*) minfo;
9085}
9086
9087////////////////////////////////////////////////////////////////////////////////
9088
9090{
9092 // The next call locks the interpreter mutex.
9093 info->CreateSignature(signature);
9094}
9095
9096////////////////////////////////////////////////////////////////////////////////
9097
9098MethodInfo_t* TCling::MethodInfo_Factory() const
9099{
9101 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl());
9102}
9103
9104////////////////////////////////////////////////////////////////////////////////
9105
9107{
9109 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), (TClingClassInfo*)clinfo);
9110}
9111
9112////////////////////////////////////////////////////////////////////////////////
9113
9115{
9116 const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
9118 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), decl);
9119}
9120
9121////////////////////////////////////////////////////////////////////////////////
9122
9123MethodInfo_t* TCling::MethodInfo_FactoryCopy(MethodInfo_t* minfo) const
9124{
9125 return (MethodInfo_t*) new TClingMethodInfo(*(TClingMethodInfo*)minfo);
9126}
9127
9128////////////////////////////////////////////////////////////////////////////////
9129
9131{
9133 // The next call locks the interpreter mutex.
9134 return info->InterfaceMethod();
9135}
9136
9137////////////////////////////////////////////////////////////////////////////////
9138
9139bool TCling::MethodInfo_IsValid(MethodInfo_t* minfo) const
9140{
9142 return info->IsValid();
9143}
9144
9145////////////////////////////////////////////////////////////////////////////////
9146
9147int TCling::MethodInfo_NArg(MethodInfo_t* minfo) const
9148{
9150 return info->NArg();
9151}
9152
9153////////////////////////////////////////////////////////////////////////////////
9154
9156{
9158 return info->NDefaultArg();
9159}
9160
9161////////////////////////////////////////////////////////////////////////////////
9162
9163int TCling::MethodInfo_Next(MethodInfo_t* minfo) const
9164{
9166 return info->Next();
9167}
9168
9169////////////////////////////////////////////////////////////////////////////////
9170
9172{
9174 // The next call locks the interpreter mutex.
9175 return info->Property();
9176}
9177
9178////////////////////////////////////////////////////////////////////////////////
9179
9181{
9183 // The next call locks the interpreter mutex.
9184 return info->ExtraProperty();
9185}
9186
9187////////////////////////////////////////////////////////////////////////////////
9188
9190{
9192 // The next call locks the interpreter mutex.
9193 return (TypeInfo_t*)info->Type();
9194}
9195
9196////////////////////////////////////////////////////////////////////////////////
9197
9198const char* TCling::MethodInfo_GetMangledName(MethodInfo_t* minfo) const
9199{
9202 // The next call locks the interpreter mutex.
9203 mangled_name = info->GetMangledName();
9204 return mangled_name;
9205}
9206
9207////////////////////////////////////////////////////////////////////////////////
9208
9209const char* TCling::MethodInfo_GetPrototype(MethodInfo_t* minfo) const
9210{
9212 // The next call locks the interpreter mutex.
9213 return info->GetPrototype();
9214}
9215
9216////////////////////////////////////////////////////////////////////////////////
9217
9218const char* TCling::MethodInfo_Name(MethodInfo_t* minfo) const
9219{
9221 // The next call locks the interpreter mutex.
9222 return info->Name();
9223}
9224
9225////////////////////////////////////////////////////////////////////////////////
9226
9227const char* TCling::MethodInfo_TypeName(MethodInfo_t* minfo) const
9228{
9230 // The next call locks the interpreter mutex.
9231 return info->TypeName();
9232}
9233
9234////////////////////////////////////////////////////////////////////////////////
9235
9236std::string TCling::MethodInfo_TypeNormalizedName(MethodInfo_t* minfo) const
9237{
9239 // The next part locks the interpreter mutex.
9240 if (info && info->IsValid())
9241 return info->Type()->NormalizedName(*fNormalizedCtxt);
9242 else
9243 return "";
9244}
9245
9246////////////////////////////////////////////////////////////////////////////////
9247
9248const char* TCling::MethodInfo_Title(MethodInfo_t* minfo) const
9249{
9251 // The next call locks the interpreter mutex.
9252 return info->Title();
9253}
9254
9255////////////////////////////////////////////////////////////////////////////////
9256
9258{
9259 if (func) {
9260 return MethodInfo_MethodCallReturnType(func->fInfo);
9261 } else {
9262 return EReturnType::kOther;
9263 }
9264}
9265
9266////////////////////////////////////////////////////////////////////////////////
9267
9269{
9271 if (info && info->IsValid()) {
9272 TClingTypeInfo *typeinfo = info->Type();
9273 clang::QualType QT( typeinfo->GetQualType().getCanonicalType() );
9274 if (QT->isEnumeralType()) {
9275 return EReturnType::kLong;
9276 } else if (QT->isPointerType()) {
9277 // Look for char*
9278 QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
9279 if ( QT->isCharType() ) {
9280 return EReturnType::kString;
9281 } else {
9282 return EReturnType::kOther;
9283 }
9284 } else if ( QT->isFloatingType() ) {
9285 int sz = typeinfo->Size();
9286 if (sz == 4 || sz == 8) {
9287 // Support only float and double.
9288 return EReturnType::kDouble;
9289 } else {
9290 return EReturnType::kOther;
9291 }
9292 } else if ( QT->isIntegerType() ) {
9293 int sz = typeinfo->Size();
9294 if (sz <= 8) {
9295 // Support only up to long long ... but
9296 // FIXME the TMethodCall::Execute only
9297 // return long (4 bytes) ...
9298 // The v5 implementation of TMethodCall::ReturnType
9299 // was not making the distinction so we let it go
9300 // as is for now, but we really need to upgrade
9301 // TMethodCall::Execute ...
9302 return EReturnType::kLong;
9303 } else {
9304 return EReturnType::kOther;
9305 }
9306 } else {
9307 return EReturnType::kOther;
9308 }
9309 } else {
9310 return EReturnType::kOther;
9311 }
9312}
9313
9314//______________________________________________________________________________
9315//
9316// MethodArgInfo interface
9317//
9318
9319////////////////////////////////////////////////////////////////////////////////
9320
9325
9326////////////////////////////////////////////////////////////////////////////////
9327
9333
9334////////////////////////////////////////////////////////////////////////////////
9335
9341
9342////////////////////////////////////////////////////////////////////////////////
9343
9349
9350////////////////////////////////////////////////////////////////////////////////
9351
9357
9358////////////////////////////////////////////////////////////////////////////////
9359
9365
9366////////////////////////////////////////////////////////////////////////////////
9367
9373
9374////////////////////////////////////////////////////////////////////////////////
9375
9377{
9379 return info->DefaultValue();
9380}
9381
9382////////////////////////////////////////////////////////////////////////////////
9383
9385{
9387 return info->Name();
9388}
9389
9390////////////////////////////////////////////////////////////////////////////////
9391
9393{
9395 return info->TypeName();
9396}
9397
9398////////////////////////////////////////////////////////////////////////////////
9399
9401{
9403 return info->Type()->NormalizedName(*fNormalizedCtxt);
9404}
9405
9406////////////////////////////////////////////////////////////////////////////////
9407
9413
9414//______________________________________________________________________________
9415//
9416// TypeInfo interface
9417//
9418
9419////////////////////////////////////////////////////////////////////////////////
9420
9422{
9423 delete (TClingTypeInfo*) tinfo;
9424}
9425
9426////////////////////////////////////////////////////////////////////////////////
9427
9433
9434////////////////////////////////////////////////////////////////////////////////
9435
9441
9442////////////////////////////////////////////////////////////////////////////////
9443
9448
9449////////////////////////////////////////////////////////////////////////////////
9450
9457
9458////////////////////////////////////////////////////////////////////////////////
9459
9461{
9463 return TClinginfo->IsValid();
9464}
9465
9466////////////////////////////////////////////////////////////////////////////////
9467
9469{
9471 return TClinginfo->Name();
9472}
9473
9474////////////////////////////////////////////////////////////////////////////////
9475
9481
9482////////////////////////////////////////////////////////////////////////////////
9483
9485{
9487 return TClinginfo->RefType();
9488}
9489
9490////////////////////////////////////////////////////////////////////////////////
9491
9493{
9495 return TClinginfo->Size();
9496}
9497
9498////////////////////////////////////////////////////////////////////////////////
9499
9501{
9503 return TClinginfo->TrueName(*fNormalizedCtxt);
9504}
9505
9506////////////////////////////////////////////////////////////////////////////////
9507
9509{
9511 return TClinginfo->QualTypePtr();
9512}
9513
9514
9515//______________________________________________________________________________
9516//
9517// TypedefInfo interface
9518//
9519
9520////////////////////////////////////////////////////////////////////////////////
9521
9526
9527////////////////////////////////////////////////////////////////////////////////
9528
9534
9535////////////////////////////////////////////////////////////////////////////////
9536
9542
9543////////////////////////////////////////////////////////////////////////////////
9544
9549
9550////////////////////////////////////////////////////////////////////////////////
9551
9559
9560////////////////////////////////////////////////////////////////////////////////
9561
9567
9568////////////////////////////////////////////////////////////////////////////////
9569
9575
9576////////////////////////////////////////////////////////////////////////////////
9577
9583
9584////////////////////////////////////////////////////////////////////////////////
9585
9591
9592////////////////////////////////////////////////////////////////////////////////
9593
9599
9600////////////////////////////////////////////////////////////////////////////////
9601
9603{
9605 return TClinginfo->Name();
9606}
9607
9608////////////////////////////////////////////////////////////////////////////////
9609
9611{
9613 return TClinginfo->Title();
9614}
9615
9616////////////////////////////////////////////////////////////////////////////////
9617
9618bool TCling::IsSameType(const void * QualTypePtr1, const void * QualTypePtr2) const
9619{
9620 clang::QualType QT1 = clang::QualType::getFromOpaquePtr(QualTypePtr1);
9621 clang::QualType QT2 = clang::QualType::getFromOpaquePtr(QualTypePtr2);
9622 return fInterpreter->getCI()->getASTContext().hasSameType(QT1, QT2);
9623}
9624
9625////////////////////////////////////////////////////////////////////////////////
9626
9627bool TCling::IsIntegerType(const void * QualTypePtr) const
9628{
9629 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9630 return QT->hasIntegerRepresentation();
9631}
9632
9633////////////////////////////////////////////////////////////////////////////////
9634
9635bool TCling::IsSignedIntegerType(const void * QualTypePtr) const
9636{
9637 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9638 return QT->hasSignedIntegerRepresentation();
9639}
9640
9641////////////////////////////////////////////////////////////////////////////////
9642
9643bool TCling::IsUnsignedIntegerType(const void * QualTypePtr) const
9644{
9645 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9646 return QT->hasUnsignedIntegerRepresentation();
9647}
9648
9649////////////////////////////////////////////////////////////////////////////////
9650
9651bool TCling::IsFloatingType(const void * QualTypePtr) const
9652{
9653 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9654 return QT->hasFloatingRepresentation();
9655}
9656
9657////////////////////////////////////////////////////////////////////////////////
9658
9659bool TCling::IsPointerType(const void * QualTypePtr) const
9660{
9661 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9662 return QT->hasPointerRepresentation();
9663}
9664
9665////////////////////////////////////////////////////////////////////////////////
9666
9667bool TCling::IsVoidPointerType(const void * QualTypePtr) const
9668{
9669 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9670 return QT->isVoidPointerType();
9671}
9672
9673////////////////////////////////////////////////////////////////////////////////
9674
9676{
9677 if (!fInitialMutex) {
9679 Error("SnapshotMutexState", "fRecurseCount != 0 even though initial mutex state is unset!");
9680 }
9681 fInitialMutex.fState = mtx->GetStateBefore();
9682 }
9683 // We will "forget" this lock once we backed out of all interpreter frames.
9684 // Here we are entering one, so ++.
9686}
9687
9688////////////////////////////////////////////////////////////////////////////////
9689
9691{
9692 if (!fInitialMutex)
9693 return;
9694 if (fInitialMutex.fRecurseCount == 0) {
9695 Error("ForgetMutexState", "mutex state's recurse count already 0!");
9696 }
9697 else if (--fInitialMutex.fRecurseCount == 0) {
9698 // We have returned from all interpreter frames. Reset the initial lock state.
9699 fInitialMutex.fState.reset();
9700 }
9701}
9702
9703////////////////////////////////////////////////////////////////////////////////
9704/// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
9705
9707{
9708 if (gInterpreterMutex) {
9709 if (delta) {
9710 auto typedDelta = static_cast<MutexStateAndRecurseCountDelta *>(delta);
9711 std::unique_ptr<MutexStateAndRecurseCountDelta> uniqueP{typedDelta};
9712 gCoreMutex->Apply(std::move(typedDelta->fDelta));
9713 // Now that we have the lock, update the global
9714 R__ASSERT(fInitialMutex.fRecurseCount == 0 && "Inconsistent state of fInitialMutex! Another thread within Interpreter critical section.");
9715 std::swap(fInitialMutex, typedDelta->fInitialState);
9716 } else {
9717 // This case happens when EnableThreadSafety is first called from
9718 // the interpreter function we just handled.
9719 // Since thread safety was not enabled at the time we rewound, there was
9720 // no lock taken and even-though we should be locking the rest of this
9721 // interpreter handling/modifying code (since there might be threads in
9722 // flight), we can't because there would not be any lock guard to release the
9723 // locks
9725 Error("ApplyToInterpreterMutex",
9726 "After returning from user code that turned on thread safety support, we notice that fInitialMutex is already used ... "
9727 "so the rest of this function/stack execution might have race condition (with the other thread that thinks it has exclusive access to the interpreter state.");
9728 }
9729 }
9730}
9731
9732////////////////////////////////////////////////////////////////////////////////
9733/// Reset the interpreter lock to the state it had before interpreter-related
9734/// calls happened.
9735
9737{
9738 if (fInitialMutex) {
9739 // Need to start a new recurse count.
9740 std::unique_ptr<MutexStateAndRecurseCountDelta> uniqueP(new MutexStateAndRecurseCountDelta());
9741 std::swap(uniqueP->fInitialState, fInitialMutex);
9742 uniqueP->fDelta = gCoreMutex->Rewind(*uniqueP->fInitialState.fState);
9743 return uniqueP.release();
9744 }
9746 return nullptr;
9747}
#define R__EXTERN
Definition DllImport.h:26
The file contains utilities which are foundational and could be used across the core component of ROO...
#define d(i)
Definition RSha256.hxx:102
#define f(i)
Definition RSha256.hxx:104
#define c(i)
Definition RSha256.hxx:101
#define a(i)
Definition RSha256.hxx:99
#define s1(x)
Definition RSha256.hxx:91
#define R(a, b, c, d, e, f, g, h, i)
Definition RSha256.hxx:110
#define e(i)
Definition RSha256.hxx:103
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
bool Bool_t
Boolean (0=false, 1=true) (bool)
Definition RtypesCore.h:77
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:59
long Longptr_t
Integer large enough to hold a pointer (platform-dependent)
Definition RtypesCore.h:89
short Version_t
Class version identifier (short)
Definition RtypesCore.h:79
unsigned long ULong_t
Unsigned long integer 4 bytes (unsigned long). Size depends on architecture.
Definition RtypesCore.h:69
long Long_t
Signed long integer 4 bytes (long). Size depends on architecture.
Definition RtypesCore.h:68
unsigned int UInt_t
Unsigned integer 4 bytes (unsigned int)
Definition RtypesCore.h:60
constexpr Bool_t kFALSE
Definition RtypesCore.h:108
constexpr Ssiz_t kNPOS
The equivalent of std::string::npos for the ROOT class TString.
Definition RtypesCore.h:131
long long Long64_t
Portable signed long integer 8 bytes.
Definition RtypesCore.h:83
unsigned long long ULong64_t
Portable unsigned long integer 8 bytes.
Definition RtypesCore.h:84
constexpr Bool_t kTRUE
Definition RtypesCore.h:107
TClass *(* DictFuncPtr_t)()
Definition Rtypes.h:86
R__EXTERN TApplication * gApplication
R__EXTERN TClassTable * gClassTable
static bool IsFromRootCling()
Definition TClass.cxx:174
static void indent(ostringstream &buf, int indent_level)
The file contains facilities to work with C++ module files extensions used to store rdict files.
void TCling__RestoreInterpreterMutex(void *delta)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
Definition TCling.cxx:357
void TCling__TransactionRollback(const cling::Transaction &T)
Definition TCling.cxx:595
static void RegisterPreIncludedHeaders(cling::Interpreter &clingInterp)
Definition TCling.cxx:1333
static bool hasParsedRootmapForLibrary(llvm::StringRef lib)
Definition TCling.cxx:7326
void TCling__InvalidateGlobal(const clang::Decl *D)
Definition TCling.cxx:590
bool TClingLookupHelper__AutoParse(const char *cname)
Allow calling autoparsing from TMetaUtils.
Definition TCling.cxx:910
R__EXTERN int optind
Definition TCling.cxx:333
void * TCling__LockCompilationDuringUserCodeExecution()
Lock the interpreter.
Definition TCling.cxx:384
void TCling__UpdateListsOnUnloaded(const cling::Transaction &T)
Definition TCling.cxx:585
void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt *&normCtxt)
Definition TCling.cxx:573
int TCling__LoadLibrary(const char *library)
Load a library.
Definition TCling.cxx:349
void TCling__DEBUG__dump(clang::DeclContext *DC)
Definition TCling.cxx:226
bool TClingLookupHelper__CheckInClassTable(const std::string &tname, std::string &result)
Check if the class name is present in TClassTable.
Definition TCling.cxx:1019
ETupleOrdering
Check in what order the member of a tuple are layout.
Definition TCling.cxx:3964
bool TCling__LibraryLoadingFailed(const std::string &errmessage, const std::string &libStem, bool permanent, bool resolved)
Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name, which is extracted by er...
Definition TCling.cxx:367
static const std::unordered_set< std::string > gIgnoredPCMNames
List of dicts that have the PCM information already in the PCH.
Definition TCling.cxx:1995
static Bool_t s_IsLibraryLoaded(const char *libname, cling::Interpreter *fInterpreter)
Definition TCling.cxx:3188
const char * TCling__GetClassSharedLibs(const char *className, bool skipCore)
Definition TCling.cxx:649
static GlobalModuleIndex * loadGlobalModuleIndex(cling::Interpreter &interp)
Definition TCling.cxx:1114
bool TClingLookupHelper__ExistingTypeCheck(const std::string &tname, std::string &result)
Try hard to avoid looking up in the Cling database as this could enduce an unwanted autoparsing.
Definition TCling.cxx:919
static bool HasASTFileOnDisk(clang::Module *M, const clang::Preprocessor &PP, std::string *FullFileName=nullptr)
Checks if there is an ASTFile on disk for the given module M.
Definition TCling.cxx:1099
void TCling__UnlockCompilationDuringUserCodeExecution(void *)
Unlock the interpreter.
Definition TCling.cxx:395
static std::string AlternateTuple(const char *classname, const cling::LookupHelper &lh, Bool_t silent)
Definition TCling.cxx:4006
static bool R__InitStreamerInfoFactory()
Helper to initialize TVirtualStreamerInfo's factor early.
Definition TCling.cxx:1718
int TCling__AutoParseCallback(const char *className)
Definition TCling.cxx:644
clang::RecordDecl * TCling__DEBUG__DCtoRecordDecl(clang::DeclContext *DC)
Definition TCling.cxx:223
int TCling_GenerateDictionary(const std::vector< std::string > &classes, const std::vector< std::string > &headers, const std::vector< std::string > &fwdDecls, const std::vector< std::string > &unknown)
Definition TCling.cxx:715
static bool HaveFullGlobalModuleIndex
Definition TCling.cxx:1113
bool TCling__TEST_isInvalidDecl(clang::Decl *D)
Definition TCling.cxx:253
void TCling__LibraryUnloadedRTTI(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:609
void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter *)
Definition TCling.cxx:580
const Decl * TCling__GetObjectDecl(TObject *obj)
Definition TCling.cxx:620
static ETupleOrdering IsTupleAscending()
Definition TCling.cxx:3982
void TCling__RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
Definition TCling.cxx:604
static void TCling__UpdateClassInfo(const NamedDecl *TD)
Update TClingClassInfo for a class (e.g. upon seeing a definition).
Definition TCling.cxx:405
clang::DeclContext * TCling__DEBUG__getDeclContext(clang::Decl *D)
Definition TCling.cxx:217
int TCling__CompileMacro(const char *fileName, const char *options)
Definition TCling.cxx:660
#define R__DLLEXPORT
Definition TCling.cxx:153
void * TCling__ResetInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:376
void TCling__DEBUG__decl_dump(void *D)
Definition TCling.cxx:235
int TCling__AutoLoadCallback(const char *className)
Definition TCling.cxx:639
static bool LoadModule(const std::string &ModuleName, cling::Interpreter &interp)
Definition TCling.cxx:1064
static void RegisterCxxModules(cling::Interpreter &clingInterp)
Definition TCling.cxx:1217
static void ConstructorName(std::string &name, const clang::Decl *decl, cling::Interpreter &interp, const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt)
Definition TCling.cxx:8815
void TCling__PrintStackTrace()
Print a StackTrace!
Definition TCling.cxx:342
static int HandleInterpreterException(cling::MetaProcessor *metaProcessor, const char *input_line, cling::Interpreter::CompilationResult &compRes, cling::Value *result)
Let cling process a command line.
Definition TCling.cxx:2480
static std::string GetSharedLibImmediateDepsSlow(std::string lib, cling::Interpreter *interp, bool skipLoadedLibs=true)
This interface returns a list of dependent libraries in the form: lib libA.so libB....
Definition TCling.cxx:7235
void TCling__DEBUG__printName(clang::Decl *D)
Definition TCling.cxx:238
static clang::ClassTemplateDecl * FindTemplateInNamespace(clang::Decl *decl)
Find a template decl within N nested namespaces, 0<=N<inf Assumes 1 and only 1 template present and 1...
Definition TCling.cxx:696
static void PrintDlError(const char *dyLibName, const char *modulename)
Definition TCling.cxx:2020
TInterpreter * CreateInterpreter(void *interpLibHandle, const char *argv[])
Definition TCling.cxx:624
static std::string GetClassSharedLibsForModule(const char *cls, cling::LookupHelper &LH, bool skipCore)
Definition TCling.cxx:7070
const char * fantomline
Definition TCling.cxx:857
void TCling__LibraryLoadedRTTI(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:599
static cling::Interpreter::CompilationResult ExecAutoParse(const char *what, Bool_t header, cling::Interpreter *interpreter)
Parse the payload or header.
Definition TCling.cxx:6396
static bool requiresRootMap(const char *rootmapfile)
Definition TCling.cxx:5576
clang::NamespaceDecl * TCling__DEBUG__DCtoNamespace(clang::DeclContext *DC)
Definition TCling.cxx:220
TObject * TCling__GetObjectAddress(const char *Name, void *&LookupCtx)
Definition TCling.cxx:616
static void LoadModules(const std::vector< std::string > &modules, cling::Interpreter &interp)
Loads the C++ modules that we require to run any ROOT program.
Definition TCling.cxx:1086
int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *nsDecl)
Definition TCling.cxx:655
void DestroyInterpreter(TInterpreter *interp)
Definition TCling.cxx:632
static bool hasPrecomputedLibraryDeps(llvm::StringRef lib)
Definition TCling.cxx:7347
void TCling__SplitAclicMode(const char *fileName, string &mode, string &args, string &io, string &fname)
Definition TCling.cxx:667
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
EDataType
Definition TDataType.h:28
@ kULong64_t
Definition TDataType.h:32
@ kLong64_t
Definition TDataType.h:32
@ kIsDestructor
@ kIsConversion
@ kIsInlined
@ kIsConstructor
@ kIsOperator
@ kIsPublic
Definition TDictionary.h:75
@ kIsConstant
Definition TDictionary.h:88
@ kIsConstMethod
Definition TDictionary.h:96
@ kIsClass
Definition TDictionary.h:65
@ kIsEnum
Definition TDictionary.h:68
@ kIsPrivate
Definition TDictionary.h:77
@ kIsFundamental
Definition TDictionary.h:70
@ kIsCompiled
Definition TDictionary.h:86
@ kIsStatic
Definition TDictionary.h:80
@ kIsExplicit
Definition TDictionary.h:94
@ kIsStruct
Definition TDictionary.h:66
@ kIsProtected
Definition TDictionary.h:76
@ kIsVirtual
Definition TDictionary.h:72
@ kIsUnion
Definition TDictionary.h:67
@ kIsPureVirtual
Definition TDictionary.h:73
@ kIsNamespace
Definition TDictionary.h:95
@ kIsNotReacheable
Definition TDictionary.h:87
#define gDirectory
Definition TDirectory.h:385
@ kEnvUser
Definition TEnv.h:71
@ kEnvGlobal
Definition TEnv.h:70
@ kEnvLocal
Definition TEnv.h:72
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:125
void Info(const char *location, const char *msgfmt,...)
Use this function for informational messages.
Definition TError.cxx:241
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:208
Int_t gErrorIgnoreLevel
errors with level below this value will be ignored. Default is kUnset.
Definition TError.cxx:33
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
Definition TError.cxx:252
void Fatal(const char *location, const char *msgfmt,...)
Use this function in case of a fatal error. It will abort the program.
Definition TError.cxx:267
#define N
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t cursor
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h length
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char cname
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
Option_t Option_t TPoint TPoint const char mode
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t property
Option_t Option_t TPoint TPoint const char text
char name[80]
Definition TGX11.cxx:110
R__EXTERN TVirtualMutex * gInterpreterMutex
#define R__LOCKGUARD_CLING(mutex)
R__EXTERN TInterpreter * gCling
#define gInterpreter
Int_t gDebug
Global variable setting the debug level. Set to 0 to disable, increase it in steps of 1 to increase t...
Definition TROOT.cxx:627
#define gROOT
Definition TROOT.h:411
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2495
@ kReadPermission
Definition TSystem.h:55
Bool_t R_ISREG(Int_t mode)
Definition TSystem.h:126
R__EXTERN TSystem * gSystem
Definition TSystem.h:572
R__EXTERN TVirtualMutex * gGlobalMutex
#define R__LOCKGUARD(mutex)
#define R__WRITE_LOCKGUARD(mutex)
#define R__READ_LOCKGUARD(mutex)
const char * proto
Definition civetweb.c:18822
#define free
Definition civetweb.c:1578
#define snprintf
Definition civetweb.c:1579
const_iterator begin() const
const_iterator end() const
void AddTemplAndNargsToKeep(const clang::ClassTemplateDecl *templ, unsigned int i)
const Config_t & GetConfig() const
virtual std::unique_ptr< StateDelta > Rewind(const State &earlierState)=0
virtual void Apply(std::unique_ptr< StateDelta > &&delta)=0
static Longptr_t ExecuteFile(const char *file, Int_t *error=nullptr, Bool_t keep=kFALSE)
Execute a file containing a C++ macro (static method).
virtual TApplicationImp * GetApplicationImp()
virtual Bool_t IsCmdThread()
Each class (see TClass) has a linked list of its base class(es).
Definition TBaseClass.h:33
TClassRef is used to implement a permanent reference to a TClass object.
Definition TClassRef.h:29
static DictFuncPtr_t GetDict(const char *cname)
Given the class name returns the Dictionary() function of a class (uses hash of name).
static TProtoClass * GetProtoNorm(const char *cname)
Given the class normalized name returns the TClassProto object for the class.
static DictFuncPtr_t GetDictNorm(const char *cname)
Given the normalized class name returns the Dictionary() function of a class (uses hash of name).
static TProtoClass * GetProto(const char *cname)
Given the class name returns the TClassProto object for the class.
static Bool_t Check(const char *cname, std::string &normname)
static void Add(const char *cname, Version_t id, const std::type_info &info, DictFuncPtr_t dict, Int_t pragmabits)
Add a class to the class table (this is a static function).
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
TDataMember * GetDataMember(const char *datamember) const
Return pointer to datamember object with name "datamember".
Definition TClass.cxx:3470
ROOT::ESTLType GetCollectionType() const
Return the 'type' of the STL the TClass is representing.
Definition TClass.cxx:2891
void RemoveStreamerInfo(Int_t slot)
Remove and delete the StreamerInfo in the given slot.
Definition TClass.cxx:7417
EState fState
cached of the streaming method to use
Definition TClass.h:285
std::atomic< TList * > fBase
Definition TClass.h:204
static void AddClassToDeclIdMap(TDictionary::DeclId_t id, TClass *cl)
static: Add a TClass* to the map of classes.
Definition TClass.cxx:576
Version_t fClassVersion
Definition TClass.h:225
TList * GetListOfFunctionTemplates(Bool_t load=kTRUE)
Return TListOfFunctionTemplates for a class.
Definition TClass.cxx:3825
void * DynamicCast(const TClass *base, void *obj, Bool_t up=kTRUE)
Cast obj of this class type up to baseclass cl if up is true.
Definition TClass.cxx:4942
static void RemoveClassDeclId(TDictionary::DeclId_t id)
Definition TClass.cxx:603
static Bool_t HasNoInfoOrEmuOrFwdDeclaredDecl(const char *)
Definition TClass.cxx:3429
static TClass * LoadClass(const char *requestedname, Bool_t silent)
Helper function used by TClass::GetClass().
Definition TClass.cxx:5788
Int_t Size() const
Return size of object of this class.
Definition TClass.cxx:5743
@ kLoading
Definition TClass.h:340
@ kUnloading
Definition TClass.h:340
TObjArray * fStreamerInfo
Definition TClass.h:201
ClassInfo_t * GetClassInfo() const
Definition TClass.h:445
ClassInfo_t * fClassInfo
Definition TClass.h:226
TVirtualCollectionProxy * GetCollectionProxy() const
Return the proxy describing the collection (if any).
Definition TClass.cxx:2902
void ResetCaches()
To clean out all caches.
Definition TClass.cxx:4242
static Int_t ReadRules()
Read the class.rules files from the default location:.
Definition TClass.cxx:1806
@ kInterpreted
Definition TClass.h:129
@ kHasTClassInit
Definition TClass.h:130
@ kEmulated
Definition TClass.h:128
@ kForwardDeclared
Definition TClass.h:127
@ kNamespaceForMeta
Definition TClass.h:134
std::atomic< Bool_t > fCanLoadClassInfo
Whether info was loaded from a root pcm.
Definition TClass.h:268
std::atomic< Bool_t > fHasRootPcmInfo
C++ Property of the class (is abstract, has virtual table, etc.)
Definition TClass.h:267
const char * GetDeclFileName() const
Return name of the file containing the declaration of this class.
Definition TClass.cxx:3494
@ kIsTObject
Definition TClass.h:103
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition TClass.cxx:2973
Emulation of the CINT BaseClassInfo class.
const char * Name() const
Emulation of the CINT CallFunc class.
void SetArgs(const char *args)
void SetFunc(const TClingClassInfo *info, const char *method, const char *arglist, Longptr_t *poffset)
void ExecWithArgsAndReturn(void *address, const void *args[]=0, int nargs=0, void *ret=0)
void Exec(void *address, TInterpreterValue *interpVal=0)
TClingMethodInfo * FactoryMethod() const
bool IsAutoLoadingEnabled() const
void SetAutoParsingSuspended(bool val=true)
void SetAutoLoadingEnabled(bool val=true)
Emulation of the CINT ClassInfo class.
static bool IsEnum(cling::Interpreter *interp, const char *name)
void FullName(std::string &output, const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) const
TClingMethodInfo GetMethodWithArgs(const char *fname, const char *arglist, Longptr_t *poffset, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch, EInheritanceMode imode=kWithInheritance) const
const clang::FunctionTemplateDecl * GetFunctionTemplate(const char *fname) const
TClingMethodInfo GetMethod(const char *fname) const
const clang::ValueDecl * GetDataMember(const char *name) const
Emulation of the CINT DataMemberInfo class.
virtual const char * Name() const
virtual bool IsValid() const
Uses clang::TextDiagnosticPrinter to format diagnostics, which are then passed to a user-specified fu...
Emulation of the CINT MethodInfo class.
bool IsValid() const override
Emulation of the CINT MethodInfo class.
TDictionary::DeclId_t GetDeclId() const
Emulation of the CINT TypeInfo class.
Emulation of the CINT TypedefInfo class.
Bridge between cling::Value and ROOT.
Definition TClingValue.h:36
const char * Data()
Definition TCling.cxx:1040
bool Append(const std::string &str)
Append string to the storage if not added already.
Definition TCling.cxx:1048
std::string fContent
Definition TCling.h:618
This class defines an interface to the cling C++ interpreter.
Definition TCling.h:102
static Int_t DeepAutoLoadImpl(const char *cls, std::unordered_set< std::string > &visited, bool nameIsNormalized)
Definition TCling.cxx:6268
const char * MethodArgInfo_DefaultValue(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9376
bool ClassInfo_IsScopedEnum(ClassInfo_t *info) const final
Definition TCling.cxx:8378
const char * TypeInfo_Name(TypeInfo_t *) const final
Definition TCling.cxx:9468
void * MethodInfo_InterfaceMethod(MethodInfo_t *minfo) const final
Definition TCling.cxx:9130
void LoadEnums(TListOfEnums &cl) const final
Create list of pointers to enums for TClass cl.
Definition TCling.cxx:4459
void UpdateListOfGlobals() final
No op: see TClingCallbacks (used to update the list of globals)
Definition TCling.cxx:3944
bool TypedefInfo_IsValid(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9562
Int_t AutoLoad(const char *classname, Bool_t knowDictNotLoaded=kFALSE) final
Load library containing the specified class.
Definition TCling.cxx:6329
void CallFunc_Init(CallFunc_t *func) const final
Definition TCling.cxx:8016
void SetGetline(const char *(*getlineFunc)(const char *prompt), void(*histaddFunc)(const char *line)) final
Set a getline function to call when input is needed.
Definition TCling.cxx:3707
bool LibraryLoadingFailed(const std::string &, const std::string &, bool, bool)
Definition TCling.cxx:6632
void GenericError(const char *error) const final
Let the interpreter issue a generic error, and set its error state.
Definition TCling.cxx:7531
std::vector< void * > fRegisterModuleDyLibs
Definition TCling.h:138
void CallFunc_ExecWithReturn(CallFunc_t *func, void *address, void *ret) const final
Definition TCling.cxx:7942
bool IsIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9627
TypeInfo_t * MethodInfo_Type(MethodInfo_t *minfo) const final
Definition TCling.cxx:9189
std::vector< std::string > fAutoLoadLibStorage
Definition TCling.h:118
void CallFunc_Delete(CallFunc_t *func) const final
Definition TCling.cxx:7919
Bool_t fLockProcessLine
Definition TCling.h:127
int LoadFile(const char *path) const final
Load a source file or library called path into the interpreter.
Definition TCling.cxx:7574
void ResetAll() final
Reset the Cling state to its initial state.
Definition TCling.cxx:3783
void SetDeclAttr(DeclId_t, const char *) final
Definition TCling.cxx:8801
void HandleNewDecl(const void *DV, bool isDeserialized, std::set< TClass * > &modifiedClasses)
Definition TCling.cxx:512
void InvalidateCachedDecl(const std::tuple< TListOfDataMembers *, TListOfFunctions *, TListOfFunctionTemplates *, TListOfEnums * > &Lists, const clang::Decl *D)
Invalidate cached TCling information for the given declaration, and removed it from the appropriate o...
Definition TCling.cxx:6966
Long_t MethodInfo_Property(MethodInfo_t *minfo) const final
Definition TCling.cxx:9171
void LoadFunctionTemplates(TClass *cl) const final
Create list of pointers to function templates for TClass cl.
Definition TCling.cxx:4506
bool ClassInfo_IsValidMethod(ClassInfo_t *info, const char *method, const char *proto, Longptr_t *offset, ROOT::EFunctionMatchMode=ROOT::kConversionMatch) const final
Definition TCling.cxx:8412
Long_t DataMemberInfo_Property(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8734
int SetClassAutoparsing(int) final
Enable/Disable the Autoparsing of headers.
Definition TCling.cxx:7659
std::vector< const char * > fCurExecutingMacros
Definition TCling.h:149
void CreateListOfDataMembers(TClass *cl) const final
Create list of pointers to data members for TClass cl.
Definition TCling.cxx:4553
void RewindDictionary() final
Rewind Cling dictionary to the point where it was before executing the current macro.
Definition TCling.cxx:3828
bool ClassInfo_IsValid(ClassInfo_t *info) const final
Definition TCling.cxx:8404
void UpdateListsOnCommitted(const cling::Transaction &T)
Definition TCling.cxx:6840
int TypeInfo_RefType(TypeInfo_t *) const final
Definition TCling.cxx:9484
void CreateListOfBaseClasses(TClass *cl) const final
Create list of pointers to base class(es) for TClass cl.
Definition TCling.cxx:4430
ClassInfo_t * ClassInfo_Factory(Bool_t all=kTRUE) const final
Definition TCling.cxx:8291
const char * MethodInfo_Name(MethodInfo_t *minfo) const final
Definition TCling.cxx:9218
BaseClassInfo_t * BaseClassInfo_Factory(ClassInfo_t *info) const final
Definition TCling.cxx:8548
Bool_t LoadText(const char *text) const final
Load the declarations from text into the interpreter.
Definition TCling.cxx:7589
const char * GetSharedLibDeps(const char *lib, bool tryDyld=false) final
Get the list a libraries on which the specified lib depends.
Definition TCling.cxx:7363
EReturnType MethodInfo_MethodCallReturnType(MethodInfo_t *minfo) const final
Definition TCling.cxx:9268
TObject * GetObjectAddress(const char *Name, void *&LookupCtx)
If the interpreter encounters Name, check whether that is an object ROOT could retrieve.
Definition TCling.cxx:7790
Longptr_t ProcessLineAsynch(const char *line, EErrorCode *error=nullptr)
Let cling process a command line asynch.
Definition TCling.cxx:3619
bool MethodInfo_IsValid(MethodInfo_t *minfo) const final
Definition TCling.cxx:9139
FuncTempInfo_t * FuncTempInfo_Factory(DeclId_t declid) const final
Construct a FuncTempInfo_t.
Definition TCling.cxx:8891
TypeInfo_t * TypeInfo_Factory() const final
Definition TCling.cxx:9428
bool IsClassAutoLoadingEnabled() const
Returns if class AutoLoading is currently enabled.
Definition TCling.cxx:7628
void InvalidateGlobal(const clang::Decl *D)
Invalidate cached TCling information for the given global declaration.
Definition TCling.cxx:6951
bool IsSameType(const void *QualTypePtr1, const void *QualTypePtr2) const final
Definition TCling.cxx:9618
int Evaluate(const char *, TInterpreterValue &) final
Get the interpreter value corresponding to the statement.
Definition TCling.cxx:7752
std::unique_ptr< TInterpreterValue > MakeInterpreterValue() const final
Definition TCling.cxx:7737
void UpdateListOfLoadedSharedLibraries()
Definition TCling.cxx:3407
const char * TypedefInfo_Title(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9610
~TCling() final
Destroy the interpreter interface.
Definition TCling.cxx:1670
void CallFunc_SetFuncProto(CallFunc_t *func, ClassInfo_t *info, const char *method, const char *proto, Longptr_t *Offset, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch) const final
Interface to cling function.
Definition TCling.cxx:8141
void InitRootmapFile(const char *name)
Create a resource table and read the (possibly) three resource files, i.e.
Definition TCling.cxx:5719
Int_t AutoParse(const char *cls) final
Parse the headers relative to the class Returns 1 in case of success, 0 in case of failure.
Definition TCling.cxx:6587
void LoadPCM(std::string pcmFileNameFullPath)
Tries to load a rdict PCM, issues diagnostics if it fails.
Definition TCling.cxx:1867
void UpdateListOfMethods(TClass *cl) const final
Update the list of pointers to method for TClass cl This is now a nop.
Definition TCling.cxx:4571
void AddFriendToClass(clang::FunctionDecl *, clang::CXXRecordDecl *) const
Inject function as a friend into klass.
Definition TCling.cxx:7843
void PrintIntro() final
No-op; see TRint instead.
Definition TCling.cxx:2705
Bool_t fCxxModulesEnabled
Definition TCling.h:128
int BaseClassInfo_Next(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8568
void RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
Internal function. Actually do the update of the ClassInfo when seeing.
Definition TCling.cxx:6698
CallFunc_t * CallFunc_FactoryCopy(CallFunc_t *func) const final
Definition TCling.cxx:7993
Double_t CallFunc_ExecDouble(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7977
void CallFunc_ResetArg(CallFunc_t *func) const final
Definition TCling.cxx:8042
const char * GetCurrentMacroName() const final
Return the file name of the currently interpreted file, included or not.
Definition TCling.cxx:5527
Bool_t IsLoaded(const char *filename) const final
Return true if the file has already been loaded by cint.
Definition TCling.cxx:3231
void SaveGlobalsContext() final
Save the current Cling state of global objects.
Definition TCling.cxx:3931
void CallFunc_IgnoreExtraArgs(CallFunc_t *func, bool ignore) const final
Definition TCling.cxx:8008
void ApplyToInterpreterMutex(void *delta)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
Definition TCling.cxx:9706
void * LazyFunctionCreatorAutoload(const std::string &mangled_name)
Autoload a library based on a missing symbol.
Definition TCling.cxx:6655
Int_t GenerateDictionary(const char *classes, const char *includes="", const char *options=nullptr) final
Generate the dictionary for the C++ classes listed in the first argument (in a semi-colon separated l...
Definition TCling.cxx:4787
Bool_t ClassInfo_Contains(ClassInfo_t *info, DeclId_t declid) const final
Return true if the entity pointed to by 'declid' is declared in the context described by 'info'.
Definition TCling.cxx:8207
Bool_t IsLibraryLoaded(const char *libname) const final
Definition TCling.cxx:3197
Long_t GetExecByteCode() const final
This routines used to return the address of the internal wrapper function (of the interpreter) that w...
Definition TCling.cxx:7553
int DataMemberInfo_ArrayDim(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8660
DataMemberInfo_t * DataMemberInfo_FactoryCopy(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8694
Bool_t HandleNewTransaction(const cling::Transaction &T)
Helper function to increase the internal Cling count of transactions that change the AST.
Definition TCling.cxx:3724
int ReadRootmapFile(const char *rootmapfile, TUniqueString *uniqueString=nullptr)
Read and parse a rootmapfile in its new format, and return 0 in case of success, -1 if the file has a...
Definition TCling.cxx:5592
std::map< SpecialObjectLookupCtx_t, SpecialObjectMap_t > fSpecialObjectMaps
Definition TCling.h:153
int ClassInfo_Next(ClassInfo_t *info) const final
Definition TCling.cxx:8428
void SetErrmsgcallback(void *p) const final
Set a callback to receive error messages.
Definition TCling.cxx:7680
bool MethodArgInfo_IsValid(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9352
int TypeInfo_Size(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9492
Int_t DeleteGlobal(void *obj) final
Delete obj from Cling symbol table so it cannot be accessed anymore.
Definition TCling.cxx:3842
int GetSecurityError() const final
Interface to cling function.
Definition TCling.cxx:7561
void SetTempLevel(int val) const final
Create / close a scope for temporaries.
Definition TCling.cxx:7716
std::set< size_t > fPayloads
Definition TCling.h:122
UInt_t FuncTempInfo_TemplateNargs(FuncTempInfo_t *) const final
Return the maximum number of template arguments of the function template described by ft_info.
Definition TCling.cxx:8925
DeclId_t GetFunctionWithPrototype(ClassInfo_t *cl, const char *method, const char *proto, Bool_t objectIsConst=kFALSE, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch) final
Return pointer to cling interface function for a method of a class with a certain prototype,...
Definition TCling.cxx:5219
TypedefInfo_t * TypedefInfo_Factory() const final
Definition TCling.cxx:9529
TObjArray * fRootmapFiles
Definition TCling.h:126
Longptr_t ProcessLine(const char *line, EErrorCode *error=nullptr) final
Definition TCling.cxx:2510
int ClassInfo_Size(ClassInfo_t *info) const final
Definition TCling.cxx:8476
const char * MethodArgInfo_TypeName(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9392
cling::Interpreter * GetInterpreterImpl() const
Definition TCling.h:643
Longptr_t ExecuteMacro(const char *filename, EErrorCode *error=nullptr) final
Execute a cling macro.
Definition TCling.cxx:5467
std::vector< std::pair< TClass *, DictFuncPtr_t > > fClassesToUpdate
Definition TCling.h:146
int DataMemberInfo_Next(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8718
const char * TypedefInfo_Name(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9602
void BaseClassInfo_Delete(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8541
Long_t MethodInfo_ExtraProperty(MethodInfo_t *minfo) const final
Definition TCling.cxx:9180
void LoadMacro(const char *filename, EErrorCode *error=nullptr) final
Load a macro file in cling's memory.
Definition TCling.cxx:3611
FuncTempInfo_t * FuncTempInfo_FactoryCopy(FuncTempInfo_t *) const final
Construct a FuncTempInfo_t.
Definition TCling.cxx:8902
int DataMemberInfo_MaxIndex(DataMemberInfo_t *dminfo, Int_t dim) const final
Definition TCling.cxx:8710
Bool_t FuncTempInfo_IsValid(FuncTempInfo_t *) const final
Check validity of a FuncTempInfo_t.
Definition TCling.cxx:8913
void AddIncludePath(const char *path) final
Add a directory to the list of directories in which the interpreter looks for include files.
Definition TCling.cxx:2719
bool ClassInfo_IsBase(ClassInfo_t *info, const char *name) const final
Definition TCling.cxx:8363
void RecursiveRemove(TObject *obj) final
Delete object from cling symbol table so it can not be used anymore.
Definition TCling.cxx:3742
const char * DataMemberInfo_TypeName(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8758
DeclId_t GetDataMemberAtAddr(const void *addr) const final
Return pointer to cling DeclId for a data member with a given name.
Definition TCling.cxx:5014
void CallFunc_SetArgArray(CallFunc_t *func, Longptr_t *paramArr, Int_t nparam) const final
Definition TCling.cxx:8098
std::string CallFunc_GetWrapperCode(CallFunc_t *func) const final
Definition TCling.cxx:8188
void * RewindInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:9736
const char * MethodArgInfo_Name(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9384
Bool_t HasPCMForLibrary(const char *libname) const final
Return true if ROOT has cxxmodules pcm for a given library name.
Definition TCling.cxx:3206
void TypedefInfo_Init(TypedefInfo_t *tinfo, const char *name) const final
Definition TCling.cxx:9552
const char * DataMemberInfo_Title(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8782
Longptr_t CallFunc_ExecInt(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7961
void ClearStack() final
Delete existing temporary values.
Definition TCling.cxx:3144
void SetAlloclockfunc(void(*)()) const final
[Place holder for Mutex Lock] Provide the interpreter with a way to acquire a lock used to protect cr...
Definition TCling.cxx:7610
Bool_t SetErrorMessages(Bool_t enable=kTRUE) final
If error messages are disabled, the interpreter should suppress its failures and warning messages fro...
Definition TCling.cxx:7430
MethodInfo_t * CallFunc_FactoryMethod(CallFunc_t *func) const final
Definition TCling.cxx:8000
TypedefInfo_t * TypedefInfo_FactoryCopy(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9545
void GetFunctionOverloads(ClassInfo_t *cl, const char *funcname, std::vector< DeclId_t > &res) const final
Insert overloads of name in cl to res.
Definition TCling.cxx:5112
void UnRegisterTClassUpdate(const TClass *oldcl) final
If the dictionary is loaded, we can remove the class from the list (otherwise the class might be load...
Definition TCling.cxx:2450
std::string MethodArgInfo_TypeNormalizedName(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9400
DeclId_t GetEnum(TClass *cl, const char *name) const final
Return pointer to cling Decl of global/static variable that is located at the address given by addr.
Definition TCling.cxx:4896
Long_t MethodArgInfo_Property(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9368
int TypedefInfo_Size(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9586
void CallFunc_ExecWithArgsAndReturn(CallFunc_t *func, void *address, const void *args[]=nullptr, int nargs=0, void *ret=nullptr) const final
Definition TCling.cxx:7950
void GetInterpreterTypeName(const char *name, std::string &output, Bool_t full=kFALSE) final
The 'name' is known to the interpreter, this function returns the internal version of this name (usua...
Definition TCling.cxx:5264
Int_t fGlobalsListSerial
Definition TCling.h:114
TString fSharedLibs
Definition TCling.h:113
std::map< std::string, llvm::StringRef > fPendingRdicts
Definition TCling.h:633
static void UpdateClassInfoWork(const char *name)
Definition TCling.cxx:6820
Int_t Load(const char *filenam, Bool_t system=kFALSE) final
Load a library file in cling's memory.
Definition TCling.cxx:3574
int TypedefInfo_Next(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9570
void * GetInterfaceMethod(TClass *cl, const char *method, const char *params, Bool_t objectIsConst=kFALSE) final
Return pointer to cling interface function for a method of a class with parameters params (params is ...
Definition TCling.cxx:5071
void TypeInfo_Init(TypeInfo_t *tinfo, const char *funcname) const final
Definition TCling.cxx:9451
Bool_t SetSuspendAutoParsing(Bool_t value) final
Suspend the Autoparsing of headers.
Definition TCling.cxx:7670
int DataMemberInfo_TypeSize(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8750
static void * fgSetOfSpecials
Definition TCling.h:105
const char * ClassInfo_Title(ClassInfo_t *info) const final
Definition TCling.cxx:8518
const char * DataMemberInfo_Name(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8774
const char * TypeName(const char *typeDesc) final
Return the absolute type of typeDesc.
Definition TCling.cxx:5542
ROOT::TMetaUtils::TNormalizedCtxt * fNormalizedCtxt
Definition TCling.h:134
void ForgetMutexState() final
Definition TCling.cxx:9690
int MethodInfo_Next(MethodInfo_t *minfo) const final
Definition TCling.cxx:9163
Long_t ClassInfo_ClassProperty(ClassInfo_t *info) const final
Definition TCling.cxx:8252
void MethodInfo_Delete(MethodInfo_t *minfo) const final
Interface to cling function.
Definition TCling.cxx:9082
bool fIsShuttingDown
Definition TCling.h:187
void MethodArgInfo_Delete(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9321
bool IsSignedIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9635
DataMemberInfo_t * DataMemberInfo_Factory(ClassInfo_t *clinfo, TDictionary::EMemberSelection selection) const final
Definition TCling.cxx:8675
void ClassInfo_Destruct(ClassInfo_t *info, void *arena) const final
Definition TCling.cxx:8283
TClass * GetClass(const std::type_info &typeinfo, Bool_t load) const final
Demangle the name (from the typeinfo) and then request the class via the usual name based interface (...
Definition TCling.cxx:6174
Int_t UnloadAllSharedLibraryMaps() final
Unload the library map entries coming from all the loaded shared libraries.
Definition TCling.cxx:6062
void ClassInfo_Init(ClassInfo_t *info, const char *funcname) const final
Definition TCling.cxx:8345
std::set< TClass * > & GetModTClasses()
Definition TCling.h:578
ClassInfo_t * BaseClassInfo_ClassInfo(BaseClassInfo_t *) const final
Definition TCling.cxx:8613
TClingCallbacks * fClingCallbacks
Definition TCling.h:139
Long64_t CallFunc_ExecInt64(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7969
Long_t ClassInfo_Property(ClassInfo_t *info) const final
Definition TCling.cxx:8468
Longptr_t ClassInfo_GetBaseOffset(ClassInfo_t *fromDerived, ClassInfo_t *toBase, void *address, bool isDerivedObject) const final
Definition TCling.cxx:8592
void UpdateEnumConstants(TEnum *enumObj, TClass *cl) const final
Definition TCling.cxx:437
void ExecuteWithArgsAndReturn(TMethod *method, void *address, const void *args[]=nullptr, int nargs=0, void *ret=nullptr) const final
Definition TCling.cxx:5449
Bool_t IsErrorMessagesEnabled() const final
If error messages are disabled, the interpreter should suppress its failures and warning messages fro...
Definition TCling.cxx:7416
TString fIncludePath
Definition TCling.h:115
int DisplayIncludePath(FILE *fout) const final
Interface to cling function.
Definition TCling.cxx:7493
void TransactionRollback(const cling::Transaction &T)
Definition TCling.cxx:7025
Long_t FuncTempInfo_Property(FuncTempInfo_t *) const final
Return the property of the function template.
Definition TCling.cxx:8946
TEnum * CreateEnum(void *VD, TClass *cl) const final
Definition TCling.cxx:485
const char * TypeInfo_TrueName(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9500
Int_t UnloadLibraryMap(const char *library) final
Unload library map entries coming from the specified library.
Definition TCling.cxx:6080
void RegisterTemporary(const TInterpreterValue &value)
Definition TCling.cxx:7763
MutexStateAndRecurseCount fInitialMutex
Definition TCling.h:174
const char * GetSharedLibs() final
Return the list of shared libraries loaded into the process.
Definition TCling.cxx:7063
int MethodArgInfo_Next(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9360
void SnapshotMutexState(ROOT::TVirtualRWMutex *mtx) final
Definition TCling.cxx:9675
Long_t TypeInfo_Property(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9476
const char * MethodInfo_GetPrototype(MethodInfo_t *minfo) const final
Definition TCling.cxx:9209
UInt_t FuncTempInfo_TemplateMinReqArgs(FuncTempInfo_t *) const final
Return the number of required template arguments of the function template described by ft_info.
Definition TCling.cxx:8936
std::vector< cling::Value > * fTemporaries
Definition TCling.h:133
void RegisterModule(const char *modulename, const char **headers, const char **includePaths, const char *payloadCode, const char *fwdDeclsCode, void(*triggerFunc)(), const FwdDeclArgsToKeepCollection_t &fwdDeclsArgToSkip, const char **classesHeaders, Bool_t lateRegistration=false, Bool_t hasCxxModule=false) final
Inject the module named "modulename" into cling; load all headers.
Definition TCling.cxx:2067
static Int_t ShallowAutoLoadImpl(const char *cls)
Definition TCling.cxx:6220
void MethodInfo_CreateSignature(MethodInfo_t *minfo, TString &signature) const final
Definition TCling.cxx:9089
Bool_t CheckClassTemplate(const char *name) final
Return true if there is a class template by the given name ...
Definition TCling.cxx:4408
void LibraryLoaded(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:7048
void RegisterTClassUpdate(TClass *oldcl, DictFuncPtr_t dict) final
Register classes that already existed prior to their dictionary loading and that already had a ClassI...
Definition TCling.cxx:2441
bool IsVoidPointerType(const void *QualTypePtr) const final
Definition TCling.cxx:9667
TObjArray * GetRootMapFiles() const final
Definition TCling.h:223
bool DataMemberInfo_IsValid(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8702
bool ClassInfo_IsEnum(const char *name) const final
Definition TCling.cxx:8371
int MethodInfo_NDefaultArg(MethodInfo_t *minfo) const final
Definition TCling.cxx:9155
bool IsFloatingType(const void *QualTypePtr) const final
Definition TCling.cxx:9651
void CreateListOfMethods(TClass *cl) const final
Create list of pointers to methods for TClass cl.
Definition TCling.cxx:4562
Int_t RescanLibraryMap() final
Scan again along the dynamic path for library maps.
Definition TCling.cxx:5989
std::map< const cling::Transaction *, size_t > fTransactionHeadersMap
Definition TCling.h:120
void ReportDiagnosticsToErrorHandler(bool enable=true) final
Report diagnostics to the ROOT error handler (see TError.h).
Definition TCling.cxx:7689
const char * MethodInfo_GetMangledName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9198
TypeInfo_t * MethodArgInfo_TypeInfo(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9408
Bool_t fHeaderParsingOnDemand
Definition TCling.h:181
std::hash< std::string > fStringHashFunction
Definition TCling.h:124
TEnv * fMapfile
Definition TCling.h:117
static void RemoveAndInvalidateObject(List &L, Object *O)
Definition TCling.h:590
void * GetInterfaceMethodWithPrototype(TClass *cl, const char *method, const char *proto, Bool_t objectIsConst=kFALSE, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch) final
Return pointer to cling interface function for a method of a class with a certain prototype,...
Definition TCling.cxx:5174
void * ClassInfo_New(ClassInfo_t *info) const final
Definition TCling.cxx:8436
int DisplayClass(FILE *fout, const char *name, int base, int start) const final
Definition TCling.cxx:7484
void GetFunctionName(const clang::Decl *decl, std::string &name) const
Definition TCling.cxx:8837
void CreateListOfMethodArgs(TFunction *m) const final
Create list of pointers to method arguments for TMethod m.
Definition TCling.cxx:4587
const char * GetSTLIncludePath() const final
Return the directory containing CINT's stl cintdlls.
Definition TCling.cxx:7475
MethodArgInfo_t * MethodArgInfo_FactoryCopy(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9344
Longptr_t BaseClassInfo_Offset(BaseClassInfo_t *toBaseClassInfo, void *address, bool isDerivedObject) const final
Definition TCling.cxx:8584
ECheckClassInfo CheckClassInfo(const char *name, Bool_t autoload, Bool_t isClassOrNamespaceOnly=kFALSE) final
Checks if an entity with the specified name is defined in Cling.
Definition TCling.cxx:4236
void * FindSym(const char *entry) const final
Interface to cling function.
Definition TCling.cxx:7522
void RegisterLoadedSharedLibrary(const char *name)
Register a new shared library name with the interpreter; add it to fSharedLibs.
Definition TCling.cxx:3474
void TypeInfo_Delete(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9421
int MethodInfo_NArg(MethodInfo_t *minfo) const final
Definition TCling.cxx:9147
DeclId_t GetDataMemberWithValue(const void *ptrvalue) const final
NOT IMPLEMENTED.
Definition TCling.cxx:5005
std::unordered_set< const clang::NamespaceDecl * > fNSFromRootmaps
Definition TCling.h:125
EReturnType MethodCallReturnType(TFunction *func) const final
Definition TCling.cxx:9257
void ProcessClassesToUpdate()
Definition TCling.cxx:2036
DeclId_t GetFunctionWithValues(ClassInfo_t *cl, const char *method, const char *params, Bool_t objectIsConst=kFALSE) final
Return pointer to cling DeclId for a method of a class with a certain prototype, i....
Definition TCling.cxx:5197
TString GetMangledName(TClass *cl, const char *method, const char *params, Bool_t objectIsConst=kFALSE) final
Return the cling mangled name for a method of a class with parameters params (params is a string of a...
Definition TCling.cxx:5026
const char * MethodInfo_Title(MethodInfo_t *minfo) const final
Definition TCling.cxx:9248
TString fRootmapLoadPath
Definition TCling.h:116
const char * BaseClassInfo_TmpltName(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8647
Bool_t Declare(const char *code) final
Declare code to the interpreter, without any of the interpreter actions that could trigger a re-inter...
Definition TCling.cxx:3157
const char * BaseClassInfo_FullName(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8629
void CallFunc_SetArgs(CallFunc_t *func, const char *param) const final
Definition TCling.cxx:8106
int UnloadFile(const char *path) const final
Definition TCling.cxx:7722
void SetClassInfo(TClass *cl, Bool_t reload=kFALSE, Bool_t silent=kFALSE) final
Set pointer to the TClingClassInfo in TClass.
Definition TCling.cxx:4100
void CallFunc_Exec(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7926
Long_t FuncTempInfo_ExtraProperty(FuncTempInfo_t *) const final
Return the property not already defined in Property See TDictionary's EFunctionProperty.
Definition TCling.cxx:9011
bool CallFunc_IsValid(CallFunc_t *func) const final
Definition TCling.cxx:8025
const char * BaseClassInfo_Name(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8639
ROOT::TMetaUtils::TClingLookupHelper * fLookupHelper
Definition TCling.h:135
const char * DataMemberInfo_ValidArrayIndex(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8790
Int_t GetMore() const final
Return whether we are waiting for more input either because the collected input contains unbalanced b...
Definition TCling.cxx:4608
Bool_t fIsAutoParsingSuspended
Definition TCling.h:182
std::string ToString(const char *type, void *obj) final
Definition TCling.cxx:1057
DeclId_t GetDeclId(const llvm::GlobalValue *gv) const
Return pointer to cling DeclId for a global value.
Definition TCling.cxx:4936
void Execute(const char *function, const char *params, int *error=nullptr) final
Execute a global function with arguments params.
Definition TCling.cxx:5297
bool ClassInfo_IsLoaded(ClassInfo_t *info) const final
Definition TCling.cxx:8396
Longptr_t ClassInfo_Tagnum(ClassInfo_t *info) const final
Definition TCling.cxx:8484
Long_t BaseClassInfo_Property(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8605
void CallFunc_SetFunc(CallFunc_t *func, ClassInfo_t *info, const char *method, const char *params, Longptr_t *Offset) const final
Definition TCling.cxx:8114
std::vector< std::string > GetUsingNamespaces(ClassInfo_t *cl) const final
Get the scopes representing using declarations of namespace.
Definition TCling.cxx:4542
const char * ClassInfo_FileName(ClassInfo_t *info) const final
Definition TCling.cxx:8492
void FuncTempInfo_Title(FuncTempInfo_t *, TString &name) const final
Return the comments associates with this function template.
Definition TCling.cxx:9050
const char * ClassInfo_TmpltName(ClassInfo_t *info) const final
Definition TCling.cxx:8526
void SaveContext() final
Save the current Cling state.
Definition TCling.cxx:3918
void LoadPCMImpl(TFile &pcmFile)
Tries to load a PCM from TFile; returns true on success.
Definition TCling.cxx:1751
Bool_t IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *nsDecl)
Definition TCling.cxx:6690
void ResetGlobals() final
Reset in Cling the list of global variables to the state saved by the last call to TCling::SaveGlobal...
Definition TCling.cxx:3799
void CodeComplete(const std::string &, size_t &, std::vector< std::string > &) final
The call to Cling's tab complition.
Definition TCling.cxx:7744
void ResetGlobalVar(void *obj) final
Reset the Cling 'user' global objects/variables state to the state saved by the last call to TCling::...
Definition TCling.cxx:3813
const char * MapCppName(const char *) const final
Interface to cling function.
Definition TCling.cxx:7597
Longptr_t Calc(const char *line, EErrorCode *error=nullptr) final
Directly execute an executable statement (e.g.
Definition TCling.cxx:3644
Int_t ReloadAllSharedLibraryMaps() final
Reload the library map entries coming from all the loaded shared libraries, after first unloading the...
Definition TCling.cxx:6001
void UpdateListOfGlobalFunctions() final
No op: see TClingCallbacks (used to update the list of global functions)
Definition TCling.cxx:3951
void DataMemberInfo_Delete(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8668
char fPrompt[64]
Definition TCling.h:110
const char * GetTopLevelMacroName() const final
Return the file name of the current un-included interpreted file.
Definition TCling.cxx:5480
void * fPrevLoadedDynLibInfo
Definition TCling.h:137
void UpdateListOfDataMembers(TClass *cl) const
Update the list of pointers to data members for TClass cl This is now a nop.
Definition TCling.cxx:4580
void InspectMembers(TMemberInspector &, const void *obj, const TClass *cl, Bool_t isTransient) final
Visit all members over members, recursing over base classes.
Definition TCling.cxx:2741
Int_t SetClassSharedLibs(const char *cls, const char *libs) final
Register the AutoLoading information for a class.
Definition TCling.cxx:6142
MethodInfo_t * MethodInfo_FactoryCopy(MethodInfo_t *minfo) const final
Definition TCling.cxx:9123
std::set< const char * > fParsedPayloadsAddresses
Definition TCling.h:123
CallFuncIFacePtr_t CallFunc_IFacePtr(CallFunc_t *func) const final
Definition TCling.cxx:8034
MethodArgInfo_t * MethodArgInfo_Factory() const final
Definition TCling.cxx:9328
static void UpdateClassInfo(char *name, Long_t tagnum)
No op: see TClingCallbacks.
Definition TCling.cxx:6814
DeclId_t GetFunction(ClassInfo_t *cl, const char *funcname) final
Return pointer to cling interface function for a method of a class with a certain name.
Definition TCling.cxx:5093
void ClassInfo_Delete(ClassInfo_t *info) const final
Definition TCling.cxx:8260
std::unique_ptr< cling::Interpreter > fInterpreter
Definition TCling.h:130
EDataType ClassInfo_GetUnderlyingType(ClassInfo_t *info) const final
Definition TCling.cxx:8387
void FuncTempInfo_Delete(FuncTempInfo_t *) const final
Delete the FuncTempInfo_t.
Definition TCling.cxx:8882
bool IsUnsignedIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9643
DeclId_t GetFunctionTemplate(ClassInfo_t *cl, const char *funcname) final
Return pointer to cling interface function for a method of a class with a certain name.
Definition TCling.cxx:5241
Int_t DeleteVariable(const char *name) final
Undeclare obj called name.
Definition TCling.cxx:3857
const char * GetClassSharedLibs(const char *cls, bool skipCore=true) final
Get the list of shared libraries containing the code for class cls.
Definition TCling.cxx:7169
Longptr_t DataMemberInfo_Offset(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8726
CallFunc_t * CallFunc_Factory() const final
Definition TCling.cxx:7985
MethodInfo_t * MethodInfo_Factory() const final
Definition TCling.cxx:9098
Long_t DataMemberInfo_TypeProperty(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8742
void ClearFileBusy() final
Reset the interpreter internal state in case a previous action was not correctly terminated.
Definition TCling.cxx:3136
cling::MetaProcessor * GetMetaProcessorImpl() const
Definition TCling.h:644
bool DiagnoseIfInterpreterException(const std::exception &e) const final
Definition TCling.cxx:2499
void SetAllocunlockfunc(void(*)()) const final
[Place holder for Mutex Unlock] Provide the interpreter with a way to release a lock used to protect ...
Definition TCling.cxx:7620
std::set< size_t > fLookedUpClasses
Definition TCling.h:121
bool IsValid() const final
Check if constructor exited correctly, ie the instance is in a valid state.
Definition TCling.cxx:3127
void AddAvailableIndentifiers(TSeqCollection &Idents) final
Definition TCling.cxx:2415
void TypedefInfo_Delete(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9522
void Reset() final
Pressing Ctrl+C should forward here.
Definition TCling.cxx:3767
const char * TypedefInfo_TrueName(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9594
int SetClassAutoLoading(int) const final
Enable/Disable the AutoLoading of libraries.
Definition TCling.cxx:7641
const char * ClassInfo_FullName(ClassInfo_t *info) const final
Definition TCling.cxx:8500
UInt_t AutoParseImplRecurse(const char *cls, bool topLevel)
Helper routine for TCling::AutoParse implementing the actual call to the parser and looping over temp...
Definition TCling.cxx:6445
const char * MethodInfo_TypeName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9227
void CallFunc_SetArg(CallFunc_t *func, Long_t param) const final
Definition TCling.cxx:8050
const char * GetIncludePath() final
Refresh the list of include paths known to the interpreter and return it with -I prepended.
Definition TCling.cxx:7444
void UpdateListsOnUnloaded(const cling::Transaction &T)
Invalidate stored TCling state for declarations included in transaction ‘T’.
Definition TCling.cxx:6924
void UpdateClassInfoWithDecl(const clang::NamedDecl *ND)
Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
Definition TCling.cxx:6756
void Initialize() final
Initialize the interpreter, once TROOT::fInterpreter is set.
Definition TCling.cxx:1688
int ClassInfo_GetMethodNArg(ClassInfo_t *info, const char *method, const char *proto, Bool_t objectIsConst=false, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch) const final
Definition TCling.cxx:8321
DeclId_t GetDataMember(ClassInfo_t *cl, const char *name) const final
Return pointer to cling Decl of global/static variable that is located at the address given by addr.
Definition TCling.cxx:4835
void * fAutoLoadCallBack
Definition TCling.h:147
void FuncTempInfo_Name(FuncTempInfo_t *, TString &name) const final
Return the name of this function template.
Definition TCling.cxx:9037
std::unique_ptr< cling::MetaProcessor > fMetaProcessor
Definition TCling.h:131
bool TypeInfo_IsValid(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9460
bool RegisterPrebuiltModulePath(const std::string &FullPath, const std::string &ModuleMapName="module.modulemap") const final
Definition TCling.cxx:1962
std::string MethodInfo_TypeNormalizedName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9236
const char * ClassInfo_Name(ClassInfo_t *info) const final
Definition TCling.cxx:8510
TClass * GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent=kFALSE) final
Generate a TClass for the given class.
Definition TCling.cxx:4618
ULong64_t fTransactionCount
Definition TCling.h:148
bool ClassInfo_HasDefaultConstructor(ClassInfo_t *info, Bool_t testio=kFALSE) const final
Definition TCling.cxx:8329
void EndOfLineAction() final
It calls a "fantom" method to synchronize user keyboard input and ROOT prompt line.
Definition TCling.cxx:3180
TypeInfo_t * TypeInfo_FactoryCopy(TypeInfo_t *) const final
Definition TCling.cxx:9444
bool ClassInfo_HasMethod(ClassInfo_t *info, const char *name) const final
Definition TCling.cxx:8337
void ClassInfo_DeleteArray(ClassInfo_t *info, void *arena, bool dtorOnly) const final
Definition TCling.cxx:8275
std::map< size_t, std::vector< const char * > > fClassesHeadersMap
Definition TCling.h:119
const char * DataMemberInfo_TypeTrueName(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8766
void ShutDown() final
Definition TCling.cxx:1709
void UpdateListOfTypes() final
No op: see TClingCallbacks (used to update the list of types)
Definition TCling.cxx:3958
void * TypeInfo_QualTypePtr(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9508
Long_t TypedefInfo_Property(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9578
void RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
Register Rdict data for future loading by LoadPCM;.
Definition TCling.cxx:1732
Longptr_t ProcessLineSynch(const char *line, EErrorCode *error=nullptr) final
Let cling process a command line synchronously, i.e we are waiting it will be finished.
Definition TCling.cxx:3628
TString GetMangledNameWithPrototype(TClass *cl, const char *method, const char *proto, Bool_t objectIsConst=kFALSE, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch) final
Return the cling mangled name for a method of a class with a certain prototype, i....
Definition TCling.cxx:5053
static void UpdateAllCanvases()
Update all canvases at end the terminal input command.
Definition TCling.cxx:6829
Int_t LoadLibraryMap(const char *rootmapfile=nullptr) final
Load map between class and library.
Definition TCling.cxx:5805
Longptr_t BaseClassInfo_Tagnum(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8621
void LibraryUnloaded(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:7055
bool IsPointerType(const void *QualTypePtr) const final
Definition TCling.cxx:9659
Collection abstract base class.
Definition TCollection.h:65
virtual Int_t GetEntries() const
virtual void SetOwner(Bool_t enable=kTRUE)
Set whether this collection is the owner (enable==true) of its content.
All ROOT classes may have RTTI (run time type identification) support added.
Definition TDataMember.h:31
Basic data type descriptor (datatype information is obtained from CINT).
Definition TDataType.h:44
EMemberSelection
Kinds of members to include in lists.
const void * DeclId_t
TDirectory::TContext keeps track and restore the current directory.
Definition TDirectory.h:89
The TEnumConstant class implements the constants of the enum type.
The TEnum class implements the enum type.
Definition TEnum.h:33
static TEnum * GetEnum(const std::type_info &ti, ESearchAction sa=kALoadAndInterpLookup)
Definition TEnum.cxx:181
@ kNone
Definition TEnum.h:49
@ kAutoload
Definition TEnum.h:50
Definition TEnv.h:86
The TEnv class reads config files, by default named .rootrc.
Definition TEnv.h:124
THashList * GetTable() const
Definition TEnv.h:140
Bool_t IgnoreDuplicates(Bool_t ignore)
If set to true, no warnings in case of duplicates are issued.
Definition TEnv.cxx:801
virtual void SetRcName(const char *name)
Definition TEnv.h:145
virtual Int_t ReadFile(const char *fname, EEnvLevel level)
Read and parse the resource file for a certain level.
Definition TEnv.cxx:604
virtual void SetValue(const char *name, const char *value, EEnvLevel level=kEnvChange, const char *type=nullptr)
Set the value of a resource or create a new resource.
Definition TEnv.cxx:744
virtual TEnvRec * Lookup(const char *n) const
Loop over all resource records and return the one with name.
Definition TEnv.cxx:559
A ROOT file is an on-disk file, usually with extension .root, that stores objects in a file-system-li...
Definition TFile.h:131
Global functions class (global functions are obtained from CINT).
Definition TFunction.h:30
Global variables class (global variables are obtained from CINT).
Definition TGlobal.h:28
THashList implements a hybrid collection class consisting of a hash table and a list to store TObject...
Definition THashList.h:34
TObject * Remove(TObject *obj) override
Remove object from the list.
THashTable implements a hash table to store TObject's.
Definition THashTable.h:35
This class defines an abstract interface to a generic command line interpreter.
virtual bool RegisterPrebuiltModulePath(const std::string &FullPath, const std::string &ModuleMapName="module.modulemap") const =0
virtual Bool_t HasPCMForLibrary(const char *libname) const =0
virtual Int_t AutoParse(const char *cls)=0
int(* AutoLoadCallBack_t)(const char *)
virtual Bool_t Declare(const char *code)=0
virtual const char * GetClassSharedLibs(const char *cls, bool skipCore=true)=0
std::vector< std::pair< std::string, int > > FwdDeclArgsToKeepCollection_t
TDictionary::DeclId_t DeclId_t
virtual TObjArray * GetRootMapFiles() const =0
Book space in a file, create I/O buffers, to fill them, (un)compress them.
Definition TKey.h:28
A collection of TDataMember objects designed for fast access given a DeclId_t and for keep track of T...
A collection of TEnum objects designed for fast access given a DeclId_t and for keep track of TEnum t...
A collection of TEnum objects designed for fast access given a DeclId_t and for keep track of TEnum t...
A collection of TFunction objects designed for fast access given a DeclId_t and for keep track of TFu...
A collection of TFunction objects designed for fast access given a DeclId_t and for keep track of TFu...
A doubly linked list.
Definition TList.h:38
TObject * At(Int_t idx) const override
Returns the object at position idx. Returns 0 if idx is out of range.
Definition TList.cxx:487
A TMemFile is like a normal TFile except that it reads and writes only from memory.
Definition TMemFile.h:27
Abstract base class for accessing the data-members of a class.
Each ROOT method (see TMethod) has a linked list of its arguments.
Definition TMethodArg.h:36
const char * GetFullTypeName() const
Get full type description of method argument, e.g.: "class TDirectory*".
const char * GetDefault() const
Get default value of method argument.
Each ROOT class (see TClass) has a linked list of methods.
Definition TMethod.h:38
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
TNamed()
Definition TNamed.h:38
An array of TObjects.
Definition TObjArray.h:31
virtual void Expand(Int_t newSize)
Expand or shrink the array to newSize elements.
virtual void Compress()
Remove empty slots from array.
Int_t GetEntries() const override
Return the number of objects in array (i.e.
TObject * Remove(TObject *obj) override
Remove object from array.
TObject * FindObject(const char *name) const override
Find an object in this collection using its name.
void Add(TObject *obj) override
Definition TObjArray.h:68
Collectable string class.
Definition TObjString.h:28
Mother of all ROOT objects.
Definition TObject.h:41
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition TObject.h:202
R__ALWAYS_INLINE Bool_t IsOnHeap() const
Definition TObject.h:158
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:1074
virtual TObject * FindObject(const char *name) const
Must be redefined in derived classes.
Definition TObject.cxx:421
static TClass * Class()
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1088
virtual void Fatal(const char *method, const char *msgfmt,...) const
Issue fatal error message.
Definition TObject.cxx:1116
virtual TClass * IsA() const
Definition TObject.h:246
void MakeZombie()
Definition TObject.h:53
@ kInvalidObject
if object ctor succeeded but object should not be used
Definition TObject.h:78
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition TObject.cxx:1062
Persistent version of a TClass.
Definition TProtoClass.h:38
static const TString & GetIncludeDir()
Get the include directory in the installation. Static utility function.
Definition TROOT.cxx:3100
static const char * GetMacroPath()
Get macro search path. Static utility function.
Definition TROOT.cxx:2766
static const std::vector< std::string > & AddExtraInterpreterArgs(const std::vector< std::string > &args)
Provide command line arguments to the interpreter construction.
Definition TROOT.cxx:2962
static const TString & GetEtcDir()
Get the sysconfig directory in the installation. Static utility function.
Definition TROOT.cxx:3110
static const char **& GetExtraInterpreterArgs()
INTERNAL function! Used by rootcling to inject interpreter arguments through a C-interface layer.
Definition TROOT.cxx:2972
static const TString & GetSharedLibDir()
Get the shared libraries directory in the installation. Static utility function.
Definition TROOT.cxx:3089
Sequenceable collection abstract base class.
Int_t LastIndex() const
Describes a persistent version of a class.
Basic string class.
Definition TString.h:138
Ssiz_t Length() const
Definition TString.h:425
const char * Data() const
Definition TString.h:384
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:713
Bool_t IsNull() const
Definition TString.h:422
TString & Append(const char *cs)
Definition TString.h:581
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition TString.cxx:2384
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:641
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition TSystem.cxx:1285
virtual void FreeDirectory(void *dirp)
Free a directory.
Definition TSystem.cxx:855
virtual void * OpenDirectory(const char *name)
Open a directory.
Definition TSystem.cxx:846
virtual const char * Getenv(const char *env)
Get environment variable.
Definition TSystem.cxx:1676
virtual const char * GetIncludePath()
Get the list of include path.
Definition TSystem.cxx:4003
virtual TString SplitAclicMode(const char *filename, TString &mode, TString &args, TString &io) const
This method split a filename of the form:
Definition TSystem.cxx:4288
virtual const char * FindFile(const char *search, TString &file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition TSystem.cxx:1549
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition TSystem.cxx:1868
int GetPathInfo(const char *path, Long_t *id, Long_t *size, Long_t *flags, Long_t *modtime)
Get info about a file: id, size, flags, modification time.
Definition TSystem.cxx:1409
virtual const char * PrependPathName(const char *dir, TString &name)
Concatenate a directory and a file name.
Definition TSystem.cxx:1092
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
Definition TSystem.cxx:1307
virtual const char * GetDirEntry(void *dirp)
Get a directory entry. Returns 0 if no more entries.
Definition TSystem.cxx:863
virtual int GetProcInfo(ProcInfo_t *info) const
Returns cpu and memory used by this process into the ProcInfo_t structure.
Definition TSystem.cxx:2500
virtual const char * BaseName(const char *pathname)
Base name of a file name. Base name of /user/root is root.
Definition TSystem.cxx:944
virtual const char * GetDynamicPath()
Return the dynamic path (used to find shared libraries).
Definition TSystem.cxx:1806
virtual const char * FindDynamicLibrary(TString &lib, Bool_t quiet=kFALSE)
Find a dynamic library using the system search paths.
Definition TSystem.cxx:2045
virtual void Sleep(UInt_t milliSec)
Sleep milliSec milli seconds.
Definition TSystem.cxx:435
virtual int CompileMacro(const char *filename, Option_t *opt="", const char *library_name="", const char *build_dir="", UInt_t dirmode=0)
This method compiles and loads a shared library containing the code from the file "filename".
Definition TSystem.cxx:2847
virtual const char * WorkingDirectory()
Return working directory.
Definition TSystem.cxx:881
virtual char * Which(const char *search, const char *file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition TSystem.cxx:1559
virtual void Setenv(const char *name, const char *value)
Set environment variable.
Definition TSystem.cxx:1660
virtual const char * HomeDirectory(const char *userName=nullptr)
Return the user's home directory.
Definition TSystem.cxx:897
virtual TString GetDirName(const char *pathname)
Return the directory name in pathname.
Definition TSystem.cxx:1042
virtual void StackTrace()
Print a stack trace.
Definition TSystem.cxx:743
char * DynamicPathName(const char *lib, Bool_t quiet=kFALSE)
Find a dynamic library called lib using the system search paths.
Definition TSystem.cxx:2031
virtual Int_t UnLock()=0
virtual Int_t Lock()=0
virtual TVirtualMutex * Factory(Bool_t=kFALSE)=0
TVirtualPad is an abstract base class for the Pad and Canvas classes.
Definition TVirtualPad.h:51
virtual void Update()=0
static void SetFactory(TVirtualStreamerInfo *factory)
static function: Set the StreamerInfo factory
TLine * line
const Int_t n
Definition legend1.C:16
Double_t ex[n]
Definition legend1.C:17
TF1 * f1
Definition legend1.C:11
#define I(x, y, z)
const std::string & GetPathSeparator()
const char & GetEnvPathSeparator()
const T * GetAnnotatedRedeclarable(const T *Redecl)
int GetClassVersion(const clang::RecordDecl *cl, const cling::Interpreter &interp)
Return the version number of the class or -1 if the function Class_Version does not exist.
void GetNormalizedName(std::string &norm_name, const clang::QualType &type, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt)
Return the type name normalized for ROOT, keeping only the ROOT opaque typedef (Double32_t,...
std::string GetModuleFileName(const char *moduleName)
Return the dictionary file name for a module.
clang::QualType ReSubstTemplateArg(clang::QualType input, const clang::Type *instance)
Check if 'input' or any of its template parameter was substituted when instantiating the class templa...
static std::string DemangleNameForDlsym(const std::string &name)
void GetCppName(std::string &output, const char *input)
Return (in the argument 'output') a valid name of the C++ symbol/type (pass as 'input') that can be u...
std::pair< bool, int > GetTrivialIntegralReturnValue(const clang::FunctionDecl *funcCV, const cling::Interpreter &interp)
If the function contains 'just': return SomeValue; this routine will extract this value and return it...
std::string GetRealPath(const std::string &path)
void GetQualifiedName(std::string &qual_name, const clang::QualType &type, const clang::NamedDecl &forcontext)
Main implementation relying on GetFullyQualifiedTypeName All other GetQualifiedName functions leverag...
llvm::StringRef GetComment(const clang::Decl &decl, clang::SourceLocation *loc=nullptr)
Returns the comment (// striped away), annotating declaration in a meaningful for ROOT IO way.
void SetPathsForRelocatability(std::vector< std::string > &clingArgs)
Organise the parameters for cling in order to guarantee relocatability It treats the gcc toolchain an...
const clang::Type * GetUnderlyingType(clang::QualType type)
Return the base/underlying type of a chain of array or pointers type.
ROOT::ESTLType IsSTLCont(const clang::RecordDecl &cl)
type : type name: vector<list<classA,allocator>,allocator> result: 0 : not stl container abs(result):...
bool ExtractAttrPropertyFromName(const clang::Decl &decl, const std::string &propName, std::string &propValue)
This routine counts on the "propName<separator>propValue" format.
R__EXTERN TVirtualRWMutex * gCoreMutex
@ kWarning
Warnings about likely unexpected behavior.
EFunctionMatchMode
@ kExactMatch
bool IsStdPairBase(std::string_view name)
Definition TClassEdit.h:235
bool IsStdArray(std::string_view name)
Definition TClassEdit.h:230
bool IsStdClass(const char *type)
return true if the class belongs to the std namespace
bool IsStdPair(std::string_view name)
Definition TClassEdit.h:231
std::string InsertStd(const char *tname)
std::string GetLong64_Name(const char *original)
Replace 'long long' and 'unsigned long long' by 'Long64_t' and 'ULong64_t'.
char * DemangleTypeIdName(const std::type_info &ti, int &errorCode)
Demangle in a portable way the type id name.
const char * GetUnqualifiedName(const char *name)
Return the start of the unqualified name include in 'original'.
void Init(TClassEdit::TInterpreterLookupHelper *helper)
ROOT::ESTLType IsSTLCont(std::string_view type)
type : type name: vector<list<classA,allocator>,allocator> result: 0 : not stl container code of cont...
char * DemangleName(const char *mangled_name, int &errorCode)
Definition TClassEdit.h:255
int GetSplit(const char *type, std::vector< std::string > &output, int &nestedLoc, EModType mode=TClassEdit::kNone)
Stores in output (after emptying it) the split type.
@ kDropStlDefault
Definition TClassEdit.h:83
EComplexType GetComplexType(const char *)
static const char * what
Definition stlLoader.cc:5
Int_t fMode
Definition TSystem.h:135
RAII used to store Parser, Sema, Preprocessor state for recursive parsing.
Definition ClingRAII.h:22
std::unique_ptr< ROOT::TVirtualRWMutex::State > fState
State of gCoreMutex when the first interpreter-related function was invoked.
Definition TCling.h:157
Int_t fRecurseCount
Interpreter-related functions will push the "entry" lock state to *this.
Definition TCling.h:162
A read-only memory range which we do not control.
Definition TMemFile.h:33
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4
static void output()