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 <stdint.h>
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 <limits.h>
157#include <stdio.h>
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"
1350 "#define ClassImp(X);\n";
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
1442 // Process externally passed arguments if present.
1443 std::optional<std::string> EnvOpt = llvm::sys::Process::GetEnv("EXTRA_CLING_ARGS");
1444 if (EnvOpt.has_value()) {
1446 while (!Env.empty()) {
1447 StringRef Arg;
1448 std::tie(Arg, Env) = Env.split(' ');
1449 clingArgsStorage.push_back(Arg.str());
1450 }
1451 }
1452
1453 auto GetEnvVarPath = [](const std::string &EnvVar, std::vector<std::string> &Paths) {
1454 std::optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(EnvVar);
1455 if (EnvOpt.has_value()) {
1457 while (!Env.empty()) {
1458 StringRef Arg;
1459 std::tie(Arg, Env) = Env.split(ROOT::FoundationUtils::GetEnvPathSeparator());
1460 if (std::find(Paths.begin(), Paths.end(), Arg.str()) == Paths.end())
1461 Paths.push_back(Arg.str());
1462 }
1463 }
1464 };
1465
1466 if (fCxxModulesEnabled) {
1467 std::vector<std::string> Paths;
1468 // ROOT usually knows better where its libraries are. This way we can
1469 // discover modules without having to should thisroot.sh and should fix
1470 // gnuinstall.
1471 Paths.push_back(TROOT::GetSharedLibDir().Data());
1472 GetEnvVarPath("CLING_PREBUILT_MODULE_PATH", Paths);
1473 std::string EnvVarPath;
1474 for (const std::string& P : Paths)
1476 // FIXME: We should make cling -fprebuilt-module-path work.
1477 gSystem->Setenv("CLING_PREBUILT_MODULE_PATH", EnvVarPath.c_str());
1478 }
1479
1480 // FIXME: This only will enable frontend timing reports.
1481 EnvOpt = llvm::sys::Process::GetEnv("ROOT_CLING_TIMING");
1482 if (EnvOpt.has_value())
1483 clingArgsStorage.push_back("-ftime-report");
1484
1485 // Add the overlay file. Note that we cannot factor it out for both root
1486 // and rootcling because rootcling activates modules only if -cxxmodule
1487 // flag is passed.
1489 // For now we prefer rootcling to enumerate explicitly its modulemaps.
1490 std::vector<std::string> ModuleMaps;
1491 std::string ModuleMapSuffix = ROOT::FoundationUtils::GetPathSeparator() + "ROOT.modulemap";
1492 ModuleMaps.push_back(TROOT::GetIncludeDir().Data() + ModuleMapSuffix);
1493 GetEnvVarPath("CLING_MODULEMAP_FILES", ModuleMaps);
1494
1495 std::string cwd = gSystem->WorkingDirectory();
1496 // Give highest precedence of the modulemap in the cwd if any.
1497 if (llvm::sys::fs::exists(cwd + ModuleMapSuffix))
1498 ModuleMaps.push_back(cwd + ModuleMapSuffix);
1499
1500 for (const std::string& M : ModuleMaps)
1501 clingArgsStorage.push_back("-fmodule-map-file=" + M);
1502
1503 std::string ModulesCachePath;
1504 EnvOpt = llvm::sys::Process::GetEnv("CLING_MODULES_CACHE_PATH");
1505 if (EnvOpt.has_value()){
1507 assert(llvm::sys::fs::exists(Env) && "Path does not exist!");
1508 ModulesCachePath = Env.str();
1509 } else {
1511 }
1512
1513 clingArgsStorage.push_back("-fmodules-cache-path=" + ModulesCachePath);
1514 }
1515
1516 std::vector<const char*> interpArgs;
1517 for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1519 interpArgs.push_back(iArg->c_str());
1520
1521 // Activate C++ modules support. If we are running within rootcling, it's up
1522 // to rootcling to set this flag depending on whether it wants to produce
1523 // C++ modules.
1525 if (fCxxModulesEnabled) {
1526 if (!fromRootCling) {
1527 // We only set this flag, rest is done by the CIFactory.
1528 interpArgs.push_back("-fmodules");
1529 interpArgs.push_back("-fno-implicit-module-maps");
1530 // We should never build modules during runtime, so let's enable the
1531 // module build remarks from clang to make it easier to spot when we do
1532 // this by accident.
1533 interpArgs.push_back("-Rmodule-build");
1534 }
1535 // ROOT implements its AutoLoading upon module's link directives. We
1536 // generate module A { header "A.h" link "A.so" export * } where ROOT's
1537 // facilities use the link directive to dynamically load the relevant
1538 // library. So, we need to suppress clang's default autolink behavior.
1539 interpArgs.push_back("-fno-autolink");
1540 }
1541
1542#ifdef R__FAST_MATH
1543 // Same setting as in rootcling_impl.cxx.
1544 interpArgs.push_back("-ffast-math");
1545#endif
1546
1548 // Add statically injected extra arguments, usually coming from rootcling.
1549 for (const char** extraArgs = TROOT::GetExtraInterpreterArgs();
1550 extraArgs && *extraArgs; ++extraArgs) {
1551 if (!strcmp(*extraArgs, "-resource-dir")) {
1552 // Take the next arg as the llvm resource directory.
1554 } else {
1555 interpArgs.push_back(*extraArgs);
1556 }
1557 }
1558
1559 std::vector<std::string> _empty;
1561 for (const auto &arg: args)
1562 interpArgs.emplace_back(arg.c_str());
1563
1564 // Add the Rdict module file extension.
1565 cling::Interpreter::ModuleFileExtensions extensions;
1566 EnvOpt = llvm::sys::Process::GetEnv("ROOTDEBUG_RDICT");
1567 if (!EnvOpt.has_value())
1568 extensions.push_back(std::make_shared<TClingRdictModuleFileExtension>());
1569
1570 fInterpreter = std::make_unique<cling::Interpreter>(interpArgs.size(),
1571 &(interpArgs[0]),
1574
1575 if (!fInterpreter->getCI()) { // Compiler instance could not be created. See https://its.cern.ch/jira/browse/ROOT-10239
1576 return;
1577 }
1578
1579 // Tell CppInterOp that the cling::Interpreter instance is managed externally by ROOT
1580 // Sets the interpreter by passing the fInterpreter handle as soon as TCling is initialized
1581 Cpp::UseExternalInterpreter((Cpp::TInterp_t*)fInterpreter.get());
1582
1583 // Don't check whether modules' files exist.
1584 fInterpreter->getCI()->getPreprocessorOpts().DisablePCHOrModuleValidation =
1585 DisableValidationForModuleKind::All;
1586
1587 // Until we can disable AutoLoading during Sema::CorrectTypo() we have
1588 // to disable spell checking.
1589 fInterpreter->getCI()->getLangOpts().SpellChecking = false;
1590
1591 // Sync modules on/off between clang and us: clang turns it on for C++ >= 20.
1592 auto isModulesArg = [](const char* arg) { return !strcmp(arg, "-fmodules"); };
1593 bool hasModulesArg = std::find_if(interpArgs.begin(), interpArgs.end(), isModulesArg) != interpArgs.end();
1594 fInterpreter->getCI()->getLangOpts().Modules = hasModulesArg;
1595
1596 // We need stream that doesn't close its file descriptor, thus we are not
1597 // using llvm::outs. Keeping file descriptor open we will be able to use
1598 // the results in pipes (Savannah #99234).
1599 static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO, /*ShouldClose*/false);
1600 fMetaProcessor = std::make_unique<cling::MetaProcessor>(*fInterpreter, fMPOuts);
1601
1604
1605 // We are now ready (enough is loaded) to init the list of opaque typedefs.
1611
1612 // Disallow auto-parsing in rootcling
1614
1615 ResetAll();
1616
1617 // Enable dynamic lookup
1618 if (!fromRootCling) {
1619 fInterpreter->enableDynamicLookup();
1620 }
1621
1622 // Enable ClinG's DefinitionShadower for ROOT.
1623 fInterpreter->getRuntimeOptions().AllowRedefinition = 1;
1624 auto &Policy = const_cast<clang::PrintingPolicy &>(fInterpreter->getCI()->getASTContext().getPrintingPolicy());
1625 // Print 'a<b<c> >' rather than 'a<b<c>>'.
1626 // FIXME: We should probably switch to the default printing policy setting
1627 // after adjusting tons of reference files.
1628 Policy.SplitTemplateClosers = true;
1629 // Keep default templare arguments, required for dictionary generation.
1630 Policy.SuppressDefaultTemplateArgs = false;
1631
1632
1633 // Attach cling callbacks last; they might need TROOT::fInterpreter
1634 // and should thus not be triggered during the equivalent of
1635 // TROOT::fInterpreter = new TCling;
1636 std::unique_ptr<TClingCallbacks>
1640 fInterpreter->setCallbacks(std::move(clingCallbacks));
1641
1642 if (!fromRootCling) {
1643 cling::DynamicLibraryManager& DLM = *fInterpreter->getDynamicLibraryManager();
1644 // Make sure cling looks into ROOT's libdir, even if not part of LD_LIBRARY_PATH
1645 // e.g. because of an RPATH build.
1646 DLM.addSearchPath(TROOT::GetSharedLibDir().Data(), /*isUser=*/true,
1647 /*prepend=*/true);
1648 auto ShouldPermanentlyIgnore = [](llvm::StringRef FileName) -> bool{
1649 llvm::StringRef stem = llvm::sys::path::stem(FileName);
1650 return stem.starts_with("libNew") || stem.starts_with("libcppyy_backend");
1651 };
1652 // Initialize the dyld for AutoloadLibraryGenerator.
1653 DLM.initializeDyld(ShouldPermanentlyIgnore);
1654 }
1655}
1656
1657
1658////////////////////////////////////////////////////////////////////////////////
1659/// Destroy the interpreter interface.
1660
1662{
1663 // ROOT's atexit functions require the interepreter to be available.
1664 // Run them before shutting down.
1665 if (!IsFromRootCling())
1666 GetInterpreterImpl()->runAtExitFuncs();
1667 fIsShuttingDown = true;
1668 delete fMapfile;
1669 delete fRootmapFiles;
1670 delete fTemporaries;
1671 delete fNormalizedCtxt;
1672 delete fLookupHelper;
1673 gCling = nullptr;
1674}
1675
1676////////////////////////////////////////////////////////////////////////////////
1677/// Initialize the interpreter, once TROOT::fInterpreter is set.
1678
1680{
1681 if (!fClingCallbacks) // Compiler instance could not be created. See https://its.cern.ch/jira/browse/ROOT-10239
1682 return;
1684
1685 // We are set up. Enable ROOT's AutoLoading.
1686 if (IsFromRootCling())
1687 return;
1688
1689 // Read the rules before enabling the auto loading to not inadvertently
1690 // load the libraries for the classes concerned even-though the user is
1691 // *not* using them.
1692 // Note this call must happen before the first call to LoadLibraryMap.
1693 assert(GetRootMapFiles() == nullptr && "Must be called before LoadLibraryMap!");
1694 TClass::ReadRules(); // Read the default customization rules ...
1695
1697 SetClassAutoLoading(true);
1698}
1699
1701{
1702 fIsShuttingDown = true;
1703 ResetGlobals();
1704}
1705
1706////////////////////////////////////////////////////////////////////////////////
1707/// Helper to initialize TVirtualStreamerInfo's factor early.
1708/// Use static initialization to insure only one TStreamerInfo is created.
1710{
1711 // Use lambda since SetFactory return void.
1712 auto setFactory = []() {
1714 return kTRUE;
1715 };
1716 static bool doneFactory = setFactory();
1717 return doneFactory; // avoid unused variable warning.
1718}
1719
1720////////////////////////////////////////////////////////////////////////////////
1721/// Register Rdict data for future loading by LoadPCM;
1722
1723void TCling::RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
1724{
1725 if (IsFromRootCling())
1726 return;
1727
1728 if (llvm::sys::fs::exists(pcmFileNameFullPath)) {
1729 ::Error("TCling::RegisterRdictForLoadPCM", "Rdict '%s' is both in Module extension and in File system.", pcmFileNameFullPath.c_str());
1730 return;
1731 }
1732
1733 // The pcmFileNameFullPath must be resolved already because we cannot resolve
1734 // a link to a non-existent file.
1736}
1737
1738////////////////////////////////////////////////////////////////////////////////
1739/// Tries to load a PCM from TFile; returns true on success.
1740/// The caller of this function should be holding the ROOT Write lock.
1741
1743{
1744 auto listOfKeys = pcmFile.GetListOfKeys();
1745
1746 // This is an empty pcm
1747 if (listOfKeys && ((listOfKeys->GetSize() == 0) || // Nothing here, or
1748 ((listOfKeys->GetSize() == 1) && // only one, and
1749 !strcmp(((TKey *)listOfKeys->At(0))->GetName(), "EMPTY") // name is EMPTY
1750 ))) {
1751 return;
1752 }
1753
1755 if (gDebug > 1)
1756 ::Info("TCling::LoadPCMImpl", "reading protoclasses for %s \n", pcmFile.GetName());
1757
1759 pcmFile.GetObject("__Enums", enums);
1760 if (enums) {
1761 // Cache the pointers
1762 auto listOfGlobals = gROOT->GetListOfGlobals();
1763 auto listOfEnums = dynamic_cast<THashList *>(gROOT->GetListOfEnums());
1764 // Loop on enums and then on enum constants
1765 for (auto selEnum : *enums) {
1766 const char *enumScope = selEnum->GetTitle();
1767 const char *enumName = selEnum->GetName();
1768 if (strcmp(enumScope, "") == 0) {
1769 // This is a global enum and is added to the
1770 // list of enums and its constants to the list of globals
1771 if (!listOfEnums->THashList::FindObject(enumName)) {
1772 ((TEnum *)selEnum)->SetClass(nullptr);
1773 listOfEnums->Add(selEnum);
1774 }
1775 for (auto enumConstant : *static_cast<TEnum *>(selEnum)->GetConstants()) {
1776 if (!listOfGlobals->FindObject(enumConstant)) {
1778 }
1779 }
1780 } else {
1781 // This enum is in a namespace. A TClass entry is bootstrapped if
1782 // none exists yet and the enum is added to it
1784 if (!nsTClassEntry) {
1786 }
1787 auto listOfEnums = nsTClassEntry->fEnums.load();
1788 if (!listOfEnums) {
1789 if ((kIsClass | kIsStruct | kIsUnion) & nsTClassEntry->Property()) {
1790 // For this case, the list will be immutable once constructed
1791 // (i.e. in this case, by the end of this routine).
1793 } else {
1794 // namespaces can have enums added to them
1796 }
1797 }
1798 if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)) {
1799 ((TEnum *)selEnum)->SetClass(nsTClassEntry);
1800 listOfEnums->Add(selEnum);
1801 }
1802 }
1803 }
1804 enums->Clear();
1805 delete enums;
1806 }
1807
1808 pcmFile.GetObject("__ProtoClasses", protoClasses);
1809
1810 if (protoClasses) {
1811 for (auto obj : *protoClasses) {
1812 TProtoClass *proto = (TProtoClass *)obj;
1814 }
1815 // Now that all TClass-es know how to set them up we can update
1816 // existing TClasses, which might cause the creation of e.g. TBaseClass
1817 // objects which in turn requires the creation of TClasses, that could
1818 // come from the PCH, but maybe later in the loop. Instead of resolving
1819 // a dependency graph the addition to the TClassTable above allows us
1820 // to create these dependent TClasses as needed below.
1821 for (auto proto : *protoClasses) {
1822 if (TClass *existingCl = (TClass *)gROOT->GetListOfClasses()->FindObject(proto->GetName())) {
1823 // We have an existing TClass object. It might be emulated
1824 // or interpreted; we now have more information available.
1825 // Make that available.
1826 if (existingCl->GetState() != TClass::kHasTClassInit) {
1827 DictFuncPtr_t dict = gClassTable->GetDict(proto->GetName());
1828 if (!dict) {
1829 ::Error("TCling::LoadPCM", "Inconsistent TClassTable for %s", proto->GetName());
1830 } else {
1831 // This will replace the existing TClass.
1832 TClass *ncl = (*dict)();
1833 if (ncl)
1834 ncl->PostLoadCheck();
1835 }
1836 }
1837 }
1838 }
1839
1840 protoClasses->Clear(); // Ownership was transfered to TClassTable.
1841 delete protoClasses;
1842 }
1843
1845 pcmFile.GetObject("__Typedefs", dataTypes);
1846 if (dataTypes) {
1847 for (auto typedf : *dataTypes)
1848 gROOT->GetListOfTypes()->Add(typedf);
1849 dataTypes->Clear(); // Ownership was transfered to TListOfTypes.
1850 delete dataTypes;
1851 }
1852}
1853
1854////////////////////////////////////////////////////////////////////////////////
1855/// Tries to load a rdict PCM, issues diagnostics if it fails.
1856/// The caller of this function should be holding the ROOT Write lock.
1857
1859{
1862 assert(!pcmFileNameFullPath.empty());
1863 assert(llvm::sys::path::is_absolute(pcmFileNameFullPath));
1864
1865 // Easier to work with the ROOT interfaces.
1867
1868 // Prevent the ROOT-PCMs hitting this during auto-load during
1869 // JITting - which will cause recursive compilation.
1870 // Avoid to call the plugin manager at all.
1872
1874 llvm::SaveAndRestore<Int_t> SaveGDebug(gDebug);
1875 if (gDebug > 5) {
1876 gDebug -= 5;
1877 ::Info("TCling::LoadPCM", "Loading ROOT PCM %s", pcmFileName.Data());
1878 } else {
1879 gDebug = 0;
1880 }
1881
1882 if (llvm::sys::fs::is_symlink_file(pcmFileNameFullPath))
1884
1886 if (pendingRdict != fPendingRdicts.end()) {
1887 llvm::StringRef pcmContent = pendingRdict->second;
1889 std::string RDictFileOpts = pcmFileNameFullPath + "?filetype=pcm";
1891
1892 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
1894 // Currently the module file are never unloaded (even if the library is
1895 // unloaded) and, of course, never reloaded.
1896 // Consequently, we must NOT remove the `pendingRdict` from the list
1897 // of pending dictionary, otherwise if a library is unloaded and then
1898 // reload we will be unable to update properly the TClass object
1899 // (because we wont be able to load the rootpcm file by executing the
1900 // above lines)
1901
1902 return;
1903 }
1904
1905 if (!llvm::sys::fs::exists(pcmFileNameFullPath)) {
1906 ::Error("TCling::LoadPCM", "ROOT PCM %s file does not exist",
1907 pcmFileNameFullPath.data());
1908 if (!fPendingRdicts.empty())
1909 for (const auto &rdict : fPendingRdicts)
1910 ::Info("TCling::LoadPCM", "In-memory ROOT PCM candidate %s\n",
1911 rdict.first.c_str());
1912 return;
1913 }
1914
1915 if (!gROOT->IsRootFile(pcmFileName)) {
1916 Fatal("LoadPCM", "The file %s is not a ROOT as was expected\n", pcmFileName.Data());
1917 return;
1918 }
1919 TFile pcmFile(pcmFileName + "?filetype=pcm", "READ");
1921}
1922
1923//______________________________________________________________________________
1924
1925namespace {
1926 using namespace clang;
1927
1928 class ExtLexicalStorageAdder: public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1929 // This class is to be considered an helper for autoparsing.
1930 // It visits the AST and marks all classes (in all of their redeclarations)
1931 // with the setHasExternalLexicalStorage method.
1932 public:
1933 bool VisitRecordDecl(clang::RecordDecl* rcd){
1934 if (gDebug > 2)
1935 Info("ExtLexicalStorageAdder",
1936 "Adding external lexical storage to class %s",
1937 rcd->getNameAsString().c_str());
1938 auto reDeclPtr = rcd->getMostRecentDecl();
1939 do {
1940 reDeclPtr->setHasExternalLexicalStorage();
1941 } while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1942
1943 return false;
1944 }
1945 };
1946
1947
1948}
1949
1950////////////////////////////////////////////////////////////////////////////////
1951///\returns true if the module map was loaded, false on error or if the map was
1952/// already loaded.
1954 const std::string &ModuleMapName /*= "module.modulemap"*/) const
1955{
1956 assert(llvm::sys::path::is_absolute(FullPath));
1957 Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
1958 FileManager &FM = PP.getFileManager();
1959 // FIXME: In a ROOT session we can add an include path (through .I /inc/path)
1960 // We should look for modulemap files there too.
1961 if (auto DE = FM.getOptionalDirectoryRef(FullPath)) {
1962 HeaderSearch &HS = PP.getHeaderSearchInfo();
1963 HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1964 const auto &ModPaths = HSOpts.PrebuiltModulePaths;
1965 bool pathExists = std::find(ModPaths.begin(), ModPaths.end(), FullPath) != ModPaths.end();
1966 if (!pathExists)
1967 HSOpts.AddPrebuiltModulePath(FullPath);
1968 // We cannot use HS.lookupModuleMapFile(DE, /*IsFramework*/ false);
1969 // because its internal call to getFile has CacheFailure set to true.
1970 // In our case, modulemaps can appear any time due to ACLiC.
1971 // Code copied from HS.lookupModuleMapFile.
1972 llvm::SmallString<256> ModuleMapFileName(DE->getName());
1973 llvm::sys::path::append(ModuleMapFileName, ModuleMapName);
1974 if (auto FE = FM.getOptionalFileRef(ModuleMapFileName, /*openFile*/ false,
1975 /*CacheFailure*/ false)) {
1976 if (!HS.loadModuleMapFile(*FE, /*IsSystem*/ false))
1977 return true;
1978 Error("RegisterPrebuiltModulePath", "Could not load modulemap in %s", ModuleMapFileName.c_str());
1979 }
1980 }
1981 return false;
1982}
1983
1984////////////////////////////////////////////////////////////////////////////////
1985/// List of dicts that have the PCM information already in the PCH.
1986static const std::unordered_set<std::string> gIgnoredPCMNames = {"libCore",
1987 "libRint",
1988 "libThread",
1989 "libRIO",
1990 "libImt",
1991 "libMultiProc",
1992 "libcomplexDict",
1993 "libdequeDict",
1994 "liblistDict",
1995 "libforward_listDict",
1996 "libvectorDict",
1997 "libmapDict",
1998 "libmultimap2Dict",
1999 "libmap2Dict",
2000 "libmultimapDict",
2001 "libsetDict",
2002 "libmultisetDict",
2003 "libunordered_setDict",
2004 "libunordered_multisetDict",
2005 "libunordered_mapDict",
2006 "libunordered_multimapDict",
2007 "libvalarrayDict",
2008 "G__GenVector32",
2009 "G__Smatrix32"};
2010
2011static void PrintDlError(const char *dyLibName, const char *modulename)
2012{
2013#ifdef R__WIN32
2014 char dyLibError[1000];
2016 dyLibError, sizeof(dyLibError), NULL);
2017#else
2018 const char *dyLibError = dlerror();
2019#endif
2020 ::Error("TCling::RegisterModule", "Cannot open shared library %s for dictionary %s:\n %s", dyLibName, modulename,
2021 (dyLibError) ? dyLibError : "");
2022}
2023
2024////////////////////////////////////////////////////////////////////////////////
2025// Update all the TClass registered in fClassesToUpdate
2026
2028{
2029 while (!fClassesToUpdate.empty()) {
2030 TClass *oldcl = fClassesToUpdate.back().first;
2031 // If somehow the TClass has already been loaded (maybe it was registered several time),
2032 // we skip it. Otherwise, the existing TClass is in mode kInterpreted, kEmulated or
2033 // maybe even kForwardDeclared and needs to replaced.
2034 if (oldcl->GetState() != TClass::kHasTClassInit) {
2035 // if (gDebug > 2) Info("RegisterModule", "Forcing TClass init for %s", oldcl->GetName());
2036 DictFuncPtr_t dict = fClassesToUpdate.back().second;
2037 fClassesToUpdate.pop_back();
2038 // Calling func could manipulate the list so, let maintain the list
2039 // then call the dictionary function.
2040 TClass *ncl = dict();
2041 if (ncl) ncl->PostLoadCheck();
2042 } else {
2043 fClassesToUpdate.pop_back();
2044 }
2045 }
2046}
2047////////////////////////////////////////////////////////////////////////////////
2048/// Inject the module named "modulename" into cling; load all headers.
2049/// headers is a 0-terminated array of header files to `#include` after
2050/// loading the module. The module is searched for in all $LD_LIBRARY_PATH
2051/// entries (or %PATH% on Windows).
2052/// This function gets called by the static initialization of dictionary
2053/// libraries.
2054/// The payload code is injected "as is" in the interpreter.
2055/// The value of 'triggerFunc' is used to find the shared library location.
2056/// The caller of this function should be holding the ROOT Write lock.
2057
2059 const char** headers,
2060 const char** includePaths,
2061 const char* payloadCode,
2062 const char* fwdDeclsCode,
2063 void (*triggerFunc)(),
2065 const char** classesHeaders,
2066 Bool_t lateRegistration /*=false*/,
2067 Bool_t hasCxxModule /*=false*/)
2068{
2069 const bool fromRootCling = IsFromRootCling();
2070 // We need the dictionary initialization but we don't want to inject the
2071 // declarations into the interpreter, except for those we really need for
2072 // I/O; see rootcling.cxx after the call to TCling__GetInterpreter().
2073 if (fromRootCling) return;
2074
2075 // When we cannot provide a module for the library we should enable header
2076 // parsing. This 'mixed' mode ensures gradual migration to modules.
2077 llvm::SaveAndRestore<bool> SaveHeaderParsing(fHeaderParsingOnDemand);
2079
2080 // Treat Aclic Libs in a special way. Do not delay the parsing.
2082 bool isACLiC = strstr(modulename, "_ACLiC_dict") != nullptr;
2084 if (gDebug>1)
2085 Info("TCling::RegisterModule",
2086 "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
2088 }
2089
2090
2091 // Make sure we relookup symbols that were search for before we loaded
2092 // their autoparse information. We could be more subtil and remove only
2093 // the failed one or only the one in this module, but for now this is
2094 // better than nothing.
2095 fLookedUpClasses.clear();
2096
2097 // Make sure we do not set off AutoLoading or autoparsing during the
2098 // module registration!
2100
2101 for (const char** inclPath = includePaths; *inclPath; ++inclPath) {
2103 }
2104 cling::Transaction* T = nullptr;
2105 // Put the template decls and the number of arguments to skip in the TNormalizedCtxt
2107 const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
2108 const int nArgsToSkip = fwdDeclArgToSkipPair.second;
2109 auto compRes = fInterpreter->declare(fwdDecl.c_str(), &T);
2110 assert(cling::Interpreter::kSuccess == compRes &&
2111 "A fwd declaration could not be compiled");
2112 if (compRes!=cling::Interpreter::kSuccess){
2113 Warning("TCling::RegisterModule",
2114 "Problems in declaring string '%s' were encountered.",
2115 fwdDecl.c_str()) ;
2116 continue;
2117 }
2118
2119 // Drill through namespaces recursively until the template is found
2120 if(ClassTemplateDecl* TD = FindTemplateInNamespace(T->getFirstDecl().getSingleDecl())){
2122 }
2123
2124 }
2125
2126 // FIXME: Remove #define __ROOTCLING__ once PCMs are there.
2127 // This is used to give Sema the same view on ACLiC'ed files (which
2128 // are then #included through the dictionary) as rootcling had.
2130 if (payloadCode)
2131 code += payloadCode;
2132
2133 std::string dyLibName = cling::DynamicLibraryManager::getSymbolLocation(triggerFunc);
2134 assert(!llvm::sys::fs::is_symlink_file(dyLibName));
2135
2136 if (dyLibName.empty()) {
2137 ::Error("TCling::RegisterModule", "Dictionary trigger function for %s not found", modulename);
2138 return;
2139 }
2140
2141 // The triggerFunc may not be in a shared object but in an executable.
2142 bool isSharedLib = cling::DynamicLibraryManager::isSharedLibrary(dyLibName);
2143
2144 bool wasDlopened = false;
2145
2146 // If this call happens after dlopen has finished (i.e. late registration)
2147 // there is no need to dlopen the library recursively. See ROOT-8437 where
2148 // the dyLibName would correspond to the binary.
2149 if (!lateRegistration) {
2150
2151 if (isSharedLib) {
2152 // We need to open the dictionary shared library, to resolve symbols
2153 // requested by the JIT from it: as the library is currently being dlopen'ed,
2154 // its symbols are not yet reachable from the process.
2155 // Recursive dlopen seems to work just fine.
2156 void* dyLibHandle = dlopen(dyLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
2157 if (dyLibHandle) {
2159 wasDlopened = true;
2160 } else {
2162 }
2163 }
2164 } // if (!lateRegistration)
2165
2167 // We now parse the forward declarations. All the classes are then modified
2168 // in order for them to have an external lexical storage.
2169 std::string fwdDeclsCodeLessEnums;
2170 {
2171 // Search for enum forward decls and only declare them if no
2172 // declaration exists yet.
2173 std::string fwdDeclsLine;
2174 std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
2175 std::vector<std::string> scopes;
2176 while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
2177 const auto enumPos = fwdDeclsLine.find("enum __attribute__((annotate(\"");
2178 // We check if the line contains a fwd declaration of an enum
2179 if (enumPos != std::string::npos) {
2180 // We clear the scopes which we may have carried from a previous iteration
2181 scopes.clear();
2182 // We check if the enum is not in a scope. If yes, save its name
2183 // and the names of the enclosing scopes.
2184 if (enumPos != 0) {
2185 // it's enclosed in namespaces. We need to understand what they are
2186 auto nsPos = fwdDeclsLine.find("namespace");
2187 R__ASSERT(nsPos < enumPos && "Inconsistent enum and enclosing scope parsing!");
2188 while (nsPos < enumPos && nsPos != std::string::npos) {
2189 // we have a namespace, let's put it in the collection of scopes
2190 const auto nsNameStart = nsPos + 10;
2191 const auto nsNameEnd = fwdDeclsLine.find('{', nsNameStart);
2192 const auto nsName = fwdDeclsLine.substr(nsNameStart, nsNameEnd - nsNameStart);
2193 scopes.push_back(nsName);
2194 nsPos = fwdDeclsLine.find("namespace", nsNameEnd);
2195 }
2196 }
2197 clang::DeclContext* DC = nullptr;
2198 for (auto &&aScope: scopes) {
2199 DC = cling::utils::Lookup::Namespace(&fInterpreter->getSema(), aScope.c_str(), DC);
2200 if (!DC) {
2201 // No decl context means we have to fwd declare the enum.
2202 break;
2203 }
2204 }
2205 if (scopes.empty() || DC) {
2206 // We know the scope; let's look for the enum. For that, look
2207 // for the *last* closing parentheses of an attribute because
2208 // there can be multiple.
2209 size_t posEnumName = fwdDeclsLine.rfind("\"))) ");
2210 R__ASSERT(posEnumName != std::string::npos && "Inconsistent enum fwd decl!");
2211 posEnumName += 5; // skip "\"))) "
2213 ++posEnumName;
2214 size_t posEnumNameEnd = fwdDeclsLine.find(" : ", posEnumName);
2215 R__ASSERT(posEnumNameEnd != std::string::npos && "Inconsistent enum fwd decl (end)!");
2218 // posEnumNameEnd now points to the last character of the name.
2219
2220 std::string enumName = fwdDeclsLine.substr(posEnumName,
2222
2223 if (clang::NamedDecl* enumDecl
2224 = cling::utils::Lookup::Named(&fInterpreter->getSema(),
2225 enumName.c_str(), DC)) {
2226 // We have an existing enum decl (forward or definition);
2227 // skip this.
2228 R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) && "not an enum decl!");
2229 (void)enumDecl;
2230 continue;
2231 }
2232 }
2233 }
2234
2236 }
2237 }
2238
2239 if (!fwdDeclsCodeLessEnums.empty()){ // Avoid the overhead if nothing is to be declared
2240 auto compRes = fInterpreter->declare(fwdDeclsCodeLessEnums, &T);
2241 assert(cling::Interpreter::kSuccess == compRes &&
2242 "The forward declarations could not be compiled");
2243 if (compRes!=cling::Interpreter::kSuccess){
2244 Warning("TCling::RegisterModule",
2245 "Problems in compiling forward declarations for module %s: '%s'",
2247 }
2248 else if (T){
2249 // Loop over all decls in the transaction and go through them all
2250 // to mark them properly.
2251 // In order to do that, we first iterate over all the DelayedCallInfos
2252 // within the transaction. Then we loop over all Decls in the DeclGroupRef
2253 // contained in the DelayedCallInfos. For each decl, we traverse.
2254 ExtLexicalStorageAdder elsa;
2255 for (auto dciIt = T->decls_begin();dciIt!=T->decls_end();dciIt++){
2256 cling::Transaction::DelayCallInfo& dci = *dciIt;
2257 for(auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
2258 clang::Decl* declPtr = *dit;
2259 elsa.TraverseDecl(declPtr);
2260 }
2261 }
2262 }
2263 }
2264
2265 // Now we register all the headers necessary for the class
2266 // Typical format of the array:
2267 // {"A", "classes.h", "@",
2268 // "vector<A>", "vector", "@",
2269 // "myClass", payloadCode, "@",
2270 // nullptr};
2271
2272 std::string temp;
2273 for (const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
2274 temp=*classesHeader;
2275
2276 size_t theTemplateHash = 0;
2277 bool addTemplate = false;
2278 size_t posTemplate = temp.find('<');
2279 if (posTemplate != std::string::npos) {
2280 // Add an entry for the template itself.
2281 std::string templateName = temp.substr(0, posTemplate);
2283 addTemplate = true;
2284 }
2285 size_t theHash = fStringHashFunction(temp);
2286 classesHeader++;
2288 // This is done in order to distinguish headers from files and from the payloadCode
2290 fPayloads.insert(theHash);
2292 }
2293 if (gDebug > 2)
2294 Info("TCling::RegisterModule",
2295 "Adding a header for %s", temp.c_str());
2297 if (addTemplate) {
2300 }
2301 addTemplate = false;
2302 }
2303 }
2304 }
2305 }
2306
2307 clang::Sema &TheSema = fInterpreter->getSema();
2308
2309 bool ModuleWasSuccessfullyLoaded = false;
2310 if (hasCxxModule) {
2311 std::string ModuleName = modulename;
2312 if (llvm::StringRef(modulename).starts_with("lib"))
2313 ModuleName = llvm::StringRef(modulename).substr(3).str();
2314
2315 // In case we are directly loading the library via gSystem->Load() without
2316 // specifying the relevant include paths we should try loading the
2317 // modulemap next to the library location.
2318 clang::Preprocessor &PP = TheSema.getPreprocessor();
2319 std::string ModuleMapName;
2320 if (isACLiC)
2321 ModuleMapName = ModuleName + ".modulemap";
2322 else
2323 ModuleMapName = "module.modulemap";
2324 RegisterPrebuiltModulePath(llvm::sys::path::parent_path(dyLibName).str(),
2326
2327 // FIXME: We should only complain for modules which we know to exist. For example, we should not complain about
2328 // modules such as GenVector32 because it needs to fall back to GenVector.
2329 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2332 // Only report if we found the module in the modulemap.
2333 clang::HeaderSearch &headerSearch = PP.getHeaderSearchInfo();
2334 clang::ModuleMap &moduleMap = headerSearch.getModuleMap();
2335 if (moduleMap.findModule(ModuleName))
2336 Info("TCling::RegisterModule", "Module %s in modulemap failed to load.", ModuleName.c_str());
2337 }
2338 }
2339
2341 llvm::SmallString<256> pcmFileNameFullPath(dyLibName);
2342 // The path dyLibName might not be absolute. This can happen if dyLibName
2343 // is linked to an executable in the same folder.
2344 llvm::sys::fs::make_absolute(pcmFileNameFullPath);
2345 llvm::sys::path::remove_filename(pcmFileNameFullPath);
2346 llvm::sys::path::append(pcmFileNameFullPath,
2348 LoadPCM(pcmFileNameFullPath.str().str());
2349 }
2350
2351 { // scope within which diagnostics are de-activated
2352 // For now we disable diagnostics because we saw them already at
2353 // dictionary generation time. That won't be an issue with the PCMs.
2354
2355 clangDiagSuppr diagSuppr(TheSema.getDiagnostics());
2356
2357#if defined(R__MUST_REVISIT)
2358#if R__MUST_REVISIT(6,2)
2359 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
2360#endif
2361#endif
2362
2365
2366 const cling::Transaction* watermark = fInterpreter->getLastTransaction();
2367 cling::Interpreter::CompilationResult compRes = fInterpreter->parseForModule(code.Data());
2368 if (isACLiC) {
2369 // Register an unload point.
2370 fMetaProcessor->registerUnloadPoint(watermark, headers[0]);
2371 }
2372
2373 assert(cling::Interpreter::kSuccess == compRes &&
2374 "Payload code of a dictionary could not be parsed correctly.");
2375 if (compRes!=cling::Interpreter::kSuccess) {
2376 Warning("TCling::RegisterModule",
2377 "Problems declaring payload for module %s.", modulename) ;
2378 }
2379 }
2380 }
2381
2382 // Now that all the header have been registered/compiled, let's
2383 // make sure to 'reset' the TClass that have a class init in this module
2384 // but already had their type information available (using information/header
2385 // loaded from other modules or from class rules or from opening a TFile
2386 // or from loading header in a way that did not provoke the loading of
2387 // the library we just loaded).
2389
2391 // __ROOTCLING__ might be pulled in through PCH
2392 fInterpreter->declare("#ifdef __ROOTCLING__\n"
2393 "#undef __ROOTCLING__\n"
2395 "#endif");
2396 }
2397
2398 if (wasDlopened) {
2400 void* dyLibHandle = fRegisterModuleDyLibs.back();
2401 fRegisterModuleDyLibs.pop_back();
2403 }
2404}
2405
2407 clang::CompilerInstance& CI = *GetInterpreterImpl()->getCI();
2408 ASTContext &C = CI.getASTContext();
2409
2410 // Do not do anything if we have no global module index.
2411 // FIXME: This is mostly to real with false positives in the TTabCom
2412 // interface for non-modules.
2413 if (!fCxxModulesEnabled)
2414 return;
2415
2416 if (IdentifierInfoLookup *External = C.Idents.getExternalIdentifierLookup()) {
2417 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
2418 for (llvm::StringRef Ident = Iter->Next(); !Ident.empty(); Ident = Iter->Next()) {
2419 std::string I = Ident.str();
2420 if (!Idents.Contains(I.data()))
2421 Idents.Add(new TObjString(I.c_str()));
2422 }
2423 }
2424}
2425
2426
2427////////////////////////////////////////////////////////////////////////////////
2428/// Register classes that already existed prior to their dictionary loading
2429/// and that already had a ClassInfo (and thus would not be refresh via
2430/// UpdateClassInfo.
2431
2433{
2434 fClassesToUpdate.push_back(std::make_pair(oldcl,dict));
2435}
2436
2437////////////////////////////////////////////////////////////////////////////////
2438/// If the dictionary is loaded, we can remove the class from the list
2439/// (otherwise the class might be loaded twice).
2440
2442{
2443 typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
2444 iterator stop = fClassesToUpdate.end();
2445 for(iterator i = fClassesToUpdate.begin();
2446 i != stop;
2447 ++i)
2448 {
2449 if ( i->first == oldcl ) {
2450 fClassesToUpdate.erase(i);
2451 return;
2452 }
2453 }
2454}
2455
2456
2457////////////////////////////////////////////////////////////////////////////////
2458/// Let cling process a command line.
2459///
2460/// If the command is executed and the error is 0, then the return value
2461/// is the int value corresponding to the result of the executed command
2462/// (float and double return values will be truncated).
2463///
2464
2465// Method for handling the interpreter exceptions.
2466// the MetaProcessor is passing in as argument to teh function, because
2467// cling::Interpreter::CompilationResult is a nested class and it cannot be
2468// forward declared, thus this method cannot be a static member function
2469// of TCling.
2470
2471static int HandleInterpreterException(cling::MetaProcessor* metaProcessor,
2472 const char* input_line,
2473 cling::Interpreter::CompilationResult& compRes,
2474 cling::Value* result)
2475{
2476 try {
2477 return metaProcessor->process(input_line, compRes, result);
2478 }
2479 catch (cling::InterpreterException& ex)
2480 {
2481 Error("HandleInterpreterException", "%s\n%s", ex.what(), "Execution of your code was aborted.");
2482 ex.diagnose();
2483 compRes = cling::Interpreter::kFailure;
2484 }
2485 return 0;
2486}
2487
2488////////////////////////////////////////////////////////////////////////////////
2489
2490bool TCling::DiagnoseIfInterpreterException(const std::exception &e) const
2491{
2492 if (auto ie = dynamic_cast<const cling::InterpreterException*>(&e)) {
2493 ie->diagnose();
2494 return true;
2495 }
2496 return false;
2497}
2498
2499////////////////////////////////////////////////////////////////////////////////
2500
2502{
2503 // Copy the passed line, it comes from a static buffer in TApplication
2504 // which can be reentered through the Cling evaluation routines,
2505 // which would overwrite the static buffer and we would forget what we
2506 // were doing.
2507 //
2509 if (strstr(line,fantomline)) {
2510 // End-Of-Line action
2511 // See the comment (copied from above):
2512 // It is a "fantom" method to synchronize user keyboard input
2513 // and ROOT prompt line (for WIN32)
2514 // and is implemented by
2515 if (gApplication) {
2516 if (gApplication->IsCmdThread()) {
2518 gROOT->SetLineIsProcessing();
2519
2521
2522 gROOT->SetLineHasBeenProcessed();
2523 }
2524 }
2525 return 0;
2526 }
2527
2529 gGlobalMutex->Lock();
2530 if (!gInterpreterMutex)
2533 }
2535 gROOT->SetLineIsProcessing();
2536
2537 struct InterpreterFlagsRAII {
2538 cling::Interpreter* fInterpreter;
2540
2541 InterpreterFlagsRAII(cling::Interpreter* interp):
2542 fInterpreter(interp),
2543 fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
2544 {
2545 fInterpreter->enableDynamicLookup(true);
2546 }
2548 fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
2549 gROOT->SetLineHasBeenProcessed();
2550 }
2552
2553 // A non-zero returned value means the given line was
2554 // not a complete statement.
2555 int indent = 0;
2556 // This will hold the resulting value of the evaluation the given line.
2557 cling::Value result;
2558 cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
2559 if (!strncmp(sLine.Data(), ".L", 2) || !strncmp(sLine.Data(), ".x", 2) ||
2560 !strncmp(sLine.Data(), ".X", 2)) {
2561 // If there was a trailing "+", then CINT compiled the code above,
2562 // and we will need to strip the "+" before passing the line to cling.
2565 TString arguments;
2566 TString io;
2568 aclicMode, arguments, io);
2569 if (aclicMode.Length()) {
2570 // Remove the leading '+'
2571 R__ASSERT(aclicMode[0]=='+' && "ACLiC mode must start with a +");
2572 aclicMode[0]='k'; // We always want to keep the .so around.
2573 if (aclicMode[1]=='+') {
2574 // We have a 2nd +
2575 aclicMode[1]='f'; // We want to force the recompilation.
2576 }
2578 // ACLiC failed.
2579 compRes = cling::Interpreter::kFailure;
2580 } else {
2581 if (strncmp(sLine.Data(), ".L", 2) != 0) {
2582 // if execution was requested.
2583
2584 if (arguments.Length() == 0) {
2585 arguments = "()";
2586 }
2587 // We need to remove the extension.
2588 Ssiz_t ext = fname.Last('.');
2589 if (ext != kNPOS) {
2590 fname.Remove(ext);
2591 }
2592 const char *function = gSystem->BaseName(fname);
2593 mod_line = function + arguments + io;
2595 }
2596 }
2597 } else if (cling::DynamicLibraryManager::isSharedLibrary(fname.Data()) &&
2598 strncmp(sLine.Data(), ".L", 2) != 0) { // .x *.so or *.dll
2599 if (gSystem->Load(fname) < 0) {
2600 // Loading failed.
2601 compRes = cling::Interpreter::kFailure;
2602 } else {
2603 if (arguments.Length() == 0) {
2604 arguments = "()";
2605 }
2606 // We need to remove the extension. (*.so or *.dll)
2607 Ssiz_t ext = fname.Last('.');
2608 if (ext != kNPOS) {
2609 fname.Remove(ext);
2610 }
2611 // Now we try to find the 'main' function to run within this shared library
2612 // We distinguish two cases: a library.so with a function library(args),
2613 // or a precompiled ACLiC macro (macro_C.so) with a function macro(args).
2614 // Only in the second case, we need to strip the suffix _C or _cpp from fname.
2615 if (!gInterpreter->GetFunction(nullptr, gSystem->BaseName(fname))) { // AcLiC macro
2616 // We need to remove the automatically appended _ extension when compiling (macro_C from macro.C)
2617 ext = fname.Last('_');
2618 if (ext != kNPOS) {
2619 fname.Remove(ext);
2620 }
2621 }
2622 const char *function = gSystem->BaseName(fname);
2623 mod_line = function + arguments + io;
2625 }
2626 } else {
2627 // neither ACLiC nor run shared-library (.x)
2628 size_t unnamedMacroOpenCurly;
2629 {
2630 std::string code;
2631 std::string codeline;
2632 // Windows requires std::ifstream::binary to properly handle
2633 // CRLF and LF line endings
2634 std::ifstream in(fname, std::ifstream::binary);
2635 while (in) {
2636 std::getline(in, codeline);
2637 code += codeline + "\n";
2638 }
2640 = cling::utils::isUnnamedMacro(code, fInterpreter->getCI()->getLangOpts());
2641 }
2642
2643 fCurExecutingMacros.push_back(fname);
2644 if (unnamedMacroOpenCurly != std::string::npos) {
2645 compRes = fMetaProcessor->readInputFromFile(fname.Data(), &result,
2647 } else {
2648 // No DynLookup for .x, .L of named macros.
2649 fInterpreter->enableDynamicLookup(false);
2651 }
2652 fCurExecutingMacros.pop_back();
2653 }
2654 } // .L / .X / .x
2655 else {
2656 if (0!=strncmp(sLine.Data(), ".autodict ",10) && sLine != ".autodict") {
2657 // explicitly ignore .autodict without having to support it
2658 // in cling.
2659
2660 // Turn off autoparsing if this is an include directive
2661 bool isInclusionDirective = sLine.Contains("\n#include") || sLine.BeginsWith("#include");
2665 } else {
2667 }
2668 }
2669 }
2670 if (result.isValid())
2672 if (indent) {
2673 if (error)
2674 *error = kProcessing;
2675 return 0;
2676 }
2677 if (error) {
2678 switch (compRes) {
2679 case cling::Interpreter::kSuccess: *error = kNoError; break;
2680 case cling::Interpreter::kFailure: *error = kRecoverable; break;
2681 case cling::Interpreter::kMoreInputExpected: *error = kProcessing; break;
2682 }
2683 }
2684 if (compRes == cling::Interpreter::kSuccess
2685 && result.isValid()
2686 && !result.isVoid())
2687 {
2688 return result.castAs<Longptr_t>();
2689 }
2690 return 0;
2691}
2692
2693////////////////////////////////////////////////////////////////////////////////
2694/// No-op; see TRint instead.
2695
2697{
2698}
2699
2700////////////////////////////////////////////////////////////////////////////////
2701/// \brief Add a directory to the list of directories in which the
2702/// interpreter looks for include files.
2703/// \param[in] path The path to the directory.
2704/// \note Only one path item can be specified at a time, i.e. "path1:path2" is
2705/// \b NOT supported.
2706/// \warning Only the path to the directory should be specified, without
2707/// prepending the \c -I prefix, i.e.
2708/// <tt>gCling->AddIncludePath("/path/to/my/includes")</tt>. If the
2709/// \c -I prefix is used it will be ignored.
2710void TCling::AddIncludePath(const char *path)
2711{
2713 // Favorite source of annoyance: gSystem->AddIncludePath() needs "-I",
2714 // gCling->AddIncludePath() does not! Work around that inconsistency:
2715 if (path[0] == '-' && path[1] == 'I')
2716 path += 2;
2717 TString sPath(path);
2719#ifdef _MSC_VER
2720 if (sPath.BeginsWith("/")) {
2721 char drive[3];
2722 snprintf(drive, 3, "%c:", _getdrive() + 'A' - 1);
2723 sPath.Prepend(drive);
2724 }
2725#endif
2726 fInterpreter->AddIncludePath(sPath.Data());
2727}
2728
2729////////////////////////////////////////////////////////////////////////////////
2730/// Visit all members over members, recursing over base classes.
2731
2733 const TClass* cl, Bool_t isTransient)
2734{
2735 if (insp.GetObjectValidity() == TMemberInspector::kUnset) {
2736 insp.SetObjectValidity(obj ? TMemberInspector::kValidObjectGiven
2738 }
2739
2740 if (!cl || cl->GetCollectionProxy()) {
2741 // We do not need to investigate the content of the STL
2742 // collection, they are opaque to us (and details are
2743 // uninteresting).
2744 return;
2745 }
2746
2747 static const TClassRef clRefString("std::string");
2748 if (clRefString == cl) {
2749 // We stream std::string without going through members..
2750 return;
2751 }
2752
2753 if (TClassEdit::IsStdArray(cl->GetName())) {
2754 // We treat std arrays as C arrays
2755 return;
2756 }
2757
2758 if (TClassEdit::IsUniquePtr(cl->GetName())) {
2759 // Ignore error caused by the inside of std::unique_ptr
2760 // This is needed solely because of rootclingIO's IsUnsupportedUniquePointer
2761 // which checks the number of elements in the GetListOfRealData.
2762 // If this usage is removed, this can be replaced with a return statement.
2763 // See https://github.com/root-project/root/issues/13574
2764 isTransient = true;
2765 }
2766
2767 const char* cobj = (const char*) obj; // for ptr arithmetics
2768
2769 // Treat the case of std::complex in a special manner. We want to enforce
2770 // the layout of a stl implementation independent class, which is the
2771 // complex as implemented in ROOT5.
2772
2773 // A simple lambda to simplify the code
2774 auto inspInspect = [&] (ptrdiff_t offset){
2775 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_real", cobj, isTransient);
2776 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_imag", cobj + offset, isTransient);
2777 };
2778
2780 switch(complexType) {
2782 {
2783 break;
2784 }
2786 {
2787 inspInspect(sizeof(float));
2788 return;
2789 }
2791 {
2792 inspInspect(sizeof(double));
2793 return;
2794 }
2796 {
2797 inspInspect(sizeof(int));
2798 return;
2799 }
2801 {
2802 inspInspect(sizeof(long));
2803 return;
2804 }
2805 }
2806
2807 static clang::PrintingPolicy
2808 printPol(fInterpreter->getCI()->getLangOpts());
2809 if (printPol.Indentation) {
2810 // not yet initialized
2811 printPol.Indentation = 0;
2812 printPol.SuppressInitializers = true;
2813 }
2814
2815 const char* clname = cl->GetName();
2816 // Printf("Inspecting class %s\n", clname);
2817
2818 const clang::ASTContext& astContext = fInterpreter->getCI()->getASTContext();
2819 const clang::Decl *scopeDecl = nullptr;
2820 const clang::Type *recordType = nullptr;
2821
2822 if (cl->GetClassInfo()) {
2824 scopeDecl = clingCI->GetDecl();
2825 recordType = clingCI->GetType();
2826 } else {
2827 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
2828 // Diags will complain about private classes:
2829 scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2830 &recordType);
2831 }
2832 if (!scopeDecl) {
2833 Error("InspectMembers", "Cannot find Decl for class %s", clname);
2834 return;
2835 }
2836 const clang::CXXRecordDecl* recordDecl
2837 = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2838 if (!recordDecl) {
2839 Error("InspectMembers", "Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2840 return;
2841 }
2842
2843 {
2844 // Force possible deserializations first. We need to have no pending
2845 // Transaction when passing control flow to the inspector below (ROOT-7779).
2846 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2847
2848 astContext.getASTRecordLayout(recordDecl);
2849
2850 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2851 eField = recordDecl->field_end(); iField != eField; ++iField) {}
2852 }
2853
2854 const clang::ASTRecordLayout& recLayout
2855 = astContext.getASTRecordLayout(recordDecl);
2856
2857 // TVirtualCollectionProxy *proxy = cl->GetCollectionProxy();
2858 // if (proxy && ( proxy->GetProperties() & TVirtualCollectionProxy::kIsEmulated ) ) {
2859 // Error("InspectMembers","The TClass for %s has an emulated proxy but we are looking at a compiled version of the collection!\n",
2860 // cl->GetName());
2861 // }
2862 if (cl->Size() != recLayout.getSize().getQuantity()) {
2863 Error("InspectMembers","TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2864 cl->GetName(),cl->Size(),(Long64_t)recLayout.getSize().getQuantity());
2865 }
2866
2867 unsigned iNField = 0;
2868 // iterate over fields
2869 // FieldDecls are non-static, else it would be a VarDecl.
2870 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2871 eField = recordDecl->field_end(); iField != eField;
2872 ++iField, ++iNField) {
2873
2874
2875 clang::QualType memberQT = iField->getType();
2876 if (recordType) {
2877 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2879 }
2880 memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2881 if (memberQT.isNull()) {
2882 std::string memberName;
2883 llvm::raw_string_ostream stream(memberName);
2884 // Don't trigger fopen of the source file to count lines:
2885 printPol.AnonymousTagLocations = false;
2886 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2887 stream.flush();
2888 Error("InspectMembers",
2889 "Cannot retrieve QualType for member %s while inspecting class %s",
2890 memberName.c_str(), clname);
2891 continue; // skip member
2892 }
2893 const clang::Type* memType = memberQT.getTypePtr();
2894 if (!memType) {
2895 std::string memberName;
2896 llvm::raw_string_ostream stream(memberName);
2897 // Don't trigger fopen of the source file to count lines:
2898 printPol.AnonymousTagLocations = false;
2899 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2900 stream.flush();
2901 Error("InspectMembers",
2902 "Cannot retrieve Type for member %s while inspecting class %s",
2903 memberName.c_str(), clname);
2904 continue; // skip member
2905 }
2906
2907 const clang::Type* memNonPtrType = memType;
2908 Bool_t ispointer = false;
2909 if (memNonPtrType->isPointerType()) {
2910 ispointer = true;
2911 clang::QualType ptrQT
2912 = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2913 if (recordType) {
2914 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2916 }
2917 ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2918 if (ptrQT.isNull()) {
2919 std::string memberName;
2920 llvm::raw_string_ostream stream(memberName);
2921 // Don't trigger fopen of the source file to count lines:
2922 printPol.AnonymousTagLocations = false;
2923 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2924 stream.flush();
2925 Error("InspectMembers",
2926 "Cannot retrieve pointee Type for member %s while inspecting class %s",
2927 memberName.c_str(), clname);
2928 continue; // skip member
2929 }
2930 memNonPtrType = ptrQT.getTypePtr();
2931 }
2932
2933 // assemble array size(s): "[12][4][]"
2934 llvm::SmallString<8> arraySize;
2935 const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2936 unsigned arrLevel = 0;
2937 bool haveErrorDueToArray = false;
2938 while (arrType) {
2939 ++arrLevel;
2940 arraySize += '[';
2941 const clang::ConstantArrayType* constArrType =
2942 clang::dyn_cast<clang::ConstantArrayType>(arrType);
2943 if (constArrType) {
2944 constArrType->getSize().toStringUnsigned(arraySize);
2945 }
2946 arraySize += ']';
2947 clang::QualType subArrQT = arrType->getElementType();
2948 if (subArrQT.isNull()) {
2949 std::string memberName;
2950 llvm::raw_string_ostream stream(memberName);
2951 // Don't trigger fopen of the source file to count lines:
2952 printPol.AnonymousTagLocations = false;
2953 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2954 stream.flush();
2955 Error("InspectMembers",
2956 "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2957 arrLevel, subArrQT.getAsString(printPol).c_str(),
2958 memberName.c_str(), clname);
2959 haveErrorDueToArray = true;
2960 break;
2961 }
2962 arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2963 }
2964 if (haveErrorDueToArray) {
2965 continue; // skip member
2966 }
2967
2968 // construct member name
2969 std::string fieldName;
2970 if (memType->isPointerType()) {
2971 fieldName = "*";
2972 }
2973
2974 // Check if this field has a custom ioname, if not, just use the one of the decl
2975 std::string ioname(iField->getName());
2977 fieldName += ioname;
2978 fieldName += arraySize;
2979
2980 // get member offset
2981 // NOTE currently we do not support bitfield and do not support
2982 // member that are not aligned on 'bit' boundaries.
2983 clang::CharUnits offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2984 ptrdiff_t fieldOffset = offset.getQuantity();
2985
2986 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fBits[2]", fBits);
2987 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fName", &fName);
2988 // R__insp.InspectMember(fName, "fName.");
2989 // R__insp.Inspect(R__cl, R__insp.GetParent(), "*fClass", &fClass);
2990
2991 // If the class has a custom streamer and the type of the filed is a
2992 // private enum, struct or class, skip it.
2993 if (!insp.IsTreatingNonAccessibleTypes()){
2994 auto iFiledQtype = iField->getType();
2995 if (auto tagDecl = iFiledQtype->getAsTagDecl()){
2996 auto declAccess = tagDecl->getAccess();
2998 continue;
2999 }
3000 }
3001 }
3002
3003 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
3004
3005 if (!ispointer) {
3006 const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
3007 if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
3008 // nested objects get an extra call to InspectMember
3009 // R__insp.InspectMember("FileStat_t", (void*)&fFileStat, "fFileStat.", false);
3010 std::string sFieldRecName;
3013 clang::QualType(memNonPtrType,0),
3014 *fInterpreter,
3016 }
3017
3018 TDataMember* mbr = cl->GetDataMember(ioname.c_str());
3019 // if we can not find the member (which should not really happen),
3020 // let's consider it transient.
3021 Bool_t transient = isTransient || !mbr || !mbr->IsPersistent();
3022 if (!mbr || !mbr->IsPersistent())
3023 insp.IncrementNestedTransient();
3024 insp.InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
3025 (fieldName + '.').c_str(), transient);
3026 if (!mbr || !mbr->IsPersistent())
3027 insp.DecrementNestedTransient();
3028
3029 }
3030 }
3031 } // loop over fields
3032
3033 // inspect bases
3034 // TNamed::ShowMembers(R__insp);
3035 unsigned iNBase = 0;
3036 for (clang::CXXRecordDecl::base_class_const_iterator iBase
3037 = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
3038 iBase != eBase; ++iBase, ++iNBase) {
3039 clang::QualType baseQT = iBase->getType();
3040 if (baseQT.isNull()) {
3041 Error("InspectMembers",
3042 "Cannot find QualType for base number %d while inspecting class %s",
3043 iNBase, clname);
3044 continue;
3045 }
3046 const clang::CXXRecordDecl* baseDecl
3047 = baseQT->getAsCXXRecordDecl();
3048 if (!baseDecl) {
3049 Error("InspectMembers",
3050 "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
3051 iNBase, clname);
3052 continue;
3053 }
3054 TClass* baseCl=nullptr;
3055 std::string sBaseName;
3056 // Try with the DeclId
3057 std::vector<TClass*> foundClasses;
3059 if (foundClasses.size()==1){
3061 } else {
3062 // Try with the normalised Name, as a fallback
3063 if (!baseCl){
3065 baseQT,
3066 *fInterpreter,
3069 }
3070 }
3071
3072 if (!baseCl){
3073 std::string qualNameForDiag;
3075 Error("InspectMembers",
3076 "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
3077 continue;
3078 }
3079
3080 int64_t baseOffset;
3081 if (iBase->isVirtual()) {
3082 if (insp.GetObjectValidity() == TMemberInspector::kNoObjectGiven) {
3083 if (!isTransient) {
3084 Error("InspectMembers",
3085 "Base %s of class %s is virtual but no object provided",
3086 sBaseName.c_str(), clname);
3087 }
3089 } else {
3090 // We have an object to determine the vbase offset.
3092 TClingClassInfo* baseCi = (TClingClassInfo*)baseCl->GetClassInfo();
3093 if (ci && baseCi) {
3094 baseOffset = ci->GetBaseOffset(baseCi, const_cast<void*>(obj),
3095 true /*isDerivedObj*/);
3096 if (baseOffset == -1) {
3097 Error("InspectMembers",
3098 "Error calculating offset of virtual base %s of class %s",
3099 sBaseName.c_str(), clname);
3100 }
3101 } else {
3102 Error("InspectMembers",
3103 "Cannot calculate offset of virtual base %s of class %s",
3104 sBaseName.c_str(), clname);
3105 continue;
3106 }
3107 }
3108 } else {
3109 baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
3110 }
3111 // TOFIX: baseCl can be null here!
3112 if (baseCl->IsLoaded()) {
3113 // For loaded class, CallShowMember will (especially for TObject)
3114 // call the virtual ShowMember rather than the class specific version
3115 // resulting in an infinite recursion.
3117 } else {
3118 baseCl->CallShowMembers(cobj + baseOffset,
3119 insp, isTransient);
3120 }
3121 } // loop over bases
3122}
3123
3124////////////////////////////////////////////////////////////////////////////////
3125/// Check if constructor exited correctly, ie the instance is in a valid state
3126/// \return true if there is a compiler instance available, false otherwise
3128{
3129 return fInterpreter->getCI() != nullptr;
3130}
3131
3132////////////////////////////////////////////////////////////////////////////////
3133/// Reset the interpreter internal state in case a previous action was not correctly
3134/// terminated.
3135
3137{
3138 // No-op there is not equivalent state (to be cleared) in Cling.
3139}
3140
3141////////////////////////////////////////////////////////////////////////////////
3142/// Delete existing temporary values.
3143
3145{
3146 // No-op for cling due to cling::Value.
3147}
3148
3149////////////////////////////////////////////////////////////////////////////////
3150/// Declare code to the interpreter, without any of the interpreter actions
3151/// that could trigger a re-interpretation of the code. I.e. make cling
3152/// behave like a compiler: no dynamic lookup, no input wrapping for
3153/// subsequent execution, no automatic provision of declarations but just a
3154/// plain `#include`.
3155/// Returns true on success, false on failure.
3156
3157bool TCling::Declare(const char* code)
3158{
3160
3163
3164 bool oldDynLookup = fInterpreter->isDynamicLookupEnabled();
3165 fInterpreter->enableDynamicLookup(false);
3166 bool oldRawInput = fInterpreter->isRawInputEnabled();
3167 fInterpreter->enableRawInput(true);
3168
3169 Bool_t ret = LoadText(code);
3170
3171 fInterpreter->enableRawInput(oldRawInput);
3172 fInterpreter->enableDynamicLookup(oldDynLookup);
3173 return ret;
3174}
3175
3176////////////////////////////////////////////////////////////////////////////////
3177/// It calls a "fantom" method to synchronize user keyboard input
3178/// and ROOT prompt line.
3179
3184
3185// This static function is a hop of TCling::IsLibraryLoaded, which is taking a lock and calling
3186// into this function. This is because we wanted to avoid a duplication in TCling::IsLoaded, which
3187// was already taking a lock.
3188static Bool_t s_IsLibraryLoaded(const char* libname, cling::Interpreter* fInterpreter)
3189{
3190 // Check shared library.
3193 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.Data());
3194 return false;
3195}
3196
3202
3203////////////////////////////////////////////////////////////////////////////////
3204/// Return true if ROOT has cxxmodules pcm for a given library name.
3205// FIXME: We need to be able to support lazy loading of pcm generated by ACLiC.
3207{
3208 llvm::StringRef ModuleName(libname);
3209 ModuleName = llvm::sys::path::stem(ModuleName);
3210 ModuleName.consume_front("lib");
3211
3212 // FIXME: In case when the modulemap is not yet loaded we will return the
3213 // wrong result. Consider a call to HasPCMForLibrary(../test/libEvent.so)
3214 // We will only load the modulemap for libEvent.so after we dlopen libEvent
3215 // which may happen after calling this interface. Maybe we should also check
3216 // if there is a Event.pcm file and a module.modulemap, load it and return
3217 // true.
3218 clang::ModuleMap &moduleMap = fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
3219 clang::Module *M = moduleMap.findModule(ModuleName);
3220 return M && !M->IsUnimportable && M->getASTFile();
3221}
3222
3223////////////////////////////////////////////////////////////////////////////////
3224/// Return true if the file has already been loaded by cint.
3225/// We will try in this order:
3226/// actual filename
3227/// filename as a path relative to
3228/// the include path
3229/// the shared library path
3230
3232{
3234
3235 //FIXME: if we use llvm::sys::fs::make_absolute all this can go away. See
3236 // cling::DynamicLibraryManager.
3237
3238 std::string file_name = filename;
3239 size_t at = std::string::npos;
3240 while ((at = file_name.find("/./")) != std::string::npos)
3241 file_name.replace(at, 3, "/");
3242
3243 std::string filesStr = "";
3244 llvm::raw_string_ostream filesOS(filesStr);
3245 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3246 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3247 filesOS.flush();
3248
3249 llvm::SmallVector<llvm::StringRef, 100> files;
3250 llvm::StringRef(filesStr).split(files, "\n");
3251
3252 std::set<std::string> fileMap;
3253 llvm::StringRef file_name_ref(file_name);
3254 // Fill fileMap; return early on exact match.
3256 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3257 if ((*iF) == file_name_ref) return kTRUE; // exact match
3258 fileMap.insert(iF->str());
3259 }
3260
3261 if (fileMap.empty()) return kFALSE;
3262
3263 // Check MacroPath.
3264 TString sFilename(file_name.c_str());
3266 && fileMap.count(sFilename.Data())) {
3267 return kTRUE;
3268 }
3269
3270 // Check IncludePath.
3271 TString incPath = gSystem->GetIncludePath(); // of the form -Idir1 -Idir2 -Idir3
3272 incPath.Append(":").Prepend(" "); // to match " -I" (note leading ' ')
3273 incPath.ReplaceAll(" -I", ":"); // of form :dir1 :dir2:dir3
3274 while (incPath.Index(" :") != -1) {
3275 incPath.ReplaceAll(" :", ":");
3276 }
3277 incPath.Prepend(".:");
3278 sFilename = file_name.c_str();
3280 && fileMap.count(sFilename.Data())) {
3281 return kTRUE;
3282 }
3283
3284 // Check shared library.
3285 if (s_IsLibraryLoaded(file_name.c_str(), GetInterpreterImpl()))
3286 return kTRUE;
3287
3288 //FIXME: We must use the cling::Interpreter::lookupFileOrLibrary iface.
3289 clang::ConstSearchDirIterator *CurDir = nullptr;
3290 clang::Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
3291 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3292 auto FE = HS.LookupFile(file_name.c_str(),
3293 clang::SourceLocation(),
3294 /*isAngled*/ false,
3295 /*FromDir*/ nullptr, CurDir,
3296 clang::ArrayRef<std::pair<clang::OptionalFileEntryRef,
3297 clang::DirectoryEntryRef>>(),
3298 /*SearchPath*/ nullptr,
3299 /*RelativePath*/ nullptr,
3300 /*RequestingModule*/ nullptr,
3301 /*SuggestedModule*/ nullptr,
3302 /*IsMapped*/ nullptr,
3303 /*IsFrameworkFound*/ nullptr,
3304 /*SkipCache*/ false,
3305 /*BuildSystemModule*/ false,
3306 /*OpenFile*/ false,
3307 /*CacheFail*/ false);
3308 if (FE) {
3309 // check in the source manager if the file is actually loaded
3310 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3311 // this works only with header (and source) files...
3312 clang::FileID FID = SM.translateFile(*FE);
3313 if (!FID.isInvalid() && FID.getHashValue() == 0)
3314 return kFALSE;
3315 else {
3316 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3317 if (SLocE.isFile() && !SLocE.getFile().getContentCache().getBufferIfLoaded())
3318 return kFALSE;
3319 if (!FID.isInvalid())
3320 return kTRUE;
3321 }
3322 // ...then check shared library again, but with full path now
3323 sFilename = FE->getName().str();
3325 && fileMap.count(sFilename.Data())) {
3326 return kTRUE;
3327 }
3328 }
3329 return kFALSE;
3330}
3331
3332
3333#if defined(R__MACOSX)
3334
3335////////////////////////////////////////////////////////////////////////////////
3336/// Check if lib is in the dynamic linker cache, returns true if it is, and if so,
3337/// modifies the library file name parameter `lib` from `/usr/lib/libFOO.dylib`
3338/// to `-lFOO` such that it can be passed to the linker.
3339/// This is a unique feature of macOS 11.
3340
3341static bool R__UpdateLibFileForLinking(TString &lib)
3342{
3343 const char *mapfile = nullptr;
3344#if __x86_64__
3345 mapfile = "/System/Library/dyld/dyld_shared_cache_x86_64.map";
3346#elif __arm64__
3347 mapfile = "/System/Library/dyld/dyld_shared_cache_arm64e.map";
3348#else
3349 #error unsupported architecture
3350#endif
3351 if (std::ifstream cacheMap{mapfile}) {
3352 std::string line;
3353 while (getline(cacheMap, line)) {
3354 if (line.find(lib) != std::string::npos) {
3355 lib.ReplaceAll("/usr/lib/lib","-l");
3356 lib.ReplaceAll(".dylib","");
3357 return true;
3358 }
3359 }
3360 return false;
3361 }
3362 return false;
3363}
3364#endif // R__MACOSX
3365
3366#if defined (R__LINUX) || defined (R__FBSD)
3367
3368////////////////////////////////////////////////////////////////////////////////
3369/// Callback for dl_iterate_phdr(), see `man dl_iterate_phdr`.
3370/// Collects opened libraries.
3371
3372static int callback_for_dl_iterate_phdr(struct dl_phdr_info *info, size_t size, void *data)
3373{
3374 // This function is called through UpdateListOfLoadedSharedLibraries() which is locked.
3375 static std::unordered_set<decltype(info->dlpi_addr)> sKnownLoadedLibBaseAddrs;
3376
3377 auto newLibs = static_cast<std::vector<std::string>*>(data);
3378 if (!sKnownLoadedLibBaseAddrs.count(info->dlpi_addr)) {
3379 // Skip \0, "", and kernel pseudo-libs linux-vdso.so.1 or linux-gate.so.1
3380 if (info->dlpi_name && info->dlpi_name[0]
3381#if defined(R__FBSD)
3382 //skip the executable (with null addr)
3383 && info->dlpi_addr
3384 //has no path
3385 && strncmp(info->dlpi_name, "[vdso]", 6)
3386 //the linker does not like to be mmapped
3387 //causes a crash in cling::DynamicLibraryManager::loadLibrary())
3388 //with error message "mmap of entire address space failed: Cannot allocate memory"
3389 && strncmp(info->dlpi_name, "/libexec/ld-elf.so.1", 20)
3390#endif
3391 && strncmp(info->dlpi_name, "linux-vdso.so", 13)
3392 && strncmp(info->dlpi_name, "linux-vdso32.so", 15)
3393 && strncmp(info->dlpi_name, "linux-vdso64.so", 15)
3394 && strncmp(info->dlpi_name, "linux-gate.so", 13))
3395 newLibs->emplace_back(info->dlpi_name);
3396 sKnownLoadedLibBaseAddrs.insert(info->dlpi_addr);
3397 }
3398 // No matter what the doc says, return != 0 means "stop the iteration".
3399 return 0;
3400}
3401
3402#endif // R__LINUX || R__FBSD
3403
3404
3405////////////////////////////////////////////////////////////////////////////////
3406
3408{
3409#if defined(R__WIN32) || defined(__CYGWIN__)
3410 HMODULE hModules[1024];
3411 void *hProcess;
3412 unsigned long cbModules;
3413 unsigned int i;
3414 hProcess = (void *)::GetCurrentProcess();
3416 // start at 1 to skip the executable itself
3417 for (i = 1; i < (cbModules / sizeof(void *)); i++) {
3418 static const int bufsize = 260;
3419 wchar_t winname[bufsize];
3420 char posixname[bufsize];
3422#if defined(__CYGWIN__)
3424#else
3425 std::wstring wpath = winname;
3426 std::replace(wpath.begin(), wpath.end(), '\\', '/');
3427 string path(wpath.begin(), wpath.end());
3428 strncpy(posixname, path.c_str(), bufsize);
3429#endif
3432 }
3433 }
3434#elif defined(R__MACOSX)
3435 // fPrevLoadedDynLibInfo stores the *next* image index to look at
3436 uint32_t imageIndex = (uint32_t) (size_t) fPrevLoadedDynLibInfo;
3437
3439 // Skip non-dylibs
3440 if (mh->filetype == MH_DYLIB) {
3441 if (const char* imageName = _dyld_get_image_name(imageIndex)) {
3443 }
3444 }
3445
3446 ++imageIndex;
3447 }
3448 fPrevLoadedDynLibInfo = (void*)(size_t)imageIndex;
3449#elif defined(R__LINUX) || defined(R__FBSD)
3450 // fPrevLoadedDynLibInfo is unused on Linux.
3451 (void) fPrevLoadedDynLibInfo;
3452
3453 std::vector<std::string> newLibs;
3455 for (auto &&lib: newLibs)
3456 RegisterLoadedSharedLibrary(lib.c_str());
3457#else
3458 Error("TCling::UpdateListOfLoadedSharedLibraries",
3459 "Platform not supported!");
3460#endif
3461}
3462
3463namespace {
3464template <int N>
3465static bool StartsWithStrLit(const char *haystack, const char (&needle)[N]) {
3466 return !strncmp(haystack, needle, N - 1);
3467}
3468}
3469
3470////////////////////////////////////////////////////////////////////////////////
3471/// Register a new shared library name with the interpreter; add it to
3472/// fSharedLibs.
3473
3475{
3476 // Ignore NULL filenames, aka "the process".
3477 if (!filename) return;
3478
3479 // Tell the interpreter that this library is available; all libraries can be
3480 // used to resolve symbols.
3481 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3482 if (!DLM->isLibraryLoaded(filename)) {
3483 DLM->loadLibrary(filename, true /*permanent*/, true /*resolved*/);
3484 }
3485
3486#if defined(R__MACOSX)
3487 // Check that this is not a system library that does not exist on disk.
3488 auto lenFilename = strlen(filename);
3489 auto isInMacOSSystemDir = [](const char *fn) {
3490 return StartsWithStrLit(fn, "/usr/lib/") || StartsWithStrLit(fn, "/System/Library/");
3491 };
3492 if (!strcmp(filename, "cl_kernels") // yepp, no directory
3493
3494 // These we should not link with (e.g. because they forward to .tbd):
3495 || StartsWithStrLit(filename, "/usr/lib/system/")
3496 || StartsWithStrLit(filename, "/usr/lib/libc++")
3497 || StartsWithStrLit(filename, "/System/Library/Frameworks/")
3498 || StartsWithStrLit(filename, "/System/Library/PrivateFrameworks/")
3499 || StartsWithStrLit(filename, "/System/Library/CoreServices/")
3500 || StartsWithStrLit(filename, "/usr/lib/libSystem")
3501 || StartsWithStrLit(filename, "/usr/lib/libstdc++")
3502 || StartsWithStrLit(filename, "/usr/lib/libicucore")
3503 || StartsWithStrLit(filename, "/usr/lib/libbsm")
3504 || StartsWithStrLit(filename, "/usr/lib/libobjc")
3505 || StartsWithStrLit(filename, "/usr/lib/libresolv")
3506 || StartsWithStrLit(filename, "/usr/lib/libauto")
3507 || StartsWithStrLit(filename, "/usr/lib/libcups")
3508 || StartsWithStrLit(filename, "/usr/lib/libDiagnosticMessagesClient")
3509 || StartsWithStrLit(filename, "/usr/lib/liblangid")
3510 || StartsWithStrLit(filename, "/usr/lib/libCRFSuite")
3511 || StartsWithStrLit(filename, "/usr/lib/libpam")
3512 || StartsWithStrLit(filename, "/usr/lib/libOpenScriptingUtil")
3513 || StartsWithStrLit(filename, "/usr/lib/libextension")
3514 || StartsWithStrLit(filename, "/usr/lib/libAudioToolboxUtility")
3515 || StartsWithStrLit(filename, "/usr/lib/liboah")
3516 || StartsWithStrLit(filename, "/usr/lib/libRosetta")
3517 || StartsWithStrLit(filename, "/usr/lib/libCoreEntitlements")
3518 || StartsWithStrLit(filename, "/usr/lib/libssl.")
3519 || StartsWithStrLit(filename, "/usr/lib/libcrypto.")
3520
3521 // The system lib is likely in macOS's blob.
3523
3524 // "Link against the umbrella framework 'System.framework' instead"
3525 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_kernel")
3526 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_platform")
3527 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_pthread")
3528
3529 // "cannot link directly with dylib/framework, your binary is not an allowed client of
3530 // /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/
3531 // SDKs/MacOSX.sdk/usr/lib/libAudioToolboxUtility.tbd for architecture x86_64
3532 || (lenFilename > 4 && !strcmp(filename + lenFilename - 4, ".tbd")))
3533 return;
3536 filename = sFileName.Data();
3537#elif defined(__CYGWIN__)
3538 // Check that this is not a system library
3539 static const int bufsize = 260;
3540 char posixwindir[bufsize];
3541 char *windir = getenv("WINDIR");
3542 if (windir)
3544 else
3545 snprintf(posixwindir, sizeof(posixwindir), "/Windows/");
3546 if (strstr(filename, posixwindir) ||
3547 strstr(filename, "/usr/bin/cyg"))
3548 return;
3549#elif defined(R__WIN32)
3550 if (strstr(filename, "/Windows/"))
3551 return;
3552#elif defined (R__LINUX)
3553 if (strstr(filename, "/ld-linux")
3554 || strstr(filename, "linux-gnu/")
3555 || strstr(filename, "/libstdc++.")
3556 || strstr(filename, "/libgcc")
3557 || strstr(filename, "/libc.")
3558 || strstr(filename, "/libdl.")
3559 || strstr(filename, "/libm."))
3560 return;
3561#endif
3562 // Update string of available libraries.
3563 if (!fSharedLibs.IsNull()) {
3564 fSharedLibs.Append(" ");
3565 }
3567}
3568
3569////////////////////////////////////////////////////////////////////////////////
3570/// Load a library file in cling's memory.
3571/// if 'system' is true, the library is never unloaded.
3572/// Return 0 on success, -1 on failure.
3573
3575{
3576 assert(!IsFromRootCling() && "Trying to load library from rootcling!");
3577
3578 // Used to return 0 on success, 1 on duplicate, -1 on failure, -2 on "fatal".
3580 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3581 std::string canonLib = DLM->lookupLibrary(filename);
3582 cling::DynamicLibraryManager::LoadLibResult res
3583 = cling::DynamicLibraryManager::kLoadLibNotFound;
3584 if (!canonLib.empty()) {
3585 if (system)
3586 res = DLM->loadLibrary(filename, system, true);
3587 else {
3588 // For the non system libs, we'd like to be able to unload them.
3589 // FIXME: Here we lose the information about kLoadLibAlreadyLoaded case.
3590 cling::Interpreter::CompilationResult compRes;
3591 HandleInterpreterException(GetMetaProcessorImpl(), Form(".L %s", canonLib.c_str()), compRes, /*cling::Value*/nullptr);
3592 if (compRes == cling::Interpreter::kSuccess)
3593 res = cling::DynamicLibraryManager::kLoadLibSuccess;
3594 }
3595 }
3596
3597 if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3599 }
3600 switch (res) {
3601 case cling::DynamicLibraryManager::kLoadLibSuccess: return 0;
3602 case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded: return 1;
3603 default: break;
3604 };
3605 return -1;
3606}
3607
3608////////////////////////////////////////////////////////////////////////////////
3609/// Load a macro file in cling's memory.
3610
3611void TCling::LoadMacro(const char* filename, EErrorCode* error)
3612{
3613 ProcessLine(Form(".L %s", filename), error);
3614}
3615
3616////////////////////////////////////////////////////////////////////////////////
3617/// Let cling process a command line asynch.
3618
3620{
3621 return ProcessLine(line, error);
3622}
3623
3624////////////////////////////////////////////////////////////////////////////////
3625/// Let cling process a command line synchronously, i.e we are waiting
3626/// it will be finished.
3627
3629{
3631 if (gApplication) {
3632 if (gApplication->IsCmdThread()) {
3633 return ProcessLine(line, error);
3634 }
3635 return 0;
3636 }
3637 return ProcessLine(line, error);
3638}
3639
3640////////////////////////////////////////////////////////////////////////////////
3641/// Directly execute an executable statement (e.g. "func()", "3+5", etc.
3642/// however not declarations, like "Int_t x;").
3643
3645{
3646#ifdef R__WIN32
3647 // Test on ApplicationImp not being 0 is needed because only at end of
3648 // TApplication ctor the IsLineProcessing flag is set to 0, so before
3649 // we can not use it.
3651 while (gROOT->IsLineProcessing() && !gApplication) {
3652 Warning("Calc", "waiting for cling thread to free");
3653 gSystem->Sleep(500);
3654 }
3655 gROOT->SetLineIsProcessing();
3656 }
3657#endif // R__WIN32
3659 if (error) {
3660 *error = TInterpreter::kNoError;
3661 }
3662 cling::Value valRef;
3663 cling::Interpreter::CompilationResult cr = cling::Interpreter::kFailure;
3664 try {
3665 cr = fInterpreter->evaluate(line, valRef);
3666 }
3667 catch (cling::InterpreterException& ex)
3668 {
3669 Error("Calc", "%s.\n%s", ex.what(), "Evaluation of your expression was aborted.");
3670 ex.diagnose();
3671 cr = cling::Interpreter::kFailure;
3672 }
3673
3674 if (cr != cling::Interpreter::kSuccess) {
3675 // Failure in compilation.
3676 if (error) {
3677 // Note: Yes these codes are weird.
3679 }
3680 return 0L;
3681 }
3682 if (!valRef.isValid()) {
3683 // Failure at runtime.
3684 if (error) {
3685 // Note: Yes these codes are weird.
3686 *error = TInterpreter::kDangerous;
3687 }
3688 return 0L;
3689 }
3690
3691 if (valRef.isVoid()) {
3692 return 0;
3693 }
3694
3696#ifdef R__WIN32
3698 gROOT->SetLineHasBeenProcessed();
3699 }
3700#endif // R__WIN32
3701 return valRef.castAs<Longptr_t>();
3702}
3703
3704////////////////////////////////////////////////////////////////////////////////
3705/// Set a getline function to call when input is needed.
3706
3707void TCling::SetGetline(const char * (*getlineFunc)(const char* prompt),
3708 void (*histaddFunc)(const char* line))
3709{
3710 // If cling offers a replacement for G__pause(), it would need to
3711 // also offer a way to customize at least the history recording.
3712
3713#if defined(R__MUST_REVISIT)
3714#if R__MUST_REVISIT(6,2)
3715 Warning("SetGetline","Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3716#endif
3717#endif
3718}
3719
3720////////////////////////////////////////////////////////////////////////////////
3721/// Helper function to increase the internal Cling count of transactions
3722/// that change the AST.
3723
3724Bool_t TCling::HandleNewTransaction(const cling::Transaction &T)
3725{
3727
3728 if ((std::distance(T.decls_begin(), T.decls_end()) != 1)
3729 || T.deserialized_decls_begin() != T.deserialized_decls_end()
3730 || T.macros_begin() != T.macros_end()
3731 || ((!T.getFirstDecl().isNull()) && ((*T.getFirstDecl().begin()) != T.getWrapperFD()))) {
3733 return true;
3734 }
3735 return false;
3736}
3737
3738////////////////////////////////////////////////////////////////////////////////
3739/// Delete object from cling symbol table so it can not be used anymore.
3740/// cling objects are always on the heap.
3741
3743{
3744 // NOTE: When replacing the mutex by a ReadWrite mutex, we **must**
3745 // put in place the Read/Write part here. Keeping the write lock
3746 // here is 'catasptrophic' for scaling as it means that ALL calls
3747 // to RecursiveRemove will take the write lock and performance
3748 // of many threads trying to access the write lock at the same
3749 // time is relatively bad.
3751 // Note that fgSetOfSpecials is supposed to be updated by TClingCallbacks::tryFindROOTSpecialInternal
3752 // (but isn't at the moment).
3753 if (obj->IsOnHeap() && fgSetOfSpecials && !((std::set<TObject*>*)fgSetOfSpecials)->empty()) {
3754 std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)fgSetOfSpecials)->find(obj);
3755 if (iSpecial != ((std::set<TObject*>*)fgSetOfSpecials)->end()) {
3757 DeleteGlobal(obj);
3758 ((std::set<TObject*>*)fgSetOfSpecials)->erase(iSpecial);
3759 }
3760 }
3761}
3762
3763////////////////////////////////////////////////////////////////////////////////
3764/// Pressing Ctrl+C should forward here. In the case where we have had
3765/// continuation requested we must reset it.
3766
3768{
3769 fMetaProcessor->cancelContinuation();
3770 // Reset the Cling state to the state saved by the last call to
3771 // TCling::SaveContext().
3772#if defined(R__MUST_REVISIT)
3773#if R__MUST_REVISIT(6,2)
3775 Warning("Reset","Cling should support the equivalent of scratch_upto(&fDictPos)");
3776#endif
3777#endif
3778}
3779
3780////////////////////////////////////////////////////////////////////////////////
3781/// Reset the Cling state to its initial state.
3782
3784{
3785#if defined(R__MUST_REVISIT)
3786#if R__MUST_REVISIT(6,2)
3788 Warning("ResetAll","Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3789#endif
3790#endif
3791}
3792
3793////////////////////////////////////////////////////////////////////////////////
3794/// Reset in Cling the list of global variables to the state saved by the last
3795/// call to TCling::SaveGlobalsContext().
3796///
3797/// Note: Right now, all we do is run the global destructors.
3798
3800{
3802 // TODO:
3803 // Here we should iterate over the transactions (N-3) and revert.
3804 // N-3 because the first three internal to cling.
3805
3806 fInterpreter->runAndRemoveStaticDestructors();
3807}
3808
3809////////////////////////////////////////////////////////////////////////////////
3810/// Reset the Cling 'user' global objects/variables state to the state saved by the last
3811/// call to TCling::SaveGlobalsContext().
3812
3814{
3815#if defined(R__MUST_REVISIT)
3816#if R__MUST_REVISIT(6,2)
3818 Warning("ResetGlobalVar","Cling should support the equivalent of resetglobalvar(obj)");
3819#endif
3820#endif
3821}
3822
3823////////////////////////////////////////////////////////////////////////////////
3824/// Rewind Cling dictionary to the point where it was before executing
3825/// the current macro. This function is typically called after SEGV or
3826/// ctlr-C after doing a longjmp back to the prompt.
3827
3829{
3830#if defined(R__MUST_REVISIT)
3831#if R__MUST_REVISIT(6,2)
3833 Warning("RewindDictionary","Cling should provide a way to revert transaction similar to rewinddictionary()");
3834#endif
3835#endif
3836}
3837
3838////////////////////////////////////////////////////////////////////////////////
3839/// Delete obj from Cling symbol table so it cannot be accessed anymore.
3840/// Returns 1 in case of success and 0 in case object was not in table.
3841
3843{
3844#if defined(R__MUST_REVISIT)
3845#if R__MUST_REVISIT(6,2)
3847 Warning("DeleteGlobal","Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3848#endif
3849#endif
3850 return 0;
3851}
3852
3853////////////////////////////////////////////////////////////////////////////////
3854/// Undeclare obj called name.
3855/// Returns 1 in case of success, 0 for failure.
3856
3858{
3859#if defined(R__MUST_REVISIT)
3860#if R__MUST_REVISIT(6,2)
3861 Warning("DeleteVariable","should do more that just reseting the value to zero");
3862#endif
3863#endif
3864
3866 llvm::StringRef srName(name);
3867 const char* unscopedName = name;
3868 llvm::StringRef::size_type posScope = srName.rfind("::");
3869 const clang::DeclContext* declCtx = nullptr;
3870 if (posScope != llvm::StringRef::npos) {
3871 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3872 const clang::Decl* scopeDecl
3873 = lh.findScope(srName.substr(0, posScope),
3874 cling::LookupHelper::WithDiagnostics);
3875 if (!scopeDecl) {
3876 Error("DeleteVariable", "Cannot find enclosing scope for variable %s",
3877 name);
3878 return 0;
3879 }
3880 declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3881 if (!declCtx) {
3882 Error("DeleteVariable",
3883 "Enclosing scope for variable %s is not a declaration context",
3884 name);
3885 return 0;
3886 }
3887 unscopedName += posScope + 2;
3888 }
3889 // Could trigger deserialization of decls.
3890 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
3891 clang::NamedDecl* nVarDecl
3892 = cling::utils::Lookup::Named(&fInterpreter->getSema(), unscopedName, declCtx);
3893 if (!nVarDecl) {
3894 Error("DeleteVariable", "Unknown variable %s", name);
3895 return 0;
3896 }
3897 clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3898 if (!varDecl) {
3899 Error("DeleteVariable", "Entity %s is not a variable", name);
3900 return 0;
3901 }
3902
3903 clang::QualType qType = varDecl->getType();
3904 const clang::Type* type = qType->getUnqualifiedDesugaredType();
3905 // Cannot set a reference's address to nullptr; the JIT can place it
3906 // into read-only memory (ROOT-7100).
3907 if (type->isPointerType()) {
3908 int** ppInt = (int**)fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3909 // set pointer to invalid.
3910 if (ppInt) *ppInt = nullptr;
3911 }
3912 return 1;
3913}
3914
3915////////////////////////////////////////////////////////////////////////////////
3916/// Save the current Cling state.
3917
3919{
3920#if defined(R__MUST_REVISIT)
3921#if R__MUST_REVISIT(6,2)
3923 Warning("SaveContext","Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3924#endif
3925#endif
3926}
3927
3928////////////////////////////////////////////////////////////////////////////////
3929/// Save the current Cling state of global objects.
3930
3932{
3933#if defined(R__MUST_REVISIT)
3934#if R__MUST_REVISIT(6,2)
3936 Warning("SaveGlobalsContext","Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3937#endif
3938#endif
3939}
3940
3941////////////////////////////////////////////////////////////////////////////////
3942/// No op: see TClingCallbacks (used to update the list of globals)
3943
3947
3948////////////////////////////////////////////////////////////////////////////////
3949/// No op: see TClingCallbacks (used to update the list of global functions)
3950
3954
3955////////////////////////////////////////////////////////////////////////////////
3956/// No op: see TClingCallbacks (used to update the list of types)
3957
3959{
3960}
3961
3962////////////////////////////////////////////////////////////////////////////////
3963/// Check in what order the member of a tuple are layout.
3964enum class ETupleOrdering {
3965 kAscending,
3968};
3969
3975
3981
3983{
3984 std::tuple<int,double> value;
3987
3988 size_t offset0 = ((char*)&(std::get<0>(value))) - ((char*)&value);
3989 size_t offset1 = ((char*)&(std::get<1>(value))) - ((char*)&value);
3990
3991 size_t ascOffset0 = ((char*)&(asc._0)) - ((char*)&asc);
3992 size_t ascOffset1 = ((char*)&(asc._1)) - ((char*)&asc);
3993
3994 size_t desOffset0 = ((char*)&(des._0)) - ((char*)&des);
3995 size_t desOffset1 = ((char*)&(des._1)) - ((char*)&des);
3996
3997 if (offset0 == ascOffset0 && offset1 == ascOffset1) {
3999 } else if (offset0 == desOffset0 && offset1 == desOffset1) {
4001 } else {
4003 }
4004}
4005
4006static std::string AlternateTuple(const char *classname, const cling::LookupHelper& lh, Bool_t silent)
4007{
4009 std::string alternateName = "TEmulatedTuple";
4010 alternateName.append( classname + 5 );
4011
4012 std::string fullname = "ROOT::Internal::" + alternateName;
4013 if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
4014 /*resultType*/nullptr, /* intantiateTemplate= */ false))
4015 return fullname;
4016
4017 {
4018 // Check if we can produce the tuple
4019 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
4020 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
4021 auto deleter = [](TypeInfo_t *type) {
4022 gInterpreter->TypeInfo_Delete(type);
4023 };
4024 std::unique_ptr<TypeInfo_t, decltype(deleter)> type{ gInterpreter->TypeInfo_Factory(), deleter };
4025 while (iter != theEnd) {
4026 gInterpreter->TypeInfo_Init(type.get(), iter->c_str());
4027 if (gInterpreter->TypeInfo_Property(type.get()) & kIsNotReacheable) {
4028 if (!silent)
4029 Error("Load","Could not declare alternate type for %s since %s (or one of its context) is private or protected",
4030 classname, iter->c_str());
4031 return "";
4032 }
4033 ++iter;
4034 }
4035 }
4036
4037 std::string guard_name;
4039 std::ostringstream guard;
4040 guard << "ROOT_INTERNAL_TEmulated_";
4041 guard << guard_name;
4042
4043 std::ostringstream alternateTuple;
4044 alternateTuple << "#ifndef " << guard.str() << "\n";
4045 alternateTuple << "#define " << guard.str() << "\n";
4046 alternateTuple << "namespace ROOT { namespace Internal {\n";
4047 alternateTuple << "template <class... Types> struct TEmulatedTuple;\n";
4048 alternateTuple << "template <> struct " << alternateName << " {\n";
4049
4050 // This could also be a compile time choice ...
4051 switch(IsTupleAscending()) {
4053 unsigned int nMember = 0;
4054 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
4055 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
4056 while (iter != theEnd) {
4057 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4058 ++iter;
4059 ++nMember;
4060 }
4061 break;
4062 }
4064 unsigned int nMember = tupleContent.fElements.size() - 3;
4065 auto iter = tupleContent.fElements.rbegin() + 1; // skip the 'stars'.
4066 auto theEnd = tupleContent.fElements.rend() - 1; // Skip the template name (tuple).
4067 while (iter != theEnd) {
4068 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4069 ++iter;
4070 --nMember;
4071 }
4072 break;
4073 }
4075 Fatal("TCling::SetClassInfo::AlternateTuple",
4076 "Layout of std::tuple on this platform is unexpected.");
4077 break;
4078 }
4079 }
4080
4081 alternateTuple << "};\n";
4082 alternateTuple << "}}\n";
4083 alternateTuple << "#endif\n";
4084 if (!gCling->Declare(alternateTuple.str().c_str()))
4085 {
4086 // Declare is not silent (yet?), so add an explicit error message
4087 // to indicate the consequence of the syntax errors.
4088 Error("Load","Could not declare %s",alternateName.c_str());
4089 return "";
4090 }
4091 alternateName = "ROOT::Internal::" + alternateName;
4092 return alternateName;
4093}
4094
4095////////////////////////////////////////////////////////////////////////////////
4096/// Set pointer to the TClingClassInfo in TClass.
4097/// If 'reload' is true, (attempt to) generate a new ClassInfo even if we
4098/// already have one.
4099
4101{
4102 // We are shutting down, there is no point in reloading, it only triggers
4103 // redundant deserializations.
4104 if (fIsShuttingDown) {
4105 // Remove the decl_id from the DeclIdToTClass map
4106 if (cl->fClassInfo) {
4109 // Test again as another thread may have set fClassInfo to nullptr.
4110 if (TClinginfo) {
4112 }
4113 delete TClinginfo;
4114 cl->fClassInfo = nullptr;
4115 }
4116 return;
4117 }
4118
4120 if (cl->fClassInfo && !reload) {
4121 return;
4122 }
4123 //Remove the decl_id from the DeclIdToTClass map
4125 if (TClinginfo) {
4127 }
4128 delete TClinginfo;
4129 cl->fClassInfo = nullptr;
4130 std::string name(cl->GetName());
4131
4132 auto SetWithoutClassInfoState = [](TClass *cl)
4133 {
4134 if (cl->fState != TClass::kHasTClassInit) {
4135 if (cl->fStreamerInfo->GetEntries() != 0) {
4137 } else {
4139 }
4140 }
4141 };
4142 // Handle the special case of 'tuple' where we ignore the real implementation
4143 // details and just overlay a 'simpler'/'simplistic' version that is easy
4144 // for the I/O to understand and handle.
4145 if (strncmp(cl->GetName(),"tuple<",std::char_traits<char>::length("tuple<"))==0) {
4146 if (!reload)
4147 name = AlternateTuple(cl->GetName(), fInterpreter->getLookupHelper(), silent);
4148 if (reload || name.empty()) {
4149 // We could not generate the alternate
4151 return;
4152 }
4153 }
4154
4156 // FIXME: Rather than adding an option to the TClingClassInfo, we should consider combining code
4157 // that is currently in the caller (like SetUnloaded) that disable AutoLoading and AutoParsing and
4158 // code is in the callee (disabling template instantiation) and end up with a more explicit class:
4159 // TClingClassInfoReadOnly.
4161 if (!info->IsValid()) {
4163 delete info;
4164 return;
4165 }
4166 cl->fClassInfo = (ClassInfo_t*)info; // Note: We are transferring ownership here.
4167 // In case a class contains an external enum, the enum will be seen as a
4168 // class. We must detect this special case and make the class a Zombie.
4169 // Here we assume that a class has at least one method.
4170 // We can NOT call TClass::Property from here, because this method
4171 // assumes that the TClass is well formed to do a lot of information
4172 // caching. The method SetClassInfo (i.e. here) is usually called during
4173 // the building phase of the TClass, hence it is NOT well formed yet.
4175 if (
4176 info->IsValid() &&
4177 !(info->Property() & (kIsClass | kIsStruct | kIsNamespace))
4178 ) {
4180 }
4181 if (!info->IsLoaded()) {
4182 if (info->Property() & (kIsNamespace)) {
4183 // Namespaces can have info but no corresponding CINT dictionary
4184 // because they are auto-created if one of their contained
4185 // classes has a dictionary.
4187 }
4188 // this happens when no dictionary is available
4189 delete info;
4190 cl->fClassInfo = nullptr;
4191 }
4192 if (zombieCandidate && !cl->GetCollectionType()) {
4193 cl->MakeZombie();
4194 }
4195 // If we reach here, the info was valid (See early returns).
4196 if (cl->fState != TClass::kHasTClassInit) {
4197 if (cl->fClassInfo) {
4199 } else {
4200// if (TClassEdit::IsSTLCont(cl->GetName()) {
4201// There will be an emulated collection proxy, is that the same?
4202// cl->fState = TClass::kEmulated;
4203// } else {
4204 if (cl->fStreamerInfo->GetEntries() != 0) {
4206 } else {
4208 }
4209// }
4210 }
4211 }
4212 if (cl->fClassInfo) {
4213 TClass::AddClassToDeclIdMap(((TClingClassInfo*)cl->fClassInfo)->GetDeclId(), cl);
4214 }
4215}
4216
4217////////////////////////////////////////////////////////////////////////////////
4218/// Checks if an entity with the specified name is defined in Cling.
4219/// Returns kUnknown if the entity is not defined.
4220/// Returns kWithClassDefInline if the entity exists and has a ClassDefInline
4221/// Returns kKnown if the entity is defined.
4222///
4223/// By default, structs, namespaces, classes, enums and unions are looked for.
4224/// If the flag isClassOrNamespaceOnly is true, classes, structs and
4225/// namespaces only are considered. I.e. if the name is an enum or a union,
4226/// the returned value is false.
4227///
4228/// In the case where the class is not loaded and belongs to a namespace
4229/// or is nested, looking for the full class name is outputting a lots of
4230/// (expected) error messages. Currently the only way to avoid this is to
4231/// specifically check that each level of nesting is already loaded.
4232/// In case of templates the idea is that everything between the outer
4233/// '<' and '>' has to be skipped, e.g.: `aap<pippo<noot>::klaas>::a_class`
4234
4237{
4239 static const char *anonEnum = "anonymous enum ";
4240 static const int cmplen = strlen(anonEnum);
4241
4242 if (fIsShuttingDown || 0 == strncmp(name, anonEnum, cmplen)) {
4243 return kUnknown;
4244 }
4245
4246 // Do not turn on the AutoLoading if it is globally off.
4248
4249 // Avoid the double search below in case the name is a fundamental type
4250 // or typedef to a fundamental type.
4251 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
4252 TDataType *fundType = (TDataType *)typeTable->THashTable::FindObject( name );
4253
4255 && fundType->GetType() > 0) {
4256 // Fundamental type, no a class.
4257 return kUnknown;
4258 }
4259
4260 // Migrated from within TClass::GetClass
4261 // If we want to know if a class or a namespace with this name exists in the
4262 // interpreter and this is an enum in the type system, before or after loading
4263 // according to the autoload function argument, return kUnknown.
4265 return kUnknown;
4266
4267 const char *classname = name;
4268
4269 // RAII to suspend and restore auto-loading and auto-parsing based on some external conditions.
4271 int fStoreAutoLoad = 0;
4272 int fStoreAutoParse = 0;
4273 bool fSuspendedAutoParse = false;
4274 public:
4276 fStoreAutoLoad = ((TCling*)gCling)->SetClassAutoLoading(autoload);
4277 }
4278
4279 void SuspendAutoParsing() {
4280 fSuspendedAutoParse = true;
4281 fStoreAutoParse = ((TCling*)gCling)->SetSuspendAutoParsing(true);
4282 }
4283
4286 ((TCling*)gCling)->SetSuspendAutoParsing(fStoreAutoParse);
4287 ((TCling*)gCling)->SetClassAutoLoading(fStoreAutoLoad);
4288 }
4289 };
4290
4292 if (TClassEdit::IsStdPair(classname) || TClassEdit::IsStdPairBase(classname))
4293 autoLoadParseRAII.SuspendAutoParsing();
4294
4295 // First we want to check whether the decl exist, but _without_
4296 // generating any template instantiation. However, the lookup
4297 // still will create a forward declaration of the class template instance
4298 // if it exist. In this case, the return value of findScope will still
4299 // be zero but the type will be initialized.
4300 // Note in the corresponding code in ROOT 5, CINT was not instantiating
4301 // this forward declaration.
4302 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4303 const clang::Type *type = nullptr;
4304 const clang::Decl *decl
4305 = lh.findScope(classname,
4306 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4307 : cling::LookupHelper::NoDiagnostics,
4308 &type, /* intantiateTemplate= */ false );
4309 if (!decl) {
4310 std::string buf = TClassEdit::InsertStd(classname);
4311 decl = lh.findScope(buf,
4312 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4313 : cling::LookupHelper::NoDiagnostics,
4314 &type,false);
4315 }
4316
4317 if (type) {
4318 // If decl==0 and the type is valid, then we have a forward declaration.
4319 if (!decl) {
4320 // If we have a forward declaration for a class template instantiation,
4321 // we want to ignore it if it was produced/induced by the call to
4322 // findScope, however we can not distinguish those from the
4323 // instantiation induce by 'soft' use (and thus also induce by the
4324 // same underlying code paths)
4325 // ['soft' use = use not requiring a complete definition]
4326 // So to reduce the amount of disruption to the existing code we
4327 // would just ignore those for STL collection, for which we really
4328 // need to have the compiled collection proxy (and thus the TClass
4329 // bootstrap).
4330 clang::ClassTemplateSpecializationDecl *tmpltDecl =
4331 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
4332 (type->getAsCXXRecordDecl());
4333 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4334 // Since the point of instantiation is invalid, we 'guess' that
4335 // the 'instantiation' of the forwarded type appended in
4336 // findscope.
4338 // For STL Collection we return kUnknown.
4339 return kUnknown;
4340 }
4341 }
4342 }
4344 if (!tci.IsValid()) {
4345 return kUnknown;
4346 }
4349
4350 if (tci.Property() & propertiesMask) {
4351 bool hasClassDefInline = false;
4353 // We do not need to check for ClassDefInline when this is called from
4354 // TClass::Init, we only do it for the call from TClass::GetClass.
4355 auto hasDictionary = tci.GetMethod("Dictionary", "", false, nullptr, ROOT::kExactMatch);
4356 auto implLineFunc = tci.GetMethod("ImplFileLine", "", false, nullptr, ROOT::kExactMatch);
4357
4358 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4359 int lineNumber = 0;
4360 bool success = false;
4361 std::tie(success, lineNumber) =
4364 }
4365 }
4366
4367 // fprintf(stderr,"CheckClassInfo: %s had dict=%d inline=%d\n",name,hasDictionary.IsValid()
4368 // , hasClassDefInline);
4369
4370 // We are now sure that the entry is not in fact an autoload entry.
4372 return kWithClassDefInline;
4373 else
4374 return kKnown;
4375 } else {
4376 // We are now sure that the entry is not in fact an autoload entry.
4377 return kUnknown;
4378 }
4379 }
4380
4381 if (decl)
4382 return kKnown;
4383 else
4384 return kUnknown;
4385
4386 // Setting up iterator part of TClingTypedefInfo is too slow.
4387 // Copy the lookup code instead:
4388 /*
4389 TClingTypedefInfo t(fInterpreter, name);
4390 if (t.IsValid() && !(t.Property() & kIsFundamental)) {
4391 delete[] classname;
4392 return kTRUE;
4393 }
4394 */
4395
4396// const clang::Decl *decl = lh.findScope(name);
4397// if (!decl) {
4398// std::string buf = TClassEdit::InsertStd(name);
4399// decl = lh.findScope(buf);
4400// }
4401
4402// return (decl);
4403}
4404
4405////////////////////////////////////////////////////////////////////////////////
4406/// Return true if there is a class template by the given name ...
4407
4409{
4410 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4411 // Interpreter transaction ahead, needs locking
4413 const clang::Decl *decl
4414 = lh.findClassTemplate(name,
4415 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4416 : cling::LookupHelper::NoDiagnostics);
4417 if (!decl) {
4418 std::string strname = "std::";
4419 strname += name;
4420 decl = lh.findClassTemplate(strname,
4421 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4422 : cling::LookupHelper::NoDiagnostics);
4423 }
4424 return nullptr != decl;
4425}
4426
4427////////////////////////////////////////////////////////////////////////////////
4428/// Create list of pointers to base class(es) for TClass cl.
4429
4431{
4433 if (cl->fBase) {
4434 return;
4435 }
4437 if (!tci) return;
4439 TList *listOfBase = new TList;
4440 while (t.Next()) {
4441 // if name cannot be obtained no use to put in list
4442 if (t.IsValid() && t.Name()) {
4444 listOfBase->Add(new TBaseClass((BaseClassInfo_t *)a, cl));
4445 }
4446 }
4447 // Now that is complete, publish it.
4448 cl->fBase = listOfBase;
4449}
4450
4451////////////////////////////////////////////////////////////////////////////////
4452/// Create list of pointers to enums for TClass cl.
4453
4455{
4457
4458 const Decl * D;
4459 TClass* cl = enumList.GetClass();
4460 if (cl) {
4461 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4462 }
4463 else {
4464 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4465 }
4466 // Iterate on the decl of the class and get the enums.
4467 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4468 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4469 // Collect all contexts of the namespace.
4470 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4471 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4473 declIter != declEnd; ++declIter) {
4474 // Iterate on all decls for each context.
4475 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4476 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4477 if (const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4478 // Get name of the enum type.
4479 std::string buf;
4480 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4481 llvm::raw_string_ostream stream(buf);
4482 // Don't trigger fopen of the source file to count lines:
4483 Policy.AnonymousTagLocations = false;
4484 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
4485 stream.flush();
4486 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
4487 if (!buf.empty()) {
4488 const char* name = buf.c_str();
4489 // Add the enum to the list of loaded enums.
4490 enumList.Get(ED, name);
4491 }
4492 }
4493 }
4494 }
4495 }
4496}
4497
4498////////////////////////////////////////////////////////////////////////////////
4499/// Create list of pointers to function templates for TClass cl.
4500
4502{
4504
4505 const Decl * D;
4507 if (cl) {
4508 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4510 }
4511 else {
4512 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4513 funcTempList = (TListOfFunctionTemplates*)gROOT->GetListOfFunctionTemplates();
4514 }
4515 // Iterate on the decl of the class and get the enums.
4516 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4517 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4518 // Collect all contexts of the namespace.
4519 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4520 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4523 // Iterate on all decls for each context.
4524 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4525 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4526 if (const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4527 funcTempList->Get(FTD);
4528 }
4529 }
4530 }
4531 }
4532}
4533
4534////////////////////////////////////////////////////////////////////////////////
4535/// Get the scopes representing using declarations of namespace
4536
4537std::vector<std::string> TCling::GetUsingNamespaces(ClassInfo_t *cl) const
4538{
4540 return ci->GetUsingNamespaces();
4541}
4542
4543////////////////////////////////////////////////////////////////////////////////
4544/// Create list of pointers to data members for TClass cl.
4545/// This is now a nop. The creation and updating is handled in
4546/// TListOfDataMembers.
4547
4549{
4550}
4551
4552////////////////////////////////////////////////////////////////////////////////
4553/// Create list of pointers to methods for TClass cl.
4554/// This is now a nop. The creation and updating is handled in
4555/// TListOfFunctions.
4556
4558{
4559}
4560
4561////////////////////////////////////////////////////////////////////////////////
4562/// Update the list of pointers to method 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 data members for TClass cl
4572/// This is now a nop. The creation and updating is handled in
4573/// TListOfDataMembers.
4574
4576{
4577}
4578
4579////////////////////////////////////////////////////////////////////////////////
4580/// Create list of pointers to method arguments for TMethod m.
4581
4583{
4585 if (m->fMethodArgs) {
4586 return;
4587 }
4588 TList *arglist = new TList;
4590 while (t.Next()) {
4591 if (t.IsValid()) {
4593 arglist->Add(new TMethodArg((MethodArgInfo_t*)a, m));
4594 }
4595 }
4596 m->fMethodArgs = arglist;
4597}
4598
4599////////////////////////////////////////////////////////////////////////////////
4600/// Return whether we are waiting for more input either because the collected
4601/// input contains unbalanced braces or last seen token was a `\` (backslash-newline)
4602
4604{
4605 return fMetaProcessor->awaitingMoreInput();
4606}
4607
4608////////////////////////////////////////////////////////////////////////////////
4609/// Generate a TClass for the given class.
4610/// Since the caller has already check the ClassInfo, let it give use the
4611/// result (via the value of emulation) rather than recalculate it.
4612
4613TClass *TCling::GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent /* = kFALSE */)
4614{
4615// For now the following line would lead to the (unwanted) instantiation
4616// of class template. This could/would need to be resurrected only if
4617// we re-introduce so sort of automatic instantiation. However this would
4618// have to include carefull look at the template parameter to avoid
4619// creating instance we can not really use (if the parameter are only forward
4620// declaration or do not have all the necessary interfaces).
4621
4622 // TClingClassInfo tci(fInterpreter, classname);
4623 // if (1 || !tci.IsValid()) {
4624
4625 Version_t version = 1;
4626 if (TClassEdit::IsSTLCont(classname)) {
4627 version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4628 }
4630 TClass *cl = new TClass(classname, version, silent);
4631 if (!emulation) {
4632 // Set the class version if the class is versioned.
4633 // Note that we cannot just call CLASS::Class_Version() as we might not have
4634 // an execution engine (when invoked from rootcling).
4635
4636 // Do not call cl->GetClassVersion(), it has side effects!
4638 if (oldvers == version && cl->GetClassInfo()) {
4639 // We have a version and it might need an update.
4641 if (llvm::isa<clang::NamespaceDecl>(cli->GetDecl())) {
4642 // Namespaces don't have class versions.
4643 return cl;
4644 }
4645 TClingMethodInfo mi = cli->GetMethod("Class_Version", "", nullptr /*poffset*/,
4648 if (!mi.IsValid()) {
4649 if (cl->TestBit(TClass::kIsTObject)) {
4650 Error("GenerateTClass",
4651 "Cannot find %s::Class_Version()! Class version might be wrong.",
4652 cl->GetName());
4653 }
4654 return cl;
4655 }
4656 Version_t newvers = ROOT::TMetaUtils::GetClassVersion(llvm::dyn_cast<clang::RecordDecl>(cli->GetDecl()),
4657 *fInterpreter);
4658 if (newvers == -1) {
4659 // Didn't manage to determine the class version from the AST.
4660 // Use runtime instead.
4661 if ((mi.Property() & kIsStatic)
4662 && !fInterpreter->isInSyntaxOnlyMode()) {
4663 // This better be a static function.
4665 callfunc.SetFunc(&mi);
4666 newvers = callfunc.ExecInt(nullptr);
4667 } else {
4668 Error("GenerateTClass",
4669 "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4670 cl->GetName());
4671 }
4672 }
4673 if (newvers != oldvers) {
4674 cl->fClassVersion = newvers;
4675 cl->fStreamerInfo->Expand(newvers + 2 + 10);
4676 }
4677 }
4678 }
4679
4680 return cl;
4681
4682// } else {
4683// return GenerateTClass(&tci,silent);
4684// }
4685}
4686
4687#if 0
4688////////////////////////////////////////////////////////////////////////////////
4689
4691{
4692 includes += info->FileName();
4693
4694 const clang::ClassTemplateSpecializationDecl *templateCl
4695 = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->GetDecl());
4696 if (templateCl) {
4697 for(unsigned int i=0; i < templateCl->getTemplateArgs().size(); ++i) {
4698 const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4699 if (arg.getKind() == clang::TemplateArgument::Type) {
4700 const clang::Type *uType = ROOT::TMetaUtils::GetUnderlyingType( arg.getAsType() );
4701
4702 if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4703 // We really need a header file.
4704 const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4705 if (argdecl) {
4706 includes += ";";
4707 TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4709 } else {
4710 std::string Result;
4711 llvm::raw_string_ostream OS(Result);
4712 arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4713 Warning("TCling::GenerateTClass","Missing header file for %s",OS.str().c_str());
4714 }
4715 }
4716 }
4717 }
4718 }
4719}
4720#endif
4721
4722////////////////////////////////////////////////////////////////////////////////
4723/// Generate a TClass for the given class.
4724
4726{
4728 if (!info || !info->IsValid()) {
4729 Fatal("GenerateTClass","Requires a valid ClassInfo object");
4730 return nullptr;
4731 }
4732 // We are in the case where we have AST nodes for this class.
4733 TClass *cl = nullptr;
4734 std::string classname;
4735 info->FullName(classname,*fNormalizedCtxt); // Could we use Name()?
4736 if (TClassEdit::IsSTLCont(classname)) {
4737#if 0
4738 Info("GenerateTClass","Will (try to) generate the compiled TClass for %s.",classname.c_str());
4739 // We need to build up the list of required headers, by
4740 // looking at each template arguments.
4743
4744 if (0 == GenerateDictionary(classname.c_str(),includes)) {
4745 // 0 means success.
4746 cl = TClass::LoadClass(classnam.c_str(), silent);
4747 if (cl == 0) {
4748 Error("GenerateTClass","Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4749 }
4750 }
4751#endif
4752 if (cl == nullptr) {
4753 int version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4754 cl = new TClass(classinfo, version, nullptr, nullptr, -1, -1, silent);
4755 }
4756 } else {
4757 // For regular class, just create a TClass on the fly ...
4758 // Not quite useful yet, but that what CINT used to do anyway.
4759 cl = new TClass(classinfo, 1, nullptr, nullptr, -1, -1, silent);
4760 }
4761 // Add the new TClass to the map of declid and TClass*.
4762 if (cl) {
4764 }
4765 return cl;
4766}
4767
4768////////////////////////////////////////////////////////////////////////////////
4769/// Generate the dictionary for the C++ classes listed in the first
4770/// argument (in a semi-colon separated list).
4771/// 'includes' contains a semi-colon separated list of file to
4772/// `#include` in the dictionary.
4773/// For example:
4774/// ~~~ {.cpp}
4775/// gInterpreter->GenerateDictionary("vector<vector<float> >;list<vector<float> >","list;vector");
4776/// ~~~
4777/// or
4778/// ~~~ {.cpp}
4779/// gInterpreter->GenerateDictionary("myclass","myclass.h;myhelper.h");
4780/// ~~~
4781
4782Int_t TCling::GenerateDictionary(const char* classes, const char* includes /* = "" */, const char* /* options = 0 */)
4783{
4784 if (classes == nullptr || classes[0] == 0) {
4785 Error("TCling::GenerateDictionary", "Cannot generate dictionary without passing classes.");
4786 return 0;
4787 }
4788 // Split the input list
4789 std::vector<std::string> listClasses;
4790 for (
4791 const char* current = classes, *prev = classes;
4792 *current != 0;
4793 ++current
4794 ) {
4795 if (*current == ';') {
4796 listClasses.push_back(std::string(prev, current - prev));
4797 prev = current + 1;
4798 }
4799 else if (*(current + 1) == 0) {
4800 listClasses.push_back(std::string(prev, current + 1 - prev));
4801 prev = current + 1;
4802 }
4803 }
4804 std::vector<std::string> listIncludes;
4805 if (!includes)
4806 includes = "";
4807 for (
4808 const char* current = includes, *prev = includes;
4809 *current != 0;
4810 ++current
4811 ) {
4812 if (*current == ';') {
4813 listIncludes.push_back(std::string(prev, current - prev));
4814 prev = current + 1;
4815 }
4816 else if (*(current + 1) == 0) {
4817 listIncludes.push_back(std::string(prev, current + 1 - prev));
4818 prev = current + 1;
4819 }
4820 }
4821 // Generate the temporary dictionary file
4823 std::vector<std::string>(), std::vector<std::string>());
4824}
4825
4826////////////////////////////////////////////////////////////////////////////////
4827/// Return pointer to cling Decl of global/static variable that is located
4828/// at the address given by addr.
4829
4831{
4833 DeclId_t d;
4835
4836 // Could trigger deserialization of decls.
4837 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4838
4839 if (cl) {
4840 d = cl->GetDataMember(name);
4841 // We check if the decl of the data member has an annotation which indicates
4842 // an ioname.
4843 // In case this is true, if the name requested is not the ioname, we
4844 // return 0, as if the member did not exist. In some sense we override
4845 // the information in the TClassInfo instance, isolating the typesystem in
4846 // TClass from the one in the AST.
4847 if (const ValueDecl* decl = (const ValueDecl*) d){
4848 std::string ioName;
4850 if (hasIoName && ioName != name) return nullptr;
4851 }
4852 return d;
4853 }
4854 // We are looking up for something on the TU scope.
4855 // FIXME: We do not want to go through TClingClassInfo(fInterpreter) because of redundant deserializations. That
4856 // interface will actually construct iterators and walk over the decls on the global scope. In would return the first
4857 // occurrence of a decl with the looked up name. However, that's not what C++ lookup would do: if we want to switch
4858 // to a more complete C++ lookup interface we need sift through the found names and pick up the declarations which
4859 // are only fulfilling ROOT's understanding for a Data Member.
4860 // FIXME: We should probably deprecate the TClingClassInfo(fInterpreter) interface and replace it withe something
4861 // similar as below.
4862 using namespace clang;
4863 Sema& SemaR = fInterpreter->getSema();
4864 DeclarationName DName = &SemaR.Context.Idents.get(name);
4865
4866 LookupResult R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4867 Sema::ForExternalRedeclaration);
4868
4869 cling::utils::Lookup::Named(&SemaR, R);
4870
4871 LookupResult::Filter F = R.makeFilter();
4872 // Filter the data-member looking decls.
4873 while (F.hasNext()) {
4874 NamedDecl *D = F.next();
4877 continue;
4878 F.erase();
4879 }
4880 F.done();
4881
4882 if (R.isSingleResult())
4883 return R.getFoundDecl();
4884 return nullptr;
4885}
4886
4887////////////////////////////////////////////////////////////////////////////////
4888/// Return pointer to cling Decl of global/static variable that is located
4889/// at the address given by addr.
4890
4892{
4894
4895 const clang::Decl* possibleEnum = nullptr;
4896 // FInd the context of the decl.
4897 if (cl) {
4899 if (cci) {
4900 const clang::DeclContext* dc = nullptr;
4901 if (const clang::Decl* D = cci->GetDecl()) {
4902 if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
4904 }
4905 }
4906 if (dc) {
4907 // If it is a data member enum.
4908 // Could trigger deserialization of decls.
4909 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4910 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name, dc);
4911 } else {
4912 Error("TCling::GetEnum", "DeclContext not found for %s .\n", name);
4913 }
4914 }
4915 } else {
4916 // If it is a global enum.
4917 // Could trigger deserialization of decls.
4918 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4919 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name);
4920 }
4921 if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
4923 return possibleEnum;
4924 }
4925 return nullptr;
4926}
4927
4928////////////////////////////////////////////////////////////////////////////////
4929/// Return pointer to cling DeclId for a global value
4930
4931TInterpreter::DeclId_t TCling::GetDeclId( const llvm::GlobalValue *gv ) const
4932{
4933 if (!gv) return nullptr;
4934
4935 llvm::StringRef mangled_name = gv->getName();
4936
4937 int err = 0;
4938 char* demangled_name_c = TClassEdit::DemangleName(mangled_name.str().c_str(), err);
4939 if (err) {
4940 if (err == -2) {
4941 // It might simply be an unmangled global name.
4942 DeclId_t d;
4944 d = gcl.GetDataMember(mangled_name.str().c_str());
4945 return d;
4946 }
4947 return nullptr;
4948 }
4949
4950 std::string scopename(demangled_name_c);
4952
4953 //
4954 // Separate out the class or namespace part of the
4955 // function name.
4956 //
4957 std::string dataname;
4958
4959 if (!strncmp(scopename.c_str(), "typeinfo for ", sizeof("typeinfo for ")-1)) {
4960 scopename.erase(0, sizeof("typeinfo for ")-1);
4961 } else if (!strncmp(scopename.c_str(), "vtable for ", sizeof("vtable for ")-1)) {
4962 scopename.erase(0, sizeof("vtable for ")-1);
4963 } else {
4964 // See if it is a function
4965 std::string::size_type pos = scopename.rfind('(');
4966 if (pos != std::string::npos) {
4967 return nullptr;
4968 }
4969 // Separate the scope and member name
4970 pos = scopename.rfind(':');
4971 if (pos != std::string::npos) {
4972 if ((pos != 0) && (scopename[pos-1] == ':')) {
4973 dataname = scopename.substr(pos+1);
4974 scopename.erase(pos-1);
4975 }
4976 } else {
4977 scopename.clear();
4979 }
4980 }
4981 //fprintf(stderr, "name: '%s'\n", name.c_str());
4982 // Now we have the class or namespace name, so do the lookup.
4983
4984
4985 DeclId_t d;
4986 if (scopename.size()) {
4988 d = cl.GetDataMember(dataname.c_str());
4989 }
4990 else {
4992 d = gcl.GetDataMember(dataname.c_str());
4993 }
4994 return d;
4995}
4996
4997////////////////////////////////////////////////////////////////////////////////
4998/// NOT IMPLEMENTED.
4999
5001{
5002 Error("GetDataMemberWithValue()", "not implemented");
5003 return nullptr;
5004}
5005
5006////////////////////////////////////////////////////////////////////////////////
5007/// Return pointer to cling DeclId for a data member with a given name.
5008
5010{
5011 // NOT IMPLEMENTED.
5012 Error("GetDataMemberAtAddr()", "not implemented");
5013 return nullptr;
5014}
5015
5016////////////////////////////////////////////////////////////////////////////////
5017/// Return the cling mangled name for a method of a class with parameters
5018/// params (params is a string of actual arguments, not formal ones). If the
5019/// class is 0 the global function list will be searched.
5020
5022 const char* params, Bool_t objectIsConst /* = kFALSE */)
5023{
5026 if (cl) {
5029 &offset);
5030 }
5031 else {
5034 func.SetFunc(&gcl, method, params, &offset);
5035 }
5037 if (!mi) return "";
5038 TString mangled_name( mi->GetMangledName() );
5039 delete mi;
5040 return mangled_name;
5041}
5042
5043////////////////////////////////////////////////////////////////////////////////
5044/// Return the cling mangled name for a method of a class with a certain
5045/// prototype, i.e. "char*,int,float". If the class is 0 the global function
5046/// list will be searched.
5047
5049 const char* proto, Bool_t objectIsConst /* = kFALSE */,
5050 EFunctionMatchMode mode /* = kConversionMatch */)
5051{
5053 if (cl) {
5054 return ((TClingClassInfo*)cl->GetClassInfo())->
5055 GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetMangledName();
5056 }
5058 return gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetMangledName();
5059}
5060
5061////////////////////////////////////////////////////////////////////////////////
5062/// Return pointer to cling interface function for a method of a class with
5063/// parameters params (params is a string of actual arguments, not formal
5064/// ones). If the class is 0 the global function list will be searched.
5065
5067 const char* params, Bool_t objectIsConst /* = kFALSE */)
5068{
5071 if (cl) {
5074 &offset);
5075 }
5076 else {
5079 func.SetFunc(&gcl, method, params, &offset);
5080 }
5081 return (void*) func.InterfaceMethod();
5082}
5083
5084////////////////////////////////////////////////////////////////////////////////
5085/// Return pointer to cling interface function for a method of a class with
5086/// a certain name.
5087
5089{
5091 DeclId_t f;
5093 if (cl) {
5094 f = cl->GetMethod(method).GetDeclId();
5095 }
5096 else {
5098 f = gcl.GetMethod(method).GetDeclId();
5099 }
5100 return f;
5101
5102}
5103
5104////////////////////////////////////////////////////////////////////////////////
5105/// Insert overloads of name in cl to res.
5106
5108 std::vector<DeclId_t>& res) const
5109{
5110 clang::Sema& S = fInterpreter->getSema();
5111 clang::ASTContext& Ctx = S.Context;
5112 const clang::Decl* CtxDecl
5113 = cl ? (const clang::Decl*)((TClingClassInfo*)cl)->GetDeclId():
5114 Ctx.getTranslationUnitDecl();
5115 auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
5116 const clang::DeclContext* DeclCtx = RecDecl;
5117
5118 if (!DeclCtx)
5120 if (!DeclCtx) return;
5121
5122 clang::DeclarationName DName;
5123 // The DeclarationName is funcname, unless it's a ctor or dtor.
5124 // FIXME: or operator or conversion! See enum clang::DeclarationName::NameKind.
5125
5126 if (RecDecl) {
5127 if (RecDecl->getNameAsString() == funcname) {
5128 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5129 DName = Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalType(QT));
5130 } else if (funcname[0] == '~' && RecDecl->getNameAsString() == funcname + 1) {
5131 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5132 DName = Ctx.DeclarationNames.getCXXDestructorName(Ctx.getCanonicalType(QT));
5133 } else {
5134 DName = &Ctx.Idents.get(funcname);
5135 }
5136 } else {
5137 DName = &Ctx.Idents.get(funcname);
5138 }
5139
5140 // NotForRedeclaration: we want to find names in inline namespaces etc.
5141 clang::LookupResult R(S, DName, clang::SourceLocation(),
5142 Sema::LookupOrdinaryName, clang::Sema::NotForRedeclaration);
5143 R.suppressDiagnostics(); // else lookup with NotForRedeclaration will check access etc
5144 S.LookupQualifiedName(R, const_cast<DeclContext*>(DeclCtx));
5145 if (R.empty()) return;
5146 R.resolveKind();
5147 res.reserve(res.size() + (R.end() - R.begin()));
5148 for (clang::LookupResult::iterator IR = R.begin(), ER = R.end();
5149 IR != ER; ++IR) {
5150 if (const clang::FunctionDecl* FD
5151 = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
5152 if (!FD->getDescribedFunctionTemplate()) {
5153 res.push_back(FD);
5154 }
5155 } else if (const auto *USD = llvm::dyn_cast<const clang::UsingShadowDecl>(*IR)) {
5156 // FIXME: multi-level using
5157 if (llvm::isa<clang::FunctionDecl>(USD->getTargetDecl())) {
5158 res.push_back(USD);
5159 }
5160 }
5161 }
5162}
5163
5164////////////////////////////////////////////////////////////////////////////////
5165/// Return pointer to cling interface function for a method of a class with
5166/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5167/// function list will be searched.
5168
5170 const char* proto,
5171 Bool_t objectIsConst /* = kFALSE */,
5172 EFunctionMatchMode mode /* = kConversionMatch */)
5173{
5175 void* f;
5176 if (cl) {
5177 f = ((TClingClassInfo*)cl->GetClassInfo())->
5178 GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).InterfaceMethod();
5179 }
5180 else {
5182 f = gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).InterfaceMethod();
5183 }
5184 return f;
5185}
5186
5187////////////////////////////////////////////////////////////////////////////////
5188/// Return pointer to cling DeclId for a method of a class with
5189/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5190/// function list will be searched.
5191
5193 const char* params,
5194 Bool_t objectIsConst /* = kFALSE */)
5195{
5197 DeclId_t f;
5199 if (cl) {
5200 f = cl->GetMethodWithArgs(method, params, objectIsConst, nullptr /*poffset*/).GetDeclId();
5201 }
5202 else {
5204 f = gcl.GetMethod(method, params, objectIsConst, nullptr /*poffset*/).GetDeclId();
5205 }
5206 return f;
5207}
5208
5209////////////////////////////////////////////////////////////////////////////////
5210/// Return pointer to cling interface function for a method of a class with
5211/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5212/// function list will be searched.
5213
5215 const char* proto,
5216 Bool_t objectIsConst /* = kFALSE */,
5217 EFunctionMatchMode mode /* = kConversionMatch */)
5218{
5220 DeclId_t f;
5222 if (cl) {
5223 f = cl->GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetDeclId();
5224 }
5225 else {
5227 f = gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetDeclId();
5228 }
5229 return f;
5230}
5231
5232////////////////////////////////////////////////////////////////////////////////
5233/// Return pointer to cling interface function for a method of a class with
5234/// a certain name.
5235
5237{
5239 DeclId_t f;
5241 if (cl) {
5242 f = cl->GetFunctionTemplate(name);
5243 }
5244 else {
5246 f = gcl.GetFunctionTemplate(name);
5247 }
5248 return f;
5249
5250}
5251
5252////////////////////////////////////////////////////////////////////////////////
5253/// The 'name' is known to the interpreter, this function returns
5254/// the internal version of this name (usually just resolving typedefs)
5255/// This is used in particular to synchronize between the name used
5256/// by rootcling and by the run-time environment (TClass)
5257/// Return 0 if the name is not known.
5258
5259void TCling::GetInterpreterTypeName(const char* name, std::string &output, Bool_t full)
5260{
5261 output.clear();
5262
5264
5266 if (!cl.IsValid()) {
5267 return ;
5268 }
5269 if (full) {
5271 return;
5272 }
5273 // Well well well, for backward compatibility we need to act a bit too
5274 // much like CINT.
5277
5278 return;
5279}
5280
5281////////////////////////////////////////////////////////////////////////////////
5282/// Execute a global function with arguments params.
5283///
5284/// FIXME: The cint-based version of this code does not check if the
5285/// SetFunc() call works, and does not do any real checking
5286/// for errors from the Exec() call. It did fetch the most
5287/// recent cint security error and return that in error, but
5288/// this does not really translate well to cling/clang. We
5289/// should enhance these interfaces so that we can report
5290/// compilation and runtime errors properly.
5291
5292void TCling::Execute(const char* function, const char* params, int* error)
5293{
5295 if (error) {
5296 *error = TInterpreter::kNoError;
5297 }
5299 Longptr_t offset = 0L;
5301 func.SetFunc(&cl, function, params, &offset);
5302 func.Exec(nullptr);
5303}
5304
5305////////////////////////////////////////////////////////////////////////////////
5306/// Execute a method from class cl with arguments params.
5307///
5308/// FIXME: The cint-based version of this code does not check if the
5309/// SetFunc() call works, and does not do any real checking
5310/// for errors from the Exec() call. It did fetch the most
5311/// recent cint security error and return that in error, but
5312/// this does not really translate well to cling/clang. We
5313/// should enhance these interfaces so that we can report
5314/// compilation and runtime errors properly.
5315
5316void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5317 const char* params, Bool_t objectIsConst, int* error)
5318{
5320 if (error) {
5321 *error = TInterpreter::kNoError;
5322 }
5323 // If the actual class of this object inherits 2nd (or more) from TObject,
5324 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5325 // hence gInterpreter->Execute will improperly correct the offset.
5326 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5327 Longptr_t offset = 0L;
5330 void* address = (void*)((Longptr_t)addr + offset);
5331 func.Exec(address);
5332}
5333
5334////////////////////////////////////////////////////////////////////////////////
5335
5336void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5337 const char* params, int* error)
5338{
5339 Execute(obj,cl,method,params,false,error);
5340}
5341
5342////////////////////////////////////////////////////////////////////////////////
5343/// Execute a method from class cl with the arguments in array params
5344/// (params[0] ... params[n] = array of TObjString parameters).
5345/// Convert the TObjArray array of TObjString parameters to a character
5346/// string of comma separated parameters.
5347/// The parameters of type 'char' are enclosed in double quotes and all
5348/// internal quotes are escaped.
5349
5351 TObjArray* params, int* error)
5352{
5353 if (!method) {
5354 Error("Execute", "No method was defined");
5355 return;
5356 }
5357 TList* argList = method->GetListOfMethodArgs();
5358 // Check number of actual parameters against of expected formal ones
5359
5360 Int_t nparms = argList->LastIndex() + 1;
5361 Int_t argc = params ? params->GetEntries() : 0;
5362
5363 if (argc > nparms) {
5364 Error("Execute","Too many parameters to call %s, got %d but expected at most %d.",method->GetName(),argc,nparms);
5365 return;
5366 }
5367 if (nparms != argc) {
5368 // Let's see if the 'missing' argument are all defaulted.
5369 // if nparms==0 then either we stopped earlier either argc is also zero and we can't reach here.
5370 assert(nparms > 0);
5371
5372 TMethodArg *arg = (TMethodArg *) argList->At( 0 );
5373 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5374 // There is a default value for the first missing
5375 // argument, so we are fine.
5376 } else {
5377 Int_t firstDefault = -1;
5378 for (Int_t i = 0; i < nparms; i ++) {
5379 arg = (TMethodArg *) argList->At( i );
5380 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5381 firstDefault = i;
5382 break;
5383 }
5384 }
5385 if (firstDefault >= 0) {
5386 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);
5387 } else {
5388 Error("Execute","Too few arguments to call %s, got only %d but expected %d.",method->GetName(),argc,nparms);
5389 }
5390 return;
5391 }
5392 }
5393
5394 const char* listpar = "";
5395 TString complete(10);
5396 if (params) {
5397 // Create a character string of parameters from TObjArray
5398 TIter next(params);
5399 for (Int_t i = 0; i < argc; i ++) {
5400 TMethodArg* arg = (TMethodArg*) argList->At(i);
5402 TObjString* nxtpar = (TObjString*) next();
5403 if (i) {
5404 complete += ',';
5405 }
5406 if (strstr(type.TrueName(*fNormalizedCtxt), "char")) {
5407 TString chpar('\"');
5408 chpar += (nxtpar->String()).ReplaceAll("\"", "\\\"");
5409 // At this point we have to check if string contains \\"
5410 // and apply some more sophisticated parser. Not implemented yet!
5411 complete += chpar;
5412 complete += '\"';
5413 }
5414 else {
5415 complete += nxtpar->String();
5416 }
5417 }
5418 listpar = complete.Data();
5419 }
5420
5421 // And now execute it.
5423 if (error) {
5424 *error = TInterpreter::kNoError;
5425 }
5426 // If the actual class of this object inherits 2nd (or more) from TObject,
5427 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5428 // hence gInterpreter->Execute will improperly correct the offset.
5429 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5432 func.Init(*minfo);
5433 func.SetArgs(listpar);
5434 // Now calculate the 'this' pointer offset for the method
5435 // when starting from the class described by cl.
5436 const CXXMethodDecl * mdecl = dyn_cast<CXXMethodDecl>(minfo->GetTargetFunctionDecl());
5437 Longptr_t offset = ((TClingClassInfo*)cl->GetClassInfo())->GetOffset(mdecl);
5438 void* address = (void*)((Longptr_t)addr + offset);
5439 func.Exec(address);
5440}
5441
5442////////////////////////////////////////////////////////////////////////////////
5443
5445 const void* args[] /*=0*/,
5446 int nargs /*=0*/,
5447 void* ret/*= 0*/) const
5448{
5449 if (!method) {
5450 Error("ExecuteWithArgsAndReturn", "No method was defined");
5451 return;
5452 }
5453
5455 TClingCallFunc func(*minfo);
5456 func.ExecWithArgsAndReturn(address, args, nargs, ret);
5457}
5458
5459////////////////////////////////////////////////////////////////////////////////
5460/// Execute a cling macro.
5461
5463{
5465 fCurExecutingMacros.push_back(filename);
5467 fCurExecutingMacros.pop_back();
5468 return result;
5469}
5470
5471////////////////////////////////////////////////////////////////////////////////
5472/// Return the file name of the current un-included interpreted file.
5473/// See the documentation for GetCurrentMacroName().
5474
5476{
5477 Warning("GetTopLevelMacroName", "Must change return type!");
5478 return fCurExecutingMacros.back();
5479}
5480
5481////////////////////////////////////////////////////////////////////////////////
5482/// Return the file name of the currently interpreted file,
5483/// included or not. Example to illustrate the difference between
5484/// GetCurrentMacroName() and GetTopLevelMacroName():
5485/// ~~~ {.cpp}
5486/// void inclfile() {
5487/// std::cout << "In inclfile.C" << std::endl;
5488/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5489/// TCling::GetCurrentMacroName() << std::endl;
5490/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5491/// TCling::GetTopLevelMacroName() << std::endl;
5492/// }
5493/// ~~~
5494/// ~~~ {.cpp}
5495/// void mymacro() {
5496/// std::cout << "In mymacro.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/// std::cout << " Now calling inclfile..." << std::endl;
5502/// gInterpreter->ProcessLine(".x inclfile.C");
5503/// }
5504/// ~~~
5505/// Running mymacro.C will print:
5506///
5507/// ~~~ {.cpp}
5508/// root [0] .x mymacro.C
5509/// ~~~
5510/// In mymacro.C
5511/// ~~~ {.cpp}
5512/// TCling::GetCurrentMacroName() returns ./mymacro.C
5513/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5514/// ~~~
5515/// Now calling inclfile...
5516/// In inclfile.h
5517/// ~~~ {.cpp}
5518/// TCling::GetCurrentMacroName() returns inclfile.C
5519/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5520/// ~~~
5521
5523{
5524#if defined(R__MUST_REVISIT)
5525#if R__MUST_REVISIT(6,0)
5526 Warning("GetCurrentMacroName", "Must change return type!");
5527#endif
5528#endif
5529 return fCurExecutingMacros.back();
5530}
5531
5532////////////////////////////////////////////////////////////////////////////////
5533/// Return the absolute type of typeDesc.
5534/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
5535/// You need to use the result immediately before it is being overwritten.
5536
5537const char* TCling::TypeName(const char* typeDesc)
5538{
5539 TTHREAD_TLS_DECL(std::string,t);
5540
5541 if (!strstr(typeDesc, "(*)(")) {
5542 const char *s = strchr(typeDesc, ' ');
5543 const char *template_start = strchr(typeDesc, '<');
5544 if (!strcmp(typeDesc, "long long")) {
5545 t = typeDesc;
5546 }
5547 else if (!strncmp(typeDesc, "unsigned ", s + 1 - typeDesc)) {
5548 t = typeDesc;
5549 }
5550 // s is the position of the second 'word' (if any)
5551 // except in the case of templates where there will be a space
5552 // just before any closing '>': eg.
5553 // TObj<std::vector<UShort_t,__malloc_alloc_template<0> > >*
5554 else if (s && (template_start == nullptr || (s < template_start))) {
5555 t = s + 1;
5556 }
5557 else {
5558 t = typeDesc;
5559 }
5560 }
5561 else {
5562 t = typeDesc;
5563 }
5564 auto l = t.length();
5565 while (l > 0 && (t[l - 1] == '*' || t[l - 1] == '&'))
5566 --l;
5567 t.resize(l);
5568 return t.c_str(); // NOLINT
5569}
5570
5571static bool requiresRootMap(const char* rootmapfile)
5572{
5574
5575 llvm::StringRef libName = llvm::sys::path::filename(rootmapfile);
5576 libName.consume_back(".rootmap");
5577
5578 return !gInterpreter->HasPCMForLibrary(libName.str().c_str());
5579}
5580
5581////////////////////////////////////////////////////////////////////////////////
5582/// Read and parse a rootmapfile in its new format, and return 0 in case of
5583/// success, -1 if the file has already been read, and -3 in case its format
5584/// is the old one (e.g. containing "Library.ClassName"), -4 in case of syntax
5585/// error.
5586
5588{
5589 if (!(rootmapfile && *rootmapfile))
5590 return 0;
5591
5593 return 0; // success
5594
5595 // For "class ", "namespace ", "typedef ", "header ", "enum ", "var " respectively
5596 const std::map<char, unsigned int> keyLenMap = {{'c',6},{'n',10},{'t',8},{'h',7},{'e',5},{'v',4}};
5597
5599#ifdef _MSC_VER
5600 std::replace(rootmapfileNoBackslash.begin(), rootmapfileNoBackslash.end(), '\\', '/');
5601#endif
5602 // Add content of a specific rootmap file
5604 return -1;
5605
5606 // Line 1 is `{ decls }`
5607 std::string lineDirective = std::string("\n#line 2 \"Forward declarations from ") + rootmapfileNoBackslash + "\"\n";
5608
5609 std::ifstream file(rootmapfileNoBackslash);
5610 std::string line;
5611 line.reserve(200);
5612 std::string lib_name;
5613 line.reserve(100);
5614 bool newFormat = false;
5615 while (getline(file, line, '\n')) {
5616 if (!newFormat && (line.compare(0, 8, "Library.") == 0 || line.compare(0, 8, "Declare.") == 0)) {
5617 file.close();
5618 return -3; // old format
5619 }
5620 newFormat = true;
5621
5622 if (line.compare(0, 9, "{ decls }") == 0) {
5623 // forward declarations
5624
5625 while (getline(file, line, '\n')) {
5626 if (line[0] == '[')
5627 break;
5628 if (!uniqueString) {
5629 Error("ReadRootmapFile", "Cannot handle \"{ decls }\" sections in custom rootmap file %s",
5630 rootmapfileNoBackslash.c_str());
5631 return -4;
5632 }
5633 if (!lineDirective.empty())
5634 uniqueString->Append(lineDirective);
5635 uniqueString->Append(line + '\n');
5636 }
5637 }
5638 const char firstChar = line[0];
5639 if (firstChar == '[') {
5640 // new section (library)
5641 auto brpos = line.find(']');
5642 if (brpos == string::npos)
5643 continue;
5644 lib_name = line.substr(1, brpos - 1);
5645 // Remove spaces at the beginning and at the end of the library name
5646 lib_name.erase(lib_name.find_last_not_of(' ') + 1);
5647 lib_name.erase(0, lib_name.find_first_not_of(' '));
5648 if (gDebug > 3) {
5649 TString lib_nameTstr(lib_name.c_str());
5650 TObjArray *tokens = lib_nameTstr.Tokenize(" ");
5651 const char *lib = ((TObjString *)tokens->At(0))->GetName();
5652 const char *wlib = gSystem->DynamicPathName(lib, kTRUE);
5653 if (wlib) {
5654 Info("ReadRootmapFile", "%s: New section for %s", rootmapfile, lib_nameTstr.Data());
5655 } else {
5656 Info("ReadRootmapFile", "%s: Section for %s (library does not exist)", rootmapfile, lib_nameTstr.Data());
5657 }
5658 delete[] wlib;
5659 delete tokens;
5660 }
5661 } else {
5662 auto keyLenIt = keyLenMap.find(firstChar);
5663 if (keyLenIt == keyLenMap.end())
5664 continue;
5665 unsigned int keyLen = keyLenIt->second;
5666 // Do not make a copy, just start after the key
5667 const char *keyname = line.c_str() + keyLen;
5668 if (gDebug > 6)
5669 Info("ReadRootmapFile", "%s: class %s in %s", rootmapfile, keyname, lib_name.c_str());
5671 if (isThere) {
5672 if (lib_name != isThere->GetValue()) { // the same key for two different libs
5673 if (firstChar == 'n') {
5674 if (gDebug > 3)
5675 Info("ReadRootmapFile",
5676 "While processing %s, namespace %s was found to be associated to %s although it is already "
5677 "associated to %s",
5678 rootmapfile, keyname, lib_name.c_str(), isThere->GetValue());
5679 } else if (firstChar == 'h') { // it is a header: add the libname to the list of libs to be loaded.
5680 lib_name += " ";
5681 lib_name += isThere->GetValue();
5682 fMapfile->SetValue(keyname, lib_name.c_str());
5683 } else if (!TClassEdit::IsSTLCont(keyname)) {
5684 Warning("ReadRootmapFile",
5685 "While processing %s, %s %s was found to be associated to %s although it is already "
5686 "associated to %s",
5687 rootmapfile, line.substr(0, keyLen - 1).c_str(), keyname, lib_name.c_str(),
5688 isThere->GetValue());
5689 }
5690 } else { // the same key for the same lib
5691 if (gDebug > 3)
5692 Info("ReadRootmapFile", "While processing %s, key %s was found to be already defined for %s",
5693 rootmapfile, keyname, lib_name.c_str());
5694 }
5695 } else {
5696 fMapfile->SetValue(keyname, lib_name.c_str());
5697 }
5698 }
5699 }
5700 file.close();
5701 return 0;
5702}
5703
5704////////////////////////////////////////////////////////////////////////////////
5705/// Create a resource table and read the (possibly) three resource files,
5706/// i.e. `$ROOTSYS/etc/system<name>` (or `ROOTETCDIR/system<name>`), `$HOME/<name>`
5707/// and `$PWD/<name>`. ROOT always reads ".rootrc" (in TROOT::InitSystem()). You
5708/// can read additional user defined resource files by creating additional TEnv
5709/// objects. By setting the shell variable ROOTENV_NO_HOME=1 the reading of
5710/// the `$HOME/<name>` resource file will be skipped. This might be useful in
5711/// case the home directory resides on an automounted remote file system
5712/// and one wants to avoid the file system from being mounted.
5713
5715{
5716 assert(requiresRootMap(name) && "We have a module!");
5717
5718 if (!requiresRootMap(name))
5719 return;
5720
5722
5724
5725 TString sname = "system";
5726 sname += name;
5728
5730 if (ret == -3) // old format
5732 delete [] s;
5733 if (!gSystem->Getenv("ROOTENV_NO_HOME")) {
5735 ret = ReadRootmapFile(s);
5736 if (ret == -3) // old format
5738 delete [] s;
5741 if (ret == -3) // old format
5743 }
5744 } else {
5746 if (ret == -3) // old format
5748 }
5750}
5751
5752
5753namespace {
5754 using namespace clang;
5755
5756 class ExtVisibleStorageAdder: public RecursiveASTVisitor<ExtVisibleStorageAdder>{
5757 // This class is to be considered an helper for AutoLoading.
5758 // It is a recursive visitor is used to inspect namespaces and specializations
5759 // coming from forward declarations in rootmaps and to set the external visible
5760 // storage flag for them.
5761 public:
5762 ExtVisibleStorageAdder(std::unordered_set<const NamespaceDecl*>& nsSet): fNSSet(nsSet) {};
5763 bool VisitNamespaceDecl(NamespaceDecl* nsDecl) {
5764 // We want to enable the external lookup for this namespace
5765 // because it may shadow the lookup of other names contained
5766 // in that namespace
5767
5768 nsDecl->setHasExternalVisibleStorage();
5769 fNSSet.insert(nsDecl);
5770 return true;
5771 }
5773 // We want to enable the external lookup for this specialization
5774 // because we can provide a definition for it!
5775 if (specDecl->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
5776 //SpecSet.insert(specDecl);
5777 specDecl->setHasExternalLexicalStorage();
5778
5779 // No need to recurse. On the contrary, recursing is actively harmful:
5780 // NOTE: must not recurse to prevent this visitor from triggering loading from
5781 // the external AST source (i.e. autoloading). This would be triggered right here,
5782 // before autoloading is even set up, as rootmap file parsing happens before that.
5783 // Even if autoloading is off and has no effect, triggering loading from external
5784 // AST source resets the flag setHasExternalLexicalStorage(), hiding this specialization
5785 // from subsequent autoloads!
5786 return false;
5787 }
5788 private:
5789 std::unordered_set<const NamespaceDecl*>& fNSSet;
5790 };
5791}
5792
5793////////////////////////////////////////////////////////////////////////////////
5794/// Load map between class and library. If rootmapfile is specified a
5795/// specific rootmap file can be added (typically used by ACLiC).
5796/// In case of error -1 is returned, 0 otherwise.
5797/// The interpreter uses this information to automatically load the shared
5798/// library for a class (autoload mechanism), see the AutoLoad() methods below.
5799
5801{
5803 return 0;
5804
5806
5807 // open the [system].rootmap files
5808 if (!fMapfile) {
5809 fMapfile = new TEnv();
5813 InitRootmapFile(".rootmap");
5814 }
5815
5816 // Prepare a list of all forward declarations for cling
5817 // For some experiments it is easily as big as 500k characters. To be on the
5818 // safe side, we go for 1M.
5819 TUniqueString uniqueString(1048576);
5820
5821 // Load all rootmap files in the dynamic load path ((DY)LD_LIBRARY_PATH, etc.).
5822 // A rootmap file must end with the string ".rootmap".
5824 if (ldpath != fRootmapLoadPath) {
5826#ifdef WIN32
5827 TObjArray* paths = ldpath.Tokenize(";");
5828#else
5829 TObjArray* paths = ldpath.Tokenize(":");
5830#endif
5831 TString d;
5832 for (Int_t i = 0; i < paths->GetEntriesFast(); i++) {
5833 d = ((TObjString *)paths->At(i))->GetString();
5834 // check if directory already scanned
5835 Int_t skip = 0;
5836 for (Int_t j = 0; j < i; j++) {
5837 TString pd = ((TObjString *)paths->At(j))->GetString();
5838 if (pd == d) {
5839 skip++;
5840 break;
5841 }
5842 }
5843 if (!skip) {
5844 void* dirp = gSystem->OpenDirectory(d);
5845 if (dirp) {
5846 if (gDebug > 3) {
5847 Info("LoadLibraryMap", "%s", d.Data());
5848 }
5849 const char* f1;
5850 while ((f1 = gSystem->GetDirEntry(dirp))) {
5851 TString f = f1;
5852 if (f.EndsWith(".rootmap")) {
5853 TString p;
5854 p = d + "/" + f;
5856 if (!fRootmapFiles->FindObject(f) && f != ".rootmap") {
5857 if (gDebug > 4) {
5858 Info("LoadLibraryMap", " rootmap file: %s", p.Data());
5859 }
5861
5862 if (ret == 0)
5863 fRootmapFiles->Add(new TNamed(gSystem->BaseName(f), p.Data()));
5864 if (ret == -3) {
5865 // old format
5867 fRootmapFiles->Add(new TNamed(f, p));
5868 }
5869 }
5870 // else {
5871 // fprintf(stderr,"Reject %s because %s is already there\n",p.Data(),f.Data());
5872 // fRootmapFiles->FindObject(f)->ls();
5873 // }
5874 }
5875 }
5876 if (f.BeginsWith("rootmap")) {
5877 TString p;
5878 p = d + "/" + f;
5879 FileStat_t stat;
5880 if (gSystem->GetPathInfo(p, stat) == 0 && R_ISREG(stat.fMode)) {
5881 Warning("LoadLibraryMap", "please rename %s to end with \".rootmap\"", p.Data());
5882 }
5883 }
5884 }
5885 }
5887 }
5888 }
5889 delete paths;
5890 if (fMapfile->GetTable() && !fMapfile->GetTable()->GetEntries()) {
5891 return -1;
5892 }
5893 }
5894 if (rootmapfile && *rootmapfile) {
5896 if (res == 0) {
5897 //TString p = gSystem->ConcatFileName(gSystem->pwd(), rootmapfile);
5898 //fRootmapFiles->Add(new TNamed(gSystem->BaseName(rootmapfile), p.Data()));
5900 }
5901 else if (res == -3) {
5902 // old format
5907 }
5908 }
5909 TEnvRec* rec;
5910 TIter next(fMapfile->GetTable());
5911 while ((rec = (TEnvRec*) next())) {
5912 TString cls = rec->GetName();
5913 if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
5914 // get the first lib from the list of lib and dependent libs
5915 TString libs = rec->GetValue();
5916 if (libs == "") {
5917 continue;
5918 }
5919 TString delim(" ");
5920 TObjArray* tokens = libs.Tokenize(delim);
5921 const char* lib = ((TObjString*)tokens->At(0))->GetName();
5922 // convert "@@" to "::", we used "@@" because TEnv
5923 // considers "::" a terminator
5924 cls.Remove(0, 8);
5925 cls.ReplaceAll("@@", "::");
5926 // convert "-" to " ", since class names may have
5927 // blanks and TEnv considers a blank a terminator
5928 cls.ReplaceAll("-", " ");
5929 if (gDebug > 6) {
5930 const char* wlib = gSystem->DynamicPathName(lib, kTRUE);
5931 if (wlib) {
5932 Info("LoadLibraryMap", "class %s in %s", cls.Data(), wlib);
5933 }
5934 else {
5935 Info("LoadLibraryMap", "class %s in %s (library does not exist)", cls.Data(), lib);
5936 }
5937 delete[] wlib;
5938 }
5939 delete tokens;
5940 }
5941 else if (!strncmp(cls.Data(), "Declare.", 8) && cls.Length() > 8) {
5942 cls.Remove(0, 8);
5943 // convert "-" to " ", since class names may have
5944 // blanks and TEnv considers a blank a terminator
5945 cls.ReplaceAll("-", " ");
5946 fInterpreter->declare(cls.Data());
5947 }
5948 }
5949
5950 // Process the forward declarations collected
5951 cling::Transaction* T = nullptr;
5952 auto compRes= fInterpreter->declare(uniqueString.Data(), &T);
5953 assert(cling::Interpreter::kSuccess == compRes && "A declaration in a rootmap could not be compiled");
5954
5955 if (compRes!=cling::Interpreter::kSuccess){
5956 Warning("LoadLibraryMap",
5957 "Problems in %s declaring '%s' were encountered.", rootmapfile, uniqueString.Data()) ;
5958 }
5959
5960 if (T) {
5961 ExtVisibleStorageAdder evsAdder(fNSFromRootmaps);
5962 for (auto declIt = T->decls_begin(); declIt < T->decls_end(); ++declIt) {
5963 if (declIt->m_DGR.isSingleDecl()) {
5964 if (Decl* D = declIt->m_DGR.getSingleDecl()) {
5965 if (clang::isa<TagDecl>(D) || clang::isa<NamespaceDecl>(D)) {
5966 evsAdder.TraverseDecl(D);
5967 }
5968 }
5969 }
5970 }
5971 }
5972
5973 // clear duplicates
5974
5975 return 0;
5976}
5977
5978////////////////////////////////////////////////////////////////////////////////
5979/// Scan again along the dynamic path for library maps. Entries for the loaded
5980/// shared libraries are unloaded first. This can be useful after reseting
5981/// the dynamic path through TSystem::SetDynamicPath()
5982/// In case of error -1 is returned, 0 otherwise.
5983
5990
5991////////////////////////////////////////////////////////////////////////////////
5992/// Reload the library map entries coming from all the loaded shared libraries,
5993/// after first unloading the current ones.
5994/// In case of error -1 is returned, 0 otherwise.
5995
5997{
5999 const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
6000 const Int_t nrSharedLibs = sharedLibL->GetEntriesFast();
6001 for (Int_t ilib = 0; ilib < nrSharedLibs; ilib++) {
6002 const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
6005 if (ret < 0) {
6006 continue;
6007 }
6009 if (sharedLibBaseStr.EndsWith(".dll")) {
6010 rootMapBaseStr.ReplaceAll(".dll", "");
6011 }
6012 else if (sharedLibBaseStr.EndsWith(".DLL")) {
6013 rootMapBaseStr.ReplaceAll(".DLL", "");
6014 }
6015 else if (sharedLibBaseStr.EndsWith(".so")) {
6016 rootMapBaseStr.ReplaceAll(".so", "");
6017 }
6018 else if (sharedLibBaseStr.EndsWith(".sl")) {
6019 rootMapBaseStr.ReplaceAll(".sl", "");
6020 }
6021 else if (sharedLibBaseStr.EndsWith(".dl")) {
6022 rootMapBaseStr.ReplaceAll(".dl", "");
6023 }
6024 else if (sharedLibBaseStr.EndsWith(".a")) {
6025 rootMapBaseStr.ReplaceAll(".a", "");
6026 }
6027 else {
6028 Error("ReloadAllSharedLibraryMaps", "Unknown library type %s", sharedLibBaseStr.Data());
6029 delete sharedLibL;
6030 return -1;
6031 }
6032 rootMapBaseStr += ".rootmap";
6034 if (!rootMap) {
6035 Error("ReloadAllSharedLibraryMaps", "Could not find rootmap %s in path", rootMapBaseStr.Data());
6036 delete[] rootMap;
6037 delete sharedLibL;
6038 return -1;
6039 }
6040 const Int_t status = LoadLibraryMap(rootMap);
6041 if (status < 0) {
6042 Error("ReloadAllSharedLibraryMaps", "Error loading map %s", rootMap);
6043 delete[] rootMap;
6044 delete sharedLibL;
6045 return -1;
6046 }
6047 delete[] rootMap;
6048 }
6049 delete sharedLibL;
6050 return 0;
6051}
6052
6053////////////////////////////////////////////////////////////////////////////////
6054/// Unload the library map entries coming from all the loaded shared libraries.
6055/// Returns 0 if succesful
6056
6058{
6060 const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
6061 for (Int_t ilib = 0; ilib < sharedLibL->GetEntriesFast(); ilib++) {
6062 const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
6065 }
6066 delete sharedLibL;
6067 return 0;
6068}
6069
6070////////////////////////////////////////////////////////////////////////////////
6071/// Unload library map entries coming from the specified library.
6072/// Returns -1 in case no entries for the specified library were found,
6073/// 0 otherwise.
6074
6076{
6077 if (!fMapfile || !library || !*library) {
6078 return 0;
6079 }
6081 Ssiz_t idx = libname.Last('.');
6082 if (idx != kNPOS) {
6083 libname.Remove(idx);
6084 }
6085 size_t len = libname.Length();
6086 TEnvRec *rec;
6087 TIter next(fMapfile->GetTable());
6089 Int_t ret = 0;
6090 while ((rec = (TEnvRec *) next())) {
6091 TString cls = rec->GetName();
6092 if (cls.Length() > 2) {
6093 // get the first lib from the list of lib and dependent libs
6094 TString libs = rec->GetValue();
6095 if (libs == "") {
6096 continue;
6097 }
6098 TString delim(" ");
6099 TObjArray* tokens = libs.Tokenize(delim);
6100 const char* lib = ((TObjString *)tokens->At(0))->GetName();
6101 if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
6102 // convert "@@" to "::", we used "@@" because TEnv
6103 // considers "::" a terminator
6104 cls.Remove(0, 8);
6105 cls.ReplaceAll("@@", "::");
6106 // convert "-" to " ", since class names may have
6107 // blanks and TEnv considers a blank a terminator
6108 cls.ReplaceAll("-", " ");
6109 }
6110 if (!strncmp(lib, libname.Data(), len)) {
6111 if (fMapfile->GetTable()->Remove(rec) == nullptr) {
6112 Error("UnloadLibraryMap", "entry for <%s, %s> not found in library map table", cls.Data(), lib);
6113 ret = -1;
6114 }
6115 }
6116 delete tokens;
6117 }
6118 }
6119 if (ret >= 0) {
6121 if (!library_rootmap.EndsWith(".rootmap"))
6122 library_rootmap.Append(".rootmap");
6123 TNamed* mfile = nullptr;
6126 delete mfile;
6127 }
6129 }
6130 return ret;
6131}
6132
6133////////////////////////////////////////////////////////////////////////////////
6134/// Register the AutoLoading information for a class.
6135/// libs is a space separated list of libraries.
6136
6137Int_t TCling::SetClassSharedLibs(const char *cls, const char *libs)
6138{
6139 if (!cls || !*cls)
6140 return 0;
6141
6142 TString key = TString("Library.") + cls;
6143 // convert "::" to "@@", we used "@@" because TEnv
6144 // considers "::" a terminator
6145 key.ReplaceAll("::", "@@");
6146 // convert "-" to " ", since class names may have
6147 // blanks and TEnv considers a blank a terminator
6148 key.ReplaceAll(" ", "-");
6149
6151 if (!fMapfile) {
6152 fMapfile = new TEnv();
6154
6157
6158 InitRootmapFile(".rootmap");
6159 }
6160 //fMapfile->SetValue(key, libs);
6162 return 1;
6163}
6164
6165////////////////////////////////////////////////////////////////////////////////
6166/// Demangle the name (from the typeinfo) and then request the class
6167/// via the usual name based interface (TClass::GetClass).
6168
6169TClass *TCling::GetClass(const std::type_info& typeinfo, Bool_t load) const
6170{
6171 int err = 0;
6173 if (err) return nullptr;
6176 return theClass;
6177}
6178
6179////////////////////////////////////////////////////////////////////////////////
6180/// Load library containing the specified class. Returns 0 in case of error
6181/// and 1 in case if success.
6182
6183Int_t TCling::AutoLoad(const std::type_info& typeinfo, Bool_t knowDictNotLoaded /* = kFALSE */)
6184{
6185 assert(IsClassAutoLoadingEnabled() && "Calling when AutoLoading is off!");
6186
6187 int err = 0;
6189 if (err) {
6190 return 0;
6191 }
6192
6193 std::string demangled_name(demangled_name_c);
6195
6196 // AutoLoad expects (because TClass::GetClass already prepares it that way) a
6197 // shortened name.
6200
6201 // No need to worry about typedef, they aren't any ... but there are
6202 // inlined namespaces ...
6203
6205 if (result == 0) {
6208 }
6209
6210 return result;
6211}
6212
6213////////////////////////////////////////////////////////////////////////////////
6214// Get the list of 'published'/'known' library for the class and load them.
6216{
6217 Int_t status = 0;
6218
6219 // lookup class to find list of dependent libraries
6221 if (!deplibs.IsNull()) {
6222 TString delim(" ");
6223 TObjArray* tokens = deplibs.Tokenize(delim);
6224 for (Int_t i = (tokens->GetEntriesFast() - 1); i > 0; --i) {
6225 const char* deplib = ((TObjString*)tokens->At(i))->GetName();
6226 if (gROOT->LoadClass(cls, deplib) == 0) {
6227 if (gDebug > 0) {
6228 gCling->Info("TCling::AutoLoad",
6229 "loaded dependent library %s for %s", deplib, cls);
6230 }
6231 }
6232 else {
6233 gCling->Error("TCling::AutoLoad",
6234 "failure loading dependent library %s for %s",
6235 deplib, cls);
6236 }
6237 }
6238 const char* lib = ((TObjString*)tokens->At(0))->GetName();
6239 if (lib && lib[0]) {
6240 if (gROOT->LoadClass(cls, lib) == 0) {
6241 if (gDebug > 0) {
6242 gCling->Info("TCling::AutoLoad",
6243 "loaded library %s for %s", lib, cls);
6244 }
6245 status = 1;
6246 }
6247 else {
6248 gCling->Error("TCling::AutoLoad",
6249 "failure loading library %s for %s", lib, cls);
6250 }
6251 }
6252 delete tokens;
6253 }
6254
6255 return status;
6256}
6257
6258////////////////////////////////////////////////////////////////////////////////
6259// Iterate through the data member of the class (either through the TProtoClass
6260// or through Cling) and trigger, recursively, the loading the necessary libraries.
6261// \note `cls` is expected to be already normalized!
6262// \returns 1 on success.
6263Int_t TCling::DeepAutoLoadImpl(const char *cls, std::unordered_set<std::string> &visited,
6264 bool nameIsNormalized)
6265{
6266 // Try to insert; if insertion failed because the entry existed, DeepAutoLoadImpl()
6267 // has previously (within the same call to `AutoLoad()`) tried to load this class
6268 // and we are done, whether success or not, as it won't work better now than before,
6269 // because there is no additional information now compared to before.
6270 if (!visited.insert(std::string(cls)).second)
6271 return 1;
6272
6273 if (ShallowAutoLoadImpl(cls) == 0) {
6274 // If ShallowAutoLoadImpl() has an error, we have an error.
6275 return 0;
6276 }
6277
6278 // Now look through the TProtoClass to load the required library/dictionary
6280 for (auto element : proto->GetData()) {
6281 if (element->IsBasic())
6282 continue;
6283 const char *subtypename = element->GetTypeName();
6285 // Failure to load a dictionary is not (quite) a failure load
6286 // the top-level library. If we return false here, then
6287 // we would end up in a situation where the library and thus
6288 // the dictionary is loaded for "cls" but the TClass is
6289 // not created and/or marked as unavailable (in case where
6290 // AutoLoad is called from TClass::GetClass).
6291 DeepAutoLoadImpl(subtypename, visited, true /*normalized*/);
6292 }
6293 }
6294 return 1;
6295 }
6296
6297 // We found no TProtoClass for cls.
6298 auto classinfo = gInterpreter->ClassInfo_Factory(cls);
6299 if (classinfo && gInterpreter->ClassInfo_IsValid(classinfo)
6300 && !(gInterpreter->ClassInfo_Property(classinfo) & kIsEnum))
6301 {
6303 while (gInterpreter->DataMemberInfo_Next(memberinfo)) {
6304 if (gInterpreter->DataMemberInfo_TypeProperty(memberinfo) & ::kIsFundamental)
6305 continue;
6306 auto membertypename = TClassEdit::GetLong64_Name(gInterpreter->TypeName(gInterpreter->DataMemberInfo_TypeTrueName(memberinfo)));
6308 // Failure to load a dictionary is not (quite) a failure load
6309 // the top-level library. See detailed comment in the TProtoClass
6310 // branch (above).
6311 (void)DeepAutoLoadImpl(membertypename.c_str(), visited, true /*normalized*/);
6312 }
6313 }
6314 gInterpreter->DataMemberInfo_Delete(memberinfo);
6315 }
6316 gInterpreter->ClassInfo_Delete(classinfo);
6317 return 1;
6318}
6319
6320////////////////////////////////////////////////////////////////////////////////
6321/// Load library containing the specified class. Returns 0 in case of error
6322/// and 1 in case if success.
6323
6325{
6326 // Prevent update to IsClassAutoloading between our check and our actions.
6328
6329 // TClass::GetClass explicitly calls gInterpreter->AutoLoad. When called from
6330 // rootcling (in *_rdict.pcm file generation) it is a no op.
6331 // FIXME: We should avoid calling autoload when we know we are not supposed
6332 // to and transform this check into an assert.
6334 // Never load any library from rootcling/genreflex.
6335 if (gDebug > 2) {
6336 Info("TCling::AutoLoad", "Explicitly disabled (the class name is %s)", cls);
6337 }
6338 return 0;
6339 }
6340
6341 assert(IsClassAutoLoadingEnabled() && "Calling when AutoLoading is off!");
6342
6344
6346 // The library is already loaded as the class's dictionary is known.
6347 // Return success.
6348 // Note: the name (cls) is expected to be normalized as it comes either
6349 // from a callbacks (that can/should calculate the normalized name from the
6350 // decl) or from TClass::GetClass (which does also calculate the normalized
6351 // name).
6352 return 1;
6353 }
6354
6355 if (gDebug > 2) {
6356 Info("TCling::AutoLoad",
6357 "Trying to autoload for %s", cls);
6358 }
6359
6360 if (!gROOT || !gInterpreter || gROOT->TestBit(TObject::kInvalidObject)) {
6361 if (gDebug > 2) {
6362 Info("TCling::AutoLoad",
6363 "Disabled due to gROOT or gInterpreter being invalid/not ready (the class name is %s)", cls);
6364 }
6365 return 0;
6366 }
6367 // Prevent the recursion when the library dictionary are loaded.
6369 // Try using externally provided callback first.
6370 if (fAutoLoadCallBack) {
6372 if (success)
6373 return success;
6374 }
6375
6376 // During the 'Deep' part of the search we will call GetClassSharedLibsForModule
6377 // (when module are enabled) which might end up calling AutoParsing but
6378 // that should only be for the cases where the library has no generated pcm
6379 // and in that case a rootmap should be available.
6380 // This avoids a very costly operation (for generally no gain) but reduce the
6381 // quality of the search (i.e. bad in case of library with no pcm and no rootmap
6382 // file).
6384 std::unordered_set<std::string> visited;
6385 return DeepAutoLoadImpl(cls, visited, false /*normalized*/);
6386}
6387
6388////////////////////////////////////////////////////////////////////////////////
6389/// Parse the payload or header.
6390
6391static cling::Interpreter::CompilationResult ExecAutoParse(const char *what,
6392 Bool_t header,
6393 cling::Interpreter *interpreter)
6394{
6395 std::string code = gNonInterpreterClassDef ;
6396 if (!header) {
6397 // This is the complete header file content and not the
6398 // name of a header.
6399 code += what;
6400
6401 } else {
6402 code += ("#include \"");
6403 code += what;
6404 code += "\"\n";
6405 }
6406 code += ("#ifdef __ROOTCLING__\n"
6407 "#undef __ROOTCLING__\n"
6409 "#endif");
6410
6411 cling::Interpreter::CompilationResult cr;
6412 {
6413 // scope within which diagnostics are de-activated
6414 // For now we disable diagnostics because we saw them already at
6415 // dictionary generation time. That won't be an issue with the PCMs.
6416
6417 Sema &SemaR = interpreter->getSema();
6419 clangDiagSuppr diagSuppr(SemaR.getDiagnostics());
6420
6421 #if defined(R__MUST_REVISIT)
6422 #if R__MUST_REVISIT(6,2)
6423 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
6424 #endif
6425 #endif
6426
6427 cr = interpreter->parseForModule(code);
6428 }
6429 return cr;
6430}
6431
6432////////////////////////////////////////////////////////////////////////////////
6433/// Helper routine for TCling::AutoParse implementing the actual call to the
6434/// parser and looping over template parameters (if
6435/// any) and when they don't have a registered header to autoparse,
6436/// recurse over their template parameters.
6437///
6438/// Returns the number of header parsed.
6439
6441{
6442 // We assume the lock has already been taken.
6443 // R__LOCKGUARD(gInterpreterMutex);
6444
6446 unsigned long offset = 0;
6447 if (strncmp(cls, "const ", 6) == 0) {
6448 offset = 6;
6449 }
6450
6451 // Loop on the possible autoparse keys
6452 bool skipFirstEntry = false;
6453 std::vector<std::string> autoparseKeys;
6454 if (strchr(cls, '<')) {
6455 int nestedLoc = 0;
6457 // Check if we can skip the name of the template in the autoparses
6458 // Take all the scopes one by one. If all of them are in the AST, we do not
6459 // need to autoparse for that particular template.
6460 if (!autoparseKeys.empty() && !autoparseKeys[0].empty()) {
6461 // autoparseKeys[0] is empty when the input is not a template instance.
6462 // The case strchr(cls, '<') != 0 but still not a template instance can
6463 // happens 'just' for string (GetSplit replaces the template by the short name
6464 // and then use that for thew splitting)
6466 auto tokens = templateName.Tokenize("::");
6467 clang::NamedDecl* previousScopeAsNamedDecl = nullptr;
6468 clang::DeclContext* previousScopeAsContext = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
6470 previousScopeAsContext = fInterpreter->getSema().getStdNamespace();
6471 auto nTokens = tokens->GetEntriesFast();
6472 for (Int_t tk = 0; tk < nTokens; ++tk) {
6473 auto scopeObj = tokens->UncheckedAt(tk);
6474 auto scopeName = ((TObjString*) scopeObj)->String().Data();
6475 previousScopeAsNamedDecl = cling::utils::Lookup::Named(&fInterpreter->getSema(), scopeName, previousScopeAsContext);
6476 // Check if we have multiple nodes in the AST with this name
6477 if ((clang::NamedDecl*)-1 == previousScopeAsNamedDecl) break;
6478 previousScopeAsContext = llvm::dyn_cast_or_null<clang::DeclContext>(previousScopeAsNamedDecl);
6479 if (!previousScopeAsContext) break; // this is not a context
6480 }
6481 delete tokens;
6482 // Now, let's check if the last scope, the template, has a definition, i.e. it's not a fwd decl
6483 if ((clang::NamedDecl*)-1 != previousScopeAsNamedDecl) {
6484 if (auto templateDecl = llvm::dyn_cast_or_null<clang::ClassTemplateDecl>(previousScopeAsNamedDecl)) {
6485 if (auto templatedDecl = templateDecl->getTemplatedDecl()) {
6486 skipFirstEntry = templatedDecl->hasDefinition();
6487 }
6488 }
6489 }
6490
6491 }
6492 }
6493 if (topLevel) autoparseKeys.emplace_back(cls);
6494
6495 for (const auto & apKeyStr : autoparseKeys) {
6496 if (skipFirstEntry) {
6497 skipFirstEntry=false;
6498 continue;
6499 }
6500 if (apKeyStr.empty()) continue;
6501 const char *apKey = apKeyStr.c_str();
6503 // If the class was not looked up
6504 if (gDebug > 1) {
6505 Info("TCling::AutoParse",
6506 "Starting autoparse for %s\n", apKey);
6507 }
6508 if (fLookedUpClasses.insert(normNameHash).second) {
6509 auto const &iter = fClassesHeadersMap.find(normNameHash);
6510 if (iter != fClassesHeadersMap.end()) {
6511 const cling::Transaction *T = fInterpreter->getCurrentTransaction();
6513 auto const &hNamesPtrs = iter->second;
6514 if (gDebug > 1) {
6515 Info("TCling::AutoParse",
6516 "We can proceed for %s. We have %s headers.", apKey, std::to_string(hNamesPtrs.size()).c_str());
6517 }
6518 for (auto & hName : hNamesPtrs) {
6519 if (fParsedPayloadsAddresses.count(hName) == 1) continue;
6520 if (0 != fPayloads.count(normNameHash)) {
6521 float initRSSval=0.f, initVSIZEval=0.f;
6522 (void) initRSSval; // Avoid unused var warning
6523 (void) initVSIZEval;
6524 if (gDebug > 0) {
6525 Info("AutoParse",
6526 "Parsing full payload for %s", apKey);
6529 initRSSval = 1e-3*info.fMemResident;
6530 initVSIZEval = 1e-3*info.fMemVirtual;
6531 }
6533 if (cRes != cling::Interpreter::kSuccess) {
6534 if (hName[0] == '\n')
6535 Error("AutoParse", "Error parsing payload code for class %s with content:\n%s", apKey, hName);
6536 } else {
6539 if (gDebug > 0){
6542 float endRSSval = 1e-3*info.fMemResident;
6543 float endVSIZEval = 1e-3*info.fMemVirtual;
6544 Info("Autoparse", ">>> RSS key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initRSSval, endRSSval, endRSSval-initRSSval);
6545 Info("Autoparse", ">>> VSIZE key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initVSIZEval, endVSIZEval, endVSIZEval-initVSIZEval);
6546 }
6547 }
6548 } else if (!IsLoaded(hName)) {
6549 if (gDebug > 0) {
6550 Info("AutoParse",
6551 "Parsing single header %s", hName);
6552 }
6554 if (cRes != cling::Interpreter::kSuccess) {
6555 Error("AutoParse", "Error parsing headerfile %s for class %s.", hName, apKey);
6556 } else {
6558 }
6559 }
6560 }
6561 }
6562 else {
6563 // There is no header registered for this class, if this a
6564 // template, it will be instantiated if/when it is requested
6565 // and if we do no load/parse its components we might end up
6566 // not using an eventual specialization.
6567 if (strchr(apKey, '<')) {
6569 }
6570 }
6571 }
6572 }
6573
6574 return nHheadersParsed;
6575
6576}
6577
6578////////////////////////////////////////////////////////////////////////////////
6579/// Parse the headers relative to the class
6580/// Returns 1 in case of success, 0 in case of failure
6581
6583{
6584 if (llvm::StringRef(cls).contains("(lambda)"))
6585 return 0;
6586
6589 return AutoLoad(cls);
6590 } else {
6591 return 0;
6592 }
6593 }
6594
6596
6597 if (gDebug > 1) {
6598 Info("TCling::AutoParse",
6599 "Trying to autoparse for %s", cls);
6600 }
6601
6602 // The catalogue of headers is in the dictionary
6604 && !gClassTable->GetDictNorm(cls)) {
6605 // Need RAII against recursive (dictionary payload) parsing (ROOT-8445).
6607 fInterpreter->getSema());
6608 AutoLoad(cls, true /*knowDictNotLoaded*/);
6609 }
6610
6611 // Prevent the recursion when the library dictionary are loaded.
6613
6614 // No recursive header parsing on demand; we require headers to be standalone.
6616
6617 Int_t nHheadersParsed = AutoParseImplRecurse(cls,/*topLevel=*/ true);
6618
6620
6621 return nHheadersParsed > 0 ? 1 : 0;
6622}
6623
6624// This is a function which gets callback from cling when DynamicLibraryManager->loadLibrary failed for some reason.
6625// Try to solve the problem by AutoLoading. Return true when AutoLoading success, return
6626// false if not.
6627bool TCling::LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
6628{
6630 if (errMsg.contains("undefined symbol: ")) {
6631 // This branch is taken when the callback was from DynamicLibraryManager::loadLibrary
6632 std::string mangled_name = std::string(errMsg.split("undefined symbol: ").second);
6633 void* res = ((TCling*)gCling)->LazyFunctionCreatorAutoload(mangled_name);
6634 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
6635 if (res && DLM && (DLM->loadLibrary(libStem, permanent, resolved) == cling::DynamicLibraryManager::kLoadLibSuccess))
6636 // Return success when LazyFunctionCreatorAutoload could find mangled_name
6637 return true;
6638 } else {
6639 // The callback is from IncrementalExecutor::diagnoseUnresolvedSymbols
6641 return true;
6642 }
6643
6644 return false;
6645}
6646
6647////////////////////////////////////////////////////////////////////////////////
6648/// Autoload a library based on a missing symbol.
6649
6652
6653 // We have already loaded the library.
6654 if (void* Addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(dlsym_mangled_name))
6655 return Addr;
6656
6657 const cling::DynamicLibraryManager &DLM = *GetInterpreterImpl()->getDynamicLibraryManager();
6659
6660 auto LibLoader = [](const std::string& LibName) -> bool {
6661 if (gSystem->Load(LibName.c_str(), "", false) < 0) {
6662 ::Error("TCling__LazyFunctionCreatorAutoloadForModule",
6663 "Failed to load library %s", LibName.c_str());
6664 return false;
6665 }
6666 return true; //success.
6667 };
6668
6669 std::string libName = DLM.searchLibrariesForSymbol(mangled_name,
6670 /*searchSystem=*/ true);
6671
6672 assert(!llvm::StringRef(libName).starts_with("libNew") && "We must not resolve symbols from libNew!");
6673
6674 if (libName.empty())
6675 return nullptr;
6676
6677 if (!LibLoader(libName))
6678 return nullptr;
6679
6680 return llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(dlsym_mangled_name);
6681}
6682
6683////////////////////////////////////////////////////////////////////////////////
6684
6686{
6687 return fNSFromRootmaps.count(nsDecl) != 0;
6688}
6689
6690////////////////////////////////////////////////////////////////////////////////
6691/// Internal function. Actually do the update of the ClassInfo when seeing
6692// new TagDecl or NamespaceDecl.
6693void TCling::RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
6694{
6695
6697 if (cci) {
6698 // If we only had a forward declaration then update the
6699 // TClingClassInfo with the definition if we have it now.
6700 const NamedDecl *oldDef = llvm::dyn_cast_or_null<NamedDecl>(cci->GetDecl());
6701 if (!oldDef || (def && def != oldDef)) {
6702 cl->ResetCaches();
6703 TClass::RemoveClassDeclId(cci->GetDeclId());
6704 if (def) {
6705 if (cci->GetType()) {
6706 // It's a tag decl, not a namespace decl.
6707 cci->Init(*cci->GetType());
6708 TClass::AddClassToDeclIdMap(cci->GetDeclId(), cl);
6709 } else {
6710 Error("RefreshClassInfo", "Should not need to update the classInfo a non type decl: %s", oldDef->getNameAsString().c_str());
6711 }
6712 }
6713 }
6714 } else if (!cl->TestBit(TClass::kLoading) && !cl->fHasRootPcmInfo) {
6715 cl->ResetCaches();
6716 if (strncmp(cl->GetName(),"tuple<",strlen("tuple<"))==0) {
6717 // We need to use the Emulated Tuple but we should not trigger parsing
6718 // yet, so delay the creation of the ClassInfo
6719 delete ((TClingClassInfo *)cl->fClassInfo);
6720 cl->fClassInfo = nullptr;
6721 cl->fCanLoadClassInfo = true;
6723 if (cl->fState != TClass::kHasTClassInit) {
6725 }
6726 return;
6727 }
6728 // yes, this is almost a waste of time, but we do need to lookup
6729 // the 'type' corresponding to the TClass anyway in order to
6730 // preserve the opaque typedefs (Double32_t)
6731 if (!alias && def != nullptr)
6733 else
6735 if (((TClingClassInfo *)cl->fClassInfo)->IsValid()) {
6736 // We now need to update the state and bits.
6737 if (cl->fState != TClass::kHasTClassInit) {
6738 // if (!cl->fClassInfo->IsValid()) cl->fState = TClass::kForwardDeclared; else
6740 }
6741 TClass::AddClassToDeclIdMap(((TClingClassInfo *)(cl->fClassInfo))->GetDeclId(), cl);
6742 } else {
6743 delete ((TClingClassInfo *)cl->fClassInfo);
6744 cl->fClassInfo = nullptr;
6745 }
6746 }
6747}
6748
6749////////////////////////////////////////////////////////////////////////////////
6750/// Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
6752{
6753 const TagDecl *td = dyn_cast<TagDecl>(ND);
6755 const NamedDecl *canon = nullptr;
6756
6757 std::string name;
6758 TagDecl* tdDef = nullptr;
6759 if (td) {
6760 canon = tdDef = td->getDefinition();
6761 // Let's pass the decl to the TClass only if it has a definition.
6762 if (!tdDef) return;
6763
6764 if (!tdDef->isCompleteDefinition() || llvm::isa<clang::FunctionDecl>(tdDef->getDeclContext())) {
6765 // Ignore incomplete definition.
6766 // Ignore declaration within a function.
6767 return;
6768 }
6769
6770 auto declName = tdDef->getNameAsString();
6771 // Check if we have registered the unqualified name into the list
6772 // of TClass that are in kNoInfo, kEmulated or kFwdDeclaredState.
6773 // Since this is used as heureutistic to avoid spurrious calls to GetNormalizedName
6774 // the unqualified name is sufficient (and the fully qualified name might be
6775 // 'wrong' if there is difference in spelling in the template paramters (for example)
6777 // 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() );
6778 return;
6779 }
6780
6781 clang::QualType type(tdDef->getTypeForDecl(), 0);
6783 } else if (ns) {
6784 canon = ns->getCanonicalDecl();
6785 name = ND->getQualifiedNameAsString();
6786 } else {
6787 name = ND->getQualifiedNameAsString();
6788 }
6789
6790 // Supposedly we are being called while something is being
6791 // loaded ... let's now tell the autoloader to do the work
6792 // yet another time.
6794 // FIXME: There can be more than one TClass for a single decl.
6795 // for example vector<double> and vector<Double32_t>
6796 TClass* cl = (TClass*)gROOT->GetListOfClasses()->FindObject(name.c_str());
6797 if (cl && GetModTClasses().find(cl) == GetModTClasses().end()) {
6798 RefreshClassInfo(cl, canon, false);
6799 }
6800 // And here we should find the other 'aliases' (eg. vector<Double32_t>)
6801 // and update them too:
6802 // foreach(aliascl in gROOT->GetListOfClasses()->FindAliasesOf(name.c_str()))
6803 // RefreshClassInfo(cl, tdDef, true);
6804}
6805
6806////////////////////////////////////////////////////////////////////////////////
6807/// No op: see TClingCallbacks
6808
6810{
6811}
6812
6813//______________________________________________________________________________
6814//FIXME: Factor out that function in TClass, because TClass does it already twice
6816{
6817 // This is a no-op as part of the API.
6818 // TCling uses UpdateClassInfoWithDecl() instead.
6819}
6820
6821////////////////////////////////////////////////////////////////////////////////
6822/// Update all canvases at end the terminal input command.
6823
6825{
6826 TIter next(gROOT->GetListOfCanvases());
6827 TVirtualPad* canvas;
6828 while ((canvas = (TVirtualPad*)next())) {
6829 canvas->Update();
6830 }
6831}
6832
6833////////////////////////////////////////////////////////////////////////////////
6834
6835void TCling::UpdateListsOnCommitted(const cling::Transaction &T) {
6836 std::set<TClass*> modifiedTClasses; // TClasses that require update after this transaction
6837
6838 // If the transaction does not contain anything we can return earlier.
6839 if (!HandleNewTransaction(T)) return;
6840
6841 bool isTUTransaction = false;
6842 if (!T.empty() && T.decls_begin() + 1 == T.decls_end() && !T.hasNestedTransactions()) {
6843 clang::Decl* FirstDecl = *(T.decls_begin()->m_DGR.begin());
6844 if (llvm::isa<clang::TranslationUnitDecl>(FirstDecl)) {
6845 // The is the first transaction, we have to expose to meta
6846 // what's already in the AST.
6847 isTUTransaction = true;
6848 }
6849 }
6850
6851 std::set<const void*> TransactionDeclSet;
6852 if (!isTUTransaction && T.decls_end() - T.decls_begin()) {
6853 const clang::Decl* WrapperFD = T.getWrapperFD();
6854 for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
6855 I != E; ++I) {
6856 if (I->m_Call != cling::Transaction::kCCIHandleTopLevelDecl
6857 && I->m_Call != cling::Transaction::kCCIHandleTagDeclDefinition)
6858 continue;
6859
6860 for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6861 DE = I->m_DGR.end(); DI != DE; ++DI) {
6862 if (*DI == WrapperFD)
6863 continue;
6864 TransactionDeclSet.insert(*DI);
6865 ((TCling*)gCling)->HandleNewDecl(*DI, false, modifiedTClasses);
6866 }
6867 }
6868 }
6869
6870 // The above might trigger more decls to be deserialized.
6871 // Thus the iteration over the deserialized decls must be last.
6872 for (cling::Transaction::const_iterator I = T.deserialized_decls_begin(),
6873 E = T.deserialized_decls_end(); I != E; ++I) {
6874 for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6875 DE = I->m_DGR.end(); DI != DE; ++DI)
6876 if (TransactionDeclSet.find(*DI) == TransactionDeclSet.end()) {
6877 //FIXME: HandleNewDecl should take DeclGroupRef
6878 ((TCling*)gCling)->HandleNewDecl(*DI, /*isDeserialized*/true,
6880 }
6881 }
6882
6883
6884 // When fully building the reflection info in TClass, a deserialization
6885 // could be triggered, which may result in request for building the
6886 // reflection info for the same TClass. This in turn will clear the caches
6887 // for the TClass in-flight and cause null ptr derefs.
6888 // FIXME: This is a quick fix, solving most of the issues. The actual
6889 // question is: Shouldn't TClass provide a lock mechanism on update or lock
6890 // itself until the update is done.
6891 //
6892 std::vector<TClass*> modifiedTClassesDiff(modifiedTClasses.size());
6893 std::vector<TClass*>::iterator it;
6895 ((TCling*)gCling)->GetModTClasses().begin(),
6896 ((TCling*)gCling)->GetModTClasses().end(),
6899
6900 // Lock the TClass for updates
6901 ((TCling*)gCling)->GetModTClasses().insert(modifiedTClassesDiff.begin(),
6903 for (std::vector<TClass*>::const_iterator I = modifiedTClassesDiff.begin(),
6904 E = modifiedTClassesDiff.end(); I != E; ++I) {
6905 // Make sure the TClass has not been deleted.
6906 if (!gROOT->GetListOfClasses()->FindObject(*I)) {
6907 continue;
6908 }
6909 // Could trigger deserialization of decls.
6910 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
6911 // Unlock the TClass for updates
6912 ((TCling*)gCling)->GetModTClasses().erase(*I);
6913
6914 }
6915}
6916
6917///\brief Invalidate stored TCling state for declarations included in transaction `T'.
6918///
6919void TCling::UpdateListsOnUnloaded(const cling::Transaction &T)
6920{
6922
6923 auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
6924 (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
6925 (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
6926 (TListOfEnums *)gROOT->GetListOfEnums());
6927
6928 cling::Transaction::const_nested_iterator iNested = T.nested_begin();
6929 for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
6930 I != E; ++I) {
6931 if (I->m_Call == cling::Transaction::kCCIHandleVTable)
6932 continue;
6933 if (I->m_Call == cling::Transaction::kCCINone) {
6935 ++iNested;
6936 continue;
6937 }
6938
6939 for (auto &D : I->m_DGR)
6941 }
6942}
6943
6944///\brief Invalidate cached TCling information for the given global declaration.
6945///
6947 auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
6948 (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
6949 (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
6950 (TListOfEnums *)gROOT->GetListOfEnums());
6952}
6953
6954///\brief Invalidate cached TCling information for the given declaration, and
6955/// removed it from the appropriate object list.
6956///\param[in] Lists - std::tuple<TListOfDataMembers&, TListOfFunctions&,
6957/// TListOfFunctionTemplates&, TListOfEnums&>
6958/// of pointers to the (global/class) object lists.
6959///\param[in] D - Decl to discard.
6960///
6964 TListOfEnums*> &Lists, const Decl *D) {
6965 if (D->isFromASTFile()) // `D' came from the PCH; ignore
6966 return;
6967
6968 TListOfDataMembers &LODM = *(std::get<0>(Lists));
6969 TListOfFunctions &LOF = *(std::get<1>(Lists));
6970 TListOfFunctionTemplates &LOFT = *(std::get<2>(Lists));
6971 TListOfEnums &LOE = *(std::get<3>(Lists));
6972
6974 TObject *O = LODM.Find((TDictionary::DeclId_t)D);
6975 if (LODM.GetClass())
6976 RemoveAndInvalidateObject(LODM, static_cast<TDataMember *>(O));
6977 else
6978 RemoveAndInvalidateObject(LODM, static_cast<TGlobal *>(O));
6979 } else if (isa<FunctionDecl>(D)) {
6981 } else if (isa<FunctionTemplateDecl>(D)) {
6983 } else if (isa<EnumDecl>(D)) {
6984 TEnum *E = LOE.Find((TDictionary::DeclId_t)D);
6985 if (!E)
6986 return;
6987
6988 // Try to invalidate enumerators (for unscoped enumerations).
6989 for (TIter I = E->GetConstants(); auto EC = (TEnumConstant *)I(); )
6991 (TEnumConstant *)LODM.FindObject(EC->GetName()));
6992
6994 } else if (isa<RecordDecl>(D) || isa<NamespaceDecl>(D)) {
6996 return;
6997
6998 std::vector<TClass *> Classes;
6999 if (!TClass::GetClass(D->getCanonicalDecl(), Classes))
7000 return;
7001 for (auto &C : Classes) {
7002 auto Lists = std::make_tuple((TListOfDataMembers *)C->GetListOfDataMembers(),
7003 (TListOfFunctions *)C->GetListOfMethods(),
7004 (TListOfFunctionTemplates *)C->GetListOfFunctionTemplates(),
7005 (TListOfEnums *)C->GetListOfEnums());
7006 for (auto &I : cast<DeclContext>(D)->decls())
7008
7009 // For NamespaceDecl (redeclarable), only invalidate this redecl.
7010 if (D->getKind() != Decl::Namespace
7011 || cast<NamespaceDecl>(D)->isOriginalNamespace())
7012 C->ResetClassInfo();
7013 }
7014 }
7015}
7016
7017////////////////////////////////////////////////////////////////////////////////
7018// If an autoparse was done during a transaction and that it is rolled back,
7019// we need to make sure the next request for the same autoparse will be
7020// honored.
7021void TCling::TransactionRollback(const cling::Transaction &T) {
7022 auto const &triter = fTransactionHeadersMap.find(&T);
7023 if (triter != fTransactionHeadersMap.end()) {
7024 std::size_t normNameHash = triter->second;
7025
7027
7028 auto const &iter = fClassesHeadersMap.find(normNameHash);
7029 if (iter != fClassesHeadersMap.end()) {
7030 auto const &hNamesPtrs = iter->second;
7031 for (auto &hName : hNamesPtrs) {
7032 if (gDebug > 0) {
7033 Info("TransactionRollback",
7034 "Restoring ability to autoaparse: %s", hName);
7035 }
7037 }
7038 }
7039 }
7040}
7041
7042////////////////////////////////////////////////////////////////////////////////
7043
7044void TCling::LibraryLoaded(const void* dyLibHandle, const char* canonicalName) {
7045// R__LOCKGUARD_CLING(gInterpreterMutex);
7046// UpdateListOfLoadedSharedLibraries();
7047}
7048
7049////////////////////////////////////////////////////////////////////////////////
7050
7051void TCling::LibraryUnloaded(const void* dyLibHandle, const char* canonicalName) {
7052 fPrevLoadedDynLibInfo = nullptr;
7053 fSharedLibs = "";
7054}
7055
7056////////////////////////////////////////////////////////////////////////////////
7057/// Return the list of shared libraries loaded into the process.
7058
7065
7066static std::string GetClassSharedLibsForModule(const char *cls, cling::LookupHelper &LH, bool skipCore)
7067{
7068 if (!cls || !*cls)
7069 return {};
7070
7071 using namespace clang;
7072 if (const Decl *D = LH.findScope(cls, cling::LookupHelper::NoDiagnostics,
7073 /*type*/ nullptr, /*instantiate*/ false)) {
7074 if (!D->isFromASTFile()) {
7075 if (gDebug > 5)
7076 Warning("GetClassSharedLibsForModule", "Decl found for %s is not part of a module", cls);
7077 return {};
7078 }
7079 class ModuleCollector : public ConstDeclVisitor<ModuleCollector> {
7080 llvm::DenseSet<Module *> &m_TopLevelModules;
7081
7082 public:
7083 ModuleCollector(llvm::DenseSet<Module *> &TopLevelModules) : m_TopLevelModules(TopLevelModules) {}
7084 void Collect(const Decl *D) { Visit(D); }
7085
7086 void VisitDecl(const Decl *D)
7087 {
7088 // FIXME: Such case is described ROOT-7765 where
7089 // ROOT_GENERATE_DICTIONARY does not contain the list of headers.
7090 // They are specified as #includes in the LinkDef file. This leads to
7091 // generation of incomplete modulemap files and this logic fails to
7092 // compute the corresponding module of D.
7093 // FIXME: If we want to support such a case, we should not rely on
7094 // the contents of the modulemap but mangle D and look it up in the
7095 // .so files.
7096 if (!D->hasOwningModule())
7097 return;
7098 if (Module *M = D->getOwningModule()->getTopLevelModule())
7099 m_TopLevelModules.insert(M);
7100 }
7101
7103 {
7104 switch (TA.getKind()) {
7105 case TemplateArgument::Null:
7106 case TemplateArgument::Integral:
7107 case TemplateArgument::Pack:
7108 case TemplateArgument::NullPtr:
7109 case TemplateArgument::StructuralValue:
7110 case TemplateArgument::Expression:
7111 case TemplateArgument::Template:
7112 case TemplateArgument::TemplateExpansion: return;
7113 case TemplateArgument::Type:
7114 if (const TagType *TagTy = dyn_cast<TagType>(TA.getAsType()))
7115 return Visit(TagTy->getDecl());
7116 return;
7117 case TemplateArgument::Declaration: return Visit(TA.getAsDecl());
7118 }
7119 llvm_unreachable("Invalid TemplateArgument::Kind!");
7120 }
7121
7123 {
7124 if (CTSD->getOwningModule())
7125 VisitDecl(CTSD);
7126 else
7127 VisitDecl(CTSD->getSpecializedTemplate());
7128 const TemplateArgumentList &ArgList = CTSD->getTemplateArgs();
7129 for (const TemplateArgument *Arg = ArgList.data(), *ArgEnd = Arg + ArgList.size(); Arg != ArgEnd; ++Arg) {
7131 }
7132 }
7133 };
7134
7135 llvm::DenseSet<Module *> TopLevelModules;
7137 m.Collect(D);
7138 std::string result;
7139 for (auto M : TopLevelModules) {
7140 // ROOT-unaware modules (i.e. not processed by rootcling) do not have a
7141 // link declaration.
7142 if (!M->LinkLibraries.size())
7143 continue;
7144 // We have preloaded the Core module thus libCore.so
7145 if (M->Name == "Core" && skipCore)
7146 continue;
7147 assert(M->LinkLibraries.size() == 1);
7148 if (!result.empty())
7149 result += ' ';
7150 result += M->LinkLibraries[0].Library;
7151 }
7152 return result;
7153 }
7154 return {};
7155}
7156
7157////////////////////////////////////////////////////////////////////////////////
7158/// Get the list of shared libraries containing the code for class cls.
7159/// The first library in the list is the one containing the class, the
7160/// others are the libraries the first one depends on. Returns 0
7161/// in case the library is not found.
7162/// \param cls the name of the class
7163/// \param skipCore if true (default), remove "Core" from the returned list
7164
7165const char* TCling::GetClassSharedLibs(const char* cls, bool skipCore)
7166{
7167 if (fCxxModulesEnabled) {
7168 // Lock the interpreter mutex before interacting with cling.
7169 // TODO: Can we move this further deep? In principle the lock should be in
7170 // GetClassSharedLibsForModule, but it might be needed also for
7171 // getLookupHelper?
7173 llvm::StringRef className = cls;
7174 // If we get a class name containing lambda, we cannot parse it and we
7175 // can exit early.
7176 // FIXME: This works around a bug when we are instantiating a template
7177 // make_unique and the substitution fails. Seen in most of the dataframe
7178 // tests.
7179 if (className.contains("(lambda)"))
7180 return nullptr;
7181 // Limit the recursion which can be induced by GetClassSharedLibsForModule.
7183 cling::LookupHelper &LH = fInterpreter->getLookupHelper();
7185 if (!libs.empty()) {
7186 fAutoLoadLibStorage.push_back(libs);
7187 return fAutoLoadLibStorage.back().c_str();
7188 }
7189 }
7190
7191 if (!cls || !*cls) {
7192 return nullptr;
7193 }
7194 // lookup class to find list of libraries
7195 if (fMapfile) {
7196 TEnvRec* libs_record = nullptr;
7198 if (libs_record) {
7199 const char* libs = libs_record->GetValue();
7200 return (*libs) ? libs : nullptr;
7201 }
7202 else {
7203 // Try the old format...
7204 TString c = TString("Library.") + cls;
7205 // convert "::" to "@@", we used "@@" because TEnv
7206 // considers "::" a terminator
7207 c.ReplaceAll("::", "@@");
7208 // convert "-" to " ", since class names may have
7209 // blanks and TEnv considers a blank a terminator
7210 c.ReplaceAll(" ", "-");
7211 // Use TEnv::Lookup here as the rootmap file must start with Library.
7212 // and do not support using any stars (so we do not need to waste time
7213 // with the search made by TEnv::GetValue).
7214 TEnvRec* libs_record = nullptr;
7216 if (libs_record) {
7217 const char* libs = libs_record->GetValue();
7218 return (*libs) ? libs : nullptr;
7219 }
7220 }
7221 }
7222 return nullptr;
7223}
7224
7225/// This interface returns a list of dependent libraries in the form:
7226/// lib libA.so libB.so libC.so. The first library is the library we are
7227/// searching dependencies for.
7228/// Note: In order to speed up the search, we display the dependencies of the
7229/// libraries which are not yet loaded. For instance, if libB.so was already
7230/// loaded the list would contain: lib libA.so libC.so.
7231static std::string GetSharedLibImmediateDepsSlow(std::string lib,
7232 cling::Interpreter *interp,
7233 bool skipLoadedLibs = true)
7234{
7235 TString LibFullPath(lib);
7236 if (!llvm::sys::path::is_absolute(lib)) {
7237 if (!gSystem->FindDynamicLibrary(LibFullPath, /*quiet=*/true)) {
7238 Error("TCling__GetSharedLibImmediateDepsSlow", "Cannot find library '%s'", lib.c_str());
7239 return "";
7240 }
7241 } else {
7242 assert(llvm::sys::fs::exists(lib) && "Must exist!");
7243 lib = llvm::sys::path::filename(lib).str();
7244 }
7245
7246 auto ObjF = llvm::object::ObjectFile::createObjectFile(LibFullPath.Data());
7247 if (!ObjF) {
7248 Warning("TCling__GetSharedLibImmediateDepsSlow", "Failed to read object file %s", lib.c_str());
7249 return "";
7250 }
7251
7252 llvm::object::ObjectFile *BinObjFile = ObjF.get().getBinary();
7253
7254 std::set<string> DedupSet;
7255 std::string Result = lib + ' ';
7256 for (const auto &S : BinObjFile->symbols()) {
7257 uint32_t Flags = llvm::cantFail(S.getFlags());
7258 // Skip defined symbols: we have them.
7259 if (!(Flags & llvm::object::SymbolRef::SF_Undefined))
7260 continue;
7261 // Skip undefined weak symbols: if we don't have them we won't need them.
7262 // `__gmon_start__` being a typical example.
7263 if (Flags & llvm::object::SymbolRef::SF_Weak)
7264 continue;
7265 llvm::Expected<StringRef> SymNameErr = S.getName();
7266 if (!SymNameErr) {
7267 Warning("GetSharedLibDepsForModule", "Failed to read symbol");
7268 continue;
7269 }
7270 llvm::StringRef SymName = SymNameErr.get();
7271 if (SymName.empty())
7272 continue;
7273
7274 if (BinObjFile->isELF()) {
7275 // Skip the symbols which are part of the C/C++ runtime and have a
7276 // fixed library version. See binutils ld VERSION. Those reside in
7277 // 'system' libraries, which we avoid in FindLibraryForSymbol.
7278 if (SymName.contains("@GLIBCXX") || SymName.contains("@CXXABI") ||
7279 SymName.contains("@GLIBC") || SymName.contains("@GCC"))
7280 continue;
7281
7282 // Those are 'weak undefined' symbols produced by gcc. We can
7283 // ignore them.
7284 // FIXME: It is unclear whether we can ignore all weak undefined
7285 // symbols:
7286 // http://lists.llvm.org/pipermail/llvm-dev/2017-October/118177.html
7287 static constexpr llvm::StringRef RegisterClasses("_Jv_RegisterClasses");
7288 static constexpr llvm::StringRef RegisterCloneTable("_ITM_registerTMCloneTable");
7289 static constexpr llvm::StringRef DeregisterCloneTable("_ITM_deregisterTMCloneTable");
7290 if (SymName == RegisterClasses ||
7293 continue;
7294 }
7295
7296 // If we can find the address of the symbol, we have loaded it. Skip.
7297 if (skipLoadedLibs) {
7299 if (llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(SymNameForDlsym))
7300 continue;
7301 }
7302
7304 std::string found = interp->getDynamicLibraryManager()->searchLibrariesForSymbol(SymName, /*searchSystem*/false);
7305 // The expected output is just filename without the full path, which
7306 // is not very accurate, because our Dyld implementation might find
7307 // a match in location a/b/c.so and if we return just c.so ROOT might
7308 // resolve it to y/z/c.so and there we might not be ABI compatible.
7309 // FIXME: Teach the users of GetSharedLibDeps to work with full paths.
7310 if (!found.empty()) {
7311 std::string cand = llvm::sys::path::filename(found).str();
7312 if (!DedupSet.insert(cand).second)
7313 continue;
7314
7315 Result += cand + ' ';
7316 }
7317 }
7318
7319 return Result;
7320}
7321
7322static bool hasParsedRootmapForLibrary(llvm::StringRef lib)
7323{
7324 // Check if we have parsed a rootmap file.
7325 llvm::SmallString<256> rootmapName;
7326 if (!lib.starts_with("lib"))
7327 rootmapName.append("lib");
7328
7329 rootmapName.append(llvm::sys::path::filename(lib));
7330 llvm::sys::path::replace_extension(rootmapName, "rootmap");
7331
7332 if (gCling->GetRootMapFiles()->FindObject(rootmapName.c_str()))
7333 return true;
7334
7335 // Perform a last resort by dropping the lib prefix.
7336 llvm::StringRef rootmapNameNoLib = rootmapName.str();
7337 if (rootmapNameNoLib.consume_front("lib"))
7338 return gCling->GetRootMapFiles()->FindObject(rootmapNameNoLib.data());
7339
7340 return false;
7341}
7342
7343static bool hasPrecomputedLibraryDeps(llvm::StringRef lib)
7344{
7345 if (gCling->HasPCMForLibrary(lib.data()))
7346 return true;
7347
7348 return hasParsedRootmapForLibrary(lib);
7349}
7350
7351////////////////////////////////////////////////////////////////////////////////
7352/// Get the list a libraries on which the specified lib depends. The
7353/// returned string contains as first element the lib itself.
7354/// Returns 0 in case the lib does not exist or does not have
7355/// any dependencies. If useDyld is true, we iterate through all available
7356/// libraries and try to construct the dependency chain by resolving each
7357/// symbol.
7358
7359const char* TCling::GetSharedLibDeps(const char* lib, bool useDyld/* = false*/)
7360{
7361 if (llvm::sys::path::is_absolute(lib) && !llvm::sys::fs::exists(lib))
7362 return nullptr;
7363
7364 if (!hasParsedRootmapForLibrary(lib)) {
7365 llvm::SmallString<512> rootmapName(lib);
7366 llvm::sys::path::replace_extension(rootmapName, "rootmap");
7367 if (llvm::sys::fs::exists(rootmapName)) {
7368 if (gDebug > 0)
7369 Info("Load", "loading %s", rootmapName.c_str());
7370 gInterpreter->LoadLibraryMap(rootmapName.c_str());
7371 }
7372 }
7373
7374 if (hasPrecomputedLibraryDeps(lib) && useDyld) {
7375 if (gDebug > 0)
7376 Warning("TCling::GetSharedLibDeps", "Precomputed dependencies available but scanning '%s'", lib);
7377 }
7378
7379 if (useDyld) {
7381 if (!libs.empty()) {
7382 fAutoLoadLibStorage.push_back(libs);
7383 return fAutoLoadLibStorage.back().c_str();
7384 }
7385 }
7386
7387 if (!fMapfile || !lib || !lib[0]) {
7388 return nullptr;
7389 }
7390 TString libname(lib);
7391 Ssiz_t idx = libname.Last('.');
7392 if (idx != kNPOS) {
7393 libname.Remove(idx);
7394 }
7395 TEnvRec* rec;
7396 TIter next(fMapfile->GetTable());
7397 size_t len = libname.Length();
7398 while ((rec = (TEnvRec*) next())) {
7399 const char* libs = rec->GetValue();
7400 if (!strncmp(libs, libname.Data(), len) && strlen(libs) >= len
7401 && (!libs[len] || libs[len] == ' ' || libs[len] == '.')) {
7402 return libs;
7403 }
7404 }
7405 return nullptr;
7406}
7407
7408////////////////////////////////////////////////////////////////////////////////
7409/// If error messages are disabled, the interpreter should suppress its
7410/// failures and warning messages from stdout.
7411
7413{
7414#if defined(R__MUST_REVISIT)
7415#if R__MUST_REVISIT(6,2)
7416 Warning("IsErrorMessagesEnabled", "Interface not available yet.");
7417#endif
7418#endif
7419 return kTRUE;
7420}
7421
7422////////////////////////////////////////////////////////////////////////////////
7423/// If error messages are disabled, the interpreter should suppress its
7424/// failures and warning messages from stdout. Return the previous state.
7425
7427{
7428#if defined(R__MUST_REVISIT)
7429#if R__MUST_REVISIT(6,2)
7430 Warning("SetErrorMessages", "Interface not available yet.");
7431#endif
7432#endif
7434}
7435
7436////////////////////////////////////////////////////////////////////////////////
7437/// Refresh the list of include paths known to the interpreter and return it
7438/// with -I prepended.
7439
7441{
7443
7444 fIncludePath = "";
7445
7446 llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7447 //false - no system header, true - with flags.
7448 fInterpreter->GetIncludePaths(includePaths, false, true);
7449 if (const size_t nPaths = includePaths.size()) {
7450 assert(!(nPaths & 1) && "GetIncludePath, number of paths and options is not equal");
7451
7452 for (size_t i = 0; i < nPaths; i += 2) {
7453 if (i)
7454 fIncludePath.Append(' ');
7455 fIncludePath.Append(includePaths[i].c_str());
7456
7457 if (includePaths[i] != "-I")
7458 fIncludePath.Append(' ');
7459 fIncludePath.Append('"');
7461 fIncludePath.Append('"');
7462 }
7463 }
7464
7465 return fIncludePath;
7466}
7467
7468////////////////////////////////////////////////////////////////////////////////
7469/// Return the directory containing CINT's stl cintdlls.
7470
7471const char* TCling::GetSTLIncludePath() const
7472{
7473 return "";
7474}
7475
7476//______________________________________________________________________________
7477// M I S C
7478//______________________________________________________________________________
7479
7480int TCling::DisplayClass(FILE* /*fout*/, const char* /*name*/, int /*base*/, int /*start*/) const
7481{
7482 // Interface to cling function
7483 return 0;
7484}
7485
7486////////////////////////////////////////////////////////////////////////////////
7487/// Interface to cling function
7488
7490{
7491 assert(fout != nullptr && "DisplayIncludePath, 'fout' parameter is null");
7492
7493 llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7494 //false - no system header, true - with flags.
7495 fInterpreter->GetIncludePaths(includePaths, false, true);
7496 if (const size_t nPaths = includePaths.size()) {
7497 assert(!(nPaths & 1) && "DisplayIncludePath, number of paths and options is not equal");
7498
7499 std::string allIncludes("include path:");
7500 for (size_t i = 0; i < nPaths; i += 2) {
7501 allIncludes += ' ';
7503
7504 if (includePaths[i] != "-I")
7505 allIncludes += ' ';
7506 allIncludes += includePaths[i + 1];
7507 }
7508
7509 fprintf(fout, "%s\n", allIncludes.c_str());
7510 }
7511
7512 return 0;
7513}
7514
7515////////////////////////////////////////////////////////////////////////////////
7516/// Interface to cling function
7517
7518void* TCling::FindSym(const char* entry) const
7519{
7521 return fInterpreter->getAddressOfGlobal(entry);
7522}
7523
7524////////////////////////////////////////////////////////////////////////////////
7525/// Let the interpreter issue a generic error, and set its error state.
7526
7527void TCling::GenericError(const char* error) const
7528{
7529#if defined(R__MUST_REVISIT)
7530#if R__MUST_REVISIT(6,2)
7531 Warning("GenericError","Interface not available yet.");
7532#endif
7533#endif
7534}
7535
7536////////////////////////////////////////////////////////////////////////////////
7537/// This routines used to return the address of the internal wrapper
7538/// function (of the interpreter) that was used to call *all* the
7539/// interpreted functions that were bytecode compiled (no longer
7540/// interpreted line by line). In Cling, there is no such
7541/// wrapper function.
7542/// In practice this routines was use to decipher whether the
7543/// pointer returns by InterfaceMethod could be used to uniquely
7544/// represent the function. In Cling if the function is in a
7545/// useable state (its compiled version is available), this is
7546/// always the case.
7547/// See TClass::GetMethod.
7548
7550{
7551 return 0;
7552}
7553
7554////////////////////////////////////////////////////////////////////////////////
7555/// Interface to cling function
7556
7558{
7559#if defined(R__MUST_REVISIT)
7560#if R__MUST_REVISIT(6,2)
7561 Warning("GetSecurityError", "Interface not available yet.");
7562#endif
7563#endif
7564 return 0;
7565}
7566
7567////////////////////////////////////////////////////////////////////////////////
7568/// Load a source file or library called path into the interpreter.
7569
7570int TCling::LoadFile(const char* path) const
7571{
7572 // Modifying the interpreter state needs locking.
7574 cling::Interpreter::CompilationResult compRes;
7575 HandleInterpreterException(GetMetaProcessorImpl(), TString::Format(".L %s", path), compRes, /*cling::Value*/nullptr);
7576 return compRes == cling::Interpreter::kFailure;
7577}
7578
7579////////////////////////////////////////////////////////////////////////////////
7580/// Load the declarations from text into the interpreter.
7581/// Note that this cannot be (top level) statements; text must contain
7582/// top level declarations.
7583/// Returns true on success, false on failure.
7584
7585Bool_t TCling::LoadText(const char* text) const
7586{
7587 return (fInterpreter->declare(text) == cling::Interpreter::kSuccess);
7588}
7589
7590////////////////////////////////////////////////////////////////////////////////
7591/// Interface to cling function
7592
7593const char* TCling::MapCppName(const char* name) const
7594{
7595 TTHREAD_TLS_DECL(std::string,buffer);
7597 return buffer.c_str(); // NOLINT
7598}
7599
7600////////////////////////////////////////////////////////////////////////////////
7601/// [Place holder for Mutex Lock]
7602/// Provide the interpreter with a way to
7603/// acquire a lock used to protect critical section
7604/// of its code (non-thread safe parts).
7605
7606void TCling::SetAlloclockfunc(void (* /* p */ )()) const
7607{
7608 // nothing to do for now.
7609}
7610
7611////////////////////////////////////////////////////////////////////////////////
7612/// [Place holder for Mutex Unlock] Provide the interpreter with a way to
7613/// release a lock used to protect critical section
7614/// of its code (non-thread safe parts).
7615
7616void TCling::SetAllocunlockfunc(void (* /* p */ )()) const
7617{
7618 // nothing to do for now.
7619}
7620
7621////////////////////////////////////////////////////////////////////////////////
7622/// Returns if class AutoLoading is currently enabled.
7623
7625{
7626 if (IsFromRootCling())
7627 return false;
7628 if (!fClingCallbacks)
7629 return false;
7631}
7632
7633////////////////////////////////////////////////////////////////////////////////
7634/// Enable/Disable the AutoLoading of libraries.
7635/// Returns the old value, i.e whether it was enabled or not.
7636
7638{
7639 // If no state change is required, exit early.
7640 // FIXME: In future we probably want to complain if we made a request which
7641 // was with the same state as before in order to catch programming errors.
7642 if ((bool) autoload == IsClassAutoLoadingEnabled())
7643 return autoload;
7644
7645 assert(fClingCallbacks && "We must have callbacks!");
7648 return oldVal;
7649}
7650
7651////////////////////////////////////////////////////////////////////////////////
7652/// Enable/Disable the Autoparsing of headers.
7653/// Returns the old value, i.e whether it was enabled or not.
7654
7661
7662////////////////////////////////////////////////////////////////////////////////
7663/// Suspend the Autoparsing of headers.
7664/// Returns the old value, i.e whether it was suspended or not.
7665
7672
7673////////////////////////////////////////////////////////////////////////////////
7674/// Set a callback to receive error messages.
7675
7677{
7678#if defined(R__MUST_REVISIT)
7679#if R__MUST_REVISIT(6,2)
7680 Warning("SetErrmsgcallback", "Interface not available yet.");
7681#endif
7682#endif
7683}
7684
7686{
7687 if (enable) {
7689 &fInterpreter->getDiagnostics().getDiagnosticOptions(),
7690 fInterpreter->getCI()->getLangOpts(),
7691 [] (clang::DiagnosticsEngine::Level Level, const std::string &Info) {
7692 if (Level == clang::DiagnosticsEngine::Warning) {
7693 ::Warning("cling", "%s", Info.c_str());
7694 } else if (Level == clang::DiagnosticsEngine::Error
7695 || Level == clang::DiagnosticsEngine::Fatal) {
7696 ::Error("cling", "%s", Info.c_str());
7697 } else {
7698 ::Info("cling", "%s", Info.c_str());
7699 }
7700 });
7701 fInterpreter->replaceDiagnosticConsumer(consumer, /*Own=*/true);
7702 } else {
7703 fInterpreter->replaceDiagnosticConsumer(nullptr);
7704 }
7705}
7706
7707
7708////////////////////////////////////////////////////////////////////////////////
7709/// Create / close a scope for temporaries. No-op for cling; use
7710/// cling::Value instead.
7711
7712void TCling::SetTempLevel(int val) const
7713{
7714}
7715
7716////////////////////////////////////////////////////////////////////////////////
7717
7718int TCling::UnloadFile(const char* path) const
7719{
7720 // Modifying the interpreter state needs locking.
7722 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
7723 std::string canonical = DLM->lookupLibrary(path);
7724 if (canonical.empty()) {
7725 canonical = path;
7726 }
7727 // Unload a shared library or a source file.
7728 cling::Interpreter::CompilationResult compRes;
7729 HandleInterpreterException(GetMetaProcessorImpl(), Form(".U %s", canonical.c_str()), compRes, /*cling::Value*/nullptr);
7730 return compRes == cling::Interpreter::kFailure;
7731}
7732
7733std::unique_ptr<TInterpreterValue> TCling::MakeInterpreterValue() const {
7734 return std::unique_ptr<TInterpreterValue>(new TClingValue);
7735}
7736
7737////////////////////////////////////////////////////////////////////////////////
7738/// The call to Cling's tab complition.
7739
7740void TCling::CodeComplete(const std::string& line, size_t& cursor,
7741 std::vector<std::string>& completions)
7742{
7743 fInterpreter->codeComplete(line, cursor, completions);
7744}
7745
7746////////////////////////////////////////////////////////////////////////////////
7747/// Get the interpreter value corresponding to the statement.
7749{
7751
7752 auto V = reinterpret_cast<cling::Value*>(value.GetValAddr());
7753 auto compRes = fInterpreter->evaluate(code, *V);
7754 return compRes!=cling::Interpreter::kSuccess ? 0 : 1 ;
7755}
7756
7757////////////////////////////////////////////////////////////////////////////////
7758
7760{
7761 using namespace cling;
7762 const Value* V = reinterpret_cast<const Value*>(value.GetValAddr());
7764}
7765
7766////////////////////////////////////////////////////////////////////////////////
7767/// Register value as a temporary, extending its lifetime to that of the
7768/// interpreter. This is needed for TCling's compatibility interfaces
7769/// returning long - the address of the temporary objects.
7770/// As such, "simple" types don't need to be stored; they are returned by
7771/// value; only pointers / references / objects need to be stored.
7772
7773void TCling::RegisterTemporary(const cling::Value& value)
7774{
7775 if (value.isValid() && value.needsManagedAllocation()) {
7777 fTemporaries->push_back(value);
7778 }
7779}
7780
7781////////////////////////////////////////////////////////////////////////////////
7782/// If the interpreter encounters Name, check whether that is an object ROOT
7783/// could retrieve. To not re-read objects from disk, cache the name/object
7784/// pair for a given LookupCtx.
7785
7787{
7788 // The call to FindSpecialObject might induces any kind of use
7789 // of the interpreter ... (library loading, function calling, etc.)
7790 // ... and we _know_ we are in the middle of parsing, so let's make
7791 // sure to save the state and then restore it.
7792
7793 if (gDirectory) {
7795 if (iSpecObjMap != fSpecialObjectMaps.end()) {
7796 auto iSpecObj = iSpecObjMap->second.find(Name);
7797 if (iSpecObj != iSpecObjMap->second.end()) {
7799 return iSpecObj->second;
7800 }
7801 }
7802 }
7803
7804 // Save state of the PP
7805 Sema &SemaR = fInterpreter->getSema();
7806 ASTContext& C = SemaR.getASTContext();
7807 Preprocessor &PP = SemaR.getPreprocessor();
7808 Parser& P = const_cast<Parser&>(fInterpreter->getParser());
7809 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
7810 Parser::ParserCurTokRestoreRAII savedCurToken(P);
7811 // After we have saved the token reset the current one to something which
7812 // is safe (semi colon usually means empty decl)
7813 Token& Tok = const_cast<Token&>(P.getCurToken());
7814 Tok.setKind(tok::semi);
7815
7816 // We can't PushDeclContext, because we go up and the routine that pops
7817 // the DeclContext assumes that we drill down always.
7818 // We have to be on the global context. At that point we are in a
7819 // wrapper function so the parent context must be the global.
7820 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(),
7821 SemaR.TUScope);
7822
7823 TObject* specObj = gROOT->FindSpecialObject(Name, LookupCtx);
7824 if (specObj) {
7825 if (!LookupCtx) {
7826 Error("GetObjectAddress", "Got a special object without LookupCtx!");
7827 } else {
7829 }
7830 }
7831 return specObj;
7832}
7833
7834////////////////////////////////////////////////////////////////////////////////
7835/// Inject function as a friend into klass.
7836/// With function being f in void f() {new N::PrivKlass(); } this enables
7837/// I/O of non-public classes.
7838
7839void TCling::AddFriendToClass(clang::FunctionDecl* function,
7840 clang::CXXRecordDecl* klass) const
7841{
7842 using namespace clang;
7843 ASTContext& Ctx = klass->getASTContext();
7844 FriendDecl::FriendUnion friendUnion(function);
7845 // one dummy object for the source location
7847 FriendDecl* friendDecl = FriendDecl::Create(Ctx, klass, sl, friendUnion, sl);
7848 klass->pushFriendDecl(friendDecl);
7849}
7850
7851//______________________________________________________________________________
7852//
7853// DeclId getter.
7854//
7855
7856////////////////////////////////////////////////////////////////////////////////
7857/// Return a unique identifier of the declaration represented by the
7858/// CallFunc
7859
7861{
7862 if (func) return ((TClingCallFunc*)func)->GetDecl()->getCanonicalDecl();
7863 return nullptr;
7864}
7865
7866////////////////////////////////////////////////////////////////////////////////
7867/// Return a (almost) unique identifier of the declaration represented by the
7868/// ClassInfo. In ROOT, this identifier can point to more than one TClass
7869/// when the underlying class is a template instance involving one of the
7870/// opaque typedef.
7871
7873{
7874 if (cinfo) return ((TClingClassInfo*)cinfo)->GetDeclId();
7875 return nullptr;
7876}
7877
7878////////////////////////////////////////////////////////////////////////////////
7879/// Return a unique identifier of the declaration represented by the
7880/// MethodInfo
7881
7883{
7884 if (data) return ((TClingDataMemberInfo*)data)->GetDeclId();
7885 return nullptr;
7886}
7887
7888////////////////////////////////////////////////////////////////////////////////
7889/// Return a unique identifier of the declaration represented by the
7890/// MethodInfo
7891
7893{
7894 if (method) return ((TClingMethodInfo*)method)->GetDeclId();
7895 return nullptr;
7896}
7897
7898////////////////////////////////////////////////////////////////////////////////
7899/// Return a unique identifier of the declaration represented by the
7900/// TypedefInfo
7901
7903{
7904 if (tinfo) return ((TClingTypedefInfo*)tinfo)->GetDecl()->getCanonicalDecl();
7905 return nullptr;
7906}
7907
7908//______________________________________________________________________________
7909//
7910// CallFunc interface
7911//
7912
7913////////////////////////////////////////////////////////////////////////////////
7914
7916{
7917 delete (TClingCallFunc*) func;
7918}
7919
7920////////////////////////////////////////////////////////////////////////////////
7921
7922void TCling::CallFunc_Exec(CallFunc_t* func, void* address) const
7923{
7924 TClingCallFunc* f = (TClingCallFunc*) func;
7925 f->Exec(address);
7926}
7927
7928////////////////////////////////////////////////////////////////////////////////
7929
7930void TCling::CallFunc_Exec(CallFunc_t* func, void* address, TInterpreterValue& val) const
7931{
7932 TClingCallFunc* f = (TClingCallFunc*) func;
7933 f->Exec(address, &val);
7934}
7935
7936////////////////////////////////////////////////////////////////////////////////
7937
7938void TCling::CallFunc_ExecWithReturn(CallFunc_t* func, void* address, void* ret) const
7939{
7940 TClingCallFunc* f = (TClingCallFunc*) func;
7941 f->ExecWithReturn(address, ret);
7942}
7943
7944////////////////////////////////////////////////////////////////////////////////
7945
7947 const void* args[] /*=0*/,
7948 int nargs /*=0*/,
7949 void* ret/*=0*/) const
7950{
7951 TClingCallFunc* f = (TClingCallFunc*) func;
7952 f->ExecWithArgsAndReturn(address, args, nargs, ret);
7953}
7954
7955////////////////////////////////////////////////////////////////////////////////
7956
7958{
7959 TClingCallFunc* f = (TClingCallFunc*) func;
7960 return f->ExecInt(address);
7961}
7962
7963////////////////////////////////////////////////////////////////////////////////
7964
7966{
7967 TClingCallFunc* f = (TClingCallFunc*) func;
7968 return f->ExecInt64(address);
7969}
7970
7971////////////////////////////////////////////////////////////////////////////////
7972
7974{
7975 TClingCallFunc* f = (TClingCallFunc*) func;
7976 return f->ExecDouble(address);
7977}
7978
7979////////////////////////////////////////////////////////////////////////////////
7980
7986
7987////////////////////////////////////////////////////////////////////////////////
7988
7990{
7991 return (CallFunc_t*) new TClingCallFunc(*(TClingCallFunc*)func);
7992}
7993
7994////////////////////////////////////////////////////////////////////////////////
7995
7997{
7998 TClingCallFunc* f = (TClingCallFunc*) func;
7999 return (MethodInfo_t*) f->FactoryMethod();
8000}
8001
8002////////////////////////////////////////////////////////////////////////////////
8003
8005{
8006 TClingCallFunc* f = (TClingCallFunc*) func;
8007 f->IgnoreExtraArgs(ignore);
8008}
8009
8010////////////////////////////////////////////////////////////////////////////////
8011
8013{
8015 TClingCallFunc* f = (TClingCallFunc*) func;
8016 f->Init();
8017}
8018
8019////////////////////////////////////////////////////////////////////////////////
8020
8022{
8023 TClingCallFunc* f = (TClingCallFunc*) func;
8024 return f->IsValid();
8025}
8026
8027////////////////////////////////////////////////////////////////////////////////
8028
8031{
8032 TClingCallFunc* f = (TClingCallFunc*) func;
8033 return f->IFacePtr();
8034}
8035
8036////////////////////////////////////////////////////////////////////////////////
8037
8039{
8040 TClingCallFunc* f = (TClingCallFunc*) func;
8041 f->ResetArg();
8042}
8043
8044////////////////////////////////////////////////////////////////////////////////
8045
8047{
8048 TClingCallFunc* f = (TClingCallFunc*) func;
8049 f->SetArg(param);
8050}
8051
8052////////////////////////////////////////////////////////////////////////////////
8053
8055{
8056 TClingCallFunc* f = (TClingCallFunc*) func;
8057 f->SetArg(param);
8058}
8059
8060////////////////////////////////////////////////////////////////////////////////
8061
8063{
8064 TClingCallFunc* f = (TClingCallFunc*) func;
8065 f->SetArg(param);
8066}
8067
8068////////////////////////////////////////////////////////////////////////////////
8069
8071{
8072 TClingCallFunc* f = (TClingCallFunc*) func;
8073 f->SetArg(param);
8074}
8075
8076////////////////////////////////////////////////////////////////////////////////
8077
8079{
8080 TClingCallFunc* f = (TClingCallFunc*) func;
8081 f->SetArg(param);
8082}
8083
8084////////////////////////////////////////////////////////////////////////////////
8085
8087{
8088 TClingCallFunc* f = (TClingCallFunc*) func;
8089 f->SetArg(param);
8090}
8091
8092////////////////////////////////////////////////////////////////////////////////
8093
8095{
8096 TClingCallFunc* f = (TClingCallFunc*) func;
8097 f->SetArgArray(paramArr, nparam);
8098}
8099
8100////////////////////////////////////////////////////////////////////////////////
8101
8102void TCling::CallFunc_SetArgs(CallFunc_t* func, const char* param) const
8103{
8104 TClingCallFunc* f = (TClingCallFunc*) func;
8105 f->SetArgs(param);
8106}
8107
8108////////////////////////////////////////////////////////////////////////////////
8109
8110void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, Longptr_t* offset) const
8111{
8112 TClingCallFunc* f = (TClingCallFunc*) func;
8114 f->SetFunc(ci, method, params, offset);
8115}
8116
8117////////////////////////////////////////////////////////////////////////////////
8118
8119void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, bool objectIsConst, Longptr_t* offset) const
8120{
8121 TClingCallFunc* f = (TClingCallFunc*) func;
8123 f->SetFunc(ci, method, params, objectIsConst, offset);
8124}
8125////////////////////////////////////////////////////////////////////////////////
8126
8127void TCling::CallFunc_SetFunc(CallFunc_t* func, MethodInfo_t* info) const
8128{
8129 TClingCallFunc* f = (TClingCallFunc*) func;
8131 f->SetFunc(minfo);
8132}
8133
8134////////////////////////////////////////////////////////////////////////////////
8135/// Interface to cling function
8136
8137void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8138{
8139 TClingCallFunc* f = (TClingCallFunc*) func;
8141 f->SetFuncProto(ci, method, proto, offset, mode);
8142}
8143
8144////////////////////////////////////////////////////////////////////////////////
8145/// Interface to cling function
8146
8147void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, bool objectIsConst, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8148{
8149 TClingCallFunc* f = (TClingCallFunc*) func;
8151 f->SetFuncProto(ci, method, proto, objectIsConst, offset, mode);
8152}
8153
8154////////////////////////////////////////////////////////////////////////////////
8155/// Interface to cling function
8156
8157void 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
8158{
8159 TClingCallFunc* f = (TClingCallFunc*) func;
8161 llvm::SmallVector<clang::QualType, 4> funcProto;
8162 for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
8163 iter != end; ++iter) {
8164 funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
8165 }
8166 f->SetFuncProto(ci, method, funcProto, offset, mode);
8167}
8168
8169////////////////////////////////////////////////////////////////////////////////
8170/// Interface to cling function
8171
8172void 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
8173{
8174 TClingCallFunc* f = (TClingCallFunc*) func;
8176 llvm::SmallVector<clang::QualType, 4> funcProto;
8177 for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
8178 iter != end; ++iter) {
8179 funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
8180 }
8181 f->SetFuncProto(ci, method, funcProto, objectIsConst, offset, mode);
8182}
8183
8185{
8186 TClingCallFunc *f = (TClingCallFunc *)func;
8187 std::string wrapper_name;
8188 std::string wrapper;
8189 f->get_wrapper_code(wrapper_name, wrapper);
8190 return wrapper;
8191}
8192
8193//______________________________________________________________________________
8194//
8195// ClassInfo interface
8196//
8197
8198////////////////////////////////////////////////////////////////////////////////
8199/// Return true if the entity pointed to by 'declid' is declared in
8200/// the context described by 'info'. If info is null, look into the
8201/// global scope (translation unit scope).
8202
8204{
8205 if (!declid)
8206 return kFALSE;
8207
8208 const clang::DeclContext *ctxt = nullptr;
8209 if (info) {
8210 ctxt = clang::Decl::castToDeclContext(((TClingClassInfo*)info)->GetDecl());
8211 } else {
8212 ctxt = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
8213 }
8214 if (!ctxt)
8215 return kFALSE;
8216
8217 const clang::Decl *decl = reinterpret_cast<const clang::Decl*>(declid);
8218 if (!decl)
8219 return kFALSE;
8220
8221 const clang::DeclContext *declDC = decl->getDeclContext();
8222 // ClassInfo_t-s are always "spellable" scopes, never unnamed or inline ones.
8223 while (true) {
8224 if (declDC->isTransparentContext()) {
8225 declDC = declDC->getParent();
8226 continue;
8227 }
8228 if (const auto *declRD = llvm::dyn_cast<clang::RecordDecl>(declDC)) {
8229 if (declRD->isAnonymousStructOrUnion()) {
8230 declDC = declRD->getParent();
8231 continue;
8232 }
8233 }
8234 if (const auto *declNS = llvm::dyn_cast<clang::NamespaceDecl>(declDC)) {
8235 if (declNS->isAnonymousNamespace() || declNS->isInlineNamespace()) {
8236 declDC = declNS->getParent();
8237 continue;
8238 }
8239 }
8240 break;
8241 }
8242
8243 return declDC->Equals(ctxt);
8244}
8245
8246////////////////////////////////////////////////////////////////////////////////
8247
8253
8254////////////////////////////////////////////////////////////////////////////////
8255
8257{
8258 delete (TClingClassInfo*) cinfo;
8259}
8260
8261////////////////////////////////////////////////////////////////////////////////
8262
8268
8269////////////////////////////////////////////////////////////////////////////////
8270
8276
8277////////////////////////////////////////////////////////////////////////////////
8278
8284
8285////////////////////////////////////////////////////////////////////////////////
8286
8292
8293////////////////////////////////////////////////////////////////////////////////
8294
8299
8300////////////////////////////////////////////////////////////////////////////////
8301
8307
8313
8314
8315////////////////////////////////////////////////////////////////////////////////
8316
8317int TCling::ClassInfo_GetMethodNArg(ClassInfo_t* cinfo, const char* method, const char* proto, Bool_t objectIsConst /* = false */, EFunctionMatchMode mode /* = kConversionMatch */) const
8318{
8320 return TClinginfo->GetMethodNArg(method, proto, objectIsConst, mode);
8321}
8322
8323////////////////////////////////////////////////////////////////////////////////
8324
8330
8331////////////////////////////////////////////////////////////////////////////////
8332
8334{
8336 return TClinginfo->HasMethod(name);
8337}
8338
8339////////////////////////////////////////////////////////////////////////////////
8340
8347
8348////////////////////////////////////////////////////////////////////////////////
8349
8351{
8354 TClinginfo->Init(tagnum);
8355}
8356
8357////////////////////////////////////////////////////////////////////////////////
8358
8360{
8362 return TClinginfo->IsBase(name);
8363}
8364
8365////////////////////////////////////////////////////////////////////////////////
8366
8367bool TCling::ClassInfo_IsEnum(const char* name) const
8368{
8370}
8371
8372////////////////////////////////////////////////////////////////////////////////
8373
8379
8380
8381////////////////////////////////////////////////////////////////////////////////
8382
8388
8389
8390////////////////////////////////////////////////////////////////////////////////
8391
8393{
8395 return TClinginfo->IsLoaded();
8396}
8397
8398////////////////////////////////////////////////////////////////////////////////
8399
8401{
8403 return TClinginfo->IsValid();
8404}
8405
8406////////////////////////////////////////////////////////////////////////////////
8407
8408bool TCling::ClassInfo_IsValidMethod(ClassInfo_t* cinfo, const char* method, const char* proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8409{
8411 return TClinginfo->IsValidMethod(method, proto, false, offset, mode);
8412}
8413
8414////////////////////////////////////////////////////////////////////////////////
8415
8417{
8419 return TClinginfo->IsValidMethod(method, proto, objectIsConst, offset, mode);
8420}
8421
8422////////////////////////////////////////////////////////////////////////////////
8423
8429
8430////////////////////////////////////////////////////////////////////////////////
8431
8437
8438////////////////////////////////////////////////////////////////////////////////
8439
8445
8446////////////////////////////////////////////////////////////////////////////////
8447
8449{
8451 return TClinginfo->New(n, arena,*fNormalizedCtxt);
8452}
8453
8454////////////////////////////////////////////////////////////////////////////////
8455
8461
8462////////////////////////////////////////////////////////////////////////////////
8463
8469
8470////////////////////////////////////////////////////////////////////////////////
8471
8477
8478////////////////////////////////////////////////////////////////////////////////
8479
8485
8486////////////////////////////////////////////////////////////////////////////////
8487
8489{
8491 return TClinginfo->FileName();
8492}
8493
8494////////////////////////////////////////////////////////////////////////////////
8495
8497{
8499 TTHREAD_TLS_DECL(std::string,output);
8500 TClinginfo->FullName(output,*fNormalizedCtxt);
8501 return output.c_str(); // NOLINT
8502}
8503
8504////////////////////////////////////////////////////////////////////////////////
8505
8507{
8509 return TClinginfo->Name();
8510}
8511
8512////////////////////////////////////////////////////////////////////////////////
8513
8515{
8517 return TClinginfo->Title();
8518}
8519
8520////////////////////////////////////////////////////////////////////////////////
8521
8523{
8525 return TClinginfo->TmpltName();
8526}
8527
8528
8529
8530//______________________________________________________________________________
8531//
8532// BaseClassInfo interface
8533//
8534
8535////////////////////////////////////////////////////////////////////////////////
8536
8541
8542////////////////////////////////////////////////////////////////////////////////
8543
8550
8551////////////////////////////////////////////////////////////////////////////////
8552
8561
8562////////////////////////////////////////////////////////////////////////////////
8563
8569
8570////////////////////////////////////////////////////////////////////////////////
8571
8577
8578////////////////////////////////////////////////////////////////////////////////
8579
8585
8586////////////////////////////////////////////////////////////////////////////////
8587
8589{
8592 // Offset to the class itself.
8593 if (TClinginfo->GetDecl() == TClinginfoBase->GetDecl()) {
8594 return 0;
8595 }
8596 return TClinginfo->GetBaseOffset(TClinginfoBase, address, isDerivedObject);
8597}
8598
8599////////////////////////////////////////////////////////////////////////////////
8600
8606
8607////////////////////////////////////////////////////////////////////////////////
8608
8614
8615////////////////////////////////////////////////////////////////////////////////
8616
8622
8623////////////////////////////////////////////////////////////////////////////////
8624
8626{
8628 TTHREAD_TLS_DECL(std::string,output);
8629 TClinginfo->FullName(output,*fNormalizedCtxt);
8630 return output.c_str(); // NOLINT
8631}
8632
8633////////////////////////////////////////////////////////////////////////////////
8634
8640
8641////////////////////////////////////////////////////////////////////////////////
8642
8648
8649//______________________________________________________________________________
8650//
8651// DataMemberInfo interface
8652//
8653
8654////////////////////////////////////////////////////////////////////////////////
8655
8661
8662////////////////////////////////////////////////////////////////////////////////
8663
8668
8669////////////////////////////////////////////////////////////////////////////////
8670
8677
8678////////////////////////////////////////////////////////////////////////////////
8679
8681{
8683 const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
8684 const clang::ValueDecl* vd = llvm::dyn_cast_or_null<clang::ValueDecl>(decl);
8686}
8687
8688////////////////////////////////////////////////////////////////////////////////
8689
8695
8696////////////////////////////////////////////////////////////////////////////////
8697
8703
8704////////////////////////////////////////////////////////////////////////////////
8705
8711
8712////////////////////////////////////////////////////////////////////////////////
8713
8719
8720////////////////////////////////////////////////////////////////////////////////
8721
8727
8728////////////////////////////////////////////////////////////////////////////////
8729
8735
8736////////////////////////////////////////////////////////////////////////////////
8737
8743
8744////////////////////////////////////////////////////////////////////////////////
8745
8751
8752////////////////////////////////////////////////////////////////////////////////
8753
8759
8760////////////////////////////////////////////////////////////////////////////////
8761
8767
8768////////////////////////////////////////////////////////////////////////////////
8769
8775
8776////////////////////////////////////////////////////////////////////////////////
8777
8783
8784////////////////////////////////////////////////////////////////////////////////
8785
8787{
8788 TTHREAD_TLS_DECL(std::string,result);
8789
8791 result = TClinginfo->ValidArrayIndex().str();
8792 return result.c_str(); // NOLINT
8793}
8794
8795////////////////////////////////////////////////////////////////////////////////
8796
8798{
8799 Decl* decl = static_cast<Decl*>(const_cast<void*>(declId));
8800 ASTContext &C = decl->getASTContext();
8801 decl->addAttr(AnnotateAttr::CreateImplicit(C, attribute, nullptr, 0));
8802}
8803
8804//______________________________________________________________________________
8805//
8806// Function Template interface
8807//
8808
8809////////////////////////////////////////////////////////////////////////////////
8810
8811static void ConstructorName(std::string &name, const clang::Decl *decl,
8812 cling::Interpreter &interp,
8814{
8815 const clang::TypeDecl* td = llvm::dyn_cast<clang::TypeDecl>(decl->getDeclContext());
8816 if (!td) return;
8817
8818 clang::QualType qualType(td->getTypeForDecl(),0);
8820 unsigned int level = 0;
8821 for(size_t cursor = name.length()-1; cursor != 0; --cursor) {
8822 if (name[cursor] == '>') ++level;
8823 else if (name[cursor] == '<' && level) --level;
8824 else if (level == 0 && name[cursor] == ':') {
8825 name.erase(0,cursor+1);
8826 break;
8827 }
8828 }
8829}
8830
8831////////////////////////////////////////////////////////////////////////////////
8832
8833void TCling::GetFunctionName(const clang::Decl *decl, std::string &output) const
8834{
8835 output.clear();
8836
8837 const auto *FD = llvm::dyn_cast<clang::FunctionDecl>(decl);
8838 if (const auto *USD = llvm::dyn_cast<clang::UsingShadowDecl>(decl)) {
8839 FD = llvm::dyn_cast<clang::FunctionDecl>(USD->getTargetDecl());
8840 }
8841 if (!FD) {
8842 Error("GetFunctionName", "NULL Decl!");
8843 return;
8844 }
8845
8846 // For using-decls, show "Derived", not "Base", i.e. use the
8847 // name of the decl context of the UsingShadowDecl (aka `decl`)
8848 // not the name of FD's decl context.
8849 if (llvm::isa<clang::CXXConstructorDecl>(FD))
8850 {
8852
8853 } else if (llvm::isa<clang::CXXDestructorDecl>(decl))
8854 {
8856 output.insert(output.begin(), '~');
8857 } else {
8858 llvm::raw_string_ostream stream(output);
8859 auto printPolicy = decl->getASTContext().getPrintingPolicy();
8860 // Don't trigger fopen of the source file to count lines:
8861 printPolicy.AnonymousTagLocations = false;
8862 FD->getNameForDiagnostic(stream, printPolicy, /*Qualified=*/false);
8863 }
8864}
8865
8866////////////////////////////////////////////////////////////////////////////////
8867/// Return a unique identifier of the declaration represented by the
8868/// FuncTempInfo
8869
8874
8875////////////////////////////////////////////////////////////////////////////////
8876/// Delete the FuncTempInfo_t
8877
8879{
8880 // Currently the address of ft_info is actually the decl itself,
8881 // so we have nothing to do.
8882}
8883
8884////////////////////////////////////////////////////////////////////////////////
8885/// Construct a 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 return (FuncTempInfo_t*)const_cast<void*>(declid);
8893}
8894
8895////////////////////////////////////////////////////////////////////////////////
8896/// Construct a FuncTempInfo_t
8897
8899{
8900 // Currently the address of ft_info is actually the decl itself,
8901 // so we have nothing to do.
8902
8903 return (FuncTempInfo_t*)ft_info;
8904}
8905
8906////////////////////////////////////////////////////////////////////////////////
8907/// Check validity of a FuncTempInfo_t
8908
8910{
8911 // Currently the address of ft_info is actually the decl itself,
8912 // so we have nothing to do.
8913
8914 return t_info != nullptr;
8915}
8916
8917////////////////////////////////////////////////////////////////////////////////
8918/// Return the maximum number of template arguments of the
8919/// function template described by ft_info.
8920
8922{
8923 if (!ft_info) return 0;
8924 const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
8925 return ft->getTemplateParameters()->size();
8926}
8927
8928////////////////////////////////////////////////////////////////////////////////
8929/// Return the number of required template arguments of the
8930/// function template described by ft_info.
8931
8933{
8934 if (!ft_info) return 0;
8935 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8936 return ft->getTemplateParameters()->getMinRequiredArguments();
8937}
8938
8939////////////////////////////////////////////////////////////////////////////////
8940/// Return the property of the function template.
8941
8943{
8944 if (!ft_info) return 0;
8945
8946 long property = 0L;
8947 property |= kIsCompiled;
8948
8949 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8950
8951 switch (ft->getAccess()) {
8952 case clang::AS_public:
8953 property |= kIsPublic;
8954 break;
8955 case clang::AS_protected:
8956 property |= kIsProtected;
8957 break;
8958 case clang::AS_private:
8959 property |= kIsPrivate;
8960 break;
8961 case clang::AS_none:
8962 if (ft->getDeclContext()->isNamespace())
8964 break;
8965 default:
8966 // IMPOSSIBLE
8967 assert(false && "Unexpected value for the access property value in Clang");
8968 break;
8969 }
8970
8971 const clang::FunctionDecl *fd = ft->getTemplatedDecl();
8972
8973 if (fd && fd->getStorageClass() == clang::SC_Static)
8974 property |= kIsStatic;
8975
8976 if (const clang::CXXMethodDecl *md =
8977 llvm::dyn_cast<clang::CXXMethodDecl>(fd)) {
8978 if (md->getMethodQualifiers().hasConst()) {
8979 property |= kIsConstant | kIsConstMethod;
8980 }
8981 if (md->isVirtual()) {
8982 property |= kIsVirtual;
8983 }
8984 if (md->isPureVirtual()) {
8985 property |= kIsPureVirtual;
8986 }
8987 if (const clang::CXXConstructorDecl *cd =
8988 llvm::dyn_cast<clang::CXXConstructorDecl>(md)) {
8989 if (cd->isExplicit()) {
8990 property |= kIsExplicit;
8991 }
8992 }
8993 else if (const clang::CXXConversionDecl *cd =
8994 llvm::dyn_cast<clang::CXXConversionDecl>(md)) {
8995 if (cd->isExplicit()) {
8996 property |= kIsExplicit;
8997 }
8998 }
8999 }
9000 return property;
9001}
9002
9003////////////////////////////////////////////////////////////////////////////////
9004/// Return the property not already defined in Property
9005/// See TDictionary's EFunctionProperty
9006
9008{
9009 if (!ft_info) return 0;
9010
9011 long property = 0L;
9012 property |= kIsCompiled;
9013
9014 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9015 const clang::FunctionDecl *fd = ft->getTemplatedDecl();
9016
9017 if (fd->isOverloadedOperator())
9019 if (llvm::isa<clang::CXXConversionDecl>(fd))
9021 if (llvm::isa<clang::CXXConstructorDecl>(fd))
9023 if (llvm::isa<clang::CXXDestructorDecl>(fd))
9025 if (fd->isInlined())
9027 return property;
9028}
9029
9030////////////////////////////////////////////////////////////////////////////////
9031/// Return the name of this function template.
9032
9034{
9035 output.Clear();
9036 if (!ft_info) return;
9037 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9038 std::string buf;
9039 GetFunctionName(ft->getTemplatedDecl(), buf);
9040 output = buf;
9041}
9042
9043////////////////////////////////////////////////////////////////////////////////
9044/// Return the comments associates with this function template.
9045
9047{
9048 output.Clear();
9049 if (!ft_info) return;
9050 const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
9051
9052 // Iterate over the redeclarations, we can have multiple definitions in the
9053 // redecl chain (came from merging of pcms).
9056 if (AnnotateAttr *A = AnnotFD->getAttr<AnnotateAttr>()) {
9057 output = A->getAnnotation().str();
9058 return;
9059 }
9060 }
9061 if (!ft->isFromASTFile()) {
9062 // Try to get the comment from the header file if present
9063 // but not for decls from AST file, where rootcling would have
9064 // created an annotation
9066 }
9067}
9068
9069
9070//______________________________________________________________________________
9071//
9072// MethodInfo interface
9073//
9074
9075////////////////////////////////////////////////////////////////////////////////
9076/// Interface to cling function
9077
9078void TCling::MethodInfo_Delete(MethodInfo_t* minfo) const
9079{
9080 delete(TClingMethodInfo*) minfo;
9081}
9082
9083////////////////////////////////////////////////////////////////////////////////
9084
9086{
9088 // The next call locks the interpreter mutex.
9089 info->CreateSignature(signature);
9090}
9091
9092////////////////////////////////////////////////////////////////////////////////
9093
9094MethodInfo_t* TCling::MethodInfo_Factory() const
9095{
9097 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl());
9098}
9099
9100////////////////////////////////////////////////////////////////////////////////
9101
9103{
9105 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), (TClingClassInfo*)clinfo);
9106}
9107
9108////////////////////////////////////////////////////////////////////////////////
9109
9111{
9112 const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
9114 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), decl);
9115}
9116
9117////////////////////////////////////////////////////////////////////////////////
9118
9119MethodInfo_t* TCling::MethodInfo_FactoryCopy(MethodInfo_t* minfo) const
9120{
9121 return (MethodInfo_t*) new TClingMethodInfo(*(TClingMethodInfo*)minfo);
9122}
9123
9124////////////////////////////////////////////////////////////////////////////////
9125
9127{
9129 // The next call locks the interpreter mutex.
9130 return info->InterfaceMethod();
9131}
9132
9133////////////////////////////////////////////////////////////////////////////////
9134
9135bool TCling::MethodInfo_IsValid(MethodInfo_t* minfo) const
9136{
9138 return info->IsValid();
9139}
9140
9141////////////////////////////////////////////////////////////////////////////////
9142
9143int TCling::MethodInfo_NArg(MethodInfo_t* minfo) const
9144{
9146 return info->NArg();
9147}
9148
9149////////////////////////////////////////////////////////////////////////////////
9150
9152{
9154 return info->NDefaultArg();
9155}
9156
9157////////////////////////////////////////////////////////////////////////////////
9158
9159int TCling::MethodInfo_Next(MethodInfo_t* minfo) const
9160{
9162 return info->Next();
9163}
9164
9165////////////////////////////////////////////////////////////////////////////////
9166
9168{
9170 // The next call locks the interpreter mutex.
9171 return info->Property();
9172}
9173
9174////////////////////////////////////////////////////////////////////////////////
9175
9177{
9179 // The next call locks the interpreter mutex.
9180 return info->ExtraProperty();
9181}
9182
9183////////////////////////////////////////////////////////////////////////////////
9184
9186{
9188 // The next call locks the interpreter mutex.
9189 return (TypeInfo_t*)info->Type();
9190}
9191
9192////////////////////////////////////////////////////////////////////////////////
9193
9194const char* TCling::MethodInfo_GetMangledName(MethodInfo_t* minfo) const
9195{
9198 // The next call locks the interpreter mutex.
9199 mangled_name = info->GetMangledName();
9200 return mangled_name;
9201}
9202
9203////////////////////////////////////////////////////////////////////////////////
9204
9205const char* TCling::MethodInfo_GetPrototype(MethodInfo_t* minfo) const
9206{
9208 // The next call locks the interpreter mutex.
9209 return info->GetPrototype();
9210}
9211
9212////////////////////////////////////////////////////////////////////////////////
9213
9214const char* TCling::MethodInfo_Name(MethodInfo_t* minfo) const
9215{
9217 // The next call locks the interpreter mutex.
9218 return info->Name();
9219}
9220
9221////////////////////////////////////////////////////////////////////////////////
9222
9223const char* TCling::MethodInfo_TypeName(MethodInfo_t* minfo) const
9224{
9226 // The next call locks the interpreter mutex.
9227 return info->TypeName();
9228}
9229
9230////////////////////////////////////////////////////////////////////////////////
9231
9232std::string TCling::MethodInfo_TypeNormalizedName(MethodInfo_t* minfo) const
9233{
9235 // The next part locks the interpreter mutex.
9236 if (info && info->IsValid())
9237 return info->Type()->NormalizedName(*fNormalizedCtxt);
9238 else
9239 return "";
9240}
9241
9242////////////////////////////////////////////////////////////////////////////////
9243
9244const char* TCling::MethodInfo_Title(MethodInfo_t* minfo) const
9245{
9247 // The next call locks the interpreter mutex.
9248 return info->Title();
9249}
9250
9251////////////////////////////////////////////////////////////////////////////////
9252
9254{
9255 if (func) {
9256 return MethodInfo_MethodCallReturnType(func->fInfo);
9257 } else {
9258 return EReturnType::kOther;
9259 }
9260}
9261
9262////////////////////////////////////////////////////////////////////////////////
9263
9265{
9267 if (info && info->IsValid()) {
9268 TClingTypeInfo *typeinfo = info->Type();
9269 clang::QualType QT( typeinfo->GetQualType().getCanonicalType() );
9270 if (QT->isEnumeralType()) {
9271 return EReturnType::kLong;
9272 } else if (QT->isPointerType()) {
9273 // Look for char*
9274 QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
9275 if ( QT->isCharType() ) {
9276 return EReturnType::kString;
9277 } else {
9278 return EReturnType::kOther;
9279 }
9280 } else if ( QT->isFloatingType() ) {
9281 int sz = typeinfo->Size();
9282 if (sz == 4 || sz == 8) {
9283 // Support only float and double.
9284 return EReturnType::kDouble;
9285 } else {
9286 return EReturnType::kOther;
9287 }
9288 } else if ( QT->isIntegerType() ) {
9289 int sz = typeinfo->Size();
9290 if (sz <= 8) {
9291 // Support only up to long long ... but
9292 // FIXME the TMethodCall::Execute only
9293 // return long (4 bytes) ...
9294 // The v5 implementation of TMethodCall::ReturnType
9295 // was not making the distinction so we let it go
9296 // as is for now, but we really need to upgrade
9297 // TMethodCall::Execute ...
9298 return EReturnType::kLong;
9299 } else {
9300 return EReturnType::kOther;
9301 }
9302 } else {
9303 return EReturnType::kOther;
9304 }
9305 } else {
9306 return EReturnType::kOther;
9307 }
9308}
9309
9310//______________________________________________________________________________
9311//
9312// MethodArgInfo interface
9313//
9314
9315////////////////////////////////////////////////////////////////////////////////
9316
9321
9322////////////////////////////////////////////////////////////////////////////////
9323
9329
9330////////////////////////////////////////////////////////////////////////////////
9331
9337
9338////////////////////////////////////////////////////////////////////////////////
9339
9345
9346////////////////////////////////////////////////////////////////////////////////
9347
9353
9354////////////////////////////////////////////////////////////////////////////////
9355
9361
9362////////////////////////////////////////////////////////////////////////////////
9363
9369
9370////////////////////////////////////////////////////////////////////////////////
9371
9373{
9375 return info->DefaultValue();
9376}
9377
9378////////////////////////////////////////////////////////////////////////////////
9379
9381{
9383 return info->Name();
9384}
9385
9386////////////////////////////////////////////////////////////////////////////////
9387
9389{
9391 return info->TypeName();
9392}
9393
9394////////////////////////////////////////////////////////////////////////////////
9395
9397{
9399 return info->Type()->NormalizedName(*fNormalizedCtxt);
9400}
9401
9402////////////////////////////////////////////////////////////////////////////////
9403
9409
9410//______________________________________________________________________________
9411//
9412// TypeInfo interface
9413//
9414
9415////////////////////////////////////////////////////////////////////////////////
9416
9418{
9419 delete (TClingTypeInfo*) tinfo;
9420}
9421
9422////////////////////////////////////////////////////////////////////////////////
9423
9429
9430////////////////////////////////////////////////////////////////////////////////
9431
9437
9438////////////////////////////////////////////////////////////////////////////////
9439
9444
9445////////////////////////////////////////////////////////////////////////////////
9446
9453
9454////////////////////////////////////////////////////////////////////////////////
9455
9457{
9459 return TClinginfo->IsValid();
9460}
9461
9462////////////////////////////////////////////////////////////////////////////////
9463
9465{
9467 return TClinginfo->Name();
9468}
9469
9470////////////////////////////////////////////////////////////////////////////////
9471
9477
9478////////////////////////////////////////////////////////////////////////////////
9479
9481{
9483 return TClinginfo->RefType();
9484}
9485
9486////////////////////////////////////////////////////////////////////////////////
9487
9489{
9491 return TClinginfo->Size();
9492}
9493
9494////////////////////////////////////////////////////////////////////////////////
9495
9497{
9499 return TClinginfo->TrueName(*fNormalizedCtxt);
9500}
9501
9502////////////////////////////////////////////////////////////////////////////////
9503
9505{
9507 return TClinginfo->QualTypePtr();
9508}
9509
9510
9511//______________________________________________________________________________
9512//
9513// TypedefInfo interface
9514//
9515
9516////////////////////////////////////////////////////////////////////////////////
9517
9522
9523////////////////////////////////////////////////////////////////////////////////
9524
9530
9531////////////////////////////////////////////////////////////////////////////////
9532
9538
9539////////////////////////////////////////////////////////////////////////////////
9540
9545
9546////////////////////////////////////////////////////////////////////////////////
9547
9555
9556////////////////////////////////////////////////////////////////////////////////
9557
9563
9564////////////////////////////////////////////////////////////////////////////////
9565
9571
9572////////////////////////////////////////////////////////////////////////////////
9573
9579
9580////////////////////////////////////////////////////////////////////////////////
9581
9587
9588////////////////////////////////////////////////////////////////////////////////
9589
9595
9596////////////////////////////////////////////////////////////////////////////////
9597
9599{
9601 return TClinginfo->Name();
9602}
9603
9604////////////////////////////////////////////////////////////////////////////////
9605
9607{
9609 return TClinginfo->Title();
9610}
9611
9612////////////////////////////////////////////////////////////////////////////////
9613
9614bool TCling::IsSameType(const void * QualTypePtr1, const void * QualTypePtr2) const
9615{
9616 clang::QualType QT1 = clang::QualType::getFromOpaquePtr(QualTypePtr1);
9617 clang::QualType QT2 = clang::QualType::getFromOpaquePtr(QualTypePtr2);
9618 return fInterpreter->getCI()->getASTContext().hasSameType(QT1, QT2);
9619}
9620
9621////////////////////////////////////////////////////////////////////////////////
9622
9623bool TCling::IsIntegerType(const void * QualTypePtr) const
9624{
9625 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9626 return QT->hasIntegerRepresentation();
9627}
9628
9629////////////////////////////////////////////////////////////////////////////////
9630
9631bool TCling::IsSignedIntegerType(const void * QualTypePtr) const
9632{
9633 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9634 return QT->hasSignedIntegerRepresentation();
9635}
9636
9637////////////////////////////////////////////////////////////////////////////////
9638
9639bool TCling::IsUnsignedIntegerType(const void * QualTypePtr) const
9640{
9641 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9642 return QT->hasUnsignedIntegerRepresentation();
9643}
9644
9645////////////////////////////////////////////////////////////////////////////////
9646
9647bool TCling::IsFloatingType(const void * QualTypePtr) const
9648{
9649 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9650 return QT->hasFloatingRepresentation();
9651}
9652
9653////////////////////////////////////////////////////////////////////////////////
9654
9655bool TCling::IsPointerType(const void * QualTypePtr) const
9656{
9657 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9658 return QT->hasPointerRepresentation();
9659}
9660
9661////////////////////////////////////////////////////////////////////////////////
9662
9663bool TCling::IsVoidPointerType(const void * QualTypePtr) const
9664{
9665 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9666 return QT->isVoidPointerType();
9667}
9668
9669////////////////////////////////////////////////////////////////////////////////
9670
9672{
9673 if (!fInitialMutex) {
9675 Error("SnapshotMutexState", "fRecurseCount != 0 even though initial mutex state is unset!");
9676 }
9677 fInitialMutex.fState = mtx->GetStateBefore();
9678 }
9679 // We will "forget" this lock once we backed out of all interpreter frames.
9680 // Here we are entering one, so ++.
9682}
9683
9684////////////////////////////////////////////////////////////////////////////////
9685
9687{
9688 if (!fInitialMutex)
9689 return;
9690 if (fInitialMutex.fRecurseCount == 0) {
9691 Error("ForgetMutexState", "mutex state's recurse count already 0!");
9692 }
9693 else if (--fInitialMutex.fRecurseCount == 0) {
9694 // We have returned from all interpreter frames. Reset the initial lock state.
9695 fInitialMutex.fState.reset();
9696 }
9697}
9698
9699////////////////////////////////////////////////////////////////////////////////
9700/// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
9701
9703{
9704 if (gInterpreterMutex) {
9705 if (delta) {
9706 auto typedDelta = static_cast<MutexStateAndRecurseCountDelta *>(delta);
9707 std::unique_ptr<MutexStateAndRecurseCountDelta> uniqueP{typedDelta};
9708 gCoreMutex->Apply(std::move(typedDelta->fDelta));
9709 // Now that we have the lock, update the global
9710 R__ASSERT(fInitialMutex.fRecurseCount == 0 && "Inconsistent state of fInitialMutex! Another thread within Interpreter critical section.");
9711 std::swap(fInitialMutex, typedDelta->fInitialState);
9712 } else {
9713 // This case happens when EnableThreadSafety is first called from
9714 // the interpreter function we just handled.
9715 // Since thread safety was not enabled at the time we rewound, there was
9716 // no lock taken and even-though we should be locking the rest of this
9717 // interpreter handling/modifying code (since there might be threads in
9718 // flight), we can't because there would not be any lock guard to release the
9719 // locks
9721 Error("ApplyToInterpreterMutex",
9722 "After returning from user code that turned on thread safety support, we notice that fInitialMutex is already used ... "
9723 "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.");
9724 }
9725 }
9726}
9727
9728////////////////////////////////////////////////////////////////////////////////
9729/// Reset the interpreter lock to the state it had before interpreter-related
9730/// calls happened.
9731
9733{
9734 if (fInitialMutex) {
9735 // Need to start a new recurse count.
9736 std::unique_ptr<MutexStateAndRecurseCountDelta> uniqueP(new MutexStateAndRecurseCountDelta());
9737 std::swap(uniqueP->fInitialState, fInitialMutex);
9738 uniqueP->fDelta = gCoreMutex->Rewind(*uniqueP->fInitialState.fState);
9739 return uniqueP.release();
9740 }
9742 return nullptr;
9743}
#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:7322
void TCling__InvalidateGlobal(const clang::Decl *D)
Definition TCling.cxx:590
bool TClingLookupHelper__AutoParse(const char *cname)
Allow calling autoparsing from TMetaUtils.
Definition TCling.cxx:910
R__EXTERN int optind
Definition TCling.cxx:333
void * TCling__LockCompilationDuringUserCodeExecution()
Lock the interpreter.
Definition TCling.cxx:384
void TCling__UpdateListsOnUnloaded(const cling::Transaction &T)
Definition TCling.cxx:585
void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt *&normCtxt)
Definition TCling.cxx:573
int TCling__LoadLibrary(const char *library)
Load a library.
Definition TCling.cxx:349
void TCling__DEBUG__dump(clang::DeclContext *DC)
Definition TCling.cxx:226
bool TClingLookupHelper__CheckInClassTable(const std::string &tname, std::string &result)
Check if the class name is present in TClassTable.
Definition TCling.cxx:1019
ETupleOrdering
Check in what order the member of a tuple are layout.
Definition TCling.cxx:3964
bool TCling__LibraryLoadingFailed(const std::string &errmessage, const std::string &libStem, bool permanent, bool resolved)
Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name, which is extracted by er...
Definition TCling.cxx:367
static const std::unordered_set< std::string > gIgnoredPCMNames
List of dicts that have the PCM information already in the PCH.
Definition TCling.cxx:1986
static Bool_t s_IsLibraryLoaded(const char *libname, cling::Interpreter *fInterpreter)
Definition TCling.cxx:3188
const char * TCling__GetClassSharedLibs(const char *className, bool skipCore)
Definition TCling.cxx:649
static GlobalModuleIndex * loadGlobalModuleIndex(cling::Interpreter &interp)
Definition TCling.cxx:1114
bool TClingLookupHelper__ExistingTypeCheck(const std::string &tname, std::string &result)
Try hard to avoid looking up in the Cling database as this could enduce an unwanted autoparsing.
Definition TCling.cxx:919
static bool HasASTFileOnDisk(clang::Module *M, const clang::Preprocessor &PP, std::string *FullFileName=nullptr)
Checks if there is an ASTFile on disk for the given module M.
Definition TCling.cxx:1099
void TCling__UnlockCompilationDuringUserCodeExecution(void *)
Unlock the interpreter.
Definition TCling.cxx:395
static std::string AlternateTuple(const char *classname, const cling::LookupHelper &lh, Bool_t silent)
Definition TCling.cxx:4006
static bool R__InitStreamerInfoFactory()
Helper to initialize TVirtualStreamerInfo's factor early.
Definition TCling.cxx:1709
int TCling__AutoParseCallback(const char *className)
Definition TCling.cxx:644
clang::RecordDecl * TCling__DEBUG__DCtoRecordDecl(clang::DeclContext *DC)
Definition TCling.cxx:223
int TCling_GenerateDictionary(const std::vector< std::string > &classes, const std::vector< std::string > &headers, const std::vector< std::string > &fwdDecls, const std::vector< std::string > &unknown)
Definition TCling.cxx:715
static bool HaveFullGlobalModuleIndex
Definition TCling.cxx:1113
bool TCling__TEST_isInvalidDecl(clang::Decl *D)
Definition TCling.cxx:253
void TCling__LibraryUnloadedRTTI(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:609
void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter *)
Definition TCling.cxx:580
const Decl * TCling__GetObjectDecl(TObject *obj)
Definition TCling.cxx:620
static ETupleOrdering IsTupleAscending()
Definition TCling.cxx:3982
void TCling__RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
Definition TCling.cxx:604
static void TCling__UpdateClassInfo(const NamedDecl *TD)
Update TClingClassInfo for a class (e.g. upon seeing a definition).
Definition TCling.cxx:405
clang::DeclContext * TCling__DEBUG__getDeclContext(clang::Decl *D)
Definition TCling.cxx:217
int TCling__CompileMacro(const char *fileName, const char *options)
Definition TCling.cxx:660
#define R__DLLEXPORT
Definition TCling.cxx:153
void * TCling__ResetInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:376
void TCling__DEBUG__decl_dump(void *D)
Definition TCling.cxx:235
int TCling__AutoLoadCallback(const char *className)
Definition TCling.cxx:639
static bool LoadModule(const std::string &ModuleName, cling::Interpreter &interp)
Definition TCling.cxx:1064
static void RegisterCxxModules(cling::Interpreter &clingInterp)
Definition TCling.cxx:1217
static void ConstructorName(std::string &name, const clang::Decl *decl, cling::Interpreter &interp, const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt)
Definition TCling.cxx:8811
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:2471
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:7231
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:2011
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:7066
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:6391
static bool requiresRootMap(const char *rootmapfile)
Definition TCling.cxx:5571
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:7343
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:2496
@ 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:3471
ROOT::ESTLType GetCollectionType() const
Return the 'type' of the STL the TClass is representing.
Definition TClass.cxx:2892
void RemoveStreamerInfo(Int_t slot)
Remove and delete the StreamerInfo in the given slot.
Definition TClass.cxx:7418
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:3826
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:4943
static void RemoveClassDeclId(TDictionary::DeclId_t id)
Definition TClass.cxx:603
static Bool_t HasNoInfoOrEmuOrFwdDeclaredDecl(const char *)
Definition TClass.cxx:3430
static TClass * LoadClass(const char *requestedname, Bool_t silent)
Helper function used by TClass::GetClass().
Definition TClass.cxx:5789
Int_t Size() const
Return size of object of this class.
Definition TClass.cxx:5744
@ 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:2903
void ResetCaches()
To clean out all caches.
Definition TClass.cxx:4243
static Int_t ReadRules()
Read the class.rules files from the default location:.
Definition TClass.cxx:1807
@ 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:3495
@ 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:2974
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:6263
const char * MethodArgInfo_DefaultValue(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9372
bool ClassInfo_IsScopedEnum(ClassInfo_t *info) const final
Definition TCling.cxx:8374
const char * TypeInfo_Name(TypeInfo_t *) const final
Definition TCling.cxx:9464
void * MethodInfo_InterfaceMethod(MethodInfo_t *minfo) const final
Definition TCling.cxx:9126
void LoadEnums(TListOfEnums &cl) const final
Create list of pointers to enums for TClass cl.
Definition TCling.cxx:4454
void UpdateListOfGlobals() final
No op: see TClingCallbacks (used to update the list of globals)
Definition TCling.cxx:3944
bool TypedefInfo_IsValid(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9558
Int_t AutoLoad(const char *classname, Bool_t knowDictNotLoaded=kFALSE) final
Load library containing the specified class.
Definition TCling.cxx:6324
void CallFunc_Init(CallFunc_t *func) const final
Definition TCling.cxx:8012
void SetGetline(const char *(*getlineFunc)(const char *prompt), void(*histaddFunc)(const char *line)) final
Set a getline function to call when input is needed.
Definition TCling.cxx:3707
bool LibraryLoadingFailed(const std::string &, const std::string &, bool, bool)
Definition TCling.cxx:6627
void GenericError(const char *error) const final
Let the interpreter issue a generic error, and set its error state.
Definition TCling.cxx:7527
std::vector< void * > fRegisterModuleDyLibs
Definition TCling.h:138
void CallFunc_ExecWithReturn(CallFunc_t *func, void *address, void *ret) const final
Definition TCling.cxx:7938
bool IsIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9623
TypeInfo_t * MethodInfo_Type(MethodInfo_t *minfo) const final
Definition TCling.cxx:9185
std::vector< std::string > fAutoLoadLibStorage
Definition TCling.h:118
void CallFunc_Delete(CallFunc_t *func) const final
Definition TCling.cxx:7915
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:7570
void ResetAll() final
Reset the Cling state to its initial state.
Definition TCling.cxx:3783
void SetDeclAttr(DeclId_t, const char *) final
Definition TCling.cxx:8797
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:6961
Long_t MethodInfo_Property(MethodInfo_t *minfo) const final
Definition TCling.cxx:9167
virtual void LoadFunctionTemplates(TClass *cl) const final
Create list of pointers to function templates for TClass cl.
Definition TCling.cxx:4501
bool ClassInfo_IsValidMethod(ClassInfo_t *info, const char *method, const char *proto, Longptr_t *offset, ROOT::EFunctionMatchMode=ROOT::kConversionMatch) const final
Definition TCling.cxx:8408
Long_t DataMemberInfo_Property(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8730
int SetClassAutoparsing(int) final
Enable/Disable the Autoparsing of headers.
Definition TCling.cxx:7655
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:4548
void RewindDictionary() final
Rewind Cling dictionary to the point where it was before executing the current macro.
Definition TCling.cxx:3828
bool ClassInfo_IsValid(ClassInfo_t *info) const final
Definition TCling.cxx:8400
void UpdateListsOnCommitted(const cling::Transaction &T)
Definition TCling.cxx:6835
int TypeInfo_RefType(TypeInfo_t *) const final
Definition TCling.cxx:9480
void CreateListOfBaseClasses(TClass *cl) const final
Create list of pointers to base class(es) for TClass cl.
Definition TCling.cxx:4430
ClassInfo_t * ClassInfo_Factory(Bool_t all=kTRUE) const final
Definition TCling.cxx:8287
const char * MethodInfo_Name(MethodInfo_t *minfo) const final
Definition TCling.cxx:9214
BaseClassInfo_t * BaseClassInfo_Factory(ClassInfo_t *info) const final
Definition TCling.cxx:8544
Bool_t LoadText(const char *text) const final
Load the declarations from text into the interpreter.
Definition TCling.cxx:7585
const char * GetSharedLibDeps(const char *lib, bool tryDyld=false) final
Get the list a libraries on which the specified lib depends.
Definition TCling.cxx:7359
EReturnType MethodInfo_MethodCallReturnType(MethodInfo_t *minfo) const final
Definition TCling.cxx:9264
TObject * GetObjectAddress(const char *Name, void *&LookupCtx)
If the interpreter encounters Name, check whether that is an object ROOT could retrieve.
Definition TCling.cxx:7786
Longptr_t ProcessLineAsynch(const char *line, EErrorCode *error=nullptr)
Let cling process a command line asynch.
Definition TCling.cxx:3619
bool MethodInfo_IsValid(MethodInfo_t *minfo) const final
Definition TCling.cxx:9135
FuncTempInfo_t * FuncTempInfo_Factory(DeclId_t declid) const final
Construct a FuncTempInfo_t.
Definition TCling.cxx:8887
TypeInfo_t * TypeInfo_Factory() const final
Definition TCling.cxx:9424
bool IsClassAutoLoadingEnabled() const
Returns if class AutoLoading is currently enabled.
Definition TCling.cxx:7624
void InvalidateGlobal(const clang::Decl *D)
Invalidate cached TCling information for the given global declaration.
Definition TCling.cxx:6946
bool IsSameType(const void *QualTypePtr1, const void *QualTypePtr2) const final
Definition TCling.cxx:9614
int Evaluate(const char *, TInterpreterValue &) final
Get the interpreter value corresponding to the statement.
Definition TCling.cxx:7748
std::unique_ptr< TInterpreterValue > MakeInterpreterValue() const final
Definition TCling.cxx:7733
void UpdateListOfLoadedSharedLibraries()
Definition TCling.cxx:3407
const char * TypedefInfo_Title(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9606
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:8137
void InitRootmapFile(const char *name)
Create a resource table and read the (possibly) three resource files, i.e.
Definition TCling.cxx:5714
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:6582
void LoadPCM(std::string pcmFileNameFullPath)
Tries to load a rdict PCM, issues diagnostics if it fails.
Definition TCling.cxx:1858
void UpdateListOfMethods(TClass *cl) const final
Update the list of pointers to method for TClass cl This is now a nop.
Definition TCling.cxx:4566
virtual ~TCling()
Destroy the interpreter interface.
Definition TCling.cxx:1661
void AddFriendToClass(clang::FunctionDecl *, clang::CXXRecordDecl *) const
Inject function as a friend into klass.
Definition TCling.cxx:7839
void PrintIntro() final
No-op; see TRint instead.
Definition TCling.cxx:2696
Bool_t fCxxModulesEnabled
Definition TCling.h:128
int BaseClassInfo_Next(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8564
void RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
Internal function. Actually do the update of the ClassInfo when seeing.
Definition TCling.cxx:6693
CallFunc_t * CallFunc_FactoryCopy(CallFunc_t *func) const final
Definition TCling.cxx:7989
Double_t CallFunc_ExecDouble(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7973
void CallFunc_ResetArg(CallFunc_t *func) const final
Definition TCling.cxx:8038
const char * GetCurrentMacroName() const final
Return the file name of the currently interpreted file, included or not.
Definition TCling.cxx:5522
Bool_t IsLoaded(const char *filename) const final
Return true if the file has already been loaded by cint.
Definition TCling.cxx:3231
void SaveGlobalsContext() final
Save the current Cling state of global objects.
Definition TCling.cxx:3931
void CallFunc_IgnoreExtraArgs(CallFunc_t *func, bool ignore) const final
Definition TCling.cxx:8004
void ApplyToInterpreterMutex(void *delta)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
Definition TCling.cxx:9702
void * LazyFunctionCreatorAutoload(const std::string &mangled_name)
Autoload a library based on a missing symbol.
Definition TCling.cxx:6650
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:4782
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:8203
Bool_t IsLibraryLoaded(const char *libname) const final
Definition TCling.cxx:3197
Long_t GetExecByteCode() const final
This routines used to return the address of the internal wrapper function (of the interpreter) that w...
Definition TCling.cxx:7549
int DataMemberInfo_ArrayDim(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8656
DataMemberInfo_t * DataMemberInfo_FactoryCopy(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8690
Bool_t HandleNewTransaction(const cling::Transaction &T)
Helper function to increase the internal Cling count of transactions that change the AST.
Definition TCling.cxx:3724
int ReadRootmapFile(const char *rootmapfile, TUniqueString *uniqueString=nullptr)
Read and parse a rootmapfile in its new format, and return 0 in case of success, -1 if the file has a...
Definition TCling.cxx:5587
std::map< SpecialObjectLookupCtx_t, SpecialObjectMap_t > fSpecialObjectMaps
Definition TCling.h:153
int ClassInfo_Next(ClassInfo_t *info) const final
Definition TCling.cxx:8424
void SetErrmsgcallback(void *p) const final
Set a callback to receive error messages.
Definition TCling.cxx:7676
bool MethodArgInfo_IsValid(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9348
int TypeInfo_Size(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9488
Int_t DeleteGlobal(void *obj) final
Delete obj from Cling symbol table so it cannot be accessed anymore.
Definition TCling.cxx:3842
int GetSecurityError() const final
Interface to cling function.
Definition TCling.cxx:7557
void SetTempLevel(int val) const final
Create / close a scope for temporaries.
Definition TCling.cxx:7712
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:8921
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:5214
TypedefInfo_t * TypedefInfo_Factory() const final
Definition TCling.cxx:9525
TObjArray * fRootmapFiles
Definition TCling.h:126
Longptr_t ProcessLine(const char *line, EErrorCode *error=nullptr) final
Definition TCling.cxx:2501
int ClassInfo_Size(ClassInfo_t *info) const final
Definition TCling.cxx:8472
const char * MethodArgInfo_TypeName(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9388
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:5462
std::vector< std::pair< TClass *, DictFuncPtr_t > > fClassesToUpdate
Definition TCling.h:146
int DataMemberInfo_Next(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8714
const char * TypedefInfo_Name(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9598
void BaseClassInfo_Delete(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8537
Long_t MethodInfo_ExtraProperty(MethodInfo_t *minfo) const final
Definition TCling.cxx:9176
void LoadMacro(const char *filename, EErrorCode *error=nullptr) final
Load a macro file in cling's memory.
Definition TCling.cxx:3611
FuncTempInfo_t * FuncTempInfo_FactoryCopy(FuncTempInfo_t *) const final
Construct a FuncTempInfo_t.
Definition TCling.cxx:8898
int DataMemberInfo_MaxIndex(DataMemberInfo_t *dminfo, Int_t dim) const final
Definition TCling.cxx:8706
Bool_t FuncTempInfo_IsValid(FuncTempInfo_t *) const final
Check validity of a FuncTempInfo_t.
Definition TCling.cxx:8909
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:2710
bool ClassInfo_IsBase(ClassInfo_t *info, const char *name) const final
Definition TCling.cxx:8359
void RecursiveRemove(TObject *obj) final
Delete object from cling symbol table so it can not be used anymore.
Definition TCling.cxx:3742
const char * DataMemberInfo_TypeName(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8754
DeclId_t GetDataMemberAtAddr(const void *addr) const final
Return pointer to cling DeclId for a data member with a given name.
Definition TCling.cxx:5009
void CallFunc_SetArgArray(CallFunc_t *func, Longptr_t *paramArr, Int_t nparam) const final
Definition TCling.cxx:8094
std::string CallFunc_GetWrapperCode(CallFunc_t *func) const final
Definition TCling.cxx:8184
void * RewindInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:9732
const char * MethodArgInfo_Name(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9380
Bool_t HasPCMForLibrary(const char *libname) const final
Return true if ROOT has cxxmodules pcm for a given library name.
Definition TCling.cxx:3206
void TypedefInfo_Init(TypedefInfo_t *tinfo, const char *name) const final
Definition TCling.cxx:9548
const char * DataMemberInfo_Title(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8778
Longptr_t CallFunc_ExecInt(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7957
void ClearStack() final
Delete existing temporary values.
Definition TCling.cxx:3144
void SetAlloclockfunc(void(*)()) const final
[Place holder for Mutex Lock] Provide the interpreter with a way to acquire a lock used to protect cr...
Definition TCling.cxx:7606
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:7426
MethodInfo_t * CallFunc_FactoryMethod(CallFunc_t *func) const final
Definition TCling.cxx:7996
TypedefInfo_t * TypedefInfo_FactoryCopy(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9541
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:5107
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:2441
std::string MethodArgInfo_TypeNormalizedName(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9396
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:4891
Long_t MethodArgInfo_Property(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9364
int TypedefInfo_Size(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9582
void CallFunc_ExecWithArgsAndReturn(CallFunc_t *func, void *address, const void *args[]=nullptr, int nargs=0, void *ret=nullptr) const final
Definition TCling.cxx:7946
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:5259
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:6815
Int_t Load(const char *filenam, Bool_t system=kFALSE) final
Load a library file in cling's memory.
Definition TCling.cxx:3574
int TypedefInfo_Next(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9566
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:5066
void TypeInfo_Init(TypeInfo_t *tinfo, const char *funcname) const final
Definition TCling.cxx:9447
Bool_t SetSuspendAutoParsing(Bool_t value) final
Suspend the Autoparsing of headers.
Definition TCling.cxx:7666
int DataMemberInfo_TypeSize(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8746
static void * fgSetOfSpecials
Definition TCling.h:105
const char * ClassInfo_Title(ClassInfo_t *info) const final
Definition TCling.cxx:8514
const char * DataMemberInfo_Name(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8770
const char * TypeName(const char *typeDesc) final
Return the absolute type of typeDesc.
Definition TCling.cxx:5537
ROOT::TMetaUtils::TNormalizedCtxt * fNormalizedCtxt
Definition TCling.h:134
void ForgetMutexState() final
Definition TCling.cxx:9686
int MethodInfo_Next(MethodInfo_t *minfo) const final
Definition TCling.cxx:9159
Long_t ClassInfo_ClassProperty(ClassInfo_t *info) const final
Definition TCling.cxx:8248
void MethodInfo_Delete(MethodInfo_t *minfo) const final
Interface to cling function.
Definition TCling.cxx:9078
bool fIsShuttingDown
Definition TCling.h:187
void MethodArgInfo_Delete(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9317
bool IsSignedIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9631
DataMemberInfo_t * DataMemberInfo_Factory(ClassInfo_t *clinfo, TDictionary::EMemberSelection selection) const final
Definition TCling.cxx:8671
void ClassInfo_Destruct(ClassInfo_t *info, void *arena) const final
Definition TCling.cxx:8279
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:6169
Int_t UnloadAllSharedLibraryMaps() final
Unload the library map entries coming from all the loaded shared libraries.
Definition TCling.cxx:6057
void ClassInfo_Init(ClassInfo_t *info, const char *funcname) const final
Definition TCling.cxx:8341
std::set< TClass * > & GetModTClasses()
Definition TCling.h:578
ClassInfo_t * BaseClassInfo_ClassInfo(BaseClassInfo_t *) const final
Definition TCling.cxx:8609
TClingCallbacks * fClingCallbacks
Definition TCling.h:139
Long64_t CallFunc_ExecInt64(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7965
Long_t ClassInfo_Property(ClassInfo_t *info) const final
Definition TCling.cxx:8464
Longptr_t ClassInfo_GetBaseOffset(ClassInfo_t *fromDerived, ClassInfo_t *toBase, void *address, bool isDerivedObject) const final
Definition TCling.cxx:8588
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:5444
Bool_t IsErrorMessagesEnabled() const final
If error messages are disabled, the interpreter should suppress its failures and warning messages fro...
Definition TCling.cxx:7412
TString fIncludePath
Definition TCling.h:115
int DisplayIncludePath(FILE *fout) const final
Interface to cling function.
Definition TCling.cxx:7489
void TransactionRollback(const cling::Transaction &T)
Definition TCling.cxx:7021
Long_t FuncTempInfo_Property(FuncTempInfo_t *) const final
Return the property of the function template.
Definition TCling.cxx:8942
TEnum * CreateEnum(void *VD, TClass *cl) const final
Definition TCling.cxx:485
const char * TypeInfo_TrueName(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9496
Int_t UnloadLibraryMap(const char *library) final
Unload library map entries coming from the specified library.
Definition TCling.cxx:6075
void RegisterTemporary(const TInterpreterValue &value)
Definition TCling.cxx:7759
MutexStateAndRecurseCount fInitialMutex
Definition TCling.h:174
const char * GetSharedLibs() final
Return the list of shared libraries loaded into the process.
Definition TCling.cxx:7059
int MethodArgInfo_Next(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9356
void SnapshotMutexState(ROOT::TVirtualRWMutex *mtx) final
Definition TCling.cxx:9671
Long_t TypeInfo_Property(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9472
const char * MethodInfo_GetPrototype(MethodInfo_t *minfo) const final
Definition TCling.cxx:9205
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:8932
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:2058
static Int_t ShallowAutoLoadImpl(const char *cls)
Definition TCling.cxx:6215
void MethodInfo_CreateSignature(MethodInfo_t *minfo, TString &signature) const final
Definition TCling.cxx:9085
Bool_t CheckClassTemplate(const char *name) final
Return true if there is a class template by the given name ...
Definition TCling.cxx:4408
void LibraryLoaded(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:7044
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:2432
bool IsVoidPointerType(const void *QualTypePtr) const final
Definition TCling.cxx:9663
TObjArray * GetRootMapFiles() const final
Definition TCling.h:223
bool DataMemberInfo_IsValid(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8698
bool ClassInfo_IsEnum(const char *name) const final
Definition TCling.cxx:8367
int MethodInfo_NDefaultArg(MethodInfo_t *minfo) const final
Definition TCling.cxx:9151
bool IsFloatingType(const void *QualTypePtr) const final
Definition TCling.cxx:9647
void CreateListOfMethods(TClass *cl) const final
Create list of pointers to methods for TClass cl.
Definition TCling.cxx:4557
Int_t RescanLibraryMap() final
Scan again along the dynamic path for library maps.
Definition TCling.cxx:5984
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:7685
const char * MethodInfo_GetMangledName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9194
TypeInfo_t * MethodArgInfo_TypeInfo(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9404
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:5169
void * ClassInfo_New(ClassInfo_t *info) const final
Definition TCling.cxx:8432
int DisplayClass(FILE *fout, const char *name, int base, int start) const final
Definition TCling.cxx:7480
virtual void GetFunctionName(const clang::Decl *decl, std::string &name) const
Definition TCling.cxx:8833
void CreateListOfMethodArgs(TFunction *m) const final
Create list of pointers to method arguments for TMethod m.
Definition TCling.cxx:4582
virtual const char * GetSTLIncludePath() const final
Return the directory containing CINT's stl cintdlls.
Definition TCling.cxx:7471
MethodArgInfo_t * MethodArgInfo_FactoryCopy(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9340
Longptr_t BaseClassInfo_Offset(BaseClassInfo_t *toBaseClassInfo, void *address, bool isDerivedObject) const final
Definition TCling.cxx:8580
ECheckClassInfo CheckClassInfo(const char *name, Bool_t autoload, Bool_t isClassOrNamespaceOnly=kFALSE) final
Checks if an entity with the specified name is defined in Cling.
Definition TCling.cxx:4236
void * FindSym(const char *entry) const final
Interface to cling function.
Definition TCling.cxx:7518
void RegisterLoadedSharedLibrary(const char *name)
Register a new shared library name with the interpreter; add it to fSharedLibs.
Definition TCling.cxx:3474
void TypeInfo_Delete(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9417
int MethodInfo_NArg(MethodInfo_t *minfo) const final
Definition TCling.cxx:9143
DeclId_t GetDataMemberWithValue(const void *ptrvalue) const final
NOT IMPLEMENTED.
Definition TCling.cxx:5000
std::unordered_set< const clang::NamespaceDecl * > fNSFromRootmaps
Definition TCling.h:125
EReturnType MethodCallReturnType(TFunction *func) const final
Definition TCling.cxx:9253
void ProcessClassesToUpdate()
Definition TCling.cxx:2027
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:5192
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:5021
const char * MethodInfo_Title(MethodInfo_t *minfo) const final
Definition TCling.cxx:9244
TString fRootmapLoadPath
Definition TCling.h:116
const char * BaseClassInfo_TmpltName(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8643
Bool_t Declare(const char *code) final
Declare code to the interpreter, without any of the interpreter actions that could trigger a re-inter...
Definition TCling.cxx:3157
const char * BaseClassInfo_FullName(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8625
void CallFunc_SetArgs(CallFunc_t *func, const char *param) const final
Definition TCling.cxx:8102
int UnloadFile(const char *path) const final
Definition TCling.cxx:7718
void SetClassInfo(TClass *cl, Bool_t reload=kFALSE, Bool_t silent=kFALSE) final
Set pointer to the TClingClassInfo in TClass.
Definition TCling.cxx:4100
void CallFunc_Exec(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7922
Long_t FuncTempInfo_ExtraProperty(FuncTempInfo_t *) const final
Return the property not already defined in Property See TDictionary's EFunctionProperty.
Definition TCling.cxx:9007
bool CallFunc_IsValid(CallFunc_t *func) const final
Definition TCling.cxx:8021
const char * BaseClassInfo_Name(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8635
ROOT::TMetaUtils::TClingLookupHelper * fLookupHelper
Definition TCling.h:135
const char * DataMemberInfo_ValidArrayIndex(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8786
Int_t GetMore() const final
Return whether we are waiting for more input either because the collected input contains unbalanced b...
Definition TCling.cxx:4603
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:4931
void Execute(const char *function, const char *params, int *error=nullptr) final
Execute a global function with arguments params.
Definition TCling.cxx:5292
bool ClassInfo_IsLoaded(ClassInfo_t *info) const final
Definition TCling.cxx:8392
Longptr_t ClassInfo_Tagnum(ClassInfo_t *info) const final
Definition TCling.cxx:8480
Long_t BaseClassInfo_Property(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8601
void CallFunc_SetFunc(CallFunc_t *func, ClassInfo_t *info, const char *method, const char *params, Longptr_t *Offset) const final
Definition TCling.cxx:8110
std::vector< std::string > GetUsingNamespaces(ClassInfo_t *cl) const final
Get the scopes representing using declarations of namespace.
Definition TCling.cxx:4537
const char * ClassInfo_FileName(ClassInfo_t *info) const final
Definition TCling.cxx:8488
void FuncTempInfo_Title(FuncTempInfo_t *, TString &name) const final
Return the comments associates with this function template.
Definition TCling.cxx:9046
const char * ClassInfo_TmpltName(ClassInfo_t *info) const final
Definition TCling.cxx:8522
void SaveContext() final
Save the current Cling state.
Definition TCling.cxx:3918
void LoadPCMImpl(TFile &pcmFile)
Tries to load a PCM from TFile; returns true on success.
Definition TCling.cxx:1742
Bool_t IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *nsDecl)
Definition TCling.cxx:6685
void ResetGlobals() final
Reset in Cling the list of global variables to the state saved by the last call to TCling::SaveGlobal...
Definition TCling.cxx:3799
void CodeComplete(const std::string &, size_t &, std::vector< std::string > &) final
The call to Cling's tab complition.
Definition TCling.cxx:7740
void ResetGlobalVar(void *obj) final
Reset the Cling 'user' global objects/variables state to the state saved by the last call to TCling::...
Definition TCling.cxx:3813
const char * MapCppName(const char *) const final
Interface to cling function.
Definition TCling.cxx:7593
Longptr_t Calc(const char *line, EErrorCode *error=nullptr) final
Directly execute an executable statement (e.g.
Definition TCling.cxx:3644
Int_t ReloadAllSharedLibraryMaps() final
Reload the library map entries coming from all the loaded shared libraries, after first unloading the...
Definition TCling.cxx:5996
void UpdateListOfGlobalFunctions() final
No op: see TClingCallbacks (used to update the list of global functions)
Definition TCling.cxx:3951
void DataMemberInfo_Delete(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8664
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:5475
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:4575
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:2732
Int_t SetClassSharedLibs(const char *cls, const char *libs) final
Register the AutoLoading information for a class.
Definition TCling.cxx:6137
MethodInfo_t * MethodInfo_FactoryCopy(MethodInfo_t *minfo) const final
Definition TCling.cxx:9119
std::set< const char * > fParsedPayloadsAddresses
Definition TCling.h:123
CallFuncIFacePtr_t CallFunc_IFacePtr(CallFunc_t *func) const final
Definition TCling.cxx:8030
MethodArgInfo_t * MethodArgInfo_Factory() const final
Definition TCling.cxx:9324
static void UpdateClassInfo(char *name, Long_t tagnum)
No op: see TClingCallbacks.
Definition TCling.cxx:6809
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:5088
void ClassInfo_Delete(ClassInfo_t *info) const final
Definition TCling.cxx:8256
std::unique_ptr< cling::Interpreter > fInterpreter
Definition TCling.h:130
EDataType ClassInfo_GetUnderlyingType(ClassInfo_t *info) const final
Definition TCling.cxx:8383
void FuncTempInfo_Delete(FuncTempInfo_t *) const final
Delete the FuncTempInfo_t.
Definition TCling.cxx:8878
bool IsUnsignedIntegerType(const void *QualTypePtr) const final
Definition TCling.cxx:9639
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:5236
Int_t DeleteVariable(const char *name) final
Undeclare obj called name.
Definition TCling.cxx:3857
const char * GetClassSharedLibs(const char *cls, bool skipCore=true) final
Get the list of shared libraries containing the code for class cls.
Definition TCling.cxx:7165
Longptr_t DataMemberInfo_Offset(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8722
CallFunc_t * CallFunc_Factory() const final
Definition TCling.cxx:7981
MethodInfo_t * MethodInfo_Factory() const final
Definition TCling.cxx:9094
Long_t DataMemberInfo_TypeProperty(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8738
void ClearFileBusy() final
Reset the interpreter internal state in case a previous action was not correctly terminated.
Definition TCling.cxx:3136
cling::MetaProcessor * GetMetaProcessorImpl() const
Definition TCling.h:644
bool DiagnoseIfInterpreterException(const std::exception &e) const final
Definition TCling.cxx:2490
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:7616
std::set< size_t > fLookedUpClasses
Definition TCling.h:121
bool IsValid() const final
Check if constructor exited correctly, ie the instance is in a valid state.
Definition TCling.cxx:3127
virtual void AddAvailableIndentifiers(TSeqCollection &Idents) final
Definition TCling.cxx:2406
void TypedefInfo_Delete(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9518
void Reset() final
Pressing Ctrl+C should forward here.
Definition TCling.cxx:3767
const char * TypedefInfo_TrueName(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9590
int SetClassAutoLoading(int) const final
Enable/Disable the AutoLoading of libraries.
Definition TCling.cxx:7637
const char * ClassInfo_FullName(ClassInfo_t *info) const final
Definition TCling.cxx:8496
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:6440
const char * MethodInfo_TypeName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9223
void CallFunc_SetArg(CallFunc_t *func, Long_t param) const final
Definition TCling.cxx:8046
const char * GetIncludePath() final
Refresh the list of include paths known to the interpreter and return it with -I prepended.
Definition TCling.cxx:7440
void UpdateListsOnUnloaded(const cling::Transaction &T)
Invalidate stored TCling state for declarations included in transaction ‘T’.
Definition TCling.cxx:6919
void UpdateClassInfoWithDecl(const clang::NamedDecl *ND)
Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
Definition TCling.cxx:6751
virtual void Initialize() final
Initialize the interpreter, once TROOT::fInterpreter is set.
Definition TCling.cxx:1679
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:8317
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:4830
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:9033
std::unique_ptr< cling::MetaProcessor > fMetaProcessor
Definition TCling.h:131
bool TypeInfo_IsValid(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9456
bool RegisterPrebuiltModulePath(const std::string &FullPath, const std::string &ModuleMapName="module.modulemap") const final
Definition TCling.cxx:1953
std::string MethodInfo_TypeNormalizedName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9232
const char * ClassInfo_Name(ClassInfo_t *info) const final
Definition TCling.cxx:8506
TClass * GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent=kFALSE) final
Generate a TClass for the given class.
Definition TCling.cxx:4613
ULong64_t fTransactionCount
Definition TCling.h:148
bool ClassInfo_HasDefaultConstructor(ClassInfo_t *info, Bool_t testio=kFALSE) const final
Definition TCling.cxx:8325
void EndOfLineAction() final
It calls a "fantom" method to synchronize user keyboard input and ROOT prompt line.
Definition TCling.cxx:3180
TypeInfo_t * TypeInfo_FactoryCopy(TypeInfo_t *) const final
Definition TCling.cxx:9440
bool ClassInfo_HasMethod(ClassInfo_t *info, const char *name) const final
Definition TCling.cxx:8333
void ClassInfo_DeleteArray(ClassInfo_t *info, void *arena, bool dtorOnly) const final
Definition TCling.cxx:8271
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:8762
virtual void ShutDown() final
Definition TCling.cxx:1700
void UpdateListOfTypes() final
No op: see TClingCallbacks (used to update the list of types)
Definition TCling.cxx:3958
void * TypeInfo_QualTypePtr(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9504
Long_t TypedefInfo_Property(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9574
void RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
Register Rdict data for future loading by LoadPCM;.
Definition TCling.cxx:1723
Longptr_t ProcessLineSynch(const char *line, EErrorCode *error=nullptr) final
Let cling process a command line synchronously, i.e we are waiting it will be finished.
Definition TCling.cxx:3628
TString GetMangledNameWithPrototype(TClass *cl, const char *method, const char *proto, Bool_t objectIsConst=kFALSE, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch) final
Return the cling mangled name for a method of a class with a certain prototype, i....
Definition TCling.cxx:5048
static void UpdateAllCanvases()
Update all canvases at end the terminal input command.
Definition TCling.cxx:6824
Int_t LoadLibraryMap(const char *rootmapfile=nullptr) final
Load map between class and library.
Definition TCling.cxx:5800
Longptr_t BaseClassInfo_Tagnum(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8617
void LibraryUnloaded(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:7051
bool IsPointerType(const void *QualTypePtr) const final
Definition TCling.cxx:9655
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:182
@ 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:793
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:592
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:736
virtual TEnvRec * Lookup(const char *n) const
Loop over all resource records and return the one with name.
Definition TEnv.cxx:547
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:355
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:1058
virtual TObject * FindObject(const char *name) const
Must be redefined in derived classes.
Definition TObject.cxx:422
static TClass * Class()
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1072
virtual void Fatal(const char *method, const char *msgfmt,...) const
Issue fatal error message.
Definition TObject.cxx:1100
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:1046
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:3098
static const char * GetMacroPath()
Get macro search path. Static utility function.
Definition TROOT.cxx:2765
static const std::vector< std::string > & AddExtraInterpreterArgs(const std::vector< std::string > &args)
Provide command line arguments to the interpreter construction.
Definition TROOT.cxx:2960
static const TString & GetEtcDir()
Get the sysconfig directory in the installation. Static utility function.
Definition TROOT.cxx:3108
static const char **& GetExtraInterpreterArgs()
INTERNAL function! Used by rootcling to inject interpreter arguments through a C-interface layer.
Definition TROOT.cxx:2970
static const TString & GetSharedLibDir()
Get the shared libraries directory in the installation. Static utility function.
Definition TROOT.cxx:3087
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:2385
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:1287
virtual void FreeDirectory(void *dirp)
Free a directory.
Definition TSystem.cxx:857
virtual void * OpenDirectory(const char *name)
Open a directory.
Definition TSystem.cxx:848
virtual const char * Getenv(const char *env)
Get environment variable.
Definition TSystem.cxx:1678
virtual const char * GetIncludePath()
Get the list of include path.
Definition TSystem.cxx:3999
virtual TString SplitAclicMode(const char *filename, TString &mode, TString &args, TString &io) const
This method split a filename of the form:
Definition TSystem.cxx:4284
virtual char * ConcatFileName(const char *dir, const char *name)
Concatenate a directory and a file name.
Definition TSystem.cxx:1084
virtual const char * FindFile(const char *search, TString &file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition TSystem.cxx:1551
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition TSystem.cxx:1870
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:1411
virtual const char * PrependPathName(const char *dir, TString &name)
Concatenate a directory and a file name.
Definition TSystem.cxx:1094
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:1309
virtual const char * GetDirEntry(void *dirp)
Get a directory entry. Returns 0 if no more entries.
Definition TSystem.cxx:865
virtual int GetProcInfo(ProcInfo_t *info) const
Returns cpu and memory used by this process into the ProcInfo_t structure.
Definition TSystem.cxx:2502
virtual const char * BaseName(const char *pathname)
Base name of a file name. Base name of /user/root is root.
Definition TSystem.cxx:946
virtual const char * GetDynamicPath()
Return the dynamic path (used to find shared libraries).
Definition TSystem.cxx:1808
virtual const char * FindDynamicLibrary(TString &lib, Bool_t quiet=kFALSE)
Find a dynamic library using the system search paths.
Definition TSystem.cxx:2047
virtual void Sleep(UInt_t milliSec)
Sleep milliSec milli seconds.
Definition TSystem.cxx:437
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:2849
virtual const char * WorkingDirectory()
Return working directory.
Definition TSystem.cxx:883
virtual char * Which(const char *search, const char *file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition TSystem.cxx:1561
virtual void Setenv(const char *name, const char *value)
Set environment variable.
Definition TSystem.cxx:1662
virtual const char * HomeDirectory(const char *userName=nullptr)
Return the user's home directory.
Definition TSystem.cxx:899
virtual TString GetDirName(const char *pathname)
Return the directory name in pathname.
Definition TSystem.cxx:1044
virtual void StackTrace()
Print a stack trace.
Definition TSystem.cxx:745
char * DynamicPathName(const char *lib, Bool_t quiet=kFALSE)
Find a dynamic library called lib using the system search paths.
Definition TSystem.cxx:2033
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.
Namespace for new ROOT classes and functions.
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()