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