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