Logo ROOT  
Reference Guide
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 "llvm/IR/GlobalValue.h"
119#include "llvm/IR/Module.h"
120
121#include "llvm/Support/DynamicLibrary.h"
122#include "llvm/Support/raw_ostream.h"
123#include "llvm/Support/Path.h"
124#include "llvm/Support/Process.h"
125#include "llvm/Object/ELFObjectFile.h"
126#include "llvm/Object/ObjectFile.h"
127#include "llvm/Object/SymbolicFile.h"
128#include "llvm/Support/FileSystem.h"
129
130#include <algorithm>
131#include <iostream>
132#include <cassert>
133#include <map>
134#include <set>
135#include <stdexcept>
136#include <stdint.h>
137#include <fstream>
138#include <sstream>
139#include <string>
140#include <tuple>
141#include <typeinfo>
142#include <unordered_map>
143#include <unordered_set>
144#include <utility>
145#include <vector>
146#include <functional>
147
148#ifndef R__WIN32
149#include <cxxabi.h>
150#define R__DLLEXPORT __attribute__ ((visibility ("default")))
151#include <sys/stat.h>
152#endif
153#include <limits.h>
154#include <stdio.h>
155
156#ifdef __APPLE__
157#include <dlfcn.h>
158#include <mach-o/dyld.h>
159#include <mach-o/loader.h>
160#endif // __APPLE__
161
162#ifdef R__UNIX
163#include <dlfcn.h>
164#endif
165
166#ifdef R__LINUX
167# ifndef _GNU_SOURCE
168# define _GNU_SOURCE
169# endif
170# include <link.h> // dl_iterate_phdr()
171#endif
172
173#if defined(__CYGWIN__)
174#include <sys/cygwin.h>
175#define HMODULE void *
176extern "C" {
177 __declspec(dllimport) void * __stdcall GetCurrentProcess();
178 __declspec(dllimport) bool __stdcall EnumProcessModules(void *, void **, unsigned long, unsigned long *);
179 __declspec(dllimport) unsigned long __stdcall GetModuleFileNameExW(void *, void *, wchar_t *, unsigned long);
180}
181#endif
182
183// Fragment copied from LLVM's raw_ostream.cpp
184#if defined(_MSC_VER)
185#ifndef STDIN_FILENO
186# define STDIN_FILENO 0
187#endif
188#ifndef STDOUT_FILENO
189# define STDOUT_FILENO 1
190#endif
191#ifndef STDERR_FILENO
192# define STDERR_FILENO 2
193#endif
194#ifndef R__WIN32
195//#if defined(HAVE_UNISTD_H)
196# include <unistd.h>
197//#endif
198#else
199#include "Windows4Root.h"
200#include <Psapi.h>
201#undef GetModuleFileName
202#define RTLD_DEFAULT ((void *)::GetModuleHandle(NULL))
203#define dlsym(library, function_name) ::GetProcAddress((HMODULE)library, function_name)
204#define dlopen(library_name, flags) ::LoadLibraryA(library_name)
205#define dlclose(library) ::FreeLibrary((HMODULE)library)
206#define R__DLLEXPORT __declspec(dllexport)
207#endif
208#endif
209
210//______________________________________________________________________________
211// These functions are helpers for debugging issues with non-LLVMDEV builds.
212//
213R__DLLEXPORT clang::DeclContext* TCling__DEBUG__getDeclContext(clang::Decl* D) {
214 return D->getDeclContext();
215}
216R__DLLEXPORT clang::NamespaceDecl* TCling__DEBUG__DCtoNamespace(clang::DeclContext* DC) {
217 return llvm::dyn_cast<clang::NamespaceDecl>(DC);
218}
219R__DLLEXPORT clang::RecordDecl* TCling__DEBUG__DCtoRecordDecl(clang::DeclContext* DC) {
220 return llvm::dyn_cast<clang::RecordDecl>(DC);
221}
222R__DLLEXPORT void TCling__DEBUG__dump(clang::DeclContext* DC) {
223 return DC->dumpDeclContext();
224}
225R__DLLEXPORT void TCling__DEBUG__dump(clang::Decl* D) {
226 return D->dump();
227}
228R__DLLEXPORT void TCling__DEBUG__dump(clang::FunctionDecl* FD) {
229 return FD->dump();
230}
232 return ((clang::Decl*)D)->dump();
233}
235 if (clang::NamedDecl* ND = llvm::dyn_cast<clang::NamedDecl>(D)) {
236 std::string name;
237 {
238 llvm::raw_string_ostream OS(name);
239 ND->getNameForDiagnostic(OS, D->getASTContext().getPrintingPolicy(),
240 true /*Qualified*/);
241 }
242 printf("%s\n", name.c_str());
243 }
244}
245//______________________________________________________________________________
246// These functions are helpers for testing issues directly rather than
247// relying on side effects.
248// This is used for the test for ROOT-7462/ROOT-6070
250 return D->isInvalidDecl();
251}
254 assert(info && info->IsValid());
255 return info->GetDecl()->isInvalidDecl();
256}
257
258using namespace std;
259using namespace clang;
260using namespace ROOT;
261
262namespace {
263 static const std::string gInterpreterClassDef = R"ICF(
264#undef ClassDef
265#define ClassDef(name, id) \
266_ClassDefInterp_(name,id,virtual,) \
267static int DeclFileLine() { return __LINE__; }
268#undef ClassDefNV
269#define ClassDefNV(name, id) \
270_ClassDefInterp_(name,id,,) \
271static int DeclFileLine() { return __LINE__; }
272#undef ClassDefOverride
273#define ClassDefOverride(name, id) \
274_ClassDefInterp_(name,id,,override) \
275static int DeclFileLine() { return __LINE__; }
276)ICF";
277
278 static const std::string gNonInterpreterClassDef = R"ICF(
279#define __ROOTCLING__ 1
280#undef ClassDef
281#define ClassDef(name,id) \
282_ClassDefOutline_(name,id,virtual,) \
283static int DeclFileLine() { return __LINE__; }
284#undef ClassDefNV
285#define ClassDefNV(name, id)\
286_ClassDefOutline_(name,id,,)\
287static int DeclFileLine() { return __LINE__; }
288#undef ClassDefOverride
289#define ClassDefOverride(name, id)\
290_ClassDefOutline_(name,id,,override)\
291static int DeclFileLine() { return __LINE__; }
292)ICF";
293
294// The macros below use ::Error, so let's ensure it is included
295 static const std::string gClassDefInterpMacro = R"ICF(
296#include "TError.h"
297
298#define _ClassDefInterp_(name,id,virtual_keyword, overrd) \
299private: \
300public: \
301 static TClass *Class() { static TClass* sIsA = 0; if (!sIsA) sIsA = TClass::GetClass(#name); return sIsA; } \
302 static const char *Class_Name() { return #name; } \
303 virtual_keyword Bool_t CheckTObjectHashConsistency() const overrd { return true; } \
304 static Version_t Class_Version() { return id; } \
305 static TClass *Dictionary() { return 0; } \
306 virtual_keyword TClass *IsA() const overrd { return name::Class(); } \
307 virtual_keyword void ShowMembers(TMemberInspector&insp) const overrd { ::ROOT::Class_ShowMembers(name::Class(), this, insp); } \
308 virtual_keyword void Streamer(TBuffer&) overrd { ::Error("Streamer", "Cannot stream interpreted class."); } \
309 void StreamerNVirtual(TBuffer&ClassDef_StreamerNVirtual_b) { name::Streamer(ClassDef_StreamerNVirtual_b); } \
310 static const char *DeclFileName() { return __FILE__; } \
311 static int ImplFileLine() { return 0; } \
312 static const char *ImplFileName() { return __FILE__; }
313)ICF";
314}
316
317// The functions are used to bridge cling/clang/llvm compiled with no-rtti and
318// ROOT (which uses rtti)
319
320////////////////////////////////////////////////////////////////////////////////
321/// Print a StackTrace!
322
323extern "C"
326}
327
328////////////////////////////////////////////////////////////////////////////////
329/// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
330
331extern "C" void TCling__RestoreInterpreterMutex(void *delta)
332{
333 ((TCling*)gCling)->ApplyToInterpreterMutex(delta);
334}
335
336////////////////////////////////////////////////////////////////////////////////
337/// Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name,
338/// which is extracted by error messages we get from callback from cling. Return true
339/// when the missing library was autoloaded.
340
341extern "C" bool TCling__LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
342{
343 return ((TCling*)gCling)->LibraryLoadingFailed(errmessage, libStem, permanent, resolved);
344}
345
346////////////////////////////////////////////////////////////////////////////////
347/// Reset the interpreter lock to the state it had before interpreter-related
348/// calls happened.
349
351{
352 return ((TCling*)gCling)->RewindInterpreterMutex();
353}
354
355////////////////////////////////////////////////////////////////////////////////
356/// Lock the interpreter.
357
359{
360 if (gInterpreterMutex) {
362 }
363 return nullptr;
364}
365
366////////////////////////////////////////////////////////////////////////////////
367/// Unlock the interpreter.
368
370{
371 if (gInterpreterMutex) {
373 }
374}
375
376////////////////////////////////////////////////////////////////////////////////
377/// Update TClingClassInfo for a class (e.g. upon seeing a definition).
378
379static void TCling__UpdateClassInfo(const NamedDecl* TD)
380{
381 static Bool_t entered = kFALSE;
382 static vector<const NamedDecl*> updateList;
383 Bool_t topLevel;
384
385 if (entered) topLevel = kFALSE;
386 else {
387 entered = kTRUE;
388 topLevel = kTRUE;
389 }
390 if (topLevel) {
391 ((TCling*)gInterpreter)->UpdateClassInfoWithDecl(TD);
392 } else {
393 // If we are called indirectly from within another call to
394 // TCling::UpdateClassInfo, we delay the update until the dictionary loading
395 // is finished (i.e. when we return to the top level TCling::UpdateClassInfo).
396 // This allows for the dictionary to be fully populated when we actually
397 // update the TClass object. The updating of the TClass sometimes
398 // (STL containers and when there is an emulated class) forces the building
399 // of the TClass object's real data (which needs the dictionary info).
400 updateList.push_back(TD);
401 }
402 if (topLevel) {
403 while (!updateList.empty()) {
404 ((TCling*)gInterpreter)->UpdateClassInfoWithDecl(updateList.back());
405 updateList.pop_back();
406 }
407 entered = kFALSE;
408 }
409}
410
411void TCling::UpdateEnumConstants(TEnum* enumObj, TClass* cl) const {
412 const clang::Decl* D = static_cast<const clang::Decl*>(enumObj->GetDeclId());
413 if(const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(D)) {
414 // Add the constants to the enum type.
415 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(),
416 EDE = ED->enumerator_end(); EDI != EDE; ++EDI) {
417 // Get name of the enum type.
418 std::string constbuf;
419 if (const NamedDecl* END = llvm::dyn_cast<NamedDecl>(*EDI)) {
420 PrintingPolicy Policy((*EDI)->getASTContext().getPrintingPolicy());
421 llvm::raw_string_ostream stream(constbuf);
422 // Don't trigger fopen of the source file to count lines:
423 Policy.AnonymousTagLocations = false;
424 (END)->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
425 }
426 const char* constantName = constbuf.c_str();
427
428 // Get value of the constant.
430 const llvm::APSInt valAPSInt = (*EDI)->getInitVal();
431 if (valAPSInt.isSigned()) {
432 value = valAPSInt.getSExtValue();
433 } else {
434 value = valAPSInt.getZExtValue();
435 }
436
437 // Create the TEnumConstant or update it if existing
438 TEnumConstant* enumConstant = nullptr;
439 TClingClassInfo* tcCInfo = (TClingClassInfo*)(cl ? cl->GetClassInfo() : 0);
440 TClingDataMemberInfo* tcDmInfo = new TClingDataMemberInfo(GetInterpreterImpl(), *EDI, tcCInfo);
441 DataMemberInfo_t* dmInfo = (DataMemberInfo_t*) tcDmInfo;
442 if (TObject* encAsTObj = enumObj->GetConstants()->FindObject(constantName)){
443 ((TEnumConstant*)encAsTObj)->Update(dmInfo);
444 } else {
445 enumConstant = new TEnumConstant(dmInfo, constantName, value, enumObj);
446 }
447
448 // Add the global constants to the list of Globals.
449 if (!cl) {
450 TCollection* globals = gROOT->GetListOfGlobals(false);
451 if (!globals->FindObject(constantName)) {
452 globals->Add(enumConstant);
453 }
454 }
455 }
456 }
457}
458
459TEnum* TCling::CreateEnum(void *VD, TClass *cl) const
460{
461 // Handle new enum declaration for either global and nested enums.
462
463 // Create the enum type.
464 TEnum* enumType = 0;
465 const clang::Decl* D = static_cast<const clang::Decl*>(VD);
466 std::string buf;
467 if (const EnumDecl* ED = llvm::dyn_cast<EnumDecl>(D)) {
468 // Get name of the enum type.
469 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
470 llvm::raw_string_ostream stream(buf);
471 // Don't trigger fopen of the source file to count lines:
472 Policy.AnonymousTagLocations = false;
473 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
474 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
475 }
476 if (buf.empty()) {
477 return 0;
478 }
479 const char* name = buf.c_str();
480 enumType = new TEnum(name, VD, cl);
481 UpdateEnumConstants(enumType, cl);
482
483 return enumType;
484}
485
486void TCling::HandleNewDecl(const void* DV, bool isDeserialized, std::set<TClass*> &modifiedTClasses) {
487 // Handle new declaration.
488 // Record the modified class, struct and namespaces in 'modifiedTClasses'.
489
490 const clang::Decl* D = static_cast<const clang::Decl*>(DV);
491
492 if (!D->isCanonicalDecl() && !isa<clang::NamespaceDecl>(D)
493 && !dyn_cast<clang::RecordDecl>(D)) return;
494
495 if (isa<clang::FunctionDecl>(D->getDeclContext())
496 || isa<clang::TagDecl>(D->getDeclContext()))
497 return;
498
499 // Don't list templates.
500 if (const clang::CXXRecordDecl* RD = dyn_cast<clang::CXXRecordDecl>(D)) {
501 if (RD->getDescribedClassTemplate())
502 return;
503 } else if (const clang::FunctionDecl* FD = dyn_cast<clang::FunctionDecl>(D)) {
504 if (FD->getDescribedFunctionTemplate())
505 return;
506 }
507
508 if (const RecordDecl *TD = dyn_cast<RecordDecl>(D)) {
509 if (TD->isCanonicalDecl() || TD->isThisDeclarationADefinition())
511 }
512 else if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
513
514 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
515 // Mostly just for EnumDecl (the other TagDecl are handled
516 // by the 'RecordDecl' if statement.
518 } else if (const NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(D)) {
520 }
521
522 // We care about declarations on the global scope.
523 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
524 return;
525
526 // Enums are lazyly created, thus we don not need to handle them here.
527 if (isa<EnumDecl>(ND))
528 return;
529
530 // ROOT says that global is enum(lazylycreated)/var/field declared on the global
531 // scope.
532 if (!(isa<VarDecl>(ND)))
533 return;
534
535 // Skip if already in the list.
536 if (gROOT->GetListOfGlobals()->FindObject(ND->getNameAsString().c_str()))
537 return;
538
539 // Put the global constants and global enums in the corresponding lists.
540 gROOT->GetListOfGlobals()->Add(new TGlobal((DataMemberInfo_t *)
542 cast<ValueDecl>(ND), 0)));
543 }
544}
545
546extern "C"
548{
549 // We are sure in this context of the type of the interpreter
550 normCtxt = &( (TCling*) gInterpreter)->GetNormalizedContext();
551}
552
553extern "C"
554void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter*) {
555 ((TCling*)gCling)->UpdateListsOnCommitted(T);
556}
557
558extern "C"
559void TCling__UpdateListsOnUnloaded(const cling::Transaction &T) {
560 ((TCling*)gCling)->UpdateListsOnUnloaded(T);
561}
562
563extern "C"
564void TCling__InvalidateGlobal(const clang::Decl *D) {
565 ((TCling*)gCling)->InvalidateGlobal(D);
566}
567
568extern "C"
569void TCling__TransactionRollback(const cling::Transaction &T) {
570 ((TCling*)gCling)->TransactionRollback(T);
571}
572
573extern "C" void TCling__LibraryLoadedRTTI(const void* dyLibHandle,
574 const char* canonicalName) {
575 ((TCling*)gCling)->LibraryLoaded(dyLibHandle, canonicalName);
576}
577
578extern "C" void TCling__RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
579{
580 ((TCling *)gCling)->RegisterRdictForLoadPCM(pcmFileNameFullPath, pcmContent);
581}
582
583extern "C" void TCling__LibraryUnloadedRTTI(const void* dyLibHandle,
584 const char* canonicalName) {
585 ((TCling*)gCling)->LibraryUnloaded(dyLibHandle, canonicalName);
586}
587
588
589extern "C"
590TObject* TCling__GetObjectAddress(const char *Name, void *&LookupCtx) {
591 return ((TCling*)gCling)->GetObjectAddress(Name, LookupCtx);
592}
593
594extern "C" const Decl* TCling__GetObjectDecl(TObject *obj) {
595 return ((TClingClassInfo*)obj->IsA()->GetClassInfo())->GetDecl();
596}
597
598extern "C" R__DLLEXPORT TInterpreter *CreateInterpreter(void* interpLibHandle,
599 const char* argv[])
600{
601 auto tcling = new TCling("C++", "cling C++ Interpreter", argv);
602 cling::DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(interpLibHandle);
603 return tcling;
604}
605
607{
608 delete interp;
609}
610
611// Load library containing specified class. Returns 0 in case of error
612// and 1 in case if success.
613extern "C" int TCling__AutoLoadCallback(const char* className)
614{
615 return ((TCling*)gCling)->AutoLoad(className);
616}
617
618extern "C" int TCling__AutoParseCallback(const char* className)
619{
620 return ((TCling*)gCling)->AutoParse(className);
621}
622
623extern "C" const char* TCling__GetClassSharedLibs(const char* className)
624{
625 return ((TCling*)gCling)->GetClassSharedLibs(className);
626}
627
628// Returns 0 for failure 1 for success
629extern "C" int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl* nsDecl)
630{
631 return ((TCling*)gCling)->IsAutoLoadNamespaceCandidate(nsDecl);
632}
633
634extern "C" int TCling__CompileMacro(const char *fileName, const char *options)
635{
636 string file(fileName);
637 string opt(options);
638 return gSystem->CompileMacro(file.c_str(), opt.c_str());
639}
640
641extern "C" void TCling__SplitAclicMode(const char* fileName, string &mode,
642 string &args, string &io, string &fname)
643{
644 string file(fileName);
645 TString f, amode, arguments, aclicio;
646 f = gSystem->SplitAclicMode(file.c_str(), amode, arguments, aclicio);
647 mode = amode.Data(); args = arguments.Data();
648 io = aclicio.Data(); fname = f.Data();
649}
650
651//______________________________________________________________________________
652//
653//
654//
655
656#ifdef R__WIN32
657extern "C" {
658 char *__unDName(char *demangled, const char *mangled, int out_len,
659 void * (* pAlloc )(size_t), void (* pFree )(void *),
660 unsigned short int flags);
661}
662#endif
663
664////////////////////////////////////////////////////////////////////////////////
665/// Find a template decl within N nested namespaces, 0<=N<inf
666/// Assumes 1 and only 1 template present and 1 and only 1 entity contained
667/// by the namespace. Example: `ns1::ns2::..::%nsN::%myTemplate`
668/// Returns nullptr in case of error
669
670static clang::ClassTemplateDecl* FindTemplateInNamespace(clang::Decl* decl)
671{
672 using namespace clang;
673 if (NamespaceDecl* nsd = llvm::dyn_cast<NamespaceDecl>(decl)){
674 return FindTemplateInNamespace(*nsd->decls_begin());
675 }
676
677 if (ClassTemplateDecl* ctd = llvm::dyn_cast<ClassTemplateDecl>(decl)){
678 return ctd;
679 }
680
681 return nullptr; // something went wrong.
682}
683
684////////////////////////////////////////////////////////////////////////////////
685/// Autoload a library provided the mangled name of a missing symbol.
686
687void* llvmLazyFunctionCreator(const std::string& mangled_name)
688{
689 return ((TCling*)gCling)->LazyFunctionCreatorAutoload(mangled_name);
690}
691
692//______________________________________________________________________________
693//
694//
695//
696
697int TCling_GenerateDictionary(const std::vector<std::string> &classes,
698 const std::vector<std::string> &headers,
699 const std::vector<std::string> &fwdDecls,
700 const std::vector<std::string> &unknown)
701{
702 //This function automatically creates the "LinkDef.h" file for templated
703 //classes then executes CompileMacro on it.
704 //The name of the file depends on the class name, and it's not generated again
705 //if the file exist.
706 if (classes.empty()) {
707 return 0;
708 }
709 // Use the name of the first class as the main name.
710 const std::string& className = classes[0];
711 //(0) prepare file name
712 TString fileName = "AutoDict_";
713 std::string::const_iterator sIt;
714 for (sIt = className.begin(); sIt != className.end(); ++sIt) {
715 if (*sIt == '<' || *sIt == '>' ||
716 *sIt == ' ' || *sIt == '*' ||
717 *sIt == ',' || *sIt == '&' ||
718 *sIt == ':') {
719 fileName += '_';
720 }
721 else {
722 fileName += *sIt;
723 }
724 }
725 if (classes.size() > 1) {
726 Int_t chk = 0;
727 std::vector<std::string>::const_iterator it = classes.begin();
728 while ((++it) != classes.end()) {
729 for (UInt_t cursor = 0; cursor != it->length(); ++cursor) {
730 chk = chk * 3 + it->at(cursor);
731 }
732 }
733 fileName += TString::Format("_%u", chk);
734 }
735 fileName += ".cxx";
736 if (gSystem->AccessPathName(fileName) != 0) {
737 //file does not exist
738 //(1) prepare file data
739 // If STL, also request iterators' operators.
740 // vector is special: we need to check whether
741 // vector::iterator is a typedef to pointer or a
742 // class.
743 static const std::set<std::string> sSTLTypes {
744 "vector","list","forward_list","deque","map","unordered_map","multimap",
745 "unordered_multimap","set","unordered_set","multiset","unordered_multiset",
746 "queue","priority_queue","stack","iterator"};
747 std::vector<std::string>::const_iterator it;
748 std::string fileContent("");
749 for (it = headers.begin(); it != headers.end(); ++it) {
750 fileContent += "#include \"" + *it + "\"\n";
751 }
752 for (it = unknown.begin(); it != unknown.end(); ++it) {
753 TClass* cl = TClass::GetClass(it->c_str());
754 if (cl && cl->GetDeclFileName()) {
755 TString header = gSystem->BaseName(cl->GetDeclFileName());
757 TString dirbase(gSystem->BaseName(dir));
758 while (dirbase.Length() && dirbase != "."
759 && dirbase != "include" && dirbase != "inc"
760 && dirbase != "prec_stl") {
761 gSystem->PrependPathName(dirbase, header);
762 dir = gSystem->GetDirName(dir);
763 }
764 fileContent += TString("#include \"") + header + "\"\n";
765 }
766 }
767 for (it = fwdDecls.begin(); it != fwdDecls.end(); ++it) {
768 fileContent += "class " + *it + ";\n";
769 }
770 fileContent += "#ifdef __CLING__ \n";
771 fileContent += "#pragma link C++ nestedclasses;\n";
772 fileContent += "#pragma link C++ nestedtypedefs;\n";
773 for (it = classes.begin(); it != classes.end(); ++it) {
774 std::string n(*it);
775 size_t posTemplate = n.find('<');
776 std::set<std::string>::const_iterator iSTLType = sSTLTypes.end();
777 if (posTemplate != std::string::npos) {
778 n.erase(posTemplate, std::string::npos);
779 if (n.compare(0, 5, "std::") == 0) {
780 n.erase(0, 5);
781 }
782 iSTLType = sSTLTypes.find(n);
783 }
784 fileContent += "#pragma link C++ class ";
785 fileContent += *it + "+;\n" ;
786 fileContent += "#pragma link C++ class ";
787 if (iSTLType != sSTLTypes.end()) {
788 // STL class; we cannot (and don't need to) store iterators;
789 // their shadow and the compiler's version don't agree. So
790 // don't ask for the '+'
791 fileContent += *it + "::*;\n" ;
792 }
793 else {
794 // Not an STL class; we need to allow the I/O of contained
795 // classes (now that we have a dictionary for them).
796 fileContent += *it + "::*+;\n" ;
797 }
798 }
799 fileContent += "#endif\n";
800 //end(1)
801 //(2) prepare the file
802 FILE* filePointer;
803 filePointer = fopen(fileName, "w");
804 if (filePointer == NULL) {
805 //can't open a file
806 return 1;
807 }
808 //end(2)
809 //write data into the file
810 fprintf(filePointer, "%s", fileContent.c_str());
811 fclose(filePointer);
812 }
813 //(3) checking if we can compile a macro, if not then cleaning
814 Int_t oldErrorIgnoreLevel = gErrorIgnoreLevel;
815 gErrorIgnoreLevel = kWarning; // no "Info: creating library..."
816 Int_t ret = gSystem->CompileMacro(fileName, "k");
817 gErrorIgnoreLevel = oldErrorIgnoreLevel;
818 if (ret == 0) { //can't compile a macro
819 return 2;
820 }
821 //end(3)
822 return 0;
823}
824
825int TCling_GenerateDictionary(const std::string& className,
826 const std::vector<std::string> &headers,
827 const std::vector<std::string> &fwdDecls,
828 const std::vector<std::string> &unknown)
829{
830 //This function automatically creates the "LinkDef.h" file for templated
831 //classes then executes CompileMacro on it.
832 //The name of the file depends on the class name, and it's not generated again
833 //if the file exist.
834 std::vector<std::string> classes;
835 classes.push_back(className);
836 return TCling_GenerateDictionary(classes, headers, fwdDecls, unknown);
837}
838
839//______________________________________________________________________________
840//
841//
842//
843
844// It is a "fantom" method to synchronize user keyboard input
845// and ROOT prompt line (for WIN32)
846const char* fantomline = "TRint::EndOfLineAction();";
847
848//______________________________________________________________________________
849//
850//
851//
852
854
855//______________________________________________________________________________
856//
857// llvm error handler through exceptions; see also cling/UserInterface
858//
859namespace {
860 // Handle fatal llvm errors by throwing an exception.
861 // Yes, throwing exceptions in error handlers is bad.
862 // Doing nothing is pretty terrible, too.
863 void exceptionErrorHandler(void * /*user_data*/,
864 const std::string& reason,
865 bool /*gen_crash_diag*/) {
866 throw std::runtime_error(std::string(">>> Interpreter compilation error:\n") + reason);
867 }
868}
869
870//______________________________________________________________________________
871//
872//
873//
874
875////////////////////////////////////////////////////////////////////////////////
876
877namespace{
878 // An instance of this class causes the diagnostics of clang to be suppressed
879 // during its lifetime
880 class clangDiagSuppr {
881 public:
882 clangDiagSuppr(clang::DiagnosticsEngine& diag): fDiagEngine(diag){
883 fOldDiagValue = fDiagEngine.getIgnoreAllWarnings();
884 fDiagEngine.setIgnoreAllWarnings(true);
885 }
886
887 ~clangDiagSuppr() {
888 fDiagEngine.setIgnoreAllWarnings(fOldDiagValue);
889 }
890 private:
891 clang::DiagnosticsEngine& fDiagEngine;
892 bool fOldDiagValue;
893 };
894
895}
896
897////////////////////////////////////////////////////////////////////////////////
898/// Allow calling autoparsing from TMetaUtils
900{
901 return gCling->AutoParse(cname);
902}
903
904////////////////////////////////////////////////////////////////////////////////
905/// Try hard to avoid looking up in the Cling database as this could enduce
906/// an unwanted autoparsing.
907
908bool TClingLookupHelper__ExistingTypeCheck(const std::string &tname,
909 std::string &result)
910{
911 result.clear();
912
913 unsigned long offset = 0;
914 if (strncmp(tname.c_str(), "const ", 6) == 0) {
915 offset = 6;
916 }
917 unsigned long end = tname.length();
918 while( end && (tname[end-1]=='&' || tname[end-1]=='*' || tname[end-1]==']') ) {
919 if ( tname[end-1]==']' ) {
920 --end;
921 while ( end && tname[end-1]!='[' ) --end;
922 }
923 --end;
924 }
925 std::string innerbuf;
926 const char *inner;
927 if (end != tname.length()) {
928 innerbuf = tname.substr(offset,end-offset);
929 inner = innerbuf.c_str();
930 } else {
931 inner = tname.c_str()+offset;
932 }
933
934 //if (strchr(tname.c_str(),'[')!=0) fprintf(stderr,"DEBUG: checking on %s vs %s %lu %lu\n",tname.c_str(),inner,offset,end);
935 if (gROOT->GetListOfClasses()->FindObject(inner)
936 || TClassTable::Check(inner,result) ) {
937 // This is a known class.
938 return true;
939 }
940
941 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
942 TDataType *type = (TDataType *)typeTable->THashTable::FindObject( inner );
943 if (type) {
944 // This is a raw type and an already loaded typedef.
945 const char *newname = type->GetFullTypeName();
946 if (type->GetType() == kLong64_t) {
947 newname = "Long64_t";
948 } else if (type->GetType() == kULong64_t) {
949 newname = "ULong64_t";
950 }
951 if (strcmp(inner,newname) == 0) {
952 return true;
953 }
954 if (offset) result = "const ";
955 result += newname;
956 if ( end != tname.length() ) {
957 result += tname.substr(end,tname.length()-end);
958 }
959 if (result == tname) result.clear();
960 return true;
961 }
962
963 // Check if the name is an enumerator
964 const auto lastPos = TClassEdit::GetUnqualifiedName(inner);
965 if (lastPos != inner) // Main switch: case 1 - scoped enum, case 2 global enum
966 {
967 // We have a scope
968 // All of this C gymnastic is to avoid allocations on the heap
969 const auto enName = lastPos;
970 const auto scopeNameSize = ((Long64_t)lastPos - (Long64_t)inner) / sizeof(decltype(*lastPos)) - 2;
971 char *scopeName = new char[scopeNameSize + 1];
972 strncpy(scopeName, inner, scopeNameSize);
973 scopeName[scopeNameSize] = '\0';
974 // Check if the scope is in the list of classes
975 if (auto scope = static_cast<TClass *>(gROOT->GetListOfClasses()->FindObject(scopeName))) {
976 auto enumTable = dynamic_cast<const THashList *>(scope->GetListOfEnums(false));
977 if (enumTable && enumTable->THashList::FindObject(enName)) { delete [] scopeName; return true; }
978 }
979 // It may still be in one of the loaded protoclasses
980 else if (auto scope = static_cast<TProtoClass *>(gClassTable->GetProtoNorm(scopeName))) {
981 auto listOfEnums = scope->GetListOfEnums();
982 if (listOfEnums) { // it could be null: no enumerators in the protoclass
983 auto enumTable = dynamic_cast<const THashList *>(listOfEnums);
984 if (enumTable && enumTable->THashList::FindObject(enName)) { delete [] scopeName; return true; }
985 }
986 }
987 delete [] scopeName;
988 } else
989 {
990 // We don't have any scope: this could only be a global enum
991 auto enumTable = dynamic_cast<const THashList *>(gROOT->GetListOfEnums());
992 if (enumTable && enumTable->THashList::FindObject(inner)) return true;
993 }
994
995 if (gCling->GetClassSharedLibs(inner))
996 {
997 // This is a class name.
998 return true;
999 }
1000
1001 return false;
1002}
1003
1004////////////////////////////////////////////////////////////////////////////////
1005
1007{
1008 fContent.reserve(size);
1009}
1010
1011////////////////////////////////////////////////////////////////////////////////
1012
1014{
1015 return fContent.c_str();
1016}
1017
1018////////////////////////////////////////////////////////////////////////////////
1019/// Append string to the storage if not added already.
1020
1021inline bool TCling::TUniqueString::Append(const std::string& str)
1022{
1023 bool notPresent = fLinesHashSet.emplace(fHashFunc(str)).second;
1024 if (notPresent){
1025 fContent+=str;
1026 }
1027 return notPresent;
1028}
1029
1030std::string TCling::ToString(const char* type, void* obj)
1031{
1032 return fInterpreter->toString(type, obj);
1033}
1034
1035////////////////////////////////////////////////////////////////////////////////
1036///\returns true if the module was loaded.
1037static bool LoadModule(const std::string &ModuleName, cling::Interpreter &interp)
1038{
1039 // When starting up ROOT, cling would load all modulemap files on the include
1040 // paths. However, in a ROOT session, it is very common to run aclic which
1041 // will invoke rootcling and possibly produce a modulemap and a module in
1042 // the current folder.
1043 //
1044 // Before failing, try loading the modulemap in the current folder and try
1045 // loading the requested module from it.
1046 std::string currentDir = gSystem->WorkingDirectory();
1047 assert(!currentDir.empty());
1049 if (gDebug > 2)
1050 ::Info("TCling::__LoadModule", "Preloading module %s. \n",
1051 ModuleName.c_str());
1052
1053 return interp.loadModule(ModuleName, /*Complain=*/true);
1054}
1055
1056////////////////////////////////////////////////////////////////////////////////
1057/// Loads the C++ modules that we require to run any ROOT program. This is just
1058/// supposed to make a C++ module from a modulemap available to the interpreter.
1059static void LoadModules(const std::vector<std::string> &modules, cling::Interpreter &interp)
1060{
1061 for (const auto &modName : modules)
1062 LoadModule(modName, interp);
1063}
1064
1065static bool IsFromRootCling() {
1066 // rootcling also uses TCling for generating the dictionary ROOT files.
1067 const static bool foundSymbol = dlsym(RTLD_DEFAULT, "usedToIdentifyRootClingByDlSym");
1068 return foundSymbol;
1069}
1070
1071/// Checks if there is an ASTFile on disk for the given module \c M.
1072static bool HasASTFileOnDisk(clang::Module *M, const clang::Preprocessor &PP, std::string *FullFileName = nullptr)
1073{
1074 const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1075
1076 std::string ModuleFileName;
1077 if (!HSOpts.PrebuiltModulePaths.empty())
1078 // Load the module from *only* in the prebuilt module path.
1079 ModuleFileName = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(M->Name);
1080 if (FullFileName)
1081 *FullFileName = ModuleFileName;
1082
1083 return !ModuleFileName.empty();
1084}
1085
1086static bool HaveFullGlobalModuleIndex = false;
1087static GlobalModuleIndex *loadGlobalModuleIndex(cling::Interpreter &interp)
1088{
1089 CompilerInstance &CI = *interp.getCI();
1090 Preprocessor &PP = CI.getPreprocessor();
1091 auto ModuleManager = CI.getModuleManager();
1092 assert(ModuleManager);
1093 // StringRef ModuleIndexPath = HSI.getModuleCachePath();
1094 // HeaderSearch& HSI = PP.getHeaderSearchInfo();
1095 // HSI.setModuleCachePath(TROOT::GetLibDir().Data());
1096 std::string ModuleIndexPath = TROOT::GetLibDir().Data();
1097 if (ModuleIndexPath.empty())
1098 return nullptr;
1099 // Get an existing global index. This loads it if not already loaded.
1100 ModuleManager->resetForReload();
1101 ModuleManager->loadGlobalIndex();
1102 GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1103
1104 // For finding modules needing to be imported for fixit messages,
1105 // we need to make the global index cover all modules, so we do that here.
1106 if (!GlobalIndex && !HaveFullGlobalModuleIndex) {
1107 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1108 bool RecreateIndex = false;
1109 for (ModuleMap::module_iterator I = MMap.module_begin(), E = MMap.module_end(); I != E; ++I) {
1110 Module *TheModule = I->second;
1111 // We want the index only of the prebuilt modules.
1112 if (!HasASTFileOnDisk(TheModule, PP))
1113 continue;
1114 LoadModule(TheModule->Name, interp);
1115 RecreateIndex = true;
1116 }
1117 if (RecreateIndex) {
1118 cling::Interpreter::PushTransactionRAII deserRAII(&interp);
1119 clang::GlobalModuleIndex::UserDefinedInterestingIDs IDs;
1120
1121 struct DefinitionFinder : public RecursiveASTVisitor<DefinitionFinder> {
1122 DefinitionFinder(clang::GlobalModuleIndex::UserDefinedInterestingIDs& IDs,
1123 clang::TranslationUnitDecl* TU) : DefinitionIDs(IDs) {
1124 TraverseDecl(TU);
1125 }
1126 bool VisitNamedDecl(NamedDecl *ND) {
1127 if (!ND->isFromASTFile())
1128 return true;
1129 if (!ND->getIdentifier())
1130 return true;
1131
1132 if (ND->getAccess() == AS_protected || ND->getAccess() == AS_private)
1133 return true;
1134
1135 if (TagDecl *TD = llvm::dyn_cast<TagDecl>(ND)) {
1136 if (TD->isCompleteDefinition())
1137 Register(TD);
1138 } else if (NamespaceDecl *NSD = llvm::dyn_cast<NamespaceDecl>(ND)) {
1139 Register(NSD, /*AddSingleEntry=*/ false);
1140 }
1141 else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(ND))
1142 Register(TND);
1143 // FIXME: Add the rest...
1144 return true; // continue decending
1145 }
1146 private:
1147 clang::GlobalModuleIndex::UserDefinedInterestingIDs &DefinitionIDs;
1148 void Register(const NamedDecl* ND, bool AddSingleEntry = true) {
1149 assert(ND->isFromASTFile());
1150 // FIXME: All decls should have an owning module once rootcling
1151 // updates its generated decls from within the LookupHelper & co.
1152 if (!ND->hasOwningModule()) {
1153#ifndef NDEBUG
1154 SourceManager &SM = ND->getASTContext().getSourceManager();
1155 SourceLocation Loc = ND->getLocation();
1156 const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
1157 (void)FE;
1158 assert(FE->getName().contains("input_line_"));
1159#endif
1160 return;
1161 }
1162
1163 Module *OwningModule = ND->getOwningModule()->getTopLevelModule();
1164 assert(OwningModule);
1165 assert(!ND->getName().empty() && "Empty name");
1166 if (AddSingleEntry && DefinitionIDs.count(ND->getName()))
1167 return;
1168 // FIXME: The FileEntry in not stable to serialize.
1169 // FIXME: We might end up with many times with the same module.
1170 // FIXME: We might end up two modules containing a definition.
1171 // FIXME: What do we do if no definition is found.
1172 DefinitionIDs[ND->getName()].push_back(OwningModule->getASTFile());
1173 }
1174 };
1175 DefinitionFinder defFinder(IDs, CI.getASTContext().getTranslationUnitDecl());
1176
1177 llvm::cantFail(GlobalModuleIndex::writeIndex(CI.getFileManager(),
1178 CI.getPCHContainerReader(),
1179 ModuleIndexPath,
1180 &IDs));
1181 ModuleManager->resetForReload();
1182 ModuleManager->loadGlobalIndex();
1183 GlobalIndex = ModuleManager->getGlobalIndex();
1184 }
1186 }
1187 return GlobalIndex;
1188}
1189
1190static void RegisterCxxModules(cling::Interpreter &clingInterp)
1191{
1192 if (!clingInterp.getCI()->getLangOpts().Modules)
1193 return;
1194
1195 // Loading of a module might deserialize.
1196 cling::Interpreter::PushTransactionRAII deserRAII(&clingInterp);
1197
1198 // Setup core C++ modules if we have any to setup.
1199
1200 // Load libc and stl first.
1201 // Load vcruntime module for windows
1202#ifdef R__WIN32
1203 LoadModule("vcruntime", clingInterp);
1204 LoadModule("services", clingInterp);
1205#endif
1206
1207#ifdef R__MACOSX
1208 LoadModule("Darwin", clingInterp);
1209#else
1210 LoadModule("libc", clingInterp);
1211#endif
1212 LoadModule("std", clingInterp);
1213
1214 LoadModule("_Builtin_intrinsics", clingInterp);
1215
1216 // Load core modules
1217 // This should be vector in order to be able to pass it to LoadModules
1218 std::vector<std::string> CoreModules = {"ROOT_Foundation_C",
1219 "ROOT_Config",
1220 "ROOT_Rtypes",
1221 "ROOT_Foundation_Stage1_NoRTTI",
1222 "Core",
1223 "Rint",
1224 "RIO"};
1225
1226 LoadModules(CoreModules, clingInterp);
1227
1228 // Take this branch only from ROOT because we don't need to preload modules in rootcling
1229 if (!IsFromRootCling()) {
1230 std::vector<std::string> CommonModules = {"MathCore"};
1231 LoadModules(CommonModules, clingInterp);
1232
1233 // These modules should not be preloaded but they fix issues.
1234 // FIXME: Hist is not a core module but is very entangled to MathCore and
1235 // causes issues.
1236 std::vector<std::string> FIXMEModules = {"Hist"};
1237 clang::CompilerInstance &CI = *clingInterp.getCI();
1238 clang::Preprocessor &PP = CI.getPreprocessor();
1239 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1240 if (MMap.findModule("RInterface"))
1241 FIXMEModules.push_back("RInterface");
1242
1243 LoadModules(FIXMEModules, clingInterp);
1244
1245 GlobalModuleIndex *GlobalIndex = nullptr;
1246 // Conservatively enable platform by platform.
1247 bool supportedPlatform =
1248#ifdef R__LINUX
1249 true
1250#elif defined(R__MACOSX)
1251 true
1252#else // Windows
1253 false
1254#endif
1255 ;
1256 // Allow forcefully enabling/disabling the GMI.
1257 llvm::Optional<std::string> envUseGMI = llvm::sys::Process::GetEnv("ROOT_USE_GMI");
1258 if (envUseGMI.hasValue()) {
1259 if (!envUseGMI->empty() && !ROOT::FoundationUtils::CanConvertEnvValueToBool(*envUseGMI))
1260 ::Warning("TCling__RegisterCxxModules",
1261 "Cannot convert '%s' to bool, setting to false!",
1262 envUseGMI->c_str());
1263
1264 bool value = envUseGMI->empty() || ROOT::FoundationUtils::ConvertEnvValueToBool(*envUseGMI);
1265
1266 if (supportedPlatform == value)
1267 ::Warning("TCling__RegisterCxxModules", "Global module index is%sused already!",
1268 (value) ? " " :" not ");
1269 supportedPlatform = value;
1270 }
1271
1272 if (supportedPlatform) {
1273 loadGlobalModuleIndex(clingInterp);
1274 // FIXME: The ASTReader still calls loadGlobalIndex and loads the file
1275 // We should investigate how to suppress it completely.
1276 GlobalIndex = CI.getModuleManager()->getGlobalIndex();
1277 }
1278
1279 llvm::StringSet<> KnownModuleFileNames;
1280 if (GlobalIndex)
1281 GlobalIndex->getKnownModuleFileNames(KnownModuleFileNames);
1282
1283 std::vector<std::string> PendingModules;
1284 PendingModules.reserve(256);
1285 for (auto I = MMap.module_begin(), E = MMap.module_end(); I != E; ++I) {
1286 clang::Module *M = I->second;
1287 assert(M);
1288
1289 // We want to load only already created modules.
1290 std::string FullASTFilePath;
1291 if (!HasASTFileOnDisk(M, PP, &FullASTFilePath))
1292 continue;
1293
1294 if (GlobalIndex && KnownModuleFileNames.count(FullASTFilePath))
1295 continue;
1296
1297 if (M->IsMissingRequirement)
1298 continue;
1299
1300 if (GlobalIndex)
1301 LoadModule(M->Name, clingInterp);
1302 else {
1303 // FIXME: We may be able to remove those checks as cling::loadModule
1304 // checks if a module was alredy loaded.
1305 if (std::find(CoreModules.begin(), CoreModules.end(), M->Name) != CoreModules.end())
1306 continue; // This is a core module which was already loaded.
1307
1308 // Load system modules now and delay the other modules after we have
1309 // loaded all system ones.
1310 if (M->IsSystem)
1311 LoadModule(M->Name, clingInterp);
1312 else
1313 PendingModules.push_back(M->Name);
1314 }
1315 }
1316 LoadModules(PendingModules, clingInterp);
1317 }
1318
1319 // Check that the gROOT macro was exported by any core module.
1320 assert(clingInterp.getMacro("gROOT") && "Couldn't load gROOT macro?");
1321
1322 // `ERROR` and `PI` are from loading R related modules, which conflict with
1323 // user's code.
1324 clingInterp.declare(R"CODE(
1325#ifdef PI
1326# undef PI
1327#endif
1328#ifdef ERROR
1329# undef ERROR
1330#endif
1331 )CODE");
1332}
1333
1334static void RegisterPreIncludedHeaders(cling::Interpreter &clingInterp)
1335{
1336 std::string PreIncludes;
1337 bool hasCxxModules = clingInterp.getCI()->getLangOpts().Modules;
1338
1339 // For the list to also include string, we have to include it now.
1340 // rootcling does parts already if needed, e.g. genreflex does not want using
1341 // namespace std.
1342 if (IsFromRootCling()) {
1343 PreIncludes += "#include \"RtypesCore.h\"\n";
1344 } else {
1345 if (!hasCxxModules)
1346 PreIncludes += "#include \"Rtypes.h\"\n";
1347
1348 PreIncludes += gClassDefInterpMacro + "\n"
1349 + gInterpreterClassDef + "\n"
1350 "#undef ClassImp\n"
1351 "#define ClassImp(X);\n";
1352 }
1353 if (!hasCxxModules)
1354 PreIncludes += "#include <string>\n";
1355
1356 // We must include it even when we have modules because it is marked as
1357 // textual in the modulemap due to the nature of the assert header.
1358#ifndef R__WIN32
1359 PreIncludes += "#include <cassert>\n";
1360#endif
1361 PreIncludes += "using namespace std;\n";
1362 clingInterp.declare(PreIncludes);
1363}
1364
1365////////////////////////////////////////////////////////////////////////////////
1366/// Initialize the cling interpreter interface.
1367/// \param name name for TInterpreter
1368/// \param title title for TInterpreter
1369/// \param argv - array of arguments passed to the cling::Interpreter constructor
1370/// e.g. `-DFOO=bar`. The last element of the array must be `nullptr`.
1371
1372TCling::TCling(const char *name, const char *title, const char* const argv[])
1373: TInterpreter(name, title), fGlobalsListSerial(-1), fMapfile(nullptr),
1377{
1378 fPrompt[0] = 0;
1379 const bool fromRootCling = IsFromRootCling();
1380
1381 fCxxModulesEnabled = false;
1382#ifdef R__USE_CXXMODULES
1383 fCxxModulesEnabled = true;
1384#endif
1385
1386 llvm::install_fatal_error_handler(&exceptionErrorHandler);
1387
1388 fTemporaries = new std::vector<cling::Value>();
1389
1390 std::vector<std::string> clingArgsStorage;
1391 clingArgsStorage.push_back("cling4root");
1392 for (const char* const* arg = argv; *arg; ++arg)
1393 clingArgsStorage.push_back(*arg);
1394
1395 // rootcling sets its arguments through TROOT::GetExtraInterpreterArgs().
1396 if (!fromRootCling) {
1398
1399 // Add -I early so ASTReader can find the headers.
1400 std::string interpInclude(TROOT::GetEtcDir().Data());
1401 clingArgsStorage.push_back("-I" + interpInclude);
1402
1403 // Add include path to etc/cling.
1404 clingArgsStorage.push_back("-I" + interpInclude + "/cling");
1405
1406 // Add include path to etc/cling.
1407 clingArgsStorage.push_back("-I" + interpInclude + "/cling/plugins/include");
1408
1409 // Add the root include directory and etc/ to list searched by default.
1410 clingArgsStorage.push_back(std::string(("-I" + TROOT::GetIncludeDir()).Data()));
1411
1412 // Add the current path to the include path
1413 // TCling::AddIncludePath(".");
1414
1415 // Attach the PCH (unless we have C++ modules enabled which provide the
1416 // same functionality).
1417 if (!fCxxModulesEnabled) {
1418 std::string pchFilename = interpInclude + "/allDict.cxx.pch";
1419 if (gSystem->Getenv("ROOT_PCH")) {
1420 pchFilename = gSystem->Getenv("ROOT_PCH");
1421 }
1422
1423 clingArgsStorage.push_back("-include-pch");
1424 clingArgsStorage.push_back(pchFilename);
1425 }
1426
1427 clingArgsStorage.push_back("-Wno-undefined-inline");
1428 clingArgsStorage.push_back("-fsigned-char");
1429 // The -O1 optimization flag has nasty side effects on Windows (32 and 64 bit)
1430 // See the GitHub issues #9809 and #9944
1431 // TODO: to be reviewed after the upgrade of LLVM & Clang
1432#ifndef _MSC_VER
1433 clingArgsStorage.push_back("-O1");
1434 // Disable optimized register allocation which is turned on automatically
1435 // by -O1, but seems to require -O2 to not explode in run time.
1436 clingArgsStorage.push_back("-mllvm");
1437 clingArgsStorage.push_back("-optimize-regalloc=0");
1438#endif
1439 }
1440
1441 // Process externally passed arguments if present.
1442 llvm::Optional<std::string> EnvOpt = llvm::sys::Process::GetEnv("EXTRA_CLING_ARGS");
1443 if (EnvOpt.hasValue()) {
1444 StringRef Env(*EnvOpt);
1445 while (!Env.empty()) {
1446 StringRef Arg;
1447 std::tie(Arg, Env) = Env.split(' ');
1448 clingArgsStorage.push_back(Arg.str());
1449 }
1450 }
1451
1452 auto GetEnvVarPath = [](const std::string &EnvVar,
1453 std::vector<std::string> &Paths) {
1454 llvm::Optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(EnvVar);
1455 if (EnvOpt.hasValue()) {
1456 StringRef Env(*EnvOpt);
1457 while (!Env.empty()) {
1458 StringRef Arg;
1459 std::tie(Arg, Env) = Env.split(ROOT::FoundationUtils::GetEnvPathSeparator());
1460 if (std::find(Paths.begin(), Paths.end(), Arg.str()) == Paths.end())
1461 Paths.push_back(Arg.str());
1462 }
1463 }
1464 };
1465
1466 if (fCxxModulesEnabled) {
1467 std::vector<std::string> Paths;
1468 // ROOT usually knows better where its libraries are. This way we can
1469 // discover modules without having to should thisroot.sh and should fix
1470 // gnuinstall.
1471#ifdef R__WIN32
1472 Paths.push_back(TROOT::GetBinDir().Data());
1473#else
1474 Paths.push_back(TROOT::GetLibDir().Data());
1475#endif
1476 GetEnvVarPath("CLING_PREBUILT_MODULE_PATH", Paths);
1477 std::string EnvVarPath;
1478 for (const std::string& P : Paths)
1480 // FIXME: We should make cling -fprebuilt-module-path work.
1481 gSystem->Setenv("CLING_PREBUILT_MODULE_PATH", EnvVarPath.c_str());
1482 }
1483
1484 // FIXME: This only will enable frontend timing reports.
1485 EnvOpt = llvm::sys::Process::GetEnv("ROOT_CLING_TIMING");
1486 if (EnvOpt.hasValue())
1487 clingArgsStorage.push_back("-ftime-report");
1488
1489 // Add the overlay file. Note that we cannot factor it out for both root
1490 // and rootcling because rootcling activates modules only if -cxxmodule
1491 // flag is passed.
1492 if (fCxxModulesEnabled && !fromRootCling) {
1493 // For now we prefer rootcling to enumerate explicitly its modulemaps.
1494 std::vector<std::string> ModuleMaps;
1495 std::string ModuleMapSuffix = ROOT::FoundationUtils::GetPathSeparator() + "module.modulemap";
1496 ModuleMaps.push_back(TROOT::GetIncludeDir().Data() + ModuleMapSuffix);
1497 GetEnvVarPath("CLING_MODULEMAP_FILES", ModuleMaps);
1498
1499 std::string cwd = gSystem->WorkingDirectory();
1500 // Give highest precedence of the modulemap in the cwd if any.
1501 if (llvm::sys::fs::exists(cwd + ModuleMapSuffix))
1502 ModuleMaps.push_back(cwd + ModuleMapSuffix);
1503
1504 for (const std::string& M : ModuleMaps)
1505 clingArgsStorage.push_back("-fmodule-map-file=" + M);
1506
1507 std::string ModulesCachePath;
1508 EnvOpt = llvm::sys::Process::GetEnv("CLING_MODULES_CACHE_PATH");
1509 if (EnvOpt.hasValue()){
1510 StringRef Env(*EnvOpt);
1511 assert(llvm::sys::fs::exists(Env) && "Path does not exist!");
1512 ModulesCachePath = Env.str();
1513 } else {
1514 ModulesCachePath = TROOT::GetLibDir();
1515 }
1516
1517 clingArgsStorage.push_back("-fmodules-cache-path=" + ModulesCachePath);
1518 }
1519
1520 std::vector<const char*> interpArgs;
1521 for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1522 eArg = clingArgsStorage.end(); iArg != eArg; ++iArg)
1523 interpArgs.push_back(iArg->c_str());
1524
1525 // Activate C++ modules support. If we are running within rootcling, it's up
1526 // to rootcling to set this flag depending on whether it wants to produce
1527 // C++ modules.
1528 TString vfsArg;
1529 if (fCxxModulesEnabled) {
1530 if (!fromRootCling) {
1531 // We only set this flag, rest is done by the CIFactory.
1532 interpArgs.push_back("-fmodules");
1533 interpArgs.push_back("-fno-implicit-module-maps");
1534 // We should never build modules during runtime, so let's enable the
1535 // module build remarks from clang to make it easier to spot when we do
1536 // this by accident.
1537 interpArgs.push_back("-Rmodule-build");
1538 }
1539 // ROOT implements its AutoLoading upon module's link directives. We
1540 // generate module A { header "A.h" link "A.so" export * } where ROOT's
1541 // facilities use the link directive to dynamically load the relevant
1542 // library. So, we need to suppress clang's default autolink behavior.
1543 interpArgs.push_back("-fno-autolink");
1544 }
1545
1546#ifdef R__FAST_MATH
1547 // Same setting as in rootcling_impl.cxx.
1548 interpArgs.push_back("-ffast-math");
1549#endif
1550
1551 TString llvmResourceDir = TROOT::GetEtcDir() + "/cling";
1552 // Add statically injected extra arguments, usually coming from rootcling.
1553 for (const char** extraArgs = TROOT::GetExtraInterpreterArgs();
1554 extraArgs && *extraArgs; ++extraArgs) {
1555 if (!strcmp(*extraArgs, "-resource-dir")) {
1556 // Take the next arg as the llvm resource directory.
1557 llvmResourceDir = *(++extraArgs);
1558 } else {
1559 interpArgs.push_back(*extraArgs);
1560 }
1561 }
1562
1563 for (const auto &arg: TROOT::AddExtraInterpreterArgs({})) {
1564 interpArgs.push_back(arg.c_str());
1565 }
1566
1567 // Add the Rdict module file extension.
1568 cling::Interpreter::ModuleFileExtensions extensions;
1569 EnvOpt = llvm::sys::Process::GetEnv("ROOTDEBUG_RDICT");
1570 if (!EnvOpt.hasValue())
1571 extensions.push_back(std::make_shared<TClingRdictModuleFileExtension>());
1572
1573 fInterpreter = llvm::make_unique<cling::Interpreter>(interpArgs.size(),
1574 &(interpArgs[0]),
1575 llvmResourceDir, extensions);
1576
1577 // Don't check whether modules' files exist.
1578 fInterpreter->getCI()->getPreprocessorOpts().DisablePCHValidation = true;
1579
1580 // Until we can disable AutoLoading during Sema::CorrectTypo() we have
1581 // to disable spell checking.
1582 fInterpreter->getCI()->getLangOpts().SpellChecking = false;
1583
1584 // We need stream that doesn't close its file descriptor, thus we are not
1585 // using llvm::outs. Keeping file descriptor open we will be able to use
1586 // the results in pipes (Savannah #99234).
1587 static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO, /*ShouldClose*/false);
1588 fMetaProcessor = llvm::make_unique<cling::MetaProcessor>(*fInterpreter, fMPOuts);
1589
1592
1593 // We are now ready (enough is loaded) to init the list of opaque typedefs.
1600
1601 // Disallow auto-parsing in rootcling
1602 fIsAutoParsingSuspended = fromRootCling;
1603
1604 ResetAll();
1605
1606 // Enable dynamic lookup
1607 if (!fromRootCling) {
1608 fInterpreter->enableDynamicLookup();
1609 }
1610
1611 // Enable ClinG's DefinitionShadower for ROOT.
1612 fInterpreter->getRuntimeOptions().AllowRedefinition = 1;
1613
1614 // Attach cling callbacks last; they might need TROOT::fInterpreter
1615 // and should thus not be triggered during the equivalent of
1616 // TROOT::fInterpreter = new TCling;
1617 std::unique_ptr<TClingCallbacks>
1618 clingCallbacks(new TClingCallbacks(GetInterpreterImpl(), /*hasCodeGen*/ !fromRootCling));
1619 fClingCallbacks = clingCallbacks.get();
1621 fInterpreter->setCallbacks(std::move(clingCallbacks));
1622
1623 if (!fromRootCling) {
1624 cling::DynamicLibraryManager& DLM = *fInterpreter->getDynamicLibraryManager();
1625 // Make sure cling looks into ROOT's libdir, even if not part of LD_LIBRARY_PATH
1626 // e.g. because of an RPATH build.
1627 DLM.addSearchPath(TROOT::GetLibDir().Data(), /*isUser=*/true,
1628 /*prepend=*/true);
1629 auto ShouldPermanentlyIgnore = [](llvm::StringRef FileName) -> bool{
1630 llvm::StringRef stem = llvm::sys::path::stem(FileName);
1631 return stem.startswith("libNew") || stem.startswith("libcppyy_backend");
1632 };
1633 // Initialize the dyld for the llvmLazyFunctionCreator.
1634 DLM.initializeDyld(ShouldPermanentlyIgnore);
1635 fInterpreter->installLazyFunctionCreator(llvmLazyFunctionCreator);
1636 }
1637}
1638
1639
1640////////////////////////////////////////////////////////////////////////////////
1641/// Destroy the interpreter interface.
1642
1644{
1645 // ROOT's atexit functions require the interepreter to be available.
1646 // Run them before shutting down.
1647 if (!IsFromRootCling())
1648 GetInterpreterImpl()->runAtExitFuncs();
1649 fIsShuttingDown = true;
1650 delete fMapfile;
1651 delete fRootmapFiles;
1652 delete fTemporaries;
1653 delete fNormalizedCtxt;
1654 delete fLookupHelper;
1655 gCling = 0;
1656}
1657
1658////////////////////////////////////////////////////////////////////////////////
1659/// Initialize the interpreter, once TROOT::fInterpreter is set.
1660
1662{
1664
1665 // We are set up. Enable ROOT's AutoLoading.
1666 if (IsFromRootCling())
1667 return;
1668
1669 // Read the rules before enabling the auto loading to not inadvertently
1670 // load the libraries for the classes concerned even-though the user is
1671 // *not* using them.
1672 // Note this call must happen before the first call to LoadLibraryMap.
1673 assert(GetRootMapFiles() == 0 && "Must be called before LoadLibraryMap!");
1674 TClass::ReadRules(); // Read the default customization rules ...
1675
1677 SetClassAutoLoading(true);
1678}
1679
1681{
1682 fIsShuttingDown = true;
1683 ResetGlobals();
1684}
1685
1686////////////////////////////////////////////////////////////////////////////////
1687/// Helper to initialize TVirtualStreamerInfo's factor early.
1688/// Use static initialization to insure only one TStreamerInfo is created.
1690{
1691 // Use lambda since SetFactory return void.
1692 auto setFactory = []() {
1694 return kTRUE;
1695 };
1696 static bool doneFactory = setFactory();
1697 return doneFactory; // avoid unused variable warning.
1698}
1699
1700////////////////////////////////////////////////////////////////////////////////
1701/// Register Rdict data for future loading by LoadPCM;
1702
1703void TCling::RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
1704{
1705 if (IsFromRootCling())
1706 return;
1707
1708 if (llvm::sys::fs::exists(pcmFileNameFullPath)) {
1709 ::Error("TCling::RegisterRdictForLoadPCM", "Rdict '%s' is both in Module extension and in File system.", pcmFileNameFullPath.c_str());
1710 return;
1711 }
1712
1713 // The pcmFileNameFullPath must be resolved already because we cannot resolve
1714 // a link to a non-existent file.
1715 fPendingRdicts[pcmFileNameFullPath] = *pcmContent;
1716}
1717
1718////////////////////////////////////////////////////////////////////////////////
1719/// Tries to load a PCM from TFile; returns true on success.
1720
1722{
1723 auto listOfKeys = pcmFile.GetListOfKeys();
1724
1725 // This is an empty pcm
1726 if (listOfKeys && ((listOfKeys->GetSize() == 0) || // Nothing here, or
1727 ((listOfKeys->GetSize() == 1) && // only one, and
1728 !strcmp(((TKey *)listOfKeys->At(0))->GetName(), "EMPTY") // name is EMPTY
1729 ))) {
1730 return;
1731 }
1732
1733 TObjArray *protoClasses;
1734 if (gDebug > 1)
1735 ::Info("TCling::LoadPCMImpl", "reading protoclasses for %s \n", pcmFile.GetName());
1736
1737 TObjArray *enums;
1738 pcmFile.GetObject("__Enums", enums);
1739 if (enums) {
1740 // Cache the pointers
1741 auto listOfGlobals = gROOT->GetListOfGlobals();
1742 auto listOfEnums = dynamic_cast<THashList *>(gROOT->GetListOfEnums());
1743 // Loop on enums and then on enum constants
1744 for (auto selEnum : *enums) {
1745 const char *enumScope = selEnum->GetTitle();
1746 const char *enumName = selEnum->GetName();
1747 if (strcmp(enumScope, "") == 0) {
1748 // This is a global enum and is added to the
1749 // list of enums and its constants to the list of globals
1750 if (!listOfEnums->THashList::FindObject(enumName)) {
1751 ((TEnum *)selEnum)->SetClass(nullptr);
1752 listOfEnums->Add(selEnum);
1753 }
1754 for (auto enumConstant : *static_cast<TEnum *>(selEnum)->GetConstants()) {
1755 if (!listOfGlobals->FindObject(enumConstant)) {
1756 listOfGlobals->Add(enumConstant);
1757 }
1758 }
1759 } else {
1760 // This enum is in a namespace. A TClass entry is bootstrapped if
1761 // none exists yet and the enum is added to it
1762 TClass *nsTClassEntry = TClass::GetClass(enumScope);
1763 if (!nsTClassEntry) {
1764 nsTClassEntry = new TClass(enumScope, 0, TClass::kNamespaceForMeta, true);
1765 }
1766 auto listOfEnums = nsTClassEntry->fEnums.load();
1767 if (!listOfEnums) {
1768 if ((kIsClass | kIsStruct | kIsUnion) & nsTClassEntry->Property()) {
1769 // For this case, the list will be immutable once constructed
1770 // (i.e. in this case, by the end of this routine).
1771 listOfEnums = nsTClassEntry->fEnums = new TListOfEnums(nsTClassEntry);
1772 } else {
1773 // namespaces can have enums added to them
1774 listOfEnums = nsTClassEntry->fEnums = new TListOfEnumsWithLock(nsTClassEntry);
1775 }
1776 }
1777 if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)) {
1778 ((TEnum *)selEnum)->SetClass(nsTClassEntry);
1779 listOfEnums->Add(selEnum);
1780 }
1781 }
1782 }
1783 enums->Clear();
1784 delete enums;
1785 }
1786
1787 pcmFile.GetObject("__ProtoClasses", protoClasses);
1788
1789 if (protoClasses) {
1790 for (auto obj : *protoClasses) {
1791 TProtoClass *proto = (TProtoClass *)obj;
1793 }
1794 // Now that all TClass-es know how to set them up we can update
1795 // existing TClasses, which might cause the creation of e.g. TBaseClass
1796 // objects which in turn requires the creation of TClasses, that could
1797 // come from the PCH, but maybe later in the loop. Instead of resolving
1798 // a dependency graph the addition to the TClassTable above allows us
1799 // to create these dependent TClasses as needed below.
1800 for (auto proto : *protoClasses) {
1801 if (TClass *existingCl = (TClass *)gROOT->GetListOfClasses()->FindObject(proto->GetName())) {
1802 // We have an existing TClass object. It might be emulated
1803 // or interpreted; we now have more information available.
1804 // Make that available.
1805 if (existingCl->GetState() != TClass::kHasTClassInit) {
1806 DictFuncPtr_t dict = gClassTable->GetDict(proto->GetName());
1807 if (!dict) {
1808 ::Error("TCling::LoadPCM", "Inconsistent TClassTable for %s", proto->GetName());
1809 } else {
1810 // This will replace the existing TClass.
1811 TClass *ncl = (*dict)();
1812 if (ncl)
1813 ncl->PostLoadCheck();
1814 }
1815 }
1816 }
1817 }
1818
1819 protoClasses->Clear(); // Ownership was transfered to TClassTable.
1820 delete protoClasses;
1821 }
1822
1823 TObjArray *dataTypes;
1824 pcmFile.GetObject("__Typedefs", dataTypes);
1825 if (dataTypes) {
1826 for (auto typedf : *dataTypes)
1827 gROOT->GetListOfTypes()->Add(typedf);
1828 dataTypes->Clear(); // Ownership was transfered to TListOfTypes.
1829 delete dataTypes;
1830 }
1831}
1832
1833////////////////////////////////////////////////////////////////////////////////
1834/// Tries to load a rdict PCM, issues diagnostics if it fails.
1835
1836void TCling::LoadPCM(std::string pcmFileNameFullPath)
1837{
1838 SuspendAutoLoadingRAII autoloadOff(this);
1839 SuspendAutoParsing autoparseOff(this);
1840 assert(!pcmFileNameFullPath.empty());
1841 assert(llvm::sys::path::is_absolute(pcmFileNameFullPath));
1842
1843 // Easier to work with the ROOT interfaces.
1844 TString pcmFileName = pcmFileNameFullPath;
1845
1846 // Prevent the ROOT-PCMs hitting this during auto-load during
1847 // JITting - which will cause recursive compilation.
1848 // Avoid to call the plugin manager at all.
1850
1852 llvm::SaveAndRestore<Int_t> SaveGDebug(gDebug);
1853 if (gDebug > 5) {
1854 gDebug -= 5;
1855 ::Info("TCling::LoadPCM", "Loading ROOT PCM %s", pcmFileName.Data());
1856 } else {
1857 gDebug = 0;
1858 }
1859
1860 if (llvm::sys::fs::is_symlink_file(pcmFileNameFullPath))
1861 pcmFileNameFullPath = ROOT::TMetaUtils::GetRealPath(pcmFileNameFullPath);
1862
1863 auto pendingRdict = fPendingRdicts.find(pcmFileNameFullPath);
1864 if (pendingRdict != fPendingRdicts.end()) {
1865 llvm::StringRef pcmContent = pendingRdict->second;
1866 TMemFile::ZeroCopyView_t range{pcmContent.data(), pcmContent.size()};
1867 std::string RDictFileOpts = pcmFileNameFullPath + "?filetype=pcm";
1868 TMemFile pcmMemFile(RDictFileOpts.c_str(), range);
1869
1870 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
1871 LoadPCMImpl(pcmMemFile);
1872 fPendingRdicts.erase(pendingRdict);
1873
1874 return;
1875 }
1876
1877 if (!llvm::sys::fs::exists(pcmFileNameFullPath)) {
1878 ::Error("TCling::LoadPCM", "ROOT PCM %s file does not exist",
1879 pcmFileNameFullPath.data());
1880 if (!fPendingRdicts.empty())
1881 for (const auto &rdict : fPendingRdicts)
1882 ::Info("TCling::LoadPCM", "In-memory ROOT PCM candidate %s\n",
1883 rdict.first.c_str());
1884 return;
1885 }
1886
1887 if (!gROOT->IsRootFile(pcmFileName)) {
1888 Fatal("LoadPCM", "The file %s is not a ROOT as was expected\n", pcmFileName.Data());
1889 return;
1890 }
1891 TFile pcmFile(pcmFileName + "?filetype=pcm", "READ");
1892 LoadPCMImpl(pcmFile);
1893}
1894
1895//______________________________________________________________________________
1896
1897namespace {
1898 using namespace clang;
1899
1900 class ExtLexicalStorageAdder: public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1901 // This class is to be considered an helper for autoparsing.
1902 // It visits the AST and marks all classes (in all of their redeclarations)
1903 // with the setHasExternalLexicalStorage method.
1904 public:
1905 bool VisitRecordDecl(clang::RecordDecl* rcd){
1906 if (gDebug > 2)
1907 Info("ExtLexicalStorageAdder",
1908 "Adding external lexical storage to class %s",
1909 rcd->getNameAsString().c_str());
1910 auto reDeclPtr = rcd->getMostRecentDecl();
1911 do {
1912 reDeclPtr->setHasExternalLexicalStorage();
1913 } while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1914
1915 return false;
1916 }
1917 };
1918
1919
1920}
1921
1922////////////////////////////////////////////////////////////////////////////////
1923///\returns true if the module map was loaded, false on error or if the map was
1924/// already loaded.
1925bool TCling::RegisterPrebuiltModulePath(const std::string &FullPath,
1926 const std::string &ModuleMapName /*= "module.modulemap"*/) const
1927{
1928 assert(llvm::sys::path::is_absolute(FullPath));
1929 Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
1930 FileManager &FM = PP.getFileManager();
1931 // FIXME: In a ROOT session we can add an include path (through .I /inc/path)
1932 // We should look for modulemap files there too.
1933 const DirectoryEntry *DE = FM.getDirectory(FullPath);
1934 if (DE) {
1935 HeaderSearch &HS = PP.getHeaderSearchInfo();
1936 HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1937 const auto &ModPaths = HSOpts.PrebuiltModulePaths;
1938 bool pathExists = std::find(ModPaths.begin(), ModPaths.end(), FullPath) != ModPaths.end();
1939 if (!pathExists)
1940 HSOpts.AddPrebuiltModulePath(FullPath);
1941 // We cannot use HS.lookupModuleMapFile(DE, /*IsFramework*/ false);
1942 // because its internal call to getFile has CacheFailure set to true.
1943 // In our case, modulemaps can appear any time due to ACLiC.
1944 // Code copied from HS.lookupModuleMapFile.
1945 llvm::SmallString<256> ModuleMapFileName(DE->getName());
1946 llvm::sys::path::append(ModuleMapFileName, ModuleMapName);
1947 const FileEntry *FE = FM.getFile(ModuleMapFileName, /*openFile*/ false,
1948 /*CacheFailure*/ false);
1949 if (FE) {
1950 if (!HS.loadModuleMapFile(FE, /*IsSystem*/ false))
1951 return true;
1952 Error("RegisterPrebuiltModulePath", "Could not load modulemap in %s", ModuleMapFileName.c_str());
1953 }
1954 }
1955 return false;
1956}
1957
1958////////////////////////////////////////////////////////////////////////////////
1959/// List of dicts that have the PCM information already in the PCH.
1960static const std::unordered_set<std::string> gIgnoredPCMNames = {"libCore",
1961 "libRint",
1962 "libThread",
1963 "libRIO",
1964 "libImt",
1965 "libMultiProc",
1966 "libcomplexDict",
1967 "libdequeDict",
1968 "liblistDict",
1969 "libforward_listDict",
1970 "libvectorDict",
1971 "libmapDict",
1972 "libmultimap2Dict",
1973 "libmap2Dict",
1974 "libmultimapDict",
1975 "libsetDict",
1976 "libmultisetDict",
1977 "libunordered_setDict",
1978 "libunordered_multisetDict",
1979 "libunordered_mapDict",
1980 "libunordered_multimapDict",
1981 "libvalarrayDict",
1982 "G__GenVector32",
1983 "G__Smatrix32"};
1984
1985static void PrintDlError(const char *dyLibName, const char *modulename)
1986{
1987#ifdef R__WIN32
1988 char dyLibError[1000];
1989 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1990 dyLibError, sizeof(dyLibError), NULL);
1991#else
1992 const char *dyLibError = dlerror();
1993#endif
1994 ::Error("TCling::RegisterModule", "Cannot open shared library %s for dictionary %s:\n %s", dyLibName, modulename,
1995 (dyLibError) ? dyLibError : "");
1996}
1997
1998////////////////////////////////////////////////////////////////////////////////
1999// Update all the TClass registered in fClassesToUpdate
2000
2002{
2003 while (!fClassesToUpdate.empty()) {
2004 TClass *oldcl = fClassesToUpdate.back().first;
2005 // If somehow the TClass has already been loaded (maybe it was registered several time),
2006 // we skip it. Otherwise, the existing TClass is in mode kInterpreted, kEmulated or
2007 // maybe even kForwardDeclared and needs to replaced.
2008 if (oldcl->GetState() != TClass::kHasTClassInit) {
2009 // if (gDebug > 2) Info("RegisterModule", "Forcing TClass init for %s", oldcl->GetName());
2010 DictFuncPtr_t dict = fClassesToUpdate.back().second;
2011 fClassesToUpdate.pop_back();
2012 // Calling func could manipulate the list so, let maintain the list
2013 // then call the dictionary function.
2014 TClass *ncl = dict();
2015 if (ncl) ncl->PostLoadCheck();
2016 } else {
2017 fClassesToUpdate.pop_back();
2018 }
2019 }
2020}
2021////////////////////////////////////////////////////////////////////////////////
2022/// Inject the module named "modulename" into cling; load all headers.
2023/// headers is a 0-terminated array of header files to `#include` after
2024/// loading the module. The module is searched for in all $LD_LIBRARY_PATH
2025/// entries (or %PATH% on Windows).
2026/// This function gets called by the static initialization of dictionary
2027/// libraries.
2028/// The payload code is injected "as is" in the interpreter.
2029/// The value of 'triggerFunc' is used to find the shared library location.
2030
2031void TCling::RegisterModule(const char* modulename,
2032 const char** headers,
2033 const char** includePaths,
2034 const char* payloadCode,
2035 const char* fwdDeclsCode,
2036 void (*triggerFunc)(),
2037 const FwdDeclArgsToKeepCollection_t& fwdDeclsArgToSkip,
2038 const char** classesHeaders,
2039 Bool_t lateRegistration /*=false*/,
2040 Bool_t hasCxxModule /*=false*/)
2041{
2042 const bool fromRootCling = IsFromRootCling();
2043 // We need the dictionary initialization but we don't want to inject the
2044 // declarations into the interpreter, except for those we really need for
2045 // I/O; see rootcling.cxx after the call to TCling__GetInterpreter().
2046 if (fromRootCling) return;
2047
2048 // When we cannot provide a module for the library we should enable header
2049 // parsing. This 'mixed' mode ensures gradual migration to modules.
2050 llvm::SaveAndRestore<bool> SaveHeaderParsing(fHeaderParsingOnDemand);
2051 fHeaderParsingOnDemand = !hasCxxModule;
2052
2053 // Treat Aclic Libs in a special way. Do not delay the parsing.
2054 bool hasHeaderParsingOnDemand = fHeaderParsingOnDemand;
2055 bool isACLiC = strstr(modulename, "_ACLiC_dict") != nullptr;
2056 if (hasHeaderParsingOnDemand && isACLiC) {
2057 if (gDebug>1)
2058 Info("TCling::RegisterModule",
2059 "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
2060 hasHeaderParsingOnDemand = false;
2061 }
2062
2063
2064 // Make sure we relookup symbols that were search for before we loaded
2065 // their autoparse information. We could be more subtil and remove only
2066 // the failed one or only the one in this module, but for now this is
2067 // better than nothing.
2068 fLookedUpClasses.clear();
2069
2070 // Make sure we do not set off AutoLoading or autoparsing during the
2071 // module registration!
2072 SuspendAutoLoadingRAII autoLoadOff(this);
2073
2074 for (const char** inclPath = includePaths; *inclPath; ++inclPath) {
2075 TCling::AddIncludePath(*inclPath);
2076 }
2077 cling::Transaction* T = 0;
2078 // Put the template decls and the number of arguments to skip in the TNormalizedCtxt
2079 for (auto& fwdDeclArgToSkipPair : fwdDeclsArgToSkip){
2080 const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
2081 const int nArgsToSkip = fwdDeclArgToSkipPair.second;
2082 auto compRes = fInterpreter->declare(fwdDecl.c_str(), &T);
2083 assert(cling::Interpreter::kSuccess == compRes &&
2084 "A fwd declaration could not be compiled");
2085 if (compRes!=cling::Interpreter::kSuccess){
2086 Warning("TCling::RegisterModule",
2087 "Problems in declaring string '%s' were encountered.",
2088 fwdDecl.c_str()) ;
2089 continue;
2090 }
2091
2092 // Drill through namespaces recursively until the template is found
2093 if(ClassTemplateDecl* TD = FindTemplateInNamespace(T->getFirstDecl().getSingleDecl())){
2094 fNormalizedCtxt->AddTemplAndNargsToKeep(TD->getCanonicalDecl(), nArgsToSkip);
2095 }
2096
2097 }
2098
2099 // FIXME: Remove #define __ROOTCLING__ once PCMs are there.
2100 // This is used to give Sema the same view on ACLiC'ed files (which
2101 // are then #included through the dictionary) as rootcling had.
2102 TString code = gNonInterpreterClassDef;
2103 if (payloadCode)
2104 code += payloadCode;
2105
2106 std::string dyLibName = cling::DynamicLibraryManager::getSymbolLocation(triggerFunc);
2107 assert(!llvm::sys::fs::is_symlink_file(dyLibName));
2108
2109 if (dyLibName.empty()) {
2110 ::Error("TCling::RegisterModule", "Dictionary trigger function for %s not found", modulename);
2111 return;
2112 }
2113
2114 // The triggerFunc may not be in a shared object but in an executable.
2115 bool isSharedLib = cling::DynamicLibraryManager::isSharedLibrary(dyLibName);
2116
2117 bool wasDlopened = false;
2118
2119 // If this call happens after dlopen has finished (i.e. late registration)
2120 // there is no need to dlopen the library recursively. See ROOT-8437 where
2121 // the dyLibName would correspond to the binary.
2122 if (!lateRegistration) {
2123
2124 if (isSharedLib) {
2125 // We need to open the dictionary shared library, to resolve symbols
2126 // requested by the JIT from it: as the library is currently being dlopen'ed,
2127 // its symbols are not yet reachable from the process.
2128 // Recursive dlopen seems to work just fine.
2129 void* dyLibHandle = dlopen(dyLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
2130 if (dyLibHandle) {
2131 fRegisterModuleDyLibs.push_back(dyLibHandle);
2132 wasDlopened = true;
2133 } else {
2134 PrintDlError(dyLibName.c_str(), modulename);
2135 }
2136 }
2137 } // if (!lateRegistration)
2138
2139 if (hasHeaderParsingOnDemand && fwdDeclsCode){
2140 // We now parse the forward declarations. All the classes are then modified
2141 // in order for them to have an external lexical storage.
2142 std::string fwdDeclsCodeLessEnums;
2143 {
2144 // Search for enum forward decls and only declare them if no
2145 // declaration exists yet.
2146 std::string fwdDeclsLine;
2147 std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
2148 std::vector<std::string> scopes;
2149 while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
2150 const auto enumPos = fwdDeclsLine.find("enum __attribute__((annotate(\"");
2151 // We check if the line contains a fwd declaration of an enum
2152 if (enumPos != std::string::npos) {
2153 // We clear the scopes which we may have carried from a previous iteration
2154 scopes.clear();
2155 // We check if the enum is not in a scope. If yes, save its name
2156 // and the names of the enclosing scopes.
2157 if (enumPos != 0) {
2158 // it's enclosed in namespaces. We need to understand what they are
2159 auto nsPos = fwdDeclsLine.find("namespace");
2160 R__ASSERT(nsPos < enumPos && "Inconsistent enum and enclosing scope parsing!");
2161 while (nsPos < enumPos && nsPos != std::string::npos) {
2162 // we have a namespace, let's put it in the collection of scopes
2163 const auto nsNameStart = nsPos + 10;
2164 const auto nsNameEnd = fwdDeclsLine.find('{', nsNameStart);
2165 const auto nsName = fwdDeclsLine.substr(nsNameStart, nsNameEnd - nsNameStart);
2166 scopes.push_back(nsName);
2167 nsPos = fwdDeclsLine.find("namespace", nsNameEnd);
2168 }
2169 }
2170 clang::DeclContext* DC = 0;
2171 for (auto &&aScope: scopes) {
2172 DC = cling::utils::Lookup::Namespace(&fInterpreter->getSema(), aScope.c_str(), DC);
2173 if (!DC) {
2174 // No decl context means we have to fwd declare the enum.
2175 break;
2176 }
2177 }
2178 if (scopes.empty() || DC) {
2179 // We know the scope; let's look for the enum.
2180 size_t posEnumName = fwdDeclsLine.find("\"))) ", 32);
2181 R__ASSERT(posEnumName != std::string::npos && "Inconsistent enum fwd decl!");
2182 posEnumName += 5; // skip "\"))) "
2183 while (isspace(fwdDeclsLine[posEnumName]))
2184 ++posEnumName;
2185 size_t posEnumNameEnd = fwdDeclsLine.find(" : ", posEnumName);
2186 R__ASSERT(posEnumNameEnd != std::string::npos && "Inconsistent enum fwd decl (end)!");
2187 while (isspace(fwdDeclsLine[posEnumNameEnd]))
2188 --posEnumNameEnd;
2189 // posEnumNameEnd now points to the last character of the name.
2190
2191 std::string enumName = fwdDeclsLine.substr(posEnumName,
2192 posEnumNameEnd - posEnumName + 1);
2193
2194 if (clang::NamedDecl* enumDecl
2195 = cling::utils::Lookup::Named(&fInterpreter->getSema(),
2196 enumName.c_str(), DC)) {
2197 // We have an existing enum decl (forward or definition);
2198 // skip this.
2199 R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) && "not an enum decl!");
2200 (void)enumDecl;
2201 continue;
2202 }
2203 }
2204 }
2205
2206 fwdDeclsCodeLessEnums += fwdDeclsLine + "\n";
2207 }
2208 }
2209
2210 if (!fwdDeclsCodeLessEnums.empty()){ // Avoid the overhead if nothing is to be declared
2211 auto compRes = fInterpreter->declare(fwdDeclsCodeLessEnums, &T);
2212 assert(cling::Interpreter::kSuccess == compRes &&
2213 "The forward declarations could not be compiled");
2214 if (compRes!=cling::Interpreter::kSuccess){
2215 Warning("TCling::RegisterModule",
2216 "Problems in compiling forward declarations for module %s: '%s'",
2217 modulename, fwdDeclsCodeLessEnums.c_str()) ;
2218 }
2219 else if (T){
2220 // Loop over all decls in the transaction and go through them all
2221 // to mark them properly.
2222 // In order to do that, we first iterate over all the DelayedCallInfos
2223 // within the transaction. Then we loop over all Decls in the DeclGroupRef
2224 // contained in the DelayedCallInfos. For each decl, we traverse.
2225 ExtLexicalStorageAdder elsa;
2226 for (auto dciIt = T->decls_begin();dciIt!=T->decls_end();dciIt++){
2227 cling::Transaction::DelayCallInfo& dci = *dciIt;
2228 for(auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
2229 clang::Decl* declPtr = *dit;
2230 elsa.TraverseDecl(declPtr);
2231 }
2232 }
2233 }
2234 }
2235
2236 // Now we register all the headers necessary for the class
2237 // Typical format of the array:
2238 // {"A", "classes.h", "@",
2239 // "vector<A>", "vector", "@",
2240 // "myClass", payloadCode, "@",
2241 // nullptr};
2242
2243 std::string temp;
2244 for (const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
2245 temp=*classesHeader;
2246
2247 size_t theTemplateHash = 0;
2248 bool addTemplate = false;
2249 size_t posTemplate = temp.find('<');
2250 if (posTemplate != std::string::npos) {
2251 // Add an entry for the template itself.
2252 std::string templateName = temp.substr(0, posTemplate);
2253 theTemplateHash = fStringHashFunction(templateName);
2254 addTemplate = true;
2255 }
2256 size_t theHash = fStringHashFunction(temp);
2257 classesHeader++;
2258 for (const char** classesHeader_inner = classesHeader; 0!=strcmp(*classesHeader_inner,"@"); ++classesHeader_inner,++classesHeader){
2259 // This is done in order to distinguish headers from files and from the payloadCode
2260 if (payloadCode == *classesHeader_inner ){
2261 fPayloads.insert(theHash);
2262 if (addTemplate) fPayloads.insert(theTemplateHash);
2263 }
2264 if (gDebug > 2)
2265 Info("TCling::RegisterModule",
2266 "Adding a header for %s", temp.c_str());
2267 fClassesHeadersMap[theHash].push_back(*classesHeader_inner);
2268 if (addTemplate) {
2269 if (fClassesHeadersMap.find(theTemplateHash) == fClassesHeadersMap.end()) {
2270 fClassesHeadersMap[theTemplateHash].push_back(*classesHeader_inner);
2271 }
2272 addTemplate = false;
2273 }
2274 }
2275 }
2276 }
2277
2278 clang::Sema &TheSema = fInterpreter->getSema();
2279
2280 bool ModuleWasSuccessfullyLoaded = false;
2281 if (hasCxxModule) {
2282 std::string ModuleName = modulename;
2283 if (llvm::StringRef(modulename).startswith("lib"))
2284 ModuleName = llvm::StringRef(modulename).substr(3).str();
2285
2286 // In case we are directly loading the library via gSystem->Load() without
2287 // specifying the relevant include paths we should try loading the
2288 // modulemap next to the library location.
2289 clang::Preprocessor &PP = TheSema.getPreprocessor();
2290 std::string ModuleMapName;
2291 if (isACLiC)
2292 ModuleMapName = ModuleName + ".modulemap";
2293 else
2294 ModuleMapName = "module.modulemap";
2295 RegisterPrebuiltModulePath(llvm::sys::path::parent_path(dyLibName),
2296 ModuleMapName);
2297
2298 // FIXME: We should only complain for modules which we know to exist. For example, we should not complain about
2299 // modules such as GenVector32 because it needs to fall back to GenVector.
2300 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2301 ModuleWasSuccessfullyLoaded = LoadModule(ModuleName, *fInterpreter);
2302 if (!ModuleWasSuccessfullyLoaded) {
2303 // Only report if we found the module in the modulemap.
2304 clang::HeaderSearch &headerSearch = PP.getHeaderSearchInfo();
2305 clang::ModuleMap &moduleMap = headerSearch.getModuleMap();
2306 if (moduleMap.findModule(ModuleName))
2307 Info("TCling::RegisterModule", "Module %s in modulemap failed to load.", ModuleName.c_str());
2308 }
2309 }
2310
2311 if (gIgnoredPCMNames.find(modulename) == gIgnoredPCMNames.end()) {
2312 llvm::SmallString<256> pcmFileNameFullPath(dyLibName);
2313 // The path dyLibName might not be absolute. This can happen if dyLibName
2314 // is linked to an executable in the same folder.
2315 llvm::sys::fs::make_absolute(pcmFileNameFullPath);
2316 llvm::sys::path::remove_filename(pcmFileNameFullPath);
2317 llvm::sys::path::append(pcmFileNameFullPath,
2319 LoadPCM(pcmFileNameFullPath.str().str());
2320 }
2321
2322 { // scope within which diagnostics are de-activated
2323 // For now we disable diagnostics because we saw them already at
2324 // dictionary generation time. That won't be an issue with the PCMs.
2325
2326 clangDiagSuppr diagSuppr(TheSema.getDiagnostics());
2327
2328#if defined(R__MUST_REVISIT)
2329#if R__MUST_REVISIT(6,2)
2330 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
2331#endif
2332#endif
2333
2334 if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand){
2335 SuspendAutoParsing autoParseRaii(this);
2336
2337 const cling::Transaction* watermark = fInterpreter->getLastTransaction();
2338 cling::Interpreter::CompilationResult compRes = fInterpreter->parseForModule(code.Data());
2339 if (isACLiC) {
2340 // Register an unload point.
2341 fMetaProcessor->registerUnloadPoint(watermark, headers[0]);
2342 }
2343
2344 assert(cling::Interpreter::kSuccess == compRes &&
2345 "Payload code of a dictionary could not be parsed correctly.");
2346 if (compRes!=cling::Interpreter::kSuccess) {
2347 Warning("TCling::RegisterModule",
2348 "Problems declaring payload for module %s.", modulename) ;
2349 }
2350 }
2351 }
2352
2353 // Now that all the header have been registered/compiled, let's
2354 // make sure to 'reset' the TClass that have a class init in this module
2355 // but already had their type information available (using information/header
2356 // loaded from other modules or from class rules or from opening a TFile
2357 // or from loading header in a way that did not provoke the loading of
2358 // the library we just loaded).
2360
2361 if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand) {
2362 // __ROOTCLING__ might be pulled in through PCH
2363 fInterpreter->declare("#ifdef __ROOTCLING__\n"
2364 "#undef __ROOTCLING__\n"
2365 + gInterpreterClassDef +
2366 "#endif");
2367 }
2368
2369 if (wasDlopened) {
2370 assert(isSharedLib);
2371 void* dyLibHandle = fRegisterModuleDyLibs.back();
2372 fRegisterModuleDyLibs.pop_back();
2373 dlclose(dyLibHandle);
2374 }
2375}
2376
2378 clang::CompilerInstance& CI = *GetInterpreterImpl()->getCI();
2379 ASTContext &C = CI.getASTContext();
2380
2381 // Do not do anything if we have no global module index.
2382 // FIXME: This is mostly to real with false positives in the TTabCom
2383 // interface for non-modules.
2384 if (!fCxxModulesEnabled)
2385 return;
2386
2387 if (IdentifierInfoLookup *External = C.Idents.getExternalIdentifierLookup()) {
2388 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
2389 for (llvm::StringRef Ident = Iter->Next(); !Ident.empty(); Ident = Iter->Next()) {
2390 std::string I = Ident.str();
2391 if (!Idents.Contains(I.data()))
2392 Idents.Add(new TObjString(I.c_str()));
2393 }
2394 }
2395}
2396
2397
2398////////////////////////////////////////////////////////////////////////////////
2399/// Register classes that already existed prior to their dictionary loading
2400/// and that already had a ClassInfo (and thus would not be refresh via
2401/// UpdateClassInfo.
2402
2404{
2405 fClassesToUpdate.push_back(std::make_pair(oldcl,dict));
2406}
2407
2408////////////////////////////////////////////////////////////////////////////////
2409/// If the dictionary is loaded, we can remove the class from the list
2410/// (otherwise the class might be loaded twice).
2411
2413{
2414 typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
2415 iterator stop = fClassesToUpdate.end();
2416 for(iterator i = fClassesToUpdate.begin();
2417 i != stop;
2418 ++i)
2419 {
2420 if ( i->first == oldcl ) {
2421 fClassesToUpdate.erase(i);
2422 return;
2423 }
2424 }
2425}
2426
2427
2428////////////////////////////////////////////////////////////////////////////////
2429/// Let cling process a command line.
2430///
2431/// If the command is executed and the error is 0, then the return value
2432/// is the int value corresponding to the result of the executed command
2433/// (float and double return values will be truncated).
2434///
2435
2436// Method for handling the interpreter exceptions.
2437// the MetaProcessor is passing in as argument to teh function, because
2438// cling::Interpreter::CompilationResult is a nested class and it cannot be
2439// forward declared, thus this method cannot be a static member function
2440// of TCling.
2441
2442static int HandleInterpreterException(cling::MetaProcessor* metaProcessor,
2443 const char* input_line,
2444 cling::Interpreter::CompilationResult& compRes,
2446{
2447 try {
2448 return metaProcessor->process(input_line, compRes, result);
2449 }
2450 catch (cling::InterpreterException& ex)
2451 {
2452 Error("HandleInterpreterException", "%s\n%s", ex.what(), "Execution of your code was aborted.");
2453 ex.diagnose();
2454 compRes = cling::Interpreter::kFailure;
2455 }
2456 return 0;
2457}
2458
2459////////////////////////////////////////////////////////////////////////////////
2460
2461bool TCling::DiagnoseIfInterpreterException(const std::exception &e) const
2462{
2463 if (auto ie = dynamic_cast<const cling::InterpreterException*>(&e)) {
2464 ie->diagnose();
2465 return true;
2466 }
2467 return false;
2468}
2469
2470////////////////////////////////////////////////////////////////////////////////
2471
2473{
2474 // Copy the passed line, it comes from a static buffer in TApplication
2475 // which can be reentered through the Cling evaluation routines,
2476 // which would overwrite the static buffer and we would forget what we
2477 // were doing.
2478 //
2479 TString sLine(line);
2480 if (strstr(line,fantomline)) {
2481 // End-Of-Line action
2482 // See the comment (copied from above):
2483 // It is a "fantom" method to synchronize user keyboard input
2484 // and ROOT prompt line (for WIN32)
2485 // and is implemented by
2486 if (gApplication) {
2487 if (gApplication->IsCmdThread()) {
2489 gROOT->SetLineIsProcessing();
2490
2492
2493 gROOT->SetLineHasBeenProcessed();
2494 }
2495 }
2496 return 0;
2497 }
2498
2500 gGlobalMutex->Lock();
2501 if (!gInterpreterMutex)
2504 }
2506 gROOT->SetLineIsProcessing();
2507
2508 struct InterpreterFlagsRAII {
2509 cling::Interpreter* fInterpreter;
2510 bool fWasDynamicLookupEnabled;
2511
2512 InterpreterFlagsRAII(cling::Interpreter* interp):
2513 fInterpreter(interp),
2514 fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
2515 {
2516 fInterpreter->enableDynamicLookup(true);
2517 }
2518 ~InterpreterFlagsRAII() {
2519 fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
2520 gROOT->SetLineHasBeenProcessed();
2521 }
2522 } interpreterFlagsRAII(GetInterpreterImpl());
2523
2524 // A non-zero returned value means the given line was
2525 // not a complete statement.
2526 int indent = 0;
2527 // This will hold the resulting value of the evaluation the given line.
2529 cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
2530 if (!strncmp(sLine.Data(), ".L", 2) || !strncmp(sLine.Data(), ".x", 2) ||
2531 !strncmp(sLine.Data(), ".X", 2)) {
2532 // If there was a trailing "+", then CINT compiled the code above,
2533 // and we will need to strip the "+" before passing the line to cling.
2534 TString mod_line(sLine);
2535 TString aclicMode;
2536 TString arguments;
2537 TString io;
2538 TString fname = gSystem->SplitAclicMode(sLine.Data() + 3,
2539 aclicMode, arguments, io);
2540 if (aclicMode.Length()) {
2541 // Remove the leading '+'
2542 R__ASSERT(aclicMode[0]=='+' && "ACLiC mode must start with a +");
2543 aclicMode[0]='k'; // We always want to keep the .so around.
2544 if (aclicMode[1]=='+') {
2545 // We have a 2nd +
2546 aclicMode[1]='f'; // We want to force the recompilation.
2547 }
2548 if (!gSystem->CompileMacro(fname,aclicMode)) {
2549 // ACLiC failed.
2550 compRes = cling::Interpreter::kFailure;
2551 } else {
2552 if (strncmp(sLine.Data(), ".L", 2) != 0) {
2553 // if execution was requested.
2554
2555 if (arguments.Length()==0) {
2556 arguments = "()";
2557 }
2558 // We need to remove the extension.
2559 Ssiz_t ext = fname.Last('.');
2560 if (ext != kNPOS) {
2561 fname.Remove(ext);
2562 }
2563 const char *function = gSystem->BaseName(fname);
2564 mod_line = function + arguments + io;
2566 }
2567 }
2568 } else {
2569 // not ACLiC
2570 size_t unnamedMacroOpenCurly;
2571 {
2572 std::string code;
2573 std::string codeline;
2574 // Windows requires std::ifstream::binary to properly handle
2575 // CRLF and LF line endings
2576 std::ifstream in(fname, std::ifstream::binary);
2577 while (in) {
2578 std::getline(in, codeline);
2579 code += codeline + "\n";
2580 }
2581 unnamedMacroOpenCurly
2582 = cling::utils::isUnnamedMacro(code, fInterpreter->getCI()->getLangOpts());
2583 }
2584
2585 fCurExecutingMacros.push_back(fname);
2586 if (unnamedMacroOpenCurly != std::string::npos) {
2587 compRes = fMetaProcessor->readInputFromFile(fname.Data(), &result,
2588 unnamedMacroOpenCurly);
2589 } else {
2590 // No DynLookup for .x, .L of named macros.
2591 fInterpreter->enableDynamicLookup(false);
2593 }
2594 fCurExecutingMacros.pop_back();
2595 }
2596 } // .L / .X / .x
2597 else {
2598 if (0!=strncmp(sLine.Data(), ".autodict ",10) && sLine != ".autodict") {
2599 // explicitly ignore .autodict without having to support it
2600 // in cling.
2601
2602 // Turn off autoparsing if this is an include directive
2603 bool isInclusionDirective = sLine.Contains("\n#include") || sLine.BeginsWith("#include");
2604 if (isInclusionDirective) {
2605 SuspendAutoParsing autoParseRaii(this);
2607 } else {
2609 }
2610 }
2611 }
2612 if (result.isValid())
2614 if (indent) {
2615 if (error)
2616 *error = kProcessing;
2617 return 0;
2618 }
2619 if (error) {
2620 switch (compRes) {
2621 case cling::Interpreter::kSuccess: *error = kNoError; break;
2622 case cling::Interpreter::kFailure: *error = kRecoverable; break;
2623 case cling::Interpreter::kMoreInputExpected: *error = kProcessing; break;
2624 }
2625 }
2626 if (compRes == cling::Interpreter::kSuccess
2627 && result.isValid()
2628 && !result.isVoid())
2629 {
2630 return result.simplisticCastAs<Longptr_t>();
2631 }
2632 return 0;
2633}
2634
2635////////////////////////////////////////////////////////////////////////////////
2636/// No-op; see TRint instead.
2637
2639{
2640}
2641
2642////////////////////////////////////////////////////////////////////////////////
2643/// \brief Add a directory to the list of directories in which the
2644/// interpreter looks for include files.
2645/// \param[in] path The path to the directory.
2646/// \note Only one path item can be specified at a time, i.e. "path1:path2" is
2647/// \b NOT supported.
2648/// \warning Only the path to the directory should be specified, without
2649/// prepending the \c -I prefix, i.e.
2650/// <tt>gCling->AddIncludePath("/path/to/my/includes")</tt>. If the
2651/// \c -I prefix is used it will be ignored.
2652void TCling::AddIncludePath(const char *path)
2653{
2655 // Favorite source of annoyance: gSystem->AddIncludePath() needs "-I",
2656 // gCling->AddIncludePath() does not! Work around that inconsistency:
2657 if (path[0] == '-' && path[1] == 'I')
2658 path += 2;
2659 TString sPath(path);
2660 gSystem->ExpandPathName(sPath);
2661 fInterpreter->AddIncludePath(sPath.Data());
2662}
2663
2664////////////////////////////////////////////////////////////////////////////////
2665/// Visit all members over members, recursing over base classes.
2666
2667void TCling::InspectMembers(TMemberInspector& insp, const void* obj,
2668 const TClass* cl, Bool_t isTransient)
2669{
2673 }
2674
2675 if (!cl || cl->GetCollectionProxy()) {
2676 // We do not need to investigate the content of the STL
2677 // collection, they are opaque to us (and details are
2678 // uninteresting).
2679 return;
2680 }
2681
2682 static const TClassRef clRefString("std::string");
2683 if (clRefString == cl) {
2684 // We stream std::string without going through members..
2685 return;
2686 }
2687
2688 if (TClassEdit::IsStdArray(cl->GetName())) {
2689 // We treat std arrays as C arrays
2690 return;
2691 }
2692
2693 const char* cobj = (const char*) obj; // for ptr arithmetics
2694
2695 // Treat the case of std::complex in a special manner. We want to enforce
2696 // the layout of a stl implementation independent class, which is the
2697 // complex as implemented in ROOT5.
2698
2699 // A simple lambda to simplify the code
2700 auto inspInspect = [&] (ptrdiff_t offset){
2701 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_real", cobj, isTransient);
2702 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_imag", cobj + offset, isTransient);
2703 };
2704
2705 auto complexType = TClassEdit::GetComplexType(cl->GetName());
2706 switch(complexType) {
2708 {
2709 break;
2710 }
2712 {
2713 inspInspect(sizeof(float));
2714 return;
2715 }
2717 {
2718 inspInspect(sizeof(double));
2719 return;
2720 }
2722 {
2723 inspInspect(sizeof(int));
2724 return;
2725 }
2727 {
2728 inspInspect(sizeof(long));
2729 return;
2730 }
2731 }
2732
2733 static clang::PrintingPolicy
2734 printPol(fInterpreter->getCI()->getLangOpts());
2735 if (printPol.Indentation) {
2736 // not yet initialized
2737 printPol.Indentation = 0;
2738 printPol.SuppressInitializers = true;
2739 }
2740
2741 const char* clname = cl->GetName();
2742 // Printf("Inspecting class %s\n", clname);
2743
2744 const clang::ASTContext& astContext = fInterpreter->getCI()->getASTContext();
2745 const clang::Decl *scopeDecl = 0;
2746 const clang::Type *recordType = 0;
2747
2748 if (cl->GetClassInfo()) {
2749 TClingClassInfo * clingCI = (TClingClassInfo *)cl->GetClassInfo();
2750 scopeDecl = clingCI->GetDecl();
2751 recordType = clingCI->GetType();
2752 } else {
2753 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
2754 // Diags will complain about private classes:
2755 scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2756 &recordType);
2757 }
2758 if (!scopeDecl) {
2759 Error("InspectMembers", "Cannot find Decl for class %s", clname);
2760 return;
2761 }
2762 const clang::CXXRecordDecl* recordDecl
2763 = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2764 if (!recordDecl) {
2765 Error("InspectMembers", "Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2766 return;
2767 }
2768
2769 {
2770 // Force possible deserializations first. We need to have no pending
2771 // Transaction when passing control flow to the inspector below (ROOT-7779).
2772 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2773
2774 astContext.getASTRecordLayout(recordDecl);
2775
2776 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2777 eField = recordDecl->field_end(); iField != eField; ++iField) {}
2778 }
2779
2780 const clang::ASTRecordLayout& recLayout
2781 = astContext.getASTRecordLayout(recordDecl);
2782
2783 // TVirtualCollectionProxy *proxy = cl->GetCollectionProxy();
2784 // if (proxy && ( proxy->GetProperties() & TVirtualCollectionProxy::kIsEmulated ) ) {
2785 // Error("InspectMembers","The TClass for %s has an emulated proxy but we are looking at a compiled version of the collection!\n",
2786 // cl->GetName());
2787 // }
2788 if (cl->Size() != recLayout.getSize().getQuantity()) {
2789 Error("InspectMembers","TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2790 cl->GetName(),cl->Size(),(Long64_t)recLayout.getSize().getQuantity());
2791 }
2792
2793 unsigned iNField = 0;
2794 // iterate over fields
2795 // FieldDecls are non-static, else it would be a VarDecl.
2796 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2797 eField = recordDecl->field_end(); iField != eField;
2798 ++iField, ++iNField) {
2799
2800
2801 clang::QualType memberQT = iField->getType();
2802 if (recordType) {
2803 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2804 memberQT = ROOT::TMetaUtils::ReSubstTemplateArg(memberQT, recordType);
2805 }
2806 memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2807 if (memberQT.isNull()) {
2808 std::string memberName;
2809 llvm::raw_string_ostream stream(memberName);
2810 // Don't trigger fopen of the source file to count lines:
2811 printPol.AnonymousTagLocations = false;
2812 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2813 stream.flush();
2814 Error("InspectMembers",
2815 "Cannot retrieve QualType for member %s while inspecting class %s",
2816 memberName.c_str(), clname);
2817 continue; // skip member
2818 }
2819 const clang::Type* memType = memberQT.getTypePtr();
2820 if (!memType) {
2821 std::string memberName;
2822 llvm::raw_string_ostream stream(memberName);
2823 // Don't trigger fopen of the source file to count lines:
2824 printPol.AnonymousTagLocations = false;
2825 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2826 stream.flush();
2827 Error("InspectMembers",
2828 "Cannot retrieve Type for member %s while inspecting class %s",
2829 memberName.c_str(), clname);
2830 continue; // skip member
2831 }
2832
2833 const clang::Type* memNonPtrType = memType;
2834 Bool_t ispointer = false;
2835 if (memNonPtrType->isPointerType()) {
2836 ispointer = true;
2837 clang::QualType ptrQT
2838 = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2839 if (recordType) {
2840 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2841 ptrQT = ROOT::TMetaUtils::ReSubstTemplateArg(ptrQT, recordType);
2842 }
2843 ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2844 if (ptrQT.isNull()) {
2845 std::string memberName;
2846 llvm::raw_string_ostream stream(memberName);
2847 // Don't trigger fopen of the source file to count lines:
2848 printPol.AnonymousTagLocations = false;
2849 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2850 stream.flush();
2851 Error("InspectMembers",
2852 "Cannot retrieve pointee Type for member %s while inspecting class %s",
2853 memberName.c_str(), clname);
2854 continue; // skip member
2855 }
2856 memNonPtrType = ptrQT.getTypePtr();
2857 }
2858
2859 // assemble array size(s): "[12][4][]"
2860 llvm::SmallString<8> arraySize;
2861 const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2862 unsigned arrLevel = 0;
2863 bool haveErrorDueToArray = false;
2864 while (arrType) {
2865 ++arrLevel;
2866 arraySize += '[';
2867 const clang::ConstantArrayType* constArrType =
2868 clang::dyn_cast<clang::ConstantArrayType>(arrType);
2869 if (constArrType) {
2870 constArrType->getSize().toStringUnsigned(arraySize);
2871 }
2872 arraySize += ']';
2873 clang::QualType subArrQT = arrType->getElementType();
2874 if (subArrQT.isNull()) {
2875 std::string memberName;
2876 llvm::raw_string_ostream stream(memberName);
2877 // Don't trigger fopen of the source file to count lines:
2878 printPol.AnonymousTagLocations = false;
2879 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2880 stream.flush();
2881 Error("InspectMembers",
2882 "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2883 arrLevel, subArrQT.getAsString(printPol).c_str(),
2884 memberName.c_str(), clname);
2885 haveErrorDueToArray = true;
2886 break;
2887 }
2888 arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2889 }
2890 if (haveErrorDueToArray) {
2891 continue; // skip member
2892 }
2893
2894 // construct member name
2895 std::string fieldName;
2896 if (memType->isPointerType()) {
2897 fieldName = "*";
2898 }
2899
2900 // Check if this field has a custom ioname, if not, just use the one of the decl
2901 std::string ioname(iField->getName());
2903 fieldName += ioname;
2904 fieldName += arraySize;
2905
2906 // get member offset
2907 // NOTE currently we do not support bitfield and do not support
2908 // member that are not aligned on 'bit' boundaries.
2909 clang::CharUnits offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2910 ptrdiff_t fieldOffset = offset.getQuantity();
2911
2912 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fBits[2]", fBits);
2913 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fName", &fName);
2914 // R__insp.InspectMember(fName, "fName.");
2915 // R__insp.Inspect(R__cl, R__insp.GetParent(), "*fClass", &fClass);
2916
2917 // If the class has a custom streamer and the type of the filed is a
2918 // private enum, struct or class, skip it.
2919 if (!insp.IsTreatingNonAccessibleTypes()){
2920 auto iFiledQtype = iField->getType();
2921 if (auto tagDecl = iFiledQtype->getAsTagDecl()){
2922 auto declAccess = tagDecl->getAccess();
2923 if (declAccess == AS_private || declAccess == AS_protected) {
2924 continue;
2925 }
2926 }
2927 }
2928
2929 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
2930
2931 if (!ispointer) {
2932 const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
2933 if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
2934 // nested objects get an extra call to InspectMember
2935 // R__insp.InspectMember("FileStat_t", (void*)&fFileStat, "fFileStat.", false);
2936 std::string sFieldRecName;
2937 if (!ROOT::TMetaUtils::ExtractAttrPropertyFromName(*fieldRecDecl,"iotype",sFieldRecName)){
2939 clang::QualType(memNonPtrType,0),
2940 *fInterpreter,
2942 }
2943
2944 TDataMember* mbr = cl->GetDataMember(ioname.c_str());
2945 // if we can not find the member (which should not really happen),
2946 // let's consider it transient.
2947 Bool_t transient = isTransient || !mbr || !mbr->IsPersistent();
2948
2949 insp.InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
2950 (fieldName + '.').c_str(), transient);
2951
2952 }
2953 }
2954 } // loop over fields
2955
2956 // inspect bases
2957 // TNamed::ShowMembers(R__insp);
2958 unsigned iNBase = 0;
2959 for (clang::CXXRecordDecl::base_class_const_iterator iBase
2960 = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
2961 iBase != eBase; ++iBase, ++iNBase) {
2962 clang::QualType baseQT = iBase->getType();
2963 if (baseQT.isNull()) {
2964 Error("InspectMembers",
2965 "Cannot find QualType for base number %d while inspecting class %s",
2966 iNBase, clname);
2967 continue;
2968 }
2969 const clang::CXXRecordDecl* baseDecl
2970 = baseQT->getAsCXXRecordDecl();
2971 if (!baseDecl) {
2972 Error("InspectMembers",
2973 "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
2974 iNBase, clname);
2975 continue;
2976 }
2977 TClass* baseCl=nullptr;
2978 std::string sBaseName;
2979 // Try with the DeclId
2980 std::vector<TClass*> foundClasses;
2981 TClass::GetClass(static_cast<DeclId_t>(baseDecl), foundClasses);
2982 if (foundClasses.size()==1){
2983 baseCl=foundClasses[0];
2984 } else {
2985 // Try with the normalised Name, as a fallback
2986 if (!baseCl){
2988 baseQT,
2989 *fInterpreter,
2991 baseCl = TClass::GetClass(sBaseName.c_str());
2992 }
2993 }
2994
2995 if (!baseCl){
2996 std::string qualNameForDiag;
2997 ROOT::TMetaUtils::GetQualifiedName(qualNameForDiag, *baseDecl);
2998 Error("InspectMembers",
2999 "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
3000 continue;
3001 }
3002
3003 int64_t baseOffset;
3004 if (iBase->isVirtual()) {
3006 if (!isTransient) {
3007 Error("InspectMembers",
3008 "Base %s of class %s is virtual but no object provided",
3009 sBaseName.c_str(), clname);
3010 }
3012 } else {
3013 // We have an object to determine the vbase offset.
3015 TClingClassInfo* baseCi = (TClingClassInfo*)baseCl->GetClassInfo();
3016 if (ci && baseCi) {
3017 baseOffset = ci->GetBaseOffset(baseCi, const_cast<void*>(obj),
3018 true /*isDerivedObj*/);
3019 if (baseOffset == -1) {
3020 Error("InspectMembers",
3021 "Error calculating offset of virtual base %s of class %s",
3022 sBaseName.c_str(), clname);
3023 }
3024 } else {
3025 Error("InspectMembers",
3026 "Cannot calculate offset of virtual base %s of class %s",
3027 sBaseName.c_str(), clname);
3028 continue;
3029 }
3030 }
3031 } else {
3032 baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
3033 }
3034 // TOFIX: baseCl can be null here!
3035 if (baseCl->IsLoaded()) {
3036 // For loaded class, CallShowMember will (especially for TObject)
3037 // call the virtual ShowMember rather than the class specific version
3038 // resulting in an infinite recursion.
3039 InspectMembers(insp, cobj + baseOffset, baseCl, isTransient);
3040 } else {
3041 baseCl->CallShowMembers(cobj + baseOffset,
3042 insp, isTransient);
3043 }
3044 } // loop over bases
3045}
3046
3047////////////////////////////////////////////////////////////////////////////////
3048/// Reset the interpreter internal state in case a previous action was not correctly
3049/// terminated.
3050
3052{
3053 // No-op there is not equivalent state (to be cleared) in Cling.
3054}
3055
3056////////////////////////////////////////////////////////////////////////////////
3057/// Delete existing temporary values.
3058
3060{
3061 // No-op for cling due to cling::Value.
3062}
3063
3064////////////////////////////////////////////////////////////////////////////////
3065/// Declare code to the interpreter, without any of the interpreter actions
3066/// that could trigger a re-interpretation of the code. I.e. make cling
3067/// behave like a compiler: no dynamic lookup, no input wrapping for
3068/// subsequent execution, no automatic provision of declarations but just a
3069/// plain `#include`.
3070/// Returns true on success, false on failure.
3071
3072bool TCling::Declare(const char* code)
3073{
3075
3076 SuspendAutoLoadingRAII autoLoadOff(this);
3077 SuspendAutoParsing autoParseRaii(this);
3078
3079 bool oldDynLookup = fInterpreter->isDynamicLookupEnabled();
3080 fInterpreter->enableDynamicLookup(false);
3081 bool oldRawInput = fInterpreter->isRawInputEnabled();
3082 fInterpreter->enableRawInput(true);
3083
3084 Bool_t ret = LoadText(code);
3085
3086 fInterpreter->enableRawInput(oldRawInput);
3087 fInterpreter->enableDynamicLookup(oldDynLookup);
3088 return ret;
3089}
3090
3091////////////////////////////////////////////////////////////////////////////////
3092/// It calls a "fantom" method to synchronize user keyboard input
3093/// and ROOT prompt line.
3094
3096{
3098}
3099
3100// This static function is a hop of TCling::IsLibraryLoaded, which is taking a lock and calling
3101// into this function. This is because we wanted to avoid a duplication in TCling::IsLoaded, which
3102// was already taking a lock.
3103static Bool_t s_IsLibraryLoaded(const char* libname, cling::Interpreter* fInterpreter)
3104{
3105 // Check shared library.
3106 TString tLibName(libname);
3107 if (gSystem->FindDynamicLibrary(tLibName, kTRUE))
3108 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.Data());
3109 return false;
3110}
3111
3112Bool_t TCling::IsLibraryLoaded(const char* libname) const
3113{
3115 return s_IsLibraryLoaded(libname, GetInterpreterImpl());
3116}
3117
3118////////////////////////////////////////////////////////////////////////////////
3119/// Return true if ROOT has cxxmodules pcm for a given library name.
3120// FIXME: We need to be able to support lazy loading of pcm generated by ACLiC.
3121Bool_t TCling::HasPCMForLibrary(const char *libname) const
3122{
3123 llvm::StringRef ModuleName(libname);
3124 ModuleName = llvm::sys::path::stem(ModuleName);
3125 ModuleName.consume_front("lib");
3126
3127 // FIXME: In case when the modulemap is not yet loaded we will return the
3128 // wrong result. Consider a call to HasPCMForLibrary(../test/libEvent.so)
3129 // We will only load the modulemap for libEvent.so after we dlopen libEvent
3130 // which may happen after calling this interface. Maybe we should also check
3131 // if there is a Event.pcm file and a module.modulemap, load it and return
3132 // true.
3133 clang::ModuleMap &moduleMap = fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
3134 clang::Module *M = moduleMap.findModule(ModuleName);
3135 return M && !M->IsMissingRequirement && M->getASTFile();
3136}
3137
3138////////////////////////////////////////////////////////////////////////////////
3139/// Return true if the file has already been loaded by cint.
3140/// We will try in this order:
3141/// actual filename
3142/// filename as a path relative to
3143/// the include path
3144/// the shared library path
3145
3147{
3149
3150 //FIXME: if we use llvm::sys::fs::make_absolute all this can go away. See
3151 // cling::DynamicLibraryManager.
3152
3153 std::string file_name = filename;
3154 size_t at = std::string::npos;
3155 while ((at = file_name.find("/./")) != std::string::npos)
3156 file_name.replace(at, 3, "/");
3157
3158 std::string filesStr = "";
3159 llvm::raw_string_ostream filesOS(filesStr);
3160 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3161 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3162 filesOS.flush();
3163
3164 llvm::SmallVector<llvm::StringRef, 100> files;
3165 llvm::StringRef(filesStr).split(files, "\n");
3166
3167 std::set<std::string> fileMap;
3168 // Fill fileMap; return early on exact match.
3169 for (llvm::SmallVector<llvm::StringRef, 100>::const_iterator
3170 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3171 if ((*iF) == file_name.c_str()) return kTRUE; // exact match
3172 fileMap.insert(*iF);
3173 }
3174
3175 if (fileMap.empty()) return kFALSE;
3176
3177 // Check MacroPath.
3178 TString sFilename(file_name.c_str());
3180 && fileMap.count(sFilename.Data())) {
3181 return kTRUE;
3182 }
3183
3184 // Check IncludePath.
3185 TString incPath = gSystem->GetIncludePath(); // of the form -Idir1 -Idir2 -Idir3
3186 incPath.Append(":").Prepend(" "); // to match " -I" (note leading ' ')
3187 incPath.ReplaceAll(" -I", ":"); // of form :dir1 :dir2:dir3
3188 while (incPath.Index(" :") != -1) {
3189 incPath.ReplaceAll(" :", ":");
3190 }
3191 incPath.Prepend(".:");
3192 sFilename = file_name.c_str();
3193 if (gSystem->FindFile(incPath, sFilename, kReadPermission)
3194 && fileMap.count(sFilename.Data())) {
3195 return kTRUE;
3196 }
3197
3198 // Check shared library.
3199 if (s_IsLibraryLoaded(file_name.c_str(), GetInterpreterImpl()))
3200 return kTRUE;
3201
3202 //FIXME: We must use the cling::Interpreter::lookupFileOrLibrary iface.
3203 const clang::DirectoryLookup *CurDir = 0;
3204 clang::Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
3205 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3206 const clang::FileEntry *FE = HS.LookupFile(file_name.c_str(),
3207 clang::SourceLocation(),
3208 /*isAngled*/ false,
3209 /*FromDir*/ 0, CurDir,
3210 clang::ArrayRef<std::pair<const clang::FileEntry *,
3211 const clang::DirectoryEntry *>>(),
3212 /*SearchPath*/ 0,
3213 /*RelativePath*/ 0,
3214 /*RequestingModule*/ 0,
3215 /*SuggestedModule*/ 0,
3216 /*IsMapped*/ 0,
3217 /*IsFrameworkFound*/ nullptr,
3218 /*SkipCache*/ false,
3219 /*BuildSystemModule*/ false,
3220 /*OpenFile*/ false,
3221 /*CacheFail*/ false);
3222 if (FE && FE->isValid()) {
3223 // check in the source manager if the file is actually loaded
3224 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3225 // this works only with header (and source) files...
3226 clang::FileID FID = SM.translateFile(FE);
3227 if (!FID.isInvalid() && FID.getHashValue() == 0)
3228 return kFALSE;
3229 else {
3230 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3231 if (SLocE.isFile() && SLocE.getFile().getContentCache()->getRawBuffer() == 0)
3232 return kFALSE;
3233 if (!FID.isInvalid())
3234 return kTRUE;
3235 }
3236 // ...then check shared library again, but with full path now
3237 sFilename = FE->getName();
3238 if (gSystem->FindDynamicLibrary(sFilename, kTRUE)
3239 && fileMap.count(sFilename.Data())) {
3240 return kTRUE;
3241 }
3242 }
3243 return kFALSE;
3244}
3245
3246
3247#if defined(R__MACOSX)
3248
3249////////////////////////////////////////////////////////////////////////////////
3250/// Check if lib is in the dynamic linker cache, returns true if it is, and if so,
3251/// modifies the library file name parameter `lib` from `/usr/lib/libFOO.dylib`
3252/// to `-lFOO` such that it can be passed to the linker.
3253/// This is a unique feature of macOS 11.
3254
3255static bool R__UpdateLibFileForLinking(TString &lib)
3256{
3257 const char *mapfile = nullptr;
3258#if __x86_64__
3259 mapfile = "/System/Library/dyld/dyld_shared_cache_x86_64.map";
3260#elif __arm64__
3261 mapfile = "/System/Library/dyld/dyld_shared_cache_arm64e.map";
3262#else
3263 #error unsupported architecture
3264#endif
3265 if (std::ifstream cacheMap{mapfile}) {
3266 std::string line;
3267 while (getline(cacheMap, line)) {
3268 if (line.find(lib) != std::string::npos) {
3269 lib.ReplaceAll("/usr/lib/lib","-l");
3270 lib.ReplaceAll(".dylib","");
3271 return true;
3272 }
3273 }
3274 return false;
3275 }
3276 return false;
3277}
3278#endif // R__MACOSX
3279
3280#ifdef R__LINUX
3281
3282////////////////////////////////////////////////////////////////////////////////
3283/// Callback for dl_iterate_phdr(), see `man dl_iterate_phdr`.
3284/// Collects opened libraries.
3285
3286static int callback_for_dl_iterate_phdr(struct dl_phdr_info *info, size_t size, void *data)
3287{
3288 // This function is called through UpdateListOfLoadedSharedLibraries() which is locked.
3289 static std::unordered_set<decltype(info->dlpi_addr)> sKnownLoadedLibBaseAddrs;
3290
3291 auto newLibs = static_cast<std::vector<std::string>*>(data);
3292 if (!sKnownLoadedLibBaseAddrs.count(info->dlpi_addr)) {
3293 // Skip \0, "", and kernel pseudo-libs linux-vdso.so.1 or linux-gate.so.1
3294 if (info->dlpi_name && info->dlpi_name[0]
3295 && strncmp(info->dlpi_name, "linux-vdso.so", 13)
3296 && strncmp(info->dlpi_name, "linux-vdso32.so", 15)
3297 && strncmp(info->dlpi_name, "linux-vdso64.so", 15)
3298 && strncmp(info->dlpi_name, "linux-gate.so", 13))
3299 newLibs->emplace_back(info->dlpi_name);
3300 sKnownLoadedLibBaseAddrs.insert(info->dlpi_addr);
3301 }
3302 // No matter what the doc says, return != 0 means "stop the iteration".
3303 return 0;
3304}
3305
3306#endif // R__LINUX
3307
3308
3309////////////////////////////////////////////////////////////////////////////////
3310
3312{
3313#if defined(R__WIN32) || defined(__CYGWIN__)
3314 HMODULE hModules[1024];
3315 void *hProcess;
3316 unsigned long cbModules;
3317 unsigned int i;
3318 hProcess = (void *)::GetCurrentProcess();
3319 ::EnumProcessModules(hProcess, hModules, sizeof(hModules), &cbModules);
3320 // start at 1 to skip the executable itself
3321 for (i = 1; i < (cbModules / sizeof(void *)); i++) {
3322 static const int bufsize = 260;
3323 wchar_t winname[bufsize];
3324 char posixname[bufsize];
3325 ::GetModuleFileNameExW(hProcess, hModules[i], winname, bufsize);
3326#if defined(__CYGWIN__)
3327 cygwin_conv_path(CCP_WIN_W_TO_POSIX, winname, posixname, bufsize);
3328#else
3329 std::wstring wpath = winname;
3330 std::replace(wpath.begin(), wpath.end(), '\\', '/');
3331 string path(wpath.begin(), wpath.end());
3332 strncpy(posixname, path.c_str(), bufsize);
3333#endif
3334 if (!fSharedLibs.Contains(posixname)) {
3335 RegisterLoadedSharedLibrary(posixname);
3336 }
3337 }
3338#elif defined(R__MACOSX)
3339 // fPrevLoadedDynLibInfo stores the *next* image index to look at
3340 uint32_t imageIndex = (uint32_t) (size_t) fPrevLoadedDynLibInfo;
3341
3342 while (const mach_header* mh = _dyld_get_image_header(imageIndex)) {
3343 // Skip non-dylibs
3344 if (mh->filetype == MH_DYLIB) {
3345 if (const char* imageName = _dyld_get_image_name(imageIndex)) {
3346 RegisterLoadedSharedLibrary(imageName);
3347 }
3348 }
3349
3350 ++imageIndex;
3351 }
3352 fPrevLoadedDynLibInfo = (void*)(size_t)imageIndex;
3353#elif defined(R__LINUX)
3354 // fPrevLoadedDynLibInfo is unused on Linux.
3356
3357 std::vector<std::string> newLibs;
3358 dl_iterate_phdr(callback_for_dl_iterate_phdr, &newLibs);
3359 for (auto &&lib: newLibs)
3360 RegisterLoadedSharedLibrary(lib.c_str());
3361#else
3362 Error("TCling::UpdateListOfLoadedSharedLibraries",
3363 "Platform not supported!");
3364#endif
3365}
3366
3367////////////////////////////////////////////////////////////////////////////////
3368/// Register a new shared library name with the interpreter; add it to
3369/// fSharedLibs.
3370
3372{
3373 // Ignore NULL filenames, aka "the process".
3374 if (!filename) return;
3375
3376 // Tell the interpreter that this library is available; all libraries can be
3377 // used to resolve symbols.
3378 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3379 if (!DLM->isLibraryLoaded(filename)) {
3380 DLM->loadLibrary(filename, true /*permanent*/, true /*resolved*/);
3381 }
3382
3383#if defined(R__MACOSX)
3384 // Check that this is not a system library
3385 auto lenFilename = strlen(filename);
3386 if (!strncmp(filename, "/usr/lib/system/", 16)
3387 || !strncmp(filename, "/usr/lib/libc++", 15)
3388 || !strncmp(filename, "/System/Library/Frameworks/", 27)
3389 || !strncmp(filename, "/System/Library/PrivateFrameworks/", 34)
3390 || !strncmp(filename, "/System/Library/CoreServices/", 29)
3391 || !strcmp(filename, "cl_kernels") // yepp, no directory
3392 || strstr(filename, "/usr/lib/libSystem")
3393 || strstr(filename, "/usr/lib/libstdc++")
3394 || strstr(filename, "/usr/lib/libicucore")
3395 || strstr(filename, "/usr/lib/libbsm")
3396 || strstr(filename, "/usr/lib/libobjc")
3397 || strstr(filename, "/usr/lib/libresolv")
3398 || strstr(filename, "/usr/lib/libauto")
3399 || strstr(filename, "/usr/lib/libcups")
3400 || strstr(filename, "/usr/lib/libDiagnosticMessagesClient")
3401 || strstr(filename, "/usr/lib/liblangid")
3402 || strstr(filename, "/usr/lib/libCRFSuite")
3403 || strstr(filename, "/usr/lib/libpam")
3404 || strstr(filename, "/usr/lib/libOpenScriptingUtil")
3405 || strstr(filename, "/usr/lib/libextension")
3406 || strstr(filename, "/usr/lib/libAudioToolboxUtility")
3407 || strstr(filename, "/usr/lib/liboah")
3408 || strstr(filename, "/usr/lib/libRosetta")
3409 || strstr(filename, "/usr/lib/libCoreEntitlements")
3410 || strstr(filename, "/usr/lib/libssl.")
3411 || strstr(filename, "/usr/lib/libcrypto.")
3412 // These are candidates for suppression, too:
3413 // -lfakelink -lapple_nghttp2 -lnetwork -lsqlite3 -lenergytrace -lCoreEntitlements
3414 // -lMobileGestalt -lcoretls -lcoretls_cfhelpers -lxar.1 -lcompression -larchive.2
3415 // -lxml2.2 -lpcap.A -ldns_services -llzma.5 -lbz2.1.0 -liconv.2 -lcharset.1
3416 // -lCheckFix -lmecabra -lmecab -lgermantok -lThaiTokenizer -lChineseTokenizer
3417 // -lcmph -lutil -lapp_launch_measurement -lxslt.1 -lspindump -late -lexpat.1
3418 // -lAudioStatistics -lSMC -lperfcheck -lmis -lIOReport -lheimdal-asn1
3419
3420 // "cannot link directly with dylib/framework, your binary is not an allowed client of
3421 // /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/
3422 // SDKs/MacOSX.sdk/usr/lib/libAudioToolboxUtility.tbd for architecture x86_64
3423 || (lenFilename > 4 && !strcmp(filename + lenFilename - 4, ".tbd")))
3424 return;
3425 TString sFileName(filename);
3426 R__UpdateLibFileForLinking(sFileName);
3427 filename = sFileName.Data();
3428#elif defined(__CYGWIN__)
3429 // Check that this is not a system library
3430 static const int bufsize = 260;
3431 char posixwindir[bufsize];
3432 char *windir = getenv("WINDIR");
3433 if (windir)
3434 cygwin_conv_path(CCP_WIN_A_TO_POSIX, windir, posixwindir, bufsize);
3435 else
3436 snprintf(posixwindir, sizeof(posixwindir), "/Windows/");
3437 if (strstr(filename, posixwindir) ||
3438 strstr(filename, "/usr/bin/cyg"))
3439 return;
3440#elif defined(R__WIN32)
3441 if (strstr(filename, "/Windows/"))
3442 return;
3443#elif defined (R__LINUX)
3444 if (strstr(filename, "/ld-linux")
3445 || strstr(filename, "linux-gnu/")
3446 || strstr(filename, "/libstdc++.")
3447 || strstr(filename, "/libgcc")
3448 || strstr(filename, "/libc.")
3449 || strstr(filename, "/libdl.")
3450 || strstr(filename, "/libm."))
3451 return;
3452#endif
3453 // Update string of available libraries.
3454 if (!fSharedLibs.IsNull()) {
3455 fSharedLibs.Append(" ");
3456 }
3458}
3459
3460////////////////////////////////////////////////////////////////////////////////
3461/// Load a library file in cling's memory.
3462/// if 'system' is true, the library is never unloaded.
3463/// Return 0 on success, -1 on failure.
3464
3465Int_t TCling::Load(const char* filename, Bool_t system)
3466{
3467 assert(!IsFromRootCling() && "Trying to load library from rootcling!");
3468
3469 // Used to return 0 on success, 1 on duplicate, -1 on failure, -2 on "fatal".
3471 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3472 std::string canonLib = DLM->lookupLibrary(filename);
3473 cling::DynamicLibraryManager::LoadLibResult res
3474 = cling::DynamicLibraryManager::kLoadLibNotFound;
3475 if (!canonLib.empty()) {
3476 if (system)
3477 res = DLM->loadLibrary(filename, system, true);
3478 else {
3479 // For the non system libs, we'd like to be able to unload them.
3480 // FIXME: Here we lose the information about kLoadLibAlreadyLoaded case.
3481 cling::Interpreter::CompilationResult compRes;
3482 HandleInterpreterException(GetMetaProcessorImpl(), Form(".L %s", canonLib.c_str()), compRes, /*cling::Value*/0);
3483 if (compRes == cling::Interpreter::kSuccess)
3484 res = cling::DynamicLibraryManager::kLoadLibSuccess;
3485 }
3486 }
3487
3488 if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3490 }
3491 switch (res) {
3492 case cling::DynamicLibraryManager::kLoadLibSuccess: return 0;
3493 case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded: return 1;
3494 default: break;
3495 };
3496 return -1;
3497}
3498
3499////////////////////////////////////////////////////////////////////////////////
3500/// Load a macro file in cling's memory.
3501
3502void TCling::LoadMacro(const char* filename, EErrorCode* error)
3503{
3504 ProcessLine(Form(".L %s", filename), error);
3505}
3506
3507////////////////////////////////////////////////////////////////////////////////
3508/// Let cling process a command line asynch.
3509
3511{
3512 return ProcessLine(line, error);
3513}
3514
3515////////////////////////////////////////////////////////////////////////////////
3516/// Let cling process a command line synchronously, i.e we are waiting
3517/// it will be finished.
3518
3520{
3522 if (gApplication) {
3523 if (gApplication->IsCmdThread()) {
3524 return ProcessLine(line, error);
3525 }
3526 return 0;
3527 }
3528 return ProcessLine(line, error);
3529}
3530
3531////////////////////////////////////////////////////////////////////////////////
3532/// Directly execute an executable statement (e.g. "func()", "3+5", etc.
3533/// however not declarations, like "Int_t x;").
3534
3536{
3537#ifdef R__WIN32
3538 // Test on ApplicationImp not being 0 is needed because only at end of
3539 // TApplication ctor the IsLineProcessing flag is set to 0, so before
3540 // we can not use it.
3542 while (gROOT->IsLineProcessing() && !gApplication) {
3543 Warning("Calc", "waiting for cling thread to free");
3544 gSystem->Sleep(500);
3545 }
3546 gROOT->SetLineIsProcessing();
3547 }
3548#endif // R__WIN32
3550 if (error) {
3551 *error = TInterpreter::kNoError;
3552 }
3553 cling::Value valRef;
3554 cling::Interpreter::CompilationResult cr = cling::Interpreter::kFailure;
3555 try {
3556 cr = fInterpreter->evaluate(line, valRef);
3557 }
3558 catch (cling::InterpreterException& ex)
3559 {
3560 Error("Calc", "%s.\n%s", ex.what(), "Evaluation of your expression was aborted.");
3561 ex.diagnose();
3562 cr = cling::Interpreter::kFailure;
3563 }
3564
3565 if (cr != cling::Interpreter::kSuccess) {
3566 // Failure in compilation.
3567 if (error) {
3568 // Note: Yes these codes are weird.
3570 }
3571 return 0L;
3572 }
3573 if (!valRef.isValid()) {
3574 // Failure at runtime.
3575 if (error) {
3576 // Note: Yes these codes are weird.
3577 *error = TInterpreter::kDangerous;
3578 }
3579 return 0L;
3580 }
3581
3582 if (valRef.isVoid()) {
3583 return 0;
3584 }
3585
3586 RegisterTemporary(valRef);
3587#ifdef R__WIN32
3589 gROOT->SetLineHasBeenProcessed();
3590 }
3591#endif // R__WIN32
3592 return valRef.simplisticCastAs<Longptr_t>();
3593}
3594
3595////////////////////////////////////////////////////////////////////////////////
3596/// Set a getline function to call when input is needed.
3597
3598void TCling::SetGetline(const char * (*getlineFunc)(const char* prompt),
3599 void (*histaddFunc)(const char* line))
3600{
3601 // If cling offers a replacement for G__pause(), it would need to
3602 // also offer a way to customize at least the history recording.
3603
3604#if defined(R__MUST_REVISIT)
3605#if R__MUST_REVISIT(6,2)
3606 Warning("SetGetline","Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3607#endif
3608#endif
3609}
3610
3611////////////////////////////////////////////////////////////////////////////////
3612/// Helper function to increase the internal Cling count of transactions
3613/// that change the AST.
3614
3615Bool_t TCling::HandleNewTransaction(const cling::Transaction &T)
3616{
3618
3619 if ((std::distance(T.decls_begin(), T.decls_end()) != 1)
3620 || T.deserialized_decls_begin() != T.deserialized_decls_end()
3621 || T.macros_begin() != T.macros_end()
3622 || ((!T.getFirstDecl().isNull()) && ((*T.getFirstDecl().begin()) != T.getWrapperFD()))) {
3624 return true;
3625 }
3626 return false;
3627}
3628
3629////////////////////////////////////////////////////////////////////////////////
3630/// Delete object from cling symbol table so it can not be used anymore.
3631/// cling objects are always on the heap.
3632
3634{
3635 // NOTE: When replacing the mutex by a ReadWrite mutex, we **must**
3636 // put in place the Read/Write part here. Keeping the write lock
3637 // here is 'catasptrophic' for scaling as it means that ALL calls
3638 // to RecursiveRemove will take the write lock and performance
3639 // of many threads trying to access the write lock at the same
3640 // time is relatively bad.
3642 // Note that fgSetOfSpecials is supposed to be updated by TClingCallbacks::tryFindROOTSpecialInternal
3643 // (but isn't at the moment).
3644 if (obj->IsOnHeap() && fgSetOfSpecials && !((std::set<TObject*>*)fgSetOfSpecials)->empty()) {
3645 std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)fgSetOfSpecials)->find(obj);
3646 if (iSpecial != ((std::set<TObject*>*)fgSetOfSpecials)->end()) {
3648 DeleteGlobal(obj);
3649 ((std::set<TObject*>*)fgSetOfSpecials)->erase(iSpecial);
3650 }
3651 }
3652}
3653
3654////////////////////////////////////////////////////////////////////////////////
3655/// Pressing Ctrl+C should forward here. In the case where we have had
3656/// continuation requested we must reset it.
3657
3659{
3660 fMetaProcessor->cancelContinuation();
3661 // Reset the Cling state to the state saved by the last call to
3662 // TCling::SaveContext().
3663#if defined(R__MUST_REVISIT)
3664#if R__MUST_REVISIT(6,2)
3666 Warning("Reset","Cling should support the equivalent of scratch_upto(&fDictPos)");
3667#endif
3668#endif
3669}
3670
3671////////////////////////////////////////////////////////////////////////////////
3672/// Reset the Cling state to its initial state.
3673
3675{
3676#if defined(R__MUST_REVISIT)
3677#if R__MUST_REVISIT(6,2)
3679 Warning("ResetAll","Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3680#endif
3681#endif
3682}
3683
3684////////////////////////////////////////////////////////////////////////////////
3685/// Reset in Cling the list of global variables to the state saved by the last
3686/// call to TCling::SaveGlobalsContext().
3687///
3688/// Note: Right now, all we do is run the global destructors.
3689
3691{
3693 // TODO:
3694 // Here we should iterate over the transactions (N-3) and revert.
3695 // N-3 because the first three internal to cling.
3696
3697 fInterpreter->runAndRemoveStaticDestructors();
3698}
3699
3700////////////////////////////////////////////////////////////////////////////////
3701/// Reset the Cling 'user' global objects/variables state to the state saved by the last
3702/// call to TCling::SaveGlobalsContext().
3703
3705{
3706#if defined(R__MUST_REVISIT)
3707#if R__MUST_REVISIT(6,2)
3709 Warning("ResetGlobalVar","Cling should support the equivalent of resetglobalvar(obj)");
3710#endif
3711#endif
3712}
3713
3714////////////////////////////////////////////////////////////////////////////////
3715/// Rewind Cling dictionary to the point where it was before executing
3716/// the current macro. This function is typically called after SEGV or
3717/// ctlr-C after doing a longjmp back to the prompt.
3718
3720{
3721#if defined(R__MUST_REVISIT)
3722#if R__MUST_REVISIT(6,2)
3724 Warning("RewindDictionary","Cling should provide a way to revert transaction similar to rewinddictionary()");
3725#endif
3726#endif
3727}
3728
3729////////////////////////////////////////////////////////////////////////////////
3730/// Delete obj from Cling symbol table so it cannot be accessed anymore.
3731/// Returns 1 in case of success and 0 in case object was not in table.
3732
3734{
3735#if defined(R__MUST_REVISIT)
3736#if R__MUST_REVISIT(6,2)
3738 Warning("DeleteGlobal","Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3739#endif
3740#endif
3741 return 0;
3742}
3743
3744////////////////////////////////////////////////////////////////////////////////
3745/// Undeclare obj called name.
3746/// Returns 1 in case of success, 0 for failure.
3747
3749{
3750#if defined(R__MUST_REVISIT)
3751#if R__MUST_REVISIT(6,2)
3752 Warning("DeleteVariable","should do more that just reseting the value to zero");
3753#endif
3754#endif
3755
3757 llvm::StringRef srName(name);
3758 const char* unscopedName = name;
3759 llvm::StringRef::size_type posScope = srName.rfind("::");
3760 const clang::DeclContext* declCtx = 0;
3761 if (posScope != llvm::StringRef::npos) {
3762 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3763 const clang::Decl* scopeDecl
3764 = lh.findScope(srName.substr(0, posScope),
3765 cling::LookupHelper::WithDiagnostics);
3766 if (!scopeDecl) {
3767 Error("DeleteVariable", "Cannot find enclosing scope for variable %s",
3768 name);
3769 return 0;
3770 }
3771 declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3772 if (!declCtx) {
3773 Error("DeleteVariable",
3774 "Enclosing scope for variable %s is not a declaration context",
3775 name);
3776 return 0;
3777 }
3778 unscopedName += posScope + 2;
3779 }
3780 // Could trigger deserialization of decls.
3781 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
3782 clang::NamedDecl* nVarDecl
3783 = cling::utils::Lookup::Named(&fInterpreter->getSema(), unscopedName, declCtx);
3784 if (!nVarDecl) {
3785 Error("DeleteVariable", "Unknown variable %s", name);
3786 return 0;
3787 }
3788 clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3789 if (!varDecl) {
3790 Error("DeleteVariable", "Entity %s is not a variable", name);
3791 return 0;
3792 }
3793
3794 clang::QualType qType = varDecl->getType();
3795 const clang::Type* type = qType->getUnqualifiedDesugaredType();
3796 // Cannot set a reference's address to nullptr; the JIT can place it
3797 // into read-only memory (ROOT-7100).
3798 if (type->isPointerType()) {
3799 int** ppInt = (int**)fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3800 // set pointer to invalid.
3801 if (ppInt) *ppInt = 0;
3802 }
3803 return 1;
3804}
3805
3806////////////////////////////////////////////////////////////////////////////////
3807/// Save the current Cling state.
3808
3810{
3811#if defined(R__MUST_REVISIT)
3812#if R__MUST_REVISIT(6,2)
3814 Warning("SaveContext","Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3815#endif
3816#endif
3817}
3818
3819////////////////////////////////////////////////////////////////////////////////
3820/// Save the current Cling state of global objects.
3821
3823{
3824#if defined(R__MUST_REVISIT)
3825#if R__MUST_REVISIT(6,2)
3827 Warning("SaveGlobalsContext","Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3828#endif
3829#endif
3830}
3831
3832////////////////////////////////////////////////////////////////////////////////
3833/// No op: see TClingCallbacks (used to update the list of globals)
3834
3836{
3837}
3838
3839////////////////////////////////////////////////////////////////////////////////
3840/// No op: see TClingCallbacks (used to update the list of global functions)
3841
3843{
3844}
3845
3846////////////////////////////////////////////////////////////////////////////////
3847/// No op: see TClingCallbacks (used to update the list of types)
3848
3850{
3851}
3852
3853////////////////////////////////////////////////////////////////////////////////
3854/// Check in what order the member of a tuple are layout.
3855enum class ETupleOrdering {
3856 kAscending,
3859};
3860
3862{
3865};
3866
3868{
3871};
3872
3874{
3875 std::tuple<int,double> value;
3878
3879 size_t offset0 = ((char*)&(std::get<0>(value))) - ((char*)&value);
3880 size_t offset1 = ((char*)&(std::get<1>(value))) - ((char*)&value);
3881
3882 size_t ascOffset0 = ((char*)&(asc._0)) - ((char*)&asc);
3883 size_t ascOffset1 = ((char*)&(asc._1)) - ((char*)&asc);
3884
3885 size_t desOffset0 = ((char*)&(des._0)) - ((char*)&des);
3886 size_t desOffset1 = ((char*)&(des._1)) - ((char*)&des);
3887
3888 if (offset0 == ascOffset0 && offset1 == ascOffset1) {
3890 } else if (offset0 == desOffset0 && offset1 == desOffset1) {
3892 } else {
3894 }
3895}
3896
3897static std::string AlternateTuple(const char *classname, const cling::LookupHelper& lh)
3898{
3899 TClassEdit::TSplitType tupleContent(classname);
3900 std::string alternateName = "TEmulatedTuple";
3901 alternateName.append( classname + 5 );
3902
3903 std::string fullname = "ROOT::Internal::" + alternateName;
3904 if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
3905 /*resultType*/nullptr, /* intantiateTemplate= */ false))
3906 return fullname;
3907
3908 std::string guard_name;
3909 ROOT::TMetaUtils::GetCppName(guard_name,alternateName.c_str());
3910 std::ostringstream guard;
3911 guard << "ROOT_INTERNAL_TEmulated_";
3912 guard << guard_name;
3913
3914 std::ostringstream alternateTuple;
3915 alternateTuple << "#ifndef " << guard.str() << "\n";
3916 alternateTuple << "#define " << guard.str() << "\n";
3917 alternateTuple << "namespace ROOT { namespace Internal {\n";
3918 alternateTuple << "template <class... Types> struct TEmulatedTuple;\n";
3919 alternateTuple << "template <> struct " << alternateName << " {\n";
3920
3921 // This could also be a compile time choice ...
3922 switch(IsTupleAscending()) {
3924 unsigned int nMember = 0;
3925 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple)
3926 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
3927 while (iter != theEnd) {
3928 alternateTuple << " " << *iter << " _" << nMember << ";\n";
3929 ++iter;
3930 ++nMember;
3931 }
3932 break;
3933 }
3935 unsigned int nMember = tupleContent.fElements.size() - 3;
3936 auto iter = tupleContent.fElements.rbegin() + 1; // Skip the template name (tuple)
3937 auto theEnd = tupleContent.fElements.rend() - 1; // skip the 'stars'.
3938 while (iter != theEnd) {
3939 alternateTuple << " " << *iter << " _" << nMember << ";\n";
3940 ++iter;
3941 --nMember;
3942 }
3943 break;
3944 }
3946 Fatal("TCling::SetClassInfo::AlternateTuple",
3947 "Layout of std::tuple on this platform is unexpected.");
3948 break;
3949 }
3950 }
3951
3952 alternateTuple << "};\n";
3953 alternateTuple << "}}\n";
3954 alternateTuple << "#endif\n";
3955 if (!gCling->Declare(alternateTuple.str().c_str())) {
3956 Error("Load","Could not declare %s",alternateName.c_str());
3957 return "";
3958 }
3959 alternateName = "ROOT::Internal::" + alternateName;
3960 return alternateName;
3961}
3962
3963////////////////////////////////////////////////////////////////////////////////
3964/// Set pointer to the TClingClassInfo in TClass.
3965/// If 'reload' is true, (attempt to) generate a new ClassInfo even if we
3966/// already have one.
3967
3969{
3970 // We are shutting down, there is no point in reloading, it only triggers
3971 // redundant deserializations.
3972 if (fIsShuttingDown) {
3973 // Remove the decl_id from the DeclIdToTClass map
3974 if (cl->fClassInfo) {
3976 TClingClassInfo* TClinginfo = (TClingClassInfo*) cl->fClassInfo;
3977 // Test again as another thread may have set fClassInfo to nullptr.
3978 if (TClinginfo) {
3979 TClass::RemoveClassDeclId(TClinginfo->GetDeclId());
3980 }
3981 delete TClinginfo;
3982 cl->fClassInfo = nullptr;
3983 }
3984 return;
3985 }
3986
3988 if (cl->fClassInfo && !reload) {
3989 return;
3990 }
3991 //Remove the decl_id from the DeclIdToTClass map
3992 TClingClassInfo* TClinginfo = (TClingClassInfo*) cl->fClassInfo;
3993 if (TClinginfo) {
3994 TClass::RemoveClassDeclId(TClinginfo->GetDeclId());
3995 }
3996 delete TClinginfo;
3997 cl->fClassInfo = 0;
3998 std::string name(cl->GetName());
3999
4000 // Handle the special case of 'tuple' where we ignore the real implementation
4001 // details and just overlay a 'simpler'/'simplistic' version that is easy
4002 // for the I/O to understand and handle.
4003 if (strncmp(cl->GetName(),"tuple<",strlen("tuple<"))==0) {
4004
4005 name = AlternateTuple(cl->GetName(), fInterpreter->getLookupHelper());
4006
4007 }
4008
4009 bool instantiateTemplate = !cl->TestBit(TClass::kUnloading);
4010 // FIXME: Rather than adding an option to the TClingClassInfo, we should consider combining code
4011 // that is currently in the caller (like SetUnloaded) that disable AutoLoading and AutoParsing and
4012 // code is in the callee (disabling template instantiation) and end up with a more explicit class:
4013 // TClingClassInfoReadOnly.
4014 TClingClassInfo* info = new TClingClassInfo(GetInterpreterImpl(), name.c_str(), instantiateTemplate);
4015 if (!info->IsValid()) {
4016 if (cl->fState != TClass::kHasTClassInit) {
4017 if (cl->fStreamerInfo->GetEntries() != 0) {
4019 } else {
4021 }
4022 }
4023 delete info;
4024 return;
4025 }
4026 cl->fClassInfo = (ClassInfo_t*)info; // Note: We are transferring ownership here.
4027 // In case a class contains an external enum, the enum will be seen as a
4028 // class. We must detect this special case and make the class a Zombie.
4029 // Here we assume that a class has at least one method.
4030 // We can NOT call TClass::Property from here, because this method
4031 // assumes that the TClass is well formed to do a lot of information
4032 // caching. The method SetClassInfo (i.e. here) is usually called during
4033 // the building phase of the TClass, hence it is NOT well formed yet.
4034 Bool_t zombieCandidate = kFALSE;
4035 if (
4036 info->IsValid() &&
4037 !(info->Property() & (kIsClass | kIsStruct | kIsNamespace))
4038 ) {
4039 zombieCandidate = kTRUE;
4040 }
4041 if (!info->IsLoaded()) {
4042 if (info->Property() & (kIsNamespace)) {
4043 // Namespaces can have info but no corresponding CINT dictionary
4044 // because they are auto-created if one of their contained
4045 // classes has a dictionary.
4046 zombieCandidate = kTRUE;
4047 }
4048 // this happens when no dictionary is available
4049 delete info;
4050 cl->fClassInfo = 0;
4051 }
4052 if (zombieCandidate && !cl->GetCollectionType()) {
4053 cl->MakeZombie();
4054 }
4055 // If we reach here, the info was valid (See early returns).
4056 if (cl->fState != TClass::kHasTClassInit) {
4057 if (cl->fClassInfo) {
4060 } else {
4061// if (TClassEdit::IsSTLCont(cl->GetName()) {
4062// There will be an emulated collection proxy, is that the same?
4063// cl->fState = TClass::kEmulated;
4064// } else {
4065 if (cl->fStreamerInfo->GetEntries() != 0) {
4067 } else {
4069 }
4070// }
4071 }
4072 }
4073 if (cl->fClassInfo) {
4074 TClass::AddClassToDeclIdMap(((TClingClassInfo*)cl->fClassInfo)->GetDeclId(), cl);
4075 }
4076}
4077
4078////////////////////////////////////////////////////////////////////////////////
4079/// Checks if an entity with the specified name is defined in Cling.
4080/// Returns kUnknown if the entity is not defined.
4081/// Returns kWithClassDefInline if the entity exists and has a ClassDefInline
4082/// Returns kKnown if the entity is defined.
4083///
4084/// By default, structs, namespaces, classes, enums and unions are looked for.
4085/// If the flag isClassOrNamespaceOnly is true, classes, structs and
4086/// namespaces only are considered. I.e. if the name is an enum or a union,
4087/// the returned value is false.
4088///
4089/// In the case where the class is not loaded and belongs to a namespace
4090/// or is nested, looking for the full class name is outputting a lots of
4091/// (expected) error messages. Currently the only way to avoid this is to
4092/// specifically check that each level of nesting is already loaded.
4093/// In case of templates the idea is that everything between the outer
4094/// '<' and '>' has to be skipped, e.g.: `aap<pippo<noot>::klaas>::a_class`
4095
4097TCling::CheckClassInfo(const char *name, Bool_t autoload, Bool_t isClassOrNamespaceOnly /* = kFALSE*/)
4098{
4100 static const char *anonEnum = "anonymous enum ";
4101 static const int cmplen = strlen(anonEnum);
4102
4103 if (fIsShuttingDown || 0 == strncmp(name, anonEnum, cmplen)) {
4104 return kUnknown;
4105 }
4106
4107 // Do not turn on the AutoLoading if it is globally off.
4108 autoload = autoload && IsClassAutoLoadingEnabled();
4109
4110 // Avoid the double search below in case the name is a fundamental type
4111 // or typedef to a fundamental type.
4112 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
4113 TDataType *fundType = (TDataType *)typeTable->THashTable::FindObject( name );
4114
4115 if (fundType && fundType->GetType() < TVirtualStreamerInfo::kObject
4116 && fundType->GetType() > 0) {
4117 // Fundamental type, no a class.
4118 return kUnknown;
4119 }
4120
4121 // Migrated from within TClass::GetClass
4122 // If we want to know if a class or a namespace with this name exists in the
4123 // interpreter and this is an enum in the type system, before or after loading
4124 // according to the autoload function argument, return kUnknown.
4125 if (isClassOrNamespaceOnly && TEnum::GetEnum(name, autoload ? TEnum::kAutoload : TEnum::kNone))
4126 return kUnknown;
4127
4128 const char *classname = name;
4129
4130 // RAII to suspend and restore auto-loading and auto-parsing based on some external conditions.
4131 class MaybeSuspendAutoLoadParse {
4132 int fStoreAutoLoad = 0;
4133 int fStoreAutoParse = 0;
4134 bool fSuspendedAutoParse = false;
4135 public:
4136 MaybeSuspendAutoLoadParse(int autoload) {
4137 fStoreAutoLoad = ((TCling*)gCling)->SetClassAutoLoading(autoload);
4138 }
4139
4140 void SuspendAutoParsing() {
4141 fSuspendedAutoParse = true;
4142 fStoreAutoParse = ((TCling*)gCling)->SetSuspendAutoParsing(true);
4143 }
4144
4145 ~MaybeSuspendAutoLoadParse() {
4146 if (fSuspendedAutoParse)
4147 ((TCling*)gCling)->SetSuspendAutoParsing(fStoreAutoParse);
4148 ((TCling*)gCling)->SetClassAutoLoading(fStoreAutoLoad);
4149 }
4150 };
4151
4152 MaybeSuspendAutoLoadParse autoLoadParseRAII( autoload );
4153 if (TClassEdit::IsStdPair(classname) || TClassEdit::IsStdPairBase(classname))
4154 autoLoadParseRAII.SuspendAutoParsing();
4155
4156 // First we want to check whether the decl exist, but _without_
4157 // generating any template instantiation. However, the lookup
4158 // still will create a forward declaration of the class template instance
4159 // if it exist. In this case, the return value of findScope will still
4160 // be zero but the type will be initialized.
4161 // Note in the corresponding code in ROOT 5, CINT was not instantiating
4162 // this forward declaration.
4163 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4164 const clang::Type *type = 0;
4165 const clang::Decl *decl
4166 = lh.findScope(classname,
4167 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4168 : cling::LookupHelper::NoDiagnostics,
4169 &type, /* intantiateTemplate= */ false );
4170 if (!decl) {
4171 std::string buf = TClassEdit::InsertStd(classname);
4172 decl = lh.findScope(buf,
4173 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4174 : cling::LookupHelper::NoDiagnostics,
4175 &type,false);
4176 }
4177
4178 if (type) {
4179 // If decl==0 and the type is valid, then we have a forward declaration.
4180 if (!decl) {
4181 // If we have a forward declaration for a class template instantiation,
4182 // we want to ignore it if it was produced/induced by the call to
4183 // findScope, however we can not distinguish those from the
4184 // instantiation induce by 'soft' use (and thus also induce by the
4185 // same underlying code paths)
4186 // ['soft' use = use not requiring a complete definition]
4187 // So to reduce the amount of disruption to the existing code we
4188 // would just ignore those for STL collection, for which we really
4189 // need to have the compiled collection proxy (and thus the TClass
4190 // bootstrap).
4191 clang::ClassTemplateSpecializationDecl *tmpltDecl =
4192 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
4193 (type->getAsCXXRecordDecl());
4194 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4195 // Since the point of instantiation is invalid, we 'guess' that
4196 // the 'instantiation' of the forwarded type appended in
4197 // findscope.
4198 if (ROOT::TMetaUtils::IsSTLCont(*tmpltDecl)) {
4199 // For STL Collection we return kUnknown.
4200 return kUnknown;
4201 }
4202 }
4203 }
4205 if (!tci.IsValid()) {
4206 return kUnknown;
4207 }
4208 auto propertiesMask = isClassOrNamespaceOnly ? kIsClass | kIsStruct | kIsNamespace :
4210
4211 if (tci.Property() & propertiesMask) {
4212 bool hasClassDefInline = false;
4213 if (isClassOrNamespaceOnly) {
4214 // We do not need to check for ClassDefInline when this is called from
4215 // TClass::Init, we only do it for the call from TClass::GetClass.
4216 auto hasDictionary = tci.GetMethod("Dictionary", "", false, 0, ROOT::kExactMatch);
4217 auto implLineFunc = tci.GetMethod("ImplFileLine", "", false, 0, ROOT::kExactMatch);
4218
4219 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4220 int lineNumber = 0;
4221 bool success = false;
4222 std::tie(success, lineNumber) =
4223 ROOT::TMetaUtils::GetTrivialIntegralReturnValue(implLineFunc.GetAsFunctionDecl(), *fInterpreter);
4224 hasClassDefInline = success && (lineNumber == -1);
4225 }
4226 }
4227
4228 // fprintf(stderr,"CheckClassInfo: %s had dict=%d inline=%d\n",name,hasDictionary.IsValid()
4229 // , hasClassDefInline);
4230
4231 // We are now sure that the entry is not in fact an autoload entry.
4232 if (hasClassDefInline)
4233 return kWithClassDefInline;
4234 else
4235 return kKnown;
4236 } else {
4237 // We are now sure that the entry is not in fact an autoload entry.
4238 return kUnknown;
4239 }
4240 }
4241
4242 if (decl)
4243 return kKnown;
4244 else
4245 return kUnknown;
4246
4247 // Setting up iterator part of TClingTypedefInfo is too slow.
4248 // Copy the lookup code instead:
4249 /*
4250 TClingTypedefInfo t(fInterpreter, name);
4251 if (t.IsValid() && !(t.Property() & kIsFundamental)) {
4252 delete[] classname;
4253 return kTRUE;
4254 }
4255 */
4256
4257// const clang::Decl *decl = lh.findScope(name);
4258// if (!decl) {
4259// std::string buf = TClassEdit::InsertStd(name);
4260// decl = lh.findScope(buf);
4261// }
4262
4263// return (decl);
4264}
4265
4266////////////////////////////////////////////////////////////////////////////////
4267/// Return true if there is a class template by the given name ...
4268
4270{
4271 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4272 const clang::Decl *decl
4273 = lh.findClassTemplate(name,
4274 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4275 : cling::LookupHelper::NoDiagnostics);
4276 if (!decl) {
4277 std::string strname = "std::";
4278 strname += name;
4279 decl = lh.findClassTemplate(strname,
4280 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4281 : cling::LookupHelper::NoDiagnostics);
4282 }
4283 return 0 != decl;
4284}
4285
4286////////////////////////////////////////////////////////////////////////////////
4287/// Create list of pointers to base class(es) for TClass cl.
4288
4290{
4292 if (cl->fBase) {
4293 return;
4294 }
4296 if (!tci) return;
4298 TList *listOfBase = new TList;
4299 while (t.Next()) {
4300 // if name cannot be obtained no use to put in list
4301 if (t.IsValid() && t.Name()) {
4303 listOfBase->Add(new TBaseClass((BaseClassInfo_t *)a, cl));
4304 }
4305 }
4306 // Now that is complete, publish it.
4307 cl->fBase = listOfBase;
4308}
4309
4310////////////////////////////////////////////////////////////////////////////////
4311/// Create list of pointers to enums for TClass cl.
4312
4313void TCling::LoadEnums(TListOfEnums& enumList) const
4314{
4316
4317 const Decl * D;
4318 TClass* cl = enumList.GetClass();
4319 if (cl) {
4320 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4321 }
4322 else {
4323 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4324 }
4325 // Iterate on the decl of the class and get the enums.
4326 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4327 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4328 // Collect all contexts of the namespace.
4329 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4330 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4331 for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(), declEnd = allDeclContexts.end();
4332 declIter != declEnd; ++declIter) {
4333 // Iterate on all decls for each context.
4334 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4335 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4336 if (const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4337 // Get name of the enum type.
4338 std::string buf;
4339 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4340 llvm::raw_string_ostream stream(buf);
4341 // Don't trigger fopen of the source file to count lines:
4342 Policy.AnonymousTagLocations = false;
4343 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
4344 stream.flush();
4345 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
4346 if (!buf.empty()) {
4347 const char* name = buf.c_str();
4348 // Add the enum to the list of loaded enums.
4349 enumList.Get(ED, name);
4350 }
4351 }
4352 }
4353 }
4354 }
4355}
4356
4357////////////////////////////////////////////////////////////////////////////////
4358/// Create list of pointers to function templates for TClass cl.
4359
4361{
4363
4364 const Decl * D;
4365 TListOfFunctionTemplates* funcTempList;
4366 if (cl) {
4367 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4368 funcTempList = (TListOfFunctionTemplates*)cl->GetListOfFunctionTemplates(false);
4369 }
4370 else {
4371 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4372 funcTempList = (TListOfFunctionTemplates*)gROOT->GetListOfFunctionTemplates();
4373 }
4374 // Iterate on the decl of the class and get the enums.
4375 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4376 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4377 // Collect all contexts of the namespace.
4378 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4379 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4380 for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(),
4381 declEnd = allDeclContexts.end(); declIter != declEnd; ++declIter) {
4382 // Iterate on all decls for each context.
4383 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4384 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4385 if (const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4386 funcTempList->Get(FTD);
4387 }
4388 }
4389 }
4390 }
4391}
4392
4393////////////////////////////////////////////////////////////////////////////////
4394/// Get the scopes representing using declarations of namespace
4395
4396std::vector<std::string> TCling::GetUsingNamespaces(ClassInfo_t *cl) const
4397{
4399 return ci->GetUsingNamespaces();
4400}
4401
4402////////////////////////////////////////////////////////////////////////////////
4403/// Create list of pointers to data members for TClass cl.
4404/// This is now a nop. The creation and updating is handled in
4405/// TListOfDataMembers.
4406
4408{
4409}
4410
4411////////////////////////////////////////////////////////////////////////////////
4412/// Create list of pointers to methods for TClass cl.
4413/// This is now a nop. The creation and updating is handled in
4414/// TListOfFunctions.
4415
4417{
4418}
4419
4420////////////////////////////////////////////////////////////////////////////////
4421/// Update the list of pointers to method for TClass cl
4422/// This is now a nop. The creation and updating is handled in
4423/// TListOfFunctions.
4424
4426{
4427}
4428
4429////////////////////////////////////////////////////////////////////////////////
4430/// Update the list of pointers to data members for TClass cl
4431/// This is now a nop. The creation and updating is handled in
4432/// TListOfDataMembers.
4433
4435{
4436}
4437
4438////////////////////////////////////////////////////////////////////////////////
4439/// Create list of pointers to method arguments for TMethod m.
4440
4442{
4444 if (m->fMethodArgs) {
4445 return;
4446 }
4447 TList *arglist = new TList;
4449 while (t.Next()) {
4450 if (t.IsValid()) {
4452 arglist->Add(new TMethodArg((MethodArgInfo_t*)a, m));
4453 }
4454 }
4455 m->fMethodArgs = arglist;
4456}
4457
4458////////////////////////////////////////////////////////////////////////////////
4459/// Return whether we are waiting for more input either because the collected
4460/// input contains unbalanced braces or last seen token was a `\` (backslash-newline)
4461
4463{
4464 return fMetaProcessor->awaitingMoreInput();
4465}
4466
4467////////////////////////////////////////////////////////////////////////////////
4468/// Generate a TClass for the given class.
4469/// Since the caller has already check the ClassInfo, let it give use the
4470/// result (via the value of emulation) rather than recalculate it.
4471
4472TClass *TCling::GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent /* = kFALSE */)
4473{
4474// For now the following line would lead to the (unwanted) instantiation
4475// of class template. This could/would need to be resurrected only if
4476// we re-introduce so sort of automatic instantiation. However this would
4477// have to include carefull look at the template parameter to avoid
4478// creating instance we can not really use (if the parameter are only forward
4479// declaration or do not have all the necessary interfaces).
4480
4481 // TClingClassInfo tci(fInterpreter, classname);
4482 // if (1 || !tci.IsValid()) {
4483
4484 Version_t version = 1;
4485 if (TClassEdit::IsSTLCont(classname)) {
4486 version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4487 }
4489 TClass *cl = new TClass(classname, version, silent);
4490 if (emulation) {
4492 } else {
4493 // Set the class version if the class is versioned.
4494 // Note that we cannot just call CLASS::Class_Version() as we might not have
4495 // an execution engine (when invoked from rootcling).
4496
4497 // Do not call cl->GetClassVersion(), it has side effects!
4498 Version_t oldvers = cl->fClassVersion;
4499 if (oldvers == version && cl->GetClassInfo()) {
4500 // We have a version and it might need an update.
4502 if (llvm::isa<clang::NamespaceDecl>(cli->GetDecl())) {
4503 // Namespaces don't have class versions.
4504 return cl;
4505 }
4506 TClingMethodInfo mi = cli->GetMethod("Class_Version", "", 0 /*poffset*/,
4509 if (!mi.IsValid()) {
4510 if (cl->TestBit(TClass::kIsTObject)) {
4511 Error("GenerateTClass",
4512 "Cannot find %s::Class_Version()! Class version might be wrong.",
4513 cl->GetName());
4514 }
4515 return cl;
4516 }
4517 Version_t newvers = ROOT::TMetaUtils::GetClassVersion(llvm::dyn_cast<clang::RecordDecl>(cli->GetDecl()),
4518 *fInterpreter);
4519 if (newvers == -1) {
4520 // Didn't manage to determine the class version from the AST.
4521 // Use runtime instead.
4522 if ((mi.Property() & kIsStatic)
4523 && !fInterpreter->isInSyntaxOnlyMode()) {
4524 // This better be a static function.
4526 callfunc.SetFunc(&mi);
4527 newvers = callfunc.ExecInt(0);
4528 } else {
4529 Error("GenerateTClass",
4530 "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4531 cl->GetName());
4532 }
4533 }
4534 if (newvers != oldvers) {
4535 cl->fClassVersion = newvers;
4536 cl->fStreamerInfo->Expand(newvers + 2 + 10);
4537 }
4538 }
4539 }
4540
4541 return cl;
4542
4543// } else {
4544// return GenerateTClass(&tci,silent);
4545// }
4546}
4547
4548#if 0
4549////////////////////////////////////////////////////////////////////////////////
4550
4551static void GenerateTClass_GatherInnerIncludes(cling::Interpreter *interp, TString &includes,TClingClassInfo *info)
4552{
4553 includes += info->FileName();
4554
4555 const clang::ClassTemplateSpecializationDecl *templateCl
4556 = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->GetDecl());
4557 if (templateCl) {
4558 for(unsigned int i=0; i < templateCl->getTemplateArgs().size(); ++i) {
4559 const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4560 if (arg.getKind() == clang::TemplateArgument::Type) {
4561 const clang::Type *uType = ROOT::TMetaUtils::GetUnderlyingType( arg.getAsType() );
4562
4563 if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4564 // We really need a header file.
4565 const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4566 if (argdecl) {
4567 includes += ";";
4568 TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4569 GenerateTClass_GatherInnerIncludes(interp, includes, &subinfo);
4570 } else {
4571 std::string Result;
4572 llvm::raw_string_ostream OS(Result);
4573 arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4574 Warning("TCling::GenerateTClass","Missing header file for %s",OS.str().c_str());
4575 }
4576 }
4577 }
4578 }
4579 }
4580}
4581#endif
4582
4583////////////////////////////////////////////////////////////////////////////////
4584/// Generate a TClass for the given class.
4585
4586TClass *TCling::GenerateTClass(ClassInfo_t *classinfo, Bool_t silent /* = kFALSE */)
4587{
4588 TClingClassInfo *info = (TClingClassInfo*)classinfo;
4589 if (!info || !info->IsValid()) {
4590 Fatal("GenerateTClass","Requires a valid ClassInfo object");
4591 return 0;
4592 }
4593 // We are in the case where we have AST nodes for this class.
4594 TClass *cl = 0;
4595 std::string classname;
4596 info->FullName(classname,*fNormalizedCtxt); // Could we use Name()?
4597 if (TClassEdit::IsSTLCont(classname)) {
4598#if 0
4599 Info("GenerateTClass","Will (try to) generate the compiled TClass for %s.",classname.c_str());
4600 // We need to build up the list of required headers, by
4601 // looking at each template arguments.
4602 TString includes;
4603 GenerateTClass_GatherInnerIncludes(fInterpreter,includes,info);
4604
4605 if (0 == GenerateDictionary(classname.c_str(),includes)) {
4606 // 0 means success.
4607 cl = TClass::LoadClass(classnam.c_str(), silent);
4608 if (cl == 0) {
4609 Error("GenerateTClass","Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4610 }
4611 }
4612#endif
4613 if (cl == 0) {
4614 int version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4615 cl = new TClass(classinfo, version, 0, 0, -1, -1, silent);
4617 }
4618 } else {
4619 // For regular class, just create a TClass on the fly ...
4620 // Not quite useful yet, but that what CINT used to do anyway.
4621 cl = new TClass(classinfo, 1, 0, 0, -1, -1, silent);
4622 }
4623 // Add the new TClass to the map of declid and TClass*.
4624 if (cl) {
4626 }
4627 return cl;
4628}
4629
4630////////////////////////////////////////////////////////////////////////////////
4631/// Generate the dictionary for the C++ classes listed in the first
4632/// argument (in a semi-colon separated list).
4633/// 'includes' contains a semi-colon separated list of file to
4634/// `#include` in the dictionary.
4635/// For example:
4636/// ~~~ {.cpp}
4637/// gInterpreter->GenerateDictionary("vector<vector<float> >;list<vector<float> >","list;vector");
4638/// ~~~
4639/// or
4640/// ~~~ {.cpp}
4641/// gInterpreter->GenerateDictionary("myclass","myclass.h;myhelper.h");
4642/// ~~~
4643
4644Int_t TCling::GenerateDictionary(const char* classes, const char* includes /* = "" */, const char* /* options = 0 */)
4645{
4646 if (classes == 0 || classes[0] == 0) {
4647 Error("TCling::GenerateDictionary", "Cannot generate dictionary without passing classes.");
4648 return 0;
4649 }
4650 // Split the input list
4651 std::vector<std::string> listClasses;
4652 for (
4653 const char* current = classes, *prev = classes;
4654 *current != 0;
4655 ++current
4656 ) {
4657 if (*current == ';') {
4658 listClasses.push_back(std::string(prev, current - prev));
4659 prev = current + 1;
4660 }
4661 else if (*(current + 1) == 0) {
4662 listClasses.push_back(std::string(prev, current + 1 - prev));
4663 prev = current + 1;
4664 }
4665 }
4666 std::vector<std::string> listIncludes;
4667 if (!includes)
4668 includes = "";
4669 for (
4670 const char* current = includes, *prev = includes;
4671 *current != 0;
4672 ++current
4673 ) {
4674 if (*current == ';') {
4675 listIncludes.push_back(std::string(prev, current - prev));
4676 prev = current + 1;
4677 }
4678 else if (*(current + 1) == 0) {
4679 listIncludes.push_back(std::string(prev, current + 1 - prev));
4680 prev = current + 1;
4681 }
4682 }
4683 // Generate the temporary dictionary file
4684 return !TCling_GenerateDictionary(listClasses, listIncludes,
4685 std::vector<std::string>(), std::vector<std::string>());
4686}
4687
4688////////////////////////////////////////////////////////////////////////////////
4689/// Return pointer to cling Decl of global/static variable that is located
4690/// at the address given by addr.
4691
4692TInterpreter::DeclId_t TCling::GetDataMember(ClassInfo_t *opaque_cl, const char *name) const
4693{
4695 DeclId_t d;
4696 TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
4697
4698 if (cl) {
4699 d = cl->GetDataMember(name);
4700 // We check if the decl of the data member has an annotation which indicates
4701 // an ioname.
4702 // In case this is true, if the name requested is not the ioname, we
4703 // return 0, as if the member did not exist. In some sense we override
4704 // the information in the TClassInfo instance, isolating the typesystem in
4705 // TClass from the one in the AST.
4706 if (const ValueDecl* decl = (const ValueDecl*) d){
4707 std::string ioName;
4708 bool hasIoName = ROOT::TMetaUtils::ExtractAttrPropertyFromName(*decl,"ioname",ioName);
4709 if (hasIoName && ioName != name) return 0;
4710 }
4711 return d;
4712 }
4713 // We are looking up for something on the TU scope.
4714 // FIXME: We do not want to go through TClingClassInfo(fInterpreter) because of redundant deserializations. That
4715 // interface will actually construct iterators and walk over the decls on the global scope. In would return the first
4716 // occurrence of a decl with the looked up name. However, that's not what C++ lookup would do: if we want to switch
4717 // to a more complete C++ lookup interface we need sift through the found names and pick up the declarations which
4718 // are only fulfilling ROOT's understanding for a Data Member.
4719 // FIXME: We should probably deprecate the TClingClassInfo(fInterpreter) interface and replace it withe something
4720 // similar as below.
4721 using namespace clang;
4722 Sema& SemaR = fInterpreter->getSema();
4723 DeclarationName DName = &SemaR.Context.Idents.get(name);
4724
4725 LookupResult R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4726 Sema::ForExternalRedeclaration);
4727
4728 // Could trigger deserialization of decls.
4729 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4730 cling::utils::Lookup::Named(&SemaR, R);
4731
4732 LookupResult::Filter F = R.makeFilter();
4733 // Filter the data-member looking decls.
4734 while (F.hasNext()) {
4735 NamedDecl *D = F.next();
4736 if (isa<VarDecl>(D) || isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) ||
4737 isa<IndirectFieldDecl>(D))
4738 continue;
4739 F.erase();
4740 }
4741 F.done();
4742
4743 if (R.isSingleResult())
4744 return R.getFoundDecl();
4745 return 0;
4746}
4747
4748////////////////////////////////////////////////////////////////////////////////
4749/// Return pointer to cling Decl of global/static variable that is located
4750/// at the address given by addr.
4751
4753{
4755
4756 const clang::Decl* possibleEnum = 0;
4757 // FInd the context of the decl.
4758 if (cl) {
4760 if (cci) {
4761 const clang::DeclContext* dc = 0;
4762 if (const clang::Decl* D = cci->GetDecl()) {
4763 if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
4764 dc = dyn_cast<clang::RecordDecl>(D);
4765 }
4766 }
4767 if (dc) {
4768 // If it is a data member enum.
4769 // Could trigger deserialization of decls.
4770 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4771 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name, dc);
4772 } else {
4773 Error("TCling::GetEnum", "DeclContext not found for %s .\n", name);
4774 }
4775 }
4776 } else {
4777 // If it is a global enum.
4778 // Could trigger deserialization of decls.
4779 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4780 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name);
4781 }
4782 if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
4783 && isa<clang::EnumDecl>(possibleEnum)) {
4784 return possibleEnum;
4785 }
4786 return 0;
4787}
4788
4789////////////////////////////////////////////////////////////////////////////////
4790/// Return pointer to cling DeclId for a global value
4791
4792TInterpreter::DeclId_t TCling::GetDeclId( const llvm::GlobalValue *gv ) const
4793{
4794 if (!gv) return 0;
4795
4796 llvm::StringRef mangled_name = gv->getName();
4797
4798 int err = 0;
4799 char* demangled_name_c = TClassEdit::DemangleName(mangled_name.str().c_str(), err);
4800 if (err) {
4801 if (err == -2) {
4802 // It might simply be an unmangled global name.
4803 DeclId_t d;
4805 d = gcl.GetDataMember(mangled_name.str().c_str());
4806 return d;
4807 }
4808 return 0;
4809 }
4810
4811 std::string scopename(demangled_name_c);
4812 free(demangled_name_c);
4813
4814 //
4815 // Separate out the class or namespace part of the
4816 // function name.
4817 //
4818 std::string dataname;
4819
4820 if (!strncmp(scopename.c_str(), "typeinfo for ", sizeof("typeinfo for ")-1)) {
4821 scopename.erase(0, sizeof("typeinfo for ")-1);
4822 } else if (!strncmp(scopename.c_str(), "vtable for ", sizeof("vtable for ")-1)) {
4823 scopename.erase(0, sizeof("vtable for ")-1);
4824 } else {
4825 // See if it is a function
4826 std::string::size_type pos = scopename.rfind('(');
4827 if (pos != std::string::npos) {
4828 return 0;
4829 }
4830 // Separate the scope and member name
4831 pos = scopename.rfind(':');
4832 if (pos != std::string::npos) {
4833 if ((pos != 0) && (scopename[pos-1] == ':')) {
4834 dataname = scopename.substr(pos+1);
4835 scopename.erase(pos-1);
4836 }
4837 } else {
4838 scopename.clear();
4839 dataname = scopename;
4840 }
4841 }
4842 //fprintf(stderr, "name: '%s'\n", name.c_str());
4843 // Now we have the class or namespace name, so do the lookup.
4844
4845
4846 DeclId_t d;
4847 if (scopename.size()) {
4848 TClingClassInfo cl(GetInterpreterImpl(), scopename.c_str());
4849 d = cl.GetDataMember(dataname.c_str());
4850 }
4851 else {
4853 d = gcl.GetDataMember(dataname.c_str());
4854 }
4855 return d;
4856}
4857
4858////////////////////////////////////////////////////////////////////////////////
4859/// NOT IMPLEMENTED.
4860
4862{
4863 Error("GetDataMemberWithValue()", "not implemented");
4864 return 0;
4865}
4866
4867////////////////////////////////////////////////////////////////////////////////
4868/// Return pointer to cling DeclId for a data member with a given name.
4869
4871{
4872 // NOT IMPLEMENTED.
4873 Error("GetDataMemberAtAddr()", "not implemented");
4874 return 0;
4875}
4876
4877////////////////////////////////////////////////////////////////////////////////
4878/// Return the cling mangled name for a method of a class with parameters
4879/// params (params is a string of actual arguments, not formal ones). If the
4880/// class is 0 the global function list will be searched.
4881
4882TString TCling::GetMangledName(TClass* cl, const char* method,
4883 const char* params, Bool_t objectIsConst /* = kFALSE */)
4884{
4887 if (cl) {
4889 func.SetFunc((TClingClassInfo*)cl->GetClassInfo(), method, params, objectIsConst,
4890 &offset);
4891 }
4892 else {
4895 func.SetFunc(&gcl, method, params, &offset);
4896 }
4898 if (!mi) return "";
4899 TString mangled_name( mi->GetMangledName() );
4900 delete mi;
4901 return mangled_name;
4902}
4903
4904////////////////////////////////////////////////////////////////////////////////
4905/// Return the cling mangled name for a method of a class with a certain
4906/// prototype, i.e. "char*,int,float". If the class is 0 the global function
4907/// list will be searched.
4908
4910 const char* proto, Bool_t objectIsConst /* = kFALSE */,
4911 EFunctionMatchMode mode /* = kConversionMatch */)
4912{
4914 if (cl) {
4915 return ((TClingClassInfo*)cl->GetClassInfo())->
4916 GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetMangledName();
4917 }
4919 return gcl.GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetMangledName();
4920}
4921
4922////////////////////////////////////////////////////////////////////////////////
4923/// Return pointer to cling interface function for a method of a class with
4924/// parameters params (params is a string of actual arguments, not formal
4925/// ones). If the class is 0 the global function list will be searched.
4926
4927void* TCling::GetInterfaceMethod(TClass* cl, const char* method,
4928 const char* params, Bool_t objectIsConst /* = kFALSE */)
4929{
4932 if (cl) {
4934 func.SetFunc((TClingClassInfo*)cl->GetClassInfo(), method, params, objectIsConst,
4935 &offset);
4936 }
4937 else {
4940 func.SetFunc(&gcl, method, params, &offset);
4941 }
4942 return (void*) func.InterfaceMethod();
4943}
4944
4945////////////////////////////////////////////////////////////////////////////////
4946/// Return pointer to cling interface function for a method of a class with
4947/// a certain name.
4948
4949TInterpreter::DeclId_t TCling::GetFunction(ClassInfo_t *opaque_cl, const char* method)
4950{
4952 DeclId_t f;
4953 TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
4954 if (cl) {
4955 f = cl->GetMethod(method).GetDeclId();
4956 }
4957 else {
4959 f = gcl.GetMethod(method).GetDeclId();
4960 }
4961 return f;
4962
4963}
4964
4965////////////////////////////////////////////////////////////////////////////////
4966/// Insert overloads of name in cl to res.
4967
4968void TCling::GetFunctionOverloads(ClassInfo_t *cl, const char *funcname,
4969 std::vector<DeclId_t>& res) const
4970{
4971 clang::Sema& S = fInterpreter->getSema();
4972 clang::ASTContext& Ctx = S.Context;
4973 const clang::Decl* CtxDecl
4974 = cl ? (const clang::Decl*)((TClingClassInfo*)cl)->GetDeclId():
4975 Ctx.getTranslationUnitDecl();
4976 auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
4977 const clang::DeclContext* DeclCtx = RecDecl;
4978
4979 if (!DeclCtx)
4980 DeclCtx = dyn_cast<clang::NamespaceDecl>(CtxDecl);
4981 if (!DeclCtx) return;
4982
4983 clang::DeclarationName DName;
4984 // The DeclarationName is funcname, unless it's a ctor or dtor.
4985 // FIXME: or operator or conversion! See enum clang::DeclarationName::NameKind.
4986
4987 if (RecDecl) {
4988 if (RecDecl->getNameAsString() == funcname) {
4989 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
4990 DName = Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalType(QT));
4991 } else if (funcname[0] == '~' && RecDecl->getNameAsString() == funcname + 1) {
4992 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
4993 DName = Ctx.DeclarationNames.getCXXDestructorName(Ctx.getCanonicalType(QT));
4994 } else {
4995 DName = &Ctx.Idents.get(funcname);
4996 }
4997 } else {
4998 DName = &Ctx.Idents.get(funcname);
4999 }
5000
5001 // NotForRedeclaration: we want to find names in inline namespaces etc.
5002 clang::LookupResult R(S, DName, clang::SourceLocation(),
5003 Sema::LookupOrdinaryName, clang::Sema::NotForRedeclaration);
5004 R.suppressDiagnostics(); // else lookup with NotForRedeclaration will check access etc
5005 S.LookupQualifiedName(R, const_cast<DeclContext*>(DeclCtx));
5006 if (R.empty()) return;
5007 R.resolveKind();
5008 res.reserve(res.size() + (R.end() - R.begin()));
5009 for (clang::LookupResult::iterator IR = R.begin(), ER = R.end();
5010 IR != ER; ++IR) {
5011 if (const clang::FunctionDecl* FD
5012 = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
5013 if (!FD->getDescribedFunctionTemplate()) {
5014 res.push_back(FD);
5015 }
5016 } else if (const auto *USD = llvm::dyn_cast<const clang::UsingShadowDecl>(*IR)) {
5017 // FIXME: multi-level using
5018 if (llvm::isa<clang::FunctionDecl>(USD->getTargetDecl())) {
5019 res.push_back(USD);
5020 }
5021 }
5022 }
5023}
5024
5025////////////////////////////////////////////////////////////////////////////////
5026/// Return pointer to cling interface function for a method of a class with
5027/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5028/// function list will be searched.
5029
5031 const char* proto,
5032 Bool_t objectIsConst /* = kFALSE */,
5033 EFunctionMatchMode mode /* = kConversionMatch */)
5034{
5036 void* f;
5037 if (cl) {
5038 f = ((TClingClassInfo*)cl->GetClassInfo())->
5039 GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).InterfaceMethod();
5040 }
5041 else {
5043 f = gcl.GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).InterfaceMethod();
5044 }
5045 return f;
5046}
5047
5048////////////////////////////////////////////////////////////////////////////////
5049/// Return pointer to cling DeclId for a method of a class with
5050/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5051/// function list will be searched.
5052
5053TInterpreter::DeclId_t TCling::GetFunctionWithValues(ClassInfo_t *opaque_cl, const char* method,
5054 const char* params,
5055 Bool_t objectIsConst /* = kFALSE */)
5056{
5058 DeclId_t f;
5059 TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
5060 if (cl) {
5061 f = cl->GetMethodWithArgs(method, params, objectIsConst, 0 /*poffset*/).GetDeclId();
5062 }
5063 else {
5065 f = gcl.GetMethod(method, params, objectIsConst, 0 /*poffset*/).GetDeclId();
5066 }
5067 return f;
5068}
5069
5070////////////////////////////////////////////////////////////////////////////////
5071/// Return pointer to cling interface function for a method of a class with
5072/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5073/// function list will be searched.
5074
5075TInterpreter::DeclId_t TCling::GetFunctionWithPrototype(ClassInfo_t *opaque_cl, const char* method,
5076 const char* proto,
5077 Bool_t objectIsConst /* = kFALSE */,
5078 EFunctionMatchMode mode /* = kConversionMatch */)
5079{
5081 DeclId_t f;
5082 TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
5083 if (cl) {
5084 f = cl->GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetDeclId();
5085 }
5086 else {
5088 f = gcl.GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetDeclId();
5089 }
5090 return f;
5091}
5092
5093////////////////////////////////////////////////////////////////////////////////
5094/// Return pointer to cling interface function for a method of a class with
5095/// a certain name.
5096
5097TInterpreter::DeclId_t TCling::GetFunctionTemplate(ClassInfo_t *opaque_cl, const char* name)
5098{
5100 DeclId_t f;
5101 TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
5102 if (cl) {
5103 f = cl->GetFunctionTemplate(name);
5104 }
5105 else {
5107 f = gcl.GetFunctionTemplate(name);
5108 }
5109 return f;
5110
5111}
5112
5113////////////////////////////////////////////////////////////////////////////////
5114/// The 'name' is known to the interpreter, this function returns
5115/// the internal version of this name (usually just resolving typedefs)
5116/// This is used in particular to synchronize between the name used
5117/// by rootcling and by the run-time environment (TClass)
5118/// Return 0 if the name is not known.
5119
5120void TCling::GetInterpreterTypeName(const char* name, std::string &output, Bool_t full)
5121{
5122 output.clear();
5123
5125
5127 if (!cl.IsValid()) {
5128 return ;
5129 }
5130 if (full) {
5132 return;
5133 }
5134 // Well well well, for backward compatibility we need to act a bit too
5135 // much like CINT.
5138
5139 return;
5140}
5141
5142////////////////////////////////////////////////////////////////////////////////
5143/// Execute a global function with arguments params.
5144///
5145/// FIXME: The cint-based version of this code does not check if the
5146/// SetFunc() call works, and does not do any real checking
5147/// for errors from the Exec() call. It did fetch the most
5148/// recent cint security error and return that in error, but
5149/// this does not really translate well to cling/clang. We
5150/// should enhance these interfaces so that we can report
5151/// compilation and runtime errors properly.
5152
5153void TCling::Execute(const char* function, const char* params, int* error)
5154{
5156 if (error) {
5157 *error = TInterpreter::kNoError;
5158 }
5160 Longptr_t offset = 0L;
5162 func.SetFunc(&cl, function, params, &offset);
5163 func.Exec(0);
5164}
5165
5166////////////////////////////////////////////////////////////////////////////////
5167/// Execute a method from class cl with arguments params.
5168///
5169/// FIXME: The cint-based version of this code does not check if the
5170/// SetFunc() call works, and does not do any real checking
5171/// for errors from the Exec() call. It did fetch the most
5172/// recent cint security error and return that in error, but
5173/// this does not really translate well to cling/clang. We
5174/// should enhance these interfaces so that we can report
5175/// compilation and runtime errors properly.
5176
5177void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5178 const char* params, Bool_t objectIsConst, int* error)
5179{
5181 if (error) {
5182 *error = TInterpreter::kNoError;
5183 }
5184 // If the actual class of this object inherits 2nd (or more) from TObject,
5185 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5186 // hence gInterpreter->Execute will improperly correct the offset.
5187 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5188 Longptr_t offset = 0L;
5190 func.SetFunc((TClingClassInfo*)cl->GetClassInfo(), method, params, objectIsConst, &offset);
5191 void* address = (void*)((Longptr_t)addr + offset);
5192 func.Exec(address);
5193}
5194
5195////////////////////////////////////////////////////////////////////////////////
5196
5197void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5198 const char* params, int* error)
5199{
5200 Execute(obj,cl,method,params,false,error);
5201}
5202
5203////////////////////////////////////////////////////////////////////////////////
5204/// Execute a method from class cl with the arguments in array params
5205/// (params[0] ... params[n] = array of TObjString parameters).
5206/// Convert the TObjArray array of TObjString parameters to a character
5207/// string of comma separated parameters.
5208/// The parameters of type 'char' are enclosed in double quotes and all
5209/// internal quotes are escaped.
5210
5211void TCling::Execute(TObject* obj, TClass* cl, TMethod* method,
5212 TObjArray* params, int* error)
5213{
5214 if (!method) {
5215 Error("Execute", "No method was defined");
5216 return;
5217 }
5218 TList* argList = method->GetListOfMethodArgs();
5219 // Check number of actual parameters against of expected formal ones
5220
5221 Int_t nparms = argList->LastIndex() + 1;
5222 Int_t argc = params ? params->GetEntries() : 0;
5223
5224 if (argc > nparms) {
5225 Error("Execute","Too many parameters to call %s, got %d but expected at most %d.",method->GetName(),argc,nparms);
5226 return;
5227 }
5228 if (nparms != argc) {
5229 // Let's see if the 'missing' argument are all defaulted.
5230 // if nparms==0 then either we stopped earlier either argc is also zero and we can't reach here.
5231 assert(nparms > 0);
5232
5233 TMethodArg *arg = (TMethodArg *) argList->At( 0 );
5234 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5235 // There is a default value for the first missing
5236 // argument, so we are fine.
5237 } else {
5238 Int_t firstDefault = -1;
5239 for (Int_t i = 0; i < nparms; i ++) {
5240 arg = (TMethodArg *) argList->At( i );
5241 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5242 firstDefault = i;
5243 break;
5244 }
5245 }
5246 if (firstDefault >= 0) {
5247 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);
5248 } else {
5249 Error("Execute","Too few arguments to call %s, got only %d but expected %d.",method->GetName(),argc,nparms);
5250 }
5251 return;
5252 }
5253 }
5254
5255 const char* listpar = "";
5256 TString complete(10);
5257 if (params) {
5258 // Create a character string of parameters from TObjArray
5259 TIter next(params);
5260 for (Int_t i = 0; i < argc; i ++) {
5261 TMethodArg* arg = (TMethodArg*) argList->At(i);
5263 TObjString* nxtpar = (TObjString*) next();
5264 if (i) {
5265 complete += ',';
5266 }
5267 if (strstr(type.TrueName(*fNormalizedCtxt), "char")) {
5268 TString chpar('\"');
5269 chpar += (nxtpar->String()).ReplaceAll("\"", "\\\"");
5270 // At this point we have to check if string contains \\"
5271 // and apply some more sophisticated parser. Not implemented yet!
5272 complete += chpar;
5273 complete += '\"';
5274 }
5275 else {
5276 complete += nxtpar->String();
5277 }
5278 }
5279 listpar = complete.Data();
5280 }
5281
5282 // And now execute it.
5284 if (error) {
5285 *error = TInterpreter::kNoError;
5286 }
5287 // If the actual class of this object inherits 2nd (or more) from TObject,
5288 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5289 // hence gInterpreter->Execute will improperly correct the offset.
5290 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5292 TClingMethodInfo *minfo = (TClingMethodInfo*)method->fInfo;
5293 func.Init(*minfo);
5294 func.SetArgs(listpar);
5295 // Now calculate the 'this' pointer offset for the method
5296 // when starting from the class described by cl.
5297 const CXXMethodDecl * mdecl = dyn_cast<CXXMethodDecl>(minfo->GetTargetFunctionDecl());
5299 void* address = (void*)((Longptr_t)addr + offset);
5300 func.Exec(address);
5301}
5302
5303////////////////////////////////////////////////////////////////////////////////
5304
5305void TCling::ExecuteWithArgsAndReturn(TMethod* method, void* address,
5306 const void* args[] /*=0*/,
5307 int nargs /*=0*/,
5308 void* ret/*= 0*/) const
5309{
5310 if (!method) {
5311 Error("ExecuteWithArgsAndReturn", "No method was defined");
5312 return;
5313 }
5314
5315 TClingMethodInfo* minfo = (TClingMethodInfo*) method->fInfo;
5316 TClingCallFunc func(*minfo);
5317 func.ExecWithArgsAndReturn(address, args, nargs, ret);
5318}
5319
5320////////////////////////////////////////////////////////////////////////////////
5321/// Execute a cling macro.
5322
5324{
5326 fCurExecutingMacros.push_back(filename);
5328 fCurExecutingMacros.pop_back();
5329 return result;
5330}
5331
5332////////////////////////////////////////////////////////////////////////////////
5333/// Return the file name of the current un-included interpreted file.
5334/// See the documentation for GetCurrentMacroName().
5335
5337{
5338 Warning("GetTopLevelMacroName", "Must change return type!");
5339 return fCurExecutingMacros.back();
5340}
5341
5342////////////////////////////////////////////////////////////////////////////////
5343/// Return the file name of the currently interpreted file,
5344/// included or not. Example to illustrate the difference between
5345/// GetCurrentMacroName() and GetTopLevelMacroName():
5346/// ~~~ {.cpp}
5347/// void inclfile() {
5348/// std::cout << "In inclfile.C" << std::endl;
5349/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5350/// TCling::GetCurrentMacroName() << std::endl;
5351/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5352/// TCling::GetTopLevelMacroName() << std::endl;
5353/// }
5354/// ~~~
5355/// ~~~ {.cpp}
5356/// void mymacro() {
5357/// std::cout << "In mymacro.C" << std::endl;
5358/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5359/// TCling::GetCurrentMacroName() << std::endl;
5360/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5361/// TCling::GetTopLevelMacroName() << std::endl;
5362/// std::cout << " Now calling inclfile..." << std::endl;
5363/// gInterpreter->ProcessLine(".x inclfile.C");;
5364/// }
5365/// ~~~
5366/// Running mymacro.C will print:
5367///
5368/// ~~~ {.cpp}
5369/// root [0] .x mymacro.C
5370/// ~~~
5371/// In mymacro.C
5372/// ~~~ {.cpp}
5373/// TCling::GetCurrentMacroName() returns ./mymacro.C
5374/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5375/// ~~~
5376/// Now calling inclfile...
5377/// In inclfile.h
5378/// ~~~ {.cpp}
5379/// TCling::GetCurrentMacroName() returns inclfile.C
5380/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5381/// ~~~
5382
5384{
5385#if defined(R__MUST_REVISIT)
5386#if R__MUST_REVISIT(6,0)
5387 Warning("GetCurrentMacroName", "Must change return type!");
5388#endif
5389#endif
5390 return fCurExecutingMacros.back();
5391}
5392
5393////////////////////////////////////////////////////////////////////////////////
5394/// Return the absolute type of typeDesc.
5395/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
5396/// You need to use the result immediately before it is being overwritten.
5397
5398const char* TCling::TypeName(const char* typeDesc)
5399{
5400 TTHREAD_TLS_DECL(std::string,t);
5401
5402 if (!strstr(typeDesc, "(*)(")) {
5403 const char *s = strchr(typeDesc, ' ');
5404 const char *template_start = strchr(typeDesc, '<');
5405 if (!strcmp(typeDesc, "long long")) {
5406 t = typeDesc;
5407 }
5408 else if (!strncmp(typeDesc, "unsigned ", s + 1 - typeDesc)) {
5409 t = typeDesc;
5410 }
5411 // s is the position of the second 'word' (if any)
5412 // except in the case of templates where there will be a space
5413 // just before any closing '>': eg.
5414 // TObj<std::vector<UShort_t,__malloc_alloc_template<0> > >*
5415 else if (s && (template_start == 0 || (s < template_start))) {
5416 t = s + 1;
5417 }
5418 else {
5419 t = typeDesc;
5420 }
5421 }
5422 else {
5423 t = typeDesc;
5424 }
5425 auto l = t.length();
5426 while (l > 0 && (t[l - 1] == '*' || t[l - 1] == '&'))
5427 --l;
5428 t.resize(l);
5429 return t.c_str(); // NOLINT
5430}
5431
5432static bool requiresRootMap(const char* rootmapfile)
5433{
5434 assert(rootmapfile && *rootmapfile);
5435
5436 llvm::StringRef libName = llvm::sys::path::filename(rootmapfile);
5437 libName.consume_back(".rootmap");
5438
5439 return !gInterpreter->HasPCMForLibrary(libName.str().c_str());
5440}
5441
5442////////////////////////////////////////////////////////////////////////////////
5443/// Read and parse a rootmapfile in its new format, and return 0 in case of
5444/// success, -1 if the file has already been read, and -3 in case its format
5445/// is the old one (e.g. containing "Library.ClassName"), -4 in case of syntax
5446/// error.
5447
5448int TCling::ReadRootmapFile(const char *rootmapfile, TUniqueString *uniqueString)
5449{
5450 if (!(rootmapfile && *rootmapfile))
5451 return 0;
5452
5453 if (!requiresRootMap(rootmapfile))
5454 return 0; //