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 transfered 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 transfered 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 if (TClassEdit::IsUniquePtr(cl->GetName())) {
2768 // Ignore error caused by the inside of std::unique_ptr
2769 // This is needed solely because of rootclingIO's IsUnsupportedUniquePointer
2770 // which checks the number of elements in the GetListOfRealData.
2771 // If this usage is removed, this can be replaced with a return statement.
2772 // See https://github.com/root-project/root/issues/13574
2773 isTransient = true;
2774 }
2775
2776 const char* cobj = (const char*) obj; // for ptr arithmetics
2777
2778 // Treat the case of std::complex in a special manner. We want to enforce
2779 // the layout of a stl implementation independent class, which is the
2780 // complex as implemented in ROOT5.
2781
2782 // A simple lambda to simplify the code
2783 auto inspInspect = [&] (ptrdiff_t offset){
2784 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_real", cobj, isTransient);
2785 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_imag", cobj + offset, isTransient);
2786 };
2787
2789 switch(complexType) {
2791 {
2792 break;
2793 }
2795 {
2796 inspInspect(sizeof(float));
2797 return;
2798 }
2800 {
2801 inspInspect(sizeof(double));
2802 return;
2803 }
2805 {
2806 inspInspect(sizeof(int));
2807 return;
2808 }
2810 {
2811 inspInspect(sizeof(long));
2812 return;
2813 }
2814 }
2815
2816 static clang::PrintingPolicy
2817 printPol(fInterpreter->getCI()->getLangOpts());
2818 if (printPol.Indentation) {
2819 // not yet initialized
2820 printPol.Indentation = 0;
2821 printPol.SuppressInitializers = true;
2822 }
2823
2824 const char* clname = cl->GetName();
2825 // Printf("Inspecting class %s\n", clname);
2826
2827 const clang::ASTContext& astContext = fInterpreter->getCI()->getASTContext();
2828 const clang::Decl *scopeDecl = nullptr;
2829 const clang::Type *recordType = nullptr;
2830
2831 if (cl->GetClassInfo()) {
2833 scopeDecl = clingCI->GetDecl();
2834 recordType = clingCI->GetType();
2835 } else {
2836 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
2837 // Diags will complain about private classes:
2838 scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2839 &recordType);
2840 }
2841 if (!scopeDecl) {
2842 Error("InspectMembers", "Cannot find Decl for class %s", clname);
2843 return;
2844 }
2845 const clang::CXXRecordDecl* recordDecl
2846 = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2847 if (!recordDecl) {
2848 Error("InspectMembers", "Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2849 return;
2850 }
2851
2852 {
2853 // Force possible deserializations first. We need to have no pending
2854 // Transaction when passing control flow to the inspector below (ROOT-7779).
2855 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2856
2857 astContext.getASTRecordLayout(recordDecl);
2858
2859 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2860 eField = recordDecl->field_end(); iField != eField; ++iField) {}
2861 }
2862
2863 const clang::ASTRecordLayout& recLayout
2864 = astContext.getASTRecordLayout(recordDecl);
2865
2866 // TVirtualCollectionProxy *proxy = cl->GetCollectionProxy();
2867 // if (proxy && ( proxy->GetProperties() & TVirtualCollectionProxy::kIsEmulated ) ) {
2868 // Error("InspectMembers","The TClass for %s has an emulated proxy but we are looking at a compiled version of the collection!\n",
2869 // cl->GetName());
2870 // }
2871 if (cl->Size() != recLayout.getSize().getQuantity()) {
2872 Error("InspectMembers","TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2873 cl->GetName(),cl->Size(),(Long64_t)recLayout.getSize().getQuantity());
2874 }
2875
2876 unsigned iNField = 0;
2877 // iterate over fields
2878 // FieldDecls are non-static, else it would be a VarDecl.
2879 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2880 eField = recordDecl->field_end(); iField != eField;
2881 ++iField, ++iNField) {
2882
2883
2884 clang::QualType memberQT = iField->getType();
2885 if (recordType) {
2886 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2888 }
2889 memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2890 if (memberQT.isNull()) {
2891 std::string memberName;
2892 llvm::raw_string_ostream stream(memberName);
2893 // Don't trigger fopen of the source file to count lines:
2894 printPol.AnonymousTagLocations = false;
2895 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2896 stream.flush();
2897 Error("InspectMembers",
2898 "Cannot retrieve QualType for member %s while inspecting class %s",
2899 memberName.c_str(), clname);
2900 continue; // skip member
2901 }
2902 const clang::Type* memType = memberQT.getTypePtr();
2903 if (!memType) {
2904 std::string memberName;
2905 llvm::raw_string_ostream stream(memberName);
2906 // Don't trigger fopen of the source file to count lines:
2907 printPol.AnonymousTagLocations = false;
2908 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2909 stream.flush();
2910 Error("InspectMembers",
2911 "Cannot retrieve Type for member %s while inspecting class %s",
2912 memberName.c_str(), clname);
2913 continue; // skip member
2914 }
2915
2916 const clang::Type* memNonPtrType = memType;
2917 Bool_t ispointer = false;
2918 if (memNonPtrType->isPointerType()) {
2919 ispointer = true;
2920 clang::QualType ptrQT
2921 = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2922 if (recordType) {
2923 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2925 }
2926 ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2927 if (ptrQT.isNull()) {
2928 std::string memberName;
2929 llvm::raw_string_ostream stream(memberName);
2930 // Don't trigger fopen of the source file to count lines:
2931 printPol.AnonymousTagLocations = false;
2932 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2933 stream.flush();
2934 Error("InspectMembers",
2935 "Cannot retrieve pointee Type for member %s while inspecting class %s",
2936 memberName.c_str(), clname);
2937 continue; // skip member
2938 }
2939 memNonPtrType = ptrQT.getTypePtr();
2940 }
2941
2942 // assemble array size(s): "[12][4][]"
2943 llvm::SmallString<8> arraySize;
2944 const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2945 unsigned arrLevel = 0;
2946 bool haveErrorDueToArray = false;
2947 while (arrType) {
2948 ++arrLevel;
2949 arraySize += '[';
2950 const clang::ConstantArrayType* constArrType =
2951 clang::dyn_cast<clang::ConstantArrayType>(arrType);
2952 if (constArrType) {
2953 constArrType->getSize().toStringUnsigned(arraySize);
2954 }
2955 arraySize += ']';
2956 clang::QualType subArrQT = arrType->getElementType();
2957 if (subArrQT.isNull()) {
2958 std::string memberName;
2959 llvm::raw_string_ostream stream(memberName);
2960 // Don't trigger fopen of the source file to count lines:
2961 printPol.AnonymousTagLocations = false;
2962 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2963 stream.flush();
2964 Error("InspectMembers",
2965 "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2966 arrLevel, subArrQT.getAsString(printPol).c_str(),
2967 memberName.c_str(), clname);
2968 haveErrorDueToArray = true;
2969 break;
2970 }
2971 arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2972 }
2973 if (haveErrorDueToArray) {
2974 continue; // skip member
2975 }
2976
2977 // construct member name
2978 std::string fieldName;
2979 if (memType->isPointerType()) {
2980 fieldName = "*";
2981 }
2982
2983 // Check if this field has a custom ioname, if not, just use the one of the decl
2984 std::string ioname(iField->getName());
2986 fieldName += ioname;
2987 fieldName += arraySize;
2988
2989 // get member offset
2990 // NOTE currently we do not support bitfield and do not support
2991 // member that are not aligned on 'bit' boundaries.
2992 clang::CharUnits offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2993 ptrdiff_t fieldOffset = offset.getQuantity();
2994
2995 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fBits[2]", fBits);
2996 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fName", &fName);
2997 // R__insp.InspectMember(fName, "fName.");
2998 // R__insp.Inspect(R__cl, R__insp.GetParent(), "*fClass", &fClass);
2999
3000 // If the class has a custom streamer and the type of the filed is a
3001 // private enum, struct or class, skip it.
3002 if (!insp.IsTreatingNonAccessibleTypes()){
3003 auto iFiledQtype = iField->getType();
3004 if (auto tagDecl = iFiledQtype->getAsTagDecl()){
3005 auto declAccess = tagDecl->getAccess();
3007 continue;
3008 }
3009 }
3010 }
3011
3012 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
3013
3014 if (!ispointer) {
3015 const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
3016 if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
3017 // nested objects get an extra call to InspectMember
3018 // R__insp.InspectMember("FileStat_t", (void*)&fFileStat, "fFileStat.", false);
3019 std::string sFieldRecName;
3022 clang::QualType(memNonPtrType,0),
3023 *fInterpreter,
3025 }
3026
3027 TDataMember* mbr = cl->GetDataMember(ioname.c_str());
3028 // if we can not find the member (which should not really happen),
3029 // let's consider it transient.
3030 Bool_t transient = isTransient || !mbr || !mbr->IsPersistent();
3031 if (!mbr || !mbr->IsPersistent())
3032 insp.IncrementNestedTransient();
3033 insp.InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
3034 (fieldName + '.').c_str(), transient);
3035 if (!mbr || !mbr->IsPersistent())
3036 insp.DecrementNestedTransient();
3037
3038 }
3039 }
3040 } // loop over fields
3041
3042 // inspect bases
3043 // TNamed::ShowMembers(R__insp);
3044 unsigned iNBase = 0;
3045 for (clang::CXXRecordDecl::base_class_const_iterator iBase
3046 = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
3047 iBase != eBase; ++iBase, ++iNBase) {
3048 clang::QualType baseQT = iBase->getType();
3049 if (baseQT.isNull()) {
3050 Error("InspectMembers",
3051 "Cannot find QualType for base number %d while inspecting class %s",
3052 iNBase, clname);
3053 continue;
3054 }
3055 const clang::CXXRecordDecl* baseDecl
3056 = baseQT->getAsCXXRecordDecl();
3057 if (!baseDecl) {
3058 Error("InspectMembers",
3059 "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
3060 iNBase, clname);
3061 continue;
3062 }
3063 TClass* baseCl=nullptr;
3064 std::string sBaseName;
3065 // Try with the DeclId
3066 std::vector<TClass*> foundClasses;
3068 if (foundClasses.size()==1){
3070 } else {
3071 // Try with the normalised Name, as a fallback
3072 if (!baseCl){
3074 baseQT,
3075 *fInterpreter,
3078 }
3079 }
3080
3081 if (!baseCl){
3082 std::string qualNameForDiag;
3084 Error("InspectMembers",
3085 "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
3086 continue;
3087 }
3088
3089 int64_t baseOffset;
3090 if (iBase->isVirtual()) {
3091 if (insp.GetObjectValidity() == TMemberInspector::kNoObjectGiven) {
3092 if (!isTransient) {
3093 Error("InspectMembers",
3094 "Base %s of class %s is virtual but no object provided",
3095 sBaseName.c_str(), clname);
3096 }
3098 } else {
3099 // We have an object to determine the vbase offset.
3101 TClingClassInfo* baseCi = (TClingClassInfo*)baseCl->GetClassInfo();
3102 if (ci && baseCi) {
3103 baseOffset = ci->GetBaseOffset(baseCi, const_cast<void*>(obj),
3104 true /*isDerivedObj*/);
3105 if (baseOffset == -1) {
3106 Error("InspectMembers",
3107 "Error calculating offset of virtual base %s of class %s",
3108 sBaseName.c_str(), clname);
3109 }
3110 } else {
3111 Error("InspectMembers",
3112 "Cannot calculate offset of virtual base %s of class %s",
3113 sBaseName.c_str(), clname);
3114 continue;
3115 }
3116 }
3117 } else {
3118 baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
3119 }
3120 // TOFIX: baseCl can be null here!
3121 if (baseCl->IsLoaded()) {
3122 // For loaded class, CallShowMember will (especially for TObject)
3123 // call the virtual ShowMember rather than the class specific version
3124 // resulting in an infinite recursion.
3126 } else {
3127 baseCl->CallShowMembers(cobj + baseOffset,
3128 insp, isTransient);
3129 }
3130 } // loop over bases
3131}
3132
3133////////////////////////////////////////////////////////////////////////////////
3134/// Check if constructor exited correctly, ie the instance is in a valid state
3135/// \return true if there is a compiler instance available, false otherwise
3137{
3138 return fInterpreter->getCI() != nullptr;
3139}
3140
3141////////////////////////////////////////////////////////////////////////////////
3142/// Reset the interpreter internal state in case a previous action was not correctly
3143/// terminated.
3144
3146{
3147 // No-op there is not equivalent state (to be cleared) in Cling.
3148}
3149
3150////////////////////////////////////////////////////////////////////////////////
3151/// Delete existing temporary values.
3152
3154{
3155 // No-op for cling due to cling::Value.
3156}
3157
3158////////////////////////////////////////////////////////////////////////////////
3159/// Declare code to the interpreter, without any of the interpreter actions
3160/// that could trigger a re-interpretation of the code. I.e. make cling
3161/// behave like a compiler: no dynamic lookup, no input wrapping for
3162/// subsequent execution, no automatic provision of declarations but just a
3163/// plain `#include`.
3164/// Returns true on success, false on failure.
3165
3166bool TCling::Declare(const char* code)
3167{
3169
3172
3173 bool oldDynLookup = fInterpreter->isDynamicLookupEnabled();
3174 fInterpreter->enableDynamicLookup(false);
3175 bool oldRawInput = fInterpreter->isRawInputEnabled();
3176 fInterpreter->enableRawInput(true);
3177
3178 Bool_t ret = LoadText(code);
3179
3180 fInterpreter->enableRawInput(oldRawInput);
3181 fInterpreter->enableDynamicLookup(oldDynLookup);
3182 return ret;
3183}
3184
3185////////////////////////////////////////////////////////////////////////////////
3186/// It calls a "fantom" method to synchronize user keyboard input
3187/// and ROOT prompt line.
3188
3193
3194// This static function is a hop of TCling::IsLibraryLoaded, which is taking a lock and calling
3195// into this function. This is because we wanted to avoid a duplication in TCling::IsLoaded, which
3196// was already taking a lock.
3197static Bool_t s_IsLibraryLoaded(const char* libname, cling::Interpreter* fInterpreter)
3198{
3199 // Check shared library.
3202 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.Data());
3203 return false;
3204}
3205
3211
3212////////////////////////////////////////////////////////////////////////////////
3213/// Return true if ROOT has cxxmodules pcm for a given library name.
3214// FIXME: We need to be able to support lazy loading of pcm generated by ACLiC.
3216{
3217 llvm::StringRef ModuleName(libname);
3218 ModuleName = llvm::sys::path::stem(ModuleName);
3219 ModuleName.consume_front("lib");
3220
3221 // FIXME: In case when the modulemap is not yet loaded we will return the
3222 // wrong result. Consider a call to HasPCMForLibrary(../test/libEvent.so)
3223 // We will only load the modulemap for libEvent.so after we dlopen libEvent
3224 // which may happen after calling this interface. Maybe we should also check
3225 // if there is a Event.pcm file and a module.modulemap, load it and return
3226 // true.
3227 clang::ModuleMap &moduleMap = fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
3228 clang::Module *M = moduleMap.findModule(ModuleName);
3229 return M && !M->IsUnimportable && M->getASTFile();
3230}
3231
3232////////////////////////////////////////////////////////////////////////////////
3233/// Return true if the file has already been loaded by cint.
3234/// We will try in this order:
3235/// actual filename
3236/// filename as a path relative to
3237/// the include path
3238/// the shared library path
3239
3241{
3243
3244 //FIXME: if we use llvm::sys::fs::make_absolute all this can go away. See
3245 // cling::DynamicLibraryManager.
3246
3247 std::string file_name = filename;
3248 size_t at = std::string::npos;
3249 while ((at = file_name.find("/./")) != std::string::npos)
3250 file_name.replace(at, 3, "/");
3251
3252 std::string filesStr = "";
3253 llvm::raw_string_ostream filesOS(filesStr);
3254 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3255 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3256 filesOS.flush();
3257
3258 llvm::SmallVector<llvm::StringRef, 100> files;
3259 llvm::StringRef(filesStr).split(files, "\n");
3260
3261 std::set<std::string> fileMap;
3262 llvm::StringRef file_name_ref(file_name);
3263 // Fill fileMap; return early on exact match.
3265 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3266 if ((*iF) == file_name_ref) return kTRUE; // exact match
3267 fileMap.insert(iF->str());
3268 }
3269
3270 if (fileMap.empty()) return kFALSE;
3271
3272 // Check MacroPath.
3273 TString sFilename(file_name.c_str());
3275 && fileMap.count(sFilename.Data())) {
3276 return kTRUE;
3277 }
3278
3279 // Check IncludePath.
3280 TString incPath = gSystem->GetIncludePath(); // of the form -Idir1 -Idir2 -Idir3
3281 incPath.Append(":").Prepend(" "); // to match " -I" (note leading ' ')
3282 incPath.ReplaceAll(" -I", ":"); // of form :dir1 :dir2:dir3
3283 while (incPath.Index(" :") != -1) {
3284 incPath.ReplaceAll(" :", ":");
3285 }
3286 incPath.Prepend(".:");
3287 sFilename = file_name.c_str();
3289 && fileMap.count(sFilename.Data())) {
3290 return kTRUE;
3291 }
3292
3293 // Check shared library.
3294 if (s_IsLibraryLoaded(file_name.c_str(), GetInterpreterImpl()))
3295 return kTRUE;
3296
3297 //FIXME: We must use the cling::Interpreter::lookupFileOrLibrary iface.
3298 clang::ConstSearchDirIterator *CurDir = nullptr;
3299 clang::Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
3300 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3301 auto FE = HS.LookupFile(file_name.c_str(),
3302 clang::SourceLocation(),
3303 /*isAngled*/ false,
3304 /*FromDir*/ nullptr, CurDir,
3305 clang::ArrayRef<std::pair<clang::OptionalFileEntryRef,
3306 clang::DirectoryEntryRef>>(),
3307 /*SearchPath*/ nullptr,
3308 /*RelativePath*/ nullptr,
3309 /*RequestingModule*/ nullptr,
3310 /*SuggestedModule*/ nullptr,
3311 /*IsMapped*/ nullptr,
3312 /*IsFrameworkFound*/ nullptr,
3313 /*SkipCache*/ false,
3314 /*BuildSystemModule*/ false,
3315 /*OpenFile*/ false,
3316 /*CacheFail*/ false);
3317 if (FE) {
3318 // check in the source manager if the file is actually loaded
3319 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3320 // this works only with header (and source) files...
3321 clang::FileID FID = SM.translateFile(*FE);
3322 if (!FID.isInvalid() && FID.getHashValue() == 0)
3323 return kFALSE;
3324 else {
3325 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3326 if (SLocE.isFile() && !SLocE.getFile().getContentCache().getBufferIfLoaded())
3327 return kFALSE;
3328 if (!FID.isInvalid())
3329 return kTRUE;
3330 }
3331 // ...then check shared library again, but with full path now
3332 sFilename = FE->getName().str();
3334 && fileMap.count(sFilename.Data())) {
3335 return kTRUE;
3336 }
3337 }
3338 return kFALSE;
3339}
3340
3341
3342#if defined(R__MACOSX)
3343
3344////////////////////////////////////////////////////////////////////////////////
3345/// Check if lib is in the dynamic linker cache, returns true if it is, and if so,
3346/// modifies the library file name parameter `lib` from `/usr/lib/libFOO.dylib`
3347/// to `-lFOO` such that it can be passed to the linker.
3348/// This is a unique feature of macOS 11.
3349
3350static bool R__UpdateLibFileForLinking(TString &lib)
3351{
3352 const char *mapfile = nullptr;
3353#if __x86_64__
3354 mapfile = "/System/Library/dyld/dyld_shared_cache_x86_64.map";
3355#elif __arm64__
3356 mapfile = "/System/Library/dyld/dyld_shared_cache_arm64e.map";
3357#else
3358 #error unsupported architecture
3359#endif
3360 if (std::ifstream cacheMap{mapfile}) {
3361 std::string line;
3362 while (getline(cacheMap, line)) {
3363 if (line.find(lib) != std::string::npos) {
3364 lib.ReplaceAll("/usr/lib/lib","-l");
3365 lib.ReplaceAll(".dylib","");
3366 return true;
3367 }
3368 }
3369 return false;
3370 }
3371 return false;
3372}
3373#endif // R__MACOSX
3374
3375#if defined (R__LINUX) || defined (R__FBSD)
3376
3377////////////////////////////////////////////////////////////////////////////////
3378/// Callback for dl_iterate_phdr(), see `man dl_iterate_phdr`.
3379/// Collects opened libraries.
3380
3381static int callback_for_dl_iterate_phdr(struct dl_phdr_info *info, size_t size, void *data)
3382{
3383 // This function is called through UpdateListOfLoadedSharedLibraries() which is locked.
3384 static std::unordered_set<decltype(info->dlpi_addr)> sKnownLoadedLibBaseAddrs;
3385
3386 auto newLibs = static_cast<std::vector<std::string>*>(data);
3387 if (!sKnownLoadedLibBaseAddrs.count(info->dlpi_addr)) {
3388 // Skip \0, "", and kernel pseudo-libs linux-vdso.so.1 or linux-gate.so.1
3389 if (info->dlpi_name && info->dlpi_name[0]
3390#if defined(R__FBSD)
3391 //skip the executable (with null addr)
3392 && info->dlpi_addr
3393 //has no path
3394 && strncmp(info->dlpi_name, "[vdso]", 6)
3395 //the linker does not like to be mmapped
3396 //causes a crash in cling::DynamicLibraryManager::loadLibrary())
3397 //with error message "mmap of entire address space failed: Cannot allocate memory"
3398 && strncmp(info->dlpi_name, "/libexec/ld-elf.so.1", 20)
3399#endif
3400 && strncmp(info->dlpi_name, "linux-vdso.so", 13)
3401 && strncmp(info->dlpi_name, "linux-vdso32.so", 15)
3402 && strncmp(info->dlpi_name, "linux-vdso64.so", 15)
3403 && strncmp(info->dlpi_name, "linux-gate.so", 13))
3404 newLibs->emplace_back(info->dlpi_name);
3405 sKnownLoadedLibBaseAddrs.insert(info->dlpi_addr);
3406 }
3407 // No matter what the doc says, return != 0 means "stop the iteration".
3408 return 0;
3409}
3410
3411#endif // R__LINUX || R__FBSD
3412
3413
3414////////////////////////////////////////////////////////////////////////////////
3415
3417{
3418#if defined(R__WIN32) || defined(__CYGWIN__)
3419 HMODULE hModules[1024];
3420 void *hProcess;
3421 unsigned long cbModules;
3422 unsigned int i;
3423 hProcess = (void *)::GetCurrentProcess();
3425 // start at 1 to skip the executable itself
3426 for (i = 1; i < (cbModules / sizeof(void *)); i++) {
3427 static const int bufsize = 260;
3428 wchar_t winname[bufsize];
3429 char posixname[bufsize];
3431#if defined(__CYGWIN__)
3433#else
3434 std::wstring wpath = winname;
3435 std::replace(wpath.begin(), wpath.end(), '\\', '/');
3436 string path(wpath.begin(), wpath.end());
3437 strncpy(posixname, path.c_str(), bufsize);
3438#endif
3441 }
3442 }
3443#elif defined(R__MACOSX)
3444 // fPrevLoadedDynLibInfo stores the *next* image index to look at
3445 uint32_t imageIndex = (uint32_t) (size_t) fPrevLoadedDynLibInfo;
3446
3448 // Skip non-dylibs
3449 if (mh->filetype == MH_DYLIB) {
3450 if (const char* imageName = _dyld_get_image_name(imageIndex)) {
3452 }
3453 }
3454
3455 ++imageIndex;
3456 }
3457 fPrevLoadedDynLibInfo = (void*)(size_t)imageIndex;
3458#elif defined(R__LINUX) || defined(R__FBSD)
3459 // fPrevLoadedDynLibInfo is unused on Linux.
3460 (void) fPrevLoadedDynLibInfo;
3461
3462 std::vector<std::string> newLibs;
3464 for (auto &&lib: newLibs)
3465 RegisterLoadedSharedLibrary(lib.c_str());
3466#else
3467 Error("TCling::UpdateListOfLoadedSharedLibraries",
3468 "Platform not supported!");
3469#endif
3470}
3471
3472namespace {
3473template <int N>
3474static bool StartsWithStrLit(const char *haystack, const char (&needle)[N]) {
3475 return !strncmp(haystack, needle, N - 1);
3476}
3477}
3478
3479////////////////////////////////////////////////////////////////////////////////
3480/// Register a new shared library name with the interpreter; add it to
3481/// fSharedLibs.
3482
3484{
3485 // Ignore NULL filenames, aka "the process".
3486 if (!filename) return;
3487
3488 // Tell the interpreter that this library is available; all libraries can be
3489 // used to resolve symbols.
3490 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3491 if (!DLM->isLibraryLoaded(filename)) {
3492 DLM->loadLibrary(filename, true /*permanent*/, true /*resolved*/);
3493 }
3494
3495#if defined(R__MACOSX)
3496 // Check that this is not a system library that does not exist on disk.
3497 auto lenFilename = strlen(filename);
3498 auto isInMacOSSystemDir = [](const char *fn) {
3499 return StartsWithStrLit(fn, "/usr/lib/") || StartsWithStrLit(fn, "/System/Library/");
3500 };
3501 if (!strcmp(filename, "cl_kernels") // yepp, no directory
3502
3503 // These we should not link with (e.g. because they forward to .tbd):
3504 || StartsWithStrLit(filename, "/usr/lib/system/")
3505 || StartsWithStrLit(filename, "/usr/lib/libc++")
3506 || StartsWithStrLit(filename, "/System/Library/Frameworks/")
3507 || StartsWithStrLit(filename, "/System/Library/PrivateFrameworks/")
3508 || StartsWithStrLit(filename, "/System/Library/CoreServices/")
3509 || StartsWithStrLit(filename, "/usr/lib/libSystem")
3510 || StartsWithStrLit(filename, "/usr/lib/libstdc++")
3511 || StartsWithStrLit(filename, "/usr/lib/libicucore")
3512 || StartsWithStrLit(filename, "/usr/lib/libbsm")
3513 || StartsWithStrLit(filename, "/usr/lib/libobjc")
3514 || StartsWithStrLit(filename, "/usr/lib/libresolv")
3515 || StartsWithStrLit(filename, "/usr/lib/libauto")
3516 || StartsWithStrLit(filename, "/usr/lib/libcups")
3517 || StartsWithStrLit(filename, "/usr/lib/libDiagnosticMessagesClient")
3518 || StartsWithStrLit(filename, "/usr/lib/liblangid")
3519 || StartsWithStrLit(filename, "/usr/lib/libCRFSuite")
3520 || StartsWithStrLit(filename, "/usr/lib/libpam")
3521 || StartsWithStrLit(filename, "/usr/lib/libOpenScriptingUtil")
3522 || StartsWithStrLit(filename, "/usr/lib/libextension")
3523 || StartsWithStrLit(filename, "/usr/lib/libAudioToolboxUtility")
3524 || StartsWithStrLit(filename, "/usr/lib/liboah")
3525 || StartsWithStrLit(filename, "/usr/lib/libRosetta")
3526 || StartsWithStrLit(filename, "/usr/lib/libCoreEntitlements")
3527 || StartsWithStrLit(filename, "/usr/lib/libssl.")
3528 || StartsWithStrLit(filename, "/usr/lib/libcrypto.")
3529
3530 // The system lib is likely in macOS's blob.
3532
3533 // "Link against the umbrella framework 'System.framework' instead"
3534 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_kernel")
3535 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_platform")
3536 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_pthread")
3537
3538 // "cannot link directly with dylib/framework, your binary is not an allowed client of
3539 // /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/
3540 // SDKs/MacOSX.sdk/usr/lib/libAudioToolboxUtility.tbd for architecture x86_64
3541 || (lenFilename > 4 && !strcmp(filename + lenFilename - 4, ".tbd")))
3542 return;
3545 filename = sFileName.Data();
3546#elif defined(__CYGWIN__)
3547 // Check that this is not a system library
3548 static const int bufsize = 260;
3549 char posixwindir[bufsize];
3550 char *windir = std::getenv("WINDIR");
3551 if (windir)
3553 else
3554 snprintf(posixwindir, sizeof(posixwindir), "/Windows/");
3555 if (strstr(filename, posixwindir) ||
3556 strstr(filename, "/usr/bin/cyg"))
3557 return;
3558#elif defined(R__WIN32)
3559 if (strstr(filename, "/Windows/"))
3560 return;
3561#elif defined (R__LINUX)
3562 if (strstr(filename, "/ld-linux")
3563 || strstr(filename, "linux-gnu/")
3564 || strstr(filename, "/libstdc++.")
3565 || strstr(filename, "/libgcc")
3566 || strstr(filename, "/libc.")
3567 || strstr(filename, "/libdl.")
3568 || strstr(filename, "/libm."))
3569 return;
3570#endif
3571 // Update string of available libraries.
3572 if (!fSharedLibs.IsNull()) {
3573 fSharedLibs.Append(" ");
3574 }
3576}
3577
3578////////////////////////////////////////////////////////////////////////////////
3579/// Load a library file in cling's memory.
3580/// if 'system' is true, the library is never unloaded.
3581/// Return 0 on success, -1 on failure.
3582
3584{
3585 assert(!IsFromRootCling() && "Trying to load library from rootcling!");
3586
3587 // Used to return 0 on success, 1 on duplicate, -1 on failure, -2 on "fatal".
3589 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3590 std::string canonLib = DLM->lookupLibrary(filename);
3591 cling::DynamicLibraryManager::LoadLibResult res
3592 = cling::DynamicLibraryManager::kLoadLibNotFound;
3593 if (!canonLib.empty()) {
3594 if (system)
3595 res = DLM->loadLibrary(filename, system, true);
3596 else {
3597 // For the non system libs, we'd like to be able to unload them.
3598 // FIXME: Here we lose the information about kLoadLibAlreadyLoaded case.
3599 cling::Interpreter::CompilationResult compRes;
3600 HandleInterpreterException(GetMetaProcessorImpl(), Form(".L %s", canonLib.c_str()), compRes, /*cling::Value*/nullptr);
3601 if (compRes == cling::Interpreter::kSuccess)
3602 res = cling::DynamicLibraryManager::kLoadLibSuccess;
3603 }
3604 }
3605
3606 if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3608 }
3609 switch (res) {
3610 case cling::DynamicLibraryManager::kLoadLibSuccess: return 0;
3611 case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded: return 1;
3612 default: break;
3613 };
3614 return -1;
3615}
3616
3617////////////////////////////////////////////////////////////////////////////////
3618/// Load a macro file in cling's memory.
3619
3620void TCling::LoadMacro(const char* filename, EErrorCode* error)
3621{
3622 ProcessLine(Form(".L %s", filename), error);
3623}
3624
3625////////////////////////////////////////////////////////////////////////////////
3626/// Let cling process a command line asynch.
3627
3629{
3630 return ProcessLine(line, error);
3631}
3632
3633////////////////////////////////////////////////////////////////////////////////
3634/// Let cling process a command line synchronously, i.e we are waiting
3635/// it will be finished.
3636
3638{
3640 if (gApplication) {
3641 if (gApplication->IsCmdThread()) {
3642 return ProcessLine(line, error);
3643 }
3644 return 0;
3645 }
3646 return ProcessLine(line, error);
3647}
3648
3649////////////////////////////////////////////////////////////////////////////////
3650/// Directly execute an executable statement (e.g. "func()", "3+5", etc.
3651/// however not declarations, like "Int_t x;").
3652
3654{
3655#ifdef R__WIN32
3656 // Test on ApplicationImp not being 0 is needed because only at end of
3657 // TApplication ctor the IsLineProcessing flag is set to 0, so before
3658 // we can not use it.
3660 while (gROOT->IsLineProcessing() && !gApplication) {
3661 Warning("Calc", "waiting for cling thread to free");
3662 gSystem->Sleep(500);
3663 }
3664 gROOT->SetLineIsProcessing();
3665 }
3666#endif // R__WIN32
3668 if (error) {
3669 *error = TInterpreter::kNoError;
3670 }
3671 cling::Value valRef;
3672 cling::Interpreter::CompilationResult cr = cling::Interpreter::kFailure;
3673 try {
3674 cr = fInterpreter->evaluate(line, valRef);
3675 }
3676 catch (cling::InterpreterException& ex)
3677 {
3678 Error("Calc", "%s.\n%s", ex.what(), "Evaluation of your expression was aborted.");
3679 ex.diagnose();
3680 cr = cling::Interpreter::kFailure;
3681 }
3682
3683 if (cr != cling::Interpreter::kSuccess) {
3684 // Failure in compilation.
3685 if (error) {
3686 // Note: Yes these codes are weird.
3688 }
3689 return 0L;
3690 }
3691 if (!valRef.isValid()) {
3692 // Failure at runtime.
3693 if (error) {
3694 // Note: Yes these codes are weird.
3695 *error = TInterpreter::kDangerous;
3696 }
3697 return 0L;
3698 }
3699
3700 if (valRef.isVoid()) {
3701 return 0;
3702 }
3703
3705#ifdef R__WIN32
3707 gROOT->SetLineHasBeenProcessed();
3708 }
3709#endif // R__WIN32
3710 return valRef.castAs<Longptr_t>();
3711}
3712
3713////////////////////////////////////////////////////////////////////////////////
3714/// Set a getline function to call when input is needed.
3715
3716void TCling::SetGetline(const char * (*getlineFunc)(const char* prompt),
3717 void (*histaddFunc)(const char* line))
3718{
3719 // If cling offers a replacement for G__pause(), it would need to
3720 // also offer a way to customize at least the history recording.
3721
3722#if defined(R__MUST_REVISIT)
3723#if R__MUST_REVISIT(6,2)
3724 Warning("SetGetline","Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3725#endif
3726#endif
3727}
3728
3729////////////////////////////////////////////////////////////////////////////////
3730/// Helper function to increase the internal Cling count of transactions
3731/// that change the AST.
3732
3733Bool_t TCling::HandleNewTransaction(const cling::Transaction &T)
3734{
3736
3737 if ((std::distance(T.decls_begin(), T.decls_end()) != 1)
3738 || T.deserialized_decls_begin() != T.deserialized_decls_end()
3739 || T.macros_begin() != T.macros_end()
3740 || ((!T.getFirstDecl().isNull()) && ((*T.getFirstDecl().begin()) != T.getWrapperFD()))) {
3742 return true;
3743 }
3744 return false;
3745}
3746
3747////////////////////////////////////////////////////////////////////////////////
3748/// Delete object from cling symbol table so it can not be used anymore.
3749/// cling objects are always on the heap.
3750
3752{
3753 // NOTE: When replacing the mutex by a ReadWrite mutex, we **must**
3754 // put in place the Read/Write part here. Keeping the write lock
3755 // here is 'catasptrophic' for scaling as it means that ALL calls
3756 // to RecursiveRemove will take the write lock and performance
3757 // of many threads trying to access the write lock at the same
3758 // time is relatively bad.
3760 // Note that fgSetOfSpecials is supposed to be updated by TClingCallbacks::tryFindROOTSpecialInternal
3761 // (but isn't at the moment).
3762 if (obj->IsOnHeap() && fgSetOfSpecials && !((std::set<TObject*>*)fgSetOfSpecials)->empty()) {
3763 std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)fgSetOfSpecials)->find(obj);
3764 if (iSpecial != ((std::set<TObject*>*)fgSetOfSpecials)->end()) {
3766 DeleteGlobal(obj);
3767 ((std::set<TObject*>*)fgSetOfSpecials)->erase(iSpecial);
3768 }
3769 }
3770}
3771
3772////////////////////////////////////////////////////////////////////////////////
3773/// Pressing Ctrl+C should forward here. In the case where we have had
3774/// continuation requested we must reset it.
3775
3777{
3778 fMetaProcessor->cancelContinuation();
3779 // Reset the Cling state to the state saved by the last call to
3780 // TCling::SaveContext().
3781#if defined(R__MUST_REVISIT)
3782#if R__MUST_REVISIT(6,2)
3784 Warning("Reset","Cling should support the equivalent of scratch_upto(&fDictPos)");
3785#endif
3786#endif
3787}
3788
3789////////////////////////////////////////////////////////////////////////////////
3790/// Reset the Cling state to its initial state.
3791
3793{
3794#if defined(R__MUST_REVISIT)
3795#if R__MUST_REVISIT(6,2)
3797 Warning("ResetAll","Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3798#endif
3799#endif
3800}
3801
3802////////////////////////////////////////////////////////////////////////////////
3803/// Reset in Cling the list of global variables to the state saved by the last
3804/// call to TCling::SaveGlobalsContext().
3805///
3806/// Note: Right now, all we do is run the global destructors.
3807
3809{
3811 // TODO:
3812 // Here we should iterate over the transactions (N-3) and revert.
3813 // N-3 because the first three internal to cling.
3814
3815 fInterpreter->runAndRemoveStaticDestructors();
3816}
3817
3818////////////////////////////////////////////////////////////////////////////////
3819/// Reset the Cling 'user' global objects/variables state to the state saved by the last
3820/// call to TCling::SaveGlobalsContext().
3821
3823{
3824#if defined(R__MUST_REVISIT)
3825#if R__MUST_REVISIT(6,2)
3827 Warning("ResetGlobalVar","Cling should support the equivalent of resetglobalvar(obj)");
3828#endif
3829#endif
3830}
3831
3832////////////////////////////////////////////////////////////////////////////////
3833/// Rewind Cling dictionary to the point where it was before executing
3834/// the current macro. This function is typically called after SEGV or
3835/// ctlr-C after doing a longjmp back to the prompt.
3836
3838{
3839#if defined(R__MUST_REVISIT)
3840#if R__MUST_REVISIT(6,2)
3842 Warning("RewindDictionary","Cling should provide a way to revert transaction similar to rewinddictionary()");
3843#endif
3844#endif
3845}
3846
3847////////////////////////////////////////////////////////////////////////////////
3848/// Delete obj from Cling symbol table so it cannot be accessed anymore.
3849/// Returns 1 in case of success and 0 in case object was not in table.
3850
3852{
3853#if defined(R__MUST_REVISIT)
3854#if R__MUST_REVISIT(6,2)
3856 Warning("DeleteGlobal","Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3857#endif
3858#endif
3859 return 0;
3860}
3861
3862////////////////////////////////////////////////////////////////////////////////
3863/// Undeclare obj called name.
3864/// Returns 1 in case of success, 0 for failure.
3865
3867{
3868#if defined(R__MUST_REVISIT)
3869#if R__MUST_REVISIT(6,2)
3870 Warning("DeleteVariable","should do more that just reseting the value to zero");
3871#endif
3872#endif
3873
3875 llvm::StringRef srName(name);
3876 const char* unscopedName = name;
3877 llvm::StringRef::size_type posScope = srName.rfind("::");
3878 const clang::DeclContext* declCtx = nullptr;
3879 if (posScope != llvm::StringRef::npos) {
3880 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3881 const clang::Decl* scopeDecl
3882 = lh.findScope(srName.substr(0, posScope),
3883 cling::LookupHelper::WithDiagnostics);
3884 if (!scopeDecl) {
3885 Error("DeleteVariable", "Cannot find enclosing scope for variable %s",
3886 name);
3887 return 0;
3888 }
3889 declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3890 if (!declCtx) {
3891 Error("DeleteVariable",
3892 "Enclosing scope for variable %s is not a declaration context",
3893 name);
3894 return 0;
3895 }
3896 unscopedName += posScope + 2;
3897 }
3898 // Could trigger deserialization of decls.
3899 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
3900 clang::NamedDecl* nVarDecl
3901 = cling::utils::Lookup::Named(&fInterpreter->getSema(), unscopedName, declCtx);
3902 if (!nVarDecl) {
3903 Error("DeleteVariable", "Unknown variable %s", name);
3904 return 0;
3905 }
3906 clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3907 if (!varDecl) {
3908 Error("DeleteVariable", "Entity %s is not a variable", name);
3909 return 0;
3910 }
3911
3912 clang::QualType qType = varDecl->getType();
3913 const clang::Type* type = qType->getUnqualifiedDesugaredType();
3914 // Cannot set a reference's address to nullptr; the JIT can place it
3915 // into read-only memory (ROOT-7100).
3916 if (type->isPointerType()) {
3917 int** ppInt = (int**)fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3918 // set pointer to invalid.
3919 if (ppInt) *ppInt = nullptr;
3920 }
3921 return 1;
3922}
3923
3924////////////////////////////////////////////////////////////////////////////////
3925/// Save the current Cling state.
3926
3928{
3929#if defined(R__MUST_REVISIT)
3930#if R__MUST_REVISIT(6,2)
3932 Warning("SaveContext","Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3933#endif
3934#endif
3935}
3936
3937////////////////////////////////////////////////////////////////////////////////
3938/// Save the current Cling state of global objects.
3939
3941{
3942#if defined(R__MUST_REVISIT)
3943#if R__MUST_REVISIT(6,2)
3945 Warning("SaveGlobalsContext","Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3946#endif
3947#endif
3948}
3949
3950////////////////////////////////////////////////////////////////////////////////
3951/// No op: see TClingCallbacks (used to update the list of globals)
3952
3956
3957////////////////////////////////////////////////////////////////////////////////
3958/// No op: see TClingCallbacks (used to update the list of global functions)
3959
3963
3964////////////////////////////////////////////////////////////////////////////////
3965/// No op: see TClingCallbacks (used to update the list of types)
3966
3968{
3969}
3970
3971////////////////////////////////////////////////////////////////////////////////
3972/// Check in what order the member of a tuple are layout.
3973enum class ETupleOrdering {
3974 kAscending,
3977};
3978
3984
3990
3992{
3993 std::tuple<int,double> value;
3996
3997 size_t offset0 = ((char*)&(std::get<0>(value))) - ((char*)&value);
3998 size_t offset1 = ((char*)&(std::get<1>(value))) - ((char*)&value);
3999
4000 size_t ascOffset0 = ((char*)&(asc._0)) - ((char*)&asc);
4001 size_t ascOffset1 = ((char*)&(asc._1)) - ((char*)&asc);
4002
4003 size_t desOffset0 = ((char*)&(des._0)) - ((char*)&des);
4004 size_t desOffset1 = ((char*)&(des._1)) - ((char*)&des);
4005
4006 if (offset0 == ascOffset0 && offset1 == ascOffset1) {
4008 } else if (offset0 == desOffset0 && offset1 == desOffset1) {
4010 } else {
4012 }
4013}
4014
4015static std::string AlternateTuple(const char *classname, const cling::LookupHelper& lh, Bool_t silent)
4016{
4018 std::string alternateName = "TEmulatedTuple";
4019 alternateName.append( classname + 5 );
4020
4021 std::string fullname = "ROOT::Internal::" + alternateName;
4022 if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
4023 /*resultType*/nullptr, /* intantiateTemplate= */ false))
4024 return fullname;
4025
4026 {
4027 // Check if we can produce the tuple
4028 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
4029 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
4030 auto deleter = [](TypeInfo_t *type) {
4031 gInterpreter->TypeInfo_Delete(type);
4032 };
4033 std::unique_ptr<TypeInfo_t, decltype(deleter)> type{ gInterpreter->TypeInfo_Factory(), deleter };
4034 while (iter != theEnd) {
4035 gInterpreter->TypeInfo_Init(type.get(), iter->c_str());
4036 if (gInterpreter->TypeInfo_Property(type.get()) & kIsNotReacheable) {
4037 if (!silent)
4038 Error("Load","Could not declare alternate type for %s since %s (or one of its context) is private or protected",
4039 classname, iter->c_str());
4040 return "";
4041 }
4042 ++iter;
4043 }
4044 }
4045
4046 std::string guard_name;
4048 std::ostringstream guard;
4049 guard << "ROOT_INTERNAL_TEmulated_";
4050 guard << guard_name;
4051
4052 std::ostringstream alternateTuple;
4053 alternateTuple << "#ifndef " << guard.str() << "\n";
4054 alternateTuple << "#define " << guard.str() << "\n";
4055 alternateTuple << "namespace ROOT { namespace Internal {\n";
4056 alternateTuple << "template <class... Types> struct TEmulatedTuple;\n";
4057 alternateTuple << "template <> struct " << alternateName << " {\n";
4058
4059 // This could also be a compile time choice ...
4060 switch(IsTupleAscending()) {
4062 unsigned int nMember = 0;
4063 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
4064 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
4065 while (iter != theEnd) {
4066 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4067 ++iter;
4068 ++nMember;
4069 }
4070 break;
4071 }
4073 unsigned int nMember = tupleContent.fElements.size() - 3;
4074 auto iter = tupleContent.fElements.rbegin() + 1; // skip the 'stars'.
4075 auto theEnd = tupleContent.fElements.rend() - 1; // Skip the template name (tuple).
4076 while (iter != theEnd) {
4077 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4078 ++iter;
4079 --nMember;
4080 }
4081 break;
4082 }
4084 Fatal("TCling::SetClassInfo::AlternateTuple",
4085 "Layout of std::tuple on this platform is unexpected.");
4086 break;
4087 }
4088 }
4089
4090 alternateTuple << "};\n";
4091 alternateTuple << "}}\n";
4092 alternateTuple << "#endif\n";
4093 if (!gCling->Declare(alternateTuple.str().c_str()))
4094 {
4095 // Declare is not silent (yet?), so add an explicit error message
4096 // to indicate the consequence of the syntax errors.
4097 Error("Load","Could not declare %s",alternateName.c_str());
4098 return "";
4099 }
4100 alternateName = "ROOT::Internal::" + alternateName;
4101 return alternateName;
4102}
4103
4104////////////////////////////////////////////////////////////////////////////////
4105/// Set pointer to the TClingClassInfo in TClass.
4106/// If 'reload' is true, (attempt to) generate a new ClassInfo even if we
4107/// already have one.
4108
4110{
4111 // We are shutting down, there is no point in reloading, it only triggers
4112 // redundant deserializations.
4113 if (fIsShuttingDown) {
4114 // Remove the decl_id from the DeclIdToTClass map
4115 if (cl->fClassInfo) {
4118 // Test again as another thread may have set fClassInfo to nullptr.
4119 if (TClinginfo) {
4121 }
4122 delete TClinginfo;
4123 cl->fClassInfo = nullptr;
4124 }
4125 return;
4126 }
4127
4129 if (cl->fClassInfo && !reload) {
4130 return;
4131 }
4132 //Remove the decl_id from the DeclIdToTClass map
4134 if (TClinginfo) {
4136 }
4137 delete TClinginfo;
4138 cl->fClassInfo = nullptr;
4139 std::string name(cl->GetName());
4140
4141 auto SetWithoutClassInfoState = [](TClass *cl)
4142 {
4143 if (cl->fState != TClass::kHasTClassInit) {
4144 if (cl->fStreamerInfo->GetEntries() != 0) {
4146 } else {
4148 }
4149 }
4150 };
4151 // Handle the special case of 'tuple' where we ignore the real implementation
4152 // details and just overlay a 'simpler'/'simplistic' version that is easy
4153 // for the I/O to understand and handle.
4154 if (strncmp(cl->GetName(),"tuple<",std::char_traits<char>::length("tuple<"))==0) {
4155 if (!reload)
4156 name = AlternateTuple(cl->GetName(), fInterpreter->getLookupHelper(), silent);
4157 if (reload || name.empty()) {
4158 // We could not generate the alternate
4160 return;
4161 }
4162 }
4163
4165 // FIXME: Rather than adding an option to the TClingClassInfo, we should consider combining code
4166 // that is currently in the caller (like SetUnloaded) that disable AutoLoading and AutoParsing and
4167 // code is in the callee (disabling template instantiation) and end up with a more explicit class:
4168 // TClingClassInfoReadOnly.
4170 if (!info->IsValid()) {
4172 delete info;
4173 return;
4174 }
4175 cl->fClassInfo = (ClassInfo_t*)info; // Note: We are transferring ownership here.
4176 // In case a class contains an external enum, the enum will be seen as a
4177 // class. We must detect this special case and make the class a Zombie.
4178 // Here we assume that a class has at least one method.
4179 // We can NOT call TClass::Property from here, because this method
4180 // assumes that the TClass is well formed to do a lot of information
4181 // caching. The method SetClassInfo (i.e. here) is usually called during
4182 // the building phase of the TClass, hence it is NOT well formed yet.
4184 if (
4185 info->IsValid() &&
4186 !(info->Property() & (kIsClass | kIsStruct | kIsNamespace))
4187 ) {
4189 }
4190 if (!info->IsLoaded()) {
4191 if (info->Property() & (kIsNamespace)) {
4192 // Namespaces can have info but no corresponding CINT dictionary
4193 // because they are auto-created if one of their contained
4194 // classes has a dictionary.
4196 }
4197 // this happens when no dictionary is available
4198 delete info;
4199 cl->fClassInfo = nullptr;
4200 }
4201 if (zombieCandidate && !cl->GetCollectionType()) {
4202 cl->MakeZombie();
4203 }
4204 // If we reach here, the info was valid (See early returns).
4205 if (cl->fState != TClass::kHasTClassInit) {
4206 if (cl->fClassInfo) {
4208 } else {
4209// if (TClassEdit::IsSTLCont(cl->GetName()) {
4210// There will be an emulated collection proxy, is that the same?
4211// cl->fState = TClass::kEmulated;
4212// } else {
4213 if (cl->fStreamerInfo->GetEntries() != 0) {
4215 } else {
4217 }
4218// }
4219 }
4220 }
4221 if (cl->fClassInfo) {
4222 TClass::AddClassToDeclIdMap(((TClingClassInfo*)cl->fClassInfo)->GetDeclId(), cl);
4223 }
4224}
4225
4226////////////////////////////////////////////////////////////////////////////////
4227/// Checks if an entity with the specified name is defined in Cling.
4228/// Returns kUnknown if the entity is not defined.
4229/// Returns kWithClassDefInline if the entity exists and has a ClassDefInline
4230/// Returns kKnown if the entity is defined.
4231///
4232/// By default, structs, namespaces, classes, enums and unions are looked for.
4233/// If the flag isClassOrNamespaceOnly is true, classes, structs and
4234/// namespaces only are considered. I.e. if the name is an enum or a union,
4235/// the returned value is false.
4236///
4237/// In the case where the class is not loaded and belongs to a namespace
4238/// or is nested, looking for the full class name is outputting a lots of
4239/// (expected) error messages. Currently the only way to avoid this is to
4240/// specifically check that each level of nesting is already loaded.
4241/// In case of templates the idea is that everything between the outer
4242/// '<' and '>' has to be skipped, e.g.: `aap<pippo<noot>::klaas>::a_class`
4243
4246{
4248 static const char *anonEnum = "anonymous enum ";
4249 static const int cmplen = strlen(anonEnum);
4250
4251 if (fIsShuttingDown || 0 == strncmp(name, anonEnum, cmplen)) {
4252 return kUnknown;
4253 }
4254
4255 // Do not turn on the AutoLoading if it is globally off.
4257
4258 // Avoid the double search below in case the name is a fundamental type
4259 // or typedef to a fundamental type.
4260 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
4261 TDataType *fundType = (TDataType *)typeTable->THashTable::FindObject( name );
4262
4264 && fundType->GetType() > 0) {
4265 // Fundamental type, no a class.
4266 return kUnknown;
4267 }
4268
4269 // Migrated from within TClass::GetClass
4270 // If we want to know if a class or a namespace with this name exists in the
4271 // interpreter and this is an enum in the type system, before or after loading
4272 // according to the autoload function argument, return kUnknown.
4274 return kUnknown;
4275
4276 const char *classname = name;
4277
4278 // RAII to suspend and restore auto-loading and auto-parsing based on some external conditions.
4280 int fStoreAutoLoad = 0;
4281 int fStoreAutoParse = 0;
4282 bool fSuspendedAutoParse = false;
4283 public:
4285 fStoreAutoLoad = ((TCling*)gCling)->SetClassAutoLoading(autoload);
4286 }
4287
4288 void SuspendAutoParsing() {
4289 fSuspendedAutoParse = true;
4290 fStoreAutoParse = ((TCling*)gCling)->SetSuspendAutoParsing(true);
4291 }
4292
4295 ((TCling*)gCling)->SetSuspendAutoParsing(fStoreAutoParse);
4296 ((TCling*)gCling)->SetClassAutoLoading(fStoreAutoLoad);
4297 }
4298 };
4299
4301 if (TClassEdit::IsStdPair(classname) || TClassEdit::IsStdPairBase(classname))
4302 autoLoadParseRAII.SuspendAutoParsing();
4303
4304 // First we want to check whether the decl exist, but _without_
4305 // generating any template instantiation. However, the lookup
4306 // still will create a forward declaration of the class template instance
4307 // if it exist. In this case, the return value of findScope will still
4308 // be zero but the type will be initialized.
4309 // Note in the corresponding code in ROOT 5, CINT was not instantiating
4310 // this forward declaration.
4311 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4312 const clang::Type *type = nullptr;
4313 const clang::Decl *decl
4314 = lh.findScope(classname,
4315 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4316 : cling::LookupHelper::NoDiagnostics,
4317 &type, /* intantiateTemplate= */ false );
4318 if (!decl) {
4319 std::string buf = TClassEdit::InsertStd(classname);
4320 decl = lh.findScope(buf,
4321 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4322 : cling::LookupHelper::NoDiagnostics,
4323 &type,false);
4324 }
4325
4326 if (type) {
4327 // If decl==0 and the type is valid, then we have a forward declaration.
4328 if (!decl) {
4329 // If we have a forward declaration for a class template instantiation,
4330 // we want to ignore it if it was produced/induced by the call to
4331 // findScope, however we can not distinguish those from the
4332 // instantiation induce by 'soft' use (and thus also induce by the
4333 // same underlying code paths)
4334 // ['soft' use = use not requiring a complete definition]
4335 // So to reduce the amount of disruption to the existing code we
4336 // would just ignore those for STL collection, for which we really
4337 // need to have the compiled collection proxy (and thus the TClass
4338 // bootstrap).
4339 clang::ClassTemplateSpecializationDecl *tmpltDecl =
4340 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
4341 (type->getAsCXXRecordDecl());
4342 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4343 // Since the point of instantiation is invalid, we 'guess' that
4344 // the 'instantiation' of the forwarded type appended in
4345 // findscope.
4347 // For STL Collection we return kUnknown.
4348 return kUnknown;
4349 }
4350 }
4351 }
4353 if (!tci.IsValid()) {
4354 return kUnknown;
4355 }
4358
4359 if (tci.Property() & propertiesMask) {
4360 bool hasClassDefInline = false;
4362 // We do not need to check for ClassDefInline when this is called from
4363 // TClass::Init, we only do it for the call from TClass::GetClass.
4364 auto hasDictionary = tci.GetMethod("Dictionary", "", false, nullptr, ROOT::kExactMatch);
4365 auto implLineFunc = tci.GetMethod("ImplFileLine", "", false, nullptr, ROOT::kExactMatch);
4366
4367 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4368 int lineNumber = 0;
4369 bool success = false;
4370 std::tie(success, lineNumber) =
4373 }
4374 }
4375
4376 // fprintf(stderr,"CheckClassInfo: %s had dict=%d inline=%d\n",name,hasDictionary.IsValid()
4377 // , hasClassDefInline);
4378
4379 // We are now sure that the entry is not in fact an autoload entry.
4381 return kWithClassDefInline;
4382 else
4383 return kKnown;
4384 } else {
4385 // We are now sure that the entry is not in fact an autoload entry.
4386 return kUnknown;
4387 }
4388 }
4389
4390 if (decl)
4391 return kKnown;
4392 else
4393 return kUnknown;
4394
4395 // Setting up iterator part of TClingTypedefInfo is too slow.
4396 // Copy the lookup code instead:
4397 /*
4398 TClingTypedefInfo t(fInterpreter, name);
4399 if (t.IsValid() && !(t.Property() & kIsFundamental)) {
4400 delete[] classname;
4401 return kTRUE;
4402 }
4403 */
4404
4405// const clang::Decl *decl = lh.findScope(name);
4406// if (!decl) {
4407// std::string buf = TClassEdit::InsertStd(name);
4408// decl = lh.findScope(buf);
4409// }
4410
4411// return (decl);
4412}
4413
4414////////////////////////////////////////////////////////////////////////////////
4415/// Return true if there is a class template by the given name ...
4416
4418{
4419 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4420 // Interpreter transaction ahead, needs locking
4422 const clang::Decl *decl
4423 = lh.findClassTemplate(name,
4424 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4425 : cling::LookupHelper::NoDiagnostics);
4426 if (!decl) {
4427 std::string strname = "std::";
4428 strname += name;
4429 decl = lh.findClassTemplate(strname,
4430 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4431 : cling::LookupHelper::NoDiagnostics);
4432 }
4433 return nullptr != decl;
4434}
4435
4436////////////////////////////////////////////////////////////////////////////////
4437/// Create list of pointers to base class(es) for TClass cl.
4438
4440{
4442 if (cl->fBase) {
4443 return;
4444 }
4446 if (!tci) return;
4448 TList *listOfBase = new TList;
4449 while (t.Next()) {
4450 // if name cannot be obtained no use to put in list
4451 if (t.IsValid() && t.Name()) {
4453 listOfBase->Add(new TBaseClass((BaseClassInfo_t *)a, cl));
4454 }
4455 }
4456 // Now that is complete, publish it.
4457 cl->fBase = listOfBase;
4458}
4459
4460////////////////////////////////////////////////////////////////////////////////
4461/// Create list of pointers to enums for TClass cl.
4462
4464{
4466
4467 const Decl * D;
4468 TClass* cl = enumList.GetClass();
4469 if (cl) {
4470 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4471 }
4472 else {
4473 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4474 }
4475 // Iterate on the decl of the class and get the enums.
4476 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4477 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4478 // Collect all contexts of the namespace.
4479 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4480 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4482 declIter != declEnd; ++declIter) {
4483 // Iterate on all decls for each context.
4484 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4485 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4486 if (const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4487 // Get name of the enum type.
4488 std::string buf;
4489 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4490 llvm::raw_string_ostream stream(buf);
4491 // Don't trigger fopen of the source file to count lines:
4492 Policy.AnonymousTagLocations = false;
4493 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
4494 stream.flush();
4495 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
4496 if (!buf.empty()) {
4497 const char* name = buf.c_str();
4498 // Add the enum to the list of loaded enums.
4499 enumList.Get(ED, name);
4500 }
4501 }
4502 }
4503 }
4504 }
4505}
4506
4507////////////////////////////////////////////////////////////////////////////////
4508/// Create list of pointers to function templates for TClass cl.
4509
4511{
4513
4514 const Decl * D;
4516 if (cl) {
4517 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4519 }
4520 else {
4521 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4522 funcTempList = (TListOfFunctionTemplates*)gROOT->GetListOfFunctionTemplates();
4523 }
4524 // Iterate on the decl of the class and get the enums.
4525 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4526 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4527 // Collect all contexts of the namespace.
4528 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4529 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4532 // Iterate on all decls for each context.
4533 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4534 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4535 if (const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4536 funcTempList->Get(FTD);
4537 }
4538 }
4539 }
4540 }
4541}
4542
4543////////////////////////////////////////////////////////////////////////////////
4544/// Get the scopes representing using declarations of namespace
4545
4546std::vector<std::string> TCling::GetUsingNamespaces(ClassInfo_t *cl) const
4547{
4549 return ci->GetUsingNamespaces();
4550}
4551
4552////////////////////////////////////////////////////////////////////////////////
4553/// Create list of pointers to data members for TClass cl.
4554/// This is now a nop. The creation and updating is handled in
4555/// TListOfDataMembers.
4556
4558{
4559}
4560
4561////////////////////////////////////////////////////////////////////////////////
4562/// Create list of pointers to methods for TClass cl.
4563/// This is now a nop. The creation and updating is handled in
4564/// TListOfFunctions.
4565
4567{
4568}
4569
4570////////////////////////////////////////////////////////////////////////////////
4571/// Update the list of pointers to method for TClass cl
4572/// This is now a nop. The creation and updating is handled in
4573/// TListOfFunctions.
4574
4576{
4577}
4578
4579////////////////////////////////////////////////////////////////////////////////
4580/// Update the list of pointers to data members for TClass cl
4581/// This is now a nop. The creation and updating is handled in
4582/// TListOfDataMembers.
4583
4585{
4586}
4587
4588////////////////////////////////////////////////////////////////////////////////
4589/// Create list of pointers to method arguments for TMethod m.
4590
4592{
4594 if (m->fMethodArgs) {
4595 return;
4596 }
4597 TList *arglist = new TList;
4599 while (t.Next()) {
4600 if (t.IsValid()) {
4602 arglist->Add(new TMethodArg((MethodArgInfo_t*)a, m));
4603 }
4604 }
4605 m->fMethodArgs = arglist;
4606}
4607
4608////////////////////////////////////////////////////////////////////////////////
4609/// Return whether we are waiting for more input either because the collected
4610/// input contains unbalanced braces or last seen token was a `\` (backslash-newline)
4611
4613{
4614 return fMetaProcessor->awaitingMoreInput();
4615}
4616
4617////////////////////////////////////////////////////////////////////////////////
4618/// Generate a TClass for the given class.
4619/// Since the caller has already check the ClassInfo, let it give use the
4620/// result (via the value of emulation) rather than recalculate it.
4621
4622TClass *TCling::GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent /* = kFALSE */)
4623{
4624// For now the following line would lead to the (unwanted) instantiation
4625// of class template. This could/would need to be resurrected only if
4626// we re-introduce so sort of automatic instantiation. However this would
4627// have to include carefull look at the template parameter to avoid
4628// creating instance we can not really use (if the parameter are only forward
4629// declaration or do not have all the necessary interfaces).
4630
4631 // TClingClassInfo tci(fInterpreter, classname);
4632 // if (1 || !tci.IsValid()) {
4633
4634 Version_t version = 1;
4635 if (TClassEdit::IsSTLCont(classname)) {
4636 version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4637 }
4639 TClass *cl = new TClass(classname, version, silent);
4640 if (!emulation) {
4641 // Set the class version if the class is versioned.
4642 // Note that we cannot just call CLASS::Class_Version() as we might not have
4643 // an execution engine (when invoked from rootcling).
4644
4645 // Do not call cl->GetClassVersion(), it has side effects!
4647 if (oldvers == version && cl->GetClassInfo()) {
4648 // We have a version and it might need an update.
4650 if (llvm::isa<clang::NamespaceDecl>(cli->GetDecl())) {
4651 // Namespaces don't have class versions.
4652 return cl;
4653 }
4654 TClingMethodInfo mi = cli->GetMethod("Class_Version", "", nullptr /*poffset*/,
4657 if (!mi.IsValid()) {
4658 if (cl->TestBit(TClass::kIsTObject)) {
4659 Error("GenerateTClass",
4660 "Cannot find %s::Class_Version()! Class version might be wrong.",
4661 cl->GetName());
4662 }
4663 return cl;
4664 }
4665 Version_t newvers = ROOT::TMetaUtils::GetClassVersion(llvm::dyn_cast<clang::RecordDecl>(cli->GetDecl()),
4666 *fInterpreter);
4667 if (newvers == -1) {
4668 // Didn't manage to determine the class version from the AST.
4669 // Use runtime instead.
4670 if ((mi.Property() & kIsStatic)
4671 && !fInterpreter->isInSyntaxOnlyMode()) {
4672 // This better be a static function.
4674 callfunc.SetFunc(&mi);
4675 newvers = callfunc.ExecInt(nullptr);
4676 } else {
4677 Error("GenerateTClass",
4678 "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4679 cl->GetName());
4680 }
4681 }
4682 if (newvers != oldvers) {
4683 cl->fClassVersion = newvers;
4684 cl->fStreamerInfo->Expand(newvers + 2 + 10);
4685 }
4686 }
4687 }
4688
4689 return cl;
4690
4691// } else {
4692// return GenerateTClass(&tci,silent);
4693// }
4694}
4695
4696#if 0
4697////////////////////////////////////////////////////////////////////////////////
4698
4700{
4701 includes += info->FileName();
4702
4703 const clang::ClassTemplateSpecializationDecl *templateCl
4704 = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->GetDecl());
4705 if (templateCl) {
4706 for(unsigned int i=0; i < templateCl->getTemplateArgs().size(); ++i) {
4707 const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4708 if (arg.getKind() == clang::TemplateArgument::Type) {
4709 const clang::Type *uType = ROOT::TMetaUtils::GetUnderlyingType( arg.getAsType() );
4710
4711 if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4712 // We really need a header file.
4713 const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4714 if (argdecl) {
4715 includes += ";";
4716 TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4718 } else {
4719 std::string Result;
4720 llvm::raw_string_ostream OS(Result);
4721 arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4722 Warning("TCling::GenerateTClass","Missing header file for %s",OS.str().c_str());
4723 }
4724 }
4725 }
4726 }
4727 }
4728}
4729#endif
4730
4731////////////////////////////////////////////////////////////////////////////////
4732/// Generate a TClass for the given class.
4733
4735{
4737 if (!info || !info->IsValid()) {
4738 Fatal("GenerateTClass","Requires a valid ClassInfo object");
4739 return nullptr;
4740 }
4741 // We are in the case where we have AST nodes for this class.
4742 TClass *cl = nullptr;
4743 std::string classname;
4744 info->FullName(classname,*fNormalizedCtxt); // Could we use Name()?
4745 if (TClassEdit::IsSTLCont(classname)) {
4746#if 0
4747 Info("GenerateTClass","Will (try to) generate the compiled TClass for %s.",classname.c_str());
4748 // We need to build up the list of required headers, by
4749 // looking at each template arguments.
4752
4753 if (0 == GenerateDictionary(classname.c_str(),includes)) {
4754 // 0 means success.
4755 cl = TClass::LoadClass(classnam.c_str(), silent);
4756 if (cl == 0) {
4757 Error("GenerateTClass","Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4758 }
4759 }
4760#endif
4761 if (cl == nullptr) {
4762 int version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4763 cl = new TClass(classinfo, version, nullptr, nullptr, -1, -1, silent);
4764 }
4765 } else {
4766 // For regular class, just create a TClass on the fly ...
4767 // Not quite useful yet, but that what CINT used to do anyway.
4768 cl = new TClass(classinfo, 1, nullptr, nullptr, -1, -1, silent);
4769 }
4770 // Add the new TClass to the map of declid and TClass*.
4771 if (cl) {
4773 }
4774 return cl;
4775}
4776
4777////////////////////////////////////////////////////////////////////////////////
4778/// Generate the dictionary for the C++ classes listed in the first
4779/// argument (in a semi-colon separated list).
4780/// 'includes' contains a semi-colon separated list of file to
4781/// `#include` in the dictionary.
4782/// For example:
4783/// ~~~ {.cpp}
4784/// gInterpreter->GenerateDictionary("vector<vector<float> >;list<vector<float> >","list;vector");
4785/// ~~~
4786/// or
4787/// ~~~ {.cpp}
4788/// gInterpreter->GenerateDictionary("myclass","myclass.h;myhelper.h");
4789/// ~~~
4790
4791Int_t TCling::GenerateDictionary(const char* classes, const char* includes /* = "" */, const char* /* options = 0 */)
4792{
4793 if (classes == nullptr || classes[0] == 0) {
4794 Error("TCling::GenerateDictionary", "Cannot generate dictionary without passing classes.");
4795 return 0;
4796 }
4797 // Split the input list
4798 std::vector<std::string> listClasses;
4799 for (
4800 const char* current = classes, *prev = classes;
4801 *current != 0;
4802 ++current
4803 ) {
4804 if (*current == ';') {
4805 listClasses.push_back(std::string(prev, current - prev));
4806 prev = current + 1;
4807 }
4808 else if (*(current + 1) == 0) {
4809 listClasses.push_back(std::string(prev, current + 1 - prev));
4810 prev = current + 1;
4811 }
4812 }
4813 std::vector<std::string> listIncludes;
4814 if (!includes)
4815 includes = "";
4816 for (
4817 const char* current = includes, *prev = includes;
4818 *current != 0;
4819 ++current
4820 ) {
4821 if (*current == ';') {
4822 listIncludes.push_back(std::string(prev, current - prev));
4823 prev = current + 1;
4824 }
4825 else if (*(current + 1) == 0) {
4826 listIncludes.push_back(std::string(prev, current + 1 - prev));
4827 prev = current + 1;
4828 }
4829 }
4830 // Generate the temporary dictionary file
4832 std::vector<std::string>(), std::vector<std::string>());
4833}
4834
4835////////////////////////////////////////////////////////////////////////////////
4836/// Return pointer to cling Decl of global/static variable that is located
4837/// at the address given by addr.
4838
4840{
4842 DeclId_t d;
4844
4845 // Could trigger deserialization of decls.
4846 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4847
4848 if (cl) {
4849 d = cl->GetDataMember(name);
4850 // We check if the decl of the data member has an annotation which indicates
4851 // an ioname.
4852 // In case this is true, if the name requested is not the ioname, we
4853 // return 0, as if the member did not exist. In some sense we override
4854 // the information in the TClassInfo instance, isolating the typesystem in
4855 // TClass from the one in the AST.
4856 if (const ValueDecl* decl = (const ValueDecl*) d){
4857 std::string ioName;
4859 if (hasIoName && ioName != name) return nullptr;
4860 }
4861 return d;
4862 }
4863 // We are looking up for something on the TU scope.
4864 // FIXME: We do not want to go through TClingClassInfo(fInterpreter) because of redundant deserializations. That
4865 // interface will actually construct iterators and walk over the decls on the global scope. In would return the first
4866 // occurrence of a decl with the looked up name. However, that's not what C++ lookup would do: if we want to switch
4867 // to a more complete C++ lookup interface we need sift through the found names and pick up the declarations which
4868 // are only fulfilling ROOT's understanding for a Data Member.
4869 // FIXME: We should probably deprecate the TClingClassInfo(fInterpreter) interface and replace it withe something
4870 // similar as below.
4871 using namespace clang;
4872 Sema& SemaR = fInterpreter->getSema();
4873 DeclarationName DName = &SemaR.Context.Idents.get(name);
4874
4875 LookupResult R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4876 Sema::ForExternalRedeclaration);
4877
4878 cling::utils::Lookup::Named(&SemaR, R);
4879
4880 LookupResult::Filter F = R.makeFilter();
4881 // Filter the data-member looking decls.
4882 while (F.hasNext()) {
4883 NamedDecl *D = F.next();
4886 continue;
4887 F.erase();
4888 }
4889 F.done();
4890
4891 if (R.isSingleResult())
4892 return R.getFoundDecl();
4893 return nullptr;
4894}
4895
4896////////////////////////////////////////////////////////////////////////////////
4897/// Return pointer to cling Decl of global/static variable that is located
4898/// at the address given by addr.
4899
4901{
4903
4904 const clang::Decl* possibleEnum = nullptr;
4905 // FInd the context of the decl.
4906 if (cl) {
4908 if (cci) {
4909 const clang::DeclContext* dc = nullptr;
4910 if (const clang::Decl* D = cci->GetDecl()) {
4911 if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
4913 }
4914 }
4915 if (dc) {
4916 // If it is a data member enum.
4917 // Could trigger deserialization of decls.
4918 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4919 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name, dc);
4920 } else {
4921 Error("TCling::GetEnum", "DeclContext not found for %s .\n", name);
4922 }
4923 }
4924 } else {
4925 // If it is a global enum.
4926 // Could trigger deserialization of decls.
4927 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4928 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name);
4929 }
4930 if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
4932 return possibleEnum;
4933 }
4934 return nullptr;
4935}
4936
4937////////////////////////////////////////////////////////////////////////////////
4938/// Return pointer to cling DeclId for a global value
4939
4940TInterpreter::DeclId_t TCling::GetDeclId( const llvm::GlobalValue *gv ) const
4941{
4942 if (!gv) return nullptr;
4943
4944 llvm::StringRef mangled_name = gv->getName();
4945
4946 int err = 0;
4947 char* demangled_name_c = TClassEdit::DemangleName(mangled_name.str().c_str(), err);
4948 if (err) {
4949 if (err == -2) {
4950 // It might simply be an unmangled global name.
4951 DeclId_t d;
4953 d = gcl.GetDataMember(mangled_name.str().c_str());
4954 return d;
4955 }
4956 return nullptr;
4957 }
4958
4959 std::string scopename(demangled_name_c);
4961
4962 //
4963 // Separate out the class or namespace part of the
4964 // function name.
4965 //
4966 std::string dataname;
4967
4968 if (!strncmp(scopename.c_str(), "typeinfo for ", sizeof("typeinfo for ")-1)) {
4969 scopename.erase(0, sizeof("typeinfo for ")-1);
4970 } else if (!strncmp(scopename.c_str(), "vtable for ", sizeof("vtable for ")-1)) {
4971 scopename.erase(0, sizeof("vtable for ")-1);
4972 } else {
4973 // See if it is a function
4974 std::string::size_type pos = scopename.rfind('(');
4975 if (pos != std::string::npos) {
4976 return nullptr;
4977 }
4978 // Separate the scope and member name
4979 pos = scopename.rfind(':');
4980 if (pos != std::string::npos) {
4981 if ((pos != 0) && (scopename[pos-1] == ':')) {
4982 dataname = scopename.substr(pos+1);
4983 scopename.erase(pos-1);
4984 }
4985 } else {
4986 scopename.clear();
4988 }
4989 }
4990 //fprintf(stderr, "name: '%s'\n", name.c_str());
4991 // Now we have the class or namespace name, so do the lookup.
4992
4993
4994 DeclId_t d;
4995 if (scopename.size()) {
4997 d = cl.GetDataMember(dataname.c_str());
4998 }
4999 else {
5001 d = gcl.GetDataMember(dataname.c_str());
5002 }
5003 return d;
5004}
5005
5006////////////////////////////////////////////////////////////////////////////////
5007/// NOT IMPLEMENTED.
5008
5010{
5011 Error("GetDataMemberWithValue()", "not implemented");
5012 return nullptr;
5013}
5014
5015////////////////////////////////////////////////////////////////////////////////
5016/// Return pointer to cling DeclId for a data member with a given name.
5017
5019{
5020 // NOT IMPLEMENTED.
5021 Error("GetDataMemberAtAddr()", "not implemented");
5022 return nullptr;
5023}
5024
5025////////////////////////////////////////////////////////////////////////////////
5026/// Return the cling mangled name for a method of a class with parameters
5027/// params (params is a string of actual arguments, not formal ones). If the
5028/// class is 0 the global function list will be searched.
5029
5031 const char* params, Bool_t objectIsConst /* = kFALSE */)
5032{
5035 if (cl) {
5038 &offset);
5039 }
5040 else {
5043 func.SetFunc(&gcl, method, params, &offset);
5044 }
5046 if (!mi) return "";
5047 TString mangled_name( mi->GetMangledName() );
5048 delete mi;
5049 return mangled_name;
5050}
5051
5052////////////////////////////////////////////////////////////////////////////////
5053/// Return the cling mangled name for a method of a class with a certain
5054/// prototype, i.e. "char*,int,float". If the class is 0 the global function
5055/// list will be searched.
5056
5058 const char* proto, Bool_t objectIsConst /* = kFALSE */,
5059 EFunctionMatchMode mode /* = kConversionMatch */)
5060{
5062 if (cl) {
5063 return ((TClingClassInfo*)cl->GetClassInfo())->
5064 GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetMangledName();
5065 }
5067 return gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetMangledName();
5068}
5069
5070////////////////////////////////////////////////////////////////////////////////
5071/// Return pointer to cling interface function for a method of a class with
5072/// parameters params (params is a string of actual arguments, not formal
5073/// ones). If the class is 0 the global function list will be searched.
5074
5076 const char* params, Bool_t objectIsConst /* = kFALSE */)
5077{
5080 if (cl) {
5083 &offset);
5084 }
5085 else {
5088 func.SetFunc(&gcl, method, params, &offset);
5089 }
5090 return (void*) func.InterfaceMethod();
5091}
5092
5093////////////////////////////////////////////////////////////////////////////////
5094/// Return pointer to cling interface function for a method of a class with
5095/// a certain name.
5096
5098{
5100 DeclId_t f;
5102 if (cl) {
5103 f = cl->GetMethod(method).GetDeclId();
5104 }
5105 else {
5107 f = gcl.GetMethod(method).GetDeclId();
5108 }
5109 return f;
5110
5111}
5112
5113////////////////////////////////////////////////////////////////////////////////
5114/// Insert overloads of name in cl to res.
5115
5117 std::vector<DeclId_t>& res) const
5118{
5119 clang::Sema& S = fInterpreter->getSema();
5120 clang::ASTContext& Ctx = S.Context;
5121 const clang::Decl* CtxDecl
5122 = cl ? (const clang::Decl*)((TClingClassInfo*)cl)->GetDeclId():
5123 Ctx.getTranslationUnitDecl();
5124 auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
5125 const clang::DeclContext* DeclCtx = RecDecl;
5126
5127 if (!DeclCtx)
5129 if (!DeclCtx) return;
5130
5131 clang::DeclarationName DName;
5132 // The DeclarationName is funcname, unless it's a ctor or dtor.
5133 // FIXME: or operator or conversion! See enum clang::DeclarationName::NameKind.
5134
5135 if (RecDecl) {
5136 if (RecDecl->getNameAsString() == funcname) {
5137 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5138 DName = Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalType(QT));
5139 } else if (funcname[0] == '~' && RecDecl->getNameAsString() == funcname + 1) {
5140 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5141 DName = Ctx.DeclarationNames.getCXXDestructorName(Ctx.getCanonicalType(QT));
5142 } else {
5143 DName = &Ctx.Idents.get(funcname);
5144 }
5145 } else {
5146 DName = &Ctx.Idents.get(funcname);
5147 }
5148
5149 // NotForRedeclaration: we want to find names in inline namespaces etc.
5150 clang::LookupResult R(S, DName, clang::SourceLocation(),
5151 Sema::LookupOrdinaryName, clang::Sema::NotForRedeclaration);
5152 R.suppressDiagnostics(); // else lookup with NotForRedeclaration will check access etc
5153 S.LookupQualifiedName(R, const_cast<DeclContext*>(DeclCtx));
5154 if (R.empty()) return;
5155 R.resolveKind();
5156 res.reserve(res.size() + (R.end() - R.begin()));
5157 for (clang::LookupResult::iterator IR = R.begin(), ER = R.end();
5158 IR != ER; ++IR) {
5159 if (const clang::FunctionDecl* FD
5160 = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
5161 if (!FD->getDescribedFunctionTemplate()) {
5162 res.push_back(FD);
5163 }
5164 } else if (const auto *USD = llvm::dyn_cast<const clang::UsingShadowDecl>(*IR)) {
5165 // FIXME: multi-level using
5166 if (llvm::isa<clang::FunctionDecl>(USD->getTargetDecl())) {
5167 res.push_back(USD);
5168 }
5169 }
5170 }
5171}
5172
5173////////////////////////////////////////////////////////////////////////////////
5174/// Return pointer to cling interface function for a method of a class with
5175/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5176/// function list will be searched.
5177
5179 const char* proto,
5180 Bool_t objectIsConst /* = kFALSE */,
5181 EFunctionMatchMode mode /* = kConversionMatch */)
5182{
5184 void* f;
5185 if (cl) {
5186 f = ((TClingClassInfo*)cl->GetClassInfo())->
5187 GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).InterfaceMethod();
5188 }
5189 else {
5191 f = gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).InterfaceMethod();
5192 }
5193 return f;
5194}
5195
5196////////////////////////////////////////////////////////////////////////////////
5197/// Return pointer to cling DeclId for a method of a class with
5198/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5199/// function list will be searched.
5200
5202 const char* params,
5203 Bool_t objectIsConst /* = kFALSE */)
5204{
5206 DeclId_t f;
5208 if (cl) {
5209 f = cl->GetMethodWithArgs(method, params, objectIsConst, nullptr /*poffset*/).GetDeclId();
5210 }
5211 else {
5213 f = gcl.GetMethod(method, params, objectIsConst, nullptr /*poffset*/).GetDeclId();
5214 }
5215 return f;
5216}
5217
5218////////////////////////////////////////////////////////////////////////////////
5219/// Return pointer to cling interface function for a method of a class with
5220/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5221/// function list will be searched.
5222
5224 const char* proto,
5225 Bool_t objectIsConst /* = kFALSE */,
5226 EFunctionMatchMode mode /* = kConversionMatch */)
5227{
5229 DeclId_t f;
5231 if (cl) {
5232 f = cl->GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetDeclId();
5233 }
5234 else {
5236 f = gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetDeclId();
5237 }
5238 return f;
5239}
5240
5241////////////////////////////////////////////////////////////////////////////////
5242/// Return pointer to cling interface function for a method of a class with
5243/// a certain name.
5244
5246{
5248 DeclId_t f;
5250 if (cl) {
5251 f = cl->GetFunctionTemplate(name);
5252 }
5253 else {
5255 f = gcl.GetFunctionTemplate(name);
5256 }
5257 return f;
5258
5259}
5260
5261////////////////////////////////////////////////////////////////////////////////
5262/// The 'name' is known to the interpreter, this function returns
5263/// the internal version of this name (usually just resolving typedefs)
5264/// This is used in particular to synchronize between the name used
5265/// by rootcling and by the run-time environment (TClass)
5266/// Return 0 if the name is not known.
5267
5268void TCling::GetInterpreterTypeName(const char* name, std::string &output, Bool_t full)
5269{
5270 output.clear();
5271
5273
5275 if (!cl.IsValid()) {
5276 return ;
5277 }
5278 if (full) {
5280 return;
5281 }
5282 // Well well well, for backward compatibility we need to act a bit too
5283 // much like CINT.
5286
5287 return;
5288}
5289
5290////////////////////////////////////////////////////////////////////////////////
5291/// Execute a global function with arguments params.
5292///
5293/// FIXME: The cint-based version of this code does not check if the
5294/// SetFunc() call works, and does not do any real checking
5295/// for errors from the Exec() call. It did fetch the most
5296/// recent cint security error and return that in error, but
5297/// this does not really translate well to cling/clang. We
5298/// should enhance these interfaces so that we can report
5299/// compilation and runtime errors properly.
5300
5301void TCling::Execute(const char* function, const char* params, int* error)
5302{
5304 if (error) {
5305 *error = TInterpreter::kNoError;
5306 }
5308 Longptr_t offset = 0L;
5310 func.SetFunc(&cl, function, params, &offset);
5311 func.Exec(nullptr);
5312}
5313
5314////////////////////////////////////////////////////////////////////////////////
5315/// Execute a method from class cl with arguments params.
5316///
5317/// FIXME: The cint-based version of this code does not check if the
5318/// SetFunc() call works, and does not do any real checking
5319/// for errors from the Exec() call. It did fetch the most
5320/// recent cint security error and return that in error, but
5321/// this does not really translate well to cling/clang. We
5322/// should enhance these interfaces so that we can report
5323/// compilation and runtime errors properly.
5324
5325void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5326 const char* params, Bool_t objectIsConst, int* error)
5327{
5329 if (error) {
5330 *error = TInterpreter::kNoError;
5331 }
5332 // If the actual class of this object inherits 2nd (or more) from TObject,
5333 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5334 // hence gInterpreter->Execute will improperly correct the offset.
5335 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5336 Longptr_t offset = 0L;
5339 void* address = (void*)((Longptr_t)addr + offset);
5340 func.Exec(address);
5341}
5342
5343////////////////////////////////////////////////////////////////////////////////
5344
5345void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5346 const char* params, int* error)
5347{
5348 Execute(obj,cl,method,params,false,error);
5349}
5350
5351////////////////////////////////////////////////////////////////////////////////
5352/// Execute a method from class cl with the arguments in array params
5353/// (params[0] ... params[n] = array of TObjString parameters).
5354/// Convert the TObjArray array of TObjString parameters to a character
5355/// string of comma separated parameters.
5356/// The parameters of type 'char' are enclosed in double quotes and all
5357/// internal quotes are escaped.
5358
5360 TObjArray* params, int* error)
5361{
5362 if (!method) {
5363 Error("Execute", "No method was defined");
5364 return;
5365 }
5366 TList* argList = method->GetListOfMethodArgs();
5367 // Check number of actual parameters against of expected formal ones
5368
5369 Int_t nparms = argList->LastIndex() + 1;
5370 Int_t argc = params ? params->GetEntries() : 0;
5371
5372 if (argc > nparms) {
5373 Error("Execute","Too many parameters to call %s, got %d but expected at most %d.",method->GetName(),argc,nparms);
5374 return;
5375 }
5376 if (nparms != argc) {
5377 // Let's see if the 'missing' argument are all defaulted.
5378 // if nparms==0 then either we stopped earlier either argc is also zero and we can't reach here.
5379 assert(nparms > 0);
5380
5381 TMethodArg *arg = (TMethodArg *) argList->At( 0 );
5382 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5383 // There is a default value for the first missing
5384 // argument, so we are fine.
5385 } else {
5386 Int_t firstDefault = -1;
5387 for (Int_t i = 0; i < nparms; i ++) {
5388 arg = (TMethodArg *) argList->At( i );
5389 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5390 firstDefault = i;
5391 break;
5392 }
5393 }
5394 if (firstDefault >= 0) {
5395 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);
5396 } else {
5397 Error("Execute","Too few arguments to call %s, got only %d but expected %d.",method->GetName(),argc,nparms);
5398 }
5399 return;
5400 }
5401 }
5402
5403 const char* listpar = "";
5404 TString complete(10);
5405 if (params) {
5406 // Create a character string of parameters from TObjArray
5407 TIter next(params);
5408 for (Int_t i = 0; i < argc; i ++) {
5409 TMethodArg* arg = (TMethodArg*) argList->At(i);
5411 TObjString* nxtpar = (TObjString*) next();
5412 if (i) {
5413 complete += ',';
5414 }
5415 if (strstr(type.TrueName(*fNormalizedCtxt), "char")) {
5416 TString chpar('\"');
5417 chpar += (nxtpar->String()).ReplaceAll("\"", "\\\"");
5418 // At this point we have to check if string contains \\"
5419 // and apply some more sophisticated parser. Not implemented yet!
5420 complete += chpar;
5421 complete += '\"';
5422 }
5423 else {
5424 complete += nxtpar->String();
5425 }
5426 }
5427 listpar = complete.Data();
5428 }
5429
5430 // And now execute it.
5432 if (error) {
5433 *error = TInterpreter::kNoError;
5434 }
5435 // If the actual class of this object inherits 2nd (or more) from TObject,
5436 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5437 // hence gInterpreter->Execute will improperly correct the offset.
5438 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5441 func.Init(*minfo);
5442 func.SetArgs(listpar);
5443 // Now calculate the 'this' pointer offset for the method
5444 // when starting from the class described by cl.
5445 const CXXMethodDecl * mdecl = dyn_cast<CXXMethodDecl>(minfo->GetTargetFunctionDecl());
5446 Longptr_t offset = ((TClingClassInfo*)cl->GetClassInfo())->GetOffset(mdecl);
5447 void* address = (void*)((Longptr_t)addr + offset);
5448 func.Exec(address);
5449}
5450
5451////////////////////////////////////////////////////////////////////////////////
5452
5454 const void* args[] /*=0*/,
5455 int nargs /*=0*/,
5456 void* ret/*= 0*/) const
5457{
5458 if (!method) {
5459 Error("ExecuteWithArgsAndReturn", "No method was defined");
5460 return;
5461 }
5462
5464 TClingCallFunc func(*minfo);
5465 func.ExecWithArgsAndReturn(address, args, nargs, ret);
5466}
5467
5468////////////////////////////////////////////////////////////////////////////////
5469/// Execute a cling macro.
5470
5472{
5474 fCurExecutingMacros.push_back(filename);
5476 fCurExecutingMacros.pop_back();
5477 return result;
5478}
5479
5480////////////////////////////////////////////////////////////////////////////////
5481/// Return the file name of the current un-included interpreted file.
5482/// See the documentation for GetCurrentMacroName().
5483
5485{
5486 Warning("GetTopLevelMacroName", "Must change return type!");
5487 return fCurExecutingMacros.back();
5488}
5489
5490////////////////////////////////////////////////////////////////////////////////
5491/// Return the file name of the currently interpreted file,
5492/// included or not. Example to illustrate the difference between
5493/// GetCurrentMacroName() and GetTopLevelMacroName():
5494/// ~~~ {.cpp}
5495/// void inclfile() {
5496/// std::cout << "In inclfile.C" << std::endl;
5497/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5498/// TCling::GetCurrentMacroName() << std::endl;
5499/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5500/// TCling::GetTopLevelMacroName() << std::endl;
5501/// }
5502/// ~~~
5503/// ~~~ {.cpp}
5504/// void mymacro() {
5505/// std::cout << "In mymacro.C" << std::endl;
5506/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5507/// TCling::GetCurrentMacroName() << std::endl;
5508/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5509/// TCling::GetTopLevelMacroName() << std::endl;
5510/// std::cout << " Now calling inclfile..." << std::endl;
5511/// gInterpreter->ProcessLine(".x inclfile.C");
5512/// }
5513/// ~~~
5514/// Running mymacro.C will print:
5515///
5516/// ~~~ {.cpp}
5517/// root [0] .x mymacro.C
5518/// ~~~
5519/// In mymacro.C
5520/// ~~~ {.cpp}
5521/// TCling::GetCurrentMacroName() returns ./mymacro.C
5522/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5523/// ~~~
5524/// Now calling inclfile...
5525/// In inclfile.h
5526/// ~~~ {.cpp}
5527/// TCling::GetCurrentMacroName() returns inclfile.C
5528/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5529/// ~~~
5530
5532{
5533#if defined(R__MUST_REVISIT)
5534#if R__MUST_REVISIT(6,0)
5535 Warning("GetCurrentMacroName", "Must change return type!");
5536#endif
5537#endif
5538 return fCurExecutingMacros.back();
5539}
5540
5541////////////////////////////////////////////////////////////////////////////////
5542/// Return the absolute type of typeDesc.
5543/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
5544/// You need to use the result immediately before it is being overwritten.
5545
5546const char* TCling::TypeName(const char* typeDesc)
5547{
5548 TTHREAD_TLS_DECL(std::string,t);
5549
5550 if (!strstr(typeDesc, "(*)(")) {
5551 const char *s = strchr(typeDesc, ' ');
5552 const char *template_start = strchr(typeDesc, '<');
5553 if (!strcmp(typeDesc, "long long")) {
5554 t = typeDesc;
5555 }
5556 else if (!strncmp(typeDesc, "unsigned ", s + 1 - typeDesc)) {
5557 t = typeDesc;
5558 }
5559 // s is the position of the second 'word' (if any)
5560 // except in the case of templates where there will be a space
5561 // just before any closing '>': eg.
5562 // TObj<std::vector<UShort_t,__malloc_alloc_template<0> > >*
5563 else if (s && (template_start == nullptr || (s < template_start))) {
5564 t = s + 1;
5565 }
5566 else {
5567 t = typeDesc;
5568 }
5569 }
5570 else {
5571 t = typeDesc;
5572 }
5573 auto l = t.length();
5574 while (l > 0 && (t[l - 1] == '*' || t[l - 1] == '&'))
5575 --l;
5576 t.resize(l);
5577 return t.c_str(); // NOLINT
5578}
5579
5580static bool requiresRootMap(const char* rootmapfile)
5581{
5583
5584 llvm::StringRef libName = llvm::sys::path::filename(rootmapfile);
5585 libName.consume_back(".rootmap");
5586
5587 return !gInterpreter->HasPCMForLibrary(libName.str().c_str());
5588}
5589
5590////////////////////////////////////////////////////////////////////////////////
5591/// Read and parse a rootmapfile in its new format, and return 0 in case of
5592/// success, -1 if the file has already been read, and -3 in case its format
5593/// is the old one (e.g. containing "Library.ClassName"), -4 in case of syntax
5594/// error.
5595
5597{
5598 if (!(rootmapfile && *rootmapfile))
5599 return 0;
5600
5602 return 0; // success
5603
5604 // For "class ", "namespace ", "typedef ", "header ", "enum ", "var " respectively
5605 const std::map<char, unsigned int> keyLenMap = {{'c',6},{'n',10},{'t',8},{'h',7},{'e',5},{'v',4}};
5606
5608#ifdef _MSC_VER
5609 std::replace(rootmapfileNoBackslash.begin(), rootmapfileNoBackslash.end(), '\\', '/');
5610#endif
5611 // Add content of a specific rootmap file
5613 return -1;
5614
5615 // Line 1 is `{ decls }`
5616 std::string lineDirective = std::string("\n#line 2 \"Forward declarations from ") + rootmapfileNoBackslash + "\"\n";
5617
5618 std::ifstream file(rootmapfileNoBackslash);
5619 std::string line;
5620 line.reserve(200);
5621 std::string lib_name;
5622 line.reserve(100);
5623 bool newFormat = false;
5624 while (getline(file, line, '\n')) {
5625 if (!newFormat && (line.compare(0, 8, "Library.") == 0 || line.compare(0, 8, "Declare.") == 0)) {
5626 file.close();
5627 return -3; // old format
5628 }
5629 newFormat = true;
5630
5631 if (line.compare(0, 9, "{ decls }") == 0) {
5632 // forward declarations
5633
5634 while (getline(file, line, '\n')) {
5635 if (line[0] == '[')
5636 break;
5637 if (!uniqueString) {
5638 Error("ReadRootmapFile", "Cannot handle \"{ decls }\" sections in custom rootmap file %s",
5639 rootmapfileNoBackslash.c_str());
5640 return -4;
5641 }
5642 if (!lineDirective.empty())
5643 uniqueString->Append(lineDirective);
5644 uniqueString->Append(line + '\n');
5645 }
5646 }
5647 const char firstChar = line[0];
5648 if (firstChar == '[') {
5649 // new section (library)
5650 auto brpos = line.find(']');
5651 if (brpos == string::npos)
5652 continue;
5653 lib_name = line.substr(1, brpos - 1);
5654 // Remove spaces at the beginning and at the end of the library name
5655 lib_name.erase(lib_name.find_last_not_of(' ') + 1);
5656 lib_name.erase(0, lib_name.find_first_not_of(' '));
5657 if (gDebug > 3) {
5658 TString lib_nameTstr(lib_name.c_str());
5659 TObjArray *tokens = lib_nameTstr.Tokenize(" ");
5660 const char *lib = ((TObjString *)tokens->At(0))->GetName();
5661 const char *wlib = gSystem->DynamicPathName(lib, kTRUE);
5662 if (wlib) {
5663 Info("ReadRootmapFile", "%s: New section for %s", rootmapfile, lib_nameTstr.Data());
5664 } else {
5665 Info("ReadRootmapFile", "%s: Section for %s (library does not exist)", rootmapfile, lib_nameTstr.Data());
5666 }
5667 delete[] wlib;
5668 delete tokens;
5669 }
5670 } else {
5671 auto keyLenIt = keyLenMap.find(firstChar);
5672 if (keyLenIt == keyLenMap.end())
5673 continue;
5674 unsigned int keyLen = keyLenIt->second;
5675 // Do not make a copy, just start after the key
5676 const char *keyname = line.c_str() + keyLen;
5677 if (gDebug > 6)
5678 Info("ReadRootmapFile", "%s: class %s in %s", rootmapfile, keyname, lib_name.c_str());
5680 if (isThere) {
5681 if (lib_name != isThere->GetValue()) { // the same key for two different libs
5682 if (firstChar == 'n') {
5683 if (gDebug > 3)
5684 Info("ReadRootmapFile",
5685 "While processing %s, namespace %s was found to be associated to %s although it is already "
5686 "associated to %s",
5687 rootmapfile, keyname, lib_name.c_str(), isThere->GetValue());
5688 } else if (firstChar == 'h') { // it is a header: add the libname to the list of libs to be loaded.
5689 lib_name += " ";
5690 lib_name += isThere->GetValue();
5691 fMapfile->SetValue(keyname, lib_name.c_str());
5692 } else if (!TClassEdit::IsSTLCont(keyname)) {
5693 Warning("ReadRootmapFile",
5694 "While processing %s, %s %s was found to be associated to %s although it is already "
5695 "associated to %s",
5696 rootmapfile, line.substr(0, keyLen - 1).c_str(), keyname, lib_name.c_str(),
5697 isThere->GetValue());
5698 }
5699 } else { // the same key for the same lib
5700 if (gDebug > 3)
5701 Info("ReadRootmapFile", "While processing %s, key %s was found to be already defined for %s",
5702 rootmapfile, keyname, lib_name.c_str());
5703 }
5704 } else {
5705 fMapfile->SetValue(keyname, lib_name.c_str());
5706 }
5707 }
5708 }
5709 file.close();
5710 return 0;
5711}
5712
5713////////////////////////////////////////////////////////////////////////////////
5714/// Create a resource table and read the (possibly) three resource files,
5715/// i.e. `$ROOTSYS/etc/system<name>` (or `ROOTETCDIR/system<name>`), `$HOME/<name>`
5716/// and `$PWD/<name>`. ROOT always reads ".rootrc" (in TROOT::InitSystem()). You
5717/// can read additional user defined resource files by creating additional TEnv
5718/// objects. By setting the shell variable ROOTENV_NO_HOME=1 the reading of
5719/// the `$HOME/<name>` resource file will be skipped. This might be useful in
5720/// case the home directory resides on an automounted remote file system
5721/// and one wants to avoid the file system from being mounted.
5722
5724{
5725 assert(requiresRootMap(name) && "We have a module!");
5726
5727 if (!requiresRootMap(name))
5728 return;
5729
5731
5733
5734 TString sname = "system";
5735 sname += name;
5737
5739 if (ret == -3) // old format
5741 delete [] s;
5742 if (!gSystem->Getenv("ROOTENV_NO_HOME")) {
5744 ret = ReadRootmapFile(s);
5745 if (ret == -3) // old format
5747 delete [] s;
5750 if (ret == -3) // old format
5752 }
5753 } else {
5755 if (ret == -3) // old format
5757 }
5759}
5760
5761
5762namespace {
5763 using namespace clang;
5764
5765 class ExtVisibleStorageAdder: public RecursiveASTVisitor<ExtVisibleStorageAdder>{
5766 // This class is to be considered an helper for AutoLoading.
5767 // It is a recursive visitor is used to inspect namespaces and specializations
5768 // coming from forward declarations in rootmaps and to set the external visible
5769 // storage flag for them.
5770 public:
5771 ExtVisibleStorageAdder(std::unordered_set<const NamespaceDecl*>& nsSet): fNSSet(nsSet) {};
5772 bool VisitNamespaceDecl(NamespaceDecl* nsDecl) {
5773 // We want to enable the external lookup for this namespace
5774 // because it may shadow the lookup of other names contained
5775 // in that namespace
5776
5777 nsDecl->setHasExternalVisibleStorage();
5778 fNSSet.insert(nsDecl);
5779 return true;
5780 }
5782 // We want to enable the external lookup for this specialization
5783 // because we can provide a definition for it!
5784 if (specDecl->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
5785 //SpecSet.insert(specDecl);
5786 specDecl->setHasExternalLexicalStorage();
5787
5788 // No need to recurse. On the contrary, recursing is actively harmful:
5789 // NOTE: must not recurse to prevent this visitor from triggering loading from
5790 // the external AST source (i.e. autoloading). This would be triggered right here,
5791 // before autoloading is even set up, as rootmap file parsing happens before that.
5792 // Even if autoloading is off and has no effect, triggering loading from external
5793 // AST source resets the flag setHasExternalLexicalStorage(), hiding this specialization
5794 // from subsequent autoloads!
5795 return false;
5796 }
5797 private:
5798 std::unordered_set<const NamespaceDecl*>& fNSSet;
5799 };
5800}
5801
5802////////////////////////////////////////////////////////////////////////////////
5803/// Load map between class and library. If rootmapfile is specified a
5804/// specific rootmap file can be added (typically used by ACLiC).
5805/// In case of error -1 is returned, 0 otherwise.
5806/// The interpreter uses this information to automatically load the shared
5807/// library for a class (autoload mechanism), see the AutoLoad() methods below.
5808
5810{
5812 return 0;
5813
5815
5816 // open the [system].rootmap files
5817 if (!fMapfile) {
5818 fMapfile = new TEnv();
5822 InitRootmapFile(".rootmap");
5823 }
5824
5825 // Prepare a list of all forward declarations for cling
5826 // For some experiments it is easily as big as 500k characters. To be on the
5827 // safe side, we go for 1M.
5828 TUniqueString uniqueString(1048576);
5829
5830 // Load all rootmap files in the dynamic load path ((DY)LD_LIBRARY_PATH, etc.).
5831 // A rootmap file must end with the string ".rootmap".
5833 if (ldpath != fRootmapLoadPath) {
5835#ifdef WIN32
5836 TObjArray* paths = ldpath.Tokenize(";");
5837#else
5838 TObjArray* paths = ldpath.Tokenize(":");
5839#endif
5840 TString d;
5841 for (Int_t i = 0; i < paths->GetEntriesFast(); i++) {
5842 d = ((TObjString *)paths->At(i))->GetString();
5843 // check if directory already scanned
5844 Int_t skip = 0;
5845 for (Int_t j = 0; j < i; j++) {
5846 TString pd = ((TObjString *)paths->At(j))->GetString();
5847 if (pd == d) {
5848 skip++;
5849 break;
5850 }
5851 }
5852 if (!skip) {
5853 void* dirp = gSystem->OpenDirectory(d);
5854 if (dirp) {
5855 if (gDebug > 3) {
5856 Info("LoadLibraryMap", "%s", d.Data());
5857 }
5858 const char* f1;
5859 while ((f1 = gSystem->GetDirEntry(dirp))) {
5860 TString f = f1;
5861 if (f.EndsWith(".rootmap")) {
5862 TString p;
5863 p = d + "/" + f;
5865 if (!fRootmapFiles->FindObject(f) && f != ".rootmap") {
5866 if (gDebug > 4) {
5867 Info("LoadLibraryMap", " rootmap file: %s", p.Data());
5868 }
5870
5871 if (ret == 0)
5872 fRootmapFiles->Add(new TNamed(gSystem->BaseName(f), p.Data()));
5873 if (ret == -3) {
5874 // old format
5876 fRootmapFiles->Add(new TNamed(f, p));
5877 }
5878 }
5879 // else {
5880 // fprintf(stderr,"Reject %s because %s is already there\n",p.Data(),f.Data());
5881 // fRootmapFiles->FindObject(f)->ls();
5882 // }
5883 }
5884 }
5885 if (f.BeginsWith("rootmap")) {
5886 TString p;
5887 p = d + "/" + f;
5888 FileStat_t stat;
5889 if (gSystem->GetPathInfo(p, stat) == 0 && R_ISREG(stat.fMode)) {
5890 Warning("LoadLibraryMap", "please rename %s to end with \".rootmap\"", p.Data());
5891 }
5892 }
5893 }
5894 }
5896 }
5897 }
5898 delete paths;
5899 if (fMapfile->GetTable() && !fMapfile->GetTable()->GetEntries()) {
5900 return -1;
5901 }
5902 }
5903 if (rootmapfile && *rootmapfile) {
5905 if (res == 0) {
5906 //TString p = gSystem->ConcatFileName(gSystem->pwd(), rootmapfile);
5907 //fRootmapFiles->Add(new TNamed(gSystem->BaseName(rootmapfile), p.Data()));
5909 }
5910 else if (res == -3) {
5911 // old format
5916 }
5917 }
5918 TEnvRec* rec;
5919 TIter next(fMapfile->GetTable());
5920 while ((rec = (TEnvRec*) next())) {
5921 TString cls = rec->GetName();
5922 if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
5923 // get the first lib from the list of lib and dependent libs
5924 TString libs = rec->GetValue();
5925 if (libs == "") {
5926 continue;
5927 }
5928 TString delim(" ");
5929 TObjArray* tokens = libs.Tokenize(delim);
5930 const char* lib = ((TObjString*)tokens->At(0))->GetName();
5931 // convert "@@" to "::", we used "@@" because TEnv
5932 // considers "::" a terminator
5933 cls.Remove(0, 8);
5934 cls.ReplaceAll("@@", "::");
5935 // convert "-" to " ", since class names may have
5936 // blanks and TEnv considers a blank a terminator
5937 cls.ReplaceAll("-", " ");
5938 if (gDebug > 6) {
5939 const char* wlib = gSystem->DynamicPathName(lib, kTRUE);
5940 if (wlib) {
5941 Info("LoadLibraryMap", "class %s in %s", cls.Data(), wlib);
5942 }
5943 else {
5944 Info("LoadLibraryMap", "class %s in %s (library does not exist)", cls.Data(), lib);
5945 }
5946 delete[] wlib;
5947 }
5948 delete tokens;
5949 }
5950 else if (!strncmp(cls.Data(), "Declare.", 8) && cls.Length() > 8) {
5951 cls.Remove(0, 8);
5952 // convert "-" to " ", since class names may have
5953 // blanks and TEnv considers a blank a terminator
5954 cls.ReplaceAll("-", " ");
5955 fInterpreter->declare(cls.Data());
5956 }
5957 }
5958
5959 // Process the forward declarations collected
5960 cling::Transaction* T = nullptr;
5961 auto compRes= fInterpreter->declare(uniqueString.Data(), &T);
5962 assert(cling::Interpreter::kSuccess == compRes && "A declaration in a rootmap could not be compiled");
5963
5964 if (compRes!=cling::Interpreter::kSuccess){
5965 Warning("LoadLibraryMap",
5966 "Problems in %s declaring '%s' were encountered.", rootmapfile, uniqueString.Data()) ;
5967 }
5968
5969 if (T) {
5970 ExtVisibleStorageAdder evsAdder(fNSFromRootmaps);
5971 for (auto declIt = T->decls_begin(); declIt < T->decls_end(); ++declIt) {
5972 if (declIt->m_DGR.isSingleDecl()) {
5973 if (Decl* D = declIt->m_DGR.getSingleDecl()) {
5974 if (clang::isa<TagDecl>(D) || clang::isa<NamespaceDecl>(D)) {
5975 evsAdder.TraverseDecl(D);
5976 }
5977 }
5978 }
5979 }
5980 }
5981
5982 // clear duplicates
5983
5984 return 0;
5985}
5986
5987////////////////////////////////////////////////////////////////////////////////
5988/// Scan again along the dynamic path for library maps. Entries for the loaded
5989/// shared libraries are unloaded first. This can be useful after reseting
5990/// the dynamic path through TSystem::SetDynamicPath()
5991/// In case of error -1 is returned, 0 otherwise.
5992
5999
6000////////////////////////////////////////////////////////////////////////////////
6001/// Reload the library map entries coming from all the loaded shared libraries,
6002/// after first unloading the current ones.
6003/// In case of error -1 is returned, 0 otherwise.
6004
6006{
6008 const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
6009 const Int_t nrSharedLibs = sharedLibL->GetEntriesFast();
6010 for (Int_t ilib = 0; ilib < nrSharedLibs; ilib++) {
6011 const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
6014 if (ret < 0) {
6015 continue;
6016 }
6018 if (sharedLibBaseStr.EndsWith(".dll")) {
6019 rootMapBaseStr.ReplaceAll(".dll", "");
6020 }
6021 else if (sharedLibBaseStr.EndsWith(".DLL")) {
6022 rootMapBaseStr.ReplaceAll(".DLL", "");
6023 }
6024 else if (sharedLibBaseStr.EndsWith(".so")) {
6025 rootMapBaseStr.ReplaceAll(".so", "");
6026 }
6027 else if (sharedLibBaseStr.EndsWith(".sl")) {
6028 rootMapBaseStr.ReplaceAll(".sl", "");
6029 }
6030 else if (sharedLibBaseStr.EndsWith(".dl")) {
6031 rootMapBaseStr.ReplaceAll(".dl", "");
6032 }
6033 else if (sharedLibBaseStr.EndsWith(".a")) {
6034 rootMapBaseStr.ReplaceAll(".a", "");
6035 }
6036 else {
6037 Error("ReloadAllSharedLibraryMaps", "Unknown library type %s", sharedLibBaseStr.Data());
6038 delete sharedLibL;
6039 return -1;
6040 }
6041 rootMapBaseStr += ".rootmap";
6043 if (!rootMap) {
6044 Error("ReloadAllSharedLibraryMaps", "Could not find rootmap %s in path", rootMapBaseStr.Data());
6045 delete[] rootMap;
6046 delete sharedLibL;
6047 return -1;
6048 }
6049 const Int_t status = LoadLibraryMap(rootMap);
6050 if (status < 0) {
6051 Error("ReloadAllSharedLibraryMaps", "Error loading map %s", rootMap);
6052 delete[] rootMap;
6053 delete sharedLibL;
6054 return -1;
6055 }
6056 delete[] rootMap;
6057 }
6058 delete sharedLibL;
6059 return 0;
6060}
6061
6062////////////////////////////////////////////////////////////////////////////////
6063/// Unload the library map entries coming from all the loaded shared libraries.
6064/// Returns 0 if succesful
6065
6067{
6069 const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
6070 for (Int_t ilib = 0; ilib < sharedLibL->GetEntriesFast(); ilib++) {
6071 const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
6074 }
6075 delete sharedLibL;
6076 return 0;
6077}
6078
6079////////////////////////////////////////////////////////////////////////////////
6080/// Unload library map entries coming from the specified library.
6081/// Returns -1 in case no entries for the specified library were found,
6082/// 0 otherwise.
6083
6085{
6086 if (!fMapfile || !library || !*library) {
6087 return 0;
6088 }
6090 Ssiz_t idx = libname.Last('.');
6091 if (idx != kNPOS) {
6092 libname.Remove(idx);
6093 }
6094 size_t len = libname.Length();
6095 TEnvRec *rec;
6096 TIter next(fMapfile->GetTable());
6098 Int_t ret = 0;
6099 while ((rec = (TEnvRec *) next())) {
6100 TString cls = rec->GetName();
6101 if (cls.Length() > 2) {
6102 // get the first lib from the list of lib and dependent libs
6103 TString libs = rec->GetValue();
6104 if (libs == "") {
6105 continue;
6106 }
6107 TString delim(" ");
6108 TObjArray* tokens = libs.Tokenize(delim);
6109 const char* lib = ((TObjString *)tokens->At(0))->GetName();
6110 if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
6111 // convert "@@" to "::", we used "@@" because TEnv
6112 // considers "::" a terminator
6113 cls.Remove(0, 8);
6114 cls.ReplaceAll("@@", "::");
6115 // convert "-" to " ", since class names may have
6116 // blanks and TEnv considers a blank a terminator
6117 cls.ReplaceAll("-", " ");
6118 }
6119 if (!strncmp(lib, libname.Data(), len)) {
6120 if (fMapfile->GetTable()->Remove(rec) == nullptr) {
6121 Error("UnloadLibraryMap", "entry for <%s, %s> not found in library map table", cls.Data(), lib);
6122 ret = -1;
6123 }
6124 }
6125 delete tokens;
6126 }
6127 }
6128 if (ret >= 0) {
6130 if (!library_rootmap.EndsWith(".rootmap"))
6131 library_rootmap.Append(".rootmap");
6132 TNamed* mfile = nullptr;
6135 delete mfile;
6136 }
6138 }
6139 return ret;
6140}
6141
6142////////////////////////////////////////////////////////////////////////////////
6143/// Register the AutoLoading information for a class.
6144/// libs is a space separated list of libraries.
6145
6146Int_t TCling::SetClassSharedLibs(const char *cls, const char *libs)
6147{
6148 if (!cls || !*cls)
6149 return 0;
6150
6151 TString key = TString("Library.") + cls;
6152 // convert "::" to "@@", we used "@@" because TEnv
6153 // considers "::" a terminator
6154 key.ReplaceAll("::", "@@");
6155 // convert "-" to " ", since class names may have
6156 // blanks and TEnv considers a blank a terminator
6157 key.ReplaceAll(" ", "-");
6158
6160 if (!fMapfile) {
6161 fMapfile = new TEnv();
6163
6166
6167 InitRootmapFile(".rootmap");
6168 }
6169 //fMapfile->SetValue(key, libs);
6171 return 1;
6172}
6173
6174////////////////////////////////////////////////////////////////////////////////
6175/// Demangle the name (from the typeinfo) and then request the class
6176/// via the usual name based interface (TClass::GetClass).
6177
6178TClass *TCling::GetClass(const std::type_info& typeinfo, Bool_t load) const
6179{
6180 int err = 0;
6182 if (err) return nullptr;
6185 return theClass;
6186}
6187
6188////////////////////////////////////////////////////////////////////////////////
6189/// Load library containing the specified class. Returns 0 in case of error
6190/// and 1 in case if success.
6191
6192Int_t TCling::AutoLoad(const std::type_info& typeinfo, Bool_t knowDictNotLoaded /* = kFALSE */)
6193{
6194 assert(IsClassAutoLoadingEnabled() && "Calling when AutoLoading is off!");
6195
6196 int err = 0;
6198 if (err) {
6199 return 0;
6200 }
6201
6202 std::string demangled_name(demangled_name_c);
6204
6205 // AutoLoad expects (because TClass::GetClass already prepares it that way) a
6206 // shortened name.
6209
6210 // No need to worry about typedef, they aren't any ... but there are
6211 // inlined namespaces ...
6212
6214 if (result == 0) {
6217 }
6218
6219 return result;
6220}
6221
6222////////////////////////////////////////////////////////////////////////////////
6223// Get the list of 'published'/'known' library for the class and load them.
6225{
6226 Int_t status = 0;
6227
6228 // lookup class to find list of dependent libraries
6230 if (!deplibs.IsNull()) {
6231 TString delim(" ");
6232 TObjArray* tokens = deplibs.Tokenize(delim);
6233 for (Int_t i = (tokens->GetEntriesFast() - 1); i > 0; --i) {
6234 const char* deplib = ((TObjString*)tokens->At(i))->GetName();
6235 if (gROOT->LoadClass(cls, deplib) == 0) {
6236 if (gDebug > 0) {
6237 gCling->Info("TCling::AutoLoad",
6238 "loaded dependent library %s for %s", deplib, cls);
6239 }
6240 }
6241 else {
6242 gCling->Error("TCling::AutoLoad",
6243 "failure loading dependent library %s for %s",
6244 deplib, cls);
6245 }
6246 }
6247 const char* lib = ((TObjString*)tokens->At(0))->GetName();
6248 if (lib && lib[0]) {
6249 if (gROOT->LoadClass(cls, lib) == 0) {
6250 if (gDebug > 0) {
6251 gCling->Info("TCling::AutoLoad",
6252 "loaded library %s for %s", lib, cls);
6253 }
6254 status = 1;
6255 }
6256 else {
6257 gCling->Error("TCling::AutoLoad",
6258 "failure loading library %s for %s", lib, cls);
6259 }
6260 }
6261 delete tokens;
6262 }
6263
6264 return status;
6265}
6266
6267////////////////////////////////////////////////////////////////////////////////
6268// Iterate through the data member of the class (either through the TProtoClass
6269// or through Cling) and trigger, recursively, the loading the necessary libraries.
6270// \note `cls` is expected to be already normalized!
6271// \returns 1 on success.
6272Int_t TCling::DeepAutoLoadImpl(const char *cls, std::unordered_set<std::string> &visited,
6273 bool nameIsNormalized)
6274{
6275 // Try to insert; if insertion failed because the entry existed, DeepAutoLoadImpl()
6276 // has previously (within the same call to `AutoLoad()`) tried to load this class
6277 // and we are done, whether success or not, as it won't work better now than before,
6278 // because there is no additional information now compared to before.
6279 if (!visited.insert(std::string(cls)).second)
6280 return 1;
6281
6282 if (ShallowAutoLoadImpl(cls) == 0) {
6283 // If ShallowAutoLoadImpl() has an error, we have an error.
6284 return 0;
6285 }
6286
6287 // Now look through the TProtoClass to load the required library/dictionary
6289 for (auto element : proto->GetData()) {
6290 if (element->IsBasic())
6291 continue;
6292 const char *subtypename = element->GetTypeName();
6294 // Failure to load a dictionary is not (quite) a failure load
6295 // the top-level library. If we return false here, then
6296 // we would end up in a situation where the library and thus
6297 // the dictionary is loaded for "cls" but the TClass is
6298 // not created and/or marked as unavailable (in case where
6299 // AutoLoad is called from TClass::GetClass).
6300 DeepAutoLoadImpl(subtypename, visited, true /*normalized*/);
6301 }
6302 }
6303 return 1;
6304 }
6305
6306 // We found no TProtoClass for cls.
6307 auto classinfo = gInterpreter->ClassInfo_Factory(cls);
6308 if (classinfo && gInterpreter->ClassInfo_IsValid(classinfo)
6309 && !(gInterpreter->ClassInfo_Property(classinfo) & kIsEnum))
6310 {
6312 while (gInterpreter->DataMemberInfo_Next(memberinfo)) {
6313 if (gInterpreter->DataMemberInfo_TypeProperty(memberinfo) & ::kIsFundamental)
6314 continue;
6315 auto membertypename = TClassEdit::GetLong64_Name(gInterpreter->TypeName(gInterpreter->DataMemberInfo_TypeTrueName(memberinfo)));
6317 // Failure to load a dictionary is not (quite) a failure load
6318 // the top-level library. See detailed comment in the TProtoClass
6319 // branch (above).
6320 (void)DeepAutoLoadImpl(membertypename.c_str(), visited, true /*normalized*/);
6321 }
6322 }
6323 gInterpreter->DataMemberInfo_Delete(memberinfo);
6324 }
6325 gInterpreter->ClassInfo_Delete(classinfo);
6326 return 1;
6327}
6328
6329////////////////////////////////////////////////////////////////////////////////
6330/// Load library containing the specified class. Returns 0 in case of error
6331/// and 1 in case if success.
6332
6334{
6335 // Prevent update to IsClassAutoloading between our check and our actions.
6337
6338 // TClass::GetClass explicitly calls gInterpreter->AutoLoad. When called from
6339 // rootcling (in *_rdict.pcm file generation) it is a no op.
6340 // FIXME: We should avoid calling autoload when we know we are not supposed
6341 // to and transform this check into an assert.
6343 // Never load any library from rootcling/genreflex.
6344 if (gDebug > 2) {
6345 Info("TCling::AutoLoad", "Explicitly disabled (the class name is %s)", cls);
6346 }
6347 return 0;
6348 }
6349
6350 assert(IsClassAutoLoadingEnabled() && "Calling when AutoLoading is off!");
6351
6353
6355 // The library is already loaded as the class's dictionary is known.
6356 // Return success.
6357 // Note: the name (cls) is expected to be normalized as it comes either
6358 // from a callbacks (that can/should calculate the normalized name from the
6359 // decl) or from TClass::GetClass (which does also calculate the normalized
6360 // name).
6361 return 1;
6362 }
6363
6364 if (gDebug > 2) {
6365 Info("TCling::AutoLoad",
6366 "Trying to autoload for %s", cls);
6367 }
6368
6369 if (!gROOT || !gInterpreter || gROOT->TestBit(TObject::kInvalidObject)) {
6370 if (gDebug > 2) {
6371 Info("TCling::AutoLoad",
6372 "Disabled due to gROOT or gInterpreter being invalid/not ready (the class name is %s)", cls);
6373 }
6374 return 0;
6375 }
6376 // Prevent the recursion when the library dictionary are loaded.
6378 // Try using externally provided callback first.
6379 if (fAutoLoadCallBack) {
6381 if (success)
6382 return success;
6383 }
6384
6385 // During the 'Deep' part of the search we will call GetClassSharedLibsForModule
6386 // (when module are enabled) which might end up calling AutoParsing but
6387 // that should only be for the cases where the library has no generated pcm
6388 // and in that case a rootmap should be available.
6389 // This avoids a very costly operation (for generally no gain) but reduce the
6390 // quality of the search (i.e. bad in case of library with no pcm and no rootmap
6391 // file).
6393 std::unordered_set<std::string> visited;
6394 return DeepAutoLoadImpl(cls, visited, false /*normalized*/);
6395}
6396
6397////////////////////////////////////////////////////////////////////////////////
6398/// Parse the payload or header.
6399
6400static cling::Interpreter::CompilationResult ExecAutoParse(const char *what,
6401 Bool_t header,
6402 cling::Interpreter *interpreter)
6403{
6404 std::string code = gNonInterpreterClassDef ;
6405 if (!header) {
6406 // This is the complete header file content and not the
6407 // name of a header.
6408 code += what;
6409
6410 } else {
6411 code += ("#include \"");
6412 code += what;
6413 code += "\"\n";
6414 }
6415 code += ("#ifdef __ROOTCLING__\n"
6416 "#undef __ROOTCLING__\n"
6418 "#endif");
6419
6420 cling::Interpreter::CompilationResult cr;
6421 {
6422 // scope within which diagnostics are de-activated
6423 // For now we disable diagnostics because we saw them already at
6424 // dictionary generation time. That won't be an issue with the PCMs.
6425
6426 Sema &SemaR = interpreter->getSema();
6428 clangDiagSuppr diagSuppr(SemaR.getDiagnostics());
6429
6430 #if defined(R__MUST_REVISIT)
6431 #if R__MUST_REVISIT(6,2)
6432 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
6433 #endif
6434 #endif
6435
6436 cr = interpreter->parseForModule(code);
6437 }
6438 return cr;
6439}
6440
6441////////////////////////////////////////////////////////////////////////////////
6442/// Helper routine for TCling::AutoParse implementing the actual call to the
6443/// parser and looping over template parameters (if
6444/// any) and when they don't have a registered header to autoparse,
6445/// recurse over their template parameters.
6446///
6447/// Returns the number of header parsed.
6448
6450{
6451 // We assume the lock has already been taken.
6452 // R__LOCKGUARD(gInterpreterMutex);
6453
6455 unsigned long offset = 0;
6456 if (strncmp(cls, "const ", 6) == 0) {
6457 offset = 6;
6458 }
6459
6460 // Loop on the possible autoparse keys
6461 bool skipFirstEntry = false;
6462 std::vector<std::string> autoparseKeys;
6463 if (strchr(cls, '<')) {
6464 int nestedLoc = 0;
6466 // Check if we can skip the name of the template in the autoparses
6467 // Take all the scopes one by one. If all of them are in the AST, we do not
6468 // need to autoparse for that particular template.
6469 if (!autoparseKeys.empty() && !autoparseKeys[0].empty()) {
6470 // autoparseKeys[0] is empty when the input is not a template instance.
6471 // The case strchr(cls, '<') != 0 but still not a template instance can
6472 // happens 'just' for string (GetSplit replaces the template by the short name
6473 // and then use that for thew splitting)
6475 auto tokens = templateName.Tokenize("::");
6476 clang::NamedDecl* previousScopeAsNamedDecl = nullptr;
6477 clang::DeclContext* previousScopeAsContext = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
6479 previousScopeAsContext = fInterpreter->getSema().getStdNamespace();
6480 auto nTokens = tokens->GetEntriesFast();
6481 for (Int_t tk = 0; tk < nTokens; ++tk) {
6482 auto scopeObj = tokens->UncheckedAt(tk);
6483 auto scopeName = ((TObjString*) scopeObj)->String().Data();
6484 previousScopeAsNamedDecl = cling::utils::Lookup::Named(&fInterpreter->getSema(), scopeName, previousScopeAsContext);
6485 // Check if we have multiple nodes in the AST with this name
6486 if ((clang::NamedDecl*)-1 == previousScopeAsNamedDecl) break;
6487 previousScopeAsContext = llvm::dyn_cast_or_null<clang::DeclContext>(previousScopeAsNamedDecl);
6488 if (!previousScopeAsContext) break; // this is not a context
6489 }
6490 delete tokens;
6491 // Now, let's check if the last scope, the template, has a definition, i.e. it's not a fwd decl
6492 if ((clang::NamedDecl*)-1 != previousScopeAsNamedDecl) {
6493 if (auto templateDecl = llvm::dyn_cast_or_null<clang::ClassTemplateDecl>(previousScopeAsNamedDecl)) {
6494 if (auto templatedDecl = templateDecl->getTemplatedDecl()) {
6495 skipFirstEntry = templatedDecl->hasDefinition();
6496 }
6497 }
6498 }
6499
6500 }
6501 }
6502 if (topLevel) autoparseKeys.emplace_back(cls);
6503
6504 for (const auto & apKeyStr : autoparseKeys) {
6505 if (skipFirstEntry) {
6506 skipFirstEntry=false;
6507 continue;
6508 }
6509 if (apKeyStr.empty()) continue;
6510 const char *apKey = apKeyStr.c_str();
6512 // If the class was not looked up
6513 if (gDebug > 1) {
6514 Info("TCling::AutoParse",
6515 "Starting autoparse for %s\n", apKey);
6516 }
6517 if (fLookedUpClasses.insert(normNameHash).second) {
6518 auto const &iter = fClassesHeadersMap.find(normNameHash);
6519 if (iter != fClassesHeadersMap.end()) {
6520 const cling::Transaction *T = fInterpreter->getCurrentTransaction();
6522 auto const &hNamesPtrs = iter->second;
6523 if (gDebug > 1) {
6524 Info("TCling::AutoParse",
6525 "We can proceed for %s. We have %s headers.", apKey, std::to_string(hNamesPtrs.size()).c_str());
6526 }
6527 for (auto & hName : hNamesPtrs) {
6528 if (fParsedPayloadsAddresses.count(hName) == 1) continue;
6529 if (0 != fPayloads.count(normNameHash)) {
6530 float initRSSval=0.f, initVSIZEval=0.f;
6531 (void) initRSSval; // Avoid unused var warning
6532 (void) initVSIZEval;
6533 if (gDebug > 0) {
6534 Info("AutoParse",
6535 "Parsing full payload for %s", apKey);
6538 initRSSval = 1e-3*info.fMemResident;
6539 initVSIZEval = 1e-3*info.fMemVirtual;
6540 }
6542 if (cRes != cling::Interpreter::kSuccess) {
6543 if (hName[0] == '\n')
6544 Error("AutoParse", "Error parsing payload code for class %s with content:\n%s", apKey, hName);
6545 } else {
6548 if (gDebug > 0){
6551 float endRSSval = 1e-3*info.fMemResident;
6552 float endVSIZEval = 1e-3*info.fMemVirtual;
6553 Info("Autoparse", ">>> RSS key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initRSSval, endRSSval, endRSSval-initRSSval);
6554 Info("Autoparse", ">>> VSIZE key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initVSIZEval, endVSIZEval, endVSIZEval-initVSIZEval);
6555 }
6556 }
6557 } else if (!IsLoaded(hName)) {
6558 if (gDebug > 0) {
6559 Info("AutoParse",
6560 "Parsing single header %s", hName);
6561 }
6563 if (cRes != cling::Interpreter::kSuccess) {
6564 Error("AutoParse", "Error parsing headerfile %s for class %s.", hName, apKey);
6565 } else {
6567 }
6568 }
6569 }
6570 }
6571 else {
6572 // There is no header registered for this class, if this a
6573 // template, it will be instantiated if/when it is requested
6574 // and if we do no load/parse its components we might end up
6575 // not using an eventual specialization.
6576 if (strchr(apKey, '<')) {
6578 }
6579 }
6580 }
6581 }
6582
6583 return nHheadersParsed;
6584
6585}
6586
6587////////////////////////////////////////////////////////////////////////////////
6588/// Parse the headers relative to the class
6589/// Returns 1 in case of success, 0 in case of failure
6590
6592{
6593 if (llvm::StringRef(cls).contains("(lambda)"))
6594 return 0;
6595
6598 return AutoLoad(cls);
6599 } else {
6600 return 0;
6601 }
6602 }
6603
6605
6606 if (gDebug > 1) {
6607 Info("TCling::AutoParse",
6608 "Trying to autoparse for %s", cls);
6609 }
6610
6611 // The catalogue of headers is in the dictionary
6613 && !gClassTable->GetDictNorm(cls)) {
6614 // Need RAII against recursive (dictionary payload) parsing (ROOT-8445).
6616 fInterpreter->getSema());
6617 AutoLoad(cls, true /*knowDictNotLoaded*/);
6618 }
6619
6620 // Prevent the recursion when the library dictionary are loaded.
6622
6623 // No recursive header parsing on demand; we require headers to be standalone.
6625
6626 Int_t nHheadersParsed = AutoParseImplRecurse(cls,/*topLevel=*/ true);
6627
6629
6630 return nHheadersParsed > 0 ? 1 : 0;
6631}
6632
6633// This is a function which gets callback from cling when DynamicLibraryManager->loadLibrary failed for some reason.
6634// Try to solve the problem by AutoLoading. Return true when AutoLoading success, return
6635// false if not.
6636bool TCling::LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
6637{
6639 if (errMsg.contains("undefined symbol: ")) {
6640 // This branch is taken when the callback was from DynamicLibraryManager::loadLibrary
6641 std::string mangled_name = std::string(errMsg.split("undefined symbol: ").second);
6642 void* res = ((TCling*)gCling)->LazyFunctionCreatorAutoload(mangled_name);
6643 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
6644 if (res && DLM && (DLM->loadLibrary(libStem, permanent, resolved) == cling::DynamicLibraryManager::kLoadLibSuccess))
6645 // Return success when LazyFunctionCreatorAutoload could find mangled_name
6646 return true;
6647 } else {
6648 // The callback is from IncrementalExecutor::diagnoseUnresolvedSymbols
6650 return true;
6651 }
6652
6653 return false;
6654}
6655
6656////////////////////////////////////////////////////////////////////////////////
6657/// Autoload a library based on a missing symbol.
6658
6661
6662 // We have already loaded the library.
6663 if (void* Addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(dlsym_mangled_name))
6664 return Addr;
6665
6666 const cling::DynamicLibraryManager &DLM = *GetInterpreterImpl()->getDynamicLibraryManager();
6668
6669 auto LibLoader = [](const std::string& LibName) -> bool {
6670 if (gSystem->Load(LibName.c_str(), "", false) < 0) {
6671 ::Error("TCling__LazyFunctionCreatorAutoloadForModule",
6672 "Failed to load library %s", LibName.c_str());
6673 return false;
6674 }
6675 return true; //success.
6676 };
6677
6678 std::string libName = DLM.searchLibrariesForSymbol(mangled_name,
6679 /*searchSystem=*/ true);
6680
6681 assert(!llvm::StringRef(libName).starts_with("libNew") && "We must not resolve symbols from libNew!");
6682
6683 if (libName.empty())
6684 return nullptr;
6685
6686 if (!LibLoader(libName))
6687 return nullptr;
6688
6689 return llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(dlsym_mangled_name);
6690}
6691
6692////////////////////////////////////////////////////////////////////////////////
6693
6695{
6696 return fNSFromRootmaps.count(nsDecl) != 0;
6697}
6698
6699////////////////////////////////////////////////////////////////////////////////
6700/// Internal function. Actually do the update of the ClassInfo when seeing
6701// new TagDecl or NamespaceDecl.
6702void TCling::RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
6703{
6704
6706 if (cci) {
6707 // If we only had a forward declaration then update the
6708 // TClingClassInfo with the definition if we have it now.
6709 const NamedDecl *oldDef = llvm::dyn_cast_or_null<NamedDecl>(cci->GetDecl());
6710 if (!oldDef || (def && def != oldDef)) {
6711 cl->ResetCaches();
6712 TClass::RemoveClassDeclId(cci->GetDeclId());
6713 if (def) {
6714 if (cci->GetType()) {
6715 // It's a tag decl, not a namespace decl.
6716 cci->Init(*cci->GetType());
6717 TClass::AddClassToDeclIdMap(cci->GetDeclId(), cl);
6718 } else {
6719 Error("RefreshClassInfo", "Should not need to update the classInfo a non type decl: %s", oldDef->getNameAsString().c_str());
6720 }
6721 }
6722 }
6723 } else if (!cl->TestBit(TClass::kLoading) && !cl->fHasRootPcmInfo) {
6724 cl->ResetCaches();
6725 if (strncmp(cl->GetName(),"tuple<",strlen("tuple<"))==0) {
6726 // We need to use the Emulated Tuple but we should not trigger parsing
6727 // yet, so delay the creation of the ClassInfo
6728 delete ((TClingClassInfo *)cl->fClassInfo);
6729 cl->fClassInfo = nullptr;
6730 cl->fCanLoadClassInfo = true;
6732 if (cl->fState != TClass::kHasTClassInit) {
6734 }
6735 return;
6736 }
6737 // yes, this is almost a waste of time, but we do need to lookup
6738 // the 'type' corresponding to the TClass anyway in order to
6739 // preserve the opaque typedefs (Double32_t)
6740 if (!alias && def != nullptr)
6742 else
6744 if (((TClingClassInfo *)cl->fClassInfo)->IsValid()) {
6745 // We now need to update the state and bits.
6746 if (cl->fState != TClass::kHasTClassInit) {
6747 // if (!cl->fClassInfo->IsValid()) cl->fState = TClass::kForwardDeclared; else
6749 }
6750 TClass::AddClassToDeclIdMap(((TClingClassInfo *)(cl->fClassInfo))->GetDeclId(), cl);
6751 } else {
6752 delete ((TClingClassInfo *)cl->fClassInfo);
6753 cl->fClassInfo = nullptr;
6754 }
6755 }
6756}
6757
6758////////////////////////////////////////////////////////////////////////////////
6759/// Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
6761{
6762 const TagDecl *td = dyn_cast<TagDecl>(ND);
6764 const NamedDecl *canon = nullptr;
6765
6766 std::string name;
6767 TagDecl* tdDef = nullptr;
6768 if (td) {
6769 canon = tdDef = td->getDefinition();
6770 // Let's pass the decl to the TClass only if it has a definition.
6771 if (!tdDef) return;
6772
6773 if (!tdDef->isCompleteDefinition() || llvm::isa<clang::FunctionDecl>(tdDef->getDeclContext())) {
6774 // Ignore incomplete definition.
6775 // Ignore declaration within a function.
6776 return;
6777 }
6778
6779 auto declName = tdDef->getNameAsString();
6780 // Check if we have registered the unqualified name into the list
6781 // of TClass that are in kNoInfo, kEmulated or kFwdDeclaredState.
6782 // Since this is used as heureutistic to avoid spurrious calls to GetNormalizedName
6783 // the unqualified name is sufficient (and the fully qualified name might be
6784 // 'wrong' if there is difference in spelling in the template paramters (for example)
6786 // 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() );
6787 return;
6788 }
6789
6790 clang::QualType type(tdDef->getTypeForDecl(), 0);
6792 } else if (ns) {
6793 canon = ns->getCanonicalDecl();
6794 name = ND->getQualifiedNameAsString();
6795 } else {
6796 name = ND->getQualifiedNameAsString();
6797 }
6798
6799 // Supposedly we are being called while something is being
6800 // loaded ... let's now tell the autoloader to do the work
6801 // yet another time.
6803 // FIXME: There can be more than one TClass for a single decl.
6804 // for example vector<double> and vector<Double32_t>
6805 TClass* cl = (TClass*)gROOT->GetListOfClasses()->FindObject(name.c_str());
6806 if (cl && GetModTClasses().find(cl) == GetModTClasses().end()) {
6807 RefreshClassInfo(cl, canon, false);
6808 }
6809 // And here we should find the other 'aliases' (eg. vector<Double32_t>)
6810 // and update them too:
6811 // foreach(aliascl in gROOT->GetListOfClasses()->FindAliasesOf(name.c_str()))
6812 // RefreshClassInfo(cl, tdDef, true);
6813}
6814
6815////////////////////////////////////////////////////////////////////////////////
6816/// No op: see TClingCallbacks
6817
6821
6822//______________________________________________________________________________
6823//FIXME: Factor out that function in TClass, because TClass does it already twice
6825{
6826 // This is a no-op as part of the API.
6827 // TCling uses UpdateClassInfoWithDecl() instead.
6828}
6829
6830////////////////////////////////////////////////////////////////////////////////
6831/// Update all canvases at end the terminal input command.
6832
6834{
6835 TIter next(gROOT->GetListOfCanvases());
6836 TVirtualPad* canvas;
6837 while ((canvas = (TVirtualPad*)next())) {
6838 canvas->Update();
6839 }
6840}
6841
6842////////////////////////////////////////////////////////////////////////////////
6843
6844void TCling::UpdateListsOnCommitted(const cling::Transaction &T) {
6845 std::set<TClass*> modifiedTClasses; // TClasses that require update after this transaction
6846
6847 // If the transaction does not contain anything we can return earlier.
6848 if (!HandleNewTransaction(T)) return;
6849
6850 bool isTUTransaction = false;
6851 if (!T.empty() && T.decls_begin() + 1 == T.decls_end() && !T.hasNestedTransactions()) {
6852 clang::Decl* FirstDecl = *(T.decls_begin()->m_DGR.begin());
6853 if (llvm::isa<clang::TranslationUnitDecl>(FirstDecl)) {
6854 // The is the first transaction, we have to expose to meta
6855 // what's already in the AST.
6856 isTUTransaction = true;
6857 }
6858 }
6859
6860 std::set<const void*> TransactionDeclSet;
6861 if (!isTUTransaction && T.decls_end() - T.decls_begin()) {
6862 const clang::Decl* WrapperFD = T.getWrapperFD();
6863 for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
6864 I != E; ++I) {
6865 if (I->m_Call != cling::Transaction::kCCIHandleTopLevelDecl
6866 && I->m_Call != cling::Transaction::kCCIHandleTagDeclDefinition)
6867 continue;
6868
6869 for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6870 DE = I->m_DGR.end(); DI != DE; ++DI) {
6871 if (*DI == WrapperFD)
6872 continue;
6873 TransactionDeclSet.insert(*DI);
6874 ((TCling*)gCling)->HandleNewDecl(*DI, false, modifiedTClasses);
6875 }
6876 }
6877 }
6878
6879 // The above might trigger more decls to be deserialized.
6880 // Thus the iteration over the deserialized decls must be last.
6881 for (cling::Transaction::const_iterator I = T.deserialized_decls_begin(),
6882 E = T.deserialized_decls_end(); I != E; ++I) {
6883 for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6884 DE = I->m_DGR.end(); DI != DE; ++DI)
6885 if (TransactionDeclSet.find(*DI) == TransactionDeclSet.end()) {
6886 //FIXME: HandleNewDecl should take DeclGroupRef
6887 ((TCling*)gCling)->HandleNewDecl(*DI, /*isDeserialized*/true,
6889 }
6890 }
6891
6892
6893 // When fully building the reflection info in TClass, a deserialization
6894 // could be triggered, which may result in request for building the
6895 // reflection info for the same TClass. This in turn will clear the caches
6896 // for the TClass in-flight and cause null ptr derefs.
6897 // FIXME: This is a quick fix, solving most of the issues. The actual
6898 // question is: Shouldn't TClass provide a lock mechanism on update or lock
6899 // itself until the update is done.
6900 //
6901 std::vector<TClass*> modifiedTClassesDiff(modifiedTClasses.size());
6902 std::vector<TClass*>::iterator it;
6904 ((TCling*)gCling)->GetModTClasses().begin(),
6905 ((TCling*)gCling)->GetModTClasses().end(),
6908
6909 // Lock the TClass for updates
6910 ((TCling*)gCling)->GetModTClasses().insert(modifiedTClassesDiff.begin(),
6912 for (std::vector<TClass*>::const_iterator I = modifiedTClassesDiff.begin(),
6913 E = modifiedTClassesDiff.end(); I != E; ++I) {
6914 // Make sure the TClass has not been deleted.
6915 if (!gROOT->GetListOfClasses()->FindObject(*I)) {
6916 continue;
6917 }
6918 // Could trigger deserialization of decls.
6919 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
6920 // Unlock the TClass for updates
6921 ((TCling*)gCling)->GetModTClasses().erase(*I);
6922
6923 }
6924}
6925
6926///\brief Invalidate stored TCling state for declarations included in transaction `T'.
6927///
6928void TCling::UpdateListsOnUnloaded(const cling::Transaction &T)
6929{
6931
6932 auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
6933 (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
6934 (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
6935 (TListOfEnums *)gROOT->GetListOfEnums());
6936
6937 cling::Transaction::const_nested_iterator iNested = T.nested_begin();
6938 for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
6939 I != E; ++I) {
6940 if (I->m_Call == cling::Transaction::kCCIHandleVTable)
6941 continue;
6942 if (I->m_Call == cling::Transaction::kCCINone) {
6944 ++iNested;
6945 continue;
6946 }
6947
6948 for (auto &D : I->m_DGR)
6950 }
6951}
6952
6953///\brief Invalidate cached TCling information for the given global declaration.
6954///
6956 auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
6957 (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
6958 (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
6959 (TListOfEnums *)gROOT->GetListOfEnums());
6961}
6962
6963///\brief Invalidate cached TCling information for the given declaration, and
6964/// removed it from the appropriate object list.
6965///\param[in] Lists - std::tuple<TListOfDataMembers&, TListOfFunctions&,
6966/// TListOfFunctionTemplates&, TListOfEnums&>
6967/// of pointers to the (global/class) object lists.
6968///\param[in] D - Decl to discard.
6969///
6973 TListOfEnums*> &Lists, const Decl *D) {
6974 if (D->isFromASTFile()) // `D' came from the PCH; ignore
6975 return;
6976
6977 TListOfDataMembers &LODM = *(std::get<0>(Lists));
6978 TListOfFunctions &LOF = *(std::get<1>(Lists));
6979 TListOfFunctionTemplates &LOFT = *(std::get<2>(Lists));
6980 TListOfEnums &LOE = *(std::get<3>(Lists));
6981
6983 TObject *O = LODM.Find((TDictionary::DeclId_t)D);
6984 if (LODM.GetClass())
6985 RemoveAndInvalidateObject(LODM, static_cast<TDataMember *>(O));
6986 else
6987 RemoveAndInvalidateObject(LODM, static_cast<TGlobal *>(O));
6988 } else if (isa<FunctionDecl>(D)) {
6990 } else if (isa<FunctionTemplateDecl>(D)) {
6992 } else if (isa<EnumDecl>(D)) {
6993 TEnum *E = LOE.Find((TDictionary::DeclId_t)D);
6994 if (!E)
6995 return;
6996
6997 // Try to invalidate enumerators (for unscoped enumerations).
6998 for (TIter I = E->GetConstants(); auto EC = (TEnumConstant *)I(); )
7000 (TEnumConstant *)LODM.FindObject(EC->GetName()));
7001
7003 } else if (isa<RecordDecl>(D) || isa<NamespaceDecl>(D)) {
7005 return;
7006
7007 std::vector<TClass *> Classes;
7008 if (!TClass::GetClass(D->getCanonicalDecl(), Classes))
7009 return;
7010 for (auto &C : Classes) {
7011 auto Lists = std::make_tuple((TListOfDataMembers *)C->GetListOfDataMembers(),
7012 (TListOfFunctions *)C->GetListOfMethods(),
7013 (TListOfFunctionTemplates *)C->GetListOfFunctionTemplates(),
7014 (TListOfEnums *)C->GetListOfEnums());
7015 for (auto &I : cast<DeclContext>(D)->decls())
7017
7018 // For NamespaceDecl (redeclarable), only invalidate this redecl.
7019 if (D->getKind() != Decl::Namespace
7020 || cast<NamespaceDecl>(D)->isOriginalNamespace())
7021 C->ResetClassInfo();
7022 }
7023 }
7024}
7025
7026////////////////////////////////////////////////////////////////////////////////
7027// If an autoparse was done during a transaction and that it is rolled back,
7028// we need to make sure the next request for the same autoparse will be
7029// honored.
7030void TCling::TransactionRollback(const cling::Transaction &T) {
7031 auto const &triter = fTransactionHeadersMap.find(&T);
7032 if (triter != fTransactionHeadersMap.end()) {
7033 std::size_t normNameHash = triter->second;
7034
7036
7037 auto const &iter = fClassesHeadersMap.find(normNameHash);
7038 if (iter != fClassesHeadersMap.end()) {
7039 auto const &hNamesPtrs = iter->second;
7040 for (auto &hName : hNamesPtrs) {
7041 if (gDebug > 0) {
7042 Info("TransactionRollback",
7043 "Restoring ability to autoaparse: %s", hName);
7044 }
7046 }
7047 }
7048 }
7049}
7050
7051////////////////////////////////////////////////////////////////////////////////
7052
7053void TCling::LibraryLoaded(const void* dyLibHandle, const char* canonicalName) {
7054// R__LOCKGUARD_CLING(gInterpreterMutex);
7055// UpdateListOfLoadedSharedLibraries();
7056}
7057
7058////////////////////////////////////////////////////////////////////////////////
7059
7060void TCling::LibraryUnloaded(const void* dyLibHandle, const char* canonicalName) {
7061 fPrevLoadedDynLibInfo = nullptr;
7062 fSharedLibs = "";
7063}
7064
7065////////////////////////////////////////////////////////////////////////////////
7066/// Return the list of shared libraries loaded into the process.
7067
7074
7075static std::string GetClassSharedLibsForModule(const char *cls, cling::LookupHelper &LH, bool skipCore)
7076{
7077 if (!cls || !*cls)
7078 return {};
7079
7080 using namespace clang;
7081 if (const Decl *D = LH.findScope(cls, cling::LookupHelper::NoDiagnostics,
7082 /*type*/ nullptr, /*instantiate*/ false)) {
7083 if (!D->isFromASTFile()) {
7084 if (gDebug > 5)
7085 Warning("GetClassSharedLibsForModule", "Decl found for %s is not part of a module", cls);
7086 return {};
7087 }
7088 class ModuleCollector : public ConstDeclVisitor<ModuleCollector> {
7089 llvm::DenseSet<Module *> &m_TopLevelModules;
7090
7091 public:
7092 ModuleCollector(llvm::DenseSet<Module *> &TopLevelModules) : m_TopLevelModules(TopLevelModules) {}
7093 void Collect(const Decl *D) { Visit(D); }
7094
7095 void VisitDecl(const Decl *D)
7096 {
7097 // FIXME: Such case is described ROOT-7765 where
7098 // ROOT_GENERATE_DICTIONARY does not contain the list of headers.
7099 // They are specified as #includes in the LinkDef file. This leads to
7100 // generation of incomplete modulemap files and this logic fails to
7101 // compute the corresponding module of D.
7102 // FIXME: If we want to support such a case, we should not rely on
7103 // the contents of the modulemap but mangle D and look it up in the
7104 // .so files.
7105 if (!D->hasOwningModule())
7106 return;
7107 if (Module *M = D->getOwningModule()->getTopLevelModule())
7108 m_TopLevelModules.insert(M);
7109 }
7110
7112 {
7113 switch (TA.getKind()) {
7114 case TemplateArgument::Null:
7115 case TemplateArgument::Integral:
7116 case TemplateArgument::Pack:
7117 case TemplateArgument::NullPtr:
7118 case TemplateArgument::StructuralValue:
7119 case TemplateArgument::Expression:
7120 case TemplateArgument::Template:
7121 case TemplateArgument::TemplateExpansion: return;
7122 case TemplateArgument::Type:
7123 if (const TagType *TagTy = dyn_cast<TagType>(TA.getAsType()))
7124 return Visit(TagTy->getDecl());
7125 return;
7126 case TemplateArgument::Declaration: return Visit(TA.getAsDecl());
7127 }
7128 llvm_unreachable("Invalid TemplateArgument::Kind!");
7129 }
7130
7132 {
7133 if (CTSD->getOwningModule())
7134 VisitDecl(CTSD);
7135 else
7136 VisitDecl(CTSD->getSpecializedTemplate());
7137 const TemplateArgumentList &ArgList = CTSD->getTemplateArgs();
7138 for (const TemplateArgument *Arg = ArgList.data(), *ArgEnd = Arg + ArgList.size(); Arg != ArgEnd; ++Arg) {
7140 }
7141 }
7142 };
7143
7144 llvm::DenseSet<Module *> TopLevelModules;
7146 m.Collect(D);
7147 std::string result;
7148 for (auto M : TopLevelModules) {
7149 // ROOT-unaware modules (i.e. not processed by rootcling) do not have a
7150 // link declaration.
7151 if (!M->LinkLibraries.size())
7152 continue;
7153 // We have preloaded the Core module thus libCore.so
7154 if (M->Name == "Core" && skipCore)
7155 continue;
7156 assert(M->LinkLibraries.size() == 1);
7157 if (!result.empty())
7158 result += ' ';
7159 result += M->LinkLibraries[0].Library;
7160 }
7161 return result;
7162 }
7163 return {};
7164}
7165
7166////////////////////////////////////////////////////////////////////////////////
7167/// Get the list of shared libraries containing the code for class cls.
7168/// The first library in the list is the one containing the class, the
7169/// others are the libraries the first one depends on. Returns 0
7170/// in case the library is not found.
7171/// \param cls the name of the class
7172/// \param skipCore if true (default), remove "Core" from the returned list
7173
7174const char* TCling::GetClassSharedLibs(const char* cls, bool skipCore)
7175{
7176 if (fCxxModulesEnabled) {
7177 // Lock the interpreter mutex before interacting with cling.
7178 // TODO: Can we move this further deep? In principle the lock should be in
7179 // GetClassSharedLibsForModule, but it might be needed also for
7180 // getLookupHelper?
7182 llvm::StringRef className = cls;
7183 // If we get a class name containing lambda, we cannot parse it and we
7184 // can exit early.
7185 // FIXME: This works around a bug when we are instantiating a template
7186 // make_unique and the substitution fails. Seen in most of the dataframe
7187 // tests.
7188 if (className.contains("(lambda)"))
7189 return nullptr;
7190 // Limit the recursion which can be induced by GetClassSharedLibsForModule.
7192 cling::LookupHelper &LH = fInterpreter->getLookupHelper();
7194 if (!libs.empty()) {
7195 fAutoLoadLibStorage.push_back(libs);
7196 return fAutoLoadLibStorage.back().c_str();
7197 }
7198 }
7199
7200 if (!cls || !*cls) {
7201 return nullptr;
7202 }
7203 // lookup class to find list of libraries
7204 if (fMapfile) {
7205 TEnvRec* libs_record = nullptr;
7207 if (libs_record) {
7208 const char* libs = libs_record->GetValue();
7209 return (*libs) ? libs : nullptr;
7210 }
7211 else {
7212 // Try the old format...
7213 TString c = TString("Library.") + cls;
7214 // convert "::" to "@@", we used "@@" because TEnv
7215 // considers "::" a terminator
7216 c.ReplaceAll("::", "@@");
7217 // convert "-" to " ", since class names may have
7218 // blanks and TEnv considers a blank a terminator
7219 c.ReplaceAll(" ", "-");
7220 // Use TEnv::Lookup here as the rootmap file must start with Library.
7221 // and do not support using any stars (so we do not need to waste time
7222 // with the search made by TEnv::GetValue).
7223 TEnvRec* libs_record = nullptr;
7225 if (libs_record) {
7226 const char* libs = libs_record->GetValue();
7227 return (*libs) ? libs : nullptr;
7228 }
7229 }
7230 }
7231 return nullptr;
7232}
7233
7234/// This interface returns a list of dependent libraries in the form:
7235/// lib libA.so libB.so libC.so. The first library is the library we are
7236/// searching dependencies for.
7237/// Note: In order to speed up the search, we display the dependencies of the
7238/// libraries which are not yet loaded. For instance, if libB.so was already
7239/// loaded the list would contain: lib libA.so libC.so.
7240static std::string GetSharedLibImmediateDepsSlow(std::string lib,
7241 cling::Interpreter *interp,
7242 bool skipLoadedLibs = true)
7243{
7244 TString LibFullPath(lib);
7245 if (!llvm::sys::path::is_absolute(lib)) {
7246 if (!gSystem->FindDynamicLibrary(LibFullPath, /*quiet=*/true)) {
7247 Error("TCling__GetSharedLibImmediateDepsSlow", "Cannot find library '%s'", lib.c_str());
7248 return "";
7249 }
7250 } else {
7251 assert(llvm::sys::fs::exists(lib) && "Must exist!");
7252 lib = llvm::sys::path::filename(lib).str();
7253 }
7254
7255 auto ObjF = llvm::object::ObjectFile::createObjectFile(LibFullPath.Data());
7256 if (!ObjF) {
7257 Warning("TCling__GetSharedLibImmediateDepsSlow", "Failed to read object file %s", lib.c_str());
7258 return "";
7259 }
7260
7261 llvm::object::ObjectFile *BinObjFile = ObjF.get().getBinary();
7262
7263 std::set<string> DedupSet;
7264 std::string Result = lib + ' ';
7265 for (const auto &S : BinObjFile->symbols()) {
7266 uint32_t Flags = llvm::cantFail(S.getFlags());
7267 // Skip defined symbols: we have them.
7268 if (!(Flags & llvm::object::SymbolRef::SF_Undefined))
7269 continue;
7270 // Skip undefined weak symbols: if we don't have them we won't need them.
7271 // `__gmon_start__` being a typical example.
7272 if (Flags & llvm::object::SymbolRef::SF_Weak)
7273 continue;
7274 llvm::Expected<StringRef> SymNameErr = S.getName();
7275 if (!SymNameErr) {
7276 Warning("GetSharedLibDepsForModule", "Failed to read symbol");
7277 continue;
7278 }
7279 llvm::StringRef SymName = SymNameErr.get();
7280 if (SymName.empty())
7281 continue;
7282
7283 if (BinObjFile->isELF()) {
7284 // Skip the symbols which are part of the C/C++ runtime and have a
7285 // fixed library version. See binutils ld VERSION. Those reside in
7286 // 'system' libraries, which we avoid in FindLibraryForSymbol.
7287 if (SymName.contains("@GLIBCXX") || SymName.contains("@CXXABI") ||
7288 SymName.contains("@GLIBC") || SymName.contains("@GCC"))
7289 continue;
7290
7291 // Those are 'weak undefined' symbols produced by gcc. We can
7292 // ignore them.
7293 // FIXME: It is unclear whether we can ignore all weak undefined
7294 // symbols:
7295 // http://lists.llvm.org/pipermail/llvm-dev/2017-October/118177.html
7296 static constexpr llvm::StringRef RegisterClasses("_Jv_RegisterClasses");
7297 static constexpr llvm::StringRef RegisterCloneTable("_ITM_registerTMCloneTable");
7298 static constexpr llvm::StringRef DeregisterCloneTable("_ITM_deregisterTMCloneTable");
7299 if (SymName == RegisterClasses ||
7302 continue;
7303 }
7304
7305 // If we can find the address of the symbol, we have loaded it. Skip.
7306 if (skipLoadedLibs) {
7308 if (llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(SymNameForDlsym))
7309 continue;
7310 }
7311
7313 std::string found = interp->getDynamicLibraryManager()->searchLibrariesForSymbol(SymName, /*searchSystem*/false);
7314 // The expected output is just filename without the full path, which
7315 // is not very accurate, because our Dyld implementation might find
7316 // a match in location a/b/c.so and if we return just c.so ROOT might
7317 // resolve it to y/z/c.so and there we might not be ABI compatible.
7318 // FIXME: Teach the users of GetSharedLibDeps to work with full paths.
7319 if (!found.empty()) {
7320 std::string cand = llvm::sys::path::filename(found).str();
7321 if (!DedupSet.insert(cand).second)
7322 continue;
7323
7324 Result += cand + ' ';
7325 }
7326 }
7327
7328 return Result;
7329}
7330
7331static bool hasParsedRootmapForLibrary(llvm::StringRef lib)
7332{
7333 // Check if we have parsed a rootmap file.
7334 llvm::SmallString<256> rootmapName;
7335 if (!lib.starts_with("lib"))
7336 rootmapName.append("lib");
7337
7338 rootmapName.append(llvm::sys::path::filename(lib));
7339 llvm::sys::path::replace_extension(rootmapName, "rootmap");
7340
7341 if (gCling->GetRootMapFiles()->FindObject(rootmapName.c_str()))
7342 return true;
7343
7344 // Perform a last resort by dropping the lib prefix.
7345 llvm::StringRef rootmapNameNoLib = rootmapName.str();
7346 if (rootmapNameNoLib.consume_front("lib"))
7347 return gCling->GetRootMapFiles()->FindObject(rootmapNameNoLib.data());
7348
7349 return false;
7350}
7351
7352static bool hasPrecomputedLibraryDeps(llvm::StringRef lib)
7353{
7354 if (gCling->HasPCMForLibrary(lib.data()))
7355 return true;
7356
7357 return hasParsedRootmapForLibrary(lib);
7358}
7359
7360////////////////////////////////////////////////////////////////////////////////
7361/// Get the list a libraries on which the specified lib depends. The
7362/// returned string contains as first element the lib itself.
7363/// Returns 0 in case the lib does not exist or does not have
7364/// any dependencies. If useDyld is true, we iterate through all available
7365/// libraries and try to construct the dependency chain by resolving each
7366/// symbol.
7367
7368const char* TCling::GetSharedLibDeps(const char* lib, bool useDyld/* = false*/)
7369{
7370 if (llvm::sys::path::is_absolute(lib) && !llvm::sys::fs::exists(lib))
7371 return nullptr;
7372
7373 if (!hasParsedRootmapForLibrary(lib)) {
7374 llvm::SmallString<512> rootmapName(lib);
7375 llvm::sys::path::replace_extension(rootmapName, "rootmap");
7376 if (llvm::sys::fs::exists(rootmapName)) {
7377 if (gDebug > 0)
7378 Info("Load", "loading %s", rootmapName.c_str());
7379 gInterpreter->LoadLibraryMap(rootmapName.c_str());
7380 }
7381 }
7382
7383 if (hasPrecomputedLibraryDeps(lib) && useDyld) {
7384 if (gDebug > 0)
7385 Warning("TCling::GetSharedLibDeps", "Precomputed dependencies available but scanning '%s'", lib);
7386 }
7387
7388 if (useDyld) {
7390 if (!libs.empty()) {
7391 fAutoLoadLibStorage.push_back(libs);
7392 return fAutoLoadLibStorage.back().c_str();
7393 }
7394 }
7395
7396 if (!fMapfile || !lib || !lib[0]) {
7397 return nullptr;
7398 }
7399 TString libname(lib);
7400 Ssiz_t idx = libname.Last('.');
7401 if (idx != kNPOS) {
7402 libname.Remove(idx);
7403 }
7404 TEnvRec* rec;
7405 TIter next(fMapfile->GetTable());
7406 size_t len = libname.Length();
7407 while ((rec = (TEnvRec*) next())) {
7408 const char* libs = rec->GetValue();
7409 if (!strncmp(libs, libname.Data(), len) && strlen(libs) >= len
7410 && (!libs[len] || libs[len] == ' ' || libs[len] == '.')) {
7411 return libs;
7412 }
7413 }
7414 return nullptr;
7415}
7416
7417////////////////////////////////////////////////////////////////////////////////
7418/// If error messages are disabled, the interpreter should suppress its
7419/// failures and warning messages from stdout.
7420
7422{
7423#if defined(R__MUST_REVISIT)
7424#if R__MUST_REVISIT(6,2)
7425 Warning("IsErrorMessagesEnabled", "Interface not available yet.");
7426#endif
7427#endif
7428 return kTRUE;
7429}
7430
7431////////////////////////////////////////////////////////////////////////////////
7432/// If error messages are disabled, the interpreter should suppress its
7433/// failures and warning messages from stdout. Return the previous state.
7434
7436{
7437#if defined(R__MUST_REVISIT)
7438#if R__MUST_REVISIT(6,2)
7439 Warning("SetErrorMessages", "Interface not available yet.");
7440#endif
7441#endif
7443}
7444
7445////////////////////////////////////////////////////////////////////////////////
7446/// Refresh the list of include paths known to the interpreter and return it
7447/// with -I prepended.
7448
7450{
7452
7453 fIncludePath = "";
7454
7455 llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7456 //false - no system header, true - with flags.
7457 fInterpreter->GetIncludePaths(includePaths, false, true);
7458 if (const size_t nPaths = includePaths.size()) {
7459 assert(!(nPaths & 1) && "GetIncludePath, number of paths and options is not equal");
7460
7461 for (size_t i = 0; i < nPaths; i += 2) {
7462 if (i)
7463 fIncludePath.Append(' ');
7464 fIncludePath.Append(includePaths[i].c_str());
7465
7466 if (includePaths[i] != "-I")
7467 fIncludePath.Append(' ');
7468 fIncludePath.Append('"');
7470 fIncludePath.Append('"');
7471 }
7472 }
7473
7474 return fIncludePath;
7475}
7476
7477////////////////////////////////////////////////////////////////////////////////
7478/// Return the directory containing CINT's stl cintdlls.
7479
7480const char* TCling::GetSTLIncludePath() const
7481{
7482 return "";
7483}
7484
7485//______________________________________________________________________________
7486// M I S C
7487//______________________________________________________________________________
7488
7489int TCling::DisplayClass(FILE* /*fout*/, const char* /*name*/, int /*base*/, int /*start*/) const
7490{
7491 // Interface to cling function
7492 return 0;
7493}
7494
7495////////////////////////////////////////////////////////////////////////////////
7496/// Interface to cling function
7497
7499{
7500 assert(fout != nullptr && "DisplayIncludePath, 'fout' parameter is null");
7501
7502 llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7503 //false - no system header, true - with flags.
7504 fInterpreter->GetIncludePaths(includePaths, false, true);
7505 if (const size_t nPaths = includePaths.size()) {
7506 assert(!(nPaths & 1) && "DisplayIncludePath, number of paths and options is not equal");
7507
7508 std::string allIncludes("include path:");
7509 for (size_t i = 0; i < nPaths; i += 2) {
7510 allIncludes += ' ';
7512
7513 if (includePaths[i] != "-I")
7514 allIncludes += ' ';
7515 allIncludes += includePaths[i + 1];
7516 }
7517
7518 fprintf(fout, "%s\n", allIncludes.c_str());
7519 }
7520
7521 return 0;
7522}
7523
7524////////////////////////////////////////////////////////////////////////////////
7525/// Interface to cling function
7526
7527void* TCling::FindSym(const char* entry) const
7528{
7530 return fInterpreter->getAddressOfGlobal(entry);
7531}
7532
7533////////////////////////////////////////////////////////////////////////////////
7534/// Let the interpreter issue a generic error, and set its error state.
7535
7536void TCling::GenericError(const char* error) const
7537{
7538#if defined(R__MUST_REVISIT)
7539#if R__MUST_REVISIT(6,2)
7540 Warning("GenericError","Interface not available yet.");
7541#endif
7542#endif
7543}
7544
7545////////////////////////////////////////////////////////////////////////////////
7546/// This routines used to return the address of the internal wrapper
7547/// function (of the interpreter) that was used to call *all* the
7548/// interpreted functions that were bytecode compiled (no longer
7549/// interpreted line by line). In Cling, there is no such
7550/// wrapper function.
7551/// In practice this routines was use to decipher whether the
7552/// pointer returns by InterfaceMethod could be used to uniquely
7553/// represent the function. In Cling if the function is in a
7554/// useable state (its compiled version is available), this is
7555/// always the case.
7556/// See TClass::GetMethod.
7557
7559{
7560 return 0;
7561}
7562
7563////////////////////////////////////////////////////////////////////////////////
7564/// Interface to cling function
7565
7567{
7568#if defined(R__MUST_REVISIT)
7569#if R__MUST_REVISIT(6,2)
7570 Warning("GetSecurityError", "Interface not available yet.");
7571#endif
7572#endif
7573 return 0;
7574}
7575
7576////////////////////////////////////////////////////////////////////////////////
7577/// Load a source file or library called path into the interpreter.
7578
7579int TCling::LoadFile(const char* path) const
7580{
7581 // Modifying the interpreter state needs locking.
7583 cling::Interpreter::CompilationResult compRes;
7584 HandleInterpreterException(GetMetaProcessorImpl(), TString::Format(".L %s", path), compRes, /*cling::Value*/nullptr);
7585 return compRes == cling::Interpreter::kFailure;
7586}
7587
7588////////////////////////////////////////////////////////////////////////////////
7589/// Load the declarations from text into the interpreter.
7590/// Note that this cannot be (top level) statements; text must contain
7591/// top level declarations.
7592/// Returns true on success, false on failure.
7593
7594Bool_t TCling::LoadText(const char* text) const
7595{
7596 return (fInterpreter->declare(text) == cling::Interpreter::kSuccess);
7597}
7598
7599////////////////////////////////////////////////////////////////////////////////
7600/// Interface to cling function
7601
7602const char* TCling::MapCppName(const char* name) const
7603{
7604 TTHREAD_TLS_DECL(std::string,buffer);
7606 return buffer.c_str(); // NOLINT
7607}
7608
7609////////////////////////////////////////////////////////////////////////////////
7610/// [Place holder for Mutex Lock]
7611/// Provide the interpreter with a way to
7612/// acquire a lock used to protect critical section
7613/// of its code (non-thread safe parts).
7614
7615void TCling::SetAlloclockfunc(void (* /* p */ )()) const
7616{
7617 // nothing to do for now.
7618}
7619
7620////////////////////////////////////////////////////////////////////////////////
7621/// [Place holder for Mutex Unlock] Provide the interpreter with a way to
7622/// release a lock used to protect critical section
7623/// of its code (non-thread safe parts).
7624
7625void TCling::SetAllocunlockfunc(void (* /* p */ )()) const
7626{
7627 // nothing to do for now.
7628}
7629
7630////////////////////////////////////////////////////////////////////////////////
7631/// Returns if class AutoLoading is currently enabled.
7632
7634{
7635 if (IsFromRootCling())
7636 return false;
7637 if (!fClingCallbacks)
7638 return false;
7640}
7641
7642////////////////////////////////////////////////////////////////////////////////
7643/// Enable/Disable the AutoLoading of libraries.
7644/// Returns the old value, i.e whether it was enabled or not.
7645
7647{
7648 // If no state change is required, exit early.
7649 // FIXME: In future we probably want to complain if we made a request which
7650 // was with the same state as before in order to catch programming errors.
7651 if ((bool) autoload == IsClassAutoLoadingEnabled())
7652 return autoload;
7653
7654 assert(fClingCallbacks && "We must have callbacks!");
7657 return oldVal;
7658}
7659
7660////////////////////////////////////////////////////////////////////////////////
7661/// Enable/Disable the Autoparsing of headers.
7662/// Returns the old value, i.e whether it was enabled or not.
7663
7670
7671////////////////////////////////////////////////////////////////////////////////
7672/// Suspend the Autoparsing of headers.
7673/// Returns the old value, i.e whether it was suspended or not.
7674
7681
7682////////////////////////////////////////////////////////////////////////////////
7683/// Set a callback to receive error messages.
7684
7686{
7687#if defined(R__MUST_REVISIT)
7688#if R__MUST_REVISIT(6,2)
7689 Warning("SetErrmsgcallback", "Interface not available yet.");
7690#endif
7691#endif
7692}
7693
7695{
7696 if (enable) {
7698 &fInterpreter->getDiagnostics().getDiagnosticOptions(),
7699 fInterpreter->getCI()->getLangOpts(),
7700 [] (clang::DiagnosticsEngine::Level Level, const std::string &Info) {
7701 if (Level == clang::DiagnosticsEngine::Warning) {
7702 ::Warning("cling", "%s", Info.c_str());
7703 } else if (Level == clang::DiagnosticsEngine::Error
7704 || Level == clang::DiagnosticsEngine::Fatal) {
7705 ::Error("cling", "%s", Info.c_str());
7706 } else {
7707 ::Info("cling", "%s", Info.c_str());
7708 }
7709 });
7710 fInterpreter->replaceDiagnosticConsumer(consumer, /*Own=*/true);
7711 } else {
7712 fInterpreter->replaceDiagnosticConsumer(nullptr);
7713 }
7714}
7715
7716
7717////////////////////////////////////////////////////////////////////////////////
7718/// Create / close a scope for temporaries. No-op for cling; use
7719/// cling::Value instead.
7720
7721void TCling::SetTempLevel(int val) const
7722{
7723}
7724
7725////////////////////////////////////////////////////////////////////////////////
7726
7727int TCling::UnloadFile(const char* path) const
7728{
7729 // Modifying the interpreter state needs locking.
7731 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
7732 std::string canonical = DLM->lookupLibrary(path);
7733 if (canonical.empty()) {
7734 canonical = path;
7735 }
7736 // Unload a shared library or a source file.
7737 cling::Interpreter::CompilationResult compRes;
7738 HandleInterpreterException(GetMetaProcessorImpl(), Form(".U %s", canonical.c_str()), compRes, /*cling::Value*/nullptr);
7739 return compRes == cling::Interpreter::kFailure;
7740}
7741
7742std::unique_ptr<TInterpreterValue> TCling::MakeInterpreterValue() const {
7743 return std::unique_ptr<TInterpreterValue>(new TClingValue);
7744}
7745
7746////////////////////////////////////////////////////////////////////////////////
7747/// The call to Cling's tab complition.
7748
7749void TCling::CodeComplete(const std::string& line, size_t& cursor,
7750 std::vector<std::string>& completions)
7751{
7752 fInterpreter->codeComplete(line, cursor, completions);
7753}
7754
7755////////////////////////////////////////////////////////////////////////////////
7756/// Get the interpreter value corresponding to the statement.
7758{
7760
7761 auto V = reinterpret_cast<cling::Value*>(value.GetValAddr());
7762 auto compRes = fInterpreter->evaluate(code, *V);
7763 return compRes!=cling::Interpreter::kSuccess ? 0 : 1 ;
7764}
7765
7766////////////////////////////////////////////////////////////////////////////////
7767
7769{
7770 using namespace cling;
7771 const Value* V = reinterpret_cast<const Value*>(value.GetValAddr());
7773}
7774
7775////////////////////////////////////////////////////////////////////////////////
7776/// Register value as a temporary, extending its lifetime to that of the
7777/// interpreter. This is needed for TCling's compatibility interfaces
7778/// returning long - the address of the temporary objects.
7779/// As such, "simple" types don't need to be stored; they are returned by
7780/// value; only pointers / references / objects need to be stored.
7781
7782void TCling::RegisterTemporary(const cling::Value& value)
7783{
7784 if (value.isValid() && value.needsManagedAllocation()) {
7786 fTemporaries->push_back(value);
7787 }
7788}
7789
7790////////////////////////////////////////////////////////////////////////////////
7791/// If the interpreter encounters Name, check whether that is an object ROOT
7792/// could retrieve. To not re-read objects from disk, cache the name/object
7793/// pair for a given LookupCtx.
7794
7796{
7797 // The call to FindSpecialObject might induces any kind of use
7798 // of the interpreter ... (library loading, function calling, etc.)
7799 // ... and we _know_ we are in the middle of parsing, so let's make
7800 // sure to save the state and then restore it.
7801
7802 if (gDirectory) {
7804 if (iSpecObjMap != fSpecialObjectMaps.end()) {
7805 auto iSpecObj = iSpecObjMap->second.find(Name);
7806 if (iSpecObj != iSpecObjMap->second.end()) {
7808 return iSpecObj->second;
7809 }
7810 }
7811 }
7812
7813 // Save state of the PP
7814 Sema &SemaR = fInterpreter->getSema();
7815 ASTContext& C = SemaR.getASTContext();
7816 Preprocessor &PP = SemaR.getPreprocessor();
7817 Parser& P = const_cast<Parser&>(fInterpreter->getParser());
7818 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
7819 Parser::ParserCurTokRestoreRAII savedCurToken(P);
7820 // After we have saved the token reset the current one to something which
7821 // is safe (semi colon usually means empty decl)
7822 Token& Tok = const_cast<Token&>(P.getCurToken());
7823 Tok.setKind(tok::semi);
7824
7825 // We can't PushDeclContext, because we go up and the routine that pops
7826 // the DeclContext assumes that we drill down always.
7827 // We have to be on the global context. At that point we are in a
7828 // wrapper function so the parent context must be the global.
7829 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(),
7830 SemaR.TUScope);
7831
7832 TObject* specObj = gROOT->FindSpecialObject(Name, LookupCtx);
7833 if (specObj) {
7834 if (!LookupCtx) {
7835 Error("GetObjectAddress", "Got a special object without LookupCtx!");
7836 } else {
7838 }
7839 }
7840 return specObj;
7841}
7842
7843////////////////////////////////////////////////////////////////////////////////
7844/// Inject function as a friend into klass.
7845/// With function being f in void f() {new N::PrivKlass(); } this enables
7846/// I/O of non-public classes.
7847
7848void TCling::AddFriendToClass(clang::FunctionDecl* function,
7849 clang::CXXRecordDecl* klass) const
7850{
7851 using namespace clang;
7852 ASTContext& Ctx = klass->getASTContext();
7853 FriendDecl::FriendUnion friendUnion(function);
7854 // one dummy object for the source location
7856 FriendDecl* friendDecl = FriendDecl::Create(Ctx, klass, sl, friendUnion, sl);
7857 klass->pushFriendDecl(friendDecl);
7858}
7859
7860//______________________________________________________________________________
7861//
7862// DeclId getter.
7863//
7864
7865////////////////////////////////////////////////////////////////////////////////
7866/// Return a unique identifier of the declaration represented by the
7867/// CallFunc
7868
7870{
7871 if (func) return ((TClingCallFunc*)func)->GetDecl()->getCanonicalDecl();
7872 return nullptr;
7873}
7874
7875////////////////////////////////////////////////////////////////////////////////
7876/// Return a (almost) unique identifier of the declaration represented by the
7877/// ClassInfo. In ROOT, this identifier can point to more than one TClass
7878/// when the underlying class is a template instance involving one of the
7879/// opaque typedef.
7880
7882{
7883 if (cinfo) return ((TClingClassInfo*)cinfo)->GetDeclId();
7884 return nullptr;
7885}
7886
7887////////////////////////////////////////////////////////////////////////////////
7888/// Return a unique identifier of the declaration represented by the
7889/// MethodInfo
7890
7892{
7893 if (data) return ((TClingDataMemberInfo*)data)->GetDeclId();
7894 return nullptr;
7895}
7896
7897////////////////////////////////////////////////////////////////////////////////
7898/// Return a unique identifier of the declaration represented by the
7899/// MethodInfo
7900
7902{
7903 if (method) return ((TClingMethodInfo*)method)->GetDeclId();
7904 return nullptr;
7905}
7906
7907////////////////////////////////////////////////////////////////////////////////
7908/// Return a unique identifier of the declaration represented by the
7909/// TypedefInfo
7910
7912{
7913 if (tinfo) return ((TClingTypedefInfo*)tinfo)->GetDecl()->getCanonicalDecl();
7914 return nullptr;
7915}
7916
7917//______________________________________________________________________________
7918//
7919// CallFunc interface
7920//
7921
7922////////////////////////////////////////////////////////////////////////////////
7923
7925{
7926 delete (TClingCallFunc*) func;
7927}
7928
7929////////////////////////////////////////////////////////////////////////////////
7930
7931void TCling::CallFunc_Exec(CallFunc_t* func, void* address) const
7932{
7933 TClingCallFunc* f = (TClingCallFunc*) func;
7934 f->Exec(address);
7935}
7936
7937////////////////////////////////////////////////////////////////////////////////
7938
7939void TCling::CallFunc_Exec(CallFunc_t* func, void* address, TInterpreterValue& val) const
7940{
7941 TClingCallFunc* f = (TClingCallFunc*) func;
7942 f->Exec(address, &val);
7943}
7944
7945////////////////////////////////////////////////////////////////////////////////
7946
7947void TCling::CallFunc_ExecWithReturn(CallFunc_t* func, void* address, void* ret) const
7948{
7949 TClingCallFunc* f = (TClingCallFunc*) func;
7950 f->ExecWithReturn(address, ret);
7951}
7952
7953////////////////////////////////////////////////////////////////////////////////
7954
7956 const void* args[] /*=0*/,
7957 int nargs /*=0*/,
7958 void* ret/*=0*/) const
7959{
7960 TClingCallFunc* f = (TClingCallFunc*) func;
7961 f->ExecWithArgsAndReturn(address, args, nargs, ret);
7962}
7963
7964////////////////////////////////////////////////////////////////////////////////
7965
7967{
7968 TClingCallFunc* f = (TClingCallFunc*) func;
7969 return f->ExecInt(address);
7970}
7971
7972////////////////////////////////////////////////////////////////////////////////
7973
7975{
7976 TClingCallFunc* f = (TClingCallFunc*) func;
7977 return f->ExecInt64(address);
7978}
7979
7980////////////////////////////////////////////////////////////////////////////////
7981
7983{
7984 TClingCallFunc* f = (TClingCallFunc*) func;
7985 return f->ExecDouble(address);
7986}
7987
7988////////////////////////////////////////////////////////////////////////////////
7989
7995
7996////////////////////////////////////////////////////////////////////////////////
7997
7999{
8000 return (CallFunc_t*) new TClingCallFunc(*(TClingCallFunc*)func);
8001}
8002
8003////////////////////////////////////////////////////////////////////////////////
8004
8006{
8007 TClingCallFunc* f = (TClingCallFunc*) func;
8008 return (MethodInfo_t*) f->FactoryMethod();
8009}
8010
8011////////////////////////////////////////////////////////////////////////////////
8012
8014{
8015 TClingCallFunc* f = (TClingCallFunc*) func;
8016 f->IgnoreExtraArgs(ignore);
8017}
8018
8019////////////////////////////////////////////////////////////////////////////////
8020
8022{
8024 TClingCallFunc* f = (TClingCallFunc*) func;
8025 f->Init();
8026}
8027
8028////////////////////////////////////////////////////////////////////////////////
8029
8031{
8032 TClingCallFunc* f = (TClingCallFunc*) func;
8033 return f->IsValid();
8034}
8035
8036////////////////////////////////////////////////////////////////////////////////
8037
8040{
8041 TClingCallFunc* f = (TClingCallFunc*) func;
8042 return f->IFacePtr();
8043}
8044
8045////////////////////////////////////////////////////////////////////////////////
8046
8048{
8049 TClingCallFunc* f = (TClingCallFunc*) func;
8050 f->ResetArg();
8051}
8052
8053////////////////////////////////////////////////////////////////////////////////
8054
8056{
8057 TClingCallFunc* f = (TClingCallFunc*) func;
8058 f->SetArg(param);
8059}
8060
8061////////////////////////////////////////////////////////////////////////////////
8062
8064{
8065 TClingCallFunc* f = (TClingCallFunc*) func;
8066 f->SetArg(param);
8067}
8068
8069////////////////////////////////////////////////////////////////////////////////
8070
8072{
8073 TClingCallFunc* f = (TClingCallFunc*) func;
8074 f->SetArg(param);
8075}
8076
8077////////////////////////////////////////////////////////////////////////////////
8078
8080{
8081 TClingCallFunc* f = (TClingCallFunc*) func;
8082 f->SetArg(param);
8083}
8084
8085////////////////////////////////////////////////////////////////////////////////
8086
8088{
8089 TClingCallFunc* f = (TClingCallFunc*) func;
8090 f->SetArg(param);
8091}
8092
8093////////////////////////////////////////////////////////////////////////////////
8094
8096{
8097 TClingCallFunc* f = (TClingCallFunc*) func;
8098 f->SetArg(param);
8099}
8100
8101////////////////////////////////////////////////////////////////////////////////
8102
8104{
8105 TClingCallFunc* f = (TClingCallFunc*) func;
8106 f->SetArgArray(paramArr, nparam);
8107}
8108
8109////////////////////////////////////////////////////////////////////////////////
8110
8111void TCling::CallFunc_SetArgs(CallFunc_t* func, const char* param) const
8112{
8113 TClingCallFunc* f = (TClingCallFunc*) func;
8114 f->SetArgs(param);
8115}
8116
8117////////////////////////////////////////////////////////////////////////////////
8118
8119void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, Longptr_t* offset) const
8120{
8121 TClingCallFunc* f = (TClingCallFunc*) func;
8123 f->SetFunc(ci, method, params, offset);
8124}
8125
8126////////////////////////////////////////////////////////////////////////////////
8127
8128void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, bool objectIsConst, Longptr_t* offset) const
8129{
8130 TClingCallFunc* f = (TClingCallFunc*) func;
8132 f->SetFunc(ci, method, params, objectIsConst, offset);
8133}
8134////////////////////////////////////////////////////////////////////////////////
8135
8136void TCling::CallFunc_SetFunc(CallFunc_t* func, MethodInfo_t* info) const
8137{
8138 TClingCallFunc* f = (TClingCallFunc*) func;
8140 f->SetFunc(minfo);
8141}
8142
8143////////////////////////////////////////////////////////////////////////////////
8144/// Interface to cling function
8145
8146void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8147{
8148 TClingCallFunc* f = (TClingCallFunc*) func;
8150 f->SetFuncProto(ci, method, proto, offset, mode);
8151}
8152
8153////////////////////////////////////////////////////////////////////////////////
8154/// Interface to cling function
8155
8156void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, bool objectIsConst, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8157{
8158 TClingCallFunc* f = (TClingCallFunc*) func;
8160 f->SetFuncProto(ci, method, proto, objectIsConst, offset, mode);
8161}
8162
8163////////////////////////////////////////////////////////////////////////////////
8164/// Interface to cling function
8165
8166void 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
8167{
8168 TClingCallFunc* f = (TClingCallFunc*) func;
8170 llvm::SmallVector<clang::QualType, 4> funcProto;
8171 for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
8172 iter != end; ++iter) {
8173 funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
8174 }
8175 f->SetFuncProto(ci, method, funcProto, offset, mode);
8176}
8177
8178////////////////////////////////////////////////////////////////////////////////
8179/// Interface to cling function
8180
8181void 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
8182{
8183 TClingCallFunc* f = (TClingCallFunc*) func;
8185 llvm::SmallVector<clang::QualType, 4> funcProto;
8186 for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
8187 iter != end; ++iter) {
8188 funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
8189 }
8190 f->SetFuncProto(ci, method, funcProto, objectIsConst, offset, mode);
8191}
8192
8194{
8195 TClingCallFunc *f = (TClingCallFunc *)func;
8196 std::string wrapper_name;
8197 std::string wrapper;
8198 f->get_wrapper_code(wrapper_name, wrapper);
8199 return wrapper;
8200}
8201
8202//______________________________________________________________________________
8203//
8204// ClassInfo interface
8205//
8206
8207////////////////////////////////////////////////////////////////////////////////
8208/// Return true if the entity pointed to by 'declid' is declared in
8209/// the context described by 'info'. If info is null, look into the
8210/// global scope (translation unit scope).
8211
8213{
8214 if (!declid)
8215 return kFALSE;
8216
8217 const clang::DeclContext *ctxt = nullptr;
8218 if (info) {
8219 ctxt = clang::Decl::castToDeclContext(((TClingClassInfo*)info)->GetDecl());
8220 } else {
8221 ctxt = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
8222 }
8223 if (!ctxt)
8224 return kFALSE;
8225
8226 const clang::Decl *decl = reinterpret_cast<const clang::Decl*>(declid);
8227 if (!decl)
8228 return kFALSE;
8229
8230 const clang::DeclContext *declDC = decl->getDeclContext();
8231 // ClassInfo_t-s are always "spellable" scopes, never unnamed or inline ones.
8232 while (true) {
8233 if (declDC->isTransparentContext()) {
8234 declDC = declDC->getParent();
8235 continue;
8236 }
8237 if (const auto *declRD = llvm::dyn_cast<clang::RecordDecl>(declDC)) {
8238 if (declRD->isAnonymousStructOrUnion()) {
8239 declDC = declRD->getParent();
8240 continue;
8241 }
8242 }
8243 if (const auto *declNS = llvm::dyn_cast<clang::NamespaceDecl>(declDC)) {
8244 if (declNS->isAnonymousNamespace() || declNS->isInlineNamespace()) {
8245 declDC = declNS->getParent();
8246 continue;
8247 }
8248 }
8249 break;
8250 }
8251
8252 return declDC->Equals(ctxt);
8253}
8254
8255////////////////////////////////////////////////////////////////////////////////
8256
8262
8263////////////////////////////////////////////////////////////////////////////////
8264
8266{
8267 delete (TClingClassInfo*) cinfo;
8268}
8269
8270////////////////////////////////////////////////////////////////////////////////
8271
8277
8278////////////////////////////////////////////////////////////////////////////////
8279
8285
8286////////////////////////////////////////////////////////////////////////////////
8287
8293
8294////////////////////////////////////////////////////////////////////////////////
8295
8301
8302////////////////////////////////////////////////////////////////////////////////
8303
8308
8309////////////////////////////////////////////////////////////////////////////////
8310
8316
8322
8323
8324////////////////////////////////////////////////////////////////////////////////
8325
8326int TCling::ClassInfo_GetMethodNArg(ClassInfo_t* cinfo, const char* method, const char* proto, Bool_t objectIsConst /* = false */, EFunctionMatchMode mode /* = kConversionMatch */) const
8327{
8329 return TClinginfo->GetMethodNArg(method, proto, objectIsConst, mode);
8330}
8331
8332////////////////////////////////////////////////////////////////////////////////
8333
8339
8340////////////////////////////////////////////////////////////////////////////////
8341
8343{
8345 return TClinginfo->HasMethod(name);
8346}
8347
8348////////////////////////////////////////////////////////////////////////////////
8349
8356
8357////////////////////////////////////////////////////////////////////////////////
8358
8365
8366////////////////////////////////////////////////////////////////////////////////
8367
8369{
8371 return TClinginfo->IsBase(name);
8372}
8373
8374////////////////////////////////////////////////////////////////////////////////
8375
8376bool TCling::ClassInfo_IsEnum(const char* name) const
8377{
8379}
8380
8381////////////////////////////////////////////////////////////////////////////////
8382
8388
8389
8390////////////////////////////////////////////////////////////////////////////////
8391
8397
8398
8399////////////////////////////////////////////////////////////////////////////////
8400
8402{
8404 return TClinginfo->IsLoaded();
8405}
8406
8407////////////////////////////////////////////////////////////////////////////////
8408
8410{
8412 return TClinginfo->IsValid();
8413}
8414
8415////////////////////////////////////////////////////////////////////////////////
8416
8417bool TCling::ClassInfo_IsValidMethod(ClassInfo_t* cinfo, const char* method, const char* proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8418{
8420 return TClinginfo->IsValidMethod(method, proto, false, offset, mode);
8421}
8422
8423////////////////////////////////////////////////////////////////////////////////
8424
8426{
8428 return TClinginfo->IsValidMethod(method, proto, objectIsConst, offset, mode);
8429}
8430
8431////////////////////////////////////////////////////////////////////////////////
8432
8438
8439////////////////////////////////////////////////////////////////////////////////
8440
8446
8447////////////////////////////////////////////////////////////////////////////////
8448
8454
8455////////////////////////////////////////////////////////////////////////////////
8456
8458{
8460 return TClinginfo->New(n, arena,*fNormalizedCtxt);
8461}
8462
8463////////////////////////////////////////////////////////////////////////////////
8464
8470
8471////////////////////////////////////////////////////////////////////////////////
8472
8478
8479////////////////////////////////////////////////////////////////////////////////
8480
8486
8487////////////////////////////////////////////////////////////////////////////////
8488
8494
8495////////////////////////////////////////////////////////////////////////////////
8496
8498{
8500 return TClinginfo->FileName();
8501}
8502
8503////////////////////////////////////////////////////////////////////////////////
8504
8506{
8508 TTHREAD_TLS_DECL(std::string,output);
8509 TClinginfo->FullName(output,*fNormalizedCtxt);
8510 return output.c_str(); // NOLINT
8511}
8512
8513////////////////////////////////////////////////////////////////////////////////
8514
8516{
8518 return TClinginfo->Name();
8519}
8520
8521////////////////////////////////////////////////////////////////////////////////
8522
8524{
8526 return TClinginfo->Title();
8527}
8528
8529////////////////////////////////////////////////////////////////////////////////
8530
8532{
8534 return TClinginfo->TmpltName();
8535}
8536
8537
8538
8539//______________________________________________________________________________
8540//
8541// BaseClassInfo interface
8542//
8543
8544////////////////////////////////////////////////////////////////////////////////
8545
8550
8551////////////////////////////////////////////////////////////////////////////////
8552
8559
8560////////////////////////////////////////////////////////////////////////////////
8561
8570
8571////////////////////////////////////////////////////////////////////////////////
8572
8578
8579////////////////////////////////////////////////////////////////////////////////
8580
8586
8587////////////////////////////////////////////////////////////////////////////////
8588
8594
8595////////////////////////////////////////////////////////////////////////////////
8596
8598{
8601 // Offset to the class itself.
8602 if (TClinginfo->GetDecl() == TClinginfoBase->GetDecl()) {
8603 return 0;
8604 }
8605 return TClinginfo->GetBaseOffset(TClinginfoBase, address, isDerivedObject);
8606}
8607
8608////////////////////////////////////////////////////////////////////////////////
8609
8615
8616////////////////////////////////////////////////////////////////////////////////
8617
8623
8624////////////////////////////////////////////////////////////////////////////////
8625
8631
8632////////////////////////////////////////////////////////////////////////////////
8633
8635{
8637 TTHREAD_TLS_DECL(std::string,output);
8638 TClinginfo->FullName(output,*fNormalizedCtxt);
8639 return output.c_str(); // NOLINT
8640}
8641
8642////////////////////////////////////////////////////////////////////////////////
8643
8649
8650////////////////////////////////////////////////////////////////////////////////
8651
8657
8658//______________________________________________________________________________
8659//
8660// DataMemberInfo interface
8661//
8662
8663////////////////////////////////////////////////////////////////////////////////
8664
8670
8671////////////////////////////////////////////////////////////////////////////////
8672
8677
8678////////////////////////////////////////////////////////////////////////////////
8679
8686
8687////////////////////////////////////////////////////////////////////////////////
8688
8690{
8692 const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
8693 const clang::ValueDecl* vd = llvm::dyn_cast_or_null<clang::ValueDecl>(decl);
8695}
8696
8697////////////////////////////////////////////////////////////////////////////////
8698
8704
8705////////////////////////////////////////////////////////////////////////////////
8706
8712
8713////////////////////////////////////////////////////////////////////////////////
8714
8720
8721////////////////////////////////////////////////////////////////////////////////
8722
8728
8729////////////////////////////////////////////////////////////////////////////////
8730
8736
8737////////////////////////////////////////////////////////////////////////////////
8738
8744
8745////////////////////////////////////////////////////////////////////////////////
8746
8752
8753////////////////////////////////////////////////////////////////////////////////
8754
8760
8761////////////////////////////////////////////////////////////////////////////////
8762
8768
8769////////////////////////////////////////////////////////////////////////////////
8770
8776
8777////////////////////////////////////////////////////////////////////////////////
8778
8784
8785////////////////////////////////////////////////////////////////////////////////
8786
8792
8793////////////////////////////////////////////////////////////////////////////////
8794
8796{
8797 TTHREAD_TLS_DECL(std::string,result);
8798
8800 result = TClinginfo->ValidArrayIndex().str();
8801 return result.c_str(); // NOLINT
8802}
8803
8804////////////////////////////////////////////////////////////////////////////////
8805
8807{
8808 Decl* decl = static_cast<Decl*>(const_cast<void*>(declId));
8809 ASTContext &C = decl->getASTContext();
8810 decl->addAttr(AnnotateAttr::CreateImplicit(C, attribute, nullptr, 0));
8811}
8812
8813//______________________________________________________________________________
8814//
8815// Function Template interface
8816//
8817
8818////////////////////////////////////////////////////////////////////////////////
8819
8820static void ConstructorName(std::string &name, const clang::Decl *decl,
8821 cling::Interpreter &interp,
8823{
8824 const clang::TypeDecl* td = llvm::dyn_cast<clang::TypeDecl>(decl->getDeclContext());
8825 if (!td) return;
8826
8827 clang::QualType qualType(td->getTypeForDecl(),0);
8829 unsigned int level = 0;
8830 for(size_t cursor = name.length()-1; cursor != 0; --cursor) {
8831 if (name[cursor] == '>') ++level;
8832 else if (name[cursor] == '<' && level) --level;
8833 else if (level == 0 && name[cursor] == ':') {
8834 name.erase(0,cursor+1);
8835 break;
8836 }
8837 }
8838}
8839
8840////////////////////////////////////////////////////////////////////////////////
8841
8842void TCling::GetFunctionName(const clang::Decl *decl, std::string &output) const
8843{
8844 output.clear();
8845
8846 const auto *FD = llvm::dyn_cast<clang::FunctionDecl>(decl);
8847 if (const auto *USD = llvm::dyn_cast<clang::UsingShadowDecl>(decl)) {
8848 FD = llvm::dyn_cast<clang::FunctionDecl>(USD->getTargetDecl());
8849 }
8850 if (!FD) {
8851 Error("GetFunctionName", "NULL Decl!");
8852 return;
8853 }
8854
8855 // For using-decls, show "Derived", not "Base", i.e. use the
8856 // name of the decl context of the UsingShadowDecl (aka `decl`)
8857 // not the name of FD's decl context.
8858 if (llvm::isa<clang::CXXConstructorDecl>(FD))
8859 {
8861
8862 } else if (llvm::isa<clang::CXXDestructorDecl>(decl))
8863 {
8865 output.insert(output.begin(), '~');
8866 } else {
8867 llvm::raw_string_ostream stream(output);
8868 auto printPolicy = decl->getASTContext().getPrintingPolicy();
8869 // Don't trigger fopen of the source file to count lines:
8870 printPolicy.AnonymousTagLocations = false;
8871 FD->getNameForDiagnostic(stream, printPolicy, /*Qualified=*/false);
8872 }
8873}
8874
8875////////////////////////////////////////////////////////////////////////////////
8876/// Return a unique identifier of the declaration represented by the
8877/// FuncTempInfo
8878
8883
8884////////////////////////////////////////////////////////////////////////////////
8885/// Delete the FuncTempInfo_t
8886
8888{
8889 // Currently the address of ft_info is actually the decl itself,
8890 // so we have nothing to do.
8891}
8892
8893////////////////////////////////////////////////////////////////////////////////
8894/// Construct a FuncTempInfo_t
8895
8897{
8898 // Currently the address of ft_info is actually the decl itself,
8899 // so we have nothing to do.
8900
8901 return (FuncTempInfo_t*)const_cast<void*>(declid);
8902}
8903
8904////////////////////////////////////////////////////////////////////////////////
8905/// Construct a FuncTempInfo_t
8906
8908{
8909 // Currently the address of ft_info is actually the decl itself,
8910 // so we have nothing to do.
8911
8912 return (FuncTempInfo_t*)ft_info;
8913}
8914
8915////////////////////////////////////////////////////////////////////////////////
8916/// Check validity of a FuncTempInfo_t
8917
8919{
8920 // Currently the address of ft_info is actually the decl itself,
8921 // so we have nothing to do.
8922
8923 return t_info != nullptr;
8924}
8925
8926////////////////////////////////////////////////////////////////////////////////
8927/// Return the maximum number of template arguments of the
8928/// function template described by ft_info.
8929
8931{
8932 if (!ft_info) return 0;
8933 const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
8934 return ft->getTemplateParameters()->size();
8935}
8936
8937////////////////////////////////////////////////////////////////////////////////
8938/// Return the number of required template arguments of the
8939/// function template described by ft_info.
8940
8942{
8943 if (!ft_info) return 0;
8944 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8945 return ft->getTemplateParameters()->getMinRequiredArguments();
8946}
8947
8948////////////////////////////////////////////////////////////////////////////////
8949/// Return the property of the function template.
8950
8952{
8953 if (!ft_info) return 0;
8954
8955 long property = 0L;
8956 property |= kIsCompiled;
8957
8958 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8959
8960 switch (ft->getAccess()) {
8961 case clang::AS_public:
8962 property |= kIsPublic;
8963 break;
8964 case clang::AS_protected:
8965 property |= kIsProtected;
8966 break;
8967 case clang::AS_private:
8968 property |= kIsPrivate;
8969 break;
8970 case clang::AS_none:
8971 if (ft->getDeclContext()->isNamespace())
8973 break;
8974 default:
8975 // IMPOSSIBLE
8976 assert(false && "Unexpected value for the access property value in Clang");
8977 break;
8978 }
8979
8980 const clang::FunctionDecl *fd = ft->getTemplatedDecl();
8981
8982 if (fd && fd->getStorageClass() == clang::SC_Static)
8983 property |= kIsStatic;
8984
8985 if (const clang::CXXMethodDecl *md =
8986 llvm::dyn_cast<clang::CXXMethodDecl>(fd)) {
8987 if (md->getMethodQualifiers().hasConst()) {
8988 property |= kIsConstant | kIsConstMethod;
8989 }
8990 if (md->isVirtual()) {
8991 property |= kIsVirtual;
8992 }
8993 if (md->isPureVirtual()) {
8994 property |= kIsPureVirtual;
8995 }
8996 if (const clang::CXXConstructorDecl *cd =
8997 llvm::dyn_cast<clang::CXXConstructorDecl>(md)) {
8998 if (cd->isExplicit()) {
8999 property |= kIsExplicit;
9000 }
9001 }
9002 else if (const clang::CXXConversionDecl *cd =
9003 llvm::dyn_cast<clang::CXXConversionDecl>(md)) {
9004 if (cd->isExplicit()) {
9005 property |= kIsExplicit;
9006 }
9007 }
9008 }
9009 return property;
9010}
9011
9012////////////////////////////////////////////////////////////////////////////////
9013/// Return the property not already defined in Property
9014/// See TDictionary's EFunctionProperty
9015
9017{
9018 if (!ft_info) return 0;
9019
9020 long property = 0L;
9021 property |= kIsCompiled;
9022
9023 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9024 const clang::FunctionDecl *fd = ft->getTemplatedDecl();
9025
9026 if (fd->isOverloadedOperator())
9028 if (llvm::isa<clang::CXXConversionDecl>(fd))
9030 if (llvm::isa<clang::CXXConstructorDecl>(fd))
9032 if (llvm::isa<clang::CXXDestructorDecl>(fd))
9034 if (fd->isInlined())
9036 return property;
9037}
9038
9039////////////////////////////////////////////////////////////////////////////////
9040/// Return the name of this function template.
9041
9043{
9044 output.Clear();
9045 if (!ft_info) return;
9046 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9047 std::string buf;
9048 GetFunctionName(ft->getTemplatedDecl(), buf);
9049 output = buf;
9050}
9051
9052////////////////////////////////////////////////////////////////////////////////
9053/// Return the comments associates with this function template.
9054
9056{
9057 output.Clear();
9058 if (!ft_info) return;
9059 const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
9060
9061 // Iterate over the redeclarations, we can have multiple definitions in the
9062 // redecl chain (came from merging of pcms).
9065 if (AnnotateAttr *A = AnnotFD->getAttr<AnnotateAttr>()) {
9066 output = A->getAnnotation().str();
9067 return;
9068 }
9069 }
9070 if (!ft->isFromASTFile()) {
9071 // Try to get the comment from the header file if present
9072 // but not for decls from AST file, where rootcling would have
9073 // created an annotation
9075 }
9076}
9077
9078
9079//______________________________________________________________________________
9080//
9081// MethodInfo interface
9082//
9083
9084////////////////////////////////////////////////////////////////////////////////
9085/// Interface to cling function
9086
9087void TCling::MethodInfo_Delete(MethodInfo_t* minfo) const
9088{
9089 delete(TClingMethodInfo*) minfo;
9090}
9091
9092////////////////////////////////////////////////////////////////////////////////
9093
9095{
9097 // The next call locks the interpreter mutex.
9098 info->CreateSignature(signature);
9099}
9100
9101////////////////////////////////////////////////////////////////////////////////
9102
9103MethodInfo_t* TCling::MethodInfo_Factory() const
9104{
9106 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl());
9107}
9108
9109////////////////////////////////////////////////////////////////////////////////
9110
9112{
9114 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), (TClingClassInfo*)clinfo);
9115}
9116
9117////////////////////////////////////////////////////////////////////////////////
9118
9120{
9121 const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
9123 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), decl);
9124}
9125
9126////////////////////////////////////////////////////////////////////////////////
9127
9128MethodInfo_t* TCling::MethodInfo_FactoryCopy(MethodInfo_t* minfo) const
9129{
9130 return (MethodInfo_t*) new TClingMethodInfo(*(TClingMethodInfo*)minfo);
9131}
9132
9133////////////////////////////////////////////////////////////////////////////////
9134
9136{
9138 // The next call locks the interpreter mutex.
9139 return info->InterfaceMethod();
9140}
9141
9142////////////////////////////////////////////////////////////////////////////////
9143
9144bool TCling::MethodInfo_IsValid(MethodInfo_t* minfo) const
9145{
9147 return info->IsValid();
9148}
9149
9150////////////////////////////////////////////////////////////////////////////////
9151
9152int TCling::MethodInfo_NArg(MethodInfo_t* minfo) const
9153{
9155 return info->NArg();
9156}
9157
9158////////////////////////////////////////////////////////////////////////////////
9159
9161{
9163 return info->NDefaultArg();
9164}
9165
9166////////////////////////////////////////////////////////////////////////////////
9167
9168int TCling::MethodInfo_Next(MethodInfo_t* minfo) const
9169{
9171 return info->Next();
9172}
9173
9174////////////////////////////////////////////////////////////////////////////////
9175
9177{
9179 // The next call locks the interpreter mutex.
9180 return info->Property();
9181}
9182
9183////////////////////////////////////////////////////////////////////////////////
9184
9186{
9188 // The next call locks the interpreter mutex.
9189 return info->ExtraProperty();
9190}
9191
9192////////////////////////////////////////////////////////////////////////////////
9193
9195{
9197 // The next call locks the interpreter mutex.
9198 return (TypeInfo_t*)info->Type();
9199}
9200
9201////////////////////////////////////////////////////////////////////////////////
9202
9203const char* TCling::MethodInfo_GetMangledName(MethodInfo_t* minfo) const
9204{
9207 // The next call locks the interpreter mutex.
9208 mangled_name = info->GetMangledName();
9209 return mangled_name;
9210}
9211
9212////////////////////////////////////////////////////////////////////////////////
9213
9214const char* TCling::MethodInfo_GetPrototype(MethodInfo_t* minfo) const
9215{
9217 // The next call locks the interpreter mutex.
9218 return info->GetPrototype();
9219}
9220
9221////////////////////////////////////////////////////////////////////////////////
9222
9223const char* TCling::MethodInfo_Name(MethodInfo_t* minfo) const
9224{
9226 // The next call locks the interpreter mutex.
9227 return info->Name();
9228}
9229
9230////////////////////////////////////////////////////////////////////////////////
9231
9232const char* TCling::MethodInfo_TypeName(MethodInfo_t* minfo) const
9233{
9235 // The next call locks the interpreter mutex.
9236 return info->TypeName();
9237}
9238
9239////////////////////////////////////////////////////////////////////////////////
9240
9241std::string TCling::MethodInfo_TypeNormalizedName(MethodInfo_t* minfo) const
9242{
9244 // The next part locks the interpreter mutex.
9245 if (info && info->IsValid())
9246 return info->Type()->NormalizedName(*fNormalizedCtxt);
9247 else
9248 return "";
9249}
9250
9251////////////////////////////////////////////////////////////////////////////////
9252
9253const char* TCling::MethodInfo_Title(MethodInfo_t* minfo) const
9254{
9256 // The next call locks the interpreter mutex.
9257 return info->Title();
9258}
9259
9260////////////////////////////////////////////////////////////////////////////////
9261
9263{
9264 if (func) {
9265 return MethodInfo_MethodCallReturnType(func->fInfo);
9266 } else {
9267 return EReturnType::kOther;
9268 }
9269}
9270
9271////////////////////////////////////////////////////////////////////////////////
9272
9274{
9276 if (info && info->IsValid()) {
9277 TClingTypeInfo *typeinfo = info->Type();
9278 clang::QualType QT( typeinfo->GetQualType().getCanonicalType() );
9279 if (QT->isEnumeralType()) {
9280 return EReturnType::kLong;
9281 } else if (QT->isPointerType()) {
9282 // Look for char*
9283 QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
9284 if ( QT->isCharType() ) {
9285 return EReturnType::kString;
9286 } else {
9287 return EReturnType::kOther;
9288 }
9289 } else if ( QT->isFloatingType() ) {
9290 int sz = typeinfo->Size();
9291 if (sz == 4 || sz == 8) {
9292 // Support only float and double.
9293 return EReturnType::kDouble;
9294 } else {
9295 return EReturnType::kOther;
9296 }
9297 } else if ( QT->isIntegerType() ) {
9298 int sz = typeinfo->Size();
9299 if (sz <= 8) {
9300 // Support only up to long long ... but
9301 // FIXME the TMethodCall::Execute only
9302 // return long (4 bytes) ...
9303 // The v5 implementation of TMethodCall::ReturnType
9304 // was not making the distinction so we let it go
9305 // as is for now, but we really need to upgrade
9306 // TMethodCall::Execute ...
9307 return EReturnType::kLong;
9308 } else {
9309 return EReturnType::kOther;
9310 }
9311 } else {
9312 return EReturnType::kOther;
9313 }
9314 } else {
9315 return EReturnType::kOther;
9316 }
9317}
9318
9319//______________________________________________________________________________
9320//
9321// MethodArgInfo interface
9322//
9323
9324////////////////////////////////////////////////////////////////////////////////
9325
9330
9331////////////////////////////////////////////////////////////////////////////////
9332
9338
9339////////////////////////////////////////////////////////////////////////////////
9340
9346
9347////////////////////////////////////////////////////////////////////////////////
9348
9354
9355////////////////////////////////////////////////////////////////////////////////
9356
9362
9363////////////////////////////////////////////////////////////////////////////////
9364
9370
9371////////////////////////////////////////////////////////////////////////////////
9372
9378
9379////////////////////////////////////////////////////////////////////////////////
9380
9382{
9384 return info->DefaultValue();
9385}
9386
9387////////////////////////////////////////////////////////////////////////////////
9388
9390{
9392 return info->Name();
9393}
9394
9395////////////////////////////////////////////////////////////////////////////////
9396
9398{
9400 return info->TypeName();
9401}
9402
9403////////////////////////////////////////////////////////////////////////////////
9404
9406{
9408 return info->Type()->NormalizedName(*fNormalizedCtxt);
9409}
9410
9411////////////////////////////////////////////////////////////////////////////////
9412
9418
9419//______________________________________________________________________________
9420//
9421// TypeInfo interface
9422//
9423
9424////////////////////////////////////////////////////////////////////////////////
9425
9427{
9428 delete (TClingTypeInfo*) tinfo;
9429}
9430
9431////////////////////////////////////////////////////////////////////////////////
9432
9438
9439////////////////////////////////////////////////////////////////////////////////
9440
9446
9447////////////////////////////////////////////////////////////////////////////////
9448
9453
9454////////////////////////////////////////////////////////////////////////////////
9455
9462
9463////////////////////////////////////////////////////////////////////////////////
9464
9466{
9468 return TClinginfo->IsValid();
9469}
9470
9471////////////////////////////////////////////////////////////////////////////////
9472
9474{
9476 return TClinginfo->Name();
9477}
9478
9479////////////////////////////////////////////////////////////////////////////////
9480
9486
9487////////////////////////////////////////////////////////////////////////////////
9488
9490{
9492 return TClinginfo->RefType();
9493}
9494
9495////////////////////////////////////////////////////////////////////////////////
9496
9498{
9500 return TClinginfo->Size();
9501}
9502
9503////////////////////////////////////////////////////////////////////////////////
9504
9506{
9508 return TClinginfo->TrueName(*fNormalizedCtxt);
9509}
9510
9511////////////////////////////////////////////////////////////////////////////////
9512
9514{
9516 return TClinginfo->QualTypePtr();
9517}
9518
9519
9520//______________________________________________________________________________
9521//
9522// TypedefInfo interface
9523//
9524
9525////////////////////////////////////////////////////////////////////////////////
9526
9531
9532////////////////////////////////////////////////////////////////////////////////
9533
9539
9540////////////////////////////////////////////////////////////////////////////////
9541
9547
9548////////////////////////////////////////////////////////////////////////////////
9549
9554
9555////////////////////////////////////////////////////////////////////////////////
9556
9564
9565////////////////////////////////////////////////////////////////////////////////
9566
9572
9573////////////////////////////////////////////////////////////////////////////////
9574
9580
9581////////////////////////////////////////////////////////////////////////////////
9582
9588
9589////////////////////////////////////////////////////////////////////////////////
9590
9596
9597////////////////////////////////////////////////////////////////////////////////
9598
9604
9605////////////////////////////////////////////////////////////////////////////////
9606
9608{
9610 return TClinginfo->Name();
9611}
9612
9613////////////////////////////////////////////////////////////////////////////////
9614
9616{
9618 return TClinginfo->Title();
9619}
9620
9621////////////////////////////////////////////////////////////////////////////////
9622
9623bool TCling::IsSameType(const void * QualTypePtr1, const void * QualTypePtr2) const
9624{
9625 clang::QualType QT1 = clang::QualType::getFromOpaquePtr(QualTypePtr1);
9626 clang::QualType QT2 = clang::QualType::getFromOpaquePtr(QualTypePtr2);
9627 return fInterpreter->getCI()->getASTContext().hasSameType(QT1, QT2);
9628}
9629
9630////////////////////////////////////////////////////////////////////////////////
9631
9632bool TCling::IsIntegerType(const void * QualTypePtr) const
9633{
9634 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9635 return QT->hasIntegerRepresentation();
9636}
9637
9638////////////////////////////////////////////////////////////////////////////////
9639
9640bool TCling::IsSignedIntegerType(const void * QualTypePtr) const
9641{
9642 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9643 return QT->hasSignedIntegerRepresentation();
9644}
9645
9646////////////////////////////////////////////////////////////////////////////////
9647
9648bool TCling::IsUnsignedIntegerType(const void * QualTypePtr) const
9649{
9650 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9651 return QT->hasUnsignedIntegerRepresentation();
9652}
9653
9654////////////////////////////////////////////////////////////////////////////////
9655
9656bool TCling::IsFloatingType(const void * QualTypePtr) const
9657{
9658 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9659 return QT->hasFloatingRepresentation();
9660}
9661
9662////////////////////////////////////////////////////////////////////////////////
9663
9664bool TCling::IsPointerType(const void * QualTypePtr) const
9665{
9666 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9667 return QT->hasPointerRepresentation();
9668}
9669
9670////////////////////////////////////////////////////////////////////////////////
9671
9672bool TCling::IsVoidPointerType(const void * QualTypePtr) const
9673{
9674 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9675 return QT->isVoidPointerType();
9676}
9677
9678////////////////////////////////////////////////////////////////////////////////
9679
9681{
9682 if (!fInitialMutex) {
9684 Error("SnapshotMutexState", "fRecurseCount != 0 even though initial mutex state is unset!");
9685 }
9686 fInitialMutex.fState = mtx->GetStateBefore();
9687 }
9688 // We will "forget" this lock once we backed out of all interpreter frames.
9689 // Here we are entering one, so ++.
9691}
9692
9693////////////////////////////////////////////////////////////////////////////////
9694
9696{
9697 if (!fInitialMutex)
9698 return;
9699 if (fInitialMutex.fRecurseCount == 0) {
9700 Error("ForgetMutexState", "mutex state's recurse count already 0!");
9701 }
9702 else if (--fInitialMutex.fRecurseCount == 0) {
9703 // We have returned from all interpreter frames. Reset the initial lock state.
9704 fInitialMutex.fState.reset();
9705 }
9706}
9707
9708////////////////////////////////////////////////////////////////////////////////
9709/// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
9710
9712{
9713 if (gInterpreterMutex) {
9714 if (delta) {
9715 auto typedDelta = static_cast<MutexStateAndRecurseCountDelta *>(delta);
9716 std::unique_ptr<MutexStateAndRecurseCountDelta> uniqueP{typedDelta};
9717 gCoreMutex->Apply(std::move(typedDelta->fDelta));
9718 // Now that we have the lock, update the global
9719 R__ASSERT(fInitialMutex.fRecurseCount == 0 && "Inconsistent state of fInitialMutex! Another thread within Interpreter critical section.");
9720 std::swap(fInitialMutex, typedDelta->fInitialState);
9721 } else {
9722 // This case happens when EnableThreadSafety is first called from
9723 // the interpreter function we just handled.
9724 // Since thread safety was not enabled at the time we rewound, there was
9725 // no lock taken and even-though we should be locking the rest of this
9726 // interpreter handling/modifying code (since there might be threads in
9727 // flight), we can't because there would not be any lock guard to release the
9728 // locks
9730 Error("ApplyToInterpreterMutex",
9731 "After returning from user code that turned on thread safety support, we notice that fInitialMutex is already used ... "
9732 "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.");
9733 }
9734 }
9735}
9736
9737////////////////////////////////////////////////////////////////////////////////
9738/// Reset the interpreter lock to the state it had before interpreter-related
9739/// calls happened.
9740
9742{
9743 if (fInitialMutex) {
9744 // Need to start a new recurse count.
9745 std::unique_ptr<MutexStateAndRecurseCountDelta> uniqueP(new MutexStateAndRecurseCountDelta());
9746 std::swap(uniqueP->fInitialState, fInitialMutex);
9747 uniqueP->fDelta = gCoreMutex->Rewind(*uniqueP->fInitialState.fState);
9748 return uniqueP.release();
9749 }
9751 return nullptr;
9752}
#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 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:7331
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:3973
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:3197
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:4015
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:3991
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:8820
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:7240
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:7075
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:6400
static bool requiresRootMap(const char *rootmapfile)
Definition TCling.cxx:5580
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:7352
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:6272
const char * MethodArgInfo_DefaultValue(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9381
bool ClassInfo_IsScopedEnum(ClassInfo_t *info) const final
Definition TCling.cxx:8383
const char * TypeInfo_Name(TypeInfo_t *) const final
Definition TCling.cxx:9473
void * MethodInfo_InterfaceMethod(MethodInfo_t *minfo) const final
Definition TCling.cxx:9135
void LoadEnums(TListOfEnums &cl) const final
Create list of pointers to enums for TClass cl.
Definition TCling.cxx:4463
void UpdateListOfGlobals() final
No op: see TClingCallbacks (used to update the list of globals)
Definition TCling.cxx:3953
bool TypedefInfo_IsValid(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9567
Int_t AutoLoad(const char *classname, Bool_t knowDictNotLoaded=kFALSE) final
Load library containing the specified class.
Definition TCling.cxx:6333
void CallFunc_Init(CallFunc_t *func) const final
Definition TCling.cxx:8021
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:3716
bool LibraryLoadingFailed(const std::string &, const std::string &, bool, bool)
Definition TCling.cxx:6636
void GenericError(const char *error) const final
Let the interpreter issue a generic error, and set its error state.
Definition TCling.cxx:7536
std::vector< void * > fRegisterModuleDyLibs
Definition TCling.h:138
void CallFunc_ExecWithReturn(CallFunc_t *func, void *address, void *ret) const final
Definition TCling.cxx:7947
bool IsIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9632
TypeInfo_t * MethodInfo_Type(MethodInfo_t *minfo) const final
Definition TCling.cxx:9194
std::vector< std::string > fAutoLoadLibStorage
Definition TCling.h:118
void CallFunc_Delete(CallFunc_t *func) const final
Definition TCling.cxx:7924
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:7579
void ResetAll() final
Reset the Cling state to its initial state.
Definition TCling.cxx:3792
void SetDeclAttr(DeclId_t, const char *) final
Definition TCling.cxx:8806
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:6970
Long_t MethodInfo_Property(MethodInfo_t *minfo) const final
Definition TCling.cxx:9176
virtual void LoadFunctionTemplates(TClass *cl) const final
Create list of pointers to function templates for TClass cl.
Definition TCling.cxx:4510
bool ClassInfo_IsValidMethod(ClassInfo_t *info, const char *method, const char *proto, Longptr_t *offset, ROOT::EFunctionMatchMode=ROOT::kConversionMatch) const final
Definition TCling.cxx:8417
Long_t DataMemberInfo_Property(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8739
int SetClassAutoparsing(int) final
Enable/Disable the Autoparsing of headers.
Definition TCling.cxx:7664
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:4557
void RewindDictionary() final
Rewind Cling dictionary to the point where it was before executing the current macro.
Definition TCling.cxx:3837
bool ClassInfo_IsValid(ClassInfo_t *info) const final
Definition TCling.cxx:8409
void UpdateListsOnCommitted(const cling::Transaction &T)
Definition TCling.cxx:6844
int TypeInfo_RefType(TypeInfo_t *) const final
Definition TCling.cxx:9489
void CreateListOfBaseClasses(TClass *cl) const final
Create list of pointers to base class(es) for TClass cl.
Definition TCling.cxx:4439
ClassInfo_t * ClassInfo_Factory(Bool_t all=kTRUE) const final
Definition TCling.cxx:8296
const char * MethodInfo_Name(MethodInfo_t *minfo) const final
Definition TCling.cxx:9223
BaseClassInfo_t * BaseClassInfo_Factory(ClassInfo_t *info) const final
Definition TCling.cxx:8553
Bool_t LoadText(const char *text) const final
Load the declarations from text into the interpreter.
Definition TCling.cxx:7594
const char * GetSharedLibDeps(const char *lib, bool tryDyld=false) final
Get the list a libraries on which the specified lib depends.
Definition TCling.cxx:7368
EReturnType MethodInfo_MethodCallReturnType(MethodInfo_t *minfo) const final
Definition TCling.cxx:9273
TObject * GetObjectAddress(const char *Name, void *&LookupCtx)
If the interpreter encounters Name, check whether that is an object ROOT could retrieve.
Definition TCling.cxx:7795
Longptr_t ProcessLineAsynch(const char *line, EErrorCode *error=nullptr)
Let cling process a command line asynch.
Definition TCling.cxx:3628
bool MethodInfo_IsValid(MethodInfo_t *minfo) const final
Definition TCling.cxx:9144
FuncTempInfo_t * FuncTempInfo_Factory(DeclId_t declid) const final
Construct a FuncTempInfo_t.
Definition TCling.cxx:8896
TypeInfo_t * TypeInfo_Factory() const final
Definition TCling.cxx:9433
bool IsClassAutoLoadingEnabled() const
Returns if class AutoLoading is currently enabled.
Definition TCling.cxx:7633
void InvalidateGlobal(const clang::Decl *D)
Invalidate cached TCling information for the given global declaration.
Definition TCling.cxx:6955
bool IsSameType(const void *QualTypePtr1, const void *QualTypePtr2) const final
Definition TCling.cxx:9623
int Evaluate(const char *, TInterpreterValue &) final
Get the interpreter value corresponding to the statement.
Definition TCling.cxx:7757
std::unique_ptr< TInterpreterValue > MakeInterpreterValue() const final
Definition TCling.cxx:7742
void UpdateListOfLoadedSharedLibraries()
Definition TCling.cxx:3416
const char * TypedefInfo_Title(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9615
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:8146
void InitRootmapFile(const char *name)
Create a resource table and read the (possibly) three resource files, i.e.
Definition TCling.cxx:5723
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:6591
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:4575
virtual ~TCling()
Destroy the interpreter interface.
Definition TCling.cxx:1670
void AddFriendToClass(clang::FunctionDecl *, clang::CXXRecordDecl *) const
Inject function as a friend into klass.
Definition TCling.cxx:7848
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:8573
void RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
Internal function. Actually do the update of the ClassInfo when seeing.
Definition TCling.cxx:6702
CallFunc_t * CallFunc_FactoryCopy(CallFunc_t *func) const final
Definition TCling.cxx:7998
Double_t CallFunc_ExecDouble(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7982
void CallFunc_ResetArg(CallFunc_t *func) const final
Definition TCling.cxx:8047
const char * GetCurrentMacroName() const final
Return the file name of the currently interpreted file, included or not.
Definition TCling.cxx:5531
Bool_t IsLoaded(const char *filename) const final
Return true if the file has already been loaded by cint.
Definition TCling.cxx:3240
void SaveGlobalsContext() final
Save the current Cling state of global objects.
Definition TCling.cxx:3940
void CallFunc_IgnoreExtraArgs(CallFunc_t *func, bool ignore) const final
Definition TCling.cxx:8013
void ApplyToInterpreterMutex(void *delta)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
Definition TCling.cxx:9711
void * LazyFunctionCreatorAutoload(const std::string &mangled_name)
Autoload a library based on a missing symbol.
Definition TCling.cxx:6659
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:4791
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:8212
Bool_t IsLibraryLoaded(const char *libname) const final
Definition TCling.cxx:3206
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:7558
int DataMemberInfo_ArrayDim(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8665
DataMemberInfo_t * DataMemberInfo_FactoryCopy(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8699
Bool_t HandleNewTransaction(const cling::Transaction &T)
Helper function to increase the internal Cling count of transactions that change the AST.
Definition TCling.cxx:3733
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:5596
std::map< SpecialObjectLookupCtx_t, SpecialObjectMap_t > fSpecialObjectMaps
Definition TCling.h:153
int ClassInfo_Next(ClassInfo_t *info) const final
Definition TCling.cxx:8433
void SetErrmsgcallback(void *p) const final
Set a callback to receive error messages.
Definition TCling.cxx:7685
bool MethodArgInfo_IsValid(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9357
int TypeInfo_Size(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9497
Int_t DeleteGlobal(void *obj) final
Delete obj from Cling symbol table so it cannot be accessed anymore.
Definition TCling.cxx:3851
int GetSecurityError() const final
Interface to cling function.
Definition TCling.cxx:7566
void SetTempLevel(int val) const final
Create / close a scope for temporaries.
Definition TCling.cxx:7721
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:8930
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:5223
TypedefInfo_t * TypedefInfo_Factory() const final
Definition TCling.cxx:9534
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:8481
const char * MethodArgInfo_TypeName(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9397
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:5471
std::vector< std::pair< TClass *, DictFuncPtr_t > > fClassesToUpdate
Definition TCling.h:146
int DataMemberInfo_Next(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8723
const char * TypedefInfo_Name(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9607
void BaseClassInfo_Delete(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8546
Long_t MethodInfo_ExtraProperty(MethodInfo_t *minfo) const final
Definition TCling.cxx:9185
void LoadMacro(const char *filename, EErrorCode *error=nullptr) final
Load a macro file in cling's memory.
Definition TCling.cxx:3620
FuncTempInfo_t * FuncTempInfo_FactoryCopy(FuncTempInfo_t *) const final
Construct a FuncTempInfo_t.
Definition TCling.cxx:8907
int DataMemberInfo_MaxIndex(DataMemberInfo_t *dminfo, Int_t dim) const final
Definition TCling.cxx:8715
Bool_t FuncTempInfo_IsValid(FuncTempInfo_t *) const final
Check validity of a FuncTempInfo_t.
Definition TCling.cxx:8918
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:8368
void RecursiveRemove(TObject *obj) final
Delete object from cling symbol table so it can not be used anymore.
Definition TCling.cxx:3751
const char * DataMemberInfo_TypeName(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8763
DeclId_t GetDataMemberAtAddr(const void *addr) const final
Return pointer to cling DeclId for a data member with a given name.
Definition TCling.cxx:5018
void CallFunc_SetArgArray(CallFunc_t *func, Longptr_t *paramArr, Int_t nparam) const final
Definition TCling.cxx:8103
std::string CallFunc_GetWrapperCode(CallFunc_t *func) const final
Definition TCling.cxx:8193
void * RewindInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:9741
const char * MethodArgInfo_Name(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9389
Bool_t HasPCMForLibrary(const char *libname) const final
Return true if ROOT has cxxmodules pcm for a given library name.
Definition TCling.cxx:3215
void TypedefInfo_Init(TypedefInfo_t *tinfo, const char *name) const final
Definition TCling.cxx:9557
const char * DataMemberInfo_Title(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8787
Longptr_t CallFunc_ExecInt(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7966
void ClearStack() final
Delete existing temporary values.
Definition TCling.cxx:3153
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:7615
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:7435
MethodInfo_t * CallFunc_FactoryMethod(CallFunc_t *func) const final
Definition TCling.cxx:8005
TypedefInfo_t * TypedefInfo_FactoryCopy(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9550
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:5116
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:9405
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:4900
Long_t MethodArgInfo_Property(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9373
int TypedefInfo_Size(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9591
void CallFunc_ExecWithArgsAndReturn(CallFunc_t *func, void *address, const void *args[]=nullptr, int nargs=0, void *ret=nullptr) const final
Definition TCling.cxx:7955
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:5268
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:6824
Int_t Load(const char *filenam, Bool_t system=kFALSE) final
Load a library file in cling's memory.
Definition TCling.cxx:3583
int TypedefInfo_Next(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9575
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:5075
void TypeInfo_Init(TypeInfo_t *tinfo, const char *funcname) const final
Definition TCling.cxx:9456
Bool_t SetSuspendAutoParsing(Bool_t value) final
Suspend the Autoparsing of headers.
Definition TCling.cxx:7675
int DataMemberInfo_TypeSize(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8755
static void * fgSetOfSpecials
Definition TCling.h:105
const char * ClassInfo_Title(ClassInfo_t *info) const final
Definition TCling.cxx:8523
const char * DataMemberInfo_Name(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8779
const char * TypeName(const char *typeDesc) final
Return the absolute type of typeDesc.
Definition TCling.cxx:5546
ROOT::TMetaUtils::TNormalizedCtxt * fNormalizedCtxt
Definition TCling.h:134
void ForgetMutexState() final
Definition TCling.cxx:9695
int MethodInfo_Next(MethodInfo_t *minfo) const final
Definition TCling.cxx:9168
Long_t ClassInfo_ClassProperty(ClassInfo_t *info) const final
Definition TCling.cxx:8257
void MethodInfo_Delete(MethodInfo_t *minfo) const final
Interface to cling function.
Definition TCling.cxx:9087
bool fIsShuttingDown
Definition TCling.h:187
void MethodArgInfo_Delete(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9326
bool IsSignedIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9640
DataMemberInfo_t * DataMemberInfo_Factory(ClassInfo_t *clinfo, TDictionary::EMemberSelection selection) const final
Definition TCling.cxx:8680
void ClassInfo_Destruct(ClassInfo_t *info, void *arena) const final
Definition TCling.cxx:8288
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:6178
Int_t UnloadAllSharedLibraryMaps() final
Unload the library map entries coming from all the loaded shared libraries.
Definition TCling.cxx:6066
void ClassInfo_Init(ClassInfo_t *info, const char *funcname) const final
Definition TCling.cxx:8350
std::set< TClass * > & GetModTClasses()
Definition TCling.h:578
ClassInfo_t * BaseClassInfo_ClassInfo(BaseClassInfo_t *) const final
Definition TCling.cxx:8618
TClingCallbacks * fClingCallbacks
Definition TCling.h:139
Long64_t CallFunc_ExecInt64(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7974
Long_t ClassInfo_Property(ClassInfo_t *info) const final
Definition TCling.cxx:8473
Longptr_t ClassInfo_GetBaseOffset(ClassInfo_t *fromDerived, ClassInfo_t *toBase, void *address, bool isDerivedObject) const final
Definition TCling.cxx:8597
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:5453
Bool_t IsErrorMessagesEnabled() const final
If error messages are disabled, the interpreter should suppress its failures and warning messages fro...
Definition TCling.cxx:7421
TString fIncludePath
Definition TCling.h:115
int DisplayIncludePath(FILE *fout) const final
Interface to cling function.
Definition TCling.cxx:7498
void TransactionRollback(const cling::Transaction &T)
Definition TCling.cxx:7030
Long_t FuncTempInfo_Property(FuncTempInfo_t *) const final
Return the property of the function template.
Definition TCling.cxx:8951
TEnum * CreateEnum(void *VD, TClass *cl) const final
Definition TCling.cxx:485
const char * TypeInfo_TrueName(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9505
Int_t UnloadLibraryMap(const char *library) final
Unload library map entries coming from the specified library.
Definition TCling.cxx:6084
void RegisterTemporary(const TInterpreterValue &value)
Definition TCling.cxx:7768
MutexStateAndRecurseCount fInitialMutex
Definition TCling.h:174
const char * GetSharedLibs() final
Return the list of shared libraries loaded into the process.
Definition TCling.cxx:7068
int MethodArgInfo_Next(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9365
void SnapshotMutexState(ROOT::TVirtualRWMutex *mtx) final
Definition TCling.cxx:9680
Long_t TypeInfo_Property(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9481
const char * MethodInfo_GetPrototype(MethodInfo_t *minfo) const final
Definition TCling.cxx:9214
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:8941
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:6224
void MethodInfo_CreateSignature(MethodInfo_t *minfo, TString &signature) const final
Definition TCling.cxx:9094
Bool_t CheckClassTemplate(const char *name) final
Return true if there is a class template by the given name ...
Definition TCling.cxx:4417
void LibraryLoaded(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:7053
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:9672
TObjArray * GetRootMapFiles() const final
Definition TCling.h:223
bool DataMemberInfo_IsValid(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8707
bool ClassInfo_IsEnum(const char *name) const final
Definition TCling.cxx:8376
int MethodInfo_NDefaultArg(MethodInfo_t *minfo) const final
Definition TCling.cxx:9160
bool IsFloatingType(const void *QualTypePtr) const final
Definition TCling.cxx:9656
void CreateListOfMethods(TClass *cl) const final
Create list of pointers to methods for TClass cl.
Definition TCling.cxx:4566
Int_t RescanLibraryMap() final
Scan again along the dynamic path for library maps.
Definition TCling.cxx:5993
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:7694
const char * MethodInfo_GetMangledName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9203
TypeInfo_t * MethodArgInfo_TypeInfo(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9413
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:5178
void * ClassInfo_New(ClassInfo_t *info) const final
Definition TCling.cxx:8441
int DisplayClass(FILE *fout, const char *name, int base, int start) const final
Definition TCling.cxx:7489
virtual void GetFunctionName(const clang::Decl *decl, std::string &name) const
Definition TCling.cxx:8842
void CreateListOfMethodArgs(TFunction *m) const final
Create list of pointers to method arguments for TMethod m.
Definition TCling.cxx:4591
virtual const char * GetSTLIncludePath() const final
Return the directory containing CINT's stl cintdlls.
Definition TCling.cxx:7480
MethodArgInfo_t * MethodArgInfo_FactoryCopy(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9349
Longptr_t BaseClassInfo_Offset(BaseClassInfo_t *toBaseClassInfo, void *address, bool isDerivedObject) const final
Definition TCling.cxx:8589
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:4245
void * FindSym(const char *entry) const final
Interface to cling function.
Definition TCling.cxx:7527
void RegisterLoadedSharedLibrary(const char *name)
Register a new shared library name with the interpreter; add it to fSharedLibs.
Definition TCling.cxx:3483
void TypeInfo_Delete(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9426
int MethodInfo_NArg(MethodInfo_t *minfo) const final
Definition TCling.cxx:9152
DeclId_t GetDataMemberWithValue(const void *ptrvalue) const final
NOT IMPLEMENTED.
Definition TCling.cxx:5009
std::unordered_set< const clang::NamespaceDecl * > fNSFromRootmaps
Definition TCling.h:125
EReturnType MethodCallReturnType(TFunction *func) const final
Definition TCling.cxx:9262
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:5201
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:5030
const char * MethodInfo_Title(MethodInfo_t *minfo) const final
Definition TCling.cxx:9253
TString fRootmapLoadPath
Definition TCling.h:116
const char * BaseClassInfo_TmpltName(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8652
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:3166
const char * BaseClassInfo_FullName(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8634
void CallFunc_SetArgs(CallFunc_t *func, const char *param) const final
Definition TCling.cxx:8111
int UnloadFile(const char *path) const final
Definition TCling.cxx:7727
void SetClassInfo(TClass *cl, Bool_t reload=kFALSE, Bool_t silent=kFALSE) final
Set pointer to the TClingClassInfo in TClass.
Definition TCling.cxx:4109
void CallFunc_Exec(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7931
Long_t FuncTempInfo_ExtraProperty(FuncTempInfo_t *) const final
Return the property not already defined in Property See TDictionary's EFunctionProperty.
Definition TCling.cxx:9016
bool CallFunc_IsValid(CallFunc_t *func) const final
Definition TCling.cxx:8030
const char * BaseClassInfo_Name(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8644
ROOT::TMetaUtils::TClingLookupHelper * fLookupHelper
Definition TCling.h:135
const char * DataMemberInfo_ValidArrayIndex(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8795
Int_t GetMore() const final
Return whether we are waiting for more input either because the collected input contains unbalanced b...
Definition TCling.cxx:4612
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:4940
void Execute(const char *function, const char *params, int *error=nullptr) final
Execute a global function with arguments params.
Definition TCling.cxx:5301
bool ClassInfo_IsLoaded(ClassInfo_t *info) const final
Definition TCling.cxx:8401
Longptr_t ClassInfo_Tagnum(ClassInfo_t *info) const final
Definition TCling.cxx:8489
Long_t BaseClassInfo_Property(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8610
void CallFunc_SetFunc(CallFunc_t *func, ClassInfo_t *info, const char *method, const char *params, Longptr_t *Offset) const final
Definition TCling.cxx:8119
std::vector< std::string > GetUsingNamespaces(ClassInfo_t *cl) const final
Get the scopes representing using declarations of namespace.
Definition TCling.cxx:4546
const char * ClassInfo_FileName(ClassInfo_t *info) const final
Definition TCling.cxx:8497
void FuncTempInfo_Title(FuncTempInfo_t *, TString &name) const final
Return the comments associates with this function template.
Definition TCling.cxx:9055
const char * ClassInfo_TmpltName(ClassInfo_t *info) const final
Definition TCling.cxx:8531
void SaveContext() final
Save the current Cling state.
Definition TCling.cxx:3927
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:6694
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:3808
void CodeComplete(const std::string &, size_t &, std::vector< std::string > &) final
The call to Cling's tab complition.
Definition TCling.cxx:7749
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:3822
const char * MapCppName(const char *) const final
Interface to cling function.
Definition TCling.cxx:7602
Longptr_t Calc(const char *line, EErrorCode *error=nullptr) final
Directly execute an executable statement (e.g.
Definition TCling.cxx:3653
Int_t ReloadAllSharedLibraryMaps() final
Reload the library map entries coming from all the loaded shared libraries, after first unloading the...
Definition TCling.cxx:6005
void UpdateListOfGlobalFunctions() final
No op: see TClingCallbacks (used to update the list of global functions)
Definition TCling.cxx:3960
void DataMemberInfo_Delete(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8673
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:5484
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:4584
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:6146
MethodInfo_t * MethodInfo_FactoryCopy(MethodInfo_t *minfo) const final
Definition TCling.cxx:9128
std::set< const char * > fParsedPayloadsAddresses
Definition TCling.h:123
CallFuncIFacePtr_t CallFunc_IFacePtr(CallFunc_t *func) const final
Definition TCling.cxx:8039
MethodArgInfo_t * MethodArgInfo_Factory() const final
Definition TCling.cxx:9333
static void UpdateClassInfo(char *name, Long_t tagnum)
No op: see TClingCallbacks.
Definition TCling.cxx:6818
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:5097
void ClassInfo_Delete(ClassInfo_t *info) const final
Definition TCling.cxx:8265
std::unique_ptr< cling::Interpreter > fInterpreter
Definition TCling.h:130
EDataType ClassInfo_GetUnderlyingType(ClassInfo_t *info) const final
Definition TCling.cxx:8392
void FuncTempInfo_Delete(FuncTempInfo_t *) const final
Delete the FuncTempInfo_t.
Definition TCling.cxx:8887
bool IsUnsignedIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9648
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:5245
Int_t DeleteVariable(const char *name) final
Undeclare obj called name.
Definition TCling.cxx:3866
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:7174
Longptr_t DataMemberInfo_Offset(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8731
CallFunc_t * CallFunc_Factory() const final
Definition TCling.cxx:7990
MethodInfo_t * MethodInfo_Factory() const final
Definition TCling.cxx:9103
Long_t DataMemberInfo_TypeProperty(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8747
void ClearFileBusy() final
Reset the interpreter internal state in case a previous action was not correctly terminated.
Definition TCling.cxx:3145
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:7625
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:3136
virtual void AddAvailableIndentifiers(TSeqCollection &Idents) final
Definition TCling.cxx:2415
void TypedefInfo_Delete(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9527
void Reset() final
Pressing Ctrl+C should forward here.
Definition TCling.cxx:3776
const char * TypedefInfo_TrueName(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9599
int SetClassAutoLoading(int) const final
Enable/Disable the AutoLoading of libraries.
Definition TCling.cxx:7646
const char * ClassInfo_FullName(ClassInfo_t *info) const final
Definition TCling.cxx:8505
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:6449
const char * MethodInfo_TypeName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9232
void CallFunc_SetArg(CallFunc_t *func, Long_t param) const final
Definition TCling.cxx:8055
const char * GetIncludePath() final
Refresh the list of include paths known to the interpreter and return it with -I prepended.
Definition TCling.cxx:7449
void UpdateListsOnUnloaded(const cling::Transaction &T)
Invalidate stored TCling state for declarations included in transaction ‘T’.
Definition TCling.cxx:6928
void UpdateClassInfoWithDecl(const clang::NamedDecl *ND)
Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
Definition TCling.cxx:6760
virtual 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:8326
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:4839
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:9042
std::unique_ptr< cling::MetaProcessor > fMetaProcessor
Definition TCling.h:131
bool TypeInfo_IsValid(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9465
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:9241
const char * ClassInfo_Name(ClassInfo_t *info) const final
Definition TCling.cxx:8515
TClass * GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent=kFALSE) final
Generate a TClass for the given class.
Definition TCling.cxx:4622
ULong64_t fTransactionCount
Definition TCling.h:148
bool ClassInfo_HasDefaultConstructor(ClassInfo_t *info, Bool_t testio=kFALSE) const final
Definition TCling.cxx:8334
void EndOfLineAction() final
It calls a "fantom" method to synchronize user keyboard input and ROOT prompt line.
Definition TCling.cxx:3189
TypeInfo_t * TypeInfo_FactoryCopy(TypeInfo_t *) const final
Definition TCling.cxx:9449
bool ClassInfo_HasMethod(ClassInfo_t *info, const char *name) const final
Definition TCling.cxx:8342
void ClassInfo_DeleteArray(ClassInfo_t *info, void *arena, bool dtorOnly) const final
Definition TCling.cxx:8280
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:8771
virtual void ShutDown() final
Definition TCling.cxx:1709
void UpdateListOfTypes() final
No op: see TClingCallbacks (used to update the list of types)
Definition TCling.cxx:3967
void * TypeInfo_QualTypePtr(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9513
Long_t TypedefInfo_Property(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9583
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:3637
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:5057
static void UpdateAllCanvases()
Update all canvases at end the terminal input command.
Definition TCling.cxx:6833
Int_t LoadLibraryMap(const char *rootmapfile=nullptr) final
Load map between class and library.
Definition TCling.cxx:5809
Longptr_t BaseClassInfo_Tagnum(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8626
void LibraryUnloaded(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:7060
bool IsPointerType(const void *QualTypePtr) const final
Definition TCling.cxx:9664
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:792
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:591
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:735
virtual TEnvRec * Lookup(const char *n) const
Loop over all resource records and return the one with name.
Definition TEnv.cxx:546
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:354
A TMemFile is like a normal TFile except that it reads and writes only from memory.
Definition TMemFile.h:19
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:1057
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:1071
virtual void Fatal(const char *method, const char *msgfmt,...) const
Issue fatal error message.
Definition TObject.cxx:1099
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:1045
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:3097
static const char * GetMacroPath()
Get macro search path. Static utility function.
Definition TROOT.cxx:2764
static const std::vector< std::string > & AddExtraInterpreterArgs(const std::vector< std::string > &args)
Provide command line arguments to the interpreter construction.
Definition TROOT.cxx:2959
static const TString & GetEtcDir()
Get the sysconfig directory in the installation. Static utility function.
Definition TROOT.cxx:3107
static const char **& GetExtraInterpreterArgs()
INTERNAL function! Used by rootcling to inject interpreter arguments through a C-interface layer.
Definition TROOT.cxx:2969
static const TString & GetSharedLibDir()
Get the shared libraries directory in the installation. Static utility function.
Definition TROOT.cxx:3086
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:712
Bool_t IsNull() const
Definition TString.h:422
TString & Append(const char *cs)
Definition TString.h:580
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:640
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:3997
virtual TString SplitAclicMode(const char *filename, TString &mode, TString &args, TString &io) const
This method split a filename of the form:
Definition TSystem.cxx:4282
virtual char * ConcatFileName(const char *dir, const char *name)
Concatenate a directory and a file name.
Definition TSystem.cxx:1082
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.
bool IsUniquePtr(std::string_view name)
Definition TClassEdit.h:229
@ 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:23
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4
static void output()