Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
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 
14 This class defines an interface to the cling C++ interpreter.
15 
16 Cling is a full ANSI compliant C++-11 interpreter based on
17 clang/LLVM technology.
18 */
19 
20 #include "TCling.h"
21 
22 #include "ROOT/FoundationUtils.hxx"
23 
24 #include "TClingBaseClassInfo.h"
25 #include "TClingCallFunc.h"
26 #include "TClingClassInfo.h"
27 #include "TClingDataMemberInfo.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 "TBaseClass.h"
44 #include "TDataMember.h"
45 #include "TMemberInspector.h"
46 #include "TMethod.h"
47 #include "TMethodArg.h"
48 #include "TFunctionTemplate.h"
49 #include "TObjArray.h"
50 #include "TObjString.h"
51 #include "TString.h"
52 #include "THashList.h"
53 #include "TOrdCollection.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"
62 #include "RConversionRuleParser.h"
63 #include "RConfigure.h"
64 #include "compiledata.h"
65 #include "TClingUtils.h"
67 #include "TVirtualStreamerInfo.h"
68 #include "TListOfDataMembers.h"
69 #include "TListOfEnums.h"
70 #include "TListOfEnumsWithLock.h"
71 #include "TListOfFunctions.h"
73 #include "TMemFile.h"
74 #include "TProtoClass.h"
75 #include "TStreamerInfo.h" // This is here to avoid to use the plugin manager
76 #include "ThreadLocalStorage.h"
77 #include "TFile.h"
78 #include "TKey.h"
79 #include "ClingRAII.h"
80 
81 #include "clang/AST/ASTContext.h"
82 #include "clang/AST/Decl.h"
83 #include "clang/AST/DeclarationName.h"
84 #include "clang/AST/GlobalDecl.h"
85 #include "clang/AST/RecordLayout.h"
86 #include "clang/AST/DeclVisitor.h"
87 #include "clang/AST/RecursiveASTVisitor.h"
88 #include "clang/AST/Type.h"
89 #include "clang/Basic/SourceLocation.h"
90 #include "clang/Basic/Specifiers.h"
91 #include "clang/Basic/TargetInfo.h"
92 #include "clang/CodeGen/ModuleBuilder.h"
93 #include "clang/Frontend/CompilerInstance.h"
94 #include "clang/Frontend/FrontendDiagnostic.h"
95 #include "clang/Lex/HeaderSearch.h"
96 #include "clang/Lex/Preprocessor.h"
97 #include "clang/Lex/PreprocessorOptions.h"
98 #include "clang/Sema/Lookup.h"
99 #include "clang/Sema/Sema.h"
100 #include "clang/Parse/Parser.h"
101 
102 #include "cling/Interpreter/ClangInternalState.h"
103 #include "cling/Interpreter/DynamicLibraryManager.h"
104 #include "cling/Interpreter/Interpreter.h"
105 #include "cling/Interpreter/LookupHelper.h"
106 #include "cling/Interpreter/Value.h"
107 #include "cling/Interpreter/Transaction.h"
108 #include "cling/MetaProcessor/MetaProcessor.h"
109 #include "cling/Utils/AST.h"
110 #include "cling/Utils/ParserStateRAII.h"
111 #include "cling/Utils/SourceNormalization.h"
112 #include "cling/Interpreter/Exception.h"
113 
114 #include "llvm/IR/GlobalValue.h"
115 #include "llvm/IR/Module.h"
116 
117 #include "llvm/Support/DynamicLibrary.h"
118 #include "llvm/Support/raw_ostream.h"
119 #include "llvm/Support/Path.h"
120 #include "llvm/Support/Process.h"
121 #include "llvm/Object/ELFObjectFile.h"
122 #include "llvm/Object/ObjectFile.h"
123 #include "llvm/Object/SymbolicFile.h"
124 #include "llvm/Support/FileSystem.h"
125 
126 #include <algorithm>
127 #include <iostream>
128 #include <cassert>
129 #include <map>
130 #include <set>
131 #include <stdexcept>
132 #include <stdint.h>
133 #include <fstream>
134 #include <sstream>
135 #include <string>
136 #include <tuple>
137 #include <typeinfo>
138 #include <unordered_map>
139 #include <utility>
140 #include <vector>
141 #include <functional>
142 
143 #ifndef R__WIN32
144 #include <cxxabi.h>
145 #define R__DLLEXPORT __attribute__ ((visibility ("default")))
146 #include <sys/stat.h>
147 #endif
148 #include <limits.h>
149 #include <stdio.h>
150 
151 #ifdef __APPLE__
152 #include <dlfcn.h>
153 #include <mach-o/dyld.h>
154 #include <mach-o/loader.h>
155 #endif // __APPLE__
156 
157 #ifdef R__UNIX
158 #include <dlfcn.h>
159 #endif
160 
161 #if defined(__CYGWIN__)
162 #include <sys/cygwin.h>
163 #define HMODULE void *
164 extern "C" {
165  __declspec(dllimport) void * __stdcall GetCurrentProcess();
166  __declspec(dllimport) bool __stdcall EnumProcessModules(void *, void **, unsigned long, unsigned long *);
167  __declspec(dllimport) unsigned long __stdcall GetModuleFileNameExW(void *, void *, wchar_t *, unsigned long);
168 }
169 #endif
170 
171 // Fragment copied from LLVM's raw_ostream.cpp
172 #if defined(_MSC_VER)
173 #ifndef STDIN_FILENO
174 # define STDIN_FILENO 0
175 #endif
176 #ifndef STDOUT_FILENO
177 # define STDOUT_FILENO 1
178 #endif
179 #ifndef STDERR_FILENO
180 # define STDERR_FILENO 2
181 #endif
182 #ifndef R__WIN32
183 //#if defined(HAVE_UNISTD_H)
184 # include <unistd.h>
185 //#endif
186 #else
187 #include "Windows4Root.h"
188 #include <Psapi.h>
189 #undef GetModuleFileName
190 #define RTLD_DEFAULT ((void *)::GetModuleHandle(NULL))
191 #define dlsym(library, function_name) ::GetProcAddress((HMODULE)library, function_name)
192 #define dlopen(library_name, flags) ::LoadLibraryA(library_name)
193 #define dlclose(library) ::FreeLibrary((HMODULE)library)
194 #define R__DLLEXPORT __declspec(dllexport)
195 #endif
196 #endif
197 
198 //______________________________________________________________________________
199 // Infrastructure to detect and react to libCling being teared down.
200 //
201 namespace {
202  class TCling_UnloadMarker {
203  public:
204  ~TCling_UnloadMarker() {
205  if (ROOT::Internal::gROOTLocal) {
206  ROOT::Internal::gROOTLocal->~TROOT();
207  }
208  }
209  };
210  static TCling_UnloadMarker gTClingUnloadMarker;
211 }
212 
213 
214 
215 //______________________________________________________________________________
216 // These functions are helpers for debugging issues with non-LLVMDEV builds.
217 //
218 R__DLLEXPORT clang::DeclContext* TCling__DEBUG__getDeclContext(clang::Decl* D) {
219  return D->getDeclContext();
220 }
221 R__DLLEXPORT clang::NamespaceDecl* TCling__DEBUG__DCtoNamespace(clang::DeclContext* DC) {
222  return llvm::dyn_cast<clang::NamespaceDecl>(DC);
223 }
224 R__DLLEXPORT clang::RecordDecl* TCling__DEBUG__DCtoRecordDecl(clang::DeclContext* DC) {
225  return llvm::dyn_cast<clang::RecordDecl>(DC);
226 }
227 R__DLLEXPORT void TCling__DEBUG__dump(clang::DeclContext* DC) {
228  return DC->dumpDeclContext();
229 }
230 R__DLLEXPORT void TCling__DEBUG__dump(clang::Decl* D) {
231  return D->dump();
232 }
233 R__DLLEXPORT void TCling__DEBUG__dump(clang::FunctionDecl* FD) {
234  return FD->dump();
235 }
236 R__DLLEXPORT void TCling__DEBUG__decl_dump(void* D) {
237  return ((clang::Decl*)D)->dump();
238 }
239 R__DLLEXPORT void TCling__DEBUG__printName(clang::Decl* D) {
240  if (clang::NamedDecl* ND = llvm::dyn_cast<clang::NamedDecl>(D)) {
241  std::string name;
242  {
243  llvm::raw_string_ostream OS(name);
244  ND->getNameForDiagnostic(OS, D->getASTContext().getPrintingPolicy(),
245  true /*Qualified*/);
246  }
247  printf("%s\n", name.c_str());
248  }
249 }
250 //______________________________________________________________________________
251 // These functions are helpers for testing issues directly rather than
252 // relying on side effects.
253 // This is used for the test for ROOT-7462/ROOT-6070
254 R__DLLEXPORT bool TCling__TEST_isInvalidDecl(clang::Decl* D) {
255  return D->isInvalidDecl();
256 }
257 R__DLLEXPORT bool TCling__TEST_isInvalidDecl(ClassInfo_t *input) {
258  TClingClassInfo *info( (TClingClassInfo*) input);
259  assert(info && info->IsValid());
260  return info->GetDecl()->isInvalidDecl();
261 }
262 
263 using namespace std;
264 using namespace clang;
265 using namespace ROOT;
266 
267 namespace {
268  static const std::string gInterpreterClassDef = R"ICF( #undef ClassDef #define ClassDef(name, id) \ _ClassDefInterp_(name,id,virtual,) \ static int DeclFileLine() { return __LINE__; } #undef ClassDefNV #define ClassDefNV(name, id) \ _ClassDefInterp_(name,id,,) \ static int DeclFileLine() { return __LINE__; } #undef ClassDefOverride #define ClassDefOverride(name, id) \ _ClassDefInterp_(name,id,,override) \ static int DeclFileLine() { return __LINE__; } )ICF";
269 
270  static const std::string gNonInterpreterClassDef = R"ICF( #define __ROOTCLING__ 1 #undef ClassDef #define ClassDef(name,id) \ _ClassDefOutline_(name,id,virtual,) \ static int DeclFileLine() { return __LINE__; } #undef ClassDefNV #define ClassDefNV(name, id)\ _ClassDefOutline_(name,id,,)\ static int DeclFileLine() { return __LINE__; } #undef ClassDefOverride #define ClassDefOverride(name, id)\ _ClassDefOutline_(name,id,,override)\ static int DeclFileLine() { return __LINE__; } )ICF";
271 
272 // The macros below use ::Error, so let's ensure it is included
273  static const std::string gClassDefInterpMacro = R"ICF( #include "TError.h" #define _ClassDefInterp_(name,id,virtual_keyword, overrd) \ private: \ public: \ static TClass *Class() { static TClass* sIsA = 0; if (!sIsA) sIsA = TClass::GetClass(#name); return sIsA; } \ static const char *Class_Name() { return #name; } \ virtual_keyword Bool_t CheckTObjectHashConsistency() const overrd { return true; } \ static Version_t Class_Version() { return id; } \ static TClass *Dictionary() { return 0; } \ virtual_keyword TClass *IsA() const overrd { return name::Class(); } \ virtual_keyword void ShowMembers(TMemberInspector&insp) const overrd { ::ROOT::Class_ShowMembers(name::Class(), this, insp); } \ virtual_keyword void Streamer(TBuffer&) overrd { ::Error("Streamer", "Cannot stream interpreted class."); } \ void StreamerNVirtual(TBuffer&ClassDef_StreamerNVirtual_b) { name::Streamer(ClassDef_StreamerNVirtual_b); } \ static const char *DeclFileName() { return __FILE__; } \ static int ImplFileLine() { return 0; } \ static const char *ImplFileName() { return __FILE__; } )ICF";
274 }
275 R__EXTERN int optind;
276 
277 // The functions are used to bridge cling/clang/llvm compiled with no-rtti and
278 // ROOT (which uses rtti)
279 
280 ////////////////////////////////////////////////////////////////////////////////
281 /// Print a StackTrace!
282 
283 extern "C"
284 void TCling__PrintStackTrace() {
285  gSystem->StackTrace();
286 }
287 
288 ////////////////////////////////////////////////////////////////////////////////
289 /// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
290 
291 extern "C" void TCling__RestoreInterpreterMutex(void *delta)
292 {
293  ((TCling*)gCling)->ApplyToInterpreterMutex(delta);
294 }
295 
296 ////////////////////////////////////////////////////////////////////////////////
297 /// Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name,
298 /// which is extracted by error messages we get from callback from cling. Return true
299 /// when the missing library was autoloaded.
300 
301 extern "C" bool TCling__LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
302 {
303  return ((TCling*)gCling)->LibraryLoadingFailed(errmessage, libStem, permanent, resolved);
304 }
305 
306 ////////////////////////////////////////////////////////////////////////////////
307 /// Reset the interpreter lock to the state it had before interpreter-related
308 /// calls happened.
309 
310 extern "C" void *TCling__ResetInterpreterMutex()
311 {
312  return ((TCling*)gCling)->RewindInterpreterMutex();
313 }
314 
315 ////////////////////////////////////////////////////////////////////////////////
316 /// Lock the interpreter.
317 
318 extern "C" void *TCling__LockCompilationDuringUserCodeExecution()
319 {
320  if (gInterpreterMutex) {
321  gInterpreterMutex->Lock();
322  }
323  return nullptr;
324 }
325 
326 ////////////////////////////////////////////////////////////////////////////////
327 /// Unlock the interpreter.
328 
329 extern "C" void TCling__UnlockCompilationDuringUserCodeExecution(void* /*state*/)
330 {
331  if (gInterpreterMutex) {
332  gInterpreterMutex->UnLock();
333  }
334 }
335 
336 ////////////////////////////////////////////////////////////////////////////////
337 /// Update TClingClassInfo for a class (e.g. upon seeing a definition).
338 
339 static void TCling__UpdateClassInfo(const NamedDecl* TD)
340 {
341  static Bool_t entered = kFALSE;
342  static vector<const NamedDecl*> updateList;
343  Bool_t topLevel;
344 
345  if (entered) topLevel = kFALSE;
346  else {
347  entered = kTRUE;
348  topLevel = kTRUE;
349  }
350  if (topLevel) {
351  ((TCling*)gInterpreter)->UpdateClassInfoWithDecl(TD);
352  } else {
353  // If we are called indirectly from within another call to
354  // TCling::UpdateClassInfo, we delay the update until the dictionary loading
355  // is finished (i.e. when we return to the top level TCling::UpdateClassInfo).
356  // This allows for the dictionary to be fully populated when we actually
357  // update the TClass object. The updating of the TClass sometimes
358  // (STL containers and when there is an emulated class) forces the building
359  // of the TClass object's real data (which needs the dictionary info).
360  updateList.push_back(TD);
361  }
362  if (topLevel) {
363  while (!updateList.empty()) {
364  ((TCling*)gInterpreter)->UpdateClassInfoWithDecl(updateList.back());
365  updateList.pop_back();
366  }
367  entered = kFALSE;
368  }
369 }
370 
371 void TCling::UpdateEnumConstants(TEnum* enumObj, TClass* cl) const {
372  const clang::Decl* D = static_cast<const clang::Decl*>(enumObj->GetDeclId());
373  if(const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(D)) {
374  // Add the constants to the enum type.
375  for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(),
376  EDE = ED->enumerator_end(); EDI != EDE; ++EDI) {
377  // Get name of the enum type.
378  std::string constbuf;
379  if (const NamedDecl* END = llvm::dyn_cast<NamedDecl>(*EDI)) {
380  PrintingPolicy Policy((*EDI)->getASTContext().getPrintingPolicy());
381  llvm::raw_string_ostream stream(constbuf);
382  // Don't trigger fopen of the source file to count lines:
383  Policy.AnonymousTagLocations = false;
384  (END)->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
385  }
386  const char* constantName = constbuf.c_str();
387 
388  // Get value of the constant.
389  Long64_t value;
390  const llvm::APSInt valAPSInt = (*EDI)->getInitVal();
391  if (valAPSInt.isSigned()) {
392  value = valAPSInt.getSExtValue();
393  } else {
394  value = valAPSInt.getZExtValue();
395  }
396 
397  // Create the TEnumConstant or update it if existing
398  TEnumConstant* enumConstant = nullptr;
399  TClingClassInfo* tcCInfo = (TClingClassInfo*)(cl ? cl->GetClassInfo() : 0);
400  TClingDataMemberInfo* tcDmInfo = new TClingDataMemberInfo(GetInterpreterImpl(), *EDI, tcCInfo);
401  DataMemberInfo_t* dmInfo = (DataMemberInfo_t*) tcDmInfo;
402  if (TObject* encAsTObj = enumObj->GetConstants()->FindObject(constantName)){
403  ((TEnumConstant*)encAsTObj)->Update(dmInfo);
404  } else {
405  enumConstant = new TEnumConstant(dmInfo, constantName, value, enumObj);
406  }
407 
408  // Add the global constants to the list of Globals.
409  if (!cl) {
410  TCollection* globals = gROOT->GetListOfGlobals(false);
411  if (!globals->FindObject(constantName)) {
412  globals->Add(enumConstant);
413  }
414  }
415  }
416  }
417 }
418 
419 TEnum* TCling::CreateEnum(void *VD, TClass *cl) const
420 {
421  // Handle new enum declaration for either global and nested enums.
422 
423  // Create the enum type.
424  TEnum* enumType = 0;
425  const clang::Decl* D = static_cast<const clang::Decl*>(VD);
426  std::string buf;
427  if (const EnumDecl* ED = llvm::dyn_cast<EnumDecl>(D)) {
428  // Get name of the enum type.
429  PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
430  llvm::raw_string_ostream stream(buf);
431  // Don't trigger fopen of the source file to count lines:
432  Policy.AnonymousTagLocations = false;
433  ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
434  // If the enum is unnamed we do not add it to the list of enums i.e unusable.
435  }
436  if (buf.empty()) {
437  return 0;
438  }
439  const char* name = buf.c_str();
440  enumType = new TEnum(name, VD, cl);
441  UpdateEnumConstants(enumType, cl);
442 
443  return enumType;
444 }
445 
446 void TCling::HandleNewDecl(const void* DV, bool isDeserialized, std::set<TClass*> &modifiedTClasses) {
447  // Handle new declaration.
448  // Record the modified class, struct and namespaces in 'modifiedTClasses'.
449 
450  const clang::Decl* D = static_cast<const clang::Decl*>(DV);
451 
452  if (!D->isCanonicalDecl() && !isa<clang::NamespaceDecl>(D)
453  && !dyn_cast<clang::RecordDecl>(D)) return;
454 
455  if (isa<clang::FunctionDecl>(D->getDeclContext())
456  || isa<clang::TagDecl>(D->getDeclContext()))
457  return;
458 
459  // Don't list templates.
460  if (const clang::CXXRecordDecl* RD = dyn_cast<clang::CXXRecordDecl>(D)) {
461  if (RD->getDescribedClassTemplate())
462  return;
463  } else if (const clang::FunctionDecl* FD = dyn_cast<clang::FunctionDecl>(D)) {
464  if (FD->getDescribedFunctionTemplate())
465  return;
466  }
467 
468  if (const RecordDecl *TD = dyn_cast<RecordDecl>(D)) {
469  if (TD->isCanonicalDecl() || TD->isThisDeclarationADefinition())
470  TCling__UpdateClassInfo(TD);
471  }
472  else if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
473 
474  if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
475  // Mostly just for EnumDecl (the other TagDecl are handled
476  // by the 'RecordDecl' if statement.
477  TCling__UpdateClassInfo(TD);
478  } else if (const NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(D)) {
479  TCling__UpdateClassInfo(NSD);
480  }
481 
482  // We care about declarations on the global scope.
483  if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
484  return;
485 
486  // Enums are lazyly created, thus we don not need to handle them here.
487  if (isa<EnumDecl>(ND))
488  return;
489 
490  // ROOT says that global is enum(lazylycreated)/var/field declared on the global
491  // scope.
492  if (!(isa<VarDecl>(ND)))
493  return;
494 
495  // Skip if already in the list.
496  if (gROOT->GetListOfGlobals()->FindObject(ND->getNameAsString().c_str()))
497  return;
498 
499  // Put the global constants and global enums in the corresponding lists.
500  gROOT->GetListOfGlobals()->Add(new TGlobal((DataMemberInfo_t *)
501  new TClingDataMemberInfo(GetInterpreterImpl(),
502  cast<ValueDecl>(ND), 0)));
503  }
504 }
505 
506 extern "C"
507 void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt*& normCtxt)
508 {
509  // We are sure in this context of the type of the interpreter
510  normCtxt = &( (TCling*) gInterpreter)->GetNormalizedContext();
511 }
512 
513 extern "C"
514 void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter*) {
515  ((TCling*)gCling)->UpdateListsOnCommitted(T);
516 }
517 
518 extern "C"
519 void TCling__UpdateListsOnUnloaded(const cling::Transaction &T) {
520  ((TCling*)gCling)->UpdateListsOnUnloaded(T);
521 }
522 
523 extern "C"
524 void TCling__InvalidateGlobal(const clang::Decl *D) {
525  ((TCling*)gCling)->InvalidateGlobal(D);
526 }
527 
528 extern "C"
529 void TCling__TransactionRollback(const cling::Transaction &T) {
530  ((TCling*)gCling)->TransactionRollback(T);
531 }
532 
533 extern "C" void TCling__LibraryLoadedRTTI(const void* dyLibHandle,
534  const char* canonicalName) {
535  ((TCling*)gCling)->LibraryLoaded(dyLibHandle, canonicalName);
536 }
537 
538 extern "C" void TCling__RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
539 {
540  ((TCling *)gCling)->RegisterRdictForLoadPCM(pcmFileNameFullPath, pcmContent);
541 }
542 
543 extern "C" void TCling__LibraryUnloadedRTTI(const void* dyLibHandle,
544  const char* canonicalName) {
545  ((TCling*)gCling)->LibraryUnloaded(dyLibHandle, canonicalName);
546 }
547 
548 
549 extern "C"
550 TObject* TCling__GetObjectAddress(const char *Name, void *&LookupCtx) {
551  return ((TCling*)gCling)->GetObjectAddress(Name, LookupCtx);
552 }
553 
554 extern "C" const Decl* TCling__GetObjectDecl(TObject *obj) {
555  return ((TClingClassInfo*)obj->IsA()->GetClassInfo())->GetDecl();
556 }
557 
558 extern "C" R__DLLEXPORT TInterpreter *CreateInterpreter(void* interpLibHandle,
559  const char* argv[])
560 {
561  cling::DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(interpLibHandle);
562  return new TCling("C++", "cling C++ Interpreter", argv);
563 }
564 
565 extern "C" R__DLLEXPORT void DestroyInterpreter(TInterpreter *interp)
566 {
567  delete interp;
568 }
569 
570 // Load library containing specified class. Returns 0 in case of error
571 // and 1 in case if success.
572 extern "C" int TCling__AutoLoadCallback(const char* className)
573 {
574  return ((TCling*)gCling)->AutoLoad(className);
575 }
576 
577 extern "C" int TCling__AutoParseCallback(const char* className)
578 {
579  return ((TCling*)gCling)->AutoParse(className);
580 }
581 
582 extern "C" const char* TCling__GetClassSharedLibs(const char* className)
583 {
584  return ((TCling*)gCling)->GetClassSharedLibs(className);
585 }
586 
587 // Returns 0 for failure 1 for success
588 extern "C" int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl* nsDecl)
589 {
590  return ((TCling*)gCling)->IsAutoLoadNamespaceCandidate(nsDecl);
591 }
592 
593 extern "C" int TCling__CompileMacro(const char *fileName, const char *options)
594 {
595  string file(fileName);
596  string opt(options);
597  return gSystem->CompileMacro(file.c_str(), opt.c_str());
598 }
599 
600 extern "C" void TCling__SplitAclicMode(const char* fileName, string &mode,
601  string &args, string &io, string &fname)
602 {
603  string file(fileName);
604  TString f, amode, arguments, aclicio;
605  f = gSystem->SplitAclicMode(file.c_str(), amode, arguments, aclicio);
606  mode = amode.Data(); args = arguments.Data();
607  io = aclicio.Data(); fname = f.Data();
608 }
609 
610 // Implemented in TClingCallbacks.
611 extern "C" void TCling__FindLoadedLibraries(std::vector<std::pair<uint32_t, std::string>> &sLibraries,
612  std::vector<std::string> &sPaths,
613  cling::Interpreter &interpreter, bool searchSystem);
614 
615 //______________________________________________________________________________
616 //
617 //
618 //
619 
620 #ifdef R__WIN32
621 extern "C" {
622  char *__unDName(char *demangled, const char *mangled, int out_len,
623  void * (* pAlloc )(size_t), void (* pFree )(void *),
624  unsigned short int flags);
625 }
626 #endif
627 
628 ////////////////////////////////////////////////////////////////////////////////
629 /// Find a template decl within N nested namespaces, 0<=N<inf
630 /// Assumes 1 and only 1 template present and 1 and only 1 entity contained
631 /// by the namespace. Example: ns1::ns2::..::nsN::myTemplate
632 /// Returns nullptr in case of error
633 
634 static clang::ClassTemplateDecl* FindTemplateInNamespace(clang::Decl* decl)
635 {
636  using namespace clang;
637  if (NamespaceDecl* nsd = llvm::dyn_cast<NamespaceDecl>(decl)){
638  return FindTemplateInNamespace(*nsd->decls_begin());
639  }
640 
641  if (ClassTemplateDecl* ctd = llvm::dyn_cast<ClassTemplateDecl>(decl)){
642  return ctd;
643  }
644 
645  return nullptr; // something went wrong.
646 }
647 
648 ////////////////////////////////////////////////////////////////////////////////
649 /// Autoload a library provided the mangled name of a missing symbol.
650 
651 void* llvmLazyFunctionCreator(const std::string& mangled_name)
652 {
653  return ((TCling*)gCling)->LazyFunctionCreatorAutoload(mangled_name);
654 }
655 
656 //______________________________________________________________________________
657 //
658 //
659 //
660 
661 int TCling_GenerateDictionary(const std::vector<std::string> &classes,
662  const std::vector<std::string> &headers,
663  const std::vector<std::string> &fwdDecls,
664  const std::vector<std::string> &unknown)
665 {
666  //This function automatically creates the "LinkDef.h" file for templated
667  //classes then executes CompileMacro on it.
668  //The name of the file depends on the class name, and it's not generated again
669  //if the file exist.
670  if (classes.empty()) {
671  return 0;
672  }
673  // Use the name of the first class as the main name.
674  const std::string& className = classes[0];
675  //(0) prepare file name
676  TString fileName = "AutoDict_";
677  std::string::const_iterator sIt;
678  for (sIt = className.begin(); sIt != className.end(); ++sIt) {
679  if (*sIt == '<' || *sIt == '>' ||
680  *sIt == ' ' || *sIt == '*' ||
681  *sIt == ',' || *sIt == '&' ||
682  *sIt == ':') {
683  fileName += '_';
684  }
685  else {
686  fileName += *sIt;
687  }
688  }
689  if (classes.size() > 1) {
690  Int_t chk = 0;
691  std::vector<std::string>::const_iterator it = classes.begin();
692  while ((++it) != classes.end()) {
693  for (UInt_t cursor = 0; cursor != it->length(); ++cursor) {
694  chk = chk * 3 + it->at(cursor);
695  }
696  }
697  fileName += TString::Format("_%u", chk);
698  }
699  fileName += ".cxx";
700  if (gSystem->AccessPathName(fileName) != 0) {
701  //file does not exist
702  //(1) prepare file data
703  // If STL, also request iterators' operators.
704  // vector is special: we need to check whether
705  // vector::iterator is a typedef to pointer or a
706  // class.
707  static const std::set<std::string> sSTLTypes {
708  "vector","list","forward_list","deque","map","unordered_map","multimap",
709  "unordered_multimap","set","unordered_set","multiset","unordered_multiset",
710  "queue","priority_queue","stack","iterator"};
711  std::vector<std::string>::const_iterator it;
712  std::string fileContent("");
713  for (it = headers.begin(); it != headers.end(); ++it) {
714  fileContent += "#include \"" + *it + "\"\n";
715  }
716  for (it = unknown.begin(); it != unknown.end(); ++it) {
717  TClass* cl = TClass::GetClass(it->c_str());
718  if (cl && cl->GetDeclFileName()) {
719  TString header(gSystem->BaseName(cl->GetDeclFileName()));
720  TString dir(gSystem->DirName(cl->GetDeclFileName()));
721  TString dirbase(gSystem->BaseName(dir));
722  while (dirbase.Length() && dirbase != "."
723  && dirbase != "include" && dirbase != "inc"
724  && dirbase != "prec_stl") {
725  gSystem->PrependPathName(dirbase, header);
726  dir = gSystem->DirName(dir);
727  }
728  fileContent += TString("#include \"") + header + "\"\n";
729  }
730  }
731  for (it = fwdDecls.begin(); it != fwdDecls.end(); ++it) {
732  fileContent += "class " + *it + ";\n";
733  }
734  fileContent += "#ifdef __CINT__ \n";
735  fileContent += "#pragma link C++ nestedclasses;\n";
736  fileContent += "#pragma link C++ nestedtypedefs;\n";
737  for (it = classes.begin(); it != classes.end(); ++it) {
738  std::string n(*it);
739  size_t posTemplate = n.find('<');
740  std::set<std::string>::const_iterator iSTLType = sSTLTypes.end();
741  if (posTemplate != std::string::npos) {
742  n.erase(posTemplate, std::string::npos);
743  if (n.compare(0, 5, "std::") == 0) {
744  n.erase(0, 5);
745  }
746  iSTLType = sSTLTypes.find(n);
747  }
748  fileContent += "#pragma link C++ class ";
749  fileContent += *it + "+;\n" ;
750  fileContent += "#pragma link C++ class ";
751  if (iSTLType != sSTLTypes.end()) {
752  // STL class; we cannot (and don't need to) store iterators;
753  // their shadow and the compiler's version don't agree. So
754  // don't ask for the '+'
755  fileContent += *it + "::*;\n" ;
756  }
757  else {
758  // Not an STL class; we need to allow the I/O of contained
759  // classes (now that we have a dictionary for them).
760  fileContent += *it + "::*+;\n" ;
761  }
762  }
763  fileContent += "#endif\n";
764  //end(1)
765  //(2) prepare the file
766  FILE* filePointer;
767  filePointer = fopen(fileName, "w");
768  if (filePointer == NULL) {
769  //can't open a file
770  return 1;
771  }
772  //end(2)
773  //write data into the file
774  fprintf(filePointer, "%s", fileContent.c_str());
775  fclose(filePointer);
776  }
777  //(3) checking if we can compile a macro, if not then cleaning
778  Int_t oldErrorIgnoreLevel = gErrorIgnoreLevel;
779  gErrorIgnoreLevel = kWarning; // no "Info: creating library..."
780  Int_t ret = gSystem->CompileMacro(fileName, "k");
781  gErrorIgnoreLevel = oldErrorIgnoreLevel;
782  if (ret == 0) { //can't compile a macro
783  return 2;
784  }
785  //end(3)
786  return 0;
787 }
788 
789 int TCling_GenerateDictionary(const std::string& className,
790  const std::vector<std::string> &headers,
791  const std::vector<std::string> &fwdDecls,
792  const std::vector<std::string> &unknown)
793 {
794  //This function automatically creates the "LinkDef.h" file for templated
795  //classes then executes CompileMacro on it.
796  //The name of the file depends on the class name, and it's not generated again
797  //if the file exist.
798  std::vector<std::string> classes;
799  classes.push_back(className);
800  return TCling_GenerateDictionary(classes, headers, fwdDecls, unknown);
801 }
802 
803 //______________________________________________________________________________
804 //
805 //
806 //
807 
808 // It is a "fantom" method to synchronize user keyboard input
809 // and ROOT prompt line (for WIN32)
810 const char* fantomline = "TRint::EndOfLineAction();";
811 
812 //______________________________________________________________________________
813 //
814 //
815 //
816 
817 void* TCling::fgSetOfSpecials = 0;
818 
819 //______________________________________________________________________________
820 //
821 // llvm error handler through exceptions; see also cling/UserInterface
822 //
823 namespace {
824  // Handle fatal llvm errors by throwing an exception.
825  // Yes, throwing exceptions in error handlers is bad.
826  // Doing nothing is pretty terrible, too.
827  void exceptionErrorHandler(void * /*user_data*/,
828  const std::string& reason,
829  bool /*gen_crash_diag*/) {
830  throw std::runtime_error(std::string(">>> Interpreter compilation error:\n") + reason);
831  }
832 }
833 
834 //______________________________________________________________________________
835 //
836 //
837 //
838 
839 ////////////////////////////////////////////////////////////////////////////////
840 
841 namespace{
842  // An instance of this class causes the diagnostics of clang to be suppressed
843  // during its lifetime
844  class clangDiagSuppr {
845  public:
846  clangDiagSuppr(clang::DiagnosticsEngine& diag): fDiagEngine(diag){
847  fOldDiagValue = fDiagEngine.getIgnoreAllWarnings();
848  fDiagEngine.setIgnoreAllWarnings(true);
849  }
850 
851  ~clangDiagSuppr() {
852  fDiagEngine.setIgnoreAllWarnings(fOldDiagValue);
853  }
854  private:
855  clang::DiagnosticsEngine& fDiagEngine;
856  bool fOldDiagValue;
857  };
858 
859 }
860 
861 ////////////////////////////////////////////////////////////////////////////////
862 /// Allow calling autoparsing from TMetaUtils
863 bool TClingLookupHelper__AutoParse(const char *cname)
864 {
865  return gCling->AutoParse(cname);
866 }
867 
868 ////////////////////////////////////////////////////////////////////////////////
869 /// Try hard to avoid looking up in the Cling database as this could enduce
870 /// an unwanted autoparsing.
871 
872 bool TClingLookupHelper__ExistingTypeCheck(const std::string &tname,
873  std::string &result)
874 {
875  result.clear();
876 
877  unsigned long offset = 0;
878  if (strncmp(tname.c_str(), "const ", 6) == 0) {
879  offset = 6;
880  }
881  unsigned long end = tname.length();
882  while( end && (tname[end-1]=='&' || tname[end-1]=='*' || tname[end-1]==']') ) {
883  if ( tname[end-1]==']' ) {
884  --end;
885  while ( end && tname[end-1]!='[' ) --end;
886  }
887  --end;
888  }
889  std::string innerbuf;
890  const char *inner;
891  if (end != tname.length()) {
892  innerbuf = tname.substr(offset,end-offset);
893  inner = innerbuf.c_str();
894  } else {
895  inner = tname.c_str()+offset;
896  }
897 
898  //if (strchr(tname.c_str(),'[')!=0) fprintf(stderr,"DEBUG: checking on %s vs %s %lu %lu\n",tname.c_str(),inner,offset,end);
899  if (gROOT->GetListOfClasses()->FindObject(inner)
900  || TClassTable::Check(inner,result) ) {
901  // This is a known class.
902  return true;
903  }
904 
905  THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
906  TDataType *type = (TDataType *)typeTable->THashTable::FindObject( inner );
907  if (type) {
908  // This is a raw type and an already loaded typedef.
909  const char *newname = type->GetFullTypeName();
910  if (type->GetType() == kLong64_t) {
911  newname = "Long64_t";
912  } else if (type->GetType() == kULong64_t) {
913  newname = "ULong64_t";
914  }
915  if (strcmp(inner,newname) == 0) {
916  return true;
917  }
918  if (offset) result = "const ";
919  result += newname;
920  if ( end != tname.length() ) {
921  result += tname.substr(end,tname.length()-end);
922  }
923  if (result == tname) result.clear();
924  return true;
925  }
926 
927  // Check if the name is an enumerator
928  const auto lastPos = TClassEdit::GetUnqualifiedName(inner);
929  if (lastPos != inner) // Main switch: case 1 - scoped enum, case 2 global enum
930  {
931  // We have a scope
932  // All of this C gymnastic is to avoid allocations on the heap
933  const auto enName = lastPos;
934  const auto scopeNameSize = ((Long64_t)lastPos - (Long64_t)inner) / sizeof(decltype(*lastPos)) - 2;
935  char *scopeName = new char[scopeNameSize + 1];
936  strncpy(scopeName, inner, scopeNameSize);
937  scopeName[scopeNameSize] = '\0';
938  // Check if the scope is in the list of classes
939  if (auto scope = static_cast<TClass *>(gROOT->GetListOfClasses()->FindObject(scopeName))) {
940  auto enumTable = dynamic_cast<const THashList *>(scope->GetListOfEnums(false));
941  if (enumTable && enumTable->THashList::FindObject(enName)) return true;
942  }
943  // It may still be in one of the loaded protoclasses
944  else if (auto scope = static_cast<TProtoClass *>(gClassTable->GetProtoNorm(scopeName))) {
945  auto listOfEnums = scope->GetListOfEnums();
946  if (listOfEnums) { // it could be null: no enumerators in the protoclass
947  auto enumTable = dynamic_cast<const THashList *>(listOfEnums);
948  if (enumTable && enumTable->THashList::FindObject(enName)) return true;
949  }
950  }
951  delete [] scopeName;
952  } else
953  {
954  // We don't have any scope: this could only be a global enum
955  auto enumTable = dynamic_cast<const THashList *>(gROOT->GetListOfEnums());
956  if (enumTable && enumTable->THashList::FindObject(inner)) return true;
957  }
958 
959  if (gCling->GetClassSharedLibs(inner))
960  {
961  // This is a class name.
962  return true;
963  }
964 
965  return false;
966 }
967 
968 ////////////////////////////////////////////////////////////////////////////////
969 
970 TCling::TUniqueString::TUniqueString(Long64_t size)
971 {
972  fContent.reserve(size);
973 }
974 
975 ////////////////////////////////////////////////////////////////////////////////
976 
977 inline const char *TCling::TUniqueString::Data()
978 {
979  return fContent.c_str();
980 }
981 
982 ////////////////////////////////////////////////////////////////////////////////
983 /// Append string to the storage if not added already.
984 
985 inline bool TCling::TUniqueString::Append(const std::string& str)
986 {
987  bool notPresent = fLinesHashSet.emplace(fHashFunc(str)).second;
988  if (notPresent){
989  fContent+=str;
990  }
991  return notPresent;
992 }
993 
994 std::string TCling::ToString(const char* type, void* obj)
995 {
996  return fInterpreter->toString(type, obj);
997 }
998 
999 ////////////////////////////////////////////////////////////////////////////////
1000 ///\returns true if the module was loaded.
1001 static bool LoadModule(const std::string &ModuleName, cling::Interpreter &interp)
1002 {
1003  // When starting up ROOT, cling would load all modulemap files on the include
1004  // paths. However, in a ROOT session, it is very common to run aclic which
1005  // will invoke rootcling and possibly produce a modulemap and a module in
1006  // the current folder.
1007  //
1008  // Before failing, try loading the modulemap in the current folder and try
1009  // loading the requested module from it.
1010  std::string currentDir = gSystem->WorkingDirectory();
1011  assert(!currentDir.empty());
1012  gCling->RegisterPrebuiltModulePath(currentDir);
1013  return interp.loadModule(ModuleName, /*Complain=*/true);
1014 }
1015 
1016 ////////////////////////////////////////////////////////////////////////////////
1017 /// Loads the C++ modules that we require to run any ROOT program. This is just
1018 /// supposed to make a C++ module from a modulemap available to the interpreter.
1019 static void LoadModules(const std::vector<std::string> &modules, cling::Interpreter &interp)
1020 {
1021  for (const auto &modName : modules)
1022  LoadModule(modName, interp);
1023 }
1024 
1025 static bool IsFromRootCling() {
1026  // rootcling also uses TCling for generating the dictionary ROOT files.
1027  const static bool foundSymbol = dlsym(RTLD_DEFAULT, "usedToIdentifyRootClingByDlSym");
1028  return foundSymbol;
1029 }
1030 
1031 static std::string GetModuleNameAsString(clang::Module *M, const clang::Preprocessor &PP)
1032 {
1033  const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1034 
1035  std::string ModuleFileName;
1036  if (!HSOpts.PrebuiltModulePaths.empty())
1037  // Load the module from *only* in the prebuilt module path.
1038  ModuleFileName = PP.getHeaderSearchInfo().getModuleFileName(M->Name, /*ModuleMapPath*/"", /*UsePrebuiltPath*/ true);
1039  if (ModuleFileName.empty()) return "";
1040 
1041  std::string ModuleName = llvm::sys::path::filename(ModuleFileName);
1042  // Return stem of the filename
1043  return std::string(llvm::sys::path::stem(ModuleName));
1044 }
1045 
1046 static void RegisterCxxModules(cling::Interpreter &clingInterp)
1047 {
1048  if (!clingInterp.getCI()->getLangOpts().Modules)
1049  return;
1050  // Setup core C++ modules if we have any to setup.
1051 
1052  // Load libc and stl first.
1053 #ifdef R__MACOSX
1054  LoadModule("Darwin", clingInterp);
1055 #else
1056  LoadModule("libc", clingInterp);
1057 #endif
1058  LoadModule("std", clingInterp);
1059 
1060  LoadModule("_Builtin_intrinsics", clingInterp);
1061 
1062  // Load core modules
1063  // This should be vector in order to be able to pass it to LoadModules
1064  std::vector<std::string> CoreModules = {"ROOT_Foundation_C",
1065  "ROOT_Config",
1066  "ROOT_Rtypes",
1067  "ROOT_Foundation_Stage1_NoRTTI",
1068  "Core",
1069  "RIO"};
1070 
1071  // FIXME: Reducing those will let us be less dependent on rootmap files
1072  static constexpr std::array<const char *, 3> ExcludeModules = {
1073  {"Rtools", "RSQLite", "RInterface"}};
1074 
1075  LoadModules(CoreModules, clingInterp);
1076 
1077  // Take this branch only from ROOT because we don't need to preload modules in rootcling
1078  if (!IsFromRootCling()) {
1079  // Dynamically get all the modules and load them if they are not in core modules
1080  clang::CompilerInstance &CI = *clingInterp.getCI();
1081  clang::ModuleMap &moduleMap = CI.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1082  clang::Preprocessor &PP = CI.getPreprocessor();
1083  std::vector<std::string> ModulesPreloaded;
1084  for (auto I = moduleMap.module_begin(), E = moduleMap.module_end(); I != E; ++I) {
1085  clang::Module *M = I->second;
1086  assert(M);
1087 
1088  std::string ModuleName = GetModuleNameAsString(M, PP);
1089  if (!ModuleName.empty() &&
1090  std::find(CoreModules.begin(), CoreModules.end(), ModuleName) == CoreModules.end() &&
1091  std::find(ExcludeModules.begin(), ExcludeModules.end(), ModuleName) ==
1092  ExcludeModules.end()) {
1093  if (M->IsSystem && !M->IsMissingRequirement)
1094  LoadModule(ModuleName, clingInterp);
1095  else if (!M->IsSystem && !M->IsMissingRequirement)
1096  ModulesPreloaded.push_back(ModuleName);
1097  }
1098  }
1099  LoadModules(ModulesPreloaded, clingInterp);
1100  }
1101 
1102  // Check that the gROOT macro was exported by any core module.
1103  assert(clingInterp.getMacro("gROOT") && "Couldn't load gROOT macro?");
1104 
1105  // C99 decided that it's a very good idea to name a macro `I` (the letter I).
1106  // This seems to screw up nearly all the template code out there as `I` is
1107  // common template parameter name and iterator variable name.
1108  // Let's follow the GCC recommendation and undefine `I` in case any of the
1109  // core modules have defined it:
1110  // https://www.gnu.org/software/libc/manual/html_node/Complex-Numbers.html
1111  clingInterp.declare("#ifdef I\n #undef I\n #endif\n");
1112 
1113  // libc++ complex.h has #define complex _Complex. Give preference to the one
1114  // in std.
1115  clingInterp.declare("#ifdef complex\n #undef complex\n #endif\n");
1116 
1117  // These macros are from loading R related modules, which conflict with
1118  // user's code.
1119  clingInterp.declare("#ifdef PI\n #undef PI\n #endif\n");
1120  clingInterp.declare("#ifdef ERROR\n #undef ERROR\n #endif\n");
1121 }
1122 
1123 static void RegisterPreIncludedHeaders(cling::Interpreter &clingInterp)
1124 {
1125  std::string PreIncludes;
1126  bool hasCxxModules = clingInterp.getCI()->getLangOpts().Modules;
1127 
1128  // For the list to also include string, we have to include it now.
1129  // rootcling does parts already if needed, e.g. genreflex does not want using
1130  // namespace std.
1131  if (IsFromRootCling()) {
1132  PreIncludes += "#include \"RtypesCore.h\"\n";
1133  } else {
1134  if (!hasCxxModules)
1135  PreIncludes += "#include \"Rtypes.h\"\n";
1136 
1137  PreIncludes += gClassDefInterpMacro + "\n"
1138  + gInterpreterClassDef + "\n"
1139  "#undef ClassImp\n"
1140  "#define ClassImp(X);\n";
1141  }
1142  if (!hasCxxModules)
1143  PreIncludes += "#include <string>\n";
1144 
1145  // We must include it even when we have modules because it is marked as
1146  // textual in the modulemap due to the nature of the assert header.
1147  PreIncludes += "#include <cassert>\n";
1148  PreIncludes += "using namespace std;\n";
1149  clingInterp.declare(PreIncludes);
1150 }
1151 
1152 ////////////////////////////////////////////////////////////////////////////////
1153 /// Initialize the cling interpreter interface.
1154 /// \param argv - array of arguments passed to the cling::Interpreter constructor
1155 /// e.g. `-DFOO=bar`. The last element of the array must be `nullptr`.
1156 
1157 TCling::TCling(const char *name, const char *title, const char* const argv[])
1158 : TInterpreter(name, title), fMore(0), fGlobalsListSerial(-1), fMapfile(nullptr),
1159  fRootmapFiles(nullptr), fLockProcessLine(true), fNormalizedCtxt(0),
1160  fPrevLoadedDynLibInfo(0), fClingCallbacks(0), fAutoLoadCallBack(0),
1161  fTransactionCount(0), fHeaderParsingOnDemand(true), fIsAutoParsingSuspended(kFALSE)
1162 {
1163  fPrompt[0] = 0;
1164  const bool fromRootCling = IsFromRootCling();
1165 
1166  fCxxModulesEnabled = false;
1167 #ifdef R__USE_CXXMODULES
1168  fCxxModulesEnabled = true;
1169 #endif
1170 
1171  llvm::install_fatal_error_handler(&exceptionErrorHandler);
1172 
1173  fTemporaries = new std::vector<cling::Value>();
1174 
1175  std::vector<std::string> clingArgsStorage;
1176  clingArgsStorage.push_back("cling4root");
1177  for (const char* const* arg = argv; *arg; ++arg)
1178  clingArgsStorage.push_back(*arg);
1179 
1180  // rootcling sets its arguments through TROOT::GetExtraInterpreterArgs().
1181  if (!fromRootCling) {
1182  ROOT::TMetaUtils::SetPathsForRelocatability(clingArgsStorage);
1183 
1184  // Add -I early so ASTReader can find the headers.
1185  std::string interpInclude(TROOT::GetEtcDir().Data());
1186  clingArgsStorage.push_back("-I" + interpInclude);
1187 
1188  // Add include path to etc/cling.
1189  clingArgsStorage.push_back("-I" + interpInclude + "/cling");
1190 
1191  // Add the root include directory and etc/ to list searched by default.
1192  clingArgsStorage.push_back(std::string(("-I" + TROOT::GetIncludeDir()).Data()));
1193 
1194  // Add the current path to the include path
1195  // TCling::AddIncludePath(".");
1196 
1197  // Attach the PCH (unless we have C++ modules enabled which provide the
1198  // same functionality).
1199  if (!fCxxModulesEnabled) {
1200  std::string pchFilename = interpInclude + "/allDict.cxx.pch";
1201  if (gSystem->Getenv("ROOT_PCH")) {
1202  pchFilename = gSystem->Getenv("ROOT_PCH");
1203  }
1204 
1205  clingArgsStorage.push_back("-include-pch");
1206  clingArgsStorage.push_back(pchFilename);
1207  }
1208 
1209  clingArgsStorage.push_back("-Wno-undefined-inline");
1210  clingArgsStorage.push_back("-fsigned-char");
1211  }
1212 
1213  // Process externally passed arguments if present.
1214  llvm::Optional<std::string> EnvOpt = llvm::sys::Process::GetEnv("EXTRA_CLING_ARGS");
1215  if (EnvOpt.hasValue()) {
1216  StringRef Env(*EnvOpt);
1217  while (!Env.empty()) {
1218  StringRef Arg;
1219  std::tie(Arg, Env) = Env.split(' ');
1220  clingArgsStorage.push_back(Arg.str());
1221  }
1222  }
1223 
1224  auto GetEnvVarPath = [](const std::string &EnvVar,
1225  std::vector<std::string> &Paths) {
1226  llvm::Optional<std::string> EnvOpt = llvm::sys::Process::GetEnv(EnvVar);
1227  if (EnvOpt.hasValue()) {
1228  StringRef Env(*EnvOpt);
1229  while (!Env.empty()) {
1230  StringRef Arg;
1231  std::tie(Arg, Env) = Env.split(ROOT::FoundationUtils::GetEnvPathSeparator());
1232  if (std::find(Paths.begin(), Paths.end(), Arg.str()) == Paths.end())
1233  Paths.push_back(Arg.str());
1234  }
1235  }
1236  };
1237 
1238  if (fCxxModulesEnabled) {
1239  std::vector<std::string> Paths;
1240  // ROOT usually knows better where its libraries are. This way we can
1241  // discover modules without having to should thisroot.sh and should fix
1242  // gnuinstall.
1243  Paths.push_back(TROOT::GetLibDir().Data());
1244  GetEnvVarPath("CLING_PREBUILT_MODULE_PATH", Paths);
1245  //GetEnvVarPath("LD_LIBRARY_PATH", Paths);
1246  std::string EnvVarPath;
1247  for (const std::string& P : Paths)
1248  EnvVarPath += P + ROOT::FoundationUtils::GetEnvPathSeparator();
1249  // FIXME: We should make cling -fprebuilt-module-path work.
1250  gSystem->Setenv("CLING_PREBUILT_MODULE_PATH", EnvVarPath.c_str());
1251  }
1252 
1253  // FIXME: This only will enable frontend timing reports.
1254  EnvOpt = llvm::sys::Process::GetEnv("ROOT_CLING_TIMING");
1255  if (EnvOpt.hasValue())
1256  clingArgsStorage.push_back("-ftime-report");
1257 
1258  // Add the overlay file. Note that we cannot factor it out for both root
1259  // and rootcling because rootcling activates modules only if -cxxmodule
1260  // flag is passed.
1261  if (fCxxModulesEnabled && !fromRootCling) {
1262  // For now we prefer rootcling to enumerate explicitly its modulemaps.
1263  std::vector<std::string> Paths;
1264  Paths.push_back(TROOT::GetIncludeDir().Data());
1265  GetEnvVarPath("CLING_MODULEMAP_PATH", Paths);
1266 
1267  // Give highest precedence of the modulemap in the cwd.
1268  Paths.push_back(gSystem->WorkingDirectory());
1269 
1270  for (const std::string& P : Paths) {
1271  std::string ModuleMapLoc = P + ROOT::FoundationUtils::GetPathSeparator()
1272  + "module.modulemap";
1273  if (!llvm::sys::fs::exists(ModuleMapLoc)) {
1274  if (gDebug > 1)
1275  ::Info("TCling::TCling", "Modulemap %s does not exist \n",
1276  ModuleMapLoc.c_str());
1277 
1278  continue;
1279  }
1280 
1281  clingArgsStorage.push_back("-fmodule-map-file=" + ModuleMapLoc);
1282  }
1283  }
1284 
1285  std::vector<const char*> interpArgs;
1286  for (std::vector<std::string>::const_iterator iArg = clingArgsStorage.begin(),
1287  eArg = clingArgsStorage.end(); iArg != eArg; ++iArg)
1288  interpArgs.push_back(iArg->c_str());
1289 
1290  // Activate C++ modules support. If we are running within rootcling, it's up
1291  // to rootcling to set this flag depending on whether it wants to produce
1292  // C++ modules.
1293  TString vfsArg;
1294  if (fCxxModulesEnabled) {
1295  if (!fromRootCling) {
1296  // We only set this flag, rest is done by the CIFactory.
1297  interpArgs.push_back("-fmodules");
1298  interpArgs.push_back("-fno-implicit-module-maps");
1299  // We should never build modules during runtime, so let's enable the
1300  // module build remarks from clang to make it easier to spot when we do
1301  // this by accident.
1302  interpArgs.push_back("-Rmodule-build");
1303  }
1304  // ROOT implements its autoloading upon module's link directives. We
1305  // generate module A { header "A.h" link "A.so" export * } where ROOT's
1306  // facilities use the link directive to dynamically load the relevant
1307  // library. So, we need to suppress clang's default autolink behavior.
1308  interpArgs.push_back("-fno-autolink");
1309  }
1310 
1311 #ifdef R__FAST_MATH
1312  // Same setting as in rootcling_impl.cxx.
1313  interpArgs.push_back("-ffast-math");
1314 #endif
1315 
1316  TString llvmResourceDir = TROOT::GetEtcDir() + "/cling";
1317  // Add statically injected extra arguments, usually coming from rootcling.
1318  for (const char** extraArgs = TROOT::GetExtraInterpreterArgs();
1319  extraArgs && *extraArgs; ++extraArgs) {
1320  if (!strcmp(*extraArgs, "-resource-dir")) {
1321  // Take the next arg as the llvm resource directory.
1322  llvmResourceDir = *(++extraArgs);
1323  } else {
1324  interpArgs.push_back(*extraArgs);
1325  }
1326  }
1327 
1328  for (const auto &arg: TROOT::AddExtraInterpreterArgs({})) {
1329  interpArgs.push_back(arg.c_str());
1330  }
1331 
1332  // Add the Rdict module file extension.
1333  cling::Interpreter::ModuleFileExtensions extensions;
1334  EnvOpt = llvm::sys::Process::GetEnv("ROOTDEBUG_RDICT");
1335  if (!EnvOpt.hasValue())
1336  extensions.push_back(std::make_shared<TClingRdictModuleFileExtension>());
1337 
1338  fInterpreter = llvm::make_unique<cling::Interpreter>(interpArgs.size(),
1339  &(interpArgs[0]),
1340  llvmResourceDir, extensions);
1341 
1342  if (!fromRootCling) {
1343  fInterpreter->installLazyFunctionCreator(llvmLazyFunctionCreator);
1344  }
1345 
1346  // Don't check whether modules' files exist.
1347  fInterpreter->getCI()->getPreprocessorOpts().DisablePCHValidation = true;
1348 
1349  // Until we can disable autoloading during Sema::CorrectTypo() we have
1350  // to disable spell checking.
1351  fInterpreter->getCI()->getLangOpts().SpellChecking = false;
1352 
1353  // We need stream that doesn't close its file descriptor, thus we are not
1354  // using llvm::outs. Keeping file descriptor open we will be able to use
1355  // the results in pipes (Savannah #99234).
1356  static llvm::raw_fd_ostream fMPOuts (STDOUT_FILENO, /*ShouldClose*/false);
1357  fMetaProcessor = llvm::make_unique<cling::MetaProcessor>(*fInterpreter, fMPOuts);
1358 
1359  RegisterCxxModules(*fInterpreter);
1360  RegisterPreIncludedHeaders(*fInterpreter);
1361 
1362  // We are now ready (enough is loaded) to init the list of opaque typedefs.
1363  fNormalizedCtxt = new ROOT::TMetaUtils::TNormalizedCtxt(fInterpreter->getLookupHelper());
1364  fLookupHelper = new ROOT::TMetaUtils::TClingLookupHelper(*fInterpreter, *fNormalizedCtxt,
1365  TClingLookupHelper__ExistingTypeCheck,
1366  TClingLookupHelper__AutoParse,
1367  &fIsShuttingDown);
1368  TClassEdit::Init(fLookupHelper);
1369 
1370  // Disallow auto-parsing in rootcling
1371  fIsAutoParsingSuspended = fromRootCling;
1372 
1373  ResetAll();
1374 
1375  // Enable dynamic lookup
1376  if (!fromRootCling) {
1377  fInterpreter->enableDynamicLookup();
1378  }
1379 
1380  // Enable ClinG's DefinitionShadower for ROOT.
1381  fInterpreter->allowRedefinition();
1382 
1383  // Attach cling callbacks last; they might need TROOT::fInterpreter
1384  // and should thus not be triggered during the equivalent of
1385  // TROOT::fInterpreter = new TCling;
1386  std::unique_ptr<TClingCallbacks>
1387  clingCallbacks(new TClingCallbacks(GetInterpreterImpl(), /*hasCodeGen*/ !fromRootCling));
1388  fClingCallbacks = clingCallbacks.get();
1389  fClingCallbacks->SetAutoParsingSuspended(fIsAutoParsingSuspended);
1390  fInterpreter->setCallbacks(std::move(clingCallbacks));
1391 
1392  if (!fromRootCling) {
1393  // Make sure cling looks into ROOT's libdir, even if not part of LD_LIBRARY_PATH
1394  // e.g. because of an RPATH build.
1395  fInterpreter->getDynamicLibraryManager()->addSearchPath(TROOT::GetLibDir().Data());
1396  }
1397 }
1398 
1399 
1400 ////////////////////////////////////////////////////////////////////////////////
1401 /// Destroy the interpreter interface.
1402 
1403 TCling::~TCling()
1404 {
1405  // ROOT's atexit functions require the interepreter to be available.
1406  // Run them before shutting down.
1407  if (!IsFromRootCling())
1408  GetInterpreterImpl()->runAtExitFuncs();
1409  fIsShuttingDown = true;
1410  delete fMapfile;
1411  delete fRootmapFiles;
1412  delete fTemporaries;
1413  delete fNormalizedCtxt;
1414  delete fLookupHelper;
1415  gCling = 0;
1416 }
1417 
1418 ////////////////////////////////////////////////////////////////////////////////
1419 /// Initialize the interpreter, once TROOT::fInterpreter is set.
1420 
1421 void TCling::Initialize()
1422 {
1423  fClingCallbacks->Initialize();
1424 
1425  // We are set up. EnableAutoLoading() is checking for fromRootCling.
1426  EnableAutoLoading();
1427 }
1428 
1429 void TCling::ShutDown()
1430 {
1431  fIsShuttingDown = true;
1432  ResetGlobals();
1433 }
1434 
1435 ////////////////////////////////////////////////////////////////////////////////
1436 /// Wrapper around dladdr (and friends)
1437 
1438 static std::string FindLibraryName(void (*func)())
1439 {
1440 #if defined(__CYGWIN__) && defined(__GNUC__)
1441  return {};
1442 #elif defined(G__WIN32)
1443  MEMORY_BASIC_INFORMATION mbi;
1444  if (!VirtualQuery (func, &mbi, sizeof (mbi)))
1445  {
1446  return {};
1447  }
1448 
1449  HMODULE hMod = (HMODULE) mbi.AllocationBase;
1450  char moduleName[MAX_PATH];
1451 
1452  if (!GetModuleFileNameA (hMod, moduleName, sizeof (moduleName)))
1453  {
1454  return {};
1455  }
1456  return ROOT::TMetaUtils::GetRealPath(moduleName);
1457 #else
1458  Dl_info info;
1459  if (dladdr((void*)func, &info) == 0) {
1460  // Not in a known shared library, let's give up
1461  return {};
1462  } else {
1463  if (strchr(info.dli_fname, '/'))
1464  return ROOT::TMetaUtils::GetRealPath(info.dli_fname);
1465  // Else absolute path. For all we know that's a binary.
1466  // Some people have dictionaries in binaries, this is how we find their path:
1467  // (see also https://stackoverflow.com/a/1024937/6182509)
1468 # if defined(R__MACOSX)
1469  char buf[PATH_MAX] = { 0 };
1470  uint32_t bufsize = sizeof(buf);
1471  if (_NSGetExecutablePath(buf, &bufsize) >= 0)
1472  return ROOT::TMetaUtils::GetRealPath(buf);
1473  return ROOT::TMetaUtils::GetRealPath(info.dli_fname);
1474 # elif defined(R__UNIX)
1475  char buf[PATH_MAX] = { 0 };
1476  // Cross our fingers that /proc/self/exe exists.
1477  if (readlink("/proc/self/exe", buf, sizeof(buf)) > 0)
1478  return ROOT::TMetaUtils::GetRealPath(buf);
1479  std::string pipeCmd = std::string("which \"") + info.dli_fname + "\"";
1480  FILE* pipe = popen(pipeCmd.c_str(), "r");
1481  if (!pipe)
1482  return ROOT::TMetaUtils::GetRealPath(info.dli_fname);
1483  std::string result;
1484  while (fgets(buf, sizeof(buf), pipe)) {
1485  result += buf;
1486  }
1487  pclose(pipe);
1488  return ROOT::TMetaUtils::GetRealPath(result);
1489 # else
1490 # error "Unsupported platform."
1491 # endif
1492  return {};
1493  }
1494 #endif
1495 
1496 }
1497 
1498 ////////////////////////////////////////////////////////////////////////////////
1499 /// Helper to initialize TVirtualStreamerInfo's factor early.
1500 /// Use static initialization to insure only one TStreamerInfo is created.
1501 static bool R__InitStreamerInfoFactory()
1502 {
1503  // Use lambda since SetFactory return void.
1504  auto setFactory = []() {
1505  TVirtualStreamerInfo::SetFactory(new TStreamerInfo());
1506  return kTRUE;
1507  };
1508  static bool doneFactory = setFactory();
1509  return doneFactory; // avoid unused variable warning.
1510 }
1511 
1512 ////////////////////////////////////////////////////////////////////////////////
1513 /// Register Rdict data for future loading by LoadPCM;
1514 
1515 void TCling::RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
1516 {
1517  if (IsFromRootCling())
1518  return;
1519 
1520  if (llvm::sys::fs::exists(pcmFileNameFullPath)) {
1521  ::Error("TCling::RegisterRdictForLoadPCM", "Rdict '%s' is both in Module extension and in File system.", pcmFileNameFullPath.c_str());
1522  return;
1523  }
1524 
1525  // The pcmFileNameFullPath must be resolved already because we cannot resolve
1526  // a link to a non-existent file.
1527  fPendingRdicts[pcmFileNameFullPath] = *pcmContent;
1528 }
1529 
1530 ////////////////////////////////////////////////////////////////////////////////
1531 /// Tries to load a PCM from TFile; returns true on success.
1532 
1533 void TCling::LoadPCMImpl(TFile &pcmFile)
1534 {
1535  auto listOfKeys = pcmFile.GetListOfKeys();
1536 
1537  // This is an empty pcm
1538  if (listOfKeys && ((listOfKeys->GetSize() == 0) || // Nothing here, or
1539  ((listOfKeys->GetSize() == 1) && // only one, and
1540  !strcmp(((TKey *)listOfKeys->At(0))->GetName(), "EMPTY") // name is EMPTY
1541  ))) {
1542  return;
1543  }
1544 
1545  TObjArray *protoClasses;
1546  if (gDebug > 1)
1547  ::Info("TCling::LoadPCMImpl", "reading protoclasses for %s \n", pcmFile.GetName());
1548 
1549  pcmFile.GetObject("__ProtoClasses", protoClasses);
1550 
1551  if (protoClasses) {
1552  for (auto obj : *protoClasses) {
1553  TProtoClass *proto = (TProtoClass *)obj;
1554  TClassTable::Add(proto);
1555  }
1556  // Now that all TClass-es know how to set them up we can update
1557  // existing TClasses, which might cause the creation of e.g. TBaseClass
1558  // objects which in turn requires the creation of TClasses, that could
1559  // come from the PCH, but maybe later in the loop. Instead of resolving
1560  // a dependency graph the addition to the TClassTable above allows us
1561  // to create these dependent TClasses as needed below.
1562  for (auto proto : *protoClasses) {
1563  if (TClass *existingCl = (TClass *)gROOT->GetListOfClasses()->FindObject(proto->GetName())) {
1564  // We have an existing TClass object. It might be emulated
1565  // or interpreted; we now have more information available.
1566  // Make that available.
1567  if (existingCl->GetState() != TClass::kHasTClassInit) {
1568  DictFuncPtr_t dict = gClassTable->GetDict(proto->GetName());
1569  if (!dict) {
1570  ::Error("TCling::LoadPCM", "Inconsistent TClassTable for %s", proto->GetName());
1571  } else {
1572  // This will replace the existing TClass.
1573  TClass *ncl = (*dict)();
1574  if (ncl)
1575  ncl->PostLoadCheck();
1576  }
1577  }
1578  }
1579  }
1580 
1581  protoClasses->Clear(); // Ownership was transfered to TClassTable.
1582  delete protoClasses;
1583  }
1584 
1585  TObjArray *dataTypes;
1586  pcmFile.GetObject("__Typedefs", dataTypes);
1587  if (dataTypes) {
1588  for (auto typedf : *dataTypes)
1589  gROOT->GetListOfTypes()->Add(typedf);
1590  dataTypes->Clear(); // Ownership was transfered to TListOfTypes.
1591  delete dataTypes;
1592  }
1593 
1594  TObjArray *enums;
1595  pcmFile.GetObject("__Enums", enums);
1596  if (enums) {
1597  // Cache the pointers
1598  auto listOfGlobals = gROOT->GetListOfGlobals();
1599  auto listOfEnums = dynamic_cast<THashList *>(gROOT->GetListOfEnums());
1600  // Loop on enums and then on enum constants
1601  for (auto selEnum : *enums) {
1602  const char *enumScope = selEnum->GetTitle();
1603  const char *enumName = selEnum->GetName();
1604  if (strcmp(enumScope, "") == 0) {
1605  // This is a global enum and is added to the
1606  // list of enums and its constants to the list of globals
1607  if (!listOfEnums->THashList::FindObject(enumName)) {
1608  ((TEnum *)selEnum)->SetClass(nullptr);
1609  listOfEnums->Add(selEnum);
1610  }
1611  for (auto enumConstant : *static_cast<TEnum *>(selEnum)->GetConstants()) {
1612  if (!listOfGlobals->FindObject(enumConstant)) {
1613  listOfGlobals->Add(enumConstant);
1614  }
1615  }
1616  } else {
1617  // This enum is in a namespace. A TClass entry is bootstrapped if
1618  // none exists yet and the enum is added to it
1619  TClass *nsTClassEntry = TClass::GetClass(enumScope);
1620  if (!nsTClassEntry) {
1621  nsTClassEntry = new TClass(enumScope, 0, TClass::kNamespaceForMeta, true);
1622  }
1623  auto listOfEnums = nsTClassEntry->fEnums.load();
1624  if (!listOfEnums) {
1625  if ((kIsClass | kIsStruct | kIsUnion) & nsTClassEntry->Property()) {
1626  // For this case, the list will be immutable once constructed
1627  // (i.e. in this case, by the end of this routine).
1628  listOfEnums = nsTClassEntry->fEnums = new TListOfEnums(nsTClassEntry);
1629  } else {
1630  // namespaces can have enums added to them
1631  listOfEnums = nsTClassEntry->fEnums = new TListOfEnumsWithLock(nsTClassEntry);
1632  }
1633  }
1634  if (listOfEnums && !listOfEnums->THashList::FindObject(enumName)) {
1635  ((TEnum *)selEnum)->SetClass(nsTClassEntry);
1636  listOfEnums->Add(selEnum);
1637  }
1638  }
1639  }
1640  enums->Clear();
1641  delete enums;
1642  }
1643 }
1644 
1645 ////////////////////////////////////////////////////////////////////////////////
1646 /// Tries to load a rdict PCM, issues diagnostics if it fails.
1647 
1648 void TCling::LoadPCM(std::string pcmFileNameFullPath)
1649 {
1650  SuspendAutoloadingRAII autoloadOff(this);
1651  SuspendAutoParsing autoparseOff(this);
1652  assert(!pcmFileNameFullPath.empty());
1653  assert(llvm::sys::path::is_absolute(pcmFileNameFullPath));
1654 
1655  // Easier to work with the ROOT interfaces.
1656  TString pcmFileName = pcmFileNameFullPath;
1657 
1658  // Prevent the ROOT-PCMs hitting this during auto-load during
1659  // JITting - which will cause recursive compilation.
1660  // Avoid to call the plugin manager at all.
1661  R__InitStreamerInfoFactory();
1662 
1663  TDirectory::TContext ctxt;
1664  llvm::SaveAndRestore<Int_t> SaveGDebug(gDebug);
1665  if (gDebug > 5) {
1666  gDebug -= 5;
1667  ::Info("TCling::LoadPCM", "Loading ROOT PCM %s", pcmFileName.Data());
1668  } else {
1669  gDebug = 0;
1670  }
1671 
1672  if (llvm::sys::fs::is_symlink_file(pcmFileNameFullPath))
1673  pcmFileNameFullPath = ROOT::TMetaUtils::GetRealPath(pcmFileNameFullPath);
1674 
1675  auto pendingRdict = fPendingRdicts.find(pcmFileNameFullPath);
1676  if (pendingRdict != fPendingRdicts.end()) {
1677  llvm::StringRef pcmContent = pendingRdict->second;
1678  TMemFile::ZeroCopyView_t range{pcmContent.data(), pcmContent.size()};
1679  std::string RDictFileOpts = pcmFileNameFullPath + "?filetype=pcm";
1680  TMemFile pcmMemFile(RDictFileOpts.c_str(), range);
1681 
1682  LoadPCMImpl(pcmMemFile);
1683 
1684  fPendingRdicts.erase(pendingRdict);
1685 
1686  return;
1687  }
1688 
1689  if (!llvm::sys::fs::exists(pcmFileNameFullPath)) {
1690  ::Error("TCling::LoadPCM", "ROOT PCM %s file does not exist",
1691  pcmFileNameFullPath.data());
1692  if (!fPendingRdicts.empty())
1693  for (const auto &rdict : fPendingRdicts)
1694  ::Info("TCling::LoadPCM", "In-memory ROOT PCM candidate %s\n",
1695  rdict.first.c_str());
1696  return;
1697  }
1698 
1699  if (!gROOT->IsRootFile(pcmFileName)) {
1700  Fatal("LoadPCM", "The file %s is not a ROOT as was expected\n", pcmFileName.Data());
1701  return;
1702  }
1703  TFile pcmFile(pcmFileName + "?filetype=pcm", "READ");
1704  LoadPCMImpl(pcmFile);
1705 }
1706 
1707 //______________________________________________________________________________
1708 
1709 namespace {
1710  using namespace clang;
1711 
1712  class ExtLexicalStorageAdder: public RecursiveASTVisitor<ExtLexicalStorageAdder>{
1713  // This class is to be considered an helper for autoparsing.
1714  // It visits the AST and marks all classes (in all of their redeclarations)
1715  // with the setHasExternalLexicalStorage method.
1716  public:
1717  bool VisitRecordDecl(clang::RecordDecl* rcd){
1718  if (gDebug > 2)
1719  Info("ExtLexicalStorageAdder",
1720  "Adding external lexical storage to class %s",
1721  rcd->getNameAsString().c_str());
1722  auto reDeclPtr = rcd->getMostRecentDecl();
1723  do {
1724  reDeclPtr->setHasExternalLexicalStorage();
1725  } while ((reDeclPtr = reDeclPtr->getPreviousDecl()));
1726 
1727  return false;
1728  }
1729  };
1730 
1731 
1732 }
1733 
1734 ////////////////////////////////////////////////////////////////////////////////
1735 ///\returns true if the module map was loaded, false on error or if the map was
1736 /// already loaded.
1737 bool TCling::RegisterPrebuiltModulePath(const std::string &FullPath,
1738  const std::string &ModuleMapName /*= "module.modulemap"*/) const
1739 {
1740  assert(llvm::sys::path::is_absolute(FullPath));
1741  Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
1742  FileManager &FM = PP.getFileManager();
1743  // FIXME: In a ROOT session we can add an include path (through .I /inc/path)
1744  // We should look for modulemap files there too.
1745  const DirectoryEntry *DE = FM.getDirectory(FullPath);
1746  if (DE) {
1747  HeaderSearch &HS = PP.getHeaderSearchInfo();
1748  HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1749  const auto &ModPaths = HSOpts.PrebuiltModulePaths;
1750  bool pathExists = std::find(ModPaths.begin(), ModPaths.end(), FullPath) != ModPaths.end();
1751  if (!pathExists)
1752  HSOpts.AddPrebuiltModulePath(FullPath);
1753  // We cannot use HS.lookupModuleMapFile(DE, /*IsFramework*/ false);
1754  // because its internal call to getFile has CacheFailure set to true.
1755  // In our case, modulemaps can appear any time due to ACLiC.
1756  // Code copied from HS.lookupModuleMapFile.
1757  llvm::SmallString<256> ModuleMapFileName(DE->getName());
1758  llvm::sys::path::append(ModuleMapFileName, ModuleMapName);
1759  const FileEntry *FE = FM.getFile(ModuleMapFileName, /*openFile*/ false,
1760  /*CacheFailure*/ false);
1761 
1762  // FIXME: Calling IsLoaded is slow! Replace this with the appropriate
1763  // call to the clang::ModuleMap class.
1764  if (FE && !this->IsLoaded(FE->getName().data())) {
1765  if (!HS.loadModuleMapFile(FE, /*IsSystem*/ false))
1766  return true;
1767  Error("RegisterPrebuiltModulePath", "Could not load modulemap in %s", ModuleMapFileName.c_str());
1768  }
1769  }
1770  return false;
1771 }
1772 
1773 ////////////////////////////////////////////////////////////////////////////////
1774 /// List of dicts that have the PCM information already in the PCH.
1775 static const std::unordered_set<std::string> gIgnoredPCMNames = {"libCore",
1776  "libRint",
1777  "libThread",
1778  "libRIO",
1779  "libImt",
1780  "libcomplexDict",
1781  "libdequeDict",
1782  "liblistDict",
1783  "libforward_listDict",
1784  "libvectorDict",
1785  "libmapDict",
1786  "libmultimap2Dict",
1787  "libmap2Dict",
1788  "libmultimapDict",
1789  "libsetDict",
1790  "libmultisetDict",
1791  "libunordered_setDict",
1792  "libunordered_multisetDict",
1793  "libunordered_mapDict",
1794  "libunordered_multimapDict",
1795  "libvalarrayDict",
1796  "G__GenVector32",
1797  "G__Smatrix32"};
1798 
1799 static void PrintDlError(const char *dyLibName, const char *modulename)
1800 {
1801 #ifdef R__WIN32
1802  char dyLibError[1000];
1803  FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1804  dyLibError, sizeof(dyLibError), NULL);
1805 #else
1806  const char *dyLibError = dlerror();
1807 #endif
1808  ::Error("TCling::RegisterModule", "Cannot open shared library %s for dictionary %s:\n %s", dyLibName, modulename,
1809  (dyLibError) ? dyLibError : "");
1810 }
1811 
1812 ////////////////////////////////////////////////////////////////////////////////
1813 // Update all the TClass registered in fClassesToUpdate
1814 
1815 void TCling::ProcessClassesToUpdate()
1816 {
1817  while (!fClassesToUpdate.empty()) {
1818  TClass *oldcl = fClassesToUpdate.back().first;
1819  // If somehow the TClass has already been loaded (maybe it was registered several time),
1820  // we skip it. Otherwise, the existing TClass is in mode kInterpreted, kEmulated or
1821  // maybe even kForwardDeclared and needs to replaced.
1822  if (oldcl->GetState() != TClass::kHasTClassInit) {
1823  // if (gDebug > 2) Info("RegisterModule", "Forcing TClass init for %s", oldcl->GetName());
1824  DictFuncPtr_t dict = fClassesToUpdate.back().second;
1825  fClassesToUpdate.pop_back();
1826  // Calling func could manipulate the list so, let maintain the list
1827  // then call the dictionary function.
1828  TClass *ncl = dict();
1829  if (ncl) ncl->PostLoadCheck();
1830  } else {
1831  fClassesToUpdate.pop_back();
1832  }
1833  }
1834 }
1835 ////////////////////////////////////////////////////////////////////////////////
1836 /// Inject the module named "modulename" into cling; load all headers.
1837 /// headers is a 0-terminated array of header files to #include after
1838 /// loading the module. The module is searched for in all $LD_LIBRARY_PATH
1839 /// entries (or %PATH% on Windows).
1840 /// This function gets called by the static initialization of dictionary
1841 /// libraries.
1842 /// The payload code is injected "as is" in the interpreter.
1843 /// The value of 'triggerFunc' is used to find the shared library location.
1844 
1845 void TCling::RegisterModule(const char* modulename,
1846  const char** headers,
1847  const char** includePaths,
1848  const char* payloadCode,
1849  const char* fwdDeclsCode,
1850  void (*triggerFunc)(),
1851  const FwdDeclArgsToKeepCollection_t& fwdDeclsArgToSkip,
1852  const char** classesHeaders,
1853  Bool_t lateRegistration /*=false*/,
1854  Bool_t hasCxxModule /*=false*/)
1855 {
1856  const bool fromRootCling = IsFromRootCling();
1857  // We need the dictionary initialization but we don't want to inject the
1858  // declarations into the interpreter, except for those we really need for
1859  // I/O; see rootcling.cxx after the call to TCling__GetInterpreter().
1860  if (fromRootCling) return;
1861 
1862  // When we cannot provide a module for the library we should enable header
1863  // parsing. This 'mixed' mode ensures gradual migration to modules.
1864  llvm::SaveAndRestore<bool> SaveHeaderParsing(fHeaderParsingOnDemand);
1865  fHeaderParsingOnDemand = !hasCxxModule;
1866 
1867  // Treat Aclic Libs in a special way. Do not delay the parsing.
1868  bool hasHeaderParsingOnDemand = fHeaderParsingOnDemand;
1869  bool isACLiC = strstr(modulename, "_ACLiC_dict") != nullptr;
1870  if (hasHeaderParsingOnDemand && isACLiC) {
1871  if (gDebug>1)
1872  Info("TCling::RegisterModule",
1873  "Header parsing on demand is active but this is an Aclic library. Disabling it for this library.");
1874  hasHeaderParsingOnDemand = false;
1875  }
1876 
1877 
1878  // Make sure we relookup symbols that were search for before we loaded
1879  // their autoparse information. We could be more subtil and remove only
1880  // the failed one or only the one in this module, but for now this is
1881  // better than nothing.
1882  fLookedUpClasses.clear();
1883 
1884  // Make sure we do not set off autoloading or autoparsing during the
1885  // module registration!
1886  SuspendAutoloadingRAII autoLoadOff(this);
1887 
1888  for (const char** inclPath = includePaths; *inclPath; ++inclPath) {
1889  TCling::AddIncludePath(*inclPath);
1890  }
1891  cling::Transaction* T = 0;
1892  // Put the template decls and the number of arguments to skip in the TNormalizedCtxt
1893  for (auto& fwdDeclArgToSkipPair : fwdDeclsArgToSkip){
1894  const std::string& fwdDecl = fwdDeclArgToSkipPair.first;
1895  const int nArgsToSkip = fwdDeclArgToSkipPair.second;
1896  auto compRes = fInterpreter->declare(fwdDecl.c_str(), &T);
1897  assert(cling::Interpreter::kSuccess == compRes &&
1898  "A fwd declaration could not be compiled");
1899  if (compRes!=cling::Interpreter::kSuccess){
1900  Warning("TCling::RegisterModule",
1901  "Problems in declaring string '%s' were encountered.",
1902  fwdDecl.c_str()) ;
1903  continue;
1904  }
1905 
1906  // Drill through namespaces recursively until the template is found
1907  if(ClassTemplateDecl* TD = FindTemplateInNamespace(T->getFirstDecl().getSingleDecl())){
1908  fNormalizedCtxt->AddTemplAndNargsToKeep(TD->getCanonicalDecl(), nArgsToSkip);
1909  }
1910 
1911  }
1912 
1913  // FIXME: Remove #define __ROOTCLING__ once PCMs are there.
1914  // This is used to give Sema the same view on ACLiC'ed files (which
1915  // are then #included through the dictionary) as rootcling had.
1916  TString code = gNonInterpreterClassDef;
1917  if (payloadCode)
1918  code += payloadCode;
1919 
1920  std::string dyLibName = FindLibraryName(triggerFunc);
1921  assert(!llvm::sys::fs::is_symlink_file(dyLibName));
1922 
1923  if (dyLibName.empty()) {
1924  ::Error("TCling::RegisterModule", "Dictionary trigger function for %s not found", modulename);
1925  return;
1926  }
1927 
1928  // The triggerFunc may not be in a shared object but in an executable.
1929  bool isSharedLib = cling::DynamicLibraryManager::isSharedLibrary(dyLibName);
1930 
1931  bool wasDlopened = false;
1932 
1933  // If this call happens after dlopen has finished (i.e. late registration)
1934  // there is no need to dlopen the library recursively. See ROOT-8437 where
1935  // the dyLibName would correspond to the binary.
1936  if (!lateRegistration) {
1937 
1938  if (isSharedLib) {
1939  // We need to open the dictionary shared library, to resolve symbols
1940  // requested by the JIT from it: as the library is currently being dlopen'ed,
1941  // its symbols are not yet reachable from the process.
1942  // Recursive dlopen seems to work just fine.
1943  void* dyLibHandle = dlopen(dyLibName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
1944  if (dyLibHandle) {
1945  fRegisterModuleDyLibs.push_back(dyLibHandle);
1946  wasDlopened = true;
1947  } else {
1948  PrintDlError(dyLibName.c_str(), modulename);
1949  }
1950  }
1951  } // if (!lateRegistration)
1952 
1953  if (hasHeaderParsingOnDemand && fwdDeclsCode){
1954  // We now parse the forward declarations. All the classes are then modified
1955  // in order for them to have an external lexical storage.
1956  std::string fwdDeclsCodeLessEnums;
1957  {
1958  // Search for enum forward decls and only declare them if no
1959  // declaration exists yet.
1960  std::string fwdDeclsLine;
1961  std::istringstream fwdDeclsCodeStr(fwdDeclsCode);
1962  std::vector<std::string> scopes;
1963  while (std::getline(fwdDeclsCodeStr, fwdDeclsLine)) {
1964  const auto enumPos = fwdDeclsLine.find("enum __attribute__((annotate(\"");
1965  // We check if the line contains a fwd declaration of an enum
1966  if (enumPos != std::string::npos) {
1967  // We clear the scopes which we may have carried from a previous iteration
1968  scopes.clear();
1969  // We check if the enum is not in a scope. If yes, save its name
1970  // and the names of the enclosing scopes.
1971  if (enumPos != 0) {
1972  // it's enclosed in namespaces. We need to understand what they are
1973  auto nsPos = fwdDeclsLine.find("namespace");
1974  R__ASSERT(nsPos < enumPos && "Inconsistent enum and enclosing scope parsing!");
1975  while (nsPos < enumPos && nsPos != std::string::npos) {
1976  // we have a namespace, let's put it in the collection of scopes
1977  const auto nsNameStart = nsPos + 10;
1978  const auto nsNameEnd = fwdDeclsLine.find('{', nsNameStart);
1979  const auto nsName = fwdDeclsLine.substr(nsNameStart, nsNameEnd - nsNameStart);
1980  scopes.push_back(nsName);
1981  nsPos = fwdDeclsLine.find("namespace", nsNameEnd);
1982  }
1983  }
1984  clang::DeclContext* DC = 0;
1985  for (auto &&aScope: scopes) {
1986  DC = cling::utils::Lookup::Namespace(&fInterpreter->getSema(), aScope.c_str(), DC);
1987  if (!DC) {
1988  // No decl context means we have to fwd declare the enum.
1989  break;
1990  }
1991  }
1992  if (scopes.empty() || DC) {
1993  // We know the scope; let's look for the enum.
1994  size_t posEnumName = fwdDeclsLine.find("\"))) ", 32);
1995  R__ASSERT(posEnumName != std::string::npos && "Inconsistent enum fwd decl!");
1996  posEnumName += 5; // skip "\"))) "
1997  while (isspace(fwdDeclsLine[posEnumName]))
1998  ++posEnumName;
1999  size_t posEnumNameEnd = fwdDeclsLine.find(" : ", posEnumName);
2000  R__ASSERT(posEnumNameEnd != std::string::npos && "Inconsistent enum fwd decl (end)!");
2001  while (isspace(fwdDeclsLine[posEnumNameEnd]))
2002  --posEnumNameEnd;
2003  // posEnumNameEnd now points to the last character of the name.
2004 
2005  std::string enumName = fwdDeclsLine.substr(posEnumName,
2006  posEnumNameEnd - posEnumName + 1);
2007 
2008  if (clang::NamedDecl* enumDecl
2009  = cling::utils::Lookup::Named(&fInterpreter->getSema(),
2010  enumName.c_str(), DC)) {
2011  // We have an existing enum decl (forward or definition);
2012  // skip this.
2013  R__ASSERT(llvm::dyn_cast<clang::EnumDecl>(enumDecl) && "not an enum decl!");
2014  (void)enumDecl;
2015  continue;
2016  }
2017  }
2018  }
2019 
2020  fwdDeclsCodeLessEnums += fwdDeclsLine + "\n";
2021  }
2022  }
2023 
2024  if (fwdDeclsCodeLessEnums.size() != 0){ // Avoid the overhead if nothing is to be declared
2025  auto compRes = fInterpreter->declare(fwdDeclsCodeLessEnums, &T);
2026  assert(cling::Interpreter::kSuccess == compRes &&
2027  "The forward declarations could not be compiled");
2028  if (compRes!=cling::Interpreter::kSuccess){
2029  Warning("TCling::RegisterModule",
2030  "Problems in compiling forward declarations for module %s: '%s'",
2031  modulename, fwdDeclsCodeLessEnums.c_str()) ;
2032  }
2033  else if (T){
2034  // Loop over all decls in the transaction and go through them all
2035  // to mark them properly.
2036  // In order to do that, we first iterate over all the DelayedCallInfos
2037  // within the transaction. Then we loop over all Decls in the DeclGroupRef
2038  // contained in the DelayedCallInfos. For each decl, we traverse.
2039  ExtLexicalStorageAdder elsa;
2040  for (auto dciIt = T->decls_begin();dciIt!=T->decls_end();dciIt++){
2041  cling::Transaction::DelayCallInfo& dci = *dciIt;
2042  for(auto dit = dci.m_DGR.begin(); dit != dci.m_DGR.end(); ++dit) {
2043  clang::Decl* declPtr = *dit;
2044  elsa.TraverseDecl(declPtr);
2045  }
2046  }
2047  }
2048  }
2049 
2050  // Now we register all the headers necessary for the class
2051  // Typical format of the array:
2052  // {"A", "classes.h", "@",
2053  // "vector<A>", "vector", "@",
2054  // "myClass", payloadCode, "@",
2055  // nullptr};
2056 
2057  std::string temp;
2058  for (const char** classesHeader = classesHeaders; *classesHeader; ++classesHeader) {
2059  temp=*classesHeader;
2060 
2061  size_t theTemplateHash = 0;
2062  bool addTemplate = false;
2063  size_t posTemplate = temp.find('<');
2064  if (posTemplate != std::string::npos) {
2065  // Add an entry for the template itself.
2066  std::string templateName = temp.substr(0, posTemplate);
2067  theTemplateHash = fStringHashFunction(templateName);
2068  addTemplate = true;
2069  }
2070  size_t theHash = fStringHashFunction(temp);
2071  classesHeader++;
2072  for (const char** classesHeader_inner = classesHeader; 0!=strcmp(*classesHeader_inner,"@"); ++classesHeader_inner,++classesHeader){
2073  // This is done in order to distinguish headers from files and from the payloadCode
2074  if (payloadCode == *classesHeader_inner ){
2075  fPayloads.insert(theHash);
2076  if (addTemplate) fPayloads.insert(theTemplateHash);
2077  }
2078  if (gDebug > 2)
2079  Info("TCling::RegisterModule",
2080  "Adding a header for %s", temp.c_str());
2081  fClassesHeadersMap[theHash].push_back(*classesHeader_inner);
2082  if (addTemplate) {
2083  if (fClassesHeadersMap.find(theTemplateHash) == fClassesHeadersMap.end()) {
2084  fClassesHeadersMap[theTemplateHash].push_back(*classesHeader_inner);
2085  }
2086  addTemplate = false;
2087  }
2088  }
2089  }
2090  }
2091 
2092  clang::Sema &TheSema = fInterpreter->getSema();
2093 
2094  bool ModuleWasSuccessfullyLoaded = false;
2095  if (hasCxxModule) {
2096  std::string ModuleName = modulename;
2097  if (llvm::StringRef(modulename).startswith("lib"))
2098  ModuleName = llvm::StringRef(modulename).substr(3).str();
2099 
2100  // In case we are directly loading the library via gSystem->Load() without
2101  // specifying the relevant include paths we should try loading the
2102  // modulemap next to the library location.
2103  clang::Preprocessor &PP = TheSema.getPreprocessor();
2104  std::string ModuleMapName;
2105  if (isACLiC)
2106  ModuleMapName = ModuleName + ".modulemap";
2107  else
2108  ModuleMapName = "module.modulemap";
2109  RegisterPrebuiltModulePath(llvm::sys::path::parent_path(dyLibName),
2110  ModuleMapName);
2111 
2112  // FIXME: We should only complain for modules which we know to exist. For example, we should not complain about
2113  // modules such as GenVector32 because it needs to fall back to GenVector.
2114  ModuleWasSuccessfullyLoaded = LoadModule(ModuleName, *fInterpreter);
2115  if (!ModuleWasSuccessfullyLoaded) {
2116  // Only report if we found the module in the modulemap.
2117  clang::HeaderSearch &headerSearch = PP.getHeaderSearchInfo();
2118  clang::ModuleMap &moduleMap = headerSearch.getModuleMap();
2119  if (moduleMap.findModule(ModuleName))
2120  Info("TCling::RegisterModule", "Module %s in modulemap failed to load.", ModuleName.c_str());
2121  }
2122  }
2123 
2124  if (gIgnoredPCMNames.find(modulename) == gIgnoredPCMNames.end()) {
2125  llvm::SmallString<256> pcmFileNameFullPath(dyLibName);
2126  // The path dyLibName might not be absolute. This can happen if dyLibName
2127  // is linked to an executable in the same folder.
2128  llvm::sys::fs::make_absolute(pcmFileNameFullPath);
2129  llvm::sys::path::remove_filename(pcmFileNameFullPath);
2130  llvm::sys::path::append(pcmFileNameFullPath,
2131  ROOT::TMetaUtils::GetModuleFileName(modulename));
2132  LoadPCM(pcmFileNameFullPath.str().str());
2133  }
2134 
2135  { // scope within which diagnostics are de-activated
2136  // For now we disable diagnostics because we saw them already at
2137  // dictionary generation time. That won't be an issue with the PCMs.
2138 
2139  clangDiagSuppr diagSuppr(TheSema.getDiagnostics());
2140 
2141 #if defined(R__MUST_REVISIT)
2142 #if R__MUST_REVISIT(6,2)
2143  Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
2144 #endif
2145 #endif
2146 
2147  if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand){
2148  SuspendAutoParsing autoParseRaii(this);
2149 
2150  const cling::Transaction* watermark = fInterpreter->getLastTransaction();
2151  cling::Interpreter::CompilationResult compRes = fInterpreter->parseForModule(code.Data());
2152  if (isACLiC) {
2153  // Register an unload point.
2154  fMetaProcessor->registerUnloadPoint(watermark, headers[0]);
2155  }
2156 
2157  assert(cling::Interpreter::kSuccess == compRes &&
2158  "Payload code of a dictionary could not be parsed correctly.");
2159  if (compRes!=cling::Interpreter::kSuccess) {
2160  Warning("TCling::RegisterModule",
2161  "Problems declaring payload for module %s.", modulename) ;
2162  }
2163  }
2164  }
2165 
2166  // Now that all the header have been registered/compiled, let's
2167  // make sure to 'reset' the TClass that have a class init in this module
2168  // but already had their type information available (using information/header
2169  // loaded from other modules or from class rules or from opening a TFile
2170  // or from loading header in a way that did not provoke the loading of
2171  // the library we just loaded).
2172  ProcessClassesToUpdate();
2173 
2174  if (!ModuleWasSuccessfullyLoaded && !hasHeaderParsingOnDemand) {
2175  // __ROOTCLING__ might be pulled in through PCH
2176  fInterpreter->declare("#ifdef __ROOTCLING__\n"
2177  "#undef __ROOTCLING__\n"
2178  + gInterpreterClassDef +
2179  "#endif");
2180  }
2181 
2182  if (wasDlopened) {
2183  assert(isSharedLib);
2184  void* dyLibHandle = fRegisterModuleDyLibs.back();
2185  fRegisterModuleDyLibs.pop_back();
2186  dlclose(dyLibHandle);
2187  }
2188 }
2189 
2190 ////////////////////////////////////////////////////////////////////////////////
2191 /// Register classes that already existed prior to their dictionary loading
2192 /// and that already had a ClassInfo (and thus would not be refresh via
2193 /// UpdateClassInfo.
2194 
2195 void TCling::RegisterTClassUpdate(TClass *oldcl,DictFuncPtr_t dict)
2196 {
2197  fClassesToUpdate.push_back(std::make_pair(oldcl,dict));
2198 }
2199 
2200 ////////////////////////////////////////////////////////////////////////////////
2201 /// If the dictionary is loaded, we can remove the class from the list
2202 /// (otherwise the class might be loaded twice).
2203 
2204 void TCling::UnRegisterTClassUpdate(const TClass *oldcl)
2205 {
2206  typedef std::vector<std::pair<TClass*,DictFuncPtr_t> >::iterator iterator;
2207  iterator stop = fClassesToUpdate.end();
2208  for(iterator i = fClassesToUpdate.begin();
2209  i != stop;
2210  ++i)
2211  {
2212  if ( i->first == oldcl ) {
2213  fClassesToUpdate.erase(i);
2214  return;
2215  }
2216  }
2217 }
2218 
2219 
2220 ////////////////////////////////////////////////////////////////////////////////
2221 /// Let cling process a command line.
2222 ///
2223 /// If the command is executed and the error is 0, then the return value
2224 /// is the int value corresponding to the result of the executed command
2225 /// (float and double return values will be truncated).
2226 ///
2227 
2228 // Method for handling the interpreter exceptions.
2229 // the MetaProcessor is passing in as argument to teh function, because
2230 // cling::Interpreter::CompilationResult is a nested class and it cannot be
2231 // forward declared, thus this method cannot be a static member function
2232 // of TCling.
2233 
2234 static int HandleInterpreterException(cling::MetaProcessor* metaProcessor,
2235  const char* input_line,
2236  cling::Interpreter::CompilationResult& compRes,
2237  cling::Value* result)
2238 {
2239  try {
2240  return metaProcessor->process(input_line, compRes, result);
2241  }
2242  catch (cling::InterpreterException& ex)
2243  {
2244  Error("HandleInterpreterException", "%s.\n%s", ex.what(), "Execution of your code was aborted.");
2245  ex.diagnose();
2246  compRes = cling::Interpreter::kFailure;
2247  }
2248  return 0;
2249 }
2250 
2251 ////////////////////////////////////////////////////////////////////////////////
2252 
2253 bool TCling::DiagnoseIfInterpreterException(const std::exception &e) const
2254 {
2255  if (auto ie = dynamic_cast<const cling::InterpreterException*>(&e)) {
2256  ie->diagnose();
2257  return true;
2258  }
2259  return false;
2260 }
2261 
2262 ////////////////////////////////////////////////////////////////////////////////
2263 
2264 Long_t TCling::ProcessLine(const char* line, EErrorCode* error/*=0*/)
2265 {
2266  // Copy the passed line, it comes from a static buffer in TApplication
2267  // which can be reentered through the Cling evaluation routines,
2268  // which would overwrite the static buffer and we would forget what we
2269  // were doing.
2270  //
2271  TString sLine(line);
2272  if (strstr(line,fantomline)) {
2273  // End-Of-Line action
2274  // See the comment (copied from above):
2275  // It is a "fantom" method to synchronize user keyboard input
2276  // and ROOT prompt line (for WIN32)
2277  // and is implemented by
2278  if (gApplication) {
2279  if (gApplication->IsCmdThread()) {
2280  R__LOCKGUARD(fLockProcessLine ? gInterpreterMutex : 0);
2281  gROOT->SetLineIsProcessing();
2282 
2283  UpdateAllCanvases();
2284 
2285  gROOT->SetLineHasBeenProcessed();
2286  }
2287  }
2288  return 0;
2289  }
2290 
2291  if (gGlobalMutex && !gInterpreterMutex && fLockProcessLine) {
2292  gGlobalMutex->Lock();
2293  if (!gInterpreterMutex)
2294  gInterpreterMutex = gGlobalMutex->Factory(kTRUE);
2295  gGlobalMutex->UnLock();
2296  }
2297  R__LOCKGUARD_CLING(fLockProcessLine ? gInterpreterMutex : 0);
2298  gROOT->SetLineIsProcessing();
2299 
2300  struct InterpreterFlagsRAII {
2301  cling::Interpreter* fInterpreter;
2302  bool fWasDynamicLookupEnabled;
2303 
2304  InterpreterFlagsRAII(cling::Interpreter* interp):
2305  fInterpreter(interp),
2306  fWasDynamicLookupEnabled(interp->isDynamicLookupEnabled())
2307  {
2308  fInterpreter->enableDynamicLookup(true);
2309  }
2310  ~InterpreterFlagsRAII() {
2311  fInterpreter->enableDynamicLookup(fWasDynamicLookupEnabled);
2312  gROOT->SetLineHasBeenProcessed();
2313  }
2314  } interpreterFlagsRAII(GetInterpreterImpl());
2315 
2316  // A non-zero returned value means the given line was
2317  // not a complete statement.
2318  int indent = 0;
2319  // This will hold the resulting value of the evaluation the given line.
2320  cling::Value result;
2321  cling::Interpreter::CompilationResult compRes = cling::Interpreter::kSuccess;
2322  if (!strncmp(sLine.Data(), ".L", 2) || !strncmp(sLine.Data(), ".x", 2) ||
2323  !strncmp(sLine.Data(), ".X", 2)) {
2324  // If there was a trailing "+", then CINT compiled the code above,
2325  // and we will need to strip the "+" before passing the line to cling.
2326  TString mod_line(sLine);
2327  TString aclicMode;
2328  TString arguments;
2329  TString io;
2330  TString fname = gSystem->SplitAclicMode(sLine.Data() + 3,
2331  aclicMode, arguments, io);
2332  if (aclicMode.Length()) {
2333  // Remove the leading '+'
2334  R__ASSERT(aclicMode[0]=='+' && "ACLiC mode must start with a +");
2335  aclicMode[0]='k'; // We always want to keep the .so around.
2336  if (aclicMode[1]=='+') {
2337  // We have a 2nd +
2338  aclicMode[1]='f'; // We want to force the recompilation.
2339  }
2340  if (!gSystem->CompileMacro(fname,aclicMode)) {
2341  // ACLiC failed.
2342  compRes = cling::Interpreter::kFailure;
2343  } else {
2344  if (strncmp(sLine.Data(), ".L", 2) != 0) {
2345  // if execution was requested.
2346 
2347  if (arguments.Length()==0) {
2348  arguments = "()";
2349  }
2350  // We need to remove the extension.
2351  Ssiz_t ext = fname.Last('.');
2352  if (ext != kNPOS) {
2353  fname.Remove(ext);
2354  }
2355  const char *function = gSystem->BaseName(fname);
2356  mod_line = function + arguments + io;
2357  indent = HandleInterpreterException(GetMetaProcessorImpl(), mod_line, compRes, &result);
2358  }
2359  }
2360  } else {
2361  // not ACLiC
2362  size_t unnamedMacroOpenCurly;
2363  {
2364  std::string code;
2365  std::string codeline;
2366  std::ifstream in(fname);
2367  while (in) {
2368  std::getline(in, codeline);
2369  code += codeline + "\n";
2370  }
2371  unnamedMacroOpenCurly
2372  = cling::utils::isUnnamedMacro(code, fInterpreter->getCI()->getLangOpts());
2373  }
2374 
2375  fCurExecutingMacros.push_back(fname);
2376  if (unnamedMacroOpenCurly != std::string::npos) {
2377  compRes = fMetaProcessor->readInputFromFile(fname.Data(), &result,
2378  unnamedMacroOpenCurly);
2379  } else {
2380  // No DynLookup for .x, .L of named macros.
2381  fInterpreter->enableDynamicLookup(false);
2382  indent = HandleInterpreterException(GetMetaProcessorImpl(), mod_line, compRes, &result);
2383  }
2384  fCurExecutingMacros.pop_back();
2385  }
2386  } // .L / .X / .x
2387  else {
2388  if (0!=strncmp(sLine.Data(), ".autodict ",10) && sLine != ".autodict") {
2389  // explicitly ignore .autodict without having to support it
2390  // in cling.
2391 
2392  // Turn off autoparsing if this is an include directive
2393  bool isInclusionDirective = sLine.Contains("\n#include") || sLine.BeginsWith("#include");
2394  if (isInclusionDirective) {
2395  SuspendAutoParsing autoParseRaii(this);
2396  indent = HandleInterpreterException(GetMetaProcessorImpl(), sLine, compRes, &result);
2397  } else {
2398  indent = HandleInterpreterException(GetMetaProcessorImpl(), sLine, compRes, &result);
2399  }
2400  }
2401  }
2402  if (result.isValid())
2403  RegisterTemporary(result);
2404  if (indent) {
2405  if (error)
2406  *error = kProcessing;
2407  return 0;
2408  }
2409  if (error) {
2410  switch (compRes) {
2411  case cling::Interpreter::kSuccess: *error = kNoError; break;
2412  case cling::Interpreter::kFailure: *error = kRecoverable; break;
2413  case cling::Interpreter::kMoreInputExpected: *error = kProcessing; break;
2414  }
2415  }
2416  if (compRes == cling::Interpreter::kSuccess
2417  && result.isValid()
2418  && !result.isVoid())
2419  {
2420  return result.simplisticCastAs<long>();
2421  }
2422  return 0;
2423 }
2424 
2425 ////////////////////////////////////////////////////////////////////////////////
2426 /// No-op; see TRint instead.
2427 
2428 void TCling::PrintIntro()
2429 {
2430 }
2431 
2432 ////////////////////////////////////////////////////////////////////////////////
2433 /// Add the given path to the list of directories in which the interpreter
2434 /// looks for include files. Only one path item can be specified at a
2435 /// time, i.e. "path1:path2" is NOT supported.
2436 
2437 void TCling::AddIncludePath(const char *path)
2438 {
2439  R__LOCKGUARD(gInterpreterMutex);
2440  // Favorite source of annoyance: gSystem->AddIncludePath() needs "-I",
2441  // gCling->AddIncludePath() does not! Work around that inconsistency:
2442  if (path[0] == '-' && path[1] == 'I')
2443  path += 2;
2444 
2445  fInterpreter->AddIncludePath(path);
2446 }
2447 
2448 ////////////////////////////////////////////////////////////////////////////////
2449 /// Visit all members over members, recursing over base classes.
2450 
2451 void TCling::InspectMembers(TMemberInspector& insp, const void* obj,
2452  const TClass* cl, Bool_t isTransient)
2453 {
2454  if (insp.GetObjectValidity() == TMemberInspector::kUnset) {
2455  insp.SetObjectValidity(obj ? TMemberInspector::kValidObjectGiven
2456  : TMemberInspector::kNoObjectGiven);
2457  }
2458 
2459  if (!cl || cl->GetCollectionProxy()) {
2460  // We do not need to investigate the content of the STL
2461  // collection, they are opaque to us (and details are
2462  // uninteresting).
2463  return;
2464  }
2465 
2466  static const TClassRef clRefString("std::string");
2467  if (clRefString == cl) {
2468  // We stream std::string without going through members..
2469  return;
2470  }
2471 
2472  if (TClassEdit::IsStdArray(cl->GetName())) {
2473  // We treat std arrays as C arrays
2474  return;
2475  }
2476 
2477  const char* cobj = (const char*) obj; // for ptr arithmetics
2478 
2479  // Treat the case of std::complex in a special manner. We want to enforce
2480  // the layout of a stl implementation independent class, which is the
2481  // complex as implemented in ROOT5.
2482 
2483  // A simple lambda to simplify the code
2484  auto inspInspect = [&] (ptrdiff_t offset){
2485  insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_real", cobj, isTransient);
2486  insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), "_imag", cobj + offset, isTransient);
2487  };
2488 
2489  auto complexType = TClassEdit::GetComplexType(cl->GetName());
2490  switch(complexType) {
2491  case TClassEdit::EComplexType::kNone:
2492  {
2493  break;
2494  }
2495  case TClassEdit::EComplexType::kFloat:
2496  {
2497  inspInspect(sizeof(float));
2498  return;
2499  }
2500  case TClassEdit::EComplexType::kDouble:
2501  {
2502  inspInspect(sizeof(double));
2503  return;
2504  }
2505  case TClassEdit::EComplexType::kInt:
2506  {
2507  inspInspect(sizeof(int));
2508  return;
2509  }
2510  case TClassEdit::EComplexType::kLong:
2511  {
2512  inspInspect(sizeof(long));
2513  return;
2514  }
2515  }
2516 
2517  static clang::PrintingPolicy
2518  printPol(fInterpreter->getCI()->getLangOpts());
2519  if (printPol.Indentation) {
2520  // not yet initialized
2521  printPol.Indentation = 0;
2522  printPol.SuppressInitializers = true;
2523  }
2524 
2525  const char* clname = cl->GetName();
2526  // Printf("Inspecting class %s\n", clname);
2527 
2528  const clang::ASTContext& astContext = fInterpreter->getCI()->getASTContext();
2529  const clang::Decl *scopeDecl = 0;
2530  const clang::Type *recordType = 0;
2531 
2532  if (cl->GetClassInfo()) {
2533  TClingClassInfo * clingCI = (TClingClassInfo *)cl->GetClassInfo();
2534  scopeDecl = clingCI->GetDecl();
2535  recordType = clingCI->GetType();
2536  } else {
2537  const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
2538  // Diags will complain about private classes:
2539  scopeDecl = lh.findScope(clname, cling::LookupHelper::NoDiagnostics,
2540  &recordType);
2541  }
2542  if (!scopeDecl) {
2543  Error("InspectMembers", "Cannot find Decl for class %s", clname);
2544  return;
2545  }
2546  const clang::CXXRecordDecl* recordDecl
2547  = llvm::dyn_cast<const clang::CXXRecordDecl>(scopeDecl);
2548  if (!recordDecl) {
2549  Error("InspectMembers", "Cannot find Decl for class %s is not a CXXRecordDecl.", clname);
2550  return;
2551  }
2552 
2553  {
2554  // Force possible deserializations first. We need to have no pending
2555  // Transaction when passing control flow to the inspector below (ROOT-7779).
2556  cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
2557 
2558  astContext.getASTRecordLayout(recordDecl);
2559 
2560  for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2561  eField = recordDecl->field_end(); iField != eField; ++iField) {}
2562  }
2563 
2564  const clang::ASTRecordLayout& recLayout
2565  = astContext.getASTRecordLayout(recordDecl);
2566 
2567  // TVirtualCollectionProxy *proxy = cl->GetCollectionProxy();
2568  // if (proxy && ( proxy->GetProperties() & TVirtualCollectionProxy::kIsEmulated ) ) {
2569  // Error("InspectMembers","The TClass for %s has an emulated proxy but we are looking at a compiled version of the collection!\n",
2570  // cl->GetName());
2571  // }
2572  if (cl->Size() != recLayout.getSize().getQuantity()) {
2573  Error("InspectMembers","TClass and cling disagree on the size of the class %s, respectively %d %lld\n",
2574  cl->GetName(),cl->Size(),(Long64_t)recLayout.getSize().getQuantity());
2575  }
2576 
2577  unsigned iNField = 0;
2578  // iterate over fields
2579  // FieldDecls are non-static, else it would be a VarDecl.
2580  for (clang::RecordDecl::field_iterator iField = recordDecl->field_begin(),
2581  eField = recordDecl->field_end(); iField != eField;
2582  ++iField, ++iNField) {
2583 
2584 
2585  clang::QualType memberQT = iField->getType();
2586  if (recordType) {
2587  // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2588  memberQT = ROOT::TMetaUtils::ReSubstTemplateArg(memberQT, recordType);
2589  }
2590  memberQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, memberQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2591  if (memberQT.isNull()) {
2592  std::string memberName;
2593  llvm::raw_string_ostream stream(memberName);
2594  // Don't trigger fopen of the source file to count lines:
2595  printPol.AnonymousTagLocations = false;
2596  iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2597  stream.flush();
2598  Error("InspectMembers",
2599  "Cannot retrieve QualType for member %s while inspecting class %s",
2600  memberName.c_str(), clname);
2601  continue; // skip member
2602  }
2603  const clang::Type* memType = memberQT.getTypePtr();
2604  if (!memType) {
2605  std::string memberName;
2606  llvm::raw_string_ostream stream(memberName);
2607  // Don't trigger fopen of the source file to count lines:
2608  printPol.AnonymousTagLocations = false;
2609  iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2610  stream.flush();
2611  Error("InspectMembers",
2612  "Cannot retrieve Type for member %s while inspecting class %s",
2613  memberName.c_str(), clname);
2614  continue; // skip member
2615  }
2616 
2617  const clang::Type* memNonPtrType = memType;
2618  Bool_t ispointer = false;
2619  if (memNonPtrType->isPointerType()) {
2620  ispointer = true;
2621  clang::QualType ptrQT
2622  = memNonPtrType->getAs<clang::PointerType>()->getPointeeType();
2623  if (recordType) {
2624  // if (we_need_to_do_the_subst_because_the_class_is_a_template_instance_of_double32_t)
2625  ptrQT = ROOT::TMetaUtils::ReSubstTemplateArg(ptrQT, recordType);
2626  }
2627  ptrQT = cling::utils::Transform::GetPartiallyDesugaredType(astContext, ptrQT, fNormalizedCtxt->GetConfig(), false /* fully qualify */);
2628  if (ptrQT.isNull()) {
2629  std::string memberName;
2630  llvm::raw_string_ostream stream(memberName);
2631  // Don't trigger fopen of the source file to count lines:
2632  printPol.AnonymousTagLocations = false;
2633  iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2634  stream.flush();
2635  Error("InspectMembers",
2636  "Cannot retrieve pointee Type for member %s while inspecting class %s",
2637  memberName.c_str(), clname);
2638  continue; // skip member
2639  }
2640  memNonPtrType = ptrQT.getTypePtr();
2641  }
2642 
2643  // assemble array size(s): "[12][4][]"
2644  llvm::SmallString<8> arraySize;
2645  const clang::ArrayType* arrType = memNonPtrType->getAsArrayTypeUnsafe();
2646  unsigned arrLevel = 0;
2647  bool haveErrorDueToArray = false;
2648  while (arrType) {
2649  ++arrLevel;
2650  arraySize += '[';
2651  const clang::ConstantArrayType* constArrType =
2652  clang::dyn_cast<clang::ConstantArrayType>(arrType);
2653  if (constArrType) {
2654  constArrType->getSize().toStringUnsigned(arraySize);
2655  }
2656  arraySize += ']';
2657  clang::QualType subArrQT = arrType->getElementType();
2658  if (subArrQT.isNull()) {
2659  std::string memberName;
2660  llvm::raw_string_ostream stream(memberName);
2661  // Don't trigger fopen of the source file to count lines:
2662  printPol.AnonymousTagLocations = false;
2663  iField->getNameForDiagnostic(stream, printPol, true /*fqi*/);
2664  stream.flush();
2665  Error("InspectMembers",
2666  "Cannot retrieve QualType for array level %d (i.e. element type of %s) for member %s while inspecting class %s",
2667  arrLevel, subArrQT.getAsString(printPol).c_str(),
2668  memberName.c_str(), clname);
2669  haveErrorDueToArray = true;
2670  break;
2671  }
2672  arrType = subArrQT.getTypePtr()->getAsArrayTypeUnsafe();
2673  }
2674  if (haveErrorDueToArray) {
2675  continue; // skip member
2676  }
2677 
2678  // construct member name
2679  std::string fieldName;
2680  if (memType->isPointerType()) {
2681  fieldName = "*";
2682  }
2683 
2684  // Check if this field has a custom ioname, if not, just use the one of the decl
2685  std::string ioname(iField->getName());
2686  ROOT::TMetaUtils::ExtractAttrPropertyFromName(**iField,"ioname",ioname);
2687  fieldName += ioname;
2688  fieldName += arraySize;
2689 
2690  // get member offset
2691  // NOTE currently we do not support bitfield and do not support
2692  // member that are not aligned on 'bit' boundaries.
2693  clang::CharUnits offset(astContext.toCharUnitsFromBits(recLayout.getFieldOffset(iNField)));
2694  ptrdiff_t fieldOffset = offset.getQuantity();
2695 
2696  // R__insp.Inspect(R__cl, R__insp.GetParent(), "fBits[2]", fBits);
2697  // R__insp.Inspect(R__cl, R__insp.GetParent(), "fName", &fName);
2698  // R__insp.InspectMember(fName, "fName.");
2699  // R__insp.Inspect(R__cl, R__insp.GetParent(), "*fClass", &fClass);
2700 
2701  // If the class has a custom streamer and the type of the filed is a
2702  // private enum, struct or class, skip it.
2703  if (!insp.IsTreatingNonAccessibleTypes()){
2704  auto iFiledQtype = iField->getType();
2705  if (auto tagDecl = iFiledQtype->getAsTagDecl()){
2706  auto declAccess = tagDecl->getAccess();
2707  if (declAccess == AS_private || declAccess == AS_protected) {
2708  continue;
2709  }
2710  }
2711  }
2712 
2713  insp.Inspect(const_cast<TClass*>(cl), insp.GetParent(), fieldName.c_str(), cobj + fieldOffset, isTransient);
2714 
2715  if (!ispointer) {
2716  const clang::CXXRecordDecl* fieldRecDecl = memNonPtrType->getAsCXXRecordDecl();
2717  if (fieldRecDecl && !fieldRecDecl->isAnonymousStructOrUnion()) {
2718  // nested objects get an extra call to InspectMember
2719  // R__insp.InspectMember("FileStat_t", (void*)&fFileStat, "fFileStat.", false);
2720  std::string sFieldRecName;
2721  if (!ROOT::TMetaUtils::ExtractAttrPropertyFromName(*fieldRecDecl,"iotype",sFieldRecName)){
2722  ROOT::TMetaUtils::GetNormalizedName(sFieldRecName,
2723  clang::QualType(memNonPtrType,0),
2724  *fInterpreter,
2725  *fNormalizedCtxt);
2726  }
2727 
2728  TDataMember* mbr = cl->GetDataMember(ioname.c_str());
2729  // if we can not find the member (which should not really happen),
2730  // let's consider it transient.
2731  Bool_t transient = isTransient || !mbr || !mbr->IsPersistent();
2732 
2733  insp.InspectMember(sFieldRecName.c_str(), cobj + fieldOffset,
2734  (fieldName + '.').c_str(), transient);
2735 
2736  }
2737  }
2738  } // loop over fields
2739 
2740  // inspect bases
2741  // TNamed::ShowMembers(R__insp);
2742  unsigned iNBase = 0;
2743  for (clang::CXXRecordDecl::base_class_const_iterator iBase
2744  = recordDecl->bases_begin(), eBase = recordDecl->bases_end();
2745  iBase != eBase; ++iBase, ++iNBase) {
2746  clang::QualType baseQT = iBase->getType();
2747  if (baseQT.isNull()) {
2748  Error("InspectMembers",
2749  "Cannot find QualType for base number %d while inspecting class %s",
2750  iNBase, clname);
2751  continue;
2752  }
2753  const clang::CXXRecordDecl* baseDecl
2754  = baseQT->getAsCXXRecordDecl();
2755  if (!baseDecl) {
2756  Error("InspectMembers",
2757  "Cannot find CXXRecordDecl for base number %d while inspecting class %s",
2758  iNBase, clname);
2759  continue;
2760  }
2761  TClass* baseCl=nullptr;
2762  std::string sBaseName;
2763  // Try with the DeclId
2764  std::vector<TClass*> foundClasses;
2765  TClass::GetClass(static_cast<DeclId_t>(baseDecl), foundClasses);
2766  if (foundClasses.size()==1){
2767  baseCl=foundClasses[0];
2768  } else {
2769  // Try with the normalised Name, as a fallback
2770  if (!baseCl){
2771  ROOT::TMetaUtils::GetNormalizedName(sBaseName,
2772  baseQT,
2773  *fInterpreter,
2774  *fNormalizedCtxt);
2775  baseCl = TClass::GetClass(sBaseName.c_str());
2776  }
2777  }
2778 
2779  if (!baseCl){
2780  std::string qualNameForDiag;
2781  ROOT::TMetaUtils::GetQualifiedName(qualNameForDiag, *baseDecl);
2782  Error("InspectMembers",
2783  "Cannot find TClass for base class %s", qualNameForDiag.c_str() );
2784  continue;
2785  }
2786 
2787  int64_t baseOffset;
2788  if (iBase->isVirtual()) {
2789  if (insp.GetObjectValidity() == TMemberInspector::kNoObjectGiven) {
2790  if (!isTransient) {
2791  Error("InspectMembers",
2792  "Base %s of class %s is virtual but no object provided",
2793  sBaseName.c_str(), clname);
2794  }
2795  baseOffset = TVirtualStreamerInfo::kNeedObjectForVirtualBaseClass;
2796  } else {
2797  // We have an object to determine the vbase offset.
2798  TClingClassInfo* ci = (TClingClassInfo*)cl->GetClassInfo();
2799  TClingClassInfo* baseCi = (TClingClassInfo*)baseCl->GetClassInfo();
2800  if (ci && baseCi) {
2801  baseOffset = ci->GetBaseOffset(baseCi, const_cast<void*>(obj),
2802  true /*isDerivedObj*/);
2803  if (baseOffset == -1) {
2804  Error("InspectMembers",
2805  "Error calculating offset of virtual base %s of class %s",
2806  sBaseName.c_str(), clname);
2807  }
2808  } else {
2809  Error("InspectMembers",
2810  "Cannot calculate offset of virtual base %s of class %s",
2811  sBaseName.c_str(), clname);
2812  continue;
2813  }
2814  }
2815  } else {
2816  baseOffset = recLayout.getBaseClassOffset(baseDecl).getQuantity();
2817  }
2818  // TOFIX: baseCl can be null here!
2819  if (baseCl->IsLoaded()) {
2820  // For loaded class, CallShowMember will (especially for TObject)
2821  // call the virtual ShowMember rather than the class specific version
2822  // resulting in an infinite recursion.
2823  InspectMembers(insp, cobj + baseOffset, baseCl, isTransient);
2824  } else {
2825  baseCl->CallShowMembers(cobj + baseOffset,
2826  insp, isTransient);
2827  }
2828  } // loop over bases
2829 }
2830 
2831 ////////////////////////////////////////////////////////////////////////////////
2832 /// Reset the interpreter internal state in case a previous action was not correctly
2833 /// terminated.
2834 
2835 void TCling::ClearFileBusy()
2836 {
2837  // No-op there is not equivalent state (to be cleared) in Cling.
2838 }
2839 
2840 ////////////////////////////////////////////////////////////////////////////////
2841 /// Delete existing temporary values.
2842 
2843 void TCling::ClearStack()
2844 {
2845  // No-op for cling due to cling::Value.
2846 }
2847 
2848 ////////////////////////////////////////////////////////////////////////////////
2849 /// Declare code to the interpreter, without any of the interpreter actions
2850 /// that could trigger a re-interpretation of the code. I.e. make cling
2851 /// behave like a compiler: no dynamic lookup, no input wrapping for
2852 /// subsequent execution, no automatic provision of declarations but just a
2853 /// plain #include.
2854 /// Returns true on success, false on failure.
2855 
2856 bool TCling::Declare(const char* code)
2857 {
2858  R__LOCKGUARD_CLING(gInterpreterMutex);
2859 
2860  SuspendAutoloadingRAII autoLoadOff(this);
2861  SuspendAutoParsing autoParseRaii(this);
2862 
2863  bool oldDynLookup = fInterpreter->isDynamicLookupEnabled();
2864  fInterpreter->enableDynamicLookup(false);
2865  bool oldRawInput = fInterpreter->isRawInputEnabled();
2866  fInterpreter->enableRawInput(true);
2867 
2868  Bool_t ret = LoadText(code);
2869 
2870  fInterpreter->enableRawInput(oldRawInput);
2871  fInterpreter->enableDynamicLookup(oldDynLookup);
2872  return ret;
2873 }
2874 
2875 ////////////////////////////////////////////////////////////////////////////////
2876 /// Enable the automatic loading of shared libraries when a class
2877 /// is used that is stored in a not yet loaded library. Uses the
2878 /// information stored in the class/library map (typically
2879 /// $ROOTSYS/etc/system.rootmap).
2880 
2881 void TCling::EnableAutoLoading()
2882 {
2883  if (IsFromRootCling())
2884  return;
2885 
2886  // Read the rules before enabling the auto loading to not inadvertently
2887  // load the libraries for the classes concerned even-though the user is
2888  // *not* using them.
2889  // Note this call must happen before the first call to LoadLibraryMap.
2890  assert(GetRootMapFiles() == 0 && "Must be called before LoadLibraryMap!");
2891  TClass::ReadRules(); // Read the default customization rules ...
2892 
2893  LoadLibraryMap();
2894  SetClassAutoloading(true);
2895 }
2896 
2897 ////////////////////////////////////////////////////////////////////////////////
2898 /// It calls a "fantom" method to synchronize user keyboard input
2899 /// and ROOT prompt line.
2900 
2901 void TCling::EndOfLineAction()
2902 {
2903  ProcessLineSynch(fantomline);
2904 }
2905 
2906 // This static function is a hop of TCling::IsLibraryLoaded, which is taking a lock and calling
2907 // into this function. This is because we wanted to avoid a duplication in TCling::IsLoaded, which
2908 // was already taking a lock.
2909 static Bool_t s_IsLibraryLoaded(const char* libname, cling::Interpreter* fInterpreter)
2910 {
2911  // Check shared library.
2912  TString tLibName(libname);
2913  if (gSystem->FindDynamicLibrary(tLibName, kTRUE))
2914  return fInterpreter->getDynamicLibraryManager()->isLibraryLoaded(tLibName.Data());
2915  return false;
2916 }
2917 
2918 Bool_t TCling::IsLibraryLoaded(const char* libname) const
2919 {
2920  R__LOCKGUARD(gInterpreterMutex);
2921  return s_IsLibraryLoaded(libname, GetInterpreterImpl());
2922 }
2923 
2924 ////////////////////////////////////////////////////////////////////////////////
2925 /// Return true if ROOT has cxxmodules pcm for a given library name.
2926 // FIXME: We need to be able to support lazy loading of pcm generated by ACLiC.
2927 Bool_t TCling::HasPCMForLibrary(const char *libname) const
2928 {
2929  llvm::StringRef ModuleName(libname);
2930  ModuleName = llvm::sys::path::stem(ModuleName);
2931  ModuleName.consume_front("lib");
2932 
2933  clang::ModuleMap &moduleMap = fInterpreter->getCI()->getPreprocessor().getHeaderSearchInfo().getModuleMap();
2934  clang::Module *M = moduleMap.findModule(ModuleName);
2935  return M && !M->IsMissingRequirement && M->getASTFile();
2936 }
2937 
2938 ////////////////////////////////////////////////////////////////////////////////
2939 /// Return true if the file has already been loaded by cint.
2940 /// We will try in this order:
2941 /// actual filename
2942 /// filename as a path relative to
2943 /// the include path
2944 /// the shared library path
2945 
2946 Bool_t TCling::IsLoaded(const char* filename) const
2947 {
2948  R__LOCKGUARD(gInterpreterMutex);
2949 
2950  //FIXME: if we use llvm::sys::fs::make_absolute all this can go away. See
2951  // cling::DynamicLibraryManager.
2952 
2953  std::string file_name = filename;
2954  size_t at = std::string::npos;
2955  while ((at = file_name.find("/./")) != std::string::npos)
2956  file_name.replace(at, 3, "/");
2957 
2958  std::string filesStr = "";
2959  llvm::raw_string_ostream filesOS(filesStr);
2960  clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
2961  cling::ClangInternalState::printIncludedFiles(filesOS, SM);
2962  filesOS.flush();
2963 
2964  llvm::SmallVector<llvm::StringRef, 100> files;
2965  llvm::StringRef(filesStr).split(files, "\n");
2966 
2967  std::set<std::string> fileMap;
2968  // Fill fileMap; return early on exact match.
2969  for (llvm::SmallVector<llvm::StringRef, 100>::const_iterator
2970  iF = files.begin(), iE = files.end(); iF != iE; ++iF) {
2971  if ((*iF) == file_name.c_str()) return kTRUE; // exact match
2972  fileMap.insert(*iF);
2973  }
2974 
2975  if (fileMap.empty()) return kFALSE;
2976 
2977  // Check MacroPath.
2978  TString sFilename(file_name.c_str());
2979  if (gSystem->FindFile(TROOT::GetMacroPath(), sFilename, kReadPermission)
2980  && fileMap.count(sFilename.Data())) {
2981  return kTRUE;
2982  }
2983 
2984  // Check IncludePath.
2985  TString incPath = gSystem->GetIncludePath(); // of the form -Idir1 -Idir2 -Idir3
2986  incPath.Append(":").Prepend(" "); // to match " -I" (note leading ' ')
2987  incPath.ReplaceAll(" -I", ":"); // of form :dir1 :dir2:dir3
2988  while (incPath.Index(" :") != -1) {
2989  incPath.ReplaceAll(" :", ":");
2990  }
2991  incPath.Prepend(".:");
2992  sFilename = file_name.c_str();
2993  if (gSystem->FindFile(incPath, sFilename, kReadPermission)
2994  && fileMap.count(sFilename.Data())) {
2995  return kTRUE;
2996  }
2997 
2998  // Check shared library.
2999  if (s_IsLibraryLoaded(file_name.c_str(), GetInterpreterImpl()))
3000  return kTRUE;
3001 
3002  //FIXME: We must use the cling::Interpreter::lookupFileOrLibrary iface.
3003  const clang::DirectoryLookup *CurDir = 0;
3004  clang::Preprocessor &PP = fInterpreter->getCI()->getPreprocessor();
3005  clang::HeaderSearch &HS = PP.getHeaderSearchInfo();
3006  const clang::FileEntry *FE = HS.LookupFile(file_name.c_str(),
3007  clang::SourceLocation(),
3008  /*isAngled*/ false,
3009  /*FromDir*/ 0, CurDir,
3010  clang::ArrayRef<std::pair<const clang::FileEntry *,
3011  const clang::DirectoryEntry *>>(),
3012  /*SearchPath*/ 0,
3013  /*RelativePath*/ 0,
3014  /*RequestingModule*/ 0,
3015  /*SuggestedModule*/ 0,
3016  /*IsMapped*/ 0,
3017  /*SkipCache*/ false,
3018  /*BuildSystemModule*/ false,
3019  /*OpenFile*/ false,
3020  /*CacheFail*/ false);
3021  if (FE && FE->isValid()) {
3022  // check in the source manager if the file is actually loaded
3023  clang::SourceManager &SM = fInterpreter->getCI()->getSourceManager();
3024  // this works only with header (and source) files...
3025  clang::FileID FID = SM.translateFile(FE);
3026  if (!FID.isInvalid() && FID.getHashValue() == 0)
3027  return kFALSE;
3028  else {
3029  clang::SrcMgr::SLocEntry SLocE = SM.getSLocEntry(FID);
3030  if (SLocE.isFile() && SLocE.getFile().getContentCache()->getRawBuffer() == 0)
3031  return kFALSE;
3032  if (!FID.isInvalid())
3033  return kTRUE;
3034  }
3035  // ...then check shared library again, but with full path now
3036  sFilename = FE->getName();
3037  if (gSystem->FindDynamicLibrary(sFilename, kTRUE)
3038  && fileMap.count(sFilename.Data())) {
3039  return kTRUE;
3040  }
3041  }
3042  return kFALSE;
3043 }
3044 
3045 ////////////////////////////////////////////////////////////////////////////////
3046 
3047 void TCling::UpdateListOfLoadedSharedLibraries()
3048 {
3049 #if defined(R__WIN32) || defined(__CYGWIN__)
3050  HMODULE hModules[1024];
3051  void *hProcess;
3052  unsigned long cbModules;
3053  unsigned int i;
3054  hProcess = (void *)::GetCurrentProcess();
3055  ::EnumProcessModules(hProcess, hModules, sizeof(hModules), &cbModules);
3056  // start at 1 to skip the executable itself
3057  for (i = 1; i < (cbModules / sizeof(void *)); i++) {
3058  static const int bufsize = 260;
3059  wchar_t winname[bufsize];
3060  char posixname[bufsize];
3061  ::GetModuleFileNameExW(hProcess, hModules[i], winname, bufsize);
3062 #if defined(__CYGWIN__)
3063  cygwin_conv_path(CCP_WIN_W_TO_POSIX, winname, posixname, bufsize);
3064 #else
3065  std::wstring wpath = winname;
3066  std::replace(wpath.begin(), wpath.end(), '\\', '/');
3067  string path(wpath.begin(), wpath.end());
3068  strncpy(posixname, path.c_str(), bufsize);
3069 #endif
3070  if (!fSharedLibs.Contains(posixname)) {
3071  RegisterLoadedSharedLibrary(posixname);
3072  }
3073  }
3074 #elif defined(R__MACOSX)
3075  // fPrevLoadedDynLibInfo stores the *next* image index to look at
3076  uint32_t imageIndex = (uint32_t) (size_t) fPrevLoadedDynLibInfo;
3077 
3078  while (const mach_header* mh = _dyld_get_image_header(imageIndex)) {
3079  // Skip non-dylibs
3080  if (mh->filetype == MH_DYLIB) {
3081  if (const char* imageName = _dyld_get_image_name(imageIndex)) {
3082  RegisterLoadedSharedLibrary(imageName);
3083  }
3084  }
3085 
3086  ++imageIndex;
3087  }
3088  fPrevLoadedDynLibInfo = (void*)(size_t)imageIndex;
3089 #elif defined(R__LINUX)
3090  struct PointerNo4 {
3091  void* fSkip[3];
3092  void* fPtr;
3093  };
3094  struct LinkMap {
3095  void* fAddr;
3096  const char* fName;
3097  void* fLd;
3098  LinkMap* fNext;
3099  LinkMap* fPrev;
3100  };
3101  if (!fPrevLoadedDynLibInfo || fPrevLoadedDynLibInfo == (void*)(size_t)-1) {
3102  PointerNo4* procLinkMap = (PointerNo4*)dlopen(0, RTLD_LAZY | RTLD_GLOBAL);
3103  // 4th pointer of 4th pointer is the linkmap.
3104  // See http://syprog.blogspot.fr/2011/12/listing-loaded-shared-objects-in-linux.html
3105  LinkMap* linkMap = (LinkMap*) ((PointerNo4*)procLinkMap->fPtr)->fPtr;
3106  RegisterLoadedSharedLibrary(linkMap->fName);
3107  fPrevLoadedDynLibInfo = linkMap;
3108  // reduce use count of link map structure:
3109  dlclose(procLinkMap);
3110  }
3111 
3112  LinkMap* iDyLib = (LinkMap*)fPrevLoadedDynLibInfo;
3113  while (iDyLib->fNext) {
3114  iDyLib = iDyLib->fNext;
3115  RegisterLoadedSharedLibrary(iDyLib->fName);
3116  }
3117  fPrevLoadedDynLibInfo = iDyLib;
3118 #else
3119  Error("TCling::UpdateListOfLoadedSharedLibraries",
3120  "Platform not supported!");
3121 #endif
3122 }
3123 
3124 ////////////////////////////////////////////////////////////////////////////////
3125 /// Register a new shared library name with the interpreter; add it to
3126 /// fSharedLibs.
3127 
3128 void TCling::RegisterLoadedSharedLibrary(const char* filename)
3129 {
3130  // Ignore NULL filenames, aka "the process".
3131  if (!filename) return;
3132 
3133  // Tell the interpreter that this library is available; all libraries can be
3134  // used to resolve symbols.
3135  cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3136  if (!DLM->isLibraryLoaded(filename)) {
3137  DLM->loadLibrary(filename, true /*permanent*/);
3138  }
3139 
3140 #if defined(R__MACOSX)
3141  // Check that this is not a system library
3142  auto lenFilename = strlen(filename);
3143  if (!strncmp(filename, "/usr/lib/system/", 16)
3144  || !strncmp(filename, "/usr/lib/libc++", 15)
3145  || !strncmp(filename, "/System/Library/Frameworks/", 27)
3146  || !strncmp(filename, "/System/Library/PrivateFrameworks/", 34)
3147  || !strncmp(filename, "/System/Library/CoreServices/", 29)
3148  || !strcmp(filename, "cl_kernels") // yepp, no directory
3149  || strstr(filename, "/usr/lib/libSystem")
3150  || strstr(filename, "/usr/lib/libstdc++")
3151  || strstr(filename, "/usr/lib/libicucore")
3152  || strstr(filename, "/usr/lib/libbsm")
3153  || strstr(filename, "/usr/lib/libobjc")
3154  || strstr(filename, "/usr/lib/libresolv")
3155  || strstr(filename, "/usr/lib/libauto")
3156  || strstr(filename, "/usr/lib/libcups")
3157  || strstr(filename, "/usr/lib/libDiagnosticMessagesClient")
3158  || strstr(filename, "/usr/lib/liblangid")
3159  || strstr(filename, "/usr/lib/libCRFSuite")
3160  || strstr(filename, "/usr/lib/libpam")
3161  || strstr(filename, "/usr/lib/libOpenScriptingUtil")
3162  || strstr(filename, "/usr/lib/libextension")
3163  || strstr(filename, "/usr/lib/libAudioToolboxUtility")
3164  // "cannot link directly with dylib/framework, your binary is not an allowed client of
3165  // /Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/
3166  // SDKs/MacOSX.sdk/usr/lib/libAudioToolboxUtility.tbd for architecture x86_64
3167  || (lenFilename > 4 && !strcmp(filename + lenFilename - 4, ".tbd")))
3168  return;
3169 #elif defined(__CYGWIN__)
3170  // Check that this is not a system library
3171  static const int bufsize = 260;
3172  char posixwindir[bufsize];
3173  char *windir = getenv("WINDIR");
3174  if (windir)
3175  cygwin_conv_path(CCP_WIN_A_TO_POSIX, windir, posixwindir, bufsize);
3176  else
3177  snprintf(posixwindir, sizeof(posixwindir), "/Windows/");
3178  if (strstr(filename, posixwindir) ||
3179  strstr(filename, "/usr/bin/cyg"))
3180  return;
3181 #elif defined(R__WIN32)
3182  if (strstr(filename, "/Windows/"))
3183  return;
3184 #elif defined (R__LINUX)
3185  if (strstr(filename, "/ld-linux")
3186  || strstr(filename, "linux-gnu/")
3187  || strstr(filename, "/libstdc++.")
3188  || strstr(filename, "/libgcc")
3189  || strstr(filename, "/libc.")
3190  || strstr(filename, "/libdl.")
3191  || strstr(filename, "/libm."))
3192  return;
3193 #endif
3194  // Update string of available libraries.
3195  if (!fSharedLibs.IsNull()) {
3196  fSharedLibs.Append(" ");
3197  }
3198  fSharedLibs.Append(filename);
3199 }
3200 
3201 ////////////////////////////////////////////////////////////////////////////////
3202 /// Load a library file in cling's memory.
3203 /// if 'system' is true, the library is never unloaded.
3204 /// Return 0 on success, -1 on failure.
3205 
3206 Int_t TCling::Load(const char* filename, Bool_t system)
3207 {
3208  assert(!IsFromRootCling() && "Trying to load library from rootcling!");
3209 
3210  // Used to return 0 on success, 1 on duplicate, -1 on failure, -2 on "fatal".
3211  R__LOCKGUARD_CLING(gInterpreterMutex);
3212  cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
3213  std::string canonLib = DLM->lookupLibrary(filename);
3214  cling::DynamicLibraryManager::LoadLibResult res
3215  = cling::DynamicLibraryManager::kLoadLibNotFound;
3216  if (!canonLib.empty()) {
3217  if (system)
3218  res = DLM->loadLibrary(filename, system);
3219  else {
3220  // For the non system libs, we'd like to be able to unload them.
3221  // FIXME: Here we lose the information about kLoadLibAlreadyLoaded case.
3222  cling::Interpreter::CompilationResult compRes;
3223  HandleInterpreterException(GetMetaProcessorImpl(), Form(".L %s", canonLib.c_str()), compRes, /*cling::Value*/0);
3224  if (compRes == cling::Interpreter::kSuccess)
3225  res = cling::DynamicLibraryManager::kLoadLibSuccess;
3226  }
3227  }
3228 
3229  if (res == cling::DynamicLibraryManager::kLoadLibSuccess) {
3230  UpdateListOfLoadedSharedLibraries();
3231  }
3232  switch (res) {
3233  case cling::DynamicLibraryManager::kLoadLibSuccess: return 0;
3234  case cling::DynamicLibraryManager::kLoadLibAlreadyLoaded: return 1;
3235  default: break;
3236  };
3237  return -1;
3238 }
3239 
3240 ////////////////////////////////////////////////////////////////////////////////
3241 /// Load a macro file in cling's memory.
3242 
3243 void TCling::LoadMacro(const char* filename, EErrorCode* error)
3244 {
3245  ProcessLine(Form(".L %s", filename), error);
3246 }
3247 
3248 ////////////////////////////////////////////////////////////////////////////////
3249 /// Let cling process a command line asynch.
3250 
3251 Long_t TCling::ProcessLineAsynch(const char* line, EErrorCode* error)
3252 {
3253  return ProcessLine(line, error);
3254 }
3255 
3256 ////////////////////////////////////////////////////////////////////////////////
3257 /// Let cling process a command line synchronously, i.e we are waiting
3258 /// it will be finished.
3259 
3260 Long_t TCling::ProcessLineSynch(const char* line, EErrorCode* error)
3261 {
3262  R__LOCKGUARD_CLING(fLockProcessLine ? gInterpreterMutex : 0);
3263  if (gApplication) {
3264  if (gApplication->IsCmdThread()) {
3265  return ProcessLine(line, error);
3266  }
3267  return 0;
3268  }
3269  return ProcessLine(line, error);
3270 }
3271 
3272 ////////////////////////////////////////////////////////////////////////////////
3273 /// Directly execute an executable statement (e.g. "func()", "3+5", etc.
3274 /// however not declarations, like "Int_t x;").
3275 
3276 Long_t TCling::Calc(const char* line, EErrorCode* error)
3277 {
3278 #ifdef R__WIN32
3279  // Test on ApplicationImp not being 0 is needed because only at end of
3280  // TApplication ctor the IsLineProcessing flag is set to 0, so before
3281  // we can not use it.
3282  if (gApplication && gApplication->GetApplicationImp()) {
3283  while (gROOT->IsLineProcessing() && !gApplication) {
3284  Warning("Calc", "waiting for cling thread to free");
3285  gSystem->Sleep(500);
3286  }
3287  gROOT->SetLineIsProcessing();
3288  }
3289 #endif // R__WIN32
3290  R__LOCKGUARD_CLING(gInterpreterMutex);
3291  if (error) {
3292  *error = TInterpreter::kNoError;
3293  }
3294  cling::Value valRef;
3295  cling::Interpreter::CompilationResult cr = fInterpreter->evaluate(line, valRef);
3296  if (cr != cling::Interpreter::kSuccess) {
3297  // Failure in compilation.
3298  if (error) {
3299  // Note: Yes these codes are weird.
3300  *error = TInterpreter::kRecoverable;
3301  }
3302  return 0L;
3303  }
3304  if (!valRef.isValid()) {
3305  // Failure at runtime.
3306  if (error) {
3307  // Note: Yes these codes are weird.
3308  *error = TInterpreter::kDangerous;
3309  }
3310  return 0L;
3311  }
3312 
3313  if (valRef.isVoid()) {
3314  return 0;
3315  }
3316 
3317  RegisterTemporary(valRef);
3318 #ifdef R__WIN32
3319  if (gApplication && gApplication->GetApplicationImp()) {
3320  gROOT->SetLineHasBeenProcessed();
3321  }
3322 #endif // R__WIN32
3323  return valRef.simplisticCastAs<long>();
3324 }
3325 
3326 ////////////////////////////////////////////////////////////////////////////////
3327 /// Set a getline function to call when input is needed.
3328 
3329 void TCling::SetGetline(const char * (*getlineFunc)(const char* prompt),
3330  void (*histaddFunc)(const char* line))
3331 {
3332  // If cling offers a replacement for G__pause(), it would need to
3333  // also offer a way to customize at least the history recording.
3334 
3335 #if defined(R__MUST_REVISIT)
3336 #if R__MUST_REVISIT(6,2)
3337  Warning("SetGetline","Cling should support the equivalent of SetGetlineFunc(getlineFunc, histaddFunc)");
3338 #endif
3339 #endif
3340 }
3341 
3342 ////////////////////////////////////////////////////////////////////////////////
3343 /// Helper function to increase the internal Cling count of transactions
3344 /// that change the AST.
3345 
3346 Bool_t TCling::HandleNewTransaction(const cling::Transaction &T)
3347 {
3348  R__LOCKGUARD(gInterpreterMutex);
3349 
3350  if ((std::distance(T.decls_begin(), T.decls_end()) != 1)
3351  || T.deserialized_decls_begin() != T.deserialized_decls_end()
3352  || T.macros_begin() != T.macros_end()
3353  || ((!T.getFirstDecl().isNull()) && ((*T.getFirstDecl().begin()) != T.getWrapperFD()))) {
3354  fTransactionCount++;
3355  return true;
3356  }
3357  return false;
3358 }
3359 
3360 ////////////////////////////////////////////////////////////////////////////////
3361 /// Delete object from cling symbol table so it can not be used anymore.
3362 /// cling objects are always on the heap.
3363 
3364 void TCling::RecursiveRemove(TObject* obj)
3365 {
3366  // NOTE: When replacing the mutex by a ReadWrite mutex, we **must**
3367  // put in place the Read/Write part here. Keeping the write lock
3368  // here is 'catasptrophic' for scaling as it means that ALL calls
3369  // to RecursiveRemove will take the write lock and performance
3370  // of many threads trying to access the write lock at the same
3371  // time is relatively bad.
3372  R__READ_LOCKGUARD(ROOT::gCoreMutex);
3373  // Note that fgSetOfSpecials is supposed to be updated by TClingCallbacks::tryFindROOTSpecialInternal
3374  // (but isn't at the moment).
3375  if (obj->IsOnHeap() && fgSetOfSpecials && !((std::set<TObject*>*)fgSetOfSpecials)->empty()) {
3376  std::set<TObject*>::iterator iSpecial = ((std::set<TObject*>*)fgSetOfSpecials)->find(obj);
3377  if (iSpecial != ((std::set<TObject*>*)fgSetOfSpecials)->end()) {
3378  R__WRITE_LOCKGUARD(ROOT::gCoreMutex);
3379  DeleteGlobal(obj);
3380  ((std::set<TObject*>*)fgSetOfSpecials)->erase(iSpecial);
3381  }
3382  }
3383 }
3384 
3385 ////////////////////////////////////////////////////////////////////////////////
3386 /// Pressing Ctrl+C should forward here. In the case where we have had
3387 /// continuation requested we must reset it.
3388 
3389 void TCling::Reset()
3390 {
3391  fMetaProcessor->cancelContinuation();
3392  // Reset the Cling state to the state saved by the last call to
3393  // TCling::SaveContext().
3394 #if defined(R__MUST_REVISIT)
3395 #if R__MUST_REVISIT(6,2)
3396  R__LOCKGUARD(gInterpreterMutex);
3397  Warning("Reset","Cling should support the equivalent of scratch_upto(&fDictPos)");
3398 #endif
3399 #endif
3400 }
3401 
3402 ////////////////////////////////////////////////////////////////////////////////
3403 /// Reset the Cling state to its initial state.
3404 
3405 void TCling::ResetAll()
3406 {
3407 #if defined(R__MUST_REVISIT)
3408 #if R__MUST_REVISIT(6,2)
3409  R__LOCKGUARD(gInterpreterMutex);
3410  Warning("ResetAll","Cling should support the equivalent of complete reset (unload everything but the startup decls.");
3411 #endif
3412 #endif
3413 }
3414 
3415 ////////////////////////////////////////////////////////////////////////////////
3416 /// Reset in Cling the list of global variables to the state saved by the last
3417 /// call to TCling::SaveGlobalsContext().
3418 ///
3419 /// Note: Right now, all we do is run the global destructors.
3420 
3421 void TCling::ResetGlobals()
3422 {
3423  R__LOCKGUARD(gInterpreterMutex);
3424  // TODO:
3425  // Here we should iterate over the transactions (N-3) and revert.
3426  // N-3 because the first three internal to cling.
3427 
3428  fInterpreter->runAndRemoveStaticDestructors();
3429 }
3430 
3431 ////////////////////////////////////////////////////////////////////////////////
3432 /// Reset the Cling 'user' global objects/variables state to the state saved by the last
3433 /// call to TCling::SaveGlobalsContext().
3434 
3435 void TCling::ResetGlobalVar(void* obj)
3436 {
3437 #if defined(R__MUST_REVISIT)
3438 #if R__MUST_REVISIT(6,2)
3439  R__LOCKGUARD(gInterpreterMutex);
3440  Warning("ResetGlobalVar","Cling should support the equivalent of resetglobalvar(obj)");
3441 #endif
3442 #endif
3443 }
3444 
3445 ////////////////////////////////////////////////////////////////////////////////
3446 /// Rewind Cling dictionary to the point where it was before executing
3447 /// the current macro. This function is typically called after SEGV or
3448 /// ctlr-C after doing a longjmp back to the prompt.
3449 
3450 void TCling::RewindDictionary()
3451 {
3452 #if defined(R__MUST_REVISIT)
3453 #if R__MUST_REVISIT(6,2)
3454  R__LOCKGUARD(gInterpreterMutex);
3455  Warning("RewindDictionary","Cling should provide a way to revert transaction similar to rewinddictionary()");
3456 #endif
3457 #endif
3458 }
3459 
3460 ////////////////////////////////////////////////////////////////////////////////
3461 /// Delete obj from Cling symbol table so it cannot be accessed anymore.
3462 /// Returns 1 in case of success and 0 in case object was not in table.
3463 
3464 Int_t TCling::DeleteGlobal(void* obj)
3465 {
3466 #if defined(R__MUST_REVISIT)
3467 #if R__MUST_REVISIT(6,2)
3468  R__LOCKGUARD(gInterpreterMutex);
3469  Warning("DeleteGlobal","Cling should provide the equivalent of deleteglobal(obj), see also DeleteVariable.");
3470 #endif
3471 #endif
3472  return 0;
3473 }
3474 
3475 ////////////////////////////////////////////////////////////////////////////////
3476 /// Undeclare obj called name.
3477 /// Returns 1 in case of success, 0 for failure.
3478 
3479 Int_t TCling::DeleteVariable(const char* name)
3480 {
3481 #if defined(R__MUST_REVISIT)
3482 #if R__MUST_REVISIT(6,2)
3483  Warning("DeleteVariable","should do more that just reseting the value to zero");
3484 #endif
3485 #endif
3486 
3487  R__LOCKGUARD(gInterpreterMutex);
3488  llvm::StringRef srName(name);
3489  const char* unscopedName = name;
3490  llvm::StringRef::size_type posScope = srName.rfind("::");
3491  const clang::DeclContext* declCtx = 0;
3492  if (posScope != llvm::StringRef::npos) {
3493  const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3494  const clang::Decl* scopeDecl
3495  = lh.findScope(srName.substr(0, posScope),
3496  cling::LookupHelper::WithDiagnostics);
3497  if (!scopeDecl) {
3498  Error("DeleteVariable", "Cannot find enclosing scope for variable %s",
3499  name);
3500  return 0;
3501  }
3502  declCtx = llvm::dyn_cast<clang::DeclContext>(scopeDecl);
3503  if (!declCtx) {
3504  Error("DeleteVariable",
3505  "Enclosing scope for variable %s is not a declaration context",
3506  name);
3507  return 0;
3508  }
3509  unscopedName += posScope + 2;
3510  }
3511  // Could trigger deserialization of decls.
3512  cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
3513  clang::NamedDecl* nVarDecl
3514  = cling::utils::Lookup::Named(&fInterpreter->getSema(), unscopedName, declCtx);
3515  if (!nVarDecl) {
3516  Error("DeleteVariable", "Unknown variable %s", name);
3517  return 0;
3518  }
3519  clang::VarDecl* varDecl = llvm::dyn_cast<clang::VarDecl>(nVarDecl);
3520  if (!varDecl) {
3521  Error("DeleteVariable", "Entity %s is not a variable", name);
3522  return 0;
3523  }
3524 
3525  clang::QualType qType = varDecl->getType();
3526  const clang::Type* type = qType->getUnqualifiedDesugaredType();
3527  // Cannot set a reference's address to nullptr; the JIT can place it
3528  // into read-only memory (ROOT-7100).
3529  if (type->isPointerType()) {
3530  int** ppInt = (int**)fInterpreter->getAddressOfGlobal(GlobalDecl(varDecl));
3531  // set pointer to invalid.
3532  if (ppInt) *ppInt = 0;
3533  }
3534  return 1;
3535 }
3536 
3537 ////////////////////////////////////////////////////////////////////////////////
3538 /// Save the current Cling state.
3539 
3540 void TCling::SaveContext()
3541 {
3542 #if defined(R__MUST_REVISIT)
3543 #if R__MUST_REVISIT(6,2)
3544  R__LOCKGUARD(gInterpreterMutex);
3545  Warning("SaveContext","Cling should provide a way to record a state watermark similar to store_dictposition(&fDictPos)");
3546 #endif
3547 #endif
3548 }
3549 
3550 ////////////////////////////////////////////////////////////////////////////////
3551 /// Save the current Cling state of global objects.
3552 
3553 void TCling::SaveGlobalsContext()
3554 {
3555 #if defined(R__MUST_REVISIT)
3556 #if R__MUST_REVISIT(6,2)
3557  R__LOCKGUARD(gInterpreterMutex);
3558  Warning("SaveGlobalsContext","Cling should provide a way to record a watermark for the list of global variable similar to store_dictposition(&fDictPosGlobals)");
3559 #endif
3560 #endif
3561 }
3562 
3563 ////////////////////////////////////////////////////////////////////////////////
3564 /// No op: see TClingCallbacks (used to update the list of globals)
3565 
3566 void TCling::UpdateListOfGlobals()
3567 {
3568 }
3569 
3570 ////////////////////////////////////////////////////////////////////////////////
3571 /// No op: see TClingCallbacks (used to update the list of global functions)
3572 
3573 void TCling::UpdateListOfGlobalFunctions()
3574 {
3575 }
3576 
3577 ////////////////////////////////////////////////////////////////////////////////
3578 /// No op: see TClingCallbacks (used to update the list of types)
3579 
3580 void TCling::UpdateListOfTypes()
3581 {
3582 }
3583 
3584 ////////////////////////////////////////////////////////////////////////////////
3585 /// Check in what order the member of a tuple are layout.
3586 enum class ETupleOrdering {
3587  kAscending,
3588  kDescending,
3589  kUnexpected
3590 };
3591 
3592 struct AlternateTupleIntDoubleAsc
3593 {
3594  Int_t _0;
3595  Double_t _1;
3596 };
3597 
3598 struct AlternateTupleIntDoubleDes
3599 {
3600  Double_t _1;
3601  Int_t _0;
3602 };
3603 
3604 static ETupleOrdering IsTupleAscending()
3605 {
3606  std::tuple<int,double> value;
3607  AlternateTupleIntDoubleAsc asc;
3608  AlternateTupleIntDoubleDes des;
3609 
3610  size_t offset0 = ((char*)&(std::get<0>(value))) - ((char*)&value);
3611  size_t offset1 = ((char*)&(std::get<1>(value))) - ((char*)&value);
3612 
3613  size_t ascOffset0 = ((char*)&(asc._0)) - ((char*)&asc);
3614  size_t ascOffset1 = ((char*)&(asc._1)) - ((char*)&asc);
3615 
3616  size_t desOffset0 = ((char*)&(des._0)) - ((char*)&des);
3617  size_t desOffset1 = ((char*)&(des._1)) - ((char*)&des);
3618 
3619  if (offset0 == ascOffset0 && offset1 == ascOffset1) {
3620  return ETupleOrdering::kAscending;
3621  } else if (offset0 == desOffset0 && offset1 == desOffset1) {
3622  return ETupleOrdering::kDescending;
3623  } else {
3624  return ETupleOrdering::kUnexpected;
3625  }
3626 }
3627 
3628 static std::string AlternateTuple(const char *classname, const cling::LookupHelper& lh)
3629 {
3630  TClassEdit::TSplitType tupleContent(classname);
3631  std::string alternateName = "TEmulatedTuple";
3632  alternateName.append( classname + 5 );
3633 
3634  std::string fullname = "ROOT::Internal::" + alternateName;
3635  if (lh.findScope(fullname, cling::LookupHelper::NoDiagnostics,
3636  /*resultType*/nullptr, /* intantiateTemplate= */ false))
3637  return fullname;
3638 
3639  std::string guard_name;
3640  ROOT::TMetaUtils::GetCppName(guard_name,alternateName.c_str());
3641  std::ostringstream guard;
3642  guard << "ROOT_INTERNAL_TEmulated_";
3643  guard << guard_name;
3644 
3645  std::ostringstream alternateTuple;
3646  alternateTuple << "#ifndef " << guard.str() << "\n";
3647  alternateTuple << "#define " << guard.str() << "\n";
3648  alternateTuple << "namespace ROOT { namespace Internal {\n";
3649  alternateTuple << "template <class... Types> struct TEmulatedTuple;\n";
3650  alternateTuple << "template <> struct " << alternateName << " {\n";
3651 
3652  // This could also be a compile time choice ...
3653  switch(IsTupleAscending()) {
3654  case ETupleOrdering::kAscending: {
3655  unsigned int nMember = 0;
3656  auto iter = tupleContent.fElements.begin() + 1; // Skip the template name (tuple)
3657  auto theEnd = tupleContent.fElements.end() - 1; // skip the 'stars'.
3658  while (iter != theEnd) {
3659  alternateTuple << " " << *iter << " _" << nMember << ";\n";
3660  ++iter;
3661  ++nMember;
3662  }
3663  break;
3664  }
3665  case ETupleOrdering::kDescending: {
3666  unsigned int nMember = tupleContent.fElements.size() - 3;
3667  auto iter = tupleContent.fElements.rbegin() + 1; // Skip the template name (tuple)
3668  auto theEnd = tupleContent.fElements.rend() - 1; // skip the 'stars'.
3669  while (iter != theEnd) {
3670  alternateTuple << " " << *iter << " _" << nMember << ";\n";
3671  ++iter;
3672  --nMember;
3673  }
3674  break;
3675  }
3676  case ETupleOrdering::kUnexpected: {
3677  Fatal("TCling::SetClassInfo::AlternateTuple",
3678  "Layout of std::tuple on this platform is unexpected.");
3679  break;
3680  }
3681  }
3682 
3683  alternateTuple << "};\n";
3684  alternateTuple << "}}\n";
3685  alternateTuple << "#endif\n";
3686  if (!gCling->Declare(alternateTuple.str().c_str())) {
3687  Error("Load","Could not declare %s",alternateName.c_str());
3688  return "";
3689  }
3690  alternateName = "ROOT::Internal::" + alternateName;
3691  return alternateName;
3692 }
3693 
3694 ////////////////////////////////////////////////////////////////////////////////
3695 /// Set pointer to the TClingClassInfo in TClass.
3696 /// If 'reload' is true, (attempt to) generate a new ClassInfo even if we
3697 /// already have one.
3698 
3699 void TCling::SetClassInfo(TClass* cl, Bool_t reload)
3700 {
3701  // We are shutting down, there is no point in reloading, it only triggers
3702  // redundant deserializations.
3703  if (fIsShuttingDown) {
3704  // Remove the decl_id from the DeclIdToTClass map
3705  if (cl->fClassInfo) {
3706  R__LOCKGUARD(gInterpreterMutex);
3707  TClingClassInfo* TClinginfo = (TClingClassInfo*) cl->fClassInfo;
3708  // Test again as another thread may have set fClassInfo to nullptr.
3709  if (TClinginfo) {
3710  TClass::RemoveClassDeclId(TClinginfo->GetDeclId());
3711  }
3712  delete TClinginfo;
3713  cl->fClassInfo = nullptr;
3714  }
3715  return;
3716  }
3717 
3718  R__LOCKGUARD(gInterpreterMutex);
3719  if (cl->fClassInfo && !reload) {
3720  return;
3721  }
3722  //Remove the decl_id from the DeclIdToTClass map
3723  TClingClassInfo* TClinginfo = (TClingClassInfo*) cl->fClassInfo;
3724  if (TClinginfo) {
3725  TClass::RemoveClassDeclId(TClinginfo->GetDeclId());
3726  }
3727  delete TClinginfo;
3728  cl->fClassInfo = 0;
3729  std::string name(cl->GetName());
3730 
3731  // Handle the special case of 'tuple' where we ignore the real implementation
3732  // details and just overlay a 'simpler'/'simplistic' version that is easy
3733  // for the I/O to understand and handle.
3734  if (strncmp(cl->GetName(),"tuple<",strlen("tuple<"))==0) {
3735 
3736  name = AlternateTuple(cl->GetName(), fInterpreter->getLookupHelper());
3737 
3738  }
3739 
3740  TClingClassInfo* info = new TClingClassInfo(GetInterpreterImpl(), name.c_str());
3741  if (!info->IsValid()) {
3742  if (cl->fState != TClass::kHasTClassInit) {
3743  if (cl->fStreamerInfo->GetEntries() != 0) {
3744  cl->fState = TClass::kEmulated;
3745  } else {
3746  cl->fState = TClass::kForwardDeclared;
3747  }
3748  }
3749  delete info;
3750  return;
3751  }
3752  cl->fClassInfo = (ClassInfo_t*)info; // Note: We are transferring ownership here.
3753  // In case a class contains an external enum, the enum will be seen as a
3754  // class. We must detect this special case and make the class a Zombie.
3755  // Here we assume that a class has at least one method.
3756  // We can NOT call TClass::Property from here, because this method
3757  // assumes that the TClass is well formed to do a lot of information
3758  // caching. The method SetClassInfo (i.e. here) is usually called during
3759  // the building phase of the TClass, hence it is NOT well formed yet.
3760  Bool_t zombieCandidate = kFALSE;
3761  if (
3762  info->IsValid() &&
3763  !(info->Property() & (kIsClass | kIsStruct | kIsNamespace))
3764  ) {
3765  zombieCandidate = kTRUE;
3766  }
3767  if (!info->IsLoaded()) {
3768  if (info->Property() & (kIsNamespace)) {
3769  // Namespaces can have info but no corresponding CINT dictionary
3770  // because they are auto-created if one of their contained
3771  // classes has a dictionary.
3772  zombieCandidate = kTRUE;
3773  }
3774  // this happens when no dictionary is available
3775  delete info;
3776  cl->fClassInfo = 0;
3777  }
3778  if (zombieCandidate && !cl->GetCollectionType()) {
3779  cl->MakeZombie();
3780  }
3781  // If we reach here, the info was valid (See early returns).
3782  if (cl->fState != TClass::kHasTClassInit) {
3783  if (cl->fClassInfo) {
3784  cl->fState = TClass::kInterpreted;
3785  cl->ResetBit(TClass::kIsEmulation);
3786  } else {
3787 // if (TClassEdit::IsSTLCont(cl->GetName()) {
3788 // There will be an emulated collection proxy, is that the same?
3789 // cl->fState = TClass::kEmulated;
3790 // } else {
3791  if (cl->fStreamerInfo->GetEntries() != 0) {
3792  cl->fState = TClass::kEmulated;
3793  } else {
3794  cl->fState = TClass::kForwardDeclared;
3795  }
3796 // }
3797  }
3798  }
3799  if (cl->fClassInfo) {
3800  TClass::AddClassToDeclIdMap(((TClingClassInfo*)cl->fClassInfo)->GetDeclId(), cl);
3801  }
3802 }
3803 
3804 ////////////////////////////////////////////////////////////////////////////////
3805 /// Checks if an entity with the specified name is defined in Cling.
3806 /// Returns kUnknown if the entity is not defined.
3807 /// Returns kWithClassDefInline if the entity exists and has a ClassDefInline
3808 /// Returns kKnown if the entity is defined.
3809 ///
3810 /// By default, structs, namespaces, classes, enums and unions are looked for.
3811 /// If the flag isClassOrNamespaceOnly is true, classes, structs and
3812 /// namespaces only are considered. I.e. if the name is an enum or a union,
3813 /// the returned value is false.
3814 ///
3815 /// In the case where the class is not loaded and belongs to a namespace
3816 /// or is nested, looking for the full class name is outputting a lots of
3817 /// (expected) error messages. Currently the only way to avoid this is to
3818 /// specifically check that each level of nesting is already loaded.
3819 /// In case of templates the idea is that everything between the outer
3820 /// '<' and '>' has to be skipped, e.g.: aap<pippo<noot>::klaas>::a_class
3821 
3822 TInterpreter::ECheckClassInfo
3823 TCling::CheckClassInfo(const char *name, Bool_t autoload, Bool_t isClassOrNamespaceOnly /* = kFALSE*/)
3824 {
3825  R__LOCKGUARD(gInterpreterMutex);
3826  static const char *anonEnum = "anonymous enum ";
3827  static const int cmplen = strlen(anonEnum);
3828 
3829  if (fIsShuttingDown || 0 == strncmp(name, anonEnum, cmplen)) {
3830  return kUnknown;
3831  }
3832 
3833  // Do not turn on the autoloading if it is globally off.
3834  autoload = autoload && IsClassAutoloadingEnabled();
3835 
3836  // Avoid the double search below in case the name is a fundamental type
3837  // or typedef to a fundamental type.
3838  THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
3839  TDataType *fundType = (TDataType *)typeTable->THashTable::FindObject( name );
3840 
3841  if (fundType && fundType->GetType() < TVirtualStreamerInfo::kObject
3842  && fundType->GetType() > 0) {
3843  // Fundamental type, no a class.
3844  return kUnknown;
3845  }
3846 
3847  // Migrated from within TClass::GetClass
3848  // If we want to know if a class or a namespace with this name exists in the
3849  // interpreter and this is an enum in the type system, before or after loading
3850  // according to the autoload function argument, return kUnknown.
3851  if (isClassOrNamespaceOnly && TEnum::GetEnum(name, autoload ? TEnum::kAutoload : TEnum::kNone))
3852  return kUnknown;
3853 
3854  const char *classname = name;
3855 
3856  int storeAutoload = SetClassAutoloading(autoload);
3857 
3858  // First we want to check whether the decl exist, but _without_
3859  // generating any template instantiation. However, the lookup
3860  // still will create a forward declaration of the class template instance
3861  // if it exist. In this case, the return value of findScope will still
3862  // be zero but the type will be initialized.
3863  // Note in the corresponding code in ROOT 5, CINT was not instantiating
3864  // this forward declaration.
3865  const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3866  const clang::Type *type = 0;
3867  const clang::Decl *decl
3868  = lh.findScope(classname,
3869  gDebug > 5 ? cling::LookupHelper::WithDiagnostics
3870  : cling::LookupHelper::NoDiagnostics,
3871  &type, /* intantiateTemplate= */ false );
3872  if (!decl) {
3873  std::string buf = TClassEdit::InsertStd(classname);
3874  decl = lh.findScope(buf,
3875  gDebug > 5 ? cling::LookupHelper::WithDiagnostics
3876  : cling::LookupHelper::NoDiagnostics,
3877  &type,false);
3878  }
3879 
3880  if (type) {
3881  // If decl==0 and the type is valid, then we have a forward declaration.
3882  if (!decl) {
3883  // If we have a forward declaration for a class template instantiation,
3884  // we want to ignore it if it was produced/induced by the call to
3885  // findScope, however we can not distinguish those from the
3886  // instantiation induce by 'soft' use (and thus also induce by the
3887  // same underlying code paths)
3888  // ['soft' use = use not requiring a complete definition]
3889  // So to reduce the amount of disruption to the existing code we
3890  // would just ignore those for STL collection, for which we really
3891  // need to have the compiled collection proxy (and thus the TClass
3892  // bootstrap).
3893  clang::ClassTemplateSpecializationDecl *tmpltDecl =
3894  llvm::dyn_cast_or_null<clang::ClassTemplateSpecializationDecl>
3895  (type->getAsCXXRecordDecl());
3896  if (tmpltDecl && !tmpltDecl->getPointOfInstantiation().isValid()) {
3897  // Since the point of instantiation is invalid, we 'guess' that
3898  // the 'instantiation' of the forwarded type appended in
3899  // findscope.
3900  if (ROOT::TMetaUtils::IsSTLCont(*tmpltDecl)) {
3901  // For STL Collection we return kUnknown.
3902  SetClassAutoloading(storeAutoload);
3903  return kUnknown;
3904  }
3905  }
3906  }
3907  TClingClassInfo tci(GetInterpreterImpl(), *type);
3908  if (!tci.IsValid()) {
3909  SetClassAutoloading(storeAutoload);
3910  return kUnknown;
3911  }
3912  auto propertiesMask = isClassOrNamespaceOnly ? kIsClass | kIsStruct | kIsNamespace :
3913  kIsClass | kIsStruct | kIsNamespace | kIsEnum | kIsUnion;
3914 
3915  if (tci.Property() & propertiesMask) {
3916  bool hasClassDefInline = false;
3917  if (isClassOrNamespaceOnly) {
3918  // We do not need to check for ClassDefInline when this is called from
3919  // TClass::Init, we only do it for the call from TClass::GetClass.
3920  auto hasDictionary = tci.GetMethod("Dictionary", "", false, 0, ROOT::kExactMatch);
3921  auto implLineFunc = tci.GetMethod("ImplFileLine", "", false, 0, ROOT::kExactMatch);
3922 
3923  if (hasDictionary.IsValid() && implLineFunc.IsValid()) {
3924  int lineNumber = 0;
3925  bool success = false;
3926  std::tie(success, lineNumber) =
3927  ROOT::TMetaUtils::GetTrivialIntegralReturnValue(implLineFunc.GetMethodDecl(), *fInterpreter);
3928  hasClassDefInline = success && (lineNumber == -1);
3929  }
3930  }
3931 
3932  // fprintf(stderr,"CheckClassInfo: %s had dict=%d inline=%d\n",name,hasDictionary.IsValid()
3933  // , hasClassDefInline);
3934 
3935  // We are now sure that the entry is not in fact an autoload entry.
3936  SetClassAutoloading(storeAutoload);
3937  if (hasClassDefInline)
3938  return kWithClassDefInline;
3939  else
3940  return kKnown;
3941  } else {
3942  // We are now sure that the entry is not in fact an autoload entry.
3943  SetClassAutoloading(storeAutoload);
3944  return kUnknown;
3945  }
3946  }
3947 
3948  SetClassAutoloading(storeAutoload);
3949  if (decl)
3950  return kKnown;
3951  else
3952  return kUnknown;
3953 
3954  // Setting up iterator part of TClingTypedefInfo is too slow.
3955  // Copy the lookup code instead:
3956  /*
3957  TClingTypedefInfo t(fInterpreter, name);
3958  if (t.IsValid() && !(t.Property() & kIsFundamental)) {
3959  delete[] classname;
3960  SetClassAutoloading(storeAutoload);
3961  return kTRUE;
3962  }
3963  */
3964 
3965 // const clang::Decl *decl = lh.findScope(name);
3966 // if (!decl) {
3967 // std::string buf = TClassEdit::InsertStd(name);
3968 // decl = lh.findScope(buf);
3969 // }
3970 
3971 // SetClassAutoloading(storeAutoload);
3972 // return (decl);
3973 }
3974 
3975 ////////////////////////////////////////////////////////////////////////////////
3976 /// Return true if there is a class template by the given name ...
3977 
3978 Bool_t TCling::CheckClassTemplate(const char *name)
3979 {
3980  const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
3981  const clang::Decl *decl
3982  = lh.findClassTemplate(name,
3983  gDebug > 5 ? cling::LookupHelper::WithDiagnostics
3984  : cling::LookupHelper::NoDiagnostics);
3985  if (!decl) {
3986  std::string strname = "std::";
3987  strname += name;
3988  decl = lh.findClassTemplate(strname,
3989  gDebug > 5 ? cling::LookupHelper::WithDiagnostics
3990  : cling::LookupHelper::NoDiagnostics);
3991  }
3992  return 0 != decl;
3993 }
3994 
3995 ////////////////////////////////////////////////////////////////////////////////
3996 /// Create list of pointers to base class(es) for TClass cl.
3997 
3998 void TCling::CreateListOfBaseClasses(TClass *cl) const
3999 {
4000  R__LOCKGUARD(gInterpreterMutex);
4001  if (cl->fBase) {
4002  return;
4003  }
4004  TClingClassInfo *tci = (TClingClassInfo *)cl->GetClassInfo();
4005  if (!tci) return;
4006  TClingBaseClassInfo t(GetInterpreterImpl(), tci);
4007  TList *listOfBase = new TList;
4008  while (t.Next()) {
4009  // if name cannot be obtained no use to put in list
4010  if (t.IsValid() && t.Name()) {
4011  TClingBaseClassInfo *a = new TClingBaseClassInfo(t);
4012  listOfBase->Add(new TBaseClass((BaseClassInfo_t *)a, cl));
4013  }
4014  }
4015  // Now that is complete, publish it.
4016  cl->fBase = listOfBase;
4017 }
4018 
4019 ////////////////////////////////////////////////////////////////////////////////
4020 /// Create list of pointers to enums for TClass cl.
4021 
4022 void TCling::LoadEnums(TListOfEnums& enumList) const
4023 {
4024  R__LOCKGUARD(gInterpreterMutex);
4025 
4026  const Decl * D;
4027  TClass* cl = enumList.GetClass();
4028  if (cl) {
4029  D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4030  }
4031  else {
4032  D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4033  }
4034  // Iterate on the decl of the class and get the enums.
4035  if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4036  cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4037  // Collect all contexts of the namespace.
4038  llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4039  const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4040  for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(), declEnd = allDeclContexts.end();
4041  declIter != declEnd; ++declIter) {
4042  // Iterate on all decls for each context.
4043  for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4044  DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4045  if (const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(*DI)) {
4046  // Get name of the enum type.
4047  std::string buf;
4048  PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
4049  llvm::raw_string_ostream stream(buf);
4050  // Don't trigger fopen of the source file to count lines:
4051  Policy.AnonymousTagLocations = false;
4052  ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
4053  stream.flush();
4054  // If the enum is unnamed we do not add it to the list of enums i.e unusable.
4055  if (!buf.empty()) {
4056  const char* name = buf.c_str();
4057  // Add the enum to the list of loaded enums.
4058  enumList.Get(ED, name);
4059  }
4060  }
4061  }
4062  }
4063  }
4064 }
4065 
4066 ////////////////////////////////////////////////////////////////////////////////
4067 /// Create list of pointers to function templates for TClass cl.
4068 
4069 void TCling::LoadFunctionTemplates(TClass* cl) const
4070 {
4071  R__LOCKGUARD(gInterpreterMutex);
4072 
4073  const Decl * D;
4074  TListOfFunctionTemplates* funcTempList;
4075  if (cl) {
4076  D = ((TClingClassInfo*)cl->GetClassInfo())->GetDecl();
4077  funcTempList = (TListOfFunctionTemplates*)cl->GetListOfFunctionTemplates(false);
4078  }
4079  else {
4080  D = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
4081  funcTempList = (TListOfFunctionTemplates*)gROOT->GetListOfFunctionTemplates();
4082  }
4083  // Iterate on the decl of the class and get the enums.
4084  if (const clang::DeclContext* DC = dyn_cast<clang::DeclContext>(D)) {
4085  cling::Interpreter::PushTransactionRAII deserRAII(GetInterpreterImpl());
4086  // Collect all contexts of the namespace.
4087  llvm::SmallVector< DeclContext *, 4> allDeclContexts;
4088  const_cast< clang::DeclContext *>(DC)->collectAllContexts(allDeclContexts);
4089  for (llvm::SmallVector<DeclContext*, 4>::iterator declIter = allDeclContexts.begin(),
4090  declEnd = allDeclContexts.end(); declIter != declEnd; ++declIter) {
4091  // Iterate on all decls for each context.
4092  for (clang::DeclContext::decl_iterator DI = (*declIter)->decls_begin(),
4093  DE = (*declIter)->decls_end(); DI != DE; ++DI) {
4094  if (const clang::FunctionTemplateDecl* FTD = dyn_cast<clang::FunctionTemplateDecl>(*DI)) {
4095  funcTempList->Get(FTD);
4096  }
4097  }
4098  }
4099  }
4100 }
4101 
4102 ////////////////////////////////////////////////////////////////////////////////
4103 /// Get the scopes representing using declarations of namespace
4104 
4105 std::vector<std::string> TCling::GetUsingNamespaces(ClassInfo_t *cl) const
4106 {
4107  TClingClassInfo *ci = (TClingClassInfo*)cl;
4108  return ci->GetUsingNamespaces();
4109 }
4110 
4111 ////////////////////////////////////////////////////////////////////////////////
4112 /// Create list of pointers to data members for TClass cl.
4113 /// This is now a nop. The creation and updating is handled in
4114 /// TListOfDataMembers.
4115 
4116 void TCling::CreateListOfDataMembers(TClass* cl) const
4117 {
4118 }
4119 
4120 ////////////////////////////////////////////////////////////////////////////////
4121 /// Create list of pointers to methods for TClass cl.
4122 /// This is now a nop. The creation and updating is handled in
4123 /// TListOfFunctions.
4124 
4125 void TCling::CreateListOfMethods(TClass* cl) const
4126 {
4127 }
4128 
4129 ////////////////////////////////////////////////////////////////////////////////
4130 /// Update the list of pointers to method for TClass cl
4131 /// This is now a nop. The creation and updating is handled in
4132 /// TListOfFunctions.
4133 
4134 void TCling::UpdateListOfMethods(TClass* cl) const
4135 {
4136 }
4137 
4138 ////////////////////////////////////////////////////////////////////////////////
4139 /// Update the list of pointers to data members for TClass cl
4140 /// This is now a nop. The creation and updating is handled in
4141 /// TListOfDataMembers.
4142 
4143 void TCling::UpdateListOfDataMembers(TClass* cl) const
4144 {
4145 }
4146 
4147 ////////////////////////////////////////////////////////////////////////////////
4148 /// Create list of pointers to method arguments for TMethod m.
4149 
4150 void TCling::CreateListOfMethodArgs(TFunction* m) const
4151 {
4152  R__LOCKGUARD(gInterpreterMutex);
4153  if (m->fMethodArgs) {
4154  return;
4155  }
4156  TList *arglist = new TList;
4157  TClingMethodArgInfo t(GetInterpreterImpl(), (TClingMethodInfo*)m->fInfo);
4158  while (t.Next()) {
4159  if (t.IsValid()) {
4160  TClingMethodArgInfo* a = new TClingMethodArgInfo(t);
4161  arglist->Add(new TMethodArg((MethodArgInfo_t*)a, m));
4162  }
4163  }
4164  m->fMethodArgs = arglist;
4165 }
4166 
4167 
4168 ////////////////////////////////////////////////////////////////////////////////
4169 /// Generate a TClass for the given class.
4170 /// Since the caller has already check the ClassInfo, let it give use the
4171 /// result (via the value of emulation) rather than recalculate it.
4172 
4173 TClass *TCling::GenerateTClass(const char *classname, Bool_t emulation, Bool_t silent /* = kFALSE */)
4174 {
4175 // For now the following line would lead to the (unwanted) instantiation
4176 // of class template. This could/would need to be resurrected only if
4177 // we re-introduce so sort of automatic instantiation. However this would
4178 // have to include carefull look at the template parameter to avoid
4179 // creating instance we can not really use (if the parameter are only forward
4180 // declaration or do not have all the necessary interfaces).
4181 
4182  // TClingClassInfo tci(fInterpreter, classname);
4183  // if (1 || !tci.IsValid()) {
4184 
4185  Version_t version = 1;
4186  if (TClassEdit::IsSTLCont(classname)) {
4187  version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4188  }
4189  TClass *cl = new TClass(classname, version, silent);
4190  if (emulation) {
4191  cl->SetBit(TClass::kIsEmulation);
4192  } else {
4193  // Set the class version if the class is versioned.
4194  // Note that we cannot just call CLASS::Class_Version() as we might not have
4195  // an execution engine (when invoked from rootcling).
4196 
4197  // Do not call cl->GetClassVersion(), it has side effects!
4198  Version_t oldvers = cl->fClassVersion;
4199  if (oldvers == version && cl->GetClassInfo()) {
4200  // We have a version and it might need an update.
4201  Version_t newvers = oldvers;
4202  TClingClassInfo* cli = (TClingClassInfo*)cl->GetClassInfo();
4203  if (llvm::isa<clang::NamespaceDecl>(cli->GetDecl())) {
4204  // Namespaces don't have class versions.
4205  return cl;
4206  }
4207  TClingMethodInfo mi = cli->GetMethod("Class_Version", "", 0 /*poffset*/,
4208  ROOT::kExactMatch,
4209  TClingClassInfo::kInThisScope);
4210  if (!mi.IsValid()) {
4211  if (cl->TestBit(TClass::kIsTObject)) {
4212  Error("GenerateTClass",
4213  "Cannot find %s::Class_Version()! Class version might be wrong.",
4214  cl->GetName());
4215  }
4216  return cl;
4217  }
4218  newvers = ROOT::TMetaUtils::GetClassVersion(llvm::dyn_cast<clang::RecordDecl>(cli->GetDecl()),
4219  *fInterpreter);
4220  if (newvers == -1) {
4221  // Didn't manage to determine the class version from the AST.
4222  // Use runtime instead.
4223  if ((mi.Property() & kIsStatic)
4224  && !fInterpreter->isInSyntaxOnlyMode()) {
4225  // This better be a static function.
4226  TClingCallFunc callfunc(GetInterpreterImpl(), *fNormalizedCtxt);
4227  callfunc.SetFunc(&mi);
4228  newvers = callfunc.ExecInt(0);
4229  } else {
4230  Error("GenerateTClass",
4231  "Cannot invoke %s::Class_Version()! Class version might be wrong.",
4232  cl->GetName());
4233  }
4234  }
4235  if (newvers != oldvers) {
4236  cl->fClassVersion = newvers;
4237  cl->fStreamerInfo->Expand(newvers + 2 + 10);
4238  }
4239  }
4240  }
4241 
4242  return cl;
4243 
4244 // } else {
4245 // return GenerateTClass(&tci,silent);
4246 // }
4247 }
4248 
4249 #if 0
4250 ////////////////////////////////////////////////////////////////////////////////
4251 
4252 static void GenerateTClass_GatherInnerIncludes(cling::Interpreter *interp, TString &includes,TClingClassInfo *info)
4253 {
4254  includes += info->FileName();
4255 
4256  const clang::ClassTemplateSpecializationDecl *templateCl
4257  = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(info->GetDecl());
4258  if (templateCl) {
4259  for(unsigned int i=0; i < templateCl->getTemplateArgs().size(); ++i) {
4260  const clang::TemplateArgument &arg( templateCl->getTemplateArgs().get(i) );
4261  if (arg.getKind() == clang::TemplateArgument::Type) {
4262  const clang::Type *uType = ROOT::TMetaUtils::GetUnderlyingType( arg.getAsType() );
4263 
4264  if (!uType->isFundamentalType() && !uType->isEnumeralType()) {
4265  // We really need a header file.
4266  const clang::CXXRecordDecl *argdecl = uType->getAsCXXRecordDecl();
4267  if (argdecl) {
4268  includes += ";";
4269  TClingClassInfo subinfo(interp,*(argdecl->getASTContext().getRecordType(argdecl).getTypePtr()));
4270  GenerateTClass_GatherInnerIncludes(interp, includes, &subinfo);
4271  } else {
4272  std::string Result;
4273  llvm::raw_string_ostream OS(Result);
4274  arg.print(argdecl->getASTContext().getPrintingPolicy(),OS);
4275  Warning("TCling::GenerateTClass","Missing header file for %s",OS.str().c_str());
4276  }
4277  }
4278  }
4279  }
4280  }
4281 }
4282 #endif
4283 
4284 ////////////////////////////////////////////////////////////////////////////////
4285 /// Generate a TClass for the given class.
4286 
4287 TClass *TCling::GenerateTClass(ClassInfo_t *classinfo, Bool_t silent /* = kFALSE */)
4288 {
4289  TClingClassInfo *info = (TClingClassInfo*)classinfo;
4290  if (!info || !info->IsValid()) {
4291  Fatal("GenerateTClass","Requires a valid ClassInfo object");
4292  return 0;
4293  }
4294  // We are in the case where we have AST nodes for this class.
4295  TClass *cl = 0;
4296  std::string classname;
4297  info->FullName(classname,*fNormalizedCtxt); // Could we use Name()?
4298  if (TClassEdit::IsSTLCont(classname)) {
4299 #if 0
4300  Info("GenerateTClass","Will (try to) generate the compiled TClass for %s.",classname.c_str());
4301  // We need to build up the list of required headers, by
4302  // looking at each template arguments.
4303  TString includes;
4304  GenerateTClass_GatherInnerIncludes(fInterpreter,includes,info);
4305 
4306  if (0 == GenerateDictionary(classname.c_str(),includes)) {
4307  // 0 means success.
4308  cl = TClass::LoadClass(classnam.c_str(), silent);
4309  if (cl == 0) {
4310  Error("GenerateTClass","Even though the dictionary generation for %s seemed successful we can't find the TClass bootstrap!",classname.c_str());
4311  }
4312  }
4313 #endif
4314  if (cl == 0) {
4315  int version = TClass::GetClass("TVirtualStreamerInfo")->GetClassVersion();
4316  cl = new TClass(classinfo, version, 0, 0, -1, -1, silent);
4317  cl->SetBit(TClass::kIsEmulation);
4318  }
4319  } else {
4320  // For regular class, just create a TClass on the fly ...
4321  // Not quite useful yet, but that what CINT used to do anyway.
4322  cl = new TClass(classinfo, 1, 0, 0, -1, -1, silent);
4323  }
4324  // Add the new TClass to the map of declid and TClass*.
4325  if (cl) {
4326  TClass::AddClassToDeclIdMap(((TClingClassInfo*)classinfo)->GetDeclId(), cl);
4327  }
4328  return cl;
4329 }
4330 
4331 ////////////////////////////////////////////////////////////////////////////////
4332 /// Generate the dictionary for the C++ classes listed in the first
4333 /// argument (in a semi-colon separated list).
4334 /// 'includes' contains a semi-colon separated list of file to
4335 /// #include in the dictionary.
4336 /// For example:
4337 /// ~~~ {.cpp}
4338 /// gInterpreter->GenerateDictionary("vector<vector<float> >;list<vector<float> >","list;vector");
4339 /// ~~~
4340 /// or
4341 /// ~~~ {.cpp}
4342 /// gInterpreter->GenerateDictionary("myclass","myclass.h;myhelper.h");
4343 /// ~~~
4344 
4345 Int_t TCling::GenerateDictionary(const char* classes, const char* includes /* = "" */, const char* /* options = 0 */)
4346 {
4347  if (classes == 0 || classes[0] == 0) {
4348  Error("TCling::GenerateDictionary", "Cannot generate dictionary without passing classes.");
4349  return 0;
4350  }
4351  // Split the input list
4352  std::vector<std::string> listClasses;
4353  for (
4354  const char* current = classes, *prev = classes;
4355  *current != 0;
4356  ++current
4357  ) {
4358  if (*current == ';') {
4359  listClasses.push_back(std::string(prev, current - prev));
4360  prev = current + 1;
4361  }
4362  else if (*(current + 1) == 0) {
4363  listClasses.push_back(std::string(prev, current + 1 - prev));
4364  prev = current + 1;
4365  }
4366  }
4367  std::vector<std::string> listIncludes;
4368  if (!includes)
4369  includes = "";
4370  for (
4371  const char* current = includes, *prev = includes;
4372  *current != 0;
4373  ++current
4374  ) {
4375  if (*current == ';') {
4376  listIncludes.push_back(std::string(prev, current - prev));
4377  prev = current + 1;
4378  }
4379  else if (*(current + 1) == 0) {
4380  listIncludes.push_back(std::string(prev, current + 1 - prev));
4381  prev = current + 1;
4382  }
4383  }
4384  // Generate the temporary dictionary file
4385  return !TCling_GenerateDictionary(listClasses, listIncludes,
4386  std::vector<std::string>(), std::vector<std::string>());
4387 }
4388 
4389 ////////////////////////////////////////////////////////////////////////////////
4390 /// Return pointer to cling Decl of global/static variable that is located
4391 /// at the address given by addr.
4392 
4393 TInterpreter::DeclId_t TCling::GetDataMember(ClassInfo_t *opaque_cl, const char *name) const
4394 {
4395  R__LOCKGUARD(gInterpreterMutex);
4396  DeclId_t d;
4397  TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
4398 
4399  if (cl) {
4400  d = cl->GetDataMember(name);
4401  // We check if the decl of the data member has an annotation which indicates
4402  // an ioname.
4403  // In case this is true, if the name requested is not the ioname, we
4404  // return 0, as if the member did not exist. In some sense we override
4405  // the information in the TClassInfo instance, isolating the typesystem in
4406  // TClass from the one in the AST.
4407  if (const ValueDecl* decl = (const ValueDecl*) d){
4408  std::string ioName;
4409  bool hasIoName = ROOT::TMetaUtils::ExtractAttrPropertyFromName(*decl,"ioname",ioName);
4410  if (hasIoName && ioName != name) return 0;
4411  }
4412  return d;
4413  }
4414  // We are looking up for something on the TU scope.
4415  // FIXME: We do not want to go through TClingClassInfo(fInterpreter) because of redundant deserializations. That
4416  // interface will actually construct iterators and walk over the decls on the global scope. In would return the first
4417  // occurrence of a decl with the looked up name. However, that's not what C++ lookup would do: if we want to switch
4418  // to a more complete C++ lookup interface we need sift through the found names and pick up the declarations which
4419  // are only fulfilling ROOT's understanding for a Data Member.
4420  // FIXME: We should probably deprecate the TClingClassInfo(fInterpreter) interface and replace it withe something
4421  // similar as below.
4422  using namespace clang;
4423  Sema& SemaR = fInterpreter->getSema();
4424  DeclarationName DName = &SemaR.Context.Idents.get(name);
4425 
4426  LookupResult R(SemaR, DName, SourceLocation(), Sema::LookupOrdinaryName,
4427  Sema::ForRedeclaration);
4428 
4429  // Could trigger deserialization of decls.
4430  cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4431  cling::utils::Lookup::Named(&SemaR, R);
4432 
4433  LookupResult::Filter F = R.makeFilter();
4434  // Filter the data-member looking decls.
4435  while (F.hasNext()) {
4436  NamedDecl *D = F.next();
4437  if (isa<VarDecl>(D) || isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) ||
4438  isa<IndirectFieldDecl>(D))
4439  continue;
4440  F.erase();
4441  }
4442  F.done();
4443 
4444  if (R.isSingleResult())
4445  return R.getFoundDecl();
4446  return 0;
4447 }
4448 
4449 ////////////////////////////////////////////////////////////////////////////////
4450 /// Return pointer to cling Decl of global/static variable that is located
4451 /// at the address given by addr.
4452 
4453 TInterpreter::DeclId_t TCling::GetEnum(TClass *cl, const char *name) const
4454 {
4455  R__LOCKGUARD(gInterpreterMutex);
4456 
4457  const clang::Decl* possibleEnum = 0;
4458  // FInd the context of the decl.
4459  if (cl) {
4460  TClingClassInfo *cci = (TClingClassInfo*)cl->GetClassInfo();
4461  if (cci) {
4462  const clang::DeclContext* dc = 0;
4463  if (const clang::Decl* D = cci->GetDecl()) {
4464  if (!(dc = dyn_cast<clang::NamespaceDecl>(D))) {
4465  dc = dyn_cast<clang::RecordDecl>(D);
4466  }
4467  }
4468  if (dc) {
4469  // If it is a data member enum.
4470  // Could trigger deserialization of decls.
4471  cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4472  possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name, dc);
4473  } else {
4474  Error("TCling::GetEnum", "DeclContext not found for %s .\n", name);
4475  }
4476  }
4477  } else {
4478  // If it is a global enum.
4479  // Could trigger deserialization of decls.
4480  cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
4481  possibleEnum = cling::utils::Lookup::Tag(&fInterpreter->getSema(), name);
4482  }
4483  if (possibleEnum && (possibleEnum != (clang::Decl*)-1)
4484  && isa<clang::EnumDecl>(possibleEnum)) {
4485  return possibleEnum;
4486  }
4487  return 0;
4488 }
4489 
4490 ////////////////////////////////////////////////////////////////////////////////
4491 /// Return pointer to cling DeclId for a global value
4492 
4493 TInterpreter::DeclId_t TCling::GetDeclId( const llvm::GlobalValue *gv ) const
4494 {
4495  if (!gv) return 0;
4496 
4497  llvm::StringRef mangled_name = gv->getName();
4498 
4499  int err = 0;
4500  char* demangled_name_c = TClassEdit::DemangleName(mangled_name.str().c_str(), err);
4501  if (err) {
4502  if (err == -2) {
4503  // It might simply be an unmangled global name.
4504  DeclId_t d;
4505  TClingClassInfo gcl(GetInterpreterImpl());
4506  d = gcl.GetDataMember(mangled_name.str().c_str());
4507  return d;
4508  }
4509  return 0;
4510  }
4511 
4512  std::string scopename(demangled_name_c);
4513  free(demangled_name_c);
4514 
4515  //
4516  // Separate out the class or namespace part of the
4517  // function name.
4518  //
4519  std::string dataname;
4520 
4521  if (!strncmp(scopename.c_str(), "typeinfo for ", sizeof("typeinfo for ")-1)) {
4522  scopename.erase(0, sizeof("typeinfo for ")-1);
4523  } else if (!strncmp(scopename.c_str(), "vtable for ", sizeof("vtable for ")-1)) {
4524  scopename.erase(0, sizeof("vtable for ")-1);
4525  } else {
4526  // See if it is a function
4527  std::string::size_type pos = scopename.rfind('(');
4528  if (pos != std::string::npos) {
4529  return 0;
4530  }
4531  // Separate the scope and member name
4532  pos = scopename.rfind(':');
4533  if (pos != std::string::npos) {
4534  if ((pos != 0) && (scopename[pos-1] == ':')) {
4535  dataname = scopename.substr(pos+1);
4536  scopename.erase(pos-1);
4537  }
4538  } else {
4539  scopename.clear();
4540  dataname = scopename;
4541  }
4542  }
4543  //fprintf(stderr, "name: '%s'\n", name.c_str());
4544  // Now we have the class or namespace name, so do the lookup.
4545 
4546 
4547  DeclId_t d;
4548  if (scopename.size()) {
4549  TClingClassInfo cl(GetInterpreterImpl(), scopename.c_str());
4550  d = cl.GetDataMember(dataname.c_str());
4551  }
4552  else {
4553  TClingClassInfo gcl(GetInterpreterImpl());
4554  d = gcl.GetDataMember(dataname.c_str());
4555  }
4556  return d;
4557 }
4558 
4559 ////////////////////////////////////////////////////////////////////////////////
4560 /// NOT IMPLEMENTED.
4561 
4562 TInterpreter::DeclId_t TCling::GetDataMemberWithValue(const void *ptrvalue) const
4563 {
4564  Error("GetDataMemberWithValue()", "not implemented");
4565  return 0;
4566 }
4567 
4568 ////////////////////////////////////////////////////////////////////////////////
4569 /// Return pointer to cling DeclId for a data member with a given name.
4570 
4571 TInterpreter::DeclId_t TCling::GetDataMemberAtAddr(const void *addr) const
4572 {
4573  // NOT IMPLEMENTED.
4574  Error("GetDataMemberAtAddr()", "not implemented");
4575  return 0;
4576 }
4577 
4578 ////////////////////////////////////////////////////////////////////////////////
4579 /// Return the cling mangled name for a method of a class with parameters
4580 /// params (params is a string of actual arguments, not formal ones). If the
4581 /// class is 0 the global function list will be searched.
4582 
4583 TString TCling::GetMangledName(TClass* cl, const char* method,
4584  const char* params, Bool_t objectIsConst /* = kFALSE */)
4585 {
4586  R__LOCKGUARD(gInterpreterMutex);
4587  TClingCallFunc func(GetInterpreterImpl(), *fNormalizedCtxt);
4588  if (cl) {
4589  Long_t offset;
4590  func.SetFunc((TClingClassInfo*)cl->GetClassInfo(), method, params, objectIsConst,
4591  &offset);
4592  }
4593  else {
4594  TClingClassInfo gcl(GetInterpreterImpl());
4595  Long_t offset;
4596  func.SetFunc(&gcl, method, params, &offset);
4597  }
4598  TClingMethodInfo* mi = (TClingMethodInfo*) func.FactoryMethod();
4599  if (!mi) return "";
4600  TString mangled_name( mi->GetMangledName() );
4601  delete mi;
4602  return mangled_name;
4603 }
4604 
4605 ////////////////////////////////////////////////////////////////////////////////
4606 /// Return the cling mangled name for a method of a class with a certain
4607 /// prototype, i.e. "char*,int,float". If the class is 0 the global function
4608 /// list will be searched.
4609 
4610 TString TCling::GetMangledNameWithPrototype(TClass* cl, const char* method,
4611  const char* proto, Bool_t objectIsConst /* = kFALSE */,
4612  EFunctionMatchMode mode /* = kConversionMatch */)
4613 {
4614  R__LOCKGUARD(gInterpreterMutex);
4615  if (cl) {
4616  return ((TClingClassInfo*)cl->GetClassInfo())->
4617  GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetMangledName();
4618  }
4619  TClingClassInfo gcl(GetInterpreterImpl());
4620  return gcl.GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetMangledName();
4621 }
4622 
4623 ////////////////////////////////////////////////////////////////////////////////
4624 /// Return pointer to cling interface function for a method of a class with
4625 /// parameters params (params is a string of actual arguments, not formal
4626 /// ones). If the class is 0 the global function list will be searched.
4627 
4628 void* TCling::GetInterfaceMethod(TClass* cl, const char* method,
4629  const char* params, Bool_t objectIsConst /* = kFALSE */)
4630 {
4631  R__LOCKGUARD(gInterpreterMutex);
4632  TClingCallFunc func(GetInterpreterImpl(), *fNormalizedCtxt);
4633  if (cl) {
4634  Long_t offset;
4635  func.SetFunc((TClingClassInfo*)cl->GetClassInfo(), method, params, objectIsConst,
4636  &offset);
4637  }
4638  else {
4639  TClingClassInfo gcl(GetInterpreterImpl());
4640  Long_t offset;
4641  func.SetFunc(&gcl, method, params, &offset);
4642  }
4643  return (void*) func.InterfaceMethod();
4644 }
4645 
4646 ////////////////////////////////////////////////////////////////////////////////
4647 /// Return pointer to cling interface function for a method of a class with
4648 /// a certain name.
4649 
4650 TInterpreter::DeclId_t TCling::GetFunction(ClassInfo_t *opaque_cl, const char* method)
4651 {
4652  R__LOCKGUARD(gInterpreterMutex);
4653  DeclId_t f;
4654  TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
4655  if (cl) {
4656  f = cl->GetMethod(method).GetDeclId();
4657  }
4658  else {
4659  TClingClassInfo gcl(GetInterpreterImpl());
4660  f = gcl.GetMethod(method).GetDeclId();
4661  }
4662  return f;
4663 
4664 }
4665 
4666 ////////////////////////////////////////////////////////////////////////////////
4667 /// Insert overloads of name in cl to res.
4668 
4669 void TCling::GetFunctionOverloads(ClassInfo_t *cl, const char *funcname,
4670  std::vector<DeclId_t>& res) const
4671 {
4672  clang::Sema& S = fInterpreter->getSema();
4673  clang::ASTContext& Ctx = S.Context;
4674  const clang::Decl* CtxDecl
4675  = cl ? (const clang::Decl*)((TClingClassInfo*)cl)->GetDeclId():
4676  Ctx.getTranslationUnitDecl();
4677  auto RecDecl = llvm::dyn_cast<const clang::RecordDecl>(CtxDecl);
4678  const clang::DeclContext* DeclCtx = RecDecl;
4679 
4680  if (!DeclCtx)
4681  DeclCtx = dyn_cast<clang::NamespaceDecl>(CtxDecl);
4682  if (!DeclCtx) return;
4683 
4684  clang::DeclarationName DName;
4685  // The DeclarationName is funcname, unless it's a ctor or dtor.
4686  // FIXME: or operator or conversion! See enum clang::DeclarationName::NameKind.
4687 
4688  if (RecDecl) {
4689  if (RecDecl->getNameAsString() == funcname) {
4690  clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
4691  DName = Ctx.DeclarationNames.getCXXConstructorName(Ctx.getCanonicalType(QT));
4692  } else if (funcname[0] == '~' && RecDecl->getNameAsString() == funcname + 1) {
4693  clang::QualType QT = Ctx.getTypeDeclType(RecDecl);
4694  DName = Ctx.DeclarationNames.getCXXDestructorName(Ctx.getCanonicalType(QT));
4695  } else {
4696  DName = &Ctx.Idents.get(funcname);
4697  }
4698  } else {
4699  DName = &Ctx.Idents.get(funcname);
4700  }
4701 
4702  clang::LookupResult R(S, DName, clang::SourceLocation(),
4703  Sema::LookupOrdinaryName, clang::Sema::ForRedeclaration);
4704  S.LookupQualifiedName(R, const_cast<DeclContext*>(DeclCtx));
4705  if (R.empty()) return;
4706  R.resolveKind();
4707  res.reserve(res.size() + (R.end() - R.begin()));
4708  for (clang::LookupResult::iterator IR = R.begin(), ER = R.end();
4709  IR != ER; ++IR) {
4710  if (const clang::FunctionDecl* FD
4711  = llvm::dyn_cast<const clang::FunctionDecl>(*IR)) {
4712  if (!FD->getDescribedFunctionTemplate()) {
4713  res.push_back(FD);
4714  }
4715  }
4716  }
4717 }
4718 
4719 ////////////////////////////////////////////////////////////////////////////////
4720 /// Return pointer to cling interface function for a method of a class with
4721 /// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
4722 /// function list will be searched.
4723 
4724 void* TCling::GetInterfaceMethodWithPrototype(TClass* cl, const char* method,
4725  const char* proto,
4726  Bool_t objectIsConst /* = kFALSE */,
4727  EFunctionMatchMode mode /* = kConversionMatch */)
4728 {
4729  R__LOCKGUARD(gInterpreterMutex);
4730  void* f;
4731  if (cl) {
4732  f = ((TClingClassInfo*)cl->GetClassInfo())->
4733  GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).InterfaceMethod(*fNormalizedCtxt);
4734  }
4735  else {
4736  TClingClassInfo gcl(GetInterpreterImpl());
4737  f = gcl.GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).InterfaceMethod(*fNormalizedCtxt);
4738  }
4739  return f;
4740 }
4741 
4742 ////////////////////////////////////////////////////////////////////////////////
4743 /// Return pointer to cling DeclId for a method of a class with
4744 /// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
4745 /// function list will be searched.
4746 
4747 TInterpreter::DeclId_t TCling::GetFunctionWithValues(ClassInfo_t *opaque_cl, const char* method,
4748  const char* params,
4749  Bool_t objectIsConst /* = kFALSE */)
4750 {
4751  R__LOCKGUARD(gInterpreterMutex);
4752  DeclId_t f;
4753  TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
4754  if (cl) {
4755  f = cl->GetMethodWithArgs(method, params, objectIsConst, 0 /*poffset*/).GetDeclId();
4756  }
4757  else {
4758  TClingClassInfo gcl(GetInterpreterImpl());
4759  f = gcl.GetMethod(method, params, objectIsConst, 0 /*poffset*/).GetDeclId();
4760  }
4761  return f;
4762 }
4763 
4764 ////////////////////////////////////////////////////////////////////////////////
4765 /// Return pointer to cling interface function for a method of a class with
4766 /// a certain prototype, i.e. "char*,int,float". If the class is 0 the global
4767 /// function list will be searched.
4768 
4769 TInterpreter::DeclId_t TCling::GetFunctionWithPrototype(ClassInfo_t *opaque_cl, const char* method,
4770  const char* proto,
4771  Bool_t objectIsConst /* = kFALSE */,
4772  EFunctionMatchMode mode /* = kConversionMatch */)
4773 {
4774  R__LOCKGUARD(gInterpreterMutex);
4775  DeclId_t f;
4776  TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
4777  if (cl) {
4778  f = cl->GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetDeclId();
4779  }
4780  else {
4781  TClingClassInfo gcl(GetInterpreterImpl());
4782  f = gcl.GetMethod(method, proto, objectIsConst, 0 /*poffset*/, mode).GetDeclId();
4783  }
4784  return f;
4785 }
4786 
4787 ////////////////////////////////////////////////////////////////////////////////
4788 /// Return pointer to cling interface function for a method of a class with
4789 /// a certain name.
4790 
4791 TInterpreter::DeclId_t TCling::GetFunctionTemplate(ClassInfo_t *opaque_cl, const char* name)
4792 {
4793  R__LOCKGUARD(gInterpreterMutex);
4794  DeclId_t f;
4795  TClingClassInfo *cl = (TClingClassInfo*)opaque_cl;
4796  if (cl) {
4797  f = cl->GetFunctionTemplate(name);
4798  }
4799  else {
4800  TClingClassInfo gcl(GetInterpreterImpl());
4801  f = gcl.GetFunctionTemplate(name);
4802  }
4803  return f;
4804 
4805 }
4806 
4807 ////////////////////////////////////////////////////////////////////////////////
4808 /// The 'name' is known to the interpreter, this function returns
4809 /// the internal version of this name (usually just resolving typedefs)
4810 /// This is used in particular to synchronize between the name used
4811 /// by rootcling and by the run-time environment (TClass)
4812 /// Return 0 if the name is not known.
4813 
4814 void TCling::GetInterpreterTypeName(const char* name, std::string &output, Bool_t full)
4815 {
4816  output.clear();
4817 
4818  R__LOCKGUARD(gInterpreterMutex);
4819 
4820  TClingClassInfo cl(GetInterpreterImpl(), name);
4821  if (!cl.IsValid()) {
4822  return ;
4823  }
4824  if (full) {
4825  cl.FullName(output,*fNormalizedCtxt);
4826  return;
4827  }
4828  // Well well well, for backward compatibility we need to act a bit too
4829  // much like CINT.
4830  TClassEdit::TSplitType splitname( cl.Name(), TClassEdit::kDropStd );
4831  splitname.ShortType(output, TClassEdit::kDropStd );
4832 
4833  return;
4834 }
4835 
4836 ////////////////////////////////////////////////////////////////////////////////
4837 /// Execute a global function with arguments params.
4838 ///
4839 /// FIXME: The cint-based version of this code does not check if the
4840 /// SetFunc() call works, and does not do any real checking
4841 /// for errors from the Exec() call. It did fetch the most
4842 /// recent cint security error and return that in error, but
4843 /// this does not really translate well to cling/clang. We
4844 /// should enhance these interfaces so that we can report
4845 /// compilation and runtime errors properly.
4846 
4847 void TCling::Execute(const char* function, const char* params, int* error)
4848 {
4849  R__LOCKGUARD_CLING(gInterpreterMutex);
4850  if (error) {
4851  *error = TInterpreter::kNoError;
4852  }
4853  TClingClassInfo cl(GetInterpreterImpl());
4854  Long_t offset = 0L;
4855  TClingCallFunc func(GetInterpreterImpl(), *fNormalizedCtxt);
4856  func.SetFunc(&cl, function, params, &offset);
4857  func.Exec(0);
4858 }
4859 
4860 ////////////////////////////////////////////////////////////////////////////////
4861 /// Execute a method from class cl with arguments params.
4862 ///
4863 /// FIXME: The cint-based version of this code does not check if the
4864 /// SetFunc() call works, and does not do any real checking
4865 /// for errors from the Exec() call. It did fetch the most
4866 /// recent cint security error and return that in error, but
4867 /// this does not really translate well to cling/clang. We
4868 /// should enhance these interfaces so that we can report
4869 /// compilation and runtime errors properly.
4870 
4871 void TCling::Execute(TObject* obj, TClass* cl, const char* method,
4872  const char* params, Bool_t objectIsConst, int* error)
4873 {
4874  R__LOCKGUARD_CLING(gInterpreterMutex);
4875  if (error) {
4876  *error = TInterpreter::kNoError;
4877  }
4878  // If the actual class of this object inherits 2nd (or more) from TObject,
4879  // 'obj' is unlikely to be the start of the object (as described by IsA()),
4880  // hence gInterpreter->Execute will improperly correct the offset.
4881  void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
4882  Long_t offset = 0L;
4883  TClingCallFunc func(GetInterpreterImpl(), *fNormalizedCtxt);
4884  func.SetFunc((TClingClassInfo*)cl->GetClassInfo(), method, params, objectIsConst, &offset);
4885  void* address = (void*)((Long_t)addr + offset);
4886  func.Exec(address);
4887 }
4888 
4889 ////////////////////////////////////////////////////////////////////////////////
4890 
4891 void TCling::Execute(TObject* obj, TClass* cl, const char* method,
4892  const char* params, int* error)
4893 {
4894  Execute(obj,cl,method,params,false,error);
4895 }
4896 
4897 ////////////////////////////////////////////////////////////////////////////////
4898 /// Execute a method from class cl with the arguments in array params
4899 /// (params[0] ... params[n] = array of TObjString parameters).
4900 /// Convert the TObjArray array of TObjString parameters to a character
4901 /// string of comma separated parameters.
4902 /// The parameters of type 'char' are enclosed in double quotes and all
4903 /// internal quotes are escaped.
4904 
4905 void TCling::Execute(TObject* obj, TClass* cl, TMethod* method,
4906  TObjArray* params, int* error)
4907 {
4908  if (!method) {
4909  Error("Execute", "No method was defined");
4910  return;
4911  }
4912  TList* argList = method->GetListOfMethodArgs();
4913  // Check number of actual parameters against of expected formal ones
4914 
4915  Int_t nparms = argList->LastIndex() + 1;
4916  Int_t argc = params ? params->GetEntries() : 0;
4917 
4918  if (argc > nparms) {
4919  Error("Execute","Too many parameters to call %s, got %d but expected at most %d.",method->GetName(),argc,nparms);
4920  return;
4921  }
4922  if (nparms != argc) {
4923  // Let's see if the 'missing' argument are all defaulted.
4924  // if nparms==0 then either we stopped earlier either argc is also zero and we can't reach here.
4925  assert(nparms > 0);
4926 
4927  TMethodArg *arg = (TMethodArg *) argList->At( 0 );
4928  if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
4929  // There is a default value for the first missing
4930  // argument, so we are fine.
4931  } else {
4932  Int_t firstDefault = -1;
4933  for (Int_t i = 0; i < nparms; i ++) {
4934  arg = (TMethodArg *) argList->At( i );
4935  if (arg && arg->GetDefault() && arg->GetDefault()[0]) {
4936  firstDefault = i;
4937  break;
4938  }
4939  }
4940  if (firstDefault >= 0) {
4941  Error("Execute","Too few arguments to call %s, got only %d but expected at least %d and at most %d.",method->GetName(),argc,firstDefault,nparms);
4942  } else {
4943  Error("Execute","Too few arguments to call %s, got only %d but expected %d.",method->GetName(),argc,nparms);
4944  }
4945  return;
4946  }
4947  }
4948 
4949  const char* listpar = "";
4950  TString complete(10);
4951  if (params) {
4952  // Create a character string of parameters from TObjArray
4953  TIter next(params);
4954  for (Int_t i = 0; i < argc; i ++) {
4955  TMethodArg* arg = (TMethodArg*) argList->At(i);
4956  TClingTypeInfo type(GetInterpreterImpl(), arg->GetFullTypeName());
4957  TObjString* nxtpar = (TObjString*) next();
4958  if (i) {
4959  complete += ',';
4960  }
4961  if (strstr(type.TrueName(*fNormalizedCtxt), "char")) {
4962  TString chpar('\"');
4963  chpar += (nxtpar->String()).ReplaceAll("\"", "\\\"");
4964  // At this point we have to check if string contains \\"
4965  // and apply some more sophisticated parser. Not implemented yet!
4966  complete += chpar;
4967  complete += '\"';
4968  }
4969  else {
4970  complete += nxtpar->String();
4971  }
4972  }
4973  listpar = complete.Data();
4974  }
4975 
4976  // And now execute it.
4977  R__LOCKGUARD_CLING(gInterpreterMutex);
4978  if (error) {
4979  *error = TInterpreter::kNoError;
4980  }
4981  // If the actual class of this object inherits 2nd (or more) from TObject,
4982  // 'obj' is unlikely to be the start of the object (as described by IsA()),
4983  // hence gInterpreter->Execute will improperly correct the offset.
4984  void* addr = cl->DynamicCast(TObject::Class(), obj, kFALSE);
4985  TClingCallFunc func(GetInterpreterImpl(), *fNormalizedCtxt);
4986  TClingMethodInfo *minfo = (TClingMethodInfo*)method->fInfo;
4987  func.Init(*minfo);
4988  func.SetArgs(listpar);
4989  // Now calculate the 'this' pointer offset for the method
4990  // when starting from the class described by cl.
4991  const CXXMethodDecl * mdecl = dyn_cast<CXXMethodDecl>(minfo->GetMethodDecl());
4992  Long_t offset = ((TClingClassInfo*)cl->GetClassInfo())->GetOffset(mdecl);
4993  void* address = (void*)((Long_t)addr + offset);
4994  func.Exec(address);
4995 }
4996 
4997 ////////////////////////////////////////////////////////////////////////////////
4998 
4999 void TCling::ExecuteWithArgsAndReturn(TMethod* method, void* address,
5000  const void* args[] /*=0*/,
5001  int nargs /*=0*/,
5002  void* ret/*= 0*/) const
5003 {
5004  if (!method) {
5005  Error("ExecuteWithArgsAndReturn", "No method was defined");
5006  return;
5007  }
5008 
5009  TClingMethodInfo* minfo = (TClingMethodInfo*) method->fInfo;
5010  TClingCallFunc func(*minfo,*fNormalizedCtxt);
5011  func.ExecWithArgsAndReturn(address, args, nargs, ret);
5012 }
5013 
5014 ////////////////////////////////////////////////////////////////////////////////
5015 /// Execute a cling macro.
5016 
5017 Long_t TCling::ExecuteMacro(const char* filename, EErrorCode* error)
5018 {
5019  R__LOCKGUARD_CLING(fLockProcessLine ? gInterpreterMutex : 0);
5020  fCurExecutingMacros.push_back(filename);
5021  Long_t result = TApplication::ExecuteFile(filename, (int*)error);
5022  fCurExecutingMacros.pop_back();
5023  return result;
5024 }
5025 
5026 ////////////////////////////////////////////////////////////////////////////////
5027 /// Return the file name of the current un-included interpreted file.
5028 /// See the documentation for GetCurrentMacroName().
5029 
5030 const char* TCling::GetTopLevelMacroName() const
5031 {
5032  Warning("GetTopLevelMacroName", "Must change return type!");
5033  return fCurExecutingMacros.back();
5034 }
5035 
5036 ////////////////////////////////////////////////////////////////////////////////
5037 /// Return the file name of the currently interpreted file,
5038 /// included or not. Example to illustrate the difference between
5039 /// GetCurrentMacroName() and GetTopLevelMacroName():
5040 /// ~~~ {.cpp}
5041 /// void inclfile() {
5042 /// std::cout << "In inclfile.C" << std::endl;
5043 /// std::cout << " TCling::GetCurrentMacroName() returns " <<
5044 /// TCling::GetCurrentMacroName() << std::endl;
5045 /// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5046 /// TCling::GetTopLevelMacroName() << std::endl;
5047 /// }
5048 /// ~~~
5049 /// ~~~ {.cpp}
5050 /// void mymacro() {
5051 /// std::cout << "In mymacro.C" << std::endl;
5052 /// std::cout << " TCling::GetCurrentMacroName() returns " <<
5053 /// TCling::GetCurrentMacroName() << std::endl;
5054 /// std::cout << " TCling::GetTopLevelMacroName() returns " <<
5055 /// TCling::GetTopLevelMacroName() << std::endl;
5056 /// std::cout << " Now calling inclfile..." << std::endl;
5057 /// gInterpreter->ProcessLine(".x inclfile.C");;
5058 /// }
5059 /// ~~~
5060 /// Running mymacro.C will print:
5061 ///
5062 /// ~~~ {.cpp}
5063 /// root [0] .x mymacro.C
5064 /// ~~~
5065 /// In mymacro.C
5066 /// ~~~ {.cpp}
5067 /// TCling::GetCurrentMacroName() returns ./mymacro.C
5068 /// TCling::GetTopLevelMacroName() returns ./mymacro.C
5069 /// ~~~
5070 /// Now calling inclfile...
5071 /// In inclfile.h
5072 /// ~~~ {.cpp}
5073 /// TCling::GetCurrentMacroName() returns inclfile.C
5074 /// TCling::GetTopLevelMacroName() returns ./mymacro.C
5075 /// ~~~
5076 
5077 const char* TCling::GetCurrentMacroName() const
5078 {
5079 #if defined(R__MUST_REVISIT)
5080 #if R__MUST_REVISIT(6,0)
5081  Warning("GetCurrentMacroName", "Must change return type!");
5082 #endif
5083 #endif
5084  return fCurExecutingMacros.back();
5085 }
5086 
5087 ////////////////////////////////////////////////////////////////////////////////
5088 /// Return the absolute type of typeDesc.
5089 /// E.g.: typeDesc = "class TNamed**", returns "TNamed".
5090 /// You need to use the result immediately before it is being overwritten.
5091 
5092 const char* TCling::TypeName(const char* typeDesc)
5093 {
5094  TTHREAD_TLS(char*) t = 0;
5095  TTHREAD_TLS(unsigned int) tlen = 0;
5096 
5097  unsigned int dlen = strlen(typeDesc);
5098  if (dlen > tlen) {
5099  delete[] t;
5100  t = new char[dlen + 1];
5101  tlen = dlen;
5102  }
5103  const char* s, *template_start;
5104  if (!strstr(typeDesc, "(*)(")) {
5105  s = strchr(typeDesc, ' ');
5106  template_start = strchr(typeDesc, '<');
5107  if (!strcmp(typeDesc, "long long")) {
5108  strlcpy(t, typeDesc, dlen + 1);
5109  }
5110  else if (!strncmp(typeDesc, "unsigned ", s + 1 - typeDesc)) {
5111  strlcpy(t, typeDesc, dlen + 1);
5112  }
5113  // s is the position of the second 'word' (if any)
5114  // except in the case of templates where there will be a space
5115  // just before any closing '>': eg.
5116  // TObj<std::vector<UShort_t,__malloc_alloc_template<0> > >*
5117  else if (s && (template_start == 0 || (s < template_start))) {
5118  strlcpy(t, s + 1, dlen + 1);
5119  }
5120  else {
5121  strlcpy(t, typeDesc, dlen + 1);
5122  }
5123  }
5124  else {
5125  strlcpy(t, typeDesc, dlen + 1);
5126  }
5127  int l = strlen(t);
5128  while (l > 0 && (t[l - 1] == '*' || t[l - 1] == '&')) {
5129  t[--l] = 0;
5130  }
5131  return t;
5132 }
5133 
5134 static bool requiresRootMap(const char* rootmapfile, cling::Interpreter* interp)
5135 {
5136  assert(rootmapfile && *rootmapfile);
5137 
5138  llvm::StringRef libName = llvm::sys::path::filename(rootmapfile);
5139  libName.consume_back(".rootmap");
5140 
5141  return !gInterpreter->HasPCMForLibrary(libName.str().c_str());
5142 }
5143 
5144 ////////////////////////////////////////////////////////////////////////////////
5145 /// Read and parse a rootmapfile in its new format, and return 0 in case of
5146 /// success, -1 if the file has already been read, and -3 in case its format
5147 /// is the old one (e.g. containing "Library.ClassName"), -4 in case of syntax
5148 /// error.
5149 
5150 int TCling::ReadRootmapFile(const char *rootmapfile, TUniqueString *uniqueString)
5151 {
5152  if (!(rootmapfile && *rootmapfile))
5153  return 0;
5154 
5155  if (!requiresRootMap(rootmapfile, GetInterpreterImpl()))
5156  return 0; // success
5157 
5158  // For "class ", "namespace ", "typedef ", "header ", "enum ", "var " respectively
5159  const std::map<char, unsigned int> keyLenMap = {{'c',6},{'n',10},{'t',8},{'h',7},{'e',5},{'v',4}};
5160 
5161  std::string rootmapfileNoBackslash(rootmapfile);
5162 #ifdef _MSC_VER
5163  std::replace(rootmapfileNoBackslash.begin(), rootmapfileNoBackslash.end(), '\\', '/');
5164 #endif
5165  // Add content of a specific rootmap file
5166  if (fRootmapFiles->FindObject(rootmapfileNoBackslash.c_str()))
5167  return -1;
5168 
5169  if (uniqueString)
5170  uniqueString->Append(std::string("\n#line 1 \"Forward declarations from ") + rootmapfileNoBackslash + "\"\n");
5171 
5172  std::ifstream file(rootmapfileNoBackslash);
5173  std::string line;
5174  line.reserve(200);
5175  std::string lib_name;
5176  line.reserve(100);
5177  bool newFormat = false;
5178  while (getline(file, line, '\n')) {
5179  if (!newFormat && (line.compare(0, 8, "Library.") == 0 || line.compare(0, 8, "Declare.") == 0)) {
5180  file.close();
5181  return -3; // old format
5182  }
5183  newFormat = true;
5184 
5185  if (line.compare(0, 9, "{ decls }") == 0) {
5186  // forward declarations
5187 
5188  while (getline(file, line, '\n')) {
5189  if (line[0] == '[')
5190  break;
5191  if (!uniqueString) {
5192  Error("ReadRootmapFile", "Cannot handle \"{ decls }\" sections in custom rootmap file %s",
5193  rootmapfileNoBackslash.c_str());
5194  return -4;
5195  }
5196  uniqueString->Append(line);
5197  }
5198  }
5199  const char firstChar = line[0];
5200  if (firstChar == '[') {
5201  // new section (library)
5202  auto brpos = line.find(']');
5203  if (brpos == string::npos)
5204  continue;
5205  lib_name = line.substr(1, brpos - 1);
5206  size_t nspaces = 0;
5207  while (lib_name[nspaces] == ' ')
5208  ++nspaces;
5209  if (nspaces)
5210  lib_name.replace(0, nspaces, "");
5211  if (gDebug > 3) {
5212  TString lib_nameTstr(lib_name.c_str());
5213  TObjArray *tokens = lib_nameTstr.Tokenize(" ");
5214  const char *lib = ((TObjString *)tokens->At(0))->GetName();
5215  const char *wlib = gSystem->DynamicPathName(lib, kTRUE);
5216  if (wlib) {
5217  Info("ReadRootmapFile", "new section for %s", lib_nameTstr.Data());
5218  } else {
5219  Info("ReadRootmapFile", "section for %s (library does not exist)", lib_nameTstr.Data());
5220  }
5221  delete[] wlib;
5222  delete tokens;
5223  }
5224  } else {
5225  auto keyLenIt = keyLenMap.find(firstChar);
5226  if (keyLenIt == keyLenMap.end())
5227  continue;
5228  unsigned int keyLen = keyLenIt->second;
5229  // Do not make a copy, just start after the key
5230  const char *keyname = line.c_str() + keyLen;
5231  if (gDebug > 6)
5232  Info("ReadRootmapFile", "class %s in %s", keyname, lib_name.c_str());
5233  TEnvRec *isThere = fMapfile->Lookup(keyname);
5234  if (isThere) {
5235  if (lib_name != isThere->GetValue()) { // the same key for two different libs
5236  if (firstChar == 'n') {
5237  if (gDebug > 3)
5238  Info("ReadRootmapFile", "namespace %s found in %s is already in %s", keyname, lib_name.c_str(),
5239  isThere->GetValue());
5240  } else if (firstChar == 'h') { // it is a header: add the libname to the list of libs to be loaded.
5241  lib_name += " ";
5242  lib_name += isThere->GetValue();
5243  fMapfile->SetValue(keyname, lib_name.c_str());
5244  } else if (!TClassEdit::IsSTLCont(keyname)) {
5245  Warning("ReadRootmapFile", "%s %s found in %s is already in %s", line.substr(0, keyLen).c_str(),
5246  keyname, lib_name.c_str(), isThere->GetValue());
5247  }
5248  } else { // the same key for the same lib
5249  if (gDebug > 3)
5250  Info("ReadRootmapFile", "Key %s was already defined for %s", keyname, lib_name.c_str());
5251  }
5252  } else {
5253  fMapfile->SetValue(keyname, lib_name.c_str());
5254  }
5255  }
5256  }
5257  file.close();
5258  return 0;
5259 }
5260 
5261 ////////////////////////////////////////////////////////////////////////////////
5262 /// Create a resource table and read the (possibly) three resource files, i.e
5263 /// $ROOTSYS/etc/system<name> (or ROOTETCDIR/system<name>), $HOME/<name> and
5264 /// ./<name>. ROOT always reads ".rootrc" (in TROOT::InitSystem()). You can
5265 /// read additional user defined resource files by creating additional TEnv
5266 /// objects. By setting the shell variable ROOTENV_NO_HOME=1 the reading of
5267 /// the $HOME/<name> resource file will be skipped. This might be useful in
5268 /// case the home directory resides on an automounted remote file system
5269 /// and one wants to avoid the file system from being mounted.
5270 
5271 void TCling::InitRootmapFile(const char *name)
5272 {
5273  assert(requiresRootMap(name, GetInterpreterImpl()) && "We have a module!");
5274 
5275  if (!requiresRootMap(name, GetInterpreterImpl()))
5276  return;
5277 
5278  Bool_t ignore = fMapfile->IgnoreDuplicates(kFALSE);
5279 
5280  fMapfile->SetRcName(name);
5281 
5282  TString sname = "system";
5283  sname += name;
5284  char *s = gSystem->ConcatFileName(TROOT::GetEtcDir(), sname);
5285 
5286  Int_t ret = ReadRootmapFile(s);
5287  if (ret == -3) // old format
5288  fMapfile->ReadFile(s, kEnvGlobal);
5289  delete [] s;
5290  if (!gSystem->Getenv("ROOTENV_NO_HOME")) {
5291  s = gSystem->ConcatFileName(gSystem->HomeDirectory(), name);
5292  ret = ReadRootmapFile(s);
5293  if (ret == -3) // old format
5294  fMapfile->ReadFile(s, kEnvUser);
5295  delete [] s;
5296  if (strcmp(gSystem->HomeDirectory(), gSystem->WorkingDirectory())) {
5297  ret = ReadRootmapFile(name);
5298  if (ret == -3) // old format
5299  fMapfile->ReadFile(name, kEnvLocal);
5300  }
5301  } else {
5302  ret = ReadRootmapFile(name);
5303  if (ret == -3) // old format
5304  fMapfile->ReadFile(name, kEnvLocal);
5305  }
5306  fMapfile->IgnoreDuplicates(ignore);
5307 }
5308 
5309 
5310 namespace {
5311  using namespace clang;
5312 
5313  class ExtVisibleStorageAdder: public RecursiveASTVisitor<ExtVisibleStorageAdder>{
5314  // This class is to be considered an helper for autoloading.
5315  // It is a recursive visitor is used to inspect namespaces coming from
5316  // forward declarations in rootmaps and to set the external visible
5317  // storage flag for them.
5318  public:
5319  ExtVisibleStorageAdder(std::unordered_set<const NamespaceDecl*>& nsSet): fNSSet(nsSet) {};
5320  bool VisitNamespaceDecl(NamespaceDecl* nsDecl) {
5321  // We want to enable the external lookup for this namespace
5322  // because it may shadow the lookup of other names contained
5323  // in that namespace
5324 
5325  nsDecl->setHasExternalVisibleStorage();
5326  fNSSet.insert(nsDecl);
5327  return true;
5328  }
5329  private:
5330  std::unordered_set<const NamespaceDecl*>& fNSSet;
5331 
5332  };
5333 }
5334 
5335 ////////////////////////////////////////////////////////////////////////////////
5336 /// Load map between class and library. If rootmapfile is specified a
5337 /// specific rootmap file can be added (typically used by ACLiC).
5338 /// In case of error -1 is returned, 0 otherwise.
5339 /// The interpreter uses this information to automatically load the shared
5340 /// library for a class (autoload mechanism), see the AutoLoad() methods below.
5341 
5342 Int_t TCling::LoadLibraryMap(const char* rootmapfile)
5343 {
5344  if (rootmapfile && *rootmapfile && !requiresRootMap(rootmapfile, GetInterpreterImpl()))
5345  return 0;
5346 
5347  R__LOCKGUARD(gInterpreterMutex);
5348 
5349  // open the [system].rootmap files
5350  if (!fMapfile) {
5351  fMapfile = new TEnv();
5352  fMapfile->IgnoreDuplicates(kTRUE);
5353  fRootmapFiles = new TObjArray;
5354  fRootmapFiles->SetOwner();
5355  InitRootmapFile(".rootmap");
5356  }
5357 
5358  // Prepare a list of all forward declarations for cling
5359  // For some experiments it is easily as big as 500k characters. To be on the
5360  // safe side, we go for 1M.
5361  TUniqueString uniqueString(1048576);
5362 
5363  // Load all rootmap files in the dynamic load path ((DY)LD_LIBRARY_PATH, etc.).
5364  // A rootmap file must end with the string ".rootmap".
5365  TString ldpath = gSystem->GetDynamicPath();
5366  if (ldpath != fRootmapLoadPath) {
5367  fRootmapLoadPath = ldpath;
5368 #ifdef WIN32
5369  TObjArray* paths = ldpath.Tokenize(";");
5370 #else
5371  TObjArray* paths = ldpath.Tokenize(":");
5372 #endif
5373  TString d;
5374  for (Int_t i = 0; i < paths->GetEntriesFast(); i++) {
5375  d = ((TObjString *)paths->At(i))->GetString();
5376  // check if directory already scanned
5377  Int_t skip = 0;
5378  for (Int_t j = 0; j < i; j++) {
5379  TString pd = ((TObjString *)paths->At(j))->GetString();
5380  if (pd == d) {
5381  skip++;
5382  break;
5383  }
5384  }
5385  if (!skip) {
5386  void* dirp = gSystem->OpenDirectory(d);
5387  if (dirp) {
5388  if (gDebug > 3) {
5389  Info("LoadLibraryMap", "%s", d.Data());
5390  }
5391  const char* f1;
5392  while ((f1 = gSystem->GetDirEntry(dirp))) {
5393  TString f = f1;
5394  if (f.EndsWith(".rootmap")) {
5395  TString p;
5396  p = d + "/" + f;
5397  if (!gSystem->AccessPathName(p, kReadPermission)) {
5398  if (!fRootmapFiles->FindObject(f) && f != ".rootmap") {
5399  if (gDebug > 4) {
5400  Info("LoadLibraryMap", " rootmap file: %s", p.Data());
5401  }
5402  Int_t ret = ReadRootmapFile(p, &uniqueString);
5403 
5404  if (ret == 0)
5405  fRootmapFiles->Add(new TNamed(gSystem->BaseName(f), p.Data()));
5406  if (ret == -3) {
5407  // old format
5408  fMapfile->ReadFile(p, kEnvGlobal);
5409  fRootmapFiles->Add(new TNamed(f, p));
5410  }
5411  }
5412  // else {
5413  // fprintf(stderr,"Reject %s because %s is already there\n",p.Data(),f.Data());
5414  // fRootmapFiles->FindObject(f)->ls();
5415  // }
5416  }
5417  }
5418  if (f.BeginsWith("rootmap")) {
5419  TString p;
5420  p = d + "/" + f;
5421  FileStat_t stat;
5422  if (gSystem->GetPathInfo(p, stat) == 0 && R_ISREG(stat.fMode)) {
5423  Warning("LoadLibraryMap", "please rename %s to end with \".rootmap\"", p.Data());
5424  }
5425  }
5426  }
5427  }
5428  gSystem->FreeDirectory(dirp);
5429  }
5430  }
5431  delete paths;
5432  if (fMapfile->GetTable() && !fMapfile->GetTable()->GetEntries()) {
5433  return -1;
5434  }
5435  }
5436  if (rootmapfile && *rootmapfile) {
5437  Int_t res = ReadRootmapFile(rootmapfile, &uniqueString);
5438  if (res == 0) {
5439  //TString p = gSystem->ConcatFileName(gSystem->pwd(), rootmapfile);
5440  //fRootmapFiles->Add(new TNamed(gSystem->BaseName(rootmapfile), p.Data()));
5441  fRootmapFiles->Add(new TNamed(gSystem->BaseName(rootmapfile), rootmapfile));
5442  }
5443  else if (res == -3) {
5444  // old format
5445  Bool_t ignore = fMapfile->IgnoreDuplicates(kFALSE);
5446  fMapfile->ReadFile(rootmapfile, kEnvGlobal);
5447  fRootmapFiles->Add(new TNamed(gSystem->BaseName(rootmapfile), rootmapfile));
5448  fMapfile->IgnoreDuplicates(ignore);
5449  }
5450  }
5451  TEnvRec* rec;
5452  TIter next(fMapfile->GetTable());
5453  while ((rec = (TEnvRec*) next())) {
5454  TString cls = rec->GetName();
5455  if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
5456  // get the first lib from the list of lib and dependent libs
5457  TString libs = rec->GetValue();
5458  if (libs == "") {
5459  continue;
5460  }
5461  TString delim(" ");
5462  TObjArray* tokens = libs.Tokenize(delim);
5463  const char* lib = ((TObjString*)tokens->At(0))->GetName();
5464  // convert "@@" to "::", we used "@@" because TEnv
5465  // considers "::" a terminator
5466  cls.Remove(0, 8);
5467  cls.ReplaceAll("@@", "::");
5468  // convert "-" to " ", since class names may have
5469  // blanks and TEnv considers a blank a terminator
5470  cls.ReplaceAll("-", " ");
5471  if (gDebug > 6) {
5472  const char* wlib = gSystem->DynamicPathName(lib, kTRUE);
5473  if (wlib) {
5474  Info("LoadLibraryMap", "class %s in %s", cls.Data(), wlib);
5475  }
5476  else {
5477  Info("LoadLibraryMap", "class %s in %s (library does not exist)", cls.Data(), lib);
5478  }
5479  delete[] wlib;
5480  }
5481  delete tokens;
5482  }
5483  else if (!strncmp(cls.Data(), "Declare.", 8) && cls.Length() > 8) {
5484  cls.Remove(0, 8);
5485  // convert "-" to " ", since class names may have
5486  // blanks and TEnv considers a blank a terminator
5487  cls.ReplaceAll("-", " ");
5488  fInterpreter->declare(cls.Data());
5489  }
5490  }
5491 
5492  // Process the forward declarations collected
5493  cling::Transaction* T = nullptr;
5494  auto compRes= fInterpreter->declare(uniqueString.Data(), &T);
5495  assert(cling::Interpreter::kSuccess == compRes && "A declaration in a rootmap could not be compiled");
5496 
5497  if (compRes!=cling::Interpreter::kSuccess){
5498  Warning("LoadLibraryMap",
5499  "Problems in %s declaring '%s' were encountered.", rootmapfile, uniqueString.Data()) ;
5500  }
5501 
5502  if (T){
5503  ExtVisibleStorageAdder evsAdder(fNSFromRootmaps);
5504  for (auto declIt = T->decls_begin(); declIt < T->decls_end(); ++declIt) {
5505  if (declIt->m_DGR.isSingleDecl()) {
5506  if (Decl* D = declIt->m_DGR.getSingleDecl()) {
5507  if (NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(D)) {
5508  evsAdder.TraverseDecl(NSD);
5509  }
5510  }
5511  }
5512  }
5513  }
5514 
5515  // clear duplicates
5516 
5517  return 0;
5518 }
5519 
5520 ////////////////////////////////////////////////////////////////////////////////
5521 /// Scan again along the dynamic path for library maps. Entries for the loaded
5522 /// shared libraries are unloaded first. This can be useful after reseting
5523 /// the dynamic path through TSystem::SetDynamicPath()
5524 /// In case of error -1 is returned, 0 otherwise.
5525 
5526 Int_t TCling::RescanLibraryMap()
5527 {
5528  UnloadAllSharedLibraryMaps();
5529  LoadLibraryMap();
5530  return 0;
5531 }
5532 
5533 ////////////////////////////////////////////////////////////////////////////////
5534 /// Reload the library map entries coming from all the loaded shared libraries,
5535 /// after first unloading the current ones.
5536 /// In case of error -1 is returned, 0 otherwise.
5537 
5538 Int_t TCling::ReloadAllSharedLibraryMaps()
5539 {
5540  const TString sharedLibLStr = GetSharedLibs();
5541  const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
5542  const Int_t nrSharedLibs = sharedLibL->GetEntriesFast();
5543  for (Int_t ilib = 0; ilib < nrSharedLibs; ilib++) {
5544  const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
5545  const TString sharedLibBaseStr = gSystem->BaseName(sharedLibStr);
5546  const Int_t ret = UnloadLibraryMap(sharedLibBaseStr);
5547  if (ret < 0) {
5548  continue;
5549  }
5550  TString rootMapBaseStr = sharedLibBaseStr;
5551  if (sharedLibBaseStr.EndsWith(".dll")) {
5552  rootMapBaseStr.ReplaceAll(".dll", "");
5553  }
5554  else if (sharedLibBaseStr.EndsWith(".DLL")) {
5555  rootMapBaseStr.ReplaceAll(".DLL", "");
5556  }
5557  else if (sharedLibBaseStr.EndsWith(".so")) {
5558  rootMapBaseStr.ReplaceAll(".so", "");
5559  }
5560  else if (sharedLibBaseStr.EndsWith(".sl")) {
5561  rootMapBaseStr.ReplaceAll(".sl", "");
5562  }
5563  else if (sharedLibBaseStr.EndsWith(".dl")) {
5564  rootMapBaseStr.ReplaceAll(".dl", "");
5565  }
5566  else if (sharedLibBaseStr.EndsWith(".a")) {
5567  rootMapBaseStr.ReplaceAll(".a", "");
5568  }
5569  else {
5570  Error("ReloadAllSharedLibraryMaps", "Unknown library type %s", sharedLibBaseStr.Data());
5571  delete sharedLibL;
5572  return -1;
5573  }
5574  rootMapBaseStr += ".rootmap";
5575  const char* rootMap = gSystem->Which(gSystem->GetDynamicPath(), rootMapBaseStr);
5576  if (!rootMap) {
5577  Error("ReloadAllSharedLibraryMaps", "Could not find rootmap %s in path", rootMapBaseStr.Data());
5578  delete[] rootMap;
5579  delete sharedLibL;
5580  return -1;
5581  }
5582  const Int_t status = LoadLibraryMap(rootMap);
5583  if (status < 0) {
5584  Error("ReloadAllSharedLibraryMaps", "Error loading map %s", rootMap);
5585  delete[] rootMap;
5586  delete sharedLibL;
5587  return -1;
5588  }
5589  delete[] rootMap;
5590  }
5591  delete sharedLibL;
5592  return 0;
5593 }
5594 
5595 ////////////////////////////////////////////////////////////////////////////////
5596 /// Unload the library map entries coming from all the loaded shared libraries.
5597 /// Returns 0 if succesful
5598 
5599 Int_t TCling::UnloadAllSharedLibraryMaps()
5600 {
5601  const TString sharedLibLStr = GetSharedLibs();
5602  const TObjArray* sharedLibL = sharedLibLStr.Tokenize(" ");
5603  for (Int_t ilib = 0; ilib < sharedLibL->GetEntriesFast(); ilib++) {
5604  const TString sharedLibStr = ((TObjString*)sharedLibL->At(ilib))->GetString();
5605  const TString sharedLibBaseStr = gSystem->BaseName(sharedLibStr);
5606  UnloadLibraryMap(sharedLibBaseStr);
5607  }
5608  delete sharedLibL;
5609  return 0;
5610 }
5611 
5612 ////////////////////////////////////////////////////////////////////////////////
5613 /// Unload library map entries coming from the specified library.
5614 /// Returns -1 in case no entries for the specified library were found,
5615 /// 0 otherwise.
5616 
5617 Int_t TCling::UnloadLibraryMap(const char* library)
5618 {
5619  if (!fMapfile || !library || !*library) {
5620  return 0;
5621  }
5622  TString libname(library);
5623  Ssiz_t idx = libname.Last('.');
5624  if (idx != kNPOS) {
5625  libname.Remove(idx);
5626  }
5627  size_t len = libname.Length();
5628  TEnvRec *rec;
5629  TIter next(fMapfile->GetTable());
5630  R__LOCKGUARD(gInterpreterMutex);
5631  Int_t ret = 0;
5632  while ((rec = (TEnvRec *) next())) {
5633  TString cls = rec->GetName();
5634  if (cls.Length() > 2) {
5635  // get the first lib from the list of lib and dependent libs
5636  TString libs = rec->GetValue();
5637  if (libs == "") {
5638  continue;
5639  }
5640  TString delim(" ");
5641  TObjArray* tokens = libs.Tokenize(delim);
5642  const char* lib = ((TObjString *)tokens->At(0))->GetName();
5643  if (!strncmp(cls.Data(), "Library.", 8) && cls.Length() > 8) {
5644  // convert "@@" to "::", we used "@@" because TEnv
5645  // considers "::" a terminator
5646  cls.Remove(0, 8);
5647  cls.ReplaceAll("@@", "::");
5648  // convert "-" to " ", since class names may have
5649  // blanks and TEnv considers a blank a terminator
5650  cls.ReplaceAll("-", " ");
5651  }
5652  if (!strncmp(lib, libname.Data(), len)) {
5653  if (fMapfile->GetTable()->Remove(rec) == 0) {
5654  Error("UnloadLibraryMap", "entry for <%s, %s> not found in library map table", cls.Data(), lib);
5655  ret = -1;
5656  }
5657  }
5658  delete tokens;
5659  }
5660  }
5661  if (ret >= 0) {
5662  TString library_rootmap(library);
5663  if (!library_rootmap.EndsWith(".rootmap"))
5664  library_rootmap.Append(".rootmap");
5665  TNamed* mfile = 0;
5666  while ((mfile = (TNamed *)fRootmapFiles->FindObject(library_rootmap))) {
5667  fRootmapFiles->Remove(mfile);
5668  delete mfile;
5669  }
5670  fRootmapFiles->Compress();
5671  }
5672  return ret;
5673 }
5674 
5675 ////////////////////////////////////////////////////////////////////////////////
5676 /// Register the autoloading information for a class.
5677 /// libs is a space separated list of libraries.
5678 
5679 Int_t TCling::SetClassSharedLibs(const char *cls, const char *libs)
5680 {
5681  if (!cls || !*cls)
5682  return 0;
5683 
5684  TString key = TString("Library.") + cls;
5685  // convert "::" to "@@", we used "@@" because TEnv
5686  // considers "::" a terminator
5687  key.ReplaceAll("::", "@@");
5688  // convert "-" to " ", since class names may have
5689  // blanks and TEnv considers a blank a terminator
5690  key.ReplaceAll(" ", "-");
5691 
5692  R__LOCKGUARD(gInterpreterMutex);
5693  if (!fMapfile) {
5694  fMapfile = new TEnv();
5695  fMapfile->IgnoreDuplicates(kTRUE);
5696 
5697  fRootmapFiles = new TObjArray;
5698  fRootmapFiles->SetOwner();
5699 
5700  InitRootmapFile(".rootmap");
5701  }
5702  //fMapfile->SetValue(key, libs);
5703  fMapfile->SetValue(cls, libs);
5704  return 1;
5705 }
5706 
5707 ////////////////////////////////////////////////////////////////////////////////
5708 /// Demangle the name (from the typeinfo) and then request the class
5709 /// via the usual name based interface (TClass::GetClass).
5710 
5711 TClass *TCling::GetClass(const std::type_info& typeinfo, Bool_t load) const
5712 {
5713  int err = 0;
5714  char* demangled_name = TClassEdit::DemangleTypeIdName(typeinfo, err);
5715  if (err) return 0;
5716  TClass* theClass = TClass::GetClass(demangled_name, load, kTRUE);
5717  free(demangled_name);
5718  return theClass;
5719 }
5720 
5721 ////////////////////////////////////////////////////////////////////////////////
5722 /// Load library containing the specified class. Returns 0 in case of error
5723 /// and 1 in case if success.
5724 
5725 Int_t TCling::AutoLoad(const std::type_info& typeinfo, Bool_t knowDictNotLoaded /* = kFALSE */)
5726 {
5727  assert(IsClassAutoloadingEnabled() && "Calling when autoloading is off!");
5728 
5729  int err = 0;
5730  char* demangled_name_c = TClassEdit::DemangleTypeIdName(typeinfo, err);
5731  if (err) {
5732  return 0;
5733  }
5734 
5735  std::string demangled_name(demangled_name_c);
5736  free(demangled_name_c);
5737 
5738  // AutoLoad expects (because TClass::GetClass already prepares it that way) a
5739  // shortened name.
5740  TClassEdit::TSplitType splitname( demangled_name.c_str(), (TClassEdit::EModType)(TClassEdit::kLong64 | TClassEdit::kDropStd) );
5741  splitname.ShortType(demangled_name, TClassEdit::kDropStlDefault | TClassEdit::kDropStd);
5742 
5743  // No need to worry about typedef, they aren't any ... but there are
5744  // inlined namespaces ...
5745 
5746  Int_t result = AutoLoad(demangled_name.c_str());
5747  if (result == 0) {
5748  demangled_name = TClassEdit::GetLong64_Name(demangled_name);
5749  result = AutoLoad(demangled_name.c_str(), knowDictNotLoaded);
5750  }
5751 
5752  return result;
5753 }
5754 
5755 ////////////////////////////////////////////////////////////////////////////////
5756 /// Load library containing the specified class. Returns 0 in case of error
5757 /// and 1 in case if success.
5758 
5759 Int_t TCling::AutoLoad(const char *cls, Bool_t knowDictNotLoaded /* = kFALSE */)
5760 {
5761  // TClass::GetClass explicitly calls gInterpreter->AutoLoad. When called from
5762  // rootcling (in *_rdict.pcm file generation) it is a no op.
5763  // FIXME: We should avoid calling autoload when we know we are not supposed
5764  // to and transform this check into an assert.
5765  if (!IsClassAutoloadingEnabled()) {
5766  // Never load any library from rootcling/genreflex.
5767  if (gDebug > 2) {
5768  Info("TCling::AutoLoad", "Explicitly disabled (the class name is %s)", cls);
5769  }
5770  return 0;
5771  }
5772 
5773  assert(IsClassAutoloadingEnabled() && "Calling when autoloading is off!");
5774 
5775  R__LOCKGUARD(gInterpreterMutex);
5776 
5777  if (!knowDictNotLoaded && gClassTable->GetDictNorm(cls)) {
5778  // The library is already loaded as the class's dictionary is known.
5779  // Return success.
5780  // Note: the name (cls) is expected to be normalized as it comes either
5781  // from a callbacks (that can/should calculate the normalized name from the
5782  // decl) or from TClass::GetClass (which does also calculate the normalized
5783  // name).
5784  return 1;
5785  }
5786 
5787  if (gDebug > 2) {
5788  Info("TCling::AutoLoad",
5789  "Trying to autoload for %s", cls);
5790  }
5791 
5792  if (!gROOT || !gInterpreter || gROOT->TestBit(TObject::kInvalidObject)) {
5793  if (gDebug > 2) {
5794  Info("TCling::AutoLoad",
5795  "Disabled due to gROOT or gInterpreter being invalid/not ready (the class name is %s)", cls);
5796  }
5797  return 0;
5798  }
5799  // Prevent the recursion when the library dictionary are loaded.
5800  SuspendAutoloadingRAII autoLoadOff(this);
5801  // Try using externally provided callback first.
5802  if (fAutoLoadCallBack) {
5803  int success = (*(AutoLoadCallBack_t)fAutoLoadCallBack)(cls);
5804  if (success)
5805  return success;
5806  }
5807  // lookup class to find list of dependent libraries
5808  Int_t status = 0;
5809  TString deplibs = GetClassSharedLibs(cls);
5810  if (!deplibs.IsNull()) {
5811  TString delim(" ");
5812  TObjArray* tokens = deplibs.Tokenize(delim);
5813  for (Int_t i = (tokens->GetEntriesFast() - 1); i > 0; --i) {
5814  const char* deplib = ((TObjString*)tokens->At(i))->GetName();
5815  if (gROOT->LoadClass(cls, deplib) == 0) {
5816  if (gDebug > 0) {
5817  Info("TCling::AutoLoad",
5818  "loaded dependent library %s for %s", deplib, cls);
5819  }
5820  }
5821  else {
5822  Error("TCling::AutoLoad",
5823  "failure loading dependent library %s for %s",
5824  deplib, cls);
5825  }
5826  }
5827  const char* lib = ((TObjString*)tokens->At(0))->GetName();
5828  if (lib && lib[0]) {
5829  if (gROOT->LoadClass(cls, lib) == 0) {
5830  if (gDebug > 0) {
5831  Info("TCling::AutoLoad",
5832  "loaded library %s for %s", lib, cls);
5833  }
5834  status = 1;
5835  }
5836  else {
5837  Error("TCling::AutoLoad",
5838  "failure loading library %s for %s", lib, cls);
5839  }
5840  }
5841  delete tokens;
5842  }
5843 
5844  return status;
5845 }
5846 
5847 ////////////////////////////////////////////////////////////////////////////////
5848 /// Parse the payload or header.
5849 
5850 static cling::Interpreter::CompilationResult ExecAutoParse(const char *what,
5851  Bool_t header,
5852  cling::Interpreter *interpreter)
5853 {
5854  std::string code = gNonInterpreterClassDef ;
5855  if (!header) {
5856  // This is the complete header file content and not the
5857  // name of a header.
5858  code += what;
5859 
5860  } else {
5861  code += ("#include \"");
5862  code += what;
5863  code += "\"\n";
5864  }
5865  code += ("#ifdef __ROOTCLING__\n"
5866  "#undef __ROOTCLING__\n"
5867  + gInterpreterClassDef +
5868  "#endif");
5869 
5870  cling::Interpreter::CompilationResult cr;
5871  {
5872  // scope within which diagnostics are de-activated
5873  // For now we disable diagnostics because we saw them already at
5874  // dictionary generation time. That won't be an issue with the PCMs.
5875 
5876  Sema &SemaR = interpreter->getSema();
5877  ROOT::Internal::ParsingStateRAII parsingStateRAII(interpreter->getParser(), SemaR);
5878  clangDiagSuppr diagSuppr(SemaR.getDiagnostics());
5879 
5880  #if defined(R__MUST_REVISIT)
5881  #if R__MUST_REVISIT(6,2)
5882  Warning("TCling::RegisterModule","Diagnostics suppression should be gone by now.");
5883  #endif
5884  #endif
5885 
5886  cr = interpreter->parseForModule(code);
5887  }
5888  return cr;
5889 }
5890 
5891 ////////////////////////////////////////////////////////////////////////////////
5892 /// Helper routine for TCling::AutoParse implementing the actual call to the
5893 /// parser and looping over template parameters (if
5894 /// any) and when they don't have a registered header to autoparse,
5895 /// recurse over their template parameters.
5896 ///
5897 /// Returns the number of header parsed.
5898 
5899 UInt_t TCling::AutoParseImplRecurse(const char *cls, bool topLevel)
5900 {
5901  // We assume the lock has already been taken.
5902  // R__LOCKGUARD(gInterpreterMutex);
5903 
5904  Int_t nHheadersParsed = 0;
5905  unsigned long offset = 0;
5906  if (strncmp(cls, "const ", 6) == 0) {
5907  offset = 6;
5908  }
5909 
5910  // Loop on the possible autoparse keys
5911  bool skipFirstEntry = false;
5912  std::vector<std::string> autoparseKeys;
5913  if (strchr(cls, '<')) {
5914  int nestedLoc = 0;
5915  TClassEdit::GetSplit(cls + offset, autoparseKeys, nestedLoc, TClassEdit::kDropTrailStar);
5916  // Check if we can skip the name of the template in the autoparses
5917  // Take all the scopes one by one. If all of them are in the AST, we do not
5918  // need to autoparse for that particular template.
5919  if (!autoparseKeys.empty() && !autoparseKeys[0].empty()) {
5920  // autoparseKeys[0] is empty when the input is not a template instance.
5921  // The case strchr(cls, '<') != 0 but still not a template instance can
5922  // happens 'just' for string (GetSplit replaces the template by the short name
5923  // and then use that for thew splitting)
5924  TString templateName(autoparseKeys[0]);
5925  auto tokens = templateName.Tokenize("::");
5926  clang::NamedDecl* previousScopeAsNamedDecl = nullptr;
5927  clang::DeclContext* previousScopeAsContext = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
5928  if (TClassEdit::IsStdClass(cls + offset))
5929  previousScopeAsContext = fInterpreter->getSema().getStdNamespace();
5930  auto nTokens = tokens->GetEntries();
5931  for (Int_t tk = 0; tk < nTokens; ++tk) {
5932  auto scopeObj = tokens->UncheckedAt(tk);
5933  auto scopeName = ((TObjString*) scopeObj)->String().Data();
5934  previousScopeAsNamedDecl = cling::utils::Lookup::Named(&fInterpreter->getSema(), scopeName, previousScopeAsContext);
5935  // Check if we have multiple nodes in the AST with this name
5936  if ((clang::NamedDecl*)-1 == previousScopeAsNamedDecl) break;
5937  previousScopeAsContext = llvm::dyn_cast_or_null<clang::DeclContext>(previousScopeAsNamedDecl);
5938  if (!previousScopeAsContext) break; // this is not a context
5939  }
5940  delete tokens;
5941  // Now, let's check if the last scope, the template, has a definition, i.e. it's not a fwd decl
5942  if ((clang::NamedDecl*)-1 != previousScopeAsNamedDecl) {
5943  if (auto templateDecl = llvm::dyn_cast_or_null<clang::ClassTemplateDecl>(previousScopeAsNamedDecl)) {
5944  if (auto templatedDecl = templateDecl->getTemplatedDecl()) {
5945  skipFirstEntry = templatedDecl->hasDefinition();
5946  }
5947  }
5948  }
5949 
5950  }
5951  }
5952  if (topLevel) autoparseKeys.emplace_back(cls);
5953 
5954  for (const auto & apKeyStr : autoparseKeys) {
5955  if (skipFirstEntry) {
5956  skipFirstEntry=false;
5957  continue;
5958  }
5959  if (apKeyStr.empty()) continue;
5960  const char *apKey = apKeyStr.c_str();
5961  std::size_t normNameHash(fStringHashFunction(apKey));
5962  // If the class was not looked up
5963  if (gDebug > 1) {
5964  Info("TCling::AutoParse",
5965  "Starting autoparse for %s\n", apKey);
5966  }
5967  if (fLookedUpClasses.insert(normNameHash).second) {
5968  auto const &iter = fClassesHeadersMap.find(normNameHash);
5969  if (iter != fClassesHeadersMap.end()) {
5970  const cling::Transaction *T = fInterpreter->getCurrentTransaction();
5971  fTransactionHeadersMap.insert({T,normNameHash});
5972  auto const &hNamesPtrs = iter->second;
5973  if (gDebug > 1) {
5974  Info("TCling::AutoParse",
5975  "We can proceed for %s. We have %s headers.", apKey, std::to_string(hNamesPtrs.size()).c_str());
5976  }
5977  for (auto & hName : hNamesPtrs) {
5978  if (fParsedPayloadsAddresses.count(hName) == 1) continue;
5979  if (0 != fPayloads.count(normNameHash)) {
5980  float initRSSval=0.f, initVSIZEval=0.f;
5981  (void) initRSSval; // Avoid unused var warning
5982  (void) initVSIZEval;
5983  if (gDebug > 0) {
5984  Info("AutoParse",
5985  "Parsing full payload for %s", apKey);
5986  ProcInfo_t info;
5987  gSystem->GetProcInfo(&info);
5988  initRSSval = 1e-3*info.fMemResident;
5989  initVSIZEval = 1e-3*info.fMemVirtual;
5990  }
5991  auto cRes = ExecAutoParse(hName, kFALSE, GetInterpreterImpl());
5992  if (cRes != cling::Interpreter::kSuccess) {
5993  if (hName[0] == '\n')
5994  Error("AutoParse", "Error parsing payload code for class %s with content:\n%s", apKey, hName);
5995  } else {
5996  fParsedPayloadsAddresses.insert(hName);
5997  nHheadersParsed++;
5998  if (gDebug > 0){
5999  ProcInfo_t info;
6000  gSystem->GetProcInfo(&info);
6001  float endRSSval = 1e-3*info.fMemResident;
6002  float endVSIZEval = 1e-3*info.fMemVirtual;
6003  Info("Autoparse", ">>> RSS key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initRSSval, endRSSval, endRSSval-initRSSval);
6004  Info("Autoparse", ">>> VSIZE key %s - before %.3f MB - after %.3f MB - delta %.3f MB", apKey, initVSIZEval, endVSIZEval, endVSIZEval-initVSIZEval);
6005  }
6006  }
6007  } else if (!IsLoaded(hName)) {
6008  if (gDebug > 0) {
6009  Info("AutoParse",
6010  "Parsing single header %s", hName);
6011  }
6012  auto cRes = ExecAutoParse(hName, kTRUE, GetInterpreterImpl());
6013  if (cRes != cling::Interpreter::kSuccess) {
6014  Error("AutoParse", "Error parsing headerfile %s for class %s.", hName, apKey);
6015  } else {
6016  nHheadersParsed++;
6017  }
6018  }
6019  }
6020  }
6021  else {
6022  // There is no header registered for this class, if this a
6023  // template, it will be instantiated if/when it is requested
6024  // and if we do no load/parse its components we might end up
6025  // not using an eventual specialization.
6026  if (strchr(apKey, '<')) {
6027  nHheadersParsed += AutoParseImplRecurse(apKey, false);
6028  }
6029  }
6030  }
6031  }
6032 
6033  return nHheadersParsed;
6034 
6035 }
6036 
6037 ////////////////////////////////////////////////////////////////////////////////
6038 /// Parse the headers relative to the class
6039 /// Returns 1 in case of success, 0 in case of failure
6040 
6041 Int_t TCling::AutoParse(const char *cls)
6042 {
6043  if (llvm::StringRef(cls).contains("(lambda)"))
6044  return 0;
6045 
6046  if (!fHeaderParsingOnDemand || fIsAutoParsingSuspended) {
6047  if (fClingCallbacks->IsAutoloadingEnabled()) {
6048  return AutoLoad(cls);
6049  } else {
6050  return 0;
6051  }
6052  }
6053 
6054  R__LOCKGUARD(gInterpreterMutex);
6055 
6056  if (gDebug > 1) {
6057  Info("TCling::AutoParse",
6058  "Trying to autoparse for %s", cls);
6059  }
6060 
6061  // The catalogue of headers is in the dictionary
6062  if (fClingCallbacks->IsAutoloadingEnabled()
6063  && !gClassTable->GetDictNorm(cls)) {
6064  // Need RAII against recursive (dictionary payload) parsing (ROOT-8445).
6065  ROOT::Internal::ParsingStateRAII parsingStateRAII(fInterpreter->getParser(),
6066  fInterpreter->getSema());
6067  AutoLoad(cls, true /*knowDictNotLoaded*/);
6068  }
6069 
6070  // Prevent the recursion when the library dictionary are loaded.
6071  SuspendAutoloadingRAII autoLoadOff(this);
6072 
6073  // No recursive header parsing on demand; we require headers to be standalone.
6074  SuspendAutoParsing autoParseRAII(this);
6075 
6076  Int_t nHheadersParsed = AutoParseImplRecurse(cls,/*topLevel=*/ true);
6077 
6078  ProcessClassesToUpdate();
6079 
6080  return nHheadersParsed > 0 ? 1 : 0;
6081 }
6082 
6083 // This is a function which gets callback from cling when DynamicLibraryManager->loadLibrary failed for some reason.
6084 // Try to solve the problem by autoloading. Return true when autoloading success, return
6085 // false if not.
6086 bool TCling::LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
6087 {
6088  StringRef errMsg(errmessage);
6089  if (errMsg.contains("undefined symbol: ")) {
6090  // This branch is taken when the callback was from DynamicLibraryManager::loadLibrary
6091  std::string mangled_name = std::string(errMsg.split("undefined symbol: ").second);
6092  void* res = ((TCling*)gCling)->LazyFunctionCreatorAutoload(mangled_name);
6093  cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
6094  if (res && DLM && (DLM->loadLibrary(libStem, permanent, resolved) == cling::DynamicLibraryManager::kLoadLibSuccess))
6095  // Return success when LazyFunctionCreatorAutoload could find mangled_name
6096  return true;
6097  } else {
6098  // The callback is from IncrementalExecutor::diagnoseUnresolvedSymbols
6099  if ( ((TCling*)gCling)->LazyFunctionCreatorAutoload(errmessage))
6100  return true;
6101  }
6102 
6103  return false;
6104 }
6105 
6106 // This is a GNU implementation of hash used in bloom filter!
6107 static uint32_t GNUHash(StringRef S) {
6108  uint32_t H = 5381;
6109  for (uint8_t C : S)
6110  H = (H << 5) + H + C;
6111  return H;
6112 }
6113 
6114 static StringRef GetGnuHashSection(llvm::object::ObjectFile *file) {
6115  for (auto S : file->sections()) {
6116  StringRef name;
6117  S.getName(name);
6118  if (name == ".gnu.hash") {
6119  StringRef content;
6120  S.getContents(content);
6121  return content;
6122  }
6123  }
6124  return "";
6125 }
6126 
6127 /// Bloom filter in a stohastic data structure which can tell us if a symbol
6128 /// name does not exist in a library with 100% certainty. If it tells us it exists
6129 /// this may not be true: https://blogs.oracle.com/solaris/gnu-hash-elf-sections-v2
6130 ///
6131 /// ELF has this optimization in the new linkers by default, It is stored in the
6132 /// gnu.hash section of the object file.
6133 ///
6134 ///\returns true true if the symbol may be in the library.
6135 static bool MayExistInObjectFile(llvm::object::ObjectFile *soFile, uint32_t hash) {
6136  if (!soFile->isELF())
6137  return true;
6138 
6139  // LLVM9: soFile->makeTriple().is64Bit()
6140  const int bits = 8 * soFile->getBytesInAddress();
6141 
6142  StringRef contents = GetGnuHashSection(soFile);
6143  if (contents.size() < 16)
6144  // We need to search if the library doesn't have .gnu.hash section!
6145  return true;
6146  const char* hashContent = contents.data();
6147 
6148  // See https://flapenguin.me/2017/05/10/elf-lookup-dt-gnu-hash/ for .gnu.hash table layout.
6149  uint32_t maskWords = *reinterpret_cast<const uint32_t *>(hashContent + 8);
6150  uint32_t shift2 = *reinterpret_cast<const uint32_t *>(hashContent + 12);
6151  uint32_t hash2 = hash >> shift2;
6152  uint32_t n = (hash / bits) % maskWords;
6153 
6154  const char *bloomfilter = hashContent + 16;
6155  const char *hash_pos = bloomfilter + n*(bits/8); // * (Bits / 8)
6156  uint64_t word = *reinterpret_cast<const uint64_t *>(hash_pos);
6157  uint64_t bitmask = ( (1ULL << (hash % bits)) | (1ULL << (hash2 % bits)));
6158  return (bitmask & word) == bitmask;
6159 }
6160 
6161 /// Looks up symbols from a an object file, representing the library.
6162 ///\returns true on success.
6163 static bool FindSymbol(const std::string &library_filename,
6164  const std::string &mangled_name, unsigned IgnoreSymbolFlags = 0)
6165 {
6166  auto ObjF = llvm::object::ObjectFile::createObjectFile(ROOT::TMetaUtils::GetRealPath(library_filename));
6167  if (!ObjF) {
6168  if (gDebug > 1)
6169  Warning("TCling__FindSymbol", "Failed to read object file %s", library_filename.c_str());
6170  return false;
6171  }
6172 
6173  llvm::object::ObjectFile *BinObjFile = ObjF.get().getBinary();
6174 
6175  uint32_t hashedMangle = GNUHash(mangled_name);
6176  // If the symbol does not exist, exit early. In case it may exist, iterate.
6177  if (!MayExistInObjectFile(BinObjFile, hashedMangle))
6178  return false;
6179 
6180  for (const auto &S : BinObjFile->symbols()) {
6181  uint32_t Flags = S.getFlags();
6182  // Do not insert in the table symbols flagged to ignore.
6183  if (Flags & IgnoreSymbolFlags)
6184  continue;
6185 
6186  // Note, we are at last resort and loading library based on a weak
6187  // symbol is allowed. Otherwise, the JIT will issue an unresolved
6188  // symbol error.
6189  //
6190  // There are other weak symbol kinds (marked as 'V') to denote
6191  // typeinfo and vtables. It is unclear whether we should load such
6192  // libraries or from which library we should resolve the symbol.
6193  // We seem to not have a way to differentiate it from the symbol API.
6194 
6195  llvm::Expected<StringRef> SymNameErr = S.getName();
6196  if (!SymNameErr) {
6197  Warning("TCling__FindSymbol", "Failed to read symbol %s", mangled_name.c_str());
6198  continue;
6199  }
6200 
6201  if (SymNameErr.get() == mangled_name) {
6202  if (gDebug > 1)
6203  Info("TCling__FindSymbol", "Symbol %s found in %s\n",
6204  mangled_name.c_str(), library_filename.c_str());
6205  return true;
6206  }
6207  }
6208 
6209  if (!BinObjFile->isELF())
6210  return false;
6211 
6212  // ELF file format has .dynstr section for the dynamic symbol table.
6213  const auto *ElfObj = cast<llvm::object::ELFObjectFileBase>(BinObjFile);
6214 
6215  for (const auto &S : ElfObj->getDynamicSymbolIterators()) {
6216  uint32_t Flags = S.getFlags();
6217  // DO NOT insert to table if symbol was undefined
6218  if (Flags & llvm::object::SymbolRef::SF_Undefined)
6219  continue;
6220 
6221  // Note, we are at last resort and loading library based on a weak
6222  // symbol is allowed. Otherwise, the JIT will issue an unresolved
6223  // symbol error.
6224  //
6225  // There are other weak symbol kinds (marked as 'V') to denote
6226  // typeinfo and vtables. It is unclear whether we should load such
6227  // libraries or from which library we should resolve the symbol.
6228  // We seem to not have a way to differentiate it from the symbol API.
6229 
6230  llvm::Expected<StringRef> SymNameErr = S.getName();
6231  if (!SymNameErr) {
6232  Warning("TCling__FindSymbol", "Failed to read symbol %s", mangled_name.c_str());
6233  continue;
6234  }
6235 
6236  if (SymNameErr.get() == mangled_name)
6237  return true;
6238  }
6239 
6240  return false;
6241 }
6242 
6243 static std::string ResolveSymbol(const std::string& mangled_name,
6244  cling::Interpreter *interp,
6245  bool searchSystem = true) {
6246  assert(!mangled_name.empty());
6247  using namespace llvm::sys::path;
6248  using namespace llvm::sys::fs;
6249 
6250  R__LOCKGUARD(gInterpreterMutex);
6251 
6252  static bool sFirstRun = true;
6253  static bool sFirstSystemLibrary = true;
6254  // LibraryPath contains a pair offset to the canonical dirname (stored as
6255  // sPaths[i]) and a filename. For example, `/home/foo/root/lib/libTMVA.so`,
6256  // the .first will contain an index in sPaths where `/home/foo/root/lib/`
6257  // will be stored and .second `libTMVA.so`.
6258  // This approach reduces the duplicate paths as at one location there may be
6259  // plenty of libraries.
6260  using LibraryPath = std::pair<uint32_t, std::string>;
6261  using LibraryPaths = std::vector<LibraryPath>;
6262  using BasePaths = std::vector<std::string>;
6263  static LibraryPaths sLibraries;
6264  static BasePaths sPaths;
6265  static LibraryPaths sQueriedLibraries;
6266 
6267  // For system header autoloading
6268  static LibraryPaths sSysLibraries;
6269 
6270  if (sFirstRun) {
6271  TCling__FindLoadedLibraries(sLibraries, sPaths, *interp, /* searchSystem */ false);
6272  sFirstRun = false;
6273  }
6274 
6275  auto GetLibFileName = [](const LibraryPath &P, const BasePaths &BaseP) {
6276  llvm::SmallString<512> Vec(BaseP[P.first]);
6277  llvm::sys::path::append(Vec, StringRef(P.second));
6278  return Vec.str().str();
6279  };
6280 
6281  if (!sQueriedLibraries.empty()) {
6282  // Last call we were asked if a library contains a symbol. Usually, the
6283  // caller wants to load this library. Check if was loaded and remove it
6284  // from our lists of not-yet-loaded libs.
6285  for (const LibraryPath &P : sQueriedLibraries) {
6286  const std::string LibName = GetLibFileName(P, sPaths);
6287  if (!gCling->IsLibraryLoaded(LibName.c_str()))
6288  continue;
6289 
6290  sLibraries.erase(std::remove(sLibraries.begin(), sLibraries.end(), P), sLibraries.end());
6291  if (!sSysLibraries.empty())
6292  sSysLibraries.erase(std::remove(sSysLibraries.begin(), sSysLibraries.end(), P), sSysLibraries.end());
6293  }
6294  }
6295 
6296  if (sFirstRun) {
6297  TCling__FindLoadedLibraries(sLibraries, sPaths, *interp, /* searchSystem */ false);
6298  sFirstRun = false;
6299  }
6300 
6301  // Iterate over files under this path. We want to get each ".so" files
6302  for (const LibraryPath &P : sLibraries) {
6303  const std::string LibName = GetLibFileName(P, sPaths);
6304 
6305  // FIXME: We should also iterate over the dynamic symbols for ROOT
6306  // libraries. However, it seems to be redundant for the moment as we do
6307  // not strictly require symbols from those sections. Enable after checking
6308  // performance!
6309  if (FindSymbol(LibName, mangled_name, /*ignore*/
6310  llvm::object::SymbolRef::SF_Undefined |
6311  llvm::object::SymbolRef::SF_Weak)) {
6312  sQueriedLibraries.push_back(P);
6313  return LibName;
6314  }
6315  }
6316 
6317  if (!searchSystem)
6318  return "";
6319 
6320  // Lookup in non-system libraries failed. Expand the search to the system.
6321  if (sFirstSystemLibrary) {
6322  TCling__FindLoadedLibraries(sSysLibraries, sPaths, *interp, /* searchSystem */ true);
6323  sFirstSystemLibrary = false;
6324  }
6325 
6326  for (const LibraryPath &P : sSysLibraries) {
6327  const std::string LibName = GetLibFileName(P, sPaths);
6328 
6329  if (FindSymbol(LibName, mangled_name, /*ignore*/
6330  llvm::object::SymbolRef::SF_Undefined |
6331  llvm::object::SymbolRef::SF_Weak)) {
6332  sQueriedLibraries.push_back(P);
6333  return LibName;
6334  }
6335  }
6336 
6337  return ""; // Search found no match.
6338 }
6339 
6340 static void* LazyFunctionCreatorAutoloadForModule(const std::string &mangled_name,
6341  cling::Interpreter *interp) {
6342 // The JIT gives us a mangled name which has only one leading underscore on
6343 // all platforms, for instance _ZN8TRandom34RndmEv. However, on OSX the
6344 // linker stores this symbol as __ZN8TRandom34RndmEv (adding an extra _).
6345  std::string maybe_prefixed_mangled_name = mangled_name;
6346 #ifdef R__MACOSX
6347  assert(!llvm::StringRef(mangled_name).startswith("__") && "Already added!");
6348  maybe_prefixed_mangled_name = "_" + maybe_prefixed_mangled_name;
6349 #endif
6350 
6351  std::string LibName = ResolveSymbol(maybe_prefixed_mangled_name, interp);
6352  if (LibName.empty())
6353  return nullptr;
6354 
6355  if (gSystem->Load(LibName.c_str(), "", false) < 0)
6356  Error("TCling__LazyFunctionCreatorAutoloadForModule",
6357  "Failed to load library %s", LibName.c_str());
6358 
6359  void* addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(mangled_name.c_str());
6360  return addr;
6361 }
6362 
6363 ////////////////////////////////////////////////////////////////////////////////
6364 /// Autoload a library based on a missing symbol.
6365 
6366 void* TCling::LazyFunctionCreatorAutoload(const std::string& mangled_name) {
6367  if (fCxxModulesEnabled)
6368  return LazyFunctionCreatorAutoloadForModule(mangled_name, GetInterpreterImpl());
6369 
6370  // First see whether the symbol is in the library that we are currently
6371  // loading. It will have access to the symbols of its dependent libraries,
6372  // thus checking "back()" is sufficient.
6373  if (!fRegisterModuleDyLibs.empty()) {
6374  if (void* addr = dlsym(fRegisterModuleDyLibs.back(),
6375  mangled_name.c_str())) {
6376  return addr;
6377  }
6378  }
6379 
6380  int err = 0;
6381  char* demangled_name_c = TClassEdit::DemangleName(mangled_name.c_str(), err);
6382  if (err) {
6383  return 0;
6384  }
6385 
6386  std::string name(demangled_name_c);
6387  free(demangled_name_c);
6388 
6389  //fprintf(stderr, "demangled name: '%s'\n", demangled_name);
6390  //
6391  // Separate out the class or namespace part of the
6392  // function name.
6393  //
6394 
6395  std::string::size_type pos = name.find("__thiscall ");
6396  if (pos != std::string::npos) {
6397  name.erase(0, pos + sizeof("__thiscall ")-1);
6398  }
6399  pos = name.find("__cdecl ");
6400  if (pos != std::string::npos) {
6401  name.erase(0, pos + sizeof("__cdecl ")-1);
6402  }
6403  if (!strncmp(name.c_str(), "typeinfo for ", sizeof("typeinfo for ")-1)) {
6404  name.erase(0, sizeof("typeinfo for ")-1);
6405  } else if (!strncmp(name.c_str(), "vtable for ", sizeof("vtable for ")-1)) {
6406  name.erase(0, sizeof("vtable for ")-1);
6407  } else if (!strncmp(name.c_str(), "operator", sizeof("operator")-1)
6408  && !isalnum(name[sizeof("operator")])) {
6409  // operator...(A, B) - let's try with A!
6410  name.erase(0, sizeof("operator")-1);
6411  pos = name.rfind('(');
6412  if (pos != std::string::npos) {
6413  name.erase(0, pos + 1);
6414  pos = name.find(",");
6415  if (pos != std::string::npos) {
6416  // remove next arg up to end, leaving only the first argument type.
6417  name.erase(pos);
6418  }
6419  pos = name.rfind(" const");
6420  if (pos != std::string::npos) {
6421  name.erase(pos, strlen(" const"));
6422  }
6423  while (!name.empty() && strchr("&*", name.back()))
6424  name.erase(name.length() - 1);
6425  }
6426  } else {
6427  TClassEdit::FunctionSplitInfo fsi;
6428  TClassEdit::SplitFunction(name, fsi);
6429  name = fsi.fScopeName;
6430  }
6431  //fprintf(stderr, "name: '%s'\n", name.c_str());
6432  // Now we have the class or namespace name, so do the lookup.
6433  TString libs = GetClassSharedLibs(name.c_str());
6434  if (libs.IsNull()) {
6435  // Not found in the map, all done.
6436  return 0;
6437  }
6438  //fprintf(stderr, "library: %s\n", iter->second.c_str());
6439  // Now we have the name of the libraries to load, so load them.
6440 
6441  TString lib;
6442  Ssiz_t posLib = 0;
6443  while (libs.Tokenize(lib, posLib)) {
6444  if (gSystem->Load(lib, "", kFALSE /*system*/) < 0) {
6445  // The library load failed, all done.
6446  //fprintf(stderr, "load failed: %s\n", errmsg.c_str());
6447  return 0;
6448  }
6449  }
6450 
6451  //fprintf(stderr, "load succeeded.\n");
6452  // Get the address of the function being called.
6453  void* addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(mangled_name.c_str());
6454  //fprintf(stderr, "addr: %016lx\n", reinterpret_cast<unsigned long>(addr));
6455  return addr;
6456 }
6457 
6458 ////////////////////////////////////////////////////////////////////////////////
6459 
6460 Bool_t TCling::IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl* nsDecl)
6461 {
6462  return fNSFromRootmaps.count(nsDecl) != 0;
6463 }
6464 
6465 ////////////////////////////////////////////////////////////////////////////////
6466 /// Internal function. Actually do the update of the ClassInfo when seeing
6467 // new TagDecl or NamespaceDecl.
6468 void TCling::RefreshClassInfo(TClass *cl, const clang::NamedDecl *def, bool alias)
6469 {
6470 
6471  TClingClassInfo *cci = ((TClingClassInfo *)cl->fClassInfo);
6472  if (cci) {
6473  // If we only had a forward declaration then update the
6474  // TClingClassInfo with the definition if we have it now.
6475  const NamedDecl *oldDef = llvm::dyn_cast_or_null<NamedDecl>(cci->GetDecl());
6476  if (!oldDef || (def && def != oldDef)) {
6477  cl->ResetCaches();
6478  TClass::RemoveClassDeclId(cci->GetDeclId());
6479  if (def) {
6480  // It's a tag decl, not a namespace decl.
6481  cci->Init(*cci->GetType());
6482  TClass::AddClassToDeclIdMap(cci->GetDeclId(), cl);
6483  }
6484  }
6485  } else if (!cl->TestBit(TClass::kLoading) && !cl->fHasRootPcmInfo) {
6486  cl->ResetCaches();
6487  // yes, this is almost a waste of time, but we do need to lookup
6488  // the 'type' corresponding to the TClass anyway in order to
6489  // preserve the opaque typedefs (Double32_t)
6490  if (!alias && def != nullptr)
6491  cl->fClassInfo = (ClassInfo_t *)new TClingClassInfo(GetInterpreterImpl(), def);
6492  else
6493  cl->fClassInfo = (ClassInfo_t *)new TClingClassInfo(GetInterpreterImpl(), cl->GetName());
6494  if (((TClingClassInfo *)cl->fClassInfo)->IsValid()) {
6495  // We now need to update the state and bits.
6496  if (cl->fState != TClass::kHasTClassInit) {
6497  // if (!cl->fClassInfo->IsValid()) cl->fState = TClass::kForwardDeclared; else
6498  cl->fState = TClass::kInterpreted;
6499  cl->ResetBit(TClass::kIsEmulation);
6500  }
6501  TClass::AddClassToDeclIdMap(((TClingClassInfo *)(cl->fClassInfo))->GetDeclId(), cl);
6502  } else {
6503  delete ((TClingClassInfo *)cl->fClassInfo);
6504  cl->fClassInfo = nullptr;
6505  }
6506  }
6507 }
6508 
6509 ////////////////////////////////////////////////////////////////////////////////
6510 /// Internal function. Inform a TClass about its new TagDecl or NamespaceDecl.
6511 void TCling::UpdateClassInfoWithDecl(const NamedDecl* ND)
6512 {
6513  const TagDecl *td = dyn_cast<TagDecl>(ND);
6514  const NamespaceDecl *ns = dyn_cast<NamespaceDecl>(ND);
6515  const NamedDecl *canon = nullptr;
6516 
6517  std::string name;
6518  TagDecl* tdDef = 0;
6519  if (td) {
6520  canon = tdDef = td->getDefinition();
6521  // Let's pass the decl to the TClass only if it has a definition.
6522  if (!tdDef) return;
6523 
6524  if (!tdDef->isCompleteDefinition() || llvm::isa<clang::FunctionDecl>(tdDef->getDeclContext())) {
6525  // Ignore incomplete definition.
6526  // Ignore declaration within a function.
6527  return;
6528  }
6529 
6530  auto declName = tdDef->getNameAsString();
6531  // Check if we have registered the unqualified name into the list
6532  // of TClass that are in kNoInfo, kEmulated or kFwdDeclaredState.
6533  // Since this is used as heureutistic to avoid spurrious calls to GetNormalizedName
6534  // the unqualified name is sufficient (and the fully qualified name might be
6535  // 'wrong' if there is difference in spelling in the template paramters (for example)
6536  if (!TClass::HasNoInfoOrEmuOrFwdDeclaredDecl(declName.c_str())){
6537  // fprintf (stderr,"WARNING: Impossible to find a TClassEntry in kNoInfo or kEmulated the decl of which would be called %s. Skip w/o building the normalized name.\n",declName.c_str() );
6538  return;
6539  }
6540 
6541  clang::QualType type(tdDef->getTypeForDecl(), 0);
6542  ROOT::TMetaUtils::GetNormalizedName(name, type, *fInterpreter, *fNormalizedCtxt);
6543  } else if (ns) {
6544  canon = ns->getCanonicalDecl();
6545  name = ND->getQualifiedNameAsString();
6546  } else {
6547  name = ND->getQualifiedNameAsString();
6548  }
6549 
6550  // Supposedly we are being called while something is being
6551  // loaded ... let's now tell the autoloader to do the work
6552  // yet another time.
6553  SuspendAutoloadingRAII autoLoadOff(this);
6554  // FIXME: There can be more than one TClass for a single decl.
6555  // for example vector<double> and vector<Double32_t>
6556  TClass* cl = (TClass*)gROOT->GetListOfClasses()->FindObject(name.c_str());
6557  if (cl && GetModTClasses().find(cl) == GetModTClasses().end()) {
6558  RefreshClassInfo(cl, canon, false);
6559  }
6560  // And here we should find the other 'aliases' (eg. vector<Double32_t>)
6561  // and update them too:
6562  // foreach(aliascl in gROOT->GetListOfClasses()->FindAliasesOf(name.c_str()))
6563  // RefreshClassInfo(cl, tdDef, true);
6564 }
6565 
6566 ////////////////////////////////////////////////////////////////////////////////
6567 /// No op: see TClingCallbacks
6568 
6569 void TCling::UpdateClassInfo(char* item, Long_t tagnum)
6570 {
6571 }
6572 
6573 //______________________________________________________________________________
6574 //FIXME: Factor out that function in TClass, because TClass does it already twice
6575 void TCling::UpdateClassInfoWork(const char* item)
6576 {
6577  // This is a no-op as part of the API.
6578  // TCling uses UpdateClassInfoWithDecl() instead.
6579 }
6580 
6581 ////////////////////////////////////////////////////////////////////////////////
6582 /// Update all canvases at end the terminal input command.
6583 
6584 void TCling::UpdateAllCanvases()
6585 {
6586  TIter next(gROOT->GetListOfCanvases());
6587  TVirtualPad* canvas;
6588  while ((canvas = (TVirtualPad*)next())) {
6589  canvas->Update();
6590  }
6591 }
6592 
6593 ////////////////////////////////////////////////////////////////////////////////
6594 
6595 void TCling::UpdateListsOnCommitted(const cling::Transaction &T) {
6596  std::set<TClass*> modifiedTClasses; // TClasses that require update after this transaction
6597 
6598  // If the transaction does not contain anything we can return earlier.
6599  if (!HandleNewTransaction(T)) return;
6600 
6601  bool isTUTransaction = false;
6602  if (!T.empty() && T.decls_begin() + 1 == T.decls_end() && !T.hasNestedTransactions()) {
6603  clang::Decl* FirstDecl = *(T.decls_begin()->m_DGR.begin());
6604  if (llvm::isa<clang::TranslationUnitDecl>(FirstDecl)) {
6605  // The is the first transaction, we have to expose to meta
6606  // what's already in the AST.
6607  isTUTransaction = true;
6608  }
6609  }
6610 
6611  std::set<const void*> TransactionDeclSet;
6612  if (!isTUTransaction && T.decls_end() - T.decls_begin()) {
6613  const clang::Decl* WrapperFD = T.getWrapperFD();
6614  for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
6615  I != E; ++I) {
6616  if (I->m_Call != cling::Transaction::kCCIHandleTopLevelDecl
6617  && I->m_Call != cling::Transaction::kCCIHandleTagDeclDefinition)
6618  continue;
6619 
6620  for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6621  DE = I->m_DGR.end(); DI != DE; ++DI) {
6622  if (*DI == WrapperFD)
6623  continue;
6624  TransactionDeclSet.insert(*DI);
6625  ((TCling*)gCling)->HandleNewDecl(*DI, false, modifiedTClasses);
6626  }
6627  }
6628  }
6629 
6630  // The above might trigger more decls to be deserialized.
6631  // Thus the iteration over the deserialized decls must be last.
6632  for (cling::Transaction::const_iterator I = T.deserialized_decls_begin(),
6633  E = T.deserialized_decls_end(); I != E; ++I) {
6634  for (DeclGroupRef::const_iterator DI = I->m_DGR.begin(),
6635  DE = I->m_DGR.end(); DI != DE; ++DI)
6636  if (TransactionDeclSet.find(*DI) == TransactionDeclSet.end()) {
6637  //FIXME: HandleNewDecl should take DeclGroupRef
6638  ((TCling*)gCling)->HandleNewDecl(*DI, /*isDeserialized*/true,
6639  modifiedTClasses);
6640  }
6641  }
6642 
6643 
6644  // When fully building the reflection info in TClass, a deserialization
6645  // could be triggered, which may result in request for building the
6646  // reflection info for the same TClass. This in turn will clear the caches
6647  // for the TClass in-flight and cause null ptr derefs.
6648  // FIXME: This is a quick fix, solving most of the issues. The actual
6649  // question is: Shouldn't TClass provide a lock mechanism on update or lock
6650  // itself until the update is done.
6651  //
6652  std::vector<TClass*> modifiedTClassesDiff(modifiedTClasses.size());
6653  std::vector<TClass*>::iterator it;
6654  it = set_difference(modifiedTClasses.begin(), modifiedTClasses.end(),
6655  ((TCling*)gCling)->GetModTClasses().begin(),
6656  ((TCling*)gCling)->GetModTClasses().end(),
6657  modifiedTClassesDiff.begin());
6658  modifiedTClassesDiff.resize(it - modifiedTClassesDiff.begin());
6659 
6660  // Lock the TClass for updates
6661  ((TCling*)gCling)->GetModTClasses().insert(modifiedTClassesDiff.begin(),
6662  modifiedTClassesDiff.end());
6663  for (std::vector<TClass*>::const_iterator I = modifiedTClassesDiff.begin(),
6664  E = modifiedTClassesDiff.end(); I != E; ++I) {
6665  // Make sure the TClass has not been deleted.
6666  if (!gROOT->GetListOfClasses()->FindObject(*I)) {
6667  continue;
6668  }
6669  // Could trigger deserialization of decls.
6670  cling::Interpreter::PushTransactionRAII RAII(GetInterpreterImpl());
6671  // Unlock the TClass for updates
6672  ((TCling*)gCling)->GetModTClasses().erase(*I);
6673 
6674  }
6675 }
6676 
6677 ///\brief Invalidate stored TCling state for declarations included in transaction `T'.
6678 ///
6679 void TCling::UpdateListsOnUnloaded(const cling::Transaction &T)
6680 {
6681  HandleNewTransaction(T);
6682 
6683  auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
6684  (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
6685  (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
6686  (TListOfEnums *)gROOT->GetListOfEnums());
6687 
6688  cling::Transaction::const_nested_iterator iNested = T.nested_begin();
6689  for (cling::Transaction::const_iterator I = T.decls_begin(), E = T.decls_end();
6690  I != E; ++I) {
6691  if (I->m_Call == cling::Transaction::kCCIHandleVTable)
6692  continue;
6693  if (I->m_Call == cling::Transaction::kCCINone) {
6694  UpdateListsOnUnloaded(*(*iNested));
6695  ++iNested;
6696  continue;
6697  }
6698 
6699  for (auto &D : I->m_DGR)
6700  InvalidateCachedDecl(Lists, D);
6701  }
6702 }
6703 
6704 ///\brief Invalidate cached TCling information for the given global declaration.
6705 ///
6706 void TCling::InvalidateGlobal(const Decl *D) {
6707  auto Lists = std::make_tuple((TListOfDataMembers *)gROOT->GetListOfGlobals(),
6708  (TListOfFunctions *)gROOT->GetListOfGlobalFunctions(),
6709  (TListOfFunctionTemplates *)gROOT->GetListOfFunctionTemplates(),
6710  (TListOfEnums *)gROOT->GetListOfEnums());
6711  InvalidateCachedDecl(Lists, D);
6712 }
6713 
6714 ///\brief Invalidate cached TCling information for the given declaration, and
6715 /// removed it from the appropriate object list.
6716 ///\param[in] Lists - std::tuple<TListOfDataMembers&, TListOfFunctions&,
6717 /// TListOfFunctionTemplates&, TListOfEnums&>
6718 /// of pointers to the (global/class) object lists.
6719 ///\param[in] D - Decl to discard.
6720 ///
6721 void TCling::InvalidateCachedDecl(const std::tuple<TListOfDataMembers*,
6722  TListOfFunctions*,
6723  TListOfFunctionTemplates*,
6724  TListOfEnums*> &Lists, const Decl *D) {
6725  if (D->isFromASTFile()) // `D' came from the PCH; ignore
6726  return;
6727 
6728  TListOfDataMembers &LODM = *(std::get<0>(Lists));
6729  TListOfFunctions &LOF = *(std::get<1>(Lists));
6730  TListOfFunctionTemplates &LOFT = *(std::get<2>(Lists));
6731  TListOfEnums &LOE = *(std::get<3>(Lists));
6732 
6733  if (isa<VarDecl>(D) || isa<FieldDecl>(D) || isa<EnumConstantDecl>(D)) {
6734  TObject *O = LODM.Find((TDictionary::DeclId_t)D);
6735  if (LODM.GetClass())
6736  RemoveAndInvalidateObject(LODM, static_cast<TDataMember *>(O));
6737  else
6738  RemoveAndInvalidateObject(LODM, static_cast<TGlobal *>(O));
6739  } else if (isa<FunctionDecl>(D)) {
6740  RemoveAndInvalidateObject(LOF, LOF.Find((TDictionary::DeclId_t)D));
6741  } else if (isa<FunctionTemplateDecl>(D)) {
6742  RemoveAndInvalidateObject(LOFT, LOFT.Get((TDictionary::DeclId_t)D));
6743  } else if (isa<EnumDecl>(D)) {
6744  TEnum *E = LOE.Find((TDictionary::DeclId_t)D);
6745  if (!E)
6746  return;
6747 
6748  // Try to invalidate enumerators (for unscoped enumerations).
6749  for (TIter I = E->GetConstants(); auto EC = (TEnumConstant *)I(); )
6750  RemoveAndInvalidateObject(LODM,
6751  (TEnumConstant *)LODM.FindObject(EC->GetName()));
6752 
6753  RemoveAndInvalidateObject(LOE, E);
6754  } else if (isa<RecordDecl>(D) || isa<NamespaceDecl>(D)) {
6755  if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->isCompleteDefinition())
6756  return;
6757 
6758  std::vector<TClass *> Classes;
6759  if (!TClass::GetClass(D->getCanonicalDecl(), Classes))
6760  return;
6761  for (auto &C : Classes) {
6762  auto Lists = std::make_tuple((TListOfDataMembers *)C->GetListOfDataMembers(),
6763  (TListOfFunctions *)C->GetListOfMethods(),
6764  (TListOfFunctionTemplates *)C->GetListOfFunctionTemplates(),
6765  (TListOfEnums *)C->GetListOfEnums());
6766  for (auto &I : cast<DeclContext>(D)->decls())
6767  InvalidateCachedDecl(Lists, I);
6768 
6769  // For NamespaceDecl (redeclarable), only invalidate this redecl.
6770  if (D->getKind() != Decl::Namespace
6771  || cast<NamespaceDecl>(D)->isOriginalNamespace())
6772  C->ResetClassInfo();
6773  }
6774  }
6775 }
6776 
6777 ////////////////////////////////////////////////////////////////////////////////
6778 // If an autoparse was done during a transaction and that it is rolled back,
6779 // we need to make sure the next request for the same autoparse will be
6780 // honored.
6781 void TCling::TransactionRollback(const cling::Transaction &T) {
6782  auto const &triter = fTransactionHeadersMap.find(&T);
6783  if (triter != fTransactionHeadersMap.end()) {
6784  std::size_t normNameHash = triter->second;
6785 
6786  fLookedUpClasses.erase(normNameHash);
6787 
6788  auto const &iter = fClassesHeadersMap.find(normNameHash);
6789  if (iter != fClassesHeadersMap.end()) {
6790  auto const &hNamesPtrs = iter->second;
6791  for (auto &hName : hNamesPtrs) {
6792  if (gDebug > 0) {
6793  Info("TransactionRollback",
6794  "Restoring ability to autoaparse: %s", hName);
6795  }
6796  fParsedPayloadsAddresses.erase(hName);
6797  }
6798  }
6799  }
6800 }
6801 
6802 ////////////////////////////////////////////////////////////////////////////////
6803 
6804 void TCling::LibraryLoaded(const void* dyLibHandle, const char* canonicalName) {
6805 // UpdateListOfLoadedSharedLibraries();
6806 }
6807 
6808 ////////////////////////////////////////////////////////////////////////////////
6809 
6810 void TCling::LibraryUnloaded(const void* dyLibHandle, const char* canonicalName) {
6811  fPrevLoadedDynLibInfo = 0;
6812  fSharedLibs = "";
6813 }
6814 
6815 ////////////////////////////////////////////////////////////////////////////////
6816 /// Return the list of shared libraries loaded into the process.
6817 
6818 const char* TCling::GetSharedLibs()
6819 {
6820  UpdateListOfLoadedSharedLibraries();
6821  return fSharedLibs;
6822 }
6823 
6824 static std::string GetClassSharedLibsForModule(const char *cls, cling::LookupHelper &LH)
6825 {
6826  if (!cls || !*cls)
6827  return {};
6828 
6829  using namespace clang;
6830  if (const Decl *D = LH.findScope(cls, cling::LookupHelper::NoDiagnostics,
6831  /*type*/ nullptr, /*instantiate*/ false)) {
6832  if (!D->isFromASTFile()) {
6833  if (gDebug > 5)
6834  Warning("GetClassSharedLibsForModule", "Decl found for %s is not part of a module", cls);
6835  return {};
6836  }
6837  class ModuleCollector : public ConstDeclVisitor<ModuleCollector> {
6838  llvm::DenseSet<Module *> &m_TopLevelModules;
6839 
6840  public:
6841  ModuleCollector(llvm::DenseSet<Module *> &TopLevelModules) : m_TopLevelModules(TopLevelModules) {}
6842  void Collect(const Decl *D) { Visit(D); }
6843 
6844  void VisitDecl(const Decl *D)
6845  {
6846  // FIXME: Such case is described ROOT-7765 where
6847  // ROOT_GENERATE_DICTIONARY does not contain the list of headers.
6848  // They are specified as #includes in the LinkDef file. This leads to
6849  // generation of incomplete modulemap files and this logic fails to
6850  // compute the corresponding module of D.
6851  // FIXME: If we want to support such a case, we should not rely on
6852  // the contents of the modulemap but mangle D and look it up in the
6853  // .so files.
6854  if (!D->hasOwningModule())
6855  return;
6856  if (Module *M = D->getOwningModule()->getTopLevelModule())
6857  m_TopLevelModules.insert(M);
6858  }
6859 
6860  void VisitTemplateArgument(const TemplateArgument &TA)
6861  {
6862  switch (TA.getKind()) {
6863  case TemplateArgument::Null:
6864  case TemplateArgument::Integral:
6865  case TemplateArgument::Pack:
6866  case TemplateArgument::NullPtr:
6867  case TemplateArgument::Expression:
6868  case TemplateArgument::Template:
6869  case TemplateArgument::TemplateExpansion: return;
6870  case TemplateArgument::Type:
6871  if (const TagType *TagTy = dyn_cast<TagType>(TA.getAsType()))
6872  return Visit(TagTy->getDecl());
6873  return;
6874  case TemplateArgument::Declaration: return Visit(TA.getAsDecl());
6875  }
6876  llvm_unreachable("Invalid TemplateArgument::Kind!");
6877  }
6878 
6879  void VisitClassTemplateSpecializationDecl(const ClassTemplateSpecializationDecl *CTSD)
6880  {
6881  if (CTSD->getOwningModule())
6882  VisitDecl(CTSD);
6883  else
6884  VisitDecl(CTSD->getSpecializedTemplate());
6885  const TemplateArgumentList &ArgList = CTSD->getTemplateArgs();
6886  for (const TemplateArgument *Arg = ArgList.data(), *ArgEnd = Arg + ArgList.size(); Arg != ArgEnd; ++Arg) {
6887  VisitTemplateArgument(*Arg);
6888  }
6889  }
6890  };
6891 
6892  llvm::DenseSet<Module *> TopLevelModules;
6893  ModuleCollector m(TopLevelModules);
6894  m.Collect(D);
6895  std::string result;
6896  for (auto M : TopLevelModules) {
6897  // ROOT-unaware modules (i.e. not processed by rootcling) do not have a
6898  // link declaration.
6899  if (!M->LinkLibraries.size())
6900  continue;
6901  // We have preloaded the Core module thus libCore.so
6902  if (M->Name == "Core")
6903  continue;
6904  assert(M->LinkLibraries.size() == 1);
6905  if (!result.empty())
6906  result += ' ';
6907  result += M->LinkLibraries[0].Library;
6908  }
6909  return result;
6910  }
6911  return {};
6912 }
6913 
6914 ////////////////////////////////////////////////////////////////////////////////
6915 /// Get the list of shared libraries containing the code for class cls.
6916 /// The first library in the list is the one containing the class, the
6917 /// others are the libraries the first one depends on. Returns 0
6918 /// in case the library is not found.
6919 
6920 const char* TCling::GetClassSharedLibs(const char* cls)
6921 {
6922  if (fCxxModulesEnabled) {
6923  llvm::StringRef className = cls;
6924  // If we get a class name containing lambda, we cannot parse it and we
6925  // can exit early.
6926  // FIXME: This works around a bug when we are instantiating a template
6927  // make_unique and the substitution fails. Seen in most of the dataframe
6928  // tests.
6929  if (className.contains("(lambda)"))
6930  return nullptr;
6931  // Limit the recursion which can be induced by GetClassSharedLibsForModule.
6932  SuspendAutoloadingRAII AutoloadingDisabled(this);
6933  cling::LookupHelper &LH = fInterpreter->getLookupHelper();
6934  std::string libs = GetClassSharedLibsForModule(cls, LH);
6935  if (!libs.empty()) {
6936  fAutoLoadLibStorage.push_back(libs);
6937  return fAutoLoadLibStorage.back().c_str();
6938  }
6939  }
6940 
6941  if (!cls || !*cls) {
6942  return 0;
6943  }
6944  // lookup class to find list of libraries
6945  if (fMapfile) {
6946  TEnvRec* libs_record = 0;
6947  libs_record = fMapfile->Lookup(cls);
6948  if (libs_record) {
6949  const char* libs = libs_record->GetValue();
6950  return (*libs) ? libs : 0;
6951  }
6952  else {
6953  // Try the old format...
6954  TString c = TString("Library.") + cls;
6955  // convert "::" to "@@", we used "@@" because TEnv
6956  // considers "::" a terminator
6957  c.ReplaceAll("::", "@@");
6958  // convert "-" to " ", since class names may have
6959  // blanks and TEnv considers a blank a terminator
6960  c.ReplaceAll(" ", "-");
6961  // Use TEnv::Lookup here as the rootmap file must start with Library.
6962  // and do not support using any stars (so we do not need to waste time
6963  // with the search made by TEnv::GetValue).
6964  TEnvRec* libs_record = 0;
6965  libs_record = fMapfile->Lookup(c);
6966  if (libs_record) {
6967  const char* libs = libs_record->GetValue();
6968  return (*libs) ? libs : 0;
6969  }
6970  }
6971  }
6972  return 0;
6973 }
6974 
6975 /// This interface returns a list of dependent libraries in the form:
6976 /// lib libA.so libB.so libC.so. The first library is the library we are
6977 /// searching dependencies for.
6978 /// Note: In order to speed up the search, we display the dependencies of the
6979 /// libraries which are not yet loaded. For instance, if libB.so was already
6980 /// loaded the list would contain: lib libA.so libC.so.
6981 static std::string GetSharedLibImmediateDepsSlow(std::string lib,
6982  cling::Interpreter *interp,
6983  bool skipLoadedLibs = true)
6984 {
6985  TString LibFullPath(lib);
6986  if (!llvm::sys::path::is_absolute(lib)) {
6987  if (!gSystem->FindDynamicLibrary(LibFullPath, /*quiet=*/true)) {
6988  Error("TCling__GetSharedLibImmediateDepsSlow", "Cannot find library '%s'", lib.c_str());
6989  return "";
6990  }
6991  } else {
6992  lib = llvm::sys::path::filename(lib);
6993  }
6994 
6995  auto ObjF = llvm::object::ObjectFile::createObjectFile(LibFullPath.Data());
6996  if (!ObjF) {
6997  Warning("TCling__GetSharedLibImmediateDepsSlow", "Failed to read object file %s", lib.c_str());
6998  return "";
6999  }
7000 
7001  llvm::object::ObjectFile *BinObjFile = ObjF.get().getBinary();
7002 
7003  std::set<string> DedupSet;
7004  std::string Result = lib + ' ';
7005  for (const auto &S : BinObjFile->symbols()) {
7006  uint32_t Flags = S.getFlags();
7007  if (Flags & llvm::object::SymbolRef::SF_Undefined) {
7008  llvm::Expected<StringRef> SymNameErr = S.getName();
7009  if (!SymNameErr) {
7010  Warning("GetSharedLibDepsForModule", "Failed to read symbol");
7011  continue;
7012  }
7013  llvm::StringRef SymName = SymNameErr.get();
7014  if (SymName.empty())
7015  continue;
7016 
7017  if (BinObjFile->isELF()) {
7018  // Skip the symbols which are part of the C/C++ runtime and have a
7019  // fixed library version. See binutils ld VERSION. Those reside in
7020  // 'system' libraries, which we avoid in ResolveSymbol.
7021  if (SymName.contains("@@GLIBCXX") || SymName.contains("@@CXXABI") ||
7022  SymName.contains("@@GLIBC") || SymName.contains("@@GCC"))
7023  continue;
7024 
7025  // Those are 'weak undefined' symbols produced by gcc. We can
7026  // ignore them.
7027  // FIXME: It is unclear whether we can ignore all weak undefined
7028  // symbols:
7029  // http://lists.llvm.org/pipermail/llvm-dev/2017-October/118177.html
7030  if (SymName == "_Jv_RegisterClasses" ||
7031  SymName == "_ITM_deregisterTMCloneTable" ||
7032  SymName == "_ITM_registerTMCloneTable")
7033  continue;
7034  }
7035 
7036  // If we can find the address of the symbol, we have loaded it. Skip.
7037  if (skipLoadedLibs && llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(SymName))
7038  continue;
7039 
7040  std::string found = ResolveSymbol(SymName, interp, /*searchSystem*/false);
7041  // The expected output is just filename without the full path, which
7042  // is not very accurate, because our Dyld implementation might find
7043  // a match in location a/b/c.so and if we return just c.so ROOT might
7044  // resolve it to y/z/c.so and there we might not be ABI compatible.
7045  // FIXME: Teach the users of GetSharedLibDeps to work with full paths.
7046  if (!found.empty()) {
7047  std::string cand = llvm::sys::path::filename(found).str();
7048  if (!DedupSet.insert(cand).second)
7049  continue;
7050 
7051  Result += cand + ' ';
7052  }
7053  }
7054  }
7055 
7056  return Result;
7057 }
7058 
7059 
7060 ////////////////////////////////////////////////////////////////////////////////
7061 /// Get the list a libraries on which the specified lib depends. The
7062 /// returned string contains as first element the lib itself.
7063 /// Returns 0 in case the lib does not exist or does not have
7064 /// any dependencies. If useDyld is true, we iterate through all available
7065 /// libraries and try to construct the dependency chain by resolving each
7066 /// symbol.
7067 
7068 const char* TCling::GetSharedLibDeps(const char* lib, bool useDyld/* = false*/)
7069 {
7070  if (useDyld) {
7071  std::string libs = GetSharedLibImmediateDepsSlow(lib, GetInterpreterImpl());
7072  if (!libs.empty()) {
7073  fAutoLoadLibStorage.push_back(libs);
7074  return fAutoLoadLibStorage.back().c_str();
7075  }
7076  }
7077 
7078  if (!fMapfile || !lib || !lib[0]) {
7079  return 0;
7080  }
7081  TString libname(lib);
7082  Ssiz_t idx = libname.Last('.');
7083  if (idx != kNPOS) {
7084  libname.Remove(idx);
7085  }
7086  TEnvRec* rec;
7087  TIter next(fMapfile->GetTable());
7088  size_t len = libname.Length();
7089  while ((rec = (TEnvRec*) next())) {
7090  const char* libs = rec->GetValue();
7091  if (!strncmp(libs, libname.Data(), len) && strlen(libs) >= len
7092  && (!libs[len] || libs[len] == ' ' || libs[len] == '.')) {
7093  return libs;
7094  }
7095  }
7096  return 0;
7097 }
7098 
7099 ////////////////////////////////////////////////////////////////////////////////
7100 /// If error messages are disabled, the interpreter should suppress its
7101 /// failures and warning messages from stdout.
7102 
7103 Bool_t TCling::IsErrorMessagesEnabled() const
7104 {
7105 #if defined(R__MUST_REVISIT)
7106 #if R__MUST_REVISIT(6,2)
7107  Warning("IsErrorMessagesEnabled", "Interface not available yet.");
7108 #endif
7109 #endif
7110  return kTRUE;
7111 }
7112 
7113 ////////////////////////////////////////////////////////////////////////////////
7114 /// If error messages are disabled, the interpreter should suppress its
7115 /// failures and warning messages from stdout. Return the previous state.
7116 
7117 Bool_t TCling::SetErrorMessages(Bool_t enable)
7118 {
7119 #if defined(R__MUST_REVISIT)
7120 #if R__MUST_REVISIT(6,2)
7121  Warning("SetErrorMessages", "Interface not available yet.");
7122 #endif
7123 #endif
7124  return TCling::IsErrorMessagesEnabled();
7125 }
7126 
7127 ////////////////////////////////////////////////////////////////////////////////
7128 /// Refresh the list of include paths known to the interpreter and return it
7129 /// with -I prepended.
7130 
7131 const char* TCling::GetIncludePath()
7132 {
7133  R__LOCKGUARD(gInterpreterMutex);
7134 
7135  fIncludePath = "";
7136 
7137  llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7138  //false - no system header, true - with flags.
7139  fInterpreter->GetIncludePaths(includePaths, false, true);
7140  if (const size_t nPaths = includePaths.size()) {
7141  assert(!(nPaths & 1) && "GetIncludePath, number of paths and options is not equal");
7142 
7143  for (size_t i = 0; i < nPaths; i += 2) {
7144  if (i)
7145  fIncludePath.Append(' ');
7146  fIncludePath.Append(includePaths[i].c_str());
7147 
7148  if (includePaths[i] != "-I")
7149  fIncludePath.Append(' ');
7150  fIncludePath.Append('"');
7151  fIncludePath.Append(includePaths[i + 1], includePaths[i + 1].length());
7152  fIncludePath.Append('"');
7153  }
7154  }
7155 
7156  return fIncludePath;
7157 }
7158 
7159 ////////////////////////////////////////////////////////////////////////////////
7160 /// Return the directory containing CINT's stl cintdlls.
7161 
7162 const char* TCling::GetSTLIncludePath() const
7163 {
7164  return "";
7165 }
7166 
7167 //______________________________________________________________________________
7168 // M I S C
7169 //______________________________________________________________________________
7170 
7171 int TCling::DisplayClass(FILE* /*fout*/, const char* /*name*/, int /*base*/, int /*start*/) const
7172 {
7173  // Interface to cling function
7174  return 0;
7175 }
7176 
7177 ////////////////////////////////////////////////////////////////////////////////
7178 /// Interface to cling function
7179 
7180 int TCling::DisplayIncludePath(FILE *fout) const
7181 {
7182  assert(fout != 0 && "DisplayIncludePath, 'fout' parameter is null");
7183 
7184  llvm::SmallVector<std::string, 10> includePaths;//Why 10? Hell if I know.
7185  //false - no system header, true - with flags.
7186  fInterpreter->GetIncludePaths(includePaths, false, true);
7187  if (const size_t nPaths = includePaths.size()) {
7188  assert(!(nPaths & 1) && "DisplayIncludePath, number of paths and options is not equal");
7189 
7190  std::string allIncludes("include path:");
7191  for (size_t i = 0; i < nPaths; i += 2) {
7192  allIncludes += ' ';
7193  allIncludes += includePaths[i];
7194 
7195  if (includePaths[i] != "-I")
7196  allIncludes += ' ';
7197  allIncludes += includePaths[i + 1];
7198  }
7199 
7200  fprintf(fout, "%s\n", allIncludes.c_str());
7201  }
7202 
7203  return 0;
7204 }
7205 
7206 ////////////////////////////////////////////////////////////////////////////////
7207 /// Interface to cling function
7208 
7209 void* TCling::FindSym(const char* entry) const
7210 {
7211  return fInterpreter->getAddressOfGlobal(entry);
7212 }
7213 
7214 ////////////////////////////////////////////////////////////////////////////////
7215 /// Let the interpreter issue a generic error, and set its error state.
7216 
7217 void TCling::GenericError(const char* error) const
7218 {
7219 #if defined(R__MUST_REVISIT)
7220 #if R__MUST_REVISIT(6,2)
7221  Warning("GenericError","Interface not available yet.");
7222 #endif
7223 #endif
7224 }
7225 
7226 ////////////////////////////////////////////////////////////////////////////////
7227 /// This routines used to return the address of the internal wrapper
7228 /// function (of the interpreter) that was used to call *all* the
7229 /// interpreted functions that were bytecode compiled (no longer
7230 /// interpreted line by line). In Cling, there is no such
7231 /// wrapper function.
7232 /// In practice this routines was use to decipher whether the
7233 /// pointer returns by InterfaceMethod could be used to uniquely
7234 /// represent the function. In Cling if the function is in a
7235 /// useable state (its compiled version is available), this is
7236 /// always the case.
7237 /// See TClass::GetMethod.
7238 
7239 Long_t TCling::GetExecByteCode() const
7240 {
7241  return 0;
7242 }
7243 
7244 ////////////////////////////////////////////////////////////////////////////////
7245 /// Interface to cling function
7246 
7247 int TCling::GetSecurityError() const
7248 {
7249 #if defined(R__MUST_REVISIT)
7250 #if R__MUST_REVISIT(6,2)
7251  Warning("GetSecurityError", "Interface not available yet.");
7252 #endif
7253 #endif
7254  return 0;
7255 }
7256 
7257 ////////////////////////////////////////////////////////////////////////////////
7258 /// Load a source file or library called path into the interpreter.
7259 
7260 int TCling::LoadFile(const char* path) const
7261 {
7262  cling::Interpreter::CompilationResult compRes;
7263  HandleInterpreterException(GetMetaProcessorImpl(), TString::Format(".L %s", path), compRes, /*cling::Value*/0);
7264  return compRes == cling::Interpreter::kFailure;
7265 }
7266 
7267 ////////////////////////////////////////////////////////////////////////////////
7268 /// Load the declarations from text into the interpreter.
7269 /// Note that this cannot be (top level) statements; text must contain
7270 /// top level declarations.
7271 /// Returns true on success, false on failure.
7272 
7273 Bool_t TCling::LoadText(const char* text) const
7274 {
7275  return (fInterpreter->declare(text) == cling::Interpreter::kSuccess);
7276 }
7277 
7278 ////////////////////////////////////////////////////////////////////////////////
7279 /// Interface to cling function
7280 
7281 const char* TCling::MapCppName(const char* name) const
7282 {
7283  TTHREAD_TLS_DECL(std::string,buffer);
7284  ROOT::TMetaUtils::GetCppName(buffer,name);
7285  return buffer.c_str();
7286 }
7287 
7288 ////////////////////////////////////////////////////////////////////////////////
7289 /// [Place holder for Mutex Lock]
7290 /// Provide the interpreter with a way to
7291 /// acquire a lock used to protect critical section
7292 /// of its code (non-thread safe parts).
7293 
7294 void TCling::SetAlloclockfunc(void (* /* p */ )()) const
7295 {
7296  // nothing to do for now.
7297 }
7298 
7299 ////////////////////////////////////////////////////////////////////////////////
7300 /// [Place holder for Mutex Unlock] Provide the interpreter with a way to
7301 /// release a lock used to protect critical section
7302 /// of its code (non-thread safe parts).
7303 
7304 void TCling::SetAllocunlockfunc(void (* /* p */ )()) const
7305 {
7306  // nothing to do for now.
7307 }
7308 
7309 ////////////////////////////////////////////////////////////////////////////////
7310 /// Returns if class autoloading is currently enabled.
7311 
7312 bool TCling::IsClassAutoloadingEnabled() const
7313 {
7314  if (IsFromRootCling())
7315  return false;
7316  if (!fClingCallbacks)
7317  return false;
7318  return fClingCallbacks->IsAutoloadingEnabled();
7319 }
7320 
7321 ////////////////////////////////////////////////////////////////////////////////
7322 /// Enable/Disable the Autoloading of libraries.
7323 /// Returns the old value, i.e whether it was enabled or not.
7324 
7325 int TCling::SetClassAutoloading(int autoload) const
7326 {
7327  // If no state change is required, exit early.
7328  // FIXME: In future we probably want to complain if we made a request which
7329  // was with the same state as before in order to catch programming errors.
7330  if ((bool) autoload == IsClassAutoloadingEnabled())
7331  return autoload;
7332 
7333  assert(fClingCallbacks && "We must have callbacks!");
7334  bool oldVal = fClingCallbacks->IsAutoloadingEnabled();
7335  fClingCallbacks->SetAutoloadingEnabled(autoload);
7336  return oldVal;
7337 }
7338 
7339 ////////////////////////////////////////////////////////////////////////////////
7340 /// Enable/Disable the Autoparsing of headers.
7341 /// Returns the old value, i.e whether it was enabled or not.
7342 
7343 int TCling::SetClassAutoparsing(int autoparse)
7344 {
7345  bool oldVal = fHeaderParsingOnDemand;
7346  fHeaderParsingOnDemand = autoparse;
7347  return oldVal;
7348 }
7349 
7350 ////////////////////////////////////////////////////////////////////////////////
7351 /// Suspend the Autoparsing of headers.
7352 /// Returns the old value, i.e whether it was suspended or not.
7353 
7354 Bool_t TCling::SetSuspendAutoParsing(Bool_t value) {
7355  Bool_t old = fIsAutoParsingSuspended;
7356  fIsAutoParsingSuspended = value;
7357  if (fClingCallbacks) fClingCallbacks->SetAutoParsingSuspended(value);
7358  return old;
7359 }
7360 
7361 ////////////////////////////////////////////////////////////////////////////////
7362 /// Set a callback to receive error messages.
7363 
7364 void TCling::SetErrmsgcallback(void* p) const
7365 {
7366 #if defined(R__MUST_REVISIT)
7367 #if R__MUST_REVISIT(6,2)
7368  Warning("SetErrmsgcallback", "Interface not available yet.");
7369 #endif
7370 #endif
7371 }
7372 
7373 
7374 ////////////////////////////////////////////////////////////////////////////////
7375 /// Create / close a scope for temporaries. No-op for cling; use
7376 /// cling::Value instead.
7377 
7378 void TCling::SetTempLevel(int val) const
7379 {
7380 }
7381 
7382 ////////////////////////////////////////////////////////////////////////////////
7383 
7384 int TCling::UnloadFile(const char* path) const
7385 {
7386  cling::DynamicLibraryManager* DLM = fInterpreter->getDynamicLibraryManager();
7387  std::string canonical = DLM->lookupLibrary(path);
7388  if (canonical.empty()) {
7389  canonical = path;
7390  }
7391  // Unload a shared library or a source file.
7392  cling::Interpreter::CompilationResult compRes;
7393  HandleInterpreterException(GetMetaProcessorImpl(), Form(".U %s", canonical.c_str()), compRes, /*cling::Value*/0);
7394  return compRes == cling::Interpreter::kFailure;
7395 }
7396 
7397 std::unique_ptr<TInterpreterValue> TCling::MakeInterpreterValue() const {
7398  return std::unique_ptr<TInterpreterValue>(new TClingValue);
7399 }
7400 
7401 ////////////////////////////////////////////////////////////////////////////////
7402 /// The call to Cling's tab complition.
7403 
7404 void TCling::CodeComplete(const std::string& line, size_t& cursor,
7405  std::vector<std::string>& completions)
7406 {
7407  fInterpreter->codeComplete(line, cursor, completions);
7408 }
7409 
7410 ////////////////////////////////////////////////////////////////////////////////
7411 /// Get the interpreter value corresponding to the statement.
7412 int TCling::Evaluate(const char* code, TInterpreterValue& value)
7413 {
7414  auto V = reinterpret_cast<cling::Value*>(value.GetValAddr());
7415  auto compRes = fInterpreter->evaluate(code, *V);
7416  return compRes!=cling::Interpreter::kSuccess ? 0 : 1 ;
7417 }
7418 
7419 ////////////////////////////////////////////////////////////////////////////////
7420 
7421 void TCling::RegisterTemporary(const TInterpreterValue& value)
7422 {
7423  using namespace cling;
7424  const Value* V = reinterpret_cast<const Value*>(value.GetValAddr());
7425  RegisterTemporary(*V);
7426 }
7427 
7428 ////////////////////////////////////////////////////////////////////////////////
7429 /// Register value as a temporary, extending its lifetime to that of the
7430 /// interpreter. This is needed for TCling's compatibility interfaces
7431 /// returning long - the address of the temporary objects.
7432 /// As such, "simple" types don't need to be stored; they are returned by
7433 /// value; only pointers / references / objects need to be stored.
7434 
7435 void TCling::RegisterTemporary(const cling::Value& value)
7436 {
7437  if (value.isValid() && value.needsManagedAllocation()) {
7438  R__LOCKGUARD(gInterpreterMutex);
7439  fTemporaries->push_back(value);
7440  }
7441 }
7442 
7443 ////////////////////////////////////////////////////////////////////////////////
7444 /// If the interpreter encounters Name, check whether that is an object ROOT
7445 /// could retrieve. To not re-read objects from disk, cache the name/object
7446 /// pair for a given LookupCtx.
7447 
7448 TObject* TCling::GetObjectAddress(const char *Name, void *&LookupCtx)
7449 {
7450  // The call to FindSpecialObject might induces any kind of use
7451  // of the interpreter ... (library loading, function calling, etc.)
7452  // ... and we _know_ we are in the middle of parsing, so let's make
7453  // sure to save the state and then restore it.
7454 
7455  if (gDirectory) {
7456  auto iSpecObjMap = fSpecialObjectMaps.find(gDirectory);
7457  if (iSpecObjMap != fSpecialObjectMaps.end()) {
7458  auto iSpecObj = iSpecObjMap->second.find(Name);
7459  if (iSpecObj != iSpecObjMap->second.end()) {
7460  LookupCtx = gDirectory;
7461  return iSpecObj->second;
7462  }
7463  }
7464  }
7465 
7466  // Save state of the PP
7467  Sema &SemaR = fInterpreter->getSema();
7468  ASTContext& C = SemaR.getASTContext();
7469  Preprocessor &PP = SemaR.getPreprocessor();
7470  Parser& P = const_cast<Parser&>(fInterpreter->getParser());
7471  Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
7472  Parser::ParserCurTokRestoreRAII savedCurToken(P);
7473  // After we have saved the token reset the current one to something which
7474  // is safe (semi colon usually means empty decl)
7475  Token& Tok = const_cast<Token&>(P.getCurToken());
7476  Tok.setKind(tok::semi);
7477 
7478  // We can't PushDeclContext, because we go up and the routine that pops
7479  // the DeclContext assumes that we drill down always.
7480  // We have to be on the global context. At that point we are in a
7481  // wrapper function so the parent context must be the global.
7482  Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(),
7483  SemaR.TUScope);
7484 
7485  TObject* specObj = gROOT->FindSpecialObject(Name, LookupCtx);
7486  if (specObj) {
7487  if (!LookupCtx) {
7488  Error("GetObjectAddress", "Got a special object without LookupCtx!");
7489  } else {
7490  fSpecialObjectMaps[LookupCtx][Name] = specObj;
7491  }
7492  }
7493  return specObj;
7494 }
7495 
7496 ////////////////////////////////////////////////////////////////////////////////
7497 /// Inject function as a friend into klass.
7498 /// With function being f in void f() {new N::PrivKlass(); } this enables
7499 /// I/O of non-public classes.
7500 
7501 void TCling::AddFriendToClass(clang::FunctionDecl* function,
7502  clang::CXXRecordDecl* klass) const
7503 {
7504  using namespace clang;
7505  ASTContext& Ctx = klass->getASTContext();
7506  FriendDecl::FriendUnion friendUnion(function);
7507  // one dummy object for the source location
7508  SourceLocation sl;
7509  FriendDecl* friendDecl = FriendDecl::Create(Ctx, klass, sl, friendUnion, sl);
7510  klass->pushFriendDecl(friendDecl);
7511 }
7512 
7513 //______________________________________________________________________________
7514 //
7515 // DeclId getter.
7516 //
7517 
7518 ////////////////////////////////////////////////////////////////////////////////
7519 /// Return a unique identifier of the declaration represented by the
7520 /// CallFunc
7521 
7522 TInterpreter::DeclId_t TCling::GetDeclId(CallFunc_t* func) const
7523 {
7524  if (func) return ((TClingCallFunc*)func)->GetDecl()->getCanonicalDecl();
7525  return 0;
7526 }
7527 
7528 ////////////////////////////////////////////////////////////////////////////////
7529 /// Return a (almost) unique identifier of the declaration represented by the
7530 /// ClassInfo. In ROOT, this identifier can point to more than one TClass
7531 /// when the underlying class is a template instance involving one of the
7532 /// opaque typedef.
7533 
7534 TInterpreter::DeclId_t TCling::GetDeclId(ClassInfo_t* cinfo) const
7535 {
7536  if (cinfo) return ((TClingClassInfo*)cinfo)->GetDeclId();
7537  return 0;
7538 }
7539 
7540 ////////////////////////////////////////////////////////////////////////////////
7541 /// Return a unique identifier of the declaration represented by the
7542 /// MethodInfo
7543 
7544 TInterpreter::DeclId_t TCling::GetDeclId(DataMemberInfo_t* data) const
7545 {
7546  if (data) return ((TClingDataMemberInfo*)data)->GetDeclId();
7547  return 0;
7548 }
7549 
7550 ////////////////////////////////////////////////////////////////////////////////
7551 /// Return a unique identifier of the declaration represented by the
7552 /// MethodInfo
7553 
7554 TInterpreter::DeclId_t TCling::GetDeclId(MethodInfo_t* method) const
7555 {
7556  if (method) return ((TClingMethodInfo*)method)->GetDeclId();
7557  return 0;
7558 }
7559 
7560 ////////////////////////////////////////////////////////////////////////////////
7561 /// Return a unique identifier of the declaration represented by the
7562 /// TypedefInfo
7563 
7564 TInterpreter::DeclId_t TCling::GetDeclId(TypedefInfo_t* tinfo) const
7565 {
7566  if (tinfo) return ((TClingTypedefInfo*)tinfo)->GetDecl()->getCanonicalDecl();
7567  return 0;
7568 }
7569 
7570 //______________________________________________________________________________
7571 //
7572 // CallFunc interface
7573 //
7574 
7575 ////////////////////////////////////////////////////////////////////////////////
7576 
7577 void TCling::CallFunc_Delete(CallFunc_t* func) const
7578 {
7579  delete (TClingCallFunc*) func;
7580 }
7581 
7582 ////////////////////////////////////////////////////////////////////////////////
7583 
7584 void TCling::CallFunc_Exec(CallFunc_t* func, void* address) const
7585 {
7586  TClingCallFunc* f = (TClingCallFunc*) func;
7587  f->Exec(address);
7588 }
7589 
7590 ////////////////////////////////////////////////////////////////////////////////
7591 
7592 void TCling::CallFunc_Exec(CallFunc_t* func, void* address, TInterpreterValue& val) const
7593 {
7594  TClingCallFunc* f = (TClingCallFunc*) func;
7595  f->Exec(address, &val);
7596 }
7597 
7598 ////////////////////////////////////////////////////////////////////////////////
7599 
7600 void TCling::CallFunc_ExecWithReturn(CallFunc_t* func, void* address, void* ret) const
7601 {
7602  TClingCallFunc* f = (TClingCallFunc*) func;
7603  f->ExecWithReturn(address, ret);
7604 }
7605 
7606 ////////////////////////////////////////////////////////////////////////////////
7607 
7608 void TCling::CallFunc_ExecWithArgsAndReturn(CallFunc_t* func, void* address,
7609  const void* args[] /*=0*/,
7610  int nargs /*=0*/,
7611  void* ret/*=0*/) const
7612 {
7613  TClingCallFunc* f = (TClingCallFunc*) func;
7614  f->ExecWithArgsAndReturn(address, args, nargs, ret);
7615 }
7616 
7617 ////////////////////////////////////////////////////////////////////////////////
7618 
7619 Long_t TCling::CallFunc_ExecInt(CallFunc_t* func, void* address) const
7620 {
7621  TClingCallFunc* f = (TClingCallFunc*) func;
7622  return f->ExecInt(address);
7623 }
7624 
7625 ////////////////////////////////////////////////////////////////////////////////
7626 
7627 Long64_t TCling::CallFunc_ExecInt64(CallFunc_t* func, void* address) const
7628 {
7629  TClingCallFunc* f = (TClingCallFunc*) func;
7630  return f->ExecInt64(address);
7631 }
7632 
7633 ////////////////////////////////////////////////////////////////////////////////
7634 
7635 Double_t TCling::CallFunc_ExecDouble(CallFunc_t* func, void* address) const
7636 {
7637  TClingCallFunc* f = (TClingCallFunc*) func;
7638  return f->ExecDouble(address);
7639 }
7640 
7641 ////////////////////////////////////////////////////////////////////////////////
7642 
7643 CallFunc_t* TCling::CallFunc_Factory() const
7644 {
7645  R__LOCKGUARD(gInterpreterMutex);
7646  return (CallFunc_t*) new TClingCallFunc(GetInterpreterImpl(), *fNormalizedCtxt);
7647 }
7648 
7649 ////////////////////////////////////////////////////////////////////////////////
7650 
7651 CallFunc_t* TCling::CallFunc_FactoryCopy(CallFunc_t* func) const
7652 {
7653  return (CallFunc_t*) new TClingCallFunc(*(TClingCallFunc*)func);
7654 }
7655 
7656 ////////////////////////////////////////////////////////////////////////////////
7657 
7658 MethodInfo_t* TCling::CallFunc_FactoryMethod(CallFunc_t* func) const
7659 {
7660  TClingCallFunc* f = (TClingCallFunc*) func;
7661  return (MethodInfo_t*) f->FactoryMethod();
7662 }
7663 
7664 ////////////////////////////////////////////////////////////////////////////////
7665 
7666 void TCling::CallFunc_IgnoreExtraArgs(CallFunc_t* func, bool ignore) const
7667 {
7668  TClingCallFunc* f = (TClingCallFunc*) func;
7669  f->IgnoreExtraArgs(ignore);
7670 }
7671 
7672 ////////////////////////////////////////////////////////////////////////////////
7673 
7674 void TCling::CallFunc_Init(CallFunc_t* func) const
7675 {
7676  R__LOCKGUARD(gInterpreterMutex);
7677  TClingCallFunc* f = (TClingCallFunc*) func;
7678  f->Init();
7679 }
7680 
7681 ////////////////////////////////////////////////////////////////////////////////
7682 
7683 bool TCling::CallFunc_IsValid(CallFunc_t* func) const
7684 {
7685  TClingCallFunc* f = (TClingCallFunc*) func;
7686  return f->IsValid();
7687 }
7688 
7689 ////////////////////////////////////////////////////////////////////////////////
7690 
7691 TInterpreter::CallFuncIFacePtr_t
7692 TCling::CallFunc_IFacePtr(CallFunc_t * func) const
7693 {
7694  TClingCallFunc* f = (TClingCallFunc*) func;
7695  return f->IFacePtr();
7696 }
7697 
7698 ////////////////////////////////////////////////////////////////////////////////
7699 
7700 void TCling::CallFunc_ResetArg(CallFunc_t* func) const
7701 {
7702  TClingCallFunc* f = (TClingCallFunc*) func;
7703  f->ResetArg();
7704 }
7705 
7706 ////////////////////////////////////////////////////////////////////////////////
7707 
7708 void TCling::CallFunc_SetArg(CallFunc_t* func, Long_t param) const
7709 {
7710  TClingCallFunc* f = (TClingCallFunc*) func;
7711  f->SetArg(param);
7712 }
7713 
7714 ////////////////////////////////////////////////////////////////////////////////
7715 
7716 void TCling::CallFunc_SetArg(CallFunc_t* func, ULong_t param) const
7717 {
7718  TClingCallFunc* f = (TClingCallFunc*) func;
7719  f->SetArg(param);
7720 }
7721 
7722 ////////////////////////////////////////////////////////////////////////////////
7723 
7724 void TCling::CallFunc_SetArg(CallFunc_t* func, Float_t param) const
7725 {
7726  TClingCallFunc* f = (TClingCallFunc*) func;
7727  f->SetArg(param);
7728 }
7729 
7730 ////////////////////////////////////////////////////////////////////////////////
7731 
7732 void TCling::CallFunc_SetArg(CallFunc_t* func, Double_t param) const
7733 {
7734  TClingCallFunc* f = (TClingCallFunc*) func;
7735  f->SetArg(param);
7736 }
7737 
7738 ////////////////////////////////////////////////////////////////////////////////
7739 
7740 void TCling::CallFunc_SetArg(CallFunc_t* func, Long64_t param) const
7741 {
7742  TClingCallFunc* f = (TClingCallFunc*) func;
7743  f->SetArg(param);
7744 }
7745 
7746 ////////////////////////////////////////////////////////////////////////////////
7747 
7748 void TCling::CallFunc_SetArg(CallFunc_t* func, ULong64_t param) const
7749 {
7750  TClingCallFunc* f = (TClingCallFunc*) func;
7751  f->SetArg(param);
7752 }
7753 
7754 ////////////////////////////////////////////////////////////////////////////////
7755 
7756 void TCling::CallFunc_SetArgArray(CallFunc_t* func, Long_t* paramArr, Int_t nparam) const
7757 {
7758  TClingCallFunc* f = (TClingCallFunc*) func;
7759  f->SetArgArray(paramArr, nparam);
7760 }
7761 
7762 ////////////////////////////////////////////////////////////////////////////////
7763 
7764 void TCling::CallFunc_SetArgs(CallFunc_t* func, const char* param) const
7765 {
7766  TClingCallFunc* f = (TClingCallFunc*) func;
7767  f->SetArgs(param);
7768 }
7769 
7770 ////////////////////////////////////////////////////////////////////////////////
7771 
7772 void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, Long_t* offset) const
7773 {
7774  TClingCallFunc* f = (TClingCallFunc*) func;
7775  TClingClassInfo* ci = (TClingClassInfo*) info;
7776  f->SetFunc(ci, method, params, offset);
7777 }
7778 
7779 ////////////////////////////////////////////////////////////////////////////////
7780 
7781 void TCling::CallFunc_SetFunc(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* params, bool objectIsConst, Long_t* offset) const
7782 {
7783  TClingCallFunc* f = (TClingCallFunc*) func;
7784  TClingClassInfo* ci = (TClingClassInfo*) info;
7785  f->SetFunc(ci, method, params, objectIsConst, offset);
7786 }
7787 ////////////////////////////////////////////////////////////////////////////////
7788 
7789 void TCling::CallFunc_SetFunc(CallFunc_t* func, MethodInfo_t* info) const
7790 {
7791  TClingCallFunc* f = (TClingCallFunc*) func;
7792  TClingMethodInfo* minfo = (TClingMethodInfo*) info;
7793  f->SetFunc(minfo);
7794 }
7795 
7796 ////////////////////////////////////////////////////////////////////////////////
7797 /// Interface to cling function
7798 
7799 void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, Long_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
7800 {
7801  TClingCallFunc* f = (TClingCallFunc*) func;
7802  TClingClassInfo* ci = (TClingClassInfo*) info;
7803  f->SetFuncProto(ci, method, proto, offset, mode);
7804 }
7805 
7806 ////////////////////////////////////////////////////////////////////////////////
7807 /// Interface to cling function
7808 
7809 void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const char* proto, bool objectIsConst, Long_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
7810 {
7811  TClingCallFunc* f = (TClingCallFunc*) func;
7812  TClingClassInfo* ci = (TClingClassInfo*) info;
7813  f->SetFuncProto(ci, method, proto, objectIsConst, offset, mode);
7814 }
7815 
7816 ////////////////////////////////////////////////////////////////////////////////
7817 /// Interface to cling function
7818 
7819 void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const std::vector<TypeInfo_t*> &proto, Long_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
7820 {
7821  TClingCallFunc* f = (TClingCallFunc*) func;
7822  TClingClassInfo* ci = (TClingClassInfo*) info;
7823  llvm::SmallVector<clang::QualType, 4> funcProto;
7824  for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
7825  iter != end; ++iter) {
7826  funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
7827  }
7828  f->SetFuncProto(ci, method, funcProto, offset, mode);
7829 }
7830 
7831 ////////////////////////////////////////////////////////////////////////////////
7832 /// Interface to cling function
7833 
7834 void TCling::CallFunc_SetFuncProto(CallFunc_t* func, ClassInfo_t* info, const char* method, const std::vector<TypeInfo_t*> &proto, bool objectIsConst, Long_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
7835 {
7836  TClingCallFunc* f = (TClingCallFunc*) func;
7837  TClingClassInfo* ci = (TClingClassInfo*) info;
7838  llvm::SmallVector<clang::QualType, 4> funcProto;
7839  for (std::vector<TypeInfo_t*>::const_iterator iter = proto.begin(), end = proto.end();
7840  iter != end; ++iter) {
7841  funcProto.push_back( ((TClingTypeInfo*)(*iter))->GetQualType() );
7842  }
7843  f->SetFuncProto(ci, method, funcProto, objectIsConst, offset, mode);
7844 }
7845 
7846 std::string TCling::CallFunc_GetWrapperCode(CallFunc_t *func) const
7847 {
7848  TClingCallFunc *f = (TClingCallFunc *)func;
7849  std::string wrapper_name;
7850  std::string wrapper;
7851  f->get_wrapper_code(wrapper_name, wrapper);
7852  return wrapper;
7853 }
7854 
7855 //______________________________________________________________________________
7856 //
7857 // ClassInfo interface
7858 //
7859 
7860 ////////////////////////////////////////////////////////////////////////////////
7861 /// Return true if the entity pointed to by 'declid' is declared in
7862 /// the context described by 'info'. If info is null, look into the
7863 /// global scope (translation unit scope).
7864 
7865 Bool_t TCling::ClassInfo_Contains(ClassInfo_t *info, DeclId_t declid) const
7866 {
7867  if (!declid) return kFALSE;
7868 
7869  const clang::Decl *scope;
7870  if (info) scope = ((TClingClassInfo*)info)->GetDecl();
7871  else scope = fInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
7872 
7873  const clang::Decl *decl = reinterpret_cast<const clang::Decl*>(declid);
7874  const clang::DeclContext *ctxt = clang::Decl::castToDeclContext(scope);
7875  if (!decl || !ctxt) return kFALSE;
7876  if (decl->getDeclContext()->Equals(ctxt))
7877  return kTRUE;
7878  else if ((decl->getDeclContext()->isTransparentContext()
7879  || decl->getDeclContext()->isInlineNamespace())
7880  && decl->getDeclContext()->getParent()->Equals(ctxt))
7881  return kTRUE;
7882  return kFALSE;
7883 }
7884 
7885 ////////////////////////////////////////////////////////////////////////////////
7886 
7887 Long_t TCling::ClassInfo_ClassProperty(ClassInfo_t* cinfo) const
7888 {
7889  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
7890  return TClinginfo->ClassProperty();
7891 }
7892 
7893 ////////////////////////////////////////////////////////////////////////////////
7894 
7895 void TCling::ClassInfo_Delete(ClassInfo_t* cinfo) const
7896 {
7897  delete (TClingClassInfo*) cinfo;
7898 }
7899 
7900 ////////////////////////////////////////////////////////////////////////////////
7901 
7902 void TCling::ClassInfo_Delete(ClassInfo_t* cinfo, void* arena) const
7903 {
7904  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
7905  TClinginfo->Delete(arena,*fNormalizedCtxt);
7906 }
7907 
7908 ////////////////////////////////////////////////////////////////////////////////
7909 
7910 void TCling::ClassInfo_DeleteArray(ClassInfo_t* cinfo, void* arena, bool dtorOnly) const
7911 {
7912  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
7913  TClinginfo->DeleteArray(arena, dtorOnly,*fNormalizedCtxt);
7914 }
7915 
7916 ////////////////////////////////////////////////////////////////////////////////
7917 
7918 void TCling::ClassInfo_Destruct(ClassInfo_t* cinfo, void* arena) const
7919 {
7920  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
7921  TClinginfo->Destruct(arena,*fNormalizedCtxt);
7922 }
7923 
7924 ////////////////////////////////////////////////////////////////////////////////
7925 
7926 ClassInfo_t* TCling::ClassInfo_Factory(Bool_t all) const
7927 {
7928  R__LOCKGUARD(gInterpreterMutex);
7929  return (ClassInfo_t*) new TClingClassInfo(GetInterpreterImpl(), all);
7930 }
7931 
7932 ////////////////////////////////////////////////////////////////////////////////
7933 
7934 ClassInfo_t* TCling::ClassInfo_Factory(ClassInfo_t* cinfo) const
7935 {
7936  return (ClassInfo_t*) new TClingClassInfo(*(TClingClassInfo*)cinfo);
7937 }
7938 
7939 ////////////////////////////////////////////////////////////////////////////////
7940 
7941 ClassInfo_t* TCling::ClassInfo_Factory(const char* name) const
7942 {
7943  R__LOCKGUARD(gInterpreterMutex);
7944  return (ClassInfo_t*) new TClingClassInfo(GetInterpreterImpl(), name);
7945 }
7946 
7947 ClassInfo_t* TCling::ClassInfo_Factory(DeclId_t declid) const
7948 {
7949  R__LOCKGUARD(gInterpreterMutex);
7950  return (ClassInfo_t*) new TClingClassInfo(GetInterpreterImpl(), (const clang::Decl*)declid);
7951 }
7952 
7953 
7954 ////////////////////////////////////////////////////////////////////////////////
7955 
7956 int TCling::ClassInfo_GetMethodNArg(ClassInfo_t* cinfo, const char* method, const char* proto, Bool_t objectIsConst /* = false */, EFunctionMatchMode mode /* = kConversionMatch */) const
7957 {
7958  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
7959  return TClinginfo->GetMethodNArg(method, proto, objectIsConst, mode);
7960 }
7961 
7962 ////////////////////////////////////////////////////////////////////////////////
7963 
7964 bool TCling::ClassInfo_HasDefaultConstructor(ClassInfo_t* cinfo) const
7965 {
7966  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
7967  return TClinginfo->HasDefaultConstructor();
7968 }
7969 
7970 ////////////////////////////////////////////////////////////////////////////////
7971 
7972 bool TCling::ClassInfo_HasMethod(ClassInfo_t* cinfo, const char* name) const
7973 {
7974  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
7975  return TClinginfo->HasMethod(name);
7976 }
7977 
7978 ////////////////////////////////////////////////////////////////////////////////
7979 
7980 void TCling::ClassInfo_Init(ClassInfo_t* cinfo, const char* name) const
7981 {
7982  R__LOCKGUARD(gInterpreterMutex);
7983  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
7984  TClinginfo->Init(name);
7985 }
7986 
7987 ////////////////////////////////////////////////////////////////////////////////
7988 
7989 void TCling::ClassInfo_Init(ClassInfo_t* cinfo, int tagnum) const
7990 {
7991  R__LOCKGUARD(gInterpreterMutex);
7992  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
7993  TClinginfo->Init(tagnum);
7994 }
7995 
7996 ////////////////////////////////////////////////////////////////////////////////
7997 
7998 bool TCling::ClassInfo_IsBase(ClassInfo_t* cinfo, const char* name) const
7999 {
8000  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8001  return TClinginfo->IsBase(name);
8002 }
8003 
8004 ////////////////////////////////////////////////////////////////////////////////
8005 
8006 bool TCling::ClassInfo_IsEnum(const char* name) const
8007 {
8008  return TClingClassInfo::IsEnum(GetInterpreterImpl(), name);
8009 }
8010 
8011 ////////////////////////////////////////////////////////////////////////////////
8012 
8013 Bool_t TCling::ClassInfo_IsScopedEnum(ClassInfo_t *info) const
8014 {
8015  TClingClassInfo* TClinginfo = (TClingClassInfo*) info;
8016  return TClinginfo->IsScopedEnum();
8017 }
8018 
8019 
8020 ////////////////////////////////////////////////////////////////////////////////
8021 
8022 EDataType TCling::ClassInfo_GetUnderlyingType(ClassInfo_t* info) const
8023 {
8024  TClingClassInfo* TClinginfo = (TClingClassInfo*) info;
8025  return TClinginfo->GetUnderlyingType();
8026 }
8027 
8028 
8029 ////////////////////////////////////////////////////////////////////////////////
8030 
8031 bool TCling::ClassInfo_IsLoaded(ClassInfo_t* cinfo) const
8032 {
8033  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8034  return TClinginfo->IsLoaded();
8035 }
8036 
8037 ////////////////////////////////////////////////////////////////////////////////
8038 
8039 bool TCling::ClassInfo_IsValid(ClassInfo_t* cinfo) const
8040 {
8041  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8042  return TClinginfo->IsValid();
8043 }
8044 
8045 ////////////////////////////////////////////////////////////////////////////////
8046 
8047 bool TCling::ClassInfo_IsValidMethod(ClassInfo_t* cinfo, const char* method, const char* proto, Long_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8048 {
8049  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8050  return TClinginfo->IsValidMethod(method, proto, false, offset, mode);
8051 }
8052 
8053 ////////////////////////////////////////////////////////////////////////////////
8054 
8055 bool TCling::ClassInfo_IsValidMethod(ClassInfo_t* cinfo, const char* method, const char* proto, Bool_t objectIsConst, Long_t* offset, EFunctionMatchMode mode /* = kConversionMatch */) const
8056 {
8057  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8058  return TClinginfo->IsValidMethod(method, proto, objectIsConst, offset, mode);
8059 }
8060 
8061 ////////////////////////////////////////////////////////////////////////////////
8062 
8063 int TCling::ClassInfo_Next(ClassInfo_t* cinfo) const
8064 {
8065  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8066  return TClinginfo->Next();
8067 }
8068 
8069 ////////////////////////////////////////////////////////////////////////////////
8070 
8071 void* TCling::ClassInfo_New(ClassInfo_t* cinfo) const
8072 {
8073  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8074  return TClinginfo->New(*fNormalizedCtxt);
8075 }
8076 
8077 ////////////////////////////////////////////////////////////////////////////////
8078 
8079 void* TCling::ClassInfo_New(ClassInfo_t* cinfo, int n) const
8080 {
8081  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8082  return TClinginfo->New(n,*fNormalizedCtxt);
8083 }
8084 
8085 ////////////////////////////////////////////////////////////////////////////////
8086 
8087 void* TCling::ClassInfo_New(ClassInfo_t* cinfo, int n, void* arena) const
8088 {
8089  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8090  return TClinginfo->New(n, arena,*fNormalizedCtxt);
8091 }
8092 
8093 ////////////////////////////////////////////////////////////////////////////////
8094 
8095 void* TCling::ClassInfo_New(ClassInfo_t* cinfo, void* arena) const
8096 {
8097  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8098  return TClinginfo->New(arena,*fNormalizedCtxt);
8099 }
8100 
8101 ////////////////////////////////////////////////////////////////////////////////
8102 
8103 Long_t TCling::ClassInfo_Property(ClassInfo_t* cinfo) const
8104 {
8105  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8106  return TClinginfo->Property();
8107 }
8108 
8109 ////////////////////////////////////////////////////////////////////////////////
8110 
8111 int TCling::ClassInfo_Size(ClassInfo_t* cinfo) const
8112 {
8113  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8114  return TClinginfo->Size();
8115 }
8116 
8117 ////////////////////////////////////////////////////////////////////////////////
8118 
8119 Long_t TCling::ClassInfo_Tagnum(ClassInfo_t* cinfo) const
8120 {
8121  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8122  return TClinginfo->Tagnum();
8123 }
8124 
8125 ////////////////////////////////////////////////////////////////////////////////
8126 
8127 const char* TCling::ClassInfo_FileName(ClassInfo_t* cinfo) const
8128 {
8129  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8130  return TClinginfo->FileName();
8131 }
8132 
8133 ////////////////////////////////////////////////////////////////////////////////
8134 
8135 const char* TCling::ClassInfo_FullName(ClassInfo_t* cinfo) const
8136 {
8137  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8138  TTHREAD_TLS_DECL(std::string,output);
8139  TClinginfo->FullName(output,*fNormalizedCtxt);
8140  return output.c_str();
8141 }
8142 
8143 ////////////////////////////////////////////////////////////////////////////////
8144 
8145 const char* TCling::ClassInfo_Name(ClassInfo_t* cinfo) const
8146 {
8147  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8148  return TClinginfo->Name();
8149 }
8150 
8151 ////////////////////////////////////////////////////////////////////////////////
8152 
8153 const char* TCling::ClassInfo_Title(ClassInfo_t* cinfo) const
8154 {
8155  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8156  return TClinginfo->Title();
8157 }
8158 
8159 ////////////////////////////////////////////////////////////////////////////////
8160 
8161 const char* TCling::ClassInfo_TmpltName(ClassInfo_t* cinfo) const
8162 {
8163  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8164  return TClinginfo->TmpltName();
8165 }
8166 
8167 
8168 
8169 //______________________________________________________________________________
8170 //
8171 // BaseClassInfo interface
8172 //
8173 
8174 ////////////////////////////////////////////////////////////////////////////////
8175 
8176 void TCling::BaseClassInfo_Delete(BaseClassInfo_t* bcinfo) const
8177 {
8178  delete(TClingBaseClassInfo*) bcinfo;
8179 }
8180 
8181 ////////////////////////////////////////////////////////////////////////////////
8182 
8183 BaseClassInfo_t* TCling::BaseClassInfo_Factory(ClassInfo_t* cinfo) const
8184 {
8185  R__LOCKGUARD(gInterpreterMutex);
8186  TClingClassInfo* TClinginfo = (TClingClassInfo*) cinfo;
8187  return (BaseClassInfo_t*) new TClingBaseClassInfo(GetInterpreterImpl(), TClinginfo);
8188 }
8189 
8190 ////////////////////////////////////////////////////////////////////////////////
8191 
8192 BaseClassInfo_t* TCling::BaseClassInfo_Factory(ClassInfo_t* derived,
8193  ClassInfo_t* base) const
8194 {
8195  R__LOCKGUARD(gInterpreterMutex);
8196  TClingClassInfo* TClinginfo = (TClingClassInfo*) derived;
8197  TClingClassInfo* TClinginfoBase = (TClingClassInfo*) base;
8198  return (BaseClassInfo_t*) new TClingBaseClassInfo(GetInterpreterImpl(), TClinginfo, TClinginfoBase);
8199 }
8200 
8201 ////////////////////////////////////////////////////////////////////////////////
8202 
8203 int TCling::BaseClassInfo_Next(BaseClassInfo_t* bcinfo) const
8204 {
8205  TClingBaseClassInfo* TClinginfo = (TClingBaseClassInfo*) bcinfo;
8206  return TClinginfo->Next();
8207 }
8208 
8209 ////////////////////////////////////////////////////////////////////////////////
8210 
8211 int TCling::BaseClassInfo_Next(BaseClassInfo_t* bcinfo, int onlyDirect) const
8212 {
8213  TClingBaseClassInfo* TClinginfo = (TClingBaseClassInfo*) bcinfo;
8214  return TClinginfo->Next(onlyDirect);
8215 }
8216 
8217 ////////////////////////////////////////////////////////////////////////////////
8218 
8219 Long_t TCling::BaseClassInfo_Offset(BaseClassInfo_t* toBaseClassInfo, void * address, bool isDerivedObject) const
8220 {
8221  TClingBaseClassInfo* TClinginfo = (TClingBaseClassInfo*) toBaseClassInfo;
8222  return TClinginfo->Offset(address, isDerivedObject);
8223 }
8224 
8225 ////////////////////////////////////////////////////////////////////////////////
8226 
8227 Long_t TCling::ClassInfo_GetBaseOffset(ClassInfo_t* fromDerived, ClassInfo_t* toBase, void * address, bool isDerivedObject) const
8228 {
8229  TClingClassInfo* TClinginfo = (TClingClassInfo*) fromDerived;
8230  TClingClassInfo* TClinginfoBase = (TClingClassInfo*) toBase;
8231  // Offset to the class itself.
8232  if (TClinginfo->GetDecl() == TClinginfoBase->GetDecl()) {
8233  return 0;
8234  }
8235  return TClinginfo->GetBaseOffset(TClinginfoBase, address, isDerivedObject);
8236 }
8237 
8238 ////////////////////////////////////////////////////////////////////////////////
8239 
8240 Long_t TCling::BaseClassInfo_Property(BaseClassInfo_t* bcinfo) const
8241 {
8242  TClingBaseClassInfo* TClinginfo = (TClingBaseClassInfo*) bcinfo;
8243  return TClinginfo->Property();
8244 }
8245 
8246 ////////////////////////////////////////////////////////////////////////////////
8247 
8248 ClassInfo_t *TCling::BaseClassInfo_ClassInfo(BaseClassInfo_t *bcinfo) const
8249 {
8250  TClingBaseClassInfo* TClinginfo = (TClingBaseClassInfo*) bcinfo;
8251  return (ClassInfo_t *)TClinginfo->GetBase();
8252 }
8253 
8254 ////////////////////////////////////////////////////////////////////////////////
8255 
8256 Long_t TCling::BaseClassInfo_Tagnum(BaseClassInfo_t* bcinfo) const
8257 {
8258  TClingBaseClassInfo* TClinginfo = (TClingBaseClassInfo*) bcinfo;
8259  return TClinginfo->Tagnum();
8260 }
8261 
8262 ////////////////////////////////////////////////////////////////////////////////
8263 
8264 const char* TCling::BaseClassInfo_FullName(BaseClassInfo_t* bcinfo) const
8265 {
8266  TClingBaseClassInfo* TClinginfo = (TClingBaseClassInfo*) bcinfo;
8267  TTHREAD_TLS_DECL(std::string,output);
8268  TClinginfo->FullName(output,*fNormalizedCtxt);
8269  return output.c_str();
8270 }
8271 
8272 ////////////////////////////////////////////////////////////////////////////////
8273 
8274 const char* TCling::BaseClassInfo_Name(BaseClassInfo_t* bcinfo) const
8275 {
8276  TClingBaseClassInfo* TClinginfo = (TClingBaseClassInfo*) bcinfo;
8277  return TClinginfo->Name();
8278 }
8279 
8280 ////////////////////////////////////////////////////////////////////////////////
8281 
8282 const char* TCling::BaseClassInfo_TmpltName(BaseClassInfo_t* bcinfo) const
8283 {
8284  TClingBaseClassInfo* TClinginfo = (TClingBaseClassInfo*) bcinfo;
8285  return TClinginfo->TmpltName();
8286 }
8287 
8288 //______________________________________________________________________________
8289 //
8290 // DataMemberInfo interface
8291 //
8292 
8293 ////////////////////////////////////////////////////////////////////////////////
8294 
8295 int TCling::DataMemberInfo_ArrayDim(DataMemberInfo_t* dminfo) const
8296 {
8297  TClingDataMemberInfo* TClinginfo = (TClingDataMemberInfo*) dminfo;
8298  return TClinginfo->ArrayDim();
8299 }
8300 
8301 ////////////////////////////////////////////////////////////////////////////////
8302 
8303 void TCling::DataMemberInfo_Delete(DataMemberInfo_t* dminfo) const
8304 {
8305  delete(TClingDataMemberInfo*) dminfo;
8306 }
8307 
8308 ////////////////////////////////////////////////////////////////////////////////
8309 
8310 DataMemberInfo_t* TCling::DataMemberInfo_Factory(ClassInfo_t* clinfo /*= 0*/) const
8311 {
8312  R__LOCKGUARD(gInterpreterMutex);
8313  TClingClassInfo* TClingclass_info = (TClingClassInfo*) clinfo;
8314  return (DataMemberInfo_t*) new TClingDataMemberInfo(GetInterpreterImpl(), TClingclass_info);
8315 }
8316 
8317 ////////////////////////////////////////////////////////////////////////////////
8318 
8319 DataMemberInfo_t* TCling::DataMemberInfo_Factory(DeclId_t declid, ClassInfo_t* clinfo) const
8320 {
8321  R__LOCKGUARD(gInterpreterMutex);
8322  const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
8323  const clang::ValueDecl* vd = llvm::dyn_cast_or_null<clang::ValueDecl>(decl);
8324  return (DataMemberInfo_t*) new TClingDataMemberInfo(GetInterpreterImpl(), vd, (TClingClassInfo*)clinfo);
8325 }
8326 
8327 ////////////////////////////////////////////////////////////////////////////////
8328 
8329 DataMemberInfo_t* TCling::DataMemberInfo_FactoryCopy(DataMemberInfo_t* dminfo) const
8330 {
8331  TClingDataMemberInfo* TClinginfo = (TClingDataMemberInfo*) dminfo;
8332  return (DataMemberInfo_t*) new TClingDataMemberInfo(*TClinginfo);
8333 }
8334 
8335 ////////////////////////////////////////////////////////////////////////////////
8336 
8337 bool TCling::DataMemberInfo_IsValid(DataMemberInfo_t* dminfo) const
8338 {
8339  TClingDataMemberInfo* TClinginfo = (TClingDataMemberInfo*) dminfo;
8340  return TClinginfo->IsValid();
8341 }
8342 
8343 ////////////////////////////////////////////////////////////////////////////////
8344 
8345 int TCling::DataMemberInfo_MaxIndex(DataMemberInfo_t* dminfo, Int_t dim) const
8346 {
8347  TClingDataMemberInfo* TClinginfo = (TClingDataMemberInfo*) dminfo;
8348  return TClinginfo->MaxIndex(dim);
8349 }
8350 
8351 ////////////////////////////////////////////////////////////////////////////////
8352 
8353 int TCling::DataMemberInfo_Next(DataMemberInfo_t* dminfo) const
8354 {
8355  TClingDataMemberInfo* TClinginfo = (TClingDataMemberInfo*) dminfo;
8356  return TClinginfo->Next();
8357 }
8358 
8359 ////////////////////////////////////////////////////////////////////////////////
8360 
8361 Long_t TCling::DataMemberInfo_Offset(DataMemberInfo_t* dminfo) const
8362 {
8363  TClingDataMemberInfo* TClinginfo = (TClingDataMemberInfo*) dminfo;
8364  return TClinginfo->Offset();
8365 }
8366 
8367 ////////////////////////////////////////////////////////////////////////////////
8368 
8369 Long_t TCling::DataMemberInfo_Property(DataMemberInfo_t* dminfo) const
8370 {
8371  TClingDataMemberInfo* TClinginfo = (TClingDataMemberInfo*) dminfo;
8372  return TClinginfo->Property();
8373 }
8374 
8375 ////////////////////////////////////////////////////////////////////////////////
8376 
8377 Long_t TCling::DataMemberInfo_TypeProperty(DataMemberInfo_t* dminfo) const
8378 {
8379  TClingDataMemberInfo* TClinginfo = (TClingDataMemberInfo*) dminfo;
8380  return TClinginfo->TypeProperty();
8381 }
8382 
8383 ////////////////////////////////////////////////////////////////////////////////
8384 
8385 int TCling::DataMemberInfo_TypeSize(DataMemberInfo_t* dminfo) const
8386 {
8387  TClingDataMemberInfo* TClinginfo = (TClingDataMemberInfo*) dminfo;
8388  return TClinginfo->TypeSize();
8389 }
8390 
8391 ////////////////////////////////////////////////////////////////////////////////
8392 
8393 const char* TCling::DataMemberInfo_TypeName(DataMemberInfo_t* dminfo) const
8394 {
8395  TClingDataMemberInfo* TClinginfo = (TClingDataMemberInfo*) dminfo;
8396  return TClinginfo->TypeName();
8397 }
8398 
8399 ////////////////////////////////////////////////////////////////////////////////
8400 
8401 const char* TCling::DataMemberInfo_TypeTrueName(DataMemberInfo_t* dminfo) const
8402 {
8403  TClingDataMemberInfo* TClinginfo = (TClingDataMemberInfo*) dminfo;
8404  return TClinginfo->TypeTrueName(*fNormalizedCtxt);
8405 }
8406 
8407 ////////////////////////////////////////////////////////////////////////////////
8408 
8409 const char* TCling::DataMemberInfo_Name(DataMemberInfo_t* dminfo) const
8410 {
8411  TClingDataMemberInfo* TClinginfo = (TClingDataMemberInfo*) dminfo;
8412  return TClinginfo->Name();
8413 }
8414 
8415 ////////////////////////////////////////////////////////////////////////////////
8416 
8417 const char* TCling::DataMemberInfo_Title(DataMemberInfo_t* dminfo) const
8418 {
8419  TClingDataMemberInfo* TClinginfo = (TClingDataMemberInfo*) dminfo;
8420  return TClinginfo->Title();
8421 }
8422 
8423 ////////////////////////////////////////////////////////////////////////////////
8424 
8425 const char* TCling::DataMemberInfo_ValidArrayIndex(DataMemberInfo_t* dminfo) const
8426 {
8427  TTHREAD_TLS_DECL(std::string,result);
8428 
8429  TClingDataMemberInfo* TClinginfo = (TClingDataMemberInfo*) dminfo;
8430  result = TClinginfo->ValidArrayIndex().str();
8431  return result.c_str();
8432 }
8433 
8434 ////////////////////////////////////////////////////////////////////////////////
8435 
8436 void TCling::SetDeclAttr(DeclId_t declId, const char* attribute)
8437 {
8438  Decl* decl = static_cast<Decl*>(const_cast<void*>(declId));
8439  ASTContext &C = decl->getASTContext();
8440  SourceRange commentRange; // this is a fake comment range
8441  decl->addAttr( new (C) AnnotateAttr( commentRange, C, attribute, 0 ) );
8442 }
8443 
8444 //______________________________________________________________________________
8445 //
8446 // Function Template interface
8447 //
8448 
8449 ////////////////////////////////////////////////////////////////////////////////
8450 
8451 static void ConstructorName(std::string &name, const clang::NamedDecl *decl,
8452  cling::Interpreter &interp,
8453  const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt)
8454 {
8455  const clang::TypeDecl* td = llvm::dyn_cast<clang::TypeDecl>(decl->getDeclContext());
8456  if (!td) return;
8457 
8458  clang::QualType qualType(td->getTypeForDecl(),0);
8459  ROOT::TMetaUtils::GetNormalizedName(name, qualType, interp, normCtxt);
8460  unsigned int level = 0;
8461  for(size_t cursor = name.length()-1; cursor != 0; --cursor) {
8462  if (name[cursor] == '>') ++level;
8463  else if (name[cursor] == '<' && level) --level;
8464  else if (level == 0 && name[cursor] == ':') {
8465  name.erase(0,cursor+1);
8466  break;
8467  }
8468  }
8469 }
8470 
8471 ////////////////////////////////////////////////////////////////////////////////
8472 
8473 void TCling::GetFunctionName(const clang::FunctionDecl *decl, std::string &output) const
8474 {
8475  output.clear();
8476  if (llvm::isa<clang::CXXConstructorDecl>(decl))
8477  {
8478  ConstructorName(output, decl, *fInterpreter, *fNormalizedCtxt);
8479 
8480  } else if (llvm::isa<clang::CXXDestructorDecl>(decl))
8481  {
8482  ConstructorName(output, decl, *fInterpreter, *fNormalizedCtxt);
8483  output.insert(output.begin(), '~');
8484  } else {
8485  llvm::raw_string_ostream stream(output);
8486  auto printPolicy = decl->getASTContext().getPrintingPolicy();
8487  // Don't trigger fopen of the source file to count lines:
8488  printPolicy.AnonymousTagLocations = false;
8489  decl->getNameForDiagnostic(stream, printPolicy, /*Qualified=*/false);
8490  }
8491 }
8492 
8493 ////////////////////////////////////////////////////////////////////////////////
8494 /// Return a unique identifier of the declaration represented by the
8495 /// FuncTempInfo
8496 
8497 TInterpreter::DeclId_t TCling::GetDeclId(FuncTempInfo_t *info) const
8498 {
8499  return (DeclId_t)info;
8500 }
8501 
8502 ////////////////////////////////////////////////////////////////////////////////
8503 /// Delete the FuncTempInfo_t
8504 
8505 void TCling::FuncTempInfo_Delete(FuncTempInfo_t * /* ft_info */) const
8506 {
8507  // Currently the address of ft_info is actually the decl itself,
8508  // so we have nothing to do.
8509 }
8510 
8511 ////////////////////////////////////////////////////////////////////////////////
8512 /// Construct a FuncTempInfo_t
8513 
8514 FuncTempInfo_t *TCling::FuncTempInfo_Factory(DeclId_t declid) const
8515 {
8516  // Currently the address of ft_info is actually the decl itself,
8517  // so we have nothing to do.
8518 
8519  return (FuncTempInfo_t*)const_cast<void*>(declid);
8520 }
8521 
8522 ////////////////////////////////////////////////////////////////////////////////
8523 /// Construct a FuncTempInfo_t
8524 
8525 FuncTempInfo_t *TCling::FuncTempInfo_FactoryCopy(FuncTempInfo_t *ft_info) const
8526 {
8527  // Currently the address of ft_info is actually the decl itself,
8528  // so we have nothing to do.
8529 
8530  return (FuncTempInfo_t*)ft_info;
8531 }
8532 
8533 ////////////////////////////////////////////////////////////////////////////////
8534 /// Check validity of a FuncTempInfo_t
8535 
8536 Bool_t TCling::FuncTempInfo_IsValid(FuncTempInfo_t *t_info) const
8537 {
8538  // Currently the address of ft_info is actually the decl itself,
8539  // so we have nothing to do.
8540 
8541  return t_info != 0;
8542 }
8543 
8544 ////////////////////////////////////////////////////////////////////////////////
8545 /// Return the maximum number of template arguments of the
8546 /// function template described by ft_info.
8547 
8548 UInt_t TCling::FuncTempInfo_TemplateNargs(FuncTempInfo_t *ft_info) const
8549 {
8550  if (!ft_info) return 0;
8551  const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
8552  return ft->getTemplateParameters()->size();
8553 }
8554 
8555 ////////////////////////////////////////////////////////////////////////////////
8556 /// Return the number of required template arguments of the
8557 /// function template described by ft_info.
8558 
8559 UInt_t TCling::FuncTempInfo_TemplateMinReqArgs(FuncTempInfo_t *ft_info) const
8560 {
8561  if (!ft_info) return 0;
8562  const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8563  return ft->getTemplateParameters()->getMinRequiredArguments();
8564 }
8565 
8566 ////////////////////////////////////////////////////////////////////////////////
8567 /// Return the property of the function template.
8568 
8569 Long_t TCling::FuncTempInfo_Property(FuncTempInfo_t *ft_info) const
8570 {
8571  if (!ft_info) return 0;
8572 
8573  long property = 0L;
8574  property |= kIsCompiled;
8575 
8576  const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8577 
8578  switch (ft->getAccess()) {
8579  case clang::AS_public:
8580  property |= kIsPublic;
8581  break;
8582  case clang::AS_protected:
8583  property |= kIsProtected;
8584  break;
8585  case clang::AS_private:
8586  property |= kIsPrivate;
8587  break;
8588  case clang::AS_none:
8589  if (ft->getDeclContext()->isNamespace())
8590  property |= kIsPublic;
8591  break;
8592  default:
8593  // IMPOSSIBLE
8594  break;
8595  }
8596 
8597  const clang::FunctionDecl *fd = ft->getTemplatedDecl();
8598  if (const clang::CXXMethodDecl *md =
8599  llvm::dyn_cast<clang::CXXMethodDecl>(fd)) {
8600  if (md->getTypeQualifiers() & clang::Qualifiers::Const) {
8601  property |= kIsConstant | kIsConstMethod;
8602  }
8603  if (md->isVirtual()) {
8604  property |= kIsVirtual;
8605  }
8606  if (md->isPure()) {
8607  property |= kIsPureVirtual;
8608  }
8609  if (const clang::CXXConstructorDecl *cd =
8610  llvm::dyn_cast<clang::CXXConstructorDecl>(md)) {
8611  if (cd->isExplicit()) {
8612  property |= kIsExplicit;
8613  }
8614  }
8615  else if (const clang::CXXConversionDecl *cd =
8616  llvm::dyn_cast<clang::CXXConversionDecl>(md)) {
8617  if (cd->isExplicit()) {
8618  property |= kIsExplicit;
8619  }
8620  }
8621  }
8622  return property;
8623 }
8624 
8625 ////////////////////////////////////////////////////////////////////////////////
8626 /// Return the property not already defined in Property
8627 /// See TDictionary's EFunctionProperty
8628 
8629 Long_t TCling::FuncTempInfo_ExtraProperty(FuncTempInfo_t* ft_info) const
8630 {
8631  if (!ft_info) return 0;
8632 
8633  long property = 0L;
8634  property |= kIsCompiled;
8635 
8636  const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8637  const clang::FunctionDecl *fd = ft->getTemplatedDecl();
8638 
8639  if (fd->isOverloadedOperator())
8640  property |= kIsOperator;
8641  if (llvm::isa<clang::CXXConversionDecl>(fd))
8642  property |= kIsConversion;
8643  if (llvm::isa<clang::CXXConstructorDecl>(fd))
8644  property |= kIsConstructor;
8645  if (llvm::isa<clang::CXXDestructorDecl>(fd))
8646  property |= kIsDestructor;
8647  if (fd->isInlined())
8648  property |= kIsInlined;
8649  return property;
8650 }
8651 
8652 ////////////////////////////////////////////////////////////////////////////////
8653 /// Return the name of this function template.
8654 
8655 void TCling::FuncTempInfo_Name(FuncTempInfo_t *ft_info, TString &output) const
8656 {
8657  output.Clear();
8658  if (!ft_info) return;
8659  const clang::FunctionTemplateDecl *ft = (clang::FunctionTemplateDecl*)ft_info;
8660  std::string buf;
8661  GetFunctionName(ft->getTemplatedDecl(), buf);
8662  output = buf;
8663 }
8664 
8665 ////////////////////////////////////////////////////////////////////////////////
8666 /// Return the comments associates with this function template.
8667 
8668 void TCling::FuncTempInfo_Title(FuncTempInfo_t *ft_info, TString &output) const
8669 {
8670  output.Clear();
8671  if (!ft_info) return;
8672  const clang::FunctionTemplateDecl *ft = (const clang::FunctionTemplateDecl*)ft_info;
8673 
8674  // Iterate over the redeclarations, we can have multiple definitions in the
8675  // redecl chain (came from merging of pcms).
8676  if (const RedeclarableTemplateDecl *AnnotFD
8677  = ROOT::TMetaUtils::GetAnnotatedRedeclarable((const RedeclarableTemplateDecl*)ft)) {
8678  if (AnnotateAttr *A = AnnotFD->getAttr<AnnotateAttr>()) {
8679  output = A->getAnnotation().str();
8680  return;
8681  }
8682  }
8683  if (!ft->isFromASTFile()) {
8684  // Try to get the comment from the header file if present
8685  // but not for decls from AST file, where rootcling would have
8686  // created an annotation
8687  output = ROOT::TMetaUtils::GetComment(*ft).str();
8688  }
8689 }
8690 
8691 
8692 //______________________________________________________________________________
8693 //
8694 // MethodInfo interface
8695 //
8696 
8697 ////////////////////////////////////////////////////////////////////////////////
8698 /// Interface to cling function
8699 
8700 void TCling::MethodInfo_Delete(MethodInfo_t* minfo) const
8701 {
8702  delete(TClingMethodInfo*) minfo;
8703 }
8704 
8705 ////////////////////////////////////////////////////////////////////////////////
8706 
8707 void TCling::MethodInfo_CreateSignature(MethodInfo_t* minfo, TString& signature) const
8708 {
8709  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8710  info->CreateSignature(signature);
8711 }
8712 
8713 ////////////////////////////////////////////////////////////////////////////////
8714 
8715 MethodInfo_t* TCling::MethodInfo_Factory() const
8716 {
8717  R__LOCKGUARD(gInterpreterMutex);
8718  return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl());
8719 }
8720 
8721 ////////////////////////////////////////////////////////////////////////////////
8722 
8723 MethodInfo_t* TCling::MethodInfo_Factory(ClassInfo_t* clinfo) const
8724 {
8725  R__LOCKGUARD(gInterpreterMutex);
8726  return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), (TClingClassInfo*)clinfo);
8727 }
8728 
8729 ////////////////////////////////////////////////////////////////////////////////
8730 
8731 MethodInfo_t* TCling::MethodInfo_Factory(DeclId_t declid) const
8732 {
8733  const clang::Decl* decl = reinterpret_cast<const clang::Decl*>(declid);
8734  R__LOCKGUARD(gInterpreterMutex);
8735  const clang::FunctionDecl* fd = llvm::dyn_cast_or_null<clang::FunctionDecl>(decl);
8736  return (MethodInfo_t*) new TClingMethodInfo(GetInterpreterImpl(), fd);
8737 }
8738 
8739 ////////////////////////////////////////////////////////////////////////////////
8740 
8741 MethodInfo_t* TCling::MethodInfo_FactoryCopy(MethodInfo_t* minfo) const
8742 {
8743  return (MethodInfo_t*) new TClingMethodInfo(*(TClingMethodInfo*)minfo);
8744 }
8745 
8746 ////////////////////////////////////////////////////////////////////////////////
8747 
8748 void* TCling::MethodInfo_InterfaceMethod(MethodInfo_t* minfo) const
8749 {
8750  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8751  return info->InterfaceMethod(*fNormalizedCtxt);
8752 }
8753 
8754 ////////////////////////////////////////////////////////////////////////////////
8755 
8756 bool TCling::MethodInfo_IsValid(MethodInfo_t* minfo) const
8757 {
8758  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8759  return info->IsValid();
8760 }
8761 
8762 ////////////////////////////////////////////////////////////////////////////////
8763 
8764 int TCling::MethodInfo_NArg(MethodInfo_t* minfo) const
8765 {
8766  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8767  return info->NArg();
8768 }
8769 
8770 ////////////////////////////////////////////////////////////////////////////////
8771 
8772 int TCling::MethodInfo_NDefaultArg(MethodInfo_t* minfo) const
8773 {
8774  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8775  return info->NDefaultArg();
8776 }
8777 
8778 ////////////////////////////////////////////////////////////////////////////////
8779 
8780 int TCling::MethodInfo_Next(MethodInfo_t* minfo) const
8781 {
8782  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8783  return info->Next();
8784 }
8785 
8786 ////////////////////////////////////////////////////////////////////////////////
8787 
8788 Long_t TCling::MethodInfo_Property(MethodInfo_t* minfo) const
8789 {
8790  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8791  return info->Property();
8792 }
8793 
8794 ////////////////////////////////////////////////////////////////////////////////
8795 
8796 Long_t TCling::MethodInfo_ExtraProperty(MethodInfo_t* minfo) const
8797 {
8798  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8799  return info->ExtraProperty();
8800 }
8801 
8802 ////////////////////////////////////////////////////////////////////////////////
8803 
8804 TypeInfo_t* TCling::MethodInfo_Type(MethodInfo_t* minfo) const
8805 {
8806  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8807  return (TypeInfo_t*)info->Type();
8808 }
8809 
8810 ////////////////////////////////////////////////////////////////////////////////
8811 
8812 const char* TCling::MethodInfo_GetMangledName(MethodInfo_t* minfo) const
8813 {
8814  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8815  TTHREAD_TLS_DECL(TString, mangled_name);
8816  mangled_name = info->GetMangledName();
8817  return mangled_name;
8818 }
8819 
8820 ////////////////////////////////////////////////////////////////////////////////
8821 
8822 const char* TCling::MethodInfo_GetPrototype(MethodInfo_t* minfo) const
8823 {
8824  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8825  return info->GetPrototype();
8826 }
8827 
8828 ////////////////////////////////////////////////////////////////////////////////
8829 
8830 const char* TCling::MethodInfo_Name(MethodInfo_t* minfo) const
8831 {
8832  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8833  return info->Name();
8834 }
8835 
8836 ////////////////////////////////////////////////////////////////////////////////
8837 
8838 const char* TCling::MethodInfo_TypeName(MethodInfo_t* minfo) const
8839 {
8840  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8841  return info->TypeName();
8842 }
8843 
8844 ////////////////////////////////////////////////////////////////////////////////
8845 
8846 std::string TCling::MethodInfo_TypeNormalizedName(MethodInfo_t* minfo) const
8847 {
8848  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8849  if (info && info->IsValid())
8850  return info->Type()->NormalizedName(*fNormalizedCtxt);
8851  else
8852  return "";
8853 }
8854 
8855 ////////////////////////////////////////////////////////////////////////////////
8856 
8857 const char* TCling::MethodInfo_Title(MethodInfo_t* minfo) const
8858 {
8859  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8860  return info->Title();
8861 }
8862 
8863 ////////////////////////////////////////////////////////////////////////////////
8864 
8865 auto TCling::MethodCallReturnType(TFunction *func) const -> EReturnType
8866 {
8867  if (func) {
8868  return MethodInfo_MethodCallReturnType(func->fInfo);
8869  } else {
8870  return EReturnType::kOther;
8871  }
8872 }
8873 
8874 ////////////////////////////////////////////////////////////////////////////////
8875 
8876 auto TCling::MethodInfo_MethodCallReturnType(MethodInfo_t* minfo) const -> EReturnType
8877 {
8878  TClingMethodInfo* info = (TClingMethodInfo*) minfo;
8879  if (info && info->IsValid()) {
8880  TClingTypeInfo *typeinfo = info->Type();
8881  clang::QualType QT( typeinfo->GetQualType().getCanonicalType() );
8882  if (QT->isEnumeralType()) {
8883  return EReturnType::kLong;
8884  } else if (QT->isPointerType()) {
8885  // Look for char*
8886  QT = llvm::cast<clang::PointerType>(QT)->getPointeeType();
8887  if ( QT->isCharType() ) {
8888  return EReturnType::kString;
8889  } else {
8890  return EReturnType::kOther;
8891  }
8892  } else if ( QT->isFloatingType() ) {
8893  int sz = typeinfo->Size();
8894  if (sz == 4 || sz == 8) {
8895  // Support only float and double.
8896  return EReturnType::kDouble;
8897  } else {
8898  return EReturnType::kOther;
8899  }
8900  } else if ( QT->isIntegerType() ) {
8901  int sz = typeinfo->Size();
8902  if (sz <= 8) {
8903  // Support only up to long long ... but
8904  // FIXME the TMethodCall::Execute only
8905  // return long (4 bytes) ...
8906  // The v5 implementation of TMethodCall::ReturnType
8907  // was not making the distinction so we let it go
8908  // as is for now, but we really need to upgrade
8909  // TMethodCall::Execute ...
8910  return EReturnType::kLong;
8911  } else {
8912  return EReturnType::kOther;
8913  }
8914  } else {
8915  return EReturnType::kOther;
8916  }
8917  } else {
8918  return EReturnType::kOther;
8919  }
8920 }
8921 
8922 //______________________________________________________________________________
8923 //
8924 // MethodArgInfo interface
8925 //
8926 
8927 ////////////////////////////////////////////////////////////////////////////////
8928 
8929 void TCling::MethodArgInfo_Delete(MethodArgInfo_t* marginfo) const
8930 {
8931  delete(TClingMethodArgInfo*) marginfo;
8932 }
8933 
8934 ////////////////////////////////////////////////////////////////////////////////
8935 
8936 MethodArgInfo_t* TCling::MethodArgInfo_Factory() const
8937 {
8938  R__LOCKGUARD(gInterpreterMutex);
8939  return (MethodArgInfo_t*) new TClingMethodArgInfo(GetInterpreterImpl());
8940 }
8941 
8942 ////////////////////////////////////////////////////////////////////////////////
8943 
8944 MethodArgInfo_t* TCling::MethodArgInfo_Factory(MethodInfo_t *minfo) const
8945 {
8946  R__LOCKGUARD(gInterpreterMutex);
8947  return (MethodArgInfo_t*) new TClingMethodArgInfo(GetInterpreterImpl(), (TClingMethodInfo*)minfo);
8948 }
8949 
8950 ////////////////////////////////////////////////////////////////////////////////
8951 
8952 MethodArgInfo_t* TCling::MethodArgInfo_FactoryCopy(MethodArgInfo_t* marginfo) const
8953 {
8954  return (MethodArgInfo_t*)
8955  new TClingMethodArgInfo(*(TClingMethodArgInfo*)marginfo);
8956 }
8957 
8958 ////////////////////////////////////////////////////////////////////////////////
8959 
8960 bool TCling::MethodArgInfo_IsValid(MethodArgInfo_t* marginfo) const
8961 {
8962  TClingMethodArgInfo* info = (TClingMethodArgInfo*) marginfo;
8963  return info->IsValid();
8964 }
8965 
8966 ////////////////////////////////////////////////////////////////////////////////
8967 
8968 int TCling::MethodArgInfo_Next(MethodArgInfo_t* marginfo) const
8969 {
8970  TClingMethodArgInfo* info = (TClingMethodArgInfo*) marginfo;
8971  return info->Next();
8972 }
8973 
8974 ////////////////////////////////////////////////////////////////////////////////
8975 
8976 Long_t TCling::MethodArgInfo_Property(MethodArgInfo_t* marginfo) const
8977 {
8978  TClingMethodArgInfo* info = (TClingMethodArgInfo*) marginfo;
8979  return info->Property();
8980 }
8981 
8982 ////////////////////////////////////////////////////////////////////////////////
8983 
8984 const char* TCling::MethodArgInfo_DefaultValue(MethodArgInfo_t* marginfo) const
8985 {
8986  TClingMethodArgInfo* info = (TClingMethodArgInfo*) marginfo;
8987  return info->DefaultValue();
8988 }
8989 
8990 ////////////////////////////////////////////////////////////////////////////////
8991 
8992 const char* TCling::MethodArgInfo_Name(MethodArgInfo_t* marginfo) const
8993 {
8994  TClingMethodArgInfo* info = (TClingMethodArgInfo*) marginfo;
8995  return info->Name();
8996 }
8997 
8998 ////////////////////////////////////////////////////////////////////////////////
8999 
9000 const char* TCling::MethodArgInfo_TypeName(MethodArgInfo_t* marginfo) const
9001 {
9002  TClingMethodArgInfo* info = (TClingMethodArgInfo*) marginfo;
9003  return info->TypeName();
9004 }
9005 
9006 ////////////////////////////////////////////////////////////////////////////////
9007 
9008 std::string TCling::MethodArgInfo_TypeNormalizedName(MethodArgInfo_t* marginfo) const
9009 {
9010  TClingMethodArgInfo* info = (TClingMethodArgInfo*) marginfo;
9011  return info->Type()->NormalizedName(*fNormalizedCtxt);
9012 }
9013 
9014 //______________________________________________________________________________
9015 //
9016 // TypeInfo interface
9017 //
9018 
9019 ////////////////////////////////////////////////////////////////////////////////
9020 
9021 void TCling::TypeInfo_Delete(TypeInfo_t* tinfo) const
9022 {
9023  delete (TClingTypeInfo*) tinfo;
9024 }
9025 
9026 ////////////////////////////////////////////////////////////////////////////////
9027 
9028 TypeInfo_t* TCling::TypeInfo_Factory() const
9029 {
9030  R__LOCKGUARD(gInterpreterMutex);
9031  return (TypeInfo_t*) new TClingTypeInfo(GetInterpreterImpl());
9032 }
9033 
9034 ////////////////////////////////////////////////////////////////////////////////
9035 
9036 TypeInfo_t* TCling::TypeInfo_Factory(const char *name) const
9037 {
9038  R__LOCKGUARD(gInterpreterMutex);
9039  return (TypeInfo_t*) new TClingTypeInfo(GetInterpreterImpl(), name);
9040 }
9041 
9042 ////////////////////////////////////////////////////////////////////////////////
9043 
9044 TypeInfo_t* TCling::TypeInfo_FactoryCopy(TypeInfo_t* tinfo) const
9045 {
9046  return (TypeInfo_t*) new TClingTypeInfo(*(TClingTypeInfo*)tinfo);
9047 }
9048 
9049 ////////////////////////////////////////////////////////////////////////////////
9050 
9051 void TCling::TypeInfo_Init(TypeInfo_t* tinfo, const char* name) const
9052 {
9053  R__LOCKGUARD(gInterpreterMutex);
9054  TClingTypeInfo* TClinginfo = (TClingTypeInfo*) tinfo;
9055  TClinginfo->Init(name);
9056 }
9057 
9058 ////////////////////////////////////////////////////////////////////////////////
9059 
9060 bool TCling::TypeInfo_IsValid(TypeInfo_t* tinfo) const
9061 {
9062  TClingTypeInfo* TClinginfo = (TClingTypeInfo*) tinfo;
9063  return TClinginfo->IsValid();
9064 }
9065 
9066 ////////////////////////////////////////////////////////////////////////////////
9067 
9068 const char* TCling::TypeInfo_Name(TypeInfo_t* tinfo) const
9069 {
9070  TClingTypeInfo* TClinginfo = (TClingTypeInfo*) tinfo;
9071  return TClinginfo->Name();
9072 }
9073 
9074 ////////////////////////////////////////////////////////////////////////////////
9075 
9076 Long_t TCling::TypeInfo_Property(TypeInfo_t* tinfo) const
9077 {
9078  TClingTypeInfo* TClinginfo = (TClingTypeInfo*) tinfo;
9079  return TClinginfo->Property();
9080 }
9081 
9082 ////////////////////////////////////////////////////////////////////////////////
9083 
9084 int TCling::TypeInfo_RefType(TypeInfo_t* tinfo) const
9085 {
9086  TClingTypeInfo* TClinginfo = (TClingTypeInfo*) tinfo;
9087  return TClinginfo->RefType();
9088 }
9089 
9090 ////////////////////////////////////////////////////////////////////////////////
9091 
9092 int TCling::TypeInfo_Size(TypeInfo_t* tinfo) const
9093 {
9094  TClingTypeInfo* TClinginfo = (TClingTypeInfo*) tinfo;
9095  return TClinginfo->Size();
9096 }
9097 
9098 ////////////////////////////////////////////////////////////////////////////////
9099 
9100 const char* TCling::TypeInfo_TrueName(TypeInfo_t* tinfo) const
9101 {
9102  TClingTypeInfo* TClinginfo = (TClingTypeInfo*) tinfo;
9103  return TClinginfo->TrueName(*fNormalizedCtxt);
9104 }
9105 
9106 
9107 //______________________________________________________________________________
9108 //
9109 // TypedefInfo interface
9110 //
9111 
9112 ////////////////////////////////////////////////////////////////////////////////
9113 
9114 void TCling::TypedefInfo_Delete(TypedefInfo_t* tinfo) const
9115 {
9116  delete(TClingTypedefInfo*) tinfo;
9117 }
9118 
9119 ////////////////////////////////////////////////////////////////////////////////
9120 
9121 TypedefInfo_t* TCling::TypedefInfo_Factory() const
9122 {
9123  R__LOCKGUARD(gInterpreterMutex);
9124  return (TypedefInfo_t*) new TClingTypedefInfo(GetInterpreterImpl());
9125 }
9126 
9127 ////////////////////////////////////////////////////////////////////////////////
9128 
9129 TypedefInfo_t* TCling::TypedefInfo_Factory(const char *name) const
9130 {
9131  R__LOCKGUARD(gInterpreterMutex);
9132  return (TypedefInfo_t*) new TClingTypedefInfo(GetInterpreterImpl(), name);
9133 }
9134 
9135 ////////////////////////////////////////////////////////////////////////////////
9136 
9137 TypedefInfo_t* TCling::TypedefInfo_FactoryCopy(TypedefInfo_t* tinfo) const
9138 {
9139  return (TypedefInfo_t*) new TClingTypedefInfo(*(TClingTypedefInfo*)tinfo);
9140 }
9141 
9142 ////////////////////////////////////////////////////////////////////////////////
9143 
9144 void TCling::TypedefInfo_Init(TypedefInfo_t* tinfo,
9145  const char* name) const
9146 {
9147  R__LOCKGUARD(gInterpreterMutex);
9148  TClingTypedefInfo* TClinginfo = (TClingTypedefInfo*) tinfo;
9149  TClinginfo->Init(name);
9150 }
9151 
9152 ////////////////////////////////////////////////////////////////////////////////
9153 
9154 bool TCling::TypedefInfo_IsValid(TypedefInfo_t* tinfo) const
9155 {
9156  TClingTypedefInfo* TClinginfo = (TClingTypedefInfo*) tinfo;
9157  return TClinginfo->IsValid();
9158 }
9159 
9160 ////////////////////////////////////////////////////////////////////////////////
9161 
9162 Int_t TCling::TypedefInfo_Next(TypedefInfo_t* tinfo) const
9163 {
9164  TClingTypedefInfo* TClinginfo = (TClingTypedefInfo*) tinfo;
9165  return TClinginfo->Next();
9166 }
9167 
9168 ////////////////////////////////////////////////////////////////////////////////
9169 
9170 Long_t TCling::TypedefInfo_Property(TypedefInfo_t* tinfo) const
9171 {
9172  TClingTypedefInfo* TClinginfo = (TClingTypedefInfo*) tinfo;
9173  return TClinginfo->Property();
9174 }
9175 
9176 ////////////////////////////////////////////////////////////////////////////////
9177 
9178 int TCling::TypedefInfo_Size(TypedefInfo_t* tinfo) const
9179 {
9180  TClingTypedefInfo* TClinginfo = (TClingTypedefInfo*) tinfo;
9181  return TClinginfo->Size();
9182 }
9183 
9184 ////////////////////////////////////////////////////////////////////////////////
9185 
9186 const char* TCling::TypedefInfo_TrueName(TypedefInfo_t* tinfo) const
9187 {
9188  TClingTypedefInfo* TClinginfo = (TClingTypedefInfo*) tinfo;
9189  return TClinginfo->TrueName(*fNormalizedCtxt);
9190 }
9191 
9192 ////////////////////////////////////////////////////////////////////////////////
9193 
9194 const char* TCling::TypedefInfo_Name(TypedefInfo_t* tinfo) const
9195 {
9196  TClingTypedefInfo* TClinginfo = (TClingTypedefInfo*) tinfo;
9197  return TClinginfo->Name();
9198 }
9199 
9200 ////////////////////////////////////////////////////////////////////////////////
9201 
9202 const char* TCling::TypedefInfo_Title(TypedefInfo_t* tinfo) const
9203 {
9204  TClingTypedefInfo* TClinginfo = (TClingTypedefInfo*) tinfo;
9205  return TClinginfo->Title();
9206 }
9207 
9208 ////////////////////////////////////////////////////////////////////////////////
9209 
9210 void TCling::SnapshotMutexState(ROOT::TVirtualRWMutex* mtx)
9211 {
9212  if (!fInitialMutex.back()) {
9213  if (fInitialMutex.back().fRecurseCount) {
9214  Error("SnapshotMutexState", "fRecurseCount != 0 even though initial mutex state is unset!");
9215  }
9216  fInitialMutex.back().fState = mtx->GetStateBefore();
9217  }
9218  // We will "forget" this lock once we backed out of all interpreter frames.
9219  // Here we are entering one, so ++.
9220  ++fInitialMutex.back().fRecurseCount;
9221 }
9222 
9223 ////////////////////////////////////////////////////////////////////////////////
9224 
9225 void TCling::ForgetMutexState()
9226 {
9227  if (!fInitialMutex.back())
9228  return;
9229  if (fInitialMutex.back().fRecurseCount == 0) {
9230  Error("ForgetMutexState", "mutex state's recurse count already 0!");
9231  }
9232  else if (--fInitialMutex.back().fRecurseCount == 0) {
9233  // We have returned from all interpreter frames. Reset the initial lock state.
9234  fInitialMutex.back().fState.reset();
9235  }
9236 }
9237 
9238 ////////////////////////////////////////////////////////////////////////////////
9239 /// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
9240 
9241 void TCling::ApplyToInterpreterMutex(void *delta)
9242 {
9243  R__ASSERT(!fInitialMutex.empty() && "Inconsistent state of fInitialMutex!");
9244  if (gInterpreterMutex) {
9245  if (delta) {
9246  auto typedDelta = static_cast<TVirtualRWMutex::StateDelta *>(delta);
9247  std::unique_ptr<TVirtualRWMutex::StateDelta> uniqueP{typedDelta};
9248  gCoreMutex->Apply(std::move(uniqueP));
9249  }
9250  }
9251  fInitialMutex.pop_back();
9252 }
9253 
9254 ////////////////////////////////////////////////////////////////////////////////
9255 /// Reset the interpreter lock to the state it had before interpreter-related
9256 /// calls happened.
9257 
9258 void *TCling::RewindInterpreterMutex()
9259 {
9260  if (fInitialMutex.back()) {
9261  std::unique_ptr<TVirtualRWMutex::StateDelta> uniqueP = gCoreMutex->Rewind(*fInitialMutex.back().fState);
9262  // Need to start a new recurse count.
9263  fInitialMutex.emplace_back();
9264  return uniqueP.release();
9265  }
9266  // Need to start a new recurse count.
9267  fInitialMutex.emplace_back();
9268  return nullptr;
9269 }