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}
252R__DLLEXPORT bool TCling__TEST_isInvalidDecl(ClassInfo_t *input) {
253 TClingClassInfo *info( (TClingClassInfo*) input);
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.
429 Long64_t value;
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
899bool TClingLookupHelper__AutoParse(const char *cname)
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 argv - array of arguments passed to the cling::Interpreter constructor
1368/// e.g. `-DFOO=bar`. The last element of the array must be `nullptr`.
1369
1370TCling::TCling(const char *name, const char *title, const char* const argv[])
1371: TInterpreter(name, title), fMore(0), fGlobalsListSerial(-1), fMapfile(nullptr),
1375{
1376 fPrompt[0] = 0;
1377 const bool fromRootCling = IsFromRootCling();
1378
1379 fCxxModulesEnabled = false;
1380#ifdef R__USE_CXXMODULES
1381 fCxxModulesEnabled = true;
1382#endif
1383
1384 llvm::install_fatal_error_handler(&exceptionErrorHandler);
1385
1386 fTemporaries = new std::vector<cling::Value>();
1387
1388 std::vector<std::string> clingArgsStorage;
1389 clingArgsStorage.push_back("cling4root");
1390 for (const char* const* arg = argv; *arg; ++arg)
1391 clingArgsStorage.push_back(*arg);
1392
1393 // rootcling sets its arguments through TROOT::GetExtraInterpreterArgs().
1394 if (!fromRootCling) {
1396
1397 // Add -I early so ASTReader can find the headers.
1398 std::string interpInclude(TROOT::GetEtcDir().Data());
1399 clingArgsStorage.push_back("-I" + interpInclude);
1400
1401 // Add include path to etc/cling.
1402 clingArgsStorage.push_back("-I" + interpInclude + "/cling");
1403
1404 // Add include path to etc/cling.
1405 clingArgsStorage.push_back("-I" + interpInclude + "/cling/plugins/include");
1406
1407 // Add the root include directory and etc/ to list searched by default.
1408 clingArgsStorage.push_back(std::string(("-I" + TROOT::GetIncludeDir()).Data()));
1409
1410 // Add the current path to the include path
1411 // TCling::AddIncludePath(".");
1412
1413 // Attach the PCH (unless we have C++ modules enabled which provide the
1414 // same functionality).
1415 if (!fCxxModulesEnabled) {
1416 std::string pchFilename = interpInclude + "/allDict.cxx.pch";
1417 if (gSystem->Getenv("ROOT_PCH")) {
1418 pchFilename = gSystem->Getenv("ROOT_PCH");
1419 }
1420
1421 clingArgsStorage.push_back("-include-pch");
1422 clingArgsStorage.push_back(pchFilename);
1423 }
1424
1425 clingArgsStorage.push_back("-Wno-undefined-inline");
1426 clingArgsStorage.push_back("-fsigned-char");
1427 }
1428
1429 // Process externally passed arguments if present.
1430 llvm::Optional<std::string> EnvOpt = llvm::sys::Process::GetEnv("EXTRA_CLING_ARGS");
1431 if (EnvOpt.hasValue()) {
1432 StringRef Env(*EnvOpt);
1433 while (!Env.empty()) {
1434 StringRef Arg;
1435 std::tie(Arg, Env) = Env.split(' ');
1436 clingArgsStorage.push_back(Arg.str());
1437 }
1438 }
1439
1440 auto GetEnvVarPath = [](const std::string &EnvVar,
1441 std::vector<std::string> &Paths) {
1442 llvm::Optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(EnvVar);
1443 if (EnvOpt.hasValue()) {
1444 StringRef Env(*EnvOpt);
1445 while (!Env.empty()) {
1446 StringRef Arg;
1447 std::tie(Arg, Env) = Env.split(ROOT::FoundationUtils::GetEnvPathSeparator());
1448 if (std::find(Paths.begin(), Paths.end(), Arg.str()) == Paths.end())
1449 Paths.push_back(Arg.str());
1450 }
1451 }
1452 };
1453
1454 if (fCxxModulesEnabled) {
1455 std::vector<std::string> Paths;
1456 // ROOT usually knows better where its libraries are. This way we can
1457 // discover modules without having to should thisroot.sh and should fix
1458 // gnuinstall.
1459#ifdef R__WIN32
1460 Paths.push_back(TROOT::GetBinDir().Data());
1461#else
1462 Paths.push_back(TROOT::GetLibDir().Data());
1463#endif
1464 GetEnvVarPath("CLING_PREBUILT_MODULE_PATH", Paths);
1465 std::string EnvVarPath;
1466 for (const std::string& P : Paths)
1468 // FIXME: We should make cling -fprebuilt-module-path work.
1469 gSystem->Setenv("CLING_PREBUILT_MODULE_PATH", EnvVarPath.c_str());
1470 }
1471
1472 // FIXME: This only will enable frontend timing reports.
1473 EnvOpt = llvm::sys::Process::GetEnv("ROOT_CLING_TIMING");
1474 if (EnvOpt.hasValue())
1475 clingArgsStorage.push_back("-ftime-report");
1476
1477 // Add the overlay file. Note that we cannot factor it out for both root
1478 // and rootcling because rootcling activates modules only if -cxxmodule
1479 // flag is passed.
1480 if (fCxxModulesEnabled && !fromRootCling) {
1481 // For now we prefer rootcling to enumerate explicitly its modulemaps.
1482 std::vector<std::string> ModuleMaps;
1483 std::string ModuleMapSuffix = ROOT::FoundationUtils::GetPathSeparator() + "module.modulemap";
1484 ModuleMaps.push_back(TROOT::GetIncludeDir().Data() + ModuleMapSuffix);
1485 GetEnvVarPath("CLING_MODULEMAP_FILES", ModuleMaps);
1486
1487 std::string cwd = gSystem->WorkingDirectory();
1488 // Give highest precedence of the modulemap in the cwd if any.
1489 if (llvm::sys::fs::exists(cwd + ModuleMapSuffix))
1490 ModuleMaps.push_back(cwd + ModuleMapSuffix);
1491
1492 for (const std::string& M : ModuleMaps)
1493 clingArgsStorage.push_back("-fmodule-map-file=" + M);
1494
1495 std::string ModulesCachePath;
1496 EnvOpt = llvm::sys::Process::GetEnv("CLING_MODULES_CACHE_PATH");
1497 if (EnvOpt.hasValue()){
1498 StringRef Env(*EnvOpt);
1499 assert(llvm::sys::fs::exists(Env) && "Path does not exist!");
1500 ModulesCachePath = Env.str();
1501 } else {
1502 ModulesCachePath = TROOT::GetLibDir();
1503 }
1504
1505 clingArgsStorage.push_back("-fmodules-cache-path=" + ModulesCachePath);
1506 }
1507
1508 std::vector<const char*> interpArgs;
1509 for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1510 eArg = clingArgsStorage.end(); iArg != eArg; ++iArg)
1511 interpArgs.push_back(iArg->c_str());
1512
1513 // Activate C++ modules support. If we are running within rootcling, it's up
1514 // to rootcling to set this flag depending on whether it wants to produce
1515 // C++ modules.
1516 TString vfsArg;
1517 if (fCxxModulesEnabled) {
1518 if (!fromRootCling) {
1519 // We only set this flag, rest is done by the CIFactory.
1520 interpArgs.push_back("-fmodules");
1521 interpArgs.push_back("-fno-implicit-module-maps");
1522 // We should never build modules during runtime, so let's enable the
1523 // module build remarks from clang to make it easier to spot when we do
1524 // this by accident.
1525 interpArgs.push_back("-Rmodule-build");
1526 }
1527 // ROOT implements its AutoLoading upon module's link directives. We
1528 // generate module A { header "A.h" link "A.so" export * } where ROOT's
1529 // facilities use the link directive to dynamically load the relevant
1530 // library. So, we need to suppress clang's default autolink behavior.
1531 interpArgs.push_back("-fno-autolink");
1532 }
1533
1534#ifdef R__FAST_MATH
1535 // Same setting as in rootcling_impl.cxx.
1536 interpArgs.push_back("-ffast-math");
1537#endif
1538
1539 TString llvmResourceDir = TROOT::GetEtcDir() + "/cling";
1540 // Add statically injected extra arguments, usually coming from rootcling.
1541 for (const char** extraArgs = TROOT::GetExtraInterpreterArgs();
1542 extraArgs && *extraArgs; ++extraArgs) {
1543 if (!strcmp(*extraArgs, "-resource-dir")) {
1544 // Take the next arg as the llvm resource directory.
1545 llvmResourceDir = *(++extraArgs);
1546 } else {
1547 interpArgs.push_back(*extraArgs);
1548 }
1549 }
1550
1551 for (const auto &arg: TROOT::AddExtraInterpreterArgs({})) {
1552 interpArgs.push_back(arg.c_str());
1553 }
1554
1555 // Add the Rdict module file extension.
1556 cling::Interpreter::ModuleFileExtensions extensions;
1557 EnvOpt = llvm::sys::Process::GetEnv("ROOTDEBUG_RDICT");
1558 if (!EnvOpt.hasValue())
1559 extensions.push_back(std::make_shared<TClingRdictModuleFileExtension>());
1560
1561 fInterpreter = llvm::make_unique<cling::Interpreter>(interpArgs.size(),
1562 &(interpArgs[0]),
1563 llvmResourceDir, extensions);
1564
1565 // Don't check whether modules' files exist.
1566 fInterpreter->getCI()->getPreprocessorOpts().DisablePCHValidation = true;
1567
1568 // Until we can disable AutoLoading during Sema::CorrectTypo() we have
1569 // to disable spell checking.
1570 fInterpreter->getCI()->getLangOpts().SpellChecking = false;
1571
1572 // We need stream that doesn't close its file descriptor, thus we are not
1573 // using llvm::outs. Keeping file descriptor open we will be able to use
1574 // the results in pipes (Savannah #99234).
1575 static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO, /*ShouldClose*/false);
1576 fMetaProcessor = llvm::make_unique<cling::MetaProcessor>(*fInterpreter, fMPOuts);
1577
1580
1581 // We are now ready (enough is loaded) to init the list of opaque typedefs.
1588
1589 // Disallow auto-parsing in rootcling
1590 fIsAutoParsingSuspended = fromRootCling;
1591
1592 ResetAll();
1593
1594 // Enable dynamic lookup
1595 if (!fromRootCling) {
1596 fInterpreter->enableDynamicLookup();
1597 }
1598
1599 // Enable ClinG's DefinitionShadower for ROOT.
1600 fInterpreter->getRuntimeOptions().AllowRedefinition = 1;
1601
1602 // Attach cling callbacks last; they might need TROOT::fInterpreter
1603 // and should thus not be triggered during the equivalent of
1604 // TROOT::fInterpreter = new TCling;
1605 std::unique_ptr<TClingCallbacks>
1606 clingCallbacks(new TClingCallbacks(GetInterpreterImpl(), /*hasCodeGen*/ !fromRootCling));
1607 fClingCallbacks = clingCallbacks.get();
1609 fInterpreter->setCallbacks(std::move(clingCallbacks));
1610
1611 if (!fromRootCling) {
1612 cling::DynamicLibraryManager& DLM = *fInterpreter->getDynamicLibraryManager();
1613 // Make sure cling looks into ROOT's libdir, even if not part of LD_LIBRARY_PATH
1614 // e.g. because of an RPATH build.
1615 DLM.addSearchPath(TROOT::GetLibDir().Data(), /*isUser=*/true,
1616 /*prepend=*/true);
1617 auto ShouldPermanentlyIgnore = [](llvm::StringRef FileName) -> bool{
1618 llvm::StringRef stem = llvm::sys::path::stem(FileName);
1619 return stem.startswith("libNew") || stem.startswith("libcppyy_backend");
1620 };
1621 // Initialize the dyld for the llvmLazyFunctionCreator.
1622 DLM.initializeDyld(ShouldPermanentlyIgnore);
1623 fInterpreter->installLazyFunctionCreator(llvmLazyFunctionCreator);
1624 }
1625}
1626
1627
1628////////////////////////////////////////////////////////////////////////////////
1629/// Destroy the interpreter interface.
1630
1632{
1633 // ROOT's atexit functions require the interepreter to be available.
1634 // Run them before shutting down.
1635 if (!IsFromRootCling())
1636 GetInterpreterImpl()->runAtExitFuncs();
1637 fIsShuttingDown = true;
1638 delete fMapfile;
1639 delete fRootmapFiles;
1640 delete fTemporaries;
1641 delete fNormalizedCtxt;
1642 delete fLookupHelper;
1643 gCling = 0;
1644}
1645
1646////////////////////////////////////////////////////////////////////////////////
1647/// Initialize the interpreter, once TROOT::fInterpreter is set.
1648
1650{
1652
1653 // We are set up. Enable ROOT's AutoLoading.
1654 if (IsFromRootCling())
1655 return;
1656
1657 // Read the rules before enabling the auto loading to not inadvertently
1658 // load the libraries for the classes concerned even-though the user is
1659 // *not* using them.
1660 // Note this call must happen before the first call to LoadLibraryMap.
1661 assert(GetRootMapFiles() == 0 && "Must be called before LoadLibraryMap!");
1662 TClass::ReadRules(); // Read the default customization rules ...
1663
1665 SetClassAutoLoading(true);
1666}
1667
1669{
1670 fIsShuttingDown = true;
1671 ResetGlobals();
1672}
1673
1674////////////////////////////////////////////////////////////////////////////////
1675/// Helper to initialize TVirtualStreamerInfo's factor early.
1676/// Use static initialization to insure only one TStreamerInfo is created.
1678{
1679 // Use lambda since SetFactory return void.
1680 auto setFactory = []() {
1682 return kTRUE;
1683 };
1684 static bool doneFactory = setFactory();
1685 return doneFactory; // avoid unused variable warning.
1686}
1687
1688////////////////////////////////////////////////////////////////////////////////
1689/// Register Rdict data for future loading by LoadPCM;
1690
1691void TCling::RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
1692{
1693 if (IsFromRootCling())
1694 return;
1695
1696 if (llvm::sys::fs::exists(pcmFileNameFullPath)) {
1697 ::Error("TCling::RegisterRdictForLoadPCM", "Rdict '%s' is both in Module extension and in File system.", pcmFileNameFullPath.c_str());
1698 return;
1699 }
1700
1701 // The pcmFileNameFullPath must be resolved already because we cannot resolve
1702 // a link to a non-existent file.
1703 fPendingRdicts[pcmFileNameFullPath] = *pcmContent;
1704}
1705
1706////////////////////////////////////////////////////////////////////////////////
1707/// Tries to load a PCM from TFile; returns true on success.
1708
1710{
1711 auto listOfKeys = pcmFile.GetListOfKeys();
1712
1713 // This is an empty pcm
1714 if (listOfKeys && ((listOfKeys->GetSize() == 0) || // Nothing here, or
1715 ((listOfKeys->GetSize() == 1) && // only one, and
1716 !strcmp(((TKey *)listOfKeys->At(0))->GetName(), "EMPTY") // name is EMPTY
1717 ))) {
1718 return;
1719 }
1720
1721 TObjArray *protoClasses;
1722 if (gDebug > 1)
1723 ::Info("TCling::LoadPCMImpl", "reading protoclasses for %s \n", pcmFile.GetName());
1724
1725 pcmFile.GetObject("__ProtoClasses", protoClasses);
1726
1727 if (protoClasses) {
1728 for (auto obj : *protoClasses) {
1729 TProtoClass *proto = (TProtoClass *)obj;
1731 }
1732 // Now that all TClass-es know how to set them up we can update
1733 // existing TClasses, which might cause the creation of e.g. TBaseClass
1734 // objects which in turn requires the creation of TClasses, that could
1735 // come from the PCH, but maybe later in the loop. Instead of resolving
1736 // a dependency graph the addition to the TClassTable above allows us
1737 // to create these dependent TClasses as needed below.
1738 for (auto proto : *protoClasses) {
1739 if (TClass *existingCl = (TClass *)gROOT->GetListOfClasses()->FindObject(proto->GetName())) {
1740 // We have an existing TClass object. It might be emulated
1741 // or interpreted; we now have more information available.
1742 // Make that available.
1743 if (existingCl->GetState() != TClass::kHasTClassInit) {
1744 DictFuncPtr_t dict = gClassTable->GetDict(proto->GetName());
1745 if (!dict) {
1746 ::Error("TCling::LoadPCM", "Inconsistent TClassTable for %s", proto->GetName());
1747 } else {
1748 // This will replace the existing TClass.
1749 TClass *ncl = (*dict)();
1750 if (ncl)
1751 ncl->PostLoadCheck();
1752 }
1753 }
1754 }
1755 }
1756
1757 protoClasses->Clear(); // Ownership was transfered to TClassTable.
1758 delete protoClasses;
1759 }
1760
1761 TObjArray *dataTypes;
1762 pcmFile.GetObject("__Typedefs", dataTypes);
1763 if (dataTypes) {
1764 for (auto typedf : *dataTypes)
1765 gROOT->GetListOfTypes()->Add(typedf);
1766 dataTypes->Clear(); // Ownership was transfered to TListOfTypes.
1767 delete dataTypes;
1768 }
1769
1770 TObjArray *enums;
1771 pcmFile.GetObject("__Enums", enums);
1772 if (enums) {
1773 // Cache the pointers
1774 auto listOfGlobals = gROOT->GetListOfGlobals();
1775 auto listOfEnums = dynamic_cast<THashList *>(gROOT->GetListOfEnums());
1776 // Loop on enums and then on enum constants
1777 for (auto selEnum : *enums) {
1778 const char *enumScope = selEnum->GetTitle();
1779 const char *enumName = selEnum->GetName();
1780 if (strcmp(enumScope, "") == 0) {
1781 // This is a global enum and is added to the
1782 // list of enums and its constants to the list of globals
1783 if (!listOfEnums->THashList::FindObject(enumName)) {
1784 ((TEnum *)selEnum)->SetClass(nullptr);
1785 listOfEnums->Add(selEnum);
1786 }
1787 for (auto enumConstant : *static_cast<TEnum *>(selEnum)->GetConstants()) {
1788 if (!listOfGlobals->FindObject(enumConstant)) {
1789 listOfGlobals->Add(enumConstant);
1790 }
1791 }
1792 } else {
1793 // This enum is in a namespace. A TClass entry is bootstrapped if
1794 // none exists yet and the enum is added to it
1795 TClass *nsTClassEntry = TClass::GetClass(enumScope);
1796 if (!nsTClassEntry) {
1797 nsTClassEntry = new TClass(enumScope, 0, TClass::kNamespaceForMeta, true);
1798 }
1799 auto listOfEnums = nsTClassEntry->fEnums.load();
1800 if (!listOfEnums) {
1801 if ((kIsClass | kIsStruct | kIsUnion) & nsTClassEntry->Property()) {
1802 // For this case, the list will be immutable once constructed
1803 // (i.e. in this case, by the end of this routine).
1804 listOfEnums = nsTClassEntry->fEnums = new TListOfEnums(nsTClassEntry);
1805 } else {
1806 // namespaces can have enums added to them
1807 listOfEnums = nsTClassEntry->fEnums = new TListOfEnumsWithLock(nsTClassEntry);
1808 }
1809 }
1810 if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)) {
1811 ((TEnum *)selEnum)->SetClass(nsTClassEntry);
1812 listOfEnums->Add(selEnum);
1813 }
1814 }
1815 }
1816 enums->Clear();
1817 delete enums;
1818 }
1819}
1820
1821////////////////////////////////////////////////////////////////////////////////
1822/// Tries to load a rdict PCM, issues diagnostics if it fails.
1823
1824void TCling::LoadPCM(std::string pcmFileNameFullPath)
1825{
1826 SuspendAutoLoadingRAII autoloadOff(this);
1827 SuspendAutoParsing autoparseOff(this);
1828 assert(!pcmFileNameFullPath.empty());
1829 assert(llvm::sys::path::is_absolute(pcmFileNameFullPath));
1830
1831 // Easier to work with the ROOT interfaces.
1832 TString pcmFileName = pcmFileNameFullPath;
1833
1834 // Prevent the ROOT-PCMs hitting this during auto-load during
1835 // JITting - which will cause recursive compilation.
1836 // Avoid to call the plugin manager at all.
1838
1840 llvm::SaveAndRestore<Int_t> SaveGDebug(gDebug);
1841 if (gDebug > 5) {
1842 gDebug -= 5;
1843 ::Info("TCling::LoadPCM", "Loading ROOT PCM %s", pcmFileName.Data());
1844 } else {
1845 gDebug = 0;
1846 }
1847
1848 if (llvm::sys::fs::is_symlink_file(pcmFileNameFullPath))
1849 pcmFileNameFullPath = ROOT::TMetaUtils::GetRealPath(pcmFileNameFullPath);
1850
1851 auto pendingRdict = fPendingRdicts.find(pcmFileNameFullPath);
1852 if (pendingRdict != fPendingRdicts.end()) {
1853 llvm::StringRef pcmContent = pendingRdict->second;
1854 TMemFile::ZeroCopyView_t range{pcmContent.data(), pcmContent.size()};
1855 std::string RDictFileOpts = pcmFileNameFullPath + "?filetype=pcm";
1856 TMemFile pcmMemFile(RDictFileOpts.c_str(), range);
1857
1858 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
1859 LoadPCMImpl(pcmMemFile);
1860 fPendingRdicts.erase(pendingRdict);
1861
1862 return;
1863 }
1864
1865 if (!llvm::sys::fs::exists(pcmFileNameFullPath)) {
1866 ::Error("TCling::LoadPCM", "ROOT PCM %s file does not exist",
1867 pcmFileNameFullPath.data());
1868 if (!fPendingRdicts.empty())
1869 for (const auto &rdict : fPendingRdicts)
1870 ::Info("TCling::LoadPCM", "In-memory ROOT PCM candidate %s\n",
1871 rdict.first.c_str());
1872 return;
1873 }
1874
1875 if (!gROOT->IsRootFile(pcmFileName)) {
1876 Fatal("LoadPCM", "The file %s is not a ROOT as was expected\n", pcmFileName.Data());
1877 return;
1878 }
1879 TFile pcmFile(pcmFileName + "?filetype=pcm", "READ");
1880 LoadPCMImpl(pcmFile);
1881}
1882
1883//______________________________________________________________________________
1884
1885namespace {
1886 using namespace clang;
1887
1888 class ExtLexicalStorageAdder: public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1889 // This class is to be considered an helper for autoparsing.
1890 // It visits the AST and marks all classes (in all of their redeclarations)
1891 // with the setHasExternalLexicalStorage method.
1892 public:
1893 bool VisitRecordDecl(clang::RecordDecl* rcd){
1894 if (gDebug > 2)
1895 Info("ExtLexicalStorageAdder",
1896 "Adding external lexical storage to class %s",
1897 rcd->getNameAsString().c_str());
1898 auto reDeclPtr = rcd->getMostRecentDecl();
1899 do {
1900 reDeclPtr->setHasExternalLexicalStorage();
1901 } while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1902
1903 return false;
1904 }
1905 };
1906
1907
1908}
1909
1910////////////////////////////////////////////////////////////////////////////////
1911///\returns true if the module map was loaded, false on error or if the map was
1912/// already loaded.
1913bool TCling::RegisterPrebuiltModulePath(const std::string &FullPath,
1914 const std::string &ModuleMapName /*= "module.modulemap"*/) const
1915{
1916 assert(llvm::sys::path::is_absolute(FullPath));
1917 Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
1918 FileManager &FM = PP.getFileManager();
1919 // FIXME: In a ROOT session we can add an include path (through .I /inc/path)
1920 // We should look for modulemap files there too.
1921 const DirectoryEntry *DE = FM.getDirectory(FullPath);
1922 if (DE) {
1923 HeaderSearch &HS = PP.getHeaderSearchInfo();
1924 HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1925 const auto &ModPaths = HSOpts.PrebuiltModulePaths;
1926 bool pathExists = std::find(ModPaths.begin(), ModPaths.end(), FullPath) != ModPaths.end();
1927 if (!pathExists)
1928 HSOpts.AddPrebuiltModulePath(FullPath);
1929 // We cannot use HS.lookupModuleMapFile(DE, /*IsFramework*/ false);
1930 // because its internal call to getFile has CacheFailure set to true.
1931 // In our case, modulemaps can appear any time due to ACLiC.
1932 // Code copied from HS.lookupModuleMapFile.
1933 llvm::SmallString<256> ModuleMapFileName(DE->getName());
1934 llvm::sys::path::append(ModuleMapFileName, ModuleMapName);
1935 const FileEntry *FE = FM.getFile(ModuleMapFileName, /*openFile*/ false,
1936 /*CacheFailure*/ false);
1937 if (FE) {
1938 if (!HS.loadModuleMapFile(FE, /*IsSystem*/ false))
1939 return true;
1940 Error("RegisterPrebuiltModulePath", "Could not load modulemap in %s", ModuleMapFileName.c_str());
1941 }
1942 }
1943 return false;
1944}
1945
1946////////////////////////////////////////////////////////////////////////////////
1947/// List of dicts that have the PCM information already in the PCH.
1948static const std::unordered_set<std::string> gIgnoredPCMNames = {"libCore",
1949 "libRint",
1950 "libThread",
1951 "libRIO",
1952 "libImt",
1953 "libMultiProc",
1954 "libcomplexDict",
1955 "libdequeDict",
1956 "liblistDict",
1957 "libforward_listDict",
1958 "libvectorDict",
1959 "libmapDict",
1960 "libmultimap2Dict",
1961 "libmap2Dict",
1962 "libmultimapDict",
1963 "libsetDict",
1964 "libmultisetDict",
1965 "libunordered_setDict",
1966 "libunordered_multisetDict",
1967 "libunordered_mapDict",
1968 "libunordered_multimapDict",
1969 "libvalarrayDict",
1970 "G__GenVector32",
1971 "G__Smatrix32"};
1972
1973static void PrintDlError(const char *dyLibName, const char *modulename)
1974{
1975#ifdef R__WIN32
1976 char dyLibError[1000];
1977 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1978 dyLibError, sizeof(dyLibError), NULL);
1979#else
1980 const char *dyLibError = dlerror();
1981#endif
1982 ::Error("TCling::RegisterModule", "Cannot open shared library %s for dictionary %s:\n %s", dyLibName, modulename,
1983 (dyLibError) ? dyLibError : "");
1984}
1985
1986////////////////////////////////////////////////////////////////////////////////
1987// Update all the TClass registered in fClassesToUpdate
1988
1990{
1991 while (!fClassesToUpdate.empty()) {
1992 TClass *oldcl = fClassesToUpdate.back().first;
1993 // If somehow the TClass has already been loaded (maybe it was registered several time),
1994 // we skip it. Otherwise, the existing TClass is in mode kInterpreted, kEmulated or
1995 // maybe even kForwardDeclared and needs to replaced.
1996 if (oldcl->GetState() != TClass::kHasTClassInit) {
1997 // if (gDebug > 2) Info("RegisterModule", "Forcing TClass init for %s", oldcl->GetName());
1998 DictFuncPtr_t dict = fClassesToUpdate.back().second;
1999 fClassesToUpdate.pop_back();
2000 // Calling func could manipulate the list so, let maintain the list
2001 // then call the dictionary function.
2002 TClass *ncl = dict();
2003 if (ncl) ncl->PostLoadCheck();
2004 } else {
2005 fClassesToUpdate.pop_back();
2006 }
2007 }
2008}
2009////////////////////////////////////////////////////////////////////////////////
2010/// Inject the module named "modulename" into cling; load all headers.
2011/// headers is a 0-terminated array of header files to #include after
2012/// loading the module. The module is searched for in all $LD_LIBRARY_PATH
2013/// entries (or %PATH% on Windows).
2014/// This function gets called by the static initialization of dictionary
2015/// libraries.
2016/// The payload code is injected "as is" in the interpreter.
2017/// The value of 'triggerFunc' is used to find the shared library location.
2018
2019void TCling::RegisterModule(const char* modulename,
2020 const char** headers,
2021 const char** includePaths,
2022 const char* payloadCode,
2023 const char* fwdDeclsCode,
2024 void (*triggerFunc)(),
2025 const FwdDeclArgsToKeepCollection_t& fwdDeclsArgToSkip,
2026 const char** classesHeaders,
2027 Bool_t lateRegistration /*=false*/,
2028 Bool_t hasCxxModule /*=false*/)
2029{
2030 const bool fromRootCling = IsFromRootCling();
2031 // We need the dictionary initialization but we don't want to inject the
2032 // declarations into the interpreter, except for those we really need for
2033 // I/O; see rootcling.cxx after the call to TCling__GetInterpreter().
2034 if (fromRootCling) return;
2035
2036 // When we cannot provide a module for the library we should enable header
2037 // parsing. This 'mixed' mode ensures gradual migration to modules.
2038 llvm::SaveAndRestore<bool> SaveHeaderParsing(fHeaderParsingOnDemand);
2039 fHeaderParsingOnDemand = !hasCxxModule;
2040
2041 // Treat Aclic Libs in a special way. Do not delay the parsing.
2042 bool hasHeaderParsingOnDemand = fHeaderParsingOnDemand;
2043 bool isACLiC = strstr(modulename, "_ACLiC_dict") != nullptr;
2044 if (hasHeaderParsingOnDemand && isACLiC) {
2045 if (gDebug>1)
2046 Info("TCling::RegisterModule",
2047 "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
2048 hasHeaderParsingOnDemand = false;
2049 }
2050
2051
2052 // Make sure we relookup symbols that were search for before we loaded
2053 // their autoparse information. We could be more subtil and remove only
2054 // the failed one or only the one in this module, but for now this is
2055 // better than nothing.
2056 fLookedUpClasses.clear();
2057
2058 // Make sure we do not set off AutoLoading or autoparsing during the
2059 // module registration!
2060 SuspendAutoLoadingRAII autoLoadOff(this);
2061
2062 for (const char** inclPath = includePaths; *inclPath; ++inclPath) {
2063 TCling::AddIncludePath(*inclPath);
2064 }
2065 cling::Transaction* T = 0;
2066 // Put the template decls and the number of arguments to skip in the TNormalizedCtxt
2067 for (auto& fwdDeclArgToSkipPair : fwdDeclsArgToSkip){
2068 const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
2069 const int nArgsToSkip = fwdDeclArgToSkipPair.second;
2070 auto compRes = fInterpreter->declare(fwdDecl.c_str(), &T);
2071 assert(cling::Interpreter::kSuccess == compRes &&
2072 "A fwd declaration could not be compiled");
2073 if (compRes!=cling::Interpreter::kSuccess){
2074 Warning("TCling::RegisterModule",
2075 "Problems in declaring string '%s' were encountered.",
2076 fwdDecl.c_str()) ;
2077 continue;
2078 }
2079
2080 // Drill through namespaces recursively until the template is found
2081 if(ClassTemplateDecl* TD = FindTemplateInNamespace(T->getFirstDecl().getSingleDecl())){
2082 fNormalizedCtxt->AddTemplAndNargsToKeep(TD->getCanonicalDecl(), nArgsToSkip);
2083 }
2084
2085 }
2086
2087 // FIXME: Remove #define __ROOTCLING__ once PCMs are there.
2088 // This is used to give Sema the same view on ACLiC'ed files (which
2089 // are then #included through the dictionary) as rootcling had.
2090 TString code = gNonInterpreterClassDef;
2091 if (payloadCode)
2092 code += payloadCode;
2093
2094 std::string dyLibName = cling::DynamicLibraryManager::getSymbolLocation(triggerFunc);
2095 assert(!llvm::sys::fs::is_symlink_file(dyLibName));
2096
2097 if (dyLibName.empty()) {
2098 ::Error("TCling::RegisterModule", "Dictionary trigger function for %s not found", modulename);
2099 return;
2100 }
2101
2102 // The triggerFunc may not be in a shared object but in an executable.
2103 bool isSharedLib = cling::DynamicLibraryManager::isSharedLibrary(dyLibName);
2104
2105 bool wasDlopened = false;
2106
2107 // If this call happens after dlopen has finished (i.e. late registration)
2108 // there is no need to dlopen the library recursively. See ROOT-8437 where
2109 // the dyLibName would correspond to the binary.
2110 if (!lateRegistration) {
2111
2112 if (isSharedLib) {
2113 // We need to open the dictionary shared library, to resolve symbols
2114 // requested by the JIT from it: as the library is currently being dlopen'ed,
2115 // its symbols are not yet reachable from the process.
2116 // Recursive dlopen seems to work just fine.
2117 void* dyLibHandle = dlopen(dyLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
2118 if (dyLibHandle) {
2119 fRegisterModuleDyLibs.push_back(dyLibHandle);
2120 wasDlopened = true;
2121 } else {
2122 PrintDlError(dyLibName.c_str(), modulename);
2123 }
2124 }
2125 } // if (!lateRegistration)
2126
2127 if (hasHeaderParsingOnDemand && fwdDeclsCode){
2128 // We now parse the forward declarations. All the classes are then modified
2129 // in order for them to have an external lexical storage.
2130 std::string fwdDeclsCodeLessEnums;
2131 {
2132 // Search for enum forward decls and only declare them if no
2133 // declaration exists yet.
2134 std::string fwdDeclsLine;
2135 std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
2136 std::vector<std::string> scopes;
2137 while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
2138 const auto enumPos = fwdDeclsLine.find("enum __attribute__((annotate(\"");
2139 // We check if the line contains a fwd declaration of an enum
2140 if (enumPos != std::string::npos) {
2141 // We clear the scopes which we may have carried from a previous iteration
2142 scopes.clear();
2143 // We check if the enum is not in a scope. If yes, save its name
2144 // and the names of the enclosing scopes.
2145 if (enumPos != 0) {
2146 // it's enclosed in namespaces. We need to understand what they are
2147 auto nsPos = fwdDeclsLine.find("namespace");
2148 R__ASSERT(nsPos < enumPos && "Inconsistent enum and enclosing scope parsing!");
2149 while (nsPos < enumPos && nsPos != std::string::npos) {
2150 // we have a namespace, let's put it in the collection of scopes
2151 const auto nsNameStart = nsPos + 10;
2152 const auto nsNameEnd = fwdDeclsLine.find('{', nsNameStart);
2153 const auto nsName = fwdDeclsLine.substr(nsNameStart, nsNameEnd - nsNameStart);
2154 scopes.push_back(nsName);
2155 nsPos = fwdDeclsLine.find("namespace", nsNameEnd);
2156 }
2157 }
2158 clang::DeclContext* DC = 0;
2159 for (auto &&aScope: scopes) {
2160 DC = cling::utils::Lookup::Namespace(&fInterpreter->getSema(), aScope.c_str(), DC);
2161 if (!DC) {
2162 // No decl context means we have to fwd declare the enum.
2163 break;
2164 }
2165 }
2166 if (scopes.empty() || DC) {
2167 // We know the scope; let's look for the enum.
2168 size_t posEnumName = fwdDeclsLine.find("\"))) ", 32);
2169 R__ASSERT(posEnumName != std::string::npos && "Inconsistent enum fwd decl!");
2170 posEnumName += 5; // skip "\"))) "
2171 while (isspace(fwdDeclsLine[posEnumName]))
2172 ++posEnumName;
2173 size_t posEnumNameEnd = fwdDeclsLine.find(" : ", posEnumName);
2174 R__ASSERT(posEnumNameEnd != std::string::npos && "Inconsistent enum fwd decl (end)!");
2175 while (isspace(fwdDeclsLine[posEnumNameEnd]))
2176 --posEnumNameEnd;
2177 // posEnumNameEnd now points to the last character of the name.
2178
2179 std::string enumName = fwdDeclsLine.substr(posEnumName,
2180 posEnumNameEnd - posEnumName + 1);
2181
2182 if (clang::NamedDecl* enumDecl
2183 = cling::utils::Lookup::Named(&fInterpreter->getSema(),
2184 enumName.c_str(), DC)) {
2185 // We have an existing enum decl (forward or definition);
2186 // skip this.
2187 R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) && "not an enum decl!");
2188 (void)enumDecl;
2189 continue;
2190 }
2191 }
2192 }
2193
2194 fwdDeclsCodeLessEnums += fwdDeclsLine + "\n";
2195 }
2196 }
2197
2198 if (!fwdDeclsCodeLessEnums.empty()){ // Avoid the overhead if nothing is to be declared
2199 auto compRes = fInterpreter->declare(fwdDeclsCodeLessEnums, &T);
2200 assert(cling::Interpreter::kSuccess == compRes &&
2201 "The forward declarations could not be compiled");
2202 if (compRes!=cling::Interpreter::kSuccess){
2203 Warning("TCling::RegisterModule",
2204 "Problems in compiling forward declarations for module %s: '%s'",
2205 modulename, fwdDeclsCodeLessEnums.c_str()) ;
2206 }
2207 else if (T){
2208 // Loop over all decls in the transaction and go through them all
2209 // to mark them properly.
2210 // In order to do that, we first iterate over all the DelayedCallInfos
2211 // within the transaction. Then we loop over all Decls in the DeclGroupRef
2212 // contained in the DelayedCallInfos. For each decl, we traverse.
2213 ExtLexicalStorageAdder elsa;
2214 for (auto dciIt = T->decls_begin();dciIt!=T->decls_end();dciIt++){
2215 cling::Transaction::DelayCallInfo& dci = *dciIt;
2216 for(auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
2217 clang::Decl* declPtr = *dit;
2218 elsa.TraverseDecl(declPtr);
2219 }
2220 }
2221 }
2222 }
2223
2224 // Now we register all the headers necessary for the class
2225 // Typical format of the array:
2226 // {"A", "classes.h", "@",
2227 // "vector<A>", "vector", "@",
2228 // "myClass", payloadCode, "@",
2229 // nullptr};
2230
2231 std::string temp;
2232 for (const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
2233 temp=*classesHeader;
2234
2235 size_t theTemplateHash = 0;
2236 bool addTemplate = false;
2237 size_t posTemplate = temp.find('<');
2238 if (posTemplate != std::string::npos) {
2239 // Add an entry for the template itself.
2240 std::string templateName = temp.substr(0, posTemplate);
2241 theTemplateHash = fStringHashFunction(templateName);
2242 addTemplate = true;
2243 }
2244 size_t theHash = fStringHashFunction(temp);
2245 classesHeader++;
2246 for (const char** classesHeader_inner = classesHeader; 0!=strcmp(*classesHeader_inner,"@"); ++classesHeader_inner,++classesHeader){
2247 // This is done in order to distinguish headers from files and from the payloadCode
2248 if (payloadCode == *classesHeader_inner ){
2249 fPayloads.insert(theHash);
2250 if (addTemplate) fPayloads.insert(theTemplateHash);
2251 }
2252 if (gDebug > 2)
2253 Info("TCling::RegisterModule",
2254 "Adding a header for %s", temp.c_str());
2255 fClassesHeadersMap[theHash].push_back(*classesHeader_inner);
2256 if (addTemplate) {
2257 if (fClassesHeadersMap.find(theTemplateHash) == fClassesHeadersMap.end()) {
2258 fClassesHeadersMap[theTemplateHash].push_back(*classesHeader_inner);
2259 }
2260 addTemplate = false;
2261 }
2262 }
2263 }
2264 }
2265
2266 clang::Sema &TheSema = fInterpreter->getSema();
2267
2268 bool ModuleWasSuccessfullyLoaded = false;
2269 if (hasCxxModule) {
2270 std::string ModuleName = modulename;
2271 if (llvm::StringRef(modulename).startswith("lib"))
2272 ModuleName = llvm::StringRef(modulename).substr(3).str();
2273
2274 // In case we are directly loading the library via gSystem->Load() without
2275 // specifying the relevant include paths we should try loading the
2276 // modulemap next to the library location.
2277 clang::Preprocessor &PP = TheSema.getPreprocessor();
2278 std::string ModuleMapName;
2279 if (isACLiC)
2280 ModuleMapName = ModuleName + ".modulemap";
2281 else
2282 ModuleMapName = "module.modulemap";
2283 RegisterPrebuiltModulePath(llvm::sys::path::parent_path(dyLibName),
2284 ModuleMapName);
2285
2286 // FIXME: We should only complain for modules which we know to exist. For example, we should not complain about
2287 // modules such as GenVector32 because it needs to fall back to GenVector.
2288 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2289 ModuleWasSuccessfullyLoaded = LoadModule(ModuleName, *fInterpreter);
2290 if (!ModuleWasSuccessfullyLoaded) {
2291 // Only report if we found the module in the modulemap.
2292 clang::HeaderSearch &headerSearch = PP.getHeaderSearchInfo();
2293 clang::ModuleMap &moduleMap = headerSearch.getModuleMap();
2294 if (moduleMap.findModule(ModuleName))
2295 Info("TCling::RegisterModule", "Module %s in modulemap failed to load.", ModuleName.c_str());
2296 }
2297 }
2298
2299 if (gIgnoredPCMNames.find(modulename) == gIgnoredPCMNames.end()) {
2300 llvm::SmallString<256> pcmFileNameFullPath(dyLibName);
2301 // The path dyLibName might not be absolute. This can happen if dyLibName
2302 // is linked to an executable in the same folder.
2303 llvm::sys::fs::make_absolute(pcmFileNameFullPath);
2304 llvm::sys::path::remove_filename(pcmFileNameFullPath);
2305 llvm::sys::path::append(pcmFileNameFullPath,
2307 LoadPCM(pcmFileNameFullPath.str().str());
2308 }
2309
2310 { // scope within which diagnostics are de-activated
2311 // For now we disable diagnostics because we saw them already at
2312 // dictionary generation time. That won't be an issue with the PCMs.
2313
2314 clangDiagSuppr diagSuppr(TheSema.getDiagnostics());
2315
2316#if defined(R__MUST_REVISIT)
2317#if R__MUST_REVISIT(6,2)
2318 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
2319#endif
2320#endif
2321
2322 if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand){
2323 SuspendAutoParsing autoParseRaii(this);
2324
2325 const cling::Transaction* watermark = fInterpreter->getLastTransaction();
2326 cling::Interpreter::CompilationResult compRes = fInterpreter->parseForModule(code.Data());
2327 if (isACLiC) {
2328 // Register an unload point.
2329 fMetaProcessor->registerUnloadPoint(watermark, headers[0]);
2330 }
2331
2332 assert(cling::Interpreter::kSuccess == compRes &&
2333 "Payload code of a dictionary could not be parsed correctly.");
2334 if (compRes!=cling::Interpreter::kSuccess) {
2335 Warning("TCling::RegisterModule",
2336 "Problems declaring payload for module %s.", modulename) ;
2337 }
2338 }
2339 }
2340
2341 // Now that all the header have been registered/compiled, let's
2342 // make sure to 'reset' the TClass that have a class init in this module
2343 // but already had their type information available (using information/header
2344 // loaded from other modules or from class rules or from opening a TFile
2345 // or from loading header in a way that did not provoke the loading of
2346 // the library we just loaded).
2348
2349 if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand) {
2350 // __ROOTCLING__ might be pulled in through PCH
2351 fInterpreter->declare("#ifdef __ROOTCLING__\n"
2352 "#undef __ROOTCLING__\n"
2353 + gInterpreterClassDef +
2354 "#endif");
2355 }
2356
2357 if (wasDlopened) {
2358 assert(isSharedLib);
2359 void* dyLibHandle = fRegisterModuleDyLibs.back();
2360 fRegisterModuleDyLibs.pop_back();
2361 dlclose(dyLibHandle);
2362 }
2363}
2364
2366 clang::CompilerInstance& CI = *GetInterpreterImpl()->getCI();
2367 ASTContext &C = CI.getASTContext();
2368
2369 // Do not do anything if we have no global module index.
2370 // FIXME: This is mostly to real with false positives in the TTabCom
2371 // interface for non-modules.
2372 if (!fCxxModulesEnabled)
2373 return;
2374
2375 if (IdentifierInfoLookup *External = C.Idents.getExternalIdentifierLookup()) {
2376 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
2377 for (llvm::StringRef Ident = Iter->Next(); !Ident.empty(); Ident = Iter->Next()) {
2378 std::string I = Ident.str();
2379 if (!Idents.Contains(I.data()))
2380 Idents.Add(new TObjString(I.c_str()));
2381 }
2382 }
2383}
2384
2385
2386////////////////////////////////////////////////////////////////////////////////
2387/// Register classes that already existed prior to their dictionary loading
2388/// and that already had a ClassInfo (and thus would not be refresh via
2389/// UpdateClassInfo.
2390
2392{
2393 fClassesToUpdate.push_back(std::make_pair(oldcl,dict));
2394}
2395
2396////////////////////////////////////////////////////////////////////////////////
2397/// If the dictionary is loaded, we can remove the class from the list
2398/// (otherwise the class might be loaded twice).
2399
2401{
2402 typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
2403 iterator stop = fClassesToUpdate.end();
2404 for(iterator i = fClassesToUpdate.begin();
2405 i != stop;
2406 ++i)
2407 {
2408 if ( i->first == oldcl ) {
2409 fClassesToUpdate.erase(i);
2410 return;
2411 }
2412 }
2413}
2414
2415
2416////////////////////////////////////////////////////////////////////////////////
2417/// Let cling process a command line.
2418///
2419/// If the command is executed and the error is 0, then the return value
2420/// is the int value corresponding to the result of the executed command
2421/// (float and double return values will be truncated).
2422///
2423
2424// Method for handling the interpreter exceptions.
2425// the MetaProcessor is passing in as argument to teh function, because
2426// cling::Interpreter::CompilationResult is a nested class and it cannot be
2427// forward declared, thus this method cannot be a static member function
2428// of TCling.
2429
2430static int HandleInterpreterException(cling::MetaProcessor* metaProcessor,
2431 const char* input_line,
2432 cling::Interpreter::CompilationResult& compRes,
2433 cling::Value* result)
2434{
2435 try {
2436 return metaProcessor->process(input_line, compRes, result);
2437 }
2438 catch (cling::InterpreterException& ex)
2439 {
2440 Error("HandleInterpreterException", "%s.\n%s", ex.what(), "Execution of your code was aborted.");
2441 ex.diagnose();
2442 compRes = cling::Interpreter::kFailure;
2443 }
2444 return 0;
2445}
2446
2447////////////////////////////////////////////////////////////////////////////////
2448
2449bool TCling::DiagnoseIfInterpreterException(const std::exception &e) const
2450{
2451 if (auto ie = dynamic_cast<const cling::InterpreterException*>(&e)) {
2452 ie->diagnose();
2453 return true;
2454 }
2455 return false;
2456}
2457
2458////////////////////////////////////////////////////////////////////////////////
2459
2461{
2462 // Copy the passed line, it comes from a static buffer in TApplication
2463 // which can be reentered through the Cling evaluation routines,
2464 // which would overwrite the static buffer and we would forget what we
2465 // were doing.
2466 //
2467 TString sLine(line);
2468 if (strstr(line,fantomline)) {
2469 // End-Of-Line action
2470 // See the comment (copied from above):
2471 // It is a "fantom" method to synchronize user keyboard input
2472 // and ROOT prompt line (for WIN32)
2473 // and is implemented by
2474 if (gApplication) {
2475 if (gApplication->IsCmdThread()) {
2477 gROOT->SetLineIsProcessing();
2478
2480
2481 gROOT->SetLineHasBeenProcessed();
2482 }
2483 }
2484 return 0;
2485 }
2486
2488 gGlobalMutex->Lock();
2489 if (!gInterpreterMutex)
2492 }
2494 gROOT->SetLineIsProcessing();
2495
2496 struct InterpreterFlagsRAII {
2497 cling::Interpreter* fInterpreter;
2498 bool fWasDynamicLookupEnabled;
2499
2500 InterpreterFlagsRAII(cling::Interpreter* interp):
2501 fInterpreter(interp),
2502 fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
2503 {
2504 fInterpreter->enableDynamicLookup(true);
2505 }
2506 ~InterpreterFlagsRAII() {
2507 fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
2508 gROOT->SetLineHasBeenProcessed();
2509 }
2510 } interpreterFlagsRAII(GetInterpreterImpl());
2511
2512 // A non-zero returned value means the given line was
2513 // not a complete statement.
2514 int indent = 0;
2515 // This will hold the resulting value of the evaluation the given line.
2516 cling::Value result;
2517 cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
2518 if (!strncmp(sLine.Data(), ".L", 2) || !strncmp(sLine.Data(), ".x", 2) ||
2519 !strncmp(sLine.Data(), ".X", 2)) {
2520 // If there was a trailing "+", then CINT compiled the code above,
2521 // and we will need to strip the "+" before passing the line to cling.
2522 TString mod_line(sLine);
2523 TString aclicMode;
2524 TString arguments;
2525 TString io;
2526 TString fname = gSystem->SplitAclicMode(sLine.Data() + 3,
2527 aclicMode, arguments, io);
2528 if (aclicMode.Length()) {
2529 // Remove the leading '+'
2530 R__ASSERT(aclicMode[0]=='+' && "ACLiC mode must start with a +");
2531 aclicMode[0]='k'; // We always want to keep the .so around.
2532 if (aclicMode[1]=='+') {
2533 // We have a 2nd +
2534 aclicMode[1]='f'; // We want to force the recompilation.
2535 }
2536 if (!gSystem->CompileMacro(fname,aclicMode)) {
2537 // ACLiC failed.
2538 compRes = cling::Interpreter::kFailure;
2539 } else {
2540 if (strncmp(sLine.Data(), ".L", 2) != 0) {
2541 // if execution was requested.
2542
2543 if (arguments.Length()==0) {
2544 arguments = "()";
2545 }
2546 // We need to remove the extension.
2547 Ssiz_t ext = fname.Last('.');
2548 if (ext != kNPOS) {
2549 fname.Remove(ext);
2550 }
2551 const char *function = gSystem->BaseName(fname);
2552 mod_line = function + arguments + io;
2553 indent = HandleInterpreterException(GetMetaProcessorImpl(), mod_line, compRes, &result);
2554 }
2555 }
2556 } else {
2557 // not ACLiC
2558 size_t unnamedMacroOpenCurly;
2559 {
2560 std::string code;
2561 std::string codeline;
2562 // Windows requires std::ifstream::binary to properly handle
2563 // CRLF and LF line endings
2564 std::ifstream in(fname, std::ifstream::binary);
2565 while (in) {
2566 std::getline(in, codeline);
2567 code += codeline + "\n";
2568 }
2569 unnamedMacroOpenCurly
2570 = cling::utils::isUnnamedMacro(code, fInterpreter->getCI()->getLangOpts());
2571 }
2572
2573 fCurExecutingMacros.push_back(fname);
2574 if (unnamedMacroOpenCurly != std::string::npos) {
2575 compRes = fMetaProcessor->readInputFromFile(fname.Data(), &result,
2576 unnamedMacroOpenCurly);
2577 } else {
2578 // No DynLookup for .x, .L of named macros.
2579 fInterpreter->enableDynamicLookup(false);
2580 indent = HandleInterpreterException(GetMetaProcessorImpl(), mod_line, compRes, &result);
2581 }
2582 fCurExecutingMacros.pop_back();
2583 }
2584 } // .L / .X / .x
2585 else {
2586 if (0!=strncmp(sLine.Data(), ".autodict ",10) && sLine != ".autodict") {
2587 // explicitly ignore .autodict without having to support it
2588 // in cling.
2589
2590 // Turn off autoparsing if this is an include directive
2591 bool isInclusionDirective = sLine.Contains("\n#include") || sLine.BeginsWith("#include");
2592 if (isInclusionDirective) {
2593 SuspendAutoParsing autoParseRaii(this);
2594 indent = HandleInterpreterException(GetMetaProcessorImpl(), sLine, compRes, &result);
2595 } else {
2596 indent = HandleInterpreterException(GetMetaProcessorImpl(), sLine, compRes, &result);
2597 }
2598 }
2599 }
2600 if (result.isValid())
2601 RegisterTemporary(result);
2602 if (indent) {
2603 if (error)
2604 *error = kProcessing;
2605 return 0;
2606 }
2607 if (error) {
2608 switch (compRes) {
2609 case cling::Interpreter::kSuccess: *error = kNoError; break;
2610 case cling::Interpreter::kFailure: *error = kRecoverable; break;
2611 case cling::Interpreter::kMoreInputExpected: *error = kProcessing; break;
2612 }
2613 }
2614 if (compRes == cling::Interpreter::kSuccess
2615 && result.isValid()
2616 && !result.isVoid())
2617 {
2618 return result.simplisticCastAs<Longptr_t>();
2619 }
2620 return 0;
2621}
2622
2623////////////////////////////////////////////////////////////////////////////////
2624/// No-op; see TRint instead.
2625
2627{
2628}
2629
2630////////////////////////////////////////////////////////////////////////////////
2631/// \brief Add a directory to the list of directories in which the
2632/// interpreter looks for include files.
2633/// \param[in] path The path to the directory.
2634/// \note Only one path item can be specified at a time, i.e. "path1:path2" is
2635/// \b NOT supported.
2636/// \warning Only the path to the directory should be specified, without
2637/// prepending the \c -I prefix, i.e.
2638/// <tt>gCling->AddIncludePath("/path/to/my/includes")</tt>. If the
2639/// \c -I prefix is used it will be ignored.
2640void TCling::AddIncludePath(const char *path)
2641{
2643 // Favorite source of annoyance: gSystem->AddIncludePath() needs "-I",
2644 // gCling->AddIncludePath() does not! Work around that inconsistency:
2645 if (path[0] == '-' && path[1] == 'I')
2646 path += 2;
2647 TString sPath(path);
2648 gSystem->ExpandPathName(sPath);
2649 fInterpreter->AddIncludePath(sPath.Data());
2650}
2651
2652////////////////////////////////////////////////////////////////////////////////
2653/// Visit all members over members, recursing over base classes.
2654
2655void TCling::InspectMembers(TMemberInspector& insp, const void* obj,
2656 const TClass* cl, Bool_t isTransient)
2657{
2661 }
2662
2663 if (!cl || cl->GetCollectionProxy()) {
2664 // We do not need to investigate the content of the STL
2665 // collection, they are opaque to us (and details are
2666 // uninteresting).
2667 return;
2668 }
2669
2670 static const TClassRef clRefString("std::string");
2671 if (clRefString == cl) {
2672 // We stream std::string without going through members..
2673 return;
2674 }
2675
2676 if (TClassEdit::IsStdArray(cl->GetName())) {
2677 // We treat std arrays as C arrays
2678 return;
2679 }
2680
2681 const char* cobj = (const char*) obj; // for ptr arithmetics
2682
2683 // Treat the case of std::complex in a special manner. We want to enforce
2684 // the layout of a stl implementation independent class, which is the
2685 // complex as implemented in ROOT5.
2686
2687 // A simple lambda to simplify the code
2688 auto inspInspect = [&] (ptrdiff_t offset){
2689 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_real", cobj, isTransient);
2690 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_imag", cobj + offset, isTransient);
2691 };
2692
2693 auto complexType = TClassEdit::GetComplexType(cl->GetName());
2694 switch(complexType) {
2696 {
2697 break;
2698 }
2700 {
2701 inspInspect(sizeof(float));
2702 return;
2703 }
2705 {
2706 inspInspect(sizeof(double));
2707 return;
2708 }
2710 {
2711 inspInspect(sizeof(int));
2712 return;
2713 }
2715 {
2716 inspInspect(sizeof(long));
2717 return;
2718 }
2719 }
2720
2721 static clang::PrintingPolicy
2722 printPol(fInterpreter->getCI()->getLangOpts());
2723 if (printPol.Indentation) {
2724 // not yet initialized
2725 printPol.Indentation = 0;
2726 printPol.SuppressInitializers = true;
2727 }
2728
2729 const char* clname = cl->GetName();
2730 // Printf("Inspecting class %s\n", clname);
2731
2732 const clang::ASTContext& astContext = fInterpreter->getCI()->getASTContext();
2733 const clang::Decl *scopeDecl = 0;
2734 const clang::Type *recordType = 0;
2735
2736 if (cl->GetClassInfo()) {
2737 TClingClassInfo * clingCI = (TClingClassInfo *)cl->GetClassInfo();
2738 scopeDecl = clingCI->GetDecl();
2739 recordType = clingCI->GetType();
2740 } else {
2741 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
2742 // Diags will complain about private classes:
2743 scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2744 &recordType);
2745 }
2746 if (!scopeDecl) {
2747 Error("InspectMembers", "Cannot find Decl for class %s", clname);
2748 return;
2749 }
2750 const clang::CXXRecordDecl* recordDecl
2751 = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2752 if (!recordDecl) {
2753 Error("InspectMembers", "Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2754 return;
2755 }
2756
2757 {
2758 // Force possible deserializations first. We need to have no pending
2759 // Transaction when passing control flow to the inspector below (ROOT-7779).
2760 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2761
2762 astContext.getASTRecordLayout(recordDecl);
2763
2764 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2765 eField = recordDecl->field_end(); iField != eField; ++iField) {}
2766 }
2767
2768 const clang::ASTRecordLayout& recLayout
2769 = astContext.getASTRecordLayout(recordDecl);
2770
2771 // TVirtualCollectionProxy *proxy = cl->GetCollectionProxy();
2772 // if (proxy && ( proxy->GetProperties() & TVirtualCollectionProxy::kIsEmulated ) ) {
2773 // Error("InspectMembers","The TClass for %s has an emulated proxy but we are looking at a compiled version of the collection!\n",
2774 // cl->GetName());
2775 // }
2776 if (cl->Size() != recLayout.getSize().getQuantity()) {
2777 Error("InspectMembers","TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2778 cl->GetName(),cl->Size(),(Long64_t)recLayout.getSize().getQuantity());
2779 }
2780
2781 unsigned iNField = 0;
2782 // iterate over fields
2783 // FieldDecls are non-static, else it would be a VarDecl.
2784 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2785 eField = recordDecl->field_end(); iField != eField;
2786 ++iField, ++iNField) {
2787
2788
2789 clang::QualType memberQT = iField->getType();
2790 if (recordType) {
2791 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2792 memberQT = ROOT::TMetaUtils::ReSubstTemplateArg(memberQT, recordType);
2793 }
2794 memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2795 if (memberQT.isNull()) {
2796 std::string memberName;
2797 llvm::raw_string_ostream stream(memberName);
2798 // Don't trigger fopen of the source file to count lines:
2799 printPol.AnonymousTagLocations = false;
2800 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2801 stream.flush();
2802 Error("InspectMembers",
2803 "Cannot retrieve QualType for member %s while inspecting class %s",
2804 memberName.c_str(), clname);
2805 continue; // skip member
2806 }
2807 const clang::Type* memType = memberQT.getTypePtr();
2808 if (!memType) {
2809 std::string memberName;
2810 llvm::raw_string_ostream stream(memberName);
2811 // Don't trigger fopen of the source file to count lines:
2812 printPol.AnonymousTagLocations = false;
2813 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2814 stream.flush();
2815 Error("InspectMembers",
2816 "Cannot retrieve Type for member %s while inspecting class %s",
2817 memberName.c_str(), clname);
2818 continue; // skip member
2819 }
2820
2821 const clang::Type* memNonPtrType = memType;
2822 Bool_t ispointer = false;
2823 if (memNonPtrType->isPointerType()) {
2824 ispointer = true;
2825 clang::QualType ptrQT
2826 = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2827 if (recordType) {
2828 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2829 ptrQT = ROOT::TMetaUtils::ReSubstTemplateArg(ptrQT, recordType);
2830 }
2831 ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2832 if (ptrQT.isNull()) {
2833 std::string memberName;
2834 llvm::raw_string_ostream stream(memberName);
2835 // Don't trigger fopen of the source file to count lines:
2836 printPol.AnonymousTagLocations = false;
2837 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2838 stream.flush();
2839 Error("InspectMembers",
2840 "Cannot retrieve pointee Type for member %s while inspecting class %s",
2841 memberName.c_str(), clname);
2842 continue; // skip member
2843 }
2844 memNonPtrType = ptrQT.getTypePtr();
2845 }
2846
2847 // assemble array size(s): "[12][4][]"
2848 llvm::SmallString<8> arraySize;
2849 const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2850 unsigned arrLevel = 0;
2851 bool haveErrorDueToArray = false;
2852 while (arrType) {
2853 ++arrLevel;
2854 arraySize += '[';
2855 const clang::ConstantArrayType* constArrType =
2856 clang::dyn_cast<clang::ConstantArrayType>(arrType);
2857 if (constArrType) {
2858 constArrType->getSize().toStringUnsigned(arraySize);
2859 }
2860 arraySize += ']';
2861 clang::QualType subArrQT = arrType->getElementType();
2862 if (subArrQT.isNull()) {
2863 std::string memberName;
2864 llvm::raw_string_ostream stream(memberName);
2865 // Don't trigger fopen of the source file to count lines:
2866 printPol.AnonymousTagLocations = false;
2867 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2868 stream.flush();
2869 Error("InspectMembers",
2870 "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2871 arrLevel, subArrQT.getAsString(printPol).c_str(),
2872 memberName.c_str(), clname);
2873 haveErrorDueToArray = true;
2874 break;
2875 }
2876 arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2877 }
2878 if (haveErrorDueToArray) {
2879 continue; // skip member
2880 }
2881
2882 // construct member name
2883 std::string fieldName;
2884 if (memType->isPointerType()) {
2885 fieldName = "*";
2886 }
2887
2888 // Check if this field has a custom ioname, if not, just use the one of the decl
2889 std::string ioname(iField->getName());
2891 fieldName += ioname;
2892 fieldName += arraySize;
2893
2894 // get member offset
2895 // NOTE currently we do not support bitfield and do not support
2896 // member that are not aligned on 'bit' boundaries.
2897 clang::CharUnits offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2898 ptrdiff_t fieldOffset = offset.getQuantity();
2899
2900 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fBits[2]", fBits);
2901 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fName", &fName);
2902 // R__insp.InspectMember(fName, "fName.");
2903 // R__insp.Inspect(R__cl, R__insp.GetParent(), "*fClass", &fClass);
2904
2905 // If the class has a custom streamer and the type of the filed is a
2906 // private enum, struct or class, skip it.
2907 if (!insp.IsTreatingNonAccessibleTypes()){
2908 auto iFiledQtype = iField->getType();
2909 if (auto tagDecl = iFiledQtype->getAsTagDecl()){
2910 auto declAccess = tagDecl->getAccess();
2911 if (declAccess == AS_private || declAccess == AS_protected) {
2912 continue;
2913 }
2914 }
2915 }
2916
2917 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
2918
2919 if (!ispointer) {
2920 const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
2921 if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
2922 // nested objects get an extra call to InspectMember
2923 // R__insp.InspectMember("FileStat_t", (void*)&fFileStat, "fFileStat.", false);
2924 std::string sFieldRecName;
2925 if (!ROOT::TMetaUtils::ExtractAttrPropertyFromName(*fieldRecDecl,"iotype",sFieldRecName)){
2927 clang::QualType(memNonPtrType,0),
2928 *fInterpreter,
2930 }
2931
2932 TDataMember* mbr = cl->GetDataMember(ioname.c_str());
2933 // if we can not find the member (which should not really happen),
2934 // let's consider it transient.
2935 Bool_t transient = isTransient || !mbr || !mbr->IsPersistent();
2936
2937 insp.InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
2938 (fieldName + '.').c_str(), transient);
2939
2940 }
2941 }
2942 } // loop over fields
2943
2944 // inspect bases
2945 // TNamed::ShowMembers(R__insp);
2946 unsigned iNBase = 0;
2947 for (clang::CXXRecordDecl::base_class_const_iterator iBase
2948 = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
2949 iBase != eBase; ++iBase, ++iNBase) {
2950 clang::QualType baseQT = iBase->getType();
2951 if (baseQT.isNull()) {
2952 Error("InspectMembers",
2953 "Cannot find QualType for base number %d while inspecting class %s",
2954 iNBase, clname);
2955 continue;
2956 }
2957 const clang::CXXRecordDecl* baseDecl
2958 = baseQT->getAsCXXRecordDecl();
2959 if (!baseDecl) {
2960 Error("InspectMembers",
2961 "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
2962 iNBase, clname);
2963 continue;
2964 }
2965 TClass* baseCl=nullptr;
2966 std::string sBaseName;
2967 // Try with the DeclId
2968 std::vector<TClass*> foundClasses;
2969 TClass::GetClass(static_cast<DeclId_t>(baseDecl), foundClasses);
2970 if (foundClasses.size()==1){
2971 baseCl=foundClasses[0];
2972 } else {
2973 // Try with the normalised Name, as a fallback
2974 if (!baseCl){
2976 baseQT,
2977 *fInterpreter,
2979 baseCl = TClass::GetClass(sBaseName.c_str());
2980 }
2981 }
2982
2983 if (!baseCl){
2984 std::string qualNameForDiag;
2985 ROOT::TMetaUtils::GetQualifiedName(qualNameForDiag, *baseDecl);
2986 Error("InspectMembers",
2987 "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
2988 continue;
2989 }
2990
2991 int64_t baseOffset;
2992 if (iBase->isVirtual()) {
2994 if (!isTransient) {
2995 Error("InspectMembers",
2996 "Base %s of class %s is virtual but no object provided",
2997 sBaseName.c_str(), clname);
2998 }
3000 } else {
3001 // We have an object to determine the vbase offset.
3003 TClingClassInfo* baseCi = (TClingClassInfo*)baseCl->GetClassInfo();
3004 if (ci && baseCi) {
3005 baseOffset = ci->GetBaseOffset(baseCi, const_cast<void*>(obj),
3006 true /*isDerivedObj*/);
3007 if (baseOffset == -1) {
3008 Error("InspectMembers",
3009 "Error calculating offset of virtual base %s of class %s",
3010 sBaseName.c_str(), clname);
3011 }
3012 } else {
3013 Error("InspectMembers",
3014 "Cannot calculate offset of virtual base %s of class %s",
3015 sBaseName.c_str(), clname);
3016 continue;
3017 }
3018 }
3019 } else {
3020 baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
3021 }
3022 // TOFIX: baseCl can be null here!
3023 if (baseCl->IsLoaded()) {
3024 // For loaded class, CallShowMember will (especially for TObject)
3025 // call the virtual ShowMember rather than the class specific version
3026 // resulting in an infinite recursion.
3027 InspectMembers(insp, cobj + baseOffset, baseCl, isTransient);
3028 } else {
3029 baseCl->CallShowMembers(cobj + baseOffset,
3030 insp, isTransient);
3031 }
3032 } // loop over bases
3033}
3034
3035////////////////////////////////////////////////////////////////////////////////
3036/// Reset the interpreter internal state in case a previous action was not correctly
3037/// terminated.
3038
3040{
3041 // No-op there is not equivalent state (to be cleared) in Cling.
3042}
3043
3044////////////////////////////////////////////////////////////////////////////////
3045/// Delete existing temporary values.
3046
3048{
3049 // No-op for cling due to cling::Value.
3050}
3051
3052////////////////////////////////////////////////////////////////////////////////
3053/// Declare code to the interpreter, without any of the interpreter actions
3054/// that could trigger a re-interpretation of the code. I.e. make cling
3055/// behave like a compiler: no dynamic lookup, no input wrapping for
3056/// subsequent execution, no automatic provision of declarations but just a
3057/// plain #include.
3058/// Returns true on success, false on failure.
3059
3060bool TCling::Declare(const char* code)
3061{
3063
3064 SuspendAutoLoadingRAII autoLoadOff(this);
3065 SuspendAutoParsing autoParseRaii(this);
3066
3067 bool oldDynLookup = fInterpreter->isDynamicLookupEnabled();
3068 fInterpreter->enableDynamicLookup(false);
3069 bool oldRawInput = fInterpreter->isRawInputEnabled();
3070 fInterpreter->enableRawInput(true);
3071
3072 Bool_t ret = LoadText(code);
3073
3074 fInterpreter->enableRawInput(oldRawInput);
3075 fInterpreter->enableDynamicLookup(oldDynLookup);
3076 return ret;
3077}
3078
3079////////////////////////////////////////////////////////////////////////////////
3080/// It calls a "fantom" method to synchronize user keyboard input
3081/// and ROOT prompt line.
3082
3084{
3086}
3087
3088// This static function is a hop of TCling::IsLibraryLoaded, which is taking a lock and calling
3089// into this function. This is because we wanted to avoid a duplication in TCling::IsLoaded, which
3090// was already taking a lock.
3091static Bool_t s_IsLibraryLoaded(const char* libname, cling::Interpreter* fInterpreter)
3092{
3093 // Check shared library.
3094 TString tLibName(libname);
3095 if (gSystem->FindDynamicLibrary(tLibName, kTRUE))
3096 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.Data());
3097 return false;
3098}
3099
3100Bool_t TCling::IsLibraryLoaded(const char* libname) const
3101{
3103 return s_IsLibraryLoaded(libname, GetInterpreterImpl());
3104}
3105
3106////////////////////////////////////////////////////////////////////////////////
3107/// Return true if ROOT has cxxmodules pcm for a given library name.
3108// FIXME: We need to be able to support lazy loading of pcm generated by ACLiC.
3109Bool_t TCling::HasPCMForLibrary(const char *libname) const
3110{
3111 llvm::StringRef ModuleName(libname);
3112 ModuleName = llvm::sys::path::stem(ModuleName);
3113 ModuleName.consume_front("lib");
3114
3115 // FIXME: In case when the modulemap is not yet loaded we will return the
3116 // wrong result. Consider a call to HasPCMForLibrary(../test/libEvent.so)
3117 // We will only load the modulemap for libEvent.so after we dlopen libEvent
3118 // which may happen after calling this interface. Maybe we should also check
3119 // if there is a Event.pcm file and a module.modulemap, load it and return
3120 // true.
3121 clang::ModuleMap &moduleMap = fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
3122 clang::Module *M = moduleMap.findModule(ModuleName);
3123 return M && !M->IsMissingRequirement && M->getASTFile();
3124}
3125
3126////////////////////////////////////////////////////////////////////////////////
3127/// Return true if the file has already been loaded by cint.
3128/// We will try in this order:
3129/// actual filename
3130/// filename as a path relative to
3131/// the include path
3132/// the shared library path
3133
3134Bool_t TCling::IsLoaded(const char* filename) const
3135{
3137
3138 //FIXME: if we use llvm::sys::fs::make_absolute all this can go away. See
3139 // cling::DynamicLibraryManager.
3140
3141 std::string file_name = filename;
3142 size_t at = std::string::npos;
3143 while ((at = file_name.find("/./")) != std::string::npos)
3144 file_name.replace(at, 3, "/");
3145
3146 std::string filesStr = "";
3147 llvm::raw_string_ostream filesOS(filesStr);
3148 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3149 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3150 filesOS.flush();
3151
3152 llvm::SmallVector<llvm::StringRef, 100> files;
3153 llvm::StringRef(filesStr).split(files, "\n");
3154
3155 std::set<std::string> fileMap;
3156 // Fill fileMap; return early on exact match.
3157 for (llvm::SmallVector<llvm::StringRef, 100>::const_iterator
3158 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3159 if ((*iF) == file_name.c_str()) return kTRUE; // exact match
3160 fileMap.insert(*iF);
3161 }
3162
3163 if (fileMap.empty()) return kFALSE;
3164
3165 // Check MacroPath.
3166 TString sFilename(file_name.c_str());
3168 && fileMap.count(sFilename.Data())) {
3169 return kTRUE;
3170 }
3171
3172 // Check IncludePath.
3173 TString incPath = gSystem->GetIncludePath(); // of the form -Idir1 -Idir2 -Idir3
3174 incPath.Append(":").Prepend(" "); // to match " -I" (note leading ' ')
3175 incPath.ReplaceAll(" -I", ":"); // of form :dir1 :dir2:dir3
3176 while (incPath.Index(" :") != -1) {
3177 incPath.ReplaceAll(" :", ":");
3178 }
3179 incPath.Prepend(".:");
3180 sFilename = file_name.c_str();
3181 if (gSystem->FindFile(incPath, sFilename, kReadPermission)
3182 && fileMap.count(sFilename.Data())) {
3183 return kTRUE;
3184 }
3185
3186 // Check shared library.
3187 if (s_IsLibraryLoaded(file_name.c_str(), GetInterpreterImpl()))
3188 return kTRUE;
3189
3190 //FIXME: We must use the cling::Interpreter::lookupFileOrLibrary iface.
3191 const clang::DirectoryLookup *CurDir = 0;
3192 clang::Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
3193 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3194 const clang::FileEntry *FE = HS.LookupFile(file_name.c_str(),
3195 clang::SourceLocation(),
3196 /*isAngled*/ false,
3197 /*FromDir*/ 0, CurDir,
3198 clang::ArrayRef<std::pair<const clang::FileEntry *,
3199 const clang::DirectoryEntry *>>(),
3200 /*SearchPath*/ 0,
3201 /*RelativePath*/ 0,
3202 /*RequestingModule*/ 0,
3203 /*SuggestedModule*/ 0,
3204 /*IsMapped*/ 0,
3205 /*IsFrameworkFound*/ nullptr,
3206 /*SkipCache*/ false,
3207 /*BuildSystemModule*/ false,
3208 /*OpenFile*/ false,
3209 /*CacheFail*/ false);
3210 if (FE && FE->isValid()) {
3211 // check in the source manager if the file is actually loaded
3212 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3213 // this works only with header (and source) files...
3214 clang::FileID FID = SM.translateFile(FE);
3215 if (!FID.isInvalid() && FID.getHashValue() == 0)
3216 return kFALSE;
3217 else {
3218 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3219 if (SLocE.isFile() && SLocE.getFile().getContentCache()->getRawBuffer() == 0)
3220 return kFALSE;
3221 if (!FID.isInvalid())
3222 return kTRUE;
3223 }
3224 // ...then check shared library again, but with full path now
3225 sFilename = FE->getName();
3226 if (gSystem->FindDynamicLibrary(sFilename, kTRUE)
3227 && fileMap.count(sFilename.Data())) {
3228 return kTRUE;
3229 }
3230 }
3231 return kFALSE;
3232}
3233
3234
3235#if defined(R__MACOSX)
3236
3237////////////////////////////////////////////////////////////////////////////////
3238/// Check if lib is in the dynamic linker cache, returns true if it is, and if so,
3239/// modifies the library file name parameter `lib` from `/usr/lib/libFOO.dylib`
3240/// to `-lFOO` such that it can be passed to the linker.
3241/// This is a unique feature of macOS 11.
3242
3243static bool R__UpdateLibFileForLinking(TString &lib)
3244{
3245 const char *mapfile = nullptr;
3246#if __x86_64__
3247 mapfile = "/System/Library/dyld/dyld_shared_cache_x86_64.map";
3248#elif __arm64__
3249 mapfile = "/System/Library/dyld/dyld_shared_cache_arm64e.map";
3250#else
3251 #error unsupported architecture
3252#endif
3253 if (std::ifstream cacheMap{mapfile}) {
3254 std::string line;
3255 while (getline(cacheMap, line)) {
3256 if (line.find(lib) != std::string::npos) {
3257 lib.ReplaceAll("/usr/lib/lib","-l");
3258 lib.ReplaceAll(".dylib","");
3259 return true;
3260 }
3261 }
3262 return false;
3263 }
3264 return false;
3265}
3266#endif // R__MACOSX
3267
3268#ifdef R__LINUX
3269
3270////////////////////////////////////////////////////////////////////////////////
3271/// Callback for dl_iterate_phdr(), see `man dl_iterate_phdr`.
3272/// Collects opened libraries.
3273
3274static int callback_for_dl_iterate_phdr(struct dl_phdr_info *info, size_t size, void *data)
3275{
3276 // This function is called through UpdateListOfLoadedSharedLibraries() which is locked.
3277 static std::unordered_set<decltype(info->dlpi_addr)> sKnownLoadedLibBaseAddrs;
3278
3279 auto newLibs = static_cast<std::vector<std::string>*>(data);
3280 if (!sKnownLoadedLibBaseAddrs.count(info->dlpi_addr)) {
3281 // Skip \0, "", and kernel pseudo-libs linux-vdso.so.1 or linux-gate.so.1
3282 if (info->dlpi_name && info->dlpi_name[0]
3283 && strncmp(info->dlpi_name, "linux-vdso.so", 13)
3284 && strncmp(info->dlpi_name, "linux-vdso32.so", 15)
3285 && strncmp(info->dlpi_name, "linux-vdso64.so", 15)
3286 && strncmp(info->dlpi_name, "linux-gate.so", 13))
3287 newLibs->emplace_back(info->dlpi_name);
3288 sKnownLoadedLibBaseAddrs.insert(info->dlpi_addr);
3289 }
3290 // No matter what the doc says, return != 0 means "stop the iteration".
3291 return 0;
3292}
3293
3294#endif // R__LINUX
3295
3296
3297////////////////////////////////////////////////////////////////////////////////
3298
3300{
3301#if defined(R__WIN32) || defined(__CYGWIN__)
3302 HMODULE hModules[1024];
3303 void *hProcess;
3304 unsigned long cbModules;
3305 unsigned int i;
3306 hProcess = (void *)::GetCurrentProcess();
3307 ::EnumProcessModules(hProcess, hModules, sizeof(hModules), &cbModules);
3308 // start at 1 to skip the executable itself
3309 for (i = 1; i < (cbModules / sizeof(void *)); i++) {
3310 static const int bufsize = 260;
3311 wchar_t winname[bufsize];
3312 char posixname[bufsize];
3313 ::GetModuleFileNameExW(hProcess, hModules[i], winname, bufsize);
3314#if defined(__CYGWIN__)
3315 cygwin_conv_path(CCP_WIN_W_TO_POSIX, winname, posixname, bufsize);
3316#else
3317 std::wstring wpath = winname;
3318 std::replace(wpath.begin(), wpath.end(), '\\', '/');
3319 string path(wpath.begin(), wpath.end());
3320 strncpy(posixname, path.c_str(), bufsize);
3321#endif
3322 if (!fSharedLibs.Contains(posixname)) {
3323 RegisterLoadedSharedLibrary(posixname);
3324 }
3325 }
3326#elif defined(R__MACOSX)
3327 // fPrevLoadedDynLibInfo stores the *next* image index to look at
3328 uint32_t imageIndex = (uint32_t) (size_t) fPrevLoadedDynLibInfo;
3329
3330 while (const mach_header* mh = _dyld_get_image_header(imageIndex)) {
3331 // Skip non-dylibs
3332 if (mh->filetype == MH_DYLIB) {
3333 if (const char* imageName = _dyld_get_image_name(imageIndex)) {
3334 RegisterLoadedSharedLibrary(imageName);
3335 }
3336 }
3337
3338 ++imageIndex;
3339 }
3340 fPrevLoadedDynLibInfo = (void*)(size_t)imageIndex;
3341#elif defined(R__LINUX)
3342 // fPrevLoadedDynLibInfo is unused on Linux.
3344
3345 std::vector<std::string> newLibs;
3346 dl_iterate_phdr(callback_for_dl_iterate_phdr, &newLibs);
3347 for (auto &&lib: newLibs)
3348 RegisterLoadedSharedLibrary(lib.c_str());
3349#else
3350 Error("TCling::UpdateListOfLoadedSharedLibraries",
3351 "Platform not supported!");
3352#endif
3353}
3354
3355////////////////////////////////////////////////////////////////////////////////
3356/// Register a new shared library name with the interpreter; add it to
3357/// fSharedLibs.
3358
3359void TCling::RegisterLoadedSharedLibrary(const char* filename)
3360{
3361 // Ignore NULL filenames, aka "the process".
3362 if (!filename) return;
3363
3364 // Tell the interpreter that this library is available; all libraries can be
3365 // used to resolve symbols.
3366 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3367 if (!DLM->isLibraryLoaded(filename)) {
3368 DLM->loadLibrary(filename, true /*permanent*/, true /*resolved*/);
3369 }
3370
3371#if defined(R__MACOSX)
3372 // Check that this is not a system library
3373 auto lenFilename = strlen(filename);
3374 if (!strncmp(filename, "/usr/lib/system/", 16)
3375 || !strncmp(filename, "/usr/lib/libc++", 15)
3376 || !strncmp(filename, "/System/Library/Frameworks/", 27)
3377 || !strncmp(filename, "/System/Library/PrivateFrameworks/", 34)
3378 || !strncmp(filename, "/System/Library/CoreServices/", 29)
3379 || !strcmp(filename, "cl_kernels") // yepp, no directory
3380 || strstr(filename, "/usr/lib/libSystem")
3381 || strstr(filename, "/usr/lib/libstdc++")
3382 || strstr(filename, "/usr/lib/libicucore")
3383 || strstr(filename, "/usr/lib/libbsm")
3384 || strstr(filename, "/usr/lib/libobjc")
3385 || strstr(filename, "/usr/lib/libresolv")
3386 || strstr(filename, "/usr/lib/libauto")
3387 || strstr(filename, "/usr/lib/libcups")
3388 || strstr(filename, "/usr/lib/libDiagnosticMessagesClient")
3389 || strstr(filename, "/usr/lib/liblangid")
3390 || strstr(filename, "/usr/lib/libCRFSuite")
3391 || strstr(filename, "/usr/lib/libpam")
3392 || strstr(filename, "/usr/lib/libOpenScriptingUtil")
3393 || strstr(filename, "/usr/lib/libextension")
3394 || strstr(filename, "/usr/lib/libAudioToolboxUtility")
3395 || strstr(filename, "/usr/lib/liboah")
3396 || strstr(filename, "/usr/lib/libRosetta")
3397 || strstr(filename, "/usr/lib/libCoreEntitlements")
3398 // These are candidates for suppression, too:
3399 // -lfakelink -lapple_nghttp2 -lnetwork -lsqlite3 -lenergytrace -lCoreEntitlements
3400 // -lMobileGestalt -lcoretls -lcoretls_cfhelpers -lxar.1 -lcompression -larchive.2
3401 // -lxml2.2 -lpcap.A -ldns_services -llzma.5 -lbz2.1.0 -liconv.2 -lcharset.1
3402 // -lCheckFix -lmecabra -lmecab -lgermantok -lThaiTokenizer -lChineseTokenizer
3403 // -lcmph -lutil -lapp_launch_measurement -lxslt.1 -lspindump -late -lexpat.1
3404 // -lAudioStatistics -lSMC -lperfcheck -lmis -lIOReport -lheimdal-asn1
3405
3406 // "cannot link directly with dylib/framework, your binary is not an allowed client of
3407 // /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/
3408 // SDKs/MacOSX.sdk/usr/lib/libAudioToolboxUtility.tbd for architecture x86_64
3409 || (lenFilename > 4 && !strcmp(filename + lenFilename - 4, ".tbd")))
3410 return;
3411 TString sFileName(filename);
3412 R__UpdateLibFileForLinking(sFileName);
3413 filename = sFileName.Data();
3414#elif defined(__CYGWIN__)
3415 // Check that this is not a system library
3416 static const int bufsize = 260;
3417 char posixwindir[bufsize];
3418 char *windir = getenv("WINDIR");
3419 if (windir)
3420 cygwin_conv_path(CCP_WIN_A_TO_POSIX, windir, posixwindir, bufsize);
3421 else
3422 snprintf(posixwindir, sizeof(posixwindir), "/Windows/");
3423 if (strstr(filename, posixwindir) ||
3424 strstr(filename, "/usr/bin/cyg"))
3425 return;
3426#elif defined(R__WIN32)
3427 if (strstr(filename, "/Windows/"))
3428 return;
3429#elif defined (R__LINUX)
3430 if (strstr(filename, "/ld-linux")
3431 || strstr(filename, "linux-gnu/")
3432 || strstr(filename, "/libstdc++.")
3433 || strstr(filename, "/libgcc")
3434 || strstr(filename, "/libc.")
3435 || strstr(filename, "/libdl.")
3436 || strstr(filename, "/libm."))
3437 return;
3438#endif
3439 // Update string of available libraries.
3440 if (!fSharedLibs.IsNull()) {
3441 fSharedLibs.Append(" ");
3442 }
3443 fSharedLibs.Append(filename);
3444}
3445
3446////////////////////////////////////////////////////////////////////////////////
3447/// Load a library file in cling's memory.
3448/// if 'system' is true, the library is never unloaded.
3449/// Return 0 on success, -1 on failure.
3450
3451Int_t TCling::Load(const char* filename, Bool_t system)
3452{
3453 assert(!IsFromRootCling() && "Trying to load library from rootcling!");
3454
3455 // Used to return 0 on success, 1 on duplicate, -1 on failure, -2 on "fatal".
3457 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3458 std::string canonLib = DLM->lookupLibrary(filename);
3459 cling::DynamicLibraryManager::LoadLibResult res
3460 = cling::DynamicLibraryManager::kLoadLibNotFound;
3461 if (!canonLib.empty()) {
3462 if (system)
3463 res = DLM->loadLibrary(filename, system, true);
3464 else {
3465 // For the non system libs, we'd like to be able to unload them.
3466 // FIXME: Here we lose the information about kLoadLibAlreadyLoaded case.
3467 cling::Interpreter::CompilationResult compRes;
3468 HandleInterpreterException(GetMetaProcessorImpl(), Form(".L %s", canonLib.c_str()), compRes, /*cling::Value*/0);
3469 if (compRes == cling::Interpreter::kSuccess)
3470 res = cling::DynamicLibraryManager::kLoadLibSuccess;
3471 }
3472 }
3473
3474 if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3476 }
3477 switch (res) {
3478 case cling::DynamicLibraryManager::kLoadLibSuccess: return 0;
3479 case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded: return 1;
3480 default: break;
3481 };
3482 return -1;
3483}
3484
3485////////////////////////////////////////////////////////////////////////////////
3486/// Load a macro file in cling's memory.
3487
3488void TCling::LoadMacro(const char* filename, EErrorCode* error)
3489{
3490 ProcessLine(Form(".L %s", filename), error);
3491}
3492
3493////////////////////////////////////////////////////////////////////////////////
3494/// Let cling process a command line asynch.
3495
3497{
3498 return ProcessLine(line, error);
3499}
3500
3501////////////////////////////////////////////////////////////////////////////////
3502/// Let cling process a command line synchronously, i.e we are waiting
3503/// it will be finished.
3504
3506{
3508 if (gApplication) {
3509 if (gApplication->IsCmdThread()) {
3510 return ProcessLine(line, error);
3511 }
3512 return 0;
3513 }
3514 return ProcessLine(line, error);
3515}
3516
3517////////////////////////////////////////////////////////////////////////////////
3518/// Directly execute an executable statement (e.g. "func()", "3+5", etc.
3519/// however not declarations, like "Int_t x;").
3520
3522{
3523#ifdef R__WIN32
3524 // Test on ApplicationImp not being 0 is needed because only at end of
3525 // TApplication ctor the IsLineProcessing flag is set to 0, so before
3526 // we can not use it.
3528 while (gROOT->IsLineProcessing() && !gApplication) {
3529 Warning("Calc", "waiting for cling thread to free");
3530 gSystem->Sleep(500);
3531 }
3532 gROOT->SetLineIsProcessing();
3533 }
3534#endif // R__WIN32
3536 if (error) {
3537 *error = TInterpreter::kNoError;
3538 }
3539 cling::Value valRef;
3540 cling::Interpreter::CompilationResult cr = cling::Interpreter::kFailure;
3541 try {
3542 cr = fInterpreter->evaluate(line, valRef);
3543 }
3544 catch (cling::InterpreterException& ex)
3545 {
3546 Error("Calc", "%s.\n%s", ex.what(), "Evaluation of your expression was aborted.");
3547 ex.diagnose();
3548 cr = cling::Interpreter::kFailure;
3549 }
3550
3551 if (cr != cling::Interpreter::kSuccess) {
3552 // Failure in compilation.
3553 if (error) {
3554 // Note: Yes these codes are weird.
3556 }
3557 return 0L;
3558 }
3559 if (!valRef.isValid()) {
3560 // Failure at runtime.
3561 if (error) {
3562 // Note: Yes these codes are weird.
3563 *error = TInterpreter::kDangerous;
3564 }
3565 return 0L;
3566 }
3567
3568 if (valRef.isVoid()) {
3569 return 0;
3570 }
3571
3572 RegisterTemporary(valRef);
3573#ifdef R__WIN32
3575 gROOT->SetLineHasBeenProcessed();
3576 }
3577#endif // R__WIN32
3578 return valRef.simplisticCastAs<Longptr_t>();
3579}
3580
3581////////////////////////////////////////////////////////////////////////////////
3582/// Set a getline function to call when input is needed.
3583
3584void TCling::SetGetline(const char * (*getlineFunc)(const char* prompt),
3585 void (*histaddFunc)(const char* line))
3586{
3587 // If cling offers a replacement for G__pause(), it would need to
3588 // also offer a way to customize at least the history recording.
3589
3590#if defined(R__MUST_REVISIT)
3591#if R__MUST_REVISIT(6,2)
3592 Warning("SetGetline","Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3593#endif
3594#endif
3595}
3596
3597////////////////////////////////////////////////////////////////////////////////
3598/// Helper function to increase the internal Cling count of transactions
3599/// that change the AST.
3600
3601Bool_t TCling::HandleNewTransaction(const cling::Transaction &T)
3602{
3604
3605 if ((std::distance(T.decls_begin(), T.decls_end()) != 1)
3606 || T.deserialized_decls_begin() != T.deserialized_decls_end()
3607 || T.macros_begin() != T.macros_end()
3608 || ((!T.getFirstDecl().isNull()) && ((*T.getFirstDecl().begin()) != T.getWrapperFD()))) {
3610 return true;
3611 }
3612 return false;
3613}
3614
3615////////////////////////////////////////////////////////////////////////////////
3616/// Delete object from cling symbol table so it can not be used anymore.
3617/// cling objects are always on the heap.
3618
3620{
3621 // NOTE: When replacing the mutex by a ReadWrite mutex, we **must**
3622 // put in place the Read/Write part here. Keeping the write lock
3623 // here is 'catasptrophic' for scaling as it means that ALL calls
3624 // to RecursiveRemove will take the write lock and performance
3625 // of many threads trying to access the write lock at the same
3626 // time is relatively bad.
3628 // Note that fgSetOfSpecials is supposed to be updated by TClingCallbacks::tryFindROOTSpecialInternal
3629 // (but isn't at the moment).
3630 if (obj->IsOnHeap() && fgSetOfSpecials && !((std::set<TObject*>*)fgSetOfSpecials)->empty()) {
3631 std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)fgSetOfSpecials)->find(obj);
3632 if (iSpecial != ((std::set<TObject*>*)fgSetOfSpecials)->end()) {
3634 DeleteGlobal(obj);
3635 ((std::set<TObject*>*)fgSetOfSpecials)->erase(iSpecial);
3636 }
3637 }
3638}
3639
3640////////////////////////////////////////////////////////////////////////////////
3641/// Pressing Ctrl+C should forward here. In the case where we have had
3642/// continuation requested we must reset it.
3643
3645{
3646 fMetaProcessor->cancelContinuation();
3647 // Reset the Cling state to the state saved by the last call to
3648 // TCling::SaveContext().
3649#if defined(R__MUST_REVISIT)
3650#if R__MUST_REVISIT(6,2)
3652 Warning("Reset","Cling should support the equivalent of scratch_upto(&fDictPos)");
3653#endif
3654#endif
3655}
3656
3657////////////////////////////////////////////////////////////////////////////////
3658/// Reset the Cling state to its initial state.
3659
3661{
3662#if defined(R__MUST_REVISIT)
3663#if R__MUST_REVISIT(6,2)
3665 Warning("ResetAll","Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3666#endif
3667#endif
3668}
3669
3670////////////////////////////////////////////////////////////////////////////////
3671/// Reset in Cling the list of global variables to the state saved by the last
3672/// call to TCling::SaveGlobalsContext().
3673///
3674/// Note: Right now, all we do is run the global destructors.
3675
3677{
3679 // TODO:
3680 // Here we should iterate over the transactions (N-3) and revert.
3681 // N-3 because the first three internal to cling.
3682
3683 fInterpreter->runAndRemoveStaticDestructors();
3684}
3685
3686////////////////////////////////////////////////////////////////////////////////
3687/// Reset the Cling 'user' global objects/variables state to the state saved by the last
3688/// call to TCling::SaveGlobalsContext().
3689
3691{
3692#if defined(R__MUST_REVISIT)
3693#if R__MUST_REVISIT(6,2)
3695 Warning("ResetGlobalVar","Cling should support the equivalent of resetglobalvar(obj)");
3696#endif
3697#endif
3698}
3699
3700////////////////////////////////////////////////////////////////////////////////
3701/// Rewind Cling dictionary to the point where it was before executing
3702/// the current macro. This function is typically called after SEGV or
3703/// ctlr-C after doing a longjmp back to the prompt.
3704
3706{
3707#if defined(R__MUST_REVISIT)
3708#if R__MUST_REVISIT(6,2)
3710 Warning("RewindDictionary","Cling should provide a way to revert transaction similar to rewinddictionary()");
3711#endif
3712#endif
3713}
3714
3715////////////////////////////////////////////////////////////////////////////////
3716/// Delete obj from Cling symbol table so it cannot be accessed anymore.
3717/// Returns 1 in case of success and 0 in case object was not in table.
3718
3720{
3721#if defined(R__MUST_REVISIT)
3722#if R__MUST_REVISIT(6,2)
3724 Warning("DeleteGlobal","Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3725#endif
3726#endif
3727 return 0;
3728}
3729
3730////////////////////////////////////////////////////////////////////////////////
3731/// Undeclare obj called name.
3732/// Returns 1 in case of success, 0 for failure.
3733
3735{
3736#if defined(R__MUST_REVISIT)
3737#if R__MUST_REVISIT(6,2)
3738 Warning("DeleteVariable","should do more that just reseting the value to zero");
3739#endif
3740#endif
3741
3743 llvm::StringRef srName(name);
3744 const char* unscopedName = name;
3745 llvm::StringRef::size_type posScope = srName.rfind("::");
3746 const clang::DeclContext* declCtx = 0;
3747 if (posScope != llvm::StringRef::npos) {
3748 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3749 const clang::Decl* scopeDecl
3750 = lh.findScope(srName.substr(0, posScope),
3751 cling::LookupHelper::WithDiagnostics);
3752 if (!scopeDecl) {
3753 Error("DeleteVariable", "Cannot find enclosing scope for variable %s",
3754 name);
3755 return 0;
3756 }
3757 declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3758 if (!declCtx) {
3759 Error("DeleteVariable",
3760 "Enclosing scope for variable %s is not a declaration context",
3761 name);
3762 return 0;
3763 }
3764 unscopedName += posScope + 2;
3765 }
3766 // Could trigger deserialization of decls.
3767 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
3768 clang::NamedDecl* nVarDecl
3769 = cling::utils::Lookup::Named(&fInterpreter->getSema(), unscopedName, declCtx);
3770 if (!nVarDecl) {
3771 Error("DeleteVariable", "Unknown variable %s", name);
3772 return 0;
3773 }
3774 clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3775 if (!varDecl) {
3776 Error("DeleteVariable", "Entity %s is not a variable", name);
3777 return 0;
3778 }
3779
3780 clang::QualType qType = varDecl->getType();
3781 const clang::Type* type = qType->getUnqualifiedDesugaredType();
3782 // Cannot set a reference's address to nullptr; the JIT can place it
3783 // into read-only memory (ROOT-7100).
3784 if (type->isPointerType()) {
3785 int** ppInt = (int**)fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3786 // set pointer to invalid.
3787 if (ppInt) *ppInt = 0;
3788 }
3789 return 1;
3790}
3791
3792////////////////////////////////////////////////////////////////////////////////
3793/// Save the current Cling state.
3794
3796{
3797#if defined(R__MUST_REVISIT)
3798#if R__MUST_REVISIT(6,2)
3800 Warning("SaveContext","Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3801#endif
3802#endif
3803}
3804
3805////////////////////////////////////////////////////////////////////////////////
3806/// Save the current Cling state of global objects.
3807
3809{
3810#if defined(R__MUST_REVISIT)
3811#if R__MUST_REVISIT(6,2)
3813 Warning("SaveGlobalsContext","Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3814#endif
3815#endif
3816}
3817
3818////////////////////////////////////////////////////////////////////////////////
3819/// No op: see TClingCallbacks (used to update the list of globals)
3820
3822{
3823}
3824
3825////////////////////////////////////////////////////////////////////////////////
3826/// No op: see TClingCallbacks (used to update the list of global functions)
3827
3829{
3830}
3831
3832////////////////////////////////////////////////////////////////////////////////
3833/// No op: see TClingCallbacks (used to update the list of types)
3834
3836{
3837}
3838
3839////////////////////////////////////////////////////////////////////////////////
3840/// Check in what order the member of a tuple are layout.
3841enum class ETupleOrdering {
3842 kAscending,
3845};
3846
3848{
3851};
3852
3854{
3857};
3858
3860{
3861 std::tuple<int,double> value;
3864
3865 size_t offset0 = ((char*)&(std::get<0>(value))) - ((char*)&value);
3866 size_t offset1 = ((char*)&(std::get<1>(value))) - ((char*)&value);
3867
3868 size_t ascOffset0 = ((char*)&(asc._0)) - ((char*)&asc);
3869 size_t ascOffset1 = ((char*)&(asc._1)) - ((char*)&asc);
3870
3871 size_t desOffset0 = ((char*)&(des._0)) - ((char*)&des);
3872 size_t desOffset1 = ((char*)&(des._1)) - ((char*)&des);
3873
3874 if (offset0 == ascOffset0 && offset1 == ascOffset1) {
3876 } else if (offset0 == desOffset0 && offset1 == desOffset1) {
3878 } else {
3880 }
3881}
3882
3883static std::string AlternateTuple(const char *classname, const cling::LookupHelper& lh)
3884{
3885 TClassEdit::TSplitType tupleContent(classname);
3886 std::string alternateName = "TEmulatedTuple";
3887 alternateName.append( classname + 5 );
3888
3889 std::string fullname = "ROOT::Internal::" + alternateName;
3890 if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
3891 /*resultType*/nullptr, /* intantiateTemplate= */ false))
3892 return fullname;
3893
3894 std::string guard_name;
3895 ROOT::TMetaUtils::GetCppName(guard_name,alternateName.c_str());
3896 std::ostringstream guard;
3897 guard << "ROOT_INTERNAL_TEmulated_";
3898 guard << guard_name;
3899
3900 std::ostringstream alternateTuple;
3901 alternateTuple << "#ifndef " << guard.str() << "\n";
3902 alternateTuple << "#define " << guard.str() << "\n";
3903 alternateTuple << "namespace ROOT { namespace Internal {\n";
3904 alternateTuple << "template <class... Types> struct TEmulatedTuple;\n";
3905 alternateTuple << "template <> struct " << alternateName << " {\n";
3906
3907 // This could also be a compile time choice ...
3908 switch(IsTupleAscending()) {
3910 unsigned int nMember = 0;
3911 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple)
3912 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
3913 while (iter != theEnd) {
3914 alternateTuple << " " << *iter << " _" << nMember << ";\n";
3915 ++iter;
3916 ++nMember;
3917 }
3918 break;
3919 }
3921 unsigned int nMember = tupleContent.fElements.size() - 3;
3922 auto iter = tupleContent.fElements.rbegin() + 1; // Skip the template name (tuple)
3923 auto theEnd = tupleContent.fElements.rend() - 1; // skip the 'stars'.
3924 while (iter != theEnd) {
3925 alternateTuple << " " << *iter << " _" << nMember << ";\n";
3926 ++iter;
3927 --nMember;
3928 }
3929 break;
3930 }
3932 Fatal("TCling::SetClassInfo::AlternateTuple",
3933 "Layout of std::tuple on this platform is unexpected.");
3934 break;
3935 }
3936 }
3937
3938 alternateTuple << "};\n";
3939 alternateTuple << "}}\n";
3940 alternateTuple << "#endif\n";
3941 if (!gCling->Declare(alternateTuple.str().c_str())) {
3942 Error("Load","Could not declare %s",alternateName.c_str());
3943 return "";
3944 }
3945 alternateName = "ROOT::Internal::" + alternateName;
3946 return alternateName;
3947}
3948
3949////////////////////////////////////////////////////////////////////////////////
3950/// Set pointer to the TClingClassInfo in TClass.
3951/// If 'reload' is true, (attempt to) generate a new ClassInfo even if we
3952/// already have one.
3953
3955{
3956 // We are shutting down, there is no point in reloading, it only triggers
3957 // redundant deserializations.
3958 if (fIsShuttingDown) {
3959 // Remove the decl_id from the DeclIdToTClass map
3960 if (cl->fClassInfo) {
3962 TClingClassInfo* TClinginfo = (TClingClassInfo*) cl->fClassInfo;
3963 // Test again as another thread may have set fClassInfo to nullptr.
3964 if (TClinginfo) {
3965 TClass::RemoveClassDeclId(TClinginfo->GetDeclId());
3966 }
3967 delete TClinginfo;
3968 cl->fClassInfo = nullptr;
3969 }
3970 return;
3971 }
3972
3974 if (cl->fClassInfo && !reload) {
3975 return;
3976 }
3977 //Remove the decl_id from the DeclIdToTClass map
3978 TClingClassInfo* TClinginfo = (TClingClassInfo*) cl->fClassInfo;
3979 if (TClinginfo) {
3980 TClass::RemoveClassDeclId(TClinginfo->GetDeclId());
3981 }
3982 delete TClinginfo;
3983 cl->fClassInfo = 0;
3984 std::string name(cl->GetName());
3985
3986 // Handle the special case of 'tuple' where we ignore the real implementation
3987 // details and just overlay a 'simpler'/'simplistic' version that is easy
3988 // for the I/O to understand and handle.
3989 if (strncmp(cl->GetName(),"tuple<",strlen("tuple<"))==0) {
3990
3991 name = AlternateTuple(cl->GetName(), fInterpreter->getLookupHelper());
3992
3993 }
3994
3995 bool instantiateTemplate = !cl->TestBit(TClass::kUnloading);
3996 // FIXME: Rather than adding an option to the TClingClassInfo, we should consider combining code
3997 // that is currently in the caller (like SetUnloaded) that disable AutoLoading and AutoParsing and
3998 // code is in the callee (disabling template instantiation) and end up with a more explicit class:
3999 // TClingClassInfoReadOnly.
4000 TClingClassInfo* info = new TClingClassInfo(GetInterpreterImpl(), name.c_str(), instantiateTemplate);
4001 if (!info->IsValid()) {
4002 if (cl->fState != TClass::kHasTClassInit) {
4003 if (cl->fStreamerInfo->GetEntries() != 0) {
4005 } else {
4007 }
4008 }
4009 delete info;
4010 return;
4011 }
4012 cl->fClassInfo = (ClassInfo_t*)info; // Note: We are transferring ownership here.
4013 // In case a class contains an external enum, the enum will be seen as a
4014 // class. We must detect this special case and make the class a Zombie.
4015 // Here we assume that a class has at least one method.
4016 // We can NOT call TClass::Property from here, because this method
4017 // assumes that the TClass is well formed to do a lot of information
4018 // caching. The method SetClassInfo (i.e. here) is usually called during
4019 // the building phase of the TClass, hence it is NOT well formed yet.
4020 Bool_t zombieCandidate = kFALSE;
4021 if (
4022 info->IsValid() &&
4023 !(info->Property() & (kIsClass | kIsStruct | kIsNamespace))
4024 ) {
4025 zombieCandidate = kTRUE;
4026 }
4027 if (!info->IsLoaded()) {
4028 if (info->Property() & (kIsNamespace)) {
4029 // Namespaces can have info but no corresponding CINT dictionary
4030 // because they are auto-created if one of their contained
4031 // classes has a dictionary.
4032 zombieCandidate = kTRUE;
4033 }
4034 // this happens when no dictionary is available
4035 delete info;
4036 cl->fClassInfo = 0;
4037 }
4038 if (zombieCandidate && !cl->GetCollectionType()) {
4039 cl->MakeZombie();
4040 }
4041 // If we reach here, the info was valid (See early returns).
4042 if (cl->fState != TClass::kHasTClassInit) {
4043 if (cl->fClassInfo) {
4046 } else {
4047// if (TClassEdit::IsSTLCont(cl->GetName()) {
4048// There will be an emulated collection proxy, is that the same?
4049// cl->fState = TClass::kEmulated;
4050// } else {
4051 if (cl->fStreamerInfo->GetEntries() != 0) {
4053 } else {
4055 }
4056// }
4057 }
4058 }
4059 if (cl->fClassInfo) {
4060 TClass::AddClassToDeclIdMap(((TClingClassInfo*)cl->fClassInfo)->GetDeclId(), cl);
4061 }
4062}
4063
4064////////////////////////////////////////////////////////////////////////////////
4065/// Checks if an entity with the specified name is defined in Cling.
4066/// Returns kUnknown if the entity is not defined.
4067/// Returns kWithClassDefInline if the entity exists and has a ClassDefInline
4068/// Returns kKnown if the entity is defined.
4069///
4070/// By default, structs, namespaces, classes, enums and unions are looked for.
4071/// If the flag isClassOrNamespaceOnly is true, classes, structs and
4072/// namespaces only are considered. I.e. if the name is an enum or a union,
4073/// the returned value is false.
4074///
4075/// In the case where the class is not loaded and belongs to a namespace
4076/// or is nested, looking for the full class name is outputting a lots of
4077/// (expected) error messages. Currently the only way to avoid this is to
4078/// specifically check that each level of nesting is already loaded.
4079/// In case of templates the idea is that everything between the outer
4080/// '<' and '>' has to be skipped, e.g.: aap<pippo<noot>::klaas>::a_class
4081
4083TCling::CheckClassInfo(const char *name, Bool_t autoload, Bool_t isClassOrNamespaceOnly /* = kFALSE*/)
4084{
4086 static const char *anonEnum = "anonymous enum ";
4087 static const int cmplen = strlen(anonEnum);
4088
4089 if (fIsShuttingDown || 0 == strncmp(name, anonEnum, cmplen)) {
4090 return kUnknown;
4091 }
4092
4093 // Do not turn on the AutoLoading if it is globally off.
4094 autoload = autoload && IsClassAutoLoadingEnabled();
4095
4096 // Avoid the double search below in case the name is a fundamental type
4097 // or typedef to a fundamental type.
4098 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
4099 TDataType *fundType = (TDataType *)typeTable->THashTable::FindObject( name );
4100
4101 if (fundType && fundType->GetType() < TVirtualStreamerInfo::kObject
4102 && fundType->GetType() > 0) {
4103 // Fundamental type, no a class.
4104 return kUnknown;
4105 }
4106
4107 // Migrated from within TClass::GetClass
4108 // If we want to know if a class or a namespace with this name exists in the
4109 // interpreter and this is an enum in the type system, before or after loading
4110 // according to the autoload function argument, return kUnknown.
4111 if (isClassOrNamespaceOnly && TEnum::GetEnum(name, autoload ? TEnum::kAutoload : TEnum::kNone))
4112 return kUnknown;
4113
4114 const char *classname = name;
4115
4116 // RAII to suspend and restore auto-loading and auto-parsing based on some external conditions.
4117 class MaybeSuspendAutoLoadParse {
4118 int fStoreAutoLoad = 0;
4119 int fStoreAutoParse = 0;
4120 bool fSuspendedAutoParse = false;
4121 public:
4122 MaybeSuspendAutoLoadParse(int autoload) {
4123 fStoreAutoLoad = ((TCling*)gCling)->SetClassAutoLoading(autoload);
4124 }
4125
4126 void SuspendAutoParsing() {
4127 fSuspendedAutoParse = true;
4128 fStoreAutoParse = ((TCling*)gCling)->SetSuspendAutoParsing(true);
4129 }
4130
4131 ~MaybeSuspendAutoLoadParse() {
4132 if (fSuspendedAutoParse)
4133 ((TCling*)gCling)->SetSuspendAutoParsing(fStoreAutoParse);
4134 ((TCling*)gCling)->SetClassAutoLoading(fStoreAutoLoad);
4135 }
4136 };
4137
4138 MaybeSuspendAutoLoadParse autoLoadParseRAII( autoload );
4139 if (TClassEdit::IsStdPair(classname) || TClassEdit::IsStdPairBase(classname))
4140 autoLoadParseRAII.SuspendAutoParsing();
4141
4142 // First we want to check whether the decl exist, but _without_
4143 // generating any template instantiation. However, the lookup
4144 // still will create a forward declaration of the class template instance
4145 // if it exist. In this case, the return value of findScope will still
4146 // be zero but the type will be initialized.
4147 // Note in the corresponding code in ROOT 5, CINT was not instantiating
4148 // this forward declaration.
4149 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4150 const clang::Type *type = 0;
4151 const clang::Decl *decl
4152 = lh.findScope(classname,
4153 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4154 : cling::LookupHelper::NoDiagnostics,
4155 &type, /* intantiateTemplate= */ false );
4156 if (!decl) {
4157 std::string buf = TClassEdit::InsertStd(classname);
4158 decl = lh.findScope(buf,
4159 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4160 : cling::LookupHelper::NoDiagnostics,
4161 &type,false);
4162 }
4163
4164 if (type) {
4165 // If decl==0 and the type is valid, then we have a forward declaration.
4166 if (!decl) {
4167 // If we have a forward declaration for a class template instantiation,
4168 // we want to ignore it if it was produced/induced by the call to
4169 // findScope, however we can not distinguish those from the
4170 // instantiation induce by 'soft' use (and thus also induce by the
4171 // same underlying code paths)
4172 // ['soft' use = use not requiring a complete definition]
4173 // So to reduce the amount of disruption to the existing code we
4174 // would just ignore those for STL collection, for which we really
4175 // need to have the compiled collection proxy (and thus the TClass
4176 // bootstrap).
4177 clang::ClassTemplateSpecializationDecl *tmpltDecl =
4178 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
4179 (type->getAsCXXRecordDecl());
4180 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4181 // Since the point of instantiation is invalid, we 'guess' that
4182 // the 'instantiation' of the forwarded type appended in
4183 // findscope.
4184 if (ROOT::TMetaUtils::IsSTLCont(*tmpltDecl)) {
4185 // For STL Collection we return kUnknown.
4186 return kUnknown;
4187 }
4188 }
4189 }
4191 if (!tci.IsValid()) {
4192 return kUnknown;
4193 }
4194 auto propertiesMask = isClassOrNamespaceOnly ? kIsClass | kIsStruct | kIsNamespace :
4196
4197 if (tci.Property() & propertiesMask) {
4198 bool hasClassDefInline = false;
4199 if (isClassOrNamespaceOnly) {
4200 // We do not need to check for ClassDefInline when this is called from
4201 // TClass::Init, we only do it for the call from TClass::GetClass.
4202 auto hasDictionary = tci.GetMethod("Dictionary", "", false, 0, ROOT::kExactMatch);
4203 auto implLineFunc = tci.GetMethod("ImplFileLine", "", false, 0, ROOT::kExactMatch);
4204
4205 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4206 int lineNumber = 0;
4207 bool success = false;
4208 std::tie(success, lineNumber) =
4209 ROOT::TMetaUtils::GetTrivialIntegralReturnValue(implLineFunc.GetAsFunctionDecl(), *fInterpreter);
4210 hasClassDefInline = success && (lineNumber == -1);
4211 }
4212 }
4213
4214 // fprintf(stderr,"CheckClassInfo: %s had dict=%d inline=%d\n",name,hasDictionary.IsValid()
4215 // , hasClassDefInline);
4216
4217 // We are now sure that the entry is not in fact an autoload entry.
4218 if (hasClassDefInline)
4219 return kWithClassDefInline;
4220 else
4221 return kKnown;
4222 } else {
4223 // We are now sure that the entry is not in fact an autoload entry.
4224 return kUnknown;
4225 }
4226 }
4227
4228 if (decl)
4229 return kKnown;
4230 else
4231 return kUnknown;
4232
4233 // Setting up iterator part of TClingTypedefInfo is too slow.
4234 // Copy the lookup code instead:
4235 /*
4236 TClingTypedefInfo t(fInterpreter, name);
4237 if (t.IsValid() && !(t.Property() & kIsFundamental)) {
4238 delete[] classname;
4239 return kTRUE;
4240 }
4241 */
4242
4243// const clang::Decl *decl = lh.findScope(name);
4244// if (!decl) {
4245// std::string buf = TClassEdit::InsertStd(name);
4246// decl = lh.findScope(buf);
4247// }
4248
4249// return (decl);
4250}
4251
4252////////////////////////////////////////////////////////////////////////////////
4253/// Return true if there is a class template by the given name ...
4254
4256{
4257 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4258 const clang::Decl *decl
4259 = lh.findClassTemplate(name,
4260 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4261 : cling::LookupHelper::NoDiagnostics);
4262 if (!decl) {
4263 std::string strname = "std::";
4264 strname += name;
4265 decl = lh.findClassTemplate(strname,
4266 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4267 : cling::LookupHelper::NoDiagnostics);
4268 }
4269 return 0 != decl;
4270}
4271
4272////////////////////////////////////////////////////////////////////////////////
4273/// Create list of pointers to base class(es) for TClass cl.
4274
4276{
4278 if (cl->fBase) {
4279 return;
4280 }
4282 if (!tci) return;
4284 TList *listOfBase = new TList;
4285 while (t.Next()) {
4286 // if name cannot be obtained no use to put in list
4287 if (t.IsValid() && t.Name()) {
4289 listOfBase->Add(new TBaseClass((BaseClassInfo_t *)a, cl));
4290 }
4291 }
4292 // Now that is complete, publish it.
4293 cl->fBase = listOfBase;
4294}
4295
4296////////////////////////////////////////////////////////////////////////////////
4297/// Create list of pointers to enums for TClass cl.
4298
4299void TCling::LoadEnums(TListOfEnums& enumList) const
4300{
4302
4303 const Decl * D;
4304 TClass* cl = enumList.GetClass();
4305 if (cl) {
4306 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4307 }
4308 else {
4309 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4310 }
4311 // Iterate on the decl of the class and get the enums.
4312 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4313 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4314 // Collect all contexts of the namespace.
4315 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4316 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4317 for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(), declEnd = allDeclContexts.end();
4318 declIter != declEnd; ++declIter) {
4319 // Iterate on all decls for each context.
4320 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4321 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4322 if (const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4323 // Get name of the enum type.
4324 std::string buf;
4325 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4326 llvm::raw_string_ostream stream(buf);
4327 // Don't trigger fopen of the source file to count lines:
4328 Policy.AnonymousTagLocations = false;
4329 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
4330 stream.flush();
4331 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
4332 if (!buf.empty()) {
4333 const char* name = buf.c_str();
4334 // Add the enum to the list of loaded enums.
4335 enumList.Get(ED, name);
4336 }
4337 }
4338 }
4339 }
4340 }
4341}
4342
4343////////////////////////////////////////////////////////////////////////////////
4344/// Create list of pointers to function templates for TClass cl.
4345
4347{
4349
4350 const Decl * D;
4351 TListOfFunctionTemplates* funcTempList;
4352 if (cl) {
4353 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4354 funcTempList = (TListOfFunctionTemplates*)cl->GetListOfFunctionTemplates(false);
4355 }
4356 else {
4357 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4358 funcTempList = (TListOfFunctionTemplates*)gROOT->GetListOfFunctionTemplates();
4359 }
4360 // Iterate on the decl of the class and get the enums.
4361 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4362 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4363 // Collect all contexts of the namespace.
4364 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4365 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4366 for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(),
4367 declEnd = allDeclContexts.end(); declIter != declEnd; ++declIter) {
4368 // Iterate on all decls for each context.
4369 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4370 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4371 if (const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4372 funcTempList->Get(FTD);
4373 }
4374 }
4375 }
4376 }
4377}
4378
4379////////////////////////////////////////////////////////////////////////////////
4380/// Get the scopes representing using declarations of namespace
4381
4382std::vector<std::string> TCling::GetUsingNamespaces(ClassInfo_t *cl) const
4383{
4385 return ci->GetUsingNamespaces();
4386}
4387
4388////////////////////////////////////////////////////////////////////////////////
4389/// Create list of pointers to data members for TClass cl.
4390/// This is now a nop. The creation and updating is handled in
4391/// TListOfDataMembers.
4392
4394{
4395}
4396
4397////////////////////////////////////////////////////////////////////////////////
4398/// Create list of pointers to methods for TClass cl.
4399/// This is now a nop. The creation and updating is handled in
4400/// TListOfFunctions.
4401
4403{
4404}
4405
4406////////////////////////////////////////////////////////////////////////////////
4407/// Update the list of pointers to method for TClass cl
4408/// This is now a nop. The creation and updating is handled in
4409/// TListOfFunctions.
4410
4412{
4413}
4414
4415////////////////////////////////////////////////////////////////////////////////
4416/// Update the list of pointers to data members for TClass cl
4417/// This is now a nop. The creation and updating is handled in
4418/// TListOfDataMembers.
4419
4421{
4422}
4423
4424////////////////////////////////////////////////////////////////////////////////
4425/// Create list of pointers to method arguments for TMethod m.
4426
4428{
4430 if (m->fMethodArgs) {
4431 return;
4432 }
4433 TList *arglist = new TList;
4435 while (t.Next()) {
4436 if (t.IsValid()) {
4438 arglist->Add(new TMethodArg((MethodArgInfo_t*)a, m));
4439 }
4440 }
4441 m->fMethodArgs = arglist;
4442}
4443
4444
4445////////////////////////////////////////////////////////////////////////////////
4446/// Generate a TClass for the given class.
4447/// Since the caller has already check the ClassInfo, let it give use the
4448/// result (via the value of emulation) rather than recalculate it.
4449
4450TClass *TCling::GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent /* = kFALSE */)
4451{
4452// For now the following line would lead to the (unwanted) instantiation
4453// of class template. This could/would need to be resurrected only if
4454// we re-introduce so sort of automatic instantiation. However this would
4455// have to include carefull look at the template parameter to avoid
4456// creating instance we can not really use (if the parameter are only forward
4457// declaration or do not have all the necessary interfaces).
4458
4459 // TClingClassInfo tci(fInterpreter, classname);
4460 // if (1 || !tci.IsValid()) {
4461
4462 Version_t version = 1;
4463 if (TClassEdit::IsSTLCont(classname)) {
4464 version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4465 }
4467 TClass *cl = new TClass(classname, version, silent);
4468 if (emulation) {
4470 } else {
4471 // Set the class version if the class is versioned.
4472 // Note that we cannot just call CLASS::Class_Version() as we might not have
4473 // an execution engine (when invoked from rootcling).
4474
4475 // Do not call cl->GetClassVersion(), it has side effects!
4476 Version_t oldvers = cl->fClassVersion;
4477 if (oldvers == version && cl->GetClassInfo()) {
4478 // We have a version and it might need an update.
4480 if (llvm::isa<clang::NamespaceDecl>(cli->GetDecl())) {
4481 // Namespaces don't have class versions.
4482 return cl;
4483 }
4484 TClingMethodInfo mi = cli->GetMethod("Class_Version", "", 0 /*poffset*/,
4487 if (!mi.IsValid()) {
4488 if (cl->TestBit(TClass::kIsTObject)) {
4489 Error("GenerateTClass",
4490 "Cannot find %s::Class_Version()! Class version might be wrong.",
4491 cl->GetName());
4492 }
4493 return cl;
4494 }
4495 Version_t newvers = ROOT::TMetaUtils::GetClassVersion(llvm::dyn_cast<clang::RecordDecl>(cli->GetDecl()),
4496 *fInterpreter);
4497 if (newvers == -1) {
4498 // Didn't manage to determine the class version from the AST.
4499 // Use runtime instead.
4500 if ((mi.Property() & kIsStatic)
4501 && !fInterpreter->isInSyntaxOnlyMode()) {
4502 // This better be a static function.
4504 callfunc.SetFunc(&mi);
4505 newvers = callfunc.ExecInt(0);
4506 } else {
4507 Error("GenerateTClass",
4508 "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4509 cl->GetName());
4510 }
4511 }
4512 if (newvers != oldvers) {
4513 cl->fClassVersion = newvers;
4514 cl->fStreamerInfo->Expand(newvers + 2 + 10);
4515 }
4516 }
4517 }
4518
4519 return cl;
4520
4521// } else {
4522// return GenerateTClass(&tci,silent);
4523// }
4524}
4525
4526#if 0
4527////////////////////////////////////////////////////////////////////////////////
4528
4529static void GenerateTClass_GatherInnerIncludes(cling::Interpreter *interp, TString &includes,TClingClassInfo *info)
4530{
4531 includes += info->FileName();
4532
4533 const clang::ClassTemplateSpecializationDecl *templateCl
4534 = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->GetDecl());
4535 if (templateCl) {
4536 for(unsigned int i=0; i < templateCl->getTemplateArgs().size(); ++i) {
4537 const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4538 if (arg.getKind() == clang::TemplateArgument::Type) {
4539 const clang::Type *uType = ROOT::TMetaUtils::GetUnderlyingType( arg.getAsType() );
4540
4541 if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4542 // We really need a header file.
4543 const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4544 if (argdecl) {
4545 includes += ";";
4546 TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4547 GenerateTClass_GatherInnerIncludes(interp, includes, &subinfo);
4548 } else {
4549 std::string Result;
4550 llvm::raw_string_ostream OS(Result);
4551 arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4552 Warning("TCling::GenerateTClass","Missing header file for %s",OS.str().c_str());
4553 }
4554 }
4555 }
4556 }
4557 }
4558}
4559#endif
4560
4561////////////////////////////////////////////////////////////////////////////////
4562/// Generate a TClass for the given class.
4563
4564TClass *TCling::GenerateTClass(ClassInfo_t *classinfo, Bool_t silent /* = kFALSE */)
4565{
4566 TClingClassInfo *info = (TClingClassInfo*)classinfo;
4567 if (!info || !info->IsValid()) {
4568 Fatal("GenerateTClass","Requires a valid ClassInfo object");
4569 return 0;
4570 }
4571 // We are in the case where we have AST nodes for this class.
4572 TClass *cl = 0;
4573 std::string classname;
4574 info->FullName(classname,*fNormalizedCtxt); // Could we use Name()?
4575 if (TClassEdit::IsSTLCont(classname)) {
4576#if 0
4577 Info("GenerateTClass","Will (try to) generate the compiled TClass for %s.",classname.c_str());
4578 // We need to build up the list of required headers, by
4579 // looking at each template arguments.
4580 TString includes;
4581 GenerateTClass_GatherInnerIncludes(fInterpreter,includes,info);
4582
4583 if (0 == GenerateDictionary(classname.c_str(),includes)) {
4584 // 0 means success.
4585 cl = TClass::LoadClass(classnam.c_str(), silent);
4586 if (cl == 0) {
4587 Error("GenerateTClass","Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4588 }
4589 }
4590#endif
4591 if (cl == 0) {
4592 int version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4593 cl = new TClass(classinfo, version, 0, 0, -1, -1, silent);
4595 }
4596 } else {
4597 // For regular class, just create a TClass on the fly ...
4598 // Not quite useful yet, but that what CINT used to do anyway.
4599 cl = new TClass(classinfo, 1, 0, 0, -1, -1, silent);
4600 }
4601 // Add the new TClass to the map of declid and TClass*.
4602 if (cl) {
4604 }
4605 return cl;
4606}
4607
4608////////////////////////////////////////////////////////////////////////////////
4609/// Generate the dictionary for the C++ classes listed in the first
4610/// argument (in a semi-colon separated list).
4611/// 'includes' contains a semi-colon separated list of file to
4612/// #include in the dictionary.
4613/// For example:
4614/// ~~~ {.cpp}
4615/// gInterpreter->GenerateDictionary("vector<vector<float> >;list<vector<float> >","list;vector");
4616/// ~~~
4617/// or
4618/// ~~~ {.cpp}
4619/// gInterpreter->GenerateDictionary("myclass","myclass.h;myhelper.h");
4620/// ~~~
4621
4622Int_t TCling::GenerateDictionary(const char* classes, const char* includes /* = "" */, const char* /* options = 0 */)
4623{
4624 if (classes == 0 || classes[0] == 0) {
4625 Error("TCling::GenerateDictionary", "Cannot generate dictionary without passing classes.");
4626 return 0;
4627 }
4628 // Split the input list
4629 std::vector<std::string> listClasses;
4630 for (
4631 const char* current = classes, *prev = classes;
4632 *current != 0;
4633 ++current
4634 ) {
4635 if (*current == ';') {
4636 listClasses.push_back(std::string(prev, current - prev));
4637 prev = current + 1;
4638 }
4639 else if (*(current + 1) == 0) {
4640 listClasses.push_back(std::string(prev, current + 1 - prev));
4641 prev = current + 1;
4642 }
4643 }
4644 std::vector<std::string> listIncludes;
4645 if (!includes)
4646 includes = "";
4647 for (
4648 const char* current = includes, *prev = includes;
4649 *current != 0;
4650 ++current
4651 ) {
4652 if (*current == ';') {
4653 listIncludes.push_back(std::string(prev, current - prev));
4654 prev = current + 1;
4655 }
4656 else if (*(current + 1) == 0) {
4657 listIncludes.push_back(std::string(prev, current + 1 - prev));
4658 prev = current + 1;
4659 }
4660 }
4661 // Generate the temporary dictionary file
4662 return !TCling_GenerateDictionary(listClasses, listIncludes,
4663 std::vector<std::string>(), std::vector<std::string>());
4664}
4665
4666////////////////////////////////////////////////////////////////////////////////
4667/// Return pointer to cling Decl of global/static variable that is located
4668/// at the address given by addr.
4669
4670TInterpreter::DeclId_t TCling::GetDataMember(ClassInfo_t *opaque_cl, const char *name) const
4671{
4673 DeclId_t d;
4674 TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
4675
4676 if (cl) {
4677 d = cl->GetDataMember(name);
4678 // We check if the decl of the data member has an annotation which indicates
4679 // an ioname.
4680 // In case this is true, if the name requested is not the ioname, we
4681 // return 0, as if the member did not exist. In some sense we override
4682 // the information in the TClassInfo instance, isolating the typesystem in
4683 // TClass from the one in the AST.
4684 if (const ValueDecl* decl = (const ValueDecl*) d){
4685 std::string ioName;
4686 bool hasIoName = ROOT::TMetaUtils::ExtractAttrPropertyFromName(*decl,"ioname",ioName);
4687 if (hasIoName && ioName != name) return 0;
4688 }
4689 return d;
4690 }
4691 // We are looking up for something on the TU scope.
4692 // FIXME: We do not want to go through TClingClassInfo(fInterpreter) because of redundant deserializations. That
4693 // interface will actually construct iterators and walk over the decls on the global scope. In would return the first
4694 // occurrence of a decl with the looked up name. However, that's not what C++ lookup would do: if we want to switch
4695 // to a more complete C++ lookup interface we need sift through the found names and pick up the declarations which
4696 // are only fulfilling ROOT's understanding for a Data Member.
4697 // FIXME: We should probably deprecate the TClingClassInfo(fInterpreter) interface and replace it withe something
4698 // similar as below.
4699 using namespace clang;
4700 Sema& SemaR = fInterpreter->getSema();
4701 DeclarationName DName = &SemaR.Context.Idents.get(name);
4702
4703 LookupResult R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4704 Sema::ForExternalRedeclaration);
4705
4706 // Could trigger deserialization of decls.
4707 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4708 cling::utils::Lookup::Named(&SemaR, R);
4709
4710 LookupResult::Filter F = R.makeFilter();
4711 // Filter the data-member looking decls.
4712 while (F.hasNext()) {
4713 NamedDecl *D = F.next();
4714 if (isa<VarDecl>(D) || isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) ||
4715 isa<IndirectFieldDecl>(D))
4716 continue;
4717 F.erase();
4718 }
4719 F.done();
4720
4721 if (R.isSingleResult())
4722 return R.getFoundDecl();
4723 return 0;
4724}
4725
4726////////////////////////////////////////////////////////////////////////////////
4727/// Return pointer to cling Decl of global/static variable that is located
4728/// at the address given by addr.
4729
4731{
4733
4734 const clang::Decl* possibleEnum = 0;
4735 // FInd the context of the decl.
4736 if (cl) {
4738 if (cci) {
4739 const clang::DeclContext* dc = 0;
4740 if (const clang::Decl* D = cci->GetDecl()) {
4741 if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
4742 dc = dyn_cast<clang::RecordDecl>(D);
4743 }
4744 }
4745 if (dc) {
4746 // If it is a data member enum.
4747 // Could trigger deserialization of decls.
4748 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4749 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name, dc);
4750 } else {
4751 Error("TCling::GetEnum", "DeclContext not found for %s .\n", name);
4752 }
4753 }
4754 } else {
4755 // If it is a global enum.
4756 // Could trigger deserialization of decls.
4757 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4758 possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name);
4759 }
4760 if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
4761 && isa<clang::EnumDecl>(possibleEnum)) {
4762 return possibleEnum;
4763 }
4764 return 0;
4765}
4766
4767////////////////////////////////////////////////////////////////////////////////
4768/// Return pointer to cling DeclId for a global value
4769
4770TInterpreter::DeclId_t TCling::GetDeclId( const llvm::GlobalValue *gv ) const
4771{
4772 if (!gv) return 0;
4773
4774 llvm::StringRef mangled_name = gv->getName();
4775
4776 int err = 0;
4777 char* demangled_name_c = TClassEdit::DemangleName(mangled_name.str().c_str(), err);
4778 if (err) {
4779 if (err == -2) {
4780 // It might simply be an unmangled global name.
4781 DeclId_t d;
4783 d = gcl.GetDataMember(mangled_name.str().c_str());
4784 return d;
4785 }
4786 return 0;
4787 }
4788
4789 std::string scopename(demangled_name_c);
4790 free(demangled_name_c);
4791
4792 //
4793 // Separate out the class or namespace part of the
4794 // function name.
4795 //
4796 std::string dataname;
4797
4798 if (!strncmp(scopename.c_str(), "typeinfo for ", sizeof("typeinfo for ")-1)) {
4799 scopename.erase(0, sizeof("typeinfo for ")-1);
4800 } else if (!strncmp(scopename.c_str(), "vtable for ", sizeof("vtable for ")-1)) {
4801 scopename.erase(0, sizeof("vtable for ")-1);
4802 } else {
4803 // See if it is a function
4804 std::string::size_type pos = scopename.rfind('(');
4805 if (pos != std::string::npos) {
4806 return 0;
4807 }
4808 // Separate the scope and member name
4809 pos = scopename.rfind(':');
4810 if (pos != std::string::npos) {
4811 if ((pos != 0) && (scopename[pos-1] == ':')) {
4812 dataname = scopename.substr(pos+1);
4813 scopename.erase(pos-1);
4814 }
4815 } else {
4816 scopename.clear();
4817 dataname = scopename;
4818 }
4819 }
4820 //fprintf(stderr, "name: '%s'\n", name.c_str());
4821 // Now we have the class or namespace name, so do the lookup.
4822
4823
4824 DeclId_t d;
4825 if (scopename.size()) {
4826 TClingClassInfo cl(GetInterpreterImpl(), scopename.c_str());
4827 d = cl.GetDataMember(dataname.c_str());
4828 }
4829 else {
4831 d = gcl.GetDataMember(dataname.c_str());
4832 }
4833 return d;
4834}
4835
4836////////////////////////////////////////////////////////////////////////////////
4837/// NOT IMPLEMENTED.
4838
4840{
4841 Error("GetDataMemberWithValue()", "not implemented");
4842 return 0;
4843}
4844
4845////////////////////////////////////////////////////////////////////////////////
4846/// Return pointer to cling DeclId for a data member with a given name.
4847
4849{
4850 // NOT IMPLEMENTED.
4851 Error("GetDataMemberAtAddr()", "not implemented");
4852 return 0;
4853}
4854
4855////////////////////////////////////////////////////////////////////////////////
4856/// Return the cling mangled name for a method of a class with parameters
4857/// params (params is a string of actual arguments, not formal ones). If the
4858/// class is 0 the global function list will be searched.
4859
4860TString TCling::GetMangledName(TClass* cl, const char* method,
4861 const char* params, Bool_t objectIsConst /* = kFALSE */)
4862{
4865 if (cl) {
4866 Longptr_t offset;
4867 func.SetFunc((TClingClassInfo*)cl->GetClassInfo(), method, params, objectIsConst,
4868 &offset);
4869 }
4870 else {
4872 Longptr_t offset;
4873 func.SetFunc(&gcl, method, params, &offset);
4874 }
4876 if (!mi) return "";
4877 TString mangled_name( mi->GetMangledName() );
4878 delete mi;
4879 return mangled_name;
4880}
4881
4882////////////////////////////////////////////////////////////////////////////////
4883/// Return the cling mangled name for a method of a class with a certain
4884/// prototype, i.e. "char*,int,float". If the class is 0 the global function
4885/// list will be searched.
4886
4888 const char* proto, Bool_t objectIsConst /* = kFALSE */,
4889 EFunctionMatchMode mode /* = kConversionMatch */)
4890{
4892 if (cl) {
4893 return ((TClingClassInfo*)cl->GetClassInfo())->
4894 GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetMangledName();
4895 }
4897 return gcl.GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetMangledName();
4898}
4899
4900////////////////////////////////////////////////////////////////////////////////
4901/// Return pointer to cling interface function for a method of a class with
4902/// parameters params (params is a string of actual arguments, not formal
4903/// ones). If the class is 0 the global function list will be searched.
4904
4905void* TCling::GetInterfaceMethod(TClass* cl, const char* method,
4906 const char* params, Bool_t objectIsConst /* = kFALSE */)
4907{
4910 if (cl) {
4911 Longptr_t offset;
4912 func.SetFunc((TClingClassInfo*)cl->GetClassInfo(), method, params, objectIsConst,
4913 &offset);
4914 }
4915 else {
4917 Longptr_t offset;
4918 func.SetFunc(&gcl, method, params, &offset);
4919 }
4920 return (void*) func.InterfaceMethod();
4921}
4922
4923////////////////////////////////////////////////////////////////////////////////
4924/// Return pointer to cling interface function for a method of a class with
4925/// a certain name.
4926
4927TInterpreter::DeclId_t TCling::GetFunction(ClassInfo_t *opaque_cl, const char* method)
4928{
4930 DeclId_t f;
4931 TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
4932 if (cl) {
4933 f = cl->GetMethod(method).GetDeclId();
4934 }
4935 else {
4937 f = gcl.GetMethod(method).GetDeclId();
4938 }
4939 return f;
4940
4941}
4942
4943////////////////////////////////////////////////////////////////////////////////
4944/// Insert overloads of name in cl to res.
4945
4946void TCling::GetFunctionOverloads(ClassInfo_t *cl, const char *funcname,
4947 std::vector<DeclId_t>& res) const
4948{
4949 clang::Sema& S = fInterpreter->getSema();
4950 clang::ASTContext& Ctx = S.Context;
4951 const clang::Decl* CtxDecl
4952 = cl ? (const clang::Decl*)((TClingClassInfo*)cl)->GetDeclId():
4953 Ctx.getTranslationUnitDecl();
4954 auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
4955 const clang::DeclContext* DeclCtx = RecDecl;
4956
4957 if (!DeclCtx)
4958 DeclCtx = dyn_cast<clang::NamespaceDecl>(CtxDecl);
4959 if (!DeclCtx) return;
4960
4961 clang::DeclarationName DName;
4962 // The DeclarationName is funcname, unless it's a ctor or dtor.
4963 // FIXME: or operator or conversion! See enum clang::DeclarationName::NameKind.
4964
4965 if (RecDecl) {
4966 if (RecDecl->getNameAsString() == funcname) {
4967 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
4968 DName = Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalType(QT));
4969 } else if (funcname[0] == '~' && RecDecl->getNameAsString() == funcname + 1) {
4970 clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
4971 DName = Ctx.DeclarationNames.getCXXDestructorName(Ctx.getCanonicalType(QT));
4972 } else {
4973 DName = &Ctx.Idents.get(funcname);
4974 }
4975 } else {
4976 DName = &Ctx.Idents.get(funcname);
4977 }
4978
4979 // NotForRedeclaration: we want to find names in inline namespaces etc.
4980 clang::LookupResult R(S, DName, clang::SourceLocation(),
4981 Sema::LookupOrdinaryName, clang::Sema::NotForRedeclaration);
4982 R.suppressDiagnostics(); // else lookup with NotForRedeclaration will check access etc
4983 S.LookupQualifiedName(R, const_cast<DeclContext*>(DeclCtx));
4984 if (R.empty()) return;
4985 R.resolveKind();
4986 res.reserve(res.size() + (R.end() - R.begin()));
4987 for (clang::LookupResult::iterator IR = R.begin(), ER = R.end();
4988 IR != ER; ++IR) {
4989 if (const clang::FunctionDecl* FD
4990 = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
4991 if (!FD->getDescribedFunctionTemplate()) {
4992 res.push_back(FD);
4993 }
4994 } else if (const auto *USD = llvm::dyn_cast<const clang::UsingShadowDecl>(*IR)) {
4995 // FIXME: multi-level using
4996 if (llvm::isa<clang::FunctionDecl>(USD->getTargetDecl())) {
4997 res.push_back(USD);
4998 }
4999 }
5000 }
5001}
5002
5003////////////////////////////////////////////////////////////////////////////////
5004/// Return pointer to cling interface function for a method of a class with
5005/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5006/// function list will be searched.
5007
5009 const char* proto,
5010 Bool_t objectIsConst /* = kFALSE */,
5011 EFunctionMatchMode mode /* = kConversionMatch */)
5012{
5014 void* f;
5015 if (cl) {
5016 f = ((TClingClassInfo*)cl->GetClassInfo())->
5017 GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).InterfaceMethod(*fNormalizedCtxt);
5018 }
5019 else {
5021 f = gcl.GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).InterfaceMethod(*fNormalizedCtxt);
5022 }
5023 return f;
5024}
5025
5026////////////////////////////////////////////////////////////////////////////////
5027/// Return pointer to cling DeclId for a method of a class with
5028/// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
5029/// function list will be searched.
5030
5031TInterpreter::DeclId_t TCling::GetFunctionWithValues(ClassInfo_t *opaque_cl, const char* method,
5032 const char* params,
5033 Bool_t objectIsConst /* = kFALSE */)
5034{
5036 DeclId_t f;
5037 TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
5038 if (cl) {
5039 f = cl->GetMethodWithArgs(method, params, objectIsConst, 0 /*poffset*/).GetDeclId();
5040 }
5041 else {
5043 f = gcl.GetMethod(method, params, objectIsConst, 0 /*poffset*/).GetDeclId();
5044 }
5045 return f;
5046}
5047
5048////////////////////////////////////////////////////////////////////////////////
5049/// Return pointer to cling interface function 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::GetFunctionWithPrototype(ClassInfo_t *opaque_cl, const char* method,
5054 const char* proto,
5055 Bool_t objectIsConst /* = kFALSE */,
5056 EFunctionMatchMode mode /* = kConversionMatch */)
5057{
5059 DeclId_t f;
5060 TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
5061 if (cl) {
5062 f = cl->GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetDeclId();
5063 }
5064 else {
5066 f = gcl.GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetDeclId();
5067 }
5068 return f;
5069}
5070
5071////////////////////////////////////////////////////////////////////////////////
5072/// Return pointer to cling interface function for a method of a class with
5073/// a certain name.
5074
5075TInterpreter::DeclId_t TCling::GetFunctionTemplate(ClassInfo_t *opaque_cl, const char* name)
5076{
5078 DeclId_t f;
5079 TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
5080 if (cl) {
5081 f = cl->GetFunctionTemplate(name);
5082 }
5083 else {
5085 f = gcl.GetFunctionTemplate(name);
5086 }
5087 return f;
5088
5089}
5090
5091////////////////////////////////////////////////////////////////////////////////
5092/// The 'name' is known to the interpreter, this function returns
5093/// the internal version of this name (usually just resolving typedefs)
5094/// This is used in particular to synchronize between the name used
5095/// by rootcling and by the run-time environment (TClass)
5096/// Return 0 if the name is not known.
5097
5098void TCling::GetInterpreterTypeName(const char* name, std::string &output, Bool_t full)
5099{
5100 output.clear();
5101
5103
5105 if (!cl.IsValid()) {
5106 return ;
5107 }
5108 if (full) {
5110 return;
5111 }
5112 // Well well well, for backward compatibility we need to act a bit too
5113 // much like CINT.
5116
5117 return;
5118}
5119
5120////////////////////////////////////////////////////////////////////////////////
5121/// Execute a global function with arguments params.
5122///
5123/// FIXME: The cint-based version of this code does not check if the
5124/// SetFunc() call works, and does not do any real checking
5125/// for errors from the Exec() call. It did fetch the most
5126/// recent cint security error and return that in error, but
5127/// this does not really translate well to cling/clang. We
5128/// should enhance these interfaces so that we can report
5129/// compilation and runtime errors properly.
5130
5131void TCling::Execute(const char* function, const char* params, int* error)
5132{
5134 if (error) {
5135 *error = TInterpreter::kNoError;
5136 }
5138 Longptr_t offset = 0L;
5140 func.SetFunc(&cl, function, params, &offset);
5141 func.Exec(0);
5142}
5143
5144////////////////////////////////////////////////////////////////////////////////
5145/// Execute a method from class cl with arguments params.
5146///
5147/// FIXME: The cint-based version of this code does not check if the
5148/// SetFunc() call works, and does not do any real checking
5149/// for errors from the Exec() call. It did fetch the most
5150/// recent cint security error and return that in error, but
5151/// this does not really translate well to cling/clang. We
5152/// should enhance these interfaces so that we can report
5153/// compilation and runtime errors properly.
5154
5155void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5156 const char* params, Bool_t objectIsConst, int* error)
5157{
5159 if (error) {
5160 *error = TInterpreter::kNoError;
5161 }
5162 // If the actual class of this object inherits 2nd (or more) from TObject,
5163 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5164 // hence gInterpreter->Execute will improperly correct the offset.
5165 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5166 Longptr_t offset = 0L;
5168 func.SetFunc((TClingClassInfo*)cl->GetClassInfo(), method, params, objectIsConst, &offset);
5169 void* address = (void*)((Longptr_t)addr + offset);
5170 func.Exec(address);
5171}
5172
5173////////////////////////////////////////////////////////////////////////////////
5174
5175void TCling::Execute(TObject* obj, TClass* cl, const char* method,
5176 const char* params, int* error)
5177{
5178 Execute(obj,cl,method,params,false,error);
5179}
5180
5181////////////////////////////////////////////////////////////////////////////////
5182/// Execute a method from class cl with the arguments in array params
5183/// (params[0] ... params[n] = array of TObjString parameters).
5184/// Convert the TObjArray array of TObjString parameters to a character
5185/// string of comma separated parameters.
5186/// The parameters of type 'char' are enclosed in double quotes and all
5187/// internal quotes are escaped.
5188
5189void TCling::Execute(TObject* obj, TClass* cl, TMethod* method,
5190 TObjArray* params, int* error)
5191{
5192 if (!method) {
5193 Error("Execute", "No method was defined");
5194 return;
5195 }
5196 TList* argList = method->GetListOfMethodArgs();
5197 // Check number of actual parameters against of expected formal ones
5198
5199 Int_t nparms = argList->LastIndex() + 1;
5200 Int_t argc = params ? params->GetEntries() : 0;
5201
5202 if (argc > nparms) {
5203 Error("Execute","Too many parameters to call %s, got %d but expected at most %d.",method->GetName(),argc,nparms);
5204 return;
5205 }
5206 if (nparms != argc) {
5207 // Let's see if the 'missing' argument are all defaulted.
5208 // if nparms==0 then either we stopped earlier either argc is also zero and we can't reach here.
5209 assert(nparms > 0);
5210
5211 TMethodArg *arg = (TMethodArg *) argList->At( 0 );
5212 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5213 // There is a default value for the first missing
5214 // argument, so we are fine.
5215 } else {
5216 Int_t firstDefault = -1;
5217 for (Int_t i = 0; i < nparms; i ++) {
5218 arg = (TMethodArg *) argList->At( i );
5219 if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
5220 firstDefault = i;
5221 break;
5222 }
5223 }
5224 if (firstDefault >= 0) {
5225 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);
5226 } else {
5227 Error("Execute","Too few arguments to call %s, got only %d but expected %d.",method->GetName(),argc,nparms);
5228 }
5229 return;
5230 }
5231 }
5232
5233 const char* listpar = "";
5234 TString complete(10);
5235 if (params) {
5236 // Create a character string of parameters from TObjArray
5237 TIter next(params);
5238 for (Int_t i = 0; i < argc; i ++) {
5239 TMethodArg* arg = (TMethodArg*) argList->At(i);
5241 TObjString* nxtpar = (TObjString*) next();
5242 if (i) {
5243 complete += ',';
5244 }
5245 if (strstr(type.TrueName(*fNormalizedCtxt), "char")) {
5246 TString chpar('\"');
5247 chpar += (nxtpar->String()).ReplaceAll("\"", "\\\"");
5248 // At this point we have to check if string contains \\"
5249 // and apply some more sophisticated parser. Not implemented yet!
5250 complete += chpar;
5251 complete += '\"';
5252 }
5253 else {
5254 complete += nxtpar->String();
5255 }
5256 }
5257 listpar = complete.Data();
5258 }
5259
5260 // And now execute it.
5262 if (error) {
5263 *error = TInterpreter::kNoError;
5264 }
5265 // If the actual class of this object inherits 2nd (or more) from TObject,
5266 // 'obj' is unlikely to be the start of the object (as described by IsA()),
5267 // hence gInterpreter->Execute will improperly correct the offset.
5268 void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
5270 TClingMethodInfo *minfo = (TClingMethodInfo*)method->fInfo;
5271 func.Init(*minfo);
5272 func.SetArgs(listpar);
5273 // Now calculate the 'this' pointer offset for the method
5274 // when starting from the class described by cl.
5275 const CXXMethodDecl * mdecl = dyn_cast<CXXMethodDecl>(minfo->GetTargetFunctionDecl());
5276 Longptr_t offset = ((TClingClassInfo*)cl->GetClassInfo())->GetOffset(mdecl);
5277 void* address = (void*)((Longptr_t)addr + offset);
5278 func.Exec(address);
5279}
5280
5281////////////////////////////////////////////////////////////////////////////////
5282
5283void TCling::ExecuteWithArgsAndReturn(TMethod* method, void* address,
5284 const void* args[] /*=0*/,
5285 int nargs /*=0*/,
5286 void* ret/*= 0*/) const
5287{
5288 if (!method) {
5289 Error("ExecuteWithArgsAndReturn", "No method was defined");
5290 return;
5291 }
5292
5293 TClingMethodInfo* minfo = (TClingMethodInfo*) method->fInfo;
5294 TClingCallFunc func(*minfo,*fNormalizedCtxt);
5295 func.ExecWithArgsAndReturn(address, args, nargs, ret);
5296}
5297
5298////////////////////////////////////////////////////////////////////////////////
5299/// Execute a cling macro.
5300
5301Longptr_t TCling::ExecuteMacro(const char* filename, EErrorCode* error)
5302{
5304 fCurExecutingMacros.push_back(filename);
5305 Longptr_t result = TApplication::ExecuteFile(filename, (int*)error);
5306 fCurExecutingMacros.pop_back();
5307 return result;
5308}
5309
5310////////////////////////////////////////////////////////////////////////////////
5311/// Return the file name of the current un-included interpreted file.
5312/// See the documentation for GetCurrentMacroName().
5313
5315{
5316 Warning("GetTopLevelMacroName", "Must change return type!");
5317 return fCurExecutingMacros.back();
5318}
5319
5320////////////////////////////////////////////////////////////////////////////////
5321/// Return the file name of the currently interpreted file,
5322/// included or not. Example to illustrate the difference between
5323/// GetCurrentMacroName() and GetTopLevelMacroName():
5324/// ~~~ {.cpp}
5325/// void inclfile() {
5326/// std::cout << "In inclfile.C" << std::endl;
5327/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5328/// TCling::GetCurrentMacroName() << std::endl;
5329/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5330/// TCling::GetTopLevelMacroName() << std::endl;
5331/// }
5332/// ~~~
5333/// ~~~ {.cpp}
5334/// void mymacro() {
5335/// std::cout << "In mymacro.C" << std::endl;
5336/// std::cout << " TCling::GetCurrentMacroName() returns " <<
5337/// TCling::GetCurrentMacroName() << std::endl;
5338/// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5339/// TCling::GetTopLevelMacroName() << std::endl;
5340/// std::cout << " Now calling inclfile..." << std::endl;
5341/// gInterpreter->ProcessLine(".x inclfile.C");;
5342/// }
5343/// ~~~
5344/// Running mymacro.C will print:
5345///
5346/// ~~~ {.cpp}
5347/// root [0] .x mymacro.C
5348/// ~~~
5349/// In mymacro.C
5350/// ~~~ {.cpp}
5351/// TCling::GetCurrentMacroName() returns ./mymacro.C
5352/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5353/// ~~~
5354/// Now calling inclfile...
5355/// In inclfile.h
5356/// ~~~ {.cpp}
5357/// TCling::GetCurrentMacroName() returns inclfile.C
5358/// TCling::GetTopLevelMacroName() returns ./mymacro.C
5359/// ~~~
5360
5362{
5363#if defined(R__MUST_REVISIT)
5364#if R__MUST_REVISIT(6,0)
5365 Warning("GetCurrentMacroName", "Must change return type!");
5366#endif
5367#endif
5368 return fCurExecutingMacros.back();
5369}
5370
5371////////////////////////////////////////////////////////////////////////////////
5372/// Return the absolute type of typeDesc.
5373/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
5374/// You need to use the result immediately before it is being overwritten.
5375
5376const char* TCling::TypeName(const char* typeDesc)
5377{
5378 TTHREAD_TLS_DECL(std::string,t);
5379
5380 if (!strstr(typeDesc, "(*)(")) {
5381 const char *s = strchr(typeDesc, ' ');
5382 const char *template_start = strchr(typeDesc, '<');
5383 if (!strcmp(typeDesc, "long long")) {
5384 t = typeDesc;
5385 }
5386 else if (!strncmp(typeDesc, "unsigned ", s + 1 - typeDesc)) {
5387 t = typeDesc;
5388 }
5389 // s is the position of the second 'word' (if any)
5390 // except in the case of templates where there will be a space
5391 // just before any closing '>': eg.
5392 // TObj<std::vector<UShort_t,__malloc_alloc_template<0> > >*
5393 else if (s && (template_start == 0 || (s < template_start))) {
5394 t = s + 1;
5395 }
5396 else {
5397 t = typeDesc;
5398 }
5399 }
5400 else {
5401 t = typeDesc;
5402 }
5403 auto l = t.length();
5404 while (l > 0 && (t[l - 1] == '*' || t[l - 1] == '&'))
5405 --l;
5406 t.resize(l);
5407 return t.c_str(); // NOLINT
5408}
5409
5410static bool requiresRootMap(const char* rootmapfile)
5411{
5412 assert(rootmapfile && *rootmapfile);
5413
5414 llvm::StringRef libName = llvm::sys::path::filename(rootmapfile);
5415 libName.consume_back(".rootmap");
5416
5417 return !gInterpreter->HasPCMForLibrary(libName.str().c_str());
5418}
5419
5420////////////////////////////////////////////////////////////////////////////////
5421/// Read and parse a rootmapfile in its new format, and return 0 in case of
5422/// success, -1 if the file has already been read, and -3 in case its format
5423/// is the old one (e.g. containing "Library.ClassName"), -4 in case of syntax
5424/// error.
5425
5426int TCling::ReadRootmapFile(const char *rootmapfile, TUniqueString *uniqueString)
5427{
5428 if (!(rootmapfile && *rootmapfile))
5429 return 0;
5430
5431 if (!requiresRootMap(rootmapfile))
5432 return 0; // success
5433
5434 // For "class ", "namespace ", "typedef ", "header ", "enum ", "var " respectively
5435 const std::map<char, unsigned int> keyLenMap = {{'c',6},{'n',10},{'t',8},{'h',7},{'e',5},{'v',4}};
5436
5437 std::string rootmapfileNoBackslash(rootmapfile);
5438#ifdef _MSC_VER
5439 std::replace(rootmapfileNoBackslash.begin(), rootmapfileNoBackslash.end(), '\\', '/');
5440#endif
5441 // Add content of a specific rootmap file
5442 if (fRootmapFiles->FindObject(rootmapfileNoBackslash.c_str()))
5443 return -1;
5444
5445 // Line 1 is `{ decls }`
5446 std::string lineDirective = std::string("\n#line 2 \"Forward declarations from ") + rootmapfileNoBackslash + "\"\n";
5447
5448 std::ifstream file(rootmapfileNoBackslash);
5449 std::string line;
5450 line.reserve(200);
5451 std::string lib_name;
5452 line.reserve(100);
5453 bool newFormat = false;
5454 while (getline(file, line, '\n')) {
5455 if (!newFormat && (line.compare(0, 8, "Library.") == 0 || line.compare(0, 8, "Declare.") == 0)) {
5456 file.close();
5457 return -3; // old format
5458 }
5459 newFormat = true;
5460
5461 if (line.compare(0, 9, "{ decls }") == 0) {
5462 // forward declarations
5463
5464 while (getline(file, line, '\n')) {
5465 if (line[0] == '[')
5466 break;
5467 if (!uniqueString) {
5468 Error("ReadRootmapFile", "Cannot handle \"{ decls }\" sections in custom rootmap file %s",
5469 rootmapfileNoBackslash.c_str());
5470 return -4;
5471 }
5472 if (!lineDirective.empty())
5473 uniqueString->Append(lineDirective);
5474 uniqueString->Append(line + '\n');
5475 }
5476 }
5477 const char firstChar = line[0];
5478 if (firstChar == '[') {
5479 // new section (library)
5480 auto brpos = line.find(']');
5481 if (brpos == string::npos)
5482 continue;
5483 lib_name = line.substr(1, brpos - 1);
5484 size_t nspaces = 0;
5485 while (lib_name[nspaces] == ' ')
5486 ++nspaces;
5487 if (nspaces)
5488 lib_name.replace(0, nspaces, "");
5489 if (gDebug > 3) {
5490 TString lib_nameTstr(lib_name.c_str());
5491 TObjArray *tokens = lib_nameTstr.Tokenize(" ");
5492 const char *lib = ((TObjString *)tokens->At(0))->GetName();
5493 const char *wlib = gSystem->DynamicPathName(lib, kTRUE);
5494 if (wlib) {
5495 Info("ReadRootmapFile", "new section for %s", lib_nameTstr.Data());
5496 } else {
5497 Info("ReadRootmapFile", "section for %s (library does not exist)", lib_nameTstr.Data());
5498 }
5499 delete[] wlib;
5500 delete tokens;
5501 }
5502 } else {
5503 auto keyLenIt = keyLenMap.find(firstChar);
5504 if (keyLenIt == keyLenMap.end())
5505 continue;
5506 unsigned int keyLen = keyLenIt->second;
5507 // Do not make a copy, just start after the key
5508 const char *keyname = line.c_str() + keyLen;
5509