-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathTROOT.cxx
More file actions
3508 lines (2998 loc) · 122 KB
/
TROOT.cxx
File metadata and controls
3508 lines (2998 loc) · 122 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @(#)root/base:$Id$
// Author: Rene Brun 08/12/94
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TROOT
\ingroup Base
ROOT top level object description.
The TROOT object is the entry point to the ROOT system.
The single instance of TROOT is accessible via the global gROOT.
Using the gROOT pointer one has access to basically every object
created in a ROOT based program. The TROOT object is essentially a
container of several lists pointing to the main ROOT objects.
The following lists are accessible from gROOT object:
~~~ {.cpp}
gROOT->GetListOfClasses
gROOT->GetListOfColors
gROOT->GetListOfTypes
gROOT->GetListOfGlobals
gROOT->GetListOfGlobalFunctions
gROOT->GetListOfFiles
gROOT->GetListOfMappedFiles
gROOT->GetListOfSockets
gROOT->GetListOfSecContexts
gROOT->GetListOfCanvases
gROOT->GetListOfStyles
gROOT->GetListOfFunctions
gROOT->GetListOfSpecials (for example graphical cuts)
gROOT->GetListOfGeometries
gROOT->GetListOfBrowsers
gROOT->GetListOfCleanups
gROOT->GetListOfMessageHandlers
~~~
The TROOT class provides also many useful services:
- Get pointer to an object in any of the lists above
- Time utilities TROOT::Time
The ROOT object must be created as a static object. An example
of a main program creating an interactive version is shown below:
### Example of a main program
~~~ {.cpp}
#include "TRint.h"
int main(int argc, char **argv)
{
TRint *theApp = new TRint("ROOT example", &argc, argv);
// Init Intrinsics, build all windows, and enter event loop
theApp->Run();
return(0);
}
~~~
*/
#include <ROOT/RConfig.hxx>
#include <ROOT/TErrorDefaultHandler.hxx>
#include <ROOT/RVersion.hxx>
#include "RConfigure.h"
#include "RConfigOptions.h"
#include <atomic>
#include <filesystem>
#include <string>
#include <map>
#include <sstream>
#include <set>
#include <cstdlib>
#ifdef WIN32
#include <io.h>
#include "Windows4Root.h"
#include <Psapi.h>
#define RTLD_DEFAULT ((void *)::GetModuleHandle(NULL))
//#define dlsym(library, function_name) ::GetProcAddress((HMODULE)library, function_name)
#define dlopen(library_name, flags) ::LoadLibrary(library_name)
#define dlclose(library) ::FreeLibrary((HMODULE)library)
char *dlerror() {
static char Msg[1000];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), Msg,
sizeof(Msg), NULL);
return Msg;
}
FARPROC dlsym(void *library, const char *function_name)
{
HMODULE hMods[1024];
DWORD cbNeeded;
FARPROC address = NULL;
unsigned int i;
if (library == RTLD_DEFAULT) {
if (EnumProcessModules(::GetCurrentProcess(), hMods, sizeof(hMods), &cbNeeded)) {
for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) {
address = ::GetProcAddress((HMODULE)hMods[i], function_name);
if (address)
return address;
}
}
return address;
} else {
return ::GetProcAddress((HMODULE)library, function_name);
}
}
#elif defined(__APPLE__)
#include <dlfcn.h>
#include <mach-o/dyld.h>
#else
#include <dlfcn.h>
#include <link.h>
#endif
#include <iostream>
#include "ROOT/FoundationUtils.hxx"
#include "TROOT.h"
#include "TClass.h"
#include "TClassEdit.h"
#include "TClassGenerator.h"
#include "TDataType.h"
#include "TStyle.h"
#include "TObjectTable.h"
#include "TClassTable.h"
#include "TSystem.h"
#include "THashList.h"
#include "TObjArray.h"
#include "TEnv.h"
#include "TError.h"
#include "TColor.h"
#include "TGlobal.h"
#include "TFunction.h"
#include "TVirtualPad.h"
#include "TBrowser.h"
#include "TSystemDirectory.h"
#include "TApplication.h"
#include "TInterpreter.h"
#include "TGuiFactory.h"
#include "TMessageHandler.h"
#include "TFolder.h"
#include "TQObject.h"
#include "TProcessUUID.h"
#include "TPluginManager.h"
#include "TVirtualMutex.h"
#include "TListOfTypes.h"
#include "TListOfDataMembers.h"
#include "TListOfEnumsWithLock.h"
#include "TListOfFunctions.h"
#include "TListOfFunctionTemplates.h"
#include "TFunctionTemplate.h"
#include "ThreadLocalStorage.h"
#include "TVirtualMapFile.h"
#include "TVirtualRWMutex.h"
#include "TVirtualX.h"
#if defined(R__UNIX)
#if defined(R__HAS_COCOA)
#include "TMacOSXSystem.h"
#include "TUrl.h"
#else
#include "TUnixSystem.h"
#endif
#elif defined(R__WIN32)
#include "TWinNTSystem.h"
#endif
extern "C" void R__SetZipMode(int);
static DestroyInterpreter_t *gDestroyInterpreter = nullptr;
static void *gInterpreterLib = nullptr;
// Mutex for protection of concurrent gROOT access
TVirtualMutex* gROOTMutex = nullptr;
ROOT::TVirtualRWMutex *ROOT::gCoreMutex = nullptr;
// For accessing TThread::Tsd indirectly.
void **(*gThreadTsd)(void*,Int_t) = nullptr;
//-------- Names of next three routines are a small homage to CMZ --------------
////////////////////////////////////////////////////////////////////////////////
/// Return version id as an integer, i.e. "2.22/04" -> 22204.
static Int_t IVERSQ()
{
Int_t maj, min, cycle;
sscanf(ROOT_RELEASE, "%d.%d.%d", &maj, &min, &cycle);
return 10000*maj + 100*min + cycle;
}
////////////////////////////////////////////////////////////////////////////////
/// Return built date as integer, i.e. "Apr 28 2000" -> 20000428.
static Int_t IDATQQ(const char *date)
{
if (!date) {
Error("TSystem::IDATQQ", "nullptr date string, expected e.g. 'Dec 21 2022'");
return -1;
}
static const char *months[] = {"Jan","Feb","Mar","Apr","May",
"Jun","Jul","Aug","Sep","Oct",
"Nov","Dec"};
char sm[12];
Int_t yy, mm=0, dd;
if (sscanf(date, "%s %d %d", sm, &dd, &yy) != 3) {
Error("TSystem::IDATQQ", "Cannot parse date string '%s', expected e.g. 'Dec 21 2022'", date);
return -1;
}
for (int i = 0; i < 12; i++)
if (!strncmp(sm, months[i], 3)) {
mm = i+1;
break;
}
return 10000*yy + 100*mm + dd;
}
////////////////////////////////////////////////////////////////////////////////
/// Return built time as integer (with min precision), i.e.
/// "17:32:37" -> 1732.
static Int_t ITIMQQ(const char *time)
{
Int_t hh, mm, ss;
sscanf(time, "%d:%d:%d", &hh, &mm, &ss);
return 100*hh + mm;
}
////////////////////////////////////////////////////////////////////////////////
/// Clean up at program termination before global objects go out of scope.
static void CleanUpROOTAtExit()
{
if (gROOT) {
R__LOCKGUARD(gROOTMutex);
if (gROOT->GetListOfFiles())
gROOT->GetListOfFiles()->Delete("slow");
if (gROOT->GetListOfSockets())
gROOT->GetListOfSockets()->Delete();
if (gROOT->GetListOfMappedFiles())
gROOT->GetListOfMappedFiles()->Delete("slow");
if (gROOT->GetListOfClosedObjects())
gROOT->GetListOfClosedObjects()->Delete("slow");
}
}
////////////////////////////////////////////////////////////////////////////////
/// A module and its headers. Intentionally not a copy:
/// If these strings end up in this struct they are
/// long lived by definition because they get passed in
/// before initialization of TCling.
namespace {
struct ModuleHeaderInfo_t {
ModuleHeaderInfo_t(const char* moduleName,
const char** headers,
const char** includePaths,
const char* payloadCode,
const char* fwdDeclCode,
void (*triggerFunc)(),
const TROOT::FwdDeclArgsToKeepCollection_t& fwdDeclsArgToSkip,
const char **classesHeaders,
bool hasCxxModule):
fModuleName(moduleName),
fHeaders(headers),
fPayloadCode(payloadCode),
fFwdDeclCode(fwdDeclCode),
fIncludePaths(includePaths),
fTriggerFunc(triggerFunc),
fClassesHeaders(classesHeaders),
fFwdNargsToKeepColl(fwdDeclsArgToSkip),
fHasCxxModule(hasCxxModule) {}
const char* fModuleName; // module name
const char** fHeaders; // 0-terminated array of header files
const char* fPayloadCode; // Additional code to be given to cling at library load
const char* fFwdDeclCode; // Additional code to let cling know about selected classes and functions
const char** fIncludePaths; // 0-terminated array of header files
void (*fTriggerFunc)(); // Pointer to the dict initialization used to find the library name
const char** fClassesHeaders; // 0-terminated list of classes and related header files
const TROOT::FwdDeclArgsToKeepCollection_t fFwdNargsToKeepColl; // Collection of
// pairs of template fwd decls and number of
bool fHasCxxModule; // Whether this module has a C++ module alongside it.
};
std::vector<ModuleHeaderInfo_t>& GetModuleHeaderInfoBuffer() {
static std::vector<ModuleHeaderInfo_t> moduleHeaderInfoBuffer;
return moduleHeaderInfoBuffer;
}
}
Int_t TROOT::fgDirLevel = 0;
Bool_t TROOT::fgRootInit = kFALSE;
static void at_exit_of_TROOT() {
if (ROOT::Internal::gROOTLocal)
ROOT::Internal::gROOTLocal->~TROOT();
}
// This local static object initializes the ROOT system
namespace ROOT {
namespace Internal {
class TROOTAllocator {
// Simple wrapper to separate, time-wise, the call to the
// TROOT destructor and the actual free-ing of the memory.
//
// Since the interpreter implementation (currently TCling) is
// loaded via dlopen by libCore, the destruction of its global
// variable (i.e. in particular clang's) is scheduled before
// those in libCore so we need to schedule the call to the TROOT
// destructor before that *but* we want to make sure the memory
// stay around until libCore itself is unloaded so that code
// using gROOT can 'properly' check for validity.
//
// The order of loading for is:
// libCore.so
// libRint.so
// ... anything other library hard linked to the executable ...
// ... for example libEvent
// libCling.so
// ... other libraries like libTree for example ....
// and the destruction order is (of course) the reverse.
// By default the unloading of the dictionary, does use
// the service of the interpreter ... which of course
// fails if libCling is already unloaded by that information
// has not been registered per se.
//
// To solve this problem, we now schedule the destruction
// of the TROOT object to happen _just_ before the
// unloading/destruction of libCling so that we can
// maximize the amount of clean-up we can do correctly
// and we can still allocate the TROOT object's memory
// statically.
//
union {
TROOT fObj;
char fHolder[sizeof(TROOT)];
};
public:
TROOTAllocator(): fObj("root", "The ROOT of EVERYTHING")
{}
~TROOTAllocator() {
if (gROOTLocal) {
gROOTLocal->~TROOT();
}
}
};
// The global gROOT is defined to be a function (ROOT::GetROOT())
// which itself is dereferencing a function pointer.
// Initially this function pointer's value is & GetROOT1 whose role is to
// create and initialize the TROOT object itself.
// At the very end of the TROOT constructor the value of the function pointer
// is switch to & GetROOT2 whose role is to initialize the interpreter.
// This mechanism was primarily intended to fix the issues with order in which
// global TROOT and LLVM globals are initialized. TROOT was initializing
// Cling, but Cling could not be used yet due to LLVM globals not being
// Initialized yet. The solution is to delay initializing the interpreter in
// TROOT till after main() when all LLVM globals are initialized.
// Technically, the mechanism used actually delay the interpreter
// initialization until the first use of gROOT *after* the end of the
// TROOT constructor.
// So to delay until after the start of main, we also made sure that none
// of the ROOT code (mostly the dictionary code) used during library loading
// is using gROOT (directly or indirectly).
// In practice, the initialization of the interpreter is now delayed until
// the first use gROOT (or gInterpreter) after the start of main (but user
// could easily break this by using gROOT in their library initialization
// code).
extern TROOT *gROOTLocal;
TROOT *GetROOT1() {
if (gROOTLocal)
return gROOTLocal;
static TROOTAllocator alloc;
return gROOTLocal;
}
TROOT *GetROOT2() {
static Bool_t initInterpreter = kFALSE;
if (!initInterpreter) {
initInterpreter = kTRUE;
gROOTLocal->InitInterpreter();
// Load and init threads library
gROOTLocal->InitThreads();
}
return gROOTLocal;
}
typedef TROOT *(*GetROOTFun_t)();
static GetROOTFun_t gGetROOT = &GetROOT1;
static Func_t GetSymInLibImt(const char *funcname)
{
const static bool loadSuccess = dlsym(RTLD_DEFAULT, "usedToIdentifyRootClingByDlSym")? false : 0 <= gSystem->Load("libImt");
if (loadSuccess) {
if (auto sym = gSystem->DynFindSymbol(nullptr, funcname)) {
return sym;
} else {
Error("GetSymInLibImt", "Cannot get symbol %s.", funcname);
}
}
return nullptr;
}
//////////////////////////////////////////////////////////////////////////////
/// Globally enables the parallel branch processing, which is a case of
/// implicit multi-threading (IMT) in ROOT, activating the required locks.
/// This IMT use case, implemented in TTree::GetEntry, spawns a task for
/// each branch of the tree. Therefore, a task takes care of the reading,
/// decompression and deserialisation of a given branch.
void EnableParBranchProcessing()
{
#ifdef R__USE_IMT
static void (*sym)() = (void(*)())Internal::GetSymInLibImt("ROOT_TImplicitMT_EnableParBranchProcessing");
if (sym)
sym();
#else
::Warning("EnableParBranchProcessing", "Cannot enable parallel branch processing, please build ROOT with -Dimt=ON");
#endif
}
//////////////////////////////////////////////////////////////////////////////
/// Globally disables the IMT use case of parallel branch processing,
/// deactivating the corresponding locks.
void DisableParBranchProcessing()
{
#ifdef R__USE_IMT
static void (*sym)() = (void(*)())Internal::GetSymInLibImt("ROOT_TImplicitMT_DisableParBranchProcessing");
if (sym)
sym();
#else
::Warning("DisableParBranchProcessing", "Cannot disable parallel branch processing, please build ROOT with -Dimt=ON");
#endif
}
//////////////////////////////////////////////////////////////////////////////
/// Returns true if parallel branch processing is enabled.
Bool_t IsParBranchProcessingEnabled()
{
#ifdef R__USE_IMT
static Bool_t (*sym)() = (Bool_t(*)())Internal::GetSymInLibImt("ROOT_TImplicitMT_IsParBranchProcessingEnabled");
if (sym)
return sym();
else
return kFALSE;
#else
return kFALSE;
#endif
}
////////////////////////////////////////////////////////////////////////////////
/// Keeps track of the status of ImplicitMT w/o resorting to the load of
/// libImt
static Bool_t &IsImplicitMTEnabledImpl()
{
static Bool_t isImplicitMTEnabled = kFALSE;
return isImplicitMTEnabled;
}
////////////////////////////////////////////////////////////////////////////////
/// \brief Test if objects such as TH1-derived classes should be implicitly
/// registered to gDirectory.
/// A default can be set in a .rootrc using "Root.ImplicitOwnership: 1" or setting
/// the environment variable "ROOT_IMPLICIT_OWNERSHIP=0".
static std::atomic_bool &IsImplicitOwnershipEnabledImpl()
{
static std::atomic_bool initCompleted = false;
static std::atomic_bool implicitOwnership = true;
if (!initCompleted.load(std::memory_order_relaxed)) {
R__LOCKGUARD(gROOTMutex);
// test again, because another thread might have raced us here
if (!initCompleted) {
std::stringstream infoMessage;
if (gEnv) {
const auto desiredValue = gEnv->GetValue("Root.ImplicitOwnership", -1);
if (desiredValue == 0) {
implicitOwnership = false;
infoMessage << "Implicit object ownership switched off in rootrc\n";
} else if (desiredValue == 1) {
implicitOwnership = true;
infoMessage << "Implicit object ownership switched on in rootrc\n";
} else if (desiredValue != -1) {
Error("TROOT", "Root.ImplicitOwnership should be 0 or 1");
}
}
if (auto env = gSystem->Getenv("ROOT_IMPLICIT_OWNERSHIP"); env) {
int desiredValue = -1;
try {
desiredValue = std::stoi(env);
} catch (std::invalid_argument &e) {
Error("TROOT", "ROOT_IMPLICIT_OWNERSHIP should be 0 or 1");
}
if (desiredValue == 0) {
implicitOwnership = false;
infoMessage << "Implicit object ownership switched off using ROOT_IMPLICIT_OWNERSHIP\n";
} else if (desiredValue == 1) {
implicitOwnership = true;
infoMessage << "Implicit object ownership switched on using ROOT_IMPLICIT_OWNERSHIP\n";
} else {
Error("TROOT", "ROOT_IMPLICIT_OWNERSHIP should be 0 or 1");
}
}
if (!infoMessage.str().empty()) {
Info("TROOT", "%s", infoMessage.str().c_str());
}
initCompleted = true;
}
}
return implicitOwnership;
}
} // end of Internal sub namespace
// back to ROOT namespace
TROOT *GetROOT() {
return (*Internal::gGetROOT)();
}
TString &GetMacroPath() {
static TString macroPath;
return macroPath;
}
// clang-format off
////////////////////////////////////////////////////////////////////////////////
/// Enables the global mutex to make ROOT thread safe/aware.
///
/// The following becomes safe:
/// - concurrent construction and destruction of TObjects, including the ones registered in ROOT's global lists (e.g. gROOT->GetListOfCleanups(), gROOT->GetListOfFiles())
/// - concurrent usage of _different_ ROOT objects from different threads, including ones with global state (e.g. TFile, TTree, TChain) with the exception of graphics classes (e.g. TCanvas)
/// - concurrent calls to ROOT's type system classes, e.g. TClass and TEnum
/// - concurrent calls to the interpreter through gInterpreter
/// - concurrent loading of ROOT plug-ins
///
/// In addition, gDirectory, gFile and gPad become a thread-local variable.
/// In all threads, gDirectory defaults to gROOT, a singleton which supports thread-safe insertion and deletion of contents.
/// gFile and gPad default to nullptr, as it is for single-thread programs.
///
/// The ROOT graphics subsystem is not made thread-safe by this method. In particular drawing or printing different
/// canvases from different threads (and analogous operations such as invoking `Draw` on a `TObject`) is not thread-safe.
///
/// Note that there is no `DisableThreadSafety()`. ROOT's thread-safety features cannot be disabled once activated.
// clang-format on
void EnableThreadSafety()
{
static void (*sym)() = (void(*)())Internal::GetSymInLibImt("ROOT_TThread_Initialize");
if (sym)
sym();
}
////////////////////////////////////////////////////////////////////////////////
/// @param[in] numthreads Number of threads to use. If not specified or
/// set to zero, the number of threads is automatically
/// decided by the implementation. Any other value is
/// used as a hint.
///
/// ROOT must be built with the compilation flag `imt=ON` for this feature to be available.
/// The following objects and methods automatically take advantage of
/// multi-threading if a call to `EnableImplicitMT` has been made before usage:
///
/// - RDataFrame internally runs the event-loop by parallelizing over clusters of entries
/// - TTree::GetEntry reads multiple branches in parallel
/// - TTree::FlushBaskets writes multiple baskets to disk in parallel
/// - TTreeCacheUnzip decompresses the baskets contained in a TTreeCache in parallel
/// - THx::Fit performs in parallel the evaluation of the objective function over the data
/// - TMVA::DNN trains the deep neural networks in parallel
/// - TMVA::BDT trains the classifier in parallel and multiclass BDTs are evaluated in parallel
///
/// EnableImplicitMT calls in turn EnableThreadSafety.
/// The 'numthreads' parameter allows to control the number of threads to
/// be used by the implicit multi-threading. However, this parameter is just
/// a hint for ROOT: it will try to satisfy the request if the execution
/// scenario allows it. For example, if ROOT is configured to use an external
/// scheduler, setting a value for 'numthreads' might not have any effect.
/// The maximum number of threads can be influenced by the environment
/// variable `ROOT_MAX_THREADS`: `export ROOT_MAX_THREADS=2` will try to set
/// the maximum number of active threads to 2, if the scheduling library
/// (such as tbb) "permits".
///
/// \note Use `DisableImplicitMT()` to disable multi-threading (some locks will remain in place as
/// described in EnableThreadSafety()). `EnableImplicitMT(1)` creates a thread-pool of size 1.
void EnableImplicitMT(UInt_t numthreads)
{
#ifdef R__USE_IMT
if (ROOT::Internal::IsImplicitMTEnabledImpl())
return;
EnableThreadSafety();
static void (*sym)(UInt_t) = (void(*)(UInt_t))Internal::GetSymInLibImt("ROOT_TImplicitMT_EnableImplicitMT");
if (sym)
sym(numthreads);
ROOT::Internal::IsImplicitMTEnabledImpl() = true;
#else
::Warning("EnableImplicitMT", "Cannot enable implicit multi-threading with %d threads, please build ROOT with -Dimt=ON", numthreads);
#endif
}
////////////////////////////////////////////////////////////////////////////////
/// @param[in] config Configuration to use. The default is kWholeMachine, which
/// will create a thread pool that spans the whole machine.
///
/// EnableImplicitMT calls in turn EnableThreadSafety.
/// If ImplicitMT is already enabled, this function does nothing.
void EnableImplicitMT(ROOT::EIMTConfig config)
{
#ifdef R__USE_IMT
if (ROOT::Internal::IsImplicitMTEnabledImpl())
return;
EnableThreadSafety();
static void (*sym)(ROOT::EIMTConfig) =
(void (*)(ROOT::EIMTConfig))Internal::GetSymInLibImt("ROOT_TImplicitMT_EnableImplicitMT_Config");
if (sym)
sym(config);
ROOT::Internal::IsImplicitMTEnabledImpl() = true;
#else
::Warning("EnableImplicitMT",
"Cannot enable implicit multi-threading with config %d, please build ROOT with -Dimt=ON",
static_cast<int>(config));
#endif
}
////////////////////////////////////////////////////////////////////////////////
/// Disables the implicit multi-threading in ROOT (see EnableImplicitMT).
void DisableImplicitMT()
{
#ifdef R__USE_IMT
static void (*sym)() = (void(*)())Internal::GetSymInLibImt("ROOT_TImplicitMT_DisableImplicitMT");
if (sym)
sym();
ROOT::Internal::IsImplicitMTEnabledImpl() = kFALSE;
#else
::Warning("DisableImplicitMT", "Cannot disable implicit multi-threading, please build ROOT with -Dimt=ON");
#endif
}
////////////////////////////////////////////////////////////////////////////////
/// Returns true if the implicit multi-threading in ROOT is enabled.
Bool_t IsImplicitMTEnabled()
{
return ROOT::Internal::IsImplicitMTEnabledImpl();
}
////////////////////////////////////////////////////////////////////////////////
/// Returns the size of ROOT's thread pool
UInt_t GetThreadPoolSize()
{
#ifdef R__USE_IMT
static UInt_t (*sym)() = (UInt_t(*)())Internal::GetSymInLibImt("ROOT_MT_GetThreadPoolSize");
if (sym)
return sym();
else
return 0;
#else
return 0;
#endif
}
namespace Experimental {
////////////////////////////////////////////////////////////////////////////////
/// \brief Switch ROOT's object ownership model to ROOT 6 mode.
///
/// In ROOT 6 mode, ROOT will implicitly assign ownership of histograms or TTrees
/// to the current \ref gDirectory, for example to the last TFile that was opened.
/// \code{.cpp}
/// TFile file(...);
/// TTree* tree = new TTree(...);
/// TH1D* histo = new TH1D(...);
/// file.Write(); // Both tree and histogram are in the file now
/// \endcode
///
/// In ROOT 7 mode, these objects won't register themselves to the current gDirectory,
/// so they are fully owned by the user. To write these to files, the user needs to do
/// one of the following:
/// - Explicitly transfer ownership:
/// \code{.cpp}
/// TFile file(...);
/// TTree* tree = new TTree(...);
/// tree->SetDirectory(&file);
/// \endcode
/// - Keep ownership of the object, but write explicitly:
/// \code{.cpp}
/// TFile file(...);
/// std::unique_ptr<TH1D> histo{new TH1D(...)};
/// file.WriteObject(histo.get(), "HistogramName");
/// file.Close();
/// // histo is still valid
/// \endcode
///
/// \note This setting has higher priority than TH1::AddDirectoryStatus() and TDirectory::AddDirectoryStatus().
/// These two will always evaluate to false if implicit ownership is off.
///
void EnableImplicitObjectOwnership()
{
ROOT::Internal::IsImplicitOwnershipEnabledImpl() = true;
}
////////////////////////////////////////////////////////////////////////////////
/// \brief Switch ROOT's object ownership model to ROOT 7 mode (no ownership).
/// \copydetails ROOT::Experimental::EnableImplicitObjectOwnership()
void DisableImplicitObjectOwnership()
{
ROOT::Internal::IsImplicitOwnershipEnabledImpl() = false;
}
////////////////////////////////////////////////////////////////////////////////
/// Test whether the current directory should take ownership of objects such as
/// TH1-derived classes, TTree, TEntryList etc.
/// \copydetails ROOT::Experimental::EnableImplicitObjectOwnership()
bool IsImplicitObjectOwnershipEnabled()
{
return ROOT::Internal::IsImplicitOwnershipEnabledImpl();
}
} // namespace Experimental
} // end of ROOT namespace
TROOT *ROOT::Internal::gROOTLocal = ROOT::GetROOT();
// Global debug flag (set to > 0 to get debug output).
// Can be set either via the interpreter (gDebug is exported to CINT),
// via the rootrc resource "Root.Debug", via the shell environment variable
// ROOTDEBUG, or via the debugger.
Int_t gDebug;
////////////////////////////////////////////////////////////////////////////////
/// Default ctor.
TROOT::TROOT() : TDirectory() {}
////////////////////////////////////////////////////////////////////////////////
/// Initialize the ROOT system. The creation of the TROOT object initializes
/// the ROOT system. It must be the first ROOT related action that is
/// performed by a program. The TROOT object must be created on the stack
/// (can not be called via new since "operator new" is protected). The
/// TROOT object is either created as a global object (outside the main()
/// program), or it is one of the first objects created in main().
/// Make sure that the TROOT object stays in scope for as long as ROOT
/// related actions are performed. TROOT is a so called singleton so
/// only one instance of it can be created. The single TROOT object can
/// always be accessed via the global pointer gROOT.
/// The name and title arguments can be used to identify the running
/// application. The initfunc argument can contain an array of
/// function pointers (last element must be 0). These functions are
/// executed at the end of the constructor. This way one can easily
/// extend the ROOT system without adding permanent dependencies
/// (e.g. the graphics system is initialized via such a function).
TROOT::TROOT(const char *name, const char *title, VoidFuncPtr_t *initfunc) : TDirectory()
{
if (fgRootInit || ROOT::Internal::gROOTLocal) {
//Warning("TROOT", "only one instance of TROOT allowed");
return;
}
R__LOCKGUARD(gROOTMutex);
ROOT::Internal::gROOTLocal = this;
gDirectory = nullptr;
SetName(name);
SetTitle(title);
// will be used by global "operator delete" so make sure it is set
// before anything is deleted
fMappedFiles = nullptr;
// create already here, but only initialize it after gEnv has been created
gPluginMgr = fPluginManager = new TPluginManager;
// Initialize Operating System interface
InitSystem();
// Initialize static directory functions
GetRootSys();
GetBinDir();
GetLibDir();
GetIncludeDir();
GetEtcDir();
GetDataDir();
GetDocDir();
GetMacroDir();
GetTutorialDir();
GetIconPath();
GetTTFFontDir();
gRootDir = GetRootSys().Data();
TDirectory::BuildDirectory(nullptr, nullptr);
// Initialize interface to CINT C++ interpreter
fVersionInt = 0; // check in TROOT dtor in case TCling fails
fClasses = nullptr; // might be checked via TCling ctor
fEnums = nullptr;
fConfigOptions = R__CONFIGUREOPTIONS;
fConfigFeatures = R__CONFIGUREFEATURES;
fVersion = ROOT_RELEASE;
fVersionCode = ROOT_VERSION_CODE;
fVersionInt = IVERSQ();
fVersionDate = IDATQQ(ROOT_RELEASE_DATE);
fVersionTime = ITIMQQ(ROOT_RELEASE_TIME);
fBuiltDate = IDATQQ(__DATE__);
fBuiltTime = ITIMQQ(__TIME__);
ReadGitInfo();
fClasses = new THashTable(800,3); fClasses->UseRWLock();
//fIdMap = new IdMap_t;
fStreamerInfo = new TObjArray(100); fStreamerInfo->UseRWLock();
fClassGenerators = new TList;
// usedToIdentifyRootClingByDlSym is available when TROOT is part of
// rootcling.
if (!dlsym(RTLD_DEFAULT, "usedToIdentifyRootClingByDlSym")) {
// initialize plugin manager early
fPluginManager->LoadHandlersFromEnv(gEnv);
}
TSystemDirectory *workdir = new TSystemDirectory("workdir", gSystem->WorkingDirectory());
auto setNameLocked = [](TSeqCollection *l, const char *collection_name) {
l->SetName(collection_name);
l->UseRWLock();
return l;
};
fTimer = 0;
fApplication = nullptr;
fColors = setNameLocked(new TObjArray(1000), "ListOfColors");
fColors->SetOwner();
fTypes = nullptr;
fGlobals = nullptr;
fGlobalFunctions = nullptr;
// fList was created in TDirectory::Build but with different sizing.
delete fList;
fList = new THashList(1000,3); fList->UseRWLock();
fClosedObjects = setNameLocked(new TList, "ClosedFiles");
fFiles = setNameLocked(new TList, "Files");
fMappedFiles = setNameLocked(new TList, "MappedFiles");
fSockets = setNameLocked(new TList, "Sockets");
fCanvases = setNameLocked(new TList, "Canvases");
fStyles = setNameLocked(new TList, "Styles");
fFunctions = setNameLocked(new TList, "Functions");
fTasks = setNameLocked(new TList, "Tasks");
fGeometries = setNameLocked(new TList, "Geometries");
fBrowsers = setNameLocked(new TList, "Browsers");
fSpecials = setNameLocked(new TList, "Specials");
fBrowsables = (TList*)setNameLocked(new TList, "Browsables");
fCleanups = setNameLocked(new THashList, "Cleanups");
fMessageHandlers = setNameLocked(new TList, "MessageHandlers");
fSecContexts = setNameLocked(new TList, "SecContexts");
fClipboard = setNameLocked(new TList, "Clipboard");
fDataSets = setNameLocked(new TList, "DataSets");
fTypes = new TListOfTypes; fTypes->UseRWLock();
TProcessID::AddProcessID();
fUUIDs = new TProcessUUID();
fRootFolder = new TFolder();
fRootFolder->SetName("root");
fRootFolder->SetTitle("root of all folders");
fRootFolder->AddFolder("Classes", "List of Active Classes",fClasses);
fRootFolder->AddFolder("Colors", "List of Active Colors",fColors);
fRootFolder->AddFolder("MapFiles", "List of MapFiles",fMappedFiles);
fRootFolder->AddFolder("Sockets", "List of Socket Connections",fSockets);
fRootFolder->AddFolder("Canvases", "List of Canvases",fCanvases);
fRootFolder->AddFolder("Styles", "List of Styles",fStyles);
fRootFolder->AddFolder("Functions", "List of Functions",fFunctions);
fRootFolder->AddFolder("Tasks", "List of Tasks",fTasks);
fRootFolder->AddFolder("Geometries","List of Geometries",fGeometries);
fRootFolder->AddFolder("Browsers", "List of Browsers",fBrowsers);
fRootFolder->AddFolder("Specials", "List of Special Objects",fSpecials);
fRootFolder->AddFolder("Handlers", "List of Message Handlers",fMessageHandlers);
fRootFolder->AddFolder("Cleanups", "List of RecursiveRemove Collections",fCleanups);
fRootFolder->AddFolder("StreamerInfo","List of Active StreamerInfo Classes",fStreamerInfo);
fRootFolder->AddFolder("SecContexts","List of Security Contexts",fSecContexts);
fRootFolder->AddFolder("ROOT Memory","List of Objects in the gROOT Directory",fList);
fRootFolder->AddFolder("ROOT Files","List of Connected ROOT Files",fFiles);
// by default, add the list of files, tasks, canvases and browsers in the Cleanups list
fCleanups->Add(fCanvases); fCanvases->SetBit(kMustCleanup);
fCleanups->Add(fBrowsers); fBrowsers->SetBit(kMustCleanup);
fCleanups->Add(fTasks); fTasks->SetBit(kMustCleanup);
fCleanups->Add(fFiles); fFiles->SetBit(kMustCleanup);
fCleanups->Add(fClosedObjects); fClosedObjects->SetBit(kMustCleanup);
// And add TROOT's TDirectory personality
fCleanups->Add(fList);
fExecutingMacro= kFALSE;
fForceStyle = kFALSE;
fFromPopUp = kFALSE;
fInterrupt = kFALSE;
fEscape = kFALSE;
fMustClean = kTRUE;
fPrimitive = nullptr;
fSelectPad = nullptr;
fEditorMode = 0;
fDefCanvasName = "c1";
fEditHistograms= kFALSE;
fLineIsProcessing = 1; // This prevents WIN32 "Windows" thread to pick ROOT objects with mouse
gDirectory = this;
gPad = nullptr;
//set name of graphical cut class for the graphics editor
//cannot call SetCutClassName at this point because the TClass of TCutG
//is not yet build
fCutClassName = "TCutG";
// Create a default MessageHandler
new TMessageHandler((TClass*)nullptr);
// Create some styles
gStyle = nullptr;
TStyle::BuildStyles();
SetStyle(gEnv->GetValue("Canvas.Style", "Modern"));
// Setup default (batch) graphics and GUI environment
gBatchGuiFactory = new TGuiFactory;
gGuiFactory = gBatchGuiFactory;
gGXBatch = new TVirtualX("Batch", "ROOT Interface to batch graphics");
gVirtualX = gGXBatch;
if (gSystem->Getenv("ROOT_BATCH"))
fBatch = kTRUE;
else {
#if defined(R__WIN32) || defined(R__HAS_COCOA)
fBatch = kFALSE;
#else
if (gSystem->Getenv("DISPLAY"))
fBatch = kFALSE;
else
fBatch = kTRUE;
#endif
}
const char *webdisplay = gSystem->Getenv("ROOT_WEBDISPLAY");
if (!webdisplay || !*webdisplay)
webdisplay = gEnv->GetValue("WebGui.Display", "");
if (webdisplay && *webdisplay)
SetWebDisplay(webdisplay);
int i = 0;
while (initfunc && initfunc[i]) {
(initfunc[i])();
fBatch = kFALSE; // put system in graphics mode (backward compatible)
i++;
}
// Set initial/default list of browsable objects
fBrowsables->Add(fRootFolder, "root");
fBrowsables->Add(workdir, gSystem->WorkingDirectory());
fBrowsables->Add(fFiles, "ROOT Files");
atexit(CleanUpROOTAtExit);
ROOT::Internal::gGetROOT = &ROOT::Internal::GetROOT2;
}
////////////////////////////////////////////////////////////////////////////////
/// Clean up and free resources used by ROOT (files, network sockets,
/// shared memory segments, etc.).
TROOT::~TROOT()
{
using namespace ROOT::Internal;
if (gROOTLocal == this) {
// TMapFile must be closed before they are deleted, so run CloseFiles
// (possibly a second time if the application has an explicit TApplication
// object, but in that this is a no-op). TMapFile needs the slow close
// so that the custome operator delete can properly find out whether the
// memory being 'freed' is part of a memory mapped file or not.
CloseFiles();
// If the interpreter has not yet been initialized, don't bother
gGetROOT = &GetROOT1;