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