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