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" {
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"
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
390{
391 static Bool_t entered = kFALSE;
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
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);
452 if (TObject* encAsTObj = enumObj->GetConstants()->FindObject(constantName)){
453 ((TEnumConstant*)encAsTObj)->Update(dmInfo);
454 } else {
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
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);
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
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());
760 while (dirbase.Length() && dirbase != "."
761 && dirbase != "include" && dirbase != "inc"
762 && dirbase != "prec_stl") {
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
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());
807 }
808 //(3) checking if we can compile a macro, if not then cleaning
810 gErrorIgnoreLevel = kWarning; // no "Info: creating library..."
811 Int_t ret = gSystem->CompileMacro(fileName, "k");
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);
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
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
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)
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
960 if (lastPos != inner) // Main switch: case 1 - scoped enum, case 2 global enum
961 {
962 // We have a scope
963 const auto enName = lastPos;
964 const auto scopeNameSize = (lastPos - inner) / sizeof(decltype(*lastPos)) - 2;
965 std::string scopeName{inner, scopeNameSize};
966 // Check if the scope is in the list of classes
967 if (auto scope = static_cast<TClass *>(gROOT->GetListOfClasses()->FindObject(scopeName.c_str()))) {
968 auto enumTable = dynamic_cast<const THashList *>(scope->GetListOfEnums(false));
969 if (enumTable && enumTable->THashList::FindObject(enName))
970 return true;
971 }
972 // It may still be in one of the loaded protoclasses
973 else if (auto scope = static_cast<TProtoClass *>(gClassTable->GetProtoNorm(scopeName.c_str()))) {
974 auto listOfEnums = scope->GetListOfEnums();
975 if (listOfEnums) { // it could be null: no enumerators in the protoclass
976 auto enumTable = dynamic_cast<const THashList *>(listOfEnums);
977 if (enumTable && enumTable->THashList::FindObject(enName))
978 return true;
979 }
980 }
981 } else
982 {
983 // We don't have any scope: this could only be a global enum
984 auto enumTable = dynamic_cast<const THashList *>(gROOT->GetListOfEnums());
985 if (enumTable && enumTable->THashList::FindObject(inner)) return true;
986 }
987
989 {
990 // This is a class name.
991 return true;
992 }
993
994 return false;
995}
996
997////////////////////////////////////////////////////////////////////////////////
998
1003
1004////////////////////////////////////////////////////////////////////////////////
1005
1007{
1008 return fContent.c_str();
1009}
1010
1011////////////////////////////////////////////////////////////////////////////////
1012/// Append string to the storage if not added already.
1013
1014inline bool TCling::TUniqueString::Append(const std::string& str)
1015{
1016 bool notPresent = fLinesHashSet.emplace(fHashFunc(str)).second;
1017 if (notPresent){
1018 fContent+=str;
1019 }
1020 return notPresent;
1021}
1022
1023std::string TCling::ToString(const char* type, void* obj)
1024{
1025 return fInterpreter->toString(type, obj);
1026}
1027
1028////////////////////////////////////////////////////////////////////////////////
1029///\returns true if the module was loaded.
1030static bool LoadModule(const std::string &ModuleName, cling::Interpreter &interp)
1031{
1032 // When starting up ROOT, cling would load all modulemap files on the include
1033 // paths. However, in a ROOT session, it is very common to run aclic which
1034 // will invoke rootcling and possibly produce a modulemap and a module in
1035 // the current folder.
1036 //
1037 // Before failing, try loading the modulemap in the current folder and try
1038 // loading the requested module from it.
1039 std::string currentDir = gSystem->WorkingDirectory();
1040 assert(!currentDir.empty());
1042 if (gDebug > 2)
1043 ::Info("TCling::__LoadModule", "Preloading module %s. \n",
1044 ModuleName.c_str());
1045
1046 return interp.loadModule(ModuleName, /*Complain=*/true);
1047}
1048
1049////////////////////////////////////////////////////////////////////////////////
1050/// Loads the C++ modules that we require to run any ROOT program. This is just
1051/// supposed to make a C++ module from a modulemap available to the interpreter.
1052static void LoadModules(const std::vector<std::string> &modules, cling::Interpreter &interp)
1053{
1054 for (const auto &modName : modules)
1056}
1057
1058static bool IsFromRootCling() {
1059 // rootcling also uses TCling for generating the dictionary ROOT files.
1060 const static bool foundSymbol = dlsym(RTLD_DEFAULT, "usedToIdentifyRootClingByDlSym");
1061 return foundSymbol;
1062}
1063
1064/// Checks if there is an ASTFile on disk for the given module \c M.
1065static bool HasASTFileOnDisk(clang::Module *M, const clang::Preprocessor &PP, std::string *FullFileName = nullptr)
1066{
1067 const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1068
1069 std::string ModuleFileName;
1070 if (!HSOpts.PrebuiltModulePaths.empty())
1071 // Load the module from *only* in the prebuilt module path.
1072 ModuleFileName = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(M->Name);
1073 if (FullFileName)
1075
1076 return !ModuleFileName.empty();
1077}
1078
1079static bool HaveFullGlobalModuleIndex = false;
1081{
1082 CompilerInstance &CI = *interp.getCI();
1083 Preprocessor &PP = CI.getPreprocessor();
1084 auto ModuleManager = CI.getASTReader();
1086 // StringRef ModuleIndexPath = HSI.getModuleCachePath();
1087 // HeaderSearch& HSI = PP.getHeaderSearchInfo();
1088 // HSI.setModuleCachePath(TROOT::GetSharedLibDir().Data());
1089 std::string ModuleIndexPath = TROOT::GetSharedLibDir().Data();
1090 if (ModuleIndexPath.empty())
1091 return nullptr;
1092 // Get an existing global index. This loads it if not already loaded.
1093 ModuleManager->resetForReload();
1094 ModuleManager->loadGlobalIndex();
1095 GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1096
1097 // For finding modules needing to be imported for fixit messages,
1098 // we need to make the global index cover all modules, so we do that here.
1100 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1101 bool RecreateIndex = false;
1102 for (ModuleMap::module_iterator I = MMap.module_begin(), E = MMap.module_end(); I != E; ++I) {
1103 Module *TheModule = I->second;
1104 // We want the index only of the prebuilt modules.
1106 continue;
1107 LoadModule(TheModule->Name, interp);
1108 RecreateIndex = true;
1109 }
1110 if (RecreateIndex) {
1111 cling::Interpreter::PushTransactionRAII deserRAII(&interp);
1112 clang::GlobalModuleIndex::UserDefinedInterestingIDs IDs;
1113
1114 struct DefinitionFinder : public RecursiveASTVisitor<DefinitionFinder> {
1115 DefinitionFinder(clang::GlobalModuleIndex::UserDefinedInterestingIDs& IDs,
1116 clang::TranslationUnitDecl* TU) : DefinitionIDs(IDs) {
1118 }
1119 bool VisitNamedDecl(NamedDecl *ND) {
1120 if (!ND->isFromASTFile())
1121 return true;
1122 if (!ND->getIdentifier())
1123 return true;
1124
1125 if (ND->getAccess() == AS_protected || ND->getAccess() == AS_private)
1126 return true;
1127
1128 if (TagDecl *TD = llvm::dyn_cast<TagDecl>(ND)) {
1129 if (TD->isCompleteDefinition())
1130 Register(TD);
1131 } else if (NamespaceDecl *NSD = llvm::dyn_cast<NamespaceDecl>(ND)) {
1132 Register(NSD, /*AddSingleEntry=*/ false);
1133 }
1135 Register(TND);
1136 // FIXME: Add the rest...
1137 return true; // continue decending
1138 }
1139 private:
1140 clang::GlobalModuleIndex::UserDefinedInterestingIDs &DefinitionIDs;
1141 void Register(const NamedDecl* ND, bool AddSingleEntry = true) {
1142 assert(ND->isFromASTFile());
1143 // FIXME: All decls should have an owning module once rootcling
1144 // updates its generated decls from within the LookupHelper & co.
1145 if (!ND->hasOwningModule()) {
1146#ifndef NDEBUG
1147 SourceManager &SM = ND->getASTContext().getSourceManager();
1148 SourceLocation Loc = ND->getLocation();
1149 const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
1150 (void)FE;
1151 assert(FE->getName().contains("input_line_"));
1152#endif
1153 return;
1154 }
1155
1156 Module *OwningModule = ND->getOwningModule()->getTopLevelModule();
1158 assert(!ND->getName().empty() && "Empty name");
1159 if (AddSingleEntry && DefinitionIDs.count(ND->getName()))
1160 return;
1161 // FIXME: The FileEntry in not stable to serialize.
1162 // FIXME: We might end up with many times with the same module.
1163 // FIXME: We might end up two modules containing a definition.
1164 // FIXME: What do we do if no definition is found.
1165 DefinitionIDs[ND->getName()].push_back(OwningModule->getASTFile());
1166 }
1167 };
1168 DefinitionFinder defFinder(IDs, CI.getASTContext().getTranslationUnitDecl());
1169
1170 llvm::cantFail(GlobalModuleIndex::writeIndex(CI.getFileManager(),
1171 CI.getPCHContainerReader(),
1173 &IDs));
1174 ModuleManager->resetForReload();
1175 ModuleManager->loadGlobalIndex();
1176 GlobalIndex = ModuleManager->getGlobalIndex();
1177 }
1179 }
1180 return GlobalIndex;
1181}
1182
1183static void RegisterCxxModules(cling::Interpreter &clingInterp)
1184{
1185 if (!clingInterp.getCI()->getLangOpts().Modules)
1186 return;
1187
1188 // Loading of a module might deserialize.
1189 cling::Interpreter::PushTransactionRAII deserRAII(&clingInterp);
1190
1191 // Setup core C++ modules if we have any to setup.
1192
1193 // Load libc and stl first.
1194 // Load vcruntime module for windows
1195#ifdef R__WIN32
1196 LoadModule("vcruntime", clingInterp);
1197 LoadModule("services", clingInterp);
1198#endif
1199
1200#ifdef R__MACOSX
1201 LoadModule("Darwin", clingInterp);
1202#else
1203 LoadModule("libc", clingInterp);
1204#endif
1205 LoadModule("std", clingInterp);
1206
1207 LoadModule("_Builtin_intrinsics", clingInterp);
1208
1209 // Load core modules
1210 // This should be vector in order to be able to pass it to LoadModules
1211 std::vector<std::string> CoreModules = {"ROOT_Foundation_C",
1212 "ROOT_Config",
1213 "ROOT_Rtypes",
1214 "ROOT_Foundation_Stage1_NoRTTI",
1215 "Core",
1216 "Rint",
1217 "RIO"};
1218
1220
1221 // Take this branch only from ROOT because we don't need to preload modules in rootcling
1222 if (!IsFromRootCling()) {
1223 std::vector<std::string> CommonModules = {"MathCore"};
1225
1226 // These modules should not be preloaded but they fix issues.
1227 // FIXME: Hist is not a core module but is very entangled to MathCore and
1228 // causes issues.
1229 std::vector<std::string> FIXMEModules = {"Hist"};
1230 clang::CompilerInstance &CI = *clingInterp.getCI();
1231 clang::Preprocessor &PP = CI.getPreprocessor();
1232 ModuleMap &MMap = PP.getHeaderSearchInfo().getModuleMap();
1233 if (MMap.findModule("RInterface"))
1234 FIXMEModules.push_back("RInterface");
1235
1237
1238 GlobalModuleIndex *GlobalIndex = nullptr;
1240 // FIXME: The ASTReader still calls loadGlobalIndex and loads the file
1241 // We should investigate how to suppress it completely.
1242 GlobalIndex = CI.getASTReader()->getGlobalIndex();
1243
1244 llvm::StringSet<> KnownModuleFileNames;
1245 if (GlobalIndex)
1246 GlobalIndex->getKnownModuleFileNames(KnownModuleFileNames);
1247
1248 std::vector<std::string> PendingModules;
1249 PendingModules.reserve(256);
1250 for (auto I = MMap.module_begin(), E = MMap.module_end(); I != E; ++I) {
1251 clang::Module *M = I->second;
1252 assert(M);
1253
1254 // We want to load only already created modules.
1255 std::string FullASTFilePath;
1257 continue;
1258
1260 continue;
1261
1262 if (M->IsUnimportable)
1263 continue;
1264
1265 if (GlobalIndex)
1266 LoadModule(M->Name, clingInterp);
1267 else {
1268 // FIXME: We may be able to remove those checks as cling::loadModule
1269 // checks if a module was alredy loaded.
1270 if (std::find(CoreModules.begin(), CoreModules.end(), M->Name) != CoreModules.end())
1271 continue; // This is a core module which was already loaded.
1272
1273 // Load system modules now and delay the other modules after we have
1274 // loaded all system ones.
1275 if (M->IsSystem)
1276 LoadModule(M->Name, clingInterp);
1277 else
1278 PendingModules.push_back(M->Name);
1279 }
1280 }
1282 }
1283
1284 // Check that the gROOT macro was exported by any core module.
1285 assert(clingInterp.getMacro("gROOT") && "Couldn't load gROOT macro?");
1286
1287 // `ERROR` and `PI` are from loading R related modules, which conflict with
1288 // user's code.
1289 clingInterp.declare(R"CODE(
1290#ifdef PI
1291# undef PI
1292#endif
1293#ifdef ERROR
1294# undef ERROR
1295#endif
1296 )CODE");
1297}
1298
1299static void RegisterPreIncludedHeaders(cling::Interpreter &clingInterp)
1300{
1301 std::string PreIncludes;
1302 bool hasCxxModules = clingInterp.getCI()->getLangOpts().Modules;
1303
1304 // For the list to also include string, we have to include it now.
1305 // rootcling does parts already if needed, e.g. genreflex does not want using
1306 // namespace std.
1307 if (IsFromRootCling()) {
1308 PreIncludes += "#include \"RtypesCore.h\"\n";
1309 } else {
1310 if (!hasCxxModules)
1311 PreIncludes += "#include \"Rtypes.h\"\n";
1312
1314 + gInterpreterClassDef + "\n"
1315 "#undef ClassImp\n"
1316 "#define ClassImp(X);\n";
1317 }
1318 if (!hasCxxModules)
1319 PreIncludes += "#include <string>\n";
1320
1321 // We must include it even when we have modules because it is marked as
1322 // textual in the modulemap due to the nature of the assert header.
1323#ifndef R__WIN32
1324 PreIncludes += "#include <cassert>\n";
1325#endif
1326 PreIncludes += "using namespace std;\n";
1327 clingInterp.declare(PreIncludes);
1328}
1329
1330////////////////////////////////////////////////////////////////////////////////
1331/// Initialize the cling interpreter interface.
1332/// \param name name for TInterpreter
1333/// \param title title for TInterpreter
1334/// \param argv - array of arguments passed to the cling::Interpreter constructor
1335/// e.g. `-DFOO=bar`. The last element of the array must be `nullptr`.
1336
1337TCling::TCling(const char *name, const char *title, const char* const argv[], void *interpLibHandle)
1338: TInterpreter(name, title), fGlobalsListSerial(-1), fMapfile(nullptr),
1339 fRootmapFiles(nullptr), fLockProcessLine(true), fNormalizedCtxt(nullptr), fLookupHelper(nullptr),
1340 fPrevLoadedDynLibInfo(nullptr), fClingCallbacks(nullptr), fAutoLoadCallBack(nullptr),
1342{
1343 fPrompt[0] = 0;
1344 const bool fromRootCling = IsFromRootCling();
1345
1346 fCxxModulesEnabled = false;
1347#ifdef R__USE_CXXMODULES
1348 fCxxModulesEnabled = true;
1349#endif
1350
1351 llvm::install_fatal_error_handler(&exceptionErrorHandler);
1352
1353 fTemporaries = new std::vector<cling::Value>();
1354
1355 std::vector<std::string> clingArgsStorage;
1356 clingArgsStorage.push_back("cling4root");
1357 for (const char* const* arg = argv; *arg; ++arg)
1358 clingArgsStorage.push_back(*arg);
1359
1360 // rootcling sets its arguments through TROOT::GetExtraInterpreterArgs().
1361 if (!fromRootCling) {
1363
1364 // Add -I early so ASTReader can find the headers.
1365 std::string interpInclude(TROOT::GetEtcDir().Data());
1366 clingArgsStorage.push_back("-I" + interpInclude);
1367
1368 // Add include path to etc/cling.
1369 clingArgsStorage.push_back("-I" + interpInclude + "/cling");
1370
1371 // Add include path to etc/cling.
1372 clingArgsStorage.push_back("-I" + interpInclude + "/cling/plugins/include");
1373
1374 // Add the root include directory and etc/ to list searched by default.
1375 clingArgsStorage.push_back(std::string(("-I" + TROOT::GetIncludeDir()).Data()));
1376
1377 // Add the current path to the include path
1378 // TCling::AddIncludePath(".");
1379
1380 // Attach the PCH (unless we have C++ modules enabled which provide the
1381 // same functionality).
1382 if (!fCxxModulesEnabled) {
1383 std::string pchFilename = interpInclude + "/allDict.cxx.pch";
1384 if (gSystem->Getenv("ROOT_PCH")) {
1385 pchFilename = gSystem->Getenv("ROOT_PCH");
1386 }
1387
1388 clingArgsStorage.push_back("-include-pch");
1389 clingArgsStorage.push_back(pchFilename);
1390 }
1391
1392 clingArgsStorage.push_back("-Wno-undefined-inline");
1393 clingArgsStorage.push_back("-fsigned-char");
1394 // The -O1 optimization flag has nasty side effects on Windows (32 and 64 bit)
1395 // See the GitHub issues #9809 and #9944
1396 // TODO: to be reviewed after the upgrade of LLVM & Clang
1397#ifndef _MSC_VER
1398 clingArgsStorage.push_back("-O1");
1399 // Disable optimized register allocation which is turned on automatically
1400 // by -O1, but seems to require -O2 to not explode in run time.
1401 clingArgsStorage.push_back("-mllvm");
1402 clingArgsStorage.push_back("-optimize-regalloc=0");
1403#endif
1404 }
1405
1406 // Process externally passed arguments if present.
1407 std::optional<std::string> EnvOpt = llvm::sys::Process::GetEnv("EXTRA_CLING_ARGS");
1408 if (EnvOpt.has_value()) {
1410 while (!Env.empty()) {
1411 StringRef Arg;
1412 std::tie(Arg, Env) = Env.split(' ');
1413 clingArgsStorage.push_back(Arg.str());
1414 }
1415 }
1416
1417 auto GetEnvVarPath = [](const std::string &EnvVar, std::vector<std::string> &Paths) {
1418 std::optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(EnvVar);
1419 if (EnvOpt.has_value()) {
1421 while (!Env.empty()) {
1422 StringRef Arg;
1423 std::tie(Arg, Env) = Env.split(ROOT::FoundationUtils::GetEnvPathSeparator());
1424 if (std::find(Paths.begin(), Paths.end(), Arg.str()) == Paths.end())
1425 Paths.push_back(Arg.str());
1426 }
1427 }
1428 };
1429
1430 if (fCxxModulesEnabled) {
1431 std::vector<std::string> Paths;
1432 // ROOT usually knows better where its libraries are. This way we can
1433 // discover modules without having to should thisroot.sh and should fix
1434 // gnuinstall.
1435 Paths.push_back(TROOT::GetSharedLibDir().Data());
1436 GetEnvVarPath("CLING_PREBUILT_MODULE_PATH", Paths);
1437 std::string EnvVarPath;
1438 for (const std::string& P : Paths)
1440 // FIXME: We should make cling -fprebuilt-module-path work.
1441 gSystem->Setenv("CLING_PREBUILT_MODULE_PATH", EnvVarPath.c_str());
1442 }
1443
1444 // FIXME: This only will enable frontend timing reports.
1445 EnvOpt = llvm::sys::Process::GetEnv("ROOT_CLING_TIMING");
1446 if (EnvOpt.has_value())
1447 clingArgsStorage.push_back("-ftime-report");
1448
1449 // Add the overlay file. Note that we cannot factor it out for both root
1450 // and rootcling because rootcling activates modules only if -cxxmodule
1451 // flag is passed.
1453 // For now we prefer rootcling to enumerate explicitly its modulemaps.
1454 std::vector<std::string> ModuleMaps;
1455 std::string ModuleMapSuffix = ROOT::FoundationUtils::GetPathSeparator() + "ROOT.modulemap";
1456 ModuleMaps.push_back(TROOT::GetIncludeDir().Data() + ModuleMapSuffix);
1457 GetEnvVarPath("CLING_MODULEMAP_FILES", ModuleMaps);
1458
1459 std::string cwd = gSystem->WorkingDirectory();
1460 // Give highest precedence of the modulemap in the cwd if any.
1461 if (llvm::sys::fs::exists(cwd + ModuleMapSuffix))
1462 ModuleMaps.push_back(cwd + ModuleMapSuffix);
1463
1464 for (const std::string& M : ModuleMaps)
1465 clingArgsStorage.push_back("-fmodule-map-file=" + M);
1466
1467 std::string ModulesCachePath;
1468 EnvOpt = llvm::sys::Process::GetEnv("CLING_MODULES_CACHE_PATH");
1469 if (EnvOpt.has_value()){
1471 assert(llvm::sys::fs::exists(Env) && "Path does not exist!");
1472 ModulesCachePath = Env.str();
1473 } else {
1475 }
1476
1477 clingArgsStorage.push_back("-fmodules-cache-path=" + ModulesCachePath);
1478 }
1479
1480 std::vector<const char*> interpArgs;
1481 for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1483 interpArgs.push_back(iArg->c_str());
1484
1485 // Activate C++ modules support. If we are running within rootcling, it's up
1486 // to rootcling to set this flag depending on whether it wants to produce
1487 // C++ modules.
1489 if (fCxxModulesEnabled) {
1490 if (!fromRootCling) {
1491 // We only set this flag, rest is done by the CIFactory.
1492 interpArgs.push_back("-fmodules");
1493 interpArgs.push_back("-fno-implicit-module-maps");
1494 // We should never build modules during runtime, so let's enable the
1495 // module build remarks from clang to make it easier to spot when we do
1496 // this by accident.
1497 interpArgs.push_back("-Rmodule-build");
1498 }
1499 // ROOT implements its AutoLoading upon module's link directives. We
1500 // generate module A { header "A.h" link "A.so" export * } where ROOT's
1501 // facilities use the link directive to dynamically load the relevant
1502 // library. So, we need to suppress clang's default autolink behavior.
1503 interpArgs.push_back("-fno-autolink");
1504 }
1505
1506#ifdef R__FAST_MATH
1507 // Same setting as in rootcling_impl.cxx.
1508 interpArgs.push_back("-ffast-math");
1509#endif
1510
1512 // Add statically injected extra arguments, usually coming from rootcling.
1513 for (const char** extraArgs = TROOT::GetExtraInterpreterArgs();
1514 extraArgs && *extraArgs; ++extraArgs) {
1515 if (!strcmp(*extraArgs, "-resource-dir")) {
1516 // Take the next arg as the llvm resource directory.
1518 } else {
1519 interpArgs.push_back(*extraArgs);
1520 }
1521 }
1522
1523 std::vector<std::string> _empty;
1525 for (const auto &arg: args)
1526 interpArgs.emplace_back(arg.c_str());
1527
1528 // Add the Rdict module file extension.
1529 cling::Interpreter::ModuleFileExtensions extensions;
1530 EnvOpt = llvm::sys::Process::GetEnv("ROOTDEBUG_RDICT");
1531 if (!EnvOpt.has_value())
1532 extensions.push_back(std::make_shared<TClingRdictModuleFileExtension>());
1533
1534 fInterpreter = std::make_unique<cling::Interpreter>(interpArgs.size(),
1535 &(interpArgs[0]),
1538
1539 if (!fInterpreter->getCI()) { // Compiler instance could not be created. See https://its.cern.ch/jira/browse/ROOT-10239
1540 return;
1541 }
1542 // Don't check whether modules' files exist.
1543 fInterpreter->getCI()->getPreprocessorOpts().DisablePCHOrModuleValidation =
1544 DisableValidationForModuleKind::All;
1545
1546 // Until we can disable AutoLoading during Sema::CorrectTypo() we have
1547 // to disable spell checking.
1548 fInterpreter->getCI()->getLangOpts().SpellChecking = false;
1549
1550 // Sync modules on/off between clang and us: clang turns it on for C++ >= 20.
1551 auto isModulesArg = [](const char* arg) { return !strcmp(arg, "-fmodules"); };
1552 bool hasModulesArg = std::find_if(interpArgs.begin(), interpArgs.end(), isModulesArg) != interpArgs.end();
1553 fInterpreter->getCI()->getLangOpts().Modules = hasModulesArg;
1554
1555 // We need stream that doesn't close its file descriptor, thus we are not
1556 // using llvm::outs. Keeping file descriptor open we will be able to use
1557 // the results in pipes (Savannah #99234).
1558 static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO, /*ShouldClose*/false);
1559 fMetaProcessor = std::make_unique<cling::MetaProcessor>(*fInterpreter, fMPOuts);
1560
1563
1564 // We are now ready (enough is loaded) to init the list of opaque typedefs.
1571
1572 // Disallow auto-parsing in rootcling
1574
1575 ResetAll();
1576
1577 // Enable dynamic lookup
1578 if (!fromRootCling) {
1579 fInterpreter->enableDynamicLookup();
1580 }
1581
1582 // Enable ClinG's DefinitionShadower for ROOT.
1583 fInterpreter->getRuntimeOptions().AllowRedefinition = 1;
1584 auto &Policy = const_cast<clang::PrintingPolicy &>(fInterpreter->getCI()->getASTContext().getPrintingPolicy());
1585 // Print 'a<b<c> >' rather than 'a<b<c>>'.
1586 // FIXME: We should probably switch to the default printing policy setting
1587 // after adjusting tons of reference files.
1588 Policy.SplitTemplateClosers = true;
1589 // Keep default templare arguments, required for dictionary generation.
1590 Policy.SuppressDefaultTemplateArgs = false;
1591
1592
1593 // Attach cling callbacks last; they might need TROOT::fInterpreter
1594 // and should thus not be triggered during the equivalent of
1595 // TROOT::fInterpreter = new TCling;
1596 std::unique_ptr<TClingCallbacks>
1600 fInterpreter->setCallbacks(std::move(clingCallbacks));
1601
1602 if (!fromRootCling) {
1603 cling::DynamicLibraryManager& DLM = *fInterpreter->getDynamicLibraryManager();
1604 // Make sure cling looks into ROOT's libdir, even if not part of LD_LIBRARY_PATH
1605 // e.g. because of an RPATH build.
1606 DLM.addSearchPath(TROOT::GetSharedLibDir().Data(), /*isUser=*/true,
1607 /*prepend=*/true);
1608 auto ShouldPermanentlyIgnore = [](llvm::StringRef FileName) -> bool{
1609 llvm::StringRef stem = llvm::sys::path::stem(FileName);
1610 return stem.startswith("libNew") || stem.startswith("libcppyy_backend");
1611 };
1612 // Initialize the dyld for AutoloadLibraryGenerator.
1613 DLM.initializeDyld(ShouldPermanentlyIgnore);
1614 }
1615}
1616
1617
1618////////////////////////////////////////////////////////////////////////////////
1619/// Destroy the interpreter interface.
1620
1622{
1623 // ROOT's atexit functions require the interepreter to be available.
1624 // Run them before shutting down.
1625 if (!IsFromRootCling())
1626 GetInterpreterImpl()->runAtExitFuncs();
1627 fIsShuttingDown = true;
1628 delete fMapfile;
1629 delete fRootmapFiles;
1630 delete fTemporaries;
1631 delete fNormalizedCtxt;
1632 delete fLookupHelper;
1633 gCling = nullptr;
1634}
1635
1636////////////////////////////////////////////////////////////////////////////////
1637/// Initialize the interpreter, once TROOT::fInterpreter is set.
1638
1640{
1641 if (!fClingCallbacks) // Compiler instance could not be created. See https://its.cern.ch/jira/browse/ROOT-10239
1642 return;
1644
1645 // We are set up. Enable ROOT's AutoLoading.
1646 if (IsFromRootCling())
1647 return;
1648
1649 // Read the rules before enabling the auto loading to not inadvertently
1650 // load the libraries for the classes concerned even-though the user is
1651 // *not* using them.
1652 // Note this call must happen before the first call to LoadLibraryMap.
1653 assert(GetRootMapFiles() == nullptr && "Must be called before LoadLibraryMap!");
1654 TClass::ReadRules(); // Read the default customization rules ...
1655
1657 SetClassAutoLoading(true);
1658}
1659
1661{
1662 fIsShuttingDown = true;
1663 ResetGlobals();
1664}
1665
1666////////////////////////////////////////////////////////////////////////////////
1667/// Helper to initialize TVirtualStreamerInfo's factor early.
1668/// Use static initialization to insure only one TStreamerInfo is created.
1670{
1671 // Use lambda since SetFactory return void.
1672 auto setFactory = []() {
1674 return kTRUE;
1675 };
1676 static bool doneFactory = setFactory();
1677 return doneFactory; // avoid unused variable warning.
1678}
1679
1680////////////////////////////////////////////////////////////////////////////////
1681/// Register Rdict data for future loading by LoadPCM;
1682
1683void TCling::RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
1684{
1685 if (IsFromRootCling())
1686 return;
1687
1688 if (llvm::sys::fs::exists(pcmFileNameFullPath)) {
1689 ::Error("TCling::RegisterRdictForLoadPCM", "Rdict '%s' is both in Module extension and in File system.", pcmFileNameFullPath.c_str());
1690 return;
1691 }
1692
1693 // The pcmFileNameFullPath must be resolved already because we cannot resolve
1694 // a link to a non-existent file.
1696}
1697
1698////////////////////////////////////////////////////////////////////////////////
1699/// Tries to load a PCM from TFile; returns true on success.
1700
1702{
1703 auto listOfKeys = pcmFile.GetListOfKeys();
1704
1705 // This is an empty pcm
1706 if (listOfKeys && ((listOfKeys->GetSize() == 0) || // Nothing here, or
1707 ((listOfKeys->GetSize() == 1) && // only one, and
1708 !strcmp(((TKey *)listOfKeys->At(0))->GetName(), "EMPTY") // name is EMPTY
1709 ))) {
1710 return;
1711 }
1712
1714 if (gDebug > 1)
1715 ::Info("TCling::LoadPCMImpl", "reading protoclasses for %s \n", pcmFile.GetName());
1716
1718 pcmFile.GetObject("__Enums", enums);
1719 if (enums) {
1720 // Cache the pointers
1721 auto listOfGlobals = gROOT->GetListOfGlobals();
1722 auto listOfEnums = dynamic_cast<THashList *>(gROOT->GetListOfEnums());
1723 // Loop on enums and then on enum constants
1724 for (auto selEnum : *enums) {
1725 const char *enumScope = selEnum->GetTitle();
1726 const char *enumName = selEnum->GetName();
1727 if (strcmp(enumScope, "") == 0) {
1728 // This is a global enum and is added to the
1729 // list of enums and its constants to the list of globals
1730 if (!listOfEnums->THashList::FindObject(enumName)) {
1731 ((TEnum *)selEnum)->SetClass(nullptr);
1732 listOfEnums->Add(selEnum);
1733 }
1734 for (auto enumConstant : *static_cast<TEnum *>(selEnum)->GetConstants()) {
1735 if (!listOfGlobals->FindObject(enumConstant)) {
1737 }
1738 }
1739 } else {
1740 // This enum is in a namespace. A TClass entry is bootstrapped if
1741 // none exists yet and the enum is added to it
1743 if (!nsTClassEntry) {
1745 }
1746 auto listOfEnums = nsTClassEntry->fEnums.load();
1747 if (!listOfEnums) {
1748 if ((kIsClass | kIsStruct | kIsUnion) & nsTClassEntry->Property()) {
1749 // For this case, the list will be immutable once constructed
1750 // (i.e. in this case, by the end of this routine).
1752 } else {
1753 // namespaces can have enums added to them
1755 }
1756 }
1757 if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)) {
1758 ((TEnum *)selEnum)->SetClass(nsTClassEntry);
1759 listOfEnums->Add(selEnum);
1760 }
1761 }
1762 }
1763 enums->Clear();
1764 delete enums;
1765 }
1766
1767 pcmFile.GetObject("__ProtoClasses", protoClasses);
1768
1769 if (protoClasses) {
1770 for (auto obj : *protoClasses) {
1771 TProtoClass *proto = (TProtoClass *)obj;
1773 }
1774 // Now that all TClass-es know how to set them up we can update
1775 // existing TClasses, which might cause the creation of e.g. TBaseClass
1776 // objects which in turn requires the creation of TClasses, that could
1777 // come from the PCH, but maybe later in the loop. Instead of resolving
1778 // a dependency graph the addition to the TClassTable above allows us
1779 // to create these dependent TClasses as needed below.
1780 for (auto proto : *protoClasses) {
1781 if (TClass *existingCl = (TClass *)gROOT->GetListOfClasses()->FindObject(proto->GetName())) {
1782 // We have an existing TClass object. It might be emulated
1783 // or interpreted; we now have more information available.
1784 // Make that available.
1785 if (existingCl->GetState() != TClass::kHasTClassInit) {
1786 DictFuncPtr_t dict = gClassTable->GetDict(proto->GetName());
1787 if (!dict) {
1788 ::Error("TCling::LoadPCM", "Inconsistent TClassTable for %s", proto->GetName());
1789 } else {
1790 // This will replace the existing TClass.
1791 TClass *ncl = (*dict)();
1792 if (ncl)
1793 ncl->PostLoadCheck();
1794 }
1795 }
1796 }
1797 }
1798
1799 protoClasses->Clear(); // Ownership was transfered to TClassTable.
1800 delete protoClasses;
1801 }
1802
1804 pcmFile.GetObject("__Typedefs", dataTypes);
1805 if (dataTypes) {
1806 for (auto typedf : *dataTypes)
1807 gROOT->GetListOfTypes()->Add(typedf);
1808 dataTypes->Clear(); // Ownership was transfered to TListOfTypes.
1809 delete dataTypes;
1810 }
1811}
1812
1813////////////////////////////////////////////////////////////////////////////////
1814/// Tries to load a rdict PCM, issues diagnostics if it fails.
1815
1817{
1820 assert(!pcmFileNameFullPath.empty());
1821 assert(llvm::sys::path::is_absolute(pcmFileNameFullPath));
1822
1823 // Easier to work with the ROOT interfaces.
1825
1826 // Prevent the ROOT-PCMs hitting this during auto-load during
1827 // JITting - which will cause recursive compilation.
1828 // Avoid to call the plugin manager at all.
1830
1832 llvm::SaveAndRestore<Int_t> SaveGDebug(gDebug);
1833 if (gDebug > 5) {
1834 gDebug -= 5;
1835 ::Info("TCling::LoadPCM", "Loading ROOT PCM %s", pcmFileName.Data());
1836 } else {
1837 gDebug = 0;
1838 }
1839
1840 if (llvm::sys::fs::is_symlink_file(pcmFileNameFullPath))
1842
1844 if (pendingRdict != fPendingRdicts.end()) {
1845 llvm::StringRef pcmContent = pendingRdict->second;
1847 std::string RDictFileOpts = pcmFileNameFullPath + "?filetype=pcm";
1849
1850 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
1852 // Currently the module file are never unloaded (even if the library is
1853 // unloaded) and, of course, never reloaded.
1854 // Consequently, we must NOT remove the `pendingRdict` from the list
1855 // of pending dictionary, otherwise if a library is unloaded and then
1856 // reload we will be unable to update properly the TClass object
1857 // (because we wont be able to load the rootpcm file by executing the
1858 // above lines)
1859
1860 return;
1861 }
1862
1863 if (!llvm::sys::fs::exists(pcmFileNameFullPath)) {
1864 ::Error("TCling::LoadPCM", "ROOT PCM %s file does not exist",
1865 pcmFileNameFullPath.data());
1866 if (!fPendingRdicts.empty())
1867 for (const auto &rdict : fPendingRdicts)
1868 ::Info("TCling::LoadPCM", "In-memory ROOT PCM candidate %s\n",
1869 rdict.first.c_str());
1870 return;
1871 }
1872
1873 if (!gROOT->IsRootFile(pcmFileName)) {
1874 Fatal("LoadPCM", "The file %s is not a ROOT as was expected\n", pcmFileName.Data());
1875 return;
1876 }
1877 TFile pcmFile(pcmFileName + "?filetype=pcm", "READ");
1879}
1880
1881//______________________________________________________________________________
1882
1883namespace {
1884 using namespace clang;
1885
1886 class ExtLexicalStorageAdder: public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1887 // This class is to be considered an helper for autoparsing.
1888 // It visits the AST and marks all classes (in all of their redeclarations)
1889 // with the setHasExternalLexicalStorage method.
1890 public:
1891 bool VisitRecordDecl(clang::RecordDecl* rcd){
1892 if (gDebug > 2)
1893 Info("ExtLexicalStorageAdder",
1894 "Adding external lexical storage to class %s",
1895 rcd->getNameAsString().c_str());
1896 auto reDeclPtr = rcd->getMostRecentDecl();
1897 do {
1898 reDeclPtr->setHasExternalLexicalStorage();
1899 } while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1900
1901 return false;
1902 }
1903 };
1904
1905
1906}
1907
1908////////////////////////////////////////////////////////////////////////////////
1909///\returns true if the module map was loaded, false on error or if the map was
1910/// already loaded.
1912 const std::string &ModuleMapName /*= "module.modulemap"*/) const
1913{
1914 assert(llvm::sys::path::is_absolute(FullPath));
1915 Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
1916 FileManager &FM = PP.getFileManager();
1917 // FIXME: In a ROOT session we can add an include path (through .I /inc/path)
1918 // We should look for modulemap files there too.
1919 if (auto DE = FM.getOptionalDirectoryRef(FullPath)) {
1920 HeaderSearch &HS = PP.getHeaderSearchInfo();
1921 HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1922 const auto &ModPaths = HSOpts.PrebuiltModulePaths;
1923 bool pathExists = std::find(ModPaths.begin(), ModPaths.end(), FullPath) != ModPaths.end();
1924 if (!pathExists)
1925 HSOpts.AddPrebuiltModulePath(FullPath);
1926 // We cannot use HS.lookupModuleMapFile(DE, /*IsFramework*/ false);
1927 // because its internal call to getFile has CacheFailure set to true.
1928 // In our case, modulemaps can appear any time due to ACLiC.
1929 // Code copied from HS.lookupModuleMapFile.
1930 llvm::SmallString<256> ModuleMapFileName(DE->getName());
1931 llvm::sys::path::append(ModuleMapFileName, ModuleMapName);
1932 if (auto FE = FM.getOptionalFileRef(ModuleMapFileName, /*openFile*/ false,
1933 /*CacheFailure*/ false)) {
1934 if (!HS.loadModuleMapFile(*FE, /*IsSystem*/ false))
1935 return true;
1936 Error("RegisterPrebuiltModulePath", "Could not load modulemap in %s", ModuleMapFileName.c_str());
1937 }
1938 }
1939 return false;
1940}
1941
1942////////////////////////////////////////////////////////////////////////////////
1943/// List of dicts that have the PCM information already in the PCH.
1944static const std::unordered_set<std::string> gIgnoredPCMNames = {"libCore",
1945 "libRint",
1946 "libThread",
1947 "libRIO",
1948 "libImt",
1949 "libMultiProc",
1950 "libcomplexDict",
1951 "libdequeDict",
1952 "liblistDict",
1953 "libforward_listDict",
1954 "libvectorDict",
1955 "libmapDict",
1956 "libmultimap2Dict",
1957 "libmap2Dict",
1958 "libmultimapDict",
1959 "libsetDict",
1960 "libmultisetDict",
1961 "libunordered_setDict",
1962 "libunordered_multisetDict",
1963 "libunordered_mapDict",
1964 "libunordered_multimapDict",
1965 "libvalarrayDict",
1966 "G__GenVector32",
1967 "G__Smatrix32"};
1968
1969static void PrintDlError(const char *dyLibName, const char *modulename)
1970{
1971#ifdef R__WIN32
1972 char dyLibError[1000];
1974 dyLibError, sizeof(dyLibError), NULL);
1975#else
1976 const char *dyLibError = dlerror();
1977#endif
1978 ::Error("TCling::RegisterModule", "Cannot open shared library %s for dictionary %s:\n %s", dyLibName, modulename,
1979 (dyLibError) ? dyLibError : "");
1980}
1981
1982////////////////////////////////////////////////////////////////////////////////
1983// Update all the TClass registered in fClassesToUpdate
1984
1986{
1987 while (!fClassesToUpdate.empty()) {
1988 TClass *oldcl = fClassesToUpdate.back().first;
1989 // If somehow the TClass has already been loaded (maybe it was registered several time),
1990 // we skip it. Otherwise, the existing TClass is in mode kInterpreted, kEmulated or
1991 // maybe even kForwardDeclared and needs to replaced.
1992 if (oldcl->GetState() != TClass::kHasTClassInit) {
1993 // if (gDebug > 2) Info("RegisterModule", "Forcing TClass init for %s", oldcl->GetName());
1994 DictFuncPtr_t dict = fClassesToUpdate.back().second;
1995 fClassesToUpdate.pop_back();
1996 // Calling func could manipulate the list so, let maintain the list
1997 // then call the dictionary function.
1998 TClass *ncl = dict();
1999 if (ncl) ncl->PostLoadCheck();
2000 } else {
2001 fClassesToUpdate.pop_back();
2002 }
2003 }
2004}
2005////////////////////////////////////////////////////////////////////////////////
2006/// Inject the module named "modulename" into cling; load all headers.
2007/// headers is a 0-terminated array of header files to `#include` after
2008/// loading the module. The module is searched for in all $LD_LIBRARY_PATH
2009/// entries (or %PATH% on Windows).
2010/// This function gets called by the static initialization of dictionary
2011/// libraries.
2012/// The payload code is injected "as is" in the interpreter.
2013/// The value of 'triggerFunc' is used to find the shared library location.
2014
2016 const char** headers,
2017 const char** includePaths,
2018 const char* payloadCode,
2019 const char* fwdDeclsCode,
2020 void (*triggerFunc)(),
2022 const char** classesHeaders,
2023 Bool_t lateRegistration /*=false*/,
2024 Bool_t hasCxxModule /*=false*/)
2025{
2026 const bool fromRootCling = IsFromRootCling();
2027 // We need the dictionary initialization but we don't want to inject the
2028 // declarations into the interpreter, except for those we really need for
2029 // I/O; see rootcling.cxx after the call to TCling__GetInterpreter().
2030 if (fromRootCling) return;
2031
2032 // When we cannot provide a module for the library we should enable header
2033 // parsing. This 'mixed' mode ensures gradual migration to modules.
2034 llvm::SaveAndRestore<bool> SaveHeaderParsing(fHeaderParsingOnDemand);
2036
2037 // Treat Aclic Libs in a special way. Do not delay the parsing.
2039 bool isACLiC = strstr(modulename, "_ACLiC_dict") != nullptr;
2041 if (gDebug>1)
2042 Info("TCling::RegisterModule",
2043 "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
2045 }
2046
2047
2048 // Make sure we relookup symbols that were search for before we loaded
2049 // their autoparse information. We could be more subtil and remove only
2050 // the failed one or only the one in this module, but for now this is
2051 // better than nothing.
2052 fLookedUpClasses.clear();
2053
2054 // Make sure we do not set off AutoLoading or autoparsing during the
2055 // module registration!
2057
2058 for (const char** inclPath = includePaths; *inclPath; ++inclPath) {
2060 }
2061 cling::Transaction* T = nullptr;
2062 // Put the template decls and the number of arguments to skip in the TNormalizedCtxt
2064 const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
2065 const int nArgsToSkip = fwdDeclArgToSkipPair.second;
2066 auto compRes = fInterpreter->declare(fwdDecl.c_str(), &T);
2067 assert(cling::Interpreter::kSuccess == compRes &&
2068 "A fwd declaration could not be compiled");
2069 if (compRes!=cling::Interpreter::kSuccess){
2070 Warning("TCling::RegisterModule",
2071 "Problems in declaring string '%s' were encountered.",
2072 fwdDecl.c_str()) ;
2073 continue;
2074 }
2075
2076 // Drill through namespaces recursively until the template is found
2077 if(ClassTemplateDecl* TD = FindTemplateInNamespace(T->getFirstDecl().getSingleDecl())){
2079 }
2080
2081 }
2082
2083 // FIXME: Remove #define __ROOTCLING__ once PCMs are there.
2084 // This is used to give Sema the same view on ACLiC'ed files (which
2085 // are then #included through the dictionary) as rootcling had.
2087 if (payloadCode)
2088 code += payloadCode;
2089
2090 std::string dyLibName = cling::DynamicLibraryManager::getSymbolLocation(triggerFunc);
2091 assert(!llvm::sys::fs::is_symlink_file(dyLibName));
2092
2093 if (dyLibName.empty()) {
2094 ::Error("TCling::RegisterModule", "Dictionary trigger function for %s not found", modulename);
2095 return;
2096 }
2097
2098 // The triggerFunc may not be in a shared object but in an executable.
2099 bool isSharedLib = cling::DynamicLibraryManager::isSharedLibrary(dyLibName);
2100
2101 bool wasDlopened = false;
2102
2103 // If this call happens after dlopen has finished (i.e. late registration)
2104 // there is no need to dlopen the library recursively. See ROOT-8437 where
2105 // the dyLibName would correspond to the binary.
2106 if (!lateRegistration) {
2107
2108 if (isSharedLib) {
2109 // We need to open the dictionary shared library, to resolve symbols
2110 // requested by the JIT from it: as the library is currently being dlopen'ed,
2111 // its symbols are not yet reachable from the process.
2112 // Recursive dlopen seems to work just fine.
2113 void* dyLibHandle = dlopen(dyLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
2114 if (dyLibHandle) {
2116 wasDlopened = true;
2117 } else {
2119 }
2120 }
2121 } // if (!lateRegistration)
2122
2124 // We now parse the forward declarations. All the classes are then modified
2125 // in order for them to have an external lexical storage.
2126 std::string fwdDeclsCodeLessEnums;
2127 {
2128 // Search for enum forward decls and only declare them if no
2129 // declaration exists yet.
2130 std::string fwdDeclsLine;
2131 std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
2132 std::vector<std::string> scopes;
2133 while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
2134 const auto enumPos = fwdDeclsLine.find("enum __attribute__((annotate(\"");
2135 // We check if the line contains a fwd declaration of an enum
2136 if (enumPos != std::string::npos) {
2137 // We clear the scopes which we may have carried from a previous iteration
2138 scopes.clear();
2139 // We check if the enum is not in a scope. If yes, save its name
2140 // and the names of the enclosing scopes.
2141 if (enumPos != 0) {
2142 // it's enclosed in namespaces. We need to understand what they are
2143 auto nsPos = fwdDeclsLine.find("namespace");
2144 R__ASSERT(nsPos < enumPos && "Inconsistent enum and enclosing scope parsing!");
2145 while (nsPos < enumPos && nsPos != std::string::npos) {
2146 // we have a namespace, let's put it in the collection of scopes
2147 const auto nsNameStart = nsPos + 10;
2148 const auto nsNameEnd = fwdDeclsLine.find('{', nsNameStart);
2149 const auto nsName = fwdDeclsLine.substr(nsNameStart, nsNameEnd - nsNameStart);
2150 scopes.push_back(nsName);
2151 nsPos = fwdDeclsLine.find("namespace", nsNameEnd);
2152 }
2153 }
2154 clang::DeclContext* DC = nullptr;
2155 for (auto &&aScope: scopes) {
2156 DC = cling::utils::Lookup::Namespace(&fInterpreter->getSema(), aScope.c_str(), DC);
2157 if (!DC) {
2158 // No decl context means we have to fwd declare the enum.
2159 break;
2160 }
2161 }
2162 if (scopes.empty() || DC) {
2163 // We know the scope; let's look for the enum. For that, look
2164 // for the *last* closing parentheses of an attribute because
2165 // there can be multiple.
2166 size_t posEnumName = fwdDeclsLine.rfind("\"))) ");
2167 R__ASSERT(posEnumName != std::string::npos && "Inconsistent enum fwd decl!");
2168 posEnumName += 5; // skip "\"))) "
2170 ++posEnumName;
2171 size_t posEnumNameEnd = fwdDeclsLine.find(" : ", posEnumName);
2172 R__ASSERT(posEnumNameEnd != std::string::npos && "Inconsistent enum fwd decl (end)!");
2175 // posEnumNameEnd now points to the last character of the name.
2176
2177 std::string enumName = fwdDeclsLine.substr(posEnumName,
2179
2180 if (clang::NamedDecl* enumDecl
2181 = cling::utils::Lookup::Named(&fInterpreter->getSema(),
2182 enumName.c_str(), DC)) {
2183 // We have an existing enum decl (forward or definition);
2184 // skip this.
2185 R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) && "not an enum decl!");
2186 (void)enumDecl;
2187 continue;
2188 }
2189 }
2190 }
2191
2193 }
2194 }
2195
2196 if (!fwdDeclsCodeLessEnums.empty()){ // Avoid the overhead if nothing is to be declared
2197 auto compRes = fInterpreter->declare(fwdDeclsCodeLessEnums, &T);
2198 assert(cling::Interpreter::kSuccess == compRes &&
2199 "The forward declarations could not be compiled");
2200 if (compRes!=cling::Interpreter::kSuccess){
2201 Warning("TCling::RegisterModule",
2202 "Problems in compiling forward declarations for module %s: '%s'",
2204 }
2205 else if (T){
2206 // Loop over all decls in the transaction and go through them all
2207 // to mark them properly.
2208 // In order to do that, we first iterate over all the DelayedCallInfos
2209 // within the transaction. Then we loop over all Decls in the DeclGroupRef
2210 // contained in the DelayedCallInfos. For each decl, we traverse.
2211 ExtLexicalStorageAdder elsa;
2212 for (auto dciIt = T->decls_begin();dciIt!=T->decls_end();dciIt++){
2213 cling::Transaction::DelayCallInfo& dci = *dciIt;
2214 for(auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
2215 clang::Decl* declPtr = *dit;
2216 elsa.TraverseDecl(declPtr);
2217 }
2218 }
2219 }
2220 }
2221
2222 // Now we register all the headers necessary for the class
2223 // Typical format of the array:
2224 // {"A", "classes.h", "@",
2225 // "vector<A>", "vector", "@",
2226 // "myClass", payloadCode, "@",
2227 // nullptr};
2228
2229 std::string temp;
2230 for (const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
2231 temp=*classesHeader;
2232
2233 size_t theTemplateHash = 0;
2234 bool addTemplate = false;
2235 size_t posTemplate = temp.find('<');
2236 if (posTemplate != std::string::npos) {
2237 // Add an entry for the template itself.
2238 std::string templateName = temp.substr(0, posTemplate);
2240 addTemplate = true;
2241 }
2242 size_t theHash = fStringHashFunction(temp);
2243 classesHeader++;
2245 // This is done in order to distinguish headers from files and from the payloadCode
2247 fPayloads.insert(theHash);
2249 }
2250 if (gDebug > 2)
2251 Info("TCling::RegisterModule",
2252 "Adding a header for %s", temp.c_str());
2254 if (addTemplate) {
2257 }
2258 addTemplate = false;
2259 }
2260 }
2261 }
2262 }
2263
2264 clang::Sema &TheSema = fInterpreter->getSema();
2265
2266 bool ModuleWasSuccessfullyLoaded = false;
2267 if (hasCxxModule) {
2268 std::string ModuleName = modulename;
2269 if (llvm::StringRef(modulename).startswith("lib"))
2270 ModuleName = llvm::StringRef(modulename).substr(3).str();
2271
2272 // In case we are directly loading the library via gSystem->Load() without
2273 // specifying the relevant include paths we should try loading the
2274 // modulemap next to the library location.
2275 clang::Preprocessor &PP = TheSema.getPreprocessor();
2276 std::string ModuleMapName;
2277 if (isACLiC)
2278 ModuleMapName = ModuleName + ".modulemap";
2279 else
2280 ModuleMapName = "module.modulemap";
2281 RegisterPrebuiltModulePath(llvm::sys::path::parent_path(dyLibName).str(),
2283
2284 // FIXME: We should only complain for modules which we know to exist. For example, we should not complain about
2285 // modules such as GenVector32 because it needs to fall back to GenVector.
2286 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2289 // Only report if we found the module in the modulemap.
2290 clang::HeaderSearch &headerSearch = PP.getHeaderSearchInfo();
2291 clang::ModuleMap &moduleMap = headerSearch.getModuleMap();
2292 if (moduleMap.findModule(ModuleName))
2293 Info("TCling::RegisterModule", "Module %s in modulemap failed to load.", ModuleName.c_str());
2294 }
2295 }
2296
2298 llvm::SmallString<256> pcmFileNameFullPath(dyLibName);
2299 // The path dyLibName might not be absolute. This can happen if dyLibName
2300 // is linked to an executable in the same folder.
2301 llvm::sys::fs::make_absolute(pcmFileNameFullPath);
2302 llvm::sys::path::remove_filename(pcmFileNameFullPath);
2303 llvm::sys::path::append(pcmFileNameFullPath,
2305 LoadPCM(pcmFileNameFullPath.str().str());
2306 }
2307
2308 { // scope within which diagnostics are de-activated
2309 // For now we disable diagnostics because we saw them already at
2310 // dictionary generation time. That won't be an issue with the PCMs.
2311
2312 clangDiagSuppr diagSuppr(TheSema.getDiagnostics());
2313
2314#if defined(R__MUST_REVISIT)
2315#if R__MUST_REVISIT(6,2)
2316 Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
2317#endif
2318#endif
2319
2322
2323 const cling::Transaction* watermark = fInterpreter->getLastTransaction();
2324 cling::Interpreter::CompilationResult compRes = fInterpreter->parseForModule(code.Data());
2325 if (isACLiC) {
2326 // Register an unload point.
2327 fMetaProcessor->registerUnloadPoint(watermark, headers[0]);
2328 }
2329
2330 assert(cling::Interpreter::kSuccess == compRes &&
2331 "Payload code of a dictionary could not be parsed correctly.");
2332 if (compRes!=cling::Interpreter::kSuccess) {
2333 Warning("TCling::RegisterModule",
2334 "Problems declaring payload for module %s.", modulename) ;
2335 }
2336 }
2337 }
2338
2339 // Now that all the header have been registered/compiled, let's
2340 // make sure to 'reset' the TClass that have a class init in this module
2341 // but already had their type information available (using information/header
2342 // loaded from other modules or from class rules or from opening a TFile
2343 // or from loading header in a way that did not provoke the loading of
2344 // the library we just loaded).
2346
2348 // __ROOTCLING__ might be pulled in through PCH
2349 fInterpreter->declare("#ifdef __ROOTCLING__\n"
2350 "#undef __ROOTCLING__\n"
2352 "#endif");
2353 }
2354
2355 if (wasDlopened) {
2357 void* dyLibHandle = fRegisterModuleDyLibs.back();
2358 fRegisterModuleDyLibs.pop_back();
2360 }
2361}
2362
2364 clang::CompilerInstance& CI = *GetInterpreterImpl()->getCI();
2365 ASTContext &C = CI.getASTContext();
2366
2367 // Do not do anything if we have no global module index.
2368 // FIXME: This is mostly to real with false positives in the TTabCom
2369 // interface for non-modules.
2370 if (!fCxxModulesEnabled)
2371 return;
2372
2373 if (IdentifierInfoLookup *External = C.Idents.getExternalIdentifierLookup()) {
2374 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
2375 for (llvm::StringRef Ident = Iter->Next(); !Ident.empty(); Ident = Iter->Next()) {
2376 std::string I = Ident.str();
2377 if (!Idents.Contains(I.data()))
2378 Idents.Add(new TObjString(I.c_str()));
2379 }
2380 }
2381}
2382
2383
2384////////////////////////////////////////////////////////////////////////////////
2385/// Register classes that already existed prior to their dictionary loading
2386/// and that already had a ClassInfo (and thus would not be refresh via
2387/// UpdateClassInfo.
2388
2390{
2391 fClassesToUpdate.push_back(std::make_pair(oldcl,dict));
2392}
2393
2394////////////////////////////////////////////////////////////////////////////////
2395/// If the dictionary is loaded, we can remove the class from the list
2396/// (otherwise the class might be loaded twice).
2397
2399{
2400 typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
2401 iterator stop = fClassesToUpdate.end();
2402 for(iterator i = fClassesToUpdate.begin();
2403 i != stop;
2404 ++i)
2405 {
2406 if ( i->first == oldcl ) {
2407 fClassesToUpdate.erase(i);
2408 return;
2409 }
2410 }
2411}
2412
2413
2414////////////////////////////////////////////////////////////////////////////////
2415/// Let cling process a command line.
2416///
2417/// If the command is executed and the error is 0, then the return value
2418/// is the int value corresponding to the result of the executed command
2419/// (float and double return values will be truncated).
2420///
2421
2422// Method for handling the interpreter exceptions.
2423// the MetaProcessor is passing in as argument to teh function, because
2424// cling::Interpreter::CompilationResult is a nested class and it cannot be
2425// forward declared, thus this method cannot be a static member function
2426// of TCling.
2427
2428static int HandleInterpreterException(cling::MetaProcessor* metaProcessor,
2429 const char* input_line,
2430 cling::Interpreter::CompilationResult& compRes,
2431 cling::Value* result)
2432{
2433 try {
2434 return metaProcessor->process(input_line, compRes, result);
2435 }
2436 catch (cling::InterpreterException& ex)
2437 {
2438 Error("HandleInterpreterException", "%s\n%s", ex.what(), "Execution of your code was aborted.");
2439 ex.diagnose();
2440 compRes = cling::Interpreter::kFailure;
2441 }
2442 return 0;
2443}
2444
2445////////////////////////////////////////////////////////////////////////////////
2446
2447bool TCling::DiagnoseIfInterpreterException(const std::exception &e) const
2448{
2449 if (auto ie = dynamic_cast<const cling::InterpreterException*>(&e)) {
2450 ie->diagnose();
2451 return true;
2452 }
2453 return false;
2454}
2455
2456////////////////////////////////////////////////////////////////////////////////
2457
2459{
2460 // Copy the passed line, it comes from a static buffer in TApplication
2461 // which can be reentered through the Cling evaluation routines,
2462 // which would overwrite the static buffer and we would forget what we
2463 // were doing.
2464 //
2466 if (strstr(line,fantomline)) {
2467 // End-Of-Line action
2468 // See the comment (copied from above):
2469 // It is a "fantom" method to synchronize user keyboard input
2470 // and ROOT prompt line (for WIN32)
2471 // and is implemented by
2472 if (gApplication) {
2473 if (gApplication->IsCmdThread()) {
2475 gROOT->SetLineIsProcessing();
2476
2478
2479 gROOT->SetLineHasBeenProcessed();
2480 }
2481 }
2482 return 0;
2483 }
2484
2486 gGlobalMutex->Lock();
2487 if (!gInterpreterMutex)
2490 }
2492 gROOT->SetLineIsProcessing();
2493
2494 struct InterpreterFlagsRAII {
2495 cling::Interpreter* fInterpreter;
2497
2498 InterpreterFlagsRAII(cling::Interpreter* interp):
2499 fInterpreter(interp),
2500 fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
2501 {
2502 fInterpreter->enableDynamicLookup(true);
2503 }
2505 fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
2506 gROOT->SetLineHasBeenProcessed();
2507 }
2509
2510 // A non-zero returned value means the given line was
2511 // not a complete statement.
2512 int indent = 0;
2513 // This will hold the resulting value of the evaluation the given line.
2514 cling::Value result;
2515 cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
2516 if (!strncmp(sLine.Data(), ".L", 2) || !strncmp(sLine.Data(), ".x", 2) ||
2517 !strncmp(sLine.Data(), ".X", 2)) {
2518 // If there was a trailing "+", then CINT compiled the code above,
2519 // and we will need to strip the "+" before passing the line to cling.
2522 TString arguments;
2523 TString io;
2525 aclicMode, arguments, io);
2526 if (aclicMode.Length()) {
2527 // Remove the leading '+'
2528 R__ASSERT(aclicMode[0]=='+' && "ACLiC mode must start with a +");
2529 aclicMode[0]='k'; // We always want to keep the .so around.
2530 if (aclicMode[1]=='+') {
2531 // We have a 2nd +
2532 aclicMode[1]='f'; // We want to force the recompilation.
2533 }
2535 // ACLiC failed.
2536 compRes = cling::Interpreter::kFailure;
2537 } else {
2538 if (strncmp(sLine.Data(), ".L", 2) != 0) {
2539 // if execution was requested.
2540
2541 if (arguments.Length() == 0) {
2542 arguments = "()";
2543 }
2544 // We need to remove the extension.
2545 Ssiz_t ext = fname.Last('.');
2546 if (ext != kNPOS) {
2547 fname.Remove(ext);
2548 }
2549 const char *function = gSystem->BaseName(fname);
2550 mod_line = function + arguments + io;
2552 }
2553 }
2554 } else if (cling::DynamicLibraryManager::isSharedLibrary(fname.Data()) &&
2555 strncmp(sLine.Data(), ".L", 2) != 0) { // .x *.so or *.dll
2556 if (gSystem->Load(fname) < 0) {
2557 // Loading failed.
2558 compRes = cling::Interpreter::kFailure;
2559 } else {
2560 if (arguments.Length() == 0) {
2561 arguments = "()";
2562 }
2563 // We need to remove the extension. (*.so or *.dll)
2564 Ssiz_t ext = fname.Last('.');
2565 if (ext != kNPOS) {
2566 fname.Remove(ext);
2567 }
2568 // Now we try to find the 'main' function to run within this shared library
2569 // We distinguish two cases: a library.so with a function library(args),
2570 // or a precompiled ACLiC macro (macro_C.so) with a function macro(args).
2571 // Only in the second case, we need to strip the suffix _C or _cpp from fname.
2572 if (!gInterpreter->GetFunction(nullptr, gSystem->BaseName(fname))) { // AcLiC macro
2573 // We need to remove the automatically appended _ extension when compiling (macro_C from macro.C)
2574 ext = fname.Last('_');
2575 if (ext != kNPOS) {
2576 fname.Remove(ext);
2577 }
2578 }
2579 const char *function = gSystem->BaseName(fname);
2580 mod_line = function + arguments + io;
2582 }
2583 } else {
2584 // neither ACLiC nor run shared-library (.x)
2585 size_t unnamedMacroOpenCurly;
2586 {
2587 std::string code;
2588 std::string codeline;
2589 // Windows requires std::ifstream::binary to properly handle
2590 // CRLF and LF line endings
2591 std::ifstream in(fname, std::ifstream::binary);
2592 while (in) {
2593 std::getline(in, codeline);
2594 code += codeline + "\n";
2595 }
2597 = cling::utils::isUnnamedMacro(code, fInterpreter->getCI()->getLangOpts());
2598 }
2599
2600 fCurExecutingMacros.push_back(fname);
2601 if (unnamedMacroOpenCurly != std::string::npos) {
2602 compRes = fMetaProcessor->readInputFromFile(fname.Data(), &result,
2604 } else {
2605 // No DynLookup for .x, .L of named macros.
2606 fInterpreter->enableDynamicLookup(false);
2608 }
2609 fCurExecutingMacros.pop_back();
2610 }
2611 } // .L / .X / .x
2612 else {
2613 if (0!=strncmp(sLine.Data(), ".autodict ",10) && sLine != ".autodict") {
2614 // explicitly ignore .autodict without having to support it
2615 // in cling.
2616
2617 // Turn off autoparsing if this is an include directive
2618 bool isInclusionDirective = sLine.Contains("\n#include") || sLine.BeginsWith("#include");
2622 } else {
2624 }
2625 }
2626 }
2627 if (result.isValid())
2629 if (indent) {
2630 if (error)
2631 *error = kProcessing;
2632 return 0;
2633 }
2634 if (error) {
2635 switch (compRes) {
2636 case cling::Interpreter::kSuccess: *error = kNoError; break;
2637 case cling::Interpreter::kFailure: *error = kRecoverable; break;
2638 case cling::Interpreter::kMoreInputExpected: *error = kProcessing; break;
2639 }
2640 }
2641 if (compRes == cling::Interpreter::kSuccess
2642 && result.isValid()
2643 && !result.isVoid())
2644 {
2645 return result.castAs<Longptr_t>();
2646 }
2647 return 0;
2648}
2649
2650////////////////////////////////////////////////////////////////////////////////
2651/// No-op; see TRint instead.
2652
2654{
2655}
2656
2657////////////////////////////////////////////////////////////////////////////////
2658/// \brief Add a directory to the list of directories in which the
2659/// interpreter looks for include files.
2660/// \param[in] path The path to the directory.
2661/// \note Only one path item can be specified at a time, i.e. "path1:path2" is
2662/// \b NOT supported.
2663/// \warning Only the path to the directory should be specified, without
2664/// prepending the \c -I prefix, i.e.
2665/// <tt>gCling->AddIncludePath("/path/to/my/includes")</tt>. If the
2666/// \c -I prefix is used it will be ignored.
2667void TCling::AddIncludePath(const char *path)
2668{
2670 // Favorite source of annoyance: gSystem->AddIncludePath() needs "-I",
2671 // gCling->AddIncludePath() does not! Work around that inconsistency:
2672 if (path[0] == '-' && path[1] == 'I')
2673 path += 2;
2674 TString sPath(path);
2676#ifdef _MSC_VER
2677 if (sPath.BeginsWith("/")) {
2678 char drive[3];
2679 snprintf(drive, 3, "%c:", _getdrive() + 'A' - 1);
2680 sPath.Prepend(drive);
2681 }
2682#endif
2683 fInterpreter->AddIncludePath(sPath.Data());
2684}
2685
2686////////////////////////////////////////////////////////////////////////////////
2687/// Visit all members over members, recursing over base classes.
2688
2690 const TClass* cl, Bool_t isTransient)
2691{
2692 if (insp.GetObjectValidity() == TMemberInspector::kUnset) {
2693 insp.SetObjectValidity(obj ? TMemberInspector::kValidObjectGiven
2695 }
2696
2697 if (!cl || cl->GetCollectionProxy()) {
2698 // We do not need to investigate the content of the STL
2699 // collection, they are opaque to us (and details are
2700 // uninteresting).
2701 return;
2702 }
2703
2704 static const TClassRef clRefString("std::string");
2705 if (clRefString == cl) {
2706 // We stream std::string without going through members..
2707 return;
2708 }
2709
2710 if (TClassEdit::IsStdArray(cl->GetName())) {
2711 // We treat std arrays as C arrays
2712 return;
2713 }
2714
2715 if (TClassEdit::IsUniquePtr(cl->GetName())) {
2716 // Ignore error caused by the inside of std::unique_ptr
2717 // This is needed solely because of rootclingIO's IsUnsupportedUniquePointer
2718 // which checks the number of elements in the GetListOfRealData.
2719 // If this usage is removed, this can be replaced with a return statement.
2720 // See https://github.com/root-project/root/issues/13574
2721 isTransient = true;
2722 }
2723
2724 const char* cobj = (const char*) obj; // for ptr arithmetics
2725
2726 // Treat the case of std::complex in a special manner. We want to enforce
2727 // the layout of a stl implementation independent class, which is the
2728 // complex as implemented in ROOT5.
2729
2730 // A simple lambda to simplify the code
2731 auto inspInspect = [&] (ptrdiff_t offset){
2732 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_real", cobj, isTransient);
2733 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_imag", cobj + offset, isTransient);
2734 };
2735
2737 switch(complexType) {
2739 {
2740 break;
2741 }
2743 {
2744 inspInspect(sizeof(float));
2745 return;
2746 }
2748 {
2749 inspInspect(sizeof(double));
2750 return;
2751 }
2753 {
2754 inspInspect(sizeof(int));
2755 return;
2756 }
2758 {
2759 inspInspect(sizeof(long));
2760 return;
2761 }
2762 }
2763
2764 static clang::PrintingPolicy
2765 printPol(fInterpreter->getCI()->getLangOpts());
2766 if (printPol.Indentation) {
2767 // not yet initialized
2768 printPol.Indentation = 0;
2769 printPol.SuppressInitializers = true;
2770 }
2771
2772 const char* clname = cl->GetName();
2773 // Printf("Inspecting class %s\n", clname);
2774
2775 const clang::ASTContext& astContext = fInterpreter->getCI()->getASTContext();
2776 const clang::Decl *scopeDecl = nullptr;
2777 const clang::Type *recordType = nullptr;
2778
2779 if (cl->GetClassInfo()) {
2781 scopeDecl = clingCI->GetDecl();
2782 recordType = clingCI->GetType();
2783 } else {
2784 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
2785 // Diags will complain about private classes:
2786 scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2787 &recordType);
2788 }
2789 if (!scopeDecl) {
2790 Error("InspectMembers", "Cannot find Decl for class %s", clname);
2791 return;
2792 }
2793 const clang::CXXRecordDecl* recordDecl
2794 = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2795 if (!recordDecl) {
2796 Error("InspectMembers", "Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2797 return;
2798 }
2799
2800 {
2801 // Force possible deserializations first. We need to have no pending
2802 // Transaction when passing control flow to the inspector below (ROOT-7779).
2803 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2804
2805 astContext.getASTRecordLayout(recordDecl);
2806
2807 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2808 eField = recordDecl->field_end(); iField != eField; ++iField) {}
2809 }
2810
2811 const clang::ASTRecordLayout& recLayout
2812 = astContext.getASTRecordLayout(recordDecl);
2813
2814 // TVirtualCollectionProxy *proxy = cl->GetCollectionProxy();
2815 // if (proxy && ( proxy->GetProperties() & TVirtualCollectionProxy::kIsEmulated ) ) {
2816 // Error("InspectMembers","The TClass for %s has an emulated proxy but we are looking at a compiled version of the collection!\n",
2817 // cl->GetName());
2818 // }
2819 if (cl->Size() != recLayout.getSize().getQuantity()) {
2820 Error("InspectMembers","TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2821 cl->GetName(),cl->Size(),(Long64_t)recLayout.getSize().getQuantity());
2822 }
2823
2824 unsigned iNField = 0;
2825 // iterate over fields
2826 // FieldDecls are non-static, else it would be a VarDecl.
2827 for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2828 eField = recordDecl->field_end(); iField != eField;
2829 ++iField, ++iNField) {
2830
2831
2832 clang::QualType memberQT = iField->getType();
2833 if (recordType) {
2834 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2836 }
2837 memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2838 if (memberQT.isNull()) {
2839 std::string memberName;
2840 llvm::raw_string_ostream stream(memberName);
2841 // Don't trigger fopen of the source file to count lines:
2842 printPol.AnonymousTagLocations = false;
2843 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2844 stream.flush();
2845 Error("InspectMembers",
2846 "Cannot retrieve QualType for member %s while inspecting class %s",
2847 memberName.c_str(), clname);
2848 continue; // skip member
2849 }
2850 const clang::Type* memType = memberQT.getTypePtr();
2851 if (!memType) {
2852 std::string memberName;
2853 llvm::raw_string_ostream stream(memberName);
2854 // Don't trigger fopen of the source file to count lines:
2855 printPol.AnonymousTagLocations = false;
2856 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2857 stream.flush();
2858 Error("InspectMembers",
2859 "Cannot retrieve Type for member %s while inspecting class %s",
2860 memberName.c_str(), clname);
2861 continue; // skip member
2862 }
2863
2864 const clang::Type* memNonPtrType = memType;
2865 Bool_t ispointer = false;
2866 if (memNonPtrType->isPointerType()) {
2867 ispointer = true;
2868 clang::QualType ptrQT
2869 = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2870 if (recordType) {
2871 // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2873 }
2874 ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2875 if (ptrQT.isNull()) {
2876 std::string memberName;
2877 llvm::raw_string_ostream stream(memberName);
2878 // Don't trigger fopen of the source file to count lines:
2879 printPol.AnonymousTagLocations = false;
2880 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2881 stream.flush();
2882 Error("InspectMembers",
2883 "Cannot retrieve pointee Type for member %s while inspecting class %s",
2884 memberName.c_str(), clname);
2885 continue; // skip member
2886 }
2887 memNonPtrType = ptrQT.getTypePtr();
2888 }
2889
2890 // assemble array size(s): "[12][4][]"
2891 llvm::SmallString<8> arraySize;
2892 const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2893 unsigned arrLevel = 0;
2894 bool haveErrorDueToArray = false;
2895 while (arrType) {
2896 ++arrLevel;
2897 arraySize += '[';
2898 const clang::ConstantArrayType* constArrType =
2899 clang::dyn_cast<clang::ConstantArrayType>(arrType);
2900 if (constArrType) {
2901 constArrType->getSize().toStringUnsigned(arraySize);
2902 }
2903 arraySize += ']';
2904 clang::QualType subArrQT = arrType->getElementType();
2905 if (subArrQT.isNull()) {
2906 std::string memberName;
2907 llvm::raw_string_ostream stream(memberName);
2908 // Don't trigger fopen of the source file to count lines:
2909 printPol.AnonymousTagLocations = false;
2910 iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2911 stream.flush();
2912 Error("InspectMembers",
2913 "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2914 arrLevel, subArrQT.getAsString(printPol).c_str(),
2915 memberName.c_str(), clname);
2916 haveErrorDueToArray = true;
2917 break;
2918 }
2919 arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2920 }
2921 if (haveErrorDueToArray) {
2922 continue; // skip member
2923 }
2924
2925 // construct member name
2926 std::string fieldName;
2927 if (memType->isPointerType()) {
2928 fieldName = "*";
2929 }
2930
2931 // Check if this field has a custom ioname, if not, just use the one of the decl
2932 std::string ioname(iField->getName());
2934 fieldName += ioname;
2935 fieldName += arraySize;
2936
2937 // get member offset
2938 // NOTE currently we do not support bitfield and do not support
2939 // member that are not aligned on 'bit' boundaries.
2940 clang::CharUnits offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2941 ptrdiff_t fieldOffset = offset.getQuantity();
2942
2943 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fBits[2]", fBits);
2944 // R__insp.Inspect(R__cl, R__insp.GetParent(), "fName", &fName);
2945 // R__insp.InspectMember(fName, "fName.");
2946 // R__insp.Inspect(R__cl, R__insp.GetParent(), "*fClass", &fClass);
2947
2948 // If the class has a custom streamer and the type of the filed is a
2949 // private enum, struct or class, skip it.
2950 if (!insp.IsTreatingNonAccessibleTypes()){
2951 auto iFiledQtype = iField->getType();
2952 if (auto tagDecl = iFiledQtype->getAsTagDecl()){
2953 auto declAccess = tagDecl->getAccess();
2955 continue;
2956 }
2957 }
2958 }
2959
2960 insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
2961
2962 if (!ispointer) {
2963 const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
2964 if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
2965 // nested objects get an extra call to InspectMember
2966 // R__insp.InspectMember("FileStat_t", (void*)&fFileStat, "fFileStat.", false);
2967 std::string sFieldRecName;
2970 clang::QualType(memNonPtrType,0),
2971 *fInterpreter,
2973 }
2974
2975 TDataMember* mbr = cl->GetDataMember(ioname.c_str());
2976 // if we can not find the member (which should not really happen),
2977 // let's consider it transient.
2978 Bool_t transient = isTransient || !mbr || !mbr->IsPersistent();
2979
2980 insp.InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
2981 (fieldName + '.').c_str(), transient);
2982
2983 }
2984 }
2985 } // loop over fields
2986
2987 // inspect bases
2988 // TNamed::ShowMembers(R__insp);
2989 unsigned iNBase = 0;
2990 for (clang::CXXRecordDecl::base_class_const_iterator iBase
2991 = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
2992 iBase != eBase; ++iBase, ++iNBase) {
2993 clang::QualType baseQT = iBase->getType();
2994 if (baseQT.isNull()) {
2995 Error("InspectMembers",
2996 "Cannot find QualType for base number %d while inspecting class %s",
2997 iNBase, clname);
2998 continue;
2999 }
3000 const clang::CXXRecordDecl* baseDecl
3001 = baseQT->getAsCXXRecordDecl();
3002 if (!baseDecl) {
3003 Error("InspectMembers",
3004 "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
3005 iNBase, clname);
3006 continue;
3007 }
3008 TClass* baseCl=nullptr;
3009 std::string sBaseName;
3010 // Try with the DeclId
3011 std::vector<TClass*> foundClasses;
3013 if (foundClasses.size()==1){
3015 } else {
3016 // Try with the normalised Name, as a fallback
3017 if (!baseCl){
3019 baseQT,
3020 *fInterpreter,
3023 }
3024 }
3025
3026 if (!baseCl){
3027 std::string qualNameForDiag;
3029 Error("InspectMembers",
3030 "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
3031 continue;
3032 }
3033
3034 int64_t baseOffset;
3035 if (iBase->isVirtual()) {
3036 if (insp.GetObjectValidity() == TMemberInspector::kNoObjectGiven) {
3037 if (!isTransient) {
3038 Error("InspectMembers",
3039 "Base %s of class %s is virtual but no object provided",
3040 sBaseName.c_str(), clname);
3041 }
3043 } else {
3044 // We have an object to determine the vbase offset.
3046 TClingClassInfo* baseCi = (TClingClassInfo*)baseCl->GetClassInfo();
3047 if (ci && baseCi) {
3048 baseOffset = ci->GetBaseOffset(baseCi, const_cast<void*>(obj),
3049 true /*isDerivedObj*/);
3050 if (baseOffset == -1) {
3051 Error("InspectMembers",
3052 "Error calculating offset of virtual base %s of class %s",
3053 sBaseName.c_str(), clname);
3054 }
3055 } else {
3056 Error("InspectMembers",
3057 "Cannot calculate offset of virtual base %s of class %s",
3058 sBaseName.c_str(), clname);
3059 continue;
3060 }
3061 }
3062 } else {
3063 baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
3064 }
3065 // TOFIX: baseCl can be null here!
3066 if (baseCl->IsLoaded()) {
3067 // For loaded class, CallShowMember will (especially for TObject)
3068 // call the virtual ShowMember rather than the class specific version
3069 // resulting in an infinite recursion.
3071 } else {
3072 baseCl->CallShowMembers(cobj + baseOffset,
3073 insp, isTransient);
3074 }
3075 } // loop over bases
3076}
3077
3078////////////////////////////////////////////////////////////////////////////////
3079/// Check if constructor exited correctly, ie the instance is in a valid state
3080/// \return true if there is a compiler instance available, false otherwise
3082{
3083 return fInterpreter->getCI() != nullptr;
3084}
3085
3086////////////////////////////////////////////////////////////////////////////////
3087/// Reset the interpreter internal state in case a previous action was not correctly
3088/// terminated.
3089
3091{
3092 // No-op there is not equivalent state (to be cleared) in Cling.
3093}
3094
3095////////////////////////////////////////////////////////////////////////////////
3096/// Delete existing temporary values.
3097
3099{
3100 // No-op for cling due to cling::Value.
3101}
3102
3103////////////////////////////////////////////////////////////////////////////////
3104/// Declare code to the interpreter, without any of the interpreter actions
3105/// that could trigger a re-interpretation of the code. I.e. make cling
3106/// behave like a compiler: no dynamic lookup, no input wrapping for
3107/// subsequent execution, no automatic provision of declarations but just a
3108/// plain `#include`.
3109/// Returns true on success, false on failure.
3110
3111bool TCling::Declare(const char* code)
3112{
3114
3117
3118 bool oldDynLookup = fInterpreter->isDynamicLookupEnabled();
3119 fInterpreter->enableDynamicLookup(false);
3120 bool oldRawInput = fInterpreter->isRawInputEnabled();
3121 fInterpreter->enableRawInput(true);
3122
3123 Bool_t ret = LoadText(code);
3124
3125 fInterpreter->enableRawInput(oldRawInput);
3126 fInterpreter->enableDynamicLookup(oldDynLookup);
3127 return ret;
3128}
3129
3130////////////////////////////////////////////////////////////////////////////////
3131/// It calls a "fantom" method to synchronize user keyboard input
3132/// and ROOT prompt line.
3133
3138
3139// This static function is a hop of TCling::IsLibraryLoaded, which is taking a lock and calling
3140// into this function. This is because we wanted to avoid a duplication in TCling::IsLoaded, which
3141// was already taking a lock.
3142static Bool_t s_IsLibraryLoaded(const char* libname, cling::Interpreter* fInterpreter)
3143{
3144 // Check shared library.
3147 return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.Data());
3148 return false;
3149}
3150
3156
3157////////////////////////////////////////////////////////////////////////////////
3158/// Return true if ROOT has cxxmodules pcm for a given library name.
3159// FIXME: We need to be able to support lazy loading of pcm generated by ACLiC.
3161{
3162 llvm::StringRef ModuleName(libname);
3163 ModuleName = llvm::sys::path::stem(ModuleName);
3164 ModuleName.consume_front("lib");
3165
3166 // FIXME: In case when the modulemap is not yet loaded we will return the
3167 // wrong result. Consider a call to HasPCMForLibrary(../test/libEvent.so)
3168 // We will only load the modulemap for libEvent.so after we dlopen libEvent
3169 // which may happen after calling this interface. Maybe we should also check
3170 // if there is a Event.pcm file and a module.modulemap, load it and return
3171 // true.
3172 clang::ModuleMap &moduleMap = fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
3173 clang::Module *M = moduleMap.findModule(ModuleName);
3174 return M && !M->IsUnimportable && M->getASTFile();
3175}
3176
3177////////////////////////////////////////////////////////////////////////////////
3178/// Return true if the file has already been loaded by cint.
3179/// We will try in this order:
3180/// actual filename
3181/// filename as a path relative to
3182/// the include path
3183/// the shared library path
3184
3186{
3188
3189 //FIXME: if we use llvm::sys::fs::make_absolute all this can go away. See
3190 // cling::DynamicLibraryManager.
3191
3192 std::string file_name = filename;
3193 size_t at = std::string::npos;
3194 while ((at = file_name.find("/./")) != std::string::npos)
3195 file_name.replace(at, 3, "/");
3196
3197 std::string filesStr = "";
3198 llvm::raw_string_ostream filesOS(filesStr);
3199 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3200 cling::ClangInternalState::printIncludedFiles(filesOS, SM);
3201 filesOS.flush();
3202
3203 llvm::SmallVector<llvm::StringRef, 100> files;
3204 llvm::StringRef(filesStr).split(files, "\n");
3205
3206 std::set<std::string> fileMap;
3207 llvm::StringRef file_name_ref(file_name);
3208 // Fill fileMap; return early on exact match.
3210 iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
3211 if ((*iF) == file_name_ref) return kTRUE; // exact match
3212 fileMap.insert(iF->str());
3213 }
3214
3215 if (fileMap.empty()) return kFALSE;
3216
3217 // Check MacroPath.
3218 TString sFilename(file_name.c_str());
3220 && fileMap.count(sFilename.Data())) {
3221 return kTRUE;
3222 }
3223
3224 // Check IncludePath.
3225 TString incPath = gSystem->GetIncludePath(); // of the form -Idir1 -Idir2 -Idir3
3226 incPath.Append(":").Prepend(" "); // to match " -I" (note leading ' ')
3227 incPath.ReplaceAll(" -I", ":"); // of form :dir1 :dir2:dir3
3228 while (incPath.Index(" :") != -1) {
3229 incPath.ReplaceAll(" :", ":");
3230 }
3231 incPath.Prepend(".:");
3232 sFilename = file_name.c_str();
3234 && fileMap.count(sFilename.Data())) {
3235 return kTRUE;
3236 }
3237
3238 // Check shared library.
3239 if (s_IsLibraryLoaded(file_name.c_str(), GetInterpreterImpl()))
3240 return kTRUE;
3241
3242 //FIXME: We must use the cling::Interpreter::lookupFileOrLibrary iface.
3243 clang::ConstSearchDirIterator *CurDir = nullptr;
3244 clang::Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
3245 clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3246 auto FE = HS.LookupFile(file_name.c_str(),
3247 clang::SourceLocation(),
3248 /*isAngled*/ false,
3249 /*FromDir*/ nullptr, CurDir,
3250 clang::ArrayRef<std::pair<clang::OptionalFileEntryRef,
3251 clang::DirectoryEntryRef>>(),
3252 /*SearchPath*/ nullptr,
3253 /*RelativePath*/ nullptr,
3254 /*RequestingModule*/ nullptr,
3255 /*SuggestedModule*/ nullptr,
3256 /*IsMapped*/ nullptr,
3257 /*IsFrameworkFound*/ nullptr,
3258 /*SkipCache*/ false,
3259 /*BuildSystemModule*/ false,
3260 /*OpenFile*/ false,
3261 /*CacheFail*/ false);
3262 if (FE) {
3263 // check in the source manager if the file is actually loaded
3264 clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3265 // this works only with header (and source) files...
3266 clang::FileID FID = SM.translateFile(*FE);
3267 if (!FID.isInvalid() && FID.getHashValue() == 0)
3268 return kFALSE;
3269 else {
3270 clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3271 if (SLocE.isFile() && !SLocE.getFile().getContentCache().getBufferIfLoaded())
3272 return kFALSE;
3273 if (!FID.isInvalid())
3274 return kTRUE;
3275 }
3276 // ...then check shared library again, but with full path now
3277 sFilename = FE->getName().str();
3279 && fileMap.count(sFilename.Data())) {
3280 return kTRUE;
3281 }
3282 }
3283 return kFALSE;
3284}
3285
3286
3287#if defined(R__MACOSX)
3288
3289////////////////////////////////////////////////////////////////////////////////
3290/// Check if lib is in the dynamic linker cache, returns true if it is, and if so,
3291/// modifies the library file name parameter `lib` from `/usr/lib/libFOO.dylib`
3292/// to `-lFOO` such that it can be passed to the linker.
3293/// This is a unique feature of macOS 11.
3294
3295static bool R__UpdateLibFileForLinking(TString &lib)
3296{
3297 const char *mapfile = nullptr;
3298#if __x86_64__
3299 mapfile = "/System/Library/dyld/dyld_shared_cache_x86_64.map";
3300#elif __arm64__
3301 mapfile = "/System/Library/dyld/dyld_shared_cache_arm64e.map";
3302#else
3303 #error unsupported architecture
3304#endif
3305 if (std::ifstream cacheMap{mapfile}) {
3306 std::string line;
3307 while (getline(cacheMap, line)) {
3308 if (line.find(lib) != std::string::npos) {
3309 lib.ReplaceAll("/usr/lib/lib","-l");
3310 lib.ReplaceAll(".dylib","");
3311 return true;
3312 }
3313 }
3314 return false;
3315 }
3316 return false;
3317}
3318#endif // R__MACOSX
3319
3320#if defined (R__LINUX) || defined (R__FBSD)
3321
3322////////////////////////////////////////////////////////////////////////////////
3323/// Callback for dl_iterate_phdr(), see `man dl_iterate_phdr`.
3324/// Collects opened libraries.
3325
3326static int callback_for_dl_iterate_phdr(struct dl_phdr_info *info, size_t size, void *data)
3327{
3328 // This function is called through UpdateListOfLoadedSharedLibraries() which is locked.
3329 static std::unordered_set<decltype(info->dlpi_addr)> sKnownLoadedLibBaseAddrs;
3330
3331 auto newLibs = static_cast<std::vector<std::string>*>(data);
3332 if (!sKnownLoadedLibBaseAddrs.count(info->dlpi_addr)) {
3333 // Skip \0, "", and kernel pseudo-libs linux-vdso.so.1 or linux-gate.so.1
3334 if (info->dlpi_name && info->dlpi_name[0]
3335#if defined(R__FBSD)
3336 //skip the executable (with null addr)
3337 && info->dlpi_addr
3338 //has no path
3339 && strncmp(info->dlpi_name, "[vdso]", 6)
3340 //the linker does not like to be mmapped
3341 //causes a crash in cling::DynamicLibraryManager::loadLibrary())
3342 //with error message "mmap of entire address space failed: Cannot allocate memory"
3343 && strncmp(info->dlpi_name, "/libexec/ld-elf.so.1", 20)
3344#endif
3345 && strncmp(info->dlpi_name, "linux-vdso.so", 13)
3346 && strncmp(info->dlpi_name, "linux-vdso32.so", 15)
3347 && strncmp(info->dlpi_name, "linux-vdso64.so", 15)
3348 && strncmp(info->dlpi_name, "linux-gate.so", 13))
3349 newLibs->emplace_back(info->dlpi_name);
3350 sKnownLoadedLibBaseAddrs.insert(info->dlpi_addr);
3351 }
3352 // No matter what the doc says, return != 0 means "stop the iteration".
3353 return 0;
3354}
3355
3356#endif // R__LINUX || R__FBSD
3357
3358
3359////////////////////////////////////////////////////////////////////////////////
3360
3362{
3363#if defined(R__WIN32) || defined(__CYGWIN__)
3364 HMODULE hModules[1024];
3365 void *hProcess;
3366 unsigned long cbModules;
3367 unsigned int i;
3368 hProcess = (void *)::GetCurrentProcess();
3370 // start at 1 to skip the executable itself
3371 for (i = 1; i < (cbModules / sizeof(void *)); i++) {
3372 static const int bufsize = 260;
3373 wchar_t winname[bufsize];
3374 char posixname[bufsize];
3376#if defined(__CYGWIN__)
3378#else
3379 std::wstring wpath = winname;
3380 std::replace(wpath.begin(), wpath.end(), '\\', '/');
3381 string path(wpath.begin(), wpath.end());
3382 strncpy(posixname, path.c_str(), bufsize);
3383#endif
3386 }
3387 }
3388#elif defined(R__MACOSX)
3389 // fPrevLoadedDynLibInfo stores the *next* image index to look at
3390 uint32_t imageIndex = (uint32_t) (size_t) fPrevLoadedDynLibInfo;
3391
3393 // Skip non-dylibs
3394 if (mh->filetype == MH_DYLIB) {
3395 if (const char* imageName = _dyld_get_image_name(imageIndex)) {
3397 }
3398 }
3399
3400 ++imageIndex;
3401 }
3402 fPrevLoadedDynLibInfo = (void*)(size_t)imageIndex;
3403#elif defined(R__LINUX) || defined(R__FBSD)
3404 // fPrevLoadedDynLibInfo is unused on Linux.
3405 (void) fPrevLoadedDynLibInfo;
3406
3407 std::vector<std::string> newLibs;
3409 for (auto &&lib: newLibs)
3410 RegisterLoadedSharedLibrary(lib.c_str());
3411#else
3412 Error("TCling::UpdateListOfLoadedSharedLibraries",
3413 "Platform not supported!");
3414#endif
3415}
3416
3417namespace {
3418template <int N>
3419static bool StartsWithStrLit(const char *haystack, const char (&needle)[N]) {
3420 return !strncmp(haystack, needle, N - 1);
3421}
3422}
3423
3424////////////////////////////////////////////////////////////////////////////////
3425/// Register a new shared library name with the interpreter; add it to
3426/// fSharedLibs.
3427
3429{
3430 // Ignore NULL filenames, aka "the process".
3431 if (!filename) return;
3432
3433 // Tell the interpreter that this library is available; all libraries can be
3434 // used to resolve symbols.
3435 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3436 if (!DLM->isLibraryLoaded(filename)) {
3437 DLM->loadLibrary(filename, true /*permanent*/, true /*resolved*/);
3438 }
3439
3440#if defined(R__MACOSX)
3441 // Check that this is not a system library that does not exist on disk.
3442 auto lenFilename = strlen(filename);
3443 auto isInMacOSSystemDir = [](const char *fn) {
3444 return StartsWithStrLit(fn, "/usr/lib/") || StartsWithStrLit(fn, "/System/Library/");
3445 };
3446 if (!strcmp(filename, "cl_kernels") // yepp, no directory
3447
3448 // These we should not link with (e.g. because they forward to .tbd):
3449 || StartsWithStrLit(filename, "/usr/lib/system/")
3450 || StartsWithStrLit(filename, "/usr/lib/libc++")
3451 || StartsWithStrLit(filename, "/System/Library/Frameworks/")
3452 || StartsWithStrLit(filename, "/System/Library/PrivateFrameworks/")
3453 || StartsWithStrLit(filename, "/System/Library/CoreServices/")
3454 || StartsWithStrLit(filename, "/usr/lib/libSystem")
3455 || StartsWithStrLit(filename, "/usr/lib/libstdc++")
3456 || StartsWithStrLit(filename, "/usr/lib/libicucore")
3457 || StartsWithStrLit(filename, "/usr/lib/libbsm")
3458 || StartsWithStrLit(filename, "/usr/lib/libobjc")
3459 || StartsWithStrLit(filename, "/usr/lib/libresolv")
3460 || StartsWithStrLit(filename, "/usr/lib/libauto")
3461 || StartsWithStrLit(filename, "/usr/lib/libcups")
3462 || StartsWithStrLit(filename, "/usr/lib/libDiagnosticMessagesClient")
3463 || StartsWithStrLit(filename, "/usr/lib/liblangid")
3464 || StartsWithStrLit(filename, "/usr/lib/libCRFSuite")
3465 || StartsWithStrLit(filename, "/usr/lib/libpam")
3466 || StartsWithStrLit(filename, "/usr/lib/libOpenScriptingUtil")
3467 || StartsWithStrLit(filename, "/usr/lib/libextension")
3468 || StartsWithStrLit(filename, "/usr/lib/libAudioToolboxUtility")
3469 || StartsWithStrLit(filename, "/usr/lib/liboah")
3470 || StartsWithStrLit(filename, "/usr/lib/libRosetta")
3471 || StartsWithStrLit(filename, "/usr/lib/libCoreEntitlements")
3472 || StartsWithStrLit(filename, "/usr/lib/libssl.")
3473 || StartsWithStrLit(filename, "/usr/lib/libcrypto.")
3474
3475 // The system lib is likely in macOS's blob.
3477
3478 // "Link against the umbrella framework 'System.framework' instead"
3479 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_kernel")
3480 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_platform")
3481 || StartsWithStrLit(filename, "/usr/lib/system/libsystem_pthread")
3482
3483 // "cannot link directly with dylib/framework, your binary is not an allowed client of
3484 // /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/
3485 // SDKs/MacOSX.sdk/usr/lib/libAudioToolboxUtility.tbd for architecture x86_64
3486 || (lenFilename > 4 && !strcmp(filename + lenFilename - 4, ".tbd")))
3487 return;
3490 filename = sFileName.Data();
3491#elif defined(__CYGWIN__)
3492 // Check that this is not a system library
3493 static const int bufsize = 260;
3494 char posixwindir[bufsize];
3495 char *windir = getenv("WINDIR");
3496 if (windir)
3498 else
3499 snprintf(posixwindir, sizeof(posixwindir), "/Windows/");
3500 if (strstr(filename, posixwindir) ||
3501 strstr(filename, "/usr/bin/cyg"))
3502 return;
3503#elif defined(R__WIN32)
3504 if (strstr(filename, "/Windows/"))
3505 return;
3506#elif defined (R__LINUX)
3507 if (strstr(filename, "/ld-linux")
3508 || strstr(filename, "linux-gnu/")
3509 || strstr(filename, "/libstdc++.")
3510 || strstr(filename, "/libgcc")
3511 || strstr(filename, "/libc.")
3512 || strstr(filename, "/libdl.")
3513 || strstr(filename, "/libm."))
3514 return;
3515#endif
3516 // Update string of available libraries.
3517 if (!fSharedLibs.IsNull()) {
3518 fSharedLibs.Append(" ");
3519 }
3521}
3522
3523////////////////////////////////////////////////////////////////////////////////
3524/// Load a library file in cling's memory.
3525/// if 'system' is true, the library is never unloaded.
3526/// Return 0 on success, -1 on failure.
3527
3529{
3530 assert(!IsFromRootCling() && "Trying to load library from rootcling!");
3531
3532 // Used to return 0 on success, 1 on duplicate, -1 on failure, -2 on "fatal".
3534 cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3535 std::string canonLib = DLM->lookupLibrary(filename);
3536 cling::DynamicLibraryManager::LoadLibResult res
3537 = cling::DynamicLibraryManager::kLoadLibNotFound;
3538 if (!canonLib.empty()) {
3539 if (system)
3540 res = DLM->loadLibrary(filename, system, true);
3541 else {
3542 // For the non system libs, we'd like to be able to unload them.
3543 // FIXME: Here we lose the information about kLoadLibAlreadyLoaded case.
3544 cling::Interpreter::CompilationResult compRes;
3545 HandleInterpreterException(GetMetaProcessorImpl(), Form(".L %s", canonLib.c_str()), compRes, /*cling::Value*/nullptr);
3546 if (compRes == cling::Interpreter::kSuccess)
3547 res = cling::DynamicLibraryManager::kLoadLibSuccess;
3548 }
3549 }
3550
3551 if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3553 }
3554 switch (res) {
3555 case cling::DynamicLibraryManager::kLoadLibSuccess: return 0;
3556 case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded: return 1;
3557 default: break;
3558 };
3559 return -1;
3560}
3561
3562////////////////////////////////////////////////////////////////////////////////
3563/// Load a macro file in cling's memory.
3564
3565void TCling::LoadMacro(const char* filename, EErrorCode* error)
3566{
3567 ProcessLine(Form(".L %s", filename), error);
3568}
3569
3570////////////////////////////////////////////////////////////////////////////////
3571/// Let cling process a command line asynch.
3572
3574{
3575 return ProcessLine(line, error);
3576}
3577
3578////////////////////////////////////////////////////////////////////////////////
3579/// Let cling process a command line synchronously, i.e we are waiting
3580/// it will be finished.
3581
3583{
3585 if (gApplication) {
3586 if (gApplication->IsCmdThread()) {
3587 return ProcessLine(line, error);
3588 }
3589 return 0;
3590 }
3591 return ProcessLine(line, error);
3592}
3593
3594////////////////////////////////////////////////////////////////////////////////
3595/// Directly execute an executable statement (e.g. "func()", "3+5", etc.
3596/// however not declarations, like "Int_t x;").
3597
3599{
3600#ifdef R__WIN32
3601 // Test on ApplicationImp not being 0 is needed because only at end of
3602 // TApplication ctor the IsLineProcessing flag is set to 0, so before
3603 // we can not use it.
3605 while (gROOT->IsLineProcessing() && !gApplication) {
3606 Warning("Calc", "waiting for cling thread to free");
3607 gSystem->Sleep(500);
3608 }
3609 gROOT->SetLineIsProcessing();
3610 }
3611#endif // R__WIN32
3613 if (error) {
3614 *error = TInterpreter::kNoError;
3615 }
3616 cling::Value valRef;
3617 cling::Interpreter::CompilationResult cr = cling::Interpreter::kFailure;
3618 try {
3619 cr = fInterpreter->evaluate(line, valRef);
3620 }
3621 catch (cling::InterpreterException& ex)
3622 {
3623 Error("Calc", "%s.\n%s", ex.what(), "Evaluation of your expression was aborted.");
3624 ex.diagnose();
3625 cr = cling::Interpreter::kFailure;
3626 }
3627
3628 if (cr != cling::Interpreter::kSuccess) {
3629 // Failure in compilation.
3630 if (error) {
3631 // Note: Yes these codes are weird.
3633 }
3634 return 0L;
3635 }
3636 if (!valRef.isValid()) {
3637 // Failure at runtime.
3638 if (error) {
3639 // Note: Yes these codes are weird.
3640 *error = TInterpreter::kDangerous;
3641 }
3642 return 0L;
3643 }
3644
3645 if (valRef.isVoid()) {
3646 return 0;
3647 }
3648
3650#ifdef R__WIN32
3652 gROOT->SetLineHasBeenProcessed();
3653 }
3654#endif // R__WIN32
3655 return valRef.castAs<Longptr_t>();
3656}
3657
3658////////////////////////////////////////////////////////////////////////////////
3659/// Set a getline function to call when input is needed.
3660
3661void TCling::SetGetline(const char * (*getlineFunc)(const char* prompt),
3662 void (*histaddFunc)(const char* line))
3663{
3664 // If cling offers a replacement for G__pause(), it would need to
3665 // also offer a way to customize at least the history recording.
3666
3667#if defined(R__MUST_REVISIT)
3668#if R__MUST_REVISIT(6,2)
3669 Warning("SetGetline","Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3670#endif
3671#endif
3672}
3673
3674////////////////////////////////////////////////////////////////////////////////
3675/// Helper function to increase the internal Cling count of transactions
3676/// that change the AST.
3677
3678Bool_t TCling::HandleNewTransaction(const cling::Transaction &T)
3679{
3681
3682 if ((std::distance(T.decls_begin(), T.decls_end()) != 1)
3683 || T.deserialized_decls_begin() != T.deserialized_decls_end()
3684 || T.macros_begin() != T.macros_end()
3685 || ((!T.getFirstDecl().isNull()) && ((*T.getFirstDecl().begin()) != T.getWrapperFD()))) {
3687 return true;
3688 }
3689 return false;
3690}
3691
3692////////////////////////////////////////////////////////////////////////////////
3693/// Delete object from cling symbol table so it can not be used anymore.
3694/// cling objects are always on the heap.
3695
3697{
3698 // NOTE: When replacing the mutex by a ReadWrite mutex, we **must**
3699 // put in place the Read/Write part here. Keeping the write lock
3700 // here is 'catasptrophic' for scaling as it means that ALL calls
3701 // to RecursiveRemove will take the write lock and performance
3702 // of many threads trying to access the write lock at the same
3703 // time is relatively bad.
3705 // Note that fgSetOfSpecials is supposed to be updated by TClingCallbacks::tryFindROOTSpecialInternal
3706 // (but isn't at the moment).
3707 if (obj->IsOnHeap() && fgSetOfSpecials && !((std::set<TObject*>*)fgSetOfSpecials)->empty()) {
3708 std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)fgSetOfSpecials)->find(obj);
3709 if (iSpecial != ((std::set<TObject*>*)fgSetOfSpecials)->end()) {
3711 DeleteGlobal(obj);
3712 ((std::set<TObject*>*)fgSetOfSpecials)->erase(iSpecial);
3713 }
3714 }
3715}
3716
3717////////////////////////////////////////////////////////////////////////////////
3718/// Pressing Ctrl+C should forward here. In the case where we have had
3719/// continuation requested we must reset it.
3720
3722{
3723 fMetaProcessor->cancelContinuation();
3724 // Reset the Cling state to the state saved by the last call to
3725 // TCling::SaveContext().
3726#if defined(R__MUST_REVISIT)
3727#if R__MUST_REVISIT(6,2)
3729 Warning("Reset","Cling should support the equivalent of scratch_upto(&fDictPos)");
3730#endif
3731#endif
3732}
3733
3734////////////////////////////////////////////////////////////////////////////////
3735/// Reset the Cling state to its initial state.
3736
3738{
3739#if defined(R__MUST_REVISIT)
3740#if R__MUST_REVISIT(6,2)
3742 Warning("ResetAll","Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3743#endif
3744#endif
3745}
3746
3747////////////////////////////////////////////////////////////////////////////////
3748/// Reset in Cling the list of global variables to the state saved by the last
3749/// call to TCling::SaveGlobalsContext().
3750///
3751/// Note: Right now, all we do is run the global destructors.
3752
3754{
3756 // TODO:
3757 // Here we should iterate over the transactions (N-3) and revert.
3758 // N-3 because the first three internal to cling.
3759
3760 fInterpreter->runAndRemoveStaticDestructors();
3761}
3762
3763////////////////////////////////////////////////////////////////////////////////
3764/// Reset the Cling 'user' global objects/variables state to the state saved by the last
3765/// call to TCling::SaveGlobalsContext().
3766
3768{
3769#if defined(R__MUST_REVISIT)
3770#if R__MUST_REVISIT(6,2)
3772 Warning("ResetGlobalVar","Cling should support the equivalent of resetglobalvar(obj)");
3773#endif
3774#endif
3775}
3776
3777////////////////////////////////////////////////////////////////////////////////
3778/// Rewind Cling dictionary to the point where it was before executing
3779/// the current macro. This function is typically called after SEGV or
3780/// ctlr-C after doing a longjmp back to the prompt.
3781
3783{
3784#if defined(R__MUST_REVISIT)
3785#if R__MUST_REVISIT(6,2)
3787 Warning("RewindDictionary","Cling should provide a way to revert transaction similar to rewinddictionary()");
3788#endif
3789#endif
3790}
3791
3792////////////////////////////////////////////////////////////////////////////////
3793/// Delete obj from Cling symbol table so it cannot be accessed anymore.
3794/// Returns 1 in case of success and 0 in case object was not in table.
3795
3797{
3798#if defined(R__MUST_REVISIT)
3799#if R__MUST_REVISIT(6,2)
3801 Warning("DeleteGlobal","Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3802#endif
3803#endif
3804 return 0;
3805}
3806
3807////////////////////////////////////////////////////////////////////////////////
3808/// Undeclare obj called name.
3809/// Returns 1 in case of success, 0 for failure.
3810
3812{
3813#if defined(R__MUST_REVISIT)
3814#if R__MUST_REVISIT(6,2)
3815 Warning("DeleteVariable","should do more that just reseting the value to zero");
3816#endif
3817#endif
3818
3820 llvm::StringRef srName(name);
3821 const char* unscopedName = name;
3822 llvm::StringRef::size_type posScope = srName.rfind("::");
3823 const clang::DeclContext* declCtx = nullptr;
3824 if (posScope != llvm::StringRef::npos) {
3825 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3826 const clang::Decl* scopeDecl
3827 = lh.findScope(srName.substr(0, posScope),
3828 cling::LookupHelper::WithDiagnostics);
3829 if (!scopeDecl) {
3830 Error("DeleteVariable", "Cannot find enclosing scope for variable %s",
3831 name);
3832 return 0;
3833 }
3834 declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3835 if (!declCtx) {
3836 Error("DeleteVariable",
3837 "Enclosing scope for variable %s is not a declaration context",
3838 name);
3839 return 0;
3840 }
3841 unscopedName += posScope + 2;
3842 }
3843 // Could trigger deserialization of decls.
3844 cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
3845 clang::NamedDecl* nVarDecl
3846 = cling::utils::Lookup::Named(&fInterpreter->getSema(), unscopedName, declCtx);
3847 if (!nVarDecl) {
3848 Error("DeleteVariable", "Unknown variable %s", name);
3849 return 0;
3850 }
3851 clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3852 if (!varDecl) {
3853 Error("DeleteVariable", "Entity %s is not a variable", name);
3854 return 0;
3855 }
3856
3857 clang::QualType qType = varDecl->getType();
3858 const clang::Type* type = qType->getUnqualifiedDesugaredType();
3859 // Cannot set a reference's address to nullptr; the JIT can place it
3860 // into read-only memory (ROOT-7100).
3861 if (type->isPointerType()) {
3862 int** ppInt = (int**)fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3863 // set pointer to invalid.
3864 if (ppInt) *ppInt = nullptr;
3865 }
3866 return 1;
3867}
3868
3869////////////////////////////////////////////////////////////////////////////////
3870/// Save the current Cling state.
3871
3873{
3874#if defined(R__MUST_REVISIT)
3875#if R__MUST_REVISIT(6,2)
3877 Warning("SaveContext","Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3878#endif
3879#endif
3880}
3881
3882////////////////////////////////////////////////////////////////////////////////
3883/// Save the current Cling state of global objects.
3884
3886{
3887#if defined(R__MUST_REVISIT)
3888#if R__MUST_REVISIT(6,2)
3890 Warning("SaveGlobalsContext","Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3891#endif
3892#endif
3893}
3894
3895////////////////////////////////////////////////////////////////////////////////
3896/// No op: see TClingCallbacks (used to update the list of globals)
3897
3901
3902////////////////////////////////////////////////////////////////////////////////
3903/// No op: see TClingCallbacks (used to update the list of global functions)
3904
3908
3909////////////////////////////////////////////////////////////////////////////////
3910/// No op: see TClingCallbacks (used to update the list of types)
3911
3913{
3914}
3915
3916////////////////////////////////////////////////////////////////////////////////
3917/// Check in what order the member of a tuple are layout.
3918enum class ETupleOrdering {
3919 kAscending,
3922};
3923
3929
3935
3937{
3938 std::tuple<int,double> value;
3941
3942 size_t offset0 = ((char*)&(std::get<0>(value))) - ((char*)&value);
3943 size_t offset1 = ((char*)&(std::get<1>(value))) - ((char*)&value);
3944
3945 size_t ascOffset0 = ((char*)&(asc._0)) - ((char*)&asc);
3946 size_t ascOffset1 = ((char*)&(asc._1)) - ((char*)&asc);
3947
3948 size_t desOffset0 = ((char*)&(des._0)) - ((char*)&des);
3949 size_t desOffset1 = ((char*)&(des._1)) - ((char*)&des);
3950
3951 if (offset0 == ascOffset0 && offset1 == ascOffset1) {
3953 } else if (offset0 == desOffset0 && offset1 == desOffset1) {
3955 } else {
3957 }
3958}
3959
3960static std::string AlternateTuple(const char *classname, const cling::LookupHelper& lh, Bool_t silent)
3961{
3963 std::string alternateName = "TEmulatedTuple";
3964 alternateName.append( classname + 5 );
3965
3966 std::string fullname = "ROOT::Internal::" + alternateName;
3967 if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
3968 /*resultType*/nullptr, /* intantiateTemplate= */ false))
3969 return fullname;
3970
3971 {
3972 // Check if we can produce the tuple
3973 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
3974 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
3975 auto deleter = [](TypeInfo_t *type) {
3976 gInterpreter->TypeInfo_Delete(type);
3977 };
3978 std::unique_ptr<TypeInfo_t, decltype(deleter)> type{ gInterpreter->TypeInfo_Factory(), deleter };
3979 while (iter != theEnd) {
3980 gInterpreter->TypeInfo_Init(type.get(), iter->c_str());
3981 if (gInterpreter->TypeInfo_Property(type.get()) & kIsNotReacheable) {
3982 if (!silent)
3983 Error("Load","Could not declare alternate type for %s since %s (or one of its context) is private or protected",
3984 classname, iter->c_str());
3985 return "";
3986 }
3987 ++iter;
3988 }
3989 }
3990
3991 std::string guard_name;
3993 std::ostringstream guard;
3994 guard << "ROOT_INTERNAL_TEmulated_";
3995 guard << guard_name;
3996
3997 std::ostringstream alternateTuple;
3998 alternateTuple << "#ifndef " << guard.str() << "\n";
3999 alternateTuple << "#define " << guard.str() << "\n";
4000 alternateTuple << "namespace ROOT { namespace Internal {\n";
4001 alternateTuple << "template <class... Types> struct TEmulatedTuple;\n";
4002 alternateTuple << "template <> struct " << alternateName << " {\n";
4003
4004 // This could also be a compile time choice ...
4005 switch(IsTupleAscending()) {
4007 unsigned int nMember = 0;
4008 auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple).
4009 auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
4010 while (iter != theEnd) {
4011 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4012 ++iter;
4013 ++nMember;
4014 }
4015 break;
4016 }
4018 unsigned int nMember = tupleContent.fElements.size() - 3;
4019 auto iter = tupleContent.fElements.rbegin() + 1; // skip the 'stars'.
4020 auto theEnd = tupleContent.fElements.rend() - 1; // Skip the template name (tuple).
4021 while (iter != theEnd) {
4022 alternateTuple << " " << *iter << " _" << nMember << ";\n";
4023 ++iter;
4024 --nMember;
4025 }
4026 break;
4027 }
4029 Fatal("TCling::SetClassInfo::AlternateTuple",
4030 "Layout of std::tuple on this platform is unexpected.");
4031 break;
4032 }
4033 }
4034
4035 alternateTuple << "};\n";
4036 alternateTuple << "}}\n";
4037 alternateTuple << "#endif\n";
4038 if (!gCling->Declare(alternateTuple.str().c_str()))
4039 {
4040 // Declare is not silent (yet?), so add an explicit error message
4041 // to indicate the consequence of the syntax errors.
4042 Error("Load","Could not declare %s",alternateName.c_str());
4043 return "";
4044 }
4045 alternateName = "ROOT::Internal::" + alternateName;
4046 return alternateName;
4047}
4048
4049////////////////////////////////////////////////////////////////////////////////
4050/// Set pointer to the TClingClassInfo in TClass.
4051/// If 'reload' is true, (attempt to) generate a new ClassInfo even if we
4052/// already have one.
4053
4055{
4056 // We are shutting down, there is no point in reloading, it only triggers
4057 // redundant deserializations.
4058 if (fIsShuttingDown) {
4059 // Remove the decl_id from the DeclIdToTClass map
4060 if (cl->fClassInfo) {
4063 // Test again as another thread may have set fClassInfo to nullptr.
4064 if (TClinginfo) {
4066 }
4067 delete TClinginfo;
4068 cl->fClassInfo = nullptr;
4069 }
4070 return;
4071 }
4072
4074 if (cl->fClassInfo && !reload) {
4075 return;
4076 }
4077 //Remove the decl_id from the DeclIdToTClass map
4079 if (TClinginfo) {
4081 }
4082 delete TClinginfo;
4083 cl->fClassInfo = nullptr;
4084 std::string name(cl->GetName());
4085
4086 auto SetWithoutClassInfoState = [](TClass *cl)
4087 {
4088 if (cl->fState != TClass::kHasTClassInit) {
4089 if (cl->fStreamerInfo->GetEntries() != 0) {
4091 } else {
4093 }
4094 }
4095 };
4096 // Handle the special case of 'tuple' where we ignore the real implementation
4097 // details and just overlay a 'simpler'/'simplistic' version that is easy
4098 // for the I/O to understand and handle.
4099 if (strncmp(cl->GetName(),"tuple<",std::char_traits<char>::length("tuple<"))==0) {
4100 if (!reload)
4101 name = AlternateTuple(cl->GetName(), fInterpreter->getLookupHelper(), silent);
4102 if (reload || name.empty()) {
4103 // We could not generate the alternate
4105 return;
4106 }
4107 }
4108
4110 // FIXME: Rather than adding an option to the TClingClassInfo, we should consider combining code
4111 // that is currently in the caller (like SetUnloaded) that disable AutoLoading and AutoParsing and
4112 // code is in the callee (disabling template instantiation) and end up with a more explicit class:
4113 // TClingClassInfoReadOnly.
4115 if (!info->IsValid()) {
4117 delete info;
4118 return;
4119 }
4120 cl->fClassInfo = (ClassInfo_t*)info; // Note: We are transferring ownership here.
4121 // In case a class contains an external enum, the enum will be seen as a
4122 // class. We must detect this special case and make the class a Zombie.
4123 // Here we assume that a class has at least one method.
4124 // We can NOT call TClass::Property from here, because this method
4125 // assumes that the TClass is well formed to do a lot of information
4126 // caching. The method SetClassInfo (i.e. here) is usually called during
4127 // the building phase of the TClass, hence it is NOT well formed yet.
4129 if (
4130 info->IsValid() &&
4131 !(info->Property() & (kIsClass | kIsStruct | kIsNamespace))
4132 ) {
4134 }
4135 if (!info->IsLoaded()) {
4136 if (info->Property() & (kIsNamespace)) {
4137 // Namespaces can have info but no corresponding CINT dictionary
4138 // because they are auto-created if one of their contained
4139 // classes has a dictionary.
4141 }
4142 // this happens when no dictionary is available
4143 delete info;
4144 cl->fClassInfo = nullptr;
4145 }
4146 if (zombieCandidate && !cl->GetCollectionType()) {
4147 cl->MakeZombie();
4148 }
4149 // If we reach here, the info was valid (See early returns).
4150 if (cl->fState != TClass::kHasTClassInit) {
4151 if (cl->fClassInfo) {
4153 } else {
4154// if (TClassEdit::IsSTLCont(cl->GetName()) {
4155// There will be an emulated collection proxy, is that the same?
4156// cl->fState = TClass::kEmulated;
4157// } else {
4158 if (cl->fStreamerInfo->GetEntries() != 0) {
4160 } else {
4162 }
4163// }
4164 }
4165 }
4166 if (cl->fClassInfo) {
4167 TClass::AddClassToDeclIdMap(((TClingClassInfo*)cl->fClassInfo)->GetDeclId(), cl);
4168 }
4169}
4170
4171////////////////////////////////////////////////////////////////////////////////
4172/// Checks if an entity with the specified name is defined in Cling.
4173/// Returns kUnknown if the entity is not defined.
4174/// Returns kWithClassDefInline if the entity exists and has a ClassDefInline
4175/// Returns kKnown if the entity is defined.
4176///
4177/// By default, structs, namespaces, classes, enums and unions are looked for.
4178/// If the flag isClassOrNamespaceOnly is true, classes, structs and
4179/// namespaces only are considered. I.e. if the name is an enum or a union,
4180/// the returned value is false.
4181///
4182/// In the case where the class is not loaded and belongs to a namespace
4183/// or is nested, looking for the full class name is outputting a lots of
4184/// (expected) error messages. Currently the only way to avoid this is to
4185/// specifically check that each level of nesting is already loaded.
4186/// In case of templates the idea is that everything between the outer
4187/// '<' and '>' has to be skipped, e.g.: `aap<pippo<noot>::klaas>::a_class`
4188
4191{
4193 static const char *anonEnum = "anonymous enum ";
4194 static const int cmplen = strlen(anonEnum);
4195
4196 if (fIsShuttingDown || 0 == strncmp(name, anonEnum, cmplen)) {
4197 return kUnknown;
4198 }
4199
4200 // Do not turn on the AutoLoading if it is globally off.
4202
4203 // Avoid the double search below in case the name is a fundamental type
4204 // or typedef to a fundamental type.
4205 THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
4206 TDataType *fundType = (TDataType *)typeTable->THashTable::FindObject( name );
4207
4209 && fundType->GetType() > 0) {
4210 // Fundamental type, no a class.
4211 return kUnknown;
4212 }
4213
4214 // Migrated from within TClass::GetClass
4215 // If we want to know if a class or a namespace with this name exists in the
4216 // interpreter and this is an enum in the type system, before or after loading
4217 // according to the autoload function argument, return kUnknown.
4219 return kUnknown;
4220
4221 const char *classname = name;
4222
4223 // RAII to suspend and restore auto-loading and auto-parsing based on some external conditions.
4225 int fStoreAutoLoad = 0;
4226 int fStoreAutoParse = 0;
4227 bool fSuspendedAutoParse = false;
4228 public:
4230 fStoreAutoLoad = ((TCling*)gCling)->SetClassAutoLoading(autoload);
4231 }
4232
4233 void SuspendAutoParsing() {
4234 fSuspendedAutoParse = true;
4235 fStoreAutoParse = ((TCling*)gCling)->SetSuspendAutoParsing(true);
4236 }
4237
4240 ((TCling*)gCling)->SetSuspendAutoParsing(fStoreAutoParse);
4241 ((TCling*)gCling)->SetClassAutoLoading(fStoreAutoLoad);
4242 }
4243 };
4244
4246 if (TClassEdit::IsStdPair(classname) || TClassEdit::IsStdPairBase(classname))
4247 autoLoadParseRAII.SuspendAutoParsing();
4248
4249 // First we want to check whether the decl exist, but _without_
4250 // generating any template instantiation. However, the lookup
4251 // still will create a forward declaration of the class template instance
4252 // if it exist. In this case, the return value of findScope will still
4253 // be zero but the type will be initialized.
4254 // Note in the corresponding code in ROOT 5, CINT was not instantiating
4255 // this forward declaration.
4256 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4257 const clang::Type *type = nullptr;
4258 const clang::Decl *decl
4259 = lh.findScope(classname,
4260 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4261 : cling::LookupHelper::NoDiagnostics,
4262 &type, /* intantiateTemplate= */ false );
4263 if (!decl) {
4264 std::string buf = TClassEdit::InsertStd(classname);
4265 decl = lh.findScope(buf,
4266 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4267 : cling::LookupHelper::NoDiagnostics,
4268 &type,false);
4269 }
4270
4271 if (type) {
4272 // If decl==0 and the type is valid, then we have a forward declaration.
4273 if (!decl) {
4274 // If we have a forward declaration for a class template instantiation,
4275 // we want to ignore it if it was produced/induced by the call to
4276 // findScope, however we can not distinguish those from the
4277 // instantiation induce by 'soft' use (and thus also induce by the
4278 // same underlying code paths)
4279 // ['soft' use = use not requiring a complete definition]
4280 // So to reduce the amount of disruption to the existing code we
4281 // would just ignore those for STL collection, for which we really
4282 // need to have the compiled collection proxy (and thus the TClass
4283 // bootstrap).
4284 clang::ClassTemplateSpecializationDecl *tmpltDecl =
4285 llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
4286 (type->getAsCXXRecordDecl());
4287 if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
4288 // Since the point of instantiation is invalid, we 'guess' that
4289 // the 'instantiation' of the forwarded type appended in
4290 // findscope.
4292 // For STL Collection we return kUnknown.
4293 return kUnknown;
4294 }
4295 }
4296 }
4298 if (!tci.IsValid()) {
4299 return kUnknown;
4300 }
4303
4304 if (tci.Property() & propertiesMask) {
4305 bool hasClassDefInline = false;
4307 // We do not need to check for ClassDefInline when this is called from
4308 // TClass::Init, we only do it for the call from TClass::GetClass.
4309 auto hasDictionary = tci.GetMethod("Dictionary", "", false, nullptr, ROOT::kExactMatch);
4310 auto implLineFunc = tci.GetMethod("ImplFileLine", "", false, nullptr, ROOT::kExactMatch);
4311
4312 if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
4313 int lineNumber = 0;
4314 bool success = false;
4315 std::tie(success, lineNumber) =
4318 }
4319 }
4320
4321 // fprintf(stderr,"CheckClassInfo: %s had dict=%d inline=%d\n",name,hasDictionary.IsValid()
4322 // , hasClassDefInline);
4323
4324 // We are now sure that the entry is not in fact an autoload entry.
4326 return kWithClassDefInline;
4327 else
4328 return kKnown;
4329 } else {
4330 // We are now sure that the entry is not in fact an autoload entry.
4331 return kUnknown;
4332 }
4333 }
4334
4335 if (decl)
4336 return kKnown;
4337 else
4338 return kUnknown;
4339
4340 // Setting up iterator part of TClingTypedefInfo is too slow.
4341 // Copy the lookup code instead:
4342 /*
4343 TClingTypedefInfo t(fInterpreter, name);
4344 if (t.IsValid() && !(t.Property() & kIsFundamental)) {
4345 delete[] classname;
4346 return kTRUE;
4347 }
4348 */
4349
4350// const clang::Decl *decl = lh.findScope(name);
4351// if (!decl) {
4352// std::string buf = TClassEdit::InsertStd(name);
4353// decl = lh.findScope(buf);
4354// }
4355
4356// return (decl);
4357}
4358
4359////////////////////////////////////////////////////////////////////////////////
4360/// Return true if there is a class template by the given name ...
4361
4363{
4364 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
4365 // Interpreter transaction ahead, needs locking
4367 const clang::Decl *decl
4368 = lh.findClassTemplate(name,
4369 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4370 : cling::LookupHelper::NoDiagnostics);
4371 if (!decl) {
4372 std::string strname = "std::";
4373 strname += name;
4374 decl = lh.findClassTemplate(strname,
4375 gDebug > 5 ? cling::LookupHelper::WithDiagnostics
4376 : cling::LookupHelper::NoDiagnostics);
4377 }
4378 return nullptr != decl;
4379}
4380
4381////////////////////////////////////////////////////////////////////////////////
4382/// Create list of pointers to base class(es) for TClass cl.
4383
4385{
4387 if (cl->fBase) {
4388 return;
4389 }
4391 if (!tci) return;
4393 TList *listOfBase = new TList;
4394 while (t.Next()) {
4395 // if name cannot be obtained no use to put in list
4396 if (t.IsValid() && t.Name()) {
4398 listOfBase->Add(new TBaseClass((BaseClassInfo_t *)a, cl));
4399 }
4400 }
4401 // Now that is complete, publish it.
4402 cl->fBase = listOfBase;
4403}
4404
4405////////////////////////////////////////////////////////////////////////////////
4406/// Create list of pointers to enums for TClass cl.
4407
4409{
4411
4412 const Decl * D;
4413 TClass* cl = enumList.GetClass();
4414 if (cl) {
4415 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4416 }
4417 else {
4418 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4419 }
4420 // Iterate on the decl of the class and get the enums.
4421 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4422 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4423 // Collect all contexts of the namespace.
4424 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4425 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4427 declIter != declEnd; ++declIter) {
4428 // Iterate on all decls for each context.
4429 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4430 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4431 if (const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4432 // Get name of the enum type.
4433 std::string buf;
4434 PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4435 llvm::raw_string_ostream stream(buf);
4436 // Don't trigger fopen of the source file to count lines:
4437 Policy.AnonymousTagLocations = false;
4438 ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
4439 stream.flush();
4440 // If the enum is unnamed we do not add it to the list of enums i.e unusable.
4441 if (!buf.empty()) {
4442 const char* name = buf.c_str();
4443 // Add the enum to the list of loaded enums.
4444 enumList.Get(ED, name);
4445 }
4446 }
4447 }
4448 }
4449 }
4450}
4451
4452////////////////////////////////////////////////////////////////////////////////
4453/// Create list of pointers to function templates for TClass cl.
4454
4456{
4458
4459 const Decl * D;
4461 if (cl) {
4462 D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4464 }
4465 else {
4466 D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4467 funcTempList = (TListOfFunctionTemplates*)gROOT->GetListOfFunctionTemplates();
4468 }
4469 // Iterate on the decl of the class and get the enums.
4470 if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4471 cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4472 // Collect all contexts of the namespace.
4473 llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4474 const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4477 // Iterate on all decls for each context.
4478 for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4479 DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4480 if (const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4481 funcTempList->Get(FTD);
4482 }
4483 }
4484 }
4485 }
4486}
4487
4488////////////////////////////////////////////////////////////////////////////////
4489/// Get the scopes representing using declarations of namespace
4490
4491std::vector<std::string> TCling::GetUsingNamespaces(ClassInfo_t *cl) const
4492{
4494 return ci->GetUsingNamespaces();
4495}
4496
4497////////////////////////////////////////////////////////////////////////////////
4498/// Create list of pointers to data members for TClass cl.
4499/// This is now a nop. The creation and updating is handled in
4500/// TListOfDataMembers.
4501
4503{
4504}
4505
4506////////////////////////////////////////////////////////////////////////////////
4507/// Create list of pointers to methods for TClass cl.
4508/// This is now a nop. The creation and updating is handled in
4509/// TListOfFunctions.
4510
4512{
4513}
4514
4515////////////////////////////////////////////////////////////////////////////////
4516/// Update the list of pointers to method for TClass cl
4517/// This is now a nop. The creation and updating is handled in
4518/// TListOfFunctions.
4519
4521{
4522}
4523
4524////////////////////////////////////////////////////////////////////////////////
4525/// Update the list of pointers to data members for TClass cl
4526/// This is now a nop. The creation and updating is handled in
4527/// TListOfDataMembers.
4528
4530{
4531}
4532
4533////////////////////////////////////////////////////////////////////////////////
4534/// Create list of pointers to method arguments for TMethod m.
4535
4537{
4539 if (m->fMethodArgs) {
4540 return;
4541 }
4542 TList *arglist = new TList;
4544 while (t.Next()) {
4545 if (t.IsValid()) {
4547 arglist->Add(new TMethodArg((MethodArgInfo_t*)a, m));
4548 }
4549 }
4550 m->fMethodArgs = arglist;
4551}
4552
4553////////////////////////////////////////////////////////////////////////////////
4554/// Return whether we are waiting for more input either because the collected
4555/// input contains unbalanced braces or last seen token was a `\` (backslash-newline)
4556
4558{
4559 return fMetaProcessor->awaitingMoreInput();
4560}
4561
4562////////////////////////////////////////////////////////////////////////////////
4563/// Generate a TClass for the given class.
4564/// Since the caller has already check the ClassInfo, let it give use the
4565/// result (via the value of emulation) rather than recalculate it.
4566
4567TClass *TCling::GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent /* = kFALSE */)
4568{
4569// For now the following line would lead to the (unwanted) instantiation
4570// of class template. This could/would need to be resurrected only if
4571// we re-introduce so sort of automatic instantiation. However this would
4572// have to include carefull look at the template parameter to avoid
4573// creating instance we can not really use (if the parameter are only forward
4574// declaration or do not have all the necessary interfaces).
4575
4576 // TClingClassInfo tci(fInterpreter, classname);
4577 // if (1 || !tci.IsValid()) {
4578
4579 Version_t version = 1;
4580 if (TClassEdit::IsSTLCont(classname)) {
4581 version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4582 }
4584 TClass *cl = new TClass(classname, version, silent);
4585 if (!emulation) {
4586 // Set the class version if the class is versioned.
4587 // Note that we cannot just call CLASS::Class_Version() as we might not have
4588 // an execution engine (when invoked from rootcling).
4589
4590 // Do not call cl->GetClassVersion(), it has side effects!
4592 if (oldvers == version && cl->GetClassInfo()) {
4593 // We have a version and it might need an update.
4595 if (llvm::isa<clang::NamespaceDecl>(cli->GetDecl())) {
4596 // Namespaces don't have class versions.
4597 return cl;
4598 }
4599 TClingMethodInfo mi = cli->GetMethod("Class_Version", "", nullptr /*poffset*/,
4602 if (!mi.IsValid()) {
4603 if (cl->TestBit(TClass::kIsTObject)) {
4604 Error("GenerateTClass",
4605