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 "clang/Interpreter/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 { return true; } \
308 static Version_t Class_Version() { return id; } \
309 static TClass *Dictionary() { return 0; } \
310 virtual_keyword TClass *IsA() const overrd { return name::Class(); } \
311 virtual_keyword void ShowMembers(TMemberInspector&insp) const overrd { ::ROOT::Class_ShowMembers(name::Class(), this, insp); } \
312 virtual_keyword void Streamer(TBuffer&) overrd { ::Error("Streamer", "Cannot stream interpreted class."); } \
313 void StreamerNVirtual(TBuffer&ClassDef_StreamerNVirtual_b) { name::Streamer(ClassDef_StreamerNVirtual_b); } \
314 static const char *DeclFileName() { return __FILE__; } \
315 static int ImplFileLine() { return 0; } \
316 static const char *ImplFileName() { return __FILE__; }
317)ICF";
318}
320
321// The functions are used to bridge cling/clang/llvm compiled with no-rtti and
322// ROOT (which uses rtti)
323
324////////////////////////////////////////////////////////////////////////////////
325/// Print a StackTrace!
326
327extern "C"
331
332////////////////////////////////////////////////////////////////////////////////
333/// Load a library.
334
335extern "C" int TCling__LoadLibrary(const char *library)
336{
337 return gSystem->Load(library, "", false);
338}
339
340////////////////////////////////////////////////////////////////////////////////
341/// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
342
343extern "C" void TCling__RestoreInterpreterMutex(void *delta)
344{
345 ((TCling*)gCling)->ApplyToInterpreterMutex(delta);
346}
347
348////////////////////////////////////////////////////////////////////////////////
349/// Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name,
350/// which is extracted by error messages we get from callback from cling. Return true
351/// when the missing library was autoloaded.
352
353extern "C" bool TCling__LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
354{
355 return ((TCling*)gCling)->LibraryLoadingFailed(errmessage, libStem, permanent, resolved);
356}
357
358////////////////////////////////////////////////////////////////////////////////
359/// Reset the interpreter lock to the state it had before interpreter-related
360/// calls happened.
361
363{
364 return ((TCling*)gCling)->RewindInterpreterMutex();
365}
366
367////////////////////////////////////////////////////////////////////////////////
368/// Lock the interpreter.
369
371{
372 if (gInterpreterMutex) {
374 }
375 return nullptr;
376}
377
378////////////////////////////////////////////////////////////////////////////////
379/// Unlock the interpreter.
380
382{
383 if (gInterpreterMutex) {
385 }
386}
387
388////////////////////////////////////////////////////////////////////////////////
389/// Update TClingClassInfo for a class (e.g. upon seeing a definition).
390
392{
393 static Bool_t entered = kFALSE;
396
397 if (entered) topLevel = kFALSE;
398 else {
399 entered = kTRUE;
400 topLevel = kTRUE;
401 }
402 if (topLevel) {
403 ((TCling*)gInterpreter)->UpdateClassInfoWithDecl(TD);
404 } else {
405 // If we are called indirectly from within another call to
406 // TCling::UpdateClassInfo, we delay the update until the dictionary loading
407 // is finished (i.e. when we return to the top level TCling::UpdateClassInfo).
408 // This allows for the dictionary to be fully populated when we actually
409 // update the TClass object. The updating of the TClass sometimes
410 // (STL containers and when there is an emulated class) forces the building
411 // of the TClass object's real data (which needs the dictionary info).
412 updateList.push_back(TD);
413 }
414 if (topLevel) {
415 while (!updateList.empty()) {
416 ((TCling*)gInterpreter)->UpdateClassInfoWithDecl(updateList.back());
417 updateList.pop_back();
418 }
419 entered = kFALSE;
420 }
421}
422
424 const clang::Decl* D = static_cast<const clang::Decl*>(enumObj->GetDeclId());
425 if(const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(D)) {
426 // Add the constants to the enum type.
427 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(),
428 EDE = ED->enumerator_end(); EDI != EDE; ++EDI) {
429 // Get name of the enum type.
430 std::string constbuf;
431 if (const NamedDecl* END = llvm::dyn_cast<NamedDecl>(*EDI)) {
432 PrintingPolicy Policy((*EDI)->getASTContext().getPrintingPolicy());
433 llvm::raw_string_ostream stream(constbuf);
434 // Don't trigger fopen of the source file to count lines:
435 Policy.AnonymousTagLocations = false;
436 (END)->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
437 }
438 const char* constantName = constbuf.c_str();
439
440 // Get value of the constant.
442 const llvm::APSInt valAPSInt = (*EDI)->getInitVal();
443 if (valAPSInt.isSigned()) {
444 value = valAPSInt.getSExtValue();
445 } else {
446 value = valAPSInt.getZExtValue();
447 }
448
449 // Create the TEnumConstant or update it if existing
450 TEnumConstant* enumConstant = nullptr;
451 TClingClassInfo* tcCInfo = (TClingClassInfo*)(cl ? cl->GetClassInfo() : nullptr);
454 if (TObject* encAsTObj = enumObj->GetConstants()->FindObject(constantName)){
455 ((TEnumConstant*)encAsTObj)->Update(dmInfo);
456 } else {
458 }
459
460 // Add the global constants to the list of Globals.
461 if (!cl) {
462 TCollection* globals = gROOT->GetListOfGlobals(false);
463 if (!globals->FindObject(constantName)) {
464 globals->Add(enumConstant);
465 }
466 }
467 }
468 }
469}
470
472{
473 // Handle new enum declaration for either global and nested enums.
474
475 // Create the enum type.
476 TEnum* enumType = nullptr;
477 const clang::Decl* D = static_cast<const clang::Decl*>(VD);
478 std::string buf;
479 if (const EnumDecl* ED = llvm::dyn_cast<EnumDecl>(D)) {
480 // Get name of the enum type.
481 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
482 llvm::raw_string_ostream stream(buf);
483 // Don't trigger fopen of the source file to count lines:
484 Policy.AnonymousTagLocations = false;
485 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
486 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
487 }
488 if (buf.empty()) {
489 return nullptr;
490 }
491 const char* name = buf.c_str();
492 enumType = new TEnum(name, VD, cl);
494
495 return enumType;
496}
497
498void TCling::HandleNewDecl(const void* DV, bool isDeserialized, std::set<TClass*> &modifiedTClasses) {
499 // Handle new declaration.
500 // Record the modified class, struct and namespaces in 'modifiedTClasses'.
501
502 const clang::Decl* D = static_cast<const clang::Decl*>(DV);
503
504 if (!D->isCanonicalDecl() && !isa<clang::NamespaceDecl>(D)
505 && !dyn_cast<clang::RecordDecl>(D)) return;
506
507 if (isa<clang::FunctionDecl>(D->getDeclContext())
508 || isa<clang::TagDecl>(D->getDeclContext()))
509 return;
510
511 // Don't list templates.
512 if (const clang::CXXRecordDecl* RD = dyn_cast<clang::CXXRecordDecl>(D)) {
513 if (RD->getDescribedClassTemplate())
514 return;
515 } else if (const clang::FunctionDecl* FD = dyn_cast<clang::FunctionDecl>(D)) {
516 if (FD->getDescribedFunctionTemplate())
517 return;
518 }
519
520 if (const RecordDecl *TD = dyn_cast<RecordDecl>(D)) {
521 if (TD->isCanonicalDecl() || TD->isThisDeclarationADefinition())
523 }
524 else if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
525
526 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
527 // Mostly just for EnumDecl (the other TagDecl are handled
528 // by the 'RecordDecl' if statement.
530 } else if (const NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(D)) {
532 }
533
534 // We care about declarations on the global scope.
535 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
536 return;
537
538 // Enums are lazyly created, thus we don not need to handle them here.
539 if (isa<EnumDecl>(ND))
540 return;
541
542 // ROOT says that global is enum(lazylycreated)/var/field declared on the global
543 // scope.
544 if (!(isa<VarDecl>(ND)))
545 return;
546
547 // Skip if already in the list.
548 if (gROOT->GetListOfGlobals()->FindObject(ND->getNameAsString().c_str()))
549 return;
550
551 // Put the global constants and global enums in the corresponding lists.
552 gROOT->GetListOfGlobals()->Add(new TGlobal((DataMemberInfo_t *)
554 cast<ValueDecl>(ND), nullptr)));
555 }
556}
557
558extern "C"
560{
561 // We are sure in this context of the type of the interpreter
562 normCtxt = &( (TCling*) gInterpreter)->GetNormalizedContext();
563}
564
565extern "C"
566void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter*) {
567 ((TCling*)gCling)->UpdateListsOnCommitted(T);
568}
569
570extern "C"
571void TCling__UpdateListsOnUnloaded(const cling::Transaction &T) {
572 ((TCling*)gCling)->UpdateListsOnUnloaded(T);
573}
574
575extern "C"
576void TCling__InvalidateGlobal(const clang::Decl *D) {
577 ((TCling*)gCling)->InvalidateGlobal(D);
578}
579
580extern "C"
581void TCling__TransactionRollback(const cling::Transaction &T) {
582 ((TCling*)gCling)->TransactionRollback(T);
583}
584
585extern "C" void TCling__LibraryLoadedRTTI(const void* dyLibHandle,
586 const char* canonicalName) {
587 ((TCling*)gCling)->LibraryLoaded(dyLibHandle, canonicalName);
588}
589
590extern "C" void TCling__RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
591{
592 ((TCling *)gCling)->RegisterRdictForLoadPCM(pcmFileNameFullPath, pcmContent);
593}
594
595extern "C" void TCling__LibraryUnloadedRTTI(const void* dyLibHandle,
596 const char* canonicalName) {
597 ((TCling*)gCling)->LibraryUnloaded(dyLibHandle, canonicalName);
598}
599
600
601extern "C"
602TObject* TCling__GetObjectAddress(const char *Name, void *&LookupCtx) {
603 return ((TCling*)gCling)->GetObjectAddress(Name, LookupCtx);
604}
605
606extern "C" const Decl* TCling__GetObjectDecl(TObject *obj) {
607 return ((TClingClassInfo*)obj->IsA()->GetClassInfo())->GetDecl();
608}
609
611 const char* argv[])
612{
613 auto tcling = new TCling("C++", "cling C++ Interpreter", argv, interpLibHandle);
614
615 return tcling;
616}
617
619{
620 delete interp;
621}
622
623// Load library containing specified class. Returns 0 in case of error
624// and 1 in case if success.
625extern "C" int TCling__AutoLoadCallback(const char* className)
626{
627 return ((TCling*)gCling)->AutoLoad(className);
628}
629
630extern "C" int TCling__AutoParseCallback(const char* className)
631{
632 return ((TCling*)gCling)->AutoParse(className);
633}
634
635extern "C" const char* TCling__GetClassSharedLibs(const char* className, bool skipCore)
636{
637 return ((TCling*)gCling)->GetClassSharedLibs(className, skipCore);
638}
639
640// Returns 0 for failure 1 for success
641extern "C" int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl* nsDecl)
642{
643 return ((TCling*)gCling)->IsAutoLoadNamespaceCandidate(nsDecl);
644}
645
646extern "C" int TCling__CompileMacro(const char *fileName, const char *options)
647{
648 string file(fileName);
649 string opt(options);
650 return gSystem->CompileMacro(file.c_str(), opt.c_str());
651}
652
653extern "C" void TCling__SplitAclicMode(const char* fileName, string &mode,
654 string &args, string &io, string &fname)
655{
656 string file(fileName);
657 TString f, amode, arguments, aclicio;
658 f = gSystem->SplitAclicMode(file.c_str(), amode, arguments, aclicio);
659 mode = amode.Data(); args = arguments.Data();
660 io = aclicio.Data(); fname = f.Data();
661}
662
663//______________________________________________________________________________
664//
665//
666//
667
668#ifdef R__WIN32
669extern "C" {
670 char *__unDName(char *demangled, const char *mangled, int out_len,
671 void * (* pAlloc )(size_t), void (* pFree )(void *),
672 unsigned short int flags);
673}
674#endif
675
676////////////////////////////////////////////////////////////////////////////////
677/// Find a template decl within N nested namespaces, 0<=N<inf
678/// Assumes 1 and only 1 template present and 1 and only 1 entity contained
679/// by the namespace. Example: `ns1::ns2::..::%nsN::%myTemplate`
680/// Returns nullptr in case of error
681
682static clang::ClassTemplateDecl* FindTemplateInNamespace(clang::Decl* decl)
683{
684 using namespace clang;
685 if (NamespaceDecl* nsd = llvm::dyn_cast<NamespaceDecl>(decl)){
686 return FindTemplateInNamespace(*nsd->decls_begin());
687 }
688
689 if (ClassTemplateDecl* ctd = llvm::dyn_cast<ClassTemplateDecl>(decl)){
690 return ctd;
691 }
692
693 return nullptr; // something went wrong.
694}
695
696//______________________________________________________________________________
697//
698//
699//
700
701int TCling_GenerateDictionary(const std::vector<std::string> &classes,
702 const std::vector<std::string> &headers,
703 const std::vector<std::string> &fwdDecls,
704 const std::vector<std::string> &unknown)
705{
706 //This function automatically creates the "LinkDef.h" file for templated
707 //classes then executes CompileMacro on it.
708 //The name of the file depends on the class name, and it's not generated again
709 //if the file exist.
710 if (classes.empty()) {
711 return 0;
712 }
713 // Use the name of the first class as the main name.
714 const std::string& className = classes[0];
715 //(0) prepare file name
716 TString fileName = "AutoDict_";
717 std::string::const_iterator sIt;
718 for (sIt = className.begin(); sIt != className.end(); ++sIt) {
719 if (*sIt == '<' || *sIt == '>' ||
720 *sIt == ' ' || *sIt == '*' ||
721 *sIt == ',' || *sIt == '&' ||
722 *sIt == ':') {
723 fileName += '_';
724 }
725 else {
726 fileName += *sIt;
727 }
728 }
729 if (classes.size() > 1) {
730 Int_t chk = 0;
731 std::vector<std::string>::const_iterator it = classes.begin();
732 while ((++it) != classes.end()) {
733 for (UInt_t cursor = 0; cursor != it->length(); ++cursor) {
734 chk = chk * 3 + it->at(cursor);
735 }
736 }
737 fileName += TString::Format("_%u", chk);
738 }
739 fileName += ".cxx";
740 if (gSystem->AccessPathName(fileName) != 0) {
741 //file does not exist
742 //(1) prepare file data
743 // If STL, also request iterators' operators.
744 // vector is special: we need to check whether
745 // vector::iterator is a typedef to pointer or a
746 // class.
747 static const std::set<std::string> sSTLTypes {
748 "vector","list","forward_list","deque","map","unordered_map","multimap",
749 "unordered_multimap","set","unordered_set","multiset","unordered_multiset",
750 "queue","priority_queue","stack","iterator"};
751 std::vector<std::string>::const_iterator it;
752 std::string fileContent("");
753 for (it = headers.begin(); it != headers.end(); ++it) {
754 fileContent += "#include \"" + *it + "\"\n";
755 }
756 for (it = unknown.begin(); it != unknown.end(); ++it) {
757 TClass* cl = TClass::GetClass(it->c_str());
758 if (cl && cl->GetDeclFileName()) {
759 TString header = gSystem->BaseName(cl->GetDeclFileName());
762 while (dirbase.Length() && dirbase != "."
763 && dirbase != "include" && dirbase != "inc"
764 && dirbase != "prec_stl") {
766 dir = gSystem->GetDirName(dir);
767 }
768 fileContent += TString("#include \"") + header + "\"\n";
769 }
770 }
771 for (it = fwdDecls.begin(); it != fwdDecls.end(); ++it) {
772 fileContent += "class " + *it + ";\n";
773 }
774 fileContent += "#ifdef __CLING__ \n";
775 fileContent += "#pragma link C++ nestedclasses;\n";
776 fileContent += "#pragma link C++ nestedtypedefs;\n";
777 for (it = classes.begin(); it != classes.end(); ++it) {
778 std::string n(*it);
779 size_t posTemplate = n.find('<');
780 std::set<std::string>::const_iterator iSTLType = sSTLTypes.end();
781 if (posTemplate != std::string::npos) {
782 n.erase(posTemplate, std::string::npos);
783 if (n.compare(0, 5, "std::") == 0) {
784 n.erase(0, 5);
785 }
786 iSTLType = sSTLTypes.find(n);
787 }
788 fileContent += "#pragma link C++ class ";
789 fileContent += *it + "+;\n" ;
790 if (iSTLType == sSTLTypes.end()) {
791 // Not an STL class; we need to allow the I/O of contained
792 // classes (now that we have a dictionary for them).
793 fileContent += "#pragma link C++ class " + *it + "::*+;\n" ;
794 }
795 }
796 fileContent += "#endif\n";
797 //end(1)
798 //(2) prepare the file
800 filePointer = fopen(fileName, "w");
801 if (filePointer == nullptr) {
802 //can't open a file
803 return 1;
804 }
805 //end(2)
806 //write data into the file
807 fprintf(filePointer, "%s", fileContent.c_str());
809 }
810 //(3) checking if we can compile a macro, if not then cleaning
812 gErrorIgnoreLevel = kWarning; // no "Info: creating library..."
813 Int_t ret = gSystem->CompileMacro(fileName, "k");
815 if (ret == 0) { //can't compile a macro
816 return 2;
817 }
818 //end(3)
819 return 0;
820}
821
822int TCling_GenerateDictionary(const std::string& className,
823 const std::vector<std::string> &headers,
824 const std::vector<std::string> &fwdDecls,
825 const std::vector<std::string> &unknown)
826{
827 //This function automatically creates the "LinkDef.h" file for templated
828 //classes then executes CompileMacro on it.
829 //The name of the file depends on the class name, and it's not generated again
830 //if the file exist.
831 std::vector<std::string> classes;
832 classes.push_back(className);
834}
835
836//______________________________________________________________________________
837//
838//
839//
840
841// It is a "fantom" method to synchronize user keyboard input
842// and ROOT prompt line (for WIN32)
843const char* fantomline = "TRint::EndOfLineAction();";
844
845//______________________________________________________________________________
846//
847//
848//
849
850void* TCling::fgSetOfSpecials = nullptr;
851
852//______________________________________________________________________________
853//
854// llvm error handler through exceptions; see also cling/UserInterface
855//
856namespace {
857 // Handle fatal llvm errors by throwing an exception.
858 // Yes, throwing exceptions in error handlers is bad.
859 // Doing nothing is pretty terrible, too.
860 void exceptionErrorHandler(void * /*user_data*/,
861 const char *reason,
862 bool /*gen_crash_diag*/) {
863 throw std::runtime_error(std::string(">>> Interpreter compilation error:\n") + reason);
864 }
865}
866
867//______________________________________________________________________________
868//
869//
870//
871
872////////////////////////////////////////////////////////////////////////////////
873
874namespace{
875 // An instance of this class causes the diagnostics of clang to be suppressed
876 // during its lifetime
877 class clangDiagSuppr {
878 public:
879 clangDiagSuppr(clang::DiagnosticsEngine& diag): fDiagEngine(diag){
880 fOldDiagValue = fDiagEngine.getIgnoreAllWarnings();
881 fDiagEngine.setIgnoreAllWarnings(true);
882 }
883
885 fDiagEngine.setIgnoreAllWarnings(fOldDiagValue);
886 }
887 private:
888 clang::DiagnosticsEngine& fDiagEngine;
889 bool fOldDiagValue;
890 };
891
892}
893
894////////////////////////////////////////////////////////////////////////////////
895/// Allow calling autoparsing from TMetaUtils
897{
898 return gCling->AutoParse(cname);
899}
900
901////////////////////////////////////////////////////////////////////////////////
902/// Try hard to avoid looking up in the Cling database as this could enduce
903/// an unwanted autoparsing.
904
906 std::string &result)
907{
908 result.clear();
909
910 unsigned long offset = 0;
911 if (strncmp(tname.c_str(), "const ", 6) == 0) {
912 offset = 6;
913 }
914 unsigned long end = tname.length();
915 while( end && (tname[end-1]=='&' || tname[end-1]=='*' || tname[end-1]==']') ) {
916 if ( tname[end-1]==']' ) {
917 --end;
918 while ( end && tname[end-1]!='[' ) --end;
919 }
920 --end;
921 }
922 std::string innerbuf;
923 const char *inner;
924 if (end != tname.length()) {
925 innerbuf = tname.substr(offset,end-offset);
926 inner = innerbuf.c_str();
927 } else {
928 inner = tname.c_str()+offset;
929 }
930
931 //if (strchr(tname.c_str(),'[')!=0) fprintf(stderr,"DEBUG: checking on %s vs %s %lu %lu\n",tname.c_str(),inner,offset,end);
932 if (gROOT->GetListOfClasses()->FindObject(inner)
934 // This is a known class.
935 return true;
936 }
937
938 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
939 TDataType *type = (TDataType *)typeTable->THashTable::FindObject( inner );
940 if (type) {
941 // This is a raw type and an already loaded typedef.
942 const char *newname = type->GetFullTypeName();
943 if (type->GetType() == kLong64_t) {
944 newname = "Long64_t";
945 } else if (type->GetType() == kULong64_t) {
946 newname = "ULong64_t";
947 }
948 if (strcmp(inner,newname) == 0) {
949 return true;
950 }
951 if (offset) result = "const ";
952 result += newname;
953 if ( end != tname.length() ) {
954 result += tname.substr(end,tname.length()-end);
955 }
956 if (result == tname) result.clear();
957 return true;
958 }
959
960 // Check if the name is an enumerator
962 if (lastPos != inner) // Main switch: case 1 - scoped enum, case 2 global enum
963 {
964 // We have a scope
965 const auto enName = lastPos;
966 const auto scopeNameSize = (lastPos - inner) / sizeof(decltype(*lastPos)) - 2;
967 std::string scopeName{inner, scopeNameSize};
968 // Check if the scope is in the list of classes
969 if (auto scope = static_cast<TClass *>(gROOT->GetListOfClasses()->FindObject(scopeName.c_str()))) {
970 auto enumTable = dynamic_cast<const THashList *>(scope->GetListOfEnums(false));
971 if (enumTable && enumTable->THashList::FindObject(enName))
972 return true;
973 }
974 // It may still be in one of the loaded protoclasses
975 else if (auto scope = static_cast<TProtoClass *>(gClassTable->GetProtoNorm(scopeName.c_str()))) {
976 auto listOfEnums = scope->GetListOfEnums();
977 if (listOfEnums) { // it could be null: no enumerators in the protoclass
978 auto enumTable = dynamic_cast<const THashList *>(listOfEnums);
979 if (enumTable && enumTable->THashList::FindObject(enName))
980 return true;
981 }
982 }
983 } else
984 {
985 // We don't have any scope: this could only be a global enum
986 auto enumTable = dynamic_cast<const THashList *>(gROOT->GetListOfEnums());
987 if (enumTable && enumTable->THashList::FindObject(inner)) return true;
988 }
989
991 {
992 // This is a class name.
993 return true;
994 }
995
996 return false;
997}
998
999////////////////////////////////////////////////////////////////////////////////
1000/// Check if the class name is present in TClassTable.
1001///
1002/// \param[in] tname class name to check.
1003/// \param[out] result If a class name has an alternative name registered in
1004/// TClassTable, it will be copied into this string.
1005bool TClingLookupHelper__CheckInClassTable(const std::string &tname, std::string &result)
1006{
1007 result.clear();
1008
1009 if (gROOT->GetListOfClasses()->FindObject(tname.c_str()) || TClassTable::Check(tname.c_str(), result)) {
1010 // This is a known class.
1011 return true;
1012 }
1013
1014 return false;
1015}
1016
1017////////////////////////////////////////////////////////////////////////////////
1018
1023
1024////////////////////////////////////////////////////////////////////////////////
1025
1027{
1028 return fContent.c_str();
1029}
1030
1031////////////////////////////////////////////////////////////////////////////////
1032/// Append string to the storage if not added already.
1033
1034inline bool TCling::TUniqueString::Append(const std::string& str)
1035{
1036 bool notPresent = fLinesHashSet.emplace(fHashFunc(str)).second;
1037 if (notPresent){
1038 fContent+=str;
1039 }
1040 return notPresent;
1041}
1042
1043std::string TCling::ToString(const char* type, void* obj)
1044{
1045 return fInterpreter->toString(type, obj);
1046}
1047
1048////////////////////////////////////////////////////////////////////////////////
1049///\returns true if the module was loaded.
1050static bool LoadModule(const std::string &ModuleName, cling::Interpreter &interp)
1051{
1052 // When starting up ROOT, cling would load all modulemap files on the include
1053 // paths. However, in a ROOT session, it is very common to run aclic which
1054 // will invoke rootcling and possibly produce a modulemap and a module in
1055 // the current folder.
1056 //
1057 // Before failing, try loading the modulemap in the current folder and try
1058 // loading the requested module from it.
1059 std::string currentDir = gSystem->WorkingDirectory();
1060 assert(!currentDir.empty());
1062 if (gDebug > 2)
1063 ::Info("TCling::__LoadModule", "Preloading module %s. \n",
1064 ModuleName.c_str());
1065
1066 return interp.loadModule(ModuleName, /*Complain=*/true);
1067}
1068
1069////////////////////////////////////////////////////////////////////////////////
1070/// Loads the C++ modules that we require to run any ROOT program. This is just
1071/// supposed to make a C++ module from a modulemap available to the interpreter.
1072static void LoadModules(const std::vector<std::string> &modules, cling::Interpreter &interp)
1073{
1074 for (const auto &modName : modules)
1076}
1077
1078static bool IsFromRootCling() {
1079 // rootcling also uses TCling for generating the dictionary ROOT files.
1080 const static bool foundSymbol = dlsym(RTLD_DEFAULT, "usedToIdentifyRootClingByDlSym");
1081 return foundSymbol;
1082}
1083
1084/// Checks if there is an ASTFile on disk for the given module \c M.
1085static bool HasASTFileOnDisk(clang::Module *M, const clang::Preprocessor &PP, std::string *FullFileName = nullptr)
1086{
1087 const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1088
1089 std::string ModuleFileName;
1090 if (!HSOpts.PrebuiltModulePaths.empty())
1091 // Load the module from *only* in the prebuilt module path.
1092 ModuleFileName = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(M->Name);
1093 if (FullFileName)
1095
1096 return !ModuleFileName.empty();
1097}
1098
1099static bool HaveFullGlobalModuleIndex = false;
1101{
1102 CompilerInstance &CI = *interp.getCI();
1103 Preprocessor &PP = CI.getPreprocessor();
1104 auto ModuleManager = CI.getASTReader();
1106 // StringRef ModuleIndexPath = HSI.getModuleCachePath();
1107 // HeaderSearch& HSI = PP.getHeaderSearchInfo();
1108 // HSI.setModuleCachePath(TROOT::GetSharedLibDir().Data());
1109 std::string ModuleIndexPath = TROOT::GetSharedLibDir().Data();
1110 if (ModuleIndexPath.empty())
1111 return nullptr;
1112 // Get an existing global index. This loads it if not already loaded.
1113 ModuleManager->resetForReload();
1114 ModuleManager->loadGlobalIndex();
1115 GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1116
1117 // For finding modules needing to be imported for fixit messages,
1118 // we need to make the global index cover all modules, so we do that here.
1120 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1121 bool RecreateIndex = false;
1122 for (ModuleMap::module_iterator I = MMap.module_begin(), E = MMap.module_end(); I != E; ++I) {
1123 Module *TheModule = I->second;
1124 // We want the index only of the prebuilt modules.
1126 continue;
1127 LoadModule(TheModule->Name, interp);
1128 RecreateIndex = true;
1129 }
1130 if (RecreateIndex) {
1131 cling::Interpreter::PushTransactionRAII deserRAII(&interp);
1132 clang::GlobalModuleIndex::UserDefinedInterestingIDs IDs;
1133
1134 struct DefinitionFinder : public RecursiveASTVisitor<DefinitionFinder> {
1135 DefinitionFinder(clang::GlobalModuleIndex::UserDefinedInterestingIDs& IDs,
1136 clang::TranslationUnitDecl* TU) : DefinitionIDs(IDs) {
1138 }
1139 bool VisitNamedDecl(NamedDecl *ND) {
1140 if (!ND->isFromASTFile())
1141 return true;
1142 if (!ND->getIdentifier())
1143 return true;
1144
1145 if (ND->getAccess() == AS_protected || ND->getAccess() == AS_private)
1146 return true;
1147
1148 if (TagDecl *TD = llvm::dyn_cast<TagDecl>(ND)) {
1149 if (TD->isCompleteDefinition())
1150 Register(TD);
1151 } else if (NamespaceDecl *NSD = llvm::dyn_cast<NamespaceDecl>(ND)) {
1152 Register(NSD, /*AddSingleEntry=*/ false);
1153 }
1155 Register(TND);
1156 // FIXME: Add the rest...
1157 return true; // continue decending
1158 }
1159 private:
1160 clang::GlobalModuleIndex::UserDefinedInterestingIDs &DefinitionIDs;
1161 void Register(const NamedDecl* ND, bool AddSingleEntry = true) {
1162 assert(ND->isFromASTFile());
1163 // FIXME: All decls should have an owning module once rootcling
1164 // updates its generated decls from within the LookupHelper & co.
1165 if (!ND->hasOwningModule()) {
1166#ifndef NDEBUG
1167 SourceManager &SM = ND->getASTContext().getSourceManager();
1168 SourceLocation Loc = ND->getLocation();
1169 OptionalFileEntryRef FE = SM.getFileEntryRefForID(SM.getFileID(Loc));
1170 (void)FE;
1171 assert(FE->getName().contains("input_line_"));
1172#endif
1173 return;
1174 }
1175
1176 Module *OwningModule = ND->getOwningModule()->getTopLevelModule();
1178 assert(!ND->getName().empty() && "Empty name");
1179 if (AddSingleEntry && DefinitionIDs.count(ND->getName()))
1180 return;
1181 // FIXME: The FileEntry in not stable to serialize.
1182 // FIXME: We might end up with many times with the same module.
1183 // FIXME: We might end up two modules containing a definition.
1184 // FIXME: What do we do if no definition is found.
1185 DefinitionIDs[ND->getName()].push_back(OwningModule->getASTFile());
1186 }
1187 };
1188 DefinitionFinder defFinder(IDs, CI.getASTContext().getTranslationUnitDecl());
1189
1190 llvm::cantFail(GlobalModuleIndex::writeIndex(CI.getFileManager(),
1191 CI.getPCHContainerReader(),
1193 &IDs));
1194 ModuleManager->resetForReload();
1195 ModuleManager->loadGlobalIndex();
1196 GlobalIndex = ModuleManager->getGlobalIndex();
1197 }
1199 }
1200 return GlobalIndex;
1201}
1202
1203static void RegisterCxxModules(cling::Interpreter &clingInterp)
1204{
1205 if (!clingInterp.getCI()->getLangOpts().Modules)
1206 return;
1207
1208 // Loading of a module might deserialize.
1209 cling::Interpreter::PushTransactionRAII deserRAII(&clingInterp);
1210
1211 // Setup core C++ modules if we have any to setup.
1212
1213 // Load libc and stl first.
1214 // Load vcruntime module for windows
1215#ifdef R__WIN32
1216 LoadModule("vcruntime", clingInterp);
1217 LoadModule("services", clingInterp);
1218#endif
1219
1220#ifdef R__MACOSX
1221 LoadModule("Darwin", clingInterp);
1222#else
1223 LoadModule("libc", clingInterp);
1224#endif
1225 LoadModule("std", clingInterp);
1226
1227 LoadModule("_Builtin_intrinsics", clingInterp);
1228
1229 // Load core modules
1230 // This should be vector in order to be able to pass it to LoadModules
1231 std::vector<std::string> CoreModules = {"ROOT_Foundation_C",
1232 "ROOT_Config",
1233 "ROOT_Rtypes",
1234 "ROOT_Foundation_Stage1_NoRTTI",
1235 "Core",
1236 "Rint",
1237 "RIO"};
1238
1240
1241 // Take this branch only from ROOT because we don't need to preload modules in rootcling
1242 if (!IsFromRootCling()) {
1243 std::vector<std::string> CommonModules = {"MathCore"};
1245
1246 // These modules should not be preloaded but they fix issues.
1247 // FIXME: Hist is not a core module but is very entangled to MathCore and
1248 // causes issues.
1249 std::vector<std::string> FIXMEModules = {"Hist"};
1250 clang::CompilerInstance &CI = *clingInterp.getCI();
1251 clang::Preprocessor &PP = CI.getPreprocessor();
1252 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1253 if (MMap.findModule("RInterface"))
1254 FIXMEModules.push_back("RInterface");
1255
1257
1258 GlobalModuleIndex *GlobalIndex = nullptr;
1260 // FIXME: The ASTReader still calls loadGlobalIndex and loads the file
1261 // We should investigate how to suppress it completely.
1262 GlobalIndex = CI.getASTReader()->getGlobalIndex();
1263
1264 llvm::StringSet<> KnownModuleFileNames;
1265 if (GlobalIndex)
1266 GlobalIndex->getKnownModuleFileNames(KnownModuleFileNames);
1267
1268 std::vector<std::string> PendingModules;
1269 PendingModules.reserve(256);
1270 for (auto I = MMap.module_begin(), E = MMap.module_end(); I != E; ++I) {
1271 clang::Module *M = I->second;
1272 assert(M);
1273
1274 // We want to load only already created modules.
1275 std::string FullASTFilePath;
1277 continue;
1278
1280 continue;
1281
1282 if (M->IsUnimportable)
1283 continue;
1284
1285 if (GlobalIndex)
1286 LoadModule(M->Name, clingInterp);
1287 else {
1288 // FIXME: We may be able to remove those checks as cling::loadModule
1289 // checks if a module was alredy loaded.
1290 if (std::find(CoreModules.begin(), CoreModules.end(), M->Name) != CoreModules.end())
1291 continue; // This is a core module which was already loaded.
1292
1293 // Load system modules now and delay the other modules after we have
1294 // loaded all system ones.
1295 if (M->IsSystem)
1296 LoadModule(M->Name, clingInterp);
1297 else
1298 PendingModules.push_back(M->Name);
1299 }
1300 }
1302 }
1303
1304 // Check that the gROOT macro was exported by any core module.
1305 assert(clingInterp.getMacro("gROOT") && "Couldn't load gROOT macro?");
1306
1307 // `ERROR` and `PI` are from loading R related modules, which conflict with
1308 // user's code.
1309 clingInterp.declare(R"CODE(
1310#ifdef PI
1311# undef PI
1312#endif
1313#ifdef ERROR
1314# undef ERROR
1315#endif
1316 )CODE");
1317}
1318
1319static void RegisterPreIncludedHeaders(cling::Interpreter &clingInterp)
1320{
1321 std::string PreIncludes;
1322 bool hasCxxModules = clingInterp.getCI()->getLangOpts().Modules;
1323
1324 // For the list to also include string, we have to include it now.
1325 // rootcling does parts already if needed, e.g. genreflex does not want using
1326 // namespace std.
1327 if (IsFromRootCling()) {
1328 PreIncludes += "#include \"RtypesCore.h\"\n";
1329 } else {
1330 if (!hasCxxModules)
1331 PreIncludes += "#include \"Rtypes.h\"\n";
1332
1334 + gInterpreterClassDef + "\n"
1335 "#undef ClassImp\n"
1336 "#define ClassImp(X);\n";
1337 }
1338 if (!hasCxxModules)
1339 PreIncludes += "#include <string>\n";
1340
1341 // We must include it even when we have modules because it is marked as
1342 // textual in the modulemap due to the nature of the assert header.
1343#ifndef R__WIN32
1344 PreIncludes += "#include <cassert>\n";
1345#endif
1346 PreIncludes += "using namespace std;\n";
1347 clingInterp.declare(PreIncludes);
1348}
1349
1350////////////////////////////////////////////////////////////////////////////////
1351/// Initialize the cling interpreter interface.
1352/// \param name name for TInterpreter
1353/// \param title title for TInterpreter
1354/// \param argv - array of arguments passed to the cling::Interpreter constructor
1355/// e.g. `-DFOO=bar`. The last element of the array must be `nullptr`.
1356/// \param interpLibHandle handle to interpreter library
1357
1358TCling::TCling(const char *name, const char *title, const char* const argv[], void *interpLibHandle)
1359: TInterpreter(name, title), fGlobalsListSerial(-1), fMapfile(nullptr),
1360 fRootmapFiles(nullptr), fLockProcessLine(true), fNormalizedCtxt(nullptr), fLookupHelper(nullptr),
1361 fPrevLoadedDynLibInfo(nullptr), fClingCallbacks(nullptr), fAutoLoadCallBack(nullptr),
1363{
1364 fPrompt[0] = 0;
1365 const bool fromRootCling = IsFromRootCling();
1366
1367 fCxxModulesEnabled = false;
1368#ifdef R__USE_CXXMODULES
1369 fCxxModulesEnabled = true;
1370#endif
1371
1372 llvm::install_fatal_error_handler(&exceptionErrorHandler);
1373
1374 fTemporaries = new std::vector<cling::Value>();
1375
1376 std::vector<std::string> clingArgsStorage;
1377 clingArgsStorage.push_back("cling4root");
1378 for (const char* const* arg = argv; *arg; ++arg)
1379 clingArgsStorage.push_back(*arg);
1380
1381 // rootcling sets its arguments through TROOT::GetExtraInterpreterArgs().
1382 if (!fromRootCling) {
1384
1385 // Add -I early so ASTReader can find the headers.
1386 std::string interpInclude(TROOT::GetEtcDir().Data());
1387 clingArgsStorage.push_back("-I" + interpInclude);
1388
1389 // Add include path to etc/cling.
1390 clingArgsStorage.push_back("-I" + interpInclude + "/cling");
1391
1392 // Add include path to etc/cling.
1393 clingArgsStorage.push_back("-I" + interpInclude + "/cling/plugins/include");
1394
1395 // Add the root include directory and etc/ to list searched by default.
1396 clingArgsStorage.push_back(std::string(("-I" + TROOT::GetIncludeDir()).Data()));
1397
1398 // Add the current path to the include path
1399 // TCling::AddIncludePath(".");
1400
1401 // Attach the PCH (unless we have C++ modules enabled which provide the
1402 // same functionality).
1403 if (!fCxxModulesEnabled) {
1404 std::string pchFilename = interpInclude + "/allDict.cxx.pch";
1405 if (gSystem->Getenv("ROOT_PCH")) {
1406 pchFilename = gSystem->Getenv("ROOT_PCH");
1407 }
1408
1409 clingArgsStorage.push_back("-include-pch");
1410 clingArgsStorage.push_back(pchFilename);
1411 }
1412
1413 clingArgsStorage.push_back("-Wno-undefined-inline");
1414 clingArgsStorage.push_back("-fsigned-char");
1415 // The -O1 optimization flag has nasty side effects on Windows (32 and 64 bit)
1416 // See the GitHub issues #9809 and #9944
1417 // TODO: to be reviewed after the upgrade of LLVM & Clang
1418#ifndef _MSC_VER
1419 clingArgsStorage.push_back("-O1");
1420 // Disable optimized register allocation which is turned on automatically
1421 // by -O1, but seems to require -O2 to not explode in run time.
1422 clingArgsStorage.push_back("-mllvm");
1423 clingArgsStorage.push_back("-optimize-regalloc=0");
1424#endif
1425 }
1426
1427 // Process externally passed arguments if present.
1428 std::optional<std::string> EnvOpt = llvm::sys::Process::GetEnv("EXTRA_CLING_ARGS");
1429 if (EnvOpt.has_value()) {
1431 while (!Env.empty()) {
1432 StringRef Arg;
1433 std::tie(Arg, Env) = Env.split(' ');
1434 clingArgsStorage.push_back(Arg.str());
1435 }
1436 }
1437
1438 auto GetEnvVarPath = [](const std::string &EnvVar, std::vector<std::string> &Paths) {
1439 std::optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(EnvVar);
1440 if (EnvOpt.has_value()) {
1442 while (!Env.empty()) {
1443 StringRef Arg;
1444 std::tie(Arg, Env) = Env.split(ROOT::FoundationUtils::GetEnvPathSeparator());
1445 if (std::find(Paths.begin(), Paths.end(), Arg.str()) == Paths.end())
1446 Paths.push_back(Arg.str());
1447 }
1448 }
1449 };
1450
1451 if (fCxxModulesEnabled) {
1452 std::vector<std::string> Paths;
1453 // ROOT usually knows better where its libraries are. This way we can
1454 // discover modules without having to should thisroot.sh and should fix
1455 // gnuinstall.
1456 Paths.push_back(TROOT::GetSharedLibDir().Data());
1457 GetEnvVarPath("CLING_PREBUILT_MODULE_PATH", Paths);
1458 std::string EnvVarPath;
1459 for (const std::string& P : Paths)
1461 // FIXME: We should make cling -fprebuilt-module-path work.
1462 gSystem->Setenv("CLING_PREBUILT_MODULE_PATH", EnvVarPath.c_str());
1463 }
1464
1465 // FIXME: This only will enable frontend timing reports.
1466 EnvOpt = llvm::sys::Process::GetEnv("ROOT_CLING_TIMING");
1467 if (EnvOpt.has_value())
1468 clingArgsStorage.push_back("-ftime-report");
1469
1470 // Add the overlay file. Note that we cannot factor it out for both root
1471 // and rootcling because rootcling activates modules only if -cxxmodule
1472 // flag is passed.
1474 // For now we prefer rootcling to enumerate explicitly its modulemaps.
1475 std::vector<std::string> ModuleMaps;
1476 std::string ModuleMapSuffix = ROOT::FoundationUtils::GetPathSeparator() + "ROOT.modulemap";
1477 ModuleMaps.push_back(TROOT::GetIncludeDir().Data() + ModuleMapSuffix);
1478 GetEnvVarPath("CLING_MODULEMAP_FILES", ModuleMaps);
1479
1480 std::string cwd = gSystem->WorkingDirectory();
1481 // Give highest precedence of the modulemap in the cwd if any.
1482 if (llvm::sys::fs::exists(cwd + ModuleMapSuffix))
1483 ModuleMaps.push_back(cwd + ModuleMapSuffix);
1484
1485 for (const std::string& M : ModuleMaps)
1486 clingArgsStorage.push_back("-fmodule-map-file=" + M);
1487
1488 std::string ModulesCachePath;
1489 EnvOpt = llvm::sys::Process::GetEnv("CLING_MODULES_CACHE_PATH");
1490 if (EnvOpt.has_value()){
1492 assert(llvm::sys::fs::exists(Env) && "Path does not exist!");
1493 ModulesCachePath = Env.str();
1494 } else {
1496 }
1497
1498 clingArgsStorage.push_back("-fmodules-cache-path=" + ModulesCachePath);
1499 }
1500
1501 std::vector<const char*> interpArgs;
1502 for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1504 interpArgs.push_back(iArg->c_str());
1505
1506 // Activate C++ modules support. If we are running within rootcling, it's up
1507 // to rootcling to set this flag depending on whether it wants to produce
1508 // C++ modules.
1510 if (fCxxModulesEnabled) {
1511 if (!fromRootCling) {
1512 // We only set this flag, rest is done by the CIFactory.
1513 interpArgs.push_back("-fmodules");
1514 interpArgs.push_back("-fno-implicit-module-maps");
1515 // We should never build modules during runtime, so let's enable the
1516 // module build remarks from clang to make it easier to spot when we do
1517 // this by accident.
1518 interpArgs.push_back("-Rmodule-build");
1519 }
1520 // ROOT implements its AutoLoading upon module's link directives. We
1521 // generate module A { header "A.h" link "A.so" export * } where ROOT's
1522 // facilities use the link directive to dynamically load the relevant
1523 // library. So, we need to suppress clang's default autolink behavior.
1524 interpArgs.push_back("-fno-autolink");
1525 }
1526
1527#ifdef R__FAST_MATH
1528 // Same setting as in rootcling_impl.cxx.
1529 interpArgs.push_back("-ffast-math");
1530#endif
1531
1533 // Add statically injected extra arguments, usually coming from rootcling.
1534 for (const char** extraArgs = TROOT::GetExtraInterpreterArgs();
1535 extraArgs && *extraArgs; ++extraArgs) {
1536 if (!strcmp(*extraArgs, "-resource-dir")) {
1537 // Take the next arg as the llvm resource directory.
1539 } else {
1540 interpArgs.push_back(*extraArgs);
1541 }
1542 }
1543
1544 std::vector<std::string> _empty;
1546 for (const auto &arg: args)
1547 interpArgs.emplace_back(arg.c_str());
1548
1549 // Add the Rdict module file extension.
1550 cling::Interpreter::ModuleFileExtensions extensions;
1551 EnvOpt = llvm::sys::Process::GetEnv("ROOTDEBUG_RDICT");
1552 if (!EnvOpt.has_value())
1553 extensions.push_back(std::make_shared<TClingRdictModuleFileExtension>());
1554
1555 fInterpreter = std::make_unique<cling::Interpreter>(interpArgs.size(),
1556 &(interpArgs[0]),
1559
1560 if (!fInterpreter->getCI()) { // Compiler instance could not be created. See https://its.cern.ch/jira/browse/ROOT-10239
1561 return;
1562 }
1563
1564 // Tell CppInterOp that the cling::Interpreter instance is managed externally by ROOT
1565 // Sets the interpreter by passing the fInterpreter handle as soon as TCling is initialized
1566 Cpp::UseExternalInterpreter((Cpp::TInterp_t*)fInterpreter.get());
1567
1568 // Don't check whether modules' files exist.
1569 fInterpreter->getCI()->getPreprocessorOpts().DisablePCHOrModuleValidation =
1570 DisableValidationForModuleKind::All;
1571
1572 // Until we can disable AutoLoading during Sema::CorrectTypo() we have
1573 // to disable spell checking.
1574 fInterpreter->getCI()->getLangOpts().SpellChecking = false;
1575
1576 // Sync modules on/off between clang and us: clang turns it on for C++ >= 20.
1577 auto isModulesArg = [](const char* arg) { return !strcmp(arg, "-fmodules"); };
1578 bool hasModulesArg = std::find_if(interpArgs.begin(), interpArgs.end(), isModulesArg) != interpArgs.end();
1579 fInterpreter->getCI()->getLangOpts().Modules = hasModulesArg;
1580
1581 // We need stream that doesn't close its file descriptor, thus we are not
1582 // using llvm::outs. Keeping file descriptor open we will be able to use
1583 // the results in pipes (Savannah #99234).
1584 static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO, /*ShouldClose*/false);
1585 fMetaProcessor = std::make_unique<cling::MetaProcessor>(*fInterpreter, fMPOuts);
1586
1589
1590 // We are now ready (enough is loaded) to init the list of opaque typedefs.
1596
1597 // Disallow auto-parsing in rootcling
1599
1600 ResetAll();
1601
1602 // Enable dynamic lookup
1603 if (!fromRootCling) {
1604 fInterpreter->enableDynamicLookup();
1605 }
1606
1607 // Enable ClinG's DefinitionShadower for ROOT.
1608 fInterpreter->getRuntimeOptions().AllowRedefinition = 1;
1609 auto &Policy = const_cast<clang::PrintingPolicy &>(fInterpreter->getCI()->getASTContext().getPrintingPolicy());
1610 // Print 'a<b<c> >' rather than 'a<b<c>>'.
1611 // FIXME: We should probably switch to the default printing policy setting
1612 // after adjusting tons of reference files.
1613 Policy.SplitTemplateClosers = true;
1614 // Keep default templare arguments, required for dictionary generation.
1615 Policy.SuppressDefaultTemplateArgs = false;
1616
1617
1618 // Attach cling callbacks last; they might need TROOT::fInterpreter
1619 // and should thus not be triggered during the equivalent of
1620 // TROOT::fInterpreter = new TCling;
1621 std::unique_ptr<TClingCallbacks>
1625 fInterpreter->setCallbacks(std::move(clingCallbacks));
1626
1627 if (!fromRootCling) {
1628 cling::DynamicLibraryManager& DLM = *fInterpreter->getDynamicLibraryManager();
1629 // Make sure cling looks into ROOT's libdir, even if not part of LD_LIBRARY_PATH
1630 // e.g. because of an RPATH build.
1631 DLM.addSearchPath(TROOT::GetSharedLibDir().Data(), /*isUser=*/true,
1632 /*prepend=*/true);
1633 auto ShouldPermanentlyIgnore = [](llvm::StringRef FileName) -> bool{
1634 llvm::StringRef stem = llvm::sys::path::stem(FileName);
1635 return stem.starts_with("libNew") || stem.starts_with("libcppyy_backend");
1636 };
1637 // Initialize the dyld for AutoloadLibraryGenerator.
1638 DLM.initializeDyld(ShouldPermanentlyIgnore);
1639 }
1640}
1641
1642
1643////////////////////////////////////////////////////////////////////////////////
1644/// Destroy the interpreter interface.
1645
1647{
1648 // ROOT's atexit functions require the interepreter to be available.
1649 // Run them before shutting down.
1650 if (!IsFromRootCling())
1651 GetInterpreterImpl()->runAtExitFuncs();
1652 fIsShuttingDown = true;
1653 delete fMapfile;
1654 delete fRootmapFiles;
1655 delete fTemporaries;
1656 delete fNormalizedCtxt;
1657 delete fLookupHelper;
1658 gCling = nullptr;
1659}
1660
1661////////////////////////////////////////////////////////////////////////////////
1662/// Initialize the interpreter, once TROOT::fInterpreter is set.
1663
1665{
1666 if (!fClingCallbacks) // Compiler instance could not be created. See https://its.cern.ch/jira/browse/ROOT-10239
1667 return;
1669
1670 // We are set up. Enable ROOT's AutoLoading.
1671 if (IsFromRootCling())
1672 return;
1673
1674 // Read the rules before enabling the auto loading to not inadvertently
1675 // load the libraries for the classes concerned even-though the user is
1676 // *not* using them.
1677 // Note this call must happen before the first call to LoadLibraryMap.
1678 assert(GetRootMapFiles() == nullptr && "Must be called before LoadLibraryMap!");
1679 TClass::ReadRules(); // Read the default customization rules ...
1680
1682 SetClassAutoLoading(true);
1683}
1684
1686{
1687 fIsShuttingDown = true;
1688 ResetGlobals();
1689}
1690
1691////////////////////////////////////////////////////////////////////////////////
1692/// Helper to initialize TVirtualStreamerInfo's factor early.
1693/// Use static initialization to insure only one TStreamerInfo is created.
1695{
1696 // Use lambda since SetFactory return void.
1697 auto setFactory = []() {
1699 return kTRUE;
1700 };
1701 static bool doneFactory = setFactory();
1702 return doneFactory; // avoid unused variable warning.
1703}
1704
1705////////////////////////////////////////////////////////////////////////////////
1706/// Register Rdict data for future loading by LoadPCM;
1707
1708void TCling::RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
1709{
1710 if (IsFromRootCling())
1711 return;
1712
1713 if (llvm::sys::fs::exists(pcmFileNameFullPath)) {
1714 ::Error("TCling::RegisterRdictForLoadPCM", "Rdict '%s' is both in Module extension and in File system.", pcmFileNameFullPath.c_str());
1715 return;
1716 }
1717
1718 // The pcmFileNameFullPath must be resolved already because we cannot resolve
1719 // a link to a non-existent file.
1721}
1722
1723////////////////////////////////////////////////////////////////////////////////
1724/// Tries to load a PCM from TFile; returns true on success.
1725/// The caller of this function should be holding the ROOT Write lock.
1726
1728{
1729 auto listOfKeys = pcmFile.GetListOfKeys();
1730
1731 // This is an empty pcm
1732 if (listOfKeys && ((listOfKeys->GetSize() == 0) || // Nothing here, or
1733 ((listOfKeys->GetSize() == 1) && // only one, and
1734 !strcmp(((TKey *)listOfKeys->At(0))->GetName(), "EMPTY") // name is EMPTY
1735 ))) {
1736 return;
1737 }
1738
1740 if (gDebug > 1)
1741 ::Info("TCling::LoadPCMImpl", "reading protoclasses for %s \n", pcmFile.GetName());
1742
1744 pcmFile.GetObject("__Enums", enums);
1745 if (enums) {
1746 // Cache the pointers
1747 auto listOfGlobals = gROOT->GetListOfGlobals();
1748 auto listOfEnums = dynamic_cast<THashList *>(gROOT->GetListOfEnums());
1749 // Loop on enums and then on enum constants
1750 for (auto selEnum : *enums) {
1751 const char *enumScope = selEnum->GetTitle();
1752 const char *enumName = selEnum->GetName();
1753 if (strcmp(enumScope, "") == 0) {
1754 // This is a global enum and is added to the
1755 // list of enums and its constants to the list of globals
1756 if (!listOfEnums->THashList::FindObject(enumName)) {
1757 ((TEnum *)selEnum)->SetClass(nullptr);
1758 listOfEnums->Add(selEnum);
1759 }
1760 for (auto enumConstant : *static_cast<TEnum *>(selEnum)->GetConstants()) {
1761 if (!listOfGlobals->FindObject(enumConstant)) {
1763 }
1764 }
1765 } else {
1766 // This enum is in a namespace. A TClass entry is bootstrapped if
1767 // none exists yet and the enum is added to it
1769 if (!nsTClassEntry) {
1771 }
1772 auto listOfEnums = nsTClassEntry->fEnums.load();
1773 if (!listOfEnums) {
1774 if ((kIsClass | kIsStruct | kIsUnion) & nsTClassEntry->Property()) {
1775 // For this case, the list will be immutable once constructed
1776 // (i.e. in this case, by the end of this routine).
1778 } else {
1779 // namespaces can have enums added to them
1781 }
1782 }
1783 if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)) {
1784 ((TEnum *)selEnum)->SetClass(nsTClassEntry);
1785 listOfEnums->Add(selEnum);
1786 }
1787 }
1788 }
1789 enums->Clear();
1790 delete enums;
1791 }
1792
1793 pcmFile.GetObject("__ProtoClasses", protoClasses);
1794
1795 if (protoClasses) {
1796 for (auto obj : *protoClasses) {
1797 TProtoClass *proto = (TProtoClass *)obj;
1799 }
1800 // Now that all TClass-es know how to set them up we can update
1801 // existing TClasses, which might cause the creation of e.g. TBaseClass
1802 // objects which in turn requires the creation of TClasses, that could
1803 // come from the PCH, but maybe later in the loop. Instead of resolving
1804 // a dependency graph the addition to the TClassTable above allows us
1805 // to create these dependent TClasses as needed below.
1806 for (auto proto : *protoClasses) {
1807 if (TClass *existingCl = (TClass *)gROOT->GetListOfClasses()->FindObject(proto->GetName())) {
1808 // We have an existing TClass object. It might be emulated
1809 // or interpreted; we now have more information available.
1810 // Make that available.
1811 if (existingCl->GetState() != TClass::kHasTClassInit) {
1812 DictFuncPtr_t dict = gClassTable->GetDict(proto->GetName());
1813 if (!dict) {
1814 ::Error("TCling::LoadPCM", "Inconsistent TClassTable for %s", proto->GetName());
1815 } else {
1816 // This will replace the existing TClass.
1817 TClass *ncl = (*dict)();
1818 if (ncl)
1819 ncl->PostLoadCheck();
1820 }
1821 }
1822 }
1823 }
1824
1825 protoClasses->Clear(); // Ownership was transfered to TClassTable.
1826 delete protoClasses;
1827 }
1828
1830 pcmFile.GetObject("__Typedefs", dataTypes);
1831 if (dataTypes) {
1832 for (auto typedf : *dataTypes)
1833 gROOT->GetListOfTypes()->Add(typedf);
1834 dataTypes->Clear(); // Ownership was transfered to TListOfTypes.
1835 delete dataTypes;
1836 }
1837}
1838
1839////////////////////////////////////////////////////////////////////////////////
1840/// Tries to load a rdict PCM, issues diagnostics if it fails.
1841/// The caller of this function should be holding the ROOT Write lock.
1842
1844{
1847 assert(!pcmFileNameFullPath.empty());
1848 assert(llvm::sys::path::is_absolute(pcmFileNameFullPath));
1849
1850 // Easier to work with the ROOT interfaces.
1852
1853 // Prevent the ROOT-PCMs hitting this during auto-load during
1854 // JITting - which will cause recursive compilation.
1855 // Avoid to call the plugin manager at all.
1857
1859 llvm::SaveAndRestore<Int_t> SaveGDebug(gDebug);
1860 if (gDebug > 5) {
1861 gDebug -= 5;
1862 ::Info("TCling::LoadPCM", "Loading ROOT PCM %s", pcmFileName.Data());
1863 } else {
1864 gDebug = 0;
1865 }
1866
1867 if (llvm::sys::fs::is_symlink_file(pcmFileNameFullPath))
1869
1871 if (pendingRdict != fPendingRdicts.end()) {
1872 llvm::StringRef pcmContent = pendingRdict->second;
1874 std::string RDictFileOpts = pcmFileNameFullPath + "?filetype=pcm";
1876
1877 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
1879 // Currently the module file are never unloaded (even if the library is
1880 // unloaded) and, of course, never reloaded.
1881 // Consequently, we must NOT remove the `pendingRdict` from the list
1882 // of pending dictionary, otherwise if a library is unloaded and then
1883 // reload we will be unable to update properly the TClass object
1884 // (because we wont be able to load the rootpcm file by executing the
1885 // above lines)
1886
1887 return;
1888 }
1889
1890 if (!llvm::sys::fs::exists(pcmFileNameFullPath)) {
1891 ::Error("TCling::LoadPCM", "ROOT PCM %s file does not exist",
1892 pcmFileNameFullPath.data());
1893 if (!fPendingRdicts.empty())
1894 for (const auto &rdict : fPendingRdicts)
1895 ::Info("TCling::LoadPCM", "In-memory ROOT PCM candidate %s\n",
1896 rdict.first.c_str());
1897 return;
1898 }
1899
1900 if (!gROOT->IsRootFile(pcmFileName)) {
1901 Fatal("LoadPCM", "The file %s is not a ROOT as was expected\n", pcmFileName.Data());
1902 return;
1903 }
1904 TFile pcmFile(pcmFileName + "?filetype=pcm", "READ");
1906}
1907
1908//______________________________________________________________________________
1909
1910namespace {
1911 using namespace clang;
1912
1913 class ExtLexicalStorageAdder: public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1914 // This class is to be considered an helper for autoparsing.
1915 // It visits the AST and marks all classes (in all of their redeclarations)
1916 // with the setHasExternalLexicalStorage method.
1917 public:
1918 bool VisitRecordDecl(clang::RecordDecl* rcd){
1919 if (gDebug > 2)
1920 Info("ExtLexicalStorageAdder",
1921 "Adding external lexical storage to class %s",
1922 rcd->getNameAsString().c_str());
1923 auto reDeclPtr = rcd->getMostRecentDecl();
1924 do {
1925 reDeclPtr->setHasExternalLexicalStorage();
1926 } while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1927
1928 return false;
1929 }
1930 };
1931
1932
1933}
1934
1935////////////////////////////////////////////////////////////////////////////////
1936///\returns true if the module map was loaded, false on error or if the map was
1937/// already loaded.
1939 const std::string &ModuleMapName /*= "module.modulemap"*/) const
1940{
1941 assert(llvm::sys::path::is_absolute(FullPath));
1942 Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
1943 FileManager &FM = PP.getFileManager();
1944 // FIXME: In a ROOT session we can add an include path (through .I /inc/path)
1945 // We should look for modulemap files there too.
1946 if (auto DE = FM.getOptionalDirectoryRef(FullPath)) {
1947 HeaderSearch &HS = PP.getHeaderSearchInfo();
1948 HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1949 const auto &ModPaths = HSOpts.PrebuiltModulePaths;
1950 bool pathExists = std::find(ModPaths.begin(), ModPaths.end(), FullPath) != ModPaths.end();
1951 if (!pathExists)
1952 HSOpts.AddPrebuiltModulePath(FullPath);
1953 // We cannot use HS.lookupModuleMapFile(DE, /*IsFramework*/ false);
1954 // because its internal call to getFile has CacheFailure set to true.
1955 // In our case, modulemaps can appear any time due to ACLiC.
1956 // Code copied from HS.lookupModuleMapFile.
1957 llvm::SmallString<256> ModuleMapFileName(DE->getName());
1958 llvm::sys::path::append(ModuleMapFileName, ModuleMapName);
1959 if (auto FE = FM.getOptionalFileRef(ModuleMapFileName, /*openFile*/ false,
1960 /*CacheFailure*/ false)) {
1961 if (!HS.loadModuleMapFile(*FE, /*IsSystem*/ false))
1962 return true;
1963 Error("RegisterPrebuiltModulePath", "Could not load modulemap in %s", ModuleMapFileName.c_str());
1964 }
1965 }
1966 return false;
1967}
1968
1969////////////////////////////////////////////////////////////////////////////////
1970/// List of dicts that have the PCM information already in the PCH.
1971static const std::unordered_set<std::string> gIgnoredPCMNames = {"libCore",
1972 "libRint",
1973 "libThread",
1974 "libRIO",
1975 "libImt",
1976 "libMultiProc",
1977 "libcomplexDict",
1978 "libdequeDict",
1979 "liblistDict",
1980 "libforward_listDict",
1981 "libvectorDict",
1982 "libmapDict",
1983 "libmultimap2Dict",
1984 "libmap2Dict",
1985 "libmultimapDict",
1986 "libsetDict",
1987 "libmultisetDict",
1988 "libunordered_setDict",
1989 "libunordered_multisetDict",
1990 "libunordered_mapDict",
1991 "libunordered_multimapDict",
1992 "libvalarrayDict",
1993 "G__GenVector32",
1994 "G__Smatrix32"};
1995
1996static void PrintDlError(const char *dyLibName, const char *modulename)
1997{
1998#ifdef R__WIN32
1999 char dyLibError[1000];
2001 dyLibError, sizeof(dyLibError), NULL);
2002#else
2003 const char *dyLibError = dlerror();
2004#endif
2005 ::Error("TCling::RegisterModule", "Cannot open shared library %s for dictionary %s:\n %s", dyLibName, modulename,
2006 (dyLibError) ? dyLibError : "");
2007}
2008
2009////////////////////////////////////////////////////////////////////////////////
2010// Update all the TClass registered in fClassesToUpdate
2011
2013{
2014 while (!fClassesToUpdate.empty()) {
2015 TClass *oldcl = fClassesToUpdate.back().first;
2016 // If somehow the TClass has already been loaded (maybe it was registered several time),
2017 // we skip it. Otherwise, the existing TClass is in mode kInterpreted, kEmulated or
2018 // maybe even kForwardDeclared and needs to replaced.
2019 if (oldcl->GetState() != TClass::kHasTClassInit) {
2020 // if (gDebug > 2) Info("RegisterModule", "Forcing TClass init for %s", oldcl->GetName());
2021 DictFuncPtr_t dict = fClassesToUpdate.back().second;
2022 fClassesToUpdate.pop_back();
2023 // Calling func could manipulate the list so, let maintain the list
2024 // then call the dictionary function.
2025 TClass *ncl = dict();
2026 if (ncl) ncl->PostLoadCheck();
2027 } else {
2028 fClassesToUpdate.pop_back();
2029 }
2030 }
2031}
2032////////////////////////////////////////////////////////////////////////////////
2033/// Inject the module named "modulename" into cling; load all headers.
2034/// headers is a 0-terminated array of header files to `#include` after
2035/// loading the module. The module is searched for in all $LD_LIBRARY_PATH
2036/// entries (or %PATH% on Windows).
2037/// This function gets called by the static initialization of dictionary
2038/// libraries.
2039/// The payload code is injected "as is" in the interpreter.
2040/// The value of 'triggerFunc' is used to find the shared library location.
2041/// The caller of this function should be holding the ROOT Write lock.
2042
2044 const char** headers,
2045 const char** includePaths,
2046 const char* payloadCode,
2047 const char* fwdDeclsCode,
2048 void (*triggerFunc)(),
2050 const char** classesHeaders,
2051 Bool_t lateRegistration /*=false*/,
2052 Bool_t hasCxxModule /*=false*/)
2053{
2054 const bool fromRootCling = IsFromRootCling();
2055 // We need the dictionary initialization but we don't want to inject the
2056 // declarations into the interpreter, except for those we really need for
2057 // I/O; see rootcling.cxx after the call to TCling__GetInterpreter().
2058 if (fromRootCling) return;
2059
2060 // When we cannot provide a module for the library we should enable header
2061 // parsing. This 'mixed' mode ensures gradual migration to modules.
2062 llvm::SaveAndRestore<bool> SaveHeaderParsing(fHeaderParsingOnDemand);
2064
2065 // Treat Aclic Libs in a special way. Do not delay the parsing.
2067 bool isACLiC = strstr(modulename, "_ACLiC_dict") != nullptr;
2069 if (gDebug>1)
2070 Info("TCling::RegisterModule",
2071 "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
2073 }
2074
2075
2076 // Make sure we relookup symbols that were search for before we loaded
2077 // their autoparse information. We could be more subtil and remove only
2078 // the failed one or only the one in this module, but for now this is
2079 // better than nothing.
2080 fLookedUpClasses.clear();
2081
2082 // Make sure we do not set off AutoLoading or autoparsing during the
2083 // module registration!
2085
2086 for (const char** inclPath = includePaths; *inclPath; ++inclPath) {
2088 }
2089 cling::Transaction* T = nullptr;
2090 // Put the template decls and the number of arguments to skip in the TNormalizedCtxt
2092 const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
2093 const int nArgsToSkip = fwdDeclArgToSkipPair.second;
2094 auto compRes = fInterpreter->declare(fwdDecl.c_str(), &T);
2095 assert(cling::Interpreter::kSuccess == compRes &&
2096 "A fwd declaration could not be compiled");
2097 if (compRes!=cling::Interpreter::kSuccess){
2098 Warning("TCling::RegisterModule",
2099 "Problems in declaring string '%s' were encountered.",
2100 fwdDecl.c_str()) ;
2101 continue;
2102 }
2103
2104 // Drill through namespaces recursively until the template is found
2105 if(ClassTemplateDecl* TD = FindTemplateInNamespace(T->getFirstDecl().getSingleDecl())){
2107 }
2108
2109 }
2110
2111 // FIXME: Remove #define __ROOTCLING__ once PCMs are there.
2112 // This is used to give Sema the same view on ACLiC'ed files (which
2113 // are then #included through the dictionary) as rootcling had.
2115 if (payloadCode)
2116 code += payloadCode;
2117
2118 std::string dyLibName = cling::DynamicLibraryManager::getSymbolLocation(triggerFunc);
2119 assert(!llvm::sys::fs::is_symlink_file(dyLibName));
2120
2121 if (dyLibName.empty()) {
2122 ::Error("TCling::RegisterModule", "Dictionary trigger function for %s not found", modulename);
2123 return;
2124 }
2125
2126 // The triggerFunc may not be in a shared object but in an executable.
2127 bool isSharedLib = cling::DynamicLibraryManager::isSharedLibrary(dyLibName);
2128
2129 bool wasDlopened = false;
2130
2131 // If this call happens after dlopen has finished (i.e. late registration)
2132 // there is no need to dlopen the library recursively. See ROOT-8437 where
2133 // the dyLibName would correspond to the binary.
2134 if (!lateRegistration) {
2135
2136 if (isSharedLib) {
2137 // We need to open the dictionary shared library, to resolve symbols
2138 // requested by the JIT from it: as the library is currently being dlopen'ed,
2139 // its symbols are not yet reachable from the process.
2140 // Recursive dlopen seems to work just fine.
2141 void* dyLibHandle = dlopen(dyLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
2142 if (dyLibHandle) {
2144 wasDlopened = true;
2145 } else {
2147 }
2148 }
2149 } // if (!lateRegistration)
2150
2152 // We now parse the forward declarations. All the classes are then modified
2153 // in order for them to have an external lexical storage.
2154 std::string fwdDeclsCodeLessEnums;
2155 {
2156 // Search for enum forward decls and only declare them if no
2157 // declaration exists yet.
2158 std::string fwdDeclsLine;
2159 std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
2160 std::vector<std::string> scopes;
2161 while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
2162 const auto enumPos = fwdDeclsLine.find("enum __attribute__((annotate(\"");
2163 // We check if the line contains a fwd declaration of an enum
2164 if (enumPos != std::string::npos) {
2165 // We clear the scopes which we may have carried from a previous iteration
2166 scopes.clear();
2167 // We check if the enum is not in a scope. If yes, save its name
2168 // and the names of the enclosing scopes.
2169 if (enumPos != 0) {
2170 // it's enclosed in namespaces. We need to understand what they are
2171 auto nsPos = fwdDeclsLine.find("namespace");
2172 R__ASSERT(nsPos < enumPos && "Inconsistent enum and enclosing scope parsing!");
2173 while (nsPos < enumPos && nsPos != std::string::npos) {
2174 // we have a namespace, let's put it in the collection of scopes
2175 const auto nsNameStart = nsPos + 10;
2176 const auto nsNameEnd = fwdDeclsLine.find('{', nsNameStart);
2177 const auto nsName = fwdDeclsLine.substr(nsNameStart, nsNameEnd - nsNameStart);
2178 scopes.push_back(nsName);
2179 nsPos = fwdDeclsLine.find("namespace", nsNameEnd);
2180 }
2181 }
2182 clang::DeclContext* DC = nullptr;
2183 for (auto &&aScope: scopes) {
2184 DC = cling::utils::Lookup::Namespace(&fInterpreter->getSema(), aScope.c_str(), DC);
2185 if (!DC) {
2186 // No decl context means we have to fwd declare the enum.
2187 break;
2188 }
2189 }
2190 if (scopes.empty() || DC) {
2191 // We know the scope; let's look for the enum. For that, look
2192 // for the *last* closing parentheses of an attribute because
2193 // there can be multiple.
2194 size_t posEnumName = fwdDeclsLine.rfind("\"))) ");
2195 R__ASSERT(posEnumName != std::string::npos && "Inconsistent enum fwd decl!");
2196 posEnumName += 5; // skip "\"))) "
2198 ++posEnumName;
2199 size_t posEnumNameEnd = fwdDeclsLine.find(" : ", posEnumName);
2200 R__ASSERT(posEnumNameEnd != std::string::npos && "Inconsistent enum fwd decl (end)!");
2203 // posEnumNameEnd now points to the last character of the name.
2204
2205 std::string enumName = fwdDeclsLine.substr(posEnumName,
2207
2208 if (clang::NamedDecl* enumDecl
2209 = cling::utils::Lookup::Named(&fInterpreter->getSema(),
2210 enumName.c_str(), DC)) {
2211 // We have an existing enum decl (forward or definition);
2212 // skip this.
2213 R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) && "not an enum decl!");
2214 (void)enumDecl;
2215 continue;
2216 }
2217 }
2218 }
2219
2221 }
2222 }
2223
2224 if (!fwdDeclsCodeLessEnums.empty()){ // Avoid the overhead if nothing is to be declared
2225 auto compRes = fInterpreter->declare(fwdDeclsCodeLessEnums, &T);
2226 assert(cling::Interpreter::kSuccess == compRes &&
2227 "The forward declarations could not be compiled");
2228 if (compRes!=cling::Interpreter::kSuccess){
2229 Warning("TCling::RegisterModule",
2230 "Problems in compiling forward declarations for module %s: '%s'",
2232 }
2233 else if (T){
2234 // Loop over all decls in the transaction and go through them all
2235 // to mark them properly.
2236 // In order to do that, we first iterate over all the DelayedCallInfos
2237 // within the transaction. Then we loop over all Decls in the DeclGroupRef
2238 // contained in the DelayedCallInfos. For each decl, we traverse.
2239 ExtLexicalStorageAdder elsa;
2240 for (auto dciIt = T->decls_begin();dciIt!=T->decls_end();dciIt++){
2241 cling::Transaction::DelayCallInfo& dci = *dciIt;
2242 for(auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
2243 clang::Decl* declPtr = *dit;
2244 elsa.TraverseDecl(declPtr);
2245 }
2246 }
2247 }
2248 }
2249
2250 // Now we register all the headers necessary for the class
2251 // Typical format of the array:
2252 // {"A", "classes.h", "@",
2253 // "vector<A>", "vector", "@",
2254 // "myClass", payloadCode, "@",
2255 // nullptr};
2256
2257 std::string temp;
2258 for (const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
2259 temp=*classesHeader;
2260
2261 size_t theTemplateHash = 0;
2262 bool addTemplate = false;
2263 size_t posTemplate = temp.find('<');
2264 if (posTemplate != std::string::npos) {
2265 // Add an entry for the template itself.
2266 std::string templateName = temp.substr(0, posTemplate);
2268 addTemplate = true;
2269 }
2270 size_t theHash = fStringHashFunction(temp);
2271 classesHeader++;
2273 // This is done in order to distinguish headers from files and from the payloadCode
2275 fPayloads.insert(theHash);
2277 }
2278 if (gDebug > 2)
2279 Info("TCling::RegisterModule",
2280 "Adding a header for %s", temp.c_str());
2282 if (addTemplate) {
2285 }
2286 addTemplate = false;
2287 }
2288 }
2289 }
2290 }
2291
2292 clang::Sema &TheSema = fInterpreter->getSema();
2293
2294 bool ModuleWasSuccessfullyLoaded = false;
2295 if (hasCxxModule) {
2296 std::string ModuleName = modulename;
2297 if (llvm::StringRef(modulename).starts_with("lib"))
2298 ModuleName = llvm::StringRef(modulename).substr(3).str();
2299
2300 // In case we are directly loading the library via gSystem->Load() without
2301 // specifying the relevant include paths we should try loading the
2302 // modulemap next to the library location.
2303 clang::Preprocessor &PP = TheSema.getPreprocessor();
2304 std::string ModuleMapName;
2305 if (isACLiC)
2306 ModuleMapName = ModuleName + ".modulemap";
2307 else
2308 ModuleMapName = "module.modulemap";
2309 RegisterPrebuiltModulePath(llvm::sys::path::parent_path(dyLibName).str(),
2311
2312 // FIXME: We should only complain for modules which we know to exist. For example, we should not complain about
2313 // modules such as GenVector32 because it needs to fall back to GenVector.
2314 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2317 // Only report if we found the module in the modulemap.
2318 clang::HeaderSearch &headerSearch = PP.getHeaderSearchInfo();
2319 clang::ModuleMap &moduleMap = headerSearch.getModuleMap();
2320 if (moduleMap.findModule(ModuleName))
2321 Info("TCling::RegisterModule", "Module %s in modulemap failed to load.", ModuleName.c_str());
2322 }
2323 }
2324
2326 llvm::SmallString<256> pcmFileNameFullPath(dyLibName);
2327 // The path dyLibName might not be absolute. This can happen if dyLibName
2328 // is linked to an executable in the same folder.
2329 llvm::sys::fs::make_absolute(pcmFileNameFullPath);
2330 llvm::sys::path::remove_filename(pcmFileNameFullPath);
2331 llvm::sys::path::append(pcmFileNameFullPath,
2333 LoadPCM(pcmFileNameFullPath.str().str());
2334 }
2335
2336 { // scope within which diagnostics are de-activated
2337 // For now we disable diagnostics because we saw them already at
2338 // dictionary generation time. That won't be an issue with the PCMs.
2339
2340 clangDiagSuppr diagSuppr(TheSema.getDiagnostics());
2341
2342#if defined(R__MUST_REVISIT)
2343#if R__MUST_REVISIT(6,2)
2344 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
2345#endif
2346#endif
2347
2350
2351 const cling::Transaction* watermark = fInterpreter->getLastTransaction();
2352 cling::Interpreter::CompilationResult compRes = fInterpreter->parseForModule(code.Data());
2353 if (isACLiC) {
2354 // Register an unload point.
2355 fMetaProcessor->registerUnloadPoint(watermark, headers[0]);
2356 }
2357
2358 assert(cling::Interpreter::kSuccess == compRes &&
2359 "Payload code of a dictionary could not be parsed correctly.");
2360 if (compRes!=cling::Interpreter::kSuccess) {
2361 Warning("TCling::RegisterModule",
2362 "Problems declaring payload for module %s.", modulename) ;
2363 }
2364 }
2365 }
2366
2367 // Now that all the header have been registered/compiled, let's
2368 // make sure to 'reset' the TClass that have a class init in this module
2369 // but already had their type information available (using information/header
2370 // loaded from other modules or from class rules or from opening a TFile
2371 // or from loading header in a way that did not provoke the loading of
2372 // the library we just loaded).
2374
2376 // __ROOTCLING__ might be pulled in through PCH
2377 fInterpreter->declare("#ifdef __ROOTCLING__\n"
2378 "#undef __ROOTCLING__\n"
2380 "#endif");
2381 }
2382
2383 if (wasDlopened) {
2385 void* dyLibHandle = fRegisterModuleDyLibs.back();
2386 fRegisterModuleDyLibs.pop_back();
2388 }
2389}
2390
2392 clang::CompilerInstance& CI = *GetInterpreterImpl()->getCI();
2393 ASTContext &C = CI.getASTContext();
2394
2395 // Do not do anything if we have no global module index.
2396 // FIXME: This is mostly to real with false positives in the TTabCom
2397 // interface for non-modules.
2398 if (!fCxxModulesEnabled)
2399 return;
2400
2401 if (IdentifierInfoLookup *External = C.Idents.getExternalIdentifierLookup()) {
2402 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
2403 for (llvm::StringRef Ident = Iter->Next(); !Ident.empty(); Ident = Iter->Next()) {
2404 std::string I = Ident.str();
2405 if (!Idents.Contains(I.data()))
2406 Idents.Add(new TObjString(I.c_str()));
2407 }
2408 }
2409}
2410
2411
2412////////////////////////////////////////////////////////////////////////////////
2413/// Register classes that already existed prior to their dictionary loading
2414/// and that already had a ClassInfo (and thus would not be refresh via
2415/// UpdateClassInfo.
2416
2418{
2419 fClassesToUpdate.push_back(std::make_pair(oldcl,dict));
2420}
2421
2422////////////////////////////////////////////////////////////////////////////////
2423/// If the dictionary is loaded, we can remove the class from the list
2424/// (otherwise the class might be loaded twice).
2425
2427{
2428 typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
2429 iterator stop = fClassesToUpdate.end();
2430 for(iterator i = fClassesToUpdate.begin();
2431 i != stop;
2432 ++i)
2433 {
2434 if ( i->first == oldcl ) {
2435 fClassesToUpdate.erase(i);
2436 return;
2437 }
2438 }
2439}
2440
2441
2442////////////////////////////////////////////////////////////////////////////////
2443/// Let cling process a command line.
2444///
2445/// If the command is executed and the error is 0, then the return value
2446/// is the int value corresponding to the result of the executed command
2447/// (float and double return values will be truncated).
2448///
2449
2450// Method for handling the interpreter exceptions.
2451// the MetaProcessor is passing in as argument to teh function, because
2452// cling::Interpreter::CompilationResult is a nested class and it cannot be
2453// forward declared, thus this method cannot be a static member function
2454// of TCling.
2455
2456static int HandleInterpreterException(cling::MetaProcessor* metaProcessor,
2457 const char* input_line,
2458 cling::Interpreter::CompilationResult& compRes,
2459 cling::Value* result)
2460{
2461 try {
2462 return metaProcessor->process(input_line, compRes, result);
2463 }
2464 catch (cling::InterpreterException& ex)
2465 {
2466 Error("HandleInterpreterException", "%s\n%s", ex.what(), "Execution of your code was aborted.");
2467 ex.diagnose();
2468 compRes = cling::Interpreter::kFailure;
2469 }
2470 return 0;
2471}
2472
2473////////////////////////////////////////////////////////////////////////////////
2474
2475bool TCling::DiagnoseIfInterpreterException(const std::exception &e) const
2476{
2477 if (auto ie = dynamic_cast<const cling::InterpreterException*>(&e)) {
2478 ie->diagnose();
2479 return true;
2480 }
2481 return false;
2482}
2483
2484////////////////////////////////////////////////////////////////////////////////
2485
2487{
2488 // Copy the passed line, it comes from a static buffer in TApplication
2489 // which can be reentered through the Cling evaluation routines,
2490 // which would overwrite the static buffer and we would forget what we
2491 // were doing.
2492 //
2494 if (strstr(line,fantomline)) {
2495 // End-Of-Line action
2496 // See the comment (copied from above):
2497 // It is a "fantom" method to synchronize user keyboard input
2498 // and ROOT prompt line (for WIN32)
2499 // and is implemented by
2500 if (gApplication) {
2501 if (gApplication->IsCmdThread()) {
2503 gROOT->SetLineIsProcessing();
2504
2506
2507 gROOT->SetLineHasBeenProcessed();
2508 }
2509 }
2510 return 0;
2511 }
2512
2514 gGlobalMutex->Lock();
2515 if (!gInterpreterMutex)
2518 }
2520 gROOT->SetLineIsProcessing();
2521
2522 struct InterpreterFlagsRAII {
2523 cling::Interpreter* fInterpreter;
2525
2526 InterpreterFlagsRAII(cling::Interpreter* interp):
2527 fInterpreter(interp),
2528 fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
2529 {
2530 fInterpreter->enableDynamicLookup(true);
2531 }
2533 fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
2534 gROOT->SetLineHasBeenProcessed();
2535 }
2537
2538 // A non-zero returned value means the given line was
2539 // not a complete statement.
2540 int indent = 0;
2541 // This will hold the resulting value of the evaluation the given line.
2542 cling::Value result;
2543 cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
2544 if (!strncmp(sLine.Data(), ".L", 2) || !strncmp(sLine.Data(), ".x", 2) ||
2545 !strncmp(sLine.Data(), ".X", 2)) {
2546 // If there was a trailing "+", then CINT compiled the code above,
2547 // and we will need to strip the "+" before passing the line to cling.
2550 TString arguments;
2551 TString io;
2553 aclicMode, arguments, io);
2554 if (aclicMode.Length()) {
2555 // Remove the leading '+'
2556 R__ASSERT(aclicMode[0]=='+' && "ACLiC mode must start with a +");
2557 aclicMode[0]='k'; // We always want to keep the .so around.
2558 if (aclicMode[1]=='+') {
2559 // We have a 2nd +
2560 aclicMode[1]='f'; // We want to force the recompilation.
2561 }
2563 // ACLiC failed.
2564 compRes = cling::Interpreter::kFailure;
2565 } else {
2566 if (strncmp(sLine.Data(), ".L", 2) != 0) {
2567 // if execution was requested.
2568
2569 if (arguments.Length() == 0) {
2570 arguments = "()";
2571 }
2572 // We need to remove the extension.
2573 Ssiz_t ext = fname.Last('.');
2574 if (ext != kNPOS) {
2575 fname.Remove(ext);
2576 }
2577 const char *function = gSystem->BaseName(fname);
2578 mod_line = function + arguments + io;
2580 }
2581 }
2582 } else if (cling::DynamicLibraryManager::isSharedLibrary(fname.Data()) &&
2583 strncmp(sLine.Data(), ".L", 2) != 0) { // .x *.so or *.dll
2584 if (gSystem->Load(fname) < 0) {
2585 // Loading failed.
2586 compRes = cling::Interpreter::kFailure;
2587 } else {
2588 if (arguments.Length() == 0) {
2589 arguments = "()";
2590 }
2591 // We need to remove the extension. (*.so or *.dll)
2592 Ssiz_t ext = fname.Last('.');
2593 if (ext != kNPOS) {
2594 fname.Remove(ext);
2595 }
2596 // Now we try to find the 'main' function to run within this shared library
2597 // We distinguish two cases: a library.so with a function library(args),
2598 // or a precompiled ACLiC macro (macro_C.so) with a function macro(args).
2599 // Only in the second case, we need to strip the suffix _C or _cpp from fname.
2600 if (!gInterpreter->GetFunction(nullptr, gSystem->BaseName(fname))) { // AcLiC macro
2601 // We need to remove the automatically appended _ extension when compiling (macro_C from macro.C)
2602 ext = fname.Last('_');
2603 if (ext != kNPOS) {
2604 fname.Remove(ext);
2605 }
2606 }
2607 const char *function = gSystem->BaseName(fname);
2608 mod_line = function + arguments + io;
2610 }
2611 } else {
2612 // neither ACLiC nor run shared-library (.x)
2613 size_t unnamedMacroOpenCurly;
2614 {
2615 std::string code;
2616 std::string codeline;
2617 // Windows requires std::ifstream::binary to properly handle
2618 // CRLF and LF line endings
2619 std::ifstream in(fname, std::ifstream::binary);
2620 while (in) {
2621 std::getline(in, codeline);
2622 code += codeline + "\n";
2623 }
2625 = cling::utils::isUnnamedMacro(code, fInterpreter->getCI()->getLangOpts());
2626 }
2627
2628 fCurExecutingMacros.push_back(fname);
2629 if (unnamedMacroOpenCurly != std::string::npos) {
2630 compRes = fMetaProcessor->readInputFromFile(fname.Data(), &result,
2632 } else {
2633 // No DynLookup for .x, .L of named macros.
2634 fInterpreter->enableDynamicLookup(false);
2636 }
2637 fCurExecutingMacros.pop_back();
2638 }
2639 } // .L / .X / .x
2640 else {
2641 if (0!=strncmp(sLine.Data(), ".autodict ",10) && sLine != ".autodict") {
2642 // explicitly ignore .autodict without having to support it
2643 // in cling.
2644
2645 // Turn off autoparsing if this is an include directive
2646 bool isInclusionDirective = sLine.Contains("\n#include") || sLine.BeginsWith("#include");
2650 } else {
2652 }
2653 }
2654 }
2655 if (result.isValid())
2657 if (indent) {
2658 if (error)
2659 *error = kProcessing;
2660 return 0;
2661 }
2662 if (error) {
2663 switch (compRes) {
2664 case cling::Interpreter::kSuccess: *error = kNoError; break;
2665 case cling::Interpreter::kFailure: *error = kRecoverable; break;
2666 case cling::Interpreter::kMoreInputExpected: *error = kProcessing; break;
2667 }
2668 }
2669 if (compRes == cling::Interpreter::kSuccess
2670 && result.isValid()
2671 && !result.isVoid())
2672 {
2673 return result.castAs<Longptr_t>();
2674 }
2675 return 0;
2676}
2677
2678////////////////////////////////////////////////////////////////////////////////
2679/// No-op; see TRint instead.
2680
2682{
2683}
2684
2685////////////////////////////////////////////////////////////////////////////////
2686/// \brief Add a directory to the list of directories in which the
2687/// interpreter looks for include files.
2688/// \param[in] path The path to the directory.
2689/// \note Only one path item can be specified at a time, i.e. "path1:path2" is
2690/// \b NOT supported.
2691/// \warning Only the path to the directory should be specified, without
2692/// prepending the \c -I prefix, i.e.
2693/// <tt>gCling->AddIncludePath("/path/to/my/includes")</tt>. If the
2694/// \c -I prefix is used it will be ignored.
2695void TCling::AddIncludePath(const char *path)
2696{
2698 // Favorite source of annoyance: gSystem->AddIncludePath() needs "-I",
2699 // gCling->AddIncludePath() does not! Work around that inconsistency:
2700 if (path[0] == '-' && path[1] == 'I')
2701 path += 2;
2702 TString sPath(path);
2704#ifdef _MSC_VER
2705 if (sPath.BeginsWith("/")) {
2706 char drive[3];
2707 snprintf(drive, 3, "%c:", _getdrive() + 'A' - 1);
2708 sPath.Prepend(drive);
2709 }
2710#endif
2711 fInterpreter->AddIncludePath(sPath.Data());
2712}
2713
2714////////////////////////////////////////////////////////////////////////////////
2715/// Visit all members over members, recursing over base classes.
2716
2718 const TClass* cl, Bool_t isTransient)
2719{
2720 if (insp.GetObjectValidity() == TMemberInspector::kUnset) {
2721 insp.SetObjectValidity(obj ? TMemberInspector::kValidObjectGiven
2723 }
2724
2725 if (!cl || cl->GetCollectionProxy()) {
2726 // We do not need to investigate the content of the STL
2727 // collection, they are opaque to us (and details are
2728 // uninteresting).
2729 return;
2730 }
2731
2732 static const TClassRef clRefString("std::string");
2733 if (clRefString == cl) {
2734 // We stream std::string without going through members..
2735 return;
2736 }
2737
2738 if (TClassEdit::IsStdArray(cl->GetName())) {
2739 // We treat std arrays as C arrays
2740 return;
2741 }
2742
2743 const char* cobj = (const char*) obj; // for ptr arithmetics
2744
2745 // Treat the case of std::complex in a special manner. We want to enforce
2746 // the layout of a stl implementation independent class, which is the
2747 // complex as implemented in ROOT5.
2748
2749 // A simple lambda to simplify the code
2750 auto inspInspect = [&] (ptrdiff_t offset){
2751 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_real", cobj, isTransient);
2752 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_imag", cobj + offset, isTransient);
2753 };
2754
2756 switch(complexType) {
2758 {
2759 break;
2760 }
2762 {
2763 inspInspect(sizeof(float));
2764 return;
2765 }
2767 {
2768 inspInspect(sizeof(double));
2769 return;
2770 }
2772 {
2773 inspInspect(sizeof(int));
2774 return;
2775 }
2777 {
2778 inspInspect(sizeof(long));
2779 return;
2780 }
2781 }
2782
2783 static clang::PrintingPolicy
2784 printPol(fInterpreter->getCI()->getLangOpts());
2785 if (printPol.Indentation) {
2786 // not yet initialized
2787 printPol.Indentation = 0;
2788 printPol.SuppressInitializers = true;
2789 }
2790
2791 const char* clname = cl->GetName();
2792 // Printf("Inspecting class %s\n", clname);
2793
2794 const clang::ASTContext& astContext = fInterpreter->getCI()->getASTContext();
2795 const clang::Decl *scopeDecl = nullptr;
2796 const clang::Type *recordType = nullptr;
2797
2798 if (cl->GetClassInfo()) {
2800 scopeDecl = clingCI->GetDecl();
2801 recordType = clingCI->GetType();
2802 } else {
2803 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
2804 // Diags will complain about private classes:
2805 scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2806 &recordType);
2807 }
2808 if (!scopeDecl) {
2809 Error("InspectMembers", "Cannot find Decl for class %s", clname);
2810 return;
2811 }
2812 const clang::CXXRecordDecl* recordDecl
2813 = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2814 if (!recordDecl) {
2815 Error("InspectMembers", "Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2816 return;
2817 }
2818
2819 {
2820 // Force possible deserializations first. We need to have no pending
2821 // Transaction when passing control flow to the inspector below (ROOT-7779).
2822 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2823
2824 astContext.getASTRecordLayout(recordDecl);
2825
2826 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2827 eField = recordDecl->field_end(); iField != eField; ++iField) {}
2828 }
2829
2830 const clang::ASTRecordLayout& recLayout
2831 = astContext.getASTRecordLayout(recordDecl);
2832
2833 // TVirtualCollectionProxy *proxy = cl->GetCollectionProxy();
2834 // if (proxy && ( proxy->GetProperties() & TVirtualCollectionProxy::kIsEmulated ) ) {
2835 // Error("InspectMembers","The TClass for %s has an emulated proxy but we are looking at a compiled version of the collection!\n",
2836 // cl->GetName());
2837 // }
2838 if (cl->Size() != recLayout.getSize().getQuantity()) {
2839 Error("InspectMembers","TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2840 cl->GetName(),cl->Size(),(Long64_t)recLayout.getSize().getQuantity());
2841 }
2842
2843 unsigned iNField = 0;
2844 // iterate over fields
2845 // FieldDecls are non-static, else it would be a VarDecl.
2846 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2847 eField = recordDecl->field_end(); iField != eField;
2848 ++iField, ++iNField) {
2849
2850
2851 clang::QualType memberQT = iField->getType();
2852 if (recordType) {
2853 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2855 }
2856 memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2857 if (memberQT.isNull()) {
2858 std::string memberName;
2859 llvm::raw_string_ostream stream(memberName);
2860 // Don't trigger fopen of the source file to count lines:
2861 printPol.AnonymousTagLocations = false;
2862 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2863 stream.flush();
2864 Error("InspectMembers",
2865 "Cannot retrieve QualType for member %s while inspecting class %s",
2866 memberName.c_str(), clname);
2867 continue; // skip member
2868 }
2869 const clang::Type* memType = memberQT.getTypePtr();
2870 if (!memType) {
2871 std::string memberName;
2872 llvm::raw_string_ostream stream(memberName);
2873 // Don't trigger fopen of the source file to count lines:
2874 printPol.AnonymousTagLocations = false;
2875 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2876 stream.flush();
2877 Error("InspectMembers",
2878 "Cannot retrieve Type for member %s while inspecting class %s",
2879 memberName.c_str(), clname);
2880 continue; // skip member
2881 }
2882
2883 const clang::Type* memNonPtrType = memType;
2884 Bool_t ispointer = false;
2885 if (memNonPtrType->isPointerType()) {
2886 ispointer = true;
2887 clang::QualType ptrQT
2888 = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2889 if (recordType) {
2890 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2892 }
2893 ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2894 if (ptrQT.isNull()) {
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 pointee Type for member %s while inspecting class %s",
2903 memberName.c_str(), clname);
2904 continue; // skip member
2905 }
2906 memNonPtrType = ptrQT.getTypePtr();
2907 }
2908
2909 // assemble array size(s): "[12][4][]"
2910 llvm::SmallString<8> arraySize;
2911 const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2912 unsigned arrLevel = 0;
2913 bool haveErrorDueToArray = false;
2914 while (arrType) {
2915 ++arrLevel;
2916 arraySize += '[';
2917 const clang::ConstantArrayType* constArrType =
2918 clang::dyn_cast<clang::ConstantArrayType>(arrType);
2919 if (constArrType) {
2920 constArrType->getSize().toStringUnsigned(arraySize);
2921 }
2922 arraySize += ']';
2923 clang::QualType subArrQT = arrType->getElementType();
2924 if (subArrQT.isNull()) {
2925 std::string memberName;
2926 llvm::raw_string_ostream stream(memberName);
2927 // Don't trigger fopen of the source file to count lines:
2928 printPol.AnonymousTagLocations = false;
2929 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2930 stream.flush();
2931 Error("InspectMembers",
2932 "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2933 arrLevel, subArrQT.getAsString(printPol).c_str(),
2934 memberName.c_str(), clname);
2935 haveErrorDueToArray = true;
2936 break;
2937 }
2938 arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2939 }
2940 if (haveErrorDueToArray) {
2941 continue; // skip member
2942 }
2943
2944 // construct member name
2945 std::string fieldName;
2946 if (memType->isPointerType()) {
2947 fieldName = "*";
2948 }
2949
2950 // Check if this field has a custom ioname, if not, just use the one of the decl
2951 std::string ioname(iField->getName());
2953 fieldName += ioname;
2954 fieldName += arraySize;
2955
2956 // get member offset
2957 // NOTE currently we do not support bitfield and do not support
2958 // member that are not aligned on 'bit' boundaries.
2959 clang::CharUnits offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2960 ptrdiff_t fieldOffset = offset.getQuantity();
2961
2962 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fBits[2]", fBits);
2963 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fName", &fName);
2964 // R__insp.InspectMember(fName, "fName.");
2965 // R__insp.Inspect(R__cl, R__insp.GetParent(), "*fClass", &fClass);
2966
2967 // If the class has a custom streamer and the type of the filed is a
2968 // private enum, struct or class, skip it.
2969 if (!insp.IsTreatingNonAccessibleTypes()){
2970 auto iFiledQtype = iField->getType();
2971 if (auto tagDecl = iFiledQtype->getAsTagDecl()){
2972 auto declAccess = tagDecl->getAccess();
2974 continue;
2975 }
2976 }
2977 }
2978
2979 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
2980
2981 if (!ispointer) {
2982 const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
2983 if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
2984 // nested objects get an extra call to InspectMember
2985 // R__insp.InspectMember("FileStat_t", (void*)&fFileStat, "fFileStat.", false);
2986 std::string sFieldRecName;
2989 clang::QualType(memNonPtrType,0),
2990 *fInterpreter,
2992 }
2993
2994 TDataMember* mbr = cl->GetDataMember(ioname.c_str());
2995 // if we can not find the member (which should not really happen),
2996 // let's consider it transient.
2997 Bool_t transient = isTransient || !mbr || !mbr->IsPersistent();
2998 if (!mbr || !mbr->IsPersistent())
2999 insp.IncrementNestedTransient();
3000 insp.InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
3001 (fieldName + '.').c_str(), transient);
3002 if (!mbr || !mbr->IsPersistent())
3003 insp.DecrementNestedTransient();
3004
3005 }
3006 }
3007 } // loop over fields
3008
3009 // inspect bases
3010 // TNamed::ShowMembers(R__insp);
3011 unsigned iNBase = 0;
3012 for (clang::CXXRecordDecl::base_class_const_iterator iBase
3013 = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
3014 iBase != eBase; ++iBase, ++iNBase) {
3015 clang::QualType baseQT = iBase->getType();
3016 if (baseQT.isNull()) {
3017 Error("InspectMembers",
3018 "Cannot find QualType for base number %d while inspecting class %s",
3019 iNBase, clname);
3020 continue;
3021 }
3022 const clang::CXXRecordDecl* baseDecl
3023 = baseQT->getAsCXXRecordDecl();
3024 if (!baseDecl) {
3025 Error("InspectMembers",
3026 "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
3027 iNBase, clname);
3028 continue;
3029 }
3030 TClass* baseCl=nullptr;
3031 std::string sBaseName;
3032 // Try with the DeclId
3033 std::vector<TClass*> foundClasses;
3035 if (foundClasses.size()==1){
3037 } else {
3038 // Try with the normalised Name, as a fallback
3039 if (!baseCl){
3041 baseQT,
3042 *fInterpreter,
3045 }
3046 }
3047
3048 if (!baseCl){
3049 std::string qualNameForDiag;
3051 Error("InspectMembers",
3052 "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
3053 continue;
3054 }
3055
3056 int64_t baseOffset;
3057 if (iBase->isVirtual()) {
3058 if (insp.GetObjectValidity() == TMemberInspector::kNoObjectGiven) {
3059 if (!isTransient) {
3060 Error("InspectMembers",
3061 "Base %s of class %s is virtual but no object provided",
3062 sBaseName.c_str(), clname);
3063 }
3065 } else {
3066 // We have an object to determine the vbase offset.
3068 TClingClassInfo* baseCi = (TClingClassInfo*)baseCl->GetClassInfo();
3069 if (ci && baseCi) {
3070 baseOffset = ci->GetBaseOffset(baseCi, const_cast<void*>(obj),
3071 true /*isDerivedObj*/);
3072 if (baseOffset == -1) {
3073 Error("InspectMembers",
3074 "Error calculating offset of virtual base %s of class %s",
3075 sBaseName.c_str(), clname);
3076 }
3077 } else {
3078 Error("InspectMembers",
3079 "Cannot calculate offset of virtual base %s of class %s",
3080 sBaseName.c_str(), clname);
3081 continue;
3082 }
3083 }
3084 } else {
3085 baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
3086 }
3087 // TOFIX: baseCl can be null here!
3088 if (baseCl->IsLoaded()) {
3089 // For loaded class, CallShowMember will (especially for TObject)
3090 // call the virtual ShowMember rather than the class specific version
3091 // resulting in an infinite recursion.
3093 } else {
3094 baseCl->CallShowMembers(cobj + baseOffset,
3095 insp, isTransient);
3096 }
3097 } // loop over bases
3098}
3099
3100////////////////////////////////////////////////////////////////////////////////
3101/// Check if constructor exited correctly, ie the instance is in a valid state
3102/// \return true if there is a compiler instance available, false otherwise
3104{
3105 return fInterpreter->getCI() != nullptr;
3106}
3107
3108////////////////////////////////////////////////////////////////////////////////
3109/// Reset the interpreter internal state in case a previous action was not correctly
3110/// terminated.
3111
3113{
3114 // No-op there is not equivalent state (to be cleared) in Cling.
3115}
3116
3117////////////////////////////////////////////////////////////////////////////////
3118/// Delete existing temporary values.
3119
3121{
3122 // No-op for cling due to cling::Value.
3123}
3124
3125////////////////////////////////////////////////////////////////////////////////
3126/// Declare code to the interpreter, without any of the interpreter actions
3127/// that could trigger a re-interpretation of the code. I.e. make cling
3128/// behave like a compiler: no dynamic lookup, no input wrapping for
3129/// subsequent execution, no automatic provision of declarations but just a
3130/// plain `#include`.
3131/// Returns true on success, false on failure.
3132
3133bool TCling::Declare(const char* code)
3134{
3136
3139
3140 bool oldDynLookup = fInterpreter->isDynamicLookupEnabled();
3141 fInterpreter->enableDynamicLookup(false);
3142 bool oldRawInput = fInterpreter->isRawInputEnabled();
3143 fInterpreter->enableRawInput(true);
3144
3145 Bool_t ret = LoadText(code);
3146
3147 fInterpreter->enableRawInput(oldRawInput);
3148 fInterpreter->enableDynamicLookup(oldDynLookup);
3149 return ret;
3150}
3151
3152////////////////////////////////////////////////////////////////////////////////
3153/// It calls a "fantom" method to synchronize user keyboard input
3154/// and ROOT prompt line.
3155
3160
3161// This static function is a hop of TCling::IsLibraryLoaded, which is taking a lock and calling
3162// into this function. This is because we wanted to avoid a duplication in TCling::IsLoaded, which
3163// was already taking a lock.
3164static Bool_t s_IsLibraryLoaded(const char* libname, cling::Interpreter* fInterpreter)
3165{
3166 // Check shared library.
3169 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.Data());
3170 return false;
3171}
3172
3178
3179////////////////////////////////////////////////////////////////////////////////
3180/// Return true if ROOT has cxxmodules pcm for a given library name.
3181// FIXME: We need to be able to support lazy loading of pcm generated by ACLiC.
3183{
3184 llvm::StringRef ModuleName(libname);
3185 ModuleName = llvm::sys::path::stem(ModuleName);
3186 ModuleName.consume_front("lib");
3187
3188 // FIXME: In case when the modulemap is not yet loaded we will return the
3189 // wrong result. Consider a call to HasPCMForLibrary(../test/libEvent.so)
3190 // We will only load the modulemap for libEvent.so after we dlopen libEvent
3191 // which may happen after calling this interface. Maybe we should also check
3192 // if there is a Event.pcm file and a module.modulemap, load it and return
3193 // true.
3194 clang::ModuleMap &moduleMap = fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
3195 clang::Module *M = moduleMap.findModule(ModuleName);
3196 return M && !M->IsUnimportable && M->getASTFile();
3197}
3198
3199////////////////////////////////////////////////////////////////////////////////
3200/// Return true if the file has already been loaded by cint.
3201/// We will try in this order:
3202/// actual filename
3203/// filename as a path relative to
3204/// the include path
3205/// the shared library path
3206
3208{
3210
3211 //FIXME: if we use llvm::sys::fs::make_absolute all this can go away. See
3212 // cling::DynamicLibraryManager.
3213
3214 std::string file_name = filename;
3215 size_t at = std::string::npos;
3216 while ((at = file_name.find("/./")) != std::string::npos)
3217 file_name.replace(at, 3, "/");
3218
3219 std::string filesStr = "";
3220 llvm::raw_string_ostream filesOS(filesStr);
3221 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3222 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3223 filesOS.flush();
3224
3225 llvm::SmallVector<llvm::StringRef, 100> files;
3226 llvm::StringRef(filesStr).split(files, "\n");
3227
3228 std::set<std::string> fileMap;
3229 llvm::StringRef file_name_ref(file_name);
3230 // Fill fileMap; return early on exact match.
3232 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3233 if ((*iF) == file_name_ref) return kTRUE; // exact match
3234 fileMap.insert(iF->str());
3235 }
3236
3237 if (fileMap.empty()) return kFALSE;
3238
3239 // Check MacroPath.
3240 TString sFilename(file_name.c_str());
3242 && fileMap.count(sFilename.Data())) {
3243 return kTRUE;
3244 }
3245
3246 // Check IncludePath.
3247 TString incPath = gSystem->GetIncludePath(); // of the form -Idir1 -Idir2 -Idir3
3248 incPath.Append(":").Prepend(" "); // to match " -I" (note leading ' ')
3249 incPath.ReplaceAll(" -I", ":"); // of form :dir1 :dir2:dir3
3250 while (incPath.Index(" :") != -1) {
3251 incPath.ReplaceAll(" :", ":");
3252 }
3253 incPath.Prepend(".:");
3254 sFilename = file_name.c_str();
3256 && fileMap.count(sFilename.Data())) {
3257 return kTRUE;
3258 }
3259
3260 // Check shared library.
3261 if (s_IsLibraryLoaded(file_name.c_str(), GetInterpreterImpl()))
3262 return kTRUE;
3263
3264 //FIXME: We must use the cling::Interpreter::lookupFileOrLibrary iface.
3265 clang::ConstSearchDirIterator *CurDir = nullptr;
3266 clang::Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
3267 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3268 auto FE = HS.LookupFile(file_name.c_str(),
3269 clang::SourceLocation(),
3270 /*isAngled*/ false,
3271 /*FromDir*/ nullptr, CurDir,
3272 clang::ArrayRef<std::pair<clang::OptionalFileEntryRef,
3273 clang::DirectoryEntryRef>>(),
3274 /*SearchPath*/ nullptr,
3275 /*RelativePath*/ nullptr,
3276 /*RequestingModule*/ nullptr,
3277 /*SuggestedModule*/ nullptr,
3278 /*IsMapped*/ nullptr,
3279 /*IsFrameworkFound*/ nullptr,
3280 /*SkipCache*/ false,
3281 /*BuildSystemModule*/ false,
3282 /*OpenFile*/ false,
3283 /*CacheFail*/ false);
3284 if (FE) {
3285 // check in the source manager if the file is actually loaded
3286 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3287 // this works only with header (and source) files...
3288 clang::FileID FID = SM.translateFile(*FE);
3289 if (!FID.isInvalid() && FID.getHashValue() == 0)
3290 return kFALSE;
3291 else {
3292 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3293 if (SLocE.isFile() && !SLocE.getFile().getContentCache().getBufferIfLoaded())
3294 return kFALSE;
3295 if (!FID.isInvalid())
3296 return kTRUE;
3297 }
3298 // ...then check shared library again, but with full path now
3299 sFilename = FE->getName().str();
3301 && fileMap.count(sFilename.Data())) {
3302 return kTRUE;
3303 }
3304 }
3305 return kFALSE;
3306}
3307
3308
3309#if defined(R__MACOSX)
3310
3311////////////////////////////////////////////////////////////////////////////////
3312/// Check if lib is in the dynamic linker cache, returns true if it is, and if so,
3313/// modifies the library file name parameter `lib` from `/usr/lib/libFOO.dylib`
3314/// to `-lFOO` such that it can be passed to the linker.
3315/// This is a unique feature of macOS 11.
3316
3317static bool R__UpdateLibFileForLinking(TString &lib)
3318{
3319 const char *mapfile = nullptr;
3320#if __x86_64__
3321 mapfile = "/System/Library/dyld/dyld_shared_cache_x86_64.map";
3322#elif __arm64__
3323 mapfile = "/System/Library/dyld/dyld_shared_cache_arm64e.map";
3324#else
3325 #error unsupported architecture
3326#endif
3327 if (std::ifstream cacheMap{mapfile}) {
3328 std::string line;
3329 while (getline(cacheMap, line)) {
3330 if (line.find(lib) != std::string::npos) {
3331 lib.ReplaceAll("/usr/lib/lib","-l");
3332 lib.ReplaceAll(".dylib","");
3333 return true;
3334 }
3335 }
3336 return false;
3337 }
3338 return false;
3339}
3340#endif // R__MACOSX
3341
3342#if defined (R__LINUX) || defined (R__FBSD)
3343
3344////////////////////////////////////////////////////////////////////////////////
3345/// Callback for dl_iterate_phdr(), see `man dl_iterate_phdr`.
3346/// Collects opened libraries.
3347
3348static int callback_for_dl_iterate_phdr(struct dl_phdr_info *info, size_t size, void *data)
3349{
3350 // This function is called through UpdateListOfLoadedSharedLibraries() which is locked.
3351 static std::unordered_set<decltype(info->dlpi_addr)> sKnownLoadedLibBaseAddrs;
3352
3353 auto newLibs = static_cast<std::vector<std::string>*>(data);
3354 if (!sKnownLoadedLibBaseAddrs.count(info->dlpi_addr)) {
3355 // Skip \0, "", and kernel pseudo-libs linux-vdso.so.1 or linux-gate.so.1
3356 if (info->dlpi_name && info->dlpi_name[0]
3357#if defined(R__FBSD)
3358 //skip the executable (with null addr)
3359 && info->dlpi_addr
3360 //has no path
3361 && strncmp(info->dlpi_name, "[vdso]", 6)
3362 //the linker does not like to be mmapped
3363 //causes a crash in cling::DynamicLibraryManager::loadLibrary())
3364 //with error message "mmap of entire address space failed: Cannot allocate memory"
3365 && strncmp(info->dlpi_name, "/libexec/ld-elf.so.1", 20)
3366#endif
3367 && strncmp(info->dlpi_name, "linux-vdso.so", 13)
3368 && strncmp(info->dlpi_name, "linux-vdso32.so", 15)
3369 && strncmp(info->dlpi_name, "linux-vdso64.so", 15)
3370 && strncmp(info->dlpi_name, "linux-gate.so", 13))
3371 newLibs->emplace_back(info->dlpi_name);
3372 sKnownLoadedLibBaseAddrs.insert(info->dlpi_addr);
3373 }
3374 // No matter what the doc says, return != 0 means "stop the iteration".
3375 return 0;
3376}
3377
3378#endif // R__LINUX || R__FBSD
3379
3380
3381////////////////////////////////////////////////////////////////////////////////
3382
3384{
3385#if defined(R__WIN32) || defined(__CYGWIN__)
3386 HMODULE hModules[1024];
3387 void *hProcess;
3388 unsigned long cbModules;
3389 unsigned int i;
3390 hProcess = (void *)::GetCurrentProcess();
3392 // start at 1 to skip the executable itself
3393 for (i = 1; i < (cbModules / sizeof(void *)); i++) {
3394 static const int bufsize = 260;
3395 wchar_t winname[bufsize];
3396 char posixname[bufsize];
3398#if defined(__CYGWIN__)
3400#else
3401 std::wstring wpath = winname;
3402 std::replace(wpath.begin(), wpath.end(), '\\', '/');
3403 string path(wpath.begin(), wpath.end());
3404 strncpy(posixname, path.c_str(), bufsize);
3405#endif
3408 }
3409 }
3410#elif defined(R__MACOSX)
3411 // fPrevLoadedDynLibInfo stores the *next* image index to look at
3412 uint32_t imageIndex = (uint32_t) (size_t) fPrevLoadedDynLibInfo;
3413
3415 // Skip non-dylibs
3416 if (mh->filetype == MH_DYLIB) {
3417 if (const char* imageName = _dyld_get_image_name(imageIndex)) {
3419 }
3420 }
3421
3422 ++imageIndex;
3423 }
3424 fPrevLoadedDynLibInfo = (void*)(size_t)imageIndex;
3425#elif defined(R__LINUX) || defined(R__FBSD)
3426 // fPrevLoadedDynLibInfo is unused on Linux.
3427 (void) fPrevLoadedDynLibInfo;
3428
3429 std::vector<std::string> newLibs;
3431 for (auto &&lib: newLibs)
3432 RegisterLoadedSharedLibrary(lib.c_str());
3433#else
3434 Error("TCling::UpdateListOfLoadedSharedLibraries",
3435 "Platform not supported!");
3436#endif
3437}
3438
3439namespace {
3440template <int N>
3441static bool StartsWithStrLit(const char *haystack, const char (&needle)[N]) {
3442 return !strncmp(haystack, needle, N - 1);
3443}
3444}
3445
3446////////////////////////////////////////////////////////////////////////////////
3447/// Register a new shared library name with the interpreter; add it to
3448/// fSharedLibs.
3449
3451{
3452 // Ignore NULL filenames, aka "the process".
3453 if (!filename) return;
3454
3455 // Tell the interpreter that this library is available; all libraries can be
3456 // used to resolve symbols.
3457 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3458 if (!DLM->isLibraryLoaded(filename)) {
3459 DLM->loadLibrary(filename, true /*permanent*/, true /*resolved*/);
3460 }
3461
3462#if defined(R__MACOSX)
3463 // Check that this is not a system library that does not exist on disk.
3464 auto lenFilename = strlen(filename);
3465 auto isInMacOSSystemDir = [](const char *fn) {
3466 return StartsWithStrLit(fn, "/usr/lib/") || StartsWithStrLit(fn, "/System/Library/");
3467 };
3468 if (!strcmp(filename, "cl_kernels") // yepp, no directory
3469
3470 // These we should not link with (e.g. because they forward to .tbd):
3471 || StartsWithStrLit(filename, "/usr/lib/system/")
3472 || StartsWithStrLit(filename, "/usr/lib/libc++")
3473 || StartsWithStrLit(filename, "/System/Library/Frameworks/")
3474 || StartsWithStrLit(filename, "/System/Library/PrivateFrameworks/")
3475 || StartsWithStrLit(filename, "/System/Library/CoreServices/")
3476 || StartsWithStrLit(filename, "/usr/lib/libSystem")
3477 || StartsWithStrLit(filename, "/usr/lib/libstdc++")
3478 || StartsWithStrLit(filename, "/usr/lib/libicucore")
3479 || StartsWithStrLit(filename, "/usr/lib/libbsm")
3480 || StartsWithStrLit(filename, "/usr/lib/libobjc")
3481 || StartsWithStrLit(filename, "/usr/lib/libresolv")
3482 || StartsWithStrLit(filename, "/usr/lib/libauto")
3483 || StartsWithStrLit(filename, "/usr/lib/libcups")
3484 || StartsWithStrLit(filename, "/usr/lib/libDiagnosticMessagesClient")
3485 || StartsWithStrLit(filename, "/usr/lib/liblangid")
3486 || StartsWithStrLit(filename, "/usr/lib/libCRFSuite")
3487 || StartsWithStrLit(filename, "/usr/lib/libpam")
3488 || StartsWithStrLit(filename, "/usr/lib/libOpenScriptingUtil")
3489 || StartsWithStrLit(filename, "/usr/lib/libextension")
3490 || StartsWithStrLit(filename, "/usr/lib/libAudioToolboxUtility")
3491 || StartsWithStrLit(filename, "/usr/lib/liboah")
3492 || StartsWithStrLit(filename, "/usr/lib/libRosetta")
3493 || StartsWithStrLit(filename, "/usr/lib/libCoreEntitlements")
3494 || StartsWithStrLit(filename, "/usr/lib/libssl.")
3495 || StartsWithStrLit(filename, "/usr/lib/libcrypto.")
3496
3497 // The system lib is likely in macOS's blob.
3499
3500 // "Link against the umbrella framework 'System.framework' instead"
3501 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_kernel")
3502 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_platform")
3503 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_pthread")
3504
3505 // "cannot link directly with dylib/framework, your binary is not an allowed client of
3506 // /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/
3507 // SDKs/MacOSX.sdk/usr/lib/libAudioToolboxUtility.tbd for architecture x86_64
3508 || (lenFilename > 4 && !strcmp(filename + lenFilename - 4, ".tbd")))
3509 return;
3512 filename = sFileName.Data();
3513#elif defined(__CYGWIN__)
3514 // Check that this is not a system library
3515 static const int bufsize = 260;
3516 char posixwindir[bufsize];
3517 char *windir = getenv("WINDIR");
3518 if (windir)
3520 else
3521 snprintf(posixwindir, sizeof(posixwindir), "/Windows/");
3522 if (strstr(filename, posixwindir) ||
3523 strstr(filename, "/usr/bin/cyg"))
3524 return;
3525#elif defined(R__WIN32)
3526 if (strstr(filename, "/Windows/"))
3527 return;
3528#elif defined (R__LINUX)
3529 if (strstr(filename, "/ld-linux")
3530 || strstr(filename, "linux-gnu/")
3531 || strstr(filename, "/libstdc++.")
3532 || strstr(filename, "/libgcc")
3533 || strstr(filename, "/libc.")
3534 || strstr(filename, "/libdl.")
3535 || strstr(filename, "/libm."))
3536 return;
3537#endif
3538 // Update string of available libraries.
3539 if (!fSharedLibs.IsNull()) {
3540 fSharedLibs.Append(" ");
3541 }
3543}
3544
3545////////////////////////////////////////////////////////////////////////////////
3546/// Load a library file in cling's memory.
3547/// if 'system' is true, the library is never unloaded.
3548/// Return 0 on success, -1 on failure.
3549
3551{
3552 assert(!IsFromRootCling() && "Trying to load library from rootcling!");
3553
3554 // Used to return 0 on success, 1 on duplicate, -1 on failure, -2 on "fatal".
3556 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3557 std::string canonLib = DLM->lookupLibrary(filename);
3558 cling::DynamicLibraryManager::LoadLibResult res
3559 = cling::DynamicLibraryManager::kLoadLibNotFound;
3560 if (!canonLib.empty()) {
3561 if (system)
3562 res = DLM->loadLibrary(filename, system, true);
3563 else {
3564 // For the non system libs, we'd like to be able to unload them.
3565 // FIXME: Here we lose the information about kLoadLibAlreadyLoaded case.
3566 cling::Interpreter::CompilationResult compRes;
3567 HandleInterpreterException(GetMetaProcessorImpl(), Form(".L %s", canonLib.c_str()), compRes, /*cling::Value*/nullptr);
3568 if (compRes == cling::Interpreter::kSuccess)
3569 res = cling::DynamicLibraryManager::kLoadLibSuccess;
3570 }
3571 }
3572
3573 if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3575 }
3576 switch (res) {
3577 case cling::DynamicLibraryManager::kLoadLibSuccess: return 0;
3578 case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded: return 1;
3579 default: break;
3580 };
3581 return -1;
3582}
3583
3584////////////////////////////////////////////////////////////////////////////////
3585/// Load a macro file in cling's memory.
3586
3587void TCling::LoadMacro(const char* filename, EErrorCode* error)
3588{
3589 ProcessLine(Form(".L %s", filename), error);
3590}
3591
3592////////////////////////////////////////////////////////////////////////////////
3593/// Let cling process a command line asynch.
3594
3596{
3597 return ProcessLine(line, error);
3598}
3599
3600////////////////////////////////////////////////////////////////////////////////
3601/// Let cling process a command line synchronously, i.e we are waiting
3602/// it will be finished.
3603
3605{
3607 if (gApplication) {
3608 if (gApplication->IsCmdThread()) {
3609 return ProcessLine(line, error);
3610 }
3611 return 0;
3612 }
3613 return ProcessLine(line, error);
3614}
3615
3616////////////////////////////////////////////////////////////////////////////////
3617/// Directly execute an executable statement (e.g. "func()", "3+5", etc.
3618/// however not declarations, like "Int_t x;").
3619
3621{
3622#ifdef R__WIN32
3623 // Test on ApplicationImp not being 0 is needed because only at end of
3624 // TApplication ctor the IsLineProcessing flag is set to 0, so before
3625 // we can not use it.
3627 while (gROOT->IsLineProcessing() && !gApplication) {
3628 Warning("Calc", "waiting for cling thread to free");
3629 gSystem->Sleep(500);
3630 }
3631 gROOT->SetLineIsProcessing();
3632 }
3633#endif // R__WIN32
3635 if (error) {
3636 *error = TInterpreter::kNoError;
3637 }
3638 cling::Value valRef;
3639 cling::Interpreter::CompilationResult cr = cling::Interpreter::kFailure;
3640 try {
3641 cr = fInterpreter->evaluate(line, valRef);
3642 }
3643 catch (cling::InterpreterException& ex)
3644 {
3645 Error("Calc", "%s.\n%s", ex.what(), "Evaluation of your expression was aborted.");
3646 ex.diagnose();
3647 cr = cling::Interpreter::kFailure;
3648 }
3649
3650 if (cr != cling::Interpreter::kSuccess) {
3651 // Failure in compilation.
3652 if (error) {
3653 // Note: Yes these codes are weird.
3655 }
3656 return 0L;
3657 }
3658 if (!valRef.isValid()) {
3659 // Failure at runtime.
3660 if (error) {
3661 // Note: Yes these codes are weird.
3662 *error = TInterpreter::kDangerous;
3663 }
3664 return 0L;
3665 }
3666
3667 if (valRef.isVoid()) {
3668 return 0;
3669 }
3670
3672#ifdef R__WIN32
3674 gROOT->SetLineHasBeenProcessed();
3675 }
3676#endif // R__WIN32
3677 return valRef.castAs<Longptr_t>();
3678}
3679
3680////////////////////////////////////////////////////////////////////////////////
3681/// Set a getline function to call when input is needed.
3682
3683void TCling::SetGetline(const char * (*getlineFunc)(const char* prompt),
3684 void (*histaddFunc)(const char* line))
3685{
3686 // If cling offers a replacement for G__pause(), it would need to
3687 // also offer a way to customize at least the history recording.
3688
3689#if defined(R__MUST_REVISIT)
3690#if R__MUST_REVISIT(6,2)
3691 Warning("SetGetline","Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3692#endif
3693#endif
3694}
3695
3696////////////////////////////////////////////////////////////////////////////////
3697/// Helper function to increase the internal Cling count of transactions
3698/// that change the AST.
3699
3700Bool_t TCling::HandleNewTransaction(const cling::Transaction &T)
3701{
3703
3704 if ((std::distance(T.decls_begin(), T.decls_end()) != 1)
3705 || T.deserialized_decls_begin() != T.deserialized_decls_end()
3706 || T.macros_begin() != T.macros_end()
3707 || ((!T.getFirstDecl().isNull()) && ((*T.getFirstDecl().begin()) != T.getWrapperFD()))) {
3709 return true;
3710 }
3711 return false;
3712}
3713
3714////////////////////////////////////////////////////////////////////////////////
3715/// Delete object from cling symbol table so it can not be used anymore.
3716/// cling objects are always on the heap.
3717
3719{
3720 // NOTE: When replacing the mutex by a ReadWrite mutex, we **must**
3721 // put in place the Read/Write part here. Keeping the write lock
3722 // here is 'catasptrophic' for scaling as it means that ALL calls
3723 // to RecursiveRemove will take the write lock and performance
3724 // of many threads trying to access the write lock at the same
3725 // time is relatively bad.
3727 // Note that fgSetOfSpecials is supposed to be updated by TClingCallbacks::tryFindROOTSpecialInternal
3728 // (but isn't at the moment).
3729 if (obj->IsOnHeap() && fgSetOfSpecials && !((std::set<TObject*>*)fgSetOfSpecials)->empty()) {
3730 std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)fgSetOfSpecials)->find(obj);
3731 if (iSpecial != ((std::set<TObject*>*)fgSetOfSpecials)->end()) {
3733 DeleteGlobal(obj);
3734 ((std::set<TObject*>*)fgSetOfSpecials)->erase(iSpecial);
3735 }
3736 }
3737}
3738
3739////////////////////////////////////////////////////////////////////////////////
3740/// Pressing Ctrl+C should forward here. In the case where we have had
3741/// continuation requested we must reset it.
3742
3744{
3745 fMetaProcessor->cancelContinuation();
3746 // Reset the Cling state to the state saved by the last call to
3747 // TCling::SaveContext().
3748#if defined(R__MUST_REVISIT)
3749#if R__MUST_REVISIT(6,2)
3751 Warning("Reset","Cling should support the equivalent of scratch_upto(&fDictPos)");
3752#endif
3753#endif
3754}
3755
3756////////////////////////////////////////////////////////////////////////////////
3757/// Reset the Cling state to its initial state.
3758
3760{
3761#if defined(R__MUST_REVISIT)
3762#if R__MUST_REVISIT(6,2)
3764 Warning("ResetAll","Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3765#endif
3766#endif
3767}
3768
3769////////////////////////////////////////////////////////////////////////////////
3770/// Reset in Cling the list of global variables to the state saved by the last
3771/// call to TCling::SaveGlobalsContext().
3772///
3773/// Note: Right now, all we do is run the global destructors.
3774
3776{
3778 // TODO:
3779 // Here we should iterate over the transactions (N-3) and revert.
3780 // N-3 because the first three internal to cling.
3781
3782 fInterpreter->runAndRemoveStaticDestructors();
3783}
3784
3785////////////////////////////////////////////////////////////////////////////////
3786/// Reset the Cling 'user' global objects/variables state to the state saved by the last
3787/// call to TCling::SaveGlobalsContext().
3788
3790{
3791#if defined(R__MUST_REVISIT)
3792#if R__MUST_REVISIT(6,2)
3794 Warning("ResetGlobalVar","Cling should support the equivalent of resetglobalvar(obj)");
3795#endif
3796#endif
3797}
3798
3799////////////////////////////////////////////////////////////////////////////////
3800/// Rewind Cling dictionary to the point where it was before executing
3801/// the current macro. This function is typically called after SEGV or
3802/// ctlr-C after doing a longjmp back to the prompt.
3803
3805{
3806#if defined(R__MUST_REVISIT)
3807#if R__MUST_REVISIT(6,2)
3809 Warning("RewindDictionary","Cling should provide a way to revert transaction similar to rewinddictionary()");
3810#endif
3811#endif
3812}
3813
3814////////////////////////////////////////////////////////////////////////////////
3815/// Delete obj from Cling symbol table so it cannot be accessed anymore.
3816/// Returns 1 in case of success and 0 in case object was not in table.
3817
3819{
3820#if defined(R__MUST_REVISIT)
3821#if R__MUST_REVISIT(6,2)
3823 Warning("DeleteGlobal","Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3824#endif
3825#endif
3826 return 0;
3827}
3828
3829////////////////////////////////////////////////////////////////////////////////
3830/// Undeclare obj called name.
3831/// Returns 1 in case of success, 0 for failure.
3832
3834{
3835#if defined(R__MUST_REVISIT)
3836#if R__MUST_REVISIT(6,2)
3837 Warning("DeleteVariable","should do more that just reseting the value to zero");
3838#endif
3839#endif
3840
3842 llvm::StringRef srName(name);
3843 const char* unscopedName = name;
3844 llvm::StringRef::size_type posScope = srName.rfind("::");
3845 const clang::DeclContext* declCtx = nullptr;
3846 if (posScope != llvm::StringRef::npos) {
3847 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3848 const clang::Decl* scopeDecl
3849 = lh.findScope(srName.substr(0, posScope),
3850 cling::LookupHelper::WithDiagnostics);
3851 if (!scopeDecl) {
3852 Error("DeleteVariable", "Cannot find enclosing scope for variable %s",
3853 name);
3854 return 0;
3855 }
3856 declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3857 if (!declCtx) {
3858 Error("DeleteVariable",
3859 "Enclosing scope for variable %s is not a declaration context",
3860 name);
3861 return 0;
3862 }
3863 unscopedName += posScope + 2;
3864 }
3865 // Could trigger deserialization of decls.
3866 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
3867 clang::NamedDecl* nVarDecl
3868 = cling::utils::Lookup::Named(&fInterpreter->getSema(), unscopedName, declCtx);
3869 if (!nVarDecl) {
3870 Error("DeleteVariable", "Unknown variable %s", name);
3871 return 0;
3872 }
3873 clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3874 if (!varDecl) {
3875 Error("DeleteVariable", "Entity %s is not a variable", name);
3876 return 0;
3877 }
3878
3879 clang::QualType qType = varDecl->getType();
3880 const clang::Type* type = qType->getUnqualifiedDesugaredType();
3881 // Cannot set a reference's address to nullptr; the JIT can place it
3882 // into read-only memory (ROOT-7100).
3883 if (type->isPointerType()) {
3884 int** ppInt = (int**)fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3885 // set pointer to invalid.
3886 if (ppInt) *ppInt = nullptr;
3887 }
3888 return 1;
3889}
3890
3891////////////////////////////////////////////////////////////////////////////////
3892/// Save the current Cling state.
3893
3895{
3896#if defined(R__MUST_REVISIT)
3897#if R__MUST_REVISIT(6,2)
3899 Warning("SaveContext","Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3900#endif
3901#endif
3902}
3903
3904////////////////////////////////////////////////////////////////////////////////
3905/// Save the current Cling state of global objects.
3906
3908{
3909#if defined(R__MUST_REVISIT)
3910#if R__MUST_REVISIT(6,2)
3912 Warning("SaveGlobalsContext","Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3913#endif
3914#endif
3915}
3916
3917////////////////////////////////////////////////////////////////////////////////
3918/// No op: see TClingCallbacks (used to update the list of globals)
3919
3923
3924////////////////////////////////////////////////////////////////////////////////
3925/// No op: see TClingCallbacks (used to update the list of global functions)
3926
3930
3931////////////////////////////////////////////////////////////////////////////////
3932/// No op: see TClingCallbacks (used to update the list of types)
3933
3935{
3936}
3937
3938////////////////////////////////////////////////////////////////////////////////
3939/// Check in what order the member of a tuple are layout.
3940enum class ETupleOrdering {
3941 kAscending,
3944};
3945
3951
3957
3959{
3960 std::tuple<int,double> value;
3963
3964 size_t offset0 = ((char*)&(std::get<0>(value))) - ((char*)&value);
3965 size_t offset1 = ((char*)&(std::get<1>(value))) - ((char*)&value);
3966
3967 size_t ascOffset0 = ((char*)&(asc._0)) - ((char*)&asc);
3968 size_t ascOffset1 = ((char*)&(asc._1)) - ((char*)&asc);
3969
3970 size_t desOffset0 = ((char*)&(des._0)) - ((char*)&des);
3971 size_t desOffset1 = ((char*)&(des._1)) - ((char*)&des);
3972
3973 if (offset0 == ascOffset0 && offset1 == ascOffset1) {
3975 } else if (offset0 == desOffset0 && offset1 == desOffset1) {
3977 } else {
3979 }
3980}
3981
3982static std::string AlternateTuple(const char *classname, const cling::LookupHelper& lh, Bool_t silent)
3983{
3985 std::string alternateName = "TEmulatedTuple";
3986 alternateName.append( classname + 5 );
3987
3988 std::string fullname = "ROOT::Internal::" + alternateName;
3989 if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
3990 /*resultType*/nullptr, /* intantiateTemplate= */ false))
3991 return fullname;
3992
3993 {
3994 // Check if we can produce the tuple
3995 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
3996 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
3997 auto deleter = [](TypeInfo_t *type) {
3998 gInterpreter->TypeInfo_Delete(type);
3999 };
4000 std::unique_ptr<TypeInfo_t, decltype(deleter)> type{ gInterpreter->TypeInfo_Factory(), deleter };
4001 while (iter != theEnd) {
4002 gInterpreter->TypeInfo_Init(type.get(), iter->c_str());
4003 if (gInterpreter->TypeInfo_Property(type.get()) & kIsNotReacheable) {
4004 if (!silent)
4005 Error("Load","Could not declare alternate type for %s since %s (or one of its context) is private or protected",
4006 classname, iter->c_str());
4007 return "";
4008 }
4009 ++iter;
4010 }
4011 }
4012
4013 std::string guard_name;
4015 std::ostringstream guard;
4016 guard << "ROOT_INTERNAL_TEmulated_";
4017 guard << guard_name;
4018
4019 std::ostringstream alternateTuple;
4020 alternateTuple << "#ifndef " << guard.str() << "\n";
4021 alternateTuple << "#define " << guard.str() << "\n";
4022 alternateTuple << "namespace ROOT { namespace Internal {\n";
4023 alternateTuple << "template <class... Types> struct TEmulatedTuple;\n";
4024 alternateTuple << "template <> struct " << alternateName << " {\n";
4025
4026 // This could also be a compile time choice ...
4027 switch(IsTupleAscending()) {
4029 unsigned int nMember = 0;
4030 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
4031 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
4032 while (iter != theEnd) {
4033 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4034 ++iter;
4035 ++nMember;
4036 }
4037 break;
4038 }
4040 unsigned int nMember = tupleContent.fElements.size() - 3;
4041 auto iter = tupleContent.fElements.rbegin() + 1; // skip the 'stars'.
4042 auto theEnd = tupleContent.fElements.rend() - 1; // Skip the template name (tuple).
4043 while (iter != theEnd) {
4044 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4045 ++iter;
4046 --nMember;
4047 }
4048 break;
4049 }
4051 Fatal("TCling::SetClassInfo::AlternateTuple",
4052 "Layout of std::tuple on this platform is unexpected.");
4053 break;
4054 }
4055 }
4056
4057 alternateTuple << "};\n";
4058 alternateTuple << "}}\n";
4059 alternateTuple << "#endif\n";
4060 if (!gCling->Declare(alternateTuple.str().c_str()))
4061 {
4062 // Declare is not silent (yet?), so add an explicit error message
4063 // to indicate the consequence of the syntax errors.
4064 Error("Load","Could not declare %s",alternateName.c_str());
4065 return "";
4066 }
4067 alternateName = "ROOT::Internal::" + alternateName;
4068 return alternateName;
4069}
4070
4071////////////////////////////////////////////////////////////////////////////////
4072/// Set pointer to the TClingClassInfo in TClass.
4073/// If 'reload' is true, (attempt to) generate a new ClassInfo even if we
4074/// already have one.
4075
4077{
4078 // We are shutting down, there is no point in reloading, it only triggers
4079 // redundant deserializations.
4080 if (fIsShuttingDown) {
4081 // Remove the decl_id from the DeclIdToTClass map
4082 if (cl->fClassInfo) {
4085 // Test again as another thread may have set fClassInfo to nullptr.
4086 if (TClinginfo) {
4088 }
4089 delete TClinginfo;
4090 cl->fClassInfo = nullptr;
4091 }
4092 return;
4093 }
4094
4096 if (cl->fClassInfo && !reload) {
4097 return;
4098 }
4099 //Remove the decl_id from the DeclIdToTClass map
4101 if (TClinginfo) {
4103 }
4104 delete TClinginfo;
4105 cl->fClassInfo = nullptr;
4106 std::string name(cl->GetName());
4107
4108 auto SetWithoutClassInfoState = [](TClass *cl)
4109 {
4110 if (cl->fState != TClass::kHasTClassInit) {
4111 if (cl->fStreamerInfo->GetEntries() != 0) {
4113 } else {
4115 }
4116 }
4117 };
4118 // Handle the special case of 'tuple' where we ignore the real implementation
4119 // details and just overlay a 'simpler'/'simplistic' version that is easy
4120 // for the I/O to understand and handle.
4121 if (strncmp(cl->GetName(),"tuple<",std::char_traits<char>::length("tuple<"))==0) {
4122 if (!reload)
4123 name = AlternateTuple(cl->GetName(), fInterpreter->getLookupHelper(), silent);
4124 if (reload || name.empty()) {
4125 // We could not generate the alternate
4127 return;
4128 }
4129 }
4130
4132 // FIXME: Rather than adding an option to the TClingClassInfo, we should consider combining code
4133 // that is currently in the caller (like SetUnloaded) that disable AutoLoading and AutoParsing and
4134 // code is in the callee (disabling template instantiation) and end up with a more explicit class:
4135 // TClingClassInfoReadOnly.
4137 if (!info->IsValid()) {
4139 delete info;
4140 return;
4141 }
4142 cl->fClassInfo = (ClassInfo_t*)info; // Note: We are transferring ownership here.
4143 // In case a class contains an external enum, the enum will be seen as a
4144 // class. We must detect this special case and make the class a Zombie.
4145 // Here we assume that a class has at least one method.
4146 // We can NOT call TClass::Property from here, because this method
4147 // assumes that the TClass is well formed to do a lot of information
4148 // caching. The method SetClassInfo (i.e. here) is usually called during
4149 // the building phase of the TClass, hence it is NOT well formed yet.
4151 if (
4152 info->IsValid() &&
4153 !(info->Property() & (kIsClass | kIsStruct | kIsNamespace))
4154 ) {
4156 }
4157 if (!info->IsLoaded()) {
4158 if (info->Property() & (kIsNamespace)) {
4159 // Namespaces can have info but no corresponding CINT dictionary
4160 // because they are auto-created if one of their contained
4161 // classes has a dictionary.
4163 }
4164 // this happens when no dictionary is available
4165 delete info;
4166 cl->fClassInfo = nullptr;
4167 }
4168 if (zombieCandidate && !cl->GetCollectionType()) {
4169 cl->MakeZombie();
4170 }
4171 // If we reach here, the info was valid (See early returns).
4172 if (cl->fState != TClass::kHasTClassInit) {
4173 if (cl->fClassInfo) {
4175 } else {
4176// if (TClassEdit::IsSTLCont(cl->GetName()) {
4177// There will be an emulated collection proxy, is that the same?
4178// cl->fState = TClass::kEmulated;
4179// } else {
4180 if (cl->fStreamerInfo->GetEntries() != 0) {
4182 } else {
4184 }
4185// }
4186 }
4187 }
4188 if (cl->fClassInfo) {
4189 TClass::AddClassToDeclIdMap(((TClingClassInfo*)cl->fClassInfo)->GetDeclId(), cl);
4190 }
4191}
4192
4193////////////////////////////////////////////////////////////////////////////////
4194/// Checks if an entity with the specified name is defined in Cling.
4195/// Returns kUnknown if the entity is not defined.
4196/// Returns kWithClassDefInline if the entity exists and has a ClassDefInline
4197/// Returns kKnown if the entity is defined.
4198///
4199/// By default, structs, namespaces, classes, enums and unions are looked for.
4200/// If the flag isClassOrNamespaceOnly is true, classes, structs and
4201/// namespaces only are considered. I.e. if the name is an enum or a union,
4202/// the returned value is false.
4203///
4204/// In the case where the class is not loaded and belongs to a namespace
4205/// or is nested, looking for the full class name is outputting a lots of
4206/// (expected) error messages. Currently the only way to avoid this is to
4207/// specifically check that each level of nesting is already loaded.
4208/// In case of templates the idea is that everything between the outer
4209/// '<' and '>' has to be skipped, e.g.: `aap<pippo<noot>::klaas>::a_class`
4210
4213{
4215 static const char *anonEnum = "anonymous enum ";
4216 static const int cmplen = strlen(anonEnum);
4217
4218 if (fIsShuttingDown || 0 == strncmp(name, anonEnum, cmplen)) {
4219 return kUnknown;
4220 }
4221
4222 // Do not turn on the AutoLoading if it is globally off.
4224
4225 // Avoid the double search below in case the name is a fundamental type
4226 // or typedef to a fundamental type.
4227 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
4228 TDataType *fundType = (TDataType *)typeTable->THashTable::FindObject( name );
4229
4231 && fundType->GetType() > 0) {
4232 // Fundamental type, no a class.
4233 return kUnknown;
4234 }
4235
4236 // Migrated from within TClass::GetClass
4237 // If we want to know if a class or a namespace with this name exists in the
4238 // interpreter and this is an enum in the type system, before or after loading
4239 // according to the autoload function argument, return kUnknown.
4241 return kUnknown;
4242
4243 const char *classname = name;
4244
4245 // RAII to suspend and restore auto-loading and auto-parsing based on some external conditions.
4247 int fStoreAutoLoad = 0;
4248 int fStoreAutoParse = 0;
4249 bool fSuspendedAutoParse = false;
4250 public:
4252 fStoreAutoLoad = ((TCling*)gCling)->SetClassAutoLoading(autoload);
4253 }
4254
4255 void SuspendAutoParsing() {
4256 fSuspendedAutoParse = true;
4257 fStoreAutoParse = ((TCling*)gCling)->SetSuspendAutoParsing(true);
4258 }
4259
4262 ((TCling*)gCling)->SetSuspendAutoParsing(fStoreAutoParse);
4263 ((TCling*)gCling)->SetClassAutoLoading(fStoreAutoLoad);
4264 }
4265 };
4266
4268 if (TClassEdit::IsStdPair(classname) || TClassEdit::IsStdPairBase(classname))
4269 autoLoadParseRAII.SuspendAutoParsing();
4270
4271 // First we want to check whether the decl exist, but _without_
4272 // generating any template instantiation. However, the lookup
4273 // still will create a forward declaration of the class template instance
4274 // if it exist. In this case, the return value of findScope will still
4275 // be zero but the type will be initialized.
4276 // Note in the corresponding code in ROOT 5, CINT was not instantiating
4277 // this forward declaration.
4278 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4279 const clang::Type *type = nullptr;
4280 const clang::Decl *decl
4281 = lh.findScope(classname,
4282 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4283 : cling::LookupHelper::NoDiagnostics,
4284 &type, /* intantiateTemplate= */ false );
4285 if (!decl) {
4286 std::string buf = TClassEdit::InsertStd(classname);
4287 decl = lh.findScope(buf,
4288 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4289 : cling::LookupHelper::NoDiagnostics,
4290 &type,false);
4291 }
4292
4293 if (type) {
4294 // If decl==0 and the type is valid, then we have a forward declaration.
4295 if (!decl) {
4296 // If we have a forward declaration for a class template instantiation,
4297 // we want to ignore it if it was produced/induced by the call to
4298 // findScope, however we can not distinguish those from the
4299 // instantiation induce by 'soft' use (and thus also induce by the
4300 // same underlying code paths)
4301 // ['soft' use = use not requiring a complete definition]
4302 // So to reduce the amount of disruption to the existing code we
4303 // would just ignore those for STL collection, for which we really
4304 // need to have the compiled collection proxy (and thus the TClass
4305 // bootstrap).
4306 clang::ClassTemplateSpecializationDecl *tmpltDecl =
4307 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
4308 (type->getAsCXXRecordDecl());
4309 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4310 // Since the point of instantiation is invalid, we 'guess' that
4311 // the 'instantiation' of the forwarded type appended in
4312 // findscope.
4314 // For STL Collection we return kUnknown.
4315 return kUnknown;
4316 }
4317 }
4318 }
4320 if (!tci.IsValid()) {
4321 return kUnknown;
4322 }
4325
4326 if (tci.Property() & propertiesMask) {
4327 bool hasClassDefInline = false;
4329 // We do not need to check for ClassDefInline when this is called from
4330 // TClass::Init, we only do it for the call from TClass::GetClass.
4331 auto hasDictionary = tci.GetMethod("Dictionary", "", false, nullptr, ROOT::kExactMatch);
4332 auto implLineFunc = tci.GetMethod("ImplFileLine", "", false, nullptr, ROOT::kExactMatch);
4333
4334 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4335 int lineNumber = 0;
4336 bool success = false;
4337 std::tie(success, lineNumber) =
4340 }
4341 }
4342
4343 // fprintf(stderr,"CheckClassInfo: %s had dict=%d inline=%d\n",name,hasDictionary.IsValid()
4344 // , hasClassDefInline);
4345
4346 // We are now sure that the entry is not in fact an autoload entry.
4348 return kWithClassDefInline;
4349 else
4350 return kKnown;
4351 } else {
4352 // We are now sure that the entry is not in fact an autoload entry.
4353 return kUnknown;
4354 }
4355 }
4356
4357 if (decl)
4358 return kKnown;
4359 else
4360 return kUnknown;
4361
4362 // Setting up iterator part of TClingTypedefInfo is too slow.
4363 // Copy the lookup code instead:
4364 /*
4365 TClingTypedefInfo t(fInterpreter, name);
4366 if (t.IsValid() && !(t.Property() & kIsFundamental)) {
4367 delete[] classname;
4368 return kTRUE;
4369 }
4370 */
4371
4372// const clang::Decl *decl = lh.findScope(name);
4373// if (!decl) {
4374// std::string buf = TClassEdit::InsertStd(name);
4375// decl = lh.findScope(buf);
4376// }
4377
4378// return (decl);
4379}
4380
4381////////////////////////////////////////////////////////////////////////////////
4382/// Return true if there is a class template by the given name ...
4383
4385{
4386 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4387 // Interpreter transaction ahead, needs locking
4389 const clang::Decl *decl
4390 = lh.findClassTemplate(name,
4391 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4392 : cling::LookupHelper::NoDiagnostics);
4393 if (!decl) {
4394 std::string strname = "std::";
4395 strname += name;
4396 decl = lh.findClassTemplate(strname,
4397 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4398 : cling::LookupHelper::NoDiagnostics);
4399 }
4400 return nullptr != decl;
4401}
4402
4403////////////////////////////////////////////////////////////////////////////////
4404/// Create list of pointers to base class(es) for TClass cl.
4405
4407{
4409 if (cl->fBase) {
4410 return;
4411 }
4413 if (!tci) return;
4415 TList *listOfBase = new TList;
4416 while (t.Next()) {
4417 // if name cannot be obtained no use to put in list
4418 if (t.IsValid() && t.Name()) {
4420 listOfBase->Add(new TBaseClass((BaseClassInfo_t *)a, cl));
4421 }
4422 }
4423 // Now that is complete, publish it.
4424 cl->fBase = listOfBase;
4425}
4426
4427////////////////////////////////////////////////////////////////////////////////
4428/// Create list of pointers to enums for TClass cl.
4429
4431{
4433
4434 const Decl * D;
4435 TClass* cl = enumList.GetClass();
4436 if (cl) {
4437 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4438 }
4439 else {
4440 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4441 }
4442 // Iterate on the decl of the class and get the enums.
4443 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4444 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4445 // Collect all contexts of the namespace.
4446 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4447 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4449 declIter != declEnd; ++declIter) {
4450 // Iterate on all decls for each context.
4451 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4452 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4453 if (const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4454 // Get name of the enum type.
4455 std::string buf;
4456 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4457 llvm::raw_string_ostream stream(buf);
4458 // Don't trigger fopen of the source file to count lines:
4459 Policy.AnonymousTagLocations = false;
4460 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
4461 stream.flush();
4462 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
4463 if (!buf.empty()) {
4464 const char* name = buf.c_str();
4465 // Add the enum to the list of loaded enums.
4466 enumList.Get(ED, name);
4467 }
4468 }
4469 }
4470 }
4471 }
4472}
4473
4474////////////////////////////////////////////////////////////////////////////////
4475/// Create list of pointers to function templates for TClass cl.
4476
4478{
4480
4481 const Decl * D;
4483 if (cl) {
4484 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4486 }
4487 else {
4488 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4489 funcTempList = (TListOfFunctionTemplates*)gROOT->GetListOfFunctionTemplates();
4490 }
4491 // Iterate on the decl of the class and get the enums.
4492 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4493 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4494 // Collect all contexts of the namespace.
4495 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4496 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4499 // Iterate on all decls for each context.
4500 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4501 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4502 if (const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4503 funcTempList->Get(FTD);
4504 }
4505 }
4506 }
4507 }
4508}
4509
4510////////////////////////////////////////////////////////////////////////////////
4511/// Get the scopes representing using declarations of namespace
4512
4513std::vector<std::string> TCling::GetUsingNamespaces(ClassInfo_t *cl) const
4514{
4516 return ci->GetUsingNamespaces();
4517}
4518
4519////////////////////////////////////////////////////////////////////////////////
4520/// Create list of pointers to data members for TClass cl.
4521/// This is now a nop. The creation and updating is handled in
4522/// TListOfDataMembers.
4523
4525{
4526}
4527
4528////////////////////////////////////////////////////////////////////////////////
4529/// Create list of pointers to methods for TClass cl.
4530/// This is now a nop. The creation and updating is handled in
4531/// TListOfFunctions.
4532
4534{
4535}
4536
4537////////////////////////////////////////////////////////////////////////////////
4538/// Update the list of pointers to method for TClass cl
4539/// This is now a nop. The creation and updating is handled in
4540/// TListOfFunctions.
4541
4543{
4544}
4545
4546////////////////////////////////////////////////////////////////////////////////
4547/// Update the list of pointers to data members for TClass cl
4548/// This is now a nop. The creation and updating is handled in
4549/// TListOfDataMembers.
4550
4552{
4553}
4554
4555////////////////////////////////////////////////////////////////////////////////
4556/// Create list of pointers to method arguments for TMethod m.
4557
4559{
4561 if (m->fMethodArgs) {
4562 return;
4563 }
4564 TList *arglist = new TList;
4566 while (t.Next()) {
4567 if (t.IsValid()) {
4569 arglist->Add(new TMethodArg((MethodArgInfo_t*)a, m));
4570 }
4571 }
4572 m->fMethodArgs = arglist;
4573}
4574
4575////////////////////////////////////////////////////////////////////////////////
4576/// Return whether we are waiting for more input either because the collected
4577/// input contains unbalanced braces or last seen token was a `\` (backslash-newline)
4578
4580{
4581 return fMetaProcessor->awaitingMoreInput();
4582}
4583
4584////////////////////////////////////////////////////////////////////////////////
4585/// Generate a TClass for the given class.
4586/// Since the caller has already check the ClassInfo, let it give use the
4587/// result (via the value of emulation) rather than recalculate it.
4588
4589TClass *TCling::GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent /* = kFALSE */)
4590{
4591// For now the following line would lead to the (unwanted) instantiation
4592// of class template. This could/would need to be resurrected only if
4593// we re-introduce so sort of automatic instantiation. However this would
4594// have to include carefull look at the template parameter to avoid
4595// creating instance we can not really use (if the parameter are only forward
4596// declaration or do not have all the necessary interfaces).
4597
4598 // TClingClassInfo tci(fInterpreter, classname);
4599 // if (1 || !tci.IsValid()) {
4600
4601 Version_t version = 1;
4602 if (TClassEdit::IsSTLCont(classname)) {
4603 version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4604 }
4606 TClass *cl = new TClass(classname, version, silent);
4607 if (!emulation) {
4608 // Set the class version if the class is versioned.
4609 // Note that we cannot just call CLASS::Class_Version() as we might not have
4610 // an execution engine (when invoked from rootcling).
4611
4612 // Do not call cl->GetClassVersion(), it has side effects!
4614 if (oldvers == version && cl->GetClassInfo()) {
4615 // We have a version and it might need an update.
4617 if (llvm::isa<clang::NamespaceDecl>(cli->GetDecl())) {
4618 // Namespaces don't have class versions.
4619 return cl;
4620 }
4621 TClingMethodInfo mi = cli->GetMethod("Class_Version", "", nullptr /*poffset*/,
4624 if (!mi.IsValid()) {
4625 if (cl->TestBit(TClass::kIsTObject)) {
4626 Error("GenerateTClass",
4627 "Cannot find %s::Class_Version()! Class version might be wrong.",
4628 cl->GetName());
4629 }
4630 return cl;
4631 }
4632 Version_t newvers = ROOT::TMetaUtils::GetClassVersion(llvm::dyn_cast<clang::RecordDecl>(cli->GetDecl()),
4633 *fInterpreter);
4634 if (newvers == -1) {
4635 // Didn't manage to determine the class version from the AST.
4636 // Use runtime instead.
4637 if ((mi.Property() & kIsStatic)
4638 && !fInterpreter->isInSyntaxOnlyMode()) {
4639 // This better be a static function.
4641 callfunc.SetFunc(&mi);
4642 newvers = callfunc.ExecInt(nullptr);
4643 } else {
4644 Error("GenerateTClass",
4645 "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4646 cl->GetName());
4647 }
4648 }
4649 if (newvers != oldvers) {
4650 cl->fClassVersion = newvers;
4651 cl->fStreamerInfo->Expand(newvers + 2 + 10);
4652 }
4653 }
4654 }
4655
4656 return cl;
4657
4658// } else {
4659// return GenerateTClass(&tci,silent);
4660// }
4661}
4662
4663#if 0
4664////////////////////////////////////////////////////////////////////////////////
4665
4667{
4668 includes += info->FileName();
4669
4670 const clang::ClassTemplateSpecializationDecl *templateCl
4671 = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->GetDecl());
4672 if (templateCl) {
4673 for(unsigned int i=0; i < templateCl->getTemplateArgs().size(); ++i) {
4674 const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4675 if (arg.getKind() == clang::TemplateArgument::Type) {
4676 const clang::Type *uType = ROOT::TMetaUtils::GetUnderlyingType( arg.getAsType() );
4677
4678 if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4679 // We really need a header file.
4680 const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4681 if (argdecl) {
4682 includes += ";";
4683 TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4685 } else {
4686 std::string Result;
4687 llvm::raw_string_ostream OS(Result);
4688 arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4689 Warning("TCling::GenerateTClass","Missing header file for %s",OS.str().c_str());
4690 }
4691 }
4692 }
4693 }
4694 }
4695}
4696#endif
4697
4698////////////////////////////////////////////////////////////////////////////////
4699/// Generate a TClass for the given class.
4700
4702{
4704 if (!info || !info->IsValid()) {
4705 Fatal("GenerateTClass","Requires a valid ClassInfo object");
4706 return nullptr;
4707 }
4708 // We are in the case where we have AST nodes for this class.
4709 TClass *cl = nullptr;
4710 std::string classname;
4711 info->FullName(classname,*fNormalizedCtxt); // Could we use Name()?
4712 if (TClassEdit::IsSTLCont(classname)) {
4713#if 0
4714 Info("GenerateTClass","Will (try to) generate the compiled TClass for %s.",classname.c_str());
4715 // We need to build up the list of required headers, by
4716 // looking at each template arguments.
4719
4720 if (0 == GenerateDictionary(classname.c_str(),includes)) {
4721 // 0 means success.
4722 cl = TClass::LoadClass(classnam.c_str(), silent);
4723 if (cl == 0) {
4724 Error("GenerateTClass","Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4725 }
4726 }
4727#endif
4728 if (cl == nullptr) {
4729 int version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4730 cl = new TClass(classinfo, version, nullptr, nullptr, -1, -1, silent);
4731 }
4732 } else {
4733 // For regular class, just create a TClass on the fly ...
4734 // Not quite useful yet, but that what CINT used to do anyway.
4735 cl = new TClass(classinfo, 1, nullptr, nullptr, -1, -1, silent);
4736 }
4737 // Add the new TClass to the map of declid and TClass*.
4738 if (cl) {
4740 }
4741 return cl;
4742}
4743
4744////////////////////////////////////////////////////////////////////////////////
4745/// Generate the dictionary for the C++ classes listed in the first
4746/// argument (in a semi-colon separated list).
4747/// 'includes' contains a semi-colon separated list of file to
4748/// `#include` in the dictionary.
4749/// For example:
4750/// ~~~ {.cpp}
4751/// gInterpreter->GenerateDictionary("vector<vector<float> >;list<vector<float> >","list;vector");
4752/// ~~~
4753/// or
4754/// ~~~ {.cpp}
4755/// gInterpreter->GenerateDictionary("myclass","myclass.h;myhelper.h");
4756/// ~~~
4757
4758Int_t TCling::GenerateDictionary(const char* classes, const char* includes /* = "" */, const char* /* options = 0 */)
4759{
4760 if (classes == nullptr || classes[0] == 0) {
4761 Error("TCling::GenerateDictionary", "Cannot generate dictionary without passing classes.");
4762 return 0;
4763 }
4764 // Split the input list
4765 std::vector<std::string> listClasses;
4766 for (
4767 const char* current = classes, *prev = classes;
4768 *current != 0;
4769 ++current
4770 ) {
4771 if (*current == ';') {
4772 listClasses.push_back(std::string(prev, current - prev));
4773 prev = current + 1;
4774 }
4775 else if (*(current + 1) == 0) {
4776 listClasses.push_back(std::string(prev, current + 1 - prev));
4777 prev = current + 1;
4778 }
4779 }
4780 std::vector<std::string> listIncludes;
4781 if (!includes)
4782 includes = "";
4783 for (
4784 const char* current = includes, *prev = includes;
4785 *current != 0;
4786 ++current
4787 ) {
4788 if (*current == ';') {
4789 listIncludes.push_back(std::string(prev, current - prev));
4790 prev = current + 1;
4791 }
4792 else if (*(current + 1) == 0) {
4793 listIncludes.push_back(std::string(prev, current + 1 - prev));
4794 prev = current + 1;
4795 }
4796 }
4797 // Generate the temporary dictionary file
4799 std::vector<std::string>(), std::vector<std::string>());
4800}
4801
4802////////////////////////////////////////////////////////////////////////////////
4803/// Return pointer to cling Decl of global/static variable that is located
4804/// at the address given by addr.
4805
4807{
4809 DeclId_t d;
4811
4812 // Could trigger deserialization of decls.
4813 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4814
4815 if (cl) {
4816 d = cl->GetDataMember(name);
4817 // We check if the decl of the data member has an annotation which indicates
4818 // an ioname.
4819 // In case this is true, if the name requested is not the ioname, we
4820 // return 0, as if the member did not exist. In some sense we override
4821 // the information in the TClassInfo instance, isolating the typesystem in
4822 // TClass from the one in the AST.
4823 if (const ValueDecl* decl = (const ValueDecl*) d){
4824 std::string ioName;
4826 if (hasIoName && ioName != name) return nullptr;
4827 }
4828 return d;
4829 }
4830 // We are looking up for something on the TU scope.
4831 // FIXME: We do not want to go through TClingClassInfo(fInterpreter) because of redundant deserializations. That
4832 // interface will actually construct iterators and walk over the decls on the global scope. In would return the first
4833 // occurrence of a decl with the looked up name. However, that's not what C++ lookup would do: if we want to switch
4834 // to a more complete C++ lookup interface we need sift through the found names and pick up the declarations which
4835 // are only fulfilling ROOT's understanding for a Data Member.
4836 // FIXME: We should probably deprecate the TClingClassInfo(fInterpreter) interface and replace it withe something
4837 // similar as below.
4838 using namespace clang;
4839 Sema& SemaR = fInterpreter->getSema();
4840 DeclarationName DName = &SemaR.Context.Idents.get(name);
4841
4842 LookupResult R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4843 Sema::ForExternalRedeclaration);
4844
4845 cling::utils::Lookup::Named(&SemaR, R);
4846
4847 LookupResult::Filter F = R.makeFilter();
4848 // Filter the data-member looking decls.
4849 while (F.hasNext()) {
4850 NamedDecl *D = F.next();
4853 continue;
4854 F.erase();
4855 }
4856 F.done();
4857
4858 if (R.isSingleResult())
4859 return R.getFoundDecl();
4860 return nullptr;
4861}
4862
4863////////////////////////////////////////////////////////////////////////////////
4864/// Return pointer to cling Decl of global/static variable that is located
4865/// at the address given by addr.
4866
4868{
4870
4871 const clang::Decl* possibleEnum = nullptr;
4872 // FInd the context of the decl.
4873 if (cl) {
4875 if (cci) {
4876 const clang::DeclContext* dc = nullptr;
4877 if (const clang::Decl* D = cci->GetDecl()) {
4878 if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
4880 }
4881 }
4882 if (dc) {
4883 // If it is a data member enum.
4884 // Could trigger deserialization of decls.
4885 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4886 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name, dc);
4887 } else {
4888 Error("TCling::GetEnum", "DeclContext not found for %s .\n", name);
4889 }
4890 }
4891 } else {
4892 // If it is a global enum.
4893 // Could trigger deserialization of decls.
4894 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4895 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name);
4896 }
4897 if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
4899 return possibleEnum;
4900 }
4901 return nullptr;
4902}
4903
4904////////////////////////////////////////////////////////////////////////////////
4905/// Return pointer to cling DeclId for a global value
4906
4907TInterpreter::DeclId_t TCling::GetDeclId( const llvm::GlobalValue *gv ) const
4908{
4909 if (!gv) return nullptr;
4910
4911 llvm::StringRef mangled_name = gv->getName();
4912
4913 int err = 0;
4914 char* demangled_name_c = TClassEdit::DemangleName(mangled_name.str().c_str(), err);
4915 if (err) {
4916 if (err == -2) {
4917 // It might simply be an unmangled global name.
4918 DeclId_t d;
4920 d = gcl.GetDataMember(mangled_name.str().c_str());
4921 return d;
4922 }
4923 return nullptr;
4924 }
4925
4926 std::string scopename(demangled_name_c);
4928
4929 //
4930 // Separate out the class or namespace part of the
4931 // function name.
4932 //
4933 std::string dataname;
4934
4935 if (!strncmp(scopename.c_str(), "typeinfo for ", sizeof("typeinfo for ")-1)) {
4936 scopename.erase(0, sizeof("typeinfo for ")-1);
4937 } else if (!strncmp(scopename.c_str(), "vtable for ", sizeof("vtable for ")-1)) {
4938 scopename.erase(0, sizeof("vtable for ")-1);
4939 } else {
4940 // See if it is a function
4941 std::string::size_type pos = scopename.rfind('(');
4942 if (pos != std::string::npos) {
4943 return nullptr;
4944 }
4945 // Separate the scope and member name
4946 pos = scopename.rfind(':');
4947 if (pos != std::string::npos) {
4948 if ((pos != 0) && (scopename[pos-1] == ':')) {
4949 dataname = scopename.substr(pos+1);
4950 scopename.erase(pos-1);
4951 }
4952 } else {
4953 scopename.clear();
4955 }
4956 }
4957 //fprintf(stderr, "name: '%s'\n", name.c_str());
4958 // Now we have the class or namespace name, so do the lookup.
4959
4960
4961 DeclId_t d;
4962 if (scopename.size()) {
4964 d = cl.GetDataMember(dataname.c_str());
4965 }
4966 else {
4968 d = gcl.GetDataMember(dataname.c_str());
4969 }
4970 return d;
4971}
4972
4973////////////////////////////////////////////////////////////////////////////////
4974/// NOT IMPLEMENTED.
4975
4977{
4978 Error("GetDataMemberWithValue()", "not implemented");
4979 return nullptr;
4980}
4981
4982////////////////////////////////////////////////////////////////////////////////
4983/// Return pointer to cling DeclId for a data member with a given name.
4984
4986{
4987 // NOT IMPLEMENTED.
4988 Error("GetDataMemberAtAddr()", "not implemented");
4989 return nullptr;
4990}
4991
4992////////////////////////////////////////////////////////////////////////////////
4993/// Return the cling mangled name for a method of a class with parameters
4994/// params (params is a string of actual arguments, not formal ones). If the
4995/// class is 0 the global function list will be searched.
4996
4998 const char* params, Bool_t objectIsConst /* = kFALSE */)
4999{
5002 if (cl) {
5005 &offset);
5006 }
5007 else {
5010 func.SetFunc(&gcl, method, params, &offset);
5011 }
5013 if (!mi) return "";
5014 TString mangled_name( mi->GetMangledName() );
5015 delete mi;
5016 return mangled_name;
5017}
5018
5019////////////////////////////////////////////////////////////////////////////////
5020/// Return the cling mangled name for a method of a class with a certain
5021/// prototype, i.e. "char*,int,float". If the class is 0 the global function
5022/// list will be searched.
5023
5025 const char* proto, Bool_t objectIsConst /* = kFALSE */,
5026 EFunctionMatchMode mode /* = kConversionMatch */)
5027{
5029 if (cl) {
5030 return ((TClingClassInfo*)cl->GetClassInfo())->
5031 GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetMangledName();
5032 }
5034 return gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetMangledName();
5035}
5036
5037////////////////////////////////////////////////////////////////////////////////
5038/// Return pointer to cling interface function for a method of a class with
5039/// parameters params (params is a string of actual arguments, not formal
5040/// ones). If the class is 0 the global function list will be searched.
5041
5043 const char* params, Bool_t objectIsConst /* = kFALSE */)
5044{
5047 if (cl) {
5050 &offset);
5051 }
5052 else {
5055 func.SetFunc(&gcl, method, params, &offset);
5056 }
5057 return (void*) func.InterfaceMethod();
5058}
5059
5060////////////////////////////////////////////////////////////////////////////////
5061/// Return pointer to cling interface function for a method of a class with
5062/// a certain name.
5063
5065{
5067 DeclId_t f;
5069 if (cl) {
5070 f = cl->GetMethod(method).GetDeclId();
5071 }
5072 else {
5074 f = gcl.GetMethod(method).GetDeclId();
5075 }
5076 return f;
5077
5078}
5079
5080////////////////////////////////////////////////////////////////////////////////
5081/// Insert overloads of name in cl to res.
5082
5084 std::vector<DeclId_t>& res) const
5085{
5086 clang::Sema& S = fInterpreter->getSema();
5087 clang::ASTContext& Ctx = S.Context;
5088 const clang::Decl* CtxDecl
5089 = cl ? (const clang::Decl*)((TClingClassInfo*)cl)->GetDeclId():
5090 Ctx.getTranslationUnitDecl();
5091 auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
5092 const clang::DeclContext* DeclCtx = RecDecl;
5093
5094 if (!DeclCtx)
5096 if (!DeclCtx) return;
5097
5098 clang::DeclarationName DName;
5099 // The DeclarationName is funcname, unless it's a ctor or dtor.
5100 // FIXME: or operator or conversion! See enum clang::DeclarationName::NameKind.
5101
5102 if (RecDecl) {
5103 if (RecDecl->getNameAsString() == funcname) {
5104 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5105 DName = Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalType(QT));
5106 } else if (funcname[0] == '~' && RecDecl->getNameAsString() == funcname + 1) {
5107 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
5108 DName = Ctx.DeclarationNames.getCXXDestructorName(Ctx.getCanonicalType(QT));
5109 } else {
5110 DName = &Ctx.Idents.get(funcname);
5111 }
5112 } else {
5113 DName = &Ctx.Idents.get(funcname);
5114 }
5115
5116 // NotForRedeclaration: we want to find names in inline namespaces etc.
5117 clang::LookupResult R(S, DName, clang::SourceLocation(),
5118 Sema::LookupOrdinaryName, clang::Sema::NotForRedeclaration);
5119 R.suppressDiagnostics(); // else lookup with NotForRedeclaration will check access etc
5120 S.LookupQualifiedName(R, const_cast<DeclContext*>(DeclCtx));
5121 if (R.empty()) return;
5122 R.resolveKind();
5123 res.reserve(res.size() + (R.end() - R.begin()));
5124 for (clang::LookupResult::iterator IR = R.begin(), ER = R.end();
5125 IR != ER; ++IR) {
5126 if (const clang::FunctionDecl* FD
5127 = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
5128 if (!FD->getDescribedFunctionTemplate()) {
5129 res.push_back(FD);
5130 }
5131 } else if (const auto *USD = llvm::dyn_cast<const clang::UsingShadowDecl>(*IR)) {
5132 // FIXME: multi-level using
5133 if (llvm::isa<clang::FunctionDecl>(USD->getTargetDecl())) {
5134 res.push_back(USD);
5135 }
5136 }
5137 }
5138}
5139
5140////////////////////////////////////////////////////////////////////////////////
5141/// Return pointer to cling interface function for a method of a class with
5142/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5143/// function list will be searched.
5144
5146 const char* proto,
5147 Bool_t objectIsConst /* = kFALSE */,
5148 EFunctionMatchMode mode /* = kConversionMatch */)
5149{
5151 void* f;
5152 if (cl) {
5153 f = ((TClingClassInfo*)cl->GetClassInfo())->
5154 GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).InterfaceMethod();
5155 }
5156 else {
5158 f = gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).InterfaceMethod();
5159 }
5160 return f;
5161}
5162
5163////////////////////////////////////////////////////////////////////////////////
5164/// Return pointer to cling DeclId for a method of a class with
5165/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5166/// function list will be searched.
5167
5169 const char* params,
5170 Bool_t objectIsConst /* = kFALSE */)
5171{
5173 DeclId_t f;
5175 if (cl) {
5176 f = cl->GetMethodWithArgs(method, params, objectIsConst, nullptr /*poffset*/).GetDeclId();
5177 }
5178 else {
5180 f = gcl.GetMethod(method, params, objectIsConst, nullptr /*poffset*/).GetDeclId();
5181 }
5182 return f;
5183}
5184
5185////////////////////////////////////////////////////////////////////////////////
5186/// Return pointer to cling interface function for a method of a class with
5187/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5188/// function list will be searched.
5189
5191 const char* proto,
5192 Bool_t objectIsConst /* = kFALSE */,
5193 EFunctionMatchMode mode /* = kConversionMatch */)
5194{
5196 DeclId_t f;
5198 if (cl) {
5199 f = cl->GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetDeclId();
5200 }
5201 else {
5203 f = gcl.GetMethod(method, proto, objectIsConst, nullptr /*poffset*/, mode).GetDeclId();
5204 }
5205 return f;
5206}
5207
5208////////////////////////////////////////////////////////////////////////////////
5209/// Return pointer to cling interface function for a method of a class with
5210/// a certain name.
5211
5213{
5215 DeclId_t f;
5217 if (cl) {
5218 f = cl->GetFunctionTemplate(name);
5219 }
5220 else {
5222 f = gcl.GetFunctionTemplate(name);
5223 }
5224 return f;
5225
5226}
5227
5228////////////////////////////////////////////////////////////////////////////////
5229/// The 'name' is known to the interpreter, this function returns
5230/// the internal version of this name (usually just resolving typedefs)
5231/// This is used in particular to synchronize between the name used
5232/// by rootcling and by the run-time environment (TClass)
5233/// Return 0 if the name is not known.
5234
5235void TCling::GetInterpreterTypeName(const char* name, std::string &output, Bool_t full)
5236{
5237 output.clear();
5238
5240
5242 if (!cl.IsValid()) {
5243 return ;
5244 }
5245 if (full) {
5247 return;
5248 }
5249 // Well well well, for backward compatibility we need to act a bit too
5250 // much like CINT.
5253
5254 return;
5255}
5256
5257////////////////////////////////////////////////////////////////////////////////
5258/// Execute a global function with arguments params.
5259///
5260/// FIXME: The cint-based version of this code does not check if the
5261/// SetFunc() call works, and does not do any real checking
5262/// for errors from the Exec() call. It did fetch the most
5263/// recent cint security error and return that in error, but
5264/// this does not really translate well to cling/clang. We
5265/// should enhance these interfaces so that we can report
5266/// compilation and runtime errors properly.
5267
5268void TCling::Execute(const char* function, const char* params, int* error)
5269{
5271 if (error) {
5272 *error = TInterpreter::kNoError;
5273 }
5275 Longptr_t offset = 0L;
5277 func.SetFunc(&cl, function, params, &offset);
5278 func.Exec(nullptr);
5279}
5280
5281////////////////////////////////////////////////////////////////////////////////
5282/// Execute a method from class cl 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(TObject* obj, TClass* cl, const char* method,
5293 const char* params, Bool_t objectIsConst, int* error)
5294{
5296 if (error) {
5297 *error = TInterpreter::kNoError;
5298 }
5299 // If the actual class of this object inherits 2nd (or more) from TObject,
5300 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5301 // hence gInterpreter->Execute will improperly correct the offset.
5302 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5303 Longptr_t offset = 0L;
5306 void* address = (void*)((Longptr_t)addr + offset);
5307 func.Exec(address);
5308}
5309
5310////////////////////////////////////////////////////////////////////////////////
5311
5312void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5313 const char* params, int* error)
5314{
5315 Execute(obj,cl,method,params,false,error);
5316}
5317
5318////////////////////////////////////////////////////////////////////////////////
5319/// Execute a method from class cl with the arguments in array params
5320/// (params[0] ... params[n] = array of TObjString parameters).
5321/// Convert the TObjArray array of TObjString parameters to a character
5322/// string of comma separated parameters.
5323/// The parameters of type 'char' are enclosed in double quotes and all
5324/// internal quotes are escaped.
5325
5327 TObjArray* params, int* error)
5328{
5329 if (!method) {
5330 Error("Execute", "No method was defined");
5331 return;
5332 }
5333 TList* argList = method->GetListOfMethodArgs();
5334 // Check number of actual parameters against of expected formal ones
5335
5336 Int_t nparms = argList->LastIndex() + 1;
5337 Int_t argc = params ? params->GetEntries() : 0;
5338
5339 if (argc > nparms) {
5340 Error("Execute","Too many parameters to call %s, got %d but expected at most %d.",method->GetName(),argc,nparms);
5341 return;
5342 }
5343 if (nparms != argc) {
5344 // Let's see if the 'missing' argument are all defaulted.
5345 // if nparms==0 then either we stopped earlier either argc is also zero and we can't reach here.
5346 assert(nparms > 0);
5347
5348 TMethodArg *arg = (TMethodArg *) argList->At( 0 );
5349 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5350 // There is a default value for the first missing
5351 // argument, so we are fine.
5352 } else {
5353 Int_t firstDefault = -1;
5354 for (Int_t i = 0; i < nparms; i ++) {
5355 arg = (TMethodArg *) argList->At( i );
5356 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5357 firstDefault = i;
5358 break;
5359 }
5360 }
5361 if (firstDefault >= 0) {
5362 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);
5363 } else {
5364 Error("Execute","Too few arguments to call %s, got only %d but expected %d.",method->GetName(),argc,nparms);
5365 }
5366 return;
5367 }
5368 }
5369
5370 const char* listpar = "";
5371 TString complete(10);
5372 if (params) {
5373 // Create a character string of parameters from TObjArray
5374 TIter next(params);
5375 for (Int_t i = 0; i < argc; i ++) {
5376 TMethodArg* arg = (TMethodArg*) argList->At(i);
5378 TObjString* nxtpar = (TObjString*) next();
5379 if (i) {
5380 complete += ',';
5381 }
5382 if (strstr(type.TrueName(*fNormalizedCtxt), "char")) {
5383 TString chpar('\"');
5384 chpar += (nxtpar->String()).ReplaceAll("\"", "\\\"");
5385 // At this point we have to check if string contains \\"
5386 // and apply some more sophisticated parser. Not implemented yet!
5387 complete += chpar;
5388 complete += '\"';
5389 }
5390 else {
5391 complete += nxtpar->String();
5392 }
5393 }
5394 listpar = complete.Data();
5395 }
5396
5397 // And now execute it.
5399 if (error) {
5400 *error = TInterpreter::kNoError;
5401 }
5402 // If the actual class of this object inherits 2nd (or more) from TObject,
5403 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5404 // hence gInterpreter->Execute will improperly correct the offset.
5405 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5408 func.Init(*minfo);
5409 func.SetArgs(listpar);
5410 // Now calculate the 'this' pointer offset for the method
5411 // when starting from the class described by cl.
5412 const CXXMethodDecl * mdecl = dyn_cast<CXXMethodDecl>(minfo->GetTargetFunctionDecl());
5413 Longptr_t offset = ((TClingClassInfo*)cl->GetClassInfo())->GetOffset(mdecl);
5414 void* address = (void*)((Longptr_t)addr + offset);
5415 func.Exec(address);
5416}
5417
5418////////////////////////////////////////////////////////////////////////////////
5419
5421 const void* args[] /*=0*/,
5422 int nargs /*=0*/,
5423 void* ret/*= 0*/) const
5424{
5425 if (!method) {
5426 Error("ExecuteWithArgsAndReturn", "No method was defined");
5427 return;
5428 }
5429
5431 TClingCallFunc func(*minfo);
5432 func.ExecWithArgsAndReturn(address, args, nargs, ret);
5433}
5434
5435////////////////////////////////////////////////////////////////////////////////
5436/// Execute a cling macro.
5437
5439{
5441 fCurExecutingMacros.push_back(filename);
5443 fCurExecutingMacros.pop_back();
5444 return result;
5445}
5446
5447////////////////////////////////////////////////////////////////////////////////
5448/// Return the file name of the current un-included interpreted file.
5449/// See the documentation for GetCurrentMacroName().
5450
5452{
5453 Warning("GetTopLevelMacroName", "Must change return type!");
5454 return fCurExecutingMacros.back();
5455}
5456
5457////////////////////////////////////////////////////////////////////////////////
5458/// Return the file name of the currently interpreted file,
5459/// included or not. Example to illustrate the difference between
5460/// GetCurrentMacroName() and GetTopLevelMacroName():
5461/// ~~~ {.cpp}
5462/// void inclfile() {
5463/// std::cout << "In inclfile.C" << std::endl;
5464/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5465/// TCling::GetCurrentMacroName() << std::endl;
5466/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5467/// TCling::GetTopLevelMacroName() << std::endl;
5468/// }
5469/// ~~~
5470/// ~~~ {.cpp}
5471/// void mymacro() {
5472/// std::cout << "In mymacro.C" << std::endl;
5473/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5474/// TCling::GetCurrentMacroName() << std::endl;
5475/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5476/// TCling::GetTopLevelMacroName() << std::endl;
5477/// std::cout << " Now calling inclfile..." << std::endl;
5478/// gInterpreter->ProcessLine(".x inclfile.C");
5479/// }
5480/// ~~~
5481/// Running mymacro.C will print:
5482///
5483/// ~~~ {.cpp}
5484/// root [0] .x mymacro.C
5485/// ~~~
5486/// In mymacro.C
5487/// ~~~ {.cpp}
5488/// TCling::GetCurrentMacroName() returns ./mymacro.C
5489/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5490/// ~~~
5491/// Now calling inclfile...
5492/// In inclfile.h
5493/// ~~~ {.cpp}
5494/// TCling::GetCurrentMacroName() returns inclfile.C
5495/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5496/// ~~~
5497
5499{
5500#if defined(R__MUST_REVISIT)
5501#if R__MUST_REVISIT(6,0)
5502 Warning("GetCurrentMacroName", "Must change return type!");
5503#endif
5504#endif
5505 return fCurExecutingMacros.back();
5506}
5507
5508////////////////////////////////////////////////////////////////////////////////
5509/// Return the absolute type of typeDesc.
5510/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
5511/// You need to use the result immediately before it is being overwritten.
5512
5513const char* TCling::TypeName(const char* typeDesc)
5514{
5515 TTHREAD_TLS_DECL(std::string,t);
5516
5517 if (!strstr(typeDesc, "(*)(")) {
5518 const char *s = strchr(typeDesc, ' ');
5519 const char *template_start = strchr(typeDesc, '<');
5520 if (!strcmp(typeDesc, "long long")) {
5521 t = typeDesc;
5522 }
5523 else if (!strncmp(typeDesc, "unsigned ", s + 1 - typeDesc)) {
5524 t = typeDesc;
5525 }
5526 // s is the position of the second 'word' (if any)
5527 // except in the case of templates where there will be a space
5528 // just before any closing '>': eg.
5529 // TObj<std::vector<UShort_t,__malloc_alloc_template<0> > >*
5530 else if (s && (template_start == nullptr || (s < template_start))) {
5531 t = s + 1;
5532 }
5533 else {
5534 t = typeDesc;
5535 }
5536 }
5537 else {
5538 t = typeDesc;
5539 }
5540 auto l = t.length();
5541 while (l > 0 && (t[l - 1] == '*' || t[l - 1] == '&'))
5542 --l;
5543 t.resize(l);
5544 return t.c_str(); // NOLINT
5545}
5546
5547static bool requiresRootMap(const char* rootmapfile)
5548{
5550
5551 llvm::StringRef libName = llvm::sys::path::filename(rootmapfile);
5552 libName.consume_back(".rootmap");
5553
5554 return !gInterpreter->HasPCMForLibrary(libName.str().c_str());
5555}
5556
5557////////////////////////////////////////////////////////////////////////////////
5558/// Read and parse a rootmapfile in its new format, and return 0 in case of
5559/// success, -1 if the file has already been read, and -3 in case its format
5560/// is the old one (e.g. containing "Library.ClassName"), -4 in case of syntax
5561/// error.
5562
5564{
5565 if (!(rootmapfile && *rootmapfile))
5566 return 0;
5567
5569 return 0; // success
5570
5571 // For "class ", "namespace ", "typedef ", "header ", "enum ", "var " respectively
5572 const std::map<char, unsigned int> keyLenMap = {{'c',6},{'n',10},{'t',8},{'h',7},{'e',5},{'v',4}};
5573
5575#ifdef _MSC_VER
5576 std::replace(rootmapfileNoBackslash.begin(), rootmapfileNoBackslash.end(), '\\', '/');
5577#endif
5578 // Add content of a specific rootmap file
5580 return -1;
5581
5582 // Line 1 is `{ decls }`
5583 std::string lineDirective = std::string("\n#line 2 \"Forward declarations from ") + rootmapfileNoBackslash + "\"\n";
5584
5585 std::ifstream file(rootmapfileNoBackslash);
5586 std::string line;
5587 line.reserve(200);
5588 std::string lib_name;
5589 line.reserve(100);
5590 bool newFormat = false;
5591 while (getline(file, line, '\n')) {
5592 if (!newFormat && (line.compare(0, 8, "Library.") == 0 || line.compare(0, 8, "Declare.") == 0)) {
5593 file.close();
5594 return -3; // old format
5595 }
5596 newFormat = true;
5597
5598 if (line.compare(0, 9, "{ decls }") == 0) {
5599 // forward declarations
5600
5601 while (getline(file, line, '\n')) {
5602 if (line[0] == '[')
5603 break;
5604 if (!uniqueString) {
5605 Error("ReadRootmapFile", "Cannot handle \"{ decls }\" sections in custom rootmap file %s",
5606 rootmapfileNoBackslash.c_str());
5607 return -4;
5608 }
5609 if (!lineDirective.empty())
5610 uniqueString->Append(lineDirective);
5611 uniqueString->Append(line + '\n');
5612 }
5613 }
5614 const char firstChar = line[0];
5615 if (firstChar == '[') {
5616 // new section (library)
5617 auto brpos = line.find(']');
5618 if (brpos == string::npos)
5619 continue;
5620 lib_name = line.substr(1, brpos - 1);
5621 // Remove spaces at the beginning and at the end of the library name
5622 lib_name.erase(lib_name.find_last_not_of(' ') + 1);
5623 lib_name.erase(0, lib_name.find_first_not_of(' '));
5624 if (gDebug > 3) {
5625 TString lib_nameTstr(lib_name.c_str());
5626 TObjArray *tokens = lib_nameTstr.Tokenize(" ");
5627 const char *lib = ((TObjString *)tokens->At(0))->GetName();
5628 const char *wlib = gSystem->DynamicPathName(lib, kTRUE);
5629 if (wlib) {
5630 Info("ReadRootmapFile", "%s: New section for %s", rootmapfile, lib_nameTstr.Data());
5631 } else {
5632 Info("ReadRootmapFile", "%s: Section for %s (library does not exist)", rootmapfile, lib_nameTstr.Data());
5633 }
5634 delete[] wlib;
5635 delete tokens;
5636 }
5637 } else {
5638 auto keyLenIt = keyLenMap.find(firstChar);
5639 if (keyLenIt == keyLenMap.end())
5640 continue;
5641 unsigned int keyLen = keyLenIt->second;
5642 // Do not make a copy, just start after the key
5643 const char *keyname = line.c_str() + keyLen;
5644 if (gDebug > 6)
5645 Info("ReadRootmapFile", "%s: class %s in %s", rootmapfile, keyname, lib_name.c_str());
5647 if (isThere) {
5648 if (lib_name != isThere->GetValue()) { // the same key for two different libs
5649 if (firstChar == 'n') {
5650 if (gDebug > 3)
5651 Info("ReadRootmapFile",
5652 "While processing %s, namespace %s was found to be associated to %s although it is already "
5653 "associated to %s",
5654 rootmapfile, keyname, lib_name.c_str(), isThere->GetValue());
5655 } else if (firstChar == 'h') { // it is a header: add the libname to the list of libs to be loaded.
5656 lib_name += " ";
5657 lib_name += isThere->GetValue();
5658 fMapfile->SetValue(keyname, lib_name.c_str());
5659 } else if (!TClassEdit::IsSTLCont(keyname)) {
5660 Warning("ReadRootmapFile",
5661 "While processing %s, %s %s was found to be associated to %s although it is already "
5662 "associated to %s",
5663 rootmapfile, line.substr(0, keyLen - 1).c_str(), keyname, lib_name.c_str(),
5664 isThere->GetValue());
5665 }
5666 } else { // the same key for the same lib
5667 if (gDebug > 3)
5668 Info("ReadRootmapFile", "While processing %s, key %s was found to be already defined for %s",
5669 rootmapfile, keyname, lib_name.c_str());
5670 }
5671 } else {
5672 fMapfile->SetValue(keyname, lib_name.c_str());
5673 }
5674 }
5675 }
5676 file.close();
5677 return 0;
5678}
5679
5680////////////////////////////////////////////////////////////////////////////////
5681/// Create a resource table and read the (possibly) three resource files,
5682/// i.e. `$ROOTSYS/etc/system<name>` (or `ROOTETCDIR/system<name>`), `$HOME/<name>`
5683/// and `$PWD/<name>`. ROOT always reads ".rootrc" (in TROOT::InitSystem()). You
5684/// can read additional user defined resource files by creating additional TEnv
5685/// objects. By setting the shell variable ROOTENV_NO_HOME=1 the reading of
5686/// the `$HOME/<name>` resource file will be skipped. This might be useful in
5687/// case the home directory resides on an automounted remote file system
5688/// and one wants to avoid the file system from being mounted.
5689
5691{
5692 assert(requiresRootMap(name) && "We have a module!");
5693
5694 if (!requiresRootMap(name))
5695 return;
5696
5698
5700
5701 TString sname = "system";
5702 sname += name;
5704
5706 if (ret == -3) // old format
5708 delete [] s;
5709 if (!gSystem->Getenv("ROOTENV_NO_HOME")) {
5711 ret = ReadRootmapFile(s);
5712 if (ret == -3) // old format
5714 delete [] s;
5717 if (ret == -3) // old format
5719 }
5720 } else {
5722 if (ret == -3) // old format
5724 }
5726}
5727
5728
5729namespace {
5730 using namespace clang;
5731
5732 class ExtVisibleStorageAdder: public RecursiveASTVisitor<ExtVisibleStorageAdder>{
5733 // This class is to be considered an helper for AutoLoading.
5734 // It is a recursive visitor is used to inspect namespaces and specializations
5735 // coming from forward declarations in rootmaps and to set the external visible
5736 // storage flag for them.
5737 public:
5738 ExtVisibleStorageAdder(std::unordered_set<const NamespaceDecl*>& nsSet): fNSSet(nsSet) {};
5739 bool VisitNamespaceDecl(NamespaceDecl* nsDecl) {
5740 // We want to enable the external lookup for this namespace
5741 // because it may shadow the lookup of other names contained
5742 // in that namespace
5743
5744 nsDecl->setHasExternalVisibleStorage();
5745 fNSSet.insert(nsDecl);
5746 return true;
5747 }
5749 // We want to enable the external lookup for this specialization
5750 // because we can provide a definition for it!
5751 if (specDecl->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
5752 //SpecSet.insert(specDecl);
5753 specDecl->setHasExternalLexicalStorage();
5754
5755 // No need to recurse. On the contrary, recursing is actively harmful:
5756 // NOTE: must not recurse to prevent this visitor from triggering loading from
5757 // the external AST source (i.e. autoloading). This would be triggered right here,
5758 // before autoloading is even set up, as rootmap file parsing happens before that.
5759 // Even if autoloading is off and has no effect, triggering loading from external
5760 // AST source resets the flag setHasExternalLexicalStorage(), hiding this specialization
5761 // from subsequent autoloads!
5762 return false;
5763 }
5764 private:
5765 std::unordered_set<const NamespaceDecl*>& fNSSet;
5766 };
5767}
5768
5769////////////////////////////////////////////////////////////////////////////////
5770/// Load map between class and library. If rootmapfile is specified a
5771/// specific rootmap file can be added (typically used by ACLiC).
5772/// In case of error -1 is returned, 0 otherwise.
5773/// The interpreter uses this information to automatically load the shared
5774/// library for a class (autoload mechanism), see the AutoLoad() methods below.
5775
5777{
5779 return 0;
5780
5782
5783 // open the [system].rootmap files
5784 if (!fMapfile) {
5785 fMapfile = new TEnv();
5789 InitRootmapFile(".rootmap");
5790 }
5791
5792 // Prepare a list of all forward declarations for cling
5793 // For some experiments it is easily as big as 500k characters. To be on the
5794 // safe side, we go for 1M.
5795 TUniqueString uniqueString(1048576);
5796
5797 // Load all rootmap files in the dynamic load path ((DY)LD_LIBRARY_PATH, etc.).
5798 // A rootmap file must end with the string ".rootmap".
5800 if (ldpath != fRootmapLoadPath) {
5802#ifdef WIN32
5803 TObjArray* paths = ldpath.Tokenize(";");
5804#else
5805 TObjArray* paths = ldpath.Tokenize(":");
5806#endif
5807 TString d;
5808 for (Int_t i = 0; i < paths->GetEntriesFast(); i++) {
5809 d = ((TObjString *)paths->At(i))->GetString();
5810 // check if directory already scanned
5811 Int_t skip = 0;
5812 for (Int_t j = 0; j < i; j++) {
5813 TString pd = ((TObjString *)paths->At(j))->GetString();
5814 if (pd == d) {
5815 skip++;
5816 break;
5817 }
5818 }
5819 if (!skip) {
5820 void* dirp = gSystem->OpenDirectory(d);
5821 if (dirp) {
5822 if (gDebug > 3) {
5823 Info("LoadLibraryMap", "%s", d.Data());
5824 }
5825 const char* f1;
5826 while ((f1 = gSystem->GetDirEntry(dirp))) {
5827 TString f = f1;
5828 if (f.EndsWith(".rootmap")) {
5829 TString p;
5830 p = d + "/" + f;
5832 if (!fRootmapFiles->FindObject(f) && f != ".rootmap") {
5833 if (gDebug > 4) {
5834 Info("LoadLibraryMap", " rootmap file: %s", p.Data());
5835 }
5837
5838 if (ret == 0)
5839 fRootmapFiles->Add(new TNamed(gSystem->BaseName(f), p.Data()));
5840 if (ret == -3) {
5841 // old format
5843 fRootmapFiles->Add(new TNamed(f, p));
5844 }
5845 }
5846 // else {
5847 // fprintf(stderr,"Reject %s because %s is already there\n",p.Data(),f.Data());
5848 // fRootmapFiles->FindObject(f)->ls();
5849 // }
5850 }
5851 }
5852 if (f.BeginsWith("rootmap")) {
5853 TString p;
5854 p = d + "/" + f;
5855 FileStat_t stat;
5856 if (gSystem->GetPathInfo(p, stat) == 0 && R_ISREG(stat.fMode)) {
5857 Warning("LoadLibraryMap", "please rename %s to end with \".rootmap\"", p.Data());
5858 }
5859 }
5860 }
5861 }
5863 }
5864 }
5865 delete paths;
5866 if (fMapfile->GetTable() && !fMapfile->GetTable()->GetEntries()) {
5867 return -1;
5868 }
5869 }
5870 if (rootmapfile && *rootmapfile) {
5872 if (res == 0) {
5873 //TString p = gSystem->ConcatFileName(gSystem->pwd(), rootmapfile);
5874 //fRootmapFiles->Add(new TNamed(gSystem->BaseName(rootmapfile), p.Data()));
5876 }
5877 else if (res == -3) {
5878 // old format
5883 }
5884 }
5885 TEnvRec* rec;
5886 TIter next(fMapfile->GetTable());
5887 while ((rec = (TEnvRec*) next())) {
5888 TString cls = rec->GetName();
5889 if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
5890 // get the first lib from the list of lib and dependent libs
5891 TString libs = rec->GetValue();
5892 if (libs == "") {
5893 continue;
5894 }
5895 TString delim(" ");
5896 TObjArray* tokens = libs.Tokenize(delim);
5897 const char* lib = ((TObjString*)tokens->At(0))->GetName();
5898 // convert "@@" to "::", we used "@@" because TEnv
5899 // considers "::" a terminator
5900 cls.Remove(0, 8);
5901 cls.ReplaceAll("@@", "::");
5902 // convert "-" to " ", since class names may have
5903 // blanks and TEnv considers a blank a terminator
5904 cls.ReplaceAll("-", " ");
5905 if (gDebug > 6) {
5906 const char* wlib = gSystem->DynamicPathName(lib, kTRUE);
5907 if (wlib) {
5908 Info("LoadLibraryMap", "class %s in %s", cls.Data(), wlib);
5909 }
5910 else {
5911 Info("LoadLibraryMap", "class %s in %s (library does not exist)", cls.Data(), lib);
5912 }
5913 delete[] wlib;
5914 }
5915 delete tokens;
5916 }
5917 else if (!strncmp(cls.Data(), "Declare.", 8) && cls.Length() > 8) {
5918 cls.Remove(0, 8);
5919 // convert "-" to " ", since class names may have
5920 // blanks and TEnv considers a blank a terminator
5921 cls.ReplaceAll("-", " ");
5922 fInterpreter->declare(cls.Data());
5923 }
5924 }
5925
5926 // Process the forward declarations collected
5927 cling::Transaction* T = nullptr;
5928 auto compRes= fInterpreter->declare(uniqueString.Data(), &T);
5929 assert(cling::Interpreter::kSuccess == compRes && "A declaration in a rootmap could not be compiled");
5930
5931 if (compRes!=cling::Interpreter::kSuccess){
5932 Warning("LoadLibraryMap",
5933 "Problems in %s declaring '%s' were encountered.", rootmapfile, uniqueString.Data()) ;
5934 }
5935
5936 if (T) {
5937 ExtVisibleStorageAdder evsAdder(fNSFromRootmaps);
5938 for (auto declIt = T->decls_begin(); declIt < T->decls_end(); ++declIt) {
5939 if (declIt->m_DGR.isSingleDecl()) {
5940 if (Decl* D = declIt->m_DGR.getSingleDecl()) {
5941 if (clang::isa<TagDecl>(D) || clang::isa<NamespaceDecl>(D)) {
5942 evsAdder.TraverseDecl(D);
5943 }
5944 }
5945 }
5946 }
5947 }
5948
5949 // clear duplicates
5950
5951 return 0;
5952}
5953
5954////////////////////////////////////////////////////////////////////////////////
5955/// Scan again along the dynamic path for library maps. Entries for the loaded
5956/// shared libraries are unloaded first. This can be useful after reseting
5957/// the dynamic path through TSystem::SetDynamicPath()
5958/// In case of error -1 is returned, 0 otherwise.
5959
5966
5967////////////////////////////////////////////////////////////////////////////////
5968/// Reload the library map entries coming from all the loaded shared libraries,
5969/// after first unloading the current ones.
5970/// In case of error -1 is returned, 0 otherwise.
5971
5973{
5975 const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
5976 const Int_t nrSharedLibs = sharedLibL->GetEntriesFast();
5977 for (Int_t ilib = 0; ilib < nrSharedLibs; ilib++) {
5978 const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
5981 if (ret < 0) {
5982 continue;
5983 }
5985 if (sharedLibBaseStr.EndsWith(".dll")) {
5986 rootMapBaseStr.ReplaceAll(".dll", "");
5987 }
5988 else if (sharedLibBaseStr.EndsWith(".DLL")) {
5989 rootMapBaseStr.ReplaceAll(".DLL", "");
5990 }
5991 else if (sharedLibBaseStr.EndsWith(".so")) {
5992 rootMapBaseStr.ReplaceAll(".so", "");
5993 }
5994 else if (sharedLibBaseStr.EndsWith(".sl")) {
5995 rootMapBaseStr.ReplaceAll(".sl", "");
5996 }
5997 else if (sharedLibBaseStr.EndsWith(".dl")) {
5998 rootMapBaseStr.ReplaceAll(".dl", "");
5999 }
6000 else if (sharedLibBaseStr.EndsWith(".a")) {
6001 rootMapBaseStr.ReplaceAll(".a", "");
6002 }
6003 else {
6004 Error("ReloadAllSharedLibraryMaps", "Unknown library type %s", sharedLibBaseStr.Data());
6005 delete sharedLibL;
6006 return -1;
6007 }
6008 rootMapBaseStr += ".rootmap";
6010 if (!rootMap) {
6011 Error("ReloadAllSharedLibraryMaps", "Could not find rootmap %s in path", rootMapBaseStr.Data());
6012 delete[] rootMap;
6013 delete sharedLibL;
6014 return -1;
6015 }
6016 const Int_t status = LoadLibraryMap(rootMap);
6017 if (status < 0) {
6018 Error("ReloadAllSharedLibraryMaps", "Error loading map %s", rootMap);
6019 delete[] rootMap;
6020 delete sharedLibL;
6021 return -1;
6022 }
6023 delete[] rootMap;
6024 }
6025 delete sharedLibL;
6026 return 0;
6027}
6028
6029////////////////////////////////////////////////////////////////////////////////
6030/// Unload the library map entries coming from all the loaded shared libraries.
6031/// Returns 0 if succesful
6032
6034{
6036 const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
6037 for (Int_t ilib = 0; ilib < sharedLibL->GetEntriesFast(); ilib++) {
6038 const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
6041 }
6042 delete sharedLibL;
6043 return 0;
6044}
6045
6046////////////////////////////////////////////////////////////////////////////////
6047/// Unload library map entries coming from the specified library.
6048/// Returns -1 in case no entries for the specified library were found,
6049/// 0 otherwise.
6050
6052{
6053 if (!fMapfile || !library || !*library) {
6054 return 0;
6055 }
6057 Ssiz_t idx = libname.Last('.');
6058 if (idx != kNPOS) {
6059 libname.Remove(idx);
6060 }
6061 size_t len = libname.Length();
6062 TEnvRec *rec;
6063 TIter next(fMapfile->GetTable());
6065 Int_t ret = 0;
6066 while ((rec = (TEnvRec *) next())) {
6067 TString cls = rec->GetName();
6068 if (cls.Length() > 2) {
6069 // get the first lib from the list of lib and dependent libs
6070 TString libs = rec->GetValue();
6071 if (libs == "") {
6072 continue;
6073 }
6074 TString delim(" ");
6075 TObjArray* tokens = libs.Tokenize(delim);
6076 const char* lib = ((TObjString *)tokens->At(0))->GetName();
6077 if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
6078 // convert "@@" to "::", we used "@@" because TEnv
6079 // considers "::" a terminator
6080 cls.Remove(0, 8);
6081 cls.ReplaceAll("@@", "::");
6082 // convert "-" to " ", since class names may have
6083 // blanks and TEnv considers a blank a terminator
6084 cls.ReplaceAll("-", " ");
6085 }
6086 if (!strncmp(lib, libname.Data(), len)) {
6087 if (fMapfile->GetTable()->Remove(rec) == nullptr) {
6088 Error("UnloadLibraryMap", "entry for <%s, %s> not found in library map table", cls.Data(), lib);
6089 ret = -1;
6090 }
6091 }
6092 delete tokens;
6093 }
6094 }
6095 if (ret >= 0) {
6097 if (!library_rootmap.EndsWith(".rootmap"))
6098 library_rootmap.Append(".rootmap");
6099 TNamed* mfile = nullptr;
6102 delete mfile;
6103 }
6105 }
6106 return ret;
6107}
6108
6109////////////////////////////////////////////////////////////////////////////////
6110/// Register the AutoLoading information for a class.
6111/// libs is a space separated list of libraries.
6112
6113Int_t TCling::SetClassSharedLibs(const char *cls, const char *libs)
6114{
6115 if (!cls || !*cls)
6116 return 0;
6117
6118 TString key = TString("Library.") + cls;
6119 // convert "::" to "@@", we used "@@" because TEnv
6120 // considers "::" a terminator
6121 key.ReplaceAll("::", "@@");
6122 // convert "-" to " ", since class names may have
6123 // blanks and TEnv considers a blank a terminator
6124 key.ReplaceAll(" ", "-");
6125
6127 if (!fMapfile) {
6128 fMapfile = new TEnv();
6130
6133
6134 InitRootmapFile(".rootmap");
6135 }
6136 //fMapfile->SetValue(key, libs);
6138 return 1;
6139}
6140
6141////////////////////////////////////////////////////////////////////////////////
6142/// Demangle the name (from the typeinfo) and then request the class
6143/// via the usual name based interface (TClass::GetClass).
6144
6145TClass *TCling::GetClass(const std::type_info& typeinfo, Bool_t load) const
6146{
6147 int err = 0;
6149 if (err) return nullptr;
6152 return theClass;
6153}
6154
6155////////////////////////////////////////////////////////////////////////////////
6156/// Load library containing the specified class. Returns 0 in case of error
6157/// and 1 in case if success.
6158
6159Int_t TCling::AutoLoad(const std::type_info& typeinfo, Bool_t knowDictNotLoaded /* = kFALSE */)
6160{
6161 assert(IsClassAutoLoadingEnabled() && "Calling when AutoLoading is off!");
6162
6163 int err = 0;
6165 if (err) {
6166 return 0;
6167 }
6168
6169 std::string demangled_name(demangled_name_c);
6171
6172 // AutoLoad expects (because TClass::GetClass already prepares it that way) a
6173 // shortened name.
6176
6177 // No need to worry about typedef, they aren't any ... but there are
6178 // inlined namespaces ...
6179
6181 if (result == 0) {
6184 }
6185
6186 return result;
6187}
6188
6189////////////////////////////////////////////////////////////////////////////////
6190// Get the list of 'published'/'known' library for the class and load them.
6192{
6193 Int_t status = 0;
6194
6195 // lookup class to find list of dependent libraries
6197 if (!deplibs.IsNull()) {
6198 TString delim(" ");
6199 TObjArray* tokens = deplibs.Tokenize(delim);
6200 for (Int_t i = (tokens->GetEntriesFast() - 1); i > 0; --i) {
6201 const char* deplib = ((TObjString*)tokens->At(i))->GetName();
6202 if (gROOT->LoadClass(cls, deplib) == 0) {
6203 if (gDebug > 0) {
6204 gCling->Info("TCling::AutoLoad",
6205 "loaded dependent library %s for %s", deplib, cls);
6206 }
6207 }
6208 else {
6209 gCling->Error("TCling::AutoLoad",
6210 "failure loading dependent library %s for %s",
6211 deplib, cls);
6212 }
6213 }
6214 const char* lib = ((TObjString*)tokens->At(0))->GetName();
6215 if (lib && lib[0]) {
6216 if (gROOT->LoadClass(cls, lib) == 0) {
6217 if (gDebug > 0) {
6218 gCling->Info("TCling::AutoLoad",
6219 "loaded library %s for %s", lib, cls);
6220 }
6221 status = 1;
6222 }
6223 else {
6224 gCling->Error("TCling::AutoLoad",
6225 "failure loading library %s for %s", lib, cls);
6226 }
6227 }
6228 delete tokens;
6229 }
6230
6231 return status;
6232}
6233
6234////////////////////////////////////////////////////////////////////////////////
6235// Iterate through the data member of the class (either through the TProtoClass
6236// or through Cling) and trigger, recursively, the loading the necessary libraries.
6237// \note `cls` is expected to be already normalized!
6238// \returns 1 on success.
6239Int_t TCling::DeepAutoLoadImpl(const char *cls, std::unordered_set<std::string> &visited,
6240 bool nameIsNormalized)
6241{
6242 // Try to insert; if insertion failed because the entry existed, DeepAutoLoadImpl()
6243 // has previously (within the same call to `AutoLoad()`) tried to load this class
6244 // and we are done, whether success or not, as it won't work better now than before,
6245 // because there is no additional information now compared to before.
6246 if (!visited.insert(std::string(cls)).second)
6247 return 1;
6248
6249 if (ShallowAutoLoadImpl(cls) == 0) {
6250 // If ShallowAutoLoadImpl() has an error, we have an error.
6251 return 0;
6252 }
6253
6254 // Now look through the TProtoClass to load the required library/dictionary
6256 for (auto element : proto->GetData()) {
6257 if (element->IsBasic())
6258 continue;
6259 const char *subtypename = element->GetTypeName();
6261 // Failure to load a dictionary is not (quite) a failure load
6262 // the top-level library. If we return false here, then
6263 // we would end up in a situation where the library and thus
6264 // the dictionary is loaded for "cls" but the TClass is
6265 // not created and/or marked as unavailable (in case where
6266 // AutoLoad is called from TClass::GetClass).
6267 DeepAutoLoadImpl(subtypename, visited, true /*normalized*/);
6268 }
6269 }
6270 return 1;
6271 }
6272
6273 // We found no TProtoClass for cls.
6274 auto classinfo = gInterpreter->ClassInfo_Factory(cls);
6275 if (classinfo && gInterpreter->ClassInfo_IsValid(classinfo)
6276 && !(gInterpreter->ClassInfo_Property(classinfo) & kIsEnum))
6277 {
6279 while (gInterpreter->DataMemberInfo_Next(memberinfo)) {
6280 if (gInterpreter->DataMemberInfo_TypeProperty(memberinfo) & ::kIsFundamental)
6281 continue;
6282 auto membertypename = TClassEdit::GetLong64_Name(gInterpreter->TypeName(gInterpreter->DataMemberInfo_TypeTrueName(memberinfo)));
6284 // Failure to load a dictionary is not (quite) a failure load
6285 // the top-level library. See detailed comment in the TProtoClass
6286 // branch (above).
6287 (void)DeepAutoLoadImpl(membertypename.c_str(), visited, true /*normalized*/);
6288 }
6289 }
6290 gInterpreter->DataMemberInfo_Delete(memberinfo);
6291 }
6292 gInterpreter->ClassInfo_Delete(classinfo);
6293 return 1;
6294}
6295
6296////////////////////////////////////////////////////////////////////////////////
6297/// Load library containing the specified class. Returns 0 in case of error
6298/// and 1 in case if success.
6299
6301{
6302 // Prevent update to IsClassAutoloading between our check and our actions.
6304
6305 // TClass::GetClass explicitly calls gInterpreter->AutoLoad. When called from
6306 // rootcling (in *_rdict.pcm file generation) it is a no op.
6307 // FIXME: We should avoid calling autoload when we know we are not supposed
6308 // to and transform this check into an assert.
6310 // Never load any library from rootcling/genreflex.
6311 if (gDebug > 2) {
6312 Info("TCling::AutoLoad", "Explicitly disabled (the class name is %s)", cls);
6313 }
6314 return 0;
6315 }
6316
6317 assert(IsClassAutoLoadingEnabled() && "Calling when AutoLoading is off!");
6318
6320
6322 // The library is already loaded as the class's dictionary is known.
6323 // Return success.
6324 // Note: the name (cls) is expected to be normalized as it comes either
6325 // from a callbacks (that can/should calculate the normalized name from the
6326 // decl) or from TClass::GetClass (which does also calculate the normalized
6327 // name).
6328 return 1;
6329 }
6330
6331 if (gDebug > 2) {
6332 Info("TCling::AutoLoad",
6333 "Trying to autoload for %s", cls);
6334 }
6335
6336 if (!gROOT || !gInterpreter || gROOT->TestBit(TObject::kInvalidObject)) {
6337 if (gDebug > 2) {
6338 Info("TCling::AutoLoad",
6339 "Disabled due to gROOT or gInterpreter being invalid/not ready (the class name is %s)", cls);
6340 }
6341 return 0;
6342 }
6343 // Prevent the recursion when the library dictionary are loaded.
6345 // Try using externally provided callback first.
6346 if (fAutoLoadCallBack) {
6348 if (success)
6349 return success;
6350 }
6351
6352 // During the 'Deep' part of the search we will call GetClassSharedLibsForModule
6353 // (when module are enabled) which might end up calling AutoParsing but
6354 // that should only be for the cases where the library has no generated pcm
6355 // and in that case a rootmap should be available.
6356 // This avoids a very costly operation (for generally no gain) but reduce the
6357 // quality of the search (i.e. bad in case of library with no pcm and no rootmap
6358 // file).
6360 std::unordered_set<std::string> visited;
6361 return DeepAutoLoadImpl(cls, visited, false /*normalized*/);
6362}
6363
6364////////////////////////////////////////////////////////////////////////////////
6365/// Parse the payload or header.
6366
6367static cling::Interpreter::CompilationResult ExecAutoParse(const char *what,
6368 Bool_t header,
6369 cling::Interpreter *interpreter)
6370{
6371 std::string code = gNonInterpreterClassDef ;
6372 if (!header) {
6373 // This is the complete header file content and not the
6374 // name of a header.
6375 code += what;
6376
6377 } else {
6378 code += ("#include \"");
6379 code += what;
6380 code += "\"\n";
6381 }
6382 code += ("#ifdef __ROOTCLING__\n"
6383 "#undef __ROOTCLING__\n"
6385 "#endif");
6386
6387 cling::Interpreter::CompilationResult cr;
6388 {
6389 // scope within which diagnostics are de-activated
6390 // For now we disable diagnostics because we saw them already at
6391 // dictionary generation time. That won't be an issue with the PCMs.
6392
6393 Sema &SemaR = interpreter->getSema();
6395 clangDiagSuppr diagSuppr(SemaR.getDiagnostics());
6396
6397 #if defined(R__MUST_REVISIT)
6398 #if R__MUST_REVISIT(6,2)
6399 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
6400 #endif
6401 #endif
6402
6403 cr = interpreter->parseForModule(code);
6404 }
6405 return cr;
6406}
6407
6408////////////////////////////////////////////////////////////////////////////////
6409/// Helper routine for TCling::AutoParse implementing the actual call to the
6410/// parser and looping over template parameters (if
6411/// any) and when they don't have a registered header to autoparse,
6412/// recurse over their template parameters.
6413///
6414/// Returns the number of header parsed.
6415
6417{
6418 // We assume the lock has already been taken.
6419 // R__LOCKGUARD(gInterpreterMutex);
6420
6422 unsigned long offset = 0;
6423 if (strncmp(cls, "const ", 6) == 0) {
6424 offset = 6;
6425 }
6426
6427 // Loop on the possible autoparse keys
6428 bool skipFirstEntry = false;
6429 std::vector<std::string> autoparseKeys;
6430 if (strchr(cls, '<')) {
6431 int nestedLoc = 0;
6433 // Check if we can skip the name of the template in the autoparses
6434 // Take all the scopes one by one. If all of them are in the AST, we do not
6435 // need to autoparse for that particular template.
6436 if (!autoparseKeys.empty() && !autoparseKeys[0].empty()) {
6437 // autoparseKeys[0] is empty when the input is not a template instance.
6438 // The case strchr(cls, '<') != 0 but still not a template instance can
6439 // happens 'just' for string (GetSplit replaces the template by the short name
6440 // and then use that for thew splitting)
6442 auto tokens = templateName.Tokenize("::");
6443 clang::NamedDecl* previousScopeAsNamedDecl = nullptr;
6444 clang::DeclContext* previousScopeAsContext = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
6446 previousScopeAsContext = fInterpreter->getSema().getStdNamespace();
6447 auto nTokens = tokens->GetEntriesFast();
6448 for (Int_t tk = 0; tk < nTokens; ++tk) {
6449 auto scopeObj = tokens->UncheckedAt(tk);
6450 auto scopeName = ((TObjString*) scopeObj)->String().Data();
6451 previousScopeAsNamedDecl = cling::utils::Lookup::Named(&fInterpreter->getSema(), scopeName, previousScopeAsContext);
6452 // Check if we have multiple nodes in the AST with this name
6453 if ((clang::NamedDecl*)-1 == previousScopeAsNamedDecl) break;
6454 previousScopeAsContext = llvm::dyn_cast_or_null<clang::DeclContext>(previousScopeAsNamedDecl);
6455 if (!previousScopeAsContext) break; // this is not a context
6456 }
6457 delete tokens;
6458 // Now, let's check if the last scope, the template, has a definition, i.e. it's not a fwd decl
6459 if ((clang::NamedDecl*)-1 != previousScopeAsNamedDecl) {
6460 if (auto templateDecl = llvm::dyn_cast_or_null<clang::ClassTemplateDecl>(previousScopeAsNamedDecl)) {
6461 if (auto templatedDecl = templateDecl->getTemplatedDecl()) {
6462 skipFirstEntry = templatedDecl->hasDefinition();
6463 }
6464 }
6465 }
6466
6467 }
6468 }
6469 if (topLevel) autoparseKeys.emplace_back(cls);
6470
6471 for (const auto & apKeyStr : autoparseKeys) {
6472 if (skipFirstEntry) {
6473 skipFirstEntry=false;
6474 continue;
6475 }
6476 if (apKeyStr.empty()) continue;
6477 const char *apKey = apKeyStr.c_str();
6479 // If the class was not looked up
6480 if (gDebug > 1) {
6481 Info("TCling::AutoParse",
6482 "Starting autoparse for %s\n", apKey);
6483 }
6484 if (fLookedUpClasses.insert(normNameHash).second) {
6485 auto const &iter = fClassesHeadersMap.find(normNameHash);
6486 if (iter != fClassesHeadersMap.end()) {
6487 const cling::Transaction *T = fInterpreter->getCurrentTransaction();
6489 auto const &hNamesPtrs = iter->second;
6490 if (gDebug > 1) {
6491 Info("TCling::AutoParse",
6492 "We can proceed for %s. We have %s headers.", apKey, std::to_string(hNamesPtrs.size()).c_str());
6493 }
6494 for (auto & hName : hNamesPtrs) {
6495 if (fParsedPayloadsAddresses.count(hName) == 1) continue;
6496 if (0 != fPayloads.count(normNameHash)) {
6497 float initRSSval=0.f, initVSIZEval=0.f;
6498 (void) initRSSval; // Avoid unused var warning
6499 (void) initVSIZEval;
6500 if (gDebug > 0) {
6501 Info("AutoParse",
6502 "Parsing full payload for %s", apKey);
6505 initRSSval = 1e-3*info.fMemResident;
6506 initVSIZEval = 1e-3*info.fMemVirtual;
6507 }
6509 if (cRes != cling::Interpreter::kSuccess) {
6510 if (hName[0] == '\n')
6511 Error("AutoParse", "Error parsing payload code for class %s with content:\n%s", apKey, hName);
6512 } else {
6515 if (gDebug > 0){
6518 float endRSSval = 1e-3*info.fMemResident;
6519 float endVSIZEval = 1e-3*info.fMemVirtual;
6520 Info("Autoparse", ">>> RSS key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initRSSval, endRSSval, endRSSval-initRSSval);
6521 Info("Autoparse", ">>> VSIZE key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initVSIZEval, endVSIZEval, endVSIZEval-initVSIZEval);
6522 }
6523 }
6524 } else if (!IsLoaded(hName)) {
6525 if (gDebug > 0) {
6526 Info("AutoParse",
6527 "Parsing single header %s", hName);
6528 }
6530 if (cRes != cling::Interpreter::kSuccess) {
6531 Error("AutoParse", "Error parsing headerfile %s for class %s.", hName, apKey);
6532 } else {
6534 }
6535 }
6536 }
6537 }
6538 else {
6539 // There is no header registered for this class, if this a
6540 // template, it will be instantiated if/when it is requested
6541 // and if we do no load/parse its components we might end up
6542 // not using an eventual specialization.
6543 if (strchr(apKey, '<')) {
6545 }
6546 }
6547 }
6548 }
6549
6550 return nHheadersParsed;
6551
6552}
6553
6554////////////////////////////////////////////////////////////////////////////////
6555/// Parse the headers relative to the class
6556/// Returns 1 in case of success, 0 in case of failure
6557
6559{
6560 if (llvm::StringRef(cls).contains("(lambda)"))
6561 return 0;
6562
6565 return AutoLoad(cls);
6566 } else {
6567 return 0;
6568 }
6569 }
6570
6572
6573 if (gDebug > 1) {
6574 Info("TCling::AutoParse",
6575 "Trying to autoparse for %s", cls);
6576 }
6577
6578 // The catalogue of headers is in the dictionary
6580 && !gClassTable->GetDictNorm(cls)) {
6581 // Need RAII against recursive (dictionary payload) parsing (ROOT-8445).
6583 fInterpreter->getSema());
6584 AutoLoad(cls, true /*knowDictNotLoaded*/);
6585 }
6586
6587 // Prevent the recursion when the library dictionary are loaded.
6589
6590 // No recursive header parsing on demand; we require headers to be standalone.
6592
6593 Int_t nHheadersParsed = AutoParseImplRecurse(cls,/*topLevel=*/ true);
6594
6596
6597 return nHheadersParsed > 0 ? 1 : 0;
6598}
6599
6600// This is a function which gets callback from cling when DynamicLibraryManager->loadLibrary failed for some reason.
6601// Try to solve the problem by AutoLoading. Return true when AutoLoading success, return
6602// false if not.
6603bool TCling::LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
6604{
6606 if (errMsg.contains("undefined symbol: ")) {
6607 // This branch is taken when the callback was from DynamicLibraryManager::loadLibrary
6608 std::string mangled_name = std::string(errMsg.split("undefined symbol: ").second);
6609 void* res = ((TCling*)gCling)->LazyFunctionCreatorAutoload(mangled_name);
6610 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
6611 if (res && DLM && (DLM->loadLibrary(libStem, permanent, resolved) == cling::DynamicLibraryManager::kLoadLibSuccess))
6612 // Return success when LazyFunctionCreatorAutoload could find mangled_name
6613 return true;
6614 } else {
6615 // The callback is from IncrementalExecutor::diagnoseUnresolvedSymbols
6617 return true;
6618 }
6619
6620 return false;
6621}
6622
6623////////////////////////////////////////////////////////////////////////////////
6624/// Autoload a library based on a missing symbol.
6625
6628
6629 // We have already loaded the library.
6630 if (void* Addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(dlsym_mangled_name))
6631 return Addr;
6632
6633 const cling::DynamicLibraryManager &DLM = *GetInterpreterImpl()->getDynamicLibraryManager();
6635
6636 auto LibLoader = [](const std::string& LibName) -> bool {
6637 if (gSystem->Load(LibName.c_str(), "", false) < 0) {
6638 ::Error("TCling__LazyFunctionCreatorAutoloadForModule",
6639 "Failed to load library %s", LibName.c_str());
6640 return false;
6641 }
6642 return true; //success.
6643 };
6644
6645 std::string libName = DLM.searchLibrariesForSymbol(mangled_name,
6646 /*searchSystem=*/ true);
6647
6648 assert(!llvm::StringRef(libName).starts_with("libNew") && "We must not resolve symbols from libNew!");
6649
6650 if (libName.empty())
6651 return nullptr;
6652
6653 if (!LibLoader(libName))
6654 return nullptr;
6655
6656 return llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(dlsym_mangled_name);
6657}
6658
6659////////////////////////////////////////////////////////////////////////////////
6660
6662{
6663 return fNSFromRootmaps.count(nsDecl) != 0;
6664}
6665
6666////////////////////////////////////////////////////////////////////////////////
6667/// Internal function. Actually do the update of the ClassInfo when seeing
6668// new TagDecl or NamespaceDecl.
6669void TCling::RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
6670{
6671
6673 if (cci) {
6674 // If we only had a forward declaration then update the
6675 // TClingClassInfo with the definition if we have it now.
6676 const NamedDecl *oldDef = llvm::dyn_cast_or_null<NamedDecl>(cci->GetDecl());
6677 if (!oldDef || (def && def != oldDef)) {
6678 cl->ResetCaches();
6679 TClass::RemoveClassDeclId(cci->GetDeclId());
6680 if (def) {
6681 if (cci->GetType()) {
6682 // It's a tag decl, not a namespace decl.
6683 cci->Init(*cci->GetType());
6684 TClass::AddClassToDeclIdMap(cci->GetDeclId(), cl);
6685 } else {
6686 Error("RefreshClassInfo", "Should not need to update the classInfo a non type decl: %s", oldDef->getNameAsString().c_str());
6687 }
6688 }
6689 }
6690 } else if (!cl->TestBit(TClass::kLoading) && !cl->fHasRootPcmInfo) {
6691 cl->ResetCaches();
6692 if (strncmp(cl->GetName(),"tuple<",strlen("tuple<"))==0) {
6693 // We need to use the Emulated Tuple but we should not trigger parsing
6694 // yet, so delay the creation of the ClassInfo
6695 delete ((TClingClassInfo *)cl->fClassInfo);
6696 cl->fClassInfo = nullptr;
6697 cl->fCanLoadClassInfo = true;
6699 if (cl->fState != TClass::kHasTClassInit) {
6701 }
6702 return;
6703 }
6704 // yes, this is almost a waste of time, but we do need to lookup
6705 // the 'type' corresponding to the TClass anyway in order to
6706 // preserve the opaque typedefs (Double32_t)
6707 if (!alias && def != nullptr)
6709 else
6711 if (((TClingClassInfo *)cl->fClassInfo)->IsValid()) {
6712 // We now need to update the state and bits.
6713 if (cl->fState != TClass::kHasTClassInit) {
6714 // if (!cl->fClassInfo->IsValid()) cl->fState = TClass::kForwardDeclared; else
6716 }
6717 TClass::AddClassToDeclIdMap(((TClingClassInfo *)(cl->fClassInfo))->GetDeclId(), cl);
6718 } else {
6719 delete ((TClingClassInfo *)cl->fClassInfo);
6720 cl->fClassInfo = nullptr;
6721 }
6722 }
6723}
6724
6725////////////////////////////////////////////////////////////////////////////////
6726/// Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
6728{
6729 const TagDecl *td = dyn_cast<TagDecl>(ND);
6731 const NamedDecl *canon = nullptr;
6732
6733 std::string name;
6734 TagDecl* tdDef = nullptr;
6735 if (td) {
6736 canon = tdDef = td->getDefinition();
6737 // Let's pass the decl to the TClass only if it has a definition.
6738 if (!tdDef) return;
6739
6740 if (!tdDef->isCompleteDefinition() || llvm::isa<clang::FunctionDecl>(tdDef->getDeclContext())) {
6741 // Ignore incomplete definition.
6742 // Ignore declaration within a function.
6743 return;
6744 }
6745
6746 auto declName = tdDef->getNameAsString();
6747 // Check if we have registered the unqualified name into the list
6748 // of TClass that are in kNoInfo, kEmulated or kFwdDeclaredState.
6749 // Since this is used as heureutistic to avoid spurrious calls to GetNormalizedName
6750 // the unqualified name is sufficient (and the fully qualified name might be
6751 // 'wrong' if there is difference in spelling in the template paramters (for example)
6753 // 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() );
6754 return;
6755 }
6756
6757 clang::QualType type(tdDef->getTypeForDecl(), 0);
6759 } else if (ns) {
6760 canon = ns->getCanonicalDecl();
6761 name = ND->getQualifiedNameAsString();
6762 } else {
6763 name = ND->getQualifiedNameAsString();
6764 }
6765
6766 // Supposedly we are being called while something is being
6767 // loaded ... let's now tell the autoloader to do the work
6768 // yet another time.
6770 // FIXME: There can be more than one TClass for a single decl.
6771 // for example vector<double> and vector<Double32_t>
6772 TClass* cl = (TClass*)gROOT->GetListOfClasses()->FindObject(name.c_str());
6773 if (cl && GetModTClasses().find(cl) == GetModTClasses().end()) {
6774 RefreshClassInfo(cl, canon, false);
6775 }
6776 // And here we should find the other 'aliases' (eg. vector<Double32_t>)
6777 // and update them too:
6778 // foreach(aliascl in gROOT->GetListOfClasses()->FindAliasesOf(name.c_str()))
6779 // RefreshClassInfo(cl, tdDef, true);
6780}
6781
6782////////////////////////////////////////////////////////////////////////////////
6783/// No op: see TClingCallbacks
6784
6786{
6787}
6788
6789//______________________________________________________________________________
6790//FIXME: Factor out that function in TClass, because TClass does it already twice
6792{
6793 // This is a no-op as part of the API.
6794 // TCling uses UpdateClassInfoWithDecl() instead.
6795}
6796
6797////////////////////////////////////////////////////////////////////////////////
6798/// Update all canvases at end the terminal input command.
6799
6801{
6802 TIter next(gROOT->GetListOfCanvases());
6803 TVirtualPad* canvas;
6804 while ((canvas = (TVirtualPad*)next())) {
6805 canvas->Update();
6806 }
6807}
6808
6809////////////////////////////////////////////////////////////////////////////////
6810
6811void TCling::UpdateListsOnCommitted(const cling::Transaction &T) {
6812 std::set<TClass*> modifiedTClasses; // TClasses that require update after this transaction
6813
6814 // If the transaction does not contain anything we can return earlier.
6815 if (!HandleNewTransaction(T)) return;
6816
6817 bool isTUTransaction = false;
6818 if (!T.empty() && T.decls_begin() + 1 == T.decls_end() && !T.hasNestedTransactions()) {
6819 clang::Decl* FirstDecl = *(T.decls_begin()->m_DGR.begin());
6820 if (llvm::isa<clang::TranslationUnitDecl>(FirstDecl)) {
6821 // The is the first transaction, we have to expose to meta
6822 // what's already in the AST.
6823 isTUTransaction = true;
6824 }
6825 }
6826
6827 std::set<const void*> TransactionDeclSet;
6828 if (!isTUTransaction && T.decls_end() - T.decls_begin()) {
6829 const clang::Decl* WrapperFD = T.getWrapperFD();
6830 for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
6831 I != E; ++I) {
6832 if (I->m_Call != cling::Transaction::kCCIHandleTopLevelDecl
6833 && I->m_Call != cling::Transaction::kCCIHandleTagDeclDefinition)
6834 continue;
6835
6836 for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6837 DE = I->m_DGR.end(); DI != DE; ++DI) {
6838 if (*DI == WrapperFD)
6839 continue;
6840 TransactionDeclSet.insert(*DI);
6841 ((TCling*)gCling)->HandleNewDecl(*DI, false, modifiedTClasses);
6842 }
6843 }
6844 }
6845
6846 // The above might trigger more decls to be deserialized.
6847 // Thus the iteration over the deserialized decls must be last.
6848 for (cling::Transaction::const_iterator I = T.deserialized_decls_begin(),
6849 E = T.deserialized_decls_end(); I != E; ++I) {
6850 for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6851 DE = I->m_DGR.end(); DI != DE; ++DI)
6852 if (TransactionDeclSet.find(*DI) == TransactionDeclSet.end()) {
6853 //FIXME: HandleNewDecl should take DeclGroupRef
6854 ((TCling*)gCling)->HandleNewDecl(*DI, /*isDeserialized*/true,
6856 }
6857 }
6858
6859
6860 // When fully building the reflection info in TClass, a deserialization
6861 // could be triggered, which may result in request for building the
6862 // reflection info for the same TClass. This in turn will clear the caches
6863 // for the TClass in-flight and cause null ptr derefs.
6864 // FIXME: This is a quick fix, solving most of the issues. The actual
6865 // question is: Shouldn't TClass provide a lock mechanism on update or lock
6866 // itself until the update is done.
6867 //
6868 std::vector<TClass*> modifiedTClassesDiff(modifiedTClasses.size());
6869 std::vector<TClass*>::iterator it;
6871 ((TCling*)gCling)->GetModTClasses().begin(),
6872 ((TCling*)gCling)->GetModTClasses().end(),
6875
6876 // Lock the TClass for updates
6877 ((TCling*)gCling)->GetModTClasses().insert(modifiedTClassesDiff.begin(),
6879 for (std::vector<TClass*>::const_iterator I = modifiedTClassesDiff.begin(),
6880 E = modifiedTClassesDiff.end(); I != E; ++I) {
6881 // Make sure the TClass has not been deleted.
6882 if (!gROOT->GetListOfClasses()->FindObject(*I)) {
6883 continue;
6884 }
6885 // Could trigger deserialization of decls.
6886 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
6887 // Unlock the TClass for updates
6888 ((TCling*)gCling)->GetModTClasses().erase(*I);
6889
6890 }
6891}
6892
6893///\brief Invalidate stored TCling state for declarations included in transaction `T'.
6894///
6895void TCling::UpdateListsOnUnloaded(const cling::Transaction &T)
6896{
6898
6899 auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
6900 (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
6901 (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
6902 (TListOfEnums *)gROOT->GetListOfEnums());
6903
6904 cling::Transaction::const_nested_iterator iNested = T.nested_begin();
6905 for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
6906 I != E; ++I) {
6907 if (I->m_Call == cling::Transaction::kCCIHandleVTable)
6908 continue;
6909 if (I->m_Call == cling::Transaction::kCCINone) {
6911 ++iNested;
6912 continue;
6913 }
6914
6915 for (auto &D : I->m_DGR)
6917 }
6918}
6919
6920///\brief Invalidate cached TCling information for the given global declaration.
6921///
6923 auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
6924 (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
6925 (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
6926 (TListOfEnums *)gROOT->GetListOfEnums());
6928}
6929
6930///\brief Invalidate cached TCling information for the given declaration, and
6931/// removed it from the appropriate object list.
6932///\param[in] Lists - std::tuple<TListOfDataMembers&, TListOfFunctions&,
6933/// TListOfFunctionTemplates&, TListOfEnums&>
6934/// of pointers to the (global/class) object lists.
6935///\param[in] D - Decl to discard.
6936///
6940 TListOfEnums*> &Lists, const Decl *D) {
6941 if (D->isFromASTFile()) // `D' came from the PCH; ignore
6942 return;
6943
6944 TListOfDataMembers &LODM = *(std::get<0>(Lists));
6945 TListOfFunctions &LOF = *(std::get<1>(Lists));
6946 TListOfFunctionTemplates &LOFT = *(std::get<2>(Lists));
6947 TListOfEnums &LOE = *(std::get<3>(Lists));
6948
6950 TObject *O = LODM.Find((TDictionary::DeclId_t)D);
6951 if (LODM.GetClass())
6952 RemoveAndInvalidateObject(LODM, static_cast<TDataMember *>(O));
6953 else
6954 RemoveAndInvalidateObject(LODM, static_cast<TGlobal *>(O));
6955 } else if (isa<FunctionDecl>(D)) {
6957 } else if (isa<FunctionTemplateDecl>(D)) {
6959 } else if (isa<EnumDecl>(D)) {
6960 TEnum *E = LOE.Find((TDictionary::DeclId_t)D);
6961 if (!E)
6962 return;
6963
6964 // Try to invalidate enumerators (for unscoped enumerations).
6965 for (TIter I = E->GetConstants(); auto EC = (TEnumConstant *)I(); )
6967 (TEnumConstant *)LODM.FindObject(EC->GetName()));
6968
6970 } else if (isa<RecordDecl>(D) || isa<NamespaceDecl>(D)) {
6972 return;
6973
6974 std::vector<TClass *> Classes;
6975 if (!TClass::GetClass(D->getCanonicalDecl(), Classes))
6976 return;
6977 for (auto &C : Classes) {
6978 auto Lists = std::make_tuple((TListOfDataMembers *)C->GetListOfDataMembers(),
6979 (TListOfFunctions *)C->GetListOfMethods(),
6980 (TListOfFunctionTemplates *)C->GetListOfFunctionTemplates(),
6981 (TListOfEnums *)C->GetListOfEnums());
6982 for (auto &I : cast<DeclContext>(D)->decls())
6984
6985 // For NamespaceDecl (redeclarable), only invalidate this redecl.
6986 if (D->getKind() != Decl::Namespace
6987 || cast<NamespaceDecl>(D)->isOriginalNamespace())
6988 C->ResetClassInfo();
6989 }
6990 }
6991}
6992
6993////////////////////////////////////////////////////////////////////////////////
6994// If an autoparse was done during a transaction and that it is rolled back,
6995// we need to make sure the next request for the same autoparse will be
6996// honored.
6997void TCling::TransactionRollback(const cling::Transaction &T) {
6998 auto const &triter = fTransactionHeadersMap.find(&T);
6999 if (triter != fTransactionHeadersMap.end()) {
7000 std::size_t normNameHash = triter->second;
7001
7003
7004 auto const &iter = fClassesHeadersMap.find(normNameHash);
7005 if (iter != fClassesHeadersMap.end()) {
7006 auto const &hNamesPtrs = iter->second;
7007 for (auto &hName : hNamesPtrs) {
7008 if (gDebug > 0) {
7009 Info("TransactionRollback",
7010 "Restoring ability to autoaparse: %s", hName);
7011 }
7013 }
7014 }
7015 }
7016}
7017
7018////////////////////////////////////////////////////////////////////////////////
7019
7020void TCling::LibraryLoaded(const void* dyLibHandle, const char* canonicalName) {
7021// R__LOCKGUARD_CLING(gInterpreterMutex);
7022// UpdateListOfLoadedSharedLibraries();
7023}
7024
7025////////////////////////////////////////////////////////////////////////////////
7026
7027void TCling::LibraryUnloaded(const void* dyLibHandle, const char* canonicalName) {
7028 fPrevLoadedDynLibInfo = nullptr;
7029 fSharedLibs = "";
7030}
7031
7032////////////////////////////////////////////////////////////////////////////////
7033/// Return the list of shared libraries loaded into the process.
7034
7041
7042static std::string GetClassSharedLibsForModule(const char *cls, cling::LookupHelper &LH, bool skipCore)
7043{
7044 if (!cls || !*cls)
7045 return {};
7046
7047 using namespace clang;
7048 if (const Decl *D = LH.findScope(cls, cling::LookupHelper::NoDiagnostics,
7049 /*type*/ nullptr, /*instantiate*/ false)) {
7050 if (!D->isFromASTFile()) {
7051 if (gDebug > 5)
7052 Warning("GetClassSharedLibsForModule", "Decl found for %s is not part of a module", cls);
7053 return {};
7054 }
7055 class ModuleCollector : public ConstDeclVisitor<ModuleCollector> {
7056 llvm::DenseSet<Module *> &m_TopLevelModules;
7057
7058 public:
7059 ModuleCollector(llvm::DenseSet<Module *> &TopLevelModules) : m_TopLevelModules(TopLevelModules) {}
7060 void Collect(const Decl *D) { Visit(D); }
7061
7062 void VisitDecl(const Decl *D)
7063 {
7064 // FIXME: Such case is described ROOT-7765 where
7065 // ROOT_GENERATE_DICTIONARY does not contain the list of headers.
7066 // They are specified as #includes in the LinkDef file. This leads to
7067 // generation of incomplete modulemap files and this logic fails to
7068 // compute the corresponding module of D.
7069 // FIXME: If we want to support such a case, we should not rely on
7070 // the contents of the modulemap but mangle D and look it up in the
7071 // .so files.
7072 if (!D->hasOwningModule())
7073 return;
7074 if (Module *M = D->getOwningModule()->getTopLevelModule())
7075 m_TopLevelModules.insert(M);
7076 }
7077
7079 {
7080 switch (TA.getKind()) {
7081 case TemplateArgument::Null:
7082 case TemplateArgument::Integral:
7083 case TemplateArgument::Pack:
7084 case TemplateArgument::NullPtr:
7085 case TemplateArgument::StructuralValue:
7086 case TemplateArgument::Expression:
7087 case TemplateArgument::Template:
7088 case TemplateArgument::TemplateExpansion: return;
7089 case TemplateArgument::Type:
7090 if (const TagType *TagTy = dyn_cast<TagType>(TA.getAsType()))
7091 return Visit(TagTy->getDecl());
7092 return;
7093 case TemplateArgument::Declaration: return Visit(TA.getAsDecl());
7094 }
7095 llvm_unreachable("Invalid TemplateArgument::Kind!");
7096 }
7097
7099 {
7100 if (CTSD->getOwningModule())
7101 VisitDecl(CTSD);
7102 else
7103 VisitDecl(CTSD->getSpecializedTemplate());
7104 const TemplateArgumentList &ArgList = CTSD->getTemplateArgs();
7105 for (const TemplateArgument *Arg = ArgList.data(), *ArgEnd = Arg + ArgList.size(); Arg != ArgEnd; ++Arg) {
7107 }
7108 }
7109 };
7110
7111 llvm::DenseSet<Module *> TopLevelModules;
7113 m.Collect(D);
7114 std::string result;
7115 for (auto M : TopLevelModules) {
7116 // ROOT-unaware modules (i.e. not processed by rootcling) do not have a
7117 // link declaration.
7118 if (!M->LinkLibraries.size())
7119 continue;
7120 // We have preloaded the Core module thus libCore.so
7121 if (M->Name == "Core" && skipCore)
7122 continue;
7123 assert(M->LinkLibraries.size() == 1);
7124 if (!result.empty())
7125 result += ' ';
7126 result += M->LinkLibraries[0].Library;
7127 }
7128 return result;
7129 }
7130 return {};
7131}
7132
7133////////////////////////////////////////////////////////////////////////////////
7134/// Get the list of shared libraries containing the code for class cls.
7135/// The first library in the list is the one containing the class, the
7136/// others are the libraries the first one depends on. Returns 0
7137/// in case the library is not found.
7138/// \param cls the name of the class
7139/// \param skipCore if true (default), remove "Core" from the returned list
7140
7141const char* TCling::GetClassSharedLibs(const char* cls, bool skipCore)
7142{
7143 if (fCxxModulesEnabled) {
7144 // Lock the interpreter mutex before interacting with cling.
7145 // TODO: Can we move this further deep? In principle the lock should be in
7146 // GetClassSharedLibsForModule, but it might be needed also for
7147 // getLookupHelper?
7149 llvm::StringRef className = cls;
7150 // If we get a class name containing lambda, we cannot parse it and we
7151 // can exit early.
7152 // FIXME: This works around a bug when we are instantiating a template
7153 // make_unique and the substitution fails. Seen in most of the dataframe
7154 // tests.
7155 if (className.contains("(lambda)"))
7156 return nullptr;
7157 // Limit the recursion which can be induced by GetClassSharedLibsForModule.
7159 cling::LookupHelper &LH = fInterpreter->getLookupHelper();
7161 if (!libs.empty()) {
7162 fAutoLoadLibStorage.push_back(libs);
7163 return fAutoLoadLibStorage.back().c_str();
7164 }
7165 }
7166
7167 if (!cls || !*cls) {
7168 return nullptr;
7169 }
7170 // lookup class to find list of libraries
7171 if (fMapfile) {
7172 TEnvRec* libs_record = nullptr;
7174 if (libs_record) {
7175 const char* libs = libs_record->GetValue();
7176 return (*libs) ? libs : nullptr;
7177 }
7178 else {
7179 // Try the old format...
7180 TString c = TString("Library.") + cls;
7181 // convert "::" to "@@", we used "@@" because TEnv
7182 // considers "::" a terminator
7183 c.ReplaceAll("::", "@@");
7184 // convert "-" to " ", since class names may have
7185 // blanks and TEnv considers a blank a terminator
7186 c.ReplaceAll(" ", "-");
7187 // Use TEnv::Lookup here as the rootmap file must start with Library.
7188 // and do not support using any stars (so we do not need to waste time
7189 // with the search made by TEnv::GetValue).
7190 TEnvRec* libs_record = nullptr;
7192 if (libs_record) {
7193 const char* libs = libs_record->GetValue();
7194 return (*libs) ? libs : nullptr;
7195 }
7196 }
7197 }
7198 return nullptr;
7199}
7200
7201/// This interface returns a list of dependent libraries in the form:
7202/// lib libA.so libB.so libC.so. The first library is the library we are
7203/// searching dependencies for.
7204/// Note: In order to speed up the search, we display the dependencies of the
7205/// libraries which are not yet loaded. For instance, if libB.so was already
7206/// loaded the list would contain: lib libA.so libC.so.
7207static std::string GetSharedLibImmediateDepsSlow(std::string lib,
7208 cling::Interpreter *interp,
7209 bool skipLoadedLibs = true)
7210{
7211 TString LibFullPath(lib);
7212 if (!llvm::sys::path::is_absolute(lib)) {
7213 if (!gSystem->FindDynamicLibrary(LibFullPath, /*quiet=*/true)) {
7214 Error("TCling__GetSharedLibImmediateDepsSlow", "Cannot find library '%s'", lib.c_str());
7215 return "";
7216 }
7217 } else {
7218 assert(llvm::sys::fs::exists(lib) && "Must exist!");
7219 lib = llvm::sys::path::filename(lib).str();
7220 }
7221
7222 auto ObjF = llvm::object::ObjectFile::createObjectFile(LibFullPath.Data());
7223 if (!ObjF) {
7224 Warning("TCling__GetSharedLibImmediateDepsSlow", "Failed to read object file %s", lib.c_str());
7225 return "";
7226 }
7227
7228 llvm::object::ObjectFile *BinObjFile = ObjF.get().getBinary();
7229
7230 std::set<string> DedupSet;
7231 std::string Result = lib + ' ';
7232 for (const auto &S : BinObjFile->symbols()) {
7233 uint32_t Flags = llvm::cantFail(S.getFlags());
7234 // Skip defined symbols: we have them.
7235 if (!(Flags & llvm::object::SymbolRef::SF_Undefined))
7236 continue;
7237 // Skip undefined weak symbols: if we don't have them we won't need them.
7238 // `__gmon_start__` being a typical example.
7239 if (Flags & llvm::object::SymbolRef::SF_Weak)
7240 continue;
7241 llvm::Expected<StringRef> SymNameErr = S.getName();
7242 if (!SymNameErr) {
7243 Warning("GetSharedLibDepsForModule", "Failed to read symbol");
7244 continue;
7245 }
7246 llvm::StringRef SymName = SymNameErr.get();
7247 if (SymName.empty())
7248 continue;
7249
7250 if (BinObjFile->isELF()) {
7251 // Skip the symbols which are part of the C/C++ runtime and have a
7252 // fixed library version. See binutils ld VERSION. Those reside in
7253 // 'system' libraries, which we avoid in FindLibraryForSymbol.
7254 if (SymName.contains("@GLIBCXX") || SymName.contains("@CXXABI") ||
7255 SymName.contains("@GLIBC") || SymName.contains("@GCC"))
7256 continue;
7257
7258 // Those are 'weak undefined' symbols produced by gcc. We can
7259 // ignore them.
7260 // FIXME: It is unclear whether we can ignore all weak undefined
7261 // symbols:
7262 // http://lists.llvm.org/pipermail/llvm-dev/2017-October/118177.html
7263 static constexpr llvm::StringRef RegisterClasses("_Jv_RegisterClasses");
7264 static constexpr llvm::StringRef RegisterCloneTable("_ITM_registerTMCloneTable");
7265 static constexpr llvm::StringRef DeregisterCloneTable("_ITM_deregisterTMCloneTable");
7266 if (SymName == RegisterClasses ||
7269 continue;
7270 }
7271
7272 // If we can find the address of the symbol, we have loaded it. Skip.
7273 if (skipLoadedLibs) {
7275 if (llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(SymNameForDlsym))
7276 continue;
7277 }
7278
7280 std::string found = interp->getDynamicLibraryManager()->searchLibrariesForSymbol(SymName, /*searchSystem*/false);
7281 // The expected output is just filename without the full path, which
7282 // is not very accurate, because our Dyld implementation might find
7283 // a match in location a/b/c.so and if we return just c.so ROOT might
7284 // resolve it to y/z/c.so and there we might not be ABI compatible.
7285 // FIXME: Teach the users of GetSharedLibDeps to work with full paths.
7286 if (!found.empty()) {
7287 std::string cand = llvm::sys::path::filename(found).str();
7288 if (!DedupSet.insert(cand).second)
7289 continue;
7290
7291 Result += cand + ' ';
7292 }
7293 }
7294
7295 return Result;
7296}
7297
7298static bool hasParsedRootmapForLibrary(llvm::StringRef lib)
7299{
7300 // Check if we have parsed a rootmap file.
7301 llvm::SmallString<256> rootmapName;
7302 if (!lib.starts_with("lib"))
7303 rootmapName.append("lib");
7304
7305 rootmapName.append(llvm::sys::path::filename(lib));
7306 llvm::sys::path::replace_extension(rootmapName, "rootmap");
7307
7308 if (gCling->GetRootMapFiles()->FindObject(rootmapName.c_str()))
7309 return true;
7310
7311 // Perform a last resort by dropping the lib prefix.
7312 llvm::StringRef rootmapNameNoLib = rootmapName.str();
7313 if (rootmapNameNoLib.consume_front("lib"))
7314 return gCling->GetRootMapFiles()->FindObject(rootmapNameNoLib.data());
7315
7316 return false;
7317}
7318
7319static bool hasPrecomputedLibraryDeps(llvm::StringRef lib)
7320{
7321 if (gCling->HasPCMForLibrary(lib.data()))
7322 return true;
7323
7324 return hasParsedRootmapForLibrary(lib);
7325}
7326
7327////////////////////////////////////////////////////////////////////////////////
7328/// Get the list a libraries on which the specified lib depends. The
7329/// returned string contains as first element the lib itself.
7330/// Returns 0 in case the lib does not exist or does not have
7331/// any dependencies. If useDyld is true, we iterate through all available
7332/// libraries and try to construct the dependency chain by resolving each
7333/// symbol.
7334
7335const char* TCling::GetSharedLibDeps(const char* lib, bool useDyld/* = false*/)
7336{
7337 if (llvm::sys::path::is_absolute(lib) && !llvm::sys::fs::exists(lib))
7338 return nullptr;
7339
7340 if (!hasParsedRootmapForLibrary(lib)) {
7341 llvm::SmallString<512> rootmapName(lib);
7342 llvm::sys::path::replace_extension(rootmapName, "rootmap");
7343 if (llvm::sys::fs::exists(rootmapName)) {
7344 if (gDebug > 0)
7345 Info("Load", "loading %s", rootmapName.c_str());
7346 gInterpreter->LoadLibraryMap(rootmapName.c_str());
7347 }
7348 }
7349
7350 if (hasPrecomputedLibraryDeps(lib) && useDyld) {
7351 if (gDebug > 0)
7352 Warning("TCling::GetSharedLibDeps", "Precomputed dependencies available but scanning '%s'", lib);
7353 }
7354
7355 if (useDyld) {
7357 if (!libs.empty()) {
7358 fAutoLoadLibStorage.push_back(libs);
7359 return fAutoLoadLibStorage.back().c_str();
7360 }
7361 }
7362
7363 if (!fMapfile || !lib || !lib[0]) {
7364 return nullptr;
7365 }
7366 TString libname(lib);
7367 Ssiz_t idx = libname.Last('.');
7368 if (idx != kNPOS) {
7369 libname.Remove(idx);
7370 }
7371 TEnvRec* rec;
7372 TIter next(fMapfile->GetTable());
7373 size_t len = libname.Length();
7374 while ((rec = (TEnvRec*) next())) {
7375 const char* libs = rec->GetValue();
7376 if (!strncmp(libs, libname.Data(), len) && strlen(libs) >= len
7377 && (!libs[len] || libs[len] == ' ' || libs[len] == '.')) {
7378 return libs;
7379 }
7380 }
7381 return nullptr;
7382}
7383
7384////////////////////////////////////////////////////////////////////////////////
7385/// If error messages are disabled, the interpreter should suppress its
7386/// failures and warning messages from stdout.
7387
7389{
7390#if defined(R__MUST_REVISIT)
7391#if R__MUST_REVISIT(6,2)
7392 Warning("IsErrorMessagesEnabled", "Interface not available yet.");
7393#endif
7394#endif
7395 return kTRUE;
7396}
7397
7398////////////////////////////////////////////////////////////////////////////////
7399/// If error messages are disabled, the interpreter should suppress its
7400/// failures and warning messages from stdout. Return the previous state.
7401
7403{
7404#if defined(R__MUST_REVISIT)
7405#if R__MUST_REVISIT(6,2)
7406 Warning("SetErrorMessages", "Interface not available yet.");
7407#endif
7408#endif
7410}
7411
7412////////////////////////////////////////////////////////////////////////////////
7413/// Refresh the list of include paths known to the interpreter and return it
7414/// with -I prepended.
7415
7417{
7419
7420 fIncludePath = "";
7421
7422 llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7423 //false - no system header, true - with flags.
7424 fInterpreter->GetIncludePaths(includePaths, false, true);
7425 if (const size_t nPaths = includePaths.size()) {
7426 assert(!(nPaths & 1) && "GetIncludePath, number of paths and options is not equal");
7427
7428 for (size_t i = 0; i < nPaths; i += 2) {
7429 if (i)
7430 fIncludePath.Append(' ');
7431 fIncludePath.Append(includePaths[i].c_str());
7432
7433 if (includePaths[i] != "-I")
7434 fIncludePath.Append(' ');
7435 fIncludePath.Append('"');
7437 fIncludePath.Append('"');
7438 }
7439 }
7440
7441 return fIncludePath;
7442}
7443
7444////////////////////////////////////////////////////////////////////////////////
7445/// Return the directory containing CINT's stl cintdlls.
7446
7447const char* TCling::GetSTLIncludePath() const
7448{
7449 return "";
7450}
7451
7452//______________________________________________________________________________
7453// M I S C
7454//______________________________________________________________________________
7455
7456int TCling::DisplayClass(FILE* /*fout*/, const char* /*name*/, int /*base*/, int /*start*/) const
7457{
7458 // Interface to cling function
7459 return 0;
7460}
7461
7462////////////////////////////////////////////////////////////////////////////////
7463/// Interface to cling function
7464
7466{
7467 assert(fout != nullptr && "DisplayIncludePath, 'fout' parameter is null");
7468
7469 llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7470 //false - no system header, true - with flags.
7471 fInterpreter->GetIncludePaths(includePaths, false, true);
7472 if (const size_t nPaths = includePaths.size()) {
7473 assert(!(nPaths & 1) && "DisplayIncludePath, number of paths and options is not equal");
7474
7475 std::string allIncludes("include path:");
7476 for (size_t i = 0; i < nPaths; i += 2) {
7477 allIncludes += ' ';
7479
7480 if (includePaths[i] != "-I")
7481 allIncludes += ' ';
7482 allIncludes += includePaths[i + 1];
7483 }
7484
7485 fprintf(fout, "%s\n", allIncludes.c_str());
7486 }
7487
7488 return 0;
7489}
7490
7491////////////////////////////////////////////////////////////////////////////////
7492/// Interface to cling function
7493
7494void* TCling::FindSym(const char* entry) const
7495{
7497 return fInterpreter->getAddressOfGlobal(entry);
7498}
7499
7500////////////////////////////////////////////////////////////////////////////////
7501/// Let the interpreter issue a generic error, and set its error state.
7502
7503void TCling::GenericError(const char* error) const
7504{
7505#if defined(R__MUST_REVISIT)
7506#if R__MUST_REVISIT(6,2)
7507 Warning("GenericError","Interface not available yet.");
7508#endif
7509#endif
7510}
7511
7512////////////////////////////////////////////////////////////////////////////////
7513/// This routines used to return the address of the internal wrapper
7514/// function (of the interpreter) that was used to call *all* the
7515/// interpreted functions that were bytecode compiled (no longer
7516/// interpreted line by line). In Cling, there is no such
7517/// wrapper function.
7518/// In practice this routines was use to decipher whether the
7519/// pointer returns by InterfaceMethod could be used to uniquely
7520/// represent the function. In Cling if the function is in a
7521/// useable state (its compiled version is available), this is
7522/// always the case.
7523/// See TClass::GetMethod.
7524
7526{
7527 return 0;
7528}
7529
7530////////////////////////////////////////////////////////////////////////////////
7531/// Interface to cling function
7532
7534{
7535#if defined(R__MUST_REVISIT)
7536#if R__MUST_REVISIT(6,2)
7537 Warning("GetSecurityError", "Interface not available yet.");
7538#endif
7539#endif
7540 return 0;
7541}
7542
7543////////////////////////////////////////////////////////////////////////////////
7544/// Load a source file or library called path into the interpreter.
7545
7546int TCling::LoadFile(const char* path) const
7547{
7548 // Modifying the interpreter state needs locking.
7550 cling::Interpreter::CompilationResult compRes;
7551 HandleInterpreterException(GetMetaProcessorImpl(), TString::Format(".L %s", path), compRes, /*cling::Value*/nullptr);
7552 return compRes == cling::Interpreter::kFailure;
7553}
7554
7555////////////////////////////////////////////////////////////////////////////////
7556/// Load the declarations from text into the interpreter.
7557/// Note that this cannot be (top level) statements; text must contain
7558/// top level declarations.
7559/// Returns true on success, false on failure.
7560
7561Bool_t TCling::LoadText(const char* text) const
7562{
7563 return (fInterpreter->declare(text) == cling::Interpreter::kSuccess);
7564}
7565
7566////////////////////////////////////////////////////////////////////////////////
7567/// Interface to cling function
7568
7569const char* TCling::MapCppName(const char* name) const
7570{
7571 TTHREAD_TLS_DECL(std::string,buffer);
7573 return buffer.c_str(); // NOLINT
7574}
7575
7576////////////////////////////////////////////////////////////////////////////////
7577/// [Place holder for Mutex Lock]
7578/// Provide the interpreter with a way to
7579/// acquire a lock used to protect critical section
7580/// of its code (non-thread safe parts).
7581
7582void TCling::SetAlloclockfunc(void (* /* p */ )()) const
7583{
7584 // nothing to do for now.
7585}
7586
7587////////////////////////////////////////////////////////////////////////////////
7588/// [Place holder for Mutex Unlock] Provide the interpreter with a way to
7589/// release a lock used to protect critical section
7590/// of its code (non-thread safe parts).
7591
7592void TCling::SetAllocunlockfunc(void (* /* p */ )()) const
7593{
7594 // nothing to do for now.
7595}
7596
7597////////////////////////////////////////////////////////////////////////////////
7598/// Returns if class AutoLoading is currently enabled.
7599
7601{
7602 if (IsFromRootCling())
7603 return false;
7604 if (!fClingCallbacks)
7605 return false;
7607}
7608
7609////////////////////////////////////////////////////////////////////////////////
7610/// Enable/Disable the AutoLoading of libraries.
7611/// Returns the old value, i.e whether it was enabled or not.
7612
7614{
7615 // If no state change is required, exit early.
7616 // FIXME: In future we probably want to complain if we made a request which
7617 // was with the same state as before in order to catch programming errors.
7618 if ((bool) autoload == IsClassAutoLoadingEnabled())
7619 return autoload;
7620
7621 assert(fClingCallbacks && "We must have callbacks!");
7624 return oldVal;
7625}
7626
7627////////////////////////////////////////////////////////////////////////////////
7628/// Enable/Disable the Autoparsing of headers.
7629/// Returns the old value, i.e whether it was enabled or not.
7630
7637
7638////////////////////////////////////////////////////////////////////////////////
7639/// Suspend the Autoparsing of headers.
7640/// Returns the old value, i.e whether it was suspended or not.
7641
7648
7649////////////////////////////////////////////////////////////////////////////////
7650/// Set a callback to receive error messages.
7651
7653{
7654#if defined(R__MUST_REVISIT)
7655#if R__MUST_REVISIT(6,2)
7656 Warning("SetErrmsgcallback", "Interface not available yet.");
7657#endif
7658#endif
7659}
7660
7662{
7663 if (enable) {
7665 &fInterpreter->getDiagnostics().getDiagnosticOptions(),
7666 fInterpreter->getCI()->getLangOpts(),
7667 [] (clang::DiagnosticsEngine::Level Level, const std::string &Info) {
7668 if (Level == clang::DiagnosticsEngine::Warning) {
7669 ::Warning("cling", "%s", Info.c_str());
7670 } else if (Level == clang::DiagnosticsEngine::Error
7671 || Level == clang::DiagnosticsEngine::Fatal) {
7672 ::Error("cling", "%s", Info.c_str());
7673 } else {
7674 ::Info("cling", "%s", Info.c_str());
7675 }
7676 });
7677 fInterpreter->replaceDiagnosticConsumer(consumer, /*Own=*/true);
7678 } else {
7679 fInterpreter->replaceDiagnosticConsumer(nullptr);
7680 }
7681}
7682
7683
7684////////////////////////////////////////////////////////////////////////////////
7685/// Create / close a scope for temporaries. No-op for cling; use
7686/// cling::Value instead.
7687
7688void TCling::SetTempLevel(int val) const
7689{
7690}
7691
7692////////////////////////////////////////////////////////////////////////////////
7693
7694int TCling::UnloadFile(const char* path) const
7695{
7696 // Modifying the interpreter state needs locking.
7698 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
7699 std::string canonical = DLM->lookupLibrary(path);
7700 if (canonical.empty()) {
7701 canonical = path;
7702 }
7703 // Unload a shared library or a source file.
7704 cling::Interpreter::CompilationResult compRes;
7705 HandleInterpreterException(GetMetaProcessorImpl(), Form(".U %s", canonical.c_str()), compRes, /*cling::Value*/nullptr);
7706 return compRes == cling::Interpreter::kFailure;
7707}
7708
7709std::unique_ptr<TInterpreterValue> TCling::MakeInterpreterValue() const {
7710 return std::unique_ptr<TInterpreterValue>(new TClingValue);
7711}
7712
7713////////////////////////////////////////////////////////////////////////////////
7714/// The call to Cling's tab complition.
7715
7716void TCling::CodeComplete(const std::string& line, size_t& cursor,
7717 std::vector<std::string>& completions)
7718{
7719 fInterpreter->codeComplete(line, cursor, completions);
7720}
7721
7722////////////////////////////////////////////////////////////////////////////////
7723/// Get the interpreter value corresponding to the statement.
7725{
7727
7728 auto V = reinterpret_cast<cling::Value*>(value.GetValAddr());
7729 auto compRes = fInterpreter->evaluate(code, *V);
7730 return compRes!=cling::Interpreter::kSuccess ? 0 : 1 ;
7731}
7732
7733////////////////////////////////////////////////////////////////////////////////
7734
7736{
7737 using namespace cling;
7738 const Value* V = reinterpret_cast<const Value*>(value.GetValAddr());
7740}
7741
7742////////////////////////////////////////////////////////////////////////////////
7743/// Register value as a temporary, extending its lifetime to that of the
7744/// interpreter. This is needed for TCling's compatibility interfaces
7745/// returning long - the address of the temporary objects.
7746/// As such, "simple" types don't need to be stored; they are returned by
7747/// value; only pointers / references / objects need to be stored.
7748
7749void TCling::RegisterTemporary(const cling::Value& value)
7750{
7751 if (value.isValid() && value.needsManagedAllocation()) {
7753 fTemporaries->push_back(value);
7754 }
7755}
7756
7757////////////////////////////////////////////////////////////////////////////////
7758/// If the interpreter encounters Name, check whether that is an object ROOT
7759/// could retrieve. To not re-read objects from disk, cache the name/object
7760/// pair for a given LookupCtx.
7761
7763{
7764 // The call to FindSpecialObject might induces any kind of use
7765 // of the interpreter ... (library loading, function calling, etc.)
7766 // ... and we _know_ we are in the middle of parsing, so let's make
7767 // sure to save the state and then restore it.
7768
7769 if (gDirectory) {
7771 if (iSpecObjMap != fSpecialObjectMaps.end()) {
7772 auto iSpecObj = iSpecObjMap->second.find(Name);
7773 if (iSpecObj != iSpecObjMap->second.end()) {
7775 return iSpecObj->second;
7776 }
7777 }
7778 }
7779
7780 // Save state of the PP
7781 Sema &SemaR = fInterpreter->getSema();
7782 ASTContext& C = SemaR.getASTContext();
7783 Preprocessor &PP = SemaR.getPreprocessor();
7784 Parser& P = const_cast<Parser&>(fInterpreter->getParser());
7785 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
7786 Parser::ParserCurTokRestoreRAII savedCurToken(P);
7787 // After we have saved the token reset the current one to something which
7788 // is safe (semi colon usually means empty decl)
7789 Token& Tok = const_cast<Token&>(P.getCurToken());
7790 Tok.setKind(tok::semi);
7791
7792 // We can't PushDeclContext, because we go up and the routine that pops
7793 // the DeclContext assumes that we drill down always.
7794 // We have to be on the global context. At that point we are in a
7795 // wrapper function so the parent context must be the global.
7796 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(),
7797 SemaR.TUScope);
7798
7799 TObject* specObj = gROOT->FindSpecialObject(Name, LookupCtx);
7800 if (specObj) {
7801 if (!LookupCtx) {
7802 Error("GetObjectAddress", "Got a special object without LookupCtx!");
7803 } else {
7805 }
7806 }
7807 return specObj;
7808}
7809
7810////////////////////////////////////////////////////////////////////////////////
7811/// Inject function as a friend into klass.
7812/// With function being f in void f() {new N::PrivKlass(); } this enables
7813/// I/O of non-public classes.
7814
7815void TCling::AddFriendToClass(clang::FunctionDecl* function,
7816 clang::CXXRecordDecl* klass) const
7817{
7818 using namespace clang;
7819 ASTContext& Ctx = klass->getASTContext();
7820 FriendDecl::FriendUnion friendUnion(function);
7821 // one dummy object for the source location
7823 FriendDecl* friendDecl = FriendDecl::Create(Ctx, klass, sl, friendUnion, sl);
7824 klass->pushFriendDecl(friendDecl);
7825}
7826
7827//______________________________________________________________________________
7828//
7829// DeclId getter.
7830//
7831
7832////////////////////////////////////////////////////////////////////////////////
7833/// Return a unique identifier of the declaration represented by the
7834/// CallFunc
7835
7837{
7838 if (func) return ((TClingCallFunc*)func)->GetDecl()->getCanonicalDecl();
7839 return nullptr;
7840}
7841
7842////////////////////////////////////////////////////////////////////////////////
7843/// Return a (almost) unique identifier of the declaration represented by the
7844/// ClassInfo. In ROOT, this identifier can point to more than one TClass
7845/// when the underlying class is a template instance involving one of the
7846/// opaque typedef.
7847
7849{
7850 if (cinfo) return ((TClingClassInfo*)cinfo)->GetDeclId();
7851 return nullptr;
7852}
7853
7854////////////////////////////////////////////////////////////////////////////////
7855/// Return a unique identifier of the declaration represented by the
7856/// MethodInfo
7857
7859{
7860 if (data) return ((TClingDataMemberInfo*)data)->GetDeclId();
7861 return nullptr;
7862}
7863
7864////////////////////////////////////////////////////////////////////////////////
7865/// Return a unique identifier of the declaration represented by the
7866/// MethodInfo
7867
7869{
7870 if (method) return ((TClingMethodInfo*)method)->GetDeclId();
7871 return nullptr;
7872}
7873
7874////////////////////////////////////////////////////////////////////////////////
7875/// Return a unique identifier of the declaration represented by the
7876/// TypedefInfo
7877
7879{
7880 if (tinfo) return ((TClingTypedefInfo*)tinfo)->GetDecl()->getCanonicalDecl();
7881 return nullptr;
7882}
7883
7884//______________________________________________________________________________
7885//
7886// CallFunc interface
7887//
7888
7889////////////////////////////////////////////////////////////////////////////////
7890
7892{
7893 delete (TClingCallFunc*) func;
7894}
7895
7896////////////////////////////////////////////////////////////////////////////////
7897
7898void TCling::CallFunc_Exec(CallFunc_t* func, void* address) const
7899{
7900 TClingCallFunc* f = (TClingCallFunc*) func;
7901 f->Exec(address);
7902}
7903
7904////////////////////////////////////////////////////////////////////////////////
7905
7906void TCling::CallFunc_Exec(CallFunc_t* func, void* address, TInterpreterValue& val) const
7907{
7908 TClingCallFunc* f = (TClingCallFunc*) func;
7909 f->Exec(address, &val);
7910}
7911
7912////////////////////////////////////////////////////////////////////////////////
7913
7914void TCling::CallFunc_ExecWithReturn(CallFunc_t* func, void* address, void* ret) const
7915{
7916 TClingCallFunc* f = (TClingCallFunc*) func;
7917 f->ExecWithReturn(address, ret);
7918}
7919
7920////////////////////////////////////////////////////////////////////////////////
7921
7923 const void* args[] /*=0*/,
7924 int nargs /*=0*/,
7925 void* ret/*=0*/) const
7926{
7927 TClingCallFunc* f = (TClingCallFunc*) func;
7928 f->ExecWithArgsAndReturn(address, args, nargs, ret);
7929}
7930
7931////////////////////////////////////////////////////////////////////////////////
7932
7934{
7935 TClingCallFunc* f = (TClingCallFunc*) func;
7936 return f->ExecInt(address);
7937}
7938
7939////////////////////////////////////////////////////////////////////////////////
7940
7942{
7943 TClingCallFunc* f = (TClingCallFunc*) func;
7944 return f->ExecInt64(address);
7945}
7946
7947////////////////////////////////////////////////////////////////////////////////
7948
7950{
7951 TClingCallFunc* f = (TClingCallFunc*) func;
7952 return f->ExecDouble(address);
7953}
7954
7955////////////////////////////////////////////////////////////////////////////////
7956
7962
7963////////////////////////////////////////////////////////////////////////////////
7964
7966{
7967 return (CallFunc_t*) new TClingCallFunc(*(TClingCallFunc*)func);
7968}
7969
7970////////////////////////////////////////////////////////////////////////////////
7971
7973{
7974 TClingCallFunc* f = (TClingCallFunc*) func;
7975 return (MethodInfo_t*) f->FactoryMethod();
7976}
7977
7978////////////////////////////////////////////////////////////////////////////////
7979
7981{
7982 TClingCallFunc* f = (TClingCallFunc*) func;
7983 f->IgnoreExtraArgs(ignore);
7984}
7985
7986////////////////////////////////////////////////////////////////////////////////
7987
7989{
7991 TClingCallFunc* f = (TClingCallFunc*) func;
7992 f->Init();
7993}
7994
7995////////////////////////////////////////////////////////////////////////////////
7996
7998{
7999 TClingCallFunc* f = (TClingCallFunc*) func;
8000 return f->IsValid();
8001}
8002
8003////////////////////////////////////////////////////////////////////////////////
8004
8007{
8008 TClingCallFunc* f = (TClingCallFunc*) func;
8009 return f->IFacePtr();
8010}
8011
8012////////////////////////////////////////////////////////////////////////////////
8013
8015{
8016 TClingCallFunc* f = (TClingCallFunc*) func;
8017 f->ResetArg();
8018}
8019
8020////////////////////////////////////////////////////////////////////////////////
8021
8023{
8024 TClingCallFunc* f = (TClingCallFunc*) func;
8025 f->SetArg(param);
8026}
8027
8028////////////////////////////////////////////////////////////////////////////////
8029
8031{
8032 TClingCallFunc* f = (TClingCallFunc*) func;
8033 f->SetArg(param);
8034}
8035
8036////////////////////////////////////////////////////////////////////////////////
8037
8039{
8040 TClingCallFunc* f = (TClingCallFunc*) func;
8041 f->SetArg(param);
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->SetArgArray(paramArr, nparam);
8074}
8075
8076////////////////////////////////////////////////////////////////////////////////
8077
8078void TCling::CallFunc_SetArgs(CallFunc_t* func, const char* param) const
8079{
8080 TClingCallFunc* f = (TClingCallFunc*) func;
8081 f->SetArgs(param);
8082}
8083
8084////////////////////////////////////////////////////////////////////////////////
8085
8086void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, Longptr_t* offset) const
8087{
8088 TClingCallFunc* f = (TClingCallFunc*) func;
8090 f->SetFunc(ci, method, params, offset);
8091}
8092
8093////////////////////////////////////////////////////////////////////////////////
8094
8095void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, bool objectIsConst, Longptr_t* offset) const
8096{
8097 TClingCallFunc* f = (TClingCallFunc*) func;
8099 f->SetFunc(ci, method, params, objectIsConst, offset);
8100}
8101////////////////////////////////////////////////////////////////////////////////
8102
8103void TCling::CallFunc_SetFunc(CallFunc_t* func, MethodInfo_t* info) const
8104{
8105 TClingCallFunc* f = (TClingCallFunc*) func;
8107 f->SetFunc(minfo);
8108}
8109
8110////////////////////////////////////////////////////////////////////////////////
8111/// Interface to cling function
8112
8113void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8114{
8115 TClingCallFunc* f = (TClingCallFunc*) func;
8117 f->SetFuncProto(ci, method, proto, offset, mode);
8118}
8119
8120////////////////////////////////////////////////////////////////////////////////
8121/// Interface to cling function
8122
8123void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, bool objectIsConst, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8124{
8125 TClingCallFunc* f = (TClingCallFunc*) func;
8127 f->SetFuncProto(ci, method, proto, objectIsConst, offset, mode);
8128}
8129
8130////////////////////////////////////////////////////////////////////////////////
8131/// Interface to cling function
8132
8133void 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
8134{
8135 TClingCallFunc* f = (TClingCallFunc*) func;
8137 llvm::SmallVector<clang::QualType, 4> funcProto;
8138 for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
8139 iter != end; ++iter) {
8140 funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
8141 }
8142 f->SetFuncProto(ci, method, funcProto, offset, mode);
8143}
8144
8145////////////////////////////////////////////////////////////////////////////////
8146/// Interface to cling function
8147
8148void 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
8149{
8150 TClingCallFunc* f = (TClingCallFunc*) func;
8152 llvm::SmallVector<clang::QualType, 4> funcProto;
8153 for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
8154 iter != end; ++iter) {
8155 funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
8156 }
8157 f->SetFuncProto(ci, method, funcProto, objectIsConst, offset, mode);
8158}
8159
8161{
8162 TClingCallFunc *f = (TClingCallFunc *)func;
8163 std::string wrapper_name;
8164 std::string wrapper;
8165 f->get_wrapper_code(wrapper_name, wrapper);
8166 return wrapper;
8167}
8168
8169//______________________________________________________________________________
8170//
8171// ClassInfo interface
8172//
8173
8174////////////////////////////////////////////////////////////////////////////////
8175/// Return true if the entity pointed to by 'declid' is declared in
8176/// the context described by 'info'. If info is null, look into the
8177/// global scope (translation unit scope).
8178
8180{
8181 if (!declid)
8182 return kFALSE;
8183
8184 const clang::DeclContext *ctxt = nullptr;
8185 if (info) {
8186 ctxt = clang::Decl::castToDeclContext(((TClingClassInfo*)info)->GetDecl());
8187 } else {
8188 ctxt = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
8189 }
8190 if (!ctxt)
8191 return kFALSE;
8192
8193 const clang::Decl *decl = reinterpret_cast<const clang::Decl*>(declid);
8194 if (!decl)
8195 return kFALSE;
8196
8197 const clang::DeclContext *declDC = decl->getDeclContext();
8198 // ClassInfo_t-s are always "spellable" scopes, never unnamed or inline ones.
8199 while (true) {
8200 if (declDC->isTransparentContext()) {
8201 declDC = declDC->getParent();
8202 continue;
8203 }
8204 if (const auto *declRD = llvm::dyn_cast<clang::RecordDecl>(declDC)) {
8205 if (declRD->isAnonymousStructOrUnion()) {
8206 declDC = declRD->getParent();
8207 continue;
8208 }
8209 }
8210 if (const auto *declNS = llvm::dyn_cast<clang::NamespaceDecl>(declDC)) {
8211 if (declNS->isAnonymousNamespace() || declNS->isInlineNamespace()) {
8212 declDC = declNS->getParent();
8213 continue;
8214 }
8215 }
8216 break;
8217 }
8218
8219 return declDC->Equals(ctxt);
8220}
8221
8222////////////////////////////////////////////////////////////////////////////////
8223
8229
8230////////////////////////////////////////////////////////////////////////////////
8231
8233{
8234 delete (TClingClassInfo*) cinfo;
8235}
8236
8237////////////////////////////////////////////////////////////////////////////////
8238
8244
8245////////////////////////////////////////////////////////////////////////////////
8246
8252
8253////////////////////////////////////////////////////////////////////////////////
8254
8260
8261////////////////////////////////////////////////////////////////////////////////
8262
8268
8269////////////////////////////////////////////////////////////////////////////////
8270
8275
8276////////////////////////////////////////////////////////////////////////////////
8277
8283
8289
8290
8291////////////////////////////////////////////////////////////////////////////////
8292
8293int TCling::ClassInfo_GetMethodNArg(ClassInfo_t* cinfo, const char* method, const char* proto, Bool_t objectIsConst /* = false */, EFunctionMatchMode mode /* = kConversionMatch */) const
8294{
8296 return TClinginfo->GetMethodNArg(method, proto, objectIsConst, mode);
8297}
8298
8299////////////////////////////////////////////////////////////////////////////////
8300
8306
8307////////////////////////////////////////////////////////////////////////////////
8308
8310{
8312 return TClinginfo->HasMethod(name);
8313}
8314
8315////////////////////////////////////////////////////////////////////////////////
8316
8323
8324////////////////////////////////////////////////////////////////////////////////
8325
8327{
8330 TClinginfo->Init(tagnum);
8331}
8332
8333////////////////////////////////////////////////////////////////////////////////
8334
8336{
8338 return TClinginfo->IsBase(name);
8339}
8340
8341////////////////////////////////////////////////////////////////////////////////
8342
8343bool TCling::ClassInfo_IsEnum(const char* name) const
8344{
8346}
8347
8348////////////////////////////////////////////////////////////////////////////////
8349
8355
8356
8357////////////////////////////////////////////////////////////////////////////////
8358
8364
8365
8366////////////////////////////////////////////////////////////////////////////////
8367
8369{
8371 return TClinginfo->IsLoaded();
8372}
8373
8374////////////////////////////////////////////////////////////////////////////////
8375
8377{
8379 return TClinginfo->IsValid();
8380}
8381
8382////////////////////////////////////////////////////////////////////////////////
8383
8384bool TCling::ClassInfo_IsValidMethod(ClassInfo_t* cinfo, const char* method, const char* proto, Longptr_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8385{
8387 return TClinginfo->IsValidMethod(method, proto, false, offset, mode);
8388}
8389
8390////////////////////////////////////////////////////////////////////////////////
8391
8393{
8395 return TClinginfo->IsValidMethod(method, proto, objectIsConst, offset, mode);
8396}
8397
8398////////////////////////////////////////////////////////////////////////////////
8399
8405
8406////////////////////////////////////////////////////////////////////////////////
8407
8413
8414////////////////////////////////////////////////////////////////////////////////
8415
8421
8422////////////////////////////////////////////////////////////////////////////////
8423
8425{
8427 return TClinginfo->New(n, arena,*fNormalizedCtxt);
8428}
8429
8430////////////////////////////////////////////////////////////////////////////////
8431
8437
8438////////////////////////////////////////////////////////////////////////////////
8439
8445
8446////////////////////////////////////////////////////////////////////////////////
8447
8453
8454////////////////////////////////////////////////////////////////////////////////
8455
8461
8462////////////////////////////////////////////////////////////////////////////////
8463
8465{
8467 return TClinginfo->FileName();
8468}
8469
8470////////////////////////////////////////////////////////////////////////////////
8471
8473{
8475 TTHREAD_TLS_DECL(std::string,output);
8476 TClinginfo->FullName(output,*fNormalizedCtxt);
8477 return output.c_str(); // NOLINT
8478}
8479
8480////////////////////////////////////////////////////////////////////////////////
8481
8483{
8485 return TClinginfo->Name();
8486}
8487
8488////////////////////////////////////////////////////////////////////////////////
8489
8491{
8493 return TClinginfo->Title();
8494}
8495
8496////////////////////////////////////////////////////////////////////////////////
8497
8499{
8501 return TClinginfo->TmpltName();
8502}
8503
8504
8505
8506//______________________________________________________________________________
8507//
8508// BaseClassInfo interface
8509//
8510
8511////////////////////////////////////////////////////////////////////////////////
8512
8517
8518////////////////////////////////////////////////////////////////////////////////
8519
8526
8527////////////////////////////////////////////////////////////////////////////////
8528
8537
8538////////////////////////////////////////////////////////////////////////////////
8539
8545
8546////////////////////////////////////////////////////////////////////////////////
8547
8553
8554////////////////////////////////////////////////////////////////////////////////
8555
8561
8562////////////////////////////////////////////////////////////////////////////////
8563
8565{
8568 // Offset to the class itself.
8569 if (TClinginfo->GetDecl() == TClinginfoBase->GetDecl()) {
8570 return 0;
8571 }
8572 return TClinginfo->GetBaseOffset(TClinginfoBase, address, isDerivedObject);
8573}
8574
8575////////////////////////////////////////////////////////////////////////////////
8576
8582
8583////////////////////////////////////////////////////////////////////////////////
8584
8590
8591////////////////////////////////////////////////////////////////////////////////
8592
8598
8599////////////////////////////////////////////////////////////////////////////////
8600
8602{
8604 TTHREAD_TLS_DECL(std::string,output);
8605 TClinginfo->FullName(output,*fNormalizedCtxt);
8606 return output.c_str(); // NOLINT
8607}
8608
8609////////////////////////////////////////////////////////////////////////////////
8610
8616
8617////////////////////////////////////////////////////////////////////////////////
8618
8624
8625//______________________________________________________________________________
8626//
8627// DataMemberInfo interface
8628//
8629
8630////////////////////////////////////////////////////////////////////////////////
8631
8637
8638////////////////////////////////////////////////////////////////////////////////
8639
8644
8645////////////////////////////////////////////////////////////////////////////////
8646
8653
8654////////////////////////////////////////////////////////////////////////////////
8655
8657{
8659 const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
8660 const clang::ValueDecl* vd = llvm::dyn_cast_or_null<clang::ValueDecl>(decl);
8662}
8663
8664////////////////////////////////////////////////////////////////////////////////
8665
8671
8672////////////////////////////////////////////////////////////////////////////////
8673
8679
8680////////////////////////////////////////////////////////////////////////////////
8681
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
8763{
8764 TTHREAD_TLS_DECL(std::string,result);
8765
8767 result = TClinginfo->ValidArrayIndex().str();
8768 return result.c_str(); // NOLINT
8769}
8770
8771////////////////////////////////////////////////////////////////////////////////
8772
8774{
8775 Decl* decl = static_cast<Decl*>(const_cast<void*>(declId));
8776 ASTContext &C = decl->getASTContext();
8777 decl->addAttr(AnnotateAttr::CreateImplicit(C, attribute, nullptr, 0));
8778}
8779
8780//______________________________________________________________________________
8781//
8782// Function Template interface
8783//
8784
8785////////////////////////////////////////////////////////////////////////////////
8786
8787static void ConstructorName(std::string &name, const clang::Decl *decl,
8788 cling::Interpreter &interp,
8790{
8791 const clang::TypeDecl* td = llvm::dyn_cast<clang::TypeDecl>(decl->getDeclContext());
8792 if (!td) return;
8793
8794 clang::QualType qualType(td->getTypeForDecl(),0);
8796 unsigned int level = 0;
8797 for(size_t cursor = name.length()-1; cursor != 0; --cursor) {
8798 if (name[cursor] == '>') ++level;
8799 else if (name[cursor] == '<' && level) --level;
8800 else if (level == 0 && name[cursor] == ':') {
8801 name.erase(0,cursor+1);
8802 break;
8803 }
8804 }
8805}
8806
8807////////////////////////////////////////////////////////////////////////////////
8808
8809void TCling::GetFunctionName(const clang::Decl *decl, std::string &output) const
8810{
8811 output.clear();
8812
8813 const auto *FD = llvm::dyn_cast<clang::FunctionDecl>(decl);
8814 if (const auto *USD = llvm::dyn_cast<clang::UsingShadowDecl>(decl)) {
8815 FD = llvm::dyn_cast<clang::FunctionDecl>(USD->getTargetDecl());
8816 }
8817 if (!FD) {
8818 Error("GetFunctionName", "NULL Decl!");
8819 return;
8820 }
8821
8822 // For using-decls, show "Derived", not "Base", i.e. use the
8823 // name of the decl context of the UsingShadowDecl (aka `decl`)
8824 // not the name of FD's decl context.
8825 if (llvm::isa<clang::CXXConstructorDecl>(FD))
8826 {
8828
8829 } else if (llvm::isa<clang::CXXDestructorDecl>(decl))
8830 {
8832 output.insert(output.begin(), '~');
8833 } else {
8834 llvm::raw_string_ostream stream(output);
8835 auto printPolicy = decl->getASTContext().getPrintingPolicy();
8836 // Don't trigger fopen of the source file to count lines:
8837 printPolicy.AnonymousTagLocations = false;
8838 FD->getNameForDiagnostic(stream, printPolicy, /*Qualified=*/false);
8839 }
8840}
8841
8842////////////////////////////////////////////////////////////////////////////////
8843/// Return a unique identifier of the declaration represented by the
8844/// FuncTempInfo
8845
8850
8851////////////////////////////////////////////////////////////////////////////////
8852/// Delete the FuncTempInfo_t
8853
8855{
8856 // Currently the address of ft_info is actually the decl itself,
8857 // so we have nothing to do.
8858}
8859
8860////////////////////////////////////////////////////////////////////////////////
8861/// Construct a FuncTempInfo_t
8862
8864{
8865 // Currently the address of ft_info is actually the decl itself,
8866 // so we have nothing to do.
8867
8868 return (FuncTempInfo_t*)const_cast<void*>(declid);
8869}
8870
8871////////////////////////////////////////////////////////////////////////////////
8872/// Construct a FuncTempInfo_t
8873
8875{
8876 // Currently the address of ft_info is actually the decl itself,
8877 // so we have nothing to do.
8878
8879 return (FuncTempInfo_t*)ft_info;
8880}
8881
8882////////////////////////////////////////////////////////////////////////////////
8883/// Check validity of a FuncTempInfo_t
8884
8886{
8887 // Currently the address of ft_info is actually the decl itself,
8888 // so we have nothing to do.
8889
8890 return t_info != nullptr;
8891}
8892
8893////////////////////////////////////////////////////////////////////////////////
8894/// Return the maximum number of template arguments of the
8895/// function template described by ft_info.
8896
8898{
8899 if (!ft_info) return 0;
8900 const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
8901 return ft->getTemplateParameters()->size();
8902}
8903
8904////////////////////////////////////////////////////////////////////////////////
8905/// Return the number of required template arguments of the
8906/// function template described by ft_info.
8907
8909{
8910 if (!ft_info) return 0;
8911 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8912 return ft->getTemplateParameters()->getMinRequiredArguments();
8913}
8914
8915////////////////////////////////////////////////////////////////////////////////
8916/// Return the property of the function template.
8917
8919{
8920 if (!ft_info) return 0;
8921
8922 long property = 0L;
8923 property |= kIsCompiled;
8924
8925 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8926
8927 switch (ft->getAccess()) {
8928 case clang::AS_public:
8929 property |= kIsPublic;
8930 break;
8931 case clang::AS_protected:
8932 property |= kIsProtected;
8933 break;
8934 case clang::AS_private:
8935 property |= kIsPrivate;
8936 break;
8937 case clang::AS_none:
8938 if (ft->getDeclContext()->isNamespace())
8940 break;
8941 default:
8942 // IMPOSSIBLE
8943 assert(false && "Unexpected value for the access property value in Clang");
8944 break;
8945 }
8946
8947 const clang::FunctionDecl *fd = ft->getTemplatedDecl();
8948 if (const clang::CXXMethodDecl *md =
8949 llvm::dyn_cast<clang::CXXMethodDecl>(fd)) {
8950 if (md->getMethodQualifiers().hasConst()) {
8951 property |= kIsConstant | kIsConstMethod;
8952 }
8953 if (md->isVirtual()) {
8954 property |= kIsVirtual;
8955 }
8956 if (md->isPureVirtual()) {
8957 property |= kIsPureVirtual;
8958 }
8959 if (const clang::CXXConstructorDecl *cd =
8960 llvm::dyn_cast<clang::CXXConstructorDecl>(md)) {
8961 if (cd->isExplicit()) {
8962 property |= kIsExplicit;
8963 }
8964 }
8965 else if (const clang::CXXConversionDecl *cd =
8966 llvm::dyn_cast<clang::CXXConversionDecl>(md)) {
8967 if (cd->isExplicit()) {
8968 property |= kIsExplicit;
8969 }
8970 }
8971 }
8972 return property;
8973}
8974
8975////////////////////////////////////////////////////////////////////////////////
8976/// Return the property not already defined in Property
8977/// See TDictionary's EFunctionProperty
8978
8980{
8981 if (!ft_info) return 0;
8982
8983 long property = 0L;
8984 property |= kIsCompiled;
8985
8986 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8987 const clang::FunctionDecl *fd = ft->getTemplatedDecl();
8988
8989 if (fd->isOverloadedOperator())
8991 if (llvm::isa<clang::CXXConversionDecl>(fd))
8993 if (llvm::isa<clang::CXXConstructorDecl>(fd))
8995 if (llvm::isa<clang::CXXDestructorDecl>(fd))
8997 if (fd->isInlined())
8999 return property;
9000}
9001
9002////////////////////////////////////////////////////////////////////////////////
9003/// Return the name of this function template.
9004
9006{
9007 output.Clear();
9008 if (!ft_info) return;
9009 const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
9010 std::string buf;
9011 GetFunctionName(ft->getTemplatedDecl(), buf);
9012 output = buf;
9013}
9014
9015////////////////////////////////////////////////////////////////////////////////
9016/// Return the comments associates with this function template.
9017
9019{
9020 output.Clear();
9021 if (!ft_info) return;
9022 const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
9023
9024 // Iterate over the redeclarations, we can have multiple definitions in the
9025 // redecl chain (came from merging of pcms).
9028 if (AnnotateAttr *A = AnnotFD->getAttr<AnnotateAttr>()) {
9029 output = A->getAnnotation().str();
9030 return;
9031 }
9032 }
9033 if (!ft->isFromASTFile()) {
9034 // Try to get the comment from the header file if present
9035 // but not for decls from AST file, where rootcling would have
9036 // created an annotation
9038 }
9039}
9040
9041
9042//______________________________________________________________________________
9043//
9044// MethodInfo interface
9045//
9046
9047////////////////////////////////////////////////////////////////////////////////
9048/// Interface to cling function
9049
9050void TCling::MethodInfo_Delete(MethodInfo_t* minfo) const
9051{
9052 delete(TClingMethodInfo*) minfo;
9053}
9054
9055////////////////////////////////////////////////////////////////////////////////
9056
9058{
9060 // The next call locks the interpreter mutex.
9061 info->CreateSignature(signature);
9062}
9063
9064////////////////////////////////////////////////////////////////////////////////
9065
9066MethodInfo_t* TCling::MethodInfo_Factory() const
9067{
9069 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl());
9070}
9071
9072////////////////////////////////////////////////////////////////////////////////
9073
9075{
9077 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), (TClingClassInfo*)clinfo);
9078}
9079
9080////////////////////////////////////////////////////////////////////////////////
9081
9083{
9084 const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
9086 return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), decl);
9087}
9088
9089////////////////////////////////////////////////////////////////////////////////
9090
9091MethodInfo_t* TCling::MethodInfo_FactoryCopy(MethodInfo_t* minfo) const
9092{
9093 return (MethodInfo_t*) new TClingMethodInfo(*(TClingMethodInfo*)minfo);
9094}
9095
9096////////////////////////////////////////////////////////////////////////////////
9097
9099{
9101 // The next call locks the interpreter mutex.
9102 return info->InterfaceMethod();
9103}
9104
9105////////////////////////////////////////////////////////////////////////////////
9106
9107bool TCling::MethodInfo_IsValid(MethodInfo_t* minfo) const
9108{
9110 return info->IsValid();
9111}
9112
9113////////////////////////////////////////////////////////////////////////////////
9114
9115int TCling::MethodInfo_NArg(MethodInfo_t* minfo) const
9116{
9118 return info->NArg();
9119}
9120
9121////////////////////////////////////////////////////////////////////////////////
9122
9124{
9126 return info->NDefaultArg();
9127}
9128
9129////////////////////////////////////////////////////////////////////////////////
9130
9131int TCling::MethodInfo_Next(MethodInfo_t* minfo) const
9132{
9134 return info->Next();
9135}
9136
9137////////////////////////////////////////////////////////////////////////////////
9138
9140{
9142 // The next call locks the interpreter mutex.
9143 return info->Property();
9144}
9145
9146////////////////////////////////////////////////////////////////////////////////
9147
9149{
9151 // The next call locks the interpreter mutex.
9152 return info->ExtraProperty();
9153}
9154
9155////////////////////////////////////////////////////////////////////////////////
9156
9158{
9160 // The next call locks the interpreter mutex.
9161 return (TypeInfo_t*)info->Type();
9162}
9163
9164////////////////////////////////////////////////////////////////////////////////
9165
9166const char* TCling::MethodInfo_GetMangledName(MethodInfo_t* minfo) const
9167{
9170 // The next call locks the interpreter mutex.
9171 mangled_name = info->GetMangledName();
9172 return mangled_name;
9173}
9174
9175////////////////////////////////////////////////////////////////////////////////
9176
9177const char* TCling::MethodInfo_GetPrototype(MethodInfo_t* minfo) const
9178{
9180 // The next call locks the interpreter mutex.
9181 return info->GetPrototype();
9182}
9183
9184////////////////////////////////////////////////////////////////////////////////
9185
9186const char* TCling::MethodInfo_Name(MethodInfo_t* minfo) const
9187{
9189 // The next call locks the interpreter mutex.
9190 return info->Name();
9191}
9192
9193////////////////////////////////////////////////////////////////////////////////
9194
9195const char* TCling::MethodInfo_TypeName(MethodInfo_t* minfo) const
9196{
9198 // The next call locks the interpreter mutex.
9199 return info->TypeName();
9200}
9201
9202////////////////////////////////////////////////////////////////////////////////
9203
9204std::string TCling::MethodInfo_TypeNormalizedName(MethodInfo_t* minfo) const
9205{
9207 // The next part locks the interpreter mutex.
9208 if (info && info->IsValid())
9209 return info->Type()->NormalizedName(*fNormalizedCtxt);
9210 else
9211 return "";
9212}
9213
9214////////////////////////////////////////////////////////////////////////////////
9215
9216const char* TCling::MethodInfo_Title(MethodInfo_t* minfo) const
9217{
9219 // The next call locks the interpreter mutex.
9220 return info->Title();
9221}
9222
9223////////////////////////////////////////////////////////////////////////////////
9224
9226{
9227 if (func) {
9228 return MethodInfo_MethodCallReturnType(func->fInfo);
9229 } else {
9230 return EReturnType::kOther;
9231 }
9232}
9233
9234////////////////////////////////////////////////////////////////////////////////
9235
9237{
9239 if (info && info->IsValid()) {
9240 TClingTypeInfo *typeinfo = info->Type();
9241 clang::QualType QT( typeinfo->GetQualType().getCanonicalType() );
9242 if (QT->isEnumeralType()) {
9243 return EReturnType::kLong;
9244 } else if (QT->isPointerType()) {
9245 // Look for char*
9246 QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
9247 if ( QT->isCharType() ) {
9248 return EReturnType::kString;
9249 } else {
9250 return EReturnType::kOther;
9251 }
9252 } else if ( QT->isFloatingType() ) {
9253 int sz = typeinfo->Size();
9254 if (sz == 4 || sz == 8) {
9255 // Support only float and double.
9256 return EReturnType::kDouble;
9257 } else {
9258 return EReturnType::kOther;
9259 }
9260 } else if ( QT->isIntegerType() ) {
9261 int sz = typeinfo->Size();
9262 if (sz <= 8) {
9263 // Support only up to long long ... but
9264 // FIXME the TMethodCall::Execute only
9265 // return long (4 bytes) ...
9266 // The v5 implementation of TMethodCall::ReturnType
9267 // was not making the distinction so we let it go
9268 // as is for now, but we really need to upgrade
9269 // TMethodCall::Execute ...
9270 return EReturnType::kLong;
9271 } else {
9272 return EReturnType::kOther;
9273 }
9274 } else {
9275 return EReturnType::kOther;
9276 }
9277 } else {
9278 return EReturnType::kOther;
9279 }
9280}
9281
9282//______________________________________________________________________________
9283//
9284// MethodArgInfo interface
9285//
9286
9287////////////////////////////////////////////////////////////////////////////////
9288
9293
9294////////////////////////////////////////////////////////////////////////////////
9295
9301
9302////////////////////////////////////////////////////////////////////////////////
9303
9309
9310////////////////////////////////////////////////////////////////////////////////
9311
9317
9318////////////////////////////////////////////////////////////////////////////////
9319
9325
9326////////////////////////////////////////////////////////////////////////////////
9327
9333
9334////////////////////////////////////////////////////////////////////////////////
9335
9341
9342////////////////////////////////////////////////////////////////////////////////
9343
9345{
9347 return info->DefaultValue();
9348}
9349
9350////////////////////////////////////////////////////////////////////////////////
9351
9353{
9355 return info->Name();
9356}
9357
9358////////////////////////////////////////////////////////////////////////////////
9359
9361{
9363 return info->TypeName();
9364}
9365
9366////////////////////////////////////////////////////////////////////////////////
9367
9369{
9371 return info->Type()->NormalizedName(*fNormalizedCtxt);
9372}
9373
9374////////////////////////////////////////////////////////////////////////////////
9375
9381
9382//______________________________________________________________________________
9383//
9384// TypeInfo interface
9385//
9386
9387////////////////////////////////////////////////////////////////////////////////
9388
9390{
9391 delete (TClingTypeInfo*) tinfo;
9392}
9393
9394////////////////////////////////////////////////////////////////////////////////
9395
9401
9402////////////////////////////////////////////////////////////////////////////////
9403
9409
9410////////////////////////////////////////////////////////////////////////////////
9411
9416
9417////////////////////////////////////////////////////////////////////////////////
9418
9425
9426////////////////////////////////////////////////////////////////////////////////
9427
9429{
9431 return TClinginfo->IsValid();
9432}
9433
9434////////////////////////////////////////////////////////////////////////////////
9435
9437{
9439 return TClinginfo->Name();
9440}
9441
9442////////////////////////////////////////////////////////////////////////////////
9443
9449
9450////////////////////////////////////////////////////////////////////////////////
9451
9453{
9455 return TClinginfo->RefType();
9456}
9457
9458////////////////////////////////////////////////////////////////////////////////
9459
9461{
9463 return TClinginfo->Size();
9464}
9465
9466////////////////////////////////////////////////////////////////////////////////
9467
9469{
9471 return TClinginfo->TrueName(*fNormalizedCtxt);
9472}
9473
9474////////////////////////////////////////////////////////////////////////////////
9475
9477{
9479 return TClinginfo->QualTypePtr();
9480}
9481
9482
9483//______________________________________________________________________________
9484//
9485// TypedefInfo interface
9486//
9487
9488////////////////////////////////////////////////////////////////////////////////
9489
9494
9495////////////////////////////////////////////////////////////////////////////////
9496
9502
9503////////////////////////////////////////////////////////////////////////////////
9504
9510
9511////////////////////////////////////////////////////////////////////////////////
9512
9517
9518////////////////////////////////////////////////////////////////////////////////
9519
9527
9528////////////////////////////////////////////////////////////////////////////////
9529
9535
9536////////////////////////////////////////////////////////////////////////////////
9537
9543
9544////////////////////////////////////////////////////////////////////////////////
9545
9551
9552////////////////////////////////////////////////////////////////////////////////
9553
9559
9560////////////////////////////////////////////////////////////////////////////////
9561
9567
9568////////////////////////////////////////////////////////////////////////////////
9569
9571{
9573 return TClinginfo->Name();
9574}
9575
9576////////////////////////////////////////////////////////////////////////////////
9577
9579{
9581 return TClinginfo->Title();
9582}
9583
9584////////////////////////////////////////////////////////////////////////////////
9585
9586bool TCling::IsSameType(const void * QualTypePtr1, const void * QualTypePtr2) const
9587{
9588 clang::QualType QT1 = clang::QualType::getFromOpaquePtr(QualTypePtr1);
9589 clang::QualType QT2 = clang::QualType::getFromOpaquePtr(QualTypePtr2);
9590 return fInterpreter->getCI()->getASTContext().hasSameType(QT1, QT2);
9591}
9592
9593////////////////////////////////////////////////////////////////////////////////
9594
9595bool TCling::IsIntegerType(const void * QualTypePtr) const
9596{
9597 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9598 return QT->hasIntegerRepresentation();
9599}
9600
9601////////////////////////////////////////////////////////////////////////////////
9602
9603bool TCling::IsSignedIntegerType(const void * QualTypePtr) const
9604{
9605 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9606 return QT->hasSignedIntegerRepresentation();
9607}
9608
9609////////////////////////////////////////////////////////////////////////////////
9610
9611bool TCling::IsUnsignedIntegerType(const void * QualTypePtr) const
9612{
9613 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9614 return QT->hasUnsignedIntegerRepresentation();
9615}
9616
9617////////////////////////////////////////////////////////////////////////////////
9618
9619bool TCling::IsFloatingType(const void * QualTypePtr) const
9620{
9621 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9622 return QT->hasFloatingRepresentation();
9623}
9624
9625////////////////////////////////////////////////////////////////////////////////
9626
9627bool TCling::IsPointerType(const void * QualTypePtr) const
9628{
9629 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9630 return QT->hasPointerRepresentation();
9631}
9632
9633////////////////////////////////////////////////////////////////////////////////
9634
9635bool TCling::IsVoidPointerType(const void * QualTypePtr) const
9636{
9637 clang::QualType QT = clang::QualType::getFromOpaquePtr(QualTypePtr);
9638 return QT->isVoidPointerType();
9639}
9640
9641////////////////////////////////////////////////////////////////////////////////
9642
9644{
9645 if (!fInitialMutex) {
9647 Error("SnapshotMutexState", "fRecurseCount != 0 even though initial mutex state is unset!");
9648 }
9649 fInitialMutex.fState = mtx->GetStateBefore();
9650 }
9651 // We will "forget" this lock once we backed out of all interpreter frames.
9652 // Here we are entering one, so ++.
9654}
9655
9656////////////////////////////////////////////////////////////////////////////////
9657
9659{
9660 if (!fInitialMutex)
9661 return;
9662 if (fInitialMutex.fRecurseCount == 0) {
9663 Error("ForgetMutexState", "mutex state's recurse count already 0!");
9664 }
9665 else if (--fInitialMutex.fRecurseCount == 0) {
9666 // We have returned from all interpreter frames. Reset the initial lock state.
9667 fInitialMutex.fState.reset();
9668 }
9669}
9670
9671////////////////////////////////////////////////////////////////////////////////
9672/// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
9673
9675{
9676 if (gInterpreterMutex) {
9677 if (delta) {
9678 auto typedDelta = static_cast<MutexStateAndRecurseCountDelta *>(delta);
9679 std::unique_ptr<MutexStateAndRecurseCountDelta> uniqueP{typedDelta};
9680 gCoreMutex->Apply(std::move(typedDelta->fDelta));
9681 // Now that we have the lock, update the global
9682 R__ASSERT(fInitialMutex.fRecurseCount == 0 && "Inconsistent state of fInitialMutex! Another thread within Interpreter critical section.");
9683 std::swap(fInitialMutex, typedDelta->fInitialState);
9684 } else {
9685 // This case happens when EnableThreadSafety is first called from
9686 // the interpreter function we just handled.
9687 // Since thread safety was not enabled at the time we rewound, there was
9688 // no lock taken and even-though we should be locking the rest of this
9689 // interpreter handling/modifying code (since there might be threads in
9690 // flight), we can't because there would not be any lock guard to release the
9691 // locks
9693 Error("ApplyToInterpreterMutex",
9694 "After returning from user code that turned on thread safety support, we notice that fInitialMutex is already used ... "
9695 "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.");
9696 }
9697 }
9698}
9699
9700////////////////////////////////////////////////////////////////////////////////
9701/// Reset the interpreter lock to the state it had before interpreter-related
9702/// calls happened.
9703
9705{
9706 if (fInitialMutex) {
9707 // Need to start a new recurse count.
9708 std::unique_ptr<MutexStateAndRecurseCountDelta> uniqueP(new MutexStateAndRecurseCountDelta());
9709 std::swap(uniqueP->fInitialState, fInitialMutex);
9710 uniqueP->fDelta = gCoreMutex->Rewind(*uniqueP->fInitialState.fState);
9711 return uniqueP.release();
9712 }
9714 return nullptr;
9715}
#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
Definition RtypesCore.h:63
int Int_t
Definition RtypesCore.h:45
long Longptr_t
Definition RtypesCore.h:75
short Version_t
Definition RtypesCore.h:65
unsigned long ULong_t
Definition RtypesCore.h:55
long Long_t
Definition RtypesCore.h:54
unsigned int UInt_t
Definition RtypesCore.h:46
constexpr Bool_t kFALSE
Definition RtypesCore.h:94
constexpr Ssiz_t kNPOS
Definition RtypesCore.h:117
long long Long64_t
Definition RtypesCore.h:69
unsigned long long ULong64_t
Definition RtypesCore.h:70
constexpr Bool_t kTRUE
Definition RtypesCore.h:93
TClass *(* DictFuncPtr_t)()
Definition Rtypes.h:85
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:343
void TCling__TransactionRollback(const cling::Transaction &T)
Definition TCling.cxx:581
static void RegisterPreIncludedHeaders(cling::Interpreter &clingInterp)
Definition TCling.cxx:1319
static bool hasParsedRootmapForLibrary(llvm::StringRef lib)
Definition TCling.cxx:7298
void TCling__InvalidateGlobal(const clang::Decl *D)
Definition TCling.cxx:576
bool TClingLookupHelper__AutoParse(const char *cname)
Allow calling autoparsing from TMetaUtils.
Definition TCling.cxx:896
R__EXTERN int optind
Definition TCling.cxx:319
void * TCling__LockCompilationDuringUserCodeExecution()
Lock the interpreter.
Definition TCling.cxx:370
void TCling__UpdateListsOnUnloaded(const cling::Transaction &T)
Definition TCling.cxx:571
void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt *&normCtxt)
Definition TCling.cxx:559
int TCling__LoadLibrary(const char *library)
Load a library.
Definition TCling.cxx:335
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:1005
ETupleOrdering
Check in what order the member of a tuple are layout.
Definition TCling.cxx:3940
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:353
static const std::unordered_set< std::string > gIgnoredPCMNames
List of dicts that have the PCM information already in the PCH.
Definition TCling.cxx:1971
static Bool_t s_IsLibraryLoaded(const char *libname, cling::Interpreter *fInterpreter)
Definition TCling.cxx:3164
const char * TCling__GetClassSharedLibs(const char *className, bool skipCore)
Definition TCling.cxx:635
static GlobalModuleIndex * loadGlobalModuleIndex(cling::Interpreter &interp)
Definition TCling.cxx:1100
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:905
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:1085
void TCling__UnlockCompilationDuringUserCodeExecution(void *)
Unlock the interpreter.
Definition TCling.cxx:381
static std::string AlternateTuple(const char *classname, const cling::LookupHelper &lh, Bool_t silent)
Definition TCling.cxx:3982
static bool R__InitStreamerInfoFactory()
Helper to initialize TVirtualStreamerInfo's factor early.
Definition TCling.cxx:1694
int TCling__AutoParseCallback(const char *className)
Definition TCling.cxx:630
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:701
static bool HaveFullGlobalModuleIndex
Definition TCling.cxx:1099
bool TCling__TEST_isInvalidDecl(clang::Decl *D)
Definition TCling.cxx:253
void TCling__LibraryUnloadedRTTI(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:595
void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter *)
Definition TCling.cxx:566
const Decl * TCling__GetObjectDecl(TObject *obj)
Definition TCling.cxx:606
static ETupleOrdering IsTupleAscending()
Definition TCling.cxx:3958
void TCling__RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
Definition TCling.cxx:590
static void TCling__UpdateClassInfo(const NamedDecl *TD)
Update TClingClassInfo for a class (e.g. upon seeing a definition).
Definition TCling.cxx:391
clang::DeclContext * TCling__DEBUG__getDeclContext(clang::Decl *D)
Definition TCling.cxx:217
int TCling__CompileMacro(const char *fileName, const char *options)
Definition TCling.cxx:646
#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:362
void TCling__DEBUG__decl_dump(void *D)
Definition TCling.cxx:235
int TCling__AutoLoadCallback(const char *className)
Definition TCling.cxx:625
static bool LoadModule(const std::string &ModuleName, cling::Interpreter &interp)
Definition TCling.cxx:1050
static void RegisterCxxModules(cling::Interpreter &clingInterp)
Definition TCling.cxx:1203
static void ConstructorName(std::string &name, const clang::Decl *decl, cling::Interpreter &interp, const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt)
Definition TCling.cxx:8787
void TCling__PrintStackTrace()
Print a StackTrace!
Definition TCling.cxx:328
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:2456
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:7207
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:682
static void PrintDlError(const char *dyLibName, const char *modulename)
Definition TCling.cxx:1996
TInterpreter * CreateInterpreter(void *interpLibHandle, const char *argv[])
Definition TCling.cxx:610
static std::string GetClassSharedLibsForModule(const char *cls, cling::LookupHelper &LH, bool skipCore)
Definition TCling.cxx:7042
const char * fantomline
Definition TCling.cxx:843
void TCling__LibraryLoadedRTTI(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:585
static cling::Interpreter::CompilationResult ExecAutoParse(const char *what, Bool_t header, cling::Interpreter *interpreter)
Parse the payload or header.
Definition TCling.cxx:6367
static bool requiresRootMap(const char *rootmapfile)
Definition TCling.cxx:5547
clang::NamespaceDecl * TCling__DEBUG__DCtoNamespace(clang::DeclContext *DC)
Definition TCling.cxx:220
TObject * TCling__GetObjectAddress(const char *Name, void *&LookupCtx)
Definition TCling.cxx:602
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:1072
int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *nsDecl)
Definition TCling.cxx:641
void DestroyInterpreter(TInterpreter *interp)
Definition TCling.cxx:618
static bool hasPrecomputedLibraryDeps(llvm::StringRef lib)
Definition TCling.cxx:7319
void TCling__SplitAclicMode(const char *fileName, string &mode, string &args, string &io, string &fname)
Definition TCling.cxx:653
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:384
@ 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 Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:185
Int_t gErrorIgnoreLevel
Error handling routines.
Definition TError.cxx:31
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
Definition TError.cxx:229
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:244
#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
void cd(Int_t id=-1)
Int_t Collect(const TSlave *sl, Long_t timeout=-1, Int_t endtype=-1, Bool_t deactonfail=kFALSE)
Int_t gDebug
Definition TROOT.cxx:622
#define gROOT
Definition TROOT.h:414
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2489
@ 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:17535
#define free
Definition civetweb.c:1539
#define snprintf
Definition civetweb.c:1540
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:3571
ROOT::ESTLType GetCollectionType() const
Return the 'type' of the STL the TClass is representing.
Definition TClass.cxx:2992
void RemoveStreamerInfo(Int_t slot)
Remove and delete the StreamerInfo in the given slot.
Definition TClass.cxx:7510
EState fState
cached of the streaming method to use
Definition TClass.h:280
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:224
TList * GetListOfFunctionTemplates(Bool_t load=kTRUE)
Return TListOfFunctionTemplates for a class.
Definition TClass.cxx:3926
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:5043
static void RemoveClassDeclId(TDictionary::DeclId_t id)
Definition TClass.cxx:603
static Bool_t HasNoInfoOrEmuOrFwdDeclaredDecl(const char *)
Definition TClass.cxx:3530
static TClass * LoadClass(const char *requestedname, Bool_t silent)
Helper function used by TClass::GetClass().
Definition TClass.cxx:5889
Int_t Size() const
Return size of object of this class.
Definition TClass.cxx:5844
@ kLoading
Definition TClass.h:335
@ kUnloading
Definition TClass.h:335
TObjArray * fStreamerInfo
Definition TClass.h:201
ClassInfo_t * GetClassInfo() const
Definition TClass.h:440
ClassInfo_t * fClassInfo
Definition TClass.h:225
TVirtualCollectionProxy * GetCollectionProxy() const
Return the proxy describing the collection (if any).
Definition TClass.cxx:3003
void ResetCaches()
To clean out all caches.
Definition TClass.cxx:4343
static Int_t ReadRules()
Read the class.rules files from the default location:.
Definition TClass.cxx:1912
@ 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:263
std::atomic< Bool_t > fHasRootPcmInfo
C++ Property of the class (is abstract, has virtual table, etc.)
Definition TClass.h:262
const char * GetDeclFileName() const
Return name of the file containing the declaration of this class.
Definition TClass.cxx:3595
@ 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:3074
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:1026
bool Append(const std::string &str)
Append string to the storage if not added already.
Definition TCling.cxx:1034
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:6239
const char * MethodArgInfo_DefaultValue(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9344
bool ClassInfo_IsScopedEnum(ClassInfo_t *info) const final
Definition TCling.cxx:8350
const char * TypeInfo_Name(TypeInfo_t *) const final
Definition TCling.cxx:9436
void * MethodInfo_InterfaceMethod(MethodInfo_t *minfo) const final
Definition TCling.cxx:9098
void LoadEnums(TListOfEnums &cl) const final
Create list of pointers to enums for TClass cl.
Definition TCling.cxx:4430
void UpdateListOfGlobals() final
No op: see TClingCallbacks (used to update the list of globals)
Definition TCling.cxx:3920
bool TypedefInfo_IsValid(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9530
Int_t AutoLoad(const char *classname, Bool_t knowDictNotLoaded=kFALSE) final
Load library containing the specified class.
Definition TCling.cxx:6300
void CallFunc_Init(CallFunc_t *func) const final
Definition TCling.cxx:7988
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:3683
bool LibraryLoadingFailed(const std::string &, const std::string &, bool, bool)
Definition TCling.cxx:6603
void GenericError(const char *error) const final
Let the interpreter issue a generic error, and set its error state.
Definition TCling.cxx:7503
std::vector< void * > fRegisterModuleDyLibs
Definition TCling.h:138
void CallFunc_ExecWithReturn(CallFunc_t *func, void *address, void *ret) const final
Definition TCling.cxx:7914
TypeInfo_t * MethodInfo_Type(MethodInfo_t *minfo) const final
Definition TCling.cxx:9157
std::vector< std::string > fAutoLoadLibStorage
Definition TCling.h:118
void CallFunc_Delete(CallFunc_t *func) const final
Definition TCling.cxx:7891
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:7546
void ResetAll() final
Reset the Cling state to its initial state.
Definition TCling.cxx:3759
void SetDeclAttr(DeclId_t, const char *) final
Definition TCling.cxx:8773
void HandleNewDecl(const void *DV, bool isDeserialized, std::set< TClass * > &modifiedClasses)
Definition TCling.cxx:498
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:6937
Long_t MethodInfo_Property(MethodInfo_t *minfo) const final
Definition TCling.cxx:9139
void LoadFunctionTemplates(TClass *cl) const final
Create list of pointers to function templates for TClass cl.
Definition TCling.cxx:4477
bool ClassInfo_IsValidMethod(ClassInfo_t *info, const char *method, const char *proto, Longptr_t *offset, ROOT::EFunctionMatchMode=ROOT::kConversionMatch) const final
Definition TCling.cxx:8384
Long_t DataMemberInfo_Property(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8706
int SetClassAutoparsing(int) final
Enable/Disable the Autoparsing of headers.
Definition TCling.cxx:7631
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:4524
void RewindDictionary() final
Rewind Cling dictionary to the point where it was before executing the current macro.
Definition TCling.cxx:3804
bool ClassInfo_IsValid(ClassInfo_t *info) const final
Definition TCling.cxx:8376
void UpdateListsOnCommitted(const cling::Transaction &T)
Definition TCling.cxx:6811
int TypeInfo_RefType(TypeInfo_t *) const final
Definition TCling.cxx:9452
void CreateListOfBaseClasses(TClass *cl) const final
Create list of pointers to base class(es) for TClass cl.
Definition TCling.cxx:4406
ClassInfo_t * ClassInfo_Factory(Bool_t all=kTRUE) const final
Definition TCling.cxx:8263
const char * MethodInfo_Name(MethodInfo_t *minfo) const final
Definition TCling.cxx:9186
BaseClassInfo_t * BaseClassInfo_Factory(ClassInfo_t *info) const final
Definition TCling.cxx:8520
Bool_t LoadText(const char *text) const final
Load the declarations from text into the interpreter.
Definition TCling.cxx:7561
const char * GetSharedLibDeps(const char *lib, bool tryDyld=false) final
Get the list a libraries on which the specified lib depends.
Definition TCling.cxx:7335
EReturnType MethodInfo_MethodCallReturnType(MethodInfo_t *minfo) const final
Definition TCling.cxx:9236
TObject * GetObjectAddress(const char *Name, void *&LookupCtx)
If the interpreter encounters Name, check whether that is an object ROOT could retrieve.
Definition TCling.cxx:7762
Longptr_t ProcessLineAsynch(const char *line, EErrorCode *error=nullptr)
Let cling process a command line asynch.
Definition TCling.cxx:3595
bool MethodInfo_IsValid(MethodInfo_t *minfo) const final
Definition TCling.cxx:9107
FuncTempInfo_t * FuncTempInfo_Factory(DeclId_t declid) const final
Construct a FuncTempInfo_t.
Definition TCling.cxx:8863
TypeInfo_t * TypeInfo_Factory() const final
Definition TCling.cxx:9396
bool IsClassAutoLoadingEnabled() const
Returns if class AutoLoading is currently enabled.
Definition TCling.cxx:7600
void InvalidateGlobal(const clang::Decl *D)
Invalidate cached TCling information for the given global declaration.
Definition TCling.cxx:6922
int Evaluate(const char *, TInterpreterValue &) final
Get the interpreter value corresponding to the statement.
Definition TCling.cxx:7724
std::unique_ptr< TInterpreterValue > MakeInterpreterValue() const final
Definition TCling.cxx:7709
void UpdateListOfLoadedSharedLibraries()
Definition TCling.cxx:3383
const char * TypedefInfo_Title(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9578
~TCling() final
Destroy the interpreter interface.
Definition TCling.cxx:1646
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:8113
void InitRootmapFile(const char *name)
Create a resource table and read the (possibly) three resource files, i.e.
Definition TCling.cxx:5690
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:6558
void LoadPCM(std::string pcmFileNameFullPath)
Tries to load a rdict PCM, issues diagnostics if it fails.
Definition TCling.cxx:1843
void UpdateListOfMethods(TClass *cl) const final
Update the list of pointers to method for TClass cl This is now a nop.
Definition TCling.cxx:4542
void AddFriendToClass(clang::FunctionDecl *, clang::CXXRecordDecl *) const
Inject function as a friend into klass.
Definition TCling.cxx:7815
void PrintIntro() final
No-op; see TRint instead.
Definition TCling.cxx:2681
Bool_t fCxxModulesEnabled
Definition TCling.h:128
int BaseClassInfo_Next(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8540
void RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
Internal function. Actually do the update of the ClassInfo when seeing.
Definition TCling.cxx:6669
CallFunc_t * CallFunc_FactoryCopy(CallFunc_t *func) const final
Definition TCling.cxx:7965
Double_t CallFunc_ExecDouble(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7949
void CallFunc_ResetArg(CallFunc_t *func) const final
Definition TCling.cxx:8014
const char * GetCurrentMacroName() const final
Return the file name of the currently interpreted file, included or not.
Definition TCling.cxx:5498
Bool_t IsLoaded(const char *filename) const final
Return true if the file has already been loaded by cint.
Definition TCling.cxx:3207
void SaveGlobalsContext() final
Save the current Cling state of global objects.
Definition TCling.cxx:3907
void CallFunc_IgnoreExtraArgs(CallFunc_t *func, bool ignore) const final
Definition TCling.cxx:7980
void ApplyToInterpreterMutex(void *delta)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
Definition TCling.cxx:9674
void * LazyFunctionCreatorAutoload(const std::string &mangled_name)
Autoload a library based on a missing symbol.
Definition TCling.cxx:6626
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:4758
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:8179
Bool_t IsLibraryLoaded(const char *libname) const final
Definition TCling.cxx:3173
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:7525
int DataMemberInfo_ArrayDim(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8632
TypeInfo_t * MethodArgInfo_TypeInfo(MethodArgInfo_t *marginfo) const
Definition TCling.cxx:9376
DataMemberInfo_t * DataMemberInfo_FactoryCopy(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8666
Bool_t HandleNewTransaction(const cling::Transaction &T)
Helper function to increase the internal Cling count of transactions that change the AST.
Definition TCling.cxx:3700
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:5563
std::map< SpecialObjectLookupCtx_t, SpecialObjectMap_t > fSpecialObjectMaps
Definition TCling.h:153
int ClassInfo_Next(ClassInfo_t *info) const final
Definition TCling.cxx:8400
void SetErrmsgcallback(void *p) const final
Set a callback to receive error messages.
Definition TCling.cxx:7652
bool MethodArgInfo_IsValid(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9320
int TypeInfo_Size(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9460
Int_t DeleteGlobal(void *obj) final
Delete obj from Cling symbol table so it cannot be accessed anymore.
Definition TCling.cxx:3818
int GetSecurityError() const final
Interface to cling function.
Definition TCling.cxx:7533
void SetTempLevel(int val) const final
Create / close a scope for temporaries.
Definition TCling.cxx:7688
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:8897
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:5190
TypedefInfo_t * TypedefInfo_Factory() const final
Definition TCling.cxx:9497
TObjArray * fRootmapFiles
Definition TCling.h:126
bool IsVoidPointerType(const void *QualTypePtr) const
Definition TCling.cxx:9635
Longptr_t ProcessLine(const char *line, EErrorCode *error=nullptr) final
Definition TCling.cxx:2486
int ClassInfo_Size(ClassInfo_t *info) const final
Definition TCling.cxx:8448
const char * MethodArgInfo_TypeName(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9360
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:5438
std::vector< std::pair< TClass *, DictFuncPtr_t > > fClassesToUpdate
Definition TCling.h:146
int DataMemberInfo_Next(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8690
const char * TypedefInfo_Name(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9570
void BaseClassInfo_Delete(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8513
Long_t MethodInfo_ExtraProperty(MethodInfo_t *minfo) const final
Definition TCling.cxx:9148
void LoadMacro(const char *filename, EErrorCode *error=nullptr) final
Load a macro file in cling's memory.
Definition TCling.cxx:3587
FuncTempInfo_t * FuncTempInfo_FactoryCopy(FuncTempInfo_t *) const final
Construct a FuncTempInfo_t.
Definition TCling.cxx:8874
int DataMemberInfo_MaxIndex(DataMemberInfo_t *dminfo, Int_t dim) const final
Definition TCling.cxx:8682
Bool_t FuncTempInfo_IsValid(FuncTempInfo_t *) const final
Check validity of a FuncTempInfo_t.
Definition TCling.cxx:8885
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:2695
bool ClassInfo_IsBase(ClassInfo_t *info, const char *name) const final
Definition TCling.cxx:8335
void RecursiveRemove(TObject *obj) final
Delete object from cling symbol table so it can not be used anymore.
Definition TCling.cxx:3718
const char * DataMemberInfo_TypeName(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8730
DeclId_t GetDataMemberAtAddr(const void *addr) const final
Return pointer to cling DeclId for a data member with a given name.
Definition TCling.cxx:4985
void CallFunc_SetArgArray(CallFunc_t *func, Longptr_t *paramArr, Int_t nparam) const final
Definition TCling.cxx:8070
std::string CallFunc_GetWrapperCode(CallFunc_t *func) const final
Definition TCling.cxx:8160
void * RewindInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:9704
const char * MethodArgInfo_Name(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9352
Bool_t HasPCMForLibrary(const char *libname) const final
Return true if ROOT has cxxmodules pcm for a given library name.
Definition TCling.cxx:3182
void TypedefInfo_Init(TypedefInfo_t *tinfo, const char *name) const final
Definition TCling.cxx:9520
const char * DataMemberInfo_Title(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8754
Longptr_t CallFunc_ExecInt(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7933
void ClearStack() final
Delete existing temporary values.
Definition TCling.cxx:3120
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:7582
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:7402
MethodInfo_t * CallFunc_FactoryMethod(CallFunc_t *func) const final
Definition TCling.cxx:7972
bool IsUnsignedIntegerType(const void *QualTypePtr) const
Definition TCling.cxx:9611
TypedefInfo_t * TypedefInfo_FactoryCopy(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9513
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:5083
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:2426
std::string MethodArgInfo_TypeNormalizedName(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9368
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:4867
Long_t MethodArgInfo_Property(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9336
int TypedefInfo_Size(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9554
void CallFunc_ExecWithArgsAndReturn(CallFunc_t *func, void *address, const void *args[]=nullptr, int nargs=0, void *ret=nullptr) const final
Definition TCling.cxx:7922
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:5235
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:6791
Int_t Load(const char *filenam, Bool_t system=kFALSE) final
Load a library file in cling's memory.
Definition TCling.cxx:3550
int TypedefInfo_Next(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9538
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:5042
void TypeInfo_Init(TypeInfo_t *tinfo, const char *funcname) const final
Definition TCling.cxx:9419
Bool_t SetSuspendAutoParsing(Bool_t value) final
Suspend the Autoparsing of headers.
Definition TCling.cxx:7642
int DataMemberInfo_TypeSize(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8722
static void * fgSetOfSpecials
Definition TCling.h:105
const char * ClassInfo_Title(ClassInfo_t *info) const final
Definition TCling.cxx:8490
const char * DataMemberInfo_Name(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8746
const char * TypeName(const char *typeDesc) final
Return the absolute type of typeDesc.
Definition TCling.cxx:5513
ROOT::TMetaUtils::TNormalizedCtxt * fNormalizedCtxt
Definition TCling.h:134
bool IsSignedIntegerType(const void *QualTypePtr) const
Definition TCling.cxx:9603
void ForgetMutexState() final
Definition TCling.cxx:9658
int MethodInfo_Next(MethodInfo_t *minfo) const final
Definition TCling.cxx:9131
Long_t ClassInfo_ClassProperty(ClassInfo_t *info) const final
Definition TCling.cxx:8224
void MethodInfo_Delete(MethodInfo_t *minfo) const final
Interface to cling function.
Definition TCling.cxx:9050
bool fIsShuttingDown
Definition TCling.h:187
void MethodArgInfo_Delete(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9289
DataMemberInfo_t * DataMemberInfo_Factory(ClassInfo_t *clinfo, TDictionary::EMemberSelection selection) const final
Definition TCling.cxx:8647
void ClassInfo_Destruct(ClassInfo_t *info, void *arena) const final
Definition TCling.cxx:8255
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:6145
Int_t UnloadAllSharedLibraryMaps() final
Unload the library map entries coming from all the loaded shared libraries.
Definition TCling.cxx:6033
void ClassInfo_Init(ClassInfo_t *info, const char *funcname) const final
Definition TCling.cxx:8317
std::set< TClass * > & GetModTClasses()
Definition TCling.h:578
ClassInfo_t * BaseClassInfo_ClassInfo(BaseClassInfo_t *) const final
Definition TCling.cxx:8585
TClingCallbacks * fClingCallbacks
Definition TCling.h:139
Long64_t CallFunc_ExecInt64(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7941
Long_t ClassInfo_Property(ClassInfo_t *info) const final
Definition TCling.cxx:8440
Longptr_t ClassInfo_GetBaseOffset(ClassInfo_t *fromDerived, ClassInfo_t *toBase, void *address, bool isDerivedObject) const final
Definition TCling.cxx:8564
void UpdateEnumConstants(TEnum *enumObj, TClass *cl) const final
Definition TCling.cxx:423
void ExecuteWithArgsAndReturn(TMethod *method, void *address, const void *args[]=nullptr, int nargs=0, void *ret=nullptr) const final
Definition TCling.cxx:5420
Bool_t IsErrorMessagesEnabled() const final
If error messages are disabled, the interpreter should suppress its failures and warning messages fro...
Definition TCling.cxx:7388
TString fIncludePath
Definition TCling.h:115
int DisplayIncludePath(FILE *fout) const final
Interface to cling function.
Definition TCling.cxx:7465
void TransactionRollback(const cling::Transaction &T)
Definition TCling.cxx:6997
Long_t FuncTempInfo_Property(FuncTempInfo_t *) const final
Return the property of the function template.
Definition TCling.cxx:8918
TEnum * CreateEnum(void *VD, TClass *cl) const final
Definition TCling.cxx:471
const char * TypeInfo_TrueName(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9468
Int_t UnloadLibraryMap(const char *library) final
Unload library map entries coming from the specified library.
Definition TCling.cxx:6051
void RegisterTemporary(const TInterpreterValue &value)
Definition TCling.cxx:7735
MutexStateAndRecurseCount fInitialMutex
Definition TCling.h:174
const char * GetSharedLibs() final
Return the list of shared libraries loaded into the process.
Definition TCling.cxx:7035
int MethodArgInfo_Next(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9328
void SnapshotMutexState(ROOT::TVirtualRWMutex *mtx) final
Definition TCling.cxx:9643
Long_t TypeInfo_Property(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9444
const char * MethodInfo_GetPrototype(MethodInfo_t *minfo) const final
Definition TCling.cxx:9177
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:8908
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:2043
static Int_t ShallowAutoLoadImpl(const char *cls)
Definition TCling.cxx:6191
void MethodInfo_CreateSignature(MethodInfo_t *minfo, TString &signature) const final
Definition TCling.cxx:9057
Bool_t CheckClassTemplate(const char *name) final
Return true if there is a class template by the given name ...
Definition TCling.cxx:4384
void LibraryLoaded(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:7020
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:2417
TObjArray * GetRootMapFiles() const final
Definition TCling.h:223
bool DataMemberInfo_IsValid(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8674
bool ClassInfo_IsEnum(const char *name) const final
Definition TCling.cxx:8343
int MethodInfo_NDefaultArg(MethodInfo_t *minfo) const final
Definition TCling.cxx:9123
void CreateListOfMethods(TClass *cl) const final
Create list of pointers to methods for TClass cl.
Definition TCling.cxx:4533
Int_t RescanLibraryMap() final
Scan again along the dynamic path for library maps.
Definition TCling.cxx:5960
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:7661
const char * MethodInfo_GetMangledName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9166
Bool_t fHeaderParsingOnDemand
Definition TCling.h:181
bool IsIntegerType(const void *QualTypePtr) const
Definition TCling.cxx:9595
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:5145
void * ClassInfo_New(ClassInfo_t *info) const final
Definition TCling.cxx:8408
int DisplayClass(FILE *fout, const char *name, int base, int start) const final
Definition TCling.cxx:7456
void GetFunctionName(const clang::Decl *decl, std::string &name) const
Definition TCling.cxx:8809
void CreateListOfMethodArgs(TFunction *m) const final
Create list of pointers to method arguments for TMethod m.
Definition TCling.cxx:4558
const char * GetSTLIncludePath() const final
Return the directory containing CINT's stl cintdlls.
Definition TCling.cxx:7447
MethodArgInfo_t * MethodArgInfo_FactoryCopy(MethodArgInfo_t *marginfo) const final
Definition TCling.cxx:9312
Longptr_t BaseClassInfo_Offset(BaseClassInfo_t *toBaseClassInfo, void *address, bool isDerivedObject) const final
Definition TCling.cxx:8556
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:4212
void * FindSym(const char *entry) const final
Interface to cling function.
Definition TCling.cxx:7494
void RegisterLoadedSharedLibrary(const char *name)
Register a new shared library name with the interpreter; add it to fSharedLibs.
Definition TCling.cxx:3450
void TypeInfo_Delete(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9389
int MethodInfo_NArg(MethodInfo_t *minfo) const final
Definition TCling.cxx:9115
DeclId_t GetDataMemberWithValue(const void *ptrvalue) const final
NOT IMPLEMENTED.
Definition TCling.cxx:4976
std::unordered_set< const clang::NamespaceDecl * > fNSFromRootmaps
Definition TCling.h:125
EReturnType MethodCallReturnType(TFunction *func) const final
Definition TCling.cxx:9225
void ProcessClassesToUpdate()
Definition TCling.cxx:2012
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:5168
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:4997
const char * MethodInfo_Title(MethodInfo_t *minfo) const final
Definition TCling.cxx:9216
TString fRootmapLoadPath
Definition TCling.h:116
const char * BaseClassInfo_TmpltName(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8619
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:3133
const char * BaseClassInfo_FullName(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8601
void CallFunc_SetArgs(CallFunc_t *func, const char *param) const final
Definition TCling.cxx:8078
int UnloadFile(const char *path) const final
Definition TCling.cxx:7694
void SetClassInfo(TClass *cl, Bool_t reload=kFALSE, Bool_t silent=kFALSE) final
Set pointer to the TClingClassInfo in TClass.
Definition TCling.cxx:4076
void CallFunc_Exec(CallFunc_t *func, void *address) const final
Definition TCling.cxx:7898
bool IsPointerType(const void *QualTypePtr) const
Definition TCling.cxx:9627
bool IsFloatingType(const void *QualTypePtr) const
Definition TCling.cxx:9619
Long_t FuncTempInfo_ExtraProperty(FuncTempInfo_t *) const final
Return the property not already defined in Property See TDictionary's EFunctionProperty.
Definition TCling.cxx:8979
bool CallFunc_IsValid(CallFunc_t *func) const final
Definition TCling.cxx:7997
const char * BaseClassInfo_Name(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8611
ROOT::TMetaUtils::TClingLookupHelper * fLookupHelper
Definition TCling.h:135
const char * DataMemberInfo_ValidArrayIndex(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8762
Int_t GetMore() const final
Return whether we are waiting for more input either because the collected input contains unbalanced b...
Definition TCling.cxx:4579
Bool_t fIsAutoParsingSuspended
Definition TCling.h:182
std::string ToString(const char *type, void *obj) final
Definition TCling.cxx:1043
DeclId_t GetDeclId(const llvm::GlobalValue *gv) const
Return pointer to cling DeclId for a global value.
Definition TCling.cxx:4907
void Execute(const char *function, const char *params, int *error=nullptr) final
Execute a global function with arguments params.
Definition TCling.cxx:5268
bool ClassInfo_IsLoaded(ClassInfo_t *info) const final
Definition TCling.cxx:8368
Longptr_t ClassInfo_Tagnum(ClassInfo_t *info) const final
Definition TCling.cxx:8456
Long_t BaseClassInfo_Property(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8577
void CallFunc_SetFunc(CallFunc_t *func, ClassInfo_t *info, const char *method, const char *params, Longptr_t *Offset) const final
Definition TCling.cxx:8086
std::vector< std::string > GetUsingNamespaces(ClassInfo_t *cl) const final
Get the scopes representing using declarations of namespace.
Definition TCling.cxx:4513
const char * ClassInfo_FileName(ClassInfo_t *info) const final
Definition TCling.cxx:8464
void FuncTempInfo_Title(FuncTempInfo_t *, TString &name) const final
Return the comments associates with this function template.
Definition TCling.cxx:9018
const char * ClassInfo_TmpltName(ClassInfo_t *info) const final
Definition TCling.cxx:8498
void SaveContext() final
Save the current Cling state.
Definition TCling.cxx:3894
void LoadPCMImpl(TFile &pcmFile)
Tries to load a PCM from TFile; returns true on success.
Definition TCling.cxx:1727
Bool_t IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *nsDecl)
Definition TCling.cxx:6661
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:3775
void CodeComplete(const std::string &, size_t &, std::vector< std::string > &) final
The call to Cling's tab complition.
Definition TCling.cxx:7716
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:3789
const char * MapCppName(const char *) const final
Interface to cling function.
Definition TCling.cxx:7569
Longptr_t Calc(const char *line, EErrorCode *error=nullptr) final
Directly execute an executable statement (e.g.
Definition TCling.cxx:3620
Int_t ReloadAllSharedLibraryMaps() final
Reload the library map entries coming from all the loaded shared libraries, after first unloading the...
Definition TCling.cxx:5972
void UpdateListOfGlobalFunctions() final
No op: see TClingCallbacks (used to update the list of global functions)
Definition TCling.cxx:3927
void DataMemberInfo_Delete(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8640
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:5451
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:4551
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:2717
Int_t SetClassSharedLibs(const char *cls, const char *libs) final
Register the AutoLoading information for a class.
Definition TCling.cxx:6113
MethodInfo_t * MethodInfo_FactoryCopy(MethodInfo_t *minfo) const final
Definition TCling.cxx:9091
std::set< const char * > fParsedPayloadsAddresses
Definition TCling.h:123
CallFuncIFacePtr_t CallFunc_IFacePtr(CallFunc_t *func) const final
Definition TCling.cxx:8006
MethodArgInfo_t * MethodArgInfo_Factory() const final
Definition TCling.cxx:9296
static void UpdateClassInfo(char *name, Long_t tagnum)
No op: see TClingCallbacks.
Definition TCling.cxx:6785
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:5064
void ClassInfo_Delete(ClassInfo_t *info) const final
Definition TCling.cxx:8232
std::unique_ptr< cling::Interpreter > fInterpreter
Definition TCling.h:130
EDataType ClassInfo_GetUnderlyingType(ClassInfo_t *info) const final
Definition TCling.cxx:8359
void FuncTempInfo_Delete(FuncTempInfo_t *) const final
Delete the FuncTempInfo_t.
Definition TCling.cxx:8854
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:5212
Int_t DeleteVariable(const char *name) final
Undeclare obj called name.
Definition TCling.cxx:3833
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:7141
Longptr_t DataMemberInfo_Offset(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8698
CallFunc_t * CallFunc_Factory() const final
Definition TCling.cxx:7957
MethodInfo_t * MethodInfo_Factory() const final
Definition TCling.cxx:9066
Long_t DataMemberInfo_TypeProperty(DataMemberInfo_t *dminfo) const final
Definition TCling.cxx:8714
void ClearFileBusy() final
Reset the interpreter internal state in case a previous action was not correctly terminated.
Definition TCling.cxx:3112
cling::MetaProcessor * GetMetaProcessorImpl() const
Definition TCling.h:644
bool DiagnoseIfInterpreterException(const std::exception &e) const final
Definition TCling.cxx:2475
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:7592
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:3103
void AddAvailableIndentifiers(TSeqCollection &Idents) final
Definition TCling.cxx:2391
void TypedefInfo_Delete(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9490
void Reset() final
Pressing Ctrl+C should forward here.
Definition TCling.cxx:3743
const char * TypedefInfo_TrueName(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9562
int SetClassAutoLoading(int) const final
Enable/Disable the AutoLoading of libraries.
Definition TCling.cxx:7613
const char * ClassInfo_FullName(ClassInfo_t *info) const final
Definition TCling.cxx:8472
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:6416
const char * MethodInfo_TypeName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9195
void CallFunc_SetArg(CallFunc_t *func, Long_t param) const final
Definition TCling.cxx:8022
const char * GetIncludePath() final
Refresh the list of include paths known to the interpreter and return it with -I prepended.
Definition TCling.cxx:7416
void UpdateListsOnUnloaded(const cling::Transaction &T)
Invalidate stored TCling state for declarations included in transaction ‘T’.
Definition TCling.cxx:6895
void UpdateClassInfoWithDecl(const clang::NamedDecl *ND)
Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
Definition TCling.cxx:6727
bool IsSameType(const void *QualTypePtr1, const void *QualTypePtr2) const
Definition TCling.cxx:9586
void Initialize() final
Initialize the interpreter, once TROOT::fInterpreter is set.
Definition TCling.cxx:1664
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:8293
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:4806
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:9005
std::unique_ptr< cling::MetaProcessor > fMetaProcessor
Definition TCling.h:131
bool TypeInfo_IsValid(TypeInfo_t *tinfo) const final
Definition TCling.cxx:9428
bool RegisterPrebuiltModulePath(const std::string &FullPath, const std::string &ModuleMapName="module.modulemap") const final
Definition TCling.cxx:1938
std::string MethodInfo_TypeNormalizedName(MethodInfo_t *minfo) const final
Definition TCling.cxx:9204
const char * ClassInfo_Name(ClassInfo_t *info) const final
Definition TCling.cxx:8482
TClass * GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent=kFALSE) final
Generate a TClass for the given class.
Definition TCling.cxx:4589
ULong64_t fTransactionCount
Definition TCling.h:148
bool ClassInfo_HasDefaultConstructor(ClassInfo_t *info, Bool_t testio=kFALSE) const final
Definition TCling.cxx:8301
void EndOfLineAction() final
It calls a "fantom" method to synchronize user keyboard input and ROOT prompt line.
Definition TCling.cxx:3156
TypeInfo_t * TypeInfo_FactoryCopy(TypeInfo_t *) const final
Definition TCling.cxx:9412
void * TypeInfo_QualTypePtr(TypeInfo_t *tinfo) const
Definition TCling.cxx:9476
bool ClassInfo_HasMethod(ClassInfo_t *info, const char *name) const final
Definition TCling.cxx:8309
void ClassInfo_DeleteArray(ClassInfo_t *info, void *arena, bool dtorOnly) const final
Definition TCling.cxx:8247
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:8738
void ShutDown() final
Definition TCling.cxx:1685
void UpdateListOfTypes() final
No op: see TClingCallbacks (used to update the list of types)
Definition TCling.cxx:3934
Long_t TypedefInfo_Property(TypedefInfo_t *tinfo) const final
Definition TCling.cxx:9546
void RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
Register Rdict data for future loading by LoadPCM;.
Definition TCling.cxx:1708
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:3604
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:5024
static void UpdateAllCanvases()
Update all canvases at end the terminal input command.
Definition TCling.cxx:6800
Int_t LoadLibraryMap(const char *rootmapfile=nullptr) final
Load map between class and library.
Definition TCling.cxx:5776
Longptr_t BaseClassInfo_Tagnum(BaseClassInfo_t *bcinfo) const final
Definition TCling.cxx:8593
void LibraryUnloaded(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:7027
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:205
R__ALWAYS_INLINE Bool_t IsOnHeap() const
Definition TObject.h:158
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:1057
virtual TObject * FindObject(const char *name) const
Must be redefined in derived classes.
Definition TObject.cxx:421
static TClass * Class()
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1071
virtual void Fatal(const char *method, const char *msgfmt,...) const
Issue fatal error message.
Definition TObject.cxx:1099
virtual TClass * IsA() const
Definition TObject.h:249
void MakeZombie()
Definition TObject.h:53
@ kInvalidObject
if object ctor succeeded but object should not be used
Definition TObject.h:78
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition TObject.cxx:1045
Persistent version of a TClass.
Definition TProtoClass.h:38
static const TString & GetIncludeDir()
Get the include directory in the installation. Static utility function.
Definition TROOT.cxx:3072
static const char * GetMacroPath()
Get macro search path. Static utility function.
Definition TROOT.cxx:2790
static const std::vector< std::string > & AddExtraInterpreterArgs(const std::vector< std::string > &args)
Provide command line arguments to the interpreter construction.
Definition TROOT.cxx:2982
static const TString & GetEtcDir()
Get the sysconfig directory in the installation. Static utility function.
Definition TROOT.cxx:3082
static const char **& GetExtraInterpreterArgs()
INTERNAL function! Used by rootcling to inject interpreter arguments through a C-interface layer.
Definition TROOT.cxx:2992
static const TString & GetSharedLibDir()
Get the shared libraries directory in the installation. Static utility function.
Definition TROOT.cxx:3061
Sequenceable collection abstract base class.
Int_t LastIndex() const
Describes a persistent version of a class.
Basic string class.
Definition TString.h:139
Ssiz_t Length() const
Definition TString.h:417
const char * Data() const
Definition TString.h:376
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:704
Bool_t IsNull() const
Definition TString.h:414
TString & Append(const char *cs)
Definition TString.h:572
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:2378
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:632
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition TSystem.cxx:1286
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:1677
virtual const char * GetIncludePath()
Get the list of include path.
Definition TSystem.cxx:3986
virtual TString SplitAclicMode(const char *filename, TString &mode, TString &args, TString &io) const
This method split a filename of the form:
Definition TSystem.cxx:4271
virtual char * ConcatFileName(const char *dir, const char *name)
Concatenate a directory and a file name. User must delete returned string.
Definition TSystem.cxx:1083
virtual const char * FindFile(const char *search, TString &file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition TSystem.cxx:1550
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition TSystem.cxx:1869
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:1410
virtual const char * PrependPathName(const char *dir, TString &name)
Concatenate a directory and a file name.
Definition TSystem.cxx:1093
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:1308
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:2501
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:1807
virtual const char * FindDynamicLibrary(TString &lib, Bool_t quiet=kFALSE)
Find a dynamic library using the system search paths.
Definition TSystem.cxx:2046
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:2848
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:1560
virtual void Setenv(const char *name, const char *value)
Set environment variable.
Definition TSystem.cxx:1661
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:2032
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
std::ostream & Info()
Definition hadd.cxx:171
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.
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
R__EXTERN TVirtualRWMutex * gCoreMutex
@ kWarning
Warnings about likely unexpected behavior.
EFunctionMatchMode
@ kExactMatch
bool IsStdPairBase(std::string_view name)
Definition TClassEdit.h:235
bool IsStdArray(std::string_view name)
Definition TClassEdit.h:230
bool IsStdClass(const char *type)
return true if the class belongs to the std namespace
bool IsStdPair(std::string_view name)
Definition TClassEdit.h:231
std::string InsertStd(const char *tname)
std::string GetLong64_Name(const char *original)
Replace 'long long' and 'unsigned long long' by 'Long64_t' and 'ULong64_t'.
char * DemangleTypeIdName(const std::type_info &ti, int &errorCode)
Demangle in a portable way the type id name.
const char * GetUnqualifiedName(const char *name)
Return the start of the unqualified name include in 'original'.
void Init(TClassEdit::TInterpreterLookupHelper *helper)
ROOT::ESTLType IsSTLCont(std::string_view type)
type : type name: vector<list<classA,allocator>,allocator> result: 0 : not stl container code of cont...
char * DemangleName(const char *mangled_name, int &errorCode)
Definition TClassEdit.h:255
int GetSplit(const char *type, std::vector< std::string > &output, int &nestedLoc, EModType mode=TClassEdit::kNone)
Stores in output (after emptying it) the split type.
@ kDropStlDefault
Definition TClassEdit.h:83
EComplexType GetComplexType(const char *)
static const char * what
Definition stlLoader.cc:5
Int_t fMode
Definition TSystem.h:135
RAII used to store Parser, Sema, Preprocessor state for recursive parsing.
Definition ClingRAII.h:22
std::unique_ptr< ROOT::TVirtualRWMutex::State > fState
State of gCoreMutex when the first interpreter-related function was invoked.
Definition TCling.h:157
Int_t fRecurseCount
Interpreter-related functions will push the "entry" lock state to *this.
Definition TCling.h:162
A read-only memory range which we do not control.
Definition TMemFile.h:23
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4
static void output()