Logo ROOT   6.12/07
Reference Guide
TUnixSystem.cxx
Go to the documentation of this file.
1 // @(#)root/unix:$Id: 887c618d89c4ed436e4034fc133f468fecad651b $
2 // Author: Fons Rademakers 15/09/95
3 
4 /*************************************************************************
5  * Copyright (C) 1995-2000, 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 //////////////////////////////////////////////////////////////////////////
13 // //
14 // TUnixSystem //
15 // //
16 // Class providing an interface to the UNIX Operating System. //
17 // //
18 //////////////////////////////////////////////////////////////////////////
19 
20 #include "RConfigure.h"
21 #include "RConfig.h"
22 #include "TUnixSystem.h"
23 #include "TROOT.h"
24 #include "TError.h"
25 #include "TOrdCollection.h"
26 #include "TRegexp.h"
27 #include "TPRegexp.h"
28 #include "TException.h"
29 #include "Demangle.h"
30 #include "TEnv.h"
31 #include "TSocket.h"
32 #include "Getline.h"
33 #include "TInterpreter.h"
34 #include "TApplication.h"
35 #include "TObjString.h"
36 #include "Riostream.h"
37 #include "TVirtualMutex.h"
38 #include "TObjArray.h"
39 #include <map>
40 #include <algorithm>
41 #include <atomic>
42 
43 //#define G__OLDEXPAND
44 
45 #include <unistd.h>
46 #include <stdlib.h>
47 #include <sys/types.h>
48 #if defined(R__SUN) || defined(R__AIX) || \
49  defined(R__LINUX) || defined(R__SOLARIS) || \
50  defined(R__FBSD) || defined(R__OBSD) || \
51  defined(R__MACOSX) || defined(R__HURD)
52 #define HAS_DIRENT
53 #endif
54 #ifdef HAS_DIRENT
55 # include <dirent.h>
56 #else
57 # include <sys/dir.h>
58 #endif
59 #if defined(ULTRIX) || defined(R__SUN)
60 # include <sgtty.h>
61 #endif
62 #if defined(R__AIX) || defined(R__LINUX) || \
63  defined(R__FBSD) || defined(R__OBSD) || \
64  defined(R__LYNXOS) || defined(R__MACOSX) || defined(R__HURD)
65 # include <sys/ioctl.h>
66 #endif
67 #if defined(R__AIX) || defined(R__SOLARIS)
68 # include <sys/select.h>
69 #endif
70 #if defined(R__LINUX) || defined(R__HURD)
71 # ifndef SIGSYS
72 # define SIGSYS SIGUNUSED // SIGSYS does not exist in linux ??
73 # endif
74 #endif
75 #if defined(R__MACOSX)
76 # include <mach-o/dyld.h>
77 # include <sys/mount.h>
78  extern "C" int statfs(const char *file, struct statfs *buffer);
79 #elif defined(R__LINUX) || defined(R__HURD)
80 # include <sys/vfs.h>
81 #elif defined(R__FBSD) || defined(R__OBSD)
82 # include <sys/param.h>
83 # include <sys/mount.h>
84 #else
85 # include <sys/statfs.h>
86 #endif
87 
88 #include <utime.h>
89 #include <syslog.h>
90 #include <sys/stat.h>
91 #include <setjmp.h>
92 #include <signal.h>
93 #include <sys/param.h>
94 #include <pwd.h>
95 #include <grp.h>
96 #include <errno.h>
97 #include <sys/resource.h>
98 #include <sys/wait.h>
99 #include <time.h>
100 #include <sys/time.h>
101 #include <sys/file.h>
102 #include <sys/socket.h>
103 #include <netinet/in.h>
104 #include <netinet/tcp.h>
105 #if defined(R__AIX)
106 # define _XOPEN_EXTENDED_SOURCE
107 # include <arpa/inet.h>
108 # undef _XOPEN_EXTENDED_SOURCE
109 # if !defined(_AIX41) && !defined(_AIX43)
110  // AIX 3.2 doesn't have it
111 # define HASNOT_INETATON
112 # endif
113 #else
114 # include <arpa/inet.h>
115 #endif
116 #include <sys/un.h>
117 #include <netdb.h>
118 #include <fcntl.h>
119 #if defined(R__SOLARIS)
120 # include <sys/systeminfo.h>
121 # include <sys/filio.h>
122 # include <sys/sockio.h>
123 # define HASNOT_INETATON
124 # ifndef INADDR_NONE
125 # define INADDR_NONE (UInt_t)-1
126 # endif
127 #endif
128 
129 #if defined(R__SOLARIS)
130 # define HAVE_UTMPX_H
131 # define UTMP_NO_ADDR
132 #endif
133 
134 #if defined(MAC_OS_X_VERSION_10_5)
135 # define HAVE_UTMPX_H
136 # define UTMP_NO_ADDR
137 #endif
138 
139 #if defined(R__FBSD)
140 # include <sys/param.h>
141 # if __FreeBSD_version >= 900007
142 # define HAVE_UTMPX_H
143 # endif
144 #endif
145 
146 #if defined(R__AIX) || defined(R__FBSD) || \
147  defined(R__OBSD) || defined(R__LYNXOS) || \
148  (defined(R__MACOSX) && !defined(MAC_OS_X_VERSION_10_5))
149 # define UTMP_NO_ADDR
150 #endif
151 
152 #if (defined(R__AIX) && !defined(_AIX43)) || \
153  (defined(R__SUNGCC3) && !defined(__arch64__))
154 # define USE_SIZE_T
155 #elif defined(R__GLIBC) || defined(R__FBSD) || \
156  (defined(R__SUNGCC3) && defined(__arch64__)) || \
157  defined(R__OBSD) || defined(MAC_OS_X_VERSION_10_4) || \
158  (defined(R__AIX) && defined(_AIX43)) || \
159  (defined(R__SOLARIS) && defined(_SOCKLEN_T))
160 # define USE_SOCKLEN_T
161 #endif
162 
163 #if defined(R__LYNXOS)
164 extern "C" {
165  extern int putenv(const char *);
166  extern int inet_aton(const char *, struct in_addr *);
167 };
168 #endif
169 
170 #ifdef HAVE_UTMPX_H
171 #include <utmpx.h>
172 #define STRUCT_UTMP struct utmpx
173 #else
174 #include <utmp.h>
175 #define STRUCT_UTMP struct utmp
176 #endif
177 #if !defined(UTMP_FILE) && defined(_PATH_UTMP) // 4.4BSD
178 #define UTMP_FILE _PATH_UTMP
179 #endif
180 #if defined(UTMPX_FILE) // Solaris, SysVr4
181 #undef UTMP_FILE
182 #define UTMP_FILE UTMPX_FILE
183 #endif
184 #ifndef UTMP_FILE
185 #define UTMP_FILE "/etc/utmp"
186 #endif
187 
188 // stack trace code
189 #if (defined(R__LINUX) || defined(R__HURD)) && !defined(R__WINGCC)
190 # if __GLIBC__ == 2 && __GLIBC_MINOR__ >= 1
191 # define HAVE_BACKTRACE_SYMBOLS_FD
192 # endif
193 # define HAVE_DLADDR
194 #endif
195 #if defined(R__MACOSX)
196 # define HAVE_BACKTRACE_SYMBOLS_FD
197 # define HAVE_DLADDR
198 #endif
199 
200 #ifdef HAVE_BACKTRACE_SYMBOLS_FD
201 # include <execinfo.h>
202 #endif
203 #ifdef HAVE_DLADDR
204 # ifndef __USE_GNU
205 # define __USE_GNU
206 # endif
207 # include <dlfcn.h>
208 #endif
209 
210 #ifdef HAVE_BACKTRACE_SYMBOLS_FD
211  // The maximum stack trace depth for systems where we request the
212  // stack depth separately (currently glibc-based systems).
213  static const int kMAX_BACKTRACE_DEPTH = 128;
214 #endif
215 
216 // FPE handling includes
217 #if (defined(R__LINUX) && !defined(R__WINGCC))
218 #include <fpu_control.h>
219 #include <fenv.h>
220 #include <sys/prctl.h> // for prctl() function used in StackTrace()
221 #endif
222 
223 #if defined(R__MACOSX) && defined(__SSE2__)
224 #include <xmmintrin.h>
225 #endif
226 
227 #if defined(R__MACOSX) && !defined(__SSE2__) && !defined(__xlC__) && \
228  !defined(__i386__) && !defined(__x86_64__) && !defined(__arm__) && \
229  !defined(__arm64__)
230 #include <fenv.h>
231 #include <signal.h>
232 #include <ucontext.h>
233 #include <stdlib.h>
234 #include <stdio.h>
235 #include <mach/thread_status.h>
236 
237 #define fegetenvd(x) asm volatile("mffs %0" : "=f" (x));
238 #define fesetenvd(x) asm volatile("mtfsf 255,%0" : : "f" (x));
239 
240 enum {
241  FE_ENABLE_INEXACT = 0x00000008,
242  FE_ENABLE_DIVBYZERO = 0x00000010,
243  FE_ENABLE_UNDERFLOW = 0x00000020,
244  FE_ENABLE_OVERFLOW = 0x00000040,
245  FE_ENABLE_INVALID = 0x00000080,
246  FE_ENABLE_ALL_EXCEPT = 0x000000F8
247 };
248 #endif
249 
250 #if defined(R__MACOSX) && !defined(__SSE2__) && \
251  (defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__arm64__))
252 #include <fenv.h>
253 #endif
254 // End FPE handling includes
255 
256 namespace {
257  // Depending on the platform the struct utmp (or utmpx) has either ut_name or ut_user
258  // which are semantically equivalent. Instead of using preprocessor magic,
259  // which is bothersome for cxx modules use SFINAE.
260 
261  template<typename T>
262  struct ut_name {
263  template<typename U = T, typename std::enable_if<std::is_member_pointer<decltype(&U::ut_name)>::value, int>::type = 0>
264  static char getValue(U* ue, int) {
265  return ue->ut_name[0];
266  }
267 
268  template<typename U = T, typename std::enable_if<std::is_member_pointer<decltype(&U::ut_user)>::value, int>::type = 0>
269  static char getValue(U* ue, long) {
270  return ue->ut_user[0];
271  }
272  };
273 
274  static char get_ut_name(STRUCT_UTMP *ue) {
275  // 0 is an integer literal forcing an overload pickup in case both ut_name and ut_user are present.
276  return ut_name<STRUCT_UTMP>::getValue(ue, 0);
277  }
278 }
279 
280 struct TUtmpContent {
281  STRUCT_UTMP *fUtmpContents;
282  UInt_t fEntries; // Number of entries in utmp file.
283 
284  TUtmpContent() : fUtmpContents(0), fEntries(0) {}
285  ~TUtmpContent() { free(fUtmpContents); }
286 
287  STRUCT_UTMP *SearchUtmpEntry(const char *tty)
288  {
289  // Look for utmp entry which is connected to terminal tty.
290 
291  STRUCT_UTMP *ue = fUtmpContents;
292 
293  UInt_t n = fEntries;
294  while (n--) {
295  if (get_ut_name(ue) && !strncmp(tty, ue->ut_line, sizeof(ue->ut_line)))
296  return ue;
297  ue++;
298  }
299  return 0;
300  }
301 
302  int ReadUtmpFile()
303  {
304  // Read utmp file. Returns number of entries in utmp file.
305 
306  FILE *utmp;
307  struct stat file_stats;
308  size_t n_read, size;
309 
310  fEntries = 0;
311 
313 
314  utmp = fopen(UTMP_FILE, "r");
315  if (!utmp)
316  return 0;
317 
318  if (fstat(fileno(utmp), &file_stats) == -1) {
319  fclose(utmp);
320  return 0;
321  }
322  size = file_stats.st_size;
323  if (size <= 0) {
324  fclose(utmp);
325  return 0;
326  }
327 
328  fUtmpContents = (STRUCT_UTMP *) malloc(size);
329  if (!fUtmpContents) {
330  fclose(utmp);
331  return 0;
332  }
333 
334  n_read = fread(fUtmpContents, 1, size, utmp);
335  if (!ferror(utmp)) {
336  if (fclose(utmp) != EOF && n_read == size) {
337  fEntries = size / sizeof(STRUCT_UTMP);
338  return fEntries;
339  }
340  } else
341  fclose(utmp);
342 
343  free(fUtmpContents);
344  fUtmpContents = 0;
345  return 0;
346  }
347 
348 };
349 
350 const char *kServerPath = "/tmp";
351 const char *kProtocolName = "tcp";
352 
353 //------------------- Unix TFdSet ----------------------------------------------
354 #ifndef HOWMANY
355 # define HOWMANY(x, y) (((x)+((y)-1))/(y))
356 #endif
357 
358 const Int_t kNFDBITS = (sizeof(Long_t) * 8); // 8 bits per byte
359 #ifdef FD_SETSIZE
360 const Int_t kFDSETSIZE = FD_SETSIZE; // Linux = 1024 file descriptors
361 #else
362 const Int_t kFDSETSIZE = 256; // upto 256 file descriptors
363 #endif
364 
365 
366 class TFdSet {
367 private:
368  ULong_t fds_bits[HOWMANY(kFDSETSIZE, kNFDBITS)];
369 public:
370  TFdSet() { memset(fds_bits, 0, sizeof(fds_bits)); }
371  TFdSet(const TFdSet &org) { memcpy(fds_bits, org.fds_bits, sizeof(org.fds_bits)); }
372  TFdSet &operator=(const TFdSet &rhs) { if (this != &rhs) { memcpy(fds_bits, rhs.fds_bits, sizeof(rhs.fds_bits));} return *this; }
373  void Zero() { memset(fds_bits, 0, sizeof(fds_bits)); }
374  void Set(Int_t n)
375  {
376  if (n >= 0 && n < kFDSETSIZE) {
377  fds_bits[n/kNFDBITS] |= (1UL << (n % kNFDBITS));
378  } else {
379  ::Fatal("TFdSet::Set","fd (%d) out of range [0..%d]", n, kFDSETSIZE-1);
380  }
381  }
382  void Clr(Int_t n)
383  {
384  if (n >= 0 && n < kFDSETSIZE) {
385  fds_bits[n/kNFDBITS] &= ~(1UL << (n % kNFDBITS));
386  } else {
387  ::Fatal("TFdSet::Clr","fd (%d) out of range [0..%d]", n, kFDSETSIZE-1);
388  }
389  }
390  Int_t IsSet(Int_t n)
391  {
392  if (n >= 0 && n < kFDSETSIZE) {
393  return (fds_bits[n/kNFDBITS] & (1UL << (n % kNFDBITS))) != 0;
394  } else {
395  ::Fatal("TFdSet::IsSet","fd (%d) out of range [0..%d]", n, kFDSETSIZE-1);
396  return 0;
397  }
398  }
399  ULong_t *GetBits() { return (ULong_t *)fds_bits; }
400 };
401 
402 ////////////////////////////////////////////////////////////////////////////////
403 /// Unix signal handler.
404 
405 static void SigHandler(ESignals sig)
406 {
407  if (gSystem)
408  ((TUnixSystem*)gSystem)->DispatchSignals(sig);
409 }
410 
411 ////////////////////////////////////////////////////////////////////////////////
412 
413 static const char *GetExePath()
414 {
415  TTHREAD_TLS_DECL(TString,exepath);
416  if (exepath == "") {
417 #if defined(R__MACOSX)
418  exepath = _dyld_get_image_name(0);
419 #elif defined(R__LINUX) || defined(R__SOLARIS) || defined(R__FBSD)
420  char buf[kMAXPATHLEN]; // exe path name
421 
422  // get the name from the link in /proc
423 #if defined(R__LINUX)
424  int ret = readlink("/proc/self/exe", buf, kMAXPATHLEN);
425 #elif defined(R__SOLARIS)
426  int ret = readlink("/proc/self/path/a.out", buf, kMAXPATHLEN);
427 #elif defined(R__FBSD)
428  int ret = readlink("/proc/curproc/file", buf, kMAXPATHLEN);
429 #endif
430  if (ret > 0 && ret < kMAXPATHLEN) {
431  buf[ret] = 0;
432  exepath = buf;
433  }
434 #else
435  if (!gApplication)
436  return exepath;
437  TString p = gApplication->Argv(0);
438  if (p.BeginsWith("/"))
439  exepath = p;
440  else if (p.Contains("/")) {
441  exepath = gSystem->WorkingDirectory();
442  exepath += "/";
443  exepath += p;
444  } else {
445  char *exe = gSystem->Which(gSystem->Getenv("PATH"), p, kExecutePermission);
446  if (exe) {
447  exepath = exe;
448  delete [] exe;
449  }
450  }
451 #endif
452  }
453  return exepath;
454 }
455 
456 #if defined(HAVE_DLADDR) && !defined(R__MACOSX)
457 ////////////////////////////////////////////////////////////////////////////////
458 
459 static void SetRootSys()
460 {
461 #ifdef ROOTPREFIX
462  if (gSystem->Getenv("ROOTIGNOREPREFIX")) {
463 #endif
464  void *addr = (void *)SetRootSys;
465  Dl_info info;
466  if (dladdr(addr, &info) && info.dli_fname && info.dli_fname[0]) {
467  char respath[kMAXPATHLEN];
468  if (!realpath(info.dli_fname, respath)) {
469  if (!gSystem->Getenv("ROOTSYS"))
470  ::SysError("TUnixSystem::SetRootSys", "error getting realpath of libCore, please set ROOTSYS in the shell");
471  } else {
472  TString rs = gSystem->DirName(respath);
473  gSystem->Setenv("ROOTSYS", gSystem->DirName(rs));
474  }
475  }
476 #ifdef ROOTPREFIX
477  }
478 #endif
479 }
480 #endif
481 
482 #if defined(R__MACOSX)
483 static TString gLinkedDylibs;
484 
485 ////////////////////////////////////////////////////////////////////////////////
486 
487 static void DylibAdded(const struct mach_header *mh, intptr_t /* vmaddr_slide */)
488 {
489  static int i = 0;
490  static Bool_t gotFirstSo = kFALSE;
491  static TString linkedDylibs;
492 
493  // to copy the local linkedDylibs to the global gLinkedDylibs call this
494  // function with mh==0
495  if (!mh) {
496  gLinkedDylibs = linkedDylibs;
497  return;
498  }
499 
500  TString lib = _dyld_get_image_name(i++);
501 
502  TRegexp sovers = "libCore\\.[0-9]+\\.*[0-9]*\\.*[0-9]*\\.so";
503  TRegexp dyvers = "libCore\\.[0-9]+\\.*[0-9]*\\.*[0-9]*\\.dylib";
504 
505 #ifdef ROOTPREFIX
506  if (gSystem->Getenv("ROOTIGNOREPREFIX")) {
507 #endif
508 #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
509  // first loaded is the app so set ROOTSYS to app bundle
510  if (i == 1) {
511  char respath[kMAXPATHLEN];
512  if (!realpath(lib, respath)) {
513  if (!gSystem->Getenv("ROOTSYS"))
514  ::SysError("TUnixSystem::DylibAdded", "error getting realpath of %s", gSystem->BaseName(lib));
515  } else {
516  TString rs = gSystem->DirName(respath);
517  gSystem->Setenv("ROOTSYS", rs);
518  }
519  }
520 #else
521  if (lib.EndsWith("libCore.dylib") || lib.EndsWith("libCore.so") ||
522  lib.Index(sovers) != kNPOS || lib.Index(dyvers) != kNPOS) {
523  char respath[kMAXPATHLEN];
524  if (!realpath(lib, respath)) {
525  if (!gSystem->Getenv("ROOTSYS"))
526  ::SysError("TUnixSystem::DylibAdded", "error getting realpath of libCore, please set ROOTSYS in the shell");
527  } else {
528  TString rs = gSystem->DirName(respath);
529  gSystem->Setenv("ROOTSYS", gSystem->DirName(rs));
530  }
531  }
532 #endif
533 #ifdef ROOTPREFIX
534  }
535 #endif
536 
537  // when libSystem.B.dylib is loaded we have finished loading all dylibs
538  // explicitly linked against the executable. Additional dylibs
539  // come when they are explicitly linked against loaded so's, currently
540  // we are not interested in these
541  if (lib.EndsWith("/libSystem.B.dylib"))
542  gotFirstSo = kTRUE;
543 
544  // add all libs loaded before libSystem.B.dylib
545  if (!gotFirstSo && (lib.EndsWith(".dylib") || lib.EndsWith(".so"))) {
546  sovers = "\\.[0-9]+\\.*[0-9]*\\.so";
547  Ssiz_t idx = lib.Index(sovers);
548  if (idx != kNPOS) {
549  lib.Remove(idx);
550  lib += ".so";
551  }
552  dyvers = "\\.[0-9]+\\.*[0-9]*\\.dylib";
553  idx = lib.Index(dyvers);
554  if (idx != kNPOS) {
555  lib.Remove(idx);
556  lib += ".dylib";
557  }
558  if (!gSystem->AccessPathName(lib, kReadPermission)) {
559  if (linkedDylibs.Length())
560  linkedDylibs += " ";
561  linkedDylibs += lib;
562  }
563  }
564 }
565 #endif
566 
568 
569 ////////////////////////////////////////////////////////////////////////////////
570 
571 TUnixSystem::TUnixSystem() : TSystem("Unix", "Unix System")
572 { }
573 
574 ////////////////////////////////////////////////////////////////////////////////
575 /// Reset to original state.
576 
578 {
580 
581  delete fReadmask;
582  delete fWritemask;
583  delete fReadready;
584  delete fWriteready;
585  delete fSignals;
586 }
587 
588 ////////////////////////////////////////////////////////////////////////////////
589 /// Initialize Unix system interface.
590 
592 {
593  if (TSystem::Init())
594  return kTRUE;
595 
596  fReadmask = new TFdSet;
597  fWritemask = new TFdSet;
598  fReadready = new TFdSet;
599  fWriteready = new TFdSet;
600  fSignals = new TFdSet;
601 
602  //--- install default handlers
612 
613 #if defined(R__MACOSX)
614  // trap loading of all dylibs to register dylib name,
615  // sets also ROOTSYS if built without ROOTPREFIX
616  _dyld_register_func_for_add_image(DylibAdded);
617 #elif defined(HAVE_DLADDR)
618  SetRootSys();
619 #endif
620 
621  // This is a fallback in case TROOT::GetRootSys() can't determine ROOTSYS
622  gRootDir = "/usr/local/root";
623 
624  return kFALSE;
625 }
626 
627 //---- Misc --------------------------------------------------------------------
628 
629 ////////////////////////////////////////////////////////////////////////////////
630 /// Set the application name (from command line, argv[0]) and copy it in
631 /// gProgName. Copy the application pathname in gProgPath.
632 /// If name is 0 let the system set the actual executable name and path
633 /// (works on MacOS X and Linux).
634 
636 {
637  if (gProgName)
638  delete [] gProgName;
639  if (gProgPath)
640  delete [] gProgPath;
641 
642  if (!name || !*name) {
643  name = GetExePath();
644  gProgName = StrDup(BaseName(name));
645  gProgPath = StrDup(DirName(name));
646  } else {
647  gProgName = StrDup(BaseName(name));
648  char *w = Which(Getenv("PATH"), gProgName);
649  gProgPath = StrDup(DirName(w));
650  delete [] w;
651  }
652 }
653 
654 ////////////////////////////////////////////////////////////////////////////////
655 /// Set DISPLAY environment variable based on utmp entry. Only for UNIX.
656 
658 {
659  if (!Getenv("DISPLAY")) {
660  char *tty = ::ttyname(0); // device user is logged in on
661  if (tty) {
662  tty += 5; // remove "/dev/"
663 
664  TUtmpContent utmp;
665  utmp.ReadUtmpFile();
666 
667  STRUCT_UTMP *utmp_entry = utmp.SearchUtmpEntry(tty);
668  if (utmp_entry) {
669  if (utmp_entry->ut_host[0]) {
670  if (strchr(utmp_entry->ut_host, ':')) {
671  Setenv("DISPLAY", utmp_entry->ut_host);
672  Warning("SetDisplay", "DISPLAY not set, setting it to %s",
673  utmp_entry->ut_host);
674  } else {
675  char disp[260];
676  snprintf(disp, sizeof(disp), "%s:0.0", utmp_entry->ut_host);
677  Setenv("DISPLAY", disp);
678  Warning("SetDisplay", "DISPLAY not set, setting it to %s",
679  disp);
680  }
681  }
682 #ifndef UTMP_NO_ADDR
683  else if (utmp_entry->ut_addr) {
684 
685  struct sockaddr_in addr;
686  addr.sin_family = AF_INET;
687  addr.sin_port = 0;
688  memcpy(&addr.sin_addr, &utmp_entry->ut_addr, sizeof(addr.sin_addr));
689  memset(&addr.sin_zero[0], 0, sizeof(addr.sin_zero));
690  struct sockaddr *sa = (struct sockaddr *) &addr; // input
691 
692  char hbuf[NI_MAXHOST];
693  if (getnameinfo(sa, sizeof(struct sockaddr), hbuf, sizeof(hbuf), nullptr, 0, NI_NAMEREQD) == 0) {
694  char disp[64];
695  snprintf(disp, sizeof(disp), "%s:0.0", hbuf);
696  Setenv("DISPLAY", disp);
697  Warning("SetDisplay", "DISPLAY not set, setting it to %s",
698  disp);
699  }
700  }
701 #endif
702  }
703  }
704  }
705 }
706 
707 ////////////////////////////////////////////////////////////////////////////////
708 /// Return system error string.
709 
711 {
712  Int_t err = GetErrno();
713  if (err == 0 && GetLastErrorString() != "")
714  return GetLastErrorString();
715 
716 #if defined(R__SOLARIS) || defined (R__LINUX) || defined(R__AIX) || \
717  defined(R__FBSD) || defined(R__OBSD) || defined(R__HURD)
718  return strerror(err);
719 #else
720  if (err < 0 || err >= sys_nerr)
721  return Form("errno out of range %d", err);
722  return sys_errlist[err];
723 #endif
724 }
725 
726 ////////////////////////////////////////////////////////////////////////////////
727 /// Return the system's host name.
728 
730 {
731  if (fHostname == "") {
732  char hn[64];
733 #if defined(R__SOLARIS)
734  sysinfo(SI_HOSTNAME, hn, sizeof(hn));
735 #else
736  gethostname(hn, sizeof(hn));
737 #endif
738  fHostname = hn;
739  }
740  return (const char *)fHostname;
741 }
742 
743 //---- EventLoop ---------------------------------------------------------------
744 
745 ////////////////////////////////////////////////////////////////////////////////
746 /// Add a file handler to the list of system file handlers. Only adds
747 /// the handler if it is not already in the list of file handlers.
748 
750 {
752 
754  if (h) {
755  int fd = h->GetFd();
756  if (h->HasReadInterest()) {
757  fReadmask->Set(fd);
758  fMaxrfd = TMath::Max(fMaxrfd, fd);
759  }
760  if (h->HasWriteInterest()) {
761  fWritemask->Set(fd);
762  fMaxwfd = TMath::Max(fMaxwfd, fd);
763  }
764  }
765 }
766 
767 ////////////////////////////////////////////////////////////////////////////////
768 /// Remove a file handler from the list of file handlers. Returns
769 /// the handler or 0 if the handler was not in the list of file handlers.
770 
772 {
773  if (!h) return 0;
774 
776 
778  if (oh) { // found
779  TFileHandler *th;
780  TIter next(fFileHandler);
781  fMaxrfd = -1;
782  fMaxwfd = -1;
783  fReadmask->Zero();
784  fWritemask->Zero();
785  while ((th = (TFileHandler *) next())) {
786  int fd = th->GetFd();
787  if (th->HasReadInterest()) {
788  fReadmask->Set(fd);
789  fMaxrfd = TMath::Max(fMaxrfd, fd);
790  }
791  if (th->HasWriteInterest()) {
792  fWritemask->Set(fd);
793  fMaxwfd = TMath::Max(fMaxwfd, fd);
794  }
795  }
796  }
797  return oh;
798 }
799 
800 ////////////////////////////////////////////////////////////////////////////////
801 /// Add a signal handler to list of system signal handlers. Only adds
802 /// the handler if it is not already in the list of signal handlers.
803 
805 {
807 
810 }
811 
812 ////////////////////////////////////////////////////////////////////////////////
813 /// Remove a signal handler from list of signal handlers. Returns
814 /// the handler or 0 if the handler was not in the list of signal handlers.
815 
817 {
818  if (!h) return 0;
819 
821 
823 
824  Bool_t last = kTRUE;
825  TSignalHandler *hs;
826  TIter next(fSignalHandler);
827 
828  while ((hs = (TSignalHandler*) next())) {
829  if (hs->GetSignal() == h->GetSignal())
830  last = kFALSE;
831  }
832  if (last)
833  ResetSignal(h->GetSignal(), kTRUE);
834 
835  return oh;
836 }
837 
838 ////////////////////////////////////////////////////////////////////////////////
839 /// If reset is true reset the signal handler for the specified signal
840 /// to the default handler, else restore previous behaviour.
841 
843 {
844  if (reset)
845  UnixResetSignal(sig);
846  else
847  UnixSignal(sig, SigHandler);
848 }
849 
850 ////////////////////////////////////////////////////////////////////////////////
851 /// Reset signals handlers to previous behaviour.
852 
854 {
856 }
857 
858 ////////////////////////////////////////////////////////////////////////////////
859 /// If ignore is true ignore the specified signal, else restore previous
860 /// behaviour.
861 
863 {
864  UnixIgnoreSignal(sig, ignore);
865 }
866 
867 ////////////////////////////////////////////////////////////////////////////////
868 /// When the argument is true the SIGALRM signal handler is set so that
869 /// interrupted syscalls will not be restarted by the kernel. This is
870 /// typically used in case one wants to put a timeout on an I/O operation.
871 /// By default interrupted syscalls will always be restarted (for all
872 /// signals). This can be controlled for each a-synchronous TTimer via
873 /// the method TTimer::SetInterruptSyscalls().
874 
876 {
878 }
879 
880 ////////////////////////////////////////////////////////////////////////////////
881 /// Return the bitmap of conditions that trigger a floating point exception.
882 
884 {
885  Int_t mask = 0;
886 
887 #if defined(R__LINUX) && !defined(__powerpc__)
888 #if defined(__GLIBC__) && (__GLIBC__>2 || __GLIBC__==2 && __GLIBC_MINOR__>=1)
889 
890 #if __GLIBC_MINOR__>=3
891 
892  Int_t oldmask = fegetexcept();
893 
894 #else
895  fenv_t oldenv;
896  fegetenv(&oldenv);
897  fesetenv(&oldenv);
898 #if __ia64__
899  Int_t oldmask = ~oldenv;
900 #else
901  Int_t oldmask = ~oldenv.__control_word;
902 #endif
903 #endif
904 
905  if (oldmask & FE_INVALID ) mask |= kInvalid;
906  if (oldmask & FE_DIVBYZERO) mask |= kDivByZero;
907  if (oldmask & FE_OVERFLOW ) mask |= kOverflow;
908  if (oldmask & FE_UNDERFLOW) mask |= kUnderflow;
909 # ifdef FE_INEXACT
910  if (oldmask & FE_INEXACT ) mask |= kInexact;
911 # endif
912 #endif
913 #endif
914 
915 #if defined(R__MACOSX) && defined(__SSE2__)
916  // OS X uses the SSE unit for all FP math by default, not the x87 FP unit
917  Int_t oldmask = ~_MM_GET_EXCEPTION_MASK();
918 
919  if (oldmask & _MM_MASK_INVALID ) mask |= kInvalid;
920  if (oldmask & _MM_MASK_DIV_ZERO ) mask |= kDivByZero;
921  if (oldmask & _MM_MASK_OVERFLOW ) mask |= kOverflow;
922  if (oldmask & _MM_MASK_UNDERFLOW) mask |= kUnderflow;
923  if (oldmask & _MM_MASK_INEXACT ) mask |= kInexact;
924 #endif
925 
926 #if defined(R__MACOSX) && !defined(__SSE2__) && \
927  (defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__arm64__))
928  fenv_t oldenv;
929  fegetenv(&oldenv);
930  fesetenv(&oldenv);
931 #if defined(__arm__)
932  Int_t oldmask = ~oldenv.__fpscr;
933 #elif defined(__arm64__)
934  Int_t oldmask = ~oldenv.__fpcr;
935 #else
936  Int_t oldmask = ~oldenv.__control;
937 #endif
938 
939  if (oldmask & FE_INVALID ) mask |= kInvalid;
940  if (oldmask & FE_DIVBYZERO) mask |= kDivByZero;
941  if (oldmask & FE_OVERFLOW ) mask |= kOverflow;
942  if (oldmask & FE_UNDERFLOW) mask |= kUnderflow;
943  if (oldmask & FE_INEXACT ) mask |= kInexact;
944 #endif
945 
946 #if defined(R__MACOSX) && !defined(__SSE2__) && !defined(__xlC__) && \
947  !defined(__i386__) && !defined(__x86_64__) && !defined(__arm__) && \
948  !defined(__arm64__)
949  Long64_t oldmask;
950  fegetenvd(oldmask);
951 
952  if (oldmask & FE_ENABLE_INVALID ) mask |= kInvalid;
953  if (oldmask & FE_ENABLE_DIVBYZERO) mask |= kDivByZero;
954  if (oldmask & FE_ENABLE_OVERFLOW ) mask |= kOverflow;
955  if (oldmask & FE_ENABLE_UNDERFLOW) mask |= kUnderflow;
956  if (oldmask & FE_ENABLE_INEXACT ) mask |= kInexact;
957 #endif
958 
959  return mask;
960 }
961 
962 ////////////////////////////////////////////////////////////////////////////////
963 /// Set which conditions trigger a floating point exception.
964 /// Return the previous set of conditions.
965 
967 {
968  if (mask) { } // use mask to avoid warning
969 
970  Int_t old = GetFPEMask();
971 
972 #if defined(R__LINUX) && !defined(__powerpc__)
973 #if defined(__GLIBC__) && (__GLIBC__>2 || __GLIBC__==2 && __GLIBC_MINOR__>=1)
974  Int_t newm = 0;
975  if (mask & kInvalid ) newm |= FE_INVALID;
976  if (mask & kDivByZero) newm |= FE_DIVBYZERO;
977  if (mask & kOverflow ) newm |= FE_OVERFLOW;
978  if (mask & kUnderflow) newm |= FE_UNDERFLOW;
979 # ifdef FE_INEXACT
980  if (mask & kInexact ) newm |= FE_INEXACT;
981 # endif
982 
983 #if __GLIBC_MINOR__>=3
984 
985  // clear pending exceptions so feenableexcept does not trigger them
986  feclearexcept(FE_ALL_EXCEPT);
987  fedisableexcept(FE_ALL_EXCEPT);
988  feenableexcept(newm);
989 
990 #else
991 
992  fenv_t cur;
993  fegetenv(&cur);
994 #if defined __ia64__
995  cur &= ~newm;
996 #else
997  cur.__control_word &= ~newm;
998 #endif
999  fesetenv(&cur);
1000 
1001 #endif
1002 #endif
1003 #endif
1004 
1005 #if defined(R__MACOSX) && defined(__SSE2__)
1006  // OS X uses the SSE unit for all FP math by default, not the x87 FP unit
1007  Int_t newm = 0;
1008  if (mask & kInvalid ) newm |= _MM_MASK_INVALID;
1009  if (mask & kDivByZero) newm |= _MM_MASK_DIV_ZERO;
1010  if (mask & kOverflow ) newm |= _MM_MASK_OVERFLOW;
1011  if (mask & kUnderflow) newm |= _MM_MASK_UNDERFLOW;
1012  if (mask & kInexact ) newm |= _MM_MASK_INEXACT;
1013 
1014  _MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~newm);
1015 #endif
1016 
1017 #if defined(R__MACOSX) && !defined(__SSE2__) && \
1018  (defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__arm64__))
1019  Int_t newm = 0;
1020  if (mask & kInvalid ) newm |= FE_INVALID;
1021  if (mask & kDivByZero) newm |= FE_DIVBYZERO;
1022  if (mask & kOverflow ) newm |= FE_OVERFLOW;
1023  if (mask & kUnderflow) newm |= FE_UNDERFLOW;
1024  if (mask & kInexact ) newm |= FE_INEXACT;
1025 
1026  fenv_t cur;
1027  fegetenv(&cur);
1028 #if defined(__arm__)
1029  cur.__fpscr &= ~newm;
1030 #elif defined(__arm64__)
1031  cur.__fpcr &= ~newm;
1032 #else
1033  cur.__control &= ~newm;
1034 #endif
1035  fesetenv(&cur);
1036 #endif
1037 
1038 #if defined(R__MACOSX) && !defined(__SSE2__) && !defined(__xlC__) && \
1039  !defined(__i386__) && !defined(__x86_64__) && !defined(__arm__) && \
1040  !defined(__arm64__)
1041  Int_t newm = 0;
1042  if (mask & kInvalid ) newm |= FE_ENABLE_INVALID;
1043  if (mask & kDivByZero) newm |= FE_ENABLE_DIVBYZERO;
1044  if (mask & kOverflow ) newm |= FE_ENABLE_OVERFLOW;
1045  if (mask & kUnderflow) newm |= FE_ENABLE_UNDERFLOW;
1046  if (mask & kInexact ) newm |= FE_ENABLE_INEXACT;
1047 
1048  Long64_t curmask;
1049  fegetenvd(curmask);
1050  curmask = (curmask & ~FE_ENABLE_ALL_EXCEPT) | newm;
1051  fesetenvd(curmask);
1052 #endif
1053 
1054  return old;
1055 }
1056 
1057 ////////////////////////////////////////////////////////////////////////////////
1058 /// Dispatch a single event.
1059 
1061 {
1062  Bool_t pollOnce = pendingOnly;
1063 
1064  while (1) {
1065  // first handle any X11 events
1066  if (gXDisplay && gXDisplay->Notify()) {
1067  if (fReadready->IsSet(gXDisplay->GetFd())) {
1068  fReadready->Clr(gXDisplay->GetFd());
1069  fNfd--;
1070  }
1071  if (!pendingOnly) return;
1072  }
1073 
1074  // check for file descriptors ready for reading/writing
1075  if (fNfd > 0 && fFileHandler && fFileHandler->GetSize() > 0)
1076  if (CheckDescriptors())
1077  if (!pendingOnly) return;
1078  fNfd = 0;
1079  fReadready->Zero();
1080  fWriteready->Zero();
1081 
1082  if (pendingOnly && !pollOnce)
1083  return;
1084 
1085  // check synchronous signals
1086  if (fSigcnt > 0 && fSignalHandler->GetSize() > 0)
1087  if (CheckSignals(kTRUE))
1088  if (!pendingOnly) return;
1089  fSigcnt = 0;
1090  fSignals->Zero();
1091 
1092  // check synchronous timers
1093  Long_t nextto;
1094  if (fTimers && fTimers->GetSize() > 0)
1095  if (DispatchTimers(kTRUE)) {
1096  // prevent timers from blocking file descriptor monitoring
1097  nextto = NextTimeOut(kTRUE);
1098  if (nextto > kItimerResolution || nextto == -1)
1099  return;
1100  }
1101 
1102  // if in pendingOnly mode poll once file descriptor activity
1103  nextto = NextTimeOut(kTRUE);
1104  if (pendingOnly) {
1105  if (fFileHandler && fFileHandler->GetSize() == 0)
1106  return;
1107  nextto = 0;
1108  pollOnce = kFALSE;
1109  }
1110 
1111  // nothing ready, so setup select call
1112  *fReadready = *fReadmask;
1113  *fWriteready = *fWritemask;
1114 
1115  int mxfd = TMath::Max(fMaxrfd, fMaxwfd);
1116  mxfd++;
1117 
1118  // if nothing to select (socket or timer) return
1119  if (mxfd == 0 && nextto == -1)
1120  return;
1121 
1122  fNfd = UnixSelect(mxfd, fReadready, fWriteready, nextto);
1123  if (fNfd < 0 && fNfd != -2) {
1124  int fd, rc;
1125  TFdSet t;
1126  for (fd = 0; fd < mxfd; fd++) {
1127  t.Set(fd);
1128  if (fReadmask->IsSet(fd)) {
1129  rc = UnixSelect(fd+1, &t, 0, 0);
1130  if (rc < 0 && rc != -2) {
1131  SysError("DispatchOneEvent", "select: read error on %d", fd);
1132  fReadmask->Clr(fd);
1133  }
1134  }
1135  if (fWritemask->IsSet(fd)) {
1136  rc = UnixSelect(fd+1, 0, &t, 0);
1137  if (rc < 0 && rc != -2) {
1138  SysError("DispatchOneEvent", "select: write error on %d", fd);
1139  fWritemask->Clr(fd);
1140  }
1141  }
1142  t.Clr(fd);
1143  }
1144  }
1145  }
1146 }
1147 
1148 ////////////////////////////////////////////////////////////////////////////////
1149 /// Sleep milliSec milliseconds.
1150 
1152 {
1153  struct timeval tv;
1154 
1155  tv.tv_sec = milliSec / 1000;
1156  tv.tv_usec = (milliSec % 1000) * 1000;
1157 
1158  select(0, 0, 0, 0, &tv);
1159 }
1160 
1161 ////////////////////////////////////////////////////////////////////////////////
1162 /// Select on file descriptors. The timeout to is in millisec. Returns
1163 /// the number of ready descriptors, or 0 in case of timeout, or < 0 in
1164 /// case of an error, with -2 being EINTR and -3 EBADF. In case of EINTR
1165 /// the errno has been reset and the method can be called again. Returns
1166 /// -4 in case the list did not contain any file handlers or file handlers
1167 /// with file descriptor >= 0.
1168 
1170 {
1171  Int_t rc = -4;
1172 
1173  TFdSet rd, wr;
1174  Int_t mxfd = -1;
1175  TIter next(act);
1176  TFileHandler *h = 0;
1177  while ((h = (TFileHandler *) next())) {
1178  Int_t fd = h->GetFd();
1179  if (fd > -1) {
1180  if (h->HasReadInterest()) {
1181  rd.Set(fd);
1182  mxfd = TMath::Max(mxfd, fd);
1183  }
1184  if (h->HasWriteInterest()) {
1185  wr.Set(fd);
1186  mxfd = TMath::Max(mxfd, fd);
1187  }
1188  h->ResetReadyMask();
1189  }
1190  }
1191  if (mxfd > -1)
1192  rc = UnixSelect(mxfd+1, &rd, &wr, to);
1193 
1194  // Set readiness bits
1195  if (rc > 0) {
1196  next.Reset();
1197  while ((h = (TFileHandler *) next())) {
1198  Int_t fd = h->GetFd();
1199  if (rd.IsSet(fd))
1200  h->SetReadReady();
1201  if (wr.IsSet(fd))
1202  h->SetWriteReady();
1203  }
1204  }
1205 
1206  return rc;
1207 }
1208 
1209 ////////////////////////////////////////////////////////////////////////////////
1210 /// Select on the file descriptor related to file handler h.
1211 /// The timeout to is in millisec. Returns the number of ready descriptors,
1212 /// or 0 in case of timeout, or < 0 in case of an error, with -2 being EINTR
1213 /// and -3 EBADF. In case of EINTR the errno has been reset and the method
1214 /// can be called again. Returns -4 in case the file handler is 0 or does
1215 /// not have a file descriptor >= 0.
1216 
1218 {
1219  Int_t rc = -4;
1220 
1221  TFdSet rd, wr;
1222  Int_t mxfd = -1;
1223  Int_t fd = -1;
1224  if (h) {
1225  fd = h->GetFd();
1226  if (fd > -1) {
1227  if (h->HasReadInterest())
1228  rd.Set(fd);
1229  if (h->HasWriteInterest())
1230  wr.Set(fd);
1231  h->ResetReadyMask();
1232  mxfd = fd;
1233  rc = UnixSelect(mxfd+1, &rd, &wr, to);
1234  }
1235  }
1236 
1237  // Fill output lists, if required
1238  if (rc > 0) {
1239  if (rd.IsSet(fd))
1240  h->SetReadReady();
1241  if (wr.IsSet(fd))
1242  h->SetWriteReady();
1243  }
1244 
1245  return rc;
1246 }
1247 
1248 //---- handling of system events -----------------------------------------------
1249 
1250 ////////////////////////////////////////////////////////////////////////////////
1251 /// Check if some signals were raised and call their Notify() member.
1252 
1254 {
1255  TSignalHandler *sh;
1256  Int_t sigdone = -1;
1257  {
1259 
1260  while ((sh = (TSignalHandler*)it.Next())) {
1261  if (sync == sh->IsSync()) {
1262  ESignals sig = sh->GetSignal();
1263  if ((fSignals->IsSet(sig) && sigdone == -1) || sigdone == sig) {
1264  if (sigdone == -1) {
1265  fSignals->Clr(sig);
1266  sigdone = sig;
1267  fSigcnt--;
1268  }
1269  if (sh->IsActive())
1270  sh->Notify();
1271  }
1272  }
1273  }
1274  }
1275  if (sigdone != -1)
1276  return kTRUE;
1277 
1278  return kFALSE;
1279 }
1280 
1281 ////////////////////////////////////////////////////////////////////////////////
1282 /// Check if children have finished.
1283 
1285 {
1286 #if 0 //rdm
1287  int pid;
1288  while ((pid = UnixWaitchild()) > 0) {
1289  TIter next(zombieHandler);
1290  register UnixPtty *pty;
1291  while ((pty = (UnixPtty*) next()))
1292  if (pty->GetPid() == pid) {
1293  zombieHandler->RemovePtr(pty);
1294  pty->DiedNotify();
1295  }
1296  }
1297 #endif
1298 }
1299 
1300 ////////////////////////////////////////////////////////////////////////////////
1301 /// Check if there is activity on some file descriptors and call their
1302 /// Notify() member.
1303 
1305 {
1306  TFileHandler *fh;
1307  Int_t fddone = -1;
1308  Bool_t read = kFALSE;
1310  while ((fh = (TFileHandler*) it.Next())) {
1311  Int_t fd = fh->GetFd();
1312  if ((fd <= fMaxrfd && fReadready->IsSet(fd) && fddone == -1) ||
1313  (fddone == fd && read)) {
1314  if (fddone == -1) {
1315  fReadready->Clr(fd);
1316  fddone = fd;
1317  read = kTRUE;
1318  fNfd--;
1319  }
1320  if (fh->IsActive())
1321  fh->ReadNotify();
1322  }
1323  if ((fd <= fMaxwfd && fWriteready->IsSet(fd) && fddone == -1) ||
1324  (fddone == fd && !read)) {
1325  if (fddone == -1) {
1326  fWriteready->Clr(fd);
1327  fddone = fd;
1328  read = kFALSE;
1329  fNfd--;
1330  }
1331  if (fh->IsActive())
1332  fh->WriteNotify();
1333  }
1334  }
1335  if (fddone != -1)
1336  return kTRUE;
1337 
1338  return kFALSE;
1339 }
1340 
1341 //---- Directories -------------------------------------------------------------
1342 
1343 ////////////////////////////////////////////////////////////////////////////////
1344 /// Make a Unix file system directory. Returns 0 in case of success and
1345 /// -1 if the directory could not be created.
1346 
1348 {
1349  TSystem *helper = FindHelper(name);
1350  if (helper)
1351  return helper->MakeDirectory(name);
1352 
1353  return UnixMakedir(name);
1354 }
1355 
1356 ////////////////////////////////////////////////////////////////////////////////
1357 /// Open a Unix file system directory. Returns 0 if directory does not exist.
1358 
1360 {
1361  TSystem *helper = FindHelper(name);
1362  if (helper)
1363  return helper->OpenDirectory(name);
1364 
1365  return UnixOpendir(name);
1366 }
1367 
1368 ////////////////////////////////////////////////////////////////////////////////
1369 /// Close a Unix file system directory.
1370 
1372 {
1373  TSystem *helper = FindHelper(0, dirp);
1374  if (helper) {
1375  helper->FreeDirectory(dirp);
1376  return;
1377  }
1378 
1379  if (dirp)
1380  ::closedir((DIR*)dirp);
1381 }
1382 
1383 ////////////////////////////////////////////////////////////////////////////////
1384 /// Get next Unix file system directory entry. Returns 0 if no more entries.
1385 
1386 const char *TUnixSystem::GetDirEntry(void *dirp)
1387 {
1388  TSystem *helper = FindHelper(0, dirp);
1389  if (helper)
1390  return helper->GetDirEntry(dirp);
1391 
1392  if (dirp)
1393  return UnixGetdirentry(dirp);
1394 
1395  return 0;
1396 }
1397 
1398 ////////////////////////////////////////////////////////////////////////////////
1399 /// Change directory. Returns kTRUE in case of success, kFALSE otherwise.
1400 
1402 {
1403  Bool_t ret = (Bool_t) (::chdir(path) == 0);
1404  if (fWdpath != "")
1405  fWdpath = ""; // invalidate path cache
1406  return ret;
1407 }
1408 
1409 ////////////////////////////////////////////////////////////////////////////////
1410 /// Return working directory.
1411 
1413 {
1414  // don't use cache as user can call chdir() directly somewhere else
1415  //if (fWdpath != "")
1416  // return fWdpath.Data();
1417 
1419 
1420  static char cwd[kMAXPATHLEN];
1421  FillWithCwd(cwd);
1422  fWdpath = cwd;
1423 
1424  return fWdpath.Data();
1425 }
1426 
1427 //////////////////////////////////////////////////////////////////////////////
1428 /// Return working directory.
1429 
1431 {
1432  char cwd[kMAXPATHLEN];
1433  FillWithCwd(cwd);
1434  return std::string(cwd);
1435 }
1436 
1437 //////////////////////////////////////////////////////////////////////////////
1438 /// Fill buffer with current working directory.
1439 
1440 void TUnixSystem::FillWithCwd(char *cwd) const
1441 {
1442  if (::getcwd(cwd, kMAXPATHLEN) == 0) {
1443  Error("WorkingDirectory", "getcwd() failed");
1444  }
1445 }
1446 
1447 ////////////////////////////////////////////////////////////////////////////////
1448 /// Return the user's home directory.
1449 
1450 const char *TUnixSystem::HomeDirectory(const char *userName)
1451 {
1452  return UnixHomedirectory(userName);
1453 }
1454 
1455 //////////////////////////////////////////////////////////////////////////////
1456 /// Return the user's home directory.
1457 
1458 std::string TUnixSystem::GetHomeDirectory(const char *userName) const
1459 {
1460  char path[kMAXPATHLEN], mydir[kMAXPATHLEN] = { '\0' };
1461  auto res = UnixHomedirectory(userName, path, mydir);
1462  if (res) return std::string(res);
1463  else return std::string();
1464 }
1465 
1466 ////////////////////////////////////////////////////////////////////////////////
1467 /// Return a user configured or systemwide directory to create
1468 /// temporary files in.
1469 
1470 const char *TUnixSystem::TempDirectory() const
1471 {
1472  const char *dir = gSystem->Getenv("TMPDIR");
1473  if (!dir || gSystem->AccessPathName(dir, kWritePermission))
1474  dir = "/tmp";
1475 
1476  return dir;
1477 }
1478 
1479 ////////////////////////////////////////////////////////////////////////////////
1480 /// Create a secure temporary file by appending a unique
1481 /// 6 letter string to base. The file will be created in
1482 /// a standard (system) directory or in the directory
1483 /// provided in dir. The full filename is returned in base
1484 /// and a filepointer is returned for safely writing to the file
1485 /// (this avoids certain security problems). Returns 0 in case
1486 /// of error.
1487 
1488 FILE *TUnixSystem::TempFileName(TString &base, const char *dir)
1489 {
1490  char *b = ConcatFileName(dir ? dir : TempDirectory(), base);
1491  base = b;
1492  base += "XXXXXX";
1493  delete [] b;
1494 
1495  char *arg = StrDup(base);
1496  int fd = mkstemp(arg);
1497  base = arg;
1498  delete [] arg;
1499 
1500  if (fd == -1) {
1501  SysError("TempFileName", "%s", base.Data());
1502  return 0;
1503  } else {
1504  FILE *fp = fdopen(fd, "w+");
1505  if (fp == 0)
1506  SysError("TempFileName", "converting filedescriptor (%d)", fd);
1507  return fp;
1508  }
1509 }
1510 
1511 ////////////////////////////////////////////////////////////////////////////////
1512 /// Concatenate a directory and a file name.
1513 
1514 const char *TUnixSystem::PrependPathName(const char *dir, TString& name)
1515 {
1516  if (name.IsNull() || name == ".") {
1517  if (dir) {
1518  name = dir;
1519  if (dir[strlen(dir) - 1] != '/')
1520  name += '/';
1521  } else name = "";
1522  return name.Data();
1523  }
1524 
1525  if (!dir || !dir[0]) dir = "/";
1526  else if (dir[strlen(dir) - 1] != '/')
1527  name.Prepend('/');
1528  name.Prepend(dir);
1529 
1530  return name.Data();
1531 }
1532 
1533 //---- Paths & Files -----------------------------------------------------------
1534 
1535 ////////////////////////////////////////////////////////////////////////////////
1536 /// Returns FALSE if one can access a file using the specified access mode.
1537 /// Mode is the same as for the Unix access(2) function.
1538 /// Attention, bizarre convention of return value!!
1539 
1541 {
1542  TSystem *helper = FindHelper(path);
1543  if (helper)
1544  return helper->AccessPathName(path, mode);
1545 
1546  if (::access(StripOffProto(path, "file:"), mode) == 0)
1547  return kFALSE;
1549 
1550  return kTRUE;
1551 }
1552 
1553 ////////////////////////////////////////////////////////////////////////////////
1554 /// Copy a file. If overwrite is true and file already exists the
1555 /// file will be overwritten. Returns 0 when successful, -1 in case
1556 /// of file open failure, -2 in case the file already exists and overwrite
1557 /// was false and -3 in case of error during copy.
1558 
1559 int TUnixSystem::CopyFile(const char *f, const char *t, Bool_t overwrite)
1560 {
1561  if (!AccessPathName(t) && !overwrite)
1562  return -2;
1563 
1564  FILE *from = fopen(f, "r");
1565  if (!from)
1566  return -1;
1567 
1568  FILE *to = fopen(t, "w");
1569  if (!to) {
1570  fclose(from);
1571  return -1;
1572  }
1573 
1574  const int bufsize = 1024;
1575  char buf[bufsize];
1576  int ret = 0;
1577  while (!ret && !feof(from)) {
1578  size_t numread = fread (buf, sizeof(char), bufsize, from);
1579  size_t numwritten = fwrite(buf, sizeof(char), numread, to);
1580  if (numread != numwritten)
1581  ret = -3;
1582  }
1583 
1584  fclose(from);
1585  fclose(to);
1586 
1587  return ret;
1588 }
1589 
1590 ////////////////////////////////////////////////////////////////////////////////
1591 /// Rename a file. Returns 0 when successful, -1 in case of failure.
1592 
1593 int TUnixSystem::Rename(const char *f, const char *t)
1594 {
1595  int ret = ::rename(f, t);
1597  return ret;
1598 }
1599 
1600 ////////////////////////////////////////////////////////////////////////////////
1601 /// Returns TRUE if the url in 'path' points to the local file system.
1602 /// This is used to avoid going through the NIC card for local operations.
1603 
1605 {
1606  TSystem *helper = FindHelper(path);
1607  if (helper)
1608  return helper->IsPathLocal(path);
1609 
1610  return TSystem::IsPathLocal(path);
1611 }
1612 
1613 ////////////////////////////////////////////////////////////////////////////////
1614 /// Get info about a file. Info is returned in the form of a FileStat_t
1615 /// structure (see TSystem.h).
1616 /// The function returns 0 in case of success and 1 if the file could
1617 /// not be stat'ed.
1618 
1619 int TUnixSystem::GetPathInfo(const char *path, FileStat_t &buf)
1620 {
1621  TSystem *helper = FindHelper(path);
1622  if (helper)
1623  return helper->GetPathInfo(path, buf);
1624 
1625  return UnixFilestat(path, buf);
1626 }
1627 
1628 ////////////////////////////////////////////////////////////////////////////////
1629 /// Get info about a file system: id, bsize, bfree, blocks.
1630 /// Id is file system type (machine dependend, see statfs())
1631 /// Bsize is block size of file system
1632 /// Blocks is total number of blocks in file system
1633 /// Bfree is number of free blocks in file system
1634 /// The function returns 0 in case of success and 1 if the file system could
1635 /// not be stat'ed.
1636 
1637 int TUnixSystem::GetFsInfo(const char *path, Long_t *id, Long_t *bsize,
1638  Long_t *blocks, Long_t *bfree)
1639 {
1640  return UnixFSstat(path, id, bsize, blocks, bfree);
1641 }
1642 
1643 ////////////////////////////////////////////////////////////////////////////////
1644 /// Create a link from file1 to file2. Returns 0 when successful,
1645 /// -1 in case of failure.
1646 
1647 int TUnixSystem::Link(const char *from, const char *to)
1648 {
1649  return ::link(from, to);
1650 }
1651 
1652 ////////////////////////////////////////////////////////////////////////////////
1653 /// Create a symlink from file1 to file2. Returns 0 when successful,
1654 /// -1 in case of failure.
1655 
1656 int TUnixSystem::Symlink(const char *from, const char *to)
1657 {
1658 #if defined(R__AIX)
1659  return ::symlink((char*)from, (char*)to);
1660 #else
1661  return ::symlink(from, to);
1662 #endif
1663 }
1664 
1665 ////////////////////////////////////////////////////////////////////////////////
1666 /// Unlink, i.e. remove, a file or directory. Returns 0 when successful,
1667 /// -1 in case of failure.
1668 
1669 int TUnixSystem::Unlink(const char *name)
1670 {
1671  TSystem *helper = FindHelper(name);
1672  if (helper)
1673  return helper->Unlink(name);
1674 
1675 #if defined(R__SEEK64)
1676  struct stat64 finfo;
1677  if (lstat64(name, &finfo) < 0)
1678 #else
1679  struct stat finfo;
1680  if (lstat(name, &finfo) < 0)
1681 #endif
1682  return -1;
1683 
1684  if (S_ISDIR(finfo.st_mode))
1685  return ::rmdir(name);
1686  else
1687  return ::unlink(name);
1688 }
1689 
1690 //---- expand the metacharacters as in the shell -------------------------------
1691 
1692 // expand the metacharacters as in the shell
1693 
1694 const char
1695 #ifdef G__OLDEXPAND
1696  kShellEscape = '\\',
1697  *kShellStuff = "(){}<>\"'",
1698 #endif
1699  *kShellMeta = "~*[]{}?$";
1700 
1701 
1702 #ifndef G__OLDEXPAND
1703 ////////////////////////////////////////////////////////////////////////////////
1704 /// Expand a pathname getting rid of special shell characters like ~.$, etc.
1705 /// For Unix/Win32 compatibility use $(XXX) instead of $XXX when using
1706 /// environment variables in a pathname. If compatibility is not an issue
1707 /// you can use on Unix directly $XXX. Returns kFALSE in case of success
1708 /// or kTRUE in case of error.
1709 
1711 {
1712  const char *p, *patbuf = (const char *)path;
1713 
1714  // skip leading blanks
1715  while (*patbuf == ' ')
1716  patbuf++;
1717 
1718  // any shell meta characters ?
1719  for (p = patbuf; *p; p++)
1720  if (strchr(kShellMeta, *p))
1721  goto expand;
1722 
1723  return kFALSE;
1724 
1725 expand:
1726  // replace $(XXX) by $XXX
1727  path.ReplaceAll("$(","$");
1728  path.ReplaceAll(")","");
1729 
1730  return ExpandFileName(path);
1731 }
1732 #endif
1733 
1734 #ifdef G__OLDEXPAND
1735 ////////////////////////////////////////////////////////////////////////////////
1736 /// Expand a pathname getting rid of special shell characters like ~.$, etc.
1737 /// For Unix/Win32 compatibility use $(XXX) instead of $XXX when using
1738 /// environment variables in a pathname. If compatibility is not an issue
1739 /// you can use on Unix directly $XXX. Returns kFALSE in case of success
1740 /// or kTRUE in case of error.
1741 
1743 {
1744  const char *patbuf = (const char *)patbuf0;
1745  const char *hd, *p;
1746  // char cmd[kMAXPATHLEN],
1747  char stuffedPat[kMAXPATHLEN], name[70];
1748  char *q;
1749  FILE *pf;
1750  int ch;
1751 
1752  // skip leading blanks
1753  while (*patbuf == ' ')
1754  patbuf++;
1755 
1756  // any shell meta characters ?
1757  for (p = patbuf; *p; p++)
1758  if (strchr(kShellMeta, *p))
1759  goto needshell;
1760 
1761  return kFALSE;
1762 
1763 needshell:
1764  // replace $(XXX) by $XXX
1765  patbuf0.ReplaceAll("$(","$");
1766  patbuf0.ReplaceAll(")","");
1767 
1768  // escape shell quote characters
1769  EscChar(patbuf, stuffedPat, sizeof(stuffedPat), (char*)kShellStuff, kShellEscape);
1770 
1771  TString cmd("echo ");
1772 
1773  // emulate csh -> popen executes sh
1774  if (stuffedPat[0] == '~') {
1775  if (stuffedPat[1] != '\0' && stuffedPat[1] != '/') {
1776  // extract user name
1777  for (p = &stuffedPat[1], q = name; *p && *p !='/';)
1778  *q++ = *p++;
1779  *q = '\0';
1780  hd = UnixHomedirectory(name);
1781  if (hd == 0)
1782  cmd += stuffedPat;
1783  else {
1784  cmd += hd;
1785  cmd += p;
1786  }
1787  } else {
1788  hd = UnixHomedirectory(0);
1789  if (hd == 0) {
1791  return kTRUE;
1792  }
1793  cmd += hd;
1794  cmd += &stuffedPat[1];
1795  }
1796  } else
1797  cmd += stuffedPat;
1798 
1799  if ((pf = ::popen(cmd.Data(), "r")) == 0) {
1801  return kTRUE;
1802  }
1803 
1804  // read first argument
1805  patbuf0 = "";
1806  int cnt = 0;
1807 #if defined(R__AIX)
1808 again:
1809 #endif
1810  for (ch = fgetc(pf); ch != EOF && ch != ' ' && ch != '\n'; ch = fgetc(pf)) {
1811  patbuf0.Append(ch);
1812  cnt++;
1813  }
1814 #if defined(R__AIX)
1815  // Work around bug timing problem due to delay in forking a large program
1816  if (cnt == 0 && ch == EOF) goto again;
1817 #endif
1818 
1819  // skip rest of pipe
1820  while (ch != EOF) {
1821  ch = fgetc(pf);
1822  if (ch == ' ' || ch == '\t') {
1823  GetLastErrorString() = "expression ambigous";
1824  ::pclose(pf);
1825  return kTRUE;
1826  }
1827  }
1828 
1829  ::pclose(pf);
1830 
1831  return kFALSE;
1832 }
1833 #endif
1834 
1835 ////////////////////////////////////////////////////////////////////////////////
1836 /// Expand a pathname getting rid of special shell characaters like ~.$, etc.
1837 /// For Unix/Win32 compatibility use $(XXX) instead of $XXX when using
1838 /// environment variables in a pathname. If compatibility is not an issue
1839 /// you can use on Unix directly $XXX. The user must delete returned string.
1840 /// Returns the expanded pathname or 0 in case of error.
1841 /// The user must delete returned string (delete []).
1842 
1843 char *TUnixSystem::ExpandPathName(const char *path)
1844 {
1845  TString patbuf = path;
1846  if (ExpandPathName(patbuf))
1847  return 0;
1848  return StrDup(patbuf.Data());
1849 }
1850 
1851 ////////////////////////////////////////////////////////////////////////////////
1852 /// Set the file permission bits. Returns -1 in case or error, 0 otherwise.
1853 
1854 int TUnixSystem::Chmod(const char *file, UInt_t mode)
1855 {
1856  return ::chmod(file, mode);
1857 }
1858 
1859 ////////////////////////////////////////////////////////////////////////////////
1860 /// Set the process file creation mode mask.
1861 
1863 {
1864  return ::umask(mask);
1865 }
1866 
1867 ////////////////////////////////////////////////////////////////////////////////
1868 /// Set a files modification and access times. If actime = 0 it will be
1869 /// set to the modtime. Returns 0 on success and -1 in case of error.
1870 
1871 int TUnixSystem::Utime(const char *file, Long_t modtime, Long_t actime)
1872 {
1873  if (!actime)
1874  actime = modtime;
1875 
1876  struct utimbuf t;
1877  t.actime = (time_t)actime;
1878  t.modtime = (time_t)modtime;
1879  return ::utime(file, &t);
1880 }
1881 
1882 ////////////////////////////////////////////////////////////////////////////////
1883 /// Find location of file "wfil" in a search path.
1884 /// The search path is specified as a : separated list of directories.
1885 /// Return value is pointing to wfile for compatibility with
1886 /// Which(const char*,const char*,EAccessMode) version.
1887 
1888 const char *TUnixSystem::FindFile(const char *search, TString& wfil, EAccessMode mode)
1889 {
1890  TString show;
1891  if (gEnv->GetValue("Root.ShowPath", 0))
1892  show.Form("Which: %s =", wfil.Data());
1893 
1894  gSystem->ExpandPathName(wfil);
1895 
1896  if (wfil[0] == '/') {
1897 #if defined(R__SEEK64)
1898  struct stat64 finfo;
1899  if (access(wfil.Data(), mode) == 0 &&
1900  stat64(wfil.Data(), &finfo) == 0 && S_ISREG(finfo.st_mode)) {
1901 #else
1902  struct stat finfo;
1903  if (access(wfil.Data(), mode) == 0 &&
1904  stat(wfil.Data(), &finfo) == 0 && S_ISREG(finfo.st_mode)) {
1905 #endif
1906  if (show != "")
1907  Printf("%s %s", show.Data(), wfil.Data());
1908  return wfil.Data();
1909  }
1910  if (show != "")
1911  Printf("%s <not found>", show.Data());
1912  wfil = "";
1913  return 0;
1914  }
1915 
1916  if (search == 0)
1917  search = ".";
1918 
1919  TString apwd(gSystem->WorkingDirectory());
1920  apwd += "/";
1921  for (const char* ptr = search; *ptr;) {
1922  TString name;
1923  if (*ptr != '/' && *ptr !='$' && *ptr != '~')
1924  name = apwd;
1925  const char* posEndOfPart = strchr(ptr, ':');
1926  if (posEndOfPart) {
1927  name.Append(ptr, posEndOfPart - ptr);
1928  ptr = posEndOfPart + 1; // skip ':'
1929  } else {
1930  name.Append(ptr);
1931  ptr += strlen(ptr);
1932  }
1933 
1934  if (!name.EndsWith("/"))
1935  name += '/';
1936  name += wfil;
1937 
1938  gSystem->ExpandPathName(name);
1939 #if defined(R__SEEK64)
1940  struct stat64 finfo;
1941  if (access(name.Data(), mode) == 0 &&
1942  stat64(name.Data(), &finfo) == 0 && S_ISREG(finfo.st_mode)) {
1943 #else
1944  struct stat finfo;
1945  if (access(name.Data(), mode) == 0 &&
1946  stat(name.Data(), &finfo) == 0 && S_ISREG(finfo.st_mode)) {
1947 #endif
1948  if (show != "")
1949  Printf("%s %s", show.Data(), name.Data());
1950  wfil = name;
1951  return wfil.Data();
1952  }
1953  }
1954 
1955  if (show != "")
1956  Printf("%s <not found>", show.Data());
1957  wfil = "";
1958  return 0;
1959 }
1960 
1961 //---- Users & Groups ----------------------------------------------------------
1962 
1963 ////////////////////////////////////////////////////////////////////////////////
1964 /// Returns the user's id. If user = 0, returns current user's id.
1965 
1966 Int_t TUnixSystem::GetUid(const char *user)
1967 {
1968  if (!user || !user[0])
1969  return getuid();
1970  else {
1971  struct passwd *apwd = getpwnam(user);
1972  if (apwd)
1973  return apwd->pw_uid;
1974  }
1975  return 0;
1976 }
1977 
1978 ////////////////////////////////////////////////////////////////////////////////
1979 /// Returns the effective user id. The effective id corresponds to the
1980 /// set id bit on the file being executed.
1981 
1983 {
1984  return geteuid();
1985 }
1986 
1987 ////////////////////////////////////////////////////////////////////////////////
1988 /// Returns the group's id. If group = 0, returns current user's group.
1989 
1991 {
1992  if (!group || !group[0])
1993  return getgid();
1994  else {
1995  struct group *grp = getgrnam(group);
1996  if (grp)
1997  return grp->gr_gid;
1998  }
1999  return 0;
2000 }
2001 
2002 ////////////////////////////////////////////////////////////////////////////////
2003 /// Returns the effective group id. The effective group id corresponds
2004 /// to the set id bit on the file being executed.
2005 
2007 {
2008  return getegid();
2009 }
2010 
2011 ////////////////////////////////////////////////////////////////////////////////
2012 /// Returns all user info in the UserGroup_t structure. The returned
2013 /// structure must be deleted by the user. In case of error 0 is returned.
2014 
2016 {
2017  typedef std::map<Int_t /*uid*/, UserGroup_t> UserInfoCache_t;
2018  static UserInfoCache_t gUserInfo;
2019 
2020  UserInfoCache_t::const_iterator iUserInfo = gUserInfo.find(uid);
2021  if (iUserInfo != gUserInfo.end())
2022  return new UserGroup_t(iUserInfo->second);
2023 
2024  struct passwd *apwd = getpwuid(uid);
2025  if (apwd) {
2026  UserGroup_t *ug = new UserGroup_t;
2027  ug->fUid = apwd->pw_uid;
2028  ug->fGid = apwd->pw_gid;
2029  ug->fUser = apwd->pw_name;
2030  ug->fPasswd = apwd->pw_passwd;
2031  ug->fRealName = apwd->pw_gecos;
2032  ug->fShell = apwd->pw_shell;
2033  UserGroup_t *gr = GetGroupInfo(apwd->pw_gid);
2034  if (gr) ug->fGroup = gr->fGroup;
2035  delete gr;
2036 
2037  gUserInfo[uid] = *ug;
2038  return ug;
2039  }
2040  return 0;
2041 }
2042 
2043 ////////////////////////////////////////////////////////////////////////////////
2044 /// Returns all user info in the UserGroup_t structure. If user = 0, returns
2045 /// current user's id info. The returned structure must be deleted by the
2046 /// user. In case of error 0 is returned.
2047 
2049 {
2050  return GetUserInfo(GetUid(user));
2051 }
2052 
2053 ////////////////////////////////////////////////////////////////////////////////
2054 /// Returns all group info in the UserGroup_t structure. The only active
2055 /// fields in the UserGroup_t structure for this call are:
2056 /// fGid and fGroup
2057 /// The returned structure must be deleted by the user. In case of
2058 /// error 0 is returned.
2059 
2061 {
2062  struct group *grp = getgrgid(gid);
2063  if (grp) {
2064  UserGroup_t *gr = new UserGroup_t;
2065  gr->fUid = 0;
2066  gr->fGid = grp->gr_gid;
2067  gr->fGroup = grp->gr_name;
2068  return gr;
2069  }
2070  return 0;
2071 }
2072 
2073 ////////////////////////////////////////////////////////////////////////////////
2074 /// Returns all group info in the UserGroup_t structure. The only active
2075 /// fields in the UserGroup_t structure for this call are:
2076 /// fGid and fGroup
2077 /// If group = 0, returns current user's group. The returned structure
2078 /// must be deleted by the user. In case of error 0 is returned.
2079 
2081 {
2082  return GetGroupInfo(GetGid(group));
2083 }
2084 
2085 //---- environment manipulation ------------------------------------------------
2086 
2087 ////////////////////////////////////////////////////////////////////////////////
2088 /// Set environment variable.
2089 
2090 void TUnixSystem::Setenv(const char *name, const char *value)
2091 {
2092  ::setenv(name, value, 1);
2093 }
2094 
2095 ////////////////////////////////////////////////////////////////////////////////
2096 /// Get environment variable.
2097 
2098 const char *TUnixSystem::Getenv(const char *name)
2099 {
2100  return ::getenv(name);
2101 }
2102 
2103 ////////////////////////////////////////////////////////////////////////////////
2104 /// Unset environment variable.
2105 
2106 void TUnixSystem::Unsetenv(const char *name)
2107 {
2108  ::unsetenv(name);
2109 }
2110 
2111 //---- Processes ---------------------------------------------------------------
2112 
2113 ////////////////////////////////////////////////////////////////////////////////
2114 /// Execute a command.
2115 
2116 int TUnixSystem::Exec(const char *shellcmd)
2117 {
2118  return ::system(shellcmd);
2119 }
2120 
2121 ////////////////////////////////////////////////////////////////////////////////
2122 /// Open a pipe.
2123 
2124 FILE *TUnixSystem::OpenPipe(const char *command, const char *mode)
2125 {
2126  return ::popen(command, mode);
2127 }
2128 
2129 ////////////////////////////////////////////////////////////////////////////////
2130 /// Close the pipe.
2131 
2132 int TUnixSystem::ClosePipe(FILE *pipe)
2133 {
2134  return ::pclose(pipe);
2135 }
2136 
2137 ////////////////////////////////////////////////////////////////////////////////
2138 /// Get process id.
2139 
2141 {
2142  return ::getpid();
2143 }
2144 
2145 ////////////////////////////////////////////////////////////////////////////////
2146 /// Exit the application.
2147 
2148 void TUnixSystem::Exit(int code, Bool_t mode)
2149 {
2150  // Insures that the files and sockets are closed before any library is unloaded
2151  // and before emptying CINT.
2152  if (gROOT) {
2153  gROOT->EndOfProcessCleanups();
2154  } else if (gInterpreter) {
2155  gInterpreter->ResetGlobals();
2156  }
2157 
2158  if (mode)
2159  ::exit(code);
2160  else
2161  ::_exit(code);
2162 }
2163 
2164 ////////////////////////////////////////////////////////////////////////////////
2165 /// Abort the application.
2166 
2168 {
2169  ::abort();
2170 }
2171 
2172 
2173 #ifdef R__MACOSX
2174 /// Use CoreSymbolication to retrieve the stacktrace.
2175 #include <mach/mach.h>
2176 extern "C" {
2177  // Adapted from https://github.com/mountainstorm/CoreSymbolication
2178  // Under the hood the framework basically just calls through to a set of C++ libraries
2179  typedef struct {
2180  void* csCppData;
2181  void* csCppObj;
2182  } CSTypeRef;
2183  typedef CSTypeRef CSSymbolicatorRef;
2184  typedef CSTypeRef CSSourceInfoRef;
2185  typedef CSTypeRef CSSymbolOwnerRef;
2186  typedef CSTypeRef CSSymbolRef;
2187 
2188  CSSymbolicatorRef CSSymbolicatorCreateWithPid(pid_t pid);
2189  CSSymbolRef CSSymbolicatorGetSymbolWithAddressAtTime(CSSymbolicatorRef cs, vm_address_t addr, uint64_t time);
2190  CSSourceInfoRef CSSymbolicatorGetSourceInfoWithAddressAtTime(CSSymbolicatorRef cs, vm_address_t addr, uint64_t time);
2191  const char* CSSymbolGetName(CSSymbolRef sym);
2192  CSSymbolOwnerRef CSSymbolGetSymbolOwner(CSSymbolRef sym);
2193  const char* CSSymbolOwnerGetPath(CSSymbolOwnerRef symbol);
2194  const char* CSSourceInfoGetPath(CSSourceInfoRef info);
2195  int CSSourceInfoGetLineNumber(CSSourceInfoRef info);
2196 }
2197 
2198 bool CSTypeRefIdValid(CSTypeRef ref) {
2199  return ref.csCppData || ref.csCppObj;
2200 }
2201 
2202 void macosx_backtrace() {
2203 void* addrlist[kMAX_BACKTRACE_DEPTH];
2204  // retrieve current stack addresses
2205  int numstacks = backtrace( addrlist, sizeof( addrlist ) / sizeof( void* ));
2206 
2207  CSSymbolicatorRef symbolicator = CSSymbolicatorCreateWithPid(getpid());
2208 
2209  // skip TUnixSystem::Backtrace(), macosx_backtrace()
2210  static const int skipFrames = 2;
2211  for (int i = skipFrames; i < numstacks; ++i) {
2212  // No debug info, try to get at least the symbol name.
2213  CSSymbolRef sym = CSSymbolicatorGetSymbolWithAddressAtTime(symbolicator,
2214  (vm_address_t)addrlist[i],
2215  0x80000000u);
2216  CSSymbolOwnerRef symOwner = CSSymbolGetSymbolOwner(sym);
2217 
2218  if (const char* libPath = CSSymbolOwnerGetPath(symOwner)) {
2219  printf("[%s]", libPath);
2220  } else {
2221  printf("[<unknown binary>]");
2222  }
2223 
2224  if (const char* symname = CSSymbolGetName(sym)) {
2225  printf(" %s", symname);
2226  }
2227 
2228  CSSourceInfoRef sourceInfo
2229  = CSSymbolicatorGetSourceInfoWithAddressAtTime(symbolicator,
2230  (vm_address_t)addrlist[i],
2231  0x80000000u /*"now"*/);
2232  if (const char* sourcePath = CSSourceInfoGetPath(sourceInfo)) {
2233  printf(" %s:%d", sourcePath, (int)CSSourceInfoGetLineNumber(sourceInfo));
2234  } else {
2235  printf(" (no debug info)");
2236  }
2237  printf("\n");
2238  }
2239 }
2240 #endif // R__MACOSX
2241 
2242 ////////////////////////////////////////////////////////////////////////////////
2243 /// Print a stack trace.
2244 
2246 {
2247  if (!gEnv->GetValue("Root.Stacktrace", 1))
2248  return;
2249 
2250 #ifndef R__MACOSX
2251  TString gdbscript = gEnv->GetValue("Root.StacktraceScript", "");
2252  gdbscript = gdbscript.Strip();
2253  if (gdbscript != "") {
2254  if (AccessPathName(gdbscript, kReadPermission)) {
2255  fprintf(stderr, "Root.StacktraceScript %s does not exist\n", gdbscript.Data());
2256  gdbscript = "";
2257  }
2258  }
2259  if (gdbscript == "") {
2260  gdbscript = "gdb-backtrace.sh";
2261  gSystem->PrependPathName(TROOT::GetEtcDir(), gdbscript);
2262  if (AccessPathName(gdbscript, kReadPermission)) {
2263  fprintf(stderr, "Error in <TUnixSystem::StackTrace> script %s is missing\n", gdbscript.Data());
2264  return;
2265  }
2266  }
2267  gdbscript += " ";
2268 
2269  TString gdbmess = gEnv->GetValue("Root.StacktraceMessage", "");
2270  gdbmess = gdbmess.Strip();
2271 
2272  std::cout.flush();
2273  fflush(stdout);
2274 
2275  std::cerr.flush();
2276  fflush(stderr);
2277 
2278  int fd = STDERR_FILENO;
2279 
2280  const char *message = " Generating stack trace...\n";
2281 
2282  if (fd && message) { } // remove unused warning (remove later)
2283 
2284  if (gApplication && !strcmp(gApplication->GetName(), "TRint"))
2285  Getlinem(kCleanUp, 0);
2286 
2287 #if defined(USE_GDB_STACK_TRACE)
2288  char *gdb = Which(Getenv("PATH"), "gdb", kExecutePermission);
2289  if (!gdb) {
2290  fprintf(stderr, "gdb not found, need it for stack trace\n");
2291  return;
2292  }
2293 
2294  // write custom message file
2295  TString gdbmessf = "gdb-message";
2296  if (gdbmess != "") {
2297  FILE *f = TempFileName(gdbmessf);
2298  fprintf(f, "%s\n", gdbmess.Data());
2299  fclose(f);
2300  }
2301 
2302  // use gdb to get stack trace
2303  gdbscript += GetExePath();
2304  gdbscript += " ";
2305  gdbscript += GetPid();
2306  if (gdbmess != "") {
2307  gdbscript += " ";
2308  gdbscript += gdbmessf;
2309  }
2310  gdbscript += " 1>&2";
2311  Exec(gdbscript);
2312  delete [] gdb;
2313  return;
2314 
2315 #elif defined(R__AIX)
2316  TString script = "procstack ";
2317  script += GetPid();
2318  Exec(script);
2319  return;
2320 #elif defined(R__SOLARIS)
2321  char *cppfilt = Which(Getenv("PATH"), "c++filt", kExecutePermission);
2322  TString script = "pstack ";
2323  script += GetPid();
2324  if (cppfilt) {
2325  script += " | ";
2326  script += cppfilt;
2327  delete [] cppfilt;
2328  }
2329  Exec(script);
2330  return;
2331 #elif defined(HAVE_BACKTRACE_SYMBOLS_FD) && defined(HAVE_DLADDR) // linux + MacOS X >= 10.5
2332  // we could have used backtrace_symbols_fd, except its output
2333  // format is pretty bad, so recode that here :-(
2334 
2335  // take care of demangling
2336  Bool_t demangle = kTRUE;
2337 
2338  // check for c++filt
2339  const char *cppfilt = "c++filt";
2340  const char *cppfiltarg = "";
2341 #ifdef R__B64
2342  const char *format1 = " 0x%016lx in %.200s %s 0x%lx from %.200s\n";
2343 #ifdef R__MACOSX
2344  const char *format2 = " 0x%016lx in %.200s\n";
2345 #else
2346  const char *format2 = " 0x%016lx in %.200s at %.200s from %.200s\n";
2347 #endif
2348  const char *format3 = " 0x%016lx in %.200s from %.200s\n";
2349  const char *format4 = " 0x%016lx in <unknown function>\n";
2350 #else
2351  const char *format1 = " 0x%08lx in %.200s %s 0x%lx from %.200s\n";
2352 #ifdef R__MACOSX
2353  const char *format2 = " 0x%08lx in %.200s\n";
2354 #else
2355  const char *format2 = " 0x%08lx in %.200s at %.200s from %.200s\n";
2356 #endif
2357  const char *format3 = " 0x%08lx in %.200s from %.200s\n";
2358  const char *format4 = " 0x%08lx in <unknown function>\n";
2359 #endif
2360 
2361  char *filter = Which(Getenv("PATH"), cppfilt, kExecutePermission);
2362  if (!filter)
2363  demangle = kFALSE;
2364 
2365 #if (__GNUC__ >= 3)
2366  // try finding supported format option for g++ v3
2367  if (filter) {
2368  FILE *p = OpenPipe(TString::Format("%s --help 2>&1", filter), "r");
2369  TString help;
2370  while (help.Gets(p)) {
2371  if (help.Index("gnu-v3") != kNPOS) {
2372  cppfiltarg = "--format=gnu-v3";
2373  break;
2374  } else if (help.Index("gnu-new-abi") != kNPOS) {
2375  cppfiltarg = "--format=gnu-new-abi";
2376  break;
2377  }
2378  }
2379  ClosePipe(p);
2380  }
2381 #endif
2382  // gdb-backtrace.sh uses gdb to produce a backtrace. See if it is available.
2383  // If it is, use it. If not proceed as before.
2384 #if (defined(R__LINUX) && !defined(R__WINGCC))
2385  // Declare the process that will be generating the stacktrace
2386  // For more see: http://askubuntu.com/questions/41629/after-upgrade-gdb-wont-attach-to-process
2387 #ifdef PR_SET_PTRACER
2388  prctl(PR_SET_PTRACER, getpid(), 0, 0, 0);
2389 #endif
2390 #endif
2391  char *gdb = Which(Getenv("PATH"), "gdb", kExecutePermission);
2392  if (gdb) {
2393  // write custom message file
2394  TString gdbmessf = "gdb-message";
2395  if (gdbmess != "") {
2396  FILE *f = TempFileName(gdbmessf);
2397  fprintf(f, "%s\n", gdbmess.Data());
2398  fclose(f);
2399  }
2400 
2401  // use gdb to get stack trace
2402 #ifdef R__MACOSX
2403  gdbscript += GetExePath();
2404  gdbscript += " ";
2405 #endif
2406  gdbscript += GetPid();
2407  if (gdbmess != "") {
2408  gdbscript += " ";
2409  gdbscript += gdbmessf;
2410  }
2411  gdbscript += " 1>&2";
2412  Exec(gdbscript);
2413  delete [] gdb;
2414  } else {
2415  // addr2line uses debug info to convert addresses into file names
2416  // and line numbers
2417 #ifdef R__MACOSX
2418  char *addr2line = Which(Getenv("PATH"), "atos", kExecutePermission);
2419 #else
2420  char *addr2line = Which(Getenv("PATH"), "addr2line", kExecutePermission);
2421 #endif
2422  if (addr2line) {
2423  // might take some time so tell what we are doing...
2424  if (write(fd, message, strlen(message)) < 0)
2425  Warning("StackTrace", "problems writing line numbers (errno: %d)", TSystem::GetErrno());
2426  }
2427 
2428  // open tmp file for demangled stack trace
2429  TString tmpf1 = "gdb-backtrace";
2430  std::ofstream file1;
2431  if (demangle) {
2432  FILE *f = TempFileName(tmpf1);
2433  if (f) fclose(f);
2434  file1.open(tmpf1);
2435  if (!file1) {
2436  Error("StackTrace", "could not open file %s", tmpf1.Data());
2437  Unlink(tmpf1);
2438  demangle = kFALSE;
2439  }
2440  }
2441 
2442 #ifdef R__MACOSX
2443  if (addr2line)
2444  demangle = kFALSE; // atos always demangles
2445 #endif
2446 
2447  char buffer[4096];
2448  void *trace[kMAX_BACKTRACE_DEPTH];
2449  int depth = backtrace(trace, kMAX_BACKTRACE_DEPTH);
2450  for (int n = 5; n < depth; n++) {
2451  ULong_t addr = (ULong_t) trace[n];
2452  Dl_info info;
2453 
2454  if (dladdr(trace[n], &info) && info.dli_fname && info.dli_fname[0]) {
2455  const char *libname = info.dli_fname;
2456  const char *symname = (info.dli_sname && info.dli_sname[0]) ?
2457  info.dli_sname : "<unknown>";
2458  ULong_t libaddr = (ULong_t) info.dli_fbase;
2459  ULong_t symaddr = (ULong_t) info.dli_saddr;
2460  Bool_t gte = (addr >= symaddr);
2461  ULong_t diff = (gte) ? addr - symaddr : symaddr - addr;
2462  if (addr2line && symaddr) {
2463  Bool_t nodebug = kTRUE;
2464 #ifdef R__MACOSX
2465  if (libaddr) { } // use libaddr
2466 #if defined(MAC_OS_X_VERSION_10_10)
2467  snprintf(buffer, sizeof(buffer), "%s -p %d 0x%016lx", addr2line, GetPid(), addr);
2468 #elif defined(MAC_OS_X_VERSION_10_9)
2469  // suppress deprecation warning with opti
2470  snprintf(buffer, sizeof(buffer), "%s -d -p %d 0x%016lx", addr2line, GetPid(), addr);
2471 #else
2472  snprintf(buffer, sizeof(buffer), "%s -p %d 0x%016lx", addr2line, GetPid(), addr);
2473 #endif
2474 #else
2475  ULong_t offset = (addr >= libaddr) ? addr - libaddr :
2476  libaddr - addr;
2477  TString name = TString(libname);
2478  Bool_t noPath = kFALSE;
2479  Bool_t noShare = kTRUE;
2480  if (name[0] != '/') noPath = kTRUE;
2481  if (name.Contains(".so") || name.Contains(".sl")) noShare = kFALSE;
2482  if (noShare) offset = addr;
2483  if (noPath) name = "`which " + name + "`";
2484  snprintf(buffer, sizeof(buffer), "%s -e %s 0x%016lx", addr2line, name.Data(), offset);
2485 #endif
2486  if (FILE *pf = ::popen(buffer, "r")) {
2487  char buf[2048];
2488  if (fgets(buf, 2048, pf)) {
2489  buf[strlen(buf)-1] = 0; // remove trailing \n
2490  if (strncmp(buf, "??", 2)) {
2491 #ifdef R__MACOSX
2492  snprintf(buffer, sizeof(buffer), format2, addr, buf);
2493 #else
2494  snprintf(buffer, sizeof(buffer), format2, addr, symname, buf, libname);
2495 #endif
2496  nodebug = kFALSE;
2497  }
2498  }
2499  ::pclose(pf);
2500  }
2501  if (nodebug)
2502  snprintf(buffer, sizeof(buffer), format1, addr, symname,
2503  gte ? "+" : "-", diff, libname);
2504  } else {
2505  if (symaddr)
2506  snprintf(buffer, sizeof(buffer), format1, addr, symname,
2507  gte ? "+" : "-", diff, libname);
2508  else
2509  snprintf(buffer, sizeof(buffer), format3, addr, symname, libname);
2510  }
2511  } else {
2512  snprintf(buffer, sizeof(buffer), format4, addr);
2513  }
2514 
2515  if (demangle)
2516  file1 << buffer;
2517  else
2518  if (write(fd, buffer, ::strlen(buffer)) < 0)
2519  Warning("StackTrace", "problems writing buffer (errno: %d)", TSystem::GetErrno());
2520  }
2521 
2522  if (demangle) {
2523  TString tmpf2 = "gdb-backtrace";
2524  FILE *f = TempFileName(tmpf2);
2525  if (f) fclose(f);
2526  file1.close();
2527  snprintf(buffer, sizeof(buffer), "%s %s < %s > %s", filter, cppfiltarg, tmpf1.Data(), tmpf2.Data());
2528  Exec(buffer);
2529  std::ifstream file2(tmpf2);
2530  TString line;
2531  while (file2) {
2532  line = "";
2533  line.ReadString(file2);
2534  if (write(fd, line.Data(), line.Length()) < 0)
2535  Warning("StackTrace", "problems writing line (errno: %d)", TSystem::GetErrno());
2536  }
2537  file2.close();
2538  Unlink(tmpf1);
2539  Unlink(tmpf2);
2540  }
2541 
2542  delete [] addr2line;
2543  }
2544  delete [] filter;
2545 #elif defined(HAVE_EXCPT_H) && defined(HAVE_PDSC_H) && \
2546  defined(HAVE_RLD_INTERFACE_H) // tru64
2547  // Tru64 stack walk. Uses the exception handling library and the
2548  // run-time linker's core functions (loader(5)). FIXME: Tru64
2549  // should have _RLD_DLADDR like IRIX below. Verify and update.
2550 
2551  char buffer [128];
2552  sigcontext context;
2553  int rc = 0;
2554 
2555  exc_capture_context (&context);
2556  while (!rc && context.sc_pc) {
2557  // FIXME: Elf32?
2558  pdsc_crd *func, *base, *crd
2559  = exc_remote_lookup_function_entry(0, 0, context.sc_pc, 0, &func, &base);
2560  Elf32_Addr addr = PDSC_CRD_BEGIN_ADDRESS(base, func);
2561  // const char *name = _rld_address_to_name(addr);
2562  const char *name = "<unknown function>";
2563  sprintf(buffer, " 0x%012lx %.200s + 0x%lx\n",
2564  context.sc_pc, name, context.sc_pc - addr);
2565  write(fd, buffer, ::strlen(buffer));
2566  rc = exc_virtual_unwind(0, &context);
2567  }
2568 #endif
2569 #else //R__MACOSX
2570  macosx_backtrace();
2571 #endif //R__MACOSX
2572 }
2573 
2574 //---- System Logging ----------------------------------------------------------
2575 
2576 ////////////////////////////////////////////////////////////////////////////////
2577 /// Open connection to system log daemon. For the use of the options and
2578 /// facility see the Unix openlog man page.
2579 
2580 void TUnixSystem::Openlog(const char *name, Int_t options, ELogFacility facility)
2581 {
2582  int fac = 0;
2583 
2584  switch (facility) {
2585  case kLogLocal0:
2586  fac = LOG_LOCAL0;
2587  break;
2588  case kLogLocal1:
2589  fac = LOG_LOCAL1;
2590  break;
2591  case kLogLocal2:
2592  fac = LOG_LOCAL2;
2593  break;
2594  case kLogLocal3:
2595  fac = LOG_LOCAL3;
2596  break;
2597  case kLogLocal4:
2598  fac = LOG_LOCAL4;
2599  break;
2600  case kLogLocal5:
2601  fac = LOG_LOCAL5;
2602  break;
2603  case kLogLocal6:
2604  fac = LOG_LOCAL6;
2605  break;
2606  case kLogLocal7:
2607  fac = LOG_LOCAL7;
2608  break;
2609  }
2610 
2611  ::openlog(name, options, fac);
2612 }
2613 
2614 ////////////////////////////////////////////////////////////////////////////////
2615 /// Send mess to syslog daemon. Level is the logging level and mess the
2616 /// message that will be written on the log.
2617 
2618 void TUnixSystem::Syslog(ELogLevel level, const char *mess)
2619 {
2620  // ELogLevel matches exactly the Unix values.
2621  ::syslog(level, "%s", mess);
2622 }
2623 
2624 ////////////////////////////////////////////////////////////////////////////////
2625 /// Close connection to system log daemon.
2626 
2628 {
2629  ::closelog();
2630 }
2631 
2632 //---- Standard output redirection ---------------------------------------------
2633 
2634 ////////////////////////////////////////////////////////////////////////////////
2635 /// Redirect standard output (stdout, stderr) to the specified file.
2636 /// If the file argument is 0 the output is set again to stderr, stdout.
2637 /// The second argument specifies whether the output should be added to the
2638 /// file ("a", default) or the file be truncated before ("w").
2639 /// This function saves internally the current state into a static structure.
2640 /// The call can be made reentrant by specifying the opaque structure pointed
2641 /// by 'h', which is filled with the relevant information. The handle 'h'
2642 /// obtained on the first call must then be used in any subsequent call,
2643 /// included ShowOutput, to display the redirected output.
2644 /// Returns 0 on success, -1 in case of error.
2645 
2646 Int_t TUnixSystem::RedirectOutput(const char *file, const char *mode,
2648 {
2649  // Instance to be used if the caller does not passes 'h'
2650  static RedirectHandle_t loch;
2651 
2652  Int_t rc = 0;
2653 
2654  // Which handle to use ?
2655  RedirectHandle_t *xh = (h) ? h : &loch;
2656 
2657  if (file) {
2658  // Save the paths
2659  Bool_t outdone = kFALSE;
2660  if (xh->fStdOutTty.IsNull()) {
2661  const char *tty = ttyname(STDOUT_FILENO);
2662  if (tty) {
2663  xh->fStdOutTty = tty;
2664  } else {
2665  if ((xh->fStdOutDup = dup(STDOUT_FILENO)) < 0) {
2666  SysError("RedirectOutput", "could not 'dup' stdout (errno: %d)", TSystem::GetErrno());
2667  return -1;
2668  }
2669  outdone = kTRUE;
2670  }
2671  }
2672  if (xh->fStdErrTty.IsNull()) {
2673  const char *tty = ttyname(STDERR_FILENO);
2674  if (tty) {
2675  xh->fStdErrTty = tty;
2676  } else {
2677  if ((xh->fStdErrDup = dup(STDERR_FILENO)) < 0) {
2678  SysError("RedirectOutput", "could not 'dup' stderr (errno: %d)", TSystem::GetErrno());
2679  if (outdone && dup2(xh->fStdOutDup, STDOUT_FILENO) < 0) {
2680  Warning("RedirectOutput", "could not restore stdout (back to original redirected"
2681  " file) (errno: %d)", TSystem::GetErrno());
2682  }
2683  return -1;
2684  }
2685  }
2686  }
2687 
2688  // Make sure mode makes sense; default "a"
2689  const char *m = (mode[0] == 'a' || mode[0] == 'w') ? mode : "a";
2690 
2691  // Current file size
2692  xh->fReadOffSet = 0;
2693  if (m[0] == 'a') {
2694  // If the file exists, save the current size
2695  FileStat_t st;
2696  if (!gSystem->GetPathInfo(file, st))
2697  xh->fReadOffSet = (st.fSize > 0) ? st.fSize : xh->fReadOffSet;
2698  }
2699  xh->fFile = file;
2700 
2701  // Redirect stdout & stderr
2702  if (freopen(file, m, stdout) == 0) {
2703  SysError("RedirectOutput", "could not freopen stdout (errno: %d)", TSystem::GetErrno());
2704  return -1;
2705  }
2706  if (freopen(file, m, stderr) == 0) {
2707  SysError("RedirectOutput", "could not freopen stderr (errno: %d)", TSystem::GetErrno());
2708  if (freopen(xh->fStdOutTty.Data(), "a", stdout) == 0)
2709  SysError("RedirectOutput", "could not restore stdout (errno: %d)", TSystem::GetErrno());
2710  return -1;
2711  }
2712  } else {
2713  // Restore stdout & stderr
2714  fflush(stdout);
2715  if (!(xh->fStdOutTty.IsNull())) {
2716  if (freopen(xh->fStdOutTty.Data(), "a", stdout) == 0) {
2717  SysError("RedirectOutput", "could not restore stdout (errno: %d)", TSystem::GetErrno());
2718  rc = -1;
2719  }
2720  xh->fStdOutTty = "";
2721  } else {
2722  if (close(STDOUT_FILENO) != 0) {
2723  SysError("RedirectOutput",
2724  "problems closing STDOUT_FILENO (%d) before 'dup2' (errno: %d)",
2725  STDOUT_FILENO, TSystem::GetErrno());
2726  rc = -1;
2727  }
2728  if (dup2(xh->fStdOutDup, STDOUT_FILENO) < 0) {
2729  SysError("RedirectOutput", "could not restore stdout (back to original redirected"
2730  " file) (errno: %d)", TSystem::GetErrno());
2731  rc = -1;
2732  }
2733  if (close(xh->fStdOutDup) != 0) {
2734  SysError("RedirectOutput",
2735  "problems closing temporary 'out' descriptor %d (errno: %d)",
2736  TSystem::GetErrno(), xh->fStdOutDup);
2737  rc = -1;
2738  }
2739  }
2740  fflush(stderr);
2741  if (!(xh->fStdErrTty.IsNull())) {
2742  if (freopen(xh->fStdErrTty.Data(), "a", stderr) == 0) {
2743  SysError("RedirectOutput", "could not restore stderr (errno: %d)", TSystem::GetErrno());
2744  rc = -1;
2745  }
2746  xh->fStdErrTty = "";
2747  } else {
2748  if (close(STDERR_FILENO) != 0) {
2749  SysError("RedirectOutput",
2750  "problems closing STDERR_FILENO (%d) before 'dup2' (errno: %d)",
2751  STDERR_FILENO, TSystem::GetErrno());
2752  rc = -1;
2753  }
2754  if (dup2(xh->fStdErrDup, STDERR_FILENO) < 0) {
2755  SysError("RedirectOutput", "could not restore stderr (back to original redirected"
2756  " file) (errno: %d)", TSystem::GetErrno());
2757  rc = -1;
2758  }
2759  if (close(xh->fStdErrDup) != 0) {
2760  SysError("RedirectOutput",
2761  "problems closing temporary 'err' descriptor %d (errno: %d)",
2762  TSystem::GetErrno(), xh->fStdErrDup);
2763  rc = -1;
2764  }
2765  }
2766  // Reset the static instance, if using that
2767  if (xh == &loch)
2768  xh->Reset();
2769  }
2770  return rc;
2771 }
2772 
2773 //---- dynamic loading and linking ---------------------------------------------
2774 
2775 ////////////////////////////////////////////////////////////////////////////////
2776 ///dynamic linking of module
2777 
2778 Func_t TUnixSystem::DynFindSymbol(const char * /*module*/, const char *entry)
2779 {
2780  return TSystem::DynFindSymbol("*", entry);
2781 }
2782 
2783 ////////////////////////////////////////////////////////////////////////////////
2784 /// Load a shared library. Returns 0 on successful loading, 1 in
2785 /// case lib was already loaded and -1 in case lib does not exist
2786 /// or in case of error.
2787 
2788 int TUnixSystem::Load(const char *module, const char *entry, Bool_t system)
2789 {
2790  return TSystem::Load(module, entry, system);
2791 }
2792 
2793 ////////////////////////////////////////////////////////////////////////////////
2794 /// Unload a shared library.
2795 
2796 void TUnixSystem::Unload(const char *module)
2797 {
2798  if (module) { TSystem::Unload(module); }
2799 }
2800 
2801 ////////////////////////////////////////////////////////////////////////////////
2802 /// List symbols in a shared library.
2803 
2804 void TUnixSystem::ListSymbols(const char * /*module*/, const char * /*regexp*/)
2805 {
2806  Error("ListSymbols", "not yet implemented");
2807 }
2808 
2809 ////////////////////////////////////////////////////////////////////////////////
2810 /// List all loaded shared libraries.
2811 
2812 void TUnixSystem::ListLibraries(const char *regexp)
2813 {
2814  TSystem::ListLibraries(regexp);
2815 }
2816 
2817 ////////////////////////////////////////////////////////////////////////////////
2818 /// Get list of shared libraries loaded at the start of the executable.
2819 /// Returns 0 in case list cannot be obtained or in case of error.
2820 
2822 {
2823  static TString linkedLibs;
2824  static Bool_t once = kFALSE;
2825 
2827 
2828  if (!linkedLibs.IsNull())
2829  return linkedLibs;
2830 
2831  if (once)
2832  return 0;
2833 
2834 #if !defined(R__MACOSX)
2835  const char *exe = GetExePath();
2836  if (!exe || !*exe)
2837  return 0;
2838 #endif
2839 
2840 #if defined(R__MACOSX)
2841  DylibAdded(0, 0);
2842  linkedLibs = gLinkedDylibs;
2843 #if 0
2844  FILE *p = OpenPipe(TString::Format("otool -L %s", exe), "r");
2845  TString otool;
2846  while (otool.Gets(p)) {
2847  TString delim(" \t");
2848  TObjArray *tok = otool.Tokenize(delim);
2849  TString dylib = ((TObjString*)tok->At(0))->String();
2850  if (dylib.EndsWith(".dylib") && !dylib.Contains("/libSystem.B.dylib")) {
2851  if (!linkedLibs.IsNull())
2852  linkedLibs += " ";
2853  linkedLibs += dylib;
2854  }
2855  delete tok;
2856  }
2857  if (p) {
2858  ClosePipe(p);
2859  }
2860 #endif
2861 #elif defined(R__LINUX) || defined(R__SOLARIS) || defined(R__AIX)
2862 #if defined(R__WINGCC )
2863  const char *cLDD="cygcheck";
2864  const char *cSOEXT=".dll";
2865  size_t lenexe = strlen(exe);
2866  if (strcmp(exe + lenexe - 4, ".exe")
2867  && strcmp(exe + lenexe - 4, ".dll")) {
2868  // it's not a dll and exe doesn't end on ".exe";
2869  // need to add it for cygcheck to find it:
2870  char* longerexe = new char[lenexe + 5];
2871  strlcpy(longerexe, exe,lenexe+5);
2872  strlcat(longerexe, ".exe",lenexe+5);
2873  delete [] exe;
2874  exe = longerexe;
2875  }
2876  TRegexp sovers = "\\.so\\.[0-9]+";
2877 #else
2878  const char *cLDD="ldd";
2879 #if defined(R__AIX)
2880  const char *cSOEXT=".a";
2881  TRegexp sovers = "\\.a\\.[0-9]+";
2882 #else
2883  const char *cSOEXT=".so";
2884  TRegexp sovers = "\\.so\\.[0-9]+";
2885 #endif
2886 #endif
2887  FILE *p = OpenPipe(TString::Format("%s '%s'", cLDD, exe), "r");
2888  if (p) {
2889  TString ldd;
2890  while (ldd.Gets(p)) {
2891  TString delim(" \t");
2892  TObjArray *tok = ldd.Tokenize(delim);
2893 
2894  // expected format:
2895  // libCore.so => /home/rdm/root/lib/libCore.so (0x40017000)
2896  TObjString *solibName = (TObjString*)tok->At(2);
2897  if (!solibName) {
2898  // case where there is only one name of the list:
2899  // /usr/platform/SUNW,UltraAX-i2/lib/libc_psr.so.1
2900  solibName = (TObjString*)tok->At(0);
2901  }
2902  if (solibName) {
2903  TString solib = solibName->String();
2904  Ssiz_t idx = solib.Index(sovers);
2905  if (solib.EndsWith(cSOEXT) || idx != kNPOS) {
2906  if (idx != kNPOS)
2907  solib.Remove(idx+3);
2908  if (!AccessPathName(solib, kReadPermission)) {
2909  if (!linkedLibs.IsNull())
2910  linkedLibs += " ";
2911  linkedLibs += solib;
2912  }
2913  }
2914  }
2915  delete tok;
2916  }
2917  ClosePipe(p);
2918  }
2919 #endif
2920 
2921  once = kTRUE;
2922 
2923  if (linkedLibs.IsNull())
2924  return 0;
2925 
2926  return linkedLibs;
2927 }
2928 
2929 //---- Time & Date -------------------------------------------------------------
2930 
2931 ////////////////////////////////////////////////////////////////////////////////
2932 /// Get current time in milliseconds since 0:00 Jan 1 1995.
2933 
2935 {
2936  return UnixNow();
2937 }
2938 
2939 ////////////////////////////////////////////////////////////////////////////////
2940 /// Handle and dispatch timers. If mode = kTRUE dispatch synchronous
2941 /// timers else a-synchronous timers.
2942 
2944 {
2945  if (!fTimers) return kFALSE;
2946 
2947  fInsideNotify = kTRUE;
2948 
2950  TTimer *t;
2951  Bool_t timedout = kFALSE;
2952 
2953  while ((t = (TTimer *) it.Next())) {
2954  // NB: the timer resolution is added in TTimer::CheckTimer()
2955  Long64_t now = UnixNow();
2956  if (mode && t->IsSync()) {
2957  if (t->CheckTimer(now))
2958  timedout = kTRUE;
2959  } else if (!mode && t->IsAsync()) {
2960  if (t->CheckTimer(now)) {
2962  timedout = kTRUE;
2963  }
2964  }
2965  }
2967  return timedout;
2968 }
2969 
2970 ////////////////////////////////////////////////////////////////////////////////
2971 /// Add timer to list of system timers.
2972 
2974 {
2975  TSystem::AddTimer(ti);
2976  ResetTimer(ti);
2977 }
2978 
2979 ////////////////////////////////////////////////////////////////////////////////
2980 /// Remove timer from list of system timers.
2981 
2983 {
2984  if (!ti) return 0;
2985 
2987 
2988  TTimer *t = TSystem::RemoveTimer(ti);
2989  if (ti->IsAsync())
2991  return t;
2992 }
2993 
2994 ////////////////////////////////////////////////////////////////////////////////
2995 /// Reset a-sync timer.
2996 
2998 {
2999  if (!fInsideNotify && ti && ti->IsAsync())
3001 }
3002 
3003 //---- RPC ---------------------------------------------------------------------
3004 
3005 ////////////////////////////////////////////////////////////////////////////////
3006 /// Get Internet Protocol (IP) address of host. Returns an TInetAddress
3007 /// object. To see if the hostname lookup was successfull call
3008 /// TInetAddress::IsValid().
3009 
3011 {
3012  TInetAddress ia;
3013  struct addrinfo hints;
3014  struct addrinfo *result, *rp;
3015  memset(&hints, 0, sizeof(struct addrinfo));
3016  hints.ai_family = AF_INET; // only IPv4
3017  hints.ai_socktype = 0; // any socket type
3018  hints.ai_protocol = 0; // any protocol
3019  hints.ai_flags = AI_CANONNAME; // get canonical name
3020 #ifdef R__MACOSX
3021  // Anything ending on ".local" causes a 5 second delay in getaddrinfo().
3022  // See e.g. https://apple.stackexchange.com/questions/175320/why-is-my-hostname-resolution-taking-so-long
3023  // Only reasonable solution: remove the "domain" part if it's ".local".
3024  size_t lenHostname = strlen(hostname);
3025  std::string hostnameWithoutLocal{hostname};
3026  if (lenHostname > 6 && !strcmp(hostname + lenHostname - 6, ".local")) {
3027  hostnameWithoutLocal.erase(lenHostname - 6);
3028  hostname = hostnameWithoutLocal.c_str();
3029  }
3030 #endif
3031 
3032  // obsolete gethostbyname() replaced by getaddrinfo()
3033  int rc = getaddrinfo(hostname, nullptr, &hints, &result);
3034  if (rc != 0) {
3035  if (rc == EAI_NONAME) {
3036  if (gDebug > 0) Error("GetHostByName", "unknown host '%s'", hostname);
3037  ia.fHostname = "UnNamedHost";
3038  } else {
3039  Error("GetHostByName", "getaddrinfo failed for '%s': %s", hostname, gai_strerror(rc));
3040  ia.fHostname = "UnknownHost";
3041  }
3042  return ia;
3043  }
3044 
3045  std::string hostcanon(result->ai_canonname ? result->ai_canonname : hostname);
3046  ia.fHostname = hostcanon.data();
3047  ia.fFamily = result->ai_family;
3048  ia.fAddresses[0] = ntohl(((struct sockaddr_in *)(result->ai_addr))->sin_addr.s_addr);
3049  // with getaddrinfo() no way to get list of aliases for a hostname
3050  if (hostcanon.compare(hostname) != 0) ia.AddAlias(hostname);
3051 
3052  // check on numeric hostname
3053  char tmp[sizeof(struct in_addr)];
3054  if (inet_pton(AF_INET, hostcanon.data(), tmp) == 1) {
3055  char hbuf[NI_MAXHOST];
3056  if (getnameinfo(result->ai_addr, result->ai_addrlen, hbuf, sizeof(hbuf), nullptr, 0, 0) == 0)
3057  ia.fHostname = hbuf;
3058  }
3059 
3060  // check other addresses (if exist)
3061  rp = result->ai_next;
3062  for (; rp != nullptr; rp = rp->ai_next) {
3063  UInt_t arp = ntohl(((struct sockaddr_in *)(rp->ai_addr))->sin_addr.s_addr);
3064  if ( !(std::find(ia.fAddresses.begin(), ia.fAddresses.end(), arp) != ia.fAddresses.end()) )
3065  ia.AddAddress(arp);
3066  }
3067 
3068  freeaddrinfo(result);
3069  return ia;
3070 }
3071 
3072 ////////////////////////////////////////////////////////////////////////////////
3073 /// Get Internet Protocol (IP) address of host and port #.
3074 
3076 {
3077  struct sockaddr addr;
3078 #if defined(USE_SIZE_T)
3079  size_t len = sizeof(addr);
3080 #elif defined(USE_SOCKLEN_T)
3081  socklen_t len = sizeof(addr);
3082 #else
3083  int len = sizeof(addr);
3084 #endif
3085 
3086  TInetAddress ia;
3087  if (getsockname(sock, &addr, &len) == -1) {
3088  SysError("GetSockName", "getsockname failed");
3089  return ia;
3090  }
3091 
3092  if (addr.sa_family != AF_INET) return ia; // only IPv4
3093  ia.fFamily = addr.sa_family;
3094  struct sockaddr_in *addrin = (struct sockaddr_in *)&addr;
3095  ia.fPort = ntohs(addrin->sin_port);
3096  ia.fAddresses[0] = ntohl(addrin->sin_addr.s_addr);
3097 
3098  char hbuf[NI_MAXHOST];
3099  if (getnameinfo(&addr, sizeof(struct sockaddr), hbuf, sizeof(hbuf), nullptr, 0, 0) != 0) {
3100  Error("GetSockName", "getnameinfo failed");
3101  ia.fHostname = "????";
3102  } else
3103  ia.fHostname = hbuf;
3104 
3105  return ia;
3106 }
3107 
3108 ////////////////////////////////////////////////////////////////////////////////
3109 /// Get Internet Protocol (IP) address of remote host and port #.
3110 
3112 {
3113  struct sockaddr addr;
3114 #if defined(USE_SIZE_T)
3115  size_t len = sizeof(addr);
3116 #elif defined(USE_SOCKLEN_T)
3117  socklen_t len = sizeof(addr);
3118 #else
3119  int len = sizeof(addr);
3120 #endif
3121 
3122  TInetAddress ia;
3123  if (getpeername(sock, &addr, &len) == -1) {
3124  SysError("GetPeerName", "getpeername failed");
3125  return ia;
3126  }
3127 
3128  if (addr.sa_family != AF_INET) return ia; // only IPv4
3129  ia.fFamily = addr.sa_family;
3130  struct sockaddr_in *addrin = (struct sockaddr_in *)&addr;
3131  ia.fPort = ntohs(addrin->sin_port);
3132  ia.fAddresses[0] = ntohl(addrin->sin_addr.s_addr);
3133 
3134  char hbuf[NI_MAXHOST];
3135  if (getnameinfo(&addr, sizeof(struct sockaddr), hbuf, sizeof(hbuf), nullptr, 0, 0) != 0) {
3136  Error("GetPeerName", "getnameinfo failed");
3137  ia.fHostname = "????";
3138  } else
3139  ia.fHostname = hbuf;
3140 
3141  return ia;
3142 }
3143 
3144 ////////////////////////////////////////////////////////////////////////////////
3145 /// Get port # of internet service.
3146 
3147 int TUnixSystem::GetServiceByName(const char *servicename)
3148 {
3149  struct servent *sp;
3150 
3151  if ((sp = getservbyname(servicename, kProtocolName)) == 0) {
3152  Error("GetServiceByName", "no service \"%s\" with protocol \"%s\"\n",
3153  servicename, kProtocolName);
3154  return -1;
3155  }
3156  return ntohs(sp->s_port);
3157 }
3158 
3159 ////////////////////////////////////////////////////////////////////////////////
3160 /// Get name of internet service.
3161 
3163 {
3164  struct servent *sp;
3165 
3166  if ((sp = getservbyport(htons(port), kProtocolName)) == 0) {
3167  //::Error("GetServiceByPort", "no service \"%d\" with protocol \"%s\"",
3168  // port, kProtocolName);
3169  return Form("%d", port);
3170  }
3171  return sp->s_name;
3172 }
3173 
3174 ////////////////////////////////////////////////////////////////////////////////
3175 /// Connect to service servicename on server servername.
3176 
3177 int TUnixSystem::ConnectService(const char *servername, int port,
3178  int tcpwindowsize, const char *protocol)
3179 {
3180  if (!strcmp(servername, "unix")) {
3181  return UnixUnixConnect(port);
3182  } else if (!gSystem->AccessPathName(servername) || servername[0] == '/') {
3183  return UnixUnixConnect(servername);
3184  }
3185 
3186  if (!strcmp(protocol, "udp")){
3187  return UnixUdpConnect(servername, port);
3188  }
3189 
3190  return UnixTcpConnect(servername, port, tcpwindowsize);
3191 }
3192 
3193 ////////////////////////////////////////////////////////////////////////////////
3194 /// Open a connection to a service on a server. Returns -1 in case
3195 /// connection cannot be opened.
3196 /// Use tcpwindowsize to specify the size of the receive buffer, it has
3197 /// to be specified here to make sure the window scale option is set (for
3198 /// tcpwindowsize > 65KB and for platforms supporting window scaling).
3199 /// Is called via the TSocket constructor.
3200 
3201 int TUnixSystem::OpenConnection(const char *server, int port, int tcpwindowsize, const char *protocol)
3202 {
3203  return ConnectService(server, port, tcpwindowsize, protocol);
3204 }
3205 
3206 ////////////////////////////////////////////////////////////////////////////////
3207 /// Announce TCP/IP service.
3208 /// Open a socket, bind to it and start listening for TCP/IP connections
3209 /// on the port. If reuse is true reuse the address, backlog specifies
3210 /// how many sockets can be waiting to be accepted.
3211 /// Use tcpwindowsize to specify the size of the receive buffer, it has
3212 /// to be specified here to make sure the window scale option is set (for
3213 /// tcpwindowsize > 65KB and for platforms supporting window scaling).
3214 /// Returns socket fd or -1 if socket() failed, -2 if bind() failed
3215 /// or -3 if listen() failed.
3216 
3217 int TUnixSystem::AnnounceTcpService(int port, Bool_t reuse, int backlog,
3218  int tcpwindowsize)
3219 {
3220  return UnixTcpService(port, reuse, backlog, tcpwindowsize);
3221 }
3222 
3223 ////////////////////////////////////////////////////////////////////////////////
3224 /// Announce UDP service.
3225 
3226 int TUnixSystem::AnnounceUdpService(int port, int backlog)
3227 {
3228  return UnixUdpService(port, backlog);
3229 }
3230 
3231 ////////////////////////////////////////////////////////////////////////////////
3232 /// Announce unix domain service on path "kServerPath/<port>"
3233 
3234 int TUnixSystem::AnnounceUnixService(int port, int backlog)
3235 {
3236  return UnixUnixService(port, backlog);
3237 }
3238 
3239 ////////////////////////////////////////////////////////////////////////////////
3240 /// Announce unix domain service on path 'sockpath'
3241 
3242 int TUnixSystem::AnnounceUnixService(const char *sockpath, int backlog)
3243 {
3244  return UnixUnixService(sockpath, backlog);
3245 }
3246 
3247 ////////////////////////////////////////////////////////////////////////////////
3248 /// Accept a connection. In case of an error return -1. In case
3249 /// non-blocking I/O is enabled and no connections are available
3250 /// return -2.
3251 
3253 {
3254  int soc = -1;
3255 
3256  while ((soc = ::accept(sock, 0, 0)) == -1 && GetErrno() == EINTR)
3257  ResetErrno();
3258 
3259  if (soc == -1) {
3260  if (GetErrno() == EWOULDBLOCK)
3261  return -2;
3262  else {
3263  SysError("AcceptConnection", "accept");
3264  return -1;
3265  }
3266  }
3267 
3268  return soc;
3269 }
3270 
3271 ////////////////////////////////////////////////////////////////////////////////
3272 /// Close socket.
3273 
3275 {
3276  if (sock < 0) return;
3277 
3278 #if !defined(R__AIX) || defined(_AIX41) || defined(_AIX43)
3279  if (force)
3280  ::shutdown(sock, 2); // will also close connection of parent
3281 #endif
3282 
3283  while (::close(sock) == -1 && GetErrno() == EINTR)
3284  ResetErrno();
3285 }
3286 
3287 ////////////////////////////////////////////////////////////////////////////////
3288 /// Receive a buffer headed by a length indicator. Length is the size of
3289 /// the buffer. Returns the number of bytes received in buf or -1 in
3290 /// case of error.
3291 
3292 int TUnixSystem::RecvBuf(int sock, void *buf, int length)
3293 {
3294  Int_t header;
3295 
3296  if (UnixRecv(sock, &header, sizeof(header), 0) > 0) {
3297  int count = ntohl(header);
3298 
3299  if (count > length) {
3300  Error("RecvBuf", "record header exceeds buffer size");
3301  return -1;
3302  } else if (count > 0) {
3303  if (UnixRecv(sock, buf, count, 0) < 0) {
3304  Error("RecvBuf", "cannot receive buffer");
3305  return -1;
3306  }
3307  }
3308  return count;
3309  }
3310  return -1;
3311 }
3312 
3313 ////////////////////////////////////////////////////////////////////////////////
3314 /// Send a buffer headed by a length indicator. Returns length of sent buffer
3315 /// or -1 in case of error.
3316 
3317 int TUnixSystem::SendBuf(int sock, const void *buf, int length)
3318 {
3319  Int_t header = htonl(length);
3320 
3321  if (UnixSend(sock, &header, sizeof(header), 0) < 0) {
3322  Error("SendBuf", "cannot send header");
3323  return -1;
3324  }
3325  if (length > 0) {
3326  if (UnixSend(sock, buf, length, 0) < 0) {
3327  Error("SendBuf", "cannot send buffer");
3328  return -1;
3329  }
3330  }
3331  return length;
3332 }
3333 
3334 ////////////////////////////////////////////////////////////////////////////////
3335 /// Receive exactly length bytes into buffer. Use opt to receive out-of-band
3336 /// data or to have a peek at what is in the buffer (see TSocket). Buffer
3337 /// must be able to store at least length bytes. Returns the number of
3338 /// bytes received (can be 0 if other side of connection was closed) or -1
3339 /// in case of error, -2 in case of MSG_OOB and errno == EWOULDBLOCK, -3
3340 /// in case of MSG_OOB and errno == EINVAL and -4 in case of kNoBlock and
3341 /// errno == EWOULDBLOCK. Returns -5 if pipe broken or reset by peer
3342 /// (EPIPE || ECONNRESET).
3343 
3344 int TUnixSystem::RecvRaw(int sock, void *buf, int length, int opt)
3345 {
3346  int flag;
3347 
3348  switch (opt) {
3349  case kDefault:
3350  flag = 0;
3351  break;
3352  case kOob:
3353  flag = MSG_OOB;
3354  break;
3355  case kPeek:
3356  flag = MSG_PEEK;
3357  break;
3358  case kDontBlock:
3359  flag = -1;
3360  break;
3361  default:
3362  flag = 0;
3363  break;
3364  }
3365 
3366  int n;
3367  if ((n = UnixRecv(sock, buf, length, flag)) <= 0) {
3368  if (n == -1 && GetErrno() != EINTR)
3369  Error("RecvRaw", "cannot receive buffer");
3370  return n;
3371  }
3372  return n;
3373 }
3374 
3375 ////////////////////////////////////////////////////////////////////////////////
3376 /// Send exactly length bytes from buffer. Use opt to send out-of-band
3377 /// data (see TSocket). Returns the number of bytes sent or -1 in case of
3378 /// error. Returns -4 in case of kNoBlock and errno == EWOULDBLOCK.
3379 /// Returns -5 if pipe broken or reset by peer (EPIPE || ECONNRESET).
3380 
3381 int TUnixSystem::SendRaw(int sock, const void *buf, int length, int opt)
3382 {
3383  int flag;
3384 
3385  switch (opt) {
3386  case kDefault:
3387  flag = 0;
3388  break;
3389  case kOob:
3390  flag = MSG_OOB;
3391  break;
3392  case kDontBlock:
3393  flag = -1;
3394  break;
3395  case kPeek: // receive only option (see RecvRaw)
3396  default:
3397  flag = 0;
3398  break;
3399  }
3400 
3401  int n;
3402  if ((n = UnixSend(sock, buf, length, flag)) <= 0) {
3403  if (n == -1 && GetErrno() != EINTR)
3404  Error("SendRaw", "cannot send buffer");
3405  return n;
3406  }
3407  return n;
3408 }
3409 
3410 ////////////////////////////////////////////////////////////////////////////////
3411 /// Set socket option.
3412 
3413 int TUnixSystem::SetSockOpt(int sock, int opt, int val)
3414 {
3415  if (sock < 0) return -1;
3416 
3417  switch (opt) {
3418  case kSendBuffer:
3419  if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)&val, sizeof(val)) == -1) {
3420  SysError("SetSockOpt", "setsockopt(SO_SNDBUF)");
3421  return -1;
3422  }
3423  break;
3424  case kRecvBuffer:
3425  if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)&val, sizeof(val)) == -1) {
3426  SysError("SetSockOpt", "setsockopt(SO_RCVBUF)");
3427  return -1;
3428  }
3429  break;
3430  case kOobInline:
3431  if (setsockopt(sock, SOL_SOCKET, SO_OOBINLINE, (char*)&val, sizeof(val)) == -1) {
3432  SysError("SetSockOpt", "setsockopt(SO_OOBINLINE)");
3433  return -1;
3434  }
3435  break;
3436  case kKeepAlive:
3437  if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&val, sizeof(val)) == -1) {
3438  SysError("SetSockOpt", "setsockopt(SO_KEEPALIVE)");
3439  return -1;
3440  }
3441  break;
3442  case kReuseAddr:
3443  if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&val, sizeof(val)) == -1) {
3444  SysError("SetSockOpt", "setsockopt(SO_REUSEADDR)");
3445  return -1;
3446  }
3447  break;
3448  case kNoDelay:
3449  if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&val, sizeof(val)) == -1) {
3450  SysError("SetSockOpt", "setsockopt(TCP_NODELAY)");
3451  return -1;
3452  }
3453  break;
3454  case kNoBlock:
3455  if (ioctl(sock, FIONBIO, (char*)&val) == -1) {
3456  SysError("SetSockOpt", "ioctl(FIONBIO)");
3457  return -1;
3458  }
3459  break;
3460  case kProcessGroup:
3461 #ifndef R__WINGCC
3462  if (ioctl(sock, SIOCSPGRP, (char*)&val) == -1) {
3463  SysError("SetSockOpt", "ioctl(SIOCSPGRP)");
3464  return -1;
3465  }
3466 #else
3467  Error("SetSockOpt", "ioctl(SIOCGPGRP) not supported on cygwin/gcc");
3468  return -1;
3469 #endif
3470  break;
3471  case kAtMark: // read-only option (see GetSockOpt)
3472  case kBytesToRead: // read-only option
3473  default:
3474  Error("SetSockOpt", "illegal option (%d)", opt);
3475  return -1;
3476  }
3477  return 0;
3478 }
3479 
3480 ////////////////////////////////////////////////////////////////////////////////
3481 /// Get socket option.
3482 
3483 int TUnixSystem::GetSockOpt(int sock, int opt, int *val)
3484 {
3485  if (sock < 0) return -1;
3486 
3487 #if defined(USE_SOCKLEN_T) || defined(_AIX43)
3488  socklen_t optlen = sizeof(*val);
3489 #elif defined(USE_SIZE_T)
3490  size_t optlen = sizeof(*val);
3491 #else
3492  int optlen = sizeof(*val);
3493 #endif
3494 
3495  switch (opt) {
3496  case kSendBuffer:
3497  if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)val, &optlen) == -1) {
3498  SysError("GetSockOpt", "getsockopt(SO_SNDBUF)");
3499  return -1;
3500  }
3501  break;
3502  case kRecvBuffer:
3503  if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)val, &optlen) == -1) {
3504  SysError("GetSockOpt", "getsockopt(SO_RCVBUF)");
3505  return -1;
3506  }
3507  break;
3508  case kOobInline:
3509  if (getsockopt(sock, SOL_SOCKET, SO_OOBINLINE, (char*)val, &optlen) == -1) {
3510  SysError("GetSockOpt", "getsockopt(SO_OOBINLINE)");
3511  return -1;
3512  }
3513  break;
3514  case kKeepAlive:
3515  if (getsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)val, &optlen) == -1) {
3516  SysError("GetSockOpt", "getsockopt(SO_KEEPALIVE)");
3517  return -1;
3518  }
3519  break;
3520  case kReuseAddr:
3521  if (getsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)val, &optlen) == -1) {
3522  SysError("GetSockOpt", "getsockopt(SO_REUSEADDR)");
3523  return -1;
3524  }
3525  break;
3526  case kNoDelay:
3527  if (getsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)val, &optlen) == -1) {
3528  SysError("GetSockOpt", "getsockopt(TCP_NODELAY)");
3529  return -1;
3530  }
3531  break;
3532  case kNoBlock:
3533  int flg;
3534  if ((flg = fcntl(sock, F_GETFL, 0)) == -1) {
3535  SysError("GetSockOpt", "fcntl(F_GETFL)");
3536  return -1;
3537  }
3538  *val = flg & O_NDELAY;
3539  break;
3540  case kProcessGroup:
3541 #if !defined(R__LYNXOS) && !defined(R__WINGCC)
3542  if (ioctl(sock, SIOCGPGRP, (char*)val) == -1) {
3543  SysError("GetSockOpt", "ioctl(SIOCGPGRP)");
3544  return -1;
3545  }
3546 #else
3547  Error("GetSockOpt", "ioctl(SIOCGPGRP) not supported on LynxOS and cygwin/gcc");
3548  return -1;
3549 #endif
3550  break;
3551  case kAtMark:
3552 #if !defined(R__LYNXOS)
3553  if (ioctl(sock, SIOCATMARK, (char*)val) == -1) {
3554  SysError("GetSockOpt", "ioctl(SIOCATMARK)");
3555  return -1;
3556  }
3557 #else
3558  Error("GetSockOpt", "ioctl(SIOCATMARK) not supported on LynxOS");
3559  return -1;
3560 #endif
3561  break;
3562  case kBytesToRead:
3563 #if !defined(R__LYNXOS)
3564  if (ioctl(sock, FIONREAD, (char*)val) == -1) {
3565  SysError("GetSockOpt", "ioctl(FIONREAD)");
3566  return -1;
3567  }
3568 #else
3569  Error("GetSockOpt", "ioctl(FIONREAD) not supported on LynxOS");
3570  return -1;
3571 #endif
3572  break;
3573  default:
3574  Error("GetSockOpt", "illegal option (%d)", opt);
3575  *val = 0;
3576  return -1;
3577  }
3578  return 0;
3579 }
3580 
3581 //////////////////////////////////////////////////////////////////////////
3582 // //
3583 // Static Protected Unix Interface functions. //
3584 // //
3585 //////////////////////////////////////////////////////////////////////////
3586 
3587 //---- signals -----------------------------------------------------------------
3588 
3589 static struct Signalmap_t {
3590  int fCode;
3591  SigHandler_t fHandler;
3592  struct sigaction *fOldHandler;
3593  const char *fSigName;
3594 } gSignalMap[kMAXSIGNALS] = { // the order of the signals should be identical
3595  { SIGBUS, 0, 0, "bus error" }, // to the one in TSysEvtHandler.h
3596  { SIGSEGV, 0, 0, "segmentation violation" },
3597  { SIGSYS, 0, 0, "bad argument to system call" },
3598  { SIGPIPE, 0, 0, "write on a pipe with no one to read it" },
3599  { SIGILL, 0, 0, "illegal instruction" },
3600  { SIGQUIT, 0, 0, "quit" },
3601  { SIGINT, 0, 0, "interrupt" },
3602  { SIGWINCH, 0, 0, "window size change" },
3603  { SIGALRM, 0, 0, "alarm clock" },
3604  { SIGCHLD, 0, 0, "death of a child" },
3605  { SIGURG, 0, 0, "urgent data arrived on an I/O channel" },
3606  { SIGFPE, 0, 0, "floating point exception" },
3607  { SIGTERM, 0, 0, "termination signal" },
3608  { SIGUSR1, 0, 0, "user-defined signal 1" },
3609  { SIGUSR2, 0, 0, "user-defined signal 2" }
3610 };
3611 
3612 
3613 ////////////////////////////////////////////////////////////////////////////////
3614 /// Call the signal handler associated with the signal.
3615 
3616 static void sighandler(int sig)
3617 {
3618  for (int i= 0; i < kMAXSIGNALS; i++) {
3619  if (gSignalMap[i].fCode == sig) {
3620  (*gSignalMap[i].fHandler)((ESignals)i);
3621  return;
3622  }
3623  }
3624 }
3625 
3626 ////////////////////////////////////////////////////////////////////////////////
3627 /// Handle and dispatch signals.
3628 
3630 {
3631  switch (sig) {
3632  case kSigAlarm:
3634  break;
3635  case kSigChild:
3636  CheckChilds();
3637  break;
3638  case kSigBus:
3641  case kSigFloatingException:
3642  Break("TUnixSystem::DispatchSignals", "%s", UnixSigname(sig));
3643  StackTrace();
3644  if (gApplication)
3645  //sig is ESignal, should it be mapped to the correct signal number?
3647  else
3648  //map to the real signal code + set the
3649  //high order bit to indicate a signal (?)
3650  Exit(gSignalMap[sig].fCode + 0x80);
3651  break;
3652  case kSigSystem:
3653  case kSigPipe:
3654  Break("TUnixSystem::DispatchSignals", "%s", UnixSigname(sig));
3655  break;
3656  case kSigWindowChanged:
3657  Gl_windowchanged();
3658  break;
3659  default:
3660  fSignals->Set(sig);
3661  fSigcnt++;
3662  break;
3663  }
3664 
3665  // check a-synchronous signals
3666  if (fSigcnt > 0 && fSignalHandler->GetSize() > 0)
3668 }
3669 
3670 ////////////////////////////////////////////////////////////////////////////////
3671 /// Set a signal handler for a signal.
3672 
3674 {
3675  if (gEnv && !gEnv->GetValue("Root.ErrorHandlers", 1))
3676  return;
3677 
3678  if (gSignalMap[sig].fHandler != handler) {
3679  struct sigaction sigact;
3680 
3681  gSignalMap[sig].fHandler = handler;
3682  gSignalMap[sig].fOldHandler = new struct sigaction();
3683 
3684 #if defined(R__SUN)
3685  sigact.sa_handler = (void (*)())sighandler;
3686 #elif defined(R__SOLARIS)
3687  sigact.sa_handler = sighandler;
3688 #elif defined(R__LYNXOS)
3689 # if (__GNUG__>=3)
3690  sigact.sa_handler = sighandler;
3691 # else
3692  sigact.sa_handler = (void (*)(...))sighandler;
3693 # endif
3694 #else
3695  sigact.sa_handler = sighandler;
3696 #endif
3697  sigemptyset(&sigact.sa_mask);
3698  sigact.sa_flags = 0;
3699 #if defined(SA_RESTART)
3700  sigact.sa_flags |= SA_RESTART;
3701 #endif
3702  if (sigaction(gSignalMap[sig].fCode, &sigact,
3703  gSignalMap[sig].fOldHandler) < 0)
3704  ::SysError("TUnixSystem::UnixSignal", "sigaction");
3705  }
3706 }
3707 
3708 ////////////////////////////////////////////////////////////////////////////////
3709 /// If ignore is true ignore the specified signal, else restore previous
3710 /// behaviour.
3711 
3713 {
3714  TTHREAD_TLS(Bool_t) ignoreSig[kMAXSIGNALS] = { kFALSE };
3715  TTHREAD_TLS_ARRAY(struct sigaction,kMAXSIGNALS,oldsigact);
3716 
3717  if (ignore != ignoreSig[sig]) {
3718  ignoreSig[sig] = ignore;
3719  if (ignore) {
3720  struct sigaction sigact;
3721 #if defined(R__SUN)
3722  sigact.sa_handler = (void (*)())SIG_IGN;
3723 #elif defined(R__SOLARIS)
3724  sigact.sa_handler = (void (*)(int))SIG_IGN;
3725 #else
3726  sigact.sa_handler = SIG_IGN;
3727 #endif
3728  sigemptyset(&sigact.sa_mask);
3729  sigact.sa_flags = 0;
3730  if (sigaction(gSignalMap[sig].fCode, &sigact, &oldsigact[sig]) < 0)
3731  ::SysError("TUnixSystem::UnixIgnoreSignal", "sigaction");
3732  } else {
3733  if (sigaction(gSignalMap[sig].fCode, &oldsigact[sig], 0) < 0)
3734  ::SysError("TUnixSystem::UnixIgnoreSignal", "sigaction");
3735  }
3736  }
3737 }
3738 
3739 ////////////////////////////////////////////////////////////////////////////////
3740 /// When the argument is true the SIGALRM signal handler is set so that
3741 /// interrupted syscalls will not be restarted by the kernel. This is
3742 /// typically used in case one wants to put a timeout on an I/O operation.
3743 /// By default interrupted syscalls will always be restarted (for all
3744 /// signals). This can be controlled for each a-synchronous TTimer via
3745 /// the method TTimer::SetInterruptSyscalls().
3746 
3748 {
3749  if (gSignalMap[kSigAlarm].fHandler) {
3750  struct sigaction sigact;
3751 #if defined(R__SUN)
3752  sigact.sa_handler = (void (*)())sighandler;
3753 #elif defined(R__SOLARIS)
3754  sigact.sa_handler = sighandler;
3755 #elif defined(R__LYNXOS)
3756 # if (__GNUG__>=3)
3757  sigact.sa_handler = sighandler;
3758 # else
3759  sigact.sa_handler = (void (*)(...))sighandler;
3760 # endif
3761 #else
3762  sigact.sa_handler = sighandler;
3763 #endif
3764  sigemptyset(&sigact.sa_mask);
3765  sigact.sa_flags = 0;
3766  if (set) {
3767 #if defined(SA_INTERRUPT) // SunOS
3768  sigact.sa_flags |= SA_INTERRUPT;
3769 #endif
3770  } else {
3771 #if defined(SA_RESTART)
3772  sigact.sa_flags |= SA_RESTART;
3773 #endif
3774  }
3775  if (sigaction(gSignalMap[kSigAlarm].fCode, &sigact, 0) < 0)
3776  ::SysError("TUnixSystem::UnixSigAlarmInterruptsSyscalls", "sigaction");
3777  }
3778 }
3779 
3780 ////////////////////////////////////////////////////////////////////////////////
3781 /// Return the signal name associated with a signal.
3782 
3784 {
3785  return gSignalMap[sig].fSigName;
3786 }
3787 
3788 ////////////////////////////////////////////////////////////////////////////////
3789 /// Restore old signal handler for specified signal.
3790 
3792 {
3793  if (gSignalMap[sig].fOldHandler) {
3794  // restore old signal handler
3795  if (sigaction(gSignalMap[sig].fCode, gSignalMap[sig].fOldHandler, 0) < 0)
3796  ::SysError("TUnixSystem::UnixSignal", "sigaction");
3797  delete gSignalMap[sig].fOldHandler;
3798  gSignalMap[sig].fOldHandler = 0;
3799  gSignalMap[sig].fHandler = 0;
3800  }
3801 }
3802 
3803 ////////////////////////////////////////////////////////////////////////////////
3804 /// Restore old signal handlers.
3805 
3807 {
3808  for (int sig = 0; sig < kMAXSIGNALS; sig++)
3809  UnixResetSignal((ESignals)sig);
3810 }
3811 
3812 //---- time --------------------------------------------------------------------
3813 
3814 ////////////////////////////////////////////////////////////////////////////////
3815 /// Get current time in milliseconds since 0:00 Jan 1 1995.
3816 
3818 {
3819  static std::atomic<time_t> jan95{0};
3820  if (!jan95) {
3821  struct tm tp;
3822  tp.tm_year = 95;
3823  tp.tm_mon = 0;
3824  tp.tm_mday = 1;
3825  tp.tm_hour = 0;
3826  tp.tm_min = 0;
3827  tp.tm_sec = 0;
3828  tp.tm_isdst = -1;
3829 
3830  jan95 = mktime(&tp);
3831  if ((int)jan95 == -1) {
3832  ::SysError("TUnixSystem::UnixNow", "error converting 950001 0:00 to time_t");
3833  return 0;
3834  }
3835  }
3836 
3837  struct timeval t;
3838  gettimeofday(&t, 0);
3839  return Long64_t(t.tv_sec-(Long_t)jan95)*1000 + t.tv_usec/1000;
3840 }
3841 
3842 ////////////////////////////////////////////////////////////////////////////////
3843 /// Set interval timer to time-out in ms milliseconds.
3844 
3846 {
3847  struct itimerval itv;
3848  itv.it_value.tv_sec = 0;
3849  itv.it_value.tv_usec = 0;
3850  itv.it_interval.tv_sec = 0;
3851  itv.it_interval.tv_usec = 0;
3852  if (ms > 0) {
3853  itv.it_value.tv_sec = time_t(ms / 1000);
3854  itv.it_value.tv_usec = time_t((ms % 1000) * 1000);
3855  }
3856  int st = setitimer(ITIMER_REAL, &itv, 0);
3857  if (st == -1)
3858  ::SysError("TUnixSystem::UnixSetitimer", "setitimer");
3859  return st;
3860 }
3861 
3862 //---- file descriptors --------------------------------------------------------
3863 
3864 ////////////////////////////////////////////////////////////////////////////////
3865 /// Wait for events on the file descriptors specified in the readready and
3866 /// writeready masks or for timeout (in milliseconds) to occur. Returns
3867 /// the number of ready descriptors, or 0 in case of timeout, or < 0 in
3868 /// case of an error, with -2 being EINTR and -3 EBADF. In case of EINTR
3869 /// the errno has been reset and the method can be called again.
3870 
3871 int TUnixSystem::UnixSelect(Int_t nfds, TFdSet *readready, TFdSet *writeready,
3872  Long_t timeout)
3873 {
3874  int retcode;
3875 
3876  fd_set *rd = (readready) ? (fd_set*)readready->GetBits() : 0;
3877  fd_set *wr = (writeready) ? (fd_set*)writeready->GetBits() : 0;
3878 
3879  if (timeout >= 0) {
3880  struct timeval tv;
3881  tv.tv_sec = Int_t(timeout / 1000);
3882  tv.tv_usec = (timeout % 1000) * 1000;
3883  retcode = select(nfds, rd, wr, 0, &tv);
3884  } else {
3885  retcode = select(nfds, rd, wr, 0, 0);
3886  }
3887  if (retcode == -1) {
3888  if (GetErrno() == EINTR) {
3889  ResetErrno(); // errno is not self reseting
3890  return -2;
3891  }
3892  if (GetErrno() == EBADF)
3893  return -3;
3894  return -1;
3895  }
3896 
3897  return retcode;
3898 }
3899 
3900 //---- directories -------------------------------------------------------------
3901 
3902 ////////////////////////////////////////////////////////////////////////////////
3903 /// Returns the user's home directory.
3904 
3905 const char *TUnixSystem::UnixHomedirectory(const char *name)
3906 {
3907  static char path[kMAXPATHLEN], mydir[kMAXPATHLEN] = { '\0' };
3908  return UnixHomedirectory(name, path, mydir);
3909 }
3910 
3911 ////////////////////////////////////////////////////////////////////////////
3912 /// Returns the user's home directory.
3913 
3914 const char *TUnixSystem::UnixHomedirectory(const char *name, char *path, char *mydir)
3915 {
3916  struct passwd *pw;
3917  if (name) {
3918  pw = getpwnam(name);
3919  if (pw) {
3920  strncpy(path, pw->pw_dir, kMAXPATHLEN-1);
3921  path[kMAXPATHLEN-1] = '\0';
3922  return path;
3923  }
3924  } else {
3925  if (mydir[0])
3926  return mydir;
3927  pw = getpwuid(getuid());
3928  if (pw && pw->pw_dir) {
3929  strncpy(mydir, pw->pw_dir, kMAXPATHLEN-1);
3930  mydir[kMAXPATHLEN-1] = '\0';
3931  return mydir;
3932  } else if (gSystem->Getenv("HOME")) {
3933  strncpy(mydir, gSystem->Getenv("HOME"), kMAXPATHLEN-1);
3934  mydir[kMAXPATHLEN-1] = '\0';
3935  return mydir;
3936  }
3937  }
3938  return 0;
3939 }
3940 
3941 ////////////////////////////////////////////////////////////////////////////////
3942 /// Make a Unix file system directory. Returns 0 in case of success and
3943 /// -1 if the directory could not be created (either already exists or
3944 /// illegal path name).
3945 
3946 int TUnixSystem::UnixMakedir(const char *dir)
3947 {
3948  return ::mkdir(StripOffProto(dir, "file:"), 0755);
3949 }
3950 
3951 ////////////////////////////////////////////////////////////////////////////////
3952 /// Open a directory.
3953 
3954 void *TUnixSystem::UnixOpendir(const char *dir)
3955 {
3956  struct stat finfo;
3957 
3958  const char *edir = StripOffProto(dir, "file:");
3959 
3960  if (stat(edir, &finfo) < 0)
3961  return 0;
3962 
3963  if (!S_ISDIR(finfo.st_mode))
3964  return 0;
3965 
3966  return (void*) opendir(edir);
3967 }
3968 
3969 #if defined(_POSIX_SOURCE)
3970 // Posix does not require that the d_ino field be present, and some
3971 // systems do not provide it.
3972 # define REAL_DIR_ENTRY(dp) 1
3973 #else
3974 # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
3975 #endif
3976 
3977 ////////////////////////////////////////////////////////////////////////////////
3978 /// Returns the next directory entry.
3979 
3980 const char *TUnixSystem::UnixGetdirentry(void *dirp1)
3981 {
3982  DIR *dirp = (DIR*)dirp1;
3983 #ifdef HAS_DIRENT
3984  struct dirent *dp;
3985 #else
3986  struct direct *dp;
3987 #endif
3988 
3989  if (dirp) {
3990  for (;;) {
3991  dp = readdir(dirp);
3992  if (dp == 0)
3993  return 0;
3994  if (REAL_DIR_ENTRY(dp))
3995  return dp->d_name;
3996  }
3997  }
3998  return 0;
3999 }
4000 
4001 //---- files -------------------------------------------------------------------
4002 
4003 ////////////////////////////////////////////////////////////////////////////////
4004 /// Get info about a file. Info is returned in the form of a FileStat_t
4005 /// structure (see TSystem.h).
4006 /// The function returns 0 in case of success and 1 if the file could
4007 /// not be stat'ed.
4008 
4009 int TUnixSystem::UnixFilestat(const char *fpath, FileStat_t &buf)
4010 {
4011  const char *path = StripOffProto(fpath, "file:");
4012  buf.fIsLink = kFALSE;
4013 
4014 #if defined(R__SEEK64)
4015  struct stat64 sbuf;
4016  if (path && lstat64(path, &sbuf) == 0) {
4017 #else
4018  struct stat sbuf;
4019  if (path && lstat(path, &sbuf) == 0) {
4020 #endif
4021  buf.fIsLink = S_ISLNK(sbuf.st_mode);
4022  if (buf.fIsLink) {
4023 #if defined(R__SEEK64)
4024  if (stat64(path, &sbuf) == -1) {
4025 #else
4026  if (stat(path, &sbuf) == -1) {
4027 #endif
4028  return 1;
4029  }
4030  }
4031  buf.fDev = sbuf.st_dev;
4032  buf.fIno = sbuf.st_ino;
4033  buf.fMode = sbuf.st_mode;
4034  buf.fUid = sbuf.st_uid;
4035  buf.fGid = sbuf.st_gid;
4036  buf.fSize = sbuf.st_size;
4037  buf.fMtime = sbuf.st_mtime;
4038 
4039  return 0;
4040  }
4041  return 1;
4042 }
4043 
4044 ////////////////////////////////////////////////////////////////////////////////
4045 /// Get info about a file system: id, bsize, bfree, blocks.
4046 /// Id is file system type (machine dependend, see statfs())
4047 /// Bsize is block size of file system
4048 /// Blocks is total number of blocks in file system
4049 /// Bfree is number of free blocks in file system
4050 /// The function returns 0 in case of success and 1 if the file system could
4051 /// not be stat'ed.
4052 
4053 int TUnixSystem::UnixFSstat(const char *path, Long_t *id, Long_t *bsize,
4054  Long_t *blocks, Long_t *bfree)
4055 {
4056  struct statfs statfsbuf;
4057 #if (defined(R__SOLARIS) && !defined(R__LINUX))
4058  if (statfs(path, &statfsbuf, sizeof(struct statfs), 0) == 0) {
4059  *id = statfsbuf.f_fstyp;
4060  *bsize = statfsbuf.f_bsize;
4061  *blocks = statfsbuf.f_blocks;
4062  *bfree = statfsbuf.f_bfree;
4063 #else
4064  if (statfs((char*)path, &statfsbuf) == 0) {
4065 #ifdef R__OBSD
4066  // Convert BSD filesystem names to Linux filesystem type numbers
4067  // where possible. Linux statfs uses a value of -1 to indicate
4068  // an unsupported field.
4069 
4070  if (!strcmp(statfsbuf.f_fstypename, MOUNT_FFS) ||
4071  !strcmp(statfsbuf.f_fstypename, MOUNT_MFS))
4072  *id = 0x11954;
4073  else if (!strcmp(statfsbuf.f_fstypename, MOUNT_NFS))
4074  *id = 0x6969;
4075  else if (!strcmp(statfsbuf.f_fstypename, MOUNT_MSDOS))
4076  *id = 0x4d44;
4077  else if (!strcmp(statfsbuf.f_fstypename, MOUNT_EXT2FS))
4078  *id = 0xef53;
4079  else if (!strcmp(statfsbuf.f_fstypename, MOUNT_CD9660))
4080  *id = 0x9660;
4081  else if (!strcmp(statfsbuf.f_fstypename, MOUNT_NCPFS))
4082  *id = 0x6969;
4083  else
4084  *id = -1;
4085 #else
4086  *id = statfsbuf.f_type;
4087 #endif
4088  *bsize = statfsbuf.f_bsize;
4089  *blocks = statfsbuf.f_blocks;
4090  *bfree = statfsbuf.f_bavail;
4091 #endif
4092  return 0;
4093  }
4094  return 1;
4095 }
4096 
4097 ////////////////////////////////////////////////////////////////////////////////
4098 /// Wait till child is finished.
4099 
4101 {
4102  int status;
4103  return (int) waitpid(0, &status, WNOHANG);
4104 }
4105 
4106 //---- RPC -------------------------------------------------------------------
4107 
4108 ////////////////////////////////////////////////////////////////////////////////
4109 /// Open a TCP/IP connection to server and connect to a service (i.e. port).
4110 /// Use tcpwindowsize to specify the size of the receive buffer, it has
4111 /// to be specified here to make sure the window scale option is set (for
4112 /// tcpwindowsize > 65KB and for platforms supporting window scaling).
4113 /// Is called via the TSocket constructor. Returns -1 in case of error.
4114 
4115 int TUnixSystem::UnixTcpConnect(const char *hostname, int port,
4116  int tcpwindowsize)
4117 {
4118  short sport;
4119  struct servent *sp;
4120 
4121  if ((sp = getservbyport(htons(port), kProtocolName)))
4122  sport = sp->s_port;
4123  else
4124  sport = htons(port);
4125 
4126  TInetAddress addr = gSystem->GetHostByName(hostname);
4127  if (!addr.IsValid()) return -1;
4128  UInt_t adr = htonl(addr.GetAddress());
4129 
4130  struct sockaddr_in server;
4131  memset(&server, 0, sizeof(server));
4132  memcpy(&server.sin_addr, &adr, sizeof(adr));
4133  server.sin_family = addr.GetFamily();
4134  server.sin_port = sport;
4135 
4136  // Create socket
4137  int sock;
4138  if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
4139  ::SysError("TUnixSystem::UnixTcpConnect", "socket (%s:%d)",
4140  hostname, port);
4141  return -1;
4142  }
4143 
4144  if (tcpwindowsize > 0) {
4145  gSystem->SetSockOpt(sock, kRecvBuffer, tcpwindowsize);
4146  gSystem->SetSockOpt(sock, kSendBuffer, tcpwindowsize);
4147  }
4148 
4149  while (connect(sock, (struct sockaddr*) &server, sizeof(server)) == -1) {
4150  if (GetErrno() == EINTR)
4151  ResetErrno();
4152  else {
4153  ::SysError("TUnixSystem::UnixTcpConnect", "connect (%s:%d)",
4154  hostname, port);
4155  close(sock);
4156  return -1;
4157  }
4158  }
4159  return sock;
4160 }
4161 
4162 
4163 ////////////////////////////////////////////////////////////////////////////////
4164 /// Creates a UDP socket connection
4165 /// Is called via the TSocket constructor. Returns -1 in case of error.
4166 
4167 int TUnixSystem::UnixUdpConnect(const char *hostname, int port)
4168 {
4169  short sport;
4170  struct servent *sp;
4171 
4172  if ((sp = getservbyport(htons(port), kProtocolName)))
4173  sport = sp->s_port;
4174  else
4175  sport = htons(port);
4176 
4177  TInetAddress addr = gSystem->GetHostByName(hostname);
4178  if (!addr.IsValid()) return -1;
4179  UInt_t adr = htonl(addr.GetAddress());
4180 
4181  struct sockaddr_in server;
4182  memset(&server, 0, sizeof(server));
4183  memcpy(&server.sin_addr, &adr, sizeof(adr));
4184  server.sin_family = addr.GetFamily();
4185  server.sin_port = sport;
4186 
4187  // Create socket
4188  int sock;
4189  if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
4190  ::SysError("TUnixSystem::UnixUdpConnect", "socket (%s:%d)",
4191  hostname, port);
4192  return -1;
4193  }
4194 
4195  while (connect(sock, (struct sockaddr*) &server, sizeof(server)) == -1) {
4196  if (GetErrno() == EINTR)
4197  ResetErrno();
4198  else {
4199  ::SysError("TUnixSystem::UnixUdpConnect", "connect (%s:%d)",
4200  hostname, port);
4201  close(sock);
4202  return -1;
4203  }
4204  }
4205  return sock;
4206 }
4207 
4208 ////////////////////////////////////////////////////////////////////////////////
4209 /// Connect to a Unix domain socket.
4210 
4212 {
4213  return UnixUnixConnect(TString::Format("%s/%d", kServerPath, port));
4214 }
4215 
4216 ////////////////////////////////////////////////////////////////////////////////
4217 /// Connect to a Unix domain socket. Returns -1 in case of error.
4218 
4219 int TUnixSystem::UnixUnixConnect(const char *sockpath)
4220 {
4221  if (!sockpath || strlen(sockpath) <= 0) {
4222  ::SysError("TUnixSystem::UnixUnixConnect", "socket path undefined");
4223  return -1;
4224  }
4225 
4226  int sock;
4227  struct sockaddr_un unserver;
4228  unserver.sun_family = AF_UNIX;
4229 
4230  if (strlen(sockpath) > sizeof(unserver.sun_path)-1) {
4231  ::Error("TUnixSystem::UnixUnixConnect", "socket path %s, longer than max allowed length (%u)",
4232  sockpath, (UInt_t)sizeof(unserver.sun_path)-1);
4233  return -1;
4234  }
4235  strcpy(unserver.sun_path, sockpath);
4236 
4237  // Open socket
4238  if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
4239  ::SysError("TUnixSystem::UnixUnixConnect", "socket");
4240  return -1;
4241  }
4242 
4243  while (connect(sock, (struct sockaddr*) &unserver, strlen(unserver.sun_path)+2) == -1) {
4244  if (GetErrno() == EINTR)
4245  ResetErrno();
4246  else {
4247  ::SysError("TUnixSystem::UnixUnixConnect", "connect");
4248  close(sock);
4249  return -1;
4250  }
4251  }
4252  return sock;
4253 }
4254 
4255 ////////////////////////////////////////////////////////////////////////////////
4256 /// Open a socket, bind to it and start listening for TCP/IP connections
4257 /// on the port. If reuse is true reuse the address, backlog specifies
4258 /// how many sockets can be waiting to be accepted. If port is 0 a port
4259 /// scan will be done to find a free port. This option is mutual exlusive
4260 /// with the reuse option.
4261 /// Use tcpwindowsize to specify the size of the receive buffer, it has
4262 /// to be specified here to make sure the window scale option is set (for
4263 /// tcpwindowsize > 65KB and for platforms supporting window scaling).
4264 /// Returns socket fd or -1 if socket() failed, -2 if bind() failed
4265 /// or -3 if listen() failed.
4266 
4267 int TUnixSystem::UnixTcpService(int port, Bool_t reuse, int backlog,
4268  int tcpwindowsize)
4269 {
4270  const short kSOCKET_MINPORT = 5000, kSOCKET_MAXPORT = 15000;
4271  short sport, tryport = kSOCKET_MINPORT;
4272  struct servent *sp;
4273 
4274  if (port == 0 && reuse) {
4275  ::Error("TUnixSystem::UnixTcpService", "cannot do a port scan while reuse is true");
4276  return -1;
4277  }
4278 
4279  if ((sp = getservbyport(htons(port), kProtocolName)))
4280  sport = sp->s_port;
4281  else
4282  sport = htons(port);
4283 
4284  // Create tcp socket
4285  int sock;
4286  if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
4287  ::SysError("TUnixSystem::UnixTcpService", "socket");
4288  return -1;
4289  }
4290 
4291  if (reuse)
4292  gSystem->SetSockOpt(sock, kReuseAddr, 1);
4293 
4294  if (tcpwindowsize > 0) {
4295  gSystem->SetSockOpt(sock, kRecvBuffer, tcpwindowsize);
4296  gSystem->SetSockOpt(sock, kSendBuffer, tcpwindowsize);
4297  }
4298 
4299  struct sockaddr_in inserver;
4300  memset(&inserver, 0, sizeof(inserver));
4301  inserver.sin_family = AF_INET;
4302  inserver.sin_addr.s_addr = htonl(INADDR_ANY);
4303  inserver.sin_port = sport;
4304 
4305  // Bind socket
4306  if (port > 0) {
4307  if (::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver))) {
4308  ::SysError("TUnixSystem::UnixTcpService", "bind");
4309  close(sock);
4310  return -2;
4311  }
4312  } else {
4313  int bret;
4314  do {
4315  inserver.sin_port = htons(tryport);
4316  bret = ::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver));
4317  tryport++;
4318  } while (bret < 0 && GetErrno() == EADDRINUSE && tryport < kSOCKET_MAXPORT);
4319  if (bret < 0) {
4320  ::SysError("TUnixSystem::UnixTcpService", "bind (port scan)");
4321  close(sock);
4322  return -2;
4323  }
4324  }
4325 
4326  // Start accepting connections
4327  if (::listen(sock, backlog)) {
4328  ::SysError("TUnixSystem::UnixTcpService", "listen");
4329  close(sock);
4330  return -3;
4331  }
4332 
4333  return sock;
4334 }
4335 
4336 ////////////////////////////////////////////////////////////////////////////////
4337 /// Open a socket, bind to it and start listening for UDP connections
4338 /// on the port. If reuse is true reuse the address, backlog specifies
4339 /// how many sockets can be waiting to be accepted. If port is 0 a port
4340 /// scan will be done to find a free port. This option is mutual exlusive
4341 /// with the reuse option.
4342 
4343 int TUnixSystem::UnixUdpService(int port, int backlog)
4344 {
4345  const short kSOCKET_MINPORT = 5000, kSOCKET_MAXPORT = 15000;
4346  short sport, tryport = kSOCKET_MINPORT;
4347  struct servent *sp;
4348 
4349  if ((sp = getservbyport(htons(port), kProtocolName)))
4350  sport = sp->s_port;
4351  else
4352  sport = htons(port);
4353 
4354  // Create udp socket
4355  int sock;
4356  if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
4357  ::SysError("TUnixSystem::UnixUdpService", "socket");
4358  return -1;
4359  }
4360 
4361  struct sockaddr_in inserver;
4362  memset(&inserver, 0, sizeof(inserver));
4363  inserver.sin_family = AF_INET;
4364  inserver.sin_addr.s_addr = htonl(INADDR_ANY);
4365  inserver.sin_port = sport;
4366 
4367  // Bind socket
4368  if (port > 0) {
4369  if (::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver))) {
4370  ::SysError("TUnixSystem::UnixUdpService", "bind");
4371  close(sock);
4372  return -2;
4373  }
4374  } else {
4375  int bret;
4376  do {
4377  inserver.sin_port = htons(tryport);
4378  bret = ::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver));
4379  tryport++;
4380  } while (bret < 0 && GetErrno() == EADDRINUSE && tryport < kSOCKET_MAXPORT);
4381  if (bret < 0) {
4382  ::SysError("TUnixSystem::UnixUdpService", "bind (port scan)");
4383  close(sock);
4384  return -2;
4385  }
4386  }
4387 
4388  // Start accepting connections
4389  if (::listen(sock, backlog)) {
4390  ::SysError("TUnixSystem::UnixUdpService", "listen");
4391  close(sock);
4392  return -3;
4393  }
4394 
4395  return sock;
4396 }
4397 
4398 ////////////////////////////////////////////////////////////////////////////////
4399 /// Open a socket, bind to it and start listening for Unix domain connections
4400 /// to it. Returns socket fd or -1.
4401 
4402 int TUnixSystem::UnixUnixService(int port, int backlog)
4403 {
4404  int oldumask;
4405 
4406  // Assure that socket directory exists
4407  oldumask = umask(0);
4408  int res = ::mkdir(kServerPath, 0777);
4409  umask(oldumask);
4410 
4411  if (res == -1)
4412  return -1;
4413 
4414  // Socket path
4415  TString sockpath;
4416  sockpath.Form("%s/%d", kServerPath, port);
4417 
4418  // Remove old socket
4419  unlink(sockpath.Data());
4420 
4421  return UnixUnixService(sockpath, backlog);
4422 }
4423 
4424 ////////////////////////////////////////////////////////////////////////////////
4425 /// Open a socket on path 'sockpath', bind to it and start listening for Unix
4426 /// domain connections to it. Returns socket fd or -1.
4427 
4428 int TUnixSystem::UnixUnixService(const char *sockpath, int backlog)
4429 {
4430  if (!sockpath || strlen(sockpath) <= 0) {
4431  ::SysError("TUnixSystem::UnixUnixService", "socket path undefined");
4432  return -1;
4433  }
4434 
4435  struct sockaddr_un unserver;
4436  int sock;
4437 
4438  // Prepare structure
4439  memset(&unserver, 0, sizeof(unserver));
4440  unserver.sun_family = AF_UNIX;
4441 
4442  if (strlen(sockpath) > sizeof(unserver.sun_path)-1) {
4443  ::Error("TUnixSystem::UnixUnixService", "socket path %s, longer than max allowed length (%u)",
4444  sockpath, (UInt_t)sizeof(unserver.sun_path)-1);
4445  return -1;
4446  }
4447  strcpy(unserver.sun_path, sockpath);
4448 
4449  // Create socket
4450  if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
4451  ::SysError("TUnixSystem::UnixUnixService", "socket");
4452  return -1;
4453  }
4454 
4455  if (::bind(sock, (struct sockaddr*) &unserver, strlen(unserver.sun_path)+2)) {
4456  ::SysError("TUnixSystem::UnixUnixService", "bind");
4457  close(sock);
4458  return -1;
4459  }
4460 
4461  // Start accepting connections
4462  if (::listen(sock, backlog)) {
4463  ::SysError("TUnixSystem::UnixUnixService", "listen");
4464  close(sock);
4465  return -1;
4466  }
4467 
4468  return sock;
4469 }
4470 
4471 ////////////////////////////////////////////////////////////////////////////////
4472 /// Receive exactly length bytes into buffer. Returns number of bytes
4473 /// received. Returns -1 in case of error, -2 in case of MSG_OOB
4474 /// and errno == EWOULDBLOCK, -3 in case of MSG_OOB and errno == EINVAL
4475 /// and -4 in case of kNoBlock and errno == EWOULDBLOCK.
4476 /// Returns -5 if pipe broken or reset by peer (EPIPE || ECONNRESET).
4477 
4478 int TUnixSystem::UnixRecv(int sock, void *buffer, int length, int flag)
4479 {
4480  ResetErrno();
4481 
4482  if (sock < 0) return -1;
4483 
4484  int once = 0;
4485  if (flag == -1) {
4486  flag = 0;
4487  once = 1;
4488  }
4489  if (flag == MSG_PEEK)
4490  once = 1;
4491 
4492  int n, nrecv = 0;
4493  char *buf = (char *)buffer;
4494 
4495  for (n = 0; n < length; n += nrecv) {
4496  if ((nrecv = recv(sock, buf+n, length-n, flag)) <= 0) {
4497  if (nrecv == 0)
4498  break; // EOF
4499  if (flag == MSG_OOB) {
4500  if (GetErrno() == EWOULDBLOCK)
4501  return -2;
4502  else if (GetErrno() == EINVAL)
4503  return -3;
4504  }
4505  if (GetErrno() == EWOULDBLOCK)
4506  return -4;
4507  else {
4508  if (GetErrno() != EINTR)
4509  ::SysError("TUnixSystem::UnixRecv", "recv");
4510  if (GetErrno() == EPIPE || GetErrno() == ECONNRESET)
4511  return -5;
4512  else
4513  return -1;
4514  }
4515  }
4516  if (once)
4517  return nrecv;
4518  }
4519  return n;
4520 }
4521 
4522 ////////////////////////////////////////////////////////////////////////////////
4523 /// Send exactly length bytes from buffer. Returns -1 in case of error,
4524 /// otherwise number of sent bytes. Returns -4 in case of kNoBlock and
4525 /// errno == EWOULDBLOCK. Returns -5 if pipe broken or reset by peer
4526 /// (EPIPE || ECONNRESET).
4527 
4528 int TUnixSystem::UnixSend(int sock, const void *buffer, int length, int flag)
4529 {
4530  if (sock < 0) return -1;
4531 
4532  int once = 0;
4533  if (flag == -1) {
4534  flag = 0;
4535  once = 1;
4536  }
4537 
4538  int n, nsent = 0;
4539  const char *buf = (const char *)buffer;
4540 
4541  for (n = 0; n < length; n += nsent) {
4542  if ((nsent = send(sock, buf+n, length-n, flag)) <= 0) {
4543  if (nsent == 0)
4544  break;
4545  if (GetErrno() == EWOULDBLOCK)
4546  return -4;
4547  else {
4548  if (GetErrno() != EINTR)
4549  ::SysError("TUnixSystem::UnixSend", "send");
4550  if (GetErrno() == EPIPE || GetErrno() == ECONNRESET)
4551  return -5;
4552  else
4553  return -1;
4554  }
4555  }
4556  if (once)
4557  return nsent;
4558  }
4559  return n;
4560 }
4561 
4562 //---- Dynamic Loading ---------------------------------------------------------
4563 
4564 ////////////////////////////////////////////////////////////////////////////////
4565 /// Get shared library search path. Static utility function.
4566 
4567 static const char *DynamicPath(const char *newpath = 0, Bool_t reset = kFALSE)
4568 {
4569  static TString dynpath;
4570  static Bool_t initialized = kFALSE;
4571  if (!initialized) {
4572  // force one time initialization of gROOT before we start
4573  // (otherwise it might be done as a side effect of gEnv->GetValue and
4574  // TROOT's initialization will call this routine).
4575  gROOT;
4576  }
4577 
4578  if (newpath) {
4579  dynpath = newpath;
4580  } else if (reset || !initialized) {
4581  initialized = kTRUE;
4582  TString rdynpath = gEnv->GetValue("Root.DynamicPath", (char*)0);
4583  rdynpath.ReplaceAll(": ", ":"); // in case DynamicPath was extended
4584  if (rdynpath.IsNull()) {
4585  rdynpath = ".:"; rdynpath += TROOT::GetLibDir();
4586  }
4587  TString ldpath;
4588 #if defined (R__AIX)
4589  ldpath = gSystem->Getenv("LIBPATH");
4590 #elif defined(R__MACOSX)
4591  ldpath = gSystem->Getenv("DYLD_LIBRARY_PATH");
4592  if (!ldpath.IsNull())
4593  ldpath += ":";
4594  ldpath += gSystem->Getenv("LD_LIBRARY_PATH");
4595  if (!ldpath.IsNull())
4596  ldpath += ":";
4597  ldpath += gSystem->Getenv("DYLD_FALLBACK_LIBRARY_PATH");
4598 #else
4599  ldpath = gSystem->Getenv("LD_LIBRARY_PATH");
4600 #endif
4601  if (ldpath.IsNull())
4602  dynpath = rdynpath;
4603  else {
4604  dynpath = ldpath; dynpath += ":"; dynpath += rdynpath;
4605  }
4606  if (!dynpath.Contains(TROOT::GetLibDir())) {
4607  dynpath += ":"; dynpath += TROOT::GetLibDir();
4608  }
4609  if (gCling) {
4610  dynpath += ":"; dynpath += gCling->GetSTLIncludePath();
4611  } else
4612  initialized = kFALSE;
4613 
4614 #if defined(R__WINGCC) || defined(R__MACOSX)
4615  if (!dynpath.EndsWith(":")) dynpath += ":";
4616  dynpath += "/usr/local/lib:/usr/X11R6/lib:/usr/lib:/lib:";
4617  dynpath += "/lib/x86_64-linux-gnu:/usr/local/lib64:/usr/lib64:/lib64:";
4618 #else
4619  // trick to get the system search path
4620  std::string cmd("LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1");
4621  FILE *pf = popen(cmd.c_str (), "r");
4622  std::string result = "";
4623  char buffer[128];
4624  while (!feof(pf)) {
4625  if (fgets(buffer, 128, pf) != NULL)
4626  result += buffer;
4627  }
4628  pclose(pf);
4629  std::size_t from = result.find("search path=", result.find("(LD_LIBRARY_PATH)"));
4630  std::size_t to = result.find("(system search path)");
4631  if (from != std::string::npos && to != std::string::npos) {
4632  from += 12;
4633  std::string sys_path = result.substr(from, to-from);
4634  sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace), sys_path.end());
4635  if (!dynpath.EndsWith(":")) dynpath += ":";
4636  dynpath += sys_path.c_str();
4637  }
4638  dynpath.ReplaceAll("::", ":");
4639 #endif
4640  if (gDebug > 0) std::cout << "dynpath = " << dynpath.Data() << std::endl;
4641  }
4642  return dynpath;
4643 }
4644 
4645 ////////////////////////////////////////////////////////////////////////////////
4646 /// Add a new directory to the dynamic path.
4647 
4648 void TUnixSystem::AddDynamicPath(const char *path)
4649 {
4650  if (path) {
4651  TString oldpath = DynamicPath(0, kFALSE);
4652  oldpath.Append(":");
4653  oldpath.Append(path);
4654  DynamicPath(oldpath);
4655  }
4656 }
4657 
4658 ////////////////////////////////////////////////////////////////////////////////
4659 /// Return the dynamic path (used to find shared libraries).
4660 
4662 {
4663  return DynamicPath(0, kFALSE);
4664 }
4665 
4666 ////////////////////////////////////////////////////////////////////////////////
4667 /// Set the dynamic path to a new value.
4668 /// If the value of 'path' is zero, the dynamic path is reset to its
4669 /// default value.
4670 
4671 void TUnixSystem::SetDynamicPath(const char *path)
4672 {
4673  if (!path)
4674  DynamicPath(0, kTRUE);
4675  else
4676  DynamicPath(path);
4677 }
4678 
4679 ////////////////////////////////////////////////////////////////////////////////
4680 /// Returns the path of a shared library (searches for library in the
4681 /// shared library search path). If no file name extension is provided
4682 /// it first tries .so, .sl, .dl and then .a (for AIX).
4683 
4685 {
4686  char buf[PATH_MAX + 1];
4687  char *res = realpath(sLib.Data(), buf);
4688  if (res) sLib = buf;
4689  TString searchFor = sLib;
4691  return sLib;
4692  }
4693  sLib = searchFor;
4694  const char* lib = sLib.Data();
4695  int len = sLib.Length();
4696  if (len > 3 && (!strcmp(lib+len-3, ".so") ||
4697  !strcmp(lib+len-3, ".dl") ||
4698  !strcmp(lib+len-4, ".dll") ||
4699  !strcmp(lib+len-4, ".DLL") ||
4700  !strcmp(lib+len-6, ".dylib") ||
4701  !strcmp(lib+len-3, ".sl") ||
4702  !strcmp(lib+len-2, ".a"))) {
4704  return sLib;
4705  }
4706  if (!quiet)
4707  Error("FindDynamicLibrary",
4708  "%s does not exist in %s", searchFor.Data(), GetDynamicPath());
4709  return 0;
4710  }
4711  static const char* exts[] = {
4712  ".so", ".dll", ".dylib", ".sl", ".dl", ".a", 0 };
4713  const char** ext = exts;
4714  while (*ext) {
4715  TString fname(sLib);
4716  fname += *ext;
4717  ++ext;
4718  if (gSystem->FindFile(GetDynamicPath(), fname, kReadPermission)) {
4719  sLib.Swap(fname);
4720  return sLib;
4721  }
4722  }
4723 
4724  if (!quiet)
4725  Error("FindDynamicLibrary",
4726  "%s[.so | .dll | .dylib | .sl | .dl | .a] does not exist in %s",
4727  searchFor.Data(), GetDynamicPath());
4728 
4729  return 0;
4730 }
4731 
4732 //---- System, CPU and Memory info ---------------------------------------------
4733 
4734 #if defined(R__MACOSX)
4735 #include <sys/resource.h>
4736 #include <mach/mach.h>
4737 #include <mach/mach_error.h>
4738 
4739 ////////////////////////////////////////////////////////////////////////////////
4740 /// Get system info for Mac OS X.
4741 
4742 static void GetDarwinSysInfo(SysInfo_t *sysinfo)
4743 {
4744  FILE *p = gSystem->OpenPipe("sysctl -n kern.ostype hw.model hw.ncpu hw.cpufrequency "
4745  "hw.busfrequency hw.l2cachesize hw.memsize", "r");
4746  TString s;
4747  s.Gets(p);
4748  sysinfo->fOS = s;
4749  s.Gets(p);
4750  sysinfo->fModel = s;
4751  s.Gets(p);
4752  sysinfo->fCpus = s.Atoi();
4753  s.Gets(p);
4754  Long64_t t = s.Atoll();
4755  sysinfo->fCpuSpeed = Int_t(t / 1000000);
4756  s.Gets(p);
4757  t = s.Atoll();
4758  sysinfo->fBusSpeed = Int_t(t / 1000000);
4759  s.Gets(p);
4760  sysinfo->fL2Cache = s.Atoi() / 1024;
4761  s.Gets(p);
4762  t = s.Atoll();
4763  sysinfo->fPhysRam = Int_t(t / 1024 / 1024);
4764  gSystem->ClosePipe(p);
4765  p = gSystem->OpenPipe("hostinfo", "r");
4766  while (s.Gets(p)) {
4767  if (s.BeginsWith("Processor type: ")) {
4768  TPRegexp("Processor type: ([^ ]+).*").Substitute(s, "$1");
4769  sysinfo->fCpuType = s;
4770  }
4771  }
4772  gSystem->ClosePipe(p);
4773 }
4774 
4775 ////////////////////////////////////////////////////////////////////////////////
4776 /// Get CPU load on Mac OS X.
4777 
4778 static void ReadDarwinCpu(long *ticks)
4779 {
4780  mach_msg_type_number_t count;
4781  kern_return_t kr;
4782  host_cpu_load_info_data_t cpu;
4783 
4784  ticks[0] = ticks[1] = ticks[2] = ticks[3] = 0;
4785 
4786  count = HOST_CPU_LOAD_INFO_COUNT;
4787  kr = host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&cpu, &count);
4788  if (kr != KERN_SUCCESS) {
4789  ::Error("TUnixSystem::ReadDarwinCpu", "host_statistics: %s", mach_error_string(kr));
4790  } else {
4791  ticks[0] = cpu.cpu_ticks[CPU_STATE_USER];
4792  ticks[1] = cpu.cpu_ticks[CPU_STATE_SYSTEM];
4793  ticks[2] = cpu.cpu_ticks[CPU_STATE_IDLE];
4794  ticks[3] = cpu.cpu_ticks[CPU_STATE_NICE];
4795  }
4796 }
4797 
4798 ////////////////////////////////////////////////////////////////////////////////
4799 /// Get CPU stat for Mac OS X. Use sampleTime to set the interval over which
4800 /// the CPU load will be measured, in ms (default 1000).
4801 
4802 static void GetDarwinCpuInfo(CpuInfo_t *cpuinfo, Int_t sampleTime)
4803 {
4804  Double_t avg[3];
4805  if (getloadavg(avg, sizeof(avg)) < 0) {
4806  ::Error("TUnixSystem::GetDarwinCpuInfo", "getloadavg failed");
4807  } else {
4808  cpuinfo->fLoad1m = (Float_t)avg[0];
4809  cpuinfo->fLoad5m = (Float_t)avg[1];
4810  cpuinfo->fLoad15m = (Float_t)avg[2];
4811  }
4812 
4813  Long_t cpu_ticks1[4], cpu_ticks2[4];
4814  ReadDarwinCpu(cpu_ticks1);
4815  gSystem->Sleep(sampleTime);
4816  ReadDarwinCpu(cpu_ticks2);
4817 
4818  Long_t userticks = (cpu_ticks2[0] + cpu_ticks2[3]) -
4819  (cpu_ticks1[0] + cpu_ticks1[3]);
4820  Long_t systicks = cpu_ticks2[1] - cpu_ticks1[1];
4821  Long_t idleticks = cpu_ticks2[2] - cpu_ticks1[2];
4822  if (userticks < 0) userticks = 0;
4823  if (systicks < 0) systicks = 0;
4824  if (idleticks < 0) idleticks = 0;
4825  Long_t totalticks = userticks + systicks + idleticks;
4826  if (totalticks) {
4827  cpuinfo->fUser = ((Float_t)(100 * userticks)) / ((Float_t)totalticks);
4828  cpuinfo->fSys = ((Float_t)(100 * systicks)) / ((Float_t)totalticks);
4829  cpuinfo->fTotal = cpuinfo->fUser + cpuinfo->fSys;
4830  cpuinfo->fIdle = ((Float_t)(100 * idleticks)) / ((Float_t)totalticks);
4831  }
4832 }
4833 
4834 ////////////////////////////////////////////////////////////////////////////////
4835 /// Get VM stat for Mac OS X.
4836 
4837 static void GetDarwinMemInfo(MemInfo_t *meminfo)
4838 {
4839  static Int_t pshift = 0;
4840  static DIR *dirp;
4841  vm_statistics_data_t vm_info;
4842  mach_msg_type_number_t count;
4843  kern_return_t kr;
4844  struct dirent *dp;
4845  Long64_t total, used, free, swap_total, swap_used;
4846 
4847  count = HOST_VM_INFO_COUNT;
4848  kr = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vm_info, &count);
4849  if (kr != KERN_SUCCESS) {
4850  ::Error("TUnixSystem::GetDarwinMemInfo", "host_statistics: %s", mach_error_string(kr));
4851  return;
4852  }
4853  if (pshift == 0) {
4854  for (int psize = getpagesize(); psize > 1; psize >>= 1)
4855  pshift++;
4856  }
4857 
4858  used = (Long64_t)(vm_info.active_count + vm_info.inactive_count + vm_info.wire_count) << pshift;
4859  free = (Long64_t)(vm_info.free_count) << pshift;
4860  total = (Long64_t)(vm_info.active_count + vm_info.inactive_count + vm_info.free_count + vm_info.wire_count) << pshift;
4861 
4862  // Swap is available at same time as mem, so grab values here.
4863  swap_used = vm_info.pageouts << pshift;
4864 
4865  // Figure out total swap. This adds up the size of the swapfiles */
4866  dirp = opendir("/private/var/vm");
4867  if (!dirp)
4868  return;
4869 
4870  swap_total = 0;
4871  while ((dp = readdir(dirp)) != 0) {
4872  struct stat sb;
4873  char fname [MAXNAMLEN];
4874  if (strncmp(dp->d_name, "swapfile", 8))
4875  continue;
4876  strlcpy(fname, "/private/var/vm/",MAXNAMLEN);
4877  strlcat (fname, dp->d_name,MAXNAMLEN);
4878  if (stat(fname, &sb) < 0)
4879  continue;
4880  swap_total += sb.st_size;
4881  }
4882  closedir(dirp);
4883 
4884  meminfo->fMemTotal = (Int_t) (total >> 20); // divide by 1024 * 1024
4885  meminfo->fMemUsed = (Int_t) (used >> 20);
4886  meminfo->fMemFree = (Int_t) (free >> 20);
4887  meminfo->fSwapTotal = (Int_t) (swap_total >> 20);
4888  meminfo->fSwapUsed = (Int_t) (swap_used >> 20);
4889  meminfo->fSwapFree = meminfo->fSwapTotal - meminfo->fSwapUsed;
4890 }
4891 
4892 ////////////////////////////////////////////////////////////////////////////////
4893 /// Get process info for this process on Mac OS X.
4894 /// Code largely taken from:
4895 /// http://www.opensource.apple.com/source/top/top-15/libtop.c
4896 /// The virtual memory usage is slightly over estimated as we don't
4897 /// subtract shared regions, but the value makes more sense
4898 /// then pure vsize, which is useless on 64-bit machines.
4899 
4900 static void GetDarwinProcInfo(ProcInfo_t *procinfo)
4901 {
4902 #ifdef _LP64
4903 #define vm_region vm_region_64
4904 #endif
4905 
4906 // taken from <mach/shared_memory_server.h> which is obsoleted in 10.5
4907 #define GLOBAL_SHARED_TEXT_SEGMENT 0x90000000U
4908 #define GLOBAL_SHARED_DATA_SEGMENT 0xA0000000U
4909 #define SHARED_TEXT_REGION_SIZE 0x10000000
4910 #define SHARED_DATA_REGION_SIZE 0x10000000
4911 
4912  struct rusage ru;
4913  if (getrusage(RUSAGE_SELF, &ru) < 0) {
4914  ::SysError("TUnixSystem::GetDarwinProcInfo", "getrusage failed");
4915  } else {
4916  procinfo->fCpuUser = (Float_t)(ru.ru_utime.tv_sec) +
4917  ((Float_t)(ru.ru_utime.tv_usec) / 1000000.);
4918  procinfo->fCpuSys = (Float_t)(ru.ru_stime.tv_sec) +
4919  ((Float_t)(ru.ru_stime.tv_usec) / 1000000.);
4920  }
4921 
4922  task_basic_info_data_t ti;
4923  mach_msg_type_number_t count;
4924  kern_return_t kr;
4925 
4926  task_t a_task = mach_task_self();
4927 
4928  count = TASK_BASIC_INFO_COUNT;
4929  kr = task_info(a_task, TASK_BASIC_INFO, (task_info_t)&ti, &count);
4930  if (kr != KERN_SUCCESS) {
4931  ::Error("TUnixSystem::GetDarwinProcInfo", "task_info: %s", mach_error_string(kr));
4932  } else {
4933  // resident size does not require any calculation. Virtual size
4934  // needs to be adjusted if traversing memory objects do not include the
4935  // globally shared text and data regions
4936  mach_port_t object_name;
4937  vm_address_t address;
4938  vm_region_top_info_data_t info;
4939  vm_size_t vsize, vprvt, rsize, size;
4940  rsize = ti.resident_size;
4941  vsize = ti.virtual_size;
4942  vprvt = 0;
4943  for (address = 0; ; address += size) {
4944  // get memory region
4945  count = VM_REGION_TOP_INFO_COUNT;
4946  if (vm_region(a_task, &address, &size,
4947  VM_REGION_TOP_INFO, (vm_region_info_t)&info, &count,
4948  &object_name) != KERN_SUCCESS) {
4949  // no more memory regions.
4950  break;
4951  }
4952 
4953  if (address >= GLOBAL_SHARED_TEXT_SEGMENT &&
4954  address < (GLOBAL_SHARED_DATA_SEGMENT + SHARED_DATA_REGION_SIZE)) {
4955  // This region is private shared.
4956  // Check if this process has the globally shared
4957  // text and data regions mapped in. If so, adjust
4958  // virtual memory size and exit loop.
4959  if (info.share_mode == SM_EMPTY) {
4960  vm_region_basic_info_data_64_t b_info;
4961  count = VM_REGION_BASIC_INFO_COUNT_64;
4962  if (vm_region_64(a_task, &address,
4963  &size, VM_REGION_BASIC_INFO,
4964  (vm_region_info_t)&b_info, &count,
4965  &object_name) != KERN_SUCCESS) {
4966  break;
4967  }
4968 
4969  if (b_info.reserved) {
4970  vsize -= (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE);
4971  //break; // only for vsize
4972  }
4973  }
4974  // Short circuit the loop if this isn't a shared
4975  // private region, since that's the only region
4976  // type we care about within the current address range.
4977  if (info.share_mode != SM_PRIVATE) {
4978  continue;
4979  }
4980  }
4981  switch (info.share_mode) {
4982  case SM_COW: {
4983  if (info.ref_count == 1) {
4984  vprvt += size;
4985  } else {
4986  vprvt += info.private_pages_resident * getpagesize();
4987  }
4988  break;
4989  }
4990  case SM_PRIVATE: {
4991  vprvt += size;
4992  break;
4993  }
4994  default:
4995  break;
4996  }
4997  }
4998 
4999  procinfo->fMemResident = (Long_t)(rsize / 1024);
5000  //procinfo->fMemVirtual = (Long_t)(vsize / 1024);
5001  procinfo->fMemVirtual = (Long_t)(vprvt / 1024);
5002  }
5003 }
5004 #endif
5005 
5006 #if defined(R__LINUX)
5007 ////////////////////////////////////////////////////////////////////////////////
5008 /// Get system info for Linux. Only fBusSpeed is not set.
5009 
5010 static void GetLinuxSysInfo(SysInfo_t *sysinfo)
5011 {
5012  TString s;
5013  FILE *f = fopen("/proc/cpuinfo", "r");
5014  if (f) {
5015  while (s.Gets(f)) {
5016  if (s.BeginsWith("model name")) {
5017  TPRegexp("^.+: *(.*$)").Substitute(s, "$1");
5018  sysinfo->fModel = s;
5019  }
5020  if (s.BeginsWith("cpu MHz")) {
5021  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5022  sysinfo->fCpuSpeed = s.Atoi();
5023  }
5024  if (s.BeginsWith("cache size")) {
5025  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5026  sysinfo->fL2Cache = s.Atoi();
5027  }
5028  if (s.BeginsWith("processor")) {
5029  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5030  sysinfo->fCpus = s.Atoi();
5031  sysinfo->fCpus++;
5032  }
5033  }
5034  fclose(f);
5035  }
5036 
5037  f = fopen("/proc/meminfo", "r");
5038  if (f) {
5039  while (s.Gets(f)) {
5040  if (s.BeginsWith("MemTotal")) {
5041  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5042  sysinfo->fPhysRam = (s.Atoi() / 1024);
5043  break;
5044  }
5045  }
5046  fclose(f);
5047  }
5048 
5049  f = gSystem->OpenPipe("uname -s -p", "r");
5050  if (f) {
5051  s.Gets(f);
5052  Ssiz_t from = 0;
5053  s.Tokenize(sysinfo->fOS, from);
5054  s.Tokenize(sysinfo->fCpuType, from);
5055  gSystem->ClosePipe(f);
5056  }
5057 }
5058 
5059 ////////////////////////////////////////////////////////////////////////////////
5060 /// Get CPU load on Linux.
5061 
5062 static void ReadLinuxCpu(long *ticks)
5063 {
5064  ticks[0] = ticks[1] = ticks[2] = ticks[3] = 0;
5065 
5066  TString s;
5067  FILE *f = fopen("/proc/stat", "r");
5068  if (!f) return;
5069  s.Gets(f);
5070  // user, user nice, sys, idle
5071  sscanf(s.Data(), "%*s %ld %ld %ld %ld", &ticks[0], &ticks[3], &ticks[1], &ticks[2]);
5072  fclose(f);
5073 }
5074 
5075 ////////////////////////////////////////////////////////////////////////////////
5076 /// Get CPU stat for Linux. Use sampleTime to set the interval over which
5077 /// the CPU load will be measured, in ms (default 1000).
5078 
5079 static void GetLinuxCpuInfo(CpuInfo_t *cpuinfo, Int_t sampleTime)
5080 {
5081  Double_t avg[3] = { -1., -1., -1. };
5082 #ifndef R__WINGCC
5083  if (getloadavg(avg, sizeof(avg)) < 0) {
5084  ::Error("TUnixSystem::GetLinuxCpuInfo", "getloadavg failed");
5085  } else
5086 #endif
5087  {
5088  cpuinfo->fLoad1m = (Float_t)avg[0];
5089  cpuinfo->fLoad5m = (Float_t)avg[1];
5090  cpuinfo->fLoad15m = (Float_t)avg[2];
5091  }
5092 
5093  Long_t cpu_ticks1[4], cpu_ticks2[4];
5094  ReadLinuxCpu(cpu_ticks1);
5095  gSystem->Sleep(sampleTime);
5096  ReadLinuxCpu(cpu_ticks2);
5097 
5098  Long_t userticks = (cpu_ticks2[0] + cpu_ticks2[3]) -
5099  (cpu_ticks1[0] + cpu_ticks1[3]);
5100  Long_t systicks = cpu_ticks2[1] - cpu_ticks1[1];
5101  Long_t idleticks = cpu_ticks2[2] - cpu_ticks1[2];
5102  if (userticks < 0) userticks = 0;
5103  if (systicks < 0) systicks = 0;
5104  if (idleticks < 0) idleticks = 0;
5105  Long_t totalticks = userticks + systicks + idleticks;
5106  if (totalticks) {
5107  cpuinfo->fUser = ((Float_t)(100 * userticks)) / ((Float_t)totalticks);
5108  cpuinfo->fSys = ((Float_t)(100 * systicks)) / ((Float_t)totalticks);
5109  cpuinfo->fTotal = cpuinfo->fUser + cpuinfo->fSys;
5110  cpuinfo->fIdle = ((Float_t)(100 * idleticks)) / ((Float_t)totalticks);
5111  }
5112 }
5113 
5114 ////////////////////////////////////////////////////////////////////////////////
5115 /// Get VM stat for Linux.
5116 
5117 static void GetLinuxMemInfo(MemInfo_t *meminfo)
5118 {
5119  TString s;
5120  FILE *f = fopen("/proc/meminfo", "r");
5121  if (!f) return;
5122  while (s.Gets(f)) {
5123  if (s.BeginsWith("MemTotal")) {
5124  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5125  meminfo->fMemTotal = (s.Atoi() / 1024);
5126  }
5127  if (s.BeginsWith("MemFree")) {
5128  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5129  meminfo->fMemFree = (s.Atoi() / 1024);
5130  }
5131  if (s.BeginsWith("SwapTotal")) {
5132  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5133  meminfo->fSwapTotal = (s.Atoi() / 1024);
5134  }
5135  if (s.BeginsWith("SwapFree")) {
5136  TPRegexp("^.+: *([^ ]+).*").Substitute(s, "$1");
5137  meminfo->fSwapFree = (s.Atoi() / 1024);
5138  }
5139  }
5140  fclose(f);
5141 
5142  meminfo->fMemUsed = meminfo->fMemTotal - meminfo->fMemFree;
5143  meminfo->fSwapUsed = meminfo->fSwapTotal - meminfo->fSwapFree;
5144 }
5145 
5146 ////////////////////////////////////////////////////////////////////////////////
5147 /// Get process info for this process on Linux.
5148 
5149 static void GetLinuxProcInfo(ProcInfo_t *procinfo)
5150 {
5151  struct rusage ru;
5152  if (getrusage(RUSAGE_SELF, &ru) < 0) {
5153  ::SysError("TUnixSystem::GetLinuxProcInfo", "getrusage failed");
5154  } else {
5155  procinfo->fCpuUser = (Float_t)(ru.ru_utime.tv_sec) +
5156  ((Float_t)(ru.ru_utime.tv_usec) / 1000000.);
5157  procinfo->fCpuSys = (Float_t)(ru.ru_stime.tv_sec) +
5158  ((Float_t)(ru.ru_stime.tv_usec) / 1000000.);
5159  }
5160 
5161  procinfo->fMemVirtual = -1;
5162  procinfo->fMemResident = -1;
5163  TString s;
5164  FILE *f = fopen(TString::Format("/proc/%d/statm", gSystem->GetPid()), "r");
5165  if (f) {
5166  s.Gets(f);
5167  fclose(f);
5168  Long_t total, rss;
5169  sscanf(s.Data(), "%ld %ld", &total, &rss);
5170  procinfo->fMemVirtual = total * (getpagesize() / 1024);
5171  procinfo->fMemResident = rss * (getpagesize() / 1024);
5172  }
5173 }
5174 #endif
5175 
5176 ////////////////////////////////////////////////////////////////////////////////
5177 /// Returns static system info, like OS type, CPU type, number of CPUs
5178 /// RAM size, etc into the SysInfo_t structure. Returns -1 in case of error,
5179 /// 0 otherwise.
5180 
5182 {
5183  if (!info) return -1;
5184 
5185  static SysInfo_t sysinfo;
5186 
5187  if (!sysinfo.fCpus) {
5188 #if defined(R__MACOSX)
5189  GetDarwinSysInfo(&sysinfo);
5190 #elif defined(R__LINUX)
5191  GetLinuxSysInfo(&sysinfo);
5192 #endif
5193  }
5194 
5195  *info = sysinfo;
5196 
5197  return 0;
5198 }
5199 
5200 ////////////////////////////////////////////////////////////////////////////////
5201 /// Returns cpu load average and load info into the CpuInfo_t structure.
5202 /// Returns -1 in case of error, 0 otherwise. Use sampleTime to set the
5203 /// interval over which the CPU load will be measured, in ms (default 1000).
5204 
5205 int TUnixSystem::GetCpuInfo(CpuInfo_t *info, Int_t sampleTime) const
5206 {
5207  if (!info) return -1;
5208 
5209 #if defined(R__MACOSX)
5210  GetDarwinCpuInfo(info, sampleTime);
5211 #elif defined(R__LINUX)
5212  GetLinuxCpuInfo(info, sampleTime);
5213 #endif
5214 
5215  return 0;
5216 }
5217 
5218 ////////////////////////////////////////////////////////////////////////////////
5219 /// Returns ram and swap memory usage info into the MemInfo_t structure.
5220 /// Returns -1 in case of error, 0 otherwise.
5221 
5223 {
5224  if (!info) return -1;
5225 
5226 #if defined(R__MACOSX)
5227  GetDarwinMemInfo(info);
5228 #elif defined(R__LINUX)
5229  GetLinuxMemInfo(info);
5230 #endif
5231 
5232  return 0;
5233 }
5234 
5235 ////////////////////////////////////////////////////////////////////////////////
5236 /// Returns cpu and memory used by this process into the ProcInfo_t structure.
5237 /// Returns -1 in case of error, 0 otherwise.
5238 
5240 {
5241  if (!info) return -1;
5242 
5243 #if defined(R__MACOSX)
5244  GetDarwinProcInfo(info);
5245 #elif defined(R__LINUX)
5246  GetLinuxProcInfo(info);
5247 #endif
5248 
5249  return 0;
5250 }
Bool_t IsPathLocal(const char *path)
Returns TRUE if the url in &#39;path&#39; points to the local file system.
Int_t fMemFree
Definition: TSystem.h:183
Int_t fGid
Definition: TSystem.h:141
void(* SigHandler_t)(ESignals)
Definition: TUnixSystem.h:28
int GetPid()
Get process id.
virtual const char * GetSTLIncludePath() const
Definition: TInterpreter.h:150
virtual const char * BaseName(const char *pathname)
Base name of a file name. Base name of /user/root is root.
Definition: TSystem.cxx:932
TString fStdErrTty
Definition: TSystem.h:207
virtual void SysError(const char *method, const char *msgfmt,...) const
Issue system error message.
Definition: TObject.cxx:894
int GetFsInfo(const char *path, Long_t *id, Long_t *bsize, Long_t *blocks, Long_t *bfree)
Get info about a file system: id, bsize, bfree, blocks.
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:1276
Float_t fLoad15m
Definition: TSystem.h:169
int GetCpuInfo(CpuInfo_t *info, Int_t sampleTime=1000) const
Returns cpu load average and load info into the CpuInfo_t structure.
void AddTimer(TTimer *ti)
Add timer to list of system timers.
virtual void SetWriteReady()
void ListSymbols(const char *module, const char *re="")
List symbols in a shared library.
virtual int GetPid()
Get process id.
Definition: TSystem.cxx:715
An array of TObjects.
Definition: TObjArray.h:37
void StackTrace()
Print a stack trace.
Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
int pw_uid
Definition: TWinNTSystem.h:50
virtual Bool_t Notify()
Notify when event occurred on descriptor associated with this handler.
virtual Bool_t IsPathLocal(const char *path)
Returns TRUE if the url in &#39;path&#39; points to the local file system.
Definition: TSystem.cxx:1285
long long Long64_t
Definition: RtypesCore.h:69
Int_t fBusSpeed
Definition: TSystem.h:157
auto * m
Definition: textangle.C:8
Int_t fPhysRam
Definition: TSystem.h:159
Int_t fSigcnt
Definition: TSystem.h:265
const char * GetError()
Return system error string.
Int_t fReadOffSet
Definition: TSystem.h:210
virtual const char * WorkingDirectory()
Return working directory.
Definition: TSystem.cxx:869
void Sleep(UInt_t milliSec)
Sleep milliSec milliseconds.
char * pw_shell
Definition: TWinNTSystem.h:55
Bool_t Init()
Initialize Unix system interface.
const char * FindFile(const char *search, TString &file, EAccessMode mode=kFileExists)
Find location of file "wfil" in a search path.
Float_t fSys
Definition: TSystem.h:171
static void UnixResetSignal(ESignals sig)
Restore old signal handler for specified signal.
Bool_t ExpandPathName(TString &patbuf)
Expand a pathname getting rid of special shell characters like ~.
virtual ~TUnixSystem()
Reset to original state.
static const char * GetExePath()
R__EXTERN TVirtualMutex * gSystemMutex
Definition: TSystem.h:226
TLine * line
void Fatal(const char *location, const char *msgfmt,...)
Collectable string class.
Definition: TObjString.h:28
float Float_t
Definition: RtypesCore.h:53
int gr_gid
Definition: TWinNTSystem.h:62
int GetPathInfo(const char *path, FileStat_t &buf)
Get info about a file.
static int UnixFilestat(const char *path, FileStat_t &buf)
Get info about a file.
Int_t GetFPEMask()
Return the bitmap of conditions that trigger a floating point exception.
static int UnixTcpConnect(const char *hostname, int port, int tcpwindowsize)
Open a TCP/IP connection to server and connect to a service (i.e.
TString fOS
Definition: TSystem.h:152
const Ssiz_t kNPOS
Definition: RtypesCore.h:111
static int UnixRecv(int sock, void *buf, int len, int flag)
Receive exactly length bytes into buffer.
int GetSockOpt(int sock, int option, int *val)
Get socket option.
Int_t fUid
Definition: TSystem.h:129
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition: TString.h:638
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:1374
Bool_t DispatchTimers(Bool_t mode)
Handle and dispatch timers.
const char * FindDynamicLibrary(TString &lib, Bool_t quiet=kFALSE)
Returns the path of a shared library (searches for library in the shared library search path)...
void demangle(char *_codeInfo, TString &_str)
demangle symbols
const char * TempDirectory() const
Return a user configured or systemwide directory to create temporary files in.
TH1 * h
Definition: legend2.C:5
TString fStdOutTty
Definition: TSystem.h:206
char * gr_name
Definition: TWinNTSystem.h:60
TString fGroup
Definition: TSystem.h:143
int Symlink(const char *from, const char *to)
Create a symlink from file1 to file2.
This class represents an Internet Protocol (IP) address.
Definition: TInetAddress.h:36
virtual int MakeDirectory(const char *name)
Make a directory.
Definition: TSystem.cxx:825
virtual void AddSignalHandler(TSignalHandler *sh)
Add a signal handler to list of system signal handlers.
Definition: TSystem.cxx:540
TString fWdpath
Definition: TSystem.h:266
int MakeDirectory(const char *name)
Make a Unix file system directory.
Regular expression class.
Definition: TRegexp.h:31
Int_t fStdOutDup
Definition: TSystem.h:208
#define gROOT
Definition: TROOT.h:402
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition: TString.h:585
Int_t Select(TList *active, Long_t timeout)
Select on file descriptors.
Int_t GetGid(const char *group=0)
Returns the group&#39;s id. If group = 0, returns current user&#39;s group.
static Long64_t UnixNow()
Get current time in milliseconds since 0:00 Jan 1 1995.
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition: TSystem.cxx:1829
Basic string class.
Definition: TString.h:125
void SetProgname(const char *name)
Set the application name (from command line, argv[0]) and copy it in gProgName.
TSeqCollection * fSignalHandler
Definition: TSystem.h:277
static struct Signalmap_t gSignalMap[kMAXSIGNALS]
TFileHandler * RemoveFileHandler(TFileHandler *fh)
Remove a file handler from the list of file handlers.
int Int_t
Definition: RtypesCore.h:41
virtual const char * DirName(const char *pathname)
Return the directory name in pathname.
Definition: TSystem.cxx:1004
bool Bool_t
Definition: RtypesCore.h:59
virtual TTimer * RemoveTimer(TTimer *t)
Remove timer from list of system timers.
Definition: TSystem.cxx:489
Int_t Substitute(TString &s, const TString &replace, const TString &mods="", Int_t start=0, Int_t nMatchMax=10)
Substitute replaces the string s by a new string in which matching patterns are replaced by the repla...
Definition: TPRegexp.cxx:472
const char * HostName()
Return the system&#39;s host name.
int SendRaw(int sock, const void *buffer, int length, int flag)
Send exactly length bytes from buffer.
int Umask(Int_t mask)
Set the process file creation mode mask.
#define gInterpreter
Definition: TInterpreter.h:526
virtual char * Which(const char *search, const char *file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition: TSystem.cxx:1522
void Break(const char *location, const char *msgfmt,...)
Long_t fMtime
Definition: TSystem.h:132
void Syslog(ELogLevel level, const char *mess)
Send mess to syslog daemon.
virtual FILE * OpenPipe(const char *command, const char *mode)
Open a pipe.
Definition: TSystem.cxx:670
#define REAL_DIR_ENTRY(dp)
virtual void ResetReadyMask()
TString & Prepend(const char *cs)
Definition: TString.h:607
R__EXTERN TApplication * gApplication
Definition: TApplication.h:165
TObject * At(Int_t idx) const
Definition: TObjArray.h:165
Basic time type with millisecond precision.
Definition: TTime.h:27
static void UnixSigAlarmInterruptsSyscalls(Bool_t set)
When the argument is true the SIGALRM signal handler is set so that interrupted syscalls will not be ...
void FillWithCwd(char *cwd) const
Fill buffer with current working directory.
int ConnectService(const char *server, int port, int tcpwindowsize, const char *protocol="tcp")
Connect to service servicename on server servername.
const char * HomeDirectory(const char *userName=0)
Return the user&#39;s home directory.
const char * kShellMeta
TString fModel
Definition: TSystem.h:153
Bool_t fInsideNotify
Definition: TSystem.h:268
#define malloc
Definition: civetweb.c:818
Long64_t fSize
Definition: TSystem.h:131
void Exit(int code, Bool_t mode=kTRUE)
Exit the application.
int Unlink(const char *name)
Unlink, i.e.
Int_t fUid
Definition: TSystem.h:140
const char * kProtocolName
#define UTMP_FILE
static int UnixSelect(Int_t nfds, TFdSet *readready, TFdSet *writeready, Long_t timeout)
Wait for events on the file descriptors specified in the readready and writeready masks or for timeou...
virtual TFileHandler * RemoveFileHandler(TFileHandler *fh)
Remove a file handler from the list of file handlers.
Definition: TSystem.cxx:572
void Reset()
Definition: TCollection.h:250
virtual int mkdir(const char *name, Bool_t recursive=kFALSE)
Make a file system directory.
Definition: TSystem.cxx:904
void SysError(const char *location, const char *msgfmt,...)
virtual const char * FindFile(const char *search, TString &file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition: TSystem.cxx:1512
static Int_t GetErrno()
Static function returning system error number.
Definition: TSystem.cxx:268
Int_t fMode
Definition: TSystem.h:128
TString fHostname
Definition: TSystem.h:267
const char * String
Definition: TXMLSetup.cxx:93
virtual Bool_t Notify()
Notify when signal occurs.
virtual const char * GetDirEntry(void *dirp)
Get a directory entry. Returns 0 if no more entries.
Definition: TSystem.cxx:851
virtual int Unlink(const char *name)
Unlink, i.e. remove, a file.
Definition: TSystem.cxx:1357
Int_t GetFamily() const
Definition: TInetAddress.h:72
Int_t Exec(const char *shellcmd)
Execute a command.
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:2365
void DispatchOneEvent(Bool_t pendingOnly=kFALSE)
Dispatch a single event.
virtual void Sleep(UInt_t milliSec)
Sleep milliSec milli seconds.
Definition: TSystem.cxx:445
Float_t fUser
Definition: TSystem.h:170
void AddSignalHandler(TSignalHandler *sh)
Add a signal handler to list of system signal handlers.
Int_t fSwapFree
Definition: TSystem.h:186
static int UnixSend(int sock, const void *buf, int len, int flag)
Send exactly length bytes from buffer.
const char * PrependPathName(const char *dir, TString &name)
Concatenate a directory and a file name.
Int_t fMaxrfd
Definition: TSystem.h:263
Int_t SetFPEMask(Int_t mask=kDefaultMask)
Set which conditions trigger a floating point exception.
static const char * DynamicPath(const char *newpath=0, Bool_t reset=kFALSE)
Get shared library search path. Static utility function.
TObject * Next()
Return next object in collection.
Int_t fNfd
Signals that were trapped.
Definition: TSystem.h:262
R__EXTERN TFileHandler * gXDisplay
Definition: TSystem.h:541
TString fShell
Definition: TSystem.h:146
static TString * ReadString(TBuffer &b, const TClass *clReq)
Read TString object from buffer.
Definition: TString.cxx:1269
TString fRealName
Definition: TSystem.h:145
static int UnixSetitimer(Long_t ms)
Set interval timer to time-out in ms milliseconds.
virtual const char * Getenv(const char *env)
Get environment variable.
Definition: TSystem.cxx:1638
virtual void ListLibraries(const char *regexp="")
List all loaded shared libraries.
Definition: TSystem.cxx:2059
static void UnixResetSignals()
Restore old signal handlers.
FILE * OpenPipe(const char *shellcmd, const char *mode)
Open a pipe.
TString & Append(const char *cs)
Definition: TString.h:495
virtual const char * PrependPathName(const char *dir, TString &name)
Concatenate a directory and a file name.
Definition: TSystem.cxx:1062
Bool_t EndsWith(const char *pat, ECaseCompare cmp=kExact) const
Return true if string ends with the specified string.
Definition: TString.cxx:2231
TInetAddress GetHostByName(const char *server)
Get Internet Protocol (IP) address of host.
int AcceptConnection(int sock)
Accept a connection.
virtual void Unload(const char *module)
Unload a shared library.
Definition: TSystem.cxx:2038
char * pw_name
Definition: TWinNTSystem.h:48
Long64_t Atoll() const
Return long long value of string.
Definition: TString.cxx:2001
TString fHostname
Definition: TInetAddress.h:52
virtual TInetAddress GetHostByName(const char *server)
Get Internet Protocol (IP) address of host.
Definition: TSystem.cxx:2320
int CopyFile(const char *from, const char *to, Bool_t overwrite=kFALSE)
Copy a file.
void ResetSignals()
Reset signals handlers to previous behaviour.
int SetSockOpt(int sock, int option, int val)
Set socket option.
Bool_t IsSync() const
Int_t fGid
Definition: TSystem.h:130
ELogLevel
Definition: TSystem.h:56
const Int_t kNFDBITS
TSeqCollection * fFileHandler
Definition: TSystem.h:278
A doubly linked list.
Definition: TList.h:44
Float_t fLoad1m
Definition: TSystem.h:167
TString & GetLastErrorString()
Return the thread local storage for the custom last error message.
Definition: TSystem.cxx:2096
static void SigHandler(ESignals sig)
Unix signal handler.
Int_t fL2Cache
Definition: TSystem.h:158
TTimer * RemoveTimer(TTimer *ti)
Remove timer from list of system timers.
virtual Bool_t WriteNotify()
Notify when something can be written to the descriptor associated with this handler.
R__EXTERN const char * gProgName
Definition: TSystem.h:224
Float_t fCpuUser
Definition: TSystem.h:194
ESignals
char * pw_gecos
Definition: TWinNTSystem.h:53
static const char * UnixHomedirectory(const char *user=0)
Returns the user&#39;s home directory.
TString fUser
Definition: TSystem.h:142
static void sighandler(int sig)
Call the signal handler associated with the signal.
int GetProcInfo(ProcInfo_t *info) const
Returns cpu and memory used by this process into the ProcInfo_t structure.
void FreeDirectory(void *dirp)
Close a Unix file system directory.
virtual void Setenv(const char *name, const char *value)
Set environment variable.
Definition: TSystem.cxx:1622
Int_t fCpus
Definition: TSystem.h:155
virtual Bool_t HasWriteInterest()
True if handler is interested in write events.
virtual Bool_t Init()
Initialize the OS interface.
Definition: TSystem.cxx:190
int Chmod(const char *file, UInt_t mode)
Set the file permission bits. Returns -1 in case or error, 0 otherwise.
Bool_t fIsLink
Definition: TSystem.h:133
R__EXTERN TSystem * gSystem
Definition: TSystem.h:540
UInt_t GetAddress() const
Definition: TInetAddress.h:68
int Utime(const char *file, Long_t modtime, Long_t actime)
Set a files modification and access times.
TInetAddress GetSockName(int sock)
Get Internet Protocol (IP) address of host and port #.
Int_t fSwapUsed
Definition: TSystem.h:185
Bool_t Gets(FILE *fp, Bool_t chop=kTRUE)
Read one line from the stream, including the , or until EOF.
Definition: Stringio.cxx:198
const char * kServerPath
Long_t fMemVirtual
Definition: TSystem.h:197
Bool_t BeginsWith(const char *s, ECaseCompare cmp=kExact) const
Definition: TString.h:561
#define HOWMANY(x, y)
Bool_t IsActive() const
virtual void SetReadReady()
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:502
void CloseConnection(int sock, Bool_t force=kFALSE)
Close socket.
std::string GetHomeDirectory(const char *userName=0) const
Return the user&#39;s home directory.
Bool_t IsSync() const
Definition: TTimer.h:80
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition: TString.cxx:2343
void Closelog()
Close connection to system log daemon.
unsigned int UInt_t
Definition: RtypesCore.h:42
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:880
char * Form(const char *fmt,...)
int GetFd() const
Ssiz_t Length() const
Definition: TString.h:386
ESignals GetSignal() const
void SetDisplay()
Set DISPLAY environment variable based on utmp entry. Only for UNIX.
static const char * StripOffProto(const char *path, const char *proto)
Definition: TSystem.h:315
Definition: TSocket.h:52
TSubString Strip(EStripType s=kTrailing, char c=' ') const
Return a substring of self stripped at beginning and/or end.
Definition: TString.cxx:1080
Handles synchronous and a-synchronous timer events.
Definition: TTimer.h:51
Bool_t CheckTimer(const TTime &now)
Check if timer timed out.
Definition: TTimer.cxx:128
Float_t fLoad5m
Definition: TSystem.h:168
std::string GetWorkingDirectory() const
Return working directory.
Bool_t CheckDescriptors()
Check if there is activity on some file descriptors and call their Notify() member.
Func_t DynFindSymbol(const char *module, const char *entry)
dynamic linking of module
static int UnixWaitchild()
Wait till child is finished.
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...
void * OpenDirectory(const char *name)
Open a Unix file system directory. Returns 0 if directory does not exist.
static int UnixUnixService(int port, int backlog)
Open a socket, bind to it and start listening for Unix domain connections to it.
static const char * UnixSigname(ESignals sig)
Return the signal name associated with a signal.
Int_t RedirectOutput(const char *name, const char *mode="a", RedirectHandle_t *h=0)
Redirect standard output (stdout, stderr) to the specified file.
static int UnixFSstat(const char *path, Long_t *id, Long_t *bsize, Long_t *blocks, Long_t *bfree)
Get info about a file system: id, bsize, bfree, blocks.
TString & String()
Definition: TObjString.h:49
const char * GetDynamicPath()
Return the dynamic path (used to find shared libraries).
static constexpr double ms
void AddAlias(const char *alias)
Add alias to list of aliases.
virtual void FreeDirectory(void *dirp)
Free a directory.
Definition: TSystem.cxx:843
virtual int ClosePipe(FILE *pipe)
Close the pipe.
Definition: TSystem.cxx:679
TGraphErrors * gr
Definition: legend1.C:25
Int_t GetUid(const char *user=0)
Returns the user&#39;s id. If user = 0, returns current user&#39;s id.
#define Printf
Definition: TGeoToOCC.h:18
void Unsetenv(const char *name)
Unset environment variable.
UserGroup_t * GetGroupInfo(Int_t gid)
Returns all group info in the UserGroup_t structure.
char * StrDup(const char *str)
Duplicate the string str.
Definition: TString.cxx:2544
#define R__LOCKGUARD2(mutex)
const Bool_t kFALSE
Definition: RtypesCore.h:88
virtual int SetSockOpt(int sock, int kind, int val)
Set socket option.
Definition: TSystem.cxx:2465
static void UnixSignal(ESignals sig, SigHandler_t h)
Set a signal handler for a signal.
static unsigned int total
TString & Remove(Ssiz_t pos)
Definition: TString.h:619
long Long_t
Definition: RtypesCore.h:50
int Ssiz_t
Definition: RtypesCore.h:63
TString fPasswd
Definition: TSystem.h:144
const char * Getenv(const char *name)
Get environment variable.
virtual TSignalHandler * RemoveSignalHandler(TSignalHandler *sh)
Remove a signal handler from list of signal handlers.
Definition: TSystem.cxx:550
static int UnixMakedir(const char *name)
Make a Unix file system directory.
TObjArray * Tokenize(const TString &delim) const
This function is used to isolate sequential tokens in a TString.
Definition: TString.cxx:2251
TFdSet * fReadready
Files that should be checked for write events.
Definition: TSystem.h:259
static int UnixUdpService(int port, int backlog)
Open a socket, bind to it and start listening for UDP connections on the port.
void AddAddress(UInt_t addr)
Add alternative address to list of addresses.
R__EXTERN const char * gProgPath
Definition: TSystem.h:225
TString & Swap(TString &other)
Definition: TString.h:650
#define ClassImp(name)
Definition: Rtypes.h:359
#define STRUCT_UTMP
Float_t fCpuSys
Definition: TSystem.h:195
Int_t GetEffectiveUid()
Returns the effective user id.
static int UnixUnixConnect(int port)
Connect to a Unix domain socket.
virtual Func_t DynFindSymbol(const char *module, const char *entry)
Find specific entry point in specified library.
Definition: TSystem.cxx:2030
static int UnixTcpService(int port, Bool_t reuse, int backlog, int tcpwindowsize)
Open a socket, bind to it and start listening for TCP/IP connections on the port. ...
const Int_t kFDSETSIZE
double Double_t
Definition: RtypesCore.h:55
TFdSet * fReadmask
Definition: TSystem.h:257
int RecvRaw(int sock, void *buffer, int length, int flag)
Receive exactly length bytes into buffer.
int RecvBuf(int sock, void *buffer, int length)
Receive a buffer headed by a length indicator.
ELogFacility
Definition: TSystem.h:67
int Rename(const char *from, const char *to)
Rename a file. Returns 0 when successful, -1 in case of failure.
int AnnounceTcpService(int port, Bool_t reuse, int backlog, int tcpwindowsize=-1)
Announce TCP/IP service.
int type
Definition: TGX11.cxx:120
R__EXTERN TEnv * gEnv
Definition: TEnv.h:171
virtual const char * ExpandFileName(const char *fname)
Expand a pathname getting rid of special shell characters like ~.
Definition: TSystem.cxx:1079
void CheckChilds()
Check if children have finished.
TString fCpuType
Definition: TSystem.h:154
#define free
Definition: civetweb.c:821
unsigned long ULong_t
Definition: RtypesCore.h:51
static const TString & GetEtcDir()
Get the sysconfig directory in the installation. Static utility function.
Definition: TROOT.cxx:2905
char ** Argv() const
Definition: TApplication.h:136
static void UnixIgnoreSignal(ESignals sig, Bool_t ignore)
If ignore is true ignore the specified signal, else restore previous behaviour.
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:570
TFdSet * fSignals
Files with writes waiting.
Definition: TSystem.h:261
static constexpr double s
static void * UnixOpendir(const char *name)
Open a directory.
Definition: TSocket.h:51
EAccessMode
Definition: TSystem.h:44
void Reset()
Definition: TSystem.h:213
Bool_t ChangeDirectory(const char *path)
Change directory. Returns kTRUE in case of success, kFALSE otherwise.
const char * GetLinkedLibraries()
Get list of shared libraries loaded at the start of the executable.
Bool_t IsNull() const
Definition: TString.h:383
char * GetServiceByPort(int port)
Get name of internet service.
Binding & operator=(OUT(*fun)(void))
Int_t fMemTotal
Definition: TSystem.h:181
int pw_gid
Definition: TWinNTSystem.h:51
#define org(otri, vertexptr)
Definition: triangle.c:1037
int EscChar(const char *src, char *dst, int dstlen, char *specchars, char escchar)
Escape specchars in src with escchar and copy to dst.
Definition: TString.cxx:2579
Bool_t IsValid() const
Definition: TInetAddress.h:76
virtual void HandleException(Int_t sig)
Handle exceptions (kSigBus, kSigSegmentationViolation, kSigIllegalInstruction and kSigFloatingExcepti...
typedef void((*Func_t)())
Int_t fMaxwfd
Definition: TSystem.h:264
TSeqCollection * fTimers
Definition: TSystem.h:276
void ResetSignal(ESignals sig, Bool_t reset=kTRUE)
If reset is true reset the signal handler for the specified signal to the default handler...
void IgnoreSignal(ESignals sig, Bool_t ignore=kTRUE)
If ignore is true ignore the specified signal, else restore previous behaviour.
static const TString & GetLibDir()
Get the library directory in the installation. Static utility function.
Definition: TROOT.cxx:2863
virtual void AddTimer(TTimer *t)
Add timer to list of system timers.
Definition: TSystem.cxx:479
static const char * UnixGetdirentry(void *dir)
Returns the next directory entry.
Definition: file.py:1
R__EXTERN const char * gRootDir
Definition: TSystem.h:223
void ResetTimer(TTimer *ti)
Reset a-sync timer.
void AddDynamicPath(const char *lib)
Add a new directory to the dynamic path.
Short_t Max(Short_t a, Short_t b)
Definition: TMathBase.h:200
const char * GetDirEntry(void *dirp)
Get next Unix file system directory entry. Returns 0 if no more entries.
Int_t fMemUsed
Definition: TSystem.h:182
you should not use this method at all Int_t Int_t Double_t Double_t Double_t Int_t Double_t Double_t Double_t Double_t b
Definition: TRolke.cxx:630
Int_t fCpuSpeed
Definition: TSystem.h:156
TInetAddress GetPeerName(int sock)
Get Internet Protocol (IP) address of remote host and port #.
void AddFileHandler(TFileHandler *fh)
Add a file handler to the list of system file handlers.
Long_t fIno
Definition: TSystem.h:127
#define snprintf
Definition: civetweb.c:822
FILE * TempFileName(TString &base, const char *dir=0)
Create a secure temporary file by appending a unique 6 letter string to base.
char * pw_passwd
Definition: TWinNTSystem.h:49
char * pw_dir
Definition: TWinNTSystem.h:54
virtual void * OpenDirectory(const char *name)
Open a directory. Returns 0 if directory does not exist.
Definition: TSystem.cxx:834
R__EXTERN Int_t gDebug
Definition: Rtypes.h:86
Iterator of ordered collection.
TSignalHandler * RemoveSignalHandler(TSignalHandler *sh)
Remove a signal handler from list of signal handlers.
Int_t Atoi() const
Return integer value of string.
Definition: TString.cxx:1975
int AnnounceUnixService(int port, int backlog)
Announce unix domain service on path "kServerPath/<port>".
virtual Bool_t ReadNotify()
Notify when something can be read from the descriptor associated with this handler.
int ClosePipe(FILE *pipe)
Close the pipe.
void SetDynamicPath(const char *lib)
Set the dynamic path to a new value.
int Link(const char *from, const char *to)
Create a link from file1 to file2.
void Abort(int code=0)
Abort the application.
void Unload(const char *module)
Unload a shared library.
TSystem * FindHelper(const char *path, void *dirptr=0)
Create helper TSystem to handle file and directory operations that might be special for remote file a...
Definition: TSystem.cxx:752
virtual void AddFileHandler(TFileHandler *fh)
Add a file handler to the list of system file handlers.
Definition: TSystem.cxx:562
static void ResetErrno()
Static function resetting system error number.
Definition: TSystem.cxx:284
void SigAlarmInterruptsSyscalls(Bool_t set)
When the argument is true the SIGALRM signal handler is set so that interrupted syscalls will not be ...
Int_t GetEffectiveGid()
Returns the effective group id.
Float_t fTotal
Definition: TSystem.h:172
Bool_t CheckSignals(Bool_t sync)
Check if some signals were raised and call their Notify() member.
static int UnixUdpConnect(const char *hostname, int port)
Creates a UDP socket connection Is called via the TSocket constructor.
int GetServiceByName(const char *service)
Get port # of internet service.
AddressList_t fAddresses
Definition: TInetAddress.h:55
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition: TSystem.cxx:1254
TTime Now()
Get current time in milliseconds since 0:00 Jan 1 1995.
TFdSet * fWriteready
Files with reads waiting.
Definition: TSystem.h:260
Int_t fSwapTotal
Definition: TSystem.h:184
void Openlog(const char *name, Int_t options, ELogFacility facility)
Open connection to system log daemon.
R__EXTERN TInterpreter * gCling
Definition: TInterpreter.h:528
Long_t fDev
Definition: TSystem.h:126
virtual const char * GetName() const
Returns name of object.
Definition: TObject.cxx:357
virtual Int_t GetSize() const
Definition: TCollection.h:180
UserGroup_t * GetUserInfo(Int_t uid)
Returns all user info in the UserGroup_t structure.
Abstract base class defining a generic interface to the underlying Operating System.
Definition: TSystem.h:248
float * q
Definition: THbookFile.cxx:87
Int_t fStdErrDup
Definition: TSystem.h:209
Ordered collection.
void DispatchSignals(ESignals sig)
Handle and dispatch signals.
int SendBuf(int sock, const void *buffer, int length)
Send a buffer headed by a length indicator.
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition: TEnv.cxx:491
TFdSet * fWritemask
Files that should be checked for read events.
Definition: TSystem.h:258
const Bool_t kTRUE
Definition: RtypesCore.h:87
virtual char * ConcatFileName(const char *dir, const char *name)
Concatenate a directory and a file name. User must delete returned string.
Definition: TSystem.cxx:1052
#define sym(otri1, otri2)
Definition: triangle.c:932
Bool_t IsAsync() const
Definition: TTimer.h:81
void ListLibraries(const char *regexp="")
List all loaded shared libraries.
Float_t fIdle
Definition: TSystem.h:173
const char * WorkingDirectory()
Return working directory.
const Int_t n
Definition: legend1.C:16
TString fFile
Definition: TSystem.h:205
int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
char name[80]
Definition: TGX11.cxx:109
Long_t fMemResident
Definition: TSystem.h:196
const char * cnt
Definition: TXMLSetup.cxx:74
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:866
void Setenv(const char *name, const char *value)
Set environment variable.
int OpenConnection(const char *server, int port, int tcpwindowsize=-1, const char *protocol="tcp")
Open a connection to a service on a server.
virtual Bool_t HasReadInterest()
True if handler is interested in read events.
const char * Data() const
Definition: TString.h:345
int AnnounceUdpService(int port, int backlog)
Announce UDP service.
int GetMemInfo(MemInfo_t *info) const
Returns ram and swap memory usage info into the MemInfo_t structure.