Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TSystem.cxx
Go to the documentation of this file.
1// @(#)root/base:$Id: 8944840ba34631ec28efc779647618db43c0eee5 $
2// Author: Fons Rademakers 15/09/95
3
4/*************************************************************************
5 * Copyright (C) 1995-2019, 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 TSystem
13\ingroup Base
14
15Abstract base class defining a generic interface to the underlying
16Operating System.
17This is not an ABC in the strict sense of the (C++) word. For
18every member function there is an implementation (often not more
19than a call to AbstractMethod() which prints a warning saying
20that the method should be overridden in a derived class), which
21allows a simple partial implementation for new OS'es.
22*/
23
26#include "strlcpy.h"
27#include "TSystem.h"
28#include "TApplication.h"
29#include "TException.h"
30#include "TROOT.h"
31#include "TClass.h"
32#include "TClassTable.h"
33#include "TEnv.h"
34#include "TOrdCollection.h"
35#include "TObject.h"
36#include "TInterpreter.h"
37#include "TRegexp.h"
38#include "TObjString.h"
39#include "TObjArray.h"
40#include "TError.h"
41#include "TPluginManager.h"
42#include "TUrl.h"
43#include "TVirtualMutex.h"
44#include "TVersionCheck.h"
45#define ROOT_compiledata_cxx
46#include "compiledata.h"
47#include "RConfigure.h"
48#include "THashList.h"
49#include "ThreadLocalStorage.h"
50
51#include <functional>
52#include <iostream>
53#include <fstream>
54#include <memory>
55#include <sstream>
56#include <string>
57#include <sys/stat.h>
58#include <set>
59
60#ifdef WIN32
61#include <algorithm>
62#include <io.h>
63#include "Windows4Root.h"
64#endif
65
66const char *gRootDir = nullptr;
67const char *gProgName = nullptr;
68const char *gProgPath = nullptr;
69
70TSystem *gSystem = nullptr;
71TFileHandler *gXDisplay = nullptr; // Display server event handler, set in TGClient
72
73static Int_t *gLibraryVersion = nullptr; // Set in TVersionCheck, used in Load()
74static Int_t gLibraryVersionIdx = 0; // Set in TVersionCheck, used in Load()
76
77// Pin vtable
79
80////////////////////////////////////////////////////////////////////////////////
81/// Create async event processor timer. Delay is in milliseconds.
82
84{
85 gROOT->SetInterrupt(kFALSE);
86 TurnOn();
87}
88
89////////////////////////////////////////////////////////////////////////////////
90/// Process events if timer did time out. Returns kTRUE if interrupt
91/// flag is set (by hitting a key in the canvas or selecting the
92/// Interrupt menu item in canvas or some other action).
93
95{
96 if (fTimeout) {
97 if (gSystem->ProcessEvents()) {
98 Remove();
99 return kTRUE;
100 } else {
101 Reset();
102 return kFALSE;
103 }
104 }
105 return kFALSE;
106}
107
108
109
110
112
113
114
115////////////////////////////////////////////////////////////////////////////////
116/// Strip off protocol string from specified path
117
118const char *TSystem::StripOffProto(const char *path, const char *proto)
119{
120 return !strncmp(path, proto, strlen(proto)) ? path + strlen(proto) : path;
121}
122
123////////////////////////////////////////////////////////////////////////////////
124/// Create a new OS interface.
125
126TSystem::TSystem(const char *name, const char *title) : TNamed(name, title)
127{
128 if (gSystem && name[0] != '-' && strcmp(name, "Generic"))
129 Error("TSystem", "only one instance of TSystem allowed");
130
131 if (!gLibraryVersion) {
133 memset(gLibraryVersion, 0, gLibraryVersionMax*sizeof(Int_t));
134 }
135}
136
137////////////////////////////////////////////////////////////////////////////////
138/// Delete the OS interface.
139
141{
142 if (fOnExitList) {
145 }
146
147 if (fSignalHandler) {
150 }
151
152 if (fFileHandler) {
155 }
156
160 }
161
162 if (fTimers) {
163 fTimers->Delete();
165 }
166
167 if (fCompiled) {
168 fCompiled->Delete();
170 }
171
172 if (fHelpers) {
173 fHelpers->Delete();
175 }
176
177 if (gSystem == this)
178 gSystem = nullptr;
179}
180
181////////////////////////////////////////////////////////////////////////////////
182/// Initialize the OS interface.
183
185{
186 fNfd = 0;
187 fMaxrfd = -1;
188 fMaxwfd = -1;
189
190 fSigcnt = 0;
191 fLevel = 0;
192
196 fTimers = new TList;
198
199 fBuildArch = BUILD_ARCH;
200 fBuildCompiler = COMPILER;
201 fBuildCompilerVersion = COMPILERVERS;
202 fBuildCompilerVersionStr = COMPILERVERSSTR;
203 fBuildNode = BUILD_NODE;
204 fFlagsDebug = CXXDEBUG;
205 fFlagsOpt = CXXOPT;
206 // fIncludePath is set in TROOT::InitSystem()
207 fLinkedLibs = LINKEDLIBS;
208 fSoExt = SOEXT;
209 fObjExt = OBJEXT;
211 fMakeSharedLib = MAKESHAREDLIB;
212 fMakeExe = MAKEEXE;
214
215 if (gEnv && fBeepDuration == 0 && fBeepFreq == 0) {
216 fBeepDuration = gEnv->GetValue("Root.System.BeepDuration", 100);
217 fBeepFreq = gEnv->GetValue("Root.System.BeepFreq", 440);
218 }
219 if (!fName.CompareTo("Generic")) return kTRUE;
220 return kFALSE;
221}
222
223////////////////////////////////////////////////////////////////////////////////
224/// Set the application name (from command line, argv[0]) and copy it in
225/// gProgName.
226
227void TSystem::SetProgname(const char *name)
228{
229 delete [] gProgName;
231}
232
233////////////////////////////////////////////////////////////////////////////////
234/// Set DISPLAY environment variable based on utmp entry. Only for UNIX.
235
237{
238}
239
240////////////////////////////////////////////////////////////////////////////////
241/// Set the system error string. This string will be used by GetError().
242/// To be used in case one does not want or can use the system error
243/// string (e.g. because error is generated by a third party POSIX like
244/// library that does not use standard errno).
245
246void TSystem::SetErrorStr(const char *errstr)
247{
248 ResetErrno(); // so GetError() uses the fLastErrorString
249 GetLastErrorString() = errstr;
250}
251
252////////////////////////////////////////////////////////////////////////////////
253/// Return system error string.
254
255const char *TSystem::GetError()
256{
257 if (GetErrno() == 0 && !GetLastErrorString().IsNull())
258 return GetLastErrorString().Data();
259 return Form("errno: %d", GetErrno());
260}
261
262////////////////////////////////////////////////////////////////////////////////
263/// Return cryptographic random number
264/// Fill provided buffer with random values. The number of requested random bytes must not exceed 256.
265/// Returns number of bytes written to buffer or -1 in case of error
266
268{
269 if (len < 0) {
270 return -1;
271 }
272 const auto rv = ROOT::Internal::GetCryptoRandom(buf, len);
273 return rv ? len : -1;
274}
275
276
277////////////////////////////////////////////////////////////////////////////////
278/// Static function returning system error number.
279
281{
282 return errno;
283}
284
285////////////////////////////////////////////////////////////////////////////////
286/// Static function resetting system error number.
287
289{
290 errno = 0;
291}
292
293////////////////////////////////////////////////////////////////////////////////
294/// Objects that should be deleted on exit of the OS interface.
295
297{
298 if (!fOnExitList)
300 if (!fOnExitList->FindObject(obj))
301 fOnExitList->Add(obj);
302}
303
304////////////////////////////////////////////////////////////////////////////////
305/// Return the system's host name.
306
307const char *TSystem::HostName()
308{
309 return "Local host";
310}
311
312////////////////////////////////////////////////////////////////////////////////
313/// Hook to tell TSystem that the TApplication object has been created.
314
316{
317 // Currently needed only for WinNT interface.
318}
319
320////////////////////////////////////////////////////////////////////////////////
321/// Beep for duration milliseconds with a tone of frequency freq.
322/// Defaults to printing the `\a` character to stdout.
323/// If freq or duration is <0 respectively, use default value.
324/// If setDefault is set, only set the frequency and duration as
325/// new defaults, but don't beep.
326/// If default freq or duration is <0, never beep (silence)
327
328void TSystem::Beep(Int_t freq /*=-1*/, Int_t duration /*=-1*/,
329 Bool_t setDefault /*=kFALSE*/)
330{
331 if (setDefault) {
332 fBeepFreq = freq;
333 fBeepDuration = duration;
334 return;
335 }
336 if (fBeepDuration < 0 || fBeepFreq < 0) return; // silence
337 if (freq < 0) freq = fBeepFreq;
338 if (duration < 0) duration = fBeepDuration;
339 DoBeep(freq, duration);
340}
341
342//---- EventLoop ---------------------------------------------------------------
343
344////////////////////////////////////////////////////////////////////////////////
345/// System event loop.
346
348{
350 fDone = kFALSE;
351
352loop_entry:
353 try {
354 RETRY {
355 while (!fDone) {
357 InnerLoop();
359 }
360 } ENDTRY;
361 }
362 catch (std::exception& exc) {
364 TStdExceptionHandler* eh = nullptr;
365 while ((eh = (TStdExceptionHandler*) next())) {
366 switch (eh->Handle(exc))
367 {
369 break;
371 goto loop_entry;
372 break;
374 Warning("Run", "instructed to abort");
375 goto loop_end;
376 break;
377 }
378 }
379 throw;
380 }
381 catch (const char *str) {
382 printf("%s\n", str);
383 }
384 // handle every exception
385 catch (...) {
386 Warning("Run", "handle uncaught exception, terminating");
387 }
388
389loop_end:
391}
392
393////////////////////////////////////////////////////////////////////////////////
394/// Exit from event loop.
395
397{
398 fDone = kTRUE;
399}
400
401////////////////////////////////////////////////////////////////////////////////
402/// Inner event loop.
403
405{
406 fLevel++;
408 fLevel--;
409}
410
411////////////////////////////////////////////////////////////////////////////////
412/// Process pending events (GUI, timers, sockets). Returns the result of
413/// TROOT::IsInterrupted(). The interrupt flag (TROOT::SetInterrupt())
414/// can be set during the handling of the events. This mechanism allows
415/// macros running in tight calculating loops to be interrupted by some
416/// GUI event (depending on the interval with which this method is
417/// called). For example hitting ctrl-c in a canvas will set the
418/// interrupt flag.
419
421{
422 gROOT->SetInterrupt(kFALSE);
423
424 if (!gROOT->TestBit(TObject::kInvalidObject))
426
427 return gROOT->IsInterrupted();
428}
429
430////////////////////////////////////////////////////////////////////////////////
431/// Dispatch a single event.
432
434{
435 AbstractMethod("DispatchOneEvent");
436}
437
438////////////////////////////////////////////////////////////////////////////////
439/// Sleep milliSec milli seconds.
440
442{
443 AbstractMethod("Sleep");
444}
445
446////////////////////////////////////////////////////////////////////////////////
447/// Select on active file descriptors (called by TMonitor).
448
450{
451 AbstractMethod("Select");
452 return -1;
453}
454////////////////////////////////////////////////////////////////////////////////
455/// Select on active file descriptors (called by TMonitor).
456
458{
459 AbstractMethod("Select");
460 return -1;
461}
462
463//---- handling of system events -----------------------------------------------
464////////////////////////////////////////////////////////////////////////////////
465/// Get current time in milliseconds since 0:00 Jan 1 1995.
466
468{
469 return TTime(0);
470}
471
472////////////////////////////////////////////////////////////////////////////////
473/// Add timer to list of system timers.
474
476{
477 if (ti && fTimers && (fTimers->FindObject(ti) == nullptr))
478 fTimers->Add(ti);
479}
480
481////////////////////////////////////////////////////////////////////////////////
482/// Remove timer from list of system timers. Returns removed timer or 0
483/// if timer was not active.
484
486{
487 if (fTimers) {
488 TTimer *tr = (TTimer*) fTimers->Remove(ti);
489 return tr;
490 }
491 return nullptr;
492}
493
494////////////////////////////////////////////////////////////////////////////////
495/// Time when next timer of mode (synchronous=kTRUE or
496/// asynchronous=kFALSE) will time-out (in ms).
497
499{
500 if (!fTimers) return -1;
501
502 TListIter it(fTimers);
503 TTimer *t, *to = nullptr;
504 Long64_t tt, tnow = Now();
505 Long_t timeout = -1;
506
507 while ((t = (TTimer *) it.Next())) {
508 if (t->IsSync() == mode) {
509 tt = (Long64_t)t->GetAbsTime() - tnow;
510 if (tt < 0) tt = 0;
511 if (timeout == -1) {
512 timeout = (Long_t)tt;
513 to = t;
514 }
515 if (tt < timeout) {
516 timeout = (Long_t)tt;
517 to = t;
518 }
519 }
520 }
521
522 if (to && to->IsAsync() && timeout > 0) {
523 if (to->IsInterruptingSyscalls())
525 else
527 }
528
529 return timeout;
530}
531
532////////////////////////////////////////////////////////////////////////////////
533/// Add a signal handler to list of system signal handlers. Only adds
534/// the handler if it is not already in the list of signal handlers.
535
541
542////////////////////////////////////////////////////////////////////////////////
543/// Remove a signal handler from list of signal handlers. Returns
544/// the handler or 0 if the handler was not in the list of signal handlers.
545
553
554////////////////////////////////////////////////////////////////////////////////
555/// Add a file handler to the list of system file handlers. Only adds
556/// the handler if it is not already in the list of file handlers.
557
563
564////////////////////////////////////////////////////////////////////////////////
565/// Remove a file handler from the list of file handlers. Returns
566/// the handler or 0 if the handler was not in the list of file handlers.
567
569{
570 if (fFileHandler)
571 return (TFileHandler *)fFileHandler->Remove(h);
572
573 return nullptr;
574}
575
576////////////////////////////////////////////////////////////////////////////////
577/// If reset is true reset the signal handler for the specified signal
578/// to the default handler, else restore previous behaviour.
579
580void TSystem::ResetSignal(ESignals /*sig*/, Bool_t /*reset*/)
581{
582 AbstractMethod("ResetSignal");
583}
584
585////////////////////////////////////////////////////////////////////////////////
586/// Reset signals handlers to previous behaviour.
587
589{
590 AbstractMethod("ResetSignals");
591}
592
593////////////////////////////////////////////////////////////////////////////////
594/// If ignore is true ignore the specified signal, else restore previous
595/// behaviour.
596
597void TSystem::IgnoreSignal(ESignals /*sig*/, Bool_t /*ignore*/)
598{
599 AbstractMethod("IgnoreSignal");
600}
601
602////////////////////////////////////////////////////////////////////////////////
603/// If ignore is true ignore the interrupt signal, else restore previous
604/// behaviour. Typically call ignore interrupt before writing to disk.
605
607{
609}
610
611////////////////////////////////////////////////////////////////////////////////
612/// Add an exception handler to list of system exception handlers. Only adds
613/// the handler if it is not already in the list of exception handlers.
614
620
621////////////////////////////////////////////////////////////////////////////////
622/// Remove an exception handler from list of exception handlers. Returns
623/// the handler or 0 if the handler was not in the list of exception handlers.
624
632
633////////////////////////////////////////////////////////////////////////////////
634/// Return the bitmap of conditions that trigger a floating point exception.
635
637{
638 AbstractMethod("GetFPEMask");
639 return 0;
640}
641
642////////////////////////////////////////////////////////////////////////////////
643/// Set which conditions trigger a floating point exception.
644/// Return the previous set of conditions.
645
647{
648 AbstractMethod("SetFPEMask");
649 return 0;
650}
651
652//---- Processes ---------------------------------------------------------------
653
654////////////////////////////////////////////////////////////////////////////////
655/// Execute a command.
656
657int TSystem::Exec(const char *)
658{
659 AbstractMethod("Exec");
660 return -1;
661}
662
663////////////////////////////////////////////////////////////////////////////////
664/// Open a pipe.
665
666FILE *TSystem::OpenPipe(const char *, const char *)
667{
668 AbstractMethod("OpenPipe");
669 return nullptr;
670}
671
672////////////////////////////////////////////////////////////////////////////////
673/// Close the pipe.
674
676{
677 AbstractMethod("ClosePipe");
678 return -1;
679}
680
681////////////////////////////////////////////////////////////////////////////////
682/// Execute command and return output in TString.
683/// @param command the command to be executed
684/// @param ret pointer to the memory where to store the returned value of the
685/// command, i.e. the result of ClosePipe (p-close stream, the status of its child).
686/// If ret is nullptr, the returned value is not stored anywhere.
687/// @param redirectStderr if true, stderr will be redirected to stdout
688/// @return the stdout of the command as TString (from the p-opened FILE stream)
689
690TString TSystem::GetFromPipe(const char *command, Int_t *ret, Bool_t redirectStderr)
691{
692 TString out;
693 TString scommand = command;
694 if (redirectStderr)
695 scommand += " 2>&1";
696 FILE *pipe = OpenPipe(scommand.Data(), "r");
697 if (!pipe) {
698 SysError("GetFromPipe", "cannot run command \"%s\"", scommand.Data());
699 return out;
700 }
701
703 while (line.Gets(pipe)) {
704 if (out != "")
705 out += "\n";
706 out += line;
707 }
708
709 Int_t r = ClosePipe(pipe);
710 if (r) {
711 Error("GetFromPipe", "command \"%s\" returned %d", scommand.Data(), r);
712 }
713 if (ret) {
714 *ret = r;
715 }
716 return out;
717}
718
719////////////////////////////////////////////////////////////////////////////////
720/// Get process id.
721
723{
724 AbstractMethod("GetPid");
725 return -1;
726}
727
728////////////////////////////////////////////////////////////////////////////////
729/// Exit the application.
730
732{
733 AbstractMethod("Exit");
734 throw; // unreachable
735}
736
737////////////////////////////////////////////////////////////////////////////////
738/// Abort the application.
739
741{
742 AbstractMethod("Abort");
743 throw; // unreachable
744}
745
746////////////////////////////////////////////////////////////////////////////////
747/// Print a stack trace.
748
750{
751 AbstractMethod("StackTrace");
752}
753
754
755//---- Directories -------------------------------------------------------------
756
757////////////////////////////////////////////////////////////////////////////////
758/// Create helper TSystem to handle file and directory operations that
759/// might be special for remote file access.
760
761TSystem *TSystem::FindHelper(const char *path, void *dirptr)
762{
763 TSystem *helper = nullptr;
764 {
766
767 if (!fHelpers) {
770 }
771
772 if (path) {
773 if (!GetDirPtr()) {
774 TUrl url(path, kTRUE);
775 if (!strcmp(url.GetProtocol(), "file"))
776 return nullptr;
777 }
778 }
779
780 // look for existing helpers
781 TIter next(fHelpers);
782 while ((helper = (TSystem*) next()))
783 if (helper->ConsistentWith(path, dirptr))
784 return helper;
785
786 if (!path)
787 return nullptr;
788 }
789
790 // create new helper
791 TRegexp re("^root.*:"); // also roots, rootk, etc
792 TString pname = path;
794 if (pname.BeginsWith("xroot:") || pname.Index(re) != kNPOS) {
795 // (x)rootd daemon ...
796 if ((h = gROOT->GetPluginManager()->FindHandler("TSystem", path))) {
797 if (h->LoadPlugin() == -1)
798 return nullptr;
799 helper = (TSystem*) h->ExecPlugin(2, path, kFALSE);
800 }
801 } else if ((h = gROOT->GetPluginManager()->FindHandler("TSystem", path))) {
802 if (h->LoadPlugin() == -1)
803 return nullptr;
804 helper = (TSystem*) h->ExecPlugin(0);
805 }
806
807 if (helper) {
809 fHelpers->Add(helper);
810 }
811
812 return helper;
813}
814
815////////////////////////////////////////////////////////////////////////////////
816/// Check consistency of this helper with the one required
817/// by 'path' or 'dirptr'
818
819Bool_t TSystem::ConsistentWith(const char *path, void *dirptr)
820{
821 Bool_t checkproto = kFALSE;
822 if (path) {
823 if (!GetDirPtr()) {
824 TUrl url(path, kTRUE);
825 if (!strncmp(url.GetProtocol(), GetName(), strlen(GetName())))
826 checkproto = kTRUE;
827 }
828 }
829
830 Bool_t checkdir = kFALSE;
831 if (GetDirPtr() && GetDirPtr() == dirptr)
832 checkdir = kTRUE;
833
834 return (checkproto || checkdir);
835}
836
837////////////////////////////////////////////////////////////////////////////////
838/// Make a directory. Returns 0 in case of success and
839/// -1 if the directory could not be created (either already exists or
840/// illegal path name).
841
842int TSystem::MakeDirectory(const char *)
843{
844 AbstractMethod("MakeDirectory");
845 return 0;
846}
847
848////////////////////////////////////////////////////////////////////////////////
849/// Open a directory. Returns 0 if directory does not exist.
850/// \note Remember to call `TSystem::FreeDirectory(returned_pointer)` later, to prevent a memory leak
851
852void *TSystem::OpenDirectory(const char *)
853{
854 AbstractMethod("OpenDirectory");
855 return nullptr;
856}
857
858////////////////////////////////////////////////////////////////////////////////
859/// Free a directory.
860
862{
863 AbstractMethod("FreeDirectory");
864}
865
866////////////////////////////////////////////////////////////////////////////////
867/// Get a directory entry. Returns 0 if no more entries.
868
869const char *TSystem::GetDirEntry(void *)
870{
871 AbstractMethod("GetDirEntry");
872 return nullptr;
873}
874
875////////////////////////////////////////////////////////////////////////////////
876/// Change directory.
877
879{
880 AbstractMethod("ChangeDirectory");
881 return kFALSE;
882}
883
884////////////////////////////////////////////////////////////////////////////////
885/// Return working directory.
886
888{
889 return nullptr;
890}
891
892//////////////////////////////////////////////////////////////////////////////
893/// Return working directory.
894
896{
897 return std::string();
898}
899
900////////////////////////////////////////////////////////////////////////////////
901/// Return the user's home directory.
902
903const char *TSystem::HomeDirectory(const char *)
904{
905 return nullptr;
906}
907
908//////////////////////////////////////////////////////////////////////////////
909/// Return the user's home directory.
910
911std::string TSystem::GetHomeDirectory(const char *) const
912{
913 return std::string();
914}
915
916////////////////////////////////////////////////////////////////////////////////
917/// Make a file system directory. Returns 0 in case of success and
918/// -1 if the directory could not be created (either already exists or
919/// illegal path name).
920/// If 'recursive' is true, makes parent directories as needed.
921
922int TSystem::mkdir(const char *name, Bool_t recursive)
923{
924 if (recursive) {
925 TString safeName = name; // local copy in case 'name' is output from
926 // TSystem::DirName as it uses static buffers
927 TString dirname = GetDirName(safeName.Data());
928 if (dirname.IsNull()) {
929 // well we should not have to make the root of the file system!
930 // (and this avoid infinite recursions!)
931 return -1;
932 }
933 if (AccessPathName(dirname.Data(), kFileExists)) {
934 int res = mkdir(dirname.Data(), kTRUE);
935 if (res) return res;
936 }
937 if (!AccessPathName(safeName.Data(), kFileExists)) {
938 return -1;
939 }
940 }
941
942 return MakeDirectory(name);
943}
944
945//---- Paths & Files -----------------------------------------------------------
946
947////////////////////////////////////////////////////////////////////////////////
948/// Base name of a file name. Base name of /user/root is root.
949
950const char *TSystem::BaseName(const char *name)
951{
952 if (name) {
953 if (name[0] == '/' && name[1] == '\0')
954 return name;
955 char *cp;
956 if ((cp = (char *)strrchr(name, '/')))
957 return ++cp;
958 return name;
959 }
960 Error("BaseName", "name = 0");
961 return nullptr;
962}
963
964////////////////////////////////////////////////////////////////////////////////
965/// Return true if dir is an absolute pathname.
966
968{
969 if (dir)
970 return dir[0] == '/';
971 return kFALSE;
972}
973
974////////////////////////////////////////////////////////////////////////////////
975/// Return true if 'name' is a file that can be found in the ROOT include
976/// path or the current directory.
977/// If 'name' contains any ACLiC style information (e.g. trailing +[+][g|O]),
978/// it will be striped off 'name'.
979/// If fullpath is != 0, the full path to the file is returned in *fullpath,
980/// which must be deleted by the caller.
981
982Bool_t TSystem::IsFileInIncludePath(const char *name, char **fullpath)
983{
984 if (!name || !name[0]) return kFALSE;
985
986 TString aclicMode;
987 TString arguments;
988 TString io;
989 TString realname = SplitAclicMode(name, aclicMode, arguments, io);
990
991 TString fileLocation = GetDirName(realname);
992
993 TString incPath = gSystem->GetIncludePath(); // of the form -Idir1 -Idir2 -Idir3
994 incPath.Append(":").Prepend(" ");
995 incPath.ReplaceAll(" -I",":"); // of form :dir1 :dir2:dir3
996 while ( incPath.Index(" :") != -1 ) {
997 incPath.ReplaceAll(" :",":");
998 }
999 // Remove double quotes around path expressions.
1000 incPath.ReplaceAll("\":", ":");
1001 incPath.ReplaceAll(":\"", ":");
1002
1003 incPath.Prepend(fileLocation+":.:");
1004
1005 char *actual = Which(incPath,realname);
1006
1007 if (!actual) {
1008 return kFALSE;
1009 } else {
1010 if (fullpath)
1011 *fullpath = actual;
1012 else
1013 delete [] actual;
1014 return kTRUE;
1015 }
1016}
1017
1018////////////////////////////////////////////////////////////////////////////////
1019/// Return the directory name in pathname. DirName of /user/root is /user.
1020/// In case no dirname is specified "." is returned.
1021
1022const char *TSystem::DirName(const char *pathname)
1023{
1024 auto res = GetDirName(pathname);
1025 if (res.IsNull() || (res == "."))
1026 return ".";
1027
1029
1030 TTHREAD_TLS(Ssiz_t) len = 0;
1031 TTHREAD_TLS(char*) buf = nullptr;
1032 if (res.Length() >= len) {
1033 if (buf) delete [] buf;
1034 len = res.Length() + 50;
1035 buf = new char [len];
1036 }
1037 if (buf)
1038 strncpy(buf, res.Data(), len);
1039 return buf;
1040}
1041
1042////////////////////////////////////////////////////////////////////////////////
1043/// Return the directory name in pathname.
1044/// DirName of /user/root is /user.
1045/// DirName of /user/root/ is also /user.
1046/// In case no dirname is specified "." is returned.
1047
1048TString TSystem::GetDirName(const char *pathname)
1049{
1050 if (!pathname || !strchr(pathname, '/'))
1051 return ".";
1052
1053 auto pathlen = strlen(pathname);
1054
1055 const char *r = pathname + pathlen - 1;
1056 // First skip the trailing '/'
1057 while ((r > pathname) && (*r == '/'))
1058 --r;
1059 // Then find the next non slash
1060 while ((r > pathname) && (*r != '/'))
1061 --r;
1062
1063 // Then skip duplicate slashes
1064 // Note the 'r>buf' is a strict comparison to allows '/topdir' to return '/'
1065 while ((r > pathname) && (*r == '/'))
1066 --r;
1067 // If all was cut away, we encountered a rel. path like 'subdir/'
1068 // and ended up at '.'.
1069 if ((r == pathname) && (*r != '/'))
1070 return ".";
1071
1072 return TString(pathname, r + 1 - pathname);
1073}
1074
1075////////////////////////////////////////////////////////////////////////////////
1076/// Convert from a local pathname to a Unix pathname. E.g. from `\user\root` to
1077/// `/user/root`.
1078
1079const char *TSystem::UnixPathName(const char *name)
1080{
1081 return name;
1082}
1083
1084////////////////////////////////////////////////////////////////////////////////
1085/// Concatenate a directory and a file name. User must delete returned string.
1086/// \deprecated Consider replacing with TSystem::PrependPathName
1087
1088char *TSystem::ConcatFileName(const char *dir, const char *name)
1089{
1090 TString nameString(name);
1091 PrependPathName(dir, nameString);
1092 return StrDup(nameString.Data());
1093}
1094
1095////////////////////////////////////////////////////////////////////////////////
1096/// Concatenate a directory and a file name.
1097
1098const char *TSystem::PrependPathName(const char *, TString&)
1099{
1100 AbstractMethod("PrependPathName");
1101 return nullptr;
1102}
1103
1104
1105//---- Paths & Files -----------------------------------------------------------
1106
1107////////////////////////////////////////////////////////////////////////////////
1108/// Expand a pathname getting rid of special shell characters like ~.$, etc.
1109/// For Unix/Win32 compatibility use $(XXX) instead of $XXX when using
1110/// environment variables in a pathname. If compatibility is not an issue
1111/// you can use on Unix directly $XXX. This is a protected function called
1112/// from the OS specific system classes, like TUnixSystem and TWinNTSystem.
1113/// Returns the expanded filename or 0 in case of error.
1114
1115const char *TSystem::ExpandFileName(const char *fname)
1116{
1117 const int kBufSize = kMAXPATHLEN;
1118 TTHREAD_TLS_ARRAY(char, kBufSize, xname);
1119
1120 Bool_t res = ExpandFileName(fname, xname, kBufSize);
1121 if (res)
1122 return nullptr;
1123 else
1124 return xname;
1125}
1126
1127//////////////////////////////////////////////////////////////////////////////
1128/// Expand a pathname getting rid of special shell characters like ~.$, etc.
1129/// This function is analogous to ExpandFileName(const char *), except that
1130/// it receives a TString reference of the pathname to be expanded.
1131/// Returns kTRUE in case of error and kFALSE otherwise.
1132
1134{
1135 const int kBufSize = kMAXPATHLEN;
1136 char xname[kBufSize];
1137
1138 Bool_t res = ExpandFileName(fname.Data(), xname, kBufSize);
1139 if (!res)
1140 fname = xname;
1141
1142 return res;
1143}
1144
1145////////////////////////////////////////////////////////////////////////////
1146/// Private method for pathname expansion.
1147/// Returns kTRUE in case of error and kFALSE otherwise.
1148
1149Bool_t TSystem::ExpandFileName(const char *fname, char *xname, const int kBufSize)
1150{
1151 int n, ier, iter, lx, ncopy;
1152 char *inp, *out, *x, *t, *buff;
1153 const char *b, *c, *e;
1154 const char *p;
1155 buff = new char[kBufSize * 4];
1156
1157 iter = 0; xname[0] = 0; inp = buff + kBufSize; out = inp + kBufSize;
1158 inp[-1] = ' '; inp[0] = 0; out[-1] = ' ';
1159 c = fname + strspn(fname, " \t\f\r");
1160 //VP if (isalnum(c[0])) { strcpy(inp, WorkingDirectory()); strcat(inp, "/"); } // add $cwd
1161
1162 strlcat(inp, c, kBufSize);
1163
1164again:
1165 iter++; c = inp; ier = 0;
1166 x = out; x[0] = 0;
1167
1168 p = nullptr; e = nullptr;
1169 if (c[0] == '~' && c[1] == '/') { // ~/ case
1170 std::string hd = GetHomeDirectory();
1171 p = hd.c_str();
1172 e = c + 1;
1173 if (p) { // we have smth to copy
1174 strlcpy(x, p, kBufSize);
1175 x += strlen(p);
1176 c = e;
1177 } else {
1178 ++ier;
1179 ++c;
1180 }
1181 } else if (c[0] == '~' && c[1] != '/') { // ~user case
1182 n = strcspn(c+1, "/ ");
1183 assert((n+1) < kBufSize && "This should have been prevented by the truncation 'strlcat(inp, c, kBufSize)'");
1184 // There is no overlap here as the buffer is segment in 4 strings of at most kBufSize
1185 (void)strlcpy(buff, c+1, n+1); // strlcpy copy 'size-1' characters.
1186 std::string hd = GetHomeDirectory(buff);
1187 e = c+1+n;
1188 if (!hd.empty()) { // we have smth to copy
1189 p = hd.c_str();
1190 strlcpy(x, p, kBufSize);
1191 x += strlen(p);
1192 c = e;
1193 } else {
1194 x++[0] = c[0];
1195 //++ier;
1196 ++c;
1197 }
1198 }
1199
1200 for ( ; c[0]; c++) {
1201
1202 p = nullptr; e = nullptr;
1203
1204 if (c[0] == '.' && c[1] == '/' && c[-1] == ' ') { // $cwd
1205 std::string wd = GetWorkingDirectory();
1206 strlcpy(buff, wd.c_str(), kBufSize);
1207 p = buff;
1208 e = c + 1;
1209 }
1210 if (p) { // we have smth to copy */
1211 strlcpy(x, p, kBufSize); x += strlen(p); c = e-1; continue;
1212 }
1213
1214 if (c[0] != '$') { // not $, simple copy
1215 x++[0] = c[0];
1216 } else { // we have a $
1217 b = c+1;
1218 if (c[1] == '(') b++;
1219 if (c[1] == '{') b++;
1220 if (b[0] == '$')
1221 e = b+1;
1222 else
1223 for (e = b; isalnum(e[0]) || e[0] == '_'; e++) ;
1224 buff[0] = 0; strncat(buff, b, e-b);
1225 p = Getenv(buff);
1226 if (!p) { // too bad, try UPPER case
1227 for (t = buff; (t[0] = toupper(t[0])); t++) ;
1228 p = Getenv(buff);
1229 }
1230 if (!p) { // too bad, try Lower case
1231 for (t = buff; (t[0] = tolower(t[0])); t++) ;
1232 p = Getenv(buff);
1233 }
1234 if (!p && !strcmp(buff, "cwd")) { // it is $cwd
1235 std::string wd = GetWorkingDirectory();
1236 strlcpy(buff, wd.c_str(), kBufSize);
1237 p = buff;
1238 }
1239 if (!p && !strcmp(buff, "$")) { // it is $$ (replace by GetPid())
1240 snprintf(buff,kBufSize*4, "%d", GetPid());
1241 p = buff;
1242 }
1243 if (!p) { // too bad, nothing can help
1244#ifdef WIN32
1245 // if we're on windows, we can have \\SomeMachine\C$ - don't
1246 // complain about that, if '$' is followed by nothing or a
1247 // path delimiter.
1248 if (c[1] && c[1]!='\\' && c[1]!=';' && c[1]!='/')
1249 ier++;
1250#else
1251 ier++;
1252#endif
1253 x++[0] = c[0];
1254 } else { // It is OK, copy result
1255 int lp = strlen(p);
1256 if (lp >= kBufSize) {
1257 // make sure lx will be >= kBufSize (see below)
1258 strlcpy(x, p, kBufSize);
1259 x += kBufSize;
1260 break;
1261 }
1262 strcpy(x,p);
1263 x += lp;
1264 c = (b==c+1) ? e-1 : e;
1265 }
1266 }
1267 }
1268
1269 x[0] = 0; lx = x - out;
1270 if (ier && iter < 3) { strlcpy(inp, out, kBufSize); goto again; }
1271 ncopy = (lx >= kBufSize) ? kBufSize-1 : lx;
1272 xname[0] = 0; strncat(xname, out, ncopy);
1273
1274 delete[] buff;
1275
1276 if (ier || ncopy != lx) {
1277 if (fname && std::strstr(fname, "~$")) {
1278 if (gDebug > 0)
1279 Info("ExpandFileName", "detected MS temp file input: %s, output: %s", fname, xname);
1280 return kFALSE;
1281 } else {
1282 ::Error("TSystem::ExpandFileName", "input: %s, output: %s", fname, xname);
1283 }
1284 return kTRUE;
1285 }
1286
1287 return kFALSE;
1288}
1289
1290
1291////////////////////////////////////////////////////////////////////////////////
1292/// Expand a pathname getting rid of special shell characters like ~.$, etc.
1293/// For Unix/Win32 compatibility use $(XXX) instead of $XXX when using
1294/// environment variables in a pathname. If compatibility is not an issue
1295/// you can use on Unix directly $XXX.
1296
1301
1302////////////////////////////////////////////////////////////////////////////////
1303/// Expand a pathname getting rid of special shell characters like ~.$, etc.
1304/// For Unix/Win32 compatibility use $(XXX) instead of $XXX when using
1305/// environment variables in a pathname. If compatibility is not an issue
1306/// you can use on Unix directly $XXX. The user must delete returned string.
1307
1308char *TSystem::ExpandPathName(const char *)
1309{
1310 return nullptr;
1311}
1312
1313////////////////////////////////////////////////////////////////////////////////
1314/// Returns FALSE if one can access a file using the specified access mode.
1315/// The file name must not contain any special shell characters line ~ or $,
1316/// in those cases first call ExpandPathName().
1317/// Attention, bizarre convention of return value!!
1318
1320{
1321 return kFALSE;
1322}
1323
1324////////////////////////////////////////////////////////////////////////////////
1325/// Returns TRUE if the url in 'path' points to the local file system.
1326/// This is used to avoid going through the NIC card for local operations.
1327
1329{
1330 Bool_t localPath = kTRUE;
1331
1332 TUrl url(path);
1333 if (strlen(url.GetHost()) > 0) {
1334 // Check locality
1335 localPath = kFALSE;
1338 if (!strcmp(a.GetHostName(), b.GetHostName()) ||
1339 !strcmp(a.GetHostAddress(), b.GetHostAddress())) {
1340 // Host OK
1341 localPath = kTRUE;
1342 // Check the user if specified
1343 if (strlen(url.GetUser()) > 0) {
1345 if (u) {
1346 if (strcmp(u->fUser, url.GetUser()))
1347 // Requested a different user
1348 localPath = kFALSE;
1349 delete u;
1350 }
1351 }
1352 }
1353 }
1354 // Done
1355 return localPath;
1356}
1357
1358////////////////////////////////////////////////////////////////////////////////
1359/// Copy a file. If overwrite is true and file already exists the
1360/// file will be overwritten. Returns 0 when successful, -1 in case
1361/// of file open failure, -2 in case the file already exists and overwrite
1362/// was false and -3 in case of error during copy.
1363
1364int TSystem::CopyFile(const char *, const char *, Bool_t)
1365{
1366 AbstractMethod("CopyFile");
1367 return -1;
1368}
1369
1370////////////////////////////////////////////////////////////////////////////////
1371/// Rename a file.
1372
1373int TSystem::Rename(const char *, const char *)
1374{
1375 AbstractMethod("Rename");
1376 return -1;
1377}
1378
1379////////////////////////////////////////////////////////////////////////////////
1380/// Create a link from file1 to file2.
1381
1382int TSystem::Link(const char *, const char *)
1383{
1384 AbstractMethod("Link");
1385 return -1;
1386}
1387
1388////////////////////////////////////////////////////////////////////////////////
1389/// Create a symbolic link from file1 to file2.
1390
1391int TSystem::Symlink(const char *, const char *)
1392{
1393 AbstractMethod("Symlink");
1394 return -1;
1395}
1396
1397////////////////////////////////////////////////////////////////////////////////
1398/// Unlink, i.e. remove, a file.
1399///
1400/// If the file is currently open by the current or another process, the behavior of this function is
1401/// implementation-defined (in particular, POSIX systems unlink the file name, while Windows does not allow the
1402/// file to be deleted and the operation is a no-op).
1403
1404int TSystem::Unlink(const char *)
1405{
1406 AbstractMethod("Unlink");
1407 return -1;
1408}
1409
1410////////////////////////////////////////////////////////////////////////////////
1411/// Get info about a file: id, size, flags, modification time.
1412/// - Id is (statbuf.st_dev << 24) + statbuf.st_ino
1413/// - Size is the file size
1414/// - Flags is file type: 0 is regular file, bit 0 set executable,
1415/// bit 1 set directory, bit 2 set special file
1416/// (socket, fifo, pipe, etc.)
1417/// Modtime is modification time.
1418/// The function returns 0 in case of success and 1 if the file could
1419/// not be stat'ed.
1420
1421int TSystem::GetPathInfo(const char *path, Long_t *id, Long_t *size,
1422 Long_t *flags, Long_t *modtime)
1423{
1424 Long64_t lsize;
1425
1426 int res = GetPathInfo(path, id, &lsize, flags, modtime);
1427
1428 if (res == 0 && size) {
1429 if (sizeof(Long_t) == 4 && lsize > kMaxInt) {
1430 Error("GetPathInfo", "file %s > 2 GB, use GetPathInfo() with Long64_t size", path);
1431 *size = kMaxInt;
1432 } else {
1433 *size = (Long_t)lsize;
1434 }
1435 }
1436
1437 return res;
1438}
1439
1440////////////////////////////////////////////////////////////////////////////////
1441/// Get info about a file: id, size, flags, modification time.
1442/// - Id is (statbuf.st_dev << 24) + statbuf.st_ino
1443/// - Size is the file size
1444/// - Flags is file type: 0 is regular file, bit 0 set executable,
1445/// bit 1 set directory, bit 2 set special file
1446/// (socket, fifo, pipe, etc.)
1447/// Modtime is modification time.
1448/// The function returns 0 in case of success and 1 if the file could
1449/// not be stat'ed.
1450
1451int TSystem::GetPathInfo(const char *path, Long_t *id, Long64_t *size,
1452 Long_t *flags, Long_t *modtime)
1453{
1454 FileStat_t buf;
1455
1456 int res = GetPathInfo(path, buf);
1457
1458 if (res == 0) {
1459 if (id)
1460 *id = (buf.fDev << 24) + buf.fIno;
1461 if (size)
1462 *size = buf.fSize;
1463 if (modtime)
1464 *modtime = buf.fMtime;
1465 if (flags) {
1466 *flags = 0;
1467 if (buf.fMode & (kS_IXUSR|kS_IXGRP|kS_IXOTH))
1468 *flags |= 1;
1469 if (R_ISDIR(buf.fMode))
1470 *flags |= 2;
1471 if (!R_ISREG(buf.fMode) && !R_ISDIR(buf.fMode))
1472 *flags |= 4;
1473 }
1474 }
1475
1476 return res;
1477}
1478
1479////////////////////////////////////////////////////////////////////////////////
1480/// Get info about a file. Info is returned in the form of a FileStat_t
1481/// structure (see TSystem.h).
1482/// The function returns 0 in case of success and 1 if the file could
1483/// not be stat'ed.
1484
1486{
1487 AbstractMethod("GetPathInfo(const char *, FileStat_t&)");
1488 return 1;
1489}
1490
1491////////////////////////////////////////////////////////////////////////////////
1492/// Get info about a file system: fs type, block size, number of blocks,
1493/// number of free blocks.
1494
1495int TSystem::GetFsInfo(const char *, Long_t *, Long_t *, Long_t *, Long_t *)
1496{
1497 AbstractMethod("GetFsInfo");
1498 return 1;
1499}
1500
1501////////////////////////////////////////////////////////////////////////////////
1502/// Return a user configured or systemwide directory to create
1503/// temporary files in.
1504
1505const char *TSystem::TempDirectory() const
1506{
1507 AbstractMethod("TempDirectory");
1508 return nullptr;
1509}
1510
1511////////////////////////////////////////////////////////////////////////////////
1512/// Create a secure temporary file by appending a unique
1513/// 6 letter string to base. The file will be created in
1514/// a standard (system) directory or in the directory
1515/// provided in dir. Optionally one can provide suffix
1516/// append to the final name - like extension ".txt" or ".html".
1517/// The full filename is returned in base
1518/// and a filepointer is returned for safely writing to the file
1519/// (this avoids certain security problems). Returns 0 in case
1520/// of error.
1521
1522FILE *TSystem::TempFileName(TString &, const char *, const char *)
1523{
1524 AbstractMethod("TempFileName");
1525 return nullptr;
1526}
1527
1528////////////////////////////////////////////////////////////////////////////////
1529/// Set the file permission bits. Returns -1 in case or error, 0 otherwise.
1530
1531int TSystem::Chmod(const char *, UInt_t)
1532{
1533 AbstractMethod("Chmod");
1534 return -1;
1535}
1536
1537////////////////////////////////////////////////////////////////////////////////
1538/// Set the process file creation mode mask.
1539
1541{
1542 AbstractMethod("Umask");
1543 return -1;
1544}
1545
1546////////////////////////////////////////////////////////////////////////////////
1547/// Set the a files modification and access times. If actime = 0 it will be
1548/// set to the modtime. Returns 0 on success and -1 in case of error.
1549
1550int TSystem::Utime(const char *, Long_t, Long_t)
1551{
1552 AbstractMethod("Utime");
1553 return -1;
1554}
1555
1556////////////////////////////////////////////////////////////////////////////////
1557/// Find location of file in a search path. Return value points to TString for
1558/// compatibility with Which(const char *, const char *, EAccessMode).
1559/// Returns 0 in case file is not found.
1560
1561const char *TSystem::FindFile(const char *, TString&, EAccessMode)
1562{
1563 AbstractMethod("FindFile");
1564 return nullptr;
1565}
1566
1567////////////////////////////////////////////////////////////////////////////////
1568/// Find location of file in a search path. User must delete returned string.
1569/// Returns 0 in case file is not found.
1570
1571char *TSystem::Which(const char *search, const char *wfil, EAccessMode mode)
1572{
1573 TString wfilString(wfil);
1574 FindFile(search, wfilString, mode);
1575 if (wfilString.IsNull())
1576 return nullptr;
1577 return StrDup(wfilString.Data());
1578}
1579
1580//---- Users & Groups ----------------------------------------------------------
1581
1582////////////////////////////////////////////////////////////////////////////////
1583/// Returns the user's id. If user = 0, returns current user's id.
1584
1585Int_t TSystem::GetUid(const char * /*user*/)
1586{
1587 AbstractMethod("GetUid");
1588 return 0;
1589}
1590
1591////////////////////////////////////////////////////////////////////////////////
1592/// Returns the effective user id. The effective id corresponds to the
1593/// set id bit on the file being executed.
1594
1596{
1597 AbstractMethod("GetEffectiveUid");
1598 return 0;
1599}
1600
1601////////////////////////////////////////////////////////////////////////////////
1602/// Returns the group's id. If group = 0, returns current user's group.
1603
1604Int_t TSystem::GetGid(const char * /*group*/)
1605{
1606 AbstractMethod("GetGid");
1607 return 0;
1608}
1609
1610////////////////////////////////////////////////////////////////////////////////
1611/// Returns the effective group id. The effective group id corresponds
1612/// to the set id bit on the file being executed.
1613
1615{
1616 AbstractMethod("GetEffectiveGid");
1617 return 0;
1618}
1619
1620////////////////////////////////////////////////////////////////////////////////
1621/// Returns all user info in the UserGroup_t structure. The returned
1622/// structure must be deleted by the user. In case of error 0 is returned.
1623
1625{
1626 AbstractMethod("GetUserInfo");
1627 return nullptr;
1628}
1629
1630////////////////////////////////////////////////////////////////////////////////
1631/// Returns all user info in the UserGroup_t structure. If user = 0, returns
1632/// current user's id info. The returned structure must be deleted by the
1633/// user. In case of error 0 is returned.
1634
1635UserGroup_t *TSystem::GetUserInfo(const char * /*user*/)
1636{
1637 AbstractMethod("GetUserInfo");
1638 return nullptr;
1639}
1640
1641////////////////////////////////////////////////////////////////////////////////
1642/// Returns all group info in the UserGroup_t structure. The only active
1643/// fields in the UserGroup_t structure for this call are:
1644/// - fGid and fGroup
1645/// The returned structure must be deleted by the user. In case of
1646/// error 0 is returned.
1647
1649{
1650 AbstractMethod("GetGroupInfo");
1651 return nullptr;
1652}
1653
1654////////////////////////////////////////////////////////////////////////////////
1655/// Returns all group info in the UserGroup_t structure. The only active
1656/// fields in the UserGroup_t structure for this call are:
1657/// - fGid and fGroup
1658/// If group = 0, returns current user's group. The returned structure
1659/// must be deleted by the user. In case of error 0 is returned.
1660
1661UserGroup_t *TSystem::GetGroupInfo(const char * /*group*/)
1662{
1663 AbstractMethod("GetGroupInfo");
1664 return nullptr;
1665}
1666
1667//---- environment manipulation ------------------------------------------------
1668
1669////////////////////////////////////////////////////////////////////////////////
1670/// Set environment variable.
1671
1672void TSystem::Setenv(const char *, const char *)
1673{
1674 AbstractMethod("Setenv");
1675}
1676
1677////////////////////////////////////////////////////////////////////////////////
1678/// Unset environment variable.
1679
1680void TSystem::Unsetenv(const char *name)
1681{
1682 Setenv(name, "");
1683}
1684
1685////////////////////////////////////////////////////////////////////////////////
1686/// Get environment variable.
1687
1688const char *TSystem::Getenv(const char *)
1689{
1690 AbstractMethod("Getenv");
1691 return nullptr;
1692}
1693
1694//---- System Logging ----------------------------------------------------------
1695
1696////////////////////////////////////////////////////////////////////////////////
1697/// Open connection to system log daemon. For the use of the options and
1698/// facility see the Unix openlog man page.
1699
1701{
1702 AbstractMethod("Openlog");
1703}
1704
1705////////////////////////////////////////////////////////////////////////////////
1706/// Send mess to syslog daemon. Level is the logging level and mess the
1707/// message that will be written on the log.
1708
1709void TSystem::Syslog(ELogLevel, const char *)
1710{
1711 AbstractMethod("Syslog");
1712}
1713
1714////////////////////////////////////////////////////////////////////////////////
1715/// Close connection to system log daemon.
1716
1718{
1719 AbstractMethod("Closelog");
1720}
1721
1722//---- Standard output redirection ---------------------------------------------
1723
1724////////////////////////////////////////////////////////////////////////////////
1725/// Redirect standard output (stdout, stderr) to the specified file.
1726/// If the file argument is 0 the output is set again to stderr, stdout.
1727/// The second argument specifies whether the output should be added to the
1728/// file ("a", default) or the file be truncated before ("w").
1729/// The implementations of this function save internally the current state into
1730/// a static structure.
1731///
1732/// The call can be made reentrant by specifying the opaque structure pointed
1733/// by 'h', which is filled with the relevant information. The handle 'h'
1734/// obtained on the first call must then be used in any subsequent call,
1735/// included ShowOutput, to display the redirected output.
1736/// Returns 0 on success, -1 in case of error.
1737
1738Int_t TSystem::RedirectOutput(const char *, const char *, RedirectHandle_t *)
1739{
1740 AbstractMethod("RedirectOutput");
1741 return -1;
1742}
1743
1744////////////////////////////////////////////////////////////////////////////////
1745/// Display the content associated with the redirection described by the
1746/// opaque handle 'h'.
1747
1749{
1750 // Check input ...
1751 if (!h) {
1752 Error("ShowOutput", "handle not specified");
1753 return;
1754 }
1755
1756 // ... and file access
1757 if (gSystem->AccessPathName(h->fFile, kReadPermission)) {
1758 Error("ShowOutput", "file '%s' cannot be read", h->fFile.Data());
1759 return;
1760 }
1761
1762 // Open the file
1763 FILE *f = nullptr;
1764 if (!(f = fopen(h->fFile.Data(), "r"))) {
1765 Error("ShowOutput", "file '%s' cannot be open", h->fFile.Data());
1766 return;
1767 }
1768
1769 // Determine the number of bytes to be read from the file.
1770 off_t ltot = lseek(fileno(f), (off_t) 0, SEEK_END);
1771 Int_t begin = (h->fReadOffSet > 0 && h->fReadOffSet < ltot) ? h->fReadOffSet : 0;
1772 lseek(fileno(f), (off_t) begin, SEEK_SET);
1773 Int_t left = ltot - begin;
1774
1775 // Now readout from file
1776 const Int_t kMAXBUF = 16384;
1777 char buf[kMAXBUF];
1778 Int_t wanted = (left > kMAXBUF-1) ? kMAXBUF-1 : left;
1779 Int_t len;
1780 do {
1781 while ((len = read(fileno(f), buf, wanted)) < 0 &&
1782 TSystem::GetErrno() == EINTR)
1784
1785 if (len < 0) {
1786 SysError("ShowOutput", "error reading log file");
1787 break;
1788 }
1789
1790 // Null-terminate
1791 buf[len] = 0;
1792 fprintf(stderr,"%s", buf);
1793
1794 // Update counters
1795 left -= len;
1796 wanted = (left > kMAXBUF) ? kMAXBUF : left;
1797
1798 } while (len > 0 && left > 0);
1799
1800 // Do not display twice the same thing
1801 h->fReadOffSet = ltot;
1802 fclose(f);
1803}
1804
1805//---- Dynamic Loading ---------------------------------------------------------
1806
1807////////////////////////////////////////////////////////////////////////////////
1808/// Add a new directory to the dynamic path.
1809
1810void TSystem::AddDynamicPath(const char *)
1811{
1812 AbstractMethod("AddDynamicPath");
1813}
1814
1815////////////////////////////////////////////////////////////////////////////////
1816/// Return the dynamic path (used to find shared libraries).
1817
1819{
1820 AbstractMethod("GetDynamicPath");
1821 return nullptr;
1822}
1823
1824////////////////////////////////////////////////////////////////////////////////
1825/// Set the dynamic path to a new value.
1826/// If the value of 'path' is zero, the dynamic path is reset to its
1827/// default value.
1828
1829void TSystem::SetDynamicPath(const char *)
1830{
1831 AbstractMethod("SetDynamicPath");
1832}
1833
1834
1835////////////////////////////////////////////////////////////////////////////////
1836/// Figure out if left and right points to the same
1837/// object in the file system.
1838
1839static bool R__MatchFilename(const char *left, const char *right)
1840{
1841 if (left == right) return kTRUE;
1842
1843 if (left==nullptr || right==nullptr) return kFALSE;
1844
1845 if ( (strcmp(right,left)==0) ) {
1846 return kTRUE;
1847 }
1848
1849#ifdef G__WIN32
1850
1851 char leftname[_MAX_PATH];
1852 char rightname[_MAX_PATH];
1853 _fullpath( leftname, left, _MAX_PATH );
1854 _fullpath( rightname, right, _MAX_PATH );
1855 return ((stricmp(leftname, rightname)==0));
1856#else
1857 struct stat rightBuf;
1858 struct stat leftBuf;
1859 return ( ( 0 == stat( left, & leftBuf ) )
1860 && ( 0 == stat( right, & rightBuf ) )
1861 && ( leftBuf.st_dev == rightBuf.st_dev ) // Files on same device
1862 && ( leftBuf.st_ino == rightBuf.st_ino ) // Files on same inode (but this is not unique on AFS so we need the next 2 test
1863 && ( leftBuf.st_size == rightBuf.st_size ) // Files of same size
1864 && ( leftBuf.st_mtime == rightBuf.st_mtime ) // Files modified at the same time
1865 );
1866#endif
1867}
1868
1869
1870////////////////////////////////////////////////////////////////////////////////
1871/// Load a shared library. Returns 0 on successful loading, 1 in
1872/// case lib was already loaded, -1 in case lib does not exist
1873/// or in case of error and -2 in case of version mismatch.
1874/// When entry is specified the loaded lib is
1875/// searched for this entry point (return -1 when entry does not exist,
1876/// 0 otherwise). When the system flag is kTRUE, the library is considered
1877/// a permanent system library that should not be unloaded during the
1878/// course of the session.
1879
1880int TSystem::Load(const char *module, const char *entry, Bool_t system)
1881{
1882 // don't load libraries that have already been loaded
1883 TString libs( GetLibraries() );
1884 TString l(BaseName(module));
1885
1886 Ssiz_t idx = l.Last('.');
1887 if (idx != kNPOS) {
1888 l.Remove(idx+1);
1889 }
1890 for (idx = libs.Index(l); idx != kNPOS; idx = libs.Index(l,idx+1)) {
1891 // The libs contains the sub-string 'l', let's make sure it is
1892 // not just part of a larger name.
1893 if (idx == 0 || libs[idx-1] == '/' || libs[idx-1] == '\\') {
1894 Ssiz_t len = libs.Length();
1895 idx += l.Length();
1896 if (!l.EndsWith(".") && libs[idx]=='.')
1897 idx++;
1898 // Skip the soversion.
1899 while (idx < len && isdigit(libs[idx])) {
1900 ++idx;
1901 // No need to test for len here, at worse idx==len and lib[idx]=='\0'
1902 if (libs[idx] == '.') {
1903 ++idx;
1904 }
1905 }
1906 while (idx < len && libs[idx] != '.') {
1907 if (libs[idx] == ' ' || idx+1 == len) {
1908 return 1;
1909 }
1910 ++idx;
1911 }
1912 }
1913 }
1914 if (l[l.Length()-1] == '.') {
1915 l.Remove(l.Length()-1);
1916 }
1917 if (l.BeginsWith("lib")) {
1918 l.Replace(0, 3, "-l");
1919 for(idx = libs.Index(l); idx != kNPOS; idx = libs.Index(l,idx+1)) {
1920 if ((idx == 0 || libs[idx-1] == ' ') &&
1921 (libs[idx+l.Length()] == ' ' || libs[idx+l.Length()] == 0)) {
1922 return 1;
1923 }
1924 }
1925 }
1926
1927 char *path = DynamicPathName(module);
1928
1929 int ret = -1;
1930 if (path) {
1931 // load any dependent libraries
1932 TString deplibs = gInterpreter->GetSharedLibDeps(path);
1933 if (!deplibs.IsNull()) {
1934 TString delim(" ");
1935 TObjArray *tokens = deplibs.Tokenize(delim);
1936 for (Int_t i = tokens->GetEntriesFast()-1; i > 0; i--) {
1937 const char *deplib = ((TObjString*)tokens->At(i))->GetName();
1938 if (strcmp(module,deplib)==0) {
1939 continue;
1940 }
1941 if (gDebug > 0)
1942 Info("Load", "loading dependent library %s for library %s",
1943 deplib, ((TObjString*)tokens->At(0))->GetName());
1944 if ((ret = Load(deplib, "", system)) < 0) {
1945 delete tokens;
1946 delete [] path;
1947 return ret;
1948 }
1949 }
1950 delete tokens;
1951 }
1952 if (!system) {
1953 // Mark the library in $ROOTSYS/lib as system.
1954 TString dirname = GetDirName(path);
1955 system = R__MatchFilename(TROOT::GetLibDir(), dirname.Data());
1956
1957 if (!system) {
1958 system = R__MatchFilename(TROOT::GetBinDir(), dirname.Data());
1959 }
1960 }
1961
1964 gLibraryVersionMax *= 2;
1966 }
1967 ret = gInterpreter->Load(path, system);
1968 if (ret < 0) ret = -1;
1969 if (gDebug > 0)
1970 Info("Load", "loaded library %s, status %d", path, ret);
1971 if (ret == 0 && gLibraryVersion[gLibraryVersionIdx]) {
1973 Error("Load", "version mismatch, %s = %d, ROOT = %d",
1974 path, v, gROOT->GetVersionInt());
1975 ret = -2;
1977 }
1979 delete [] path;
1980 }
1981
1982 if (!entry || !entry[0] || ret < 0) return ret;
1983
1984 Func_t f = DynFindSymbol(module, entry);
1985 if (f) return 0;
1986 return -1;
1987}
1988
1989///////////////////////////////////////////////////////////////////////////////
1990/// Load all libraries known to ROOT via the rootmap system.
1991/// Returns the number of top level libraries successfully loaded.
1992
1994{
1995 UInt_t nlibs = 0;
1996
1997 TEnv* mapfile = gInterpreter->GetMapfile();
1998 if (!mapfile || !mapfile->GetTable()) return 0;
1999
2000 std::set<std::string> loadedlibs;
2001 std::set<std::string> failedlibs;
2002
2003 TEnvRec* rec = nullptr;
2004 TIter iEnvRec(mapfile->GetTable());
2005 while ((rec = (TEnvRec*) iEnvRec())) {
2006 TString libs = rec->GetValue();
2007 TString lib;
2008 Ssiz_t pos = 0;
2009 while (libs.Tokenize(lib, pos)) {
2010 // check that none of the libs failed to load
2011 if (failedlibs.find(lib.Data()) != failedlibs.end()) {
2012 // don't load it or any of its dependencies
2013 libs = "";
2014 break;
2015 }
2016 }
2017 pos = 0;
2018 while (libs.Tokenize(lib, pos)) {
2019 // ignore libCore - it's already loaded
2020 if (lib.BeginsWith("libCore"))
2021 continue;
2022
2023 if (loadedlibs.find(lib.Data()) == loadedlibs.end()) {
2024 // just load the first library - TSystem will do the rest.
2025 auto res = gSystem->Load(lib);
2026 if (res >=0) {
2027 if (res == 0) ++nlibs;
2028 loadedlibs.insert(lib.Data());
2029 } else {
2030 failedlibs.insert(lib.Data());
2031 }
2032 }
2033 }
2034 }
2035 return nlibs;
2036}
2037
2038////////////////////////////////////////////////////////////////////////////////
2039/// Find a dynamic library called lib using the system search paths.
2040/// Appends known extensions if needed. Returned string must be deleted
2041/// by the user!
2042
2043char *TSystem::DynamicPathName(const char *lib, Bool_t quiet /*=kFALSE*/)
2044{
2045 TString sLib(lib);
2046 if (FindDynamicLibrary(sLib, quiet))
2047 return StrDup(sLib);
2048 return nullptr;
2049}
2050
2051////////////////////////////////////////////////////////////////////////////////
2052/// Find a dynamic library using the system search paths. lib will be updated
2053/// to contain the absolute filename if found. Returns lib if found, or NULL
2054/// if a library called lib was not found.
2055/// This function does not open the library.
2056
2058{
2059 AbstractMethod("FindDynamicLibrary");
2060 return nullptr;
2061}
2062
2063////////////////////////////////////////////////////////////////////////////////
2064/// Find specific entry point in specified library. Specify "*" for lib
2065/// to search in all libraries.
2066
2067Func_t TSystem::DynFindSymbol(const char * /*lib*/, const char *entry)
2068{
2069 return (Func_t) gInterpreter->FindSym(entry);
2070}
2071
2072////////////////////////////////////////////////////////////////////////////////
2073/// Unload a shared library.
2074
2075void TSystem::Unload(const char *module)
2076{
2077 char *path;
2078 if ((path = DynamicPathName(module))) {
2079 gInterpreter->UnloadFile(path);
2080 delete [] path;
2081 }
2082}
2083
2084////////////////////////////////////////////////////////////////////////////////
2085/// List symbols in a shared library.
2086
2087void TSystem::ListSymbols(const char *, const char *)
2088{
2089 AbstractMethod("ListSymbols");
2090}
2091
2092////////////////////////////////////////////////////////////////////////////////
2093/// List the loaded shared libraries.
2094/// `regexp` is a regular expression allowing to filter the list.
2095///
2096/// Examples:
2097///
2098/// The following line lists all the libraries currently loaded:
2099/// ~~~ {.cpp}
2100/// gSystem->ListLibraries()
2101/// ~~~
2102///
2103/// The following line lists all the libraries currently loaded having "RIO" in their names:
2104/// ~~~ {.cpp}
2105/// gSystem->ListLibraries(".*RIO.*")
2106/// ~~~
2107
2108void TSystem::ListLibraries(const char *regexp) {
2109 if (!(regexp && regexp[0]))
2110 regexp = ".*";
2111 TRegexp pat(regexp, kFALSE);
2112 TString libs(GetLibraries());
2113 TString tok;
2114 Ssiz_t from = 0, ext;
2115 while (libs.Tokenize(tok, from, " ")) {
2116 if ((tok.Index(pat, &ext) != 0) || (ext != tok.Length()))
2117 continue;
2118 std::cout << tok << "\n";
2119 }
2120}
2121
2122////////////////////////////////////////////////////////////////////////////////
2123/// Return the thread local storage for the custom last error message
2124
2126{
2127 TTHREAD_TLS_DECL( TString, gLastErrorString);
2128 return gLastErrorString;
2129}
2130
2131////////////////////////////////////////////////////////////////////////////////
2132/// Return the thread local storage for the custom last error message
2133
2135{
2136 return const_cast<TSystem*>(this)->GetLastErrorString();
2137}
2138
2139////////////////////////////////////////////////////////////////////////////////
2140/// Get list of shared libraries loaded at the start of the executable.
2141/// Returns 0 in case list cannot be obtained or in case of error.
2142
2144{
2145 return nullptr;
2146}
2147
2148////////////////////////////////////////////////////////////////////////////////
2149/// Return a space separated list of loaded shared libraries.
2150/// Regexp is a wildcard expression, see TRegexp::MakeWildcard.
2151/// This list is of a format suitable for a linker, i.e it may contain
2152/// -Lpathname and/or -lNameOfLib.
2153/// Option can be any of:
2154/// - S: shared libraries loaded at the start of the executable, because
2155/// they were specified on the link line.
2156/// - D: shared libraries dynamically loaded after the start of the program.
2157/// - L: this option is ignored, and available for backward compatibility.
2158
2159const char *TSystem::GetLibraries(const char *regexp, const char *options,
2160 Bool_t isRegexp)
2161{
2162 fListLibs.Clear();
2163
2164 TString libs;
2165 TString opt(options);
2166 Bool_t so2dylib = (opt.First('L') != kNPOS);
2167 if (so2dylib)
2168 opt.ReplaceAll("L", "");
2169
2170 if (opt.IsNull() || opt.First('D') != kNPOS)
2171 libs += gInterpreter->GetSharedLibs();
2172
2173 // Cint currently register all libraries that
2174 // are loaded and have a dictionary in them, this
2175 // includes all the libraries that are included
2176 // in the list of (hard) linked libraries.
2177
2178 TString slinked;
2179 const char *linked;
2180 if ((linked = GetLinkedLibraries())) {
2181 if (fLinkedLibs != LINKEDLIBS) {
2182 // This is not the default value, we need to keep the custom part.
2183 TString custom = fLinkedLibs;
2184 custom.ReplaceAll(LINKEDLIBS,linked);
2185 if (custom == fLinkedLibs) {
2186 // no replacement done, let's append linked
2187 slinked.Append(linked);
2188 slinked.Append(" ");
2189 }
2190 slinked.Append(custom);
2191 } else {
2192 slinked.Append(linked);
2193 }
2194 } else {
2195 slinked.Append(fLinkedLibs);
2196 }
2197
2198 if (opt.IsNull() || opt.First('S') != kNPOS) {
2199 // We are done, the statically linked libraries are already included.
2200 if (libs.Length() == 0) {
2201 libs = slinked;
2202 } else {
2203 // We need to add the missing linked library
2204
2205 static TString lastLinked;
2206 static TString lastAddMissing;
2207 if ( lastLinked != slinked ) {
2208 // Recalculate only if there was a change.
2209 static TRegexp separator("[^ \\t\\s]+");
2210 lastLinked = slinked;
2211 lastAddMissing.Clear();
2212
2213 Ssiz_t start, index, end;
2214 start = index = end = 0;
2215
2216 while ((start < slinked.Length()) && (index != kNPOS)) {
2217 index = slinked.Index(separator,&end,start);
2218 if (index >= 0) {
2219 TString sub = slinked(index,end);
2220 if (sub[0]=='-' && sub[1]=='L') {
2221 lastAddMissing.Prepend(" ");
2222 lastAddMissing.Prepend(sub);
2223 } else {
2224 if (libs.Index(sub) == kNPOS) {
2225 lastAddMissing.Prepend(" ");
2226 lastAddMissing.Prepend(sub);
2227 }
2228 }
2229 }
2230 start += end+1;
2231 }
2232 }
2233 libs.Prepend(lastAddMissing);
2234 }
2235 } else if (libs.Length() != 0) {
2236 // Let remove the statically linked library
2237 // from the list.
2238 static TRegexp separator("[^ \\t\\s]+");
2239 Ssiz_t start, index, end;
2240 start = index = end = 0;
2241
2242 while ((start < slinked.Length()) && (index != kNPOS)) {
2243 index = slinked.Index(separator,&end,start);
2244 if (index >= 0) {
2245 TString sub = slinked(index,end);
2246 if (sub[0]!='-' && sub[1]!='L') {
2247 libs.ReplaceAll(sub,"");
2248 }
2249 }
2250 start += end+1;
2251 }
2252 libs = libs.Strip(TString::kBoth);
2253 }
2254
2255 // Select according to regexp
2256 if (regexp && *regexp) {
2257 static TRegexp separator("[^ \\t\\s]+");
2258 TRegexp user_re(regexp, kTRUE);
2259 TString s;
2260 Ssiz_t start, index, end;
2261 start = index = end = 0;
2262
2263 while ((start < libs.Length()) && (index != kNPOS)) {
2264 index = libs.Index(separator,&end,start);
2265 if (index >= 0) {
2266 s = libs(index,end);
2267 if ((isRegexp && s.Index(user_re) != kNPOS) ||
2268 (!isRegexp && s.Index(regexp) != kNPOS)) {
2269 if (!fListLibs.IsNull())
2270 fListLibs.Append(" ");
2271 fListLibs.Append(s);
2272 }
2273 }
2274 start += end+1;
2275 }
2276 } else
2277 fListLibs = libs;
2278
2279#if defined(R__MACOSX)
2280// We need to remove the libraries that are dynamically loaded and not linked
2281{
2282 TString libs2 = fListLibs;
2283 TString maclibs;
2284
2285 static TRegexp separator("[^ \\t\\s]+");
2286 static TRegexp dynload("/lib-dynload/");
2287 // Skip libffi, it is a private library used by the system. This is visible in the stub .tbd file:
2288 // allowable-clients:
2289 // clients: [ '!' ]
2290 // See https://github.com/Homebrew/homebrew-core/issues/272324#issuecomment-5119880493 for more info
2291 static TRegexp libffiMatch("/usr/lib/libffi");
2292
2293 Ssiz_t start, index, end;
2294 start = index = end = 0;
2295
2296 while ((start < libs2.Length()) && (index != kNPOS)) {
2297 index = libs2.Index(separator, &end, start);
2298 if (index >= 0) {
2299 TString s = libs2(index, end);
2300 if (s.Index(dynload) == kNPOS && s.Index(libffiMatch) == kNPOS) {
2301 if (!maclibs.IsNull()) maclibs.Append(" ");
2302 maclibs.Append(s);
2303 }
2304 }
2305 start += end+1;
2306 }
2307 fListLibs = maclibs;
2308}
2309#endif
2310
2311 return fListLibs.Data();
2312}
2313
2314//---- RPC ---------------------------------------------------------------------
2315
2316////////////////////////////////////////////////////////////////////////////////
2317/// Get Internet Protocol (IP) address of host.
2318
2320{
2321 AbstractMethod("GetHostByName");
2322 return TInetAddress();
2323}
2324
2325////////////////////////////////////////////////////////////////////////////////
2326/// Get Internet Protocol (IP) address of remote host and port #.
2327
2329{
2330 AbstractMethod("GetPeerName");
2331 return TInetAddress();
2332}
2333
2334////////////////////////////////////////////////////////////////////////////////
2335/// Get Internet Protocol (IP) address of host and port #.
2336
2338{
2339 AbstractMethod("GetSockName");
2340 return TInetAddress();
2341}
2342
2343////////////////////////////////////////////////////////////////////////////////
2344/// Get port # of internet service.
2345
2347{
2348 AbstractMethod("GetServiceByName");
2349 return -1;
2350}
2351
2352////////////////////////////////////////////////////////////////////////////////
2353/// Get name of internet service.
2354
2356{
2357 AbstractMethod("GetServiceByPort");
2358 return nullptr;
2359}
2360
2361////////////////////////////////////////////////////////////////////////////////
2362/// Open a connection to another host.
2363
2364int TSystem::OpenConnection(const char *, int, int, const char *)
2365{
2366 AbstractMethod("OpenConnection");
2367 return -1;
2368}
2369
2370////////////////////////////////////////////////////////////////////////////////
2371/// Announce TCP/IP service.
2372
2374{
2375 AbstractMethod("AnnounceTcpService");
2376 return -1;
2377}
2378
2379////////////////////////////////////////////////////////////////////////////////
2380/// Announce UDP service.
2381
2383{
2384 AbstractMethod("AnnounceUdpService");
2385 return -1;
2386}
2387
2388////////////////////////////////////////////////////////////////////////////////
2389/// Announce unix domain service.
2390
2392{
2393 AbstractMethod("AnnounceUnixService");
2394 return -1;
2395}
2396
2397////////////////////////////////////////////////////////////////////////////////
2398/// Announce unix domain service.
2399
2400int TSystem::AnnounceUnixService(const char *, int)
2401{
2402 AbstractMethod("AnnounceUnixService");
2403 return -1;
2404}
2405
2406////////////////////////////////////////////////////////////////////////////////
2407/// Accept a connection.
2408
2410{
2411 AbstractMethod("AcceptConnection");
2412 return -1;
2413}
2414
2415////////////////////////////////////////////////////////////////////////////////
2416/// Close socket connection.
2417
2419{
2420 AbstractMethod("CloseConnection");
2421}
2422
2423////////////////////////////////////////////////////////////////////////////////
2424/// Receive exactly length bytes into buffer. Use opt to receive out-of-band
2425/// data or to have a peek at what is in the buffer (see TSocket).
2426
2427int TSystem::RecvRaw(int, void *, int, int)
2428{
2429 AbstractMethod("RecvRaw");
2430 return -1;
2431}
2432
2433////////////////////////////////////////////////////////////////////////////////
2434/// Send exactly length bytes from buffer. Use opt to send out-of-band
2435/// data (see TSocket).
2436
2437int TSystem::SendRaw(int, const void *, int, int)
2438{
2439 AbstractMethod("SendRaw");
2440 return -1;
2441}
2442
2443////////////////////////////////////////////////////////////////////////////////
2444/// Receive a buffer headed by a length indicator.
2445
2446int TSystem::RecvBuf(int, void *, int)
2447{
2448 AbstractMethod("RecvBuf");
2449 return -1;
2450}
2451
2452////////////////////////////////////////////////////////////////////////////////
2453/// Send a buffer headed by a length indicator.
2454
2455int TSystem::SendBuf(int, const void *, int)
2456{
2457 AbstractMethod("SendBuf");
2458 return -1;
2459}
2460
2461////////////////////////////////////////////////////////////////////////////////
2462/// Set socket option.
2463
2464int TSystem::SetSockOpt(int, int, int)
2465{
2466 AbstractMethod("SetSockOpt");
2467 return -1;
2468}
2469
2470////////////////////////////////////////////////////////////////////////////////
2471/// Get socket option.
2472
2473int TSystem::GetSockOpt(int, int, int*)
2474{
2475 AbstractMethod("GetSockOpt");
2476 return -1;
2477}
2478
2479//---- System, CPU and Memory info ---------------------------------------------
2480
2481////////////////////////////////////////////////////////////////////////////////
2482/// Returns static system info, like OS type, CPU type, number of CPUs
2483/// RAM size, etc into the SysInfo_t structure. Returns -1 in case of error,
2484/// 0 otherwise.
2485
2487{
2488 AbstractMethod("GetSysInfo");
2489 return -1;
2490}
2491
2492////////////////////////////////////////////////////////////////////////////////
2493/// Returns cpu load average and load info into the CpuInfo_t structure.
2494/// Returns -1 in case of error, 0 otherwise. Use sampleTime to set the
2495/// interval over which the CPU load will be measured, in ms (default 1000).
2496
2498{
2499 AbstractMethod("GetCpuInfo");
2500 return -1;
2501}
2502
2503////////////////////////////////////////////////////////////////////////////////
2504/// Returns ram and swap memory usage info into the MemInfo_t structure.
2505/// Returns -1 in case of error, 0 otherwise.
2506
2508{
2509 AbstractMethod("GetMemInfo");
2510 return -1;
2511}
2512
2513////////////////////////////////////////////////////////////////////////////////
2514/// Returns cpu and memory used by this process into the ProcInfo_t structure.
2515/// Returns -1 in case of error, 0 otherwise.
2516
2518{
2519 AbstractMethod("GetProcInfo");
2520 return -1;
2521}
2522
2523//---- Script Compiler ---------------------------------------------------------
2524
2525void AssignAndDelete(TString& target, char *tobedeleted)
2526{
2527 // Assign the char* value to the TString and then delete it.
2528
2529 target = tobedeleted;
2530 delete [] tobedeleted;
2531}
2532
2533#ifdef WIN32
2534
2535static TString R__Exec(const char *cmd)
2536{
2537 // Execute a command and return the stdout in a string.
2538
2539 FILE * f = gSystem->OpenPipe(cmd,"r");
2540 if (!f) {
2541 return "";
2542 }
2544
2545 char x;
2546 while ((x = fgetc(f))!=EOF ) {
2547 if (x=='\n' || x=='\r') break;
2548 result += x;
2549 }
2550
2551 fclose(f);
2552 return result;
2553}
2554
2555static void R__FixLink(TString &cmd)
2556{
2557 // Replace the call to 'link' by a full path name call based on where cl.exe is.
2558 // This prevents us from using inadvertently the link.exe provided by cygwin.
2559
2560 // check if link is the microsoft one...
2561 TString res = R__Exec("link 2>&1");
2562 if (res.Length()) {
2563 if (res.Contains("Microsoft (R) Incremental Linker"))
2564 return;
2565 }
2566 // else check availability of cygpath...
2567 res = R__Exec("cygpath . 2>&1");
2568 if (res.Length()) {
2569 if (res != ".")
2570 return;
2571 }
2572
2573 res = R__Exec("which cl.exe 2>&1|grep cl|sed 's,cl\\.exe$,link\\.exe,' 2>&1");
2574 if (res.Length()) {
2575 res = R__Exec(Form("cygpath -w '%s' 2>&1",res.Data()));
2576 if (res.Length()) {
2577 cmd.ReplaceAll(" link ",Form(" \"%s\" ",res.Data()));
2578 }
2579 }
2580}
2581#endif
2582
2583#if defined(__CYGWIN__)
2584static void R__AddPath(TString &target, const TString &path) {
2585 if (path.Length() > 2 && path[1]==':') {
2586 target += TString::Format("/cygdrive/%c",path[0]) + path(2,path.Length()-2);
2587 } else {
2588 target += path;
2589 }
2590}
2591#else
2592static void R__AddPath(TString &target, const TString &path) {
2593 target += path;
2594}
2595#endif
2596
2597static bool R__GenerateCompilerDependencies(const TString &depfilename, const TString &filename, const TString &targetname,
2598 const TString &includes, const TString &defines)
2599{
2600 TString compiler = CXX;
2601
2602 TString cmd = compiler;
2603 cmd += " " CXXOPT;
2604 cmd += " " ROOT_CXX_STANDARD_OPTION;
2605#ifdef WIN32
2606 cmd += " /nologo /EP /showIncludes";
2607#else
2608 cmd += " -MM";
2609 cmd += " -MF \"" + depfilename + "\"";
2610 cmd += " -MT \"";
2611 R__AddPath(cmd, targetname);
2612 cmd += "\" ";
2613#endif
2614 TString rootsysInclude = TROOT::GetIncludeDir();
2615 cmd += " -I\"";
2616 R__AddPath(cmd, rootsysInclude);
2617 cmd += "\" ";
2618
2619 cmd += includes;
2620 cmd += defines;
2621
2622#ifdef WIN32
2623 cmd += " /TP"; // avoid warning when header is .h but is C++ code
2624#else
2625 cmd += " -x c++-header"; // avoid warning when header is .h but is C++ code
2626#endif
2627 cmd += " \"";
2628 R__AddPath(cmd, filename);
2629 cmd += "\"";
2630
2631 if (gDebug > 4)
2632 ::Info("ACLiC", "%s", cmd.Data());
2633
2634#ifdef WIN32
2635 cmd += " > NUL 2>&1"; // ignore preprocessed C++ on stdout, redirect stderr to the pipe stream which includes the 'Note: including' part
2636 cmd = "\"" + cmd + "\"";
2637 FILE *pipe = gSystem->OpenPipe(cmd, "r");
2638 if (!pipe) {
2639 ::Warning("ACLiC", "Failed to open pipe dependencies for %s", filename.Data());
2640 return false;
2641 }
2642 std::ofstream depFile(depfilename, std::ios::out | std::ios::trunc);
2643 std::string allLines; // for error output
2644 if (depFile) {
2645 depFile << targetname << ": \\\n";
2646 char buffer[4096];
2647 const char *prefix = "Note: including file:";
2648 size_t prefixLen = strlen(prefix);
2649 while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
2650 std::string line(buffer);
2651 // MSVC prints "Note: including file: Windows_Full_Path_To_include"
2652 // Find and strip "Note: including file:"
2653 size_t pos = line.find(prefix);
2654 if (pos != std::string::npos) {
2655 std::string path = line.substr(pos + prefixLen);
2656 // Trim leading/trailing spaces or newlines
2657 path.erase(0, path.find_first_not_of(" \t"));
2658 path.erase(path.find_last_not_of(" \r\n\t") + 1);
2659 // Convert Windows backslashes to forward slashes for Makefile compatibility
2660 std::replace(path.begin(), path.end(), '\\', '/');
2661 if (!path.empty()) {
2662 depFile << " \"" << path << "\" \\\n";
2663 }
2664 } else { // other errors printed to stderr (for debugging)
2665 allLines += line + "\n";
2666 }
2667 }
2668 depFile << "#\n";
2669 depFile.close();
2670 }
2671 int retVal = gSystem->ClosePipe(pipe);
2672 if (retVal == -1) {
2673 ::Warning("ACLiC", "Failed to close pipe dependencies for %s, status '%d' when executing %s", filename.Data(), retVal, cmd.Data());
2674 ::Warning("ACLiC", "%s", allLines.c_str());
2675 return false;
2676 }
2677#else
2678 if (gSystem->Exec(cmd)) {
2679 ::Warning("ACLiC", "Failed to generate dependencies for %s", filename.Data());
2680 return false;
2681 }
2682#endif
2683
2684 return true;
2685}
2686
2687static TString R__GetRootDictionaryDependencies(const TString &targetname, const TString &incPath)
2688{
2689 TString adddictdep;
2690 R__AddPath(adddictdep,targetname);
2691 adddictdep += ": ";
2692 TString rootsysInclude = TROOT::GetIncludeDir();
2693
2694#if defined(R__HAS_CLING_DICTVERSION)
2695 {
2696 char *clingdictversion = gSystem->Which(incPath,"clingdictversion.h");
2697 if (clingdictversion) {
2698 R__AddPath(adddictdep,clingdictversion);
2699 adddictdep += " ";
2700 delete [] clingdictversion;
2701 } else {
2702 R__AddPath(adddictdep,rootsysInclude+"/clingdictversion.h ");
2703 }
2704 }
2705#endif
2706 {
2707 constexpr const char *dictHeaders[] = {"ROOT/RConfig.hxx",
2708 "TClass.h",
2709 "TDictAttributeMap.h",
2710 "TInterpreter.h",
2711 "TROOT.h",
2712 "TBuffer.h",
2713 "TMemberInspector.h",
2714 "TError.h",
2715 "RtypesImp.h",
2716 "TIsAProxy.h",
2717 "TFileMergeInfo.h",
2718 "TCollectionProxyInfo.h"};
2719
2720 for (const char *header : dictHeaders) {
2721 char *rootVersion = gSystem->Which(incPath, header);
2722 if (rootVersion) {
2723 R__AddPath(adddictdep,rootVersion);
2724 delete [] rootVersion;
2725 } else {
2726 R__AddPath(adddictdep, rootsysInclude + "/" + header);
2727 }
2728 adddictdep += " ";
2729 }
2730 }
2731 {
2732 // Add dependency on rootcling.
2733 char *rootCling = gSystem->Which(gSystem->Getenv("PATH"),"rootcling");
2734 if (rootCling) {
2735 R__AddPath(adddictdep,rootCling);
2736 adddictdep += " ";
2737 delete [] rootCling;
2738 }
2739 }
2740 return adddictdep;
2741}
2742
2743static void R__WriteDependencyFile(const TString & build_loc, const TString &depfilename, const TString &filename, const TString &library, const TString &libname,
2744 const TString &extension, const char *version_var_prefix, const TString &includes, const TString &defines, const TString &incPath)
2745{
2746 (void)build_loc;
2747 (void)extension;
2748 TString targetname;
2749 if (library.BeginsWith(gSystem->WorkingDirectory())) {
2750 Int_t len = strlen(gSystem->WorkingDirectory());
2751 if ( library.Length() > (len+1) ) {
2752 if (library[len] == '/' || library[len+1] != '\\' ) {
2753 targetname = library.Data() + len + 1;
2754 } else {
2755 targetname = library.Data() + len + 2;
2756 }
2757 } else {
2758 targetname = library;
2759 }
2760 } else {
2761 targetname = library;
2762 }
2763 if (!R__GenerateCompilerDependencies(depfilename, filename, targetname, includes, defines))
2764 return;
2765
2766 TString adddictdep = R__GetRootDictionaryDependencies(targetname, incPath);
2767
2768 std::ofstream depFile(depfilename, std::ios::out | std::ios::app);
2769 if (!depFile) {
2770 ::Warning("ACLiC", "Failed to open dependency file %s for %s after running rmkdepend", depfilename.Data(),
2771 library.Data());
2772 return;
2773 }
2774 depFile << adddictdep << "\n";
2775 depFile << libname << version_var_prefix << " \"" << ROOT_RELEASE << "\"\n";
2776}
2777
2778////////////////////////////////////////////////////////////////////////////////
2779/// This method compiles and loads a shared library containing
2780/// the code from the file "filename".
2781///
2782/// The return value is true (1) in case of success and false (0)
2783/// in case of error.
2784///
2785/// The possible options are:
2786/// - k : keep the shared library after the session end.
2787/// - f : force recompilation.
2788/// - g : compile with debug symbol
2789/// - O : optimized the code
2790/// - c : compile only, do not attempt to load the library.
2791/// - s : silence all informational output
2792/// - v : output all information output
2793/// - d : debug ACLiC, keep all the output files.
2794/// - - : if buildir is set, use a flat structure (see buildir below)
2795///
2796/// If library_specified is specified, CompileMacro generates the file
2797/// "library_specified".soext where soext is the shared library extension for
2798/// the current platform.
2799///
2800/// If build_dir is specified, it is used as an alternative 'root' for the
2801/// generation of the shared library. The library is stored in a sub-directories
2802/// of 'build_dir' including the full pathname of the script unless a flat
2803/// directory structure is requested ('-' option). With the '-' option the libraries
2804/// are created directly in the directory 'build_dir'; in particular this means that
2805/// 2 scripts with the same name in different source directory will over-write each
2806/// other's library.
2807/// See also TSystem::SetBuildDir.
2808///
2809/// If dirmode is not zero and we need to create the target directory, the
2810/// file mode bit will be change to 'dirmode' using chmod.
2811///
2812/// If library_specified is not specified, CompileMacro generate a default name
2813/// for library by taking the name of the file "filename" but replacing the
2814/// dot before the extension by an underscore and by adding the shared
2815/// library extension for the current platform.
2816/// For example on most platform, hsimple.cxx will generate hsimple_cxx.so
2817///
2818/// It uses the directive fMakeSharedLibs to create a shared library.
2819/// If loading the shared library fails, it tries to output a list of missing
2820/// symbols by creating an executable (on some platforms like OSF, this does
2821/// not HAVE to be an executable) containing the script. It uses the
2822/// directive fMakeExe to do so.
2823/// For both directives, before passing them to TSystem::Exec, it expands the
2824/// variables $SourceFiles, $SharedLib, $LibName, $IncludePath, $LinkedLibs,
2825/// $DepLibs, $ExeName and $ObjectFiles. See SetMakeSharedLib() for more
2826/// information on those variables.
2827///
2828/// This method is used to implement the following feature:
2829///
2830/// Synopsis:
2831///
2832/// The purpose of this addition is to allow the user to use an external
2833/// compiler to create a shared library from its C++ macro (scripts).
2834/// Currently in order to execute a script, a user has to type at the root
2835/// prompt
2836/// ~~~ {.cpp}
2837/// .X myfunc.C(arg1,arg2)
2838/// ~~~
2839/// We allow them to type:
2840/// ~~~ {.cpp}
2841/// .X myfunc.C++(arg1,arg2)
2842/// ~~~
2843/// or
2844/// ~~~ {.cpp}
2845/// .X myfunc.C+(arg1,arg2)
2846/// ~~~
2847/// In which case an external compiler will be called to create a shared
2848/// library. This shared library will then be loaded and the function
2849/// myfunc will be called with the two arguments. With '++' the shared library
2850/// is always recompiled. With '+' the shared library is recompiled only
2851/// if it does not exist yet or the macro file is newer than the shared
2852/// library.
2853///
2854/// Of course the + and ++ notation is supported in similar way for .x and .L.
2855///
2856/// Through the function TSystem::SetMakeSharedLib(), the user will be able to
2857/// indicate, with shell commands, how to build a shared library (a good
2858/// default will be provided). The most common change, namely where to find
2859/// header files, will be available through the function
2860/// TSystem::SetIncludePath().
2861/// A good default will be provided so that a typical user session should be at
2862/// most:
2863/// ~~~ {.cpp}
2864/// root[1] gSystem->SetIncludePath("-I$ROOTSYS/include
2865/// -I$HOME/mypackage/include");
2866/// root[2] .x myfunc.C++(10,20);
2867/// ~~~
2868/// The user may sometimes try to compile a script before it has loaded all the
2869/// needed shared libraries. In this case we want to be helpful and output a
2870/// list of the unresolved symbols. So if the loading of the created shared
2871/// library fails, we will try to build a executable that contains the
2872/// script. The linker should then output a list of missing symbols.
2873///
2874/// To support this we provide a TSystem::SetMakeExe() function, that sets the
2875/// directive telling how to create an executable. The loader will need
2876/// to be informed of all the libraries available. The information about
2877/// the libraries that has been loaded by .L and TSystem::Load() is accessible
2878/// to the script compiler. However, the information about
2879/// the libraries that have been selected at link time by the application
2880/// builder (like the root libraries for root.exe) are not available and need
2881/// to be explicitly listed in fLinkedLibs (either by default or by a call to
2882/// TSystem::SetLinkedLibs()).
2883///
2884/// To simplify customization we could also add to the .rootrc support for the
2885/// variables
2886/// ~~~ {.cpp}
2887/// Unix.*.Root.IncludePath: -I$ROOTSYS/include
2888/// WinNT.*.Root.IncludePath: -I%ROOTSYS%/include
2889///
2890/// Unix.*.Root.LinkedLibs: -L$ROOTSYS/lib -lBase ....
2891/// WinNT.*.Root.LinkedLibs: %ROOTSYS%/lib/*.lib msvcrt.lib ....
2892/// ~~~
2893/// And also support for MakeSharedLibs() and MakeExe().
2894///
2895/// (the ... have to be replaced by the actual values and are here only to
2896/// shorten this comment).
2897///
2898/// Note that the default behavior is to remove libraries when closing ROOT,
2899/// ie TSystem::CleanCompiledMacros() is called in the TROOT destructor.
2900/// The default behavior of .L script.C+ is the opposite one, leaving things
2901/// after closing, without removing. In other words, .L always passes the 'k'
2902/// option behind the scenes.
2903
2905 const char *library_specified,
2906 const char *build_dir,
2907 UInt_t dirmode)
2908{
2909 static const char *version_var_prefix = "__ROOTBUILDVERSION=";
2910
2911 // ======= Analyze the options
2912 Bool_t keep = kFALSE;
2913 Bool_t recompile = kFALSE;
2914 int mode = fAclicMode;
2915 Bool_t loadLib = kTRUE;
2916 Bool_t withInfo = kTRUE;
2917 Bool_t verbose = kFALSE;
2918 Bool_t internalDebug = kFALSE;
2919 if (opt) {
2920 keep = (strchr(opt,'k')!=nullptr);
2921 recompile = (strchr(opt,'f')!=nullptr);
2922 if (strchr(opt,'O')!=nullptr) {
2923 mode |= kOpt;
2924 }
2925 if (strchr(opt,'g')!=nullptr) {
2926 mode |= kDebug;
2927 }
2928 if (strchr(opt,'c')!=nullptr) {
2929 loadLib = kFALSE;
2930 }
2931 withInfo = strchr(opt, 's') == nullptr;
2932 verbose = strchr(opt, 'v') != nullptr;
2933 internalDebug = strchr(opt, 'd') != nullptr;
2934 }
2935 if (mode==kDefault) {
2936 TString rootbuild = ROOTBUILD;
2937 if (rootbuild.Index("debug",0,TString::kIgnoreCase)==kNPOS) {
2938 mode = kOpt;
2939 } else {
2940 mode = kDebug;
2941 }
2942 }
2943#if defined(_MSC_VER) && defined(_DEBUG)
2944 // if ROOT is build in debug mode, ACLiC must also build in debug mode
2945 // for compatibility reasons
2946 if (!(mode & kDebug))
2947 mode |= kDebug;
2948#endif
2949 UInt_t verboseLevel = verbose ? 7 : gDebug;
2950 Bool_t flatBuildDir = (fAclicProperties & kFlatBuildDir) || (opt && strchr(opt,'-')!=nullptr);
2951
2952 // if non-zero, build_loc indicates where to build the shared library.
2953 TString build_loc = ExpandFileName(GetBuildDir());
2954 if (build_dir && strlen(build_dir)) build_loc = build_dir;
2955 if (build_loc == ".") {
2956 build_loc = WorkingDirectory();
2957 } else if (build_loc.Length() && (!IsAbsoluteFileName(build_loc)) ) {
2958 PrependPathName( WorkingDirectory(), build_loc );
2959 }
2960
2961 // Get the include directory list in the dir1:dir2:dir3 format
2962 // [Used for generating the .d file and to look for header files for
2963 // the linkdef file]
2964 TString incPath = GetIncludePath(); // of the form -Idir1 -Idir2 -Idir3
2965 incPath.Append(":").Prepend(" ");
2966 if (gEnv) {
2967 TString fromConfig = gEnv->GetValue("ACLiC.IncludePaths","");
2968 incPath.Append(fromConfig);
2969 }
2970 incPath.ReplaceAll(" -I",":"); // of form :dir1 :dir2:dir3
2971 auto posISysRoot = incPath.Index(" -isysroot \"");
2972 if (posISysRoot != kNPOS) {
2973 auto posISysRootEnd = incPath.Index('"', posISysRoot + 12);
2974 if (posISysRootEnd != kNPOS) {
2975 // NOTE: should probably just skip isysroot for dependency analysis.
2976 // (And will, in the future - once we rely on compiler-generated .d files.)
2977 incPath.Insert(posISysRootEnd - 1, "/usr/include/");
2978 incPath.Replace(posISysRoot, 12, ":\"");
2979 }
2980 }
2981 while ( incPath.Index(" :") != -1 ) {
2982 incPath.ReplaceAll(" :",":");
2983 }
2984 incPath.Prepend(":.:");
2985 incPath.Prepend(WorkingDirectory());
2986
2987 // ======= Get the right file names for the dictionary and the shared library
2988 TString expFileName(filename);
2989 ExpandPathName( expFileName );
2990 expFileName = gSystem->UnixPathName(expFileName);
2991 TString library = expFileName;
2992 if (! IsAbsoluteFileName(library) )
2993 {
2994 const char *whichlibrary = Which(incPath,library);
2995 if (whichlibrary) {
2996 library = whichlibrary;
2997 delete [] whichlibrary;
2998 } else {
2999 ::Error("ACLiC","The file %s can not be found in the include path: %s",filename,incPath.Data());
3000 return kFALSE;
3001 }
3002 } else {
3003 if (gSystem->AccessPathName(library)) {
3004 ::Error("ACLiC","The file %s can not be found.",filename);
3005 return kFALSE;
3006 }
3007 }
3008 { // Remove multiple '/' characters, rootcling treats them as comments.
3009 Ssiz_t pos = 0;
3010 while ((pos = library.Index("//", 2, pos, TString::kExact)) != kNPOS) {
3011 library.Remove(pos, 1);
3012 }
3013 }
3014 library = gSystem->UnixPathName(library);
3015 TString filename_fullpath = library;
3016
3017 TString file_dirname = GetDirName( filename_fullpath );
3018 // For some probably good reason, DirName on Windows returns the 'name' of
3019 // the directory, omitting the drive letter (even if there was one). In
3020 // consequence the result is not usable as a 'root directory', we need to
3021 // add the drive letter if there was one..
3022 if (library.Length()>1 && isalpha(library[0]) && library[1]==':') {
3023 file_dirname.Prepend(library(0,2));
3024 }
3025 TString file_location( file_dirname ); // Location of the script.
3026 incPath.Prepend( file_location + ":" );
3027
3028 Ssiz_t dot_pos = library.Last('.');
3029 TString extension, libname_noext = library;
3030 if (dot_pos >= 0) {
3031 libname_noext.Remove(dot_pos);
3032 extension = library(dot_pos+1, library.Length()-dot_pos-1);
3033 }
3034
3035 // Extension of shared library is platform dependent!!
3036 TString suffix = TString("_") + extension + "." + fSoExt;
3037 if (dot_pos >= 0)
3038 library.Replace( dot_pos, library.Length()-dot_pos, suffix);
3039 else
3040 library.Append(suffix);
3041
3042 TString libname ( BaseName( libname_noext ) );
3043 libname.Append("_").Append(extension);
3044
3045 if (library_specified && strlen(library_specified) ) {
3046 // Use the specified name instead of the default
3047 libname = BaseName( library_specified );
3048 library = library_specified;
3049 ExpandPathName( library );
3050 if (! IsAbsoluteFileName(library) ) {
3051 PrependPathName( WorkingDirectory(), library );
3052 }
3053 libname_noext = library_specified;
3054 library = TString(library) + "." + fSoExt;
3055 }
3056 library = gSystem->UnixPathName(library);
3057
3058 TString libname_ext ( libname );
3059 libname_ext += "." + fSoExt;
3060
3061 TString lib_dirname = GetDirName( library );
3062 // For some probably good reason, DirName on Windows returns the 'name' of
3063 // the directory, omitting the drive letter (even if there was one). In
3064 // consequence the result is not useable as a 'root directory', we need to
3065 // add the drive letter if there was one..
3066 if (library.Length()>1 && isalpha(library[0]) && library[1]==':') {
3067 lib_dirname.Prepend(library(0,2));
3068 }
3069 // Strip potential, somewhat redundant '/.' from the pathname ...
3070 if ( strncmp( &(lib_dirname[lib_dirname.Length()-2]), "/.", 2) == 0 ) {
3071 lib_dirname.Remove(lib_dirname.Length()-2);
3072 }
3073 if ( strncmp( &(lib_dirname[lib_dirname.Length()-2]), "\\.", 2) == 0 ) {
3074 lib_dirname.Remove(lib_dirname.Length()-2);
3075 }
3076 TString lib_location( lib_dirname );
3077 Bool_t mkdirFailed = kFALSE;
3078
3079 if (build_loc.Length()==0) {
3080 build_loc = lib_location;
3081 } else {
3082 // Removes an existing disk specification from the names
3083 TRegexp disk_finder ("[A-z]:");
3084 Int_t pos = library.Index( disk_finder );
3085 if (pos==0) library.Remove(pos,3);
3086 pos = lib_location.Index( disk_finder );
3087 if (pos==0) lib_location.Remove(pos,3);
3088
3089 if (flatBuildDir) {
3090 library = libname_ext;
3091 PrependPathName( build_loc, library) ;
3092 } else {
3093 PrependPathName( build_loc, library) ;
3094 }
3095
3096 Bool_t canWriteBuild_loc = !gSystem->AccessPathName(build_loc,kWritePermission);
3097 TString build_loc_store( build_loc );
3098 if (!flatBuildDir) {
3099 TString temp_lib_location = lib_location;
3100 build_loc = PrependPathName( build_loc, temp_lib_location);
3101 }
3102
3103 if (gSystem->AccessPathName(build_loc,kFileExists)) {
3104 mkdirFailed = (0 != mkdir(build_loc, true));
3105 if (mkdirFailed && !canWriteBuild_loc) {
3106 // The mkdir failed __and__ we can not write to the target directory,
3107 // let make sure the error message will be about the target directory
3108 build_loc = build_loc_store;
3109 mkdirFailed = kFALSE;
3110 } else if (!mkdirFailed && dirmode!=0) {
3111 Chmod(build_loc,dirmode);
3112 }
3113 }
3114 }
3115 library = gSystem->UnixPathName(library);
3116
3117 // ======= Check if the library need to loaded or compiled
3118 if (!gInterpreter->IsLibraryLoaded(library) && gInterpreter->IsLoaded(expFileName)) {
3119 // the script has already been loaded in interpreted mode
3120 // Let's warn the user and unload it.
3121
3122 if (withInfo) {
3123 ::Info("ACLiC","script has already been loaded in interpreted mode");
3124 ::Info("ACLiC","unloading %s and compiling it", filename);
3125 }
3126
3127 if ( gInterpreter->UnloadFile( expFileName ) != 0 ) {
3128 // We can not unload it.
3129 return kFALSE;
3130 }
3131 }
3132
3133 // Calculate the -I lines
3134 TString includes = GetIncludePath();
3135 includes.ReplaceAll("-I ", "-I");
3136 includes.Prepend(' ');
3137
3138 {
3139 // I need to replace the -Isomerelativepath by -I../ (or -I..\ on NT)
3140 TRegexp rel_inc(" -I[^\"/\\\\$\\%-][^:\\s]+");
3141 Int_t len,pos;
3142 pos = rel_inc.Index(includes,&len);
3143 while( len != 0 ) {
3144 TString sub = includes(pos,len);
3145 sub.Remove(0,3); // Remove ' -I'
3147 sub.Prepend(" -I\"");
3148 if (sub.EndsWith(" "))
3149 sub.Chop(); // Remove trailing space (i.e between the -Is ...
3150 sub.Append("\" ");
3151 includes.Replace(pos,len,sub);
3152 pos = rel_inc.Index(includes,&len);
3153 }
3154 }
3155 {
3156 // I need to replace the -I"somerelativepath" by -I"$cwd/ (or -I"$cwd\ on NT)
3157 TRegexp rel_inc(" -I\"[^/\\\\$\\%-][^:\\s]+");
3158 Int_t len,pos;
3159 pos = rel_inc.Index(includes,&len);
3160 while( len != 0 ) {
3161 TString sub = includes(pos,len);
3162 sub.Remove(0,4); // Remove ' -I"'
3164 sub.Prepend(" -I\"");
3165 includes.Replace(pos,len,sub);
3166 pos = rel_inc.Index(includes,&len);
3167 }
3168 }
3169 //includes += " -I\"" + build_loc;
3170 //includes += "\" -I\"";
3171 //includes += WorkingDirectory();
3172// if (includes[includes.Length()-1] == '\\') {
3173// // The current directory is (most likely) the root of a windows drive and
3174// // has a trailing \ which would espace the quote if left by itself.
3175// includes += '\\';
3176// }
3177// includes += "\"";
3178 if (gEnv) {
3179 TString fromConfig = gEnv->GetValue("ACLiC.IncludePaths","");
3180 includes.Append(" ").Append(fromConfig).Append(" ");
3181 }
3182
3183 // Extract the -D for the dependency generation.
3184 TString defines = " ";
3185 {
3186 TString cmd = GetMakeSharedLib();
3187 TRegexp rel_def("-D[^\\s\\t\\n\\r]*");
3188 Int_t len,pos;
3189 pos = rel_def.Index(cmd,&len);
3190 while( len != 0 ) {
3191 defines += cmd(pos,len);
3192 defines += " ";
3193 pos = rel_def.Index(cmd,&len,pos+1);
3194 }
3195
3196 }
3197
3198 TString emergency_loc;
3199 {
3201 if (ug) {
3202 emergency_loc = (ug->fUser).Data();
3203 PrependPathName( TempDirectory(), emergency_loc );
3204 delete ug;
3205 } else {
3206 emergency_loc = TempDirectory();
3207 }
3208 }
3209
3210 Bool_t canWrite = !gSystem->AccessPathName(build_loc,kWritePermission);
3211
3212 Bool_t modified = kFALSE;
3213
3214 // Generate the dependency filename
3215 TString depdir = build_loc;
3216 TString depfilename = BaseName(libname_noext);
3217 PrependPathName(depdir, depfilename);
3218 depfilename += "_" + extension + ".d";
3219
3220 if ( !recompile ) {
3221
3222 Long_t lib_time, file_time;
3223
3224 if ((gSystem->GetPathInfo( library, nullptr, (Long_t*)nullptr, nullptr, &lib_time ) != 0) ||
3225 (gSystem->GetPathInfo( expFileName, nullptr, (Long_t*)nullptr, nullptr, &file_time ) == 0 &&
3226 (lib_time < file_time))) {
3227
3228 // the library does not exist or is older than the script.
3229 recompile = kTRUE;
3230 modified = kTRUE;
3231
3232 } else {
3233
3234 if ( gSystem->GetPathInfo( depfilename, nullptr,(Long_t*) nullptr, nullptr, &file_time ) != 0 ) {
3235 if (!canWrite) {
3236 depdir = emergency_loc;
3237 depfilename = BaseName(libname_noext);
3238 PrependPathName(depdir, depfilename);
3239 depfilename += "_" + extension + ".d";
3240 }
3241 R__WriteDependencyFile(build_loc, depfilename, filename_fullpath, library, libname, extension, version_var_prefix, includes, defines, incPath);
3242 }
3243 }
3244
3245 if (!modified) {
3246
3247 // We need to check the dependencies
3248 FILE * depfile = fopen(depfilename.Data(),"r");
3249 if (depfile==nullptr) {
3250 // there is no accessible dependency file, let's assume the library has been
3251 // modified
3252 modified = kTRUE;
3253 recompile = kTRUE;
3254
3255 } else {
3256
3257 TString version_var = libname + version_var_prefix;
3258
3259 Int_t sz = 256;
3260 char *line = new char[sz];
3261 line[0] = 0;
3262
3263 int c;
3264 Int_t current = 0;
3265 Int_t nested = 0;
3266 Bool_t hasversion = false;
3267
3268 while ((c = fgetc(depfile)) != EOF) {
3269 if (c=='#') {
3270 // skip comment
3271 while ((c = fgetc(depfile)) != EOF) {
3272 if (c=='\n') {
3273 break;
3274 }
3275 }
3276 continue;
3277 }
3278 if (current && line[current-1]=='=' && strncmp(version_var.Data(),line,current)==0) {
3279
3280 // The next word will be the version number.
3281 hasversion = kTRUE;
3282 line[0] = 0;
3283 current = 0;
3284 } else if (isspace(c) && !nested) {
3285 if (current) {
3286 if (line[current-1]!=':') {
3287 // ignore target
3288 line[current] = 0;
3289
3290 Long_t filetime;
3291 if (hasversion) {
3292 modified |= strcmp(ROOT_RELEASE,line)!=0;
3293 hasversion = kFALSE;
3294 } else if ( gSystem->GetPathInfo( line, nullptr, (Long_t*)nullptr, nullptr, &filetime ) == 0 ) {
3295 modified |= ( lib_time <= filetime );
3296 }
3297 }
3298 }
3299 current = 0;
3300 line[0] = 0;
3301 } else {
3302 if (current==sz-1) {
3303 sz = 2*sz;
3304 char *newline = new char[sz];
3305 memcpy(newline,line, current);
3306 delete [] line;
3307 line = newline;
3308 }
3309 if (c=='"') nested = !nested;
3310 else {
3311 line[current] = c;
3312 current++;
3313 }
3314 }
3315 }
3316 delete [] line;
3317 fclose(depfile);
3318 recompile = modified;
3319
3320 }
3321
3322 }
3323 }
3324
3325 if ( gInterpreter->IsLibraryLoaded(library)
3326 || strlen(GetLibraries(library,"D",kFALSE)) != 0 ) {
3327 // The library has already been built and loaded.
3328
3329 Bool_t reload = kFALSE;
3330 TNamed *libinfo = (TNamed*)fCompiled->FindObject(library);
3331 if (libinfo) {
3332 Long_t load_time = libinfo->GetUniqueID();
3333 Long_t lib_time;
3334 if ( gSystem->GetPathInfo( library, nullptr, (Long_t*)nullptr, nullptr, &lib_time ) == 0
3335 && (lib_time>load_time)) {
3336 reload = kTRUE;
3337 }
3338 }
3339
3340 if ( !recompile && reload ) {
3341
3342 if (withInfo) {
3343 ::Info("ACLiC","%s has been modified and will be reloaded",
3344 libname.Data());
3345 }
3346 if ( gInterpreter->UnloadFile( library.Data() ) != 0 ) {
3347 // The library is being used. We can not unload it.
3348 return kFALSE;
3349 }
3350 if (libinfo) {
3351 fCompiled->Remove(libinfo);
3352 delete libinfo;
3353 libinfo = nullptr;
3354 }
3355 TNamed *k = new TNamed(library,library);
3356 Long_t lib_time;
3357 gSystem->GetPathInfo( library, nullptr, (Long_t*)nullptr, nullptr, &lib_time );
3358 k->SetUniqueID(lib_time);
3359 if (!keep) k->SetBit(kMustCleanup);
3360 fCompiled->Add(k);
3361
3362 return !gSystem->Load(library);
3363 }
3364
3365 if (withInfo) {
3366 ::Info("ACLiC","%s script has already been compiled and loaded",
3367 modified ? "modified" : "unmodified");
3368 }
3369
3370 if ( !recompile ) {
3371 return kTRUE;
3372 } else {
3373 if (withInfo) {
3374 ::Info("ACLiC","it will be regenerated and reloaded!");
3375 }
3376 if ( gInterpreter->UnloadFile( library.Data() ) != 0 ) {
3377 // The library is being used. We can not unload it.
3378 return kFALSE;
3379 }
3380 if (libinfo) {
3381 fCompiled->Remove(libinfo);
3382 delete libinfo;
3383 libinfo = nullptr;
3384 }
3385 Unlink(library);
3386 }
3387
3388 }
3389
3390 TString libmapfilename = libname;
3391 PrependPathName( build_loc, libmapfilename );
3392 libmapfilename += ".rootmap";
3393#if (defined(R__MACOSX) && !defined(MAC_OS_X_VERSION_10_5)) || defined(R__WIN32)
3394 Bool_t produceRootmap = kTRUE;
3395#else
3396 Bool_t produceRootmap = kFALSE;
3397#endif
3398 Bool_t linkDepLibraries = !produceRootmap;
3399 if (gEnv) {
3400#if (defined(R__MACOSX) && !defined(MAC_OS_X_VERSION_10_5))
3401 Int_t linkLibs = gEnv->GetValue("ACLiC.LinkLibs",2);
3402#elif defined(R__WIN32)
3403 Int_t linkLibs = gEnv->GetValue("ACLiC.LinkLibs",3);
3404#else
3405 Int_t linkLibs = gEnv->GetValue("ACLiC.LinkLibs",1);
3406#endif
3407 produceRootmap = linkLibs & 0x2;
3408 linkDepLibraries = linkLibs & 0x1;
3409 }
3410
3411 // FIXME: Triggers clang false positive warning -Wunused-lambda-capture.
3412 /*constexpr const*/ bool useCxxModules =
3413#ifdef R__USE_CXXMODULES
3414 true;
3415#else
3416 false;
3417#endif
3418
3419 // FIXME: Switch to generic polymorphic when we make c++14 default.
3420 auto ForeachSharedLibDep = [](const char *lib, std::function<bool(const char *)> f) {
3421 using std::string, std::vector, std::istringstream, std::istream_iterator;
3422 string deps = gInterpreter->GetSharedLibDeps(lib, /*tryDyld*/ true);
3423 istringstream iss(deps);
3424 vector<string> libs{istream_iterator<std::string>{iss}, istream_iterator<string>{}};
3425 // Skip the first element: it is a relative path to `lib`.
3426 for (auto I = libs.begin() + 1, E = libs.end(); I != E; ++I)
3427 if (!f(I->c_str()))
3428 break;
3429 };
3430 auto LoadLibrary = [useCxxModules, produceRootmap, ForeachSharedLibDep](const TString &lib) {
3431 // We have no rootmap files or modules to construct `-l` flags enabling
3432 // explicit linking. We have to resolve the dependencies by ourselves
3433 // taking the job of the dyld.
3434 // FIXME: This is a rare case where we have rootcling running with
3435 // modules disabled. Remove this code once we fully switch to modules,
3436 // or implement a special flag in rootcling which selective enables
3437 // modules for dependent libraries and does not produce a module for
3438 // the ACLiC library.
3439 if (useCxxModules && !produceRootmap) {
3440 std::function<bool(const char *)> LoadLibF = [](const char *dep) {
3441 return gInterpreter->Load(dep, /*skipReload*/ true) >= 0;
3442 };
3443 ForeachSharedLibDep(lib, LoadLibF);
3444 }
3445 return !gSystem->Load(lib);
3446 };
3447
3448 if (!recompile) {
3449 // The library already exist, let's just load it.
3450 if (loadLib) {
3451 TNamed *k = new TNamed(library,library);
3452 Long_t lib_time;
3453 gSystem->GetPathInfo( library, nullptr, (Long_t*)nullptr, nullptr, &lib_time );
3454 k->SetUniqueID(lib_time);
3455 if (!keep) k->SetBit(kMustCleanup);
3456 fCompiled->Add(k);
3457
3458 gInterpreter->GetSharedLibDeps(library);
3459
3460 return LoadLibrary(library);
3461 }
3462 else return kTRUE;
3463 }
3464
3465 if (!canWrite && recompile) {
3466
3467 if (mkdirFailed) {
3468 ::Warning("ACLiC","Could not create the directory: %s",
3469 build_loc.Data());
3470 } else {
3471 ::Warning("ACLiC","%s is not writable!",
3472 build_loc.Data());
3473 }
3474 if (emergency_loc == build_dir ) {
3475 ::Error("ACLiC","%s is the last resort location (i.e. temp location)",build_loc.Data());
3476 return kFALSE;
3477 }
3478 ::Warning("ACLiC","Output will be written to %s",
3479 emergency_loc.Data());
3480 return CompileMacro(expFileName, opt, library_specified, emergency_loc, dirmode);
3481 }
3482
3483 if (withInfo) {
3484 Info("ACLiC","creating shared library %s",library.Data());
3485 }
3486
3487 R__WriteDependencyFile(build_loc, depfilename, filename_fullpath, library, libname, extension, version_var_prefix, includes, defines, incPath);
3488
3489 // ======= Select the dictionary name
3490 TString dict = libname + "_ACLiC_dict";
3491
3492 // the file name end up in the file produced
3493 // by rootcling as a variable name so all character need to be valid!
3494 static const int maxforbidden = 27;
3495 static const char *forbidden_chars[maxforbidden] =
3496 { "+","-","*","/","&","%","|","^",">","<",
3497 "=","~",".","(",")","[","]","!",",","$",
3498 " ",":","'","#","@","\\","\"" };
3499 for( int ic = 0; ic < maxforbidden; ic++ ) {
3500 dict.ReplaceAll( forbidden_chars[ic],"_" );
3501 }
3502 if ( dict.Last('.')!=dict.Length()-1 ) dict.Append(".");
3503 PrependPathName( build_loc, dict ) ;
3504 TString dicth = dict;
3505 TString dictObj = dict;
3506 dict += "cxx"; //no need to keep the extension of the original file, any extension will do
3507 dicth += "h";
3508 dictObj += fObjExt;
3509
3510 // ======= Generate a linkdef file
3511 TString linkdef = libname;
3512 PrependPathName( build_loc, linkdef );
3513 linkdef += "_ACLiC_linkdef.h";
3514 std::ofstream linkdefFile( linkdef, std::ios::out );
3515 linkdefFile << "// File Automatically generated by the ROOT Script Compiler "
3516 << std::endl;
3517 linkdefFile << std::endl;
3518 linkdefFile << "#ifdef __CLING__" << std::endl;
3519 linkdefFile << std::endl;
3520 linkdefFile << "#pragma link C++ nestedclasses;" << std::endl;
3521 linkdefFile << "#pragma link C++ nestedtypedefs;" << std::endl;
3522 linkdefFile << std::endl;
3523
3524 // We want to look for a header file that has the same name as the macro
3525
3526 const char * extensions[] = { ".h", ".hh", ".hpp", ".hxx", ".hPP", ".hXX" };
3527
3528 int i;
3529 for (i = 0; i < 6; i++ ) {
3530 char * name;
3531 TString extra_linkdef = BaseName( libname_noext );
3532 extra_linkdef.Append(GetLinkdefSuffix());
3533 extra_linkdef.Append(extensions[i]);
3534 name = Which(incPath,extra_linkdef);
3535 if (name) {
3536 if (verboseLevel>4 && withInfo) {
3537 Info("ACLiC","including extra linkdef file: %s",name);
3538 }
3539 linkdefFile << "#include \"" << name << "\"" << std::endl;
3540 delete [] name;
3541 }
3542 }
3543
3544 if (verboseLevel>5 && withInfo) {
3545 Info("ACLiC","looking for header in: %s",incPath.Data());
3546 }
3547 for (i = 0; i < 6; i++ ) {
3548 char * name;
3549 TString lookup = BaseName( libname_noext );
3550 lookup.Append(extensions[i]);
3551 name = Which(incPath,lookup);
3552 if (name) {
3553 linkdefFile << "#pragma link C++ defined_in "<<gSystem->UnixPathName(name)<<";"<< std::endl;
3554 delete [] name;
3555 }
3556 }
3557 linkdefFile << "#pragma link C++ defined_in \""<<filename_fullpath << "\";" << std::endl;
3558 linkdefFile << std::endl;
3559 linkdefFile << "#endif" << std::endl;
3560 linkdefFile.close();
3561 // ======= Generate the list of rootmap files to be looked at
3562
3563 TString mapfile = libname;
3564 PrependPathName( build_loc, mapfile );
3565 mapfile += "_ACLiC_map";
3566 TString mapfilein = mapfile + ".in";
3567 TString mapfileout = mapfile + ".out";
3568
3569 Bool_t needLoadMap = kFALSE;
3570 if (!useCxxModules) {
3571 if (gInterpreter->GetSharedLibDeps(library) != nullptr) {
3572 gInterpreter->UnloadLibraryMap(libname);
3573 needLoadMap = kTRUE;
3574 }
3575 }
3576
3577 std::ofstream mapfileStream( mapfilein, std::ios::out );
3578 {
3579 TString name = ".rootmap";
3580 TString sname = "system.rootmap";
3581 TString file = sname;
3583 if (gSystem->AccessPathName(file)) {
3584 // for backward compatibility check also $ROOTSYS/system<name> if
3585 // $ROOTSYS/etc/system<name> does not exist
3586 file = sname;
3588 if (gSystem->AccessPathName(file)) {
3589 // for backward compatibility check also $ROOTSYS/<name> if
3590 // $ROOTSYS/system<name> does not exist
3591 file = name;
3593 }
3594 }
3595 mapfileStream << file << std::endl;
3596 file = name;
3598 mapfileStream << file << std::endl;
3599 mapfileStream << name << std::endl;
3600 if (gInterpreter->GetRootMapFiles()) {
3601 for (i = 0; i < gInterpreter->GetRootMapFiles()->GetEntriesFast(); i++) {
3602 mapfileStream << ((TNamed*)gInterpreter->GetRootMapFiles()->At(i))->GetTitle() << std::endl;
3603 }
3604 }
3605 }
3606 mapfileStream.close();
3607
3608 // ======= Generate the rootcling command line
3609 TString rcling = "rootcling";
3611 rcling += " \"--lib-list-prefix=";
3612 rcling += mapfile;
3613 rcling += "\" -f \"";
3614 rcling.Append(dict).Append("\" ");
3615
3616 if (produceRootmap && !useCxxModules) {
3617 rcling += " -rml " + libname + " -rmf \"" + libmapfilename + "\" ";
3618 rcling.Append("-DR__ACLIC_ROOTMAP ");
3619 }
3620 rcling.Append(GetIncludePath()).Append(" -D__ACLIC__ ");
3621 if (gEnv) {
3622 TString fromConfig = gEnv->GetValue("ACLiC.IncludePaths","");
3623 rcling.Append(fromConfig);
3624 TString extraFlags = gEnv->GetValue("ACLiC.ExtraRootclingFlags","");
3625 if (!extraFlags.IsNull()) {
3626 extraFlags.Prepend(" ");
3627 extraFlags.Append(" ");
3628 rcling.Append(extraFlags);
3629 }
3630 }
3631
3632 // Create a modulemap
3633 // FIXME: Merge the modulemap generation from cmake and here in rootcling.
3634 if (useCxxModules && produceRootmap) {
3635 rcling += " -cxxmodule ";
3636 // TString moduleMapFileName = file_dirname + "/" + libname + ".modulemap";
3637 TString moduleName = libname + "_ACLiC_dict";
3638 if (moduleName.BeginsWith("lib"))
3639 moduleName = moduleName.Remove(0, 3);
3640 TString moduleMapName = moduleName + ".modulemap";
3641 TString moduleMapFullPath = build_loc + "/" + moduleMapName;
3642 // A modulemap may exist from previous runs, overwrite it.
3643 if (verboseLevel > 3 && !AccessPathName(moduleMapFullPath))
3644 ::Info("ACLiC", "File %s already exists!", moduleMapFullPath.Data());
3645
3646 std::string curDir = ROOT::FoundationUtils::GetCurrentDir();
3647 std::string relative_path = ROOT::FoundationUtils::MakePathRelative(filename_fullpath.Data(), curDir);
3648 std::ofstream moduleMapFile(moduleMapFullPath, std::ios::out);
3649 moduleMapFile << "module \"" << moduleName << "\" {" << std::endl;
3650 moduleMapFile << " header \"" << relative_path << "\"" << std::endl;
3651 moduleMapFile << " export *" << std::endl;
3652 moduleMapFile << " link \"" << libname_ext << "\"" << std::endl;
3653 moduleMapFile << "}" << std::endl;
3654 moduleMapFile.close();
3655 gInterpreter->RegisterPrebuiltModulePath(build_loc.Data(), moduleMapName.Data());
3656 rcling.Append(" \"-moduleMapFile=" + moduleMapFullPath + "\" ");
3657 }
3658
3659 rcling.Append(" \"").Append(filename_fullpath).Append("\" ");
3660 rcling.Append("\"").Append(linkdef).Append("\"");
3661
3662 // ======= Run rootcling
3663 if (withInfo) {
3664 if (verboseLevel>3) {
3665 ::Info("ACLiC","creating the dictionary files");
3666 if (verboseLevel>4) ::Info("ACLiC", "%s", rcling.Data());
3667 }
3668 }
3669
3670 ///\returns true on success.
3671 auto ExecAndReport = [](TString cmd) -> bool {
3672 Int_t result = gSystem->Exec(cmd);
3673 if (result) {
3674 if (result == 139)
3675 ::Error("ACLiC", "Executing '%s' failed with a core dump!", cmd.Data());
3676 else
3677 ::Error("ACLiC", "Executing '%s' failed!", cmd.Data());
3678 }
3679 return !result;
3680 };
3681
3682 Bool_t result = ExecAndReport(rcling);
3683 TString depLibraries;
3684
3685 // ======= Load the library the script might depend on
3686 if (result) {
3687 TString linkedlibs = GetLibraries("", "S");
3688 TString libtoload;
3689 TString all_libtoload;
3690 std::ifstream liblist(mapfileout);
3691
3692 while ( liblist >> libtoload ) {
3693 // Load the needed library except for the library we are currently building!
3694 if (libtoload == "#") {
3695 // The comment terminates the list of libraries.
3696 std::string toskipcomment;
3697 std::getline(liblist,toskipcomment);
3698 break;
3699 }
3700 if (libtoload != library && libtoload != libname && libtoload != libname_ext) {
3701 if (produceRootmap) {
3702 if (loadLib || linkDepLibraries /* For GetLibraries to Work */) {
3703 result = gROOT->LoadClass("", libtoload) >= 0;
3704 if (!result) {
3705 // We failed to load one of the dependency.
3706 break;
3707 }
3708 }
3709 if (!linkedlibs.Contains(libtoload)) {
3710 all_libtoload.Append(" ").Append(libtoload);
3711 depLibraries.Append(" ");
3712 depLibraries.Append(GetLibraries(libtoload,"DSL",kFALSE));
3713 depLibraries = depLibraries.Strip(); // Remove any trailing spaces.
3714 }
3715 } else {
3716 gROOT->LoadClass("", libtoload);
3717 }
3718 }
3719 unsigned char c = liblist.peek();
3720 if (c=='\n' || c=='\r') {
3721 // Consume the character
3722 liblist.get();
3723 break;
3724 }
3725 }
3726
3727// depLibraries = all_libtoload;
3728// depLibraries.ReplaceAll(" lib"," -l");
3729// depLibraries.ReplaceAll(TString::Format(".%s",fSoExt.Data()),"");
3730 }
3731
3732 // ======= Calculate the libraries for linking:
3733 TString linkLibraries;
3734 /*
3735 this is intentionally disabled until it can become useful
3736 if (gEnv) {
3737 linkLibraries = gEnv->GetValue("ACLiC.Libraries","");
3738 linkLibraries.Prepend(" ");
3739 }
3740 */
3741 TString linkLibrariesNoQuotes(GetLibraries("","SDL"));
3742 // We need to enclose the single paths in quotes to account for paths with spaces
3743 TString librariesWithQuotes;
3744 TString singleLibrary;
3745 Bool_t collectingSingleLibraryNameTokens = kFALSE;
3746 std::unique_ptr<TObjArray> tokens( linkLibrariesNoQuotes.Tokenize(" ") );
3747 for (auto tokenObj : *tokens) {
3748 singleLibrary = ((TObjString*)tokenObj)->GetString();
3749 if (singleLibrary[0]=='-' || !AccessPathName(singleLibrary)) {
3750 if (collectingSingleLibraryNameTokens) {
3751 librariesWithQuotes.Chop();
3752 librariesWithQuotes += "\" \"" + singleLibrary + "\"";
3753 collectingSingleLibraryNameTokens = kFALSE;
3754 } else {
3755 librariesWithQuotes += " \"" + singleLibrary + "\"";
3756 }
3757 } else {
3758 if (collectingSingleLibraryNameTokens) {
3759 librariesWithQuotes += singleLibrary + " ";
3760 } else {
3761 collectingSingleLibraryNameTokens = kTRUE;
3762 librariesWithQuotes += " \"" + singleLibrary + " ";
3763 }
3764 }
3765 }
3766
3767#ifdef _MSC_VER
3768 linkLibraries.Prepend(linkLibrariesNoQuotes);
3769#else
3770 linkLibraries.Prepend(librariesWithQuotes);
3771#endif
3772
3773 // ======= Generate the build command lines
3774 TString cmd = fMakeSharedLib;
3775 // we do not add filename because it is already included via the dictionary(in dicth) !
3776 // dict.Append(" ").Append(filename);
3777 cmd.ReplaceAll("$SourceFiles","-D__ACLIC__ \"$SourceFiles\"");
3778 cmd.ReplaceAll("$SourceFiles",dict);
3779 cmd.ReplaceAll("$ObjectFiles","\"$ObjectFiles\"");
3780 cmd.ReplaceAll("$ObjectFiles",dictObj);
3781 cmd.ReplaceAll("$IncludePath",includes);
3782 cmd.ReplaceAll("$SharedLib","\"$SharedLib\"");
3783 cmd.ReplaceAll("$SharedLib",library);
3784 if (linkDepLibraries) {
3785 if (produceRootmap) {
3786 cmd.ReplaceAll("$DepLibs",depLibraries);
3787 } else {
3788 cmd.ReplaceAll("$DepLibs",linkLibraries);
3789 }
3790 }
3791 cmd.ReplaceAll("$LinkedLibs",linkLibraries);
3792 cmd.ReplaceAll("$LibName",libname);
3793 cmd.ReplaceAll("\"$BuildDir","$BuildDir");
3794 cmd.ReplaceAll("$BuildDir","\"$BuildDir\"");
3795 cmd.ReplaceAll("$BuildDir",build_loc);
3796 // Add relevant directories to RPATH:
3797 // - Directory with all the ROOT libraries.
3798 // - Directory where this shared library is being created. This enables creating multiple
3799 // libraries via ACLiC in the same session and have them depend on each other without
3800 // the need to set further environment variables.
3801 cmd.ReplaceAll("$RPath", "-Wl,-rpath," + gROOT->GetSharedLibDir() + " -Wl,-rpath," + build_loc);
3802 TString optdebFlags;
3803 if (mode & kDebug)
3804 optdebFlags = fFlagsDebug + " ";
3805#ifdef WIN32
3806 else
3807#endif
3808 if (mode & kOpt)
3809 optdebFlags += fFlagsOpt;
3810 cmd.ReplaceAll("$Opt", optdebFlags);
3811#ifdef WIN32
3812 R__FixLink(cmd);
3813 cmd.ReplaceAll("-std=", "-std:");
3814 if (mode & kDebug) {
3815 cmd.ReplaceAll(" && link ", "&& link /DEBUG ");
3816 }
3817#endif
3818
3819 TString testcmd = fMakeExe;
3820 TString fakeMain = libname;
3821 PrependPathName( build_loc, fakeMain );
3822 fakeMain += "_ACLiC_main";
3823 fakeMain += extension;
3824 std::ofstream fakeMainFile( fakeMain, std::ios::out );
3825 fakeMainFile << "// File Automatically generated by the ROOT Script Compiler "
3826 << std::endl;
3827 fakeMainFile << "int main(char*argc,char**argvv) {};" << std::endl;
3828 fakeMainFile.close();
3829 // We could append this fake main routine to the compilation line.
3830 // But in this case compiler may output the name of the dictionary file
3831 // and of the fakeMain file while it compiles it. (this would be useless
3832 // confusing output).
3833 // We could also the fake main routine to the end of the dictionary file
3834 // however compilation would fail if a main is already there
3835 // (like stress.cxx)
3836 // dict.Append(" ").Append(fakeMain);
3837 TString exec = libname;
3838 PrependPathName( build_loc, exec );
3839 exec += "_ACLiC_exec";
3840 testcmd.ReplaceAll("$SourceFiles","-D__ACLIC__ \"$SourceFiles\"");
3841 testcmd.ReplaceAll("$SourceFiles",dict);
3842 testcmd.ReplaceAll("$ObjectFiles","\"$ObjectFiles\"");
3843 testcmd.ReplaceAll("$ObjectFiles",dictObj);
3844 testcmd.ReplaceAll("$IncludePath",includes);
3845 testcmd.ReplaceAll("$ExeName",exec);
3846 testcmd.ReplaceAll("$LinkedLibs",linkLibraries);
3847 testcmd.ReplaceAll("$BuildDir",build_loc);
3848 if (mode==kDebug)
3849 testcmd.ReplaceAll("$Opt",fFlagsDebug);
3850 else
3851 testcmd.ReplaceAll("$Opt",fFlagsOpt);
3852
3853#ifdef WIN32
3854 R__FixLink(testcmd);
3855 testcmd.ReplaceAll("-std=", "-std:");
3856#endif
3857
3858 // ======= Build the library
3859 if (result) {
3860 TString cmdAllowUnresolved = cmd;
3861#ifdef R__MACOSX
3862 // Allow linking to succeed despite the missing symbols.
3863 cmdAllowUnresolved.ReplaceAll("-dynamiclib", "-dynamiclib -Wl,-w -Wl,-undefined,dynamic_lookup");
3864#endif
3865 if (verboseLevel > 3 && withInfo) {
3866 ::Info("ACLiC","compiling the dictionary and script files");
3867 if (verboseLevel>4)
3868 ::Info("ACLiC", "%s", cmdAllowUnresolved.Data());
3869 }
3870 Int_t success = ExecAndReport(cmdAllowUnresolved);
3871 if (!success) {
3872 if (produceRootmap) {
3873 gSystem->Unlink(libmapfilename);
3874 }
3875 }
3876 result = success;
3877 }
3878
3879 if ( result ) {
3880 if (linkDepLibraries) {
3881 // We may have unresolved symbols. Use dyld to resolve the dependent
3882 // libraries and relink.
3883 // FIXME: We will likely have duplicated libraries as we are appending
3884 // FIXME: This likely makes rootcling --lib-list-prefix redundant.
3885 TString depLibsFullPaths;
3886 std::function<bool(const char *)> CollectF = [&depLibsFullPaths](const char *dep) {
3887 TString LibFullPath(dep);
3888 if (!gSystem->FindDynamicLibrary(LibFullPath, /*quiet=*/true)) {
3889 ::Error("TSystem::CompileMacro", "Cannot find library '%s'", dep);
3890 return false; // abort
3891 }
3892 depLibsFullPaths += " " + LibFullPath;
3893 return true;
3894 };
3895 ForeachSharedLibDep(library, CollectF);
3896
3897 TString relink_cmd = cmd.Strip(TString::kTrailing, ';');
3898 relink_cmd += depLibsFullPaths;
3899 if (verboseLevel > 3 && withInfo) {
3900 ::Info("ACLiC", "relinking against all dependencies");
3901 if (verboseLevel > 4)
3902 ::Info("ACLiC", "%s", relink_cmd.Data());
3903 }
3904 result = ExecAndReport(relink_cmd);
3905 }
3906
3907 TNamed *k = new TNamed(library,library);
3908 Long_t lib_time;
3909 gSystem->GetPathInfo( library, nullptr, (Long_t*)nullptr, nullptr, &lib_time );
3910 k->SetUniqueID(lib_time);
3911 if (!keep) k->SetBit(kMustCleanup);
3912 fCompiled->Add(k);
3913
3914 if (needLoadMap) {
3915 gInterpreter->LoadLibraryMap(libmapfilename);
3916 }
3917 if (verboseLevel>3 && withInfo) ::Info("ACLiC","loading the shared library");
3918 if (loadLib)
3919 result = LoadLibrary(library);
3920 else
3921 result = kTRUE;
3922
3923 if ( !result ) {
3924 if (verboseLevel>3 && withInfo) {
3925 ::Info("ACLiC","testing for missing symbols:");
3926 if (verboseLevel>4) ::Info("ACLiC", "%s", testcmd.Data());
3927 }
3928 gSystem->Exec(testcmd);
3929 gSystem->Unlink( exec );
3930 }
3931
3932 };
3933
3934 if (verboseLevel<=5 && !internalDebug) {
3935 gSystem->Unlink( dict );
3936 gSystem->Unlink( dicth );
3937 gSystem->Unlink( dictObj );
3938 gSystem->Unlink( linkdef );
3939 gSystem->Unlink( mapfilein );
3940 gSystem->Unlink( mapfileout );
3941 gSystem->Unlink( fakeMain );
3942 gSystem->Unlink( exec );
3943 }
3944 if (verboseLevel>6) {
3945 rcling.Prepend("echo ");
3946 cmd.Prepend("echo \" ").Append(" \" ");
3947 testcmd.Prepend("echo \" ").Append(" \" ");
3948 gSystem->Exec(rcling);
3949 gSystem->Exec( cmd );
3950 gSystem->Exec(testcmd);
3951 }
3952
3953 return result;
3954}
3955
3956////////////////////////////////////////////////////////////////////////////////
3957/// Return the ACLiC properties field. See EAclicProperties for details
3958/// on the semantic of each bit.
3959
3961{
3962 return fAclicProperties;
3963}
3964
3965////////////////////////////////////////////////////////////////////////////////
3966/// Return the build architecture.
3967
3968const char *TSystem::GetBuildArch() const
3969{
3970 return fBuildArch;
3971}
3972
3973////////////////////////////////////////////////////////////////////////////////
3974/// Return the build compiler
3975
3976const char *TSystem::GetBuildCompiler() const
3977{
3978 return fBuildCompiler;
3979}
3980
3981////////////////////////////////////////////////////////////////////////////////
3982/// Return the build compiler version
3983
3985{
3986 return fBuildCompilerVersion;
3987}
3988
3989////////////////////////////////////////////////////////////////////////////////
3990/// Return the build compiler version identifier string
3991
3993{
3995}
3996
3997////////////////////////////////////////////////////////////////////////////////
3998/// Return the build node name.
3999
4000const char *TSystem::GetBuildNode() const
4001{
4002 return fBuildNode;
4003}
4004
4005////////////////////////////////////////////////////////////////////////////////
4006/// Return the path of the build directory.
4007
4008const char *TSystem::GetBuildDir() const
4009{
4010 if (fBuildDir.Length()==0) {
4011 if (!gEnv) return "";
4012 const_cast<TSystem*>(this)->fBuildDir = gEnv->GetValue("ACLiC.BuildDir","");
4013 }
4014 return fBuildDir;
4015}
4016
4017////////////////////////////////////////////////////////////////////////////////
4018/// Return the debug flags.
4019
4020const char *TSystem::GetFlagsDebug() const
4021{
4022 return fFlagsDebug;
4023}
4024
4025////////////////////////////////////////////////////////////////////////////////
4026/// Return the optimization flags.
4027
4028const char *TSystem::GetFlagsOpt() const
4029{
4030 return fFlagsOpt;
4031}
4032
4033////////////////////////////////////////////////////////////////////////////////
4034/// AclicMode indicates whether the library should be built in
4035/// debug mode or optimized. The values are:
4036/// - TSystem::kDefault : compile the same as the current ROOT
4037/// - TSystem::kDebug : compiled in debug mode
4038/// - TSystem::kOpt : optimized the library
4039
4044
4045////////////////////////////////////////////////////////////////////////////////
4046/// Return the command line use to make a shared library.
4047/// See TSystem::CompileMacro for more details.
4048
4049const char *TSystem::GetMakeSharedLib() const
4050{
4051 return fMakeSharedLib;
4052}
4053
4054////////////////////////////////////////////////////////////////////////////////
4055/// Return the command line use to make an executable.
4056/// See TSystem::CompileMacro for more details.
4057
4058const char *TSystem::GetMakeExe() const
4059{
4060 return fMakeExe;
4061}
4062
4063////////////////////////////////////////////////////////////////////////////////
4064/// Get the list of include path.
4065
4067{
4069#ifndef _MSC_VER
4070 // FIXME: This is a temporary fix for the following error with ACLiC
4071 // (and this is apparently not needed anyway):
4072 // 48: input_line_12:8:38: error: use of undeclared identifier 'IC'
4073 // 48: "C:/Users/bellenot/build/debug/etc" -IC:/Users/bellenot/build/debug/etc//cling -IC:/Users/bellenot/build/debug/include"",
4074 // 48: ^
4075 // 48: Error in <ACLiC>: Dictionary generation failed!
4076 fListPaths.Append(" ").Append(gInterpreter->GetIncludePath());
4077#endif
4078 return fListPaths;
4079}
4080
4081////////////////////////////////////////////////////////////////////////////////
4082/// Return the list of library linked to this executable.
4083/// See TSystem::CompileMacro for more details.
4084
4085const char *TSystem::GetLinkedLibs() const
4086{
4087 return fLinkedLibs;
4088}
4089
4090////////////////////////////////////////////////////////////////////////////////
4091/// Return the linkdef suffix chosen by the user for ACLiC.
4092/// See TSystem::CompileMacro for more details.
4093
4094const char *TSystem::GetLinkdefSuffix() const
4095{
4096 if (fLinkdefSuffix.Length()==0) {
4097 if (!gEnv) return "_linkdef";
4098 const_cast<TSystem*>(this)->fLinkdefSuffix = gEnv->GetValue("ACLiC.Linkdef","_linkdef");
4099 }
4100 return fLinkdefSuffix;
4101}
4102
4103////////////////////////////////////////////////////////////////////////////////
4104/// Get the shared library extension.
4105
4106const char *TSystem::GetSoExt() const
4107{
4108 return fSoExt;
4109}
4110
4111////////////////////////////////////////////////////////////////////////////////
4112/// Get the object file extension.
4113
4114const char *TSystem::GetObjExt() const
4115{
4116 return fObjExt;
4117}
4118
4119////////////////////////////////////////////////////////////////////////////////
4120/// Set the location where ACLiC will create libraries and use as
4121/// a scratch area. If unset, libraries will be created at the same
4122/// location than the script.
4123///
4124/// \param build_dir the name of the build directory
4125/// \param isflat If false (default), then the libraries are actually stored
4126/// in sub-directories of 'build_dir' including the full pathname
4127/// of the script. If the script is located at `/full/path/name/macro.C`
4128/// the library will be located at `build_dir+/full/path/name/macro_C.so`
4129/// If 'isflat' is true, then no subdirectory is created and the library
4130/// is created directly in the directory 'build_dir'. Note that in this
4131/// mode there is a risk than 2 script of the same in different source
4132/// directory will over-write each other.
4133/// \note This `build_dir` can also be controlled via `ACLiC.BuildDir` in
4134/// your `.rootrc`.
4135
4136void TSystem::SetBuildDir(const char *build_dir, Bool_t isflat)
4137{
4138 fBuildDir = build_dir;
4139 if (isflat)
4141 else
4142 fAclicProperties &= ~kFlatBuildDir;
4143}
4144
4145////////////////////////////////////////////////////////////////////////////////
4146/// FlagsDebug should contain the options to pass to the C++ compiler
4147/// in order to compile the library in debug mode.
4148
4149void TSystem::SetFlagsDebug(const char *flags)
4150{
4151 fFlagsDebug = flags;
4152}
4153
4154////////////////////////////////////////////////////////////////////////////////
4155/// FlagsOpt should contain the options to pass to the C++ compiler
4156/// in order to compile the library in optimized mode.
4157
4158void TSystem::SetFlagsOpt(const char *flags)
4159{
4160 fFlagsOpt = flags;
4161}
4162
4163////////////////////////////////////////////////////////////////////////////////
4164/// AclicMode indicates whether the library should be built in
4165/// debug mode or optimized. The values are:
4166/// - TSystem::kDefault : compile the same as the current ROOT
4167/// - TSystem::kDebug : compiled in debug mode
4168/// - TSystem::kOpt : optimized the library
4169
4174
4175////////////////////////////////////////////////////////////////////////////////
4176/// Directives has the same syntax as the argument of SetMakeSharedLib but is
4177/// used to create an executable. This creation is used as a means to output
4178/// a list of unresolved symbols, when loading a shared library has failed.
4179/// The required variable is $ExeName rather than $SharedLib, e.g.:
4180/// ~~~ {.cpp}
4181/// gSystem->SetMakeExe(
4182/// "g++ -Wall -fPIC $IncludePath $SourceFiles
4183/// -o $ExeName $LinkedLibs -L/usr/X11R6/lib -lX11 -lm -ldl -rdynamic");
4184/// ~~~
4185
4186void TSystem::SetMakeExe(const char *directives)
4187{
4188 fMakeExe = directives;
4189 // NOTE: add verification that the directives has the required variables
4190}
4191
4192////////////////////////////////////////////////////////////////////////////////
4193/// Directives should contain the description on how to compile and link a
4194/// shared lib. This description can be any valid shell command, including
4195/// the use of ';' to separate several instructions. However, shell specific
4196/// construct should be avoided. In particular this description can contain
4197/// environment variables, like $ROOTSYS (or %ROOTSYS% on windows).
4198/// ~~~ {.cpp}
4199/// The following special variables will be expanded before execution:
4200/// Variable name Expands to
4201/// ------------- ----------
4202/// $SourceFiles Name of source files to be compiled
4203/// $SharedLib Name of the shared library being created
4204/// $LibName Name of shared library without extension
4205/// $BuildDir Directory where the files will be created
4206/// $IncludePath value of fIncludePath
4207/// $LinkedLibs value of fLinkedLibs
4208/// $RPath ROOT's library directory is added as -rpath
4209/// $DepLibs libraries on which this library depends on
4210/// $ObjectFiles Name of source files to be compiler with
4211/// their extension changed to .o or .obj
4212/// $Opt location of the optimization/debug options
4213/// set fFlagsDebug and fFlagsOpt
4214/// ~~~
4215/// e.g.:
4216/// ~~~ {.cpp}
4217/// gSystem->SetMakeSharedLib(
4218/// "KCC -n32 --strict $IncludePath -K0 \$Opt $SourceFile
4219/// --no_exceptions --signed_chars --display_error_number
4220/// --diag_suppress 68 -o $SharedLib");
4221///
4222/// // Or adding an rpath to the generated libraries (ROOT's rpath is inserted automatically into $RPath):
4223/// gSystem->SetMakeSharedLib(
4224/// "Cxx $IncludePath -c $SourceFile;
4225/// ld -L/usr/lib/cmplrs/cxx -rpath /usr/lib/cmplrs/cxx -expect_unresolved
4226/// \$Opt \$RPath -shared /usr/lib/cmplrs/cc/crt0.o /usr/lib/cmplrs/cxx/_main.o
4227/// -o $SharedLib $ObjectFile -lcxxstd -lcxx -lexc -lots -lc"
4228///
4229/// gSystem->SetMakeSharedLib(
4230/// "$HOME/mygcc/bin/g++ \$Opt -Wall -fPIC $IncludePath $SourceFile
4231/// -shared -o $SharedLib");
4232///
4233/// gSystem->SetMakeSharedLib(
4234/// "cl -DWIN32 -D_WIN32 -D_MT -D_DLL -MD /O2 /G5 /MD -DWIN32
4235/// -D_WINDOWS $IncludePath $SourceFile
4236/// /link -PDB:NONE /NODEFAULTLIB /INCREMENTAL:NO /RELEASE /NOLOGO
4237/// $LinkedLibs -entry:_DllMainCRTStartup@12 -dll /out:$SharedLib")
4238/// ~~~
4239
4240void TSystem::SetMakeSharedLib(const char *directives)
4241{
4242 fMakeSharedLib = directives;
4243 // NOTE: add verification that the directives has the required variables
4244}
4245
4246////////////////////////////////////////////////////////////////////////////////
4247/// \brief Add a directory to the already set include path.
4248/// \param[in] includePath The path to the directory.
4249/// \note This interface is mostly relevant for ACLiC and it does *not* inform
4250/// gInterpreter for this include path. If the TInterpreter needs to know
4251/// about the include path please use TInterpreter::AddIncludePath() .
4252/// \warning The path should start with the \c -I prefix, i.e.
4253/// <tt>gSystem->AddIncludePath("-I /path/to/my/includes")</tt>.
4254void TSystem::AddIncludePath(const char *includePath)
4255{
4256 if (includePath) {
4257 fIncludePath += " ";
4258 fIncludePath += includePath;
4259 }
4260}
4261
4262////////////////////////////////////////////////////////////////////////////////
4263/// Add linkedLib to already set linked libs.
4264
4265void TSystem::AddLinkedLibs(const char *linkedLib)
4266{
4267 if (linkedLib) {
4268 fLinkedLibs += " ";
4269 fLinkedLibs += linkedLib;
4270 }
4271}
4272
4273////////////////////////////////////////////////////////////////////////////////
4274/// IncludePath should contain the list of compiler flags to indicate where
4275/// to find user defined header files. It is used to expand $IncludePath in
4276/// the directives given to SetMakeSharedLib() and SetMakeExe(), e.g.:
4277/// ~~~ {.cpp}
4278/// gSystem->SetInclude("-I$ROOTSYS/include -Imydirectory/include");
4279/// ~~~
4280/// the default value of IncludePath on Unix is:
4281/// ~~~ {.cpp}
4282/// "-I$ROOTSYS/include "
4283/// ~~~
4284/// and on Windows:
4285/// ~~~ {.cpp}
4286/// "/I%ROOTSYS%/include "
4287/// ~~~
4288
4289void TSystem::SetIncludePath(const char *includePath)
4290{
4291 fIncludePath = includePath;
4292}
4293
4294////////////////////////////////////////////////////////////////////////////////
4295/// LinkedLibs should contain the library directory and list of libraries
4296/// needed to recreate the current executable. It is used to expand $LinkedLibs
4297/// in the directives given to SetMakeSharedLib() and SetMakeExe()
4298/// The default value on Unix is: `root-config --glibs`
4299
4300void TSystem::SetLinkedLibs(const char *linkedLibs)
4301{
4302 fLinkedLibs = linkedLibs;
4303}
4304
4305////////////////////////////////////////////////////////////////////////////////
4306/// The 'suffix' will be appended to the name of a script loaded by ACLiC
4307/// and used to locate any eventual additional linkdef information that
4308/// ACLiC should used to produce the dictionary.
4309///
4310/// So by default, when doing .L MyScript.cxx, ACLiC will look
4311/// for a file name MyScript_linkdef and having one of the .h (.hpp,
4312/// etc.) extensions. If such a file exist, it will be added to
4313/// the end of the linkdef file used to created the ACLiC dictionary.
4314/// This effectively enable the full customization of the creation
4315/// of the dictionary. It should be noted that the file is intended
4316/// as a linkdef `fragment`, so usually you would not list the
4317/// typical:
4318/// ~~~ {.cpp}
4319/// #pragma link off ....
4320/// ~~~
4321
4322void TSystem::SetLinkdefSuffix(const char *suffix)
4323{
4324 fLinkdefSuffix = suffix;
4325}
4326
4327
4328////////////////////////////////////////////////////////////////////////////////
4329/// Set shared library extension, should be either .so, .sl, .a, .dll, etc.
4330
4331void TSystem::SetSoExt(const char *SoExt)
4332{
4333 fSoExt = SoExt;
4334}
4335
4336////////////////////////////////////////////////////////////////////////////////
4337/// Set object files extension, should be either .o, .obj, etc.
4338
4339void TSystem::SetObjExt(const char *ObjExt)
4340{
4341 fObjExt = ObjExt;
4342}
4343
4344////////////////////////////////////////////////////////////////////////////////
4345/// This method split a filename of the form:
4346/// ~~~ {.cpp}
4347/// [path/]macro.C[+|++[k|f|g|O|c|s|d|v|-]][(args)].
4348/// ~~~
4349/// It stores the ACliC mode [+|++[options]] in 'mode',
4350/// the arguments (including parenthesis) in arg
4351/// and the I/O indirection in io
4352
4354 TString &arguments, TString &io) const
4355{
4356 char *fname = Strip(filename);
4357 TString filenameCopy = fname;
4358 filenameCopy = filenameCopy.Strip();
4359
4360 if (filenameCopy.EndsWith(";")) {
4361 filenameCopy.Remove(filenameCopy.Length() - 1);
4362 filenameCopy = filenameCopy.Strip();
4363 }
4364 if (filenameCopy.EndsWith(")")) {
4365 Ssiz_t posArgEnd = filenameCopy.Length() - 1;
4366 // There is an argument; find its start!
4367 int parenNestCount = 1;
4368 bool inString = false;
4369 Ssiz_t posArgBegin = posArgEnd - 1;
4370 for (; parenNestCount && posArgBegin >= 0; --posArgBegin) {
4371 // Escaped if the previous character is a `\` - but not if it
4372 // itself is preceded by a `\`!
4373 if (posArgBegin > 0 && filenameCopy[posArgBegin] == '\\' &&
4374 (posArgBegin == 1 || filenameCopy[posArgBegin - 1] != '\\')) {
4375 // skip escape.
4376 --posArgBegin;
4377 continue;
4378 }
4379 switch (filenameCopy[posArgBegin]) {
4380 case ')':
4381 if (!inString)
4382 ++parenNestCount;
4383 break;
4384 case '(':
4385 if (!inString)
4386 --parenNestCount;
4387 break;
4388 case '"': inString = !inString; break;
4389 }
4390 }
4391 if (parenNestCount || inString) {
4392 Error("SplitAclicMode", "Cannot parse argument in %s", filename);
4393 } else {
4394 arguments = filenameCopy(posArgBegin + 1, posArgEnd - 1);
4395 fname[posArgBegin + 1] = 0;
4396 }
4397 }
4398
4399 // strip off I/O redirect tokens from filename
4400 {
4401 char *s2 = nullptr;
4402 char *s3;
4403 s2 = strstr(fname, ">>");
4404 if (!s2) s2 = strstr(fname, "2>");
4405 if (!s2) s2 = strchr(fname, '>');
4406 s3 = strchr(fname, '<');
4407 if (s2 && s3) s2 = s2<s3 ? s2 : s3;
4408 if (s3 && !s2) s2 = s3;
4409 if (s2==fname) {
4410 io = fname;
4411 aclicMode = "";
4412 arguments = "";
4413 delete []fname;
4414 return "";
4415 } else if (s2) {
4416 if (s2 > fname) {
4417 // Skip/trim spaces
4418 s2--;
4419 while (s2 > fname && *s2 == ' ') s2--;
4420 s2++;
4421 }
4422 io = s2; // ssave = *s2;
4423 *s2 = 0;
4424 } else
4425 io = "";
4426 }
4427
4428 // remove the possible ACLiC + or ++ and g or O etc
4429 aclicMode.Clear();
4430 int len = strlen(fname);
4431 TString mode;
4432 while (len > 1) {
4433 if (strchr("kfgOcsdv-", fname[len - 1])) {
4434 mode += fname[len - 1];
4435 --len;
4436 } else {
4437 break;
4438 }
4439 }
4440 Bool_t compile = len && fname[len - 1] == '+';
4441 Bool_t remove = compile && len > 1 && fname[len - 2] == '+';
4442 if (compile) {
4443 if (mode.Length()) {
4444 fname[len] = 0;
4445 }
4446 if (remove) {
4447 fname[strlen(fname)-2] = 0;
4448 aclicMode = "++";
4449 } else {
4450 fname[strlen(fname)-1] = 0;
4451 aclicMode = "+";
4452 }
4453 if (mode.Length())
4454 aclicMode += mode;
4455 }
4456
4457 TString resFilename = fname;
4458
4459 delete []fname;
4460 return resFilename;
4461}
4462
4463////////////////////////////////////////////////////////////////////////////////
4464/// Remove the shared libs produced by the CompileMacro() function, together
4465/// with their rootmaps, linkdefs, and pcms (and some more on Windows).
4466
4468{
4469 TIter next(fCompiled);
4470 TNamed *lib;
4471 const char *extensions[] = {".lib", ".exp", ".d", ".def", ".rootmap", "_ACLiC_linkdef.h", "_ACLiC_dict_rdict.pcm"};
4472 while ((lib = (TNamed*)next())) {
4473 if (lib->TestBit(kMustCleanup)) {
4474 TString libname = lib->GetTitle();
4475#ifdef WIN32
4476 // On Windows, we need to unload the dll before deleting it
4477 if (gInterpreter->IsLibraryLoaded(libname))
4478 ::FreeLibrary(::GetModuleHandle(libname));
4479#endif
4480 Unlink(libname);
4481 TString target, soExt = "." + fSoExt;
4482 libname.ReplaceAll(soExt, "");
4483 for (const char *ext : extensions) {
4484 target = libname + ext;
4485 Unlink(target);
4486 }
4487 }
4488 }
4489}
4490
4491////////////////////////////////////////////////////////////////////////////////
4492/// Register version of plugin library.
4493
4495{
4496 if (versionCode != TROOT::RootVersionCode() && gLibraryVersion)
4497 gLibraryVersion[gLibraryVersionIdx] = versionCode;
4498}
The file contains utilities which are foundational and could be used across the core component of ROO...
#define SafeDelete(p)
Definition RConfig.hxx:507
#define b(i)
Definition RSha256.hxx:100
#define f(i)
Definition RSha256.hxx:104
#define c(i)
Definition RSha256.hxx:101
#define a(i)
Definition RSha256.hxx:99
#define h(i)
Definition RSha256.hxx:106
#define e(i)
Definition RSha256.hxx:103
#define ROOT_RELEASE
Definition RVersion.hxx:47
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:60
constexpr Int_t kMaxInt
Definition RtypesCore.h:120
long Long_t
Signed long integer 4 bytes (long). Size depends on architecture.
Definition RtypesCore.h:69
constexpr Bool_t kFALSE
Definition RtypesCore.h:109
constexpr Ssiz_t kNPOS
The equivalent of std::string::npos for the ROOT class TString.
Definition RtypesCore.h:132
long long Long64_t
Portable signed long integer 8 bytes.
Definition RtypesCore.h:84
constexpr Bool_t kTRUE
Definition RtypesCore.h:108
const char Option_t
Option string (const char)
Definition RtypesCore.h:81
@ kMAXPATHLEN
Definition Rtypes.h:60
R__EXTERN TApplication * gApplication
R__EXTERN TEnv * gEnv
Definition TEnv.h:126
void Info(const char *location, const char *msgfmt,...)
Use this function for informational messages.
Definition TError.cxx:241
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
Definition TError.cxx:252
#define ENDTRY
Definition TException.h:64
#define RETRY
Definition TException.h:44
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t target
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
Option_t Option_t TPoint TPoint const char mode
char name[80]
Definition TGX11.cxx:142
#define gInterpreter
Int_t gDebug
Global variable setting the debug level. Set to 0 to disable, increase it in steps of 1 to increase t...
Definition TROOT.cxx:792
#define gROOT
Definition TROOT.h:417
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2571
char * Strip(const char *str, char c=' ')
Strip leading and trailing c (blanks by default) from a string.
Definition TString.cxx:2603
char * StrDup(const char *str)
Duplicate the string str.
Definition TString.cxx:2639
ESignals
@ kSigInterrupt
TSystem * gSystem
Definition TSystem.cxx:70
static Int_t gLibraryVersionIdx
Definition TSystem.cxx:74
TVirtualMutex * gSystemMutex
Definition TSystem.cxx:111
void AssignAndDelete(TString &target, char *tobedeleted)
Definition TSystem.cxx:2525
static void R__WriteDependencyFile(const TString &build_loc, const TString &depfilename, const TString &filename, const TString &library, const TString &libname, const TString &extension, const char *version_var_prefix, const TString &includes, const TString &defines, const TString &incPath)
Definition TSystem.cxx:2743
static bool R__MatchFilename(const char *left, const char *right)
Figure out if left and right points to the same object in the file system.
Definition TSystem.cxx:1839
static void R__AddPath(TString &target, const TString &path)
Definition TSystem.cxx:2592
static Int_t * gLibraryVersion
Definition TSystem.cxx:73
static TString R__GetRootDictionaryDependencies(const TString &targetname, const TString &incPath)
Definition TSystem.cxx:2687
const char * gRootDir
Definition TSystem.cxx:66
static bool R__GenerateCompilerDependencies(const TString &depfilename, const TString &filename, const TString &targetname, const TString &includes, const TString &defines)
Definition TSystem.cxx:2597
static Int_t gLibraryVersionMax
Definition TSystem.cxx:75
TFileHandler * gXDisplay
Definition TSystem.cxx:71
const char * gProgPath
Definition TSystem.cxx:68
const char * gProgName
Definition TSystem.cxx:67
R__EXTERN const char * gProgName
Definition TSystem.h:252
R__EXTERN TVirtualMutex * gSystemMutex
Definition TSystem.h:254
void(* Func_t)()
Definition TSystem.h:249
EAccessMode
Definition TSystem.h:51
@ kFileExists
Definition TSystem.h:52
@ kReadPermission
Definition TSystem.h:55
@ kWritePermission
Definition TSystem.h:54
Bool_t R_ISREG(Int_t mode)
Definition TSystem.h:126
ELogFacility
Definition TSystem.h:74
ESocketBindOption
Options for binging the sockets created.
Definition TSystem.h:46
ELogLevel
Definition TSystem.h:63
Bool_t R_ISDIR(Int_t mode)
Definition TSystem.h:123
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
@ kS_IXOTH
Definition TSystem.h:120
@ kS_IXUSR
Definition TSystem.h:112
@ kS_IXGRP
Definition TSystem.h:116
#define R__LOCKGUARD2(mutex)
#define R__WRITE_LOCKGUARD(mutex)
#define R__READ_LOCKGUARD(mutex)
virtual void StopIdleing()
Called when system stops idleing.
virtual void StartIdleing()
Called when system starts idleing.
virtual TObject * Remove(TObject *obj)=0
virtual bool UseRWLock(Bool_t enable=true)
Set this collection to use a RW lock upon access, making it thread safe.
TObject * FindObject(const char *name) const override
Find an object in this collection using its name.
void Delete(Option_t *option="") override=0
Delete this object.
Definition TEnv.h:41
const char * GetValue() const
Definition TEnv.h:65
The TEnv class reads config files, by default named .rootrc.
Definition TEnv.h:79
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition TEnv.cxx:511
THashList * GetTable() const
Definition TEnv.h:96
This class represents an Internet Protocol (IP) address.
Iterator of linked list.
Definition TList.h:196
TObject * Next() override
Return next object in the list. Returns 0 when no more objects in list.
Definition TList.cxx:1243
A doubly linked list.
Definition TList.h:38
TObject * FindObject(const char *name) const override
Find an object in this list using its name.
Definition TList.cxx:708
void Add(TObject *obj) override
Definition TList.h:81
TObject * Remove(TObject *obj) override
Remove object from the list.
Definition TList.cxx:952
void Delete(Option_t *option="") override
Remove all objects from the list AND delete all heap based objects.
Definition TList.cxx:600
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
const char * GetTitle() const override
Returns title of object.
Definition TNamed.h:50
TNamed()
Definition TNamed.h:38
TString fName
Definition TNamed.h:32
An array of TObjects.
Definition TObjArray.h:31
Int_t GetEntriesFast() const
Definition TObjArray.h:58
TObject * At(Int_t idx) const override
Definition TObjArray.h:170
Collectable string class.
Definition TObjString.h:28
Mother of all ROOT objects.
Definition TObject.h:42
void AbstractMethod(const char *method) const
Call this function within a function that you don't want to define as purely virtual,...
Definition TObject.cxx:1147
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition TObject.h:204
virtual UInt_t GetUniqueID() const
Return the unique object id.
Definition TObject.cxx:479
virtual void SysError(const char *method, const char *msgfmt,...) const
Issue system error message.
Definition TObject.cxx:1110
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:1082
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition TObject.cxx:886
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1096
virtual void SetUniqueID(UInt_t uid)
Set the unique object id.
Definition TObject.cxx:897
@ kInvalidObject
if object ctor succeeded but object should not be used
Definition TObject.h:81
@ kMustCleanup
if object destructor must call RecursiveRemove()
Definition TObject.h:73
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition TObject.cxx:1070
Ordered collection.
TProcessEventTimer(Long_t delay)
Create async event processor timer. Delay is in milliseconds.
Definition TSystem.cxx:83
Bool_t ProcessEvents()
Process events if timer did time out.
Definition TSystem.cxx:94
static const TString & GetBinDir()
Get the binary directory in the installation. Static utility function.
Definition TROOT.cxx:3166
static const TString & GetIncludeDir()
Get the include directory in the installation. Static utility function.
Definition TROOT.cxx:3363
static Int_t ConvertVersionCode2Int(Int_t code)
Convert version code to an integer, i.e. 331527 -> 51507.
Definition TROOT.cxx:3099
static const TString & GetRootSys()
Get the rootsys directory in the installation. Static utility function.
Definition TROOT.cxx:3156
static Int_t RootVersionCode()
Return ROOT version code as defined in ROOT/RVersion.hxx.
Definition TROOT.cxx:3118
static const TString & GetEtcDir()
Get the sysconfig directory in the installation. Static utility function.
Definition TROOT.cxx:3397
static const TString & GetLibDir()
Get the library directory in the installation.
Definition TROOT.cxx:3194
Regular expression class.
Definition TRegexp.h:31
Ssiz_t Index(const TString &str, Ssiz_t *len, Ssiz_t start=0) const
Find the first occurrence of the regexp in string and return the position, or -1 if there is no match...
Definition TRegexp.cxx:213
void Add(TObject *obj) override
virtual EStatus Handle(std::exception &exc)=0
static Int_t * ReAllocInt(Int_t *vp, size_t size, size_t oldsize)
Reallocate (i.e.
Definition TStorage.cxx:257
Basic string class.
Definition TString.h:137
Ssiz_t Length() const
Definition TString.h:426
int CompareTo(const char *cs, ECaseCompare cmp=kExact) const
Compare a string to char *cs2.
Definition TString.cxx:465
TString & Insert(Ssiz_t pos, const char *s)
Definition TString.h:671
Bool_t EndsWith(const char *pat, ECaseCompare cmp=kExact) const
Return true if string ends with the specified string.
Definition TString.cxx:2325
TSubString Strip(EStripType s=kTrailing, char c=' ') const
Return a substring of self stripped at beginning and/or end.
Definition TString.cxx:1171
void Clear()
Clear string without changing its capacity.
Definition TString.cxx:1242
TString & Replace(Ssiz_t pos, Ssiz_t n, const char *s)
Definition TString.h:704
Ssiz_t First(char c) const
Find first occurrence of a character c.
Definition TString.cxx:546
const char * Data() const
Definition TString.h:385
TString & Chop()
Definition TString.h:701
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:714
@ kTrailing
Definition TString.h:283
@ kBoth
Definition TString.h:283
@ kIgnoreCase
Definition TString.h:284
@ kExact
Definition TString.h:284
Ssiz_t Last(char c) const
Find last occurrence of a character c.
Definition TString.cxx:939
TObjArray * Tokenize(const TString &delim) const
This function is used to isolate sequential tokens in a TString.
Definition TString.cxx:2345
Bool_t BeginsWith(const char *s, ECaseCompare cmp=kExact) const
Definition TString.h:633
TString & Prepend(const char *cs)
Definition TString.h:683
Bool_t IsNull() const
Definition TString.h:423
TString & Remove(Ssiz_t pos)
Definition TString.h:695
TString & Append(const char *cs)
Definition TString.h:582
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition TString.cxx:2460
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:642
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition TString.h:661
Abstract base class defining a generic interface to the underlying Operating System.
Definition TSystem.h:276
TString fListPaths
Definition TSystem.h:330
virtual void NotifyApplicationCreated()
Hook to tell TSystem that the TApplication object has been created.
Definition TSystem.cxx:315
virtual const char * GetBuildNode() const
Return the build node name.
Definition TSystem.cxx:4000
virtual int Umask(Int_t mask)
Set the process file creation mode mask.
Definition TSystem.cxx:1540
virtual int SendBuf(int sock, const void *buffer, int length)
Send a buffer headed by a length indicator.
Definition TSystem.cxx:2455
virtual int GetServiceByName(const char *service)
Get port # of internet service.
Definition TSystem.cxx:2346
virtual Bool_t IsFileInIncludePath(const char *name, char **fullpath=nullptr)
Return true if 'name' is a file that can be found in the ROOT include path or the current directory.
Definition TSystem.cxx:982
virtual void Unload(const char *module)
Unload a shared library.
Definition TSystem.cxx:2075
virtual FILE * TempFileName(TString &base, const char *dir=nullptr, const char *suffix=nullptr)
Create a secure temporary file by appending a unique 6 letter string to base.
Definition TSystem.cxx:1522
virtual const char * GetMakeSharedLib() const
Return the command line use to make a shared library.
Definition TSystem.cxx:4049
Bool_t fInControl
Definition TSystem.h:310
TSeqCollection * fFileHandler
Definition TSystem.h:316
Int_t fAclicProperties
Definition TSystem.h:339
Int_t fMaxrfd
Definition TSystem.h:301
virtual void AddFileHandler(TFileHandler *fh)
Add a file handler to the list of system file handlers.
Definition TSystem.cxx:558
TString & GetLastErrorString()
Return the thread local storage for the custom last error message.
Definition TSystem.cxx:2125
virtual void AddLinkedLibs(const char *linkedLib)
Add linkedLib to already set linked libs.
Definition TSystem.cxx:4265
virtual Int_t RedirectOutput(const char *name, const char *mode="a", RedirectHandle_t *h=nullptr)
Redirect standard output (stdout, stderr) to the specified file.
Definition TSystem.cxx:1738
virtual const char * GetBuildCompilerVersion() const
Return the build compiler version.
Definition TSystem.cxx:3984
virtual void ResetSignal(ESignals sig, Bool_t reset=kTRUE)
If reset is true reset the signal handler for the specified signal to the default handler,...
Definition TSystem.cxx:580
virtual TInetAddress GetSockName(int sock)
Get Internet Protocol (IP) address of host and port #.
Definition TSystem.cxx:2337
virtual int GetFsInfo(const char *path, Long_t *id, Long_t *bsize, Long_t *blocks, Long_t *bfree)
Get info about a file system: fs type, block size, number of blocks, number of free blocks.
Definition TSystem.cxx:1495
virtual Func_t DynFindSymbol(const char *module, const char *entry)
Find specific entry point in specified library.
Definition TSystem.cxx:2067
virtual const char * GetLinkedLibs() const
Return the list of library linked to this executable.
Definition TSystem.cxx:4085
void Beep(Int_t freq=-1, Int_t duration=-1, Bool_t setDefault=kFALSE)
Beep for duration milliseconds with a tone of frequency freq.
Definition TSystem.cxx:328
Int_t fBeepDuration
Definition TSystem.h:308
virtual void IgnoreInterrupt(Bool_t ignore=kTRUE)
If ignore is true ignore the interrupt signal, else restore previous behaviour.
Definition TSystem.cxx:606
virtual void Syslog(ELogLevel level, const char *mess)
Send mess to syslog daemon.
Definition TSystem.cxx:1709
virtual int Symlink(const char *from, const char *to)
Create a symbolic link from file1 to file2.
Definition TSystem.cxx:1391
virtual void SetAclicMode(EAclicMode mode)
AclicMode indicates whether the library should be built in debug mode or optimized.
Definition TSystem.cxx:4170
static void ResetErrno()
Static function resetting system error number.
Definition TSystem.cxx:288
virtual UInt_t LoadAllLibraries()
Load all libraries known to ROOT via the rootmap system.
Definition TSystem.cxx:1993
virtual void * GetDirPtr() const
Definition TSystem.h:436
virtual void SetObjExt(const char *objExt)
Set object files extension, should be either .o, .obj, etc.
Definition TSystem.cxx:4339
virtual void SetLinkdefSuffix(const char *suffix)
The 'suffix' will be appended to the name of a script loaded by ACLiC and used to locate any eventual...
Definition TSystem.cxx:4322
TSeqCollection * fHelpers
Definition TSystem.h:341
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition TSystem.cxx:1297
virtual const char * GetBuildDir() const
Return the path of the build directory.
Definition TSystem.cxx:4008
virtual void Openlog(const char *name, Int_t options, ELogFacility facility)
Open connection to system log daemon.
Definition TSystem.cxx:1700
static Int_t GetErrno()
Static function returning system error number.
Definition TSystem.cxx:280
virtual void AddIncludePath(const char *includePath)
Add a directory to the already set include path.
Definition TSystem.cxx:4254
virtual int Chmod(const char *file, UInt_t mode)
Set the file permission bits. Returns -1 in case or error, 0 otherwise.
Definition TSystem.cxx:1531
virtual Int_t GetEffectiveGid()
Returns the effective group id.
Definition TSystem.cxx:1614
@ kDefault
Definition TSystem.h:285
@ kDebug
Definition TSystem.h:289
virtual ~TSystem()
Delete the OS interface.
Definition TSystem.cxx:140
virtual void SetDisplay()
Set DISPLAY environment variable based on utmp entry. Only for UNIX.
Definition TSystem.cxx:236
virtual const char * DirName(const char *pathname)
Return the directory name in pathname.
Definition TSystem.cxx:1022
virtual void FreeDirectory(void *dirp)
Free a directory.
Definition TSystem.cxx:861
virtual void SetFlagsOpt(const char *)
FlagsOpt should contain the options to pass to the C++ compiler in order to compile the library in op...
Definition TSystem.cxx:4158
void RemoveOnExit(TObject *obj)
Objects that should be deleted on exit of the OS interface.
Definition TSystem.cxx:296
TSeqCollection * fStdExceptionHandler
Definition TSystem.h:317
virtual char * GetServiceByPort(int port)
Get name of internet service.
Definition TSystem.cxx:2355
virtual void * OpenDirectory(const char *name)
Open a directory.
Definition TSystem.cxx:852
virtual int GetPid()
Get process id.
Definition TSystem.cxx:722
virtual int RecvBuf(int sock, void *buffer, int length)
Receive a buffer headed by a length indicator.
Definition TSystem.cxx:2446
virtual int CopyFile(const char *from, const char *to, Bool_t overwrite=kFALSE)
Copy a file.
Definition TSystem.cxx:1364
virtual Long_t NextTimeOut(Bool_t mode)
Time when next timer of mode (synchronous=kTRUE or asynchronous=kFALSE) will time-out (in ms).
Definition TSystem.cxx:498
virtual int SetSockOpt(int sock, int kind, int val)
Set socket option.
Definition TSystem.cxx:2464
virtual const char * Getenv(const char *env)
Get environment variable.
Definition TSystem.cxx:1688
virtual TStdExceptionHandler * RemoveStdExceptionHandler(TStdExceptionHandler *eh)
Remove an exception handler from list of exception handlers.
Definition TSystem.cxx:625
virtual const char * GetIncludePath()
Get the list of include path.
Definition TSystem.cxx:4066
virtual int AcceptConnection(int sock)
Accept a connection.
Definition TSystem.cxx:2409
virtual Int_t GetAclicProperties() const
Return the ACLiC properties field.
Definition TSystem.cxx:3960
virtual TString SplitAclicMode(const char *filename, TString &mode, TString &args, TString &io) const
This method split a filename of the form:
Definition TSystem.cxx:4353
TString fListLibs
Definition TSystem.h:320
virtual void ShowOutput(RedirectHandle_t *h)
Display the content associated with the redirection described by the opaque handle 'h'.
Definition TSystem.cxx:1748
virtual char * ConcatFileName(const char *dir, const char *name)
Concatenate a directory and a file name.
Definition TSystem.cxx:1088
virtual UserGroup_t * GetGroupInfo(Int_t gid)
Returns all group info in the UserGroup_t structure.
Definition TSystem.cxx:1648
virtual void CleanCompiledMacros()
Remove the shared libs produced by the CompileMacro() function, together with their rootmaps,...
Definition TSystem.cxx:4467
virtual Bool_t IsPathLocal(const char *path)
Returns TRUE if the url in 'path' points to the local file system.
Definition TSystem.cxx:1328
TString fMakeExe
Definition TSystem.h:337
virtual const char * FindFile(const char *search, TString &file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition TSystem.cxx:1561
virtual int mkdir(const char *name, Bool_t recursive=kFALSE)
Make a file system directory.
Definition TSystem.cxx:922
virtual int MakeDirectory(const char *name)
Make a directory.
Definition TSystem.cxx:842
TString fBuildCompilerVersionStr
Definition TSystem.h:325
virtual const char * ExpandFileName(const char *fname)
Expand a pathname getting rid of special shell characters like ~.
Definition TSystem.cxx:1115
TSystem(const TSystem &)=delete
EAclicMode fAclicMode
Definition TSystem.h:335
virtual TInetAddress GetPeerName(int sock)
Get Internet Protocol (IP) address of remote host and port #.
Definition TSystem.cxx:2328
virtual TTime Now()
Get current time in milliseconds since 0:00 Jan 1 1995.
Definition TSystem.cxx:467
virtual Int_t Exec(const char *shellcmd)
Execute a command.
Definition TSystem.cxx:657
virtual int GetSysInfo(SysInfo_t *info) const
Returns static system info, like OS type, CPU type, number of CPUs RAM size, etc into the SysInfo_t s...
Definition TSystem.cxx:2486
TString fFlagsOpt
Definition TSystem.h:329
virtual int GetMemInfo(MemInfo_t *info) const
Returns ram and swap memory usage info into the MemInfo_t structure.
Definition TSystem.cxx:2507
virtual EAclicMode GetAclicMode() const
AclicMode indicates whether the library should be built in debug mode or optimized.
Definition TSystem.cxx:4040
virtual const char * GetLinkedLibraries()
Get list of shared libraries loaded at the start of the executable.
Definition TSystem.cxx:2143
virtual void SetIncludePath(const char *includePath)
IncludePath should contain the list of compiler flags to indicate where to find user defined header f...
Definition TSystem.cxx:4289
virtual TFileHandler * RemoveFileHandler(TFileHandler *fh)
Remove a file handler from the list of file handlers.
Definition TSystem.cxx:568
TString fLinkedLibs
Definition TSystem.h:332
Int_t fSigcnt
Definition TSystem.h:303
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition TSystem.cxx:1880
virtual void ListSymbols(const char *module, const char *re="")
List symbols in a shared library.
Definition TSystem.cxx:2087
virtual void DoBeep(Int_t=-1, Int_t=-1) const
Definition TSystem.h:352
TString fObjExt
Definition TSystem.h:334
TString fLinkdefSuffix
Definition TSystem.h:338
Int_t fBeepFreq
Definition TSystem.h:307
virtual int GetCpuInfo(CpuInfo_t *info, Int_t sampleTime=1000) const
Returns cpu load average and load info into the CpuInfo_t structure.
Definition TSystem.cxx:2497
@ kFlatBuildDir
Definition TSystem.h:291
virtual void ListLibraries(const char *regexp="")
List the loaded shared libraries.
Definition TSystem.cxx:2108
virtual FILE * OpenPipe(const char *command, const char *mode)
Open a pipe.
Definition TSystem.cxx:666
virtual void SetMakeSharedLib(const char *directives)
Directives should contain the description on how to compile and link a shared lib.
Definition TSystem.cxx:4240
int GetPathInfo(const char *path, Long_t *id, Long_t *size, Long_t *flags, Long_t *modtime)
Get info about a file: id, size, flags, modification time.
Definition TSystem.cxx:1421
virtual void InnerLoop()
Inner event loop.
Definition TSystem.cxx:404
virtual const char * PrependPathName(const char *dir, TString &name)
Concatenate a directory and a file name.
Definition TSystem.cxx:1098
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
Definition TSystem.cxx:1319
virtual int OpenConnection(const char *server, int port, int tcpwindowsize=-1, const char *protocol="tcp")
Open a connection to another host.
Definition TSystem.cxx:2364
virtual const char * GetDirEntry(void *dirp)
Get a directory entry. Returns 0 if no more entries.
Definition TSystem.cxx:869
virtual void IgnoreSignal(ESignals sig, Bool_t ignore=kTRUE)
If ignore is true ignore the specified signal, else restore previous behaviour.
Definition TSystem.cxx:597
virtual void Run()
System event loop.
Definition TSystem.cxx:347
virtual int GetSockOpt(int sock, int kind, int *val)
Get socket option.
Definition TSystem.cxx:2473
virtual void ExitLoop()
Exit from event loop.
Definition TSystem.cxx:396
virtual Bool_t ChangeDirectory(const char *path)
Change directory.
Definition TSystem.cxx:878
virtual std::string GetHomeDirectory(const char *userName=nullptr) const
Return the user's home directory.
Definition TSystem.cxx:911
virtual const char * UnixPathName(const char *unixpathname)
Convert from a local pathname to a Unix pathname.
Definition TSystem.cxx:1079
virtual int RecvRaw(int sock, void *buffer, int length, int flag)
Receive exactly length bytes into buffer.
Definition TSystem.cxx:2427
virtual Bool_t Init()
Initialize the OS interface.
Definition TSystem.cxx:184
virtual void AddTimer(TTimer *t)
Add timer to list of system timers.
Definition TSystem.cxx:475
virtual int GetProcInfo(ProcInfo_t *info) const
Returns cpu and memory used by this process into the ProcInfo_t structure.
Definition TSystem.cxx:2517
virtual const char * GetBuildCompilerVersionStr() const
Return the build compiler version identifier string.
Definition TSystem.cxx:3992
static Int_t GetCryptoRandom(void *buf, Int_t len)
Return cryptographic random number Fill provided buffer with random values.
Definition TSystem.cxx:267
virtual void DispatchOneEvent(Bool_t pendingOnly=kFALSE)
Dispatch a single event.
Definition TSystem.cxx:433
virtual int Rename(const char *from, const char *to)
Rename a file.
Definition TSystem.cxx:1373
virtual int ClosePipe(FILE *pipe)
Close the pipe.
Definition TSystem.cxx:675
virtual const char * BaseName(const char *pathname)
Base name of a file name. Base name of /user/root is root.
Definition TSystem.cxx:950
TString fBuildArch
Definition TSystem.h:322
virtual void AddSignalHandler(TSignalHandler *sh)
Add a signal handler to list of system signal handlers.
Definition TSystem.cxx:536
virtual const char * GetDynamicPath()
Return the dynamic path (used to find shared libraries).
Definition TSystem.cxx:1818
TSeqCollection * fSignalHandler
Definition TSystem.h:315
virtual const char * GetMakeExe() const
Return the command line use to make an executable.
Definition TSystem.cxx:4058
virtual const char * FindDynamicLibrary(TString &lib, Bool_t quiet=kFALSE)
Find a dynamic library using the system search paths.
Definition TSystem.cxx:2057
virtual TString GetFromPipe(const char *command, Int_t *ret=nullptr, Bool_t redirectStderr=kFALSE)
Execute command and return output in TString.
Definition TSystem.cxx:690
virtual void SetFlagsDebug(const char *)
FlagsDebug should contain the options to pass to the C++ compiler in order to compile the library in ...
Definition TSystem.cxx:4149
virtual void Exit(int code, Bool_t mode=kTRUE)
Exit the application.
Definition TSystem.cxx:731
virtual Int_t GetGid(const char *group=nullptr)
Returns the group's id. If group = 0, returns current user's group.
Definition TSystem.cxx:1604
virtual void SetMakeExe(const char *directives)
Directives has the same syntax as the argument of SetMakeSharedLib but is used to create an executabl...
Definition TSystem.cxx:4186
TSeqCollection * fCompiled
Definition TSystem.h:340
TString fBuildCompilerVersion
Definition TSystem.h:324
TSystem * FindHelper(const char *path, void *dirptr=nullptr)
Create helper TSystem to handle file and directory operations that might be special for remote file a...
Definition TSystem.cxx:761
virtual const char * GetFlagsDebug() const
Return the debug flags.
Definition TSystem.cxx:4020
virtual const char * HostName()
Return the system's host name.
Definition TSystem.cxx:307
Bool_t fDone
Definition TSystem.h:311
TList * fTimers
Definition TSystem.h:314
Int_t fNfd
Definition TSystem.h:300
virtual void Unsetenv(const char *name)
Unset environment variable.
Definition TSystem.cxx:1680
virtual Bool_t IsAbsoluteFileName(const char *dir)
Return true if dir is an absolute pathname.
Definition TSystem.cxx:967
virtual void AddDynamicPath(const char *pathname)
Add a new directory to the dynamic path.
Definition TSystem.cxx:1810
virtual Int_t Select(TList *active, Long_t timeout)
Select on active file descriptors (called by TMonitor).
Definition TSystem.cxx:449
TSeqCollection * fOnExitList
Definition TSystem.h:318
virtual const char * GetObjExt() const
Get the object file extension.
Definition TSystem.cxx:4114
virtual int AnnounceUnixService(int port, int backlog)
Announce unix domain service.
Definition TSystem.cxx:2391
TString fIncludePath
Definition TSystem.h:331
virtual Int_t GetUid(const char *user=nullptr)
Returns the user's id. If user = 0, returns current user's id.
Definition TSystem.cxx:1585
virtual Int_t GetEffectiveUid()
Returns the effective user id.
Definition TSystem.cxx:1595
TString fFlagsDebug
Definition TSystem.h:328
virtual const char * GetLinkdefSuffix() const
Return the linkdef suffix chosen by the user for ACLiC.
Definition TSystem.cxx:4094
virtual void SetDynamicPath(const char *pathname)
Set the dynamic path to a new value.
Definition TSystem.cxx:1829
TString fMakeSharedLib
Definition TSystem.h:336
virtual void Sleep(UInt_t milliSec)
Sleep milliSec milli seconds.
Definition TSystem.cxx:441
Int_t fMaxwfd
Definition TSystem.h:302
virtual int CompileMacro(const char *filename, Option_t *opt="", const char *library_name="", const char *build_dir="", UInt_t dirmode=0)
This method compiles and loads a shared library containing the code from the file "filename".
Definition TSystem.cxx:2904
virtual const char * WorkingDirectory()
Return working directory.
Definition TSystem.cxx:887
virtual void AddStdExceptionHandler(TStdExceptionHandler *eh)
Add an exception handler to list of system exception handlers.
Definition TSystem.cxx:615
virtual char * Which(const char *search, const char *file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition TSystem.cxx:1571
virtual TInetAddress GetHostByName(const char *server)
Get Internet Protocol (IP) address of host.
Definition TSystem.cxx:2319
virtual void SetProgname(const char *name)
Set the application name (from command line, argv[0]) and copy it in gProgName.
Definition TSystem.cxx:227
virtual int SendRaw(int sock, const void *buffer, int length, int flag)
Send exactly length bytes from buffer.
Definition TSystem.cxx:2437
virtual Int_t SetFPEMask(Int_t mask=kDefaultMask)
Set which conditions trigger a floating point exception.
Definition TSystem.cxx:646
Int_t fLevel
Definition TSystem.h:312
virtual const char * GetBuildCompiler() const
Return the build compiler.
Definition TSystem.cxx:3976
virtual void CloseConnection(int sock, Bool_t force=kFALSE)
Close socket connection.
Definition TSystem.cxx:2418
virtual const char * GetLibraries(const char *regexp="", const char *option="", Bool_t isRegexp=kTRUE)
Return a space separated list of loaded shared libraries.
Definition TSystem.cxx:2159
TString fBuildDir
Definition TSystem.h:327
void SetErrorStr(const char *errstr)
Set the system error string.
Definition TSystem.cxx:246
virtual TSignalHandler * RemoveSignalHandler(TSignalHandler *sh)
Remove a signal handler from list of signal handlers.
Definition TSystem.cxx:546
virtual void SetSoExt(const char *soExt)
Set shared library extension, should be either .so, .sl, .a, .dll, etc.
Definition TSystem.cxx:4331
virtual void Closelog()
Close connection to system log daemon.
Definition TSystem.cxx:1717
TString fBuildCompiler
Definition TSystem.h:323
virtual void Setenv(const char *name, const char *value)
Set environment variable.
Definition TSystem.cxx:1672
virtual const char * GetBuildArch() const
Return the build architecture.
Definition TSystem.cxx:3968
virtual int Link(const char *from, const char *to)
Create a link from file1 to file2.
Definition TSystem.cxx:1382
virtual void SigAlarmInterruptsSyscalls(Bool_t)
Definition TSystem.h:350
virtual const char * HomeDirectory(const char *userName=nullptr)
Return the user's home directory.
Definition TSystem.cxx:903
virtual void SetLinkedLibs(const char *linkedLibs)
LinkedLibs should contain the library directory and list of libraries needed to recreate the current ...
Definition TSystem.cxx:4300
virtual std::string GetWorkingDirectory() const
Return working directory.
Definition TSystem.cxx:895
TString fSoExt
Definition TSystem.h:333
virtual void SetBuildDir(const char *build_dir, Bool_t isflat=kFALSE)
Set the location where ACLiC will create libraries and use as a scratch area.
Definition TSystem.cxx:4136
static const char * StripOffProto(const char *path, const char *proto)
Strip off protocol string from specified path.
Definition TSystem.cxx:118
virtual void Abort(int code=0)
Abort the application.
Definition TSystem.cxx:740
virtual Bool_t ProcessEvents()
Process pending events (GUI, timers, sockets).
Definition TSystem.cxx:420
virtual const char * GetSoExt() const
Get the shared library extension.
Definition TSystem.cxx:4106
virtual int Utime(const char *file, Long_t modtime, Long_t actime)
Set the a files modification and access times.
Definition TSystem.cxx:1550
virtual const char * GetError()
Return system error string.
Definition TSystem.cxx:255
virtual int AnnounceTcpService(int port, Bool_t reuse, int backlog, int tcpwindowsize=-1, ESocketBindOption socketBindOption=ESocketBindOption::kInaddrAny)
Announce TCP/IP service.
Definition TSystem.cxx:2373
virtual TTimer * RemoveTimer(TTimer *t)
Remove timer from list of system timers.
Definition TSystem.cxx:485
virtual TString GetDirName(const char *pathname)
Return the directory name in pathname.
Definition TSystem.cxx:1048
virtual Int_t GetFPEMask()
Return the bitmap of conditions that trigger a floating point exception.
Definition TSystem.cxx:636
virtual int Unlink(const char *name)
Unlink, i.e.
Definition TSystem.cxx:1404
virtual void StackTrace()
Print a stack trace.
Definition TSystem.cxx:749
virtual UserGroup_t * GetUserInfo(Int_t uid)
Returns all user info in the UserGroup_t structure.
Definition TSystem.cxx:1624
virtual int AnnounceUdpService(int port, int backlog, ESocketBindOption socketBindOption=ESocketBindOption::kInaddrAny)
Announce UDP service.
Definition TSystem.cxx:2382
virtual void ResetSignals()
Reset signals handlers to previous behaviour.
Definition TSystem.cxx:588
TString fBuildNode
Definition TSystem.h:326
virtual const char * TempDirectory() const
Return a user configured or systemwide directory to create temporary files in.
Definition TSystem.cxx:1505
virtual const char * GetFlagsOpt() const
Return the optimization flags.
Definition TSystem.cxx:4028
virtual Bool_t ConsistentWith(const char *path, void *dirptr=nullptr)
Check consistency of this helper with the one required by 'path' or 'dirptr'.
Definition TSystem.cxx:819
char * DynamicPathName(const char *lib, Bool_t quiet=kFALSE)
Find a dynamic library called lib using the system search paths.
Definition TSystem.cxx:2043
Basic time type with millisecond precision.
Definition TTime.h:27
Handles synchronous and a-synchronous timer events.
Definition TTimer.h:51
TTime GetAbsTime() const
Definition TTimer.h:78
virtual void TurnOn()
Add the timer to the system timer list.
Definition TTimer.cxx:246
Bool_t IsAsync() const
Definition TTimer.h:81
void Reset()
Reset the timer.
Definition TTimer.cxx:162
Bool_t IsInterruptingSyscalls() const
Definition TTimer.h:82
void Remove() override
Definition TTimer.h:86
Bool_t fTimeout
Definition TTimer.h:56
Bool_t IsSync() const
Definition TTimer.h:80
This class represents a WWW compatible URL.
Definition TUrl.h:33
const char * GetUser() const
Definition TUrl.h:65
const char * GetHost() const
Definition TUrl.h:67
const char * GetProtocol() const
Definition TUrl.h:64
TVersionCheck(int versionCode)
Register version of plugin library.
Definition TSystem.cxx:4494
This class implements a mutex interface.
TLine * line
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
std::string MakePathRelative(const std::string &path, const std::string &base, bool isBuildingROOT=false)
bool GetCryptoRandom(void *buf, unsigned int len)
Get random bytes from the operating system's cryptographic random number generator The requested numb...
R__EXTERN TVirtualRWMutex * gCoreMutex
Int_t fMode
Definition TSystem.h:135
Long64_t fSize
Definition TSystem.h:138
Long_t fDev
Definition TSystem.h:133
Long_t fMtime
Definition TSystem.h:139
Long_t fIno
Definition TSystem.h:134
virtual ~ProcInfo_t()
Definition TSystem.cxx:78
TString fUser
Definition TSystem.h:149
TLine l
Definition textangle.C:4
auto * tt
Definition textangle.C:16