ROOT  6.06/04
Reference Guide
TWinNTSystem.cxx
Go to the documentation of this file.
1 // @(#)root/winnt:$Id: db9b3139b1551a1b4e31a17f57866a276d5cd419 $
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 // TWinNTSystem //
15 // //
16 // Class providing an interface to the Windows NT/Windows 95 Operating Systems. //
17 // //
18 //////////////////////////////////////////////////////////////////////////////////
19 
20 
21 #ifdef HAVE_CONFIG
22 #include "config.h"
23 #endif
24 
25 #include "Windows4Root.h"
26 #include "TWinNTSystem.h"
27 #include "TROOT.h"
28 #include "TError.h"
29 #include "TOrdCollection.h"
30 #include "TRegexp.h"
31 #include "TException.h"
32 #include "TEnv.h"
33 #include "TSocket.h"
34 #include "TApplication.h"
35 #include "TWin32SplashThread.h"
36 #include "Win32Constants.h"
37 #include "TInterpreter.h"
38 #include "TObjString.h"
39 #include "TVirtualX.h"
40 #include "TUrl.h"
41 
42 #include <sys/utime.h>
43 #include <sys/timeb.h>
44 #include <process.h>
45 #include <io.h>
46 #include <direct.h>
47 #include <ctype.h>
48 #include <float.h>
49 #include <sys/stat.h>
50 #include <signal.h>
51 #include <stdio.h>
52 #include <errno.h>
53 #include <lm.h>
54 #include <dbghelp.h>
55 #include <Tlhelp32.h>
56 #include <sstream>
57 #include <iostream>
58 #include <list>
59 #include <shlobj.h>
60 #include <conio.h>
61 
62 #if defined (_MSC_VER) && (_MSC_VER >= 1400)
63  #include <intrin.h>
64 #elif defined (_M_IX86)
65  static void __cpuid(int* cpuid_data, int info_type)
66  {
67  __asm {
68  push ebx
69  push edi
70  mov edi, cpuid_data
71  mov eax, info_type
72  cpuid
73  mov [edi], eax
74  mov [edi + 4], ebx
75  mov [edi + 8], ecx
76  mov [edi + 12], edx
77  pop edi
78  pop ebx
79  }
80  }
81  __int64 __rdtsc()
82  {
83  LARGE_INTEGER li;
84  __asm {
85  rdtsc
86  mov li.LowPart, eax
87  mov li.HighPart, edx
88  }
89  return li.QuadPart;
90  }
91 #else
92  static void __cpuid(int* cpuid_data, int) {
93  cpuid_data[0] = 0x00000000;
94  cpuid_data[1] = 0x00000000;
95  cpuid_data[2] = 0x00000000;
96  cpuid_data[3] = 0x00000000;
97  }
98  __int64 __rdtsc() { return (__int64)0; }
99 #endif
100 
101 extern "C" {
102  extern void Gl_setwidth(int width);
103  void *_ReturnAddress(void);
104 }
105 
106 //////////////////// Windows TFdSet ////////////////////////////////////////////////
107 class TFdSet {
108 private:
109  fd_set *fds_bits; // file descriptors (according MSDN maximum is 64)
110 public:
111  TFdSet() { fds_bits = new fd_set; fds_bits->fd_count = 0; }
112  virtual ~TFdSet() { delete fds_bits; }
113  void Copy(TFdSet &fd) const { memcpy((void*)fd.fds_bits, fds_bits, sizeof(fd_set)); }
114  TFdSet(const TFdSet& fd) { fd.Copy(*this); }
115  TFdSet& operator=(const TFdSet& fd) { fd.Copy(*this); return *this; }
116  void Zero() { fds_bits->fd_count = 0; }
117  void Set(Int_t fd)
118  {
119  if (fds_bits->fd_count < FD_SETSIZE-1) // protect out of bound access (64)
120  fds_bits->fd_array[fds_bits->fd_count++] = (SOCKET)fd;
121  else
122  ::SysError("TFdSet::Set", "fd_count will exeed FD_SETSIZE");
123  }
124  void Clr(Int_t fd)
125  {
126  int i;
127  for (i=0; i<fds_bits->fd_count; i++) {
128  if (fds_bits->fd_array[i]==(SOCKET)fd) {
129  while (i<fds_bits->fd_count-1) {
130  fds_bits->fd_array[i] = fds_bits->fd_array[i+1];
131  i++;
132  }
133  fds_bits->fd_count--;
134  break;
135  }
136  }
137  }
138  Int_t IsSet(Int_t fd) { return __WSAFDIsSet((SOCKET)fd, fds_bits); }
139  Int_t *GetBits() { return fds_bits && fds_bits->fd_count ? (Int_t*)fds_bits : 0; }
140  UInt_t GetCount() { return (UInt_t)fds_bits->fd_count; }
141  Int_t GetFd(Int_t i) { return i<fds_bits->fd_count ? fds_bits->fd_array[i] : 0; }
142 };
143 
144 namespace {
145  const char *kProtocolName = "tcp";
146  typedef void (*SigHandler_t)(ESignals);
147  static TWinNTSystem::ThreadMsgFunc_t gGUIThreadMsgFunc = 0; // GUI thread message handler func
148 
149  static HANDLE gGlobalEvent;
150  static HANDLE gTimerThreadHandle;
151  typedef NET_API_STATUS (WINAPI *pfn1)(LPVOID);
152  typedef NET_API_STATUS (WINAPI *pfn2)(LPCWSTR, LPCWSTR, DWORD, LPBYTE*);
153  typedef NET_API_STATUS (WINAPI *pfn3)(LPCWSTR, LPCWSTR, DWORD, LPBYTE*,
154  DWORD, LPDWORD, LPDWORD, PDWORD);
155  typedef NET_API_STATUS (WINAPI *pfn4)(LPCWSTR, DWORD, LPBYTE*, DWORD, LPDWORD,
156  LPDWORD, PDWORD);
157  static pfn1 p2NetApiBufferFree;
158  static pfn2 p2NetUserGetInfo;
159  static pfn3 p2NetLocalGroupGetMembers;
160  static pfn4 p2NetLocalGroupEnum;
161 
162  static struct signal_map {
163  int code;
164  SigHandler_t handler;
165  char *signame;
166  } signal_map[kMAXSIGNALS] = { // the order of the signals should be identical
167  -1 /*SIGBUS*/, 0, "bus error", // to the one in SysEvtHandler.h
168  SIGSEGV, 0, "segmentation violation",
169  -1 /*SIGSYS*/, 0, "bad argument to system call",
170  -1 /*SIGPIPE*/, 0, "write on a pipe with no one to read it",
171  SIGILL, 0, "illegal instruction",
172  -1 /*SIGQUIT*/, 0, "quit",
173  SIGINT, 0, "interrupt",
174  -1 /*SIGWINCH*/, 0, "window size change",
175  -1 /*SIGALRM*/, 0, "alarm clock",
176  -1 /*SIGCHLD*/, 0, "death of a child",
177  -1 /*SIGURG*/, 0, "urgent data arrived on an I/O channel",
178  SIGFPE, 0, "floating point exception",
179  SIGTERM, 0, "termination signal",
180  -1 /*SIGUSR1*/, 0, "user-defined signal 1",
181  -1 /*SIGUSR2*/, 0, "user-defined signal 2"
182  };
183 
184  ////// static functions providing interface to raw WinNT ////////////////////
185 
186  //---- RPC -------------------------------------------------------------------
187  //*-* Error codes set by the Windows Sockets implementation are not made available
188  //*-* via the errno variable. Additionally, for the getXbyY class of functions,
189  //*-* error codes are NOT made available via the h_errno variable. Instead, error
190  //*-* codes are accessed by using the WSAGetLastError . This function is provided
191  //*-* in Windows Sockets as a precursor (and eventually an alias) for the Win32
192  //*-* function GetLastError. This is intended to provide a reliable way for a thread
193  //*-* in a multithreaded process to obtain per-thread error information.
194 
195  /////////////////////////////////////////////////////////////////////////////
196  /// Receive exactly length bytes into buffer. Returns number of bytes
197  /// received. Returns -1 in case of error, -2 in case of MSG_OOB
198  /// and errno == EWOULDBLOCK, -3 in case of MSG_OOB and errno == EINVAL
199  /// and -4 in case of kNonBlock and errno == EWOULDBLOCK.
200  /// Returns -5 if pipe broken or reset by peer (EPIPE || ECONNRESET).
201 
202  static int WinNTRecv(int socket, void *buffer, int length, int flag)
203  {
204  if (socket == -1) return -1;
205  SOCKET sock = socket;
206 
207  int once = 0;
208  if (flag == -1) {
209  flag = 0;
210  once = 1;
211  }
212  if (flag == MSG_PEEK) {
213  once = 1;
214  }
215 
216  int nrecv, n;
217  char *buf = (char *)buffer;
218 
219  for (n = 0; n < length; n += nrecv) {
220  if ((nrecv = ::recv(sock, buf+n, length-n, flag)) <= 0) {
221  if (nrecv == 0) {
222  break; // EOF
223  }
224  if (flag == MSG_OOB) {
225  if (::WSAGetLastError() == WSAEWOULDBLOCK) {
226  return -2;
227  } else if (::WSAGetLastError() == WSAEINVAL) {
228  return -3;
229  }
230  }
231  if (::WSAGetLastError() == WSAEWOULDBLOCK) {
232  return -4;
233  } else {
234  if (::WSAGetLastError() != WSAEINTR)
235  ::SysError("TWinNTSystem::WinNTRecv", "recv");
236  if (::WSAGetLastError() == EPIPE ||
237  ::WSAGetLastError() == WSAECONNRESET)
238  return -5;
239  else
240  return -1;
241  }
242  }
243  if (once) {
244  return nrecv;
245  }
246  }
247  return n;
248  }
249 
250  /////////////////////////////////////////////////////////////////////////////
251  /// Send exactly length bytes from buffer. Returns -1 in case of error,
252  /// otherwise number of sent bytes. Returns -4 in case of kNoBlock and
253  /// errno == EWOULDBLOCK. Returns -5 if pipe broken or reset by peer
254  /// (EPIPE || ECONNRESET).
255 
256  static int WinNTSend(int socket, const void *buffer, int length, int flag)
257  {
258  if (socket < 0) return -1;
259  SOCKET sock = socket;
260 
261  int once = 0;
262  if (flag == -1) {
263  flag = 0;
264  once = 1;
265  }
266 
267  int nsent, n;
268  const char *buf = (const char *)buffer;
269 
270  for (n = 0; n < length; n += nsent) {
271  if ((nsent = ::send(sock, buf+n, length-n, flag)) <= 0) {
272  if (nsent == 0) {
273  break;
274  }
275  if (::WSAGetLastError() == WSAEWOULDBLOCK) {
276  return -4;
277  } else {
278  if (::WSAGetLastError() != WSAEINTR)
279  ::SysError("TWinNTSystem::WinNTSend", "send");
280  if (::WSAGetLastError() == EPIPE ||
281  ::WSAGetLastError() == WSAECONNRESET)
282  return -5;
283  else
284  return -1;
285  }
286  }
287  if (once) {
288  return nsent;
289  }
290  }
291  return n;
292  }
293 
294  /////////////////////////////////////////////////////////////////////////////
295  /// Wait for events on the file descriptors specified in the readready and
296  /// writeready masks or for timeout (in milliseconds) to occur.
297 
298  static int WinNTSelect(TFdSet *readready, TFdSet *writeready, Long_t timeout)
299  {
300  int retcode;
301  fd_set* rbits = readready ? (fd_set*)readready->GetBits() : 0;
302  fd_set* wbits = writeready ? (fd_set*)writeready->GetBits() : 0;
303 
304  if (timeout >= 0) {
305  timeval tv;
306  tv.tv_sec = timeout / 1000;
307  tv.tv_usec = (timeout % 1000) * 1000;
308 
309  retcode = ::select(0, rbits, wbits, 0, &tv);
310  } else {
311  retcode = ::select(0, rbits, wbits, 0, 0);
312  }
313 
314  if (retcode == SOCKET_ERROR) {
315  int errcode = ::WSAGetLastError();
316 
317  // if file descriptor is not a socket, assume it is the pipe used
318  // by TXSocket
319  if (errcode == WSAENOTSOCK) {
320  struct __stat64 buf;
321  int result = _fstat64( readready->GetFd(0), &buf );
322  if ( result == 0 ) {
323  if (buf.st_size > 0)
324  return 1;
325  }
326  // yield execution to another thread that is ready to run
327  // if no other thread is ready, sleep 1 ms before to return
328  if (gGlobalEvent) {
329  ::WaitForSingleObject(gGlobalEvent, 1);
330  ::ResetEvent(gGlobalEvent);
331  }
332  return 0;
333  }
334 
335  if ( errcode == WSAEINTR) {
336  TSystem::ResetErrno(); // errno is not self reseting
337  return -2;
338  }
339  if (errcode == EBADF) {
340  return -3;
341  }
342  return -1;
343  }
344  return retcode;
345  }
346 
347  /////////////////////////////////////////////////////////////////////////////
348  /// Get shared library search path.
349 
350  static const char *DynamicPath(const char *newpath = 0, Bool_t reset = kFALSE)
351  {
352  static TString dynpath;
353 
354  if (reset || newpath) {
355  dynpath = "";
356  }
357  if (newpath) {
358 
359  dynpath = newpath;
360 
361  } else if (dynpath == "") {
362  TString rdynpath = gEnv ? gEnv->GetValue("Root.DynamicPath", (char*)0) : "";
363  rdynpath.ReplaceAll("; ", ";"); // in case DynamicPath was extended
364  if (rdynpath == "") {
365  rdynpath = ".;"; rdynpath += TROOT::GetBinDir();
366  }
367  TString path = gSystem->Getenv("PATH");
368  if (path == "")
369  dynpath = rdynpath;
370  else {
371  dynpath = path; dynpath += ";"; dynpath += rdynpath;
372  }
373 
374  }
375 
376  if (!dynpath.Contains(TROOT::GetLibDir())) {
377  dynpath += ";"; dynpath += TROOT::GetLibDir();
378  }
379 
380  return dynpath;
381  }
382 
383  /////////////////////////////////////////////////////////////////////////////
384  /// Call the signal handler associated with the signal.
385 
386  static void sighandler(int sig)
387  {
388  for (int i = 0; i < kMAXSIGNALS; i++) {
389  if (signal_map[i].code == sig) {
390  (*signal_map[i].handler)((ESignals)i);
391  return;
392  }
393  }
394  }
395 
396  /////////////////////////////////////////////////////////////////////////////
397  /// Set a signal handler for a signal.
398 
399  static void WinNTSignal(ESignals sig, SigHandler_t handler)
400  {
401  signal_map[sig].handler = handler;
402  if (signal_map[sig].code != -1)
403  (SigHandler_t)signal(signal_map[sig].code, sighandler);
404  }
405 
406  /////////////////////////////////////////////////////////////////////////////
407  /// Return the signal name associated with a signal.
408 
409  static char *WinNTSigname(ESignals sig)
410  {
411  return signal_map[sig].signame;
412  }
413 
414  /////////////////////////////////////////////////////////////////////////////
415  /// WinNT signal handler.
416 
417  static BOOL ConsoleSigHandler(DWORD sig)
418  {
419  switch (sig) {
420  case CTRL_C_EVENT:
421  if (gSystem) {
422  ((TWinNTSystem*)gSystem)->DispatchSignals(kSigInterrupt);
423  }
424  else {
425  Break("TInterruptHandler::Notify", "keyboard interrupt");
426  if (TROOT::Initialized()) {
427  gInterpreter->RewindDictionary();
428  }
429  }
430  return kTRUE;
431  case CTRL_BREAK_EVENT:
432  case CTRL_LOGOFF_EVENT:
433  case CTRL_SHUTDOWN_EVENT:
434  case CTRL_CLOSE_EVENT:
435  default:
436  printf("\n *** Break *** keyboard interrupt - ROOT is terminated\n");
437  gSystem->Exit(-1);
438  return kTRUE;
439  }
440  }
441 
442  static CONTEXT *fgXcptContext = 0;
443  /////////////////////////////////////////////////////////////////////////////
444 
445  static void SigHandler(ESignals sig)
446  {
447  if (gSystem)
448  ((TWinNTSystem*)gSystem)->DispatchSignals(sig);
449  }
450 
451  /////////////////////////////////////////////////////////////////////////////
452  /// Function that's called when an unhandled exception occurs.
453  /// Produces a stack trace, and lets the system deal with it
454  /// as if it was an unhandled excecption (usually ::abort)
455 
456  LONG WINAPI ExceptionFilter(LPEXCEPTION_POINTERS pXcp)
457  {
458  fgXcptContext = pXcp->ContextRecord;
459  gSystem->StackTrace();
460  return EXCEPTION_CONTINUE_SEARCH;
461  }
462 
463 
464 #pragma intrinsic(_ReturnAddress)
465 #pragma auto_inline(off)
466  DWORD_PTR GetProgramCounter()
467  {
468  // Returns the current program counter.
469  return (DWORD_PTR)_ReturnAddress();
470  }
471 #pragma auto_inline(on)
472 
473  /////////////////////////////////////////////////////////////////////////////
474  /// Message processing loop for the TGWin32 related GUI
475  /// thread for processing windows messages (aka Main/Server thread).
476  /// We need to start the thread outside the TGWin32 / GUI related
477  /// dll, because starting threads at DLL init time does not work.
478  /// Instead, we start an ideling thread at binary startup, and only
479  /// call the "real" message processing function
480  /// TGWin32::GUIThreadMessageFunc() once gVirtualX comes up.
481 
482  static DWORD WINAPI GUIThreadMessageProcessingLoop(void *p)
483  {
484  MSG msg;
485 
486  // force to create message queue
487  ::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
488 
489  Int_t erret = 0;
490  Bool_t endLoop = kFALSE;
491  while (!endLoop) {
492  if (gGlobalEvent) ::SetEvent(gGlobalEvent);
493  erret = ::GetMessage(&msg, NULL, NULL, NULL);
494  if (erret <= 0) endLoop = kTRUE;
495  if (gGUIThreadMsgFunc)
496  endLoop = (*gGUIThreadMsgFunc)(&msg);
497  }
498 
499  gVirtualX->CloseDisplay();
500 
501  // exit thread
502  if (erret == -1) {
503  erret = ::GetLastError();
504  Error("MsgLoop", "Error in GetMessage");
505  ::ExitThread(-1);
506  } else {
507  ::ExitThread(0);
508  }
509  return 0;
510  }
511 
512  //=========================================================================
513  // Load IMAGEHLP.DLL and get the address of functions in it that we'll use
514  // by Microsoft, from http://www.microsoft.com/msj/0597/hoodtextfigs.htm#fig1
515  //=========================================================================
516  // Make typedefs for some IMAGEHLP.DLL functions so that we can use them
517  // with GetProcAddress
518  typedef BOOL (__stdcall *SYMINITIALIZEPROC)( HANDLE, LPSTR, BOOL );
519  typedef BOOL (__stdcall *SYMCLEANUPPROC)( HANDLE );
520  typedef BOOL (__stdcall *STACKWALK64PROC)
521  ( DWORD, HANDLE, HANDLE, LPSTACKFRAME64, LPVOID,
522  PREAD_PROCESS_MEMORY_ROUTINE,PFUNCTION_TABLE_ACCESS_ROUTINE,
523  PGET_MODULE_BASE_ROUTINE, PTRANSLATE_ADDRESS_ROUTINE );
524  typedef LPVOID (__stdcall *SYMFUNCTIONTABLEACCESS64PROC)( HANDLE, DWORD64 );
525  typedef DWORD (__stdcall *SYMGETMODULEBASE64PROC)( HANDLE, DWORD64 );
526  typedef BOOL (__stdcall *SYMGETMODULEINFO64PROC)(HANDLE, DWORD64, PIMAGEHLP_MODULE64);
527  typedef BOOL (__stdcall *SYMGETSYMFROMADDR64PROC)( HANDLE, DWORD64, PDWORD64, PIMAGEHLP_SYMBOL64);
528  typedef BOOL (__stdcall *SYMGETLINEFROMADDR64PROC)(HANDLE, DWORD64, PDWORD, PIMAGEHLP_LINE64);
529  typedef DWORD (__stdcall *UNDECORATESYMBOLNAMEPROC)(PCSTR, PSTR, DWORD, DWORD);
530 
531 
532  static SYMINITIALIZEPROC _SymInitialize = 0;
533  static SYMCLEANUPPROC _SymCleanup = 0;
534  static STACKWALK64PROC _StackWalk64 = 0;
535  static SYMFUNCTIONTABLEACCESS64PROC _SymFunctionTableAccess64 = 0;
536  static SYMGETMODULEBASE64PROC _SymGetModuleBase64 = 0;
537  static SYMGETMODULEINFO64PROC _SymGetModuleInfo64 = 0;
538  static SYMGETSYMFROMADDR64PROC _SymGetSymFromAddr64 = 0;
539  static SYMGETLINEFROMADDR64PROC _SymGetLineFromAddr64 = 0;
540  static UNDECORATESYMBOLNAMEPROC _UnDecorateSymbolName = 0;
541 
542  BOOL InitImagehlpFunctions()
543  {
544  // Fetches function addresses from IMAGEHLP.DLL at run-time, so we
545  // don't need to link against its import library. These functions
546  // are used in StackTrace; if they cannot be found (e.g. because
547  // IMAGEHLP.DLL doesn't exist or has the wrong version) we cannot
548  // produce a stack trace.
549 
550  HMODULE hModImagehlp = LoadLibrary( "IMAGEHLP.DLL" );
551  if (!hModImagehlp)
552  return FALSE;
553 
554  _SymInitialize = (SYMINITIALIZEPROC) GetProcAddress( hModImagehlp, "SymInitialize" );
555  if (!_SymInitialize)
556  return FALSE;
557 
558  _SymCleanup = (SYMCLEANUPPROC) GetProcAddress( hModImagehlp, "SymCleanup" );
559  if (!_SymCleanup)
560  return FALSE;
561 
562  _StackWalk64 = (STACKWALK64PROC) GetProcAddress( hModImagehlp, "StackWalk64" );
563  if (!_StackWalk64)
564  return FALSE;
565 
566  _SymFunctionTableAccess64 = (SYMFUNCTIONTABLEACCESS64PROC) GetProcAddress(hModImagehlp, "SymFunctionTableAccess64" );
567  if (!_SymFunctionTableAccess64)
568  return FALSE;
569 
570  _SymGetModuleBase64=(SYMGETMODULEBASE64PROC)GetProcAddress(hModImagehlp, "SymGetModuleBase64");
571  if (!_SymGetModuleBase64)
572  return FALSE;
573 
574  _SymGetModuleInfo64=(SYMGETMODULEINFO64PROC)GetProcAddress(hModImagehlp, "SymGetModuleInfo64");
575  if (!_SymGetModuleInfo64)
576  return FALSE;
577 
578  _SymGetSymFromAddr64=(SYMGETSYMFROMADDR64PROC)GetProcAddress(hModImagehlp, "SymGetSymFromAddr64");
579  if (!_SymGetSymFromAddr64)
580  return FALSE;
581 
582  _SymGetLineFromAddr64=(SYMGETLINEFROMADDR64PROC)GetProcAddress(hModImagehlp, "SymGetLineFromAddr64");
583  if (!_SymGetLineFromAddr64)
584  return FALSE;
585 
586  _UnDecorateSymbolName=(UNDECORATESYMBOLNAMEPROC)GetProcAddress(hModImagehlp, "UnDecorateSymbolName");
587  if (!_UnDecorateSymbolName)
588  return FALSE;
589 
590  if (!_SymInitialize(GetCurrentProcess(), 0, TRUE ))
591  return FALSE;
592 
593  return TRUE;
594  }
595 
596  // stack trace helpers getModuleName, getFunctionName by
597  /**************************************************************************
598  * VRS - The Virtual Rendering System
599  * Copyright (C) 2000-2004 Computer Graphics Systems Group at the
600  * Hasso-Plattner-Institute (HPI), Potsdam, Germany.
601  * This library is free software; you can redistribute it and/or modify it
602  * under the terms of the GNU Lesser General Public License as published by
603  * the Free Software Foundation; either version 2.1 of the License, or
604  * (at your option) any later version.
605  ***************************************************************************/
606  std::string GetModuleName(DWORD64 address)
607  {
608  // Return the name of the module that contains the function at address.
609  // Used by StackTrace.
610  std::ostringstream out;
611  HANDLE process = ::GetCurrentProcess();
612 
613  DWORD lineDisplacement = 0;
614  IMAGEHLP_LINE64 line;
615  ::ZeroMemory(&line, sizeof(line));
616  line.SizeOfStruct = sizeof(line);
617  if(_SymGetLineFromAddr64(process, address, &lineDisplacement, &line)) {
618  out << line.FileName << "(" << line.LineNumber << "): ";
619  } else {
620  IMAGEHLP_MODULE64 module;
621  ::ZeroMemory(&module, sizeof(module));
622  module.SizeOfStruct = sizeof(module);
623  if(_SymGetModuleInfo64(process, address, &module)) {
624  out << module.ModuleName << "!";
625  } else {
626  out << "0x" << std::hex << address << std::dec << " ";
627  }
628  }
629 
630  return out.str();
631  }
632 
633  std::string GetFunctionName(DWORD64 address)
634  {
635  // Return the name of the function at address.
636  // Used by StackTrace.
637  DWORD64 symbolDisplacement = 0;
638  HANDLE process = ::GetCurrentProcess();
639 
640  const unsigned int SYMBOL_BUFFER_SIZE = 8192;
641  char symbolBuffer[SYMBOL_BUFFER_SIZE];
642  PIMAGEHLP_SYMBOL64 symbol = reinterpret_cast<PIMAGEHLP_SYMBOL64>(symbolBuffer);
643  ::ZeroMemory(symbol, SYMBOL_BUFFER_SIZE);
644  symbol->SizeOfStruct = SYMBOL_BUFFER_SIZE;
645  symbol->MaxNameLength = SYMBOL_BUFFER_SIZE - sizeof(IMAGEHLP_SYMBOL64);
646 
647  if(_SymGetSymFromAddr64(process, address, &symbolDisplacement, symbol)) {
648  // Make the symbol readable for humans
649  const unsigned int NAME_SIZE = 8192;
650  char name[NAME_SIZE];
651  _UnDecorateSymbolName(
652  symbol->Name,
653  name,
654  NAME_SIZE,
655  UNDNAME_COMPLETE |
656  UNDNAME_NO_THISTYPE |
657  UNDNAME_NO_SPECIAL_SYMS |
658  UNDNAME_NO_MEMBER_TYPE |
659  UNDNAME_NO_MS_KEYWORDS |
660  UNDNAME_NO_ACCESS_SPECIFIERS
661  );
662 
663  std::string result;
664  result += name;
665  result += "()";
666  return result;
667  } else {
668  return "??";
669  }
670  }
671 
672  ////// Shortcuts helper functions IsShortcut and ResolveShortCut ///////////
673 
674  /////////////////////////////////////////////////////////////////////////////
675  /// Validates if a file name has extension '.lnk'. Returns true if file
676  /// name have extension same as Window's shortcut file (.lnk).
677 
678  static BOOL IsShortcut(const char *filename)
679  {
680  //File extension for the Window's shortcuts (.lnk)
681  const char *extLnk = ".lnk";
682  if (filename != NULL) {
683  //Validate extension
684  TString strfilename(filename);
685  if (strfilename.EndsWith(extLnk))
686  return TRUE;
687  }
688  return FALSE;
689  }
690 
691  /////////////////////////////////////////////////////////////////////////////
692  /// Resolve a ShellLink (i.e. c:\path\shortcut.lnk) to a real path.
693 
694  static BOOL ResolveShortCut(LPCSTR pszShortcutFile, char *pszPath, int maxbuf)
695  {
696  HRESULT hres;
697  IShellLink* psl;
698  char szGotPath[MAX_PATH];
699  WIN32_FIND_DATA wfd;
700 
701  *pszPath = 0; // assume failure
702 
703  // Make typedefs for some ole32.dll functions so that we can use them
704  // with GetProcAddress
705  typedef HRESULT (__stdcall *COINITIALIZEPROC)( LPVOID );
706  static COINITIALIZEPROC _CoInitialize = 0;
707  typedef void (__stdcall *COUNINITIALIZEPROC)( void );
708  static COUNINITIALIZEPROC _CoUninitialize = 0;
709  typedef HRESULT (__stdcall *COCREATEINSTANCEPROC)( REFCLSID, LPUNKNOWN,
710  DWORD, REFIID, LPVOID );
711  static COCREATEINSTANCEPROC _CoCreateInstance = 0;
712 
713  HMODULE hModImagehlp = LoadLibrary( "ole32.dll" );
714  if (!hModImagehlp)
715  return FALSE;
716 
717  _CoInitialize = (COINITIALIZEPROC) GetProcAddress( hModImagehlp, "CoInitialize" );
718  if (!_CoInitialize)
719  return FALSE;
720  _CoUninitialize = (COUNINITIALIZEPROC) GetProcAddress( hModImagehlp, "CoUninitialize");
721  if (!_CoUninitialize)
722  return FALSE;
723  _CoCreateInstance = (COCREATEINSTANCEPROC) GetProcAddress( hModImagehlp, "CoCreateInstance" );
724  if (!_CoCreateInstance)
725  return FALSE;
726 
727  _CoInitialize(NULL);
728 
729  hres = _CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
730  IID_IShellLink, (void **) &psl);
731  if (SUCCEEDED(hres)) {
732  IPersistFile* ppf;
733 
734  hres = psl->QueryInterface(IID_IPersistFile, (void **) &ppf);
735  if (SUCCEEDED(hres)) {
736  WCHAR wsz[MAX_PATH];
737  MultiByteToWideChar(CP_ACP, 0, pszShortcutFile, -1, wsz, MAX_PATH);
738 
739  hres = ppf->Load(wsz, STGM_READ);
740  if (SUCCEEDED(hres)) {
741  hres = psl->Resolve(HWND_DESKTOP, SLR_ANY_MATCH | SLR_NO_UI | SLR_UPDATE);
742  if (SUCCEEDED(hres)) {
743  strlcpy(szGotPath, pszShortcutFile,MAX_PATH);
744  hres = psl->GetPath(szGotPath, MAX_PATH, (WIN32_FIND_DATA *)&wfd,
745  SLGP_UNCPRIORITY | SLGP_RAWPATH);
746  strlcpy(pszPath,szGotPath, maxbuf);
747  if (maxbuf) pszPath[maxbuf-1] = 0;
748  }
749  }
750  ppf->Release();
751  }
752  psl->Release();
753  }
754  _CoUninitialize();
755 
756  return SUCCEEDED(hres);
757  }
758 
759  void UpdateRegistry(TWinNTSystem* sys, char* buf /* size of buffer: MAX_MODULE_NAME32 + 1 */) {
760  // register ROOT as the .root file handler:
761  GetModuleFileName(0, buf, MAX_MODULE_NAME32 + 1);
762  if (strcmp(sys->TWinNTSystem::BaseName(buf), "root.exe"))
763  return;
764  HKEY regCUS;
765  if (!::RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &regCUS) == ERROR_SUCCESS)
766  return;
767  HKEY regCUSC;
768  if (!::RegOpenKeyEx(regCUS, "Classes", 0, KEY_READ, &regCUSC) == ERROR_SUCCESS) {
769  ::RegCloseKey(regCUS);
770  return;
771  }
772 
773  HKEY regROOT;
774  bool regROOTwrite = false;
775  TString iconloc(buf);
776  iconloc += ",-101";
777 
778  if (::RegOpenKeyEx(regCUSC, "ROOTDEV.ROOT", 0, KEY_READ, &regROOT) != ERROR_SUCCESS) {
779  ::RegCloseKey(regCUSC);
780  if (::RegOpenKeyEx(regCUS, "Classes", 0, KEY_READ | KEY_WRITE, &regCUSC) == ERROR_SUCCESS &&
781  ::RegCreateKeyEx(regCUSC, "ROOTDEV.ROOT", 0, NULL, 0, KEY_READ | KEY_WRITE,
782  NULL, &regROOT, NULL) == ERROR_SUCCESS) {
783  regROOTwrite = true;
784  }
785  } else {
786  HKEY regROOTIcon;
787  if (::RegOpenKeyEx(regROOT, "DefaultIcon", 0, KEY_READ, &regROOTIcon) == ERROR_SUCCESS) {
788  char bufIconLoc[1024];
789  DWORD dwType;
790  DWORD dwSize = sizeof(bufIconLoc);
791 
792  if (::RegQueryValueEx(regROOTIcon, NULL, NULL, &dwType, (BYTE*)bufIconLoc, &dwSize) == ERROR_SUCCESS)
793  regROOTwrite = (iconloc != bufIconLoc);
794  else
795  regROOTwrite = true;
796  ::RegCloseKey(regROOTIcon);
797  } else
798  regROOTwrite = true;
799  if (regROOTwrite) {
800  // re-open for writing
801  ::RegCloseKey(regCUSC);
802  ::RegCloseKey(regROOT);
803  if (::RegOpenKeyEx(regCUS, "Classes", 0, KEY_READ | KEY_WRITE, &regCUSC) != ERROR_SUCCESS) {
804  // error opening key for writing:
805  regROOTwrite = false;
806  } else {
807  if (::RegOpenKeyEx(regCUSC, "ROOTDEV.ROOT", 0, KEY_WRITE, &regROOT) != ERROR_SUCCESS) {
808  // error opening key for writing:
809  regROOTwrite = false;
810  ::RegCloseKey(regCUSC);
811  }
812  }
813  }
814  }
815 
816  // determine the fileopen.C file path:
817  TString fileopen = "fileopen.C";
819 
820  if (regROOTwrite) {
821  // only write to registry if fileopen.C is readable
822  regROOTwrite = (::_access(fileopen, kReadPermission) == 0);
823  }
824 
825  if (!regROOTwrite) {
826  ::RegCloseKey(regROOT);
827  ::RegCloseKey(regCUSC);
828  ::RegCloseKey(regCUS);
829  return;
830  }
831 
832  static const char apptitle[] = "ROOT data file";
833  ::RegSetValueEx(regROOT, NULL, 0, REG_SZ, (BYTE*)apptitle, sizeof(apptitle));
834  DWORD editflags = /*FTA_OpenIsSafe*/ 0x00010000; // trust downloaded files
835  ::RegSetValueEx(regROOT, "EditFlags", 0, REG_DWORD, (BYTE*)&editflags, sizeof(editflags));
836 
837  HKEY regROOTIcon;
838  if (::RegCreateKeyEx(regROOT, "DefaultIcon", 0, NULL, 0, KEY_READ | KEY_WRITE,
839  NULL, &regROOTIcon, NULL) == ERROR_SUCCESS) {
840  TString iconloc(buf);
841  iconloc += ",-101";
842  ::RegSetValueEx(regROOTIcon, NULL, 0, REG_SZ, (BYTE*)iconloc.Data(), iconloc.Length() + 1);
843  ::RegCloseKey(regROOTIcon);
844  }
845 
846  // "open" verb
847  HKEY regROOTshell;
848  if (::RegCreateKeyEx(regROOT, "shell", 0, NULL, 0, KEY_READ | KEY_WRITE,
849  NULL, &regROOTshell, NULL) == ERROR_SUCCESS) {
850  HKEY regShellOpen;
851  if (::RegCreateKeyEx(regROOTshell, "open", 0, NULL, 0, KEY_READ | KEY_WRITE,
852  NULL, &regShellOpen, NULL) == ERROR_SUCCESS) {
853  HKEY regShellOpenCmd;
854  if (::RegCreateKeyEx(regShellOpen, "command", 0, NULL, 0, KEY_READ | KEY_WRITE,
855  NULL, &regShellOpenCmd, NULL) == ERROR_SUCCESS) {
856  TString cmd(buf);
857  cmd += " -l \"%1\" \"";
858  cmd += fileopen;
859  cmd += "\"";
860  ::RegSetValueEx(regShellOpenCmd, NULL, 0, REG_SZ, (BYTE*)cmd.Data(), cmd.Length() + 1);
861  ::RegCloseKey(regShellOpenCmd);
862  }
863  ::RegCloseKey(regShellOpen);
864  }
865  ::RegCloseKey(regROOTshell);
866  }
867  ::RegCloseKey(regROOT);
868 
869  if (::RegCreateKeyEx(regCUSC, ".root", 0, NULL, 0, KEY_READ | KEY_WRITE,
870  NULL, &regROOT, NULL) == ERROR_SUCCESS) {
871  static const char appname[] = "ROOTDEV.ROOT";
872  ::RegSetValueEx(regROOT, NULL, 0, REG_SZ, (BYTE*)appname, sizeof(appname));
873  }
874  ::RegCloseKey(regCUSC);
875  ::RegCloseKey(regCUS);
876 
877  // tell Windows that the association was changed
878  ::SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
879  } // UpdateRegistry()
880 
881  /////////////////////////////////////////////////////////////////////////////
882  /// return kFALSE if option "-l" was specified as main programm command arg
883 
884  bool NeedSplash()
885  {
886  static bool once = true;
887  if (!once || gROOT->IsBatch() || !gApplication) return false;
889  if ((arg != "root") && (arg != "rootn") &&
890  (arg != "root.exe") && (arg != "rootn.exe")) return false;
891  for(int i=1; i<gApplication->Argc(); i++) {
892  arg = gApplication->Argv(i);
893  arg.Strip(TString::kBoth);
894  if ((arg == "-l") || (arg == "-b")) {
895  return false;
896  }
897  }
898  if (once) {
899  once = false;
900  return true;
901  }
902  return false;
903  }
904 
905  /////////////////////////////////////////////////////////////////////////////
906 
907  static void SetConsoleWindowName()
908  {
909  char pszNewWindowTitle[1024]; // contains fabricated WindowTitle
910  char pszOldWindowTitle[1024]; // contains original WindowTitle
911  HANDLE hStdout;
912  CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
913 
914  if (!::GetConsoleTitle(pszOldWindowTitle, 1024))
915  return;
916  // format a "unique" NewWindowTitle
917  wsprintf(pszNewWindowTitle,"%d/%d", ::GetTickCount(), ::GetCurrentProcessId());
918  // change current window title
919  if (!::SetConsoleTitle(pszNewWindowTitle))
920  return;
921  // ensure window title has been updated
922  ::Sleep(40);
923  // look for NewWindowTitle
924  gConsoleWindow = (ULong_t)::FindWindow(0, pszNewWindowTitle);
925  if (gConsoleWindow) {
926  // restore original window title
927  ::ShowWindow((HWND)gConsoleWindow, SW_RESTORE);
928  //::SetForegroundWindow((HWND)gConsoleWindow);
929  ::SetConsoleTitle("ROOT session");
930  }
931  hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
932  ::SetConsoleMode(hStdout, ENABLE_PROCESSED_OUTPUT |
933  ENABLE_WRAP_AT_EOL_OUTPUT);
934  if (!::GetConsoleScreenBufferInfo(hStdout, &csbiInfo))
935  return;
936  Gl_setwidth(csbiInfo.dwMaximumWindowSize.X);
937  }
938 
939 } // end unnamed namespace
940 
941 
942 ///////////////////////////////////////////////////////////////////////////////
944 
946 
947 ////////////////////////////////////////////////////////////////////////////////
948 ///
949 
950 Bool_t TWinNTSystem::HandleConsoleEvent()
951 {
952  TSignalHandler *sh;
953  TIter next(fSignalHandler);
954  ESignals s;
955 
956  while (sh = (TSignalHandler*)next()) {
957  s = sh->GetSignal();
958  if (s == kSigInterrupt) {
959  sh->Notify();
960  Throw(SIGINT);
961  return kTRUE;
962  }
963  }
964  return kFALSE;
965 }
966 
967 ////////////////////////////////////////////////////////////////////////////////
968 /// ctor
969 
970 TWinNTSystem::TWinNTSystem() : TSystem("WinNT", "WinNT System"),
971 fGUIThreadHandle(0), fGUIThreadId(0)
972 {
973  fhProcess = ::GetCurrentProcess();
974  fDirNameBuffer = 0;
975 
976  WSADATA WSAData;
977  int initwinsock = 0;
978 
979  if (initwinsock = ::WSAStartup(MAKEWORD(2, 0), &WSAData)) {
980  Error("TWinNTSystem()","Starting sockets failed");
981  }
982 
983  // use ::MessageBeep by default for TWinNTSystem
984  fBeepDuration = 1;
985  fBeepFreq = 0;
986  if (gEnv) {
987  fBeepDuration = gEnv->GetValue("Root.System.BeepDuration", 1);
988  fBeepFreq = gEnv->GetValue("Root.System.BeepFreq", 0);
989  }
990 
991  char *buf = new char[MAX_MODULE_NAME32 + 1];
992 
993 #ifdef ROOTPREFIX
994  if (gSystem->Getenv("ROOTIGNOREPREFIX") {
995 #endif
996  // set ROOTSYS
997  HMODULE hModCore = ::GetModuleHandle("libCore.dll");
998  if (hModCore) {
999  ::GetModuleFileName(hModCore, buf, MAX_MODULE_NAME32 + 1);
1000  char *pLibName = strstr(buf, "libCore.dll");
1001  if (pLibName) {
1002  --pLibName; // skip trailing \\ or /
1003  while (--pLibName >= buf && *pLibName != '\\' && *pLibName != '/');
1004  *pLibName = 0; // replace trailing \\ or / with 0
1005  TString check_path = buf;
1006  check_path += "\\etc";
1007  // look for $ROOTSYS (it should contain the "etc" subdirectory)
1008  while (buf[0] && GetFileAttributes(check_path.Data()) == INVALID_FILE_ATTRIBUTES) {
1009  while (--pLibName >= buf && *pLibName != '\\' && *pLibName != '/');
1010  *pLibName = 0;
1011  check_path = buf;
1012  check_path += "\\etc";
1013  }
1014  if (buf[0]) {
1015  Setenv("ROOTSYS", buf);
1016  TString path = buf;
1017  path += "\\bin;";
1018  path += Getenv("PATH");
1019  Setenv("PATH", path.Data());
1020  }
1021  }
1022  }
1023 #ifdef ROOTPREFIX
1024  }
1025 #endif
1026 
1027  UpdateRegistry(this, buf);
1028 
1029  delete [] buf;
1030 }
1031 
1032 ////////////////////////////////////////////////////////////////////////////////
1033 /// dtor
1034 
1036 {
1037  // Revert back the accuracy of Sleep() without needing to link to winmm.lib
1038  typedef UINT (WINAPI* LPTIMEENDPERIOD)( UINT uPeriod );
1039  HINSTANCE hInstWinMM = LoadLibrary( "winmm.dll" );
1040  if( hInstWinMM ) {
1041  LPTIMEENDPERIOD pTimeEndPeriod = (LPTIMEENDPERIOD)GetProcAddress( hInstWinMM, "timeEndPeriod" );
1042  if( NULL != pTimeEndPeriod )
1043  pTimeEndPeriod(1);
1044  FreeLibrary(hInstWinMM);
1045  }
1046  // Clean up the WinSocket connectios
1047  ::WSACleanup();
1048 
1049  if (fDirNameBuffer) {
1050  delete [] fDirNameBuffer;
1051  fDirNameBuffer = 0;
1052  }
1053 
1054  if (gGlobalEvent) {
1055  ::ResetEvent(gGlobalEvent);
1056  ::CloseHandle(gGlobalEvent);
1057  gGlobalEvent = 0;
1058  }
1059  if (gTimerThreadHandle) {
1060  ::TerminateThread(gTimerThreadHandle, 0);
1061  ::CloseHandle(gTimerThreadHandle);
1062  }
1063 }
1064 
1065 ////////////////////////////////////////////////////////////////////////////////
1066 /// Initialize WinNT system interface.
1067 
1069 {
1070  const char *dir = 0;
1071 
1072  if (TSystem::Init()) {
1073  return kTRUE;
1074  }
1075 
1076  fReadmask = new TFdSet;
1077  fWritemask = new TFdSet;
1078  fReadready = new TFdSet;
1079  fWriteready = new TFdSet;
1080  fSignals = new TFdSet;
1081  fNfd = 0;
1082 
1083  //--- install default handlers
1084  // Actually: don't. If we want a stack trace we need a context for the
1085  // signal. Signals don't have one. If we don't handle them, Windows will
1086  // raise an exception, which has a context, and which is handled by
1087  // ExceptionFilter.
1088  /*
1089  WinNTSignal(kSigChild, SigHandler);
1090  WinNTSignal(kSigBus, SigHandler);
1091  WinNTSignal(kSigSegmentationViolation, SigHandler);
1092  WinNTSignal(kSigIllegalInstruction, SigHandler);
1093  WinNTSignal(kSigSystem, SigHandler);
1094  WinNTSignal(kSigPipe, SigHandler);
1095  WinNTSignal(kSigAlarm, SigHandler);
1096  WinNTSignal(kSigFloatingException, SigHandler);
1097  */
1098  ::SetUnhandledExceptionFilter(ExceptionFilter);
1099 
1100  fSigcnt = 0;
1101 
1102  // This is a fallback in case TROOT::GetRootSys() can't determine ROOTSYS
1103  static char lpFilename[MAX_PATH];
1104  if (::GetModuleFileName(
1105  NULL, // handle to module to find filename for
1106  lpFilename, // pointer to buffer to receive module path
1107  sizeof(lpFilename))) { // size of buffer, in characters
1108  const char *dirName = DirName(DirName(lpFilename));
1109  gRootDir = StrDup(dirName);
1110  } else {
1111  gRootDir = 0;
1112  }
1113 
1114  // Increase the accuracy of Sleep() without needing to link to winmm.lib
1115  typedef UINT (WINAPI* LPTIMEBEGINPERIOD)( UINT uPeriod );
1116  HINSTANCE hInstWinMM = LoadLibrary( "winmm.dll" );
1117  if( hInstWinMM ) {
1118  LPTIMEBEGINPERIOD pTimeBeginPeriod = (LPTIMEBEGINPERIOD)GetProcAddress( hInstWinMM, "timeBeginPeriod" );
1119  if( NULL != pTimeBeginPeriod )
1120  pTimeBeginPeriod(1);
1121  FreeLibrary(hInstWinMM);
1122  }
1123  gTimerThreadHandle = ::CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ThreadStub,
1124  this, NULL, NULL);
1125 
1126  gGlobalEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL);
1127  fGUIThreadHandle = ::CreateThread( NULL, 0, &GUIThreadMessageProcessingLoop, 0, 0, &fGUIThreadId );
1128 
1129  char *buf = new char[MAX_MODULE_NAME32 + 1];
1130  HMODULE hModCore = ::GetModuleHandle("libCore.dll");
1131  if (hModCore) {
1132  ::GetModuleFileName(hModCore, buf, MAX_MODULE_NAME32 + 1);
1133  char *pLibName = strstr(buf, "libCore.dll");
1134  --pLibName; // remove trailing \\ or /
1135  *pLibName = 0;
1136  // add the directory containing libCore.dll in the dynamic search path
1137  if (buf[0]) AddDynamicPath(buf);
1138  }
1139  delete [] buf;
1140  SetConsoleWindowName();
1142  fFirstFile = kTRUE;
1143 
1144  return kFALSE;
1145 }
1146 
1147 //---- Misc --------------------------------------------------------------------
1148 
1149 ////////////////////////////////////////////////////////////////////////////////
1150 /// Base name of a file name. Base name of /user/root is root.
1151 /// But the base name of '/' is '/'
1152 /// 'c:\' is 'c:\'
1153 
1154 const char *TWinNTSystem::BaseName(const char *name)
1155 {
1156  // BB 28/10/05 : Removed (commented out) StrDup() :
1157  // - To get same behaviour on Windows and on Linux
1158  // - To avoid the need to use #ifdefs
1159  // - Solve memory leaks (mainly in TTF::SetTextFont())
1160  // No need for the calling routine to use free() anymore.
1161 
1162  if (name) {
1163  int idx = 0;
1164  const char *symbol=name;
1165 
1166  // Skip leading blanks
1167  while ( (*symbol == ' ' || *symbol == '\t') && *symbol) symbol++;
1168 
1169  if (*symbol) {
1170  if (isalpha(symbol[idx]) && symbol[idx+1] == ':') idx = 2;
1171  if ( (symbol[idx] == '/' || symbol[idx] == '\\') && symbol[idx+1] == '\0') {
1172  //return StrDup(symbol);
1173  return symbol;
1174  }
1175  } else {
1176  Error("BaseName", "name = 0");
1177  return 0;
1178  }
1179  char *cp;
1180  char *bslash = (char *)strrchr(&symbol[idx],'\\');
1181  char *rslash = (char *)strrchr(&symbol[idx],'/');
1182  if (cp = std::max(rslash, bslash)) {
1183  //return StrDup(++cp);
1184  return ++cp;
1185  }
1186  //return StrDup(&symbol[idx]);
1187  return &symbol[idx];
1188  }
1189  Error("BaseName", "name = 0");
1190  return 0;
1191 }
1192 
1193 ////////////////////////////////////////////////////////////////////////////////
1194 /// Set the application name (from command line, argv[0]) and copy it in
1195 /// gProgName. Copy the application pathname in gProgPath.
1196 
1198 {
1199  ULong_t idot = 0;
1200  char *dot = 0;
1201  char *progname;
1202  char *fullname = 0; // the program name with extension
1203 
1204  // On command prompt the progname can be supplied with no extension (under Windows)
1205  ULong_t namelen=name ? strlen(name) : 0;
1206  if (name && namelen > 0) {
1207  // Check whether the name contains "extention"
1208  fullname = new char[namelen+5];
1209  strlcpy(fullname, name,namelen+5);
1210  if ( !strrchr(fullname, '.') )
1211  strlcat(fullname, ".exe",namelen+5);
1212 
1213  progname = StrDup(BaseName(fullname));
1214  dot = strrchr(progname, '.');
1215  idot = dot ? (ULong_t)(dot - progname) : strlen(progname);
1216 
1217  char *which = 0;
1218 
1219  if (IsAbsoluteFileName(fullname) && !AccessPathName(fullname)) {
1220  which = StrDup(fullname);
1221  } else {
1222  which = Which(Form("%s;%s", WorkingDirectory(), Getenv("PATH")), progname);
1223  }
1224 
1225  if (which) {
1226  TString dirname;
1227  char driveletter = DriveName(which);
1228  const char *d = DirName(which);
1229 
1230  if (driveletter) {
1231  dirname.Form("%c:%s", driveletter, d);
1232  } else {
1233  dirname.Form("%s", d);
1234  }
1235 
1236  gProgPath = StrDup(dirname);
1237  } else {
1238  // Do not issue a warning - ROOT is not using gProgPath anyway.
1239  // Warning("SetProgname",
1240  // "Cannot find this program named \"%s\" (Did you create a TApplication? Is this program in your %%PATH%%?)",
1241  // fullname);
1243  }
1244 
1245  // Cut the extension for progname off
1246  progname[idot] = '\0';
1247  gProgName = StrDup(progname);
1248  if (which) delete [] which;
1249  delete[] fullname;
1250  delete[] progname;
1251  }
1252  if (::NeedSplash()) {
1253  new TWin32SplashThread(FALSE);
1254  }
1255 }
1256 
1257 ////////////////////////////////////////////////////////////////////////////////
1258 /// Return system error string.
1259 
1261 {
1262  Int_t err = GetErrno();
1263  if (err == 0 && GetLastErrorString() != "")
1264  return GetLastErrorString();
1265  if (err < 0 || err >= sys_nerr) {
1266  static TString error_msg;
1267  error_msg.Form("errno out of range %d", err);
1268  return error_msg;
1269  }
1270  return sys_errlist[err];
1271 }
1272 
1273 ////////////////////////////////////////////////////////////////////////////////
1274 /// Return the system's host name.
1275 
1277 {
1278  if (fHostname == "")
1279  fHostname = ::getenv("COMPUTERNAME");
1280  if (fHostname == "") {
1281  // This requires a DNS query - but we need it for fallback
1282  char hn[64];
1283  DWORD il = sizeof(hn);
1284  ::GetComputerName(hn, &il);
1285  fHostname = hn;
1286  }
1287  return fHostname;
1288 }
1289 
1290 ////////////////////////////////////////////////////////////////////////////////
1291 /// Beep. If freq==0 (the default for TWinNTSystem), use ::MessageBeep.
1292 /// Otherwise ::Beep with freq and duration.
1293 
1294 void TWinNTSystem::DoBeep(Int_t freq /*=-1*/, Int_t duration /*=-1*/) const
1295 {
1296  if (freq == 0) {
1297  ::MessageBeep(-1);
1298  return;
1299  }
1300  if (freq < 37) freq = 440;
1301  if (duration < 0) duration = 100;
1302  ::Beep(freq, duration);
1303 }
1304 
1305 ////////////////////////////////////////////////////////////////////////////////
1306 /// Set the (static part of) the event handler func for GUI messages.
1307 
1309 {
1310  gGUIThreadMsgFunc = func;
1311 }
1312 
1313 ////////////////////////////////////////////////////////////////////////////////
1314 /// Hook to tell TSystem that the TApplication object has been created.
1315 
1317 {
1318  // send a dummy message to the GUI thread to kick it into life
1319  ::PostThreadMessage(fGUIThreadId, 0, NULL, 0L);
1320 }
1321 
1322 
1323 //---- EventLoop ---------------------------------------------------------------
1324 
1325 ////////////////////////////////////////////////////////////////////////////////
1326 /// Add a file handler to the list of system file handlers. Only adds
1327 /// the handler if it is not already in the list of file handlers.
1328 
1330 {
1332  if (h) {
1333  int fd = h->GetFd();
1334  if (!fd) return;
1335 
1336  if (h->HasReadInterest()) {
1337  fReadmask->Set(fd);
1338  }
1339  if (h->HasWriteInterest()) {
1340  fWritemask->Set(fd);
1341  }
1342  }
1343 }
1344 
1345 ////////////////////////////////////////////////////////////////////////////////
1346 /// Remove a file handler from the list of file handlers. Returns
1347 /// the handler or 0 if the handler was not in the list of file handlers.
1348 
1350 {
1351  if (!h) return 0;
1352 
1354  if (oh) { // found
1355  fReadmask->Clr(h->GetFd());
1356  fWritemask->Clr(h->GetFd());
1357  }
1358  return oh;
1359 }
1360 
1361 ////////////////////////////////////////////////////////////////////////////////
1362 /// Add a signal handler to list of system signal handlers. Only adds
1363 /// the handler if it is not already in the list of signal handlers.
1364 
1366 {
1367  Bool_t set_console = kFALSE;
1368  ESignals sig = h->GetSignal();
1369 
1370  if (sig == kSigInterrupt) {
1371  set_console = kTRUE;
1372  TSignalHandler *hs;
1373  TIter next(fSignalHandler);
1374 
1375  while ((hs = (TSignalHandler*) next())) {
1376  if (hs->GetSignal() == kSigInterrupt)
1377  set_console = kFALSE;
1378  }
1379  }
1381 
1382  // Add our handler to the list of the console handlers
1383  if (set_console)
1384  ::SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleSigHandler, TRUE);
1385  else
1386  WinNTSignal(h->GetSignal(), SigHandler);
1387 }
1388 
1389 ////////////////////////////////////////////////////////////////////////////////
1390 /// Remove a signal handler from list of signal handlers. Returns
1391 /// the handler or 0 if the handler was not in the list of signal handlers.
1392 
1394 {
1395  if (!h) return 0;
1396 
1397  int sig = h->GetSignal();
1398 
1399  if (sig = kSigInterrupt) {
1400  Bool_t last = kTRUE;
1401  TSignalHandler *hs;
1402  TIter next(fSignalHandler);
1403 
1404  while ((hs = (TSignalHandler*) next())) {
1405  if (hs->GetSignal() == kSigInterrupt)
1406  last = kFALSE;
1407  }
1408  // Remove our handler from the list of the console handlers
1409  if (last)
1410  ::SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleSigHandler, FALSE);
1411  }
1412  return TSystem::RemoveSignalHandler(h);
1413 }
1414 
1415 ////////////////////////////////////////////////////////////////////////////////
1416 /// If reset is true reset the signal handler for the specified signal
1417 /// to the default handler, else restore previous behaviour.
1418 
1420 {
1421  //FIXME!
1422 }
1423 
1424 ////////////////////////////////////////////////////////////////////////////////
1425 /// Reset signals handlers to previous behaviour.
1426 
1428 {
1429  //FIXME!
1430 }
1431 
1432 ////////////////////////////////////////////////////////////////////////////////
1433 /// If ignore is true ignore the specified signal, else restore previous
1434 /// behaviour.
1435 
1437 {
1438  // FIXME!
1439 }
1440 
1441 ////////////////////////////////////////////////////////////////////////////////
1442 /// Print a stack trace, if gEnv entry "Root.Stacktrace" is unset or 1,
1443 /// and if the image helper functions can be found (see InitImagehlpFunctions()).
1444 /// The stack trace is printed for each thread; if fgXcptContext is set (e.g.
1445 /// because there was an exception) use it to define the current thread's context.
1446 /// For each frame in the stack, the frame's module name, the frame's function
1447 /// name, and the frame's line number are printed.
1448 
1450 {
1451  if (!gEnv->GetValue("Root.Stacktrace", 1))
1452  return;
1453 
1454  HANDLE snapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD,::GetCurrentProcessId());
1455 
1456  std::cerr.flush();
1457  fflush (stderr);
1458 
1459  if (!InitImagehlpFunctions()) {
1460  std::cerr << "No stack trace: cannot find (functions in) dbghelp.dll!" << std::endl;
1461  return;
1462  }
1463 
1464  // what system are we on?
1465  SYSTEM_INFO sysInfo;
1466  ::GetSystemInfo(&sysInfo);
1467  DWORD machineType = IMAGE_FILE_MACHINE_I386;
1468  switch (sysInfo.wProcessorArchitecture) {
1469  case PROCESSOR_ARCHITECTURE_AMD64:
1470  machineType = IMAGE_FILE_MACHINE_AMD64;
1471  break;
1472  case PROCESSOR_ARCHITECTURE_IA64:
1473  machineType = IMAGE_FILE_MACHINE_IA64;
1474  break;
1475  }
1476 
1477  DWORD currentThreadID = ::GetCurrentThreadId();
1478  DWORD currentProcessID = ::GetCurrentProcessId();
1479 
1480  if (snapshot == INVALID_HANDLE_VALUE) return;
1481 
1482  THREADENTRY32 threadentry;
1483  threadentry.dwSize = sizeof(THREADENTRY32);
1484  if (!::Thread32First(snapshot, &threadentry)) return;
1485 
1486  std::cerr << std::endl << "==========================================" << std::endl;
1487  std::cerr << "=============== STACKTRACE ===============" << std::endl;
1488  std::cerr << "==========================================" << std::endl << std::endl;
1489  UInt_t iThread = 0;
1490  do {
1491  if (threadentry.th32OwnerProcessID != currentProcessID)
1492  continue;
1493  HANDLE thread = ::OpenThread(THREAD_GET_CONTEXT|THREAD_SUSPEND_RESUME|THREAD_QUERY_INFORMATION,
1494  FALSE, threadentry.th32ThreadID);
1495  CONTEXT context;
1496  memset(&context, 0, sizeof(CONTEXT));
1497 
1498  if (threadentry.th32ThreadID != currentThreadID) {
1499  ::SuspendThread(thread);
1500  context.ContextFlags = CONTEXT_ALL;
1501  ::GetThreadContext(thread, &context);
1502  ::ResumeThread(thread);
1503  } else {
1504  if (fgXcptContext) {
1505  context = *fgXcptContext;
1506  } else {
1507  typedef void (WINAPI *RTLCCTXT)(PCONTEXT);
1508  RTLCCTXT p2RtlCCtxt = (RTLCCTXT) ::GetProcAddress(
1509  GetModuleHandle("kernel32.dll"), "RtlCaptureContext");
1510  if (p2RtlCCtxt) {
1511  context.ContextFlags = CONTEXT_ALL;
1512  p2RtlCCtxt(&context);
1513  }
1514  }
1515  }
1516 
1517  STACKFRAME64 frame;
1518  ::ZeroMemory(&frame, sizeof(frame));
1519 
1520  frame.AddrPC.Mode = AddrModeFlat;
1521  frame.AddrFrame.Mode = AddrModeFlat;
1522  frame.AddrStack.Mode = AddrModeFlat;
1523 #if defined(_M_IX86)
1524  frame.AddrPC.Offset = context.Eip;
1525  frame.AddrFrame.Offset = context.Ebp;
1526  frame.AddrStack.Offset = context.Esp;
1527 #elif defined(_M_X64)
1528  frame.AddrPC.Offset = context.Rip;
1529  frame.AddrFrame.Offset = context.Rsp;
1530  frame.AddrStack.Offset = context.Rsp;
1531 #elif defined(_M_IA64)
1532  frame.AddrPC.Offset = context.StIIP;
1533  frame.AddrFrame.Offset = context.IntSp;
1534  frame.AddrStack.Offset = context.IntSp;
1535  frame.AddrBStore.Offset= context.RsBSP;
1536 #else
1537  std::cerr << "Stack traces not supported on your architecture yet." << std::endl;
1538  return;
1539 #endif
1540 
1541  Bool_t bFirst = kTRUE;
1542  while (_StackWalk64(machineType, (HANDLE)::GetCurrentProcess(), thread, (LPSTACKFRAME64)&frame,
1543  (LPVOID)&context, (PREAD_PROCESS_MEMORY_ROUTINE)NULL, (PFUNCTION_TABLE_ACCESS_ROUTINE)_SymFunctionTableAccess64,
1544  (PGET_MODULE_BASE_ROUTINE)_SymGetModuleBase64, NULL)) {
1545  if (bFirst)
1546  std::cerr << std::endl << "================ Thread " << iThread++ << " ================" << std::endl;
1547  if (!bFirst || threadentry.th32ThreadID != currentThreadID) {
1548  const std::string moduleName = GetModuleName(frame.AddrPC.Offset);
1549  const std::string functionName = GetFunctionName(frame.AddrPC.Offset);
1550  std::cerr << " " << moduleName << functionName << std::endl;
1551  }
1552  bFirst = kFALSE;
1553  }
1554  ::CloseHandle(thread);
1555  } while (::Thread32Next(snapshot, &threadentry));
1556 
1557  std::cerr << std::endl << "==========================================" << std::endl;
1558  std::cerr << "============= END STACKTRACE =============" << std::endl;
1559  std::cerr << "==========================================" << std::endl << std::endl;
1560  ::CloseHandle(snapshot);
1561  _SymCleanup(GetCurrentProcess());
1562 }
1563 
1564 ////////////////////////////////////////////////////////////////////////////////
1565 /// Return the bitmap of conditions that trigger a floating point exception.
1566 
1568 {
1569  Int_t mask = 0;
1570  UInt_t oldmask = _statusfp( );
1571 
1572  if (oldmask & _EM_INVALID ) mask |= kInvalid;
1573  if (oldmask & _EM_ZERODIVIDE) mask |= kDivByZero;
1574  if (oldmask & _EM_OVERFLOW ) mask |= kOverflow;
1575  if (oldmask & _EM_UNDERFLOW) mask |= kUnderflow;
1576  if (oldmask & _EM_INEXACT ) mask |= kInexact;
1577 
1578  return mask;
1579 }
1580 
1581 ////////////////////////////////////////////////////////////////////////////////
1582 /// Set which conditions trigger a floating point exception.
1583 /// Return the previous set of conditions.
1584 
1586 {
1587  Int_t old = GetFPEMask();
1588 
1589  UInt_t newm = 0;
1590  if (mask & kInvalid ) newm |= _EM_INVALID;
1591  if (mask & kDivByZero) newm |= _EM_ZERODIVIDE;
1592  if (mask & kOverflow ) newm |= _EM_OVERFLOW;
1593  if (mask & kUnderflow) newm |= _EM_UNDERFLOW;
1594  if (mask & kInexact ) newm |= _EM_INEXACT;
1595 
1596  UInt_t cm = ::_statusfp();
1597  cm &= ~newm;
1598  ::_controlfp(cm , _MCW_EM);
1599 
1600  return old;
1601 }
1602 
1603 ////////////////////////////////////////////////////////////////////////////////
1604 /// process pending events, i.e. DispatchOneEvent(kTRUE)
1605 
1607 {
1608  return TSystem::ProcessEvents();
1609 }
1610 
1611 ////////////////////////////////////////////////////////////////////////////////
1612 /// Dispatch a single event in TApplication::Run() loop
1613 
1615 {
1616  // check for keyboard events
1617  if (pendingOnly && gGlobalEvent) ::SetEvent(gGlobalEvent);
1618 
1619  Bool_t pollOnce = pendingOnly;
1620 
1621  while (1) {
1622  if (_kbhit()) {
1623  if (gROOT->GetApplication()) {
1625  if (gSplash) { // terminate splash window after first key press
1626  delete gSplash;
1627  gSplash = 0;
1628  }
1629  if (!pendingOnly) {
1630  return;
1631  }
1632  }
1633  }
1634  if (gROOT->IsLineProcessing() && (!gVirtualX || !gVirtualX->IsCmdThread())) {
1635  if (!pendingOnly) {
1636  // yield execution to another thread that is ready to run
1637  // if no other thread is ready, sleep 1 ms before to return
1638  if (gGlobalEvent) {
1639  ::WaitForSingleObject(gGlobalEvent, 1);
1640  ::ResetEvent(gGlobalEvent);
1641  }
1642  return;
1643  }
1644  }
1645  // first handle any GUI events
1646  if (gXDisplay && !gROOT->IsBatch()) {
1647  if (gXDisplay->Notify()) {
1648  if (!pendingOnly) {
1649  return;
1650  }
1651  }
1652  }
1653 
1654  // check for file descriptors ready for reading/writing
1655  if ((fNfd > 0) && fFileHandler && (fFileHandler->GetSize() > 0)) {
1656  if (CheckDescriptors()) {
1657  if (!pendingOnly) {
1658  return;
1659  }
1660  }
1661  }
1662  fNfd = 0;
1663  fReadready->Zero();
1664  fWriteready->Zero();
1665 
1666  if (pendingOnly && !pollOnce)
1667  return;
1668 
1669  // check synchronous signals
1670  if (fSigcnt > 0 && fSignalHandler->GetSize() > 0) {
1671  if (CheckSignals(kTRUE)) {
1672  if (!pendingOnly) {
1673  return;
1674  }
1675  }
1676  }
1677  fSigcnt = 0;
1678  fSignals->Zero();
1679 
1680  // handle past due timers
1681  Long_t nextto;
1682  if (fTimers && fTimers->GetSize() > 0) {
1683  if (DispatchTimers(kTRUE)) {
1684  // prevent timers from blocking the rest types of events
1685  nextto = NextTimeOut(kTRUE);
1686  if (nextto > (kItimerResolution>>1) || nextto == -1) {
1687  return;
1688  }
1689  }
1690  }
1691 
1692  // if in pendingOnly mode poll once file descriptor activity
1693  nextto = NextTimeOut(kTRUE);
1694  if (pendingOnly) {
1695  if (fFileHandler && fFileHandler->GetSize() == 0)
1696  return;
1697  nextto = 0;
1698  pollOnce = kFALSE;
1699  }
1700 
1701  if (fReadmask && !fReadmask->GetBits() &&
1702  fWritemask && !fWritemask->GetBits()) {
1703  // yield execution to another thread that is ready to run
1704  // if no other thread is ready, sleep 1 ms before to return
1705  if (!pendingOnly && gGlobalEvent) {
1706  ::WaitForSingleObject(gGlobalEvent, 1);
1707  ::ResetEvent(gGlobalEvent);
1708  }
1709  return;
1710  }
1711 
1712  *fReadready = *fReadmask;
1713  *fWriteready = *fWritemask;
1714 
1715  fNfd = WinNTSelect(fReadready, fWriteready, nextto);
1716 
1717  // serious error has happened -> reset all file descrptors
1718  if ((fNfd < 0) && (fNfd != -2)) {
1719  int rc, i;
1720 
1721  for (i = 0; i < fReadmask->GetCount(); i++) {
1722  TFdSet t;
1723  Int_t fd = fReadmask->GetFd(i);
1724  t.Set(fd);
1725  if (fReadmask->IsSet(fd)) {
1726  rc = WinNTSelect(&t, 0, 0);
1727  if (rc < 0 && rc != -2) {
1728  ::SysError("DispatchOneEvent", "select: read error on %d\n", fd);
1729  fReadmask->Clr(fd);
1730  }
1731  }
1732  }
1733 
1734  for (i = 0; i < fWritemask->GetCount(); i++) {
1735  TFdSet t;
1736  Int_t fd = fWritemask->GetFd(i);
1737  t.Set(fd);
1738 
1739  if (fWritemask->IsSet(fd)) {
1740  rc = WinNTSelect(0, &t, 0);
1741  if (rc < 0 && rc != -2) {
1742  ::SysError("DispatchOneEvent", "select: write error on %d\n", fd);
1743  fWritemask->Clr(fd);
1744  }
1745  }
1746  t.Clr(fd);
1747  }
1748  }
1749  }
1750 }
1751 
1752 ////////////////////////////////////////////////////////////////////////////////
1753 /// Exit from event loop.
1754 
1756 {
1758 }
1759 
1760 //---- handling of system events -----------------------------------------------
1761 ////////////////////////////////////////////////////////////////////////////////
1762 /// Handle and dispatch signals.
1763 
1765 {
1766  if (sig == kSigInterrupt) {
1767  fSignals->Set(sig);
1768  fSigcnt++;
1769  }
1770  else {
1771  StackTrace();
1772  if (TROOT::Initialized()) {
1773  ::Throw(sig);
1774  }
1775  Abort(-1);
1776  }
1777 
1778  // check a-synchronous signals
1779  if (fSigcnt > 0 && fSignalHandler->GetSize() > 0)
1781 }
1782 
1783 ////////////////////////////////////////////////////////////////////////////////
1784 /// Check if some signals were raised and call their Notify() member.
1785 
1787 {
1788  TSignalHandler *sh;
1789  Int_t sigdone = -1;
1790  {
1791  TIter next(fSignalHandler);
1792 
1793  while (sh = (TSignalHandler*)next()) {
1794  if (sync == sh->IsSync()) {
1795  ESignals sig = sh->GetSignal();
1796  if ((fSignals->IsSet(sig) && sigdone == -1) || sigdone == sig) {
1797  if (sigdone == -1) {
1798  fSignals->Clr(sig);
1799  sigdone = sig;
1800  fSigcnt--;
1801  }
1802  sh->Notify();
1803  }
1804  }
1805  }
1806  }
1807  if (sigdone != -1) return kTRUE;
1808 
1809  return kFALSE;
1810 }
1811 
1812 ////////////////////////////////////////////////////////////////////////////////
1813 /// Check if there is activity on some file descriptors and call their
1814 /// Notify() member.
1815 
1817 {
1818  TFileHandler *fh;
1819  Int_t fddone = -1;
1820  Bool_t read = kFALSE;
1821 
1823 
1824  while ((fh = (TFileHandler*) it.Next())) {
1825  Int_t fd = fh->GetFd();
1826  if (!fd) continue; // ignore TTermInputHandler
1827 
1828  if ((fReadready->IsSet(fd) && fddone == -1) ||
1829  (fddone == fd && read)) {
1830  if (fddone == -1) {
1831  fReadready->Clr(fd);
1832  fddone = fd;
1833  read = kTRUE;
1834  fNfd--;
1835  }
1836  fh->ReadNotify();
1837  }
1838  if ((fWriteready->IsSet(fd) && fddone == -1) ||
1839  (fddone == fd && !read)) {
1840  if (fddone == -1) {
1841  fWriteready->Clr(fd);
1842  fddone = fd;
1843  read = kFALSE;
1844  fNfd--;
1845  }
1846  fh->WriteNotify();
1847  }
1848  }
1849  if (fddone != -1) return kTRUE;
1850 
1851  return kFALSE;
1852 }
1853 
1854 //---- Directories -------------------------------------------------------------
1855 
1856 ////////////////////////////////////////////////////////////////////////////////
1857 /// Make a file system directory. Returns 0 in case of success and
1858 /// -1 if the directory could not be created (either already exists or
1859 /// illegal path name).
1860 /// If 'recursive' is true, makes parent directories as needed.
1861 
1862 int TWinNTSystem::mkdir(const char *name, Bool_t recursive)
1863 {
1864  if (recursive) {
1865  TString dirname = DirName(name);
1866  if (dirname.Length() == 0) {
1867  // well we should not have to make the root of the file system!
1868  // (and this avoid infinite recursions!)
1869  return 0;
1870  }
1871  if (IsAbsoluteFileName(name)) {
1872  // For some good reason DirName strips off the drive letter
1873  // (if present), we need it to make the directory on the
1874  // right disk, so let's put it back!
1875  const char driveletter = DriveName(name);
1876  if (driveletter) {
1877  dirname.Prepend(":");
1878  dirname.Prepend(driveletter);
1879  }
1880  }
1881  if (AccessPathName(dirname, kFileExists)) {
1882  int res = this->mkdir(dirname, kTRUE);
1883  if (res) return res;
1884  }
1885  if (!AccessPathName(name, kFileExists)) {
1886  return -1;
1887  }
1888  }
1889  return MakeDirectory(name);
1890 }
1891 
1892 ////////////////////////////////////////////////////////////////////////////////
1893 /// Make a WinNT file system directory. Returns 0 in case of success and
1894 /// -1 if the directory could not be created (either already exists or
1895 /// illegal path name).
1896 
1898 {
1899  TSystem *helper = FindHelper(name);
1900  if (helper) {
1901  return helper->MakeDirectory(name);
1902  }
1903  const char *proto = (strstr(name, "file:///")) ? "file://" : "file:";
1904 #ifdef WATCOM
1905  // It must be as follows
1906  if (!name) return 0;
1907  return ::mkdir(StripOffProto(name, proto));
1908 #else
1909  // but to be in line with TUnixSystem I did like this
1910  if (!name) return 0;
1911  return ::_mkdir(StripOffProto(name, proto));
1912 #endif
1913 }
1914 
1915 ////////////////////////////////////////////////////////////////////////////////
1916 /// Close a WinNT file system directory.
1917 
1919 {
1920  TSystem *helper = FindHelper(0, dirp);
1921  if (helper) {
1922  helper->FreeDirectory(dirp);
1923  return;
1924  }
1925 
1926  if (dirp) {
1927  ::FindClose(dirp);
1928  }
1929 }
1930 
1931 ////////////////////////////////////////////////////////////////////////////////
1932 /// Returns the next directory entry.
1933 
1934 const char *TWinNTSystem::GetDirEntry(void *dirp)
1935 {
1936  TSystem *helper = FindHelper(0, dirp);
1937  if (helper) {
1938  return helper->GetDirEntry(dirp);
1939  }
1940 
1941  if (dirp) {
1942  HANDLE searchFile = (HANDLE)dirp;
1943  if (fFirstFile) {
1944  // when calling TWinNTSystem::OpenDirectory(), the fFindFileData
1945  // structure is filled by a call to FindFirstFile().
1946  // So first returns this one, before calling FindNextFile()
1947  fFirstFile = kFALSE;
1948  return (const char *)fFindFileData.cFileName;
1949  }
1950  if (::FindNextFile(searchFile, &fFindFileData)) {
1951  return (const char *)fFindFileData.cFileName;
1952  }
1953  }
1954  return 0;
1955 }
1956 
1957 ////////////////////////////////////////////////////////////////////////////////
1958 /// Change directory.
1959 
1961 {
1962  Bool_t ret = (Bool_t) (::chdir(path) == 0);
1963  if (fWdpath != "")
1964  fWdpath = ""; // invalidate path cache
1965  return ret;
1966 }
1967 
1968 ////////////////////////////////////////////////////////////////////////////////
1969 ///
1970 /// Inline function to check for a double-backslash at the
1971 /// beginning of a string
1972 ///
1973 
1974 __inline BOOL DBL_BSLASH(LPCTSTR psz)
1975 {
1976  return (psz[0] == TEXT('\\') && psz[1] == TEXT('\\'));
1977 }
1978 
1979 ////////////////////////////////////////////////////////////////////////////////
1980 /// Returns TRUE if the given string is a UNC path.
1981 ///
1982 /// TRUE
1983 /// "\\foo\bar"
1984 /// "\\foo" <- careful
1985 /// "\\"
1986 /// FALSE
1987 /// "\foo"
1988 /// "foo"
1989 /// "c:\foo"
1990 
1991 BOOL PathIsUNC(LPCTSTR pszPath)
1992 {
1993  return DBL_BSLASH(pszPath);
1994 }
1995 
1996 #pragma data_seg(".text", "CODE")
1997 const TCHAR c_szColonSlash[] = TEXT(":\\");
1998 #pragma data_seg()
1999 
2000 ////////////////////////////////////////////////////////////////////////////////
2001 ///
2002 /// check if a path is a root
2003 ///
2004 /// returns:
2005 /// TRUE for "\" "X:\" "\\foo\asdf" "\\foo\"
2006 /// FALSE for others
2007 ///
2008 
2009 BOOL PathIsRoot(LPCTSTR pPath)
2010 {
2011  if (!IsDBCSLeadByte(*pPath)) {
2012  if (!lstrcmpi(pPath + 1, c_szColonSlash))
2013  // "X:\" case
2014  return TRUE;
2015  }
2016  if ((*pPath == TEXT('\\')) && (*(pPath + 1) == 0))
2017  // "\" case
2018  return TRUE;
2019  if (DBL_BSLASH(pPath)) {
2020  // smells like UNC name
2021  LPCTSTR p;
2022  int cBackslashes = 0;
2023  for (p = pPath + 2; *p; p = CharNext(p)) {
2024  if (*p == TEXT('\\') && (++cBackslashes > 1))
2025  return FALSE; // not a bare UNC name, therefore not a root dir
2026  }
2027  // end of string with only 1 more backslash
2028  // must be a bare UNC, which looks like a root dir
2029  return TRUE;
2030  }
2031  return FALSE;
2032 }
2033 
2034 ////////////////////////////////////////////////////////////////////////////////
2035 /// Open a directory. Returns 0 if directory does not exist.
2036 
2037 void *TWinNTSystem::OpenDirectory(const char *fdir)
2038 {
2039  TSystem *helper = FindHelper(fdir);
2040  if (helper) {
2041  return helper->OpenDirectory(fdir);
2042  }
2043 
2044  const char *proto = (strstr(fdir, "file:///")) ? "file://" : "file:";
2045  const char *sdir = StripOffProto(fdir, proto);
2046 
2047  char *dir = new char[MAX_PATH];
2048  if (IsShortcut(sdir)) {
2049  if (!ResolveShortCut(sdir, dir, MAX_PATH))
2050  strlcpy(dir, sdir,MAX_PATH);
2051  }
2052  else
2053  strlcpy(dir, sdir,MAX_PATH);
2054 
2055  int nche = strlen(dir)+3;
2056  char *entry = new char[nche];
2057  struct _stati64 finfo;
2058 
2059  if(PathIsUNC(dir)) {
2060  strlcpy(entry, dir,nche);
2061  if ((entry[strlen(dir)-1] == '/') || (entry[strlen(dir)-1] == '\\' )) {
2062  entry[strlen(dir)-1] = '\0';
2063  }
2064  if(PathIsRoot(entry)) {
2065  strlcat(entry,"\\",nche);
2066  }
2067  if (_stati64(entry, &finfo) < 0) {
2068  delete [] entry;
2069  delete [] dir;
2070  return 0;
2071  }
2072  }
2073  else {
2074  strlcpy(entry, dir,nche);
2075  if ((entry[strlen(dir)-1] == '/') || (entry[strlen(dir)-1] == '\\' )) {
2076  if(!PathIsRoot(entry))
2077  entry[strlen(dir)-1] = '\0';
2078  }
2079  if (_stati64(entry, &finfo) < 0) {
2080  delete [] entry;
2081  delete [] dir;
2082  return 0;
2083  }
2084  }
2085 
2086  if (finfo.st_mode & S_IFDIR) {
2087  strlcpy(entry, dir,nche);
2088  if (!(entry[strlen(dir)-1] == '/' || entry[strlen(dir)-1] == '\\' )) {
2089  strlcat(entry,"\\",nche);
2090  }
2091  strlcat(entry,"*",nche);
2092 
2093  HANDLE searchFile;
2094  searchFile = ::FindFirstFile(entry, &fFindFileData);
2095  if (searchFile == INVALID_HANDLE_VALUE) {
2096  ((TWinNTSystem *)gSystem)->Error( "Unable to find' for reading:", entry);
2097  delete [] entry;
2098  delete [] dir;
2099  return 0;
2100  }
2101  delete [] entry;
2102  delete [] dir;
2103  fFirstFile = kTRUE;
2104  return searchFile;
2105  } else {
2106  delete [] entry;
2107  delete [] dir;
2108  return 0;
2109  }
2110 }
2111 
2112 ////////////////////////////////////////////////////////////////////////////////
2113 /// Return the working directory for the default drive
2114 
2116 {
2117  return WorkingDirectory('\0');
2118 }
2119 
2120 ////////////////////////////////////////////////////////////////////////////////
2121 /// Return working directory for the selected drive
2122 /// driveletter == 0 means return the working durectory for the default drive
2123 
2124 const char *TWinNTSystem::WorkingDirectory(char driveletter)
2125 {
2126  char *wdpath = 0;
2127  char drive = driveletter ? toupper( driveletter ) - 'A' + 1 : 0;
2128 
2129  // don't use cache as user can call chdir() directly somewhere else
2130  //if (fWdpath != "" )
2131  // return fWdpath;
2132 
2133  if (!(wdpath = ::_getdcwd( (int)drive, wdpath, kMAXPATHLEN))) {
2134  free(wdpath);
2135  Warning("WorkingDirectory", "getcwd() failed");
2136  return 0;
2137  }
2138  fWdpath = wdpath;
2139  // Make sure the drive letter is upper case
2140  if (fWdpath[1] == ':')
2141  fWdpath[0] = toupper(fWdpath[0]);
2142  free(wdpath);
2143  return fWdpath;
2144 }
2145 
2146 ////////////////////////////////////////////////////////////////////////////////
2147 /// Return the user's home directory.
2148 
2149 const char *TWinNTSystem::HomeDirectory(const char *userName)
2150 {
2151  static char mydir[kMAXPATHLEN] = "./";
2152  const char *h = 0;
2153  if (!(h = ::getenv("home"))) h = ::getenv("HOME");
2154 
2155  if (h) {
2156  strlcpy(mydir, h,kMAXPATHLEN);
2157  } else {
2158  // for Windows NT HOME might be defined as either $(HOMESHARE)/$(HOMEPATH)
2159  // or $(HOMEDRIVE)/$(HOMEPATH)
2160  h = ::getenv("HOMESHARE");
2161  if (!h) h = ::getenv("HOMEDRIVE");
2162  if (h) {
2163  strlcpy(mydir, h,kMAXPATHLEN);
2164  h = ::getenv("HOMEPATH");
2165  if(h) strlcat(mydir, h,kMAXPATHLEN);
2166  }
2167  // on Windows Vista HOME is usually defined as $(USERPROFILE)
2168  if (!h) {
2169  h = ::getenv("USERPROFILE");
2170  if (h) strlcpy(mydir, h,kMAXPATHLEN);
2171  }
2172  }
2173  // Make sure the drive letter is upper case
2174  if (mydir[1] == ':')
2175  mydir[0] = toupper(mydir[0]);
2176  return mydir;
2177 }
2178 
2179 ////////////////////////////////////////////////////////////////////////////////
2180 /// Return a user configured or systemwide directory to create
2181 /// temporary files in.
2182 
2183 const char *TWinNTSystem::TempDirectory() const
2184 {
2185  const char *dir = gSystem->Getenv("TEMP");
2186  if (!dir) dir = gSystem->Getenv("TEMPDIR");
2187  if (!dir) dir = gSystem->Getenv("TEMP_DIR");
2188  if (!dir) dir = gSystem->Getenv("TMP");
2189  if (!dir) dir = gSystem->Getenv("TMPDIR");
2190  if (!dir) dir = gSystem->Getenv("TMP_DIR");
2191  if (!dir) dir = "c:\\";
2192 
2193  return dir;
2194 }
2195 
2196 ////////////////////////////////////////////////////////////////////////////////
2197 /// Create a secure temporary file by appending a unique
2198 /// 6 letter string to base. The file will be created in
2199 /// a standard (system) directory or in the directory
2200 /// provided in dir. The full filename is returned in base
2201 /// and a filepointer is returned for safely writing to the file
2202 /// (this avoids certain security problems). Returns 0 in case
2203 /// of error.
2204 
2205 FILE *TWinNTSystem::TempFileName(TString &base, const char *dir)
2206 {
2207  char tmpName[MAX_PATH];
2208 
2209  ::GetTempFileName(dir ? dir : TempDirectory(), base.Data(), 0, tmpName);
2210  base = tmpName;
2211  FILE *fp = fopen(tmpName, "w+");
2212 
2213  if (!fp) ::SysError("TempFileName", "error opening %s", tmpName);
2214 
2215  return fp;
2216 }
2217 
2218 //---- Paths & Files -----------------------------------------------------------
2219 
2220 ////////////////////////////////////////////////////////////////////////////////
2221 /// Get list of volumes (drives) mounted on the system.
2222 /// The returned TList must be deleted by the user using "delete".
2223 
2225 {
2226  Int_t curdrive;
2227  UInt_t type;
2228  TString sDrive, sType;
2229  char szFs[32];
2230 
2231  if (!opt || !opt[0]) {
2232  return 0;
2233  }
2234 
2235  // prevent the system dialog box to pop-up if a drive is empty
2236  UINT nOldErrorMode = ::SetErrorMode(SEM_FAILCRITICALERRORS);
2237  TList *drives = new TList();
2238  drives->SetOwner();
2239  // Save current drive
2240  curdrive = _getdrive();
2241  if (strstr(opt, "cur")) {
2242  *szFs='\0';
2243  sDrive.Form("%c:", (curdrive + 'A' - 1));
2244  sType.Form("Unknown Drive (%s)", sDrive.Data());
2245  ::GetVolumeInformation(Form("%s\\", sDrive.Data()), NULL, 0, NULL, NULL,
2246  NULL, (LPSTR)szFs, 32);
2247  type = ::GetDriveType(sDrive.Data());
2248  switch (type) {
2249  case DRIVE_UNKNOWN:
2250  case DRIVE_NO_ROOT_DIR:
2251  break;
2252  case DRIVE_REMOVABLE:
2253  sType.Form("Removable Disk (%s)", sDrive.Data());
2254  break;
2255  case DRIVE_FIXED:
2256  sType.Form("Local Disk (%s)", sDrive.Data());
2257  break;
2258  case DRIVE_REMOTE:
2259  sType.Form("Network Drive (%s) (%s)", szFs, sDrive.Data());
2260  break;
2261  case DRIVE_CDROM:
2262  sType.Form("CD/DVD Drive (%s)", sDrive.Data());
2263  break;
2264  case DRIVE_RAMDISK:
2265  sType.Form("RAM Disk (%s)", sDrive.Data());
2266  break;
2267  }
2268  drives->Add(new TNamed(sDrive.Data(), sType.Data()));
2269  }
2270  else if (strstr(opt, "all")) {
2271  TCHAR szTemp[512];
2272  szTemp[0] = '\0';
2273  if (::GetLogicalDriveStrings(511, szTemp)) {
2274  TCHAR szDrive[3] = TEXT(" :");
2275  TCHAR* p = szTemp;
2276  do {
2277  // Copy the drive letter to the template string
2278  *szDrive = *p;
2279  *szFs='\0';
2280  sDrive.Form("%s", szDrive);
2281  // skip floppy drives, to avoid accessing them each time...
2282  if ((sDrive == "A:") || (sDrive == "B:")) {
2283  while (*p++);
2284  continue;
2285  }
2286  sType.Form("Unknown Drive (%s)", sDrive.Data());
2287  ::GetVolumeInformation(Form("%s\\", sDrive.Data()), NULL, 0, NULL,
2288  NULL, NULL, (LPSTR)szFs, 32);
2289  type = ::GetDriveType(sDrive.Data());
2290  switch (type) {
2291  case DRIVE_UNKNOWN:
2292  case DRIVE_NO_ROOT_DIR:
2293  break;
2294  case DRIVE_REMOVABLE:
2295  sType.Form("Removable Disk (%s)", sDrive.Data());
2296  break;
2297  case DRIVE_FIXED:
2298  sType.Form("Local Disk (%s)", sDrive.Data());
2299  break;
2300  case DRIVE_REMOTE:
2301  sType.Form("Network Drive (%s) (%s)", szFs, sDrive.Data());
2302  break;
2303  case DRIVE_CDROM:
2304  sType.Form("CD/DVD Drive (%s)", sDrive.Data());
2305  break;
2306  case DRIVE_RAMDISK:
2307  sType.Form("RAM Disk (%s)", sDrive.Data());
2308  break;
2309  }
2310  drives->Add(new TNamed(sDrive.Data(), sType.Data()));
2311  // Go to the next NULL character.
2312  while (*p++);
2313  } while (*p); // end of string
2314  }
2315  }
2316  // restore previous error mode
2317  ::SetErrorMode(nOldErrorMode);
2318  return drives;
2319 }
2320 
2321 ////////////////////////////////////////////////////////////////////////////////
2322 /// Return the directory name in pathname. DirName of c:/user/root is /user.
2323 /// It creates output with 'new char []' operator. Returned string has to
2324 /// be deleted.
2325 
2326 const char *TWinNTSystem::DirName(const char *pathname)
2327 {
2328  // Delete old buffer
2329  if (fDirNameBuffer) {
2330  // delete [] fDirNameBuffer;
2331  fDirNameBuffer = 0;
2332  }
2333 
2334  // Create a buffer to keep the path name
2335  if (pathname) {
2336  if (strchr(pathname, '/') || strchr(pathname, '\\')) {
2337  const char *rslash = strrchr(pathname, '/');
2338  const char *bslash = strrchr(pathname, '\\');
2339  const char *r = std::max(rslash, bslash);
2340  const char *ptr = pathname;
2341  while (ptr <= r) {
2342  if (*ptr == ':') {
2343  // Windows path may contain a drive letter
2344  // For NTFS ":" may be a "stream" delimiter as well
2345  pathname = ptr + 1;
2346  break;
2347  }
2348  ptr++;
2349  }
2350  int len = r - pathname;
2351  if (len > 0) {
2352  fDirNameBuffer = new char[len+1];
2353  memcpy(fDirNameBuffer, pathname, len);
2354  fDirNameBuffer[len] = 0;
2355  }
2356  }
2357  }
2358  if (!fDirNameBuffer) {
2359  fDirNameBuffer = new char[1];
2360  *fDirNameBuffer = '\0'; // Set the empty default response
2361  }
2362  return fDirNameBuffer;
2363 }
2364 
2365 ////////////////////////////////////////////////////////////////////////////////
2366 /////////////////////////////////////////////////////////////////////////////
2367 /// Return the drive letter in pathname. DriveName of 'c:/user/root' is 'c'//
2368 /// Input: //
2369 /// pathname - the string containing file name //
2370 /// Return: //
2371 /// = Letter presenting the drive letter in the file name //
2372 /// = The current drive if the pathname has no drive assigment //
2373 /// = 0 if pathname is an empty string or uses UNC syntax //
2374 /// Note: //
2375 /// It doesn't chech whether pathname presents the 'real filename //
2376 /// This subroutine looks for 'single letter' is follows with a ':' //
2377 /////////////////////////////////////////////////////////////////////////////
2378 
2379 const char TWinNTSystem::DriveName(const char *pathname)
2380 {
2381  if (!pathname) return 0;
2382  if (!pathname[0]) return 0;
2383 
2384  const char *lpchar;
2385  lpchar = pathname;
2386 
2387  // Skip blanks
2388  while(*lpchar == ' ') lpchar++;
2389 
2390  if (isalpha((int)*lpchar) && *(lpchar+1) == ':') {
2391  return *lpchar;
2392  }
2393  // Test UNC syntax
2394  if ( (*lpchar == '\\' || *lpchar == '/' ) &&
2395  (*(lpchar+1) == '\\' || *(lpchar+1) == '/') ) return 0;
2396 
2397  // return the current drive
2398  return DriveName(WorkingDirectory());
2399 }
2400 
2401 ////////////////////////////////////////////////////////////////////////////////
2402 /// Return true if dir is an absolute pathname.
2403 
2405 {
2406  if (dir) {
2407  int idx = 0;
2408  if (strchr(dir,':')) idx = 2;
2409  return (dir[idx] == '/' || dir[idx] == '\\');
2410  }
2411  return kFALSE;
2412 }
2413 
2414 ////////////////////////////////////////////////////////////////////////////////
2415 /// Convert a pathname to a unix pathname. E.g. form \user\root to /user/root.
2416 /// General rules for applications creating names for directories and files or
2417 /// processing names supplied by the user include the following:
2418 ///
2419 /// * Use any character in the current code page for a name, but do not use
2420 /// a path separator, a character in the range 0 through 31, or any character
2421 /// explicitly disallowed by the file system. A name can contain characters
2422 /// in the extended character set (128-255).
2423 /// * Use the backslash (\), the forward slash (/), or both to separate
2424 /// components in a path. No other character is acceptable as a path separator.
2425 /// * Use a period (.) as a directory component in a path to represent the
2426 /// current directory.
2427 /// * Use two consecutive periods (..) as a directory component in a path to
2428 /// represent the parent of the current directory.
2429 /// * Use a period (.) to separate components in a directory name or filename.
2430 /// * Do not use the following characters in directory names or filenames, because
2431 /// they are reserved for Windows:
2432 /// < > : " / \ |
2433 /// * Do not use reserved words, such as aux, con, and prn, as filenames or
2434 /// directory names.
2435 /// * Process a path as a null-terminated string. The maximum length for a path
2436 /// is given by MAX_PATH.
2437 /// * Do not assume case sensitivity. Consider names such as OSCAR, Oscar, and
2438 /// oscar to be the same.
2439 
2440 const char *TWinNTSystem::UnixPathName(const char *name)
2441 {
2442  static char temp[1024];
2443  strlcpy(temp, name,1024);
2444  char *currentChar = temp;
2445 
2446  while (*currentChar != '\0') {
2447  if (*currentChar == '\\') *currentChar = '/';
2448  currentChar++;
2449  }
2450  return temp;
2451 }
2452 
2453 ////////////////////////////////////////////////////////////////////////////////
2454 /// Returns FALSE if one can access a file using the specified access mode.
2455 /// Mode is the same as for the WinNT access(2) function.
2456 /// Attention, bizarre convention of return value!!
2457 
2459 {
2460  TSystem *helper = FindHelper(path);
2461  if (helper)
2462  return helper->AccessPathName(path, mode);
2463 
2464  // prevent the system dialog box to pop-up if a drive is empty
2465  UINT nOldErrorMode = ::SetErrorMode(SEM_FAILCRITICALERRORS);
2466  if (mode==kExecutePermission)
2467  // cannot test on exe - use read instead
2468  mode=kReadPermission;
2469  const char *proto = (strstr(path, "file:///")) ? "file://" : "file:";
2470  if (::_access(StripOffProto(path, proto), mode) == 0) {
2471  // restore previous error mode
2472  ::SetErrorMode(nOldErrorMode);
2473  return kFALSE;
2474  }
2476  // restore previous error mode
2477  ::SetErrorMode(nOldErrorMode);
2478  return kTRUE;
2479 }
2480 
2481 ////////////////////////////////////////////////////////////////////////////////
2482 /// Returns TRUE if the url in 'path' points to the local file system.
2483 /// This is used to avoid going through the NIC card for local operations.
2484 
2486 {
2487  TSystem *helper = FindHelper(path);
2488  if (helper)
2489  return helper->IsPathLocal(path);
2490 
2491  return TSystem::IsPathLocal(path);
2492 }
2493 
2494 ////////////////////////////////////////////////////////////////////////////////
2495 /// Concatenate a directory and a file name.
2496 
2497 const char *TWinNTSystem::PrependPathName(const char *dir, TString& name)
2498 {
2499  if (name == ".") name = "";
2500  if (dir && dir[0]) {
2501  // Test whether the last symbol of the directory is a separator
2502  char last = dir[strlen(dir) - 1];
2503  if (last != '/' && last != '\\') {
2504  name.Prepend('\\');
2505  }
2506  name.Prepend(dir);
2507  name.ReplaceAll("/", "\\");
2508  }
2509  return name.Data();
2510 }
2511 
2512 ////////////////////////////////////////////////////////////////////////////////
2513 /// Copy a file. If overwrite is true and file already exists the
2514 /// file will be overwritten. Returns 0 when successful, -1 in case
2515 /// of failure, -2 in case the file already exists and overwrite was false.
2516 
2517 int TWinNTSystem::CopyFile(const char *f, const char *t, Bool_t overwrite)
2518 {
2519  if (AccessPathName(f, kReadPermission)) return -1;
2520  if (!AccessPathName(t) && !overwrite) return -2;
2521 
2522  Bool_t ret = ::CopyFileA(f, t, kFALSE);
2523 
2524  if (!ret) return -1;
2525  return 0;
2526 }
2527 
2528 ////////////////////////////////////////////////////////////////////////////////
2529 /// Rename a file. Returns 0 when successful, -1 in case of failure.
2530 
2531 int TWinNTSystem::Rename(const char *f, const char *t)
2532 {
2533  int ret = ::rename(f, t);
2535  return ret;
2536 }
2537 
2538 ////////////////////////////////////////////////////////////////////////////////
2539 /// Get info about a file. Info is returned in the form of a FileStat_t
2540 /// structure (see TSystem.h).
2541 /// The function returns 0 in case of success and 1 if the file could
2542 /// not be stat'ed.
2543 
2544 int TWinNTSystem::GetPathInfo(const char *path, FileStat_t &buf)
2545 {
2546  TSystem *helper = FindHelper(path);
2547  if (helper)
2548  return helper->GetPathInfo(path, buf);
2549 
2550  struct _stati64 sbuf;
2551 
2552  // Remove trailing backslashes
2553  const char *proto = (strstr(path, "file:///")) ? "file://" : "file:";
2554  char *newpath = StrDup(StripOffProto(path, proto));
2555  int l = strlen(newpath);
2556  while (l > 1) {
2557  if (newpath[--l] != '\\' || newpath[--l] != '/') {
2558  break;
2559  }
2560  newpath[l] = '\0';
2561  }
2562 
2563  if (newpath && ::_stati64(newpath, &sbuf) >= 0) {
2564 
2565  buf.fDev = sbuf.st_dev;
2566  buf.fIno = sbuf.st_ino;
2567  buf.fMode = sbuf.st_mode;
2568  buf.fUid = sbuf.st_uid;
2569  buf.fGid = sbuf.st_gid;
2570  buf.fSize = sbuf.st_size;
2571  buf.fMtime = sbuf.st_mtime;
2572  buf.fIsLink = IsShortcut(newpath); // kFALSE;
2573 
2574  char *lpath = new char[MAX_PATH];
2575  if (IsShortcut(newpath)) {
2576  struct _stati64 sbuf2;
2577  if (ResolveShortCut(newpath, lpath, MAX_PATH)) {
2578  if (::_stati64(lpath, &sbuf2) >= 0) {
2579  buf.fMode = sbuf2.st_mode;
2580  }
2581  }
2582  }
2583  delete [] lpath;
2584 
2585  delete [] newpath;
2586  return 0;
2587  }
2588  delete [] newpath;
2589  return 1;
2590 }
2591 
2592 ////////////////////////////////////////////////////////////////////////////////
2593 /// Get info about a file system: id, bsize, bfree, blocks.
2594 /// Id is file system type (machine dependend, see statfs())
2595 /// Bsize is block size of file system
2596 /// Blocks is total number of blocks in file system
2597 /// Bfree is number of free blocks in file system
2598 /// The function returns 0 in case of success and 1 if the file system could
2599 /// not be stat'ed.
2600 
2601 int TWinNTSystem::GetFsInfo(const char *path, Long_t *id, Long_t *bsize,
2602  Long_t *blocks, Long_t *bfree)
2603 {
2604  // address of root directory of the file system
2605  LPCTSTR lpRootPathName = path;
2606 
2607  // address of name of the volume
2608  LPTSTR lpVolumeNameBuffer = 0;
2609  DWORD nVolumeNameSize = 0;
2610 
2611  DWORD volumeSerialNumber; // volume serial number
2612  DWORD maximumComponentLength; // system's maximum filename length
2613 
2614  // file system flags
2615  DWORD fileSystemFlags;
2616 
2617  // address of name of file system
2618  char fileSystemNameBuffer[512];
2619  DWORD nFileSystemNameSize = sizeof(fileSystemNameBuffer);
2620 
2621  // prevent the system dialog box to pop-up if the drive is empty
2622  UINT nOldErrorMode = ::SetErrorMode(SEM_FAILCRITICALERRORS);
2623  if (!::GetVolumeInformation(lpRootPathName,
2624  lpVolumeNameBuffer, nVolumeNameSize,
2625  &volumeSerialNumber,
2626  &maximumComponentLength,
2627  &fileSystemFlags,
2628  fileSystemNameBuffer, nFileSystemNameSize)) {
2629  // restore previous error mode
2630  ::SetErrorMode(nOldErrorMode);
2631  return 1;
2632  }
2633 
2634  const char *fsNames[] = { "FAT", "NTFS" };
2635  int i;
2636  for (i = 0; i < 2; i++) {
2637  if (!strncmp(fileSystemNameBuffer, fsNames[i], nFileSystemNameSize))
2638  break;
2639  }
2640  *id = i;
2641 
2642  DWORD sectorsPerCluster; // # sectors per cluster
2643  DWORD bytesPerSector; // # bytes per sector
2644  DWORD numberOfFreeClusters; // # free clusters
2645  DWORD totalNumberOfClusters; // # total of clusters
2646 
2647  if (!::GetDiskFreeSpace(lpRootPathName,
2648  &sectorsPerCluster,
2649  &bytesPerSector,
2650  &numberOfFreeClusters,
2651  &totalNumberOfClusters)) {
2652  // restore previous error mode
2653  ::SetErrorMode(nOldErrorMode);
2654  return 1;
2655  }
2656  // restore previous error mode
2657  ::SetErrorMode(nOldErrorMode);
2658 
2659  *bsize = sectorsPerCluster * bytesPerSector;
2660  *blocks = totalNumberOfClusters;
2661  *bfree = numberOfFreeClusters;
2662 
2663  return 0;
2664 }
2665 
2666 ////////////////////////////////////////////////////////////////////////////////
2667 /// Create a link from file1 to file2.
2668 
2669 int TWinNTSystem::Link(const char *from, const char *to)
2670 {
2671  struct _stati64 finfo;
2672  char winDrive[256];
2673  char winDir[256];
2674  char winName[256];
2675  char winExt[256];
2676  char linkname[1024];
2677  LPTSTR lpszFilePart;
2678  TCHAR szPath[MAX_PATH];
2679  DWORD dwRet = 0;
2680 
2681  typedef BOOL (__stdcall *CREATEHARDLINKPROC)( LPCTSTR, LPCTSTR, LPSECURITY_ATTRIBUTES );
2682  static CREATEHARDLINKPROC _CreateHardLink = 0;
2683 
2684  HMODULE hModImagehlp = LoadLibrary( "Kernel32.dll" );
2685  if (!hModImagehlp)
2686  return -1;
2687 
2688 #ifdef _UNICODE
2689  _CreateHardLink = (CREATEHARDLINKPROC) GetProcAddress( hModImagehlp, "CreateHardLinkW" );
2690 #else
2691  _CreateHardLink = (CREATEHARDLINKPROC) GetProcAddress( hModImagehlp, "CreateHardLinkA" );
2692 #endif
2693  if (!_CreateHardLink)
2694  return -1;
2695 
2696  dwRet = GetFullPathName(from, sizeof(szPath) / sizeof(TCHAR),
2697  szPath, &lpszFilePart);
2698 
2699  if (_stati64(szPath, &finfo) < 0)
2700  return -1;
2701 
2702  if (finfo.st_mode & S_IFDIR)
2703  return -1;
2704 
2705  snprintf(linkname,1024,"%s",to);
2706  _splitpath(linkname,winDrive,winDir,winName,winExt);
2707  if ((!winDrive[0] ) &&
2708  (!winDir[0] )) {
2709  _splitpath(szPath,winDrive,winDir,winName,winExt);
2710  snprintf(linkname,1024,"%s\\%s\\%s", winDrive, winDir, to);
2711  }
2712  else if (!winDrive[0]) {
2713  _splitpath(szPath,winDrive,winDir,winName,winExt);
2714  snprintf(linkname,1024,"%s\\%s", winDrive, to);
2715  }
2716 
2717  if (!_CreateHardLink(linkname, szPath, NULL))
2718  return -1;
2719 
2720  return 0;
2721 }
2722 
2723 ////////////////////////////////////////////////////////////////////////////////
2724 /// Create a symlink from file1 to file2. Returns 0 when successful,
2725 /// -1 in case of failure.
2726 
2727 int TWinNTSystem::Symlink(const char *from, const char *to)
2728 {
2729  HRESULT hRes; /* Returned COM result code */
2730  IShellLink* pShellLink; /* IShellLink object pointer */
2731  IPersistFile* pPersistFile; /* IPersistFile object pointer */
2732  WCHAR wszLinkfile[MAX_PATH]; /* pszLinkfile as Unicode string */
2733  int iWideCharsWritten; /* Number of wide characters written */
2734  DWORD dwRet = 0;
2735  LPTSTR lpszFilePart;
2736  TCHAR szPath[MAX_PATH];
2737 
2738  hRes = E_INVALIDARG;
2739  if ((from == NULL) || (!from[0]) || (to == NULL) ||
2740  (!to[0]))
2741  return -1;
2742 
2743  // Make typedefs for some ole32.dll functions so that we can use them
2744  // with GetProcAddress
2745  typedef HRESULT (__stdcall *COINITIALIZEPROC)( LPVOID );
2746  static COINITIALIZEPROC _CoInitialize = 0;
2747  typedef void (__stdcall *COUNINITIALIZEPROC)( void );
2748  static COUNINITIALIZEPROC _CoUninitialize = 0;
2749  typedef HRESULT (__stdcall *COCREATEINSTANCEPROC)( REFCLSID, LPUNKNOWN, DWORD, REFIID, LPVOID );
2750  static COCREATEINSTANCEPROC _CoCreateInstance = 0;
2751 
2752  HMODULE hModImagehlp = LoadLibrary( "ole32.dll" );
2753  if (!hModImagehlp)
2754  return -1;
2755 
2756  _CoInitialize = (COINITIALIZEPROC) GetProcAddress( hModImagehlp, "CoInitialize" );
2757  if (!_CoInitialize)
2758  return -1;
2759  _CoUninitialize = (COUNINITIALIZEPROC) GetProcAddress( hModImagehlp, "CoUninitialize" );
2760  if (!_CoUninitialize)
2761  return -1;
2762  _CoCreateInstance = (COCREATEINSTANCEPROC) GetProcAddress( hModImagehlp, "CoCreateInstance" );
2763  if (!_CoCreateInstance)
2764  return -1;
2765 
2766  TString linkname(to);
2767  if (!linkname.EndsWith(".lnk"))
2768  linkname.Append(".lnk");
2769 
2770  _CoInitialize(NULL);
2771 
2772  // Retrieve the full path and file name of a specified file
2773  dwRet = GetFullPathName(from, sizeof(szPath) / sizeof(TCHAR),
2774  szPath, &lpszFilePart);
2775  hRes = _CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2776  IID_IShellLink, (LPVOID *)&pShellLink);
2777  if (SUCCEEDED(hRes)) {
2778  // Set the fields in the IShellLink object
2779  hRes = pShellLink->SetPath(szPath);
2780  // Use the IPersistFile object to save the shell link
2781  hRes = pShellLink->QueryInterface(IID_IPersistFile, (void **)&pPersistFile);
2782  if (SUCCEEDED(hRes)){
2783  iWideCharsWritten = MultiByteToWideChar(CP_ACP, 0, linkname.Data(), -1,
2784  wszLinkfile, MAX_PATH);
2785  hRes = pPersistFile->Save(wszLinkfile, TRUE);
2786  pPersistFile->Release();
2787  }
2788  pShellLink->Release();
2789  }
2790  _CoUninitialize();
2791  return 0;
2792 }
2793 
2794 ////////////////////////////////////////////////////////////////////////////////
2795 /// Unlink, i.e. remove, a file or directory.
2796 
2797 int TWinNTSystem::Unlink(const char *name)
2798 {
2799  TSystem *helper = FindHelper(name);
2800  if (helper)
2801  return helper->Unlink(name);
2802 
2803  struct _stati64 finfo;
2804 
2805  if (_stati64(name, &finfo) < 0) {
2806  return -1;
2807  }
2808 
2809  if (finfo.st_mode & S_IFDIR) {
2810  return ::_rmdir(name);
2811  } else {
2812  return ::_unlink(name);
2813  }
2814 }
2815 
2816 ////////////////////////////////////////////////////////////////////////////////
2817 /// Make descriptor fd non-blocking.
2818 
2820 {
2821  if (::ioctlsocket(fd, FIONBIO, (u_long *)1) == SOCKET_ERROR) {
2822  ::SysError("SetNonBlock", "ioctlsocket");
2823  return -1;
2824  }
2825  return 0;
2826 }
2827 
2828 // expand the metacharacters as in the shell
2829 
2830 static char
2831  *shellMeta = "~*[]{}?$%",
2832  *shellStuff = "(){}<>\"'",
2833  shellEscape = '\\';
2834 
2835 ////////////////////////////////////////////////////////////////////////////////
2836 /// Expand a pathname getting rid of special shell characaters like ~.$, etc.
2837 
2839 {
2840  const char *patbuf = (const char *)patbuf0;
2841  const char *p;
2842  char *cmd = 0;
2843  char *q;
2844 
2845  Int_t old_level = gErrorIgnoreLevel;
2846  gErrorIgnoreLevel = kFatal; // Explicitly remove all messages
2847  TUrl urlpath(patbuf0, kTRUE);
2848  TString proto = urlpath.GetProtocol();
2849  gErrorIgnoreLevel = old_level;
2850  if (!proto.EqualTo("file")) // don't expand urls!!!
2851  return kFALSE;
2852 
2853  // skip the "file:" protocol, if any
2854  if (patbuf0.BeginsWith("file:"))
2855  patbuf += 5;
2856 
2857  // skip leading blanks
2858  while (*patbuf == ' ') {
2859  patbuf++;
2860  }
2861 
2862  // skip leading ':'
2863  while (*patbuf == ':') {
2864  patbuf++;
2865  }
2866 
2867  // skip leading ';'
2868  while (*patbuf == ';') {
2869  patbuf++;
2870  }
2871 
2872  // Transform a Unix list of directories into a Windows list
2873  // by changing the separator from ':' into ';'
2874  for (q = (char*)patbuf; *q; q++) {
2875  if ( *q == ':' ) {
2876  // We are avoiding substitution in the case of
2877  // ....;c:.... and of ...;root:/... where root can be any url protocol
2878  if ( (((q-2)>patbuf) && ( (*(q-2)!=';') || !isalpha(*(q-1)) )) &&
2879  *(q+1)!='/' ) {
2880  *q=';';
2881  }
2882  }
2883  }
2884  // any shell meta characters ?
2885  for (p = patbuf; *p; p++) {
2886  if (strchr(shellMeta, *p)) {
2887  goto needshell;
2888  }
2889  }
2890  return kFALSE;
2891 
2892 needshell:
2893 
2894  // Because (problably) we built with cygwin, the path name like:
2895  // LOCALS~1\\Temp
2896  // gets extended to
2897  // LOCALSc:\\Devel
2898  // The most likely cause is that '~' is used with Unix semantic of the
2899  // home directory (and it also cuts the path short after ... who knows why!)
2900  // So we need to detect this case and prevents its expansion :(.
2901 
2902  char replacement[4];
2903 
2904  // intentionally a non visible, unlikely character
2905  for (int k = 0; k<3; k++) replacement[k] = 0x1;
2906 
2907  replacement[3] = 0x0;
2908  Ssiz_t pos = 0;
2909  TRegexp TildaNum = "~[0-9]";
2910 
2911  while ( (pos = patbuf0.Index(TildaNum,pos)) != kNPOS ) {
2912  patbuf0.Replace(pos, 1, replacement);
2913  }
2914 
2915  // escape shell quote characters
2916  // EscChar(patbuf, stuffedPat, sizeof(stuffedPat), shellStuff, shellEscape);
2917  patbuf0 = ExpandFileName(patbuf0.Data());
2918  Int_t lbuf = ::ExpandEnvironmentStrings(
2919  patbuf0.Data(), // pointer to string with environment variables
2920  cmd, // pointer to string with expanded environment variables
2921  0 // maximum characters in expanded string
2922  );
2923  if (lbuf > 0) {
2924  cmd = new char[lbuf+1];
2925  ::ExpandEnvironmentStrings(
2926  patbuf0.Data(), // pointer to string with environment variables
2927  cmd, // pointer to string with expanded environment variables
2928  lbuf // maximum characters in expanded string
2929  );
2930  patbuf0 = cmd;
2931  patbuf0.ReplaceAll(replacement, "~");
2932  delete [] cmd;
2933  return kFALSE;
2934  }
2935  return kTRUE;
2936 }
2937 
2938 ////////////////////////////////////////////////////////////////////////////////
2939 /// Expand a pathname getting rid of special shell characaters like ~.$, etc.
2940 /// User must delete returned string.
2941 
2942 char *TWinNTSystem::ExpandPathName(const char *path)
2943 {
2944  char newpath[MAX_PATH];
2945  if (IsShortcut(path)) {
2946  if (!ResolveShortCut(path, newpath, MAX_PATH))
2947  strlcpy(newpath, path, MAX_PATH);
2948  }
2949  else
2950  strlcpy(newpath, path, MAX_PATH);
2951  TString patbuf = newpath;
2952  if (ExpandPathName(patbuf)) return 0;
2953 
2954  return StrDup(patbuf.Data());
2955 }
2956 
2957 ////////////////////////////////////////////////////////////////////////////////
2958 /// Set the file permission bits. Returns -1 in case or error, 0 otherwise.
2959 /// On windows mode can only be a combination of "user read" (0400),
2960 /// "user write" (0200) or "user read | user write" (0600). Any other value
2961 /// for mode are ignored.
2962 
2963 int TWinNTSystem::Chmod(const char *file, UInt_t mode)
2964 {
2965  return ::_chmod(file, mode);
2966 }
2967 
2968 ////////////////////////////////////////////////////////////////////////////////
2969 /// Set the process file creation mode mask.
2970 
2972 {
2973  return ::umask(mask);
2974 }
2975 
2976 ////////////////////////////////////////////////////////////////////////////////
2977 /// Set a files modification and access times. If actime = 0 it will be
2978 /// set to the modtime. Returns 0 on success and -1 in case of error.
2979 
2980 int TWinNTSystem::Utime(const char *file, Long_t modtime, Long_t actime)
2981 {
2982  if (AccessPathName(file, kWritePermission)) {
2983  Error("Utime", "need write permission for %s to change utime", file);
2984  return -1;
2985  }
2986  if (!actime) actime = modtime;
2987 
2988  struct utimbuf t;
2989  t.actime = (time_t)actime;
2990  t.modtime = (time_t)modtime;
2991  return ::utime(file, &t);
2992 }
2993 
2994 ////////////////////////////////////////////////////////////////////////////////
2995 /// Find location of file in a search path.
2996 /// User must delete returned string. Returns 0 in case file is not found.
2997 
2998 const char *TWinNTSystem::FindFile(const char *search, TString& infile, EAccessMode mode)
2999 {
3000  // Windows cannot check on execution mode - all we can do is kReadPermission
3001  if (mode==kExecutePermission)
3002  mode=kReadPermission;
3003 
3004  // Expand parameters
3005 
3006  gSystem->ExpandPathName(infile);
3007  // Check whether this infile has the absolute path first
3008  if (IsAbsoluteFileName(infile.Data()) ) {
3009  if (!AccessPathName(infile.Data(), mode))
3010  return infile.Data();
3011  infile = "";
3012  return 0;
3013  }
3014  TString exsearch(search);
3015  gSystem->ExpandPathName(exsearch);
3016 
3017  // Need to use Windows delimiters
3018  Int_t lastDelim = -1;
3019  for(int i=0; i < exsearch.Length(); ++i) {
3020  switch( exsearch[i] ) {
3021  case ':':
3022  // Replace the ':' unless there are after a disk suffix (aka ;c:\mydirec...)
3023  if (i-lastDelim!=2) exsearch[i] = ';';
3024  lastDelim = i;
3025  break;
3026  case ';': lastDelim = i; break;
3027  }
3028  }
3029 
3030  // Check access
3031  struct stat finfo;
3032  char name[kMAXPATHLEN];
3033  char *lpFilePart = 0;
3034  if (::SearchPath(exsearch.Data(), infile.Data(), NULL, kMAXPATHLEN, name, &lpFilePart) &&
3035  ::access(name, mode) == 0 && stat(name, &finfo) == 0 &&
3036  finfo.st_mode & S_IFREG) {
3037  if (gEnv->GetValue("Root.ShowPath", 0)) {
3038  Printf("Which: %s = %s", infile, name);
3039  }
3040  infile = name;
3041  return infile.Data();
3042  }
3043  infile = "";
3044  return 0;
3045 }
3046 
3047 //---- Users & Groups ----------------------------------------------------------
3048 
3049 ////////////////////////////////////////////////////////////////////////////////
3050 /// Collect local users and groups accounts information
3051 
3053 {
3054  // Net* API functions allowed and OS is Windows NT/2000/XP
3055  if ((gEnv->GetValue("WinNT.UseNetAPI", 0)) && (::GetVersion() < 0x80000000)) {
3056  fActUser = -1;
3057  fNbGroups = fNbUsers = 0;
3058  HINSTANCE netapi = ::LoadLibrary("netapi32.DLL");
3059  if (!netapi) return kFALSE;
3060 
3061  p2NetApiBufferFree = (pfn1)::GetProcAddress(netapi, "NetApiBufferFree");
3062  p2NetUserGetInfo = (pfn2)::GetProcAddress(netapi, "NetUserGetInfo");
3063  p2NetLocalGroupGetMembers = (pfn3)::GetProcAddress(netapi, "NetLocalGroupGetMembers");
3064  p2NetLocalGroupEnum = (pfn4)::GetProcAddress(netapi, "NetLocalGroupEnum");
3065 
3066  if (!p2NetApiBufferFree || !p2NetUserGetInfo ||
3067  !p2NetLocalGroupGetMembers || !p2NetLocalGroupEnum) return kFALSE;
3068 
3069  GetNbGroups();
3070 
3071  fGroups = (struct group *)calloc(fNbGroups, sizeof(struct group));
3072  for(int i=0;i<fNbGroups;i++) {
3073  fGroups[i].gr_mem = (char **)calloc(fNbUsers, sizeof (char*));
3074  }
3075  fPasswords = (struct passwd *)calloc(fNbUsers, sizeof(struct passwd));
3076 
3077  CollectGroups();
3078  ::FreeLibrary(netapi);
3079  }
3081  return kTRUE;
3082 }
3083 
3084 ////////////////////////////////////////////////////////////////////////////////
3085 
3086 Bool_t TWinNTSystem::CountMembers(const char *lpszGroupName)
3087 {
3088  NET_API_STATUS NetStatus = NERR_Success;
3089  LPBYTE Data = NULL;
3090  DWORD Index = 0, ResumeHandle = 0, Total = 0;
3091  LOCALGROUP_MEMBERS_INFO_1 *MemberInfo;
3092  WCHAR wszGroupName[256];
3093  int iRetOp = 0;
3094  DWORD dwLastError = 0;
3095 
3096  iRetOp = MultiByteToWideChar (
3097  (UINT)CP_ACP, // code page
3098  (DWORD)MB_PRECOMPOSED, // character-type options
3099  (LPCSTR)lpszGroupName, // address of string to map
3100  (int)-1, // number of bytes in string
3101  (LPWSTR)wszGroupName, // address of wide-character buffer
3102  (int)sizeof(wszGroupName) ); // size of buffer
3103 
3104  if (iRetOp == 0) {
3105  dwLastError = GetLastError();
3106  if (Data)
3107  p2NetApiBufferFree(Data);
3108  return FALSE;
3109  }
3110 
3111  // The NetLocalGroupGetMembers() API retrieves a list of the members
3112  // of a particular local group.
3113  NetStatus = p2NetLocalGroupGetMembers (NULL, wszGroupName, 1,
3114  &Data, 8192, &Index, &Total, &ResumeHandle );
3115 
3116  if (NetStatus != NERR_Success || Data == NULL) {
3117  dwLastError = GetLastError();
3118 
3119  if (dwLastError == ERROR_ENVVAR_NOT_FOUND) {
3120  // This usually means that the current Group has no members.
3121  // We call NetLocalGroupGetMembers() again.
3122  // This time, we set the level to 0.
3123  // We do this just to confirm that the number of members in
3124  // this group is zero.
3125  NetStatus = p2NetLocalGroupGetMembers ( NULL, wszGroupName, 0,
3126  &Data, 8192, &Index, &Total, &ResumeHandle );
3127  }
3128 
3129  if (Data)
3130  p2NetApiBufferFree(Data);
3131  return FALSE;
3132  }
3133 
3134  fNbUsers += Total;
3135  MemberInfo = (LOCALGROUP_MEMBERS_INFO_1 *)Data;
3136 
3137  if (Data)
3138  p2NetApiBufferFree(Data);
3139 
3140  return TRUE;
3141 }
3142 
3143 ////////////////////////////////////////////////////////////////////////////////
3144 
3146 {
3147  NET_API_STATUS NetStatus = NERR_Success;
3148  LPBYTE Data = NULL;
3149  DWORD Index = 0, ResumeHandle = 0, Total = 0, i;
3150  LOCALGROUP_INFO_0 *GroupInfo;
3151  char szAnsiName[256];
3152  DWORD dwLastError = 0;
3153  int iRetOp = 0;
3154 
3155  NetStatus = p2NetLocalGroupEnum(NULL, 0, &Data, 8192, &Index,
3156  &Total, &ResumeHandle );
3157 
3158  if (NetStatus != NERR_Success || Data == NULL) {
3159  dwLastError = GetLastError();
3160  if (Data)
3161  p2NetApiBufferFree(Data);
3162  return FALSE;
3163  }
3164 
3165  fNbGroups = Total;
3166  GroupInfo = (LOCALGROUP_INFO_0 *)Data;
3167  for (i=0; i < Total; i++) {
3168  // Convert group name from UNICODE to ansi.
3169  iRetOp = WideCharToMultiByte (
3170  (UINT)CP_ACP, // code page
3171  (DWORD)0, // performance and mapping flags
3172  (LPCWSTR)(GroupInfo->lgrpi0_name), // address of wide-char string
3173  (int)-1, // number of characters in string
3174  (LPSTR)szAnsiName, // address of buffer for new string
3175  (int)(sizeof(szAnsiName)), // size of buffer
3176  (LPCSTR)NULL, // address of default for unmappable characters
3177  (LPBOOL)NULL ); // address of flag set when default char used.
3178 
3179  // Now lookup all members of this group and record down their names and
3180  // SIDs into the output file.
3181  CountMembers((LPCTSTR)szAnsiName);
3182 
3183  GroupInfo++;
3184  }
3185 
3186  if (Data)
3187  p2NetApiBufferFree(Data);
3188 
3189  return TRUE;
3190 }
3191 
3192 ////////////////////////////////////////////////////////////////////////////////
3193 ///
3194 /// Take the name and look up a SID so that we can get full
3195 /// domain/user information
3196 ///
3197 
3198 Long_t TWinNTSystem::LookupSID (const char *lpszAccountName, int what,
3199  int &groupIdx, int &memberIdx)
3200 {
3201  BOOL bRetOp = FALSE;
3202  PSID pSid = NULL;
3203  DWORD dwSidSize, dwDomainNameSize;
3204  BYTE bySidBuffer[MAX_SID_SIZE];
3205  char szDomainName[MAX_NAME_STRING];
3206  SID_NAME_USE sidType;
3207  PUCHAR puchar_SubAuthCount = NULL;
3208  SID_IDENTIFIER_AUTHORITY sid_identifier_authority;
3209  PSID_IDENTIFIER_AUTHORITY psid_identifier_authority = NULL;
3210  unsigned char j = 0;
3211  DWORD dwLastError = 0;
3212 
3213  pSid = (PSID)bySidBuffer;
3214  dwSidSize = sizeof(bySidBuffer);
3215  dwDomainNameSize = sizeof(szDomainName);
3216 
3217  bRetOp = LookupAccountName (
3218  (LPCTSTR)NULL, // address of string for system name
3219  (LPCTSTR)lpszAccountName, // address of string for account name
3220  (PSID)pSid, // address of security identifier
3221  (LPDWORD)&dwSidSize, // address of size of security identifier
3222  (LPTSTR)szDomainName, // address of string for referenced domain
3223  (LPDWORD)&dwDomainNameSize,// address of size of domain string
3224  (PSID_NAME_USE)&sidType ); // address of SID-type indicator
3225 
3226  if (bRetOp == FALSE) {
3227  dwLastError = GetLastError();
3228  return -1; // Unable to obtain Account SID.
3229  }
3230 
3231  bRetOp = IsValidSid((PSID)pSid);
3232 
3233  if (bRetOp == FALSE) {
3234  dwLastError = GetLastError();
3235  return -2; // SID returned is invalid.
3236  }
3237 
3238  // Obtain via APIs the identifier authority value.
3239  psid_identifier_authority = GetSidIdentifierAuthority ((PSID)pSid);
3240 
3241  // Make a copy of it.
3242  memcpy (&sid_identifier_authority, psid_identifier_authority,
3243  sizeof(SID_IDENTIFIER_AUTHORITY));
3244 
3245  // Determine how many sub-authority values there are in the current SID.
3246  puchar_SubAuthCount = (PUCHAR)GetSidSubAuthorityCount((PSID)pSid);
3247  // Assign it to a more convenient variable.
3248  j = (unsigned char)(*puchar_SubAuthCount);
3249  // Now obtain all the sub-authority values from the current SID.
3250  DWORD dwSubAuth = 0;
3251  PDWORD pdwSubAuth = NULL;
3252  // Obtain the current sub-authority DWORD (referenced by a pointer)
3253  pdwSubAuth = (PDWORD)GetSidSubAuthority (
3254  (PSID)pSid, // address of security identifier to query
3255  (DWORD)j-1); // index of subauthority to retrieve
3256  dwSubAuth = *pdwSubAuth;
3257  if(what == SID_MEMBER) {
3258  fPasswords[memberIdx].pw_uid = dwSubAuth;
3259  fPasswords[memberIdx].pw_gid = fGroups[groupIdx].gr_gid;
3260  fPasswords[memberIdx].pw_group = strdup(fGroups[groupIdx].gr_name);
3261  }
3262  else if(what == SID_GROUP) {
3263  fGroups[groupIdx].gr_gid = dwSubAuth;
3264  }
3265  return 0;
3266 }
3267 
3268 ////////////////////////////////////////////////////////////////////////////////
3269 ///
3270 
3271 Bool_t TWinNTSystem::CollectMembers(const char *lpszGroupName, int &groupIdx,
3272  int &memberIdx)
3273 {
3274 
3275  NET_API_STATUS NetStatus = NERR_Success;
3276  LPBYTE Data = NULL;
3277  DWORD Index = 0, ResumeHandle = 0, Total = 0, i;
3278  LOCALGROUP_MEMBERS_INFO_1 *MemberInfo;
3279  char szAnsiMemberName[256];
3280  char szFullMemberName[256];
3281  char szMemberHomeDir[256];
3282  WCHAR wszGroupName[256];
3283  int iRetOp = 0;
3284  char act_name[256];
3285  DWORD length = sizeof (act_name);
3286  DWORD dwLastError = 0;
3287  LPUSER_INFO_11 pUI11Buf = NULL;
3288  NET_API_STATUS nStatus;
3289 
3290  iRetOp = MultiByteToWideChar (
3291  (UINT)CP_ACP, // code page
3292  (DWORD)MB_PRECOMPOSED, // character-type options
3293  (LPCSTR)lpszGroupName, // address of string to map
3294  (int)-1, // number of bytes in string
3295  (LPWSTR)wszGroupName, // address of wide-character buffer
3296  (int)sizeof(wszGroupName) ); // size of buffer
3297 
3298  if (iRetOp == 0) {
3299  dwLastError = GetLastError();
3300  if (Data)
3301  p2NetApiBufferFree(Data);
3302  return FALSE;
3303  }
3304 
3305  GetUserName (act_name, &length);
3306 
3307  // The NetLocalGroupGetMembers() API retrieves a list of the members
3308  // of a particular local group.
3309  NetStatus = p2NetLocalGroupGetMembers (NULL, wszGroupName, 1,
3310  &Data, 8192, &Index, &Total, &ResumeHandle );
3311 
3312  if (NetStatus != NERR_Success || Data == NULL) {
3313  dwLastError = GetLastError();
3314 
3315  if (dwLastError == ERROR_ENVVAR_NOT_FOUND) {
3316  // This usually means that the current Group has no members.
3317  // We call NetLocalGroupGetMembers() again.
3318  // This time, we set the level to 0.
3319  // We do this just to confirm that the number of members in
3320  // this group is zero.
3321  NetStatus = p2NetLocalGroupGetMembers ( NULL, wszGroupName, 0,
3322  &Data, 8192, &Index, &Total, &ResumeHandle );
3323  }
3324 
3325  if (Data)
3326  p2NetApiBufferFree(Data);
3327  return FALSE;
3328  }
3329 
3330  MemberInfo = (LOCALGROUP_MEMBERS_INFO_1 *)Data;
3331  for (i=0; i < Total; i++) {
3332  iRetOp = WideCharToMultiByte (
3333  (UINT)CP_ACP, // code page
3334  (DWORD)0, // performance and mapping flags
3335  (LPCWSTR)(MemberInfo->lgrmi1_name), // address of wide-char string
3336  (int)-1, // number of characters in string
3337  (LPSTR)szAnsiMemberName, // address of buffer for new string
3338  (int)(sizeof(szAnsiMemberName)), // size of buffer
3339  (LPCSTR)NULL, // address of default for unmappable characters
3340  (LPBOOL)NULL ); // address of flag set when default char used.
3341 
3342  if (iRetOp == 0) {
3343  dwLastError = GetLastError();
3344  }
3345 
3346  fPasswords[memberIdx].pw_name = strdup(szAnsiMemberName);
3347  fPasswords[memberIdx].pw_passwd = strdup("");
3348  fGroups[groupIdx].gr_mem[i] = strdup(szAnsiMemberName);
3349 
3350  if(fActUser == -1 && !stricmp(fPasswords[memberIdx].pw_name,act_name))
3351  fActUser = memberIdx;
3352 
3353 
3354  TCHAR szUserName[255]=TEXT("");
3355  MultiByteToWideChar(CP_ACP, 0, szAnsiMemberName, -1, (LPWSTR)szUserName, 255);
3356  //
3357  // Call the NetUserGetInfo function; specify level 10.
3358  //
3359  nStatus = p2NetUserGetInfo(NULL, (LPCWSTR)szUserName, 11, (LPBYTE *)&pUI11Buf);
3360  //
3361  // If the call succeeds, print the user information.
3362  //
3363  if (nStatus == NERR_Success) {
3364  if (pUI11Buf != NULL) {
3365  wsprintf(szFullMemberName,"%S",pUI11Buf->usri11_full_name);
3366  fPasswords[memberIdx].pw_gecos = strdup(szFullMemberName);
3367  wsprintf(szMemberHomeDir,"%S",pUI11Buf->usri11_home_dir);
3368  fPasswords[memberIdx].pw_dir = strdup(szMemberHomeDir);
3369  }
3370  }
3371  if((fPasswords[memberIdx].pw_gecos == NULL) || (strlen(fPasswords[memberIdx].pw_gecos) == 0))
3372  fPasswords[memberIdx].pw_gecos = strdup(fPasswords[memberIdx].pw_name);
3373  if((fPasswords[memberIdx].pw_dir == NULL) || (strlen(fPasswords[memberIdx].pw_dir) == 0))
3374  fPasswords[memberIdx].pw_dir = strdup("c:\\");
3375  //
3376  // Free the allocated memory.
3377  //
3378  if (pUI11Buf != NULL) {
3379  p2NetApiBufferFree(pUI11Buf);
3380  pUI11Buf = NULL;
3381  }
3382 
3383  /* Ensure SHELL is defined. */
3384  if (getenv("SHELL") == NULL)
3385  putenv ((GetVersion () & 0x80000000) ? "SHELL=command" : "SHELL=cmd");
3386 
3387  /* Set dir and shell from environment variables. */
3388  fPasswords[memberIdx].pw_shell = getenv("SHELL");
3389 
3390  // Find out the SID of the Member.
3391  LookupSID ((LPCTSTR)szAnsiMemberName, SID_MEMBER, groupIdx, memberIdx);
3392  memberIdx++;
3393  MemberInfo++;
3394  }
3395  if(fActUser == -1) fActUser = 0;
3396 
3397  if (Data)
3398  p2NetApiBufferFree(Data);
3399 
3400  return TRUE;
3401 }
3402 
3403 ////////////////////////////////////////////////////////////////////////////////
3404 ///
3405 
3407 {
3408  NET_API_STATUS NetStatus = NERR_Success;
3409  LPBYTE Data = NULL;
3410  DWORD Index = 0, ResumeHandle = 0, Total = 0, i;
3411  LOCALGROUP_INFO_0 *GroupInfo;
3412  char szAnsiName[256];
3413  DWORD dwLastError = 0;
3414  int iRetOp = 0, iGroupIdx = 0, iMemberIdx = 0;
3415 
3416  NetStatus = p2NetLocalGroupEnum(NULL, 0, &Data, 8192, &Index,
3417  &Total, &ResumeHandle );
3418 
3419  if (NetStatus != NERR_Success || Data == NULL) {
3420  dwLastError = GetLastError();
3421  if (Data)
3422  p2NetApiBufferFree(Data);
3423  return FALSE;
3424  }
3425 
3426  GroupInfo = (LOCALGROUP_INFO_0 *)Data;
3427  for (i=0; i < Total; i++) {
3428  // Convert group name from UNICODE to ansi.
3429  iRetOp = WideCharToMultiByte (
3430  (UINT)CP_ACP, // code page
3431  (DWORD)0, // performance and mapping flags
3432  (LPCWSTR)(GroupInfo->lgrpi0_name), // address of wide-char string
3433  (int)-1, // number of characters in string
3434  (LPSTR)szAnsiName, // address of buffer for new string
3435  (int)(sizeof(szAnsiName)), // size of buffer
3436  (LPCSTR)NULL, // address of default for unmappable characters
3437  (LPBOOL)NULL ); // address of flag set when default char used.
3438 
3439  fGroups[iGroupIdx].gr_name = strdup(szAnsiName);
3440  fGroups[iGroupIdx].gr_passwd = strdup("");
3441 
3442  // Find out the SID of the Group.
3443  LookupSID ((LPCTSTR)szAnsiName, SID_GROUP, iGroupIdx, iMemberIdx);
3444  // Now lookup all members of this group and record down their names and
3445  // SIDs into the output file.
3446  CollectMembers((LPCTSTR)szAnsiName, iGroupIdx, iMemberIdx);
3447 
3448  iGroupIdx++;
3449  GroupInfo++;
3450  }
3451 
3452  if (Data)
3453  p2NetApiBufferFree(Data);
3454 
3455  return TRUE;
3456 }
3457 
3458 ////////////////////////////////////////////////////////////////////////////////
3459 /// Returns the user's id. If user = 0, returns current user's id.
3460 
3461 Int_t TWinNTSystem::GetUid(const char *user)
3462 {
3463  if(!fGroupsInitDone)
3464  InitUsersGroups();
3465 
3466  // Net* API functions not allowed or OS not Windows NT/2000/XP
3467  if ((!gEnv->GetValue("WinNT.UseNetAPI", 0)) || (::GetVersion() >= 0x80000000)) {
3468  int uid;
3469  char name[256];
3470  DWORD length = sizeof (name);
3471  if (::GetUserName (name, &length)) {
3472  if (stricmp ("administrator", name) == 0)
3473  uid = 0;
3474  else
3475  uid = 123;
3476  }
3477  else {
3478  uid = 123;
3479  }
3480  return uid;
3481  }
3482  if (!user || !user[0])
3483  return fPasswords[fActUser].pw_uid;
3484  else {
3485  struct passwd *pwd = 0;
3486  for(int i=0;i<fNbUsers;i++) {
3487  if (!stricmp (user, fPasswords[i].pw_name)) {
3488  pwd = &fPasswords[i];
3489  break;
3490  }
3491  }
3492  if (pwd)
3493  return pwd->pw_uid;
3494  }
3495  return 0;
3496 }
3497 
3498 ////////////////////////////////////////////////////////////////////////////////
3499 /// Returns the effective user id. The effective id corresponds to the
3500 /// set id bit on the file being executed.
3501 
3503 {
3504  if(!fGroupsInitDone)
3505  InitUsersGroups();
3506 
3507  // Net* API functions not allowed or OS not Windows NT/2000/XP
3508  if ((!gEnv->GetValue("WinNT.UseNetAPI", 0)) || (::GetVersion() >= 0x80000000)) {
3509  int uid;
3510  char name[256];
3511  DWORD length = sizeof (name);
3512  if (::GetUserName (name, &length)) {
3513  if (stricmp ("administrator", name) == 0)
3514  uid = 0;
3515  else
3516  uid = 123;
3517  }
3518  else {
3519  uid = 123;
3520  }
3521  return uid;
3522  }
3523  return fPasswords[fActUser].pw_uid;
3524 }
3525 
3526 ////////////////////////////////////////////////////////////////////////////////
3527 /// Returns the group's id. If group = 0, returns current user's group.
3528 
3530 {
3531  if(!fGroupsInitDone)
3532  InitUsersGroups();
3533 
3534  // Net* API functions not allowed or OS not Windows NT/2000/XP
3535  if ((!gEnv->GetValue("WinNT.UseNetAPI", 0)) || (::GetVersion() >= 0x80000000)) {
3536  int gid;
3537  char name[256];
3538  DWORD length = sizeof (name);
3539  if (::GetUserName (name, &length)) {
3540  if (stricmp ("administrator", name) == 0)
3541  gid = 0;
3542  else
3543  gid = 123;
3544  }
3545  else {
3546  gid = 123;
3547  }
3548  return gid;
3549  }
3550  if (!group || !group[0])
3551  return fPasswords[fActUser].pw_gid;
3552  else {
3553  struct group *grp = 0;
3554  for(int i=0;i<fNbGroups;i++) {
3555  if (!stricmp (group, fGroups[i].gr_name)) {
3556  grp = &fGroups[i];
3557  break;
3558  }
3559  }
3560  if (grp)
3561  return grp->gr_gid;
3562  }
3563  return 0;
3564 }
3565 
3566 ////////////////////////////////////////////////////////////////////////////////
3567 /// Returns the effective group id. The effective group id corresponds
3568 /// to the set id bit on the file being executed.
3569 
3571 {
3572  if(!fGroupsInitDone)
3573  InitUsersGroups();
3574 
3575  // Net* API functions not allowed or OS not Windows NT/2000/XP
3576  if ((!gEnv->GetValue("WinNT.UseNetAPI", 0)) || (::GetVersion() >= 0x80000000)) {
3577  int gid;
3578  char name[256];
3579  DWORD length = sizeof (name);
3580  if (::GetUserName (name, &length)) {
3581  if (stricmp ("administrator", name) == 0)
3582  gid = 0;
3583  else
3584  gid = 123;
3585  }
3586  else {
3587  gid = 123;
3588  }
3589  return gid;
3590  }
3591  return fPasswords[fActUser].pw_gid;
3592 }
3593 
3594 ////////////////////////////////////////////////////////////////////////////////
3595 /// Returns all user info in the UserGroup_t structure. The returned
3596 /// structure must be deleted by the user. In case of error 0 is returned.
3597 
3599 {
3600  if(!fGroupsInitDone)
3601  InitUsersGroups();
3602 
3603  // Net* API functions not allowed or OS not Windows NT/2000/XP
3604  if ((!gEnv->GetValue("WinNT.UseNetAPI", 0)) || (::GetVersion() >= 0x80000000)) {
3605  char name[256];
3606  DWORD length = sizeof (name);
3607  UserGroup_t *ug = new UserGroup_t;
3608  if (::GetUserName (name, &length)) {
3609  ug->fUser = name;
3610  if (stricmp ("administrator", name) == 0) {
3611  ug->fUid = 0;
3612  ug->fGroup = "administrators";
3613  }
3614  else {
3615  ug->fUid = 123;
3616  ug->fGroup = "users";
3617  }
3618  ug->fGid = ug->fUid;
3619  }
3620  else {
3621  ug->fUser = "unknown";
3622  ug->fGroup = "unknown";
3623  ug->fUid = ug->fGid = 123;
3624  }
3625  ug->fPasswd = "";
3626  ug->fRealName = ug->fUser;
3627  ug->fShell = "command";
3628  return ug;
3629  }
3630  struct passwd *pwd = 0;
3631  if (uid == 0)
3632  pwd = &fPasswords[fActUser];
3633  else {
3634  for (int i = 0; i < fNbUsers; i++) {
3635  if (uid == fPasswords[i].pw_uid) {
3636  pwd = &fPasswords[i];
3637  break;
3638  }
3639  }
3640  }
3641  if (pwd) {
3642  UserGroup_t *ug = new UserGroup_t;
3643  ug->fUid = pwd->pw_uid;
3644  ug->fGid = pwd->pw_gid;
3645  ug->fUser = pwd->pw_name;
3646  ug->fPasswd = pwd->pw_passwd;
3647  ug->fRealName = pwd->pw_gecos;
3648  ug->fShell = pwd->pw_shell;
3649  ug->fGroup = pwd->pw_group;
3650  return ug;
3651  }
3652  return 0;
3653 }
3654 
3655 ////////////////////////////////////////////////////////////////////////////////
3656 /// Returns all user info in the UserGroup_t structure. If user = 0, returns
3657 /// current user's id info. The returned structure must be deleted by the
3658 /// user. In case of error 0 is returned.
3659 
3661 {
3662  return GetUserInfo(GetUid(user));
3663 }
3664 
3665 ////////////////////////////////////////////////////////////////////////////////
3666 /// Returns all group info in the UserGroup_t structure. The only active
3667 /// fields in the UserGroup_t structure for this call are:
3668 /// fGid and fGroup
3669 /// The returned structure must be deleted by the user. In case of
3670 /// error 0 is returned.
3671 
3673 {
3674  if(!fGroupsInitDone)
3675  InitUsersGroups();
3676 
3677  // Net* API functions not allowed or OS not Windows NT/2000/XP
3678  if ((!gEnv->GetValue("WinNT.UseNetAPI", 0)) || (::GetVersion() >= 0x80000000)) {
3679  char name[256];
3680  DWORD length = sizeof (name);
3681  UserGroup_t *gr = new UserGroup_t;
3682  if (::GetUserName (name, &length)) {
3683  if (stricmp ("administrator", name) == 0) {
3684  gr->fGroup = "administrators";
3685  gr->fGid = 0;
3686  }
3687  else {
3688  gr->fGroup = "users";
3689  gr->fGid = 123;
3690  }
3691  }
3692  else {
3693  gr->fGroup = "unknown";
3694  gr->fGid = 123;
3695  }
3696  gr->fUid = 0;
3697  return gr;
3698  }
3699  struct group *grp = 0;
3700  for(int i=0;i<fNbGroups;i++) {
3701  if (gid == fGroups[i].gr_gid) {
3702  grp = &fGroups[i];
3703  break;
3704  }
3705  }
3706  if (grp) {
3707  UserGroup_t *gr = new UserGroup_t;
3708  gr->fUid = 0;
3709  gr->fGid = grp->gr_gid;
3710  gr->fGroup = grp->gr_name;
3711  return gr;
3712  }
3713  return 0;
3714 
3715 }
3716 
3717 ////////////////////////////////////////////////////////////////////////////////
3718 /// Returns all group info in the UserGroup_t structure. The only active
3719 /// fields in the UserGroup_t structure for this call are:
3720 /// fGid and fGroup
3721 /// If group = 0, returns current user's group. The returned structure
3722 /// must be deleted by the user. In case of error 0 is returned.
3723 
3725 {
3726  return GetGroupInfo(GetGid(group));
3727 }
3728 
3729 //---- environment manipulation ------------------------------------------------
3730 
3731 ////////////////////////////////////////////////////////////////////////////////
3732 /// Set environment variable.
3733 
3734 void TWinNTSystem::Setenv(const char *name, const char *value)
3735 {
3736  ::_putenv(TString::Format("%s=%s", name, value));
3737 }
3738 
3739 ////////////////////////////////////////////////////////////////////////////////
3740 /// Get environment variable.
3741 
3742 const char *TWinNTSystem::Getenv(const char *name)
3743 {
3744  const char *env = ::getenv(name);
3745  if (!env) {
3746  if (::_stricmp(name,"home") == 0 ) {
3747  env = HomeDirectory();
3748  } else if (::_stricmp(name, "rootsys") == 0 ) {
3749  env = gRootDir;
3750  }
3751  }
3752  return env;
3753 }
3754 
3755 //---- Processes ---------------------------------------------------------------
3756 
3757 ////////////////////////////////////////////////////////////////////////////////
3758 /// Execute a command.
3759 
3760 int TWinNTSystem::Exec(const char *shellcmd)
3761 {
3762  return ::system(shellcmd);
3763 }
3764 
3765 ////////////////////////////////////////////////////////////////////////////////
3766 /// Open a pipe.
3767 
3768 FILE *TWinNTSystem::OpenPipe(const char *command, const char *mode)
3769 {
3770  return ::_popen(command, mode);
3771 }
3772 
3773 ////////////////////////////////////////////////////////////////////////////////
3774 /// Close the pipe.
3775 
3777 {
3778  return ::_pclose(pipe);
3779 }
3780 
3781 ////////////////////////////////////////////////////////////////////////////////
3782 /// Get process id.
3783 
3785 {
3786  return ::getpid();
3787 }
3788 
3789 ////////////////////////////////////////////////////////////////////////////////
3790 /// Get current process handle
3791 
3793 {
3794  return fhProcess;
3795 }
3796 
3797 ////////////////////////////////////////////////////////////////////////////////
3798 /// Exit the application.
3799 
3800 void TWinNTSystem::Exit(int code, Bool_t mode)
3801 {
3802  // Insures that the files and sockets are closed before any library is unloaded
3803  // and before emptying CINT.
3804  if (gROOT) {
3805  gROOT->CloseFiles();
3806  if (gROOT->GetListOfBrowsers()) {
3807  // GetListOfBrowsers()->Delete() creates problems when a browser is
3808  // created on the stack, calling CloseWindow() solves the problem
3809  //gROOT->GetListOfBrowsers()->Delete();
3810  TBrowser *b;
3811  TIter next(gROOT->GetListOfBrowsers());
3812  while ((b = (TBrowser*) next()))
3813  gROOT->ProcessLine(TString::Format("((TBrowser*)0x%lx)->GetBrowserImp()->GetMainFrame()->CloseWindow();",
3814  (ULong_t)b));
3815  }
3816  }
3817  if (gInterpreter) {
3818  gInterpreter->ResetGlobals();
3819  }
3820  gVirtualX->CloseDisplay();
3821 
3822  if (mode) {
3823  ::exit(code);
3824  } else {
3825  ::_exit(code);
3826  }
3827 }
3828 
3829 ////////////////////////////////////////////////////////////////////////////////
3830 /// Abort the application.
3831 
3833 {
3834  ::abort();
3835 }
3836 
3837 //---- Standard output redirection ---------------------------------------------
3838 
3839 ////////////////////////////////////////////////////////////////////////////////
3840 /// Redirect standard output (stdout, stderr) to the specified file.
3841 /// If the file argument is 0 the output is set again to stderr, stdout.
3842 /// The second argument specifies whether the output should be added to the
3843 /// file ("a", default) or the file be truncated before ("w").
3844 /// This function saves internally the current state into a static structure.
3845 /// The call can be made reentrant by specifying the opaque structure pointed
3846 /// by 'h', which is filled with the relevant information. The handle 'h'
3847 /// obtained on the first call must then be used in any subsequent call,
3848 /// included ShowOutput, to display the redirected output.
3849 /// Returns 0 on success, -1 in case of error.
3850 
3851 Int_t TWinNTSystem::RedirectOutput(const char *file, const char *mode,
3853 {
3854  FILE *fout, *ferr;
3855  static int fd1=0, fd2=0;
3856  static fpos_t pos1=0, pos2=0;
3857  // Instance to be used if the caller does not passes 'h'
3858  static RedirectHandle_t loch;
3859  Int_t rc = 0;
3860 
3861  // Which handle to use ?
3862  RedirectHandle_t *xh = (h) ? h : &loch;
3863 
3864  if (file) {
3865  // Make sure mode makes sense; default "a"
3866  const char *m = (mode[0] == 'a' || mode[0] == 'w') ? mode : "a";
3867 
3868  // Current file size
3869  xh->fReadOffSet = 0;
3870  if (m[0] == 'a') {
3871  // If the file exists, save the current size
3872  FileStat_t st;
3873  if (!gSystem->GetPathInfo(file, st))
3874  xh->fReadOffSet = (st.fSize > 0) ? st.fSize : xh->fReadOffSet;
3875  }
3876  xh->fFile = file;
3877 
3878  fflush(stdout);
3879  fgetpos(stdout, &pos1);
3880  fd1 = _dup(fileno(stdout));
3881  // redirect stdout & stderr
3882  if ((fout = freopen(file, m, stdout)) == 0) {
3883  SysError("RedirectOutput", "could not freopen stdout");
3884  if (fd1 > 0) {
3885  _dup2(fd1, fileno(stdout));
3886  close(fd1);
3887  }
3888  clearerr(stdout);
3889  fsetpos(stdout, &pos1);
3890  fd1 = fd2 = 0;
3891  return -1;
3892  }
3893  fflush(stderr);
3894  fgetpos(stderr, &pos2);
3895  fd2 = _dup(fileno(stderr));
3896  if ((ferr = freopen(file, m, stderr)) == 0) {
3897  SysError("RedirectOutput", "could not freopen stderr");
3898  if (fd1 > 0) {
3899  _dup2(fd1, fileno(stdout));
3900  close(fd1);
3901  }
3902  clearerr(stdout);
3903  fsetpos(stdout, &pos1);
3904  if (fd2 > 0) {
3905  _dup2(fd2, fileno(stderr));
3906  close(fd2);
3907  }
3908  clearerr(stderr);
3909  fsetpos(stderr, &pos2);
3910  fd1 = fd2 = 0;
3911  return -1;
3912  }
3913  if (m[0] == 'a') {
3914  fseek(fout, 0, SEEK_END);
3915  fseek(ferr, 0, SEEK_END);
3916  }
3917  } else {
3918  // Restore stdout & stderr
3919  fflush(stdout);
3920  if (fd1) {
3921  if (fd1 > 0) {
3922  if (_dup2(fd1, fileno(stdout))) {
3923  SysError("RedirectOutput", "could not restore stdout");
3924  rc = -1;
3925  }
3926  close(fd1);
3927  }
3928  clearerr(stdout);
3929  fsetpos(stdout, &pos1);
3930  fd1 = 0;
3931  }
3932 
3933  fflush(stderr);
3934  if (fd2) {
3935  if (fd2 > 0) {
3936  if (_dup2(fd2, fileno(stderr))) {
3937  SysError("RedirectOutput", "could not restore stderr");
3938  rc = -1;
3939  }
3940  close(fd2);
3941  }
3942  clearerr(stderr);
3943  fsetpos(stderr, &pos2);
3944  fd2 = 0;
3945  }
3946 
3947  // Reset the static instance, if using that
3948  if (xh == &loch)
3949  xh->Reset();
3950  }
3951  return rc;
3952 }
3953 
3954 //---- dynamic loading and linking ---------------------------------------------
3955 
3956 ////////////////////////////////////////////////////////////////////////////////
3957 /// Add a new directory to the dynamic path.
3958 
3959 void TWinNTSystem::AddDynamicPath(const char *dir)
3960 {
3961  if (dir) {
3962  TString oldpath = DynamicPath(0, kFALSE);
3963  oldpath.Append(";");
3964  oldpath.Append(dir);
3965  DynamicPath(oldpath);
3966  }
3967 }
3968 
3969 ////////////////////////////////////////////////////////////////////////////////
3970 /// Return the dynamic path (used to find shared libraries).
3971 
3973 {
3974  return DynamicPath(0, kFALSE);
3975 }
3976 
3977 ////////////////////////////////////////////////////////////////////////////////
3978 /// Set the dynamic path to a new value.
3979 /// If the value of 'path' is zero, the dynamic path is reset to its
3980 /// default value.
3981 
3982 void TWinNTSystem::SetDynamicPath(const char *path)
3983 {
3984  if (!path)
3985  DynamicPath(0, kTRUE);
3986  else
3987  DynamicPath(path);
3988 }
3989 
3990 ////////////////////////////////////////////////////////////////////////////////
3991 /// Returns and updates sLib to the path of a dynamic library
3992 /// (searches for library in the dynamic library search path).
3993 /// If no file name extension is provided it tries .DLL.
3994 
3996 {
3997  int len = sLib.Length();
3998  if (len > 4 && (!stricmp(sLib.Data()+len-4, ".dll"))) {
4000  return sLib;
4001  } else {
4002  TString sLibDll(sLib);
4003  sLibDll += ".dll";
4004  if (gSystem->FindFile(GetDynamicPath(), sLibDll, kReadPermission)) {
4005  sLibDll.Swap(sLib);
4006  return sLib;
4007  }
4008  }
4009 
4010  if (!quiet) {
4011  Error("DynamicPathName",
4012  "%s does not exist in %s,\nor has wrong file extension (.dll)",
4013  sLib.Data(), GetDynamicPath());
4014  }
4015  return 0;
4016 }
4017 
4018 ////////////////////////////////////////////////////////////////////////////////
4019 /// Load a shared library. Returns 0 on successful loading, 1 in
4020 /// case lib was already loaded and -1 in case lib does not exist
4021 /// or in case of error.
4022 
4023 int TWinNTSystem::Load(const char *module, const char *entry, Bool_t system)
4024 {
4025  return TSystem::Load(module, entry, system);
4026 }
4027 
4028 /* nonstandard extension used : zero-sized array in struct/union */
4029 #pragma warning(push)
4030 #pragma warning(disable:4200)
4031 ////////////////////////////////////////////////////////////////////////////////
4032 /// Get list of shared libraries loaded at the start of the executable.
4033 /// Returns 0 in case list cannot be obtained or in case of error.
4034 
4036 {
4037  char winDrive[256];
4038  char winDir[256];
4039  char winName[256];
4040  char winExt[256];
4041 
4042  if (!gApplication) return 0;
4043 
4044  static Bool_t once = kFALSE;
4045  static TString linkedLibs;
4046 
4047  if (!linkedLibs.IsNull())
4048  return linkedLibs;
4049 
4050  if (once)
4051  return 0;
4052 
4053  char *exe = gSystem->Which(Getenv("PATH"), gApplication->Argv(0),
4055  if (!exe) {
4056  once = kTRUE;
4057  return 0;
4058  }
4059 
4060  HANDLE hFile, hMapping;
4061  void *basepointer;
4062 
4063  if((hFile = CreateFile(exe,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,0))==INVALID_HANDLE_VALUE) {
4064  delete [] exe;
4065  return 0;
4066  }
4067  if(!(hMapping = CreateFileMapping(hFile,0,PAGE_READONLY|SEC_COMMIT,0,0,0))) {
4068  CloseHandle(hFile);
4069  delete [] exe;
4070  return 0;
4071  }
4072  if(!(basepointer = MapViewOfFile(hMapping,FILE_MAP_READ,0,0,0))) {
4073  CloseHandle(hMapping);
4074  CloseHandle(hFile);
4075  delete [] exe;
4076  return 0;
4077  }
4078 
4079  int sect;
4080  IMAGE_DOS_HEADER *dos_head = (IMAGE_DOS_HEADER *)basepointer;
4081  struct header {
4082  DWORD signature;
4083  IMAGE_FILE_HEADER _head;
4084  IMAGE_OPTIONAL_HEADER opt_head;
4085  IMAGE_SECTION_HEADER section_header[]; // actual number in NumberOfSections
4086  };
4087  struct header *pheader;
4088  const IMAGE_SECTION_HEADER * section_header;
4089 
4090  if(dos_head->e_magic!='ZM') {
4091  delete [] exe;
4092  return 0;
4093  } // verify DOS-EXE-Header
4094  // after end of DOS-EXE-Header: offset to PE-Header
4095  pheader = (struct header *)((char*)dos_head + dos_head->e_lfanew);
4096 
4097  if(IsBadReadPtr(pheader,sizeof(struct header))) { // start of PE-Header
4098  delete [] exe;
4099  return 0;
4100  }
4101  if(pheader->signature!=IMAGE_NT_SIGNATURE) { // verify PE format
4102  switch((unsigned short)pheader->signature) {
4103  case IMAGE_DOS_SIGNATURE:
4104  delete [] exe;
4105  return 0;
4106  case IMAGE_OS2_SIGNATURE:
4107  delete [] exe;
4108  return 0;
4109  case IMAGE_OS2_SIGNATURE_LE:
4110  delete [] exe;
4111  return 0;
4112  default: // unknown signature
4113  delete [] exe;
4114  return 0;
4115  }
4116  }
4117 #define isin(address,start,length) ((address)>=(start) && (address)<(start)+(length))
4118  TString odump;
4119  // walk through sections
4120  for(sect=0,section_header=pheader->section_header;
4121  sect<pheader->_head.NumberOfSections;sect++,section_header++) {
4122  int directory;
4123  const void * const section_data =
4124  (char*)basepointer + section_header->PointerToRawData;
4125  for(directory=0;directory<IMAGE_NUMBEROF_DIRECTORY_ENTRIES;directory++) {
4126  if(isin(pheader->opt_head.DataDirectory[directory].VirtualAddress,
4127  section_header->VirtualAddress,
4128  section_header->SizeOfRawData)) {
4129  const IMAGE_IMPORT_DESCRIPTOR *stuff_start =
4130  (IMAGE_IMPORT_DESCRIPTOR *)((char*)section_data +
4131  (pheader->opt_head.DataDirectory[directory].VirtualAddress -
4132  section_header->VirtualAddress));
4133  // (virtual address of stuff - virtual address of section) =
4134  // offset of stuff in section
4135  const unsigned stuff_length =
4136  pheader->opt_head.DataDirectory[directory].Size;
4137  if(directory == IMAGE_DIRECTORY_ENTRY_IMPORT) {
4138  while(!IsBadReadPtr(stuff_start,sizeof(*stuff_start)) &&
4139  stuff_start->Name) {
4140  TString dll = (char*)section_data +
4141  ((DWORD)(stuff_start->Name)) -
4142  section_header->VirtualAddress;
4143  if (dll.EndsWith(".dll")) {
4144  char *dllPath = DynamicPathName(dll, kTRUE);
4145  if (dllPath) {
4146  char *winPath = getenv("windir");
4147  _splitpath(winPath,winDrive,winDir,winName,winExt);
4148  if(!strstr(dllPath, winDir)) {
4149  if (!linkedLibs.IsNull())
4150  linkedLibs += " ";
4151  linkedLibs += dllPath;
4152  }
4153  }
4154  delete [] dllPath;
4155  }
4156  stuff_start++;
4157  }
4158  }
4159  }
4160  }
4161  }
4162 
4163  UnmapViewOfFile(basepointer);
4164  CloseHandle(hMapping);
4165  CloseHandle(hFile);
4166 
4167  delete [] exe;
4168 
4169  once = kTRUE;
4170 
4171  if (linkedLibs.IsNull())
4172  return 0;
4173 
4174  return linkedLibs;
4175 }
4176 #pragma warning(pop)
4177 
4178 ////////////////////////////////////////////////////////////////////////////////
4179 /// Return a space separated list of loaded shared libraries.
4180 /// This list is of a format suitable for a linker, i.e it may contain
4181 /// -Lpathname and/or -lNameOfLib.
4182 /// Option can be any of:
4183 /// S: shared libraries loaded at the start of the executable, because
4184 /// they were specified on the link line.
4185 /// D: shared libraries dynamically loaded after the start of the program.
4186 /// L: list the .LIB rather than the .DLL (this is intended for linking)
4187 /// [This options is not the default]
4188 
4189 const char *TWinNTSystem::GetLibraries(const char *regexp, const char *options,
4190  Bool_t isRegexp)
4191 {
4192  TString libs(TSystem::GetLibraries(regexp, options, isRegexp));
4193  TString ntlibs;
4194  TString opt = options;
4195 
4196  if ( (opt.First('L')!=kNPOS) ) {
4197  TRegexp separator("[^ \\t\\s]+");
4198  TRegexp user_dll("\\.dll$");
4199  TRegexp user_lib("\\.lib$");
4200  FileStat_t sbuf;
4201  TString s;
4202  Ssiz_t start, index, end;
4203  start = index = end = 0;
4204 
4205  while ((start < libs.Length()) && (index != kNPOS)) {
4206  index = libs.Index(separator, &end, start);
4207  if (index >= 0) {
4208  // Change .dll into .lib and remove the
4209  // path info if it not accessible.
4210  s = libs(index, end);
4211  if (s.Index(user_dll) != kNPOS) {
4212  s.ReplaceAll(".dll",".lib");
4213  if ( GetPathInfo( s, sbuf ) != 0 ) {
4214  s.Replace( 0, s.Last('/')+1, 0, 0);
4215  s.Replace( 0, s.Last('\\')+1, 0, 0);
4216  }
4217  } else if (s.Index(user_lib) != kNPOS) {
4218  if ( GetPathInfo( s, sbuf ) != 0 ) {
4219  s.Replace( 0, s.Last('/')+1, 0, 0);
4220  s.Replace( 0, s.Last('\\')+1, 0, 0);
4221  }
4222  }
4223  if (!ntlibs.IsNull()) ntlibs.Append(" ");
4224  ntlibs.Append(s);
4225  }
4226  start += end+1;
4227  }
4228  } else {
4229  ntlibs = libs;
4230  }
4231 
4232  fListLibs = ntlibs;
4233  fListLibs.ReplaceAll("/","\\");
4234  return fListLibs;
4235 }
4236 
4237 //---- Time & Date -------------------------------------------------------------
4238 
4239 ////////////////////////////////////////////////////////////////////////////////
4240 /// Add timer to list of system timers.
4241 
4243 {
4244  TSystem::AddTimer(ti);
4245 }
4246 
4247 ////////////////////////////////////////////////////////////////////////////////
4248 /// Remove timer from list of system timers.
4249 
4251 {
4252  if (!ti) return 0;
4253 
4254  TTimer *t = TSystem::RemoveTimer(ti);
4255  return t;
4256 }
4257 
4258 ////////////////////////////////////////////////////////////////////////////////
4259 /// Special Thread to check asynchronous timers.
4260 
4262 {
4263  while (1) {
4264  if (!fInsideNotify)
4267  }
4268 }
4269 
4270 ////////////////////////////////////////////////////////////////////////////////
4271 /// Handle and dispatch timers. If mode = kTRUE dispatch synchronous
4272 /// timers else a-synchronous timers.
4273 
4275 {
4276  if (!fTimers) return kFALSE;
4277 
4278  fInsideNotify = kTRUE;
4279 
4281  TTimer *t;
4282  Bool_t timedout = kFALSE;
4283 
4284  while ((t = (TTimer *) it.Next())) {
4285  // NB: the timer resolution is added in TTimer::CheckTimer()
4286  TTime now = Now();
4287  if (mode && t->IsSync()) {
4288  if (t->CheckTimer(now)) {
4289  timedout = kTRUE;
4290  }
4291  } else if (!mode && t->IsAsync()) {
4292  if (t->CheckTimer(now)) {
4293  timedout = kTRUE;
4294  }
4295  }
4296  }
4298 
4299  return timedout;
4300 }
4301 
4302 const Double_t gTicks = 1.0e-7;
4303 ////////////////////////////////////////////////////////////////////////////////
4304 ///
4305 
4307 {
4308  union {
4309  FILETIME ftFileTime;
4310  __int64 ftInt64;
4311  } ftRealTime; // time the process has spent in kernel mode
4312 
4313  ::GetSystemTimeAsFileTime(&ftRealTime.ftFileTime);
4314  return (Double_t)ftRealTime.ftInt64 * gTicks;
4315 }
4316 
4317 ////////////////////////////////////////////////////////////////////////////////
4318 ///
4319 
4321 {
4322  OSVERSIONINFO OsVersionInfo;
4323 
4324 //*-* Value Platform
4325 //*-* ----------------------------------------------------
4326 //*-* VER_PLATFORM_WIN32s Win32s on Windows 3.1
4327 //*-* VER_PLATFORM_WIN32_WINDOWS Win32 on Windows 95
4328 //*-* VER_PLATFORM_WIN32_NT Windows NT
4329 //*-*
4330 
4331  OsVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
4332  GetVersionEx(&OsVersionInfo);
4333  if (OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) {
4334  DWORD ret;
4335  FILETIME ftCreate, // when the process was created
4336  ftExit; // when the process exited
4337 
4338  union {
4339  FILETIME ftFileTime;
4340  __int64 ftInt64;
4341  } ftKernel; // time the process has spent in kernel mode
4342 
4343  union {
4344  FILETIME ftFileTime;
4345  __int64 ftInt64;
4346  } ftUser; // time the process has spent in user mode
4347 
4348  HANDLE hThread = GetCurrentThread();
4349  ret = GetThreadTimes (hThread, &ftCreate, &ftExit,
4350  &ftKernel.ftFileTime,
4351  &ftUser.ftFileTime);
4352  if (ret != TRUE){
4353  ret = ::GetLastError();
4354  ::Error("GetCPUTime", " Error on GetProcessTimes 0x%lx", (int)ret);
4355  }
4356 
4357  // Process times are returned in a 64-bit structure, as the number of
4358  // 100 nanosecond ticks since 1 January 1601. User mode and kernel mode
4359  // times for this process are in separate 64-bit structures.
4360  // To convert to floating point seconds, we will:
4361  // Convert sum of high 32-bit quantities to 64-bit int
4362 
4363  return (Double_t) (ftKernel.ftInt64 + ftUser.ftInt64) * gTicks;
4364  } else {
4365  return GetRealTime();
4366  }
4367 }
4368 
4369 ////////////////////////////////////////////////////////////////////////////////
4370 /// Get current time in milliseconds since 0:00 Jan 1 1995.
4371 
4373 {
4374  static time_t jan95 = 0;
4375  if (!jan95) {
4376  struct tm tp;
4377  tp.tm_year = 95;
4378  tp.tm_mon = 0;
4379  tp.tm_mday = 1;
4380  tp.tm_hour = 0;
4381  tp.tm_min = 0;
4382  tp.tm_sec = 0;
4383  tp.tm_isdst = -1;
4384 
4385  jan95 = mktime(&tp);
4386  if ((int)jan95 == -1) {
4387  ::SysError("TWinNTSystem::Now", "error converting 950001 0:00 to time_t");
4388  return 0;
4389  }
4390  }
4391 
4392  _timeb now;
4393  _ftime(&now);
4394  return TTime((now.time-(Long_t)jan95)*1000 + now.millitm);
4395 }
4396 
4397 ////////////////////////////////////////////////////////////////////////////////
4398 /// Sleep milliSec milli seconds.
4399 /// The Sleep function suspends the execution of the CURRENT THREAD for
4400 /// a specified interval.
4401 
4403 {
4404  ::Sleep(milliSec);
4405 }
4406 
4407 ////////////////////////////////////////////////////////////////////////////////
4408 /// Select on file descriptors. The timeout to is in millisec.
4409 
4411 {
4412  Int_t rc = -4;
4413 
4414  TFdSet rd, wr;
4415  Int_t mxfd = -1;
4416  TIter next(act);
4417  TFileHandler *h = 0;
4418  while ((h = (TFileHandler *) next())) {
4419  Int_t fd = h->GetFd();
4420  if (h->HasReadInterest())
4421  rd.Set(fd);
4422  if (h->HasWriteInterest())
4423  wr.Set(fd);
4424  h->ResetReadyMask();
4425  }
4426  rc = WinNTSelect(&rd, &wr, to);
4427 
4428  // Set readiness bits
4429  if (rc > 0) {
4430  next.Reset();
4431  while ((h = (TFileHandler *) next())) {
4432  Int_t fd = h->GetFd();
4433  if (rd.IsSet(fd))
4434  h->SetReadReady();
4435  if (wr.IsSet(fd))
4436  h->SetWriteReady();
4437  }
4438  }
4439 
4440  return rc;
4441 }
4442 
4443 ////////////////////////////////////////////////////////////////////////////////
4444 /// Select on the file descriptor related to file handler h.
4445 /// The timeout to is in millisec.
4446 
4448 {
4449  Int_t rc = -4;
4450 
4451  TFdSet rd, wr;
4452  Int_t fd = -1;
4453  if (h) {
4454  fd = h->GetFd();
4455  if (h->HasReadInterest())
4456  rd.Set(fd);
4457  if (h->HasWriteInterest())
4458  wr.Set(fd);
4459  h->ResetReadyMask();
4460  rc = WinNTSelect(&rd, &wr, to);
4461  }
4462 
4463  // Fill output lists, if required
4464  if (rc > 0) {
4465  if (rd.IsSet(fd))
4466  h->SetReadReady();
4467  if (wr.IsSet(fd))
4468  h->SetWriteReady();
4469  }
4470 
4471  return rc;
4472 }
4473 
4474 //---- RPC ---------------------------------------------------------------------
4475 ////////////////////////////////////////////////////////////////////////////////
4476 /// Get port # of internet service.
4477 
4478 int TWinNTSystem::GetServiceByName(const char *servicename)
4479 {
4480  struct servent *sp;
4481 
4482  if ((sp = ::getservbyname(servicename, kProtocolName)) == 0) {
4483  Error("GetServiceByName", "no service \"%s\" with protocol \"%s\"\n",
4484  servicename, kProtocolName);
4485  return -1;
4486  }
4487  return ::ntohs(sp->s_port);
4488 }
4489 
4490 ////////////////////////////////////////////////////////////////////////////////
4491 
4493 {
4494  // Get name of internet service.
4495 
4496  struct servent *sp;
4497 
4498  if ((sp = ::getservbyport(::htons(port), kProtocolName)) == 0) {
4499  return Form("%d", port);
4500  }
4501  return sp->s_name;
4502 }
4503 
4504 ////////////////////////////////////////////////////////////////////////////////
4505 /// Get Internet Protocol (IP) address of host.
4506 
4508 {
4509  struct hostent *host_ptr;
4510  const char *host;
4511  int type;
4512  UInt_t addr; // good for 4 byte addresses
4513 
4514  if ((addr = ::inet_addr(hostname)) != INADDR_NONE) {
4515  type = AF_INET;
4516  if ((host_ptr = ::gethostbyaddr((const char *)&addr,
4517  sizeof(addr), AF_INET))) {
4518  host = host_ptr->h_name;
4519  TInetAddress a(host, ntohl(addr), type);
4520  UInt_t addr2;
4521  Int_t i;
4522  for (i = 1; host_ptr->h_addr_list[i]; i++) {
4523  memcpy(&addr2, host_ptr->h_addr_list[i], host_ptr->h_length);
4524  a.AddAddress(ntohl(addr2));
4525  }
4526  for (i = 0; host_ptr->h_aliases[i]; i++)
4527  a.AddAlias(host_ptr->h_aliases[i]);
4528  return a;
4529  } else {
4530  host = "UnNamedHost";
4531  }
4532  } else if ((host_ptr = ::gethostbyname(hostname))) {
4533  // Check the address type for an internet host
4534  if (host_ptr->h_addrtype != AF_INET) {
4535  Error("GetHostByName", "%s is not an internet host\n", hostname);
4536  return TInetAddress();
4537  }
4538  memcpy(&addr, host_ptr->h_addr, host_ptr->h_length);
4539  host = host_ptr->h_name;
4540  type = host_ptr->h_addrtype;
4541  TInetAddress a(host, ntohl(addr), type);
4542  UInt_t addr2;
4543  Int_t i;
4544  for (i = 1; host_ptr->h_addr_list[i]; i++) {
4545  memcpy(&addr2, host_ptr->h_addr_list[i], host_ptr->h_length);
4546  a.AddAddress(ntohl(addr2));
4547  }
4548  for (i = 0; host_ptr->h_aliases[i]; i++)
4549  a.AddAlias(host_ptr->h_aliases[i]);
4550  return a;
4551  } else {
4552  if (gDebug > 0) Error("GetHostByName", "unknown host %s", hostname);
4553  return TInetAddress(hostname, 0, -1);
4554  }
4555 
4556  return TInetAddress(host, ::ntohl(addr), type);
4557 }
4558 
4559 ////////////////////////////////////////////////////////////////////////////////
4560 /// Get Internet Protocol (IP) address of remote host and port #.
4561 
4563 {
4564  SOCKET sock = socket;
4565  struct sockaddr_in addr;
4566  int len = sizeof(addr);
4567 
4568  if (::getpeername(sock, (struct sockaddr *)&addr, &len) == SOCKET_ERROR) {
4569  ::SysError("GetPeerName", "getpeername");
4570  return TInetAddress();
4571  }
4572 
4573  struct hostent *host_ptr;
4574  const char *hostname;
4575  int family;
4576  UInt_t iaddr;
4577 
4578  if ((host_ptr = ::gethostbyaddr((const char *)&addr.sin_addr,
4579  sizeof(addr.sin_addr), AF_INET))) {
4580  memcpy(&iaddr, host_ptr->h_addr, host_ptr->h_length);
4581  hostname = host_ptr->h_name;
4582  family = host_ptr->h_addrtype;
4583  } else {
4584  memcpy(&iaddr, &addr.sin_addr, sizeof(addr.sin_addr));
4585  hostname = "????";
4586  family = AF_INET;
4587  }
4588 
4589  return TInetAddress(hostname, ::ntohl(iaddr), family, ::ntohs(addr.sin_port));
4590 }
4591 
4592 ////////////////////////////////////////////////////////////////////////////////
4593 /// Get Internet Protocol (IP) address of host and port #.
4594 
4596 {
4597  SOCKET sock = socket;
4598  struct sockaddr_in addr;
4599  int len = sizeof(addr);
4600 
4601  if (::getsockname(sock, (struct sockaddr *)&addr, &len) == SOCKET_ERROR) {
4602  ::SysError("GetSockName", "getsockname");
4603  return TInetAddress();
4604  }
4605 
4606  struct hostent *host_ptr;
4607  const char *hostname;
4608  int family;
4609  UInt_t iaddr;
4610 
4611  if ((host_ptr = ::gethostbyaddr((const char *)&addr.sin_addr,
4612  sizeof(addr.sin_addr), AF_INET))) {
4613  memcpy(&iaddr, host_ptr->h_addr, host_ptr->h_length);
4614  hostname = host_ptr->h_name;
4615  family = host_ptr->h_addrtype;
4616  } else {
4617  memcpy(&iaddr, &addr.sin_addr, sizeof(addr.sin_addr));
4618  hostname = "????";
4619  family = AF_INET;
4620  }
4621 
4622  return TInetAddress(hostname, ::ntohl(iaddr), family, ::ntohs(addr.sin_port));
4623 }
4624 
4625 ////////////////////////////////////////////////////////////////////////////////
4626 /// Announce unix domain service.
4627 
4629 {
4630  SOCKET sock;
4631 
4632  // Create socket
4633  if ((sock = ::socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
4634  ::SysError("TWinNTSystem::AnnounceUnixService", "socket");
4635  return -1;
4636  }
4637 
4638  struct sockaddr_in inserver;
4639  memset(&inserver, 0, sizeof(inserver));
4640  inserver.sin_family = AF_INET;
4641  inserver.sin_addr.s_addr = ::htonl(INADDR_LOOPBACK);
4642  inserver.sin_port = port;
4643 
4644  // Bind socket
4645  if (port > 0) {
4646  if (::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver)) == SOCKET_ERROR) {
4647  ::SysError("TWinNTSystem::AnnounceUnixService", "bind");
4648  return -2;
4649  }
4650  }
4651  // Start accepting connections
4652  if (::listen(sock, backlog)) {
4653  ::SysError("TWinNTSystem::AnnounceUnixService", "listen");
4654  return -1;
4655  }
4656  return (int)sock;
4657 }
4658 
4659 ////////////////////////////////////////////////////////////////////////////////
4660 /// Open a socket on path 'sockpath', bind to it and start listening for Unix
4661 /// domain connections to it. Returns socket fd or -1.
4662 
4663 int TWinNTSystem::AnnounceUnixService(const char *sockpath, int backlog)
4664 {
4665  if (!sockpath || strlen(sockpath) <= 0) {
4666  ::SysError("TWinNTSystem::AnnounceUnixService", "socket path undefined");
4667  return -1;
4668  }
4669 
4670  struct sockaddr_in myaddr;
4671  FILE * fp;
4672  int len = sizeof myaddr;
4673  int rc;
4674  int sock;
4675 
4676  // Create socket
4677  if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
4678  ::SysError("TWinNTSystem::AnnounceUnixService", "socket");
4679  return -1;
4680  }
4681 
4682  memset(&myaddr, 0, sizeof(myaddr));
4683  myaddr.sin_port = 0;
4684  myaddr.sin_family = AF_INET;
4685  myaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4686 
4687  rc = bind(sock, (struct sockaddr *)&myaddr, len);
4688  if (rc) {
4689  ::SysError("TWinNTSystem::AnnounceUnixService", "bind");
4690  return rc;
4691  }
4692  rc = getsockname(sock, (struct sockaddr *)&myaddr, &len);
4693  if (rc) {
4694  ::SysError("TWinNTSystem::AnnounceUnixService", "getsockname");
4695  return rc;
4696  }
4697  TString socketpath = sockpath;
4698  socketpath.ReplaceAll("/", "\\");
4699  fp = fopen(socketpath, "wb");
4700  if (!fp) {
4701  ::SysError("TWinNTSystem::AnnounceUnixService", "fopen");
4702  return -1;
4703  }
4704  fprintf(fp, "%d", myaddr.sin_port);
4705  fclose(fp);
4706 
4707  // Start accepting connections
4708  if (listen(sock, backlog)) {
4709  ::SysError("TWinNTSystem::AnnounceUnixService", "listen");
4710  return -1;
4711  }
4712 
4713  return sock;
4714 }
4715 
4716 ////////////////////////////////////////////////////////////////////////////////
4717 /// Close socket.
4718 
4719 void TWinNTSystem::CloseConnection(int socket, Bool_t force)
4720 {
4721  if (socket == -1) return;
4722  SOCKET sock = socket;
4723 
4724  if (force) {
4725  ::shutdown(sock, 2);
4726  }
4727  struct linger linger = {0, 0};
4728  ::setsockopt(sock, SOL_SOCKET, SO_LINGER, (char *) &linger, sizeof(linger));
4729  while (::closesocket(sock) == SOCKET_ERROR && WSAGetLastError() == WSAEINTR) {
4731  }
4732 }
4733 
4734 ////////////////////////////////////////////////////////////////////////////////
4735 /// Receive a buffer headed by a length indicator. Length is the size of
4736 /// the buffer. Returns the number of bytes received in buf or -1 in
4737 /// case of error.
4738 
4739 int TWinNTSystem::RecvBuf(int sock, void *buf, int length)
4740 {
4741  Int_t header;
4742 
4743  if (WinNTRecv(sock, &header, sizeof(header), 0) > 0) {
4744  int count = ::ntohl(header);
4745 
4746  if (count > length) {
4747  Error("RecvBuf", "record header exceeds buffer size");
4748  return -1;
4749  } else if (count > 0) {
4750  if (WinNTRecv(sock, buf, count, 0) < 0) {
4751  Error("RecvBuf", "cannot receive buffer");
4752  return -1;
4753  }
4754  }
4755  return count;
4756  }
4757  return -1;
4758 }
4759 
4760 ////////////////////////////////////////////////////////////////////////////////
4761 /// Send a buffer headed by a length indicator. Returns length of sent buffer
4762 /// or -1 in case of error.
4763 
4764 int TWinNTSystem::SendBuf(int sock, const void *buf, int length)
4765 {
4766  Int_t header = ::htonl(length);
4767 
4768  if (WinNTSend(sock, &header, sizeof(header), 0) < 0) {
4769  Error("SendBuf", "cannot send header");
4770  return -1;
4771  }
4772  if (length > 0) {
4773  if (WinNTSend(sock, buf, length, 0) < 0) {
4774  Error("SendBuf", "cannot send buffer");
4775  return -1;
4776  }
4777  }
4778  return length;
4779 }
4780 
4781 ////////////////////////////////////////////////////////////////////////////////
4782 /// Receive exactly length bytes into buffer. Use opt to receive out-of-band
4783 /// data or to have a peek at what is in the buffer (see TSocket). Buffer
4784 /// must be able to store at least length bytes. Returns the number of
4785 /// bytes received (can be 0 if other side of connection was closed) or -1
4786 /// in case of error, -2 in case of MSG_OOB and errno == EWOULDBLOCK, -3
4787 /// in case of MSG_OOB and errno == EINVAL and -4 in case of kNoBlock and
4788 /// errno == EWOULDBLOCK. Returns -5 if pipe broken or reset by peer
4789 /// (EPIPE || ECONNRESET).
4790 
4791 int TWinNTSystem::RecvRaw(int sock, void *buf, int length, int opt)
4792 {
4793  int flag;
4794 
4795  switch (opt) {
4796  case kDefault:
4797  flag = 0;
4798  break;
4799  case kOob:
4800  flag = MSG_OOB;
4801  break;
4802  case kPeek:
4803  flag = MSG_PEEK;
4804  break;
4805  case kDontBlock:
4806  flag = -1;
4807  break;
4808  default:
4809  flag = 0;
4810  break;
4811  }
4812 
4813  int n;
4814  if ((n = WinNTRecv(sock, buf, length, flag)) <= 0) {
4815  if (n == -1) {
4816  Error("RecvRaw", "cannot receive buffer");
4817  }
4818  return n;
4819  }
4820  return n;
4821 }
4822 
4823 ////////////////////////////////////////////////////////////////////////////////
4824 /// Send exactly length bytes from buffer. Use opt to send out-of-band
4825 /// data (see TSocket). Returns the number of bytes sent or -1 in case of
4826 /// error. Returns -4 in case of kNoBlock and errno == EWOULDBLOCK.
4827 /// Returns -5 if pipe broken or reset by peer (EPIPE || ECONNRESET).
4828 
4829 int TWinNTSystem::SendRaw(int sock, const void *buf, int length, int opt)
4830 {
4831  int flag;
4832 
4833  switch (opt) {
4834  case kDefault:
4835  flag = 0;
4836  break;
4837  case kOob:
4838  flag = MSG_OOB;
4839  break;
4840  case kDontBlock:
4841  flag = -1;
4842  break;
4843  case kPeek: // receive only option (see RecvRaw)
4844  default:
4845  flag = 0;
4846  break;
4847  }
4848 
4849  int n;
4850  if ((n = WinNTSend(sock, buf, length, flag)) <= 0) {
4851  if (n == -1 && GetErrno() != EINTR) {
4852  Error("SendRaw", "cannot send buffer");
4853  }
4854  return n;
4855  }
4856  return n;
4857 }
4858 
4859 ////////////////////////////////////////////////////////////////////////////////
4860 /// Set socket option.
4861 
4862 int TWinNTSystem::SetSockOpt(int socket, int opt, int value)
4863 {
4864  u_long val = value;
4865  if (socket == -1) return -1;
4866  SOCKET sock = socket;
4867 
4868  switch (opt) {
4869  case kSendBuffer:
4870  if (::setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)&val, sizeof(val)) == SOCKET_ERROR) {
4871  ::SysError("SetSockOpt", "setsockopt(SO_SNDBUF)");
4872  return -1;
4873  }
4874  break;
4875  case kRecvBuffer:
4876  if (::setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)&val, sizeof(val)) == SOCKET_ERROR) {
4877  ::SysError("SetSockOpt", "setsockopt(SO_RCVBUF)");
4878  return -1;
4879  }
4880  break;
4881  case kOobInline:
4882  if (::setsockopt(sock, SOL_SOCKET, SO_OOBINLINE, (char*)&val, sizeof(val)) == SOCKET_ERROR) {
4883  SysError("SetSockOpt", "setsockopt(SO_OOBINLINE)");
4884  return -1;
4885  }
4886  break;
4887  case kKeepAlive:
4888  if (::setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&val, sizeof(val)) == SOCKET_ERROR) {
4889  ::SysError("SetSockOpt", "setsockopt(SO_KEEPALIVE)");
4890  return -1;
4891  }
4892  break;
4893  case kReuseAddr:
4894  if (::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&val, sizeof(val)) == SOCKET_ERROR) {
4895  ::SysError("SetSockOpt", "setsockopt(SO_REUSEADDR)");
4896  return -1;
4897  }
4898  break;
4899  case kNoDelay:
4900  if (::setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&val, sizeof(val)) == SOCKET_ERROR) {
4901  ::SysError("SetSockOpt", "setsockopt(TCP_NODELAY)");
4902  return -1;
4903  }
4904  break;
4905  case kNoBlock:
4906  if (::ioctlsocket(sock, FIONBIO, &val) == SOCKET_ERROR) {
4907  ::SysError("SetSockOpt", "ioctl(FIONBIO)");
4908  return -1;
4909  }
4910  break;
4911 #if 0
4912  case kProcessGroup:
4913  if (::ioctl(sock, SIOCSPGRP, &val) == -1) {
4914  ::SysError("SetSockOpt", "ioctl(SIOCSPGRP)");
4915  return -1;
4916  }
4917  break;
4918 #endif
4919  case kAtMark: // read-only option (see GetSockOpt)
4920  case kBytesToRead: // read-only option
4921  default:
4922  Error("SetSockOpt", "illegal option (%d)", opt);
4923  return -1;
4924  break;
4925  }
4926  return 0;
4927 }
4928 
4929 ////////////////////////////////////////////////////////////////////////////////
4930 /// Get socket option.
4931 
4932 int TWinNTSystem::GetSockOpt(int socket, int opt, int *val)
4933 {
4934  if (socket == -1) return -1;
4935  SOCKET sock = socket;
4936 
4937  int optlen = sizeof(*val);
4938 
4939  switch (opt) {
4940  case kSendBuffer:
4941  if (::getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)val, &optlen) == SOCKET_ERROR) {
4942  ::SysError("GetSockOpt", "getsockopt(SO_SNDBUF)");
4943  return -1;
4944  }
4945  break;
4946  case kRecvBuffer:
4947  if (::getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)val, &optlen) == SOCKET_ERROR) {
4948  ::SysError("GetSockOpt", "getsockopt(SO_RCVBUF)");
4949  return -1;
4950  }
4951  break;
4952  case kOobInline:
4953  if (::getsockopt(sock, SOL_SOCKET, SO_OOBINLINE, (char*)val, &optlen) == SOCKET_ERROR) {
4954  ::SysError("GetSockOpt", "getsockopt(SO_OOBINLINE)");
4955  return -1;
4956  }
4957  break;
4958  case kKeepAlive:
4959  if (::getsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)val, &optlen) == SOCKET_ERROR) {
4960  ::SysError("GetSockOpt", "getsockopt(SO_KEEPALIVE)");
4961  return -1;
4962  }
4963  break;
4964  case kReuseAddr:
4965  if (::getsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)val, &optlen) == SOCKET_ERROR) {
4966  ::SysError("GetSockOpt", "getsockopt(SO_REUSEADDR)");
4967  return -1;
4968  }
4969  break;
4970  case kNoDelay:
4971  if (::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)val, &optlen) == SOCKET_ERROR) {
4972  ::SysError("GetSockOpt", "getsockopt(TCP_NODELAY)");
4973  return -1;
4974  }
4975  break;
4976  case kNoBlock:
4977  {
4978  int flg = 0;
4979  if (sock == INVALID_SOCKET) {
4980  ::SysError("GetSockOpt", "INVALID_SOCKET");
4981  }
4982  return -1;
4983  *val = flg; // & O_NDELAY; It is not been defined for WIN32
4984  }
4985  break;
4986 #if 0
4987  case kProcessGroup:
4988  if (::ioctlsocket(sock, SIOCGPGRP, (u_long*)val) == SOCKET_ERROR) {
4989  ::SysError("GetSockOpt", "ioctl(SIOCGPGRP)");
4990  return -1;
4991  }
4992  break;
4993 #endif
4994  case kAtMark:
4995  if (::ioctlsocket(sock, SIOCATMARK, (u_long*)val) == SOCKET_ERROR) {
4996  ::SysError("GetSockOpt", "ioctl(SIOCATMARK)");
4997  return -1;
4998  }
4999  break;
5000  case kBytesToRead:
5001  if (::ioctlsocket(sock, FIONREAD, (u_long*)val) == SOCKET_ERROR) {
5002  ::SysError("GetSockOpt", "ioctl(FIONREAD)");
5003  return -1;
5004  }
5005  break;
5006  default:
5007  Error("GetSockOpt", "illegal option (%d)", opt);
5008  *val = 0;
5009  return -1;
5010  break;
5011  }
5012  return 0;
5013 }
5014 
5015 ////////////////////////////////////////////////////////////////////////////////
5016 /// Connect to service servicename on server servername.
5017 
5018 int TWinNTSystem::ConnectService(const char *servername, int port,
5019  int tcpwindowsize, const char *protocol)
5020 {
5021  short sport;
5022  struct servent *sp;
5023 
5024  if (!strcmp(servername, "unix")) {
5025  return WinNTUnixConnect(port);
5026  }
5027  else if (!gSystem->AccessPathName(servername) || servername[0] == '/' ||
5028  (servername[1] == ':' && servername[2] == '/')) {
5029  return WinNTUnixConnect(servername);
5030  }
5031 
5032  if (!strcmp(protocol, "udp")){
5033  return WinNTUdpConnect(servername, port);
5034  }
5035 
5036  if ((sp = ::getservbyport(::htons(port), kProtocolName))) {
5037  sport = sp->s_port;
5038  } else {
5039  sport = ::htons(port);
5040  }
5041 
5042  TInetAddress addr = gSystem->GetHostByName(servername);
5043  if (!addr.IsValid()) return -1;
5044  UInt_t adr = ::htonl(addr.GetAddress());
5045 
5046  struct sockaddr_in server;
5047  memset(&server, 0, sizeof(server));
5048  memcpy(&server.sin_addr, &adr, sizeof(adr));
5049  server.sin_family = addr.GetFamily();
5050  server.sin_port = sport;
5051 
5052  // Create socket
5053  SOCKET sock;
5054  if ((sock = ::socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
5055  ::SysError("TWinNTSystem::WinNTConnectTcp", "socket");
5056  return -1;
5057  }
5058 
5059  if (tcpwindowsize > 0) {
5060  gSystem->SetSockOpt((int)sock, kRecvBuffer, tcpwindowsize);
5061  gSystem->SetSockOpt((int)sock, kSendBuffer, tcpwindowsize);
5062  }
5063 
5064  if (::connect(sock, (struct sockaddr*) &server, sizeof(server)) == INVALID_SOCKET) {
5065  //::SysError("TWinNTSystem::UnixConnectTcp", "connect");
5066  ::closesocket(sock);
5067  return -1;
5068  }
5069  return (int) sock;
5070 }
5071 
5072 ////////////////////////////////////////////////////////////////////////////////
5073 /// Connect to a Unix domain socket.
5074 
5076 {
5077  struct sockaddr_in myaddr;
5078  int sock;
5079 
5080  memset(&myaddr, 0, sizeof(myaddr));
5081  myaddr.sin_family = AF_INET;
5082  myaddr.sin_port = port;
5083  myaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5084 
5085  // Open socket
5086  if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
5087  ::SysError("TWinNTSystem::WinNTUnixConnect", "socket");
5088  return -1;
5089  }
5090 
5091  while ((connect(sock, (struct sockaddr *)&myaddr, sizeof myaddr)) == -1) {
5092  if (GetErrno() == EINTR)
5093  ResetErrno();
5094  else {
5095  ::SysError("TWinNTSystem::WinNTUnixConnect", "connect");
5096  close(sock);
5097  return -1;
5098  }
5099  }
5100  return sock;
5101 }
5102 
5103 ////////////////////////////////////////////////////////////////////////////////
5104 /// Connect to a Unix domain socket. Returns -1 in case of error.
5105 
5106 int TWinNTSystem::WinNTUnixConnect(const char *sockpath)
5107 {
5108  FILE *fp;
5109  int port = 0;
5110 
5111  if (!sockpath || strlen(sockpath) <= 0) {
5112  ::SysError("TWinNTSystem::WinNTUnixConnect", "socket path undefined");
5113  return -1;
5114  }
5115  TString socketpath = sockpath;
5116  socketpath.ReplaceAll("/", "\\");
5117  fp = fopen(socketpath.Data(), "rb");
5118  if (!fp) {
5119  ::SysError("TWinNTSystem::WinNTUnixConnect", "fopen");
5120  return -1;
5121  }
5122  fscanf(fp, "%d", &port);
5123  fclose(fp);
5124  /* XXX: set errno in this case */
5125  if (port < 0 || port > 65535) {
5126  ::SysError("TWinNTSystem::WinNTUnixConnect", "invalid port");
5127  return -1;
5128  }
5129  return WinNTUnixConnect(port);
5130 }
5131 
5132 ////////////////////////////////////////////////////////////////////////////////
5133 /// Creates a UDP socket connection
5134 /// Is called via the TSocket constructor. Returns -1 in case of error.
5135 
5136 int TWinNTSystem::WinNTUdpConnect(const char *hostname, int port)
5137 {
5138  short sport;
5139  struct servent *sp;
5140 
5141  if ((sp = getservbyport(htons(port), kProtocolName)))
5142  sport = sp->s_port;
5143  else
5144  sport = htons(port);
5145 
5146  TInetAddress addr = gSystem->GetHostByName(hostname);
5147  if (!addr.IsValid()) return -1;
5148  UInt_t adr = htonl(addr.GetAddress());
5149 
5150  struct sockaddr_in server;
5151  memset(&server, 0, sizeof(server));
5152  memcpy(&server.sin_addr, &adr, sizeof(adr));
5153  server.sin_family = addr.GetFamily();
5154  server.sin_port = sport;
5155 
5156  // Create socket
5157  int sock;
5158  if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
5159  ::SysError("TWinNTSystem::WinNTUdpConnect", "socket (%s:%d)",
5160  hostname, port);
5161  return -1;
5162  }
5163 
5164  while (connect(sock, (struct sockaddr*) &server, sizeof(server)) == -1) {
5165  if (GetErrno() == EINTR)
5166  ResetErrno();
5167  else {
5168  ::SysError("TWinNTSystem::WinNTUdpConnect", "connect (%s:%d)",
5169  hostname, port);
5170  close(sock);
5171  return -1;
5172  }
5173  }
5174  return sock;
5175 }
5176 
5177 ////////////////////////////////////////////////////////////////////////////////
5178 /// Open a connection to a service on a server. Returns -1 in case
5179 /// connection cannot be opened.
5180 /// Use tcpwindowsize to specify the size of the receive buffer, it has
5181 /// to be specified here to make sure the window scale option is set (for
5182 /// tcpwindowsize > 65KB and for platforms supporting window scaling).
5183 /// Is called via the TSocket constructor.
5184 
5185 int TWinNTSystem::OpenConnection(const char *server, int port, int tcpwindowsize,
5186  const char *protocol)
5187 {
5188  return ConnectService(server, port, tcpwindowsize, protocol);
5189 }
5190 
5191 ////////////////////////////////////////////////////////////////////////////////
5192 /// Announce TCP/IP service.
5193 /// Open a socket, bind to it and start listening for TCP/IP connections
5194 /// on the port. If reuse is true reuse the address, backlog specifies
5195 /// how many sockets can be waiting to be accepted.
5196 /// Use tcpwindowsize to specify the size of the receive buffer, it has
5197 /// to be specified here to make sure the window scale option is set (for
5198 /// tcpwindowsize > 65KB and for platforms supporting window scaling).
5199 /// Returns socket fd or -1 if socket() failed, -2 if bind() failed
5200 /// or -3 if listen() failed.
5201 
5202 int TWinNTSystem::AnnounceTcpService(int port, Bool_t reuse, int backlog,
5203  int tcpwindowsize)
5204 {
5205  short sport;
5206  struct servent *sp;
5207  const short kSOCKET_MINPORT = 5000, kSOCKET_MAXPORT = 15000;
5208  short tryport = kSOCKET_MINPORT;
5209 
5210  if ((sp = ::getservbyport(::htons(port), kProtocolName))) {
5211  sport = sp->s_port;
5212  } else {
5213  sport = ::htons(port);
5214  }
5215 
5216  if (port == 0 && reuse) {
5217  ::Error("TWinNTSystem::WinNTTcpService", "cannot do a port scan while reuse is true");
5218  return -1;
5219  }
5220 
5221  if ((sp = ::getservbyport(::htons(port), kProtocolName))) {
5222  sport = sp->s_port;
5223  } else {
5224  sport = ::htons(port);
5225  }
5226 
5227  // Create tcp socket
5228  SOCKET sock;
5229  if ((sock = ::socket(AF_INET, SOCK_STREAM, 0)) < 0) {
5230  ::SysError("TWinNTSystem::WinNTTcpService", "socket");
5231  return -1;
5232  }
5233 
5234  if (reuse) {
5235  gSystem->SetSockOpt((int)sock, kReuseAddr, 1);
5236  }
5237 
5238  if (tcpwindowsize > 0) {
5239  gSystem->SetSockOpt((int)sock, kRecvBuffer, tcpwindowsize);
5240  gSystem->SetSockOpt((int)sock, kSendBuffer, tcpwindowsize);
5241  }
5242 
5243  struct sockaddr_in inserver;
5244  memset(&inserver, 0, sizeof(inserver));
5245  inserver.sin_family = AF_INET;
5246  inserver.sin_addr.s_addr = ::htonl(INADDR_ANY);
5247  inserver.sin_port = sport;
5248 
5249  // Bind socket
5250  if (port > 0) {
5251  if (::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver)) == SOCKET_ERROR) {
5252  ::SysError("TWinNTSystem::WinNTTcpService", "bind");
5253  return -2;
5254  }
5255  } else {
5256  int bret;
5257  do {
5258  inserver.sin_port = ::htons(tryport++);
5259  bret = ::bind(sock, (struct sockaddr*) &inserver, sizeof(inserver));
5260  } while (bret == SOCKET_ERROR && WSAGetLastError() == WSAEADDRINUSE &&
5261  tryport < kSOCKET_MAXPORT);
5262  if (bret == SOCKET_ERROR) {
5263  ::SysError("TWinNTSystem::WinNTTcpService", "bind (port scan)");
5264  return -2;
5265  }
5266  }
5267 
5268  // Start accepting connections
5269  if (::listen(sock, backlog) == SOCKET_ERROR) {
5270  ::SysError("TWinNTSystem::WinNTTcpService", "listen");
5271  return -3;
5272  }
5273  return (int)sock;
5274 }
5275 
5276 ////////////////////////////////////////////////////////////////////////////////
5277 /// Announce UDP service.
5278 
5280 {
5281  // Open a socket, bind to it and start listening for UDP connections
5282  // on the port. If reuse is true reuse the address, backlog specifies
5283  // how many sockets can be waiting to be accepted. If port is 0 a port
5284  // scan will be done to find a free port. This option is mutual exlusive
5285  // with the reuse option.
5286 
5287  const short kSOCKET_MINPORT = 5000, kSOCKET_MAXPORT = 15000;
5288  short sport, tryport = kSOCKET_MINPORT;
5289  struct servent *sp;
5290 
5291  if ((sp = getservbyport(htons(port), kProtocolName)))
5292  sport = sp->s_port;
5293  else
5294  sport = htons(port);
5295 
5296  // Create udp socket
5297  int sock;
5298  if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
5299  ::SysError("TUnixSystem::UnixUdpService", "socket");
5300  return -1;
5301  }
5302 
5303  struct sockaddr_in inserver;
5304  memset(&inserver, 0, sizeof(inserver));
5305  inserver.sin_family = AF_INET;
5306  inserver.sin_addr.s_addr = htonl(INADDR_ANY);
5307  inserver.sin_port = sport;
5308 
5309  // Bind socket
5310  if (port > 0) {
5311  if (bind(sock, (struct sockaddr*) &inserver, sizeof(inserver))) {
5312  ::SysError("TWinNTSystem::AnnounceUdpService", "bind");
5313  return -2;
5314  }
5315  } else {
5316  int bret;
5317  do {
5318  inserver.sin_port = htons(tryport++);
5319  bret = bind(sock, (struct sockaddr*) &inserver, sizeof(inserver));
5320  } while (bret == SOCKET_ERROR && WSAGetLastError() == WSAEADDRINUSE &&
5321  tryport < kSOCKET_MAXPORT);
5322  if (bret < 0) {
5323  ::SysError("TWinNTSystem::AnnounceUdpService", "bind (port scan)");
5324  return -2;
5325  }
5326  }
5327 
5328  // Start accepting connections
5329  if (listen(sock, backlog)) {
5330  ::SysError("TWinNTSystem::AnnounceUdpService", "listen");
5331  return -3;
5332  }
5333 
5334  return sock;
5335 }
5336 
5337 ////////////////////////////////////////////////////////////////////////////////
5338 /// Accept a connection. In case of an error return -1. In case
5339 /// non-blocking I/O is enabled and no connections are available
5340 /// return -2.
5341 
5343 {
5344  int soc = -1;
5345  SOCKET sock = socket;
5346 
5347  while ((soc = ::accept(sock, 0, 0)) == INVALID_SOCKET &&
5348  (::WSAGetLastError() == WSAEINTR)) {
5350  }
5351 
5352  if (soc == -1) {
5353  if (::WSAGetLastError() == WSAEWOULDBLOCK) {
5354  return -2;
5355  } else {
5356  ::SysError("AcceptConnection", "accept");
5357  return -1;
5358  }
5359  }
5360  return soc;
5361 }
5362 
5363 //---- System, CPU and Memory info ---------------------------------------------
5364 
5365 // !!! using undocumented functions and structures !!!
5366 
5367 #define SystemBasicInformation 0
5368 #define SystemPerformanceInformation 2
5369 
5370 typedef struct
5371 {
5372  DWORD dwUnknown1;
5373  ULONG uKeMaximumIncrement;
5374  ULONG uPageSize;
5375  ULONG uMmNumberOfPhysicalPages;
5376  ULONG uMmLowestPhysicalPage;
5377  ULONG UMmHighestPhysicalPage;
5378  ULONG uAllocationGranularity;
5379  PVOID pLowestUserAddress;
5380  PVOID pMmHighestUserAddress;
5381  ULONG uKeActiveProcessors;
5382  BYTE bKeNumberProcessors;
5383  BYTE bUnknown2;
5384  WORD bUnknown3;
5385 } SYSTEM_BASIC_INFORMATION;
5386 
5387 typedef struct
5388 {
5389  LARGE_INTEGER liIdleTime;
5390  DWORD dwSpare[76];
5391 } SYSTEM_PERFORMANCE_INFORMATION;
5392 
5393 typedef struct _PROCESS_MEMORY_COUNTERS {
5394  DWORD cb;
5395  DWORD PageFaultCount;
5396  SIZE_T PeakWorkingSetSize;
5397  SIZE_T WorkingSetSize;
5398  SIZE_T QuotaPeakPagedPoolUsage;
5399  SIZE_T QuotaPagedPoolUsage;
5400  SIZE_T QuotaPeakNonPagedPoolUsage;
5401  SIZE_T QuotaNonPagedPoolUsage;
5402  SIZE_T PagefileUsage;
5403  SIZE_T PeakPagefileUsage;
5405 
5406 typedef LONG (WINAPI *PROCNTQSI) (UINT, PVOID, ULONG, PULONG);
5407 
5408 #define Li2Double(x) ((double)((x).HighPart) * 4.294967296E9 + (double)((x).LowPart))
5409 
5410 ////////////////////////////////////////////////////////////////////////////////
5411 /// Calculate the CPU clock speed using the 'rdtsc' instruction.
5412 /// RDTSC: Read Time Stamp Counter.
5413 
5414 static DWORD GetCPUSpeed()
5415 {
5416  LARGE_INTEGER ulFreq, ulTicks, ulValue, ulStartCounter;
5417 
5418  // Query for high-resolution counter frequency
5419  // (this is not the CPU frequency):
5420  if (QueryPerformanceFrequency(&ulFreq)) {
5421  // Query current value:
5422  QueryPerformanceCounter(&ulTicks);
5423  // Calculate end value (one second interval);
5424  // this is (current + frequency)
5425  ulValue.QuadPart = ulTicks.QuadPart + ulFreq.QuadPart/10;
5426  ulStartCounter.QuadPart = __rdtsc();
5427 
5428  // Loop for one second (measured with the high-resolution counter):
5429  do {
5430  QueryPerformanceCounter(&ulTicks);
5431  } while (ulTicks.QuadPart <= ulValue.QuadPart);
5432  // Now again read CPU time-stamp counter:
5433  return (DWORD)((__rdtsc() - ulStartCounter.QuadPart)/100000);
5434  } else {
5435  // No high-resolution counter present:
5436  return 0;
5437  }
5438 }
5439 
5440 #define BUFSIZE 80
5441 #define SM_SERVERR2 89
5442 typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
5443 
5444 ////////////////////////////////////////////////////////////////////////////////
5445 
5446 static char *GetWindowsVersion()
5447 {
5448  OSVERSIONINFOEX osvi;
5449  SYSTEM_INFO si;
5450  PGNSI pGNSI;
5451  BOOL bOsVersionInfoEx;
5452  static char *strReturn = 0;
5453  char temp[512];
5454 
5455  if (strReturn == 0)
5456  strReturn = new char[2048];
5457  else
5458  return strReturn;
5459 
5460  ZeroMemory(&si, sizeof(SYSTEM_INFO));
5461  ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
5462 
5463  // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
5464  // If that fails, try using the OSVERSIONINFO structure.
5465 
5466  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
5467 
5468  if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) )
5469  {
5470  osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
5471  if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) )
5472  return "";
5473  }
5474 
5475  // Call GetNativeSystemInfo if supported or GetSystemInfo otherwise.
5476  pGNSI = (PGNSI) GetProcAddress( GetModuleHandle("kernel32.dll"),
5477  "GetNativeSystemInfo");
5478  if(NULL != pGNSI)
5479  pGNSI(&si);
5480  else GetSystemInfo(&si);
5481 
5482  switch (osvi.dwPlatformId)
5483  {
5484  // Test for the Windows NT product family.
5485  case VER_PLATFORM_WIN32_NT:
5486 
5487  // Test for the specific product.
5488  if ( osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0 )
5489  {
5490  if( osvi.wProductType == VER_NT_WORKSTATION )
5491  strlcpy(strReturn, "Microsoft Windows Vista ",2048);
5492  else strlcpy(strReturn, "Windows Server \"Longhorn\" " ,2048);
5493  }
5494  if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2 )
5495  {
5496  if( GetSystemMetrics(SM_SERVERR2) )
5497  strlcpy(strReturn, "Microsoft Windows Server 2003 \"R2\" ",2048);
5498  else if( osvi.wProductType == VER_NT_WORKSTATION &&
5499  si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64)
5500  {
5501  strlcpy(strReturn, "Microsoft Windows XP Professional x64 Edition ",2048);
5502  }
5503  else strlcpy(strReturn, "Microsoft Windows Server 2003, ",2048);
5504  }
5505  if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 )
5506  strlcpy(strReturn, "Microsoft Windows XP ",2048);
5507 
5508  if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0 )
5509  strlcpy(strReturn, "Microsoft Windows 2000 ",2048);
5510 
5511  if ( osvi.dwMajorVersion <= 4 )
5512  strlcpy(strReturn, "Microsoft Windows NT ",2048);
5513 
5514  // Test for specific product on Windows NT 4.0 SP6 and later.
5515  if( bOsVersionInfoEx )
5516  {
5517  // Test for the workstation type.
5518  if ( osvi.wProductType == VER_NT_WORKSTATION &&
5519  si.wProcessorArchitecture!=PROCESSOR_ARCHITECTURE_AMD64)
5520  {
5521  if( osvi.dwMajorVersion == 4 )
5522  strlcat(strReturn, "Workstation 4.0 ",2048 );
5523  else if( osvi.wSuiteMask & VER_SUITE_PERSONAL )
5524  strlcat(strReturn, "Home Edition " ,2048);
5525  else strlcat(strReturn, "Professional " ,2048);
5526  }
5527  // Test for the server type.
5528  else if ( osvi.wProductType == VER_NT_SERVER ||
5529  osvi.wProductType == VER_NT_DOMAIN_CONTROLLER )
5530  {
5531  if(osvi.dwMajorVersion==5 && osvi.dwMinorVersion==2)
5532  {
5533  if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_IA64 )
5534  {
5535  if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
5536  strlcat(strReturn, "Datacenter Edition for Itanium-based Systems",2048 );
5537  else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
5538  strlcat(strReturn, "Enterprise Edition for Itanium-based Systems" ,2048);
5539  }
5540  else if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64 )
5541  {
5542  if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
5543  strlcat(strReturn, "Datacenter x64 Edition ",2048 );
5544  else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
5545  strlcat(strReturn, "Enterprise x64 Edition ",2048 );
5546  else strlcat(strReturn, "Standard x64 Edition ",2048 );
5547  }
5548  else
5549  {
5550  if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
5551  strlcat(strReturn, "Datacenter Edition ",2048 );
5552  else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
5553  strlcat(strReturn, "Enterprise Edition ",2048 );
5554  else if ( osvi.wSuiteMask == VER_SUITE_BLADE )
5555  strlcat(strReturn, "Web Edition " ,2048);
5556  else strlcat(strReturn, "Standard Edition ",2048 );
5557  }
5558  }
5559  else if(osvi.dwMajorVersion==5 && osvi.dwMinorVersion==0)
5560  {
5561  if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
5562  strlcat(strReturn, "Datacenter Server ",2048 );
5563  else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
5564  strlcat(strReturn, "Advanced Server ",2048 );
5565  else strlcat(strReturn, "Server ",2048 );
5566  }
5567  else // Windows NT 4.0
5568  {
5569  if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
5570  strlcat(strReturn, "Server 4.0, Enterprise Edition " ,2048);
5571  else strlcat(strReturn, "Server 4.0 ",2048 );
5572  }
5573  }
5574  }
5575  // Test for specific product on Windows NT 4.0 SP5 and earlier
5576  else
5577  {
5578  HKEY hKey;
5579  TCHAR szProductType[BUFSIZE];
5580  DWORD dwBufLen=BUFSIZE*sizeof(TCHAR);
5581  LONG lRet;
5582 
5583  lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
5584  "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
5585  0, KEY_QUERY_VALUE, &hKey );
5586  if( lRet != ERROR_SUCCESS )
5587  return "";
5588 
5589  lRet = RegQueryValueEx( hKey, "ProductType", NULL, NULL,
5590  (LPBYTE) szProductType, &dwBufLen);
5591  RegCloseKey( hKey );
5592 
5593  if( (lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE*sizeof(TCHAR)) )
5594  return "";
5595 
5596  if ( lstrcmpi( "WINNT", szProductType) == 0 )
5597  strlcat(strReturn, "Workstation " ,2048);
5598  if ( lstrcmpi( "LANMANNT", szProductType) == 0 )
5599  strlcat(strReturn, "Server " ,2048);
5600  if ( lstrcmpi( "SERVERNT", szProductType) == 0 )
5601  strlcat(strReturn, "Advanced Server " ,2048);
5602  snprintf(temp,512, "%d.%d ", osvi.dwMajorVersion, osvi.dwMinorVersion);
5603  strlcat(strReturn, temp,2048);
5604  }
5605 
5606  // Display service pack (if any) and build number.
5607 
5608  if( osvi.dwMajorVersion == 4 &&
5609  lstrcmpi( osvi.szCSDVersion, "Service Pack 6" ) == 0 )
5610  {
5611  HKEY hKey;
5612  LONG lRet;
5613 
5614  // Test for SP6 versus SP6a.
5615  lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
5616  "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
5617  0, KEY_QUERY_VALUE, &hKey );
5618  if( lRet == ERROR_SUCCESS ) {
5619  snprintf(temp, 512, "Service Pack 6a (Build %d)", osvi.dwBuildNumber & 0xFFFF );
5620  strlcat(strReturn, temp,2048 );
5621  }
5622  else // Windows NT 4.0 prior to SP6a
5623  {
5624  snprintf(temp,512, "%s (Build %d)", osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF);
5625  strlcat(strReturn, temp,2048 );
5626  }
5627 
5628  RegCloseKey( hKey );
5629  }
5630  else // not Windows NT 4.0
5631  {
5632  snprintf(temp, 512,"%s (Build %d)", osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF);
5633  strlcat(strReturn, temp,2048 );
5634  }
5635 
5636  break;
5637 
5638  // Test for the Windows Me/98/95.
5639  case VER_PLATFORM_WIN32_WINDOWS:
5640 
5641  if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
5642  {
5643  strlcpy(strReturn, "Microsoft Windows 95 ",2048);
5644  if (osvi.szCSDVersion[1]=='C' || osvi.szCSDVersion[1]=='B')
5645  strlcat(strReturn, "OSR2 " ,2048);
5646  }
5647 
5648  if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
5649  {
5650  strlcpy(strReturn, "Microsoft Windows 98 ",2048);
5651  if ( osvi.szCSDVersion[1]=='A' || osvi.szCSDVersion[1]=='B')
5652  strlcat(strReturn, "SE ",2048 );
5653  }
5654 
5655  if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
5656  {
5657  strlcpy(strReturn, "Microsoft Windows Millennium Edition",2048);
5658  }
5659  break;
5660 
5661  case VER_PLATFORM_WIN32s:
5662  strlcpy(strReturn, "Microsoft Win32s",2048);
5663  break;
5664  }
5665  return strReturn;
5666 }
5667 
5668 ////////////////////////////////////////////////////////////////////////////////
5669 /// Use assembly to retrieve the L2 cache information ...
5670 
5671 static int GetL2CacheSize()
5672 {
5673  unsigned nHighestFeatureEx;
5674  int nBuff[4];
5675 
5676  __cpuid(nBuff, 0x80000000);
5677  nHighestFeatureEx = (unsigned)nBuff[0];
5678  // Get cache size
5679  if (nHighestFeatureEx >= 0x80000006) {
5680  __cpuid(nBuff, 0x80000006);
5681  return (((unsigned)nBuff[2])>>16);
5682  }
5683  else return 0;
5684 }
5685 
5686 ////////////////////////////////////////////////////////////////////////////////
5687 /// Get system info for Windows NT.
5688 
5689 static void GetWinNTSysInfo(SysInfo_t *sysinfo)
5690 {
5691  SYSTEM_PERFORMANCE_INFORMATION SysPerfInfo;
5692  SYSTEM_INFO sysInfo;
5693  MEMORYSTATUSEX statex;
5694  OSVERSIONINFO OsVersionInfo;
5695  HKEY hKey;
5696  char szKeyValueString[80];
5697  DWORD szKeyValueDword;
5698  DWORD dwBufLen;
5699  LONG status;
5700  PROCNTQSI NtQuerySystemInformation;
5701 
5702  NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(
5703  GetModuleHandle("ntdll"), "NtQuerySystemInformation");
5704 
5705  if (!NtQuerySystemInformation) {
5706  ::Error("GetWinNTSysInfo",
5707  "Error on GetProcAddress(NtQuerySystemInformation)");
5708  return;
5709  }
5710 
5711  status = NtQuerySystemInformation(SystemPerformanceInformation,
5712  &SysPerfInfo, sizeof(SysPerfInfo),
5713  NULL);
5714  OsVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
5715  GetVersionEx(&OsVersionInfo);
5716  GetSystemInfo(&sysInfo);
5717  statex.dwLength = sizeof(statex);
5718  if (!GlobalMemoryStatusEx(&statex)) {
5719  ::Error("GetWinNTSysInfo", "Error on GlobalMemoryStatusEx()");
5720  return;
5721  }
5722  sysinfo->fCpus = sysInfo.dwNumberOfProcessors;
5723  sysinfo->fPhysRam = (Int_t)(statex.ullTotalPhys >> 20);
5724  sysinfo->fOS = GetWindowsVersion();
5725  sysinfo->fModel = "";
5726  sysinfo->fCpuType = "";
5727  sysinfo->fCpuSpeed = GetCPUSpeed();
5728  sysinfo->fBusSpeed = 0; // bus speed in MHz
5729  sysinfo->fL2Cache = GetL2CacheSize();
5730 
5731  status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System",
5732  0, KEY_QUERY_VALUE, &hKey);
5733  if (status == ERROR_SUCCESS) {
5734  dwBufLen = sizeof(szKeyValueString);
5735  RegQueryValueEx(hKey, "Identifier", NULL, NULL,(LPBYTE)szKeyValueString,
5736  &dwBufLen);
5737  sysinfo->fModel = szKeyValueString;
5738  RegCloseKey (hKey);
5739  }
5740  status = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
5741  "Hardware\\Description\\System\\CentralProcessor\\0",
5742  0, KEY_QUERY_VALUE, &hKey);
5743  if (status == ERROR_SUCCESS) {
5744  dwBufLen = sizeof(szKeyValueString);
5745  status = RegQueryValueEx(hKey, "ProcessorNameString", NULL, NULL,
5746  (LPBYTE)szKeyValueString, &dwBufLen);
5747  if (status == ERROR_SUCCESS)
5748  sysinfo->fCpuType = szKeyValueString;
5749  dwBufLen = sizeof(DWORD);
5750  status = RegQueryValueEx(hKey,"~MHz",NULL,NULL,(LPBYTE)&szKeyValueDword,
5751  &dwBufLen);
5752  if ((status == ERROR_SUCCESS) && ((sysinfo->fCpuSpeed <= 0) ||
5753  (sysinfo->fCpuSpeed < (szKeyValueDword >> 1))))
5754  sysinfo->fCpuSpeed = (Int_t)szKeyValueDword;
5755  RegCloseKey (hKey);
5756  }
5757  sysinfo->fCpuType.Remove(TString::kBoth, ' ');
5758  sysinfo->fModel.Remove(TString::kBoth, ' ');
5759 }
5760 
5761 ////////////////////////////////////////////////////////////////////////////////
5762 /// Get CPU stat for Window. Use sampleTime to set the interval over which
5763 /// the CPU load will be measured, in ms (default 1000).
5764 
5765 static void GetWinNTCpuInfo(CpuInfo_t *cpuinfo, Int_t sampleTime)
5766 {
5767  SYSTEM_INFO sysInfo;
5768  Float_t idle_ratio, kernel_ratio, user_ratio, total_ratio;
5769  FILETIME ft_sys_idle, ft_sys_kernel, ft_sys_user, ft_fun_time;
5770  SYSTEMTIME st_fun_time;
5771 
5772  ULARGE_INTEGER ul_sys_idle, ul_sys_kernel, ul_sys_user;
5773  static ULARGE_INTEGER ul_sys_idleold = {0, 0};
5774  static ULARGE_INTEGER ul_sys_kernelold = {0, 0};
5775  static ULARGE_INTEGER ul_sys_userold = {0, 0};
5776  ULARGE_INTEGER ul_sys_idle_diff, ul_sys_kernel_diff, ul_sys_user_diff;
5777 
5778  ULARGE_INTEGER ul_fun_time;
5779  ULARGE_INTEGER ul_fun_timeold = {0, 0};
5780  ULARGE_INTEGER ul_fun_time_diff;
5781 
5782  typedef BOOL (__stdcall *GetSystemTimesProc)( LPFILETIME lpIdleTime,
5783  LPFILETIME lpKernelTime, LPFILETIME lpUserTime );
5784  static GetSystemTimesProc pGetSystemTimes = 0;
5785 
5786  HMODULE hModImagehlp = LoadLibrary( "Kernel32.dll" );
5787  if (!hModImagehlp) {
5788  ::Error("GetWinNTCpuInfo", "Error on LoadLibrary(Kernel32.dll)");
5789  return;
5790  }
5791 
5792  pGetSystemTimes = (GetSystemTimesProc) GetProcAddress( hModImagehlp,
5793  "GetSystemTimes" );
5794  if (!pGetSystemTimes) {
5795  ::Error("GetWinNTCpuInfo", "Error on GetProcAddress(GetSystemTimes)");
5796  return;
5797  }
5798  GetSystemInfo(&sysInfo);
5799 
5800 again:
5801  pGetSystemTimes(&ft_sys_idle,&ft_sys_kernel,&ft_sys_user);
5802  GetSystemTime(&st_fun_time);
5803  SystemTimeToFileTime(&st_fun_time,&ft_fun_time);
5804 
5805  memcpy(&ul_sys_idle, &ft_sys_idle, sizeof(FILETIME));
5806  memcpy(&ul_sys_kernel, &ft_sys_kernel, sizeof(FILETIME));
5807  memcpy(&ul_sys_user, &ft_sys_user, sizeof(FILETIME));
5808  memcpy(&ul_fun_time, &ft_fun_time, sizeof(FILETIME));
5809 
5810  ul_sys_idle_diff.QuadPart = ul_sys_idle.QuadPart -
5811  ul_sys_idleold.QuadPart;
5812  ul_sys_kernel_diff.QuadPart = ul_sys_kernel.QuadPart -
5813  ul_sys_kernelold.QuadPart;
5814  ul_sys_user_diff.QuadPart = ul_sys_user.QuadPart -
5815  ul_sys_userold.QuadPart;
5816 
5817  ul_fun_time_diff.QuadPart = ul_fun_time.QuadPart -
5818  ul_fun_timeold.QuadPart;
5819 
5820  ul_sys_idleold.QuadPart = ul_sys_idle.QuadPart;
5821  ul_sys_kernelold.QuadPart = ul_sys_kernel.QuadPart;
5822  ul_sys_userold.QuadPart = ul_sys_user.QuadPart;
5823 
5824  if (ul_fun_timeold.QuadPart == 0) {
5825  Sleep(sampleTime);
5826  ul_fun_timeold.QuadPart = ul_fun_time.QuadPart;
5827  goto again;
5828  }
5829  ul_fun_timeold.QuadPart = ul_fun_time.QuadPart;
5830 
5831  idle_ratio = (Float_t)(Li2Double(ul_sys_idle_diff)/
5832  Li2Double(ul_fun_time_diff))*100.0;
5833  user_ratio = (Float_t)(Li2Double(ul_sys_user_diff)/
5834  Li2Double(ul_fun_time_diff))*100.0;
5835  kernel_ratio = (Float_t)(Li2Double(ul_sys_kernel_diff)/
5836  Li2Double(ul_fun_time_diff))*100.0;
5837  idle_ratio /= (Float_t)sysInfo.dwNumberOfProcessors;
5838  user_ratio /= (Float_t)sysInfo.dwNumberOfProcessors;
5839  kernel_ratio /= (Float_t)sysInfo.dwNumberOfProcessors;
5840  total_ratio = 100.0 - idle_ratio;
5841 
5842  cpuinfo->fLoad1m = 0; // cpu load average over 1 m
5843  cpuinfo->fLoad5m = 0; // cpu load average over 5 m
5844  cpuinfo->fLoad15m = 0; // cpu load average over 15 m
5845  cpuinfo->fUser = user_ratio; // cpu user load in percentage
5846  cpuinfo->fSys = kernel_ratio; // cpu sys load in percentage
5847  cpuinfo->fTotal = total_ratio; // cpu user+sys load in percentage
5848  cpuinfo->fIdle = idle_ratio; // cpu idle percentage
5849 }
5850 
5851 ////////////////////////////////////////////////////////////////////////////////
5852 /// Get VM stat for Windows NT.
5853 
5854 static void GetWinNTMemInfo(MemInfo_t *meminfo)
5855 {
5856  Long64_t total, used, free, swap_total, swap_used, swap_avail;
5857  MEMORYSTATUSEX statex;
5858  statex.dwLength = sizeof(statex);
5859  if (!GlobalMemoryStatusEx(&statex)) {
5860  ::Error("GetWinNTMemInfo", "Error on GlobalMemoryStatusEx()");
5861  return;
5862  }
5863  used = (Long64_t)(statex.ullTotalPhys - statex.ullAvailPhys);
5864  free = (Long64_t) statex.ullAvailPhys;
5865  total = (Long64_t) statex.ullTotalPhys;
5866 
5867  meminfo->fMemTotal = (Int_t) (total >> 20); // divide by 1024 * 1024
5868  meminfo->fMemUsed = (Int_t) (used >> 20);
5869  meminfo->fMemFree = (Int_t) (free >> 20);
5870 
5871  swap_total = (Long64_t)(statex.ullTotalPageFile - statex.ullTotalPhys);
5872  swap_avail = (Long64_t)(statex.ullAvailPageFile - statex.ullAvailPhys);
5873  swap_used = swap_total - swap_avail;
5874 
5875  meminfo->fSwapTotal = (Int_t) (swap_total >> 20);
5876  meminfo->fSwapUsed = (Int_t) (swap_used >> 20);
5877  meminfo->fSwapFree = (Int_t) (swap_avail >> 20);
5878 }
5879 
5880 ////////////////////////////////////////////////////////////////////////////////
5881 /// Get process info for this process on Windows NT.
5882 
5883 static void GetWinNTProcInfo(ProcInfo_t *procinfo)
5884 {
5886  FILETIME starttime, exittime, kerneltime, usertime;
5887  timeval ru_stime, ru_utime;
5888  ULARGE_INTEGER li;
5889 
5890  typedef BOOL (__stdcall *GetProcessMemoryInfoProc)( HANDLE Process,
5891  PPROCESS_MEMORY_COUNTERS ppsmemCounters, DWORD cb );
5892  static GetProcessMemoryInfoProc pGetProcessMemoryInfo = 0;
5893 
5894  HMODULE hModImagehlp = LoadLibrary( "Psapi.dll" );
5895  if (!hModImagehlp) {
5896  ::Error("GetWinNTProcInfo", "Error on LoadLibrary(Psapi.dll)");
5897  return;
5898  }
5899 
5900  pGetProcessMemoryInfo = (GetProcessMemoryInfoProc) GetProcAddress(
5901  hModImagehlp, "GetProcessMemoryInfo" );
5902  if (!pGetProcessMemoryInfo) {
5903  ::Error("GetWinNTProcInfo",
5904  "Error on GetProcAddress(GetProcessMemoryInfo)");
5905  return;
5906  }
5907 
5908  if ( pGetProcessMemoryInfo( GetCurrentProcess(), &pmc, sizeof(pmc)) ) {
5909  procinfo->fMemResident = pmc.WorkingSetSize / 1024;
5910  procinfo->fMemVirtual = pmc.PagefileUsage / 1024;
5911  }
5912  if ( GetProcessTimes(GetCurrentProcess(), &starttime, &exittime,
5913  &kerneltime, &usertime)) {
5914 
5915  /* Convert FILETIMEs (0.1 us) to struct timeval */
5916  memcpy(&li, &kerneltime, sizeof(FILETIME));
5917  li.QuadPart /= 10L; /* Convert to microseconds */
5918  ru_stime.tv_sec = li.QuadPart / 1000000L;
5919  ru_stime.tv_usec = li.QuadPart % 1000000L;
5920 
5921  memcpy(&li, &usertime, sizeof(FILETIME));
5922  li.QuadPart /= 10L; /* Convert to microseconds */
5923  ru_utime.tv_sec = li.QuadPart / 1000000L;
5924  ru_utime.tv_usec = li.QuadPart % 1000000L;
5925 
5926  procinfo->fCpuUser = (Float_t)(ru_utime.tv_sec) +
5927  ((Float_t)(ru_utime.tv_usec) / 1000000.);
5928  procinfo->fCpuSys = (Float_t)(ru_stime.tv_sec) +
5929  ((Float_t)(ru_stime.tv_usec) / 1000000.);
5930  }
5931 }
5932 
5933 ////////////////////////////////////////////////////////////////////////////////
5934 /// Returns static system info, like OS type, CPU type, number of CPUs
5935 /// RAM size, etc into the SysInfo_t structure. Returns -1 in case of error,
5936 /// 0 otherwise.
5937 
5939 {
5940  if (!info) return -1;
5941  GetWinNTSysInfo(info);
5942  return 0;
5943 }
5944 
5945 ////////////////////////////////////////////////////////////////////////////////
5946 /// Returns cpu load average and load info into the CpuInfo_t structure.
5947 /// Returns -1 in case of error, 0 otherwise. Use sampleTime to set the
5948 /// interval over which the CPU load will be measured, in ms (default 1000).
5949 
5951 {
5952  if (!info) return -1;
5953  GetWinNTCpuInfo(info, sampleTime);
5954  return 0;
5955 }
5956 
5957 ////////////////////////////////////////////////////////////////////////////////
5958 /// Returns ram and swap memory usage info into the MemInfo_t structure.
5959 /// Returns -1 in case of error, 0 otherwise.
5960 
5962 {
5963  if (!info) return -1;
5964  GetWinNTMemInfo(info);
5965  return 0;
5966 }
5967 
5968 ////////////////////////////////////////////////////////////////////////////////
5969 /// Returns cpu and memory used by this process into the ProcInfo_t structure.
5970 /// Returns -1 in case of error, 0 otherwise.
5971 
5973 {
5974  if (!info) return -1;
5975  GetWinNTProcInfo(info);
5976  return 0;
5977 }
Int_t GetGid(const char *group=0)
Returns the group&#39;s id. If group = 0, returns current user&#39;s group.
Int_t fMemFree
Definition: TSystem.h:193
void DispatchOneEvent(Bool_t pendingOnly=kFALSE)
Dispatch a single event in TApplication::Run() loop.
Int_t fGid
Definition: TSystem.h:151
void(* SigHandler_t)(ESignals)
Definition: TUnixSystem.h:34
virtual const char * BaseName(const char *pathname)
Base name of a file name. Base name of /user/root is root.
Definition: TSystem.cxx:912
const TCHAR c_szColonSlash[]
const char * FindFile(const char *search, TString &file, EAccessMode mode=kFileExists)
Find location of file in a search path.
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
int GetSockOpt(int sock, int opt, int *val)
Get socket option.
Bool_t fFirstFile
Definition: TWinNTSystem.h:81
FILE * OpenPipe(const char *shellcmd, const char *mode)
Open a pipe.
Float_t fLoad15m
Definition: TSystem.h:179
double read(const std::string &file_name)
reading
Ssiz_t Last(char c) const
Find last occurrence of a character c.
Definition: TString.cxx:864
static void GetWinNTProcInfo(ProcInfo_t *procinfo)
Get process info for this process on Windows NT.
virtual void SetWriteReady()
Int_t GetEffectiveGid()
Returns the effective group id.
static void __cpuid(int *cpuid_data, int)
UserGroup_t * GetUserInfo(Int_t uid)
Returns all user info in the UserGroup_t structure.
virtual Bool_t ProcessEvents()
Process pending events (GUI, timers, sockets).
Definition: TSystem.cxx:420
const char * HomeDirectory(const char *userName=0)
Return the user&#39;s home directory.
int pw_uid
Definition: TWinNTSystem.h:52
static const TString & GetMacroDir()
Get the macro directory in the installation. Static utility function.
Definition: TROOT.cxx:2653
virtual Bool_t Notify()
Notify when event occurred on descriptor associated with this handler.
int RecvRaw(int sock, void *buffer, int length, int flag)
Receive exactly length bytes into buffer.
const char * HostName()
Return the system&#39;s host name.
WIN32_FIND_DATA fFindFileData
Definition: TWinNTSystem.h:87
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
void SetDynamicPath(const char *path)
Set the dynamic path to a new value.
long long Long64_t
Definition: RtypesCore.h:69
Int_t fBusSpeed
Definition: TSystem.h:167
struct group * fGroups
Definition: TWinNTSystem.h:75
Int_t fPhysRam
Definition: TSystem.h:169
Int_t fSigcnt
Definition: TSystem.h:275
R__EXTERN Int_t gErrorIgnoreLevel
Definition: TError.h:107
unsigned int hex
Definition: math.cpp:442
#define BUFSIZE
Int_t fReadOffSet
Definition: TSystem.h:220
static DWORD GetCPUSpeed()
Calculate the CPU clock speed using the &#39;rdtsc&#39; instruction.
Bool_t IsSync() const
char * pw_shell
Definition: TWinNTSystem.h:57
int Link(const char *from, const char *to)
Create a link from file1 to file2.
virtual void StackTrace()
Print a stack trace.
Definition: TSystem.cxx:736
const char * GetError()
Return system error string.
Bool_t GetNbGroups()
BOOL PathIsUNC(LPCTSTR pszPath)
Returns TRUE if the given string is a UNC path.
Float_t fSys
Definition: TSystem.h:181
Ssiz_t Length() const
Definition: TString.h:390
const char * GetLinkedLibraries()
Get list of shared libraries loaded at the start of the executable.
TLine * line
#define INVALID_HANDLE_VALUE
Definition: TMapFile.cxx:84
int Unlink(const char *name)
Unlink, i.e. remove, a file or directory.
HANDLE GetProcess()
Get current process handle.
void DoBeep(Int_t freq=-1, Int_t duration=-1) const
Beep.
float Float_t
Definition: RtypesCore.h:53
TTime Now()
Get current time in milliseconds since 0:00 Jan 1 1995.
void CloseConnection(int sock, Bool_t force=kFALSE)
Close socket.
int gr_gid
Definition: TWinNTSystem.h:64
int CopyFile(const char *from, const char *to, Bool_t overwrite=kFALSE)
Copy a file.
const char Option_t
Definition: RtypesCore.h:62
void * _ReturnAddress(void)
RooArgList L(const RooAbsArg &v1)
const char * PrependPathName(const char *dir, TString &name)
Concatenate a directory and a file name.
Int_t fBeepFreq
Definition: TSystem.h:279
TString fOS
Definition: TSystem.h:162
This class represents a WWW compatible URL.
Definition: TUrl.h:41
Int_t fUid
Definition: TSystem.h:139
Int_t Argc() const
Definition: TApplication.h:141
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
#define closesocket(a)
Definition: civetweb.c:275
static char * GetWindowsVersion()
virtual void SetOwner(Bool_t enable=kTRUE)
Set whether this collection is the owner (enable==true) of its content.
const char * GetProtocol() const
Definition: TUrl.h:73
TH1 * h
Definition: legend2.C:5
void AddDynamicPath(const char *dir)
Add a new directory to the dynamic path.
char * gr_name
Definition: TWinNTSystem.h:62
TString fGroup
Definition: TSystem.h:153
TTimer * RemoveTimer(TTimer *ti)
Remove timer from list of system timers.
typedef ULONG
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
int GetPathInfo(const char *path, FileStat_t &buf)
Get info about a file.
virtual void AddSignalHandler(TSignalHandler *sh)
Add a signal handler to list of system signal handlers.
Definition: TSystem.cxx:536
Int_t 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...
TString fWdpath
Definition: TSystem.h:276
Regular expression class.
Definition: TRegexp.h:35
int Umask(Int_t mask)
Set the process file creation mode mask.
static const char * filename()
TString ferr
Definition: pq2main.cxx:38
#define gROOT
Definition: TROOT.h:352
static char shellEscape
char * GetServiceByPort(int port)
Get name of internet service.
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition: TSystem.cxx:1766
int SendRaw(int sock, const void *buffer, int length, int flag)
Send exactly length bytes from buffer.
Basic string class.
Definition: TString.h:137
TSeqCollection * fSignalHandler
Definition: TSystem.h:287
Int_t GetMemInfo(MemInfo_t *info) const
Returns ram and swap memory usage info into the MemInfo_t structure.
void(WINAPI * PGNSI)(LPSYSTEM_INFO)
#define MAX_NAME_STRING
Definition: TWinNTSystem.h:44
int Int_t
Definition: RtypesCore.h:41
void IgnoreSignal(ESignals sig, Bool_t ignore=kTRUE)
If ignore is true ignore the specified signal, else restore previous behaviour.
bool Bool_t
Definition: RtypesCore.h:59
virtual TTimer * RemoveTimer(TTimer *t)
Remove timer from list of system timers.
Definition: TSystem.cxx:485
Bool_t IsAbsoluteFileName(const char *dir)
Return true if dir is an absolute pathname.
TArc * a
Definition: textangle.C:12
const Bool_t kFALSE
Definition: Rtypes.h:92
char * gr_passwd
Definition: TWinNTSystem.h:63
#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
Bool_t CheckDescriptors()
Check if there is activity on some file descriptors and call their Notify() member.
const char * DirName(const char *pathname)
Return the directory name in pathname.
static void ThreadStub(void *Parameter)
Definition: TWinNTSystem.h:101
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
int ClosePipe(FILE *pipe)
Close the pipe.
Bool_t IsPathLocal(const char *path)
Returns TRUE if the url in &#39;path&#39; points to the local file system.
TString fModel
Definition: TSystem.h:163
Bool_t fInsideNotify
Definition: TSystem.h:278
typedef PVOID
Long64_t fSize
Definition: TSystem.h:141
void * fGUIThreadHandle
Definition: TWinNTSystem.h:84
Bool_t BeginsWith(const char *s, ECaseCompare cmp=kExact) const
Definition: TString.h:558
typedef LONG(WINAPI *PROCNTQSI)(UINT
Int_t fUid
Definition: TSystem.h:150
Int_t GetEffectiveUid()
Returns the effective user id.
HANDLE fhProcess
Definition: TWinNTSystem.h:83
const char * kProtocolName
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
TWinNTSystem()
ctor
void NotifyApplicationCreated()
Hook to tell TSystem that the TApplication object has been created.
void SysError(const char *location, const char *msgfmt,...)
virtual Bool_t HandleTermInput()
Definition: TApplication.h:117
virtual const char * FindFile(const char *search, TString &file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition: TSystem.cxx:1449
Bool_t DispatchTimers(Bool_t mode)
Handle and dispatch timers.
const Double_t gTicks
TString & Replace(Ssiz_t pos, Ssiz_t n, const char *s)
Definition: TString.h:625
static Int_t GetErrno()
Static function returning system error number.
Definition: TSystem.cxx:264
Int_t fMode
Definition: TSystem.h:138
int SOCKET
Definition: civetweb.c:282
Int_t GetCpuInfo(CpuInfo_t *info, Int_t sampleTime=1000) const
Returns cpu load average and load info into the CpuInfo_t structure.
void Abort(int code=0)
Abort the application.
TString fHostname
Definition: TSystem.h:277
const char * Data() const
Definition: TString.h:349
static int GetL2CacheSize()
Use assembly to retrieve the L2 cache information ...
void AddSignalHandler(TSignalHandler *sh)
Add a signal handler to list of system signal handlers.
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
Bool_t ChangeDirectory(const char *path)
Change directory.
Double_t dot(const TVector2 &v1, const TVector2 &v2)
Definition: CsgOps.cxx:333
static int WinNTUnixConnect(int port)
Connect to a Unix domain socket.
BOOL PathIsRoot(LPCTSTR pPath)
check if a path is a root
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
TSignalHandler * RemoveSignalHandler(TSignalHandler *sh)
Remove a signal handler from list of signal handlers.
Vc_ALWAYS_INLINE void free(T *p)
Frees memory that was allocated with Vc::malloc.
Definition: memory.h:94
Float_t fUser
Definition: TSystem.h:180
Bool_t IsValid() const
Definition: TInetAddress.h:80
Int_t fSwapFree
Definition: TSystem.h:196
static const std::string separator("@@@")
Int_t bsize[]
Definition: SparseFit4.cxx:31
Int_t GetProcInfo(ProcInfo_t *info) const
Returns cpu and memory used by this process into the ProcInfo_t structure.
Int_t SetFPEMask(Int_t mask=kDefaultMask)
Set which conditions trigger a floating point exception.
int AcceptConnection(int sock)
Accept a connection.
static Bool_t Initialized()
Return kTRUE if the TROOT object has been initialized.
Definition: TROOT.cxx:2449
static const char * DynamicPath(const char *newpath=0, Bool_t reset=kFALSE)
Get shared library search path. Static utility function.
const char * FindDynamicLibrary(TString &lib, Bool_t quiet=kFALSE)
Returns and updates sLib to the path of a dynamic library (searches for library in the dynamic librar...
int GetPid()
Get process id.
TObject * Next()
Return next object in collection.
const Int_t kFatal
Definition: TError.h:44
R__EXTERN TFileHandler * gXDisplay
Definition: TSystem.h:546
Int_t fNfd
Signals that were trapped.
Definition: TSystem.h:272
TString fShell
Definition: TSystem.h:156
TString fRealName
Definition: TSystem.h:155
static char * shellMeta
void AddTimer(TTimer *ti)
Add timer to list of system timers.
virtual const char * Getenv(const char *env)
Get environment variable.
Definition: TSystem.cxx:1575
const char * TempDirectory() const
Return a user configured or systemwide directory to create temporary files in.
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
std::vector< std::vector< double > > Data
#define SM_SERVERR2
virtual void ExitLoop()
Exit from event loop.
Definition: TSystem.cxx:396
struct _PROCESS_MEMORY_COUNTERS PROCESS_MEMORY_COUNTERS
char * pw_name
Definition: TWinNTSystem.h:50
const char * WorkingDirectory()
Return the working directory for the default drive.
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:918
int GetServiceByName(const char *service)
Get port # of internet service.
virtual TInetAddress GetHostByName(const char *server)
Get Internet Protocol (IP) address of host.
Definition: TSystem.cxx:2181
int OpenConnection(const char *server, int port, int tcpwindowsize=-1, const char *protocol="tcp")
Open a connection to a service on a server.
std::string GetModuleFileName(const char *moduleName)
Return the dictionary file name for a module.
void Error(const char *location, const char *msgfmt,...)
Int_t fGid
Definition: TSystem.h:140
UInt_t GetAddress() const
Definition: TInetAddress.h:72
#define Li2Double(x)
const char * GetDynamicPath()
Return the dynamic path (used to find shared libraries).
TSeqCollection * fFileHandler
Definition: TSystem.h:288
Bool_t CollectGroups()
A doubly linked list.
Definition: TList.h:47
Float_t fLoad1m
Definition: TSystem.h:177
TString & GetLastErrorString()
Return the thread local storage for the custom last error message.
Definition: TSystem.cxx:1984
static const char * what
Definition: stlLoader.cc:6
struct _PROCESS_MEMORY_COUNTERS * PPROCESS_MEMORY_COUNTERS
const char * pwd()
Definition: TSystem.h:411
char ** Argv() const
Definition: TApplication.h:142
Bool_t InitUsersGroups()
Collect local users and groups accounts information.
static void SigHandler(ESignals sig)
Unix signal handler.
Int_t fL2Cache
Definition: TSystem.h:168
virtual ~TWinNTSystem()
dtor
int MakeDirectory(const char *name)
Make a WinNT file system directory.
int GetFd() const
Using a TBrowser one can browse all ROOT objects.
Definition: TBrowser.h:41
virtual Bool_t WriteNotify()
Notify when something can be written to the descriptor associated with this handler.
const char * GetDirEntry(void *dirp)
Returns the next directory entry.
R__EXTERN const char * gProgName
Definition: TSystem.h:234
#define MAX_SID_SIZE
Definition: TWinNTSystem.h:42
Float_t fCpuUser
Definition: TSystem.h:204
static int WinNTUdpConnect(const char *hostname, int port)
Creates a UDP socket connection Is called via the TSocket constructor.
ESignals
char * pw_gecos
Definition: TWinNTSystem.h:55
TString fUser
Definition: TSystem.h:152
Bool_t Init()
Initialize WinNT system interface.
static void sighandler(int sig)
Call the signal handler associated with the signal.
void Sleep(UInt_t milliSec)
Sleep milliSec milli seconds.
ULong_t fGUIThreadId
Definition: TWinNTSystem.h:85
Int_t fCpus
Definition: TSystem.h:165
virtual Bool_t HasWriteInterest()
True if handler is interested in write events.
const char * BaseName(const char *name)
Base name of a file name.
Bool_t ProcessEvents()
process pending events, i.e. DispatchOneEvent(kTRUE)
ROOT::R::TRInterface & r
Definition: Object.C:4
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
Bool_t fIsLink
Definition: TSystem.h:143
R__EXTERN TSystem * gSystem
Definition: TSystem.h:545
Int_t GetFPEMask()
Return the bitmap of conditions that trigger a floating point exception.
Bool_t EqualTo(const char *cs, ECaseCompare cmp=kExact) const
Definition: TString.h:576
virtual const char * GetLibraries(const char *regexp="", const char *option="", Bool_t isRegexp=kTRUE)
Return a space separated list of loaded shared libraries.
Definition: TSystem.cxx:2020
#define SID_MEMBER
Definition: TWinNTSystem.h:47
#define SystemPerformanceInformation
char * pw_group
Definition: TWinNTSystem.h:58
virtual Int_t GetValue(const char *name, Int_t dflt)
Returns the integer value for a resource.
Definition: TEnv.cxx:480
Int_t fSwapUsed
Definition: TSystem.h:195
int ConnectService(const char *servername, int port, int tcpwindowsize, const char *protocol="tcp")
Connect to service servicename on server servername.
Long_t fMemVirtual
Definition: TSystem.h:207
virtual void SetReadReady()
virtual Long_t NextTimeOut(Bool_t mode)
Time when next timer of mode (synchronous=kTRUE or asynchronous=kFALSE) will time-out (in ms)...
Definition: TSystem.cxx:498
void AddFileHandler(TFileHandler *fh)
Add a file handler to the list of system file handlers.
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition: TString.cxx:2321
unsigned int UInt_t
Definition: RtypesCore.h:42
TMarker * m
Definition: textangle.C:8
#define isin(address, start, length)
char * Form(const char *fmt,...)
void Exit(int code, Bool_t mode=kTRUE)
Exit the application.
int Utime(const char *file, Long_t modtime, Long_t actime)
Set a files modification and access times.
void ResetSignal(ESignals sig, Bool_t reset=kTRUE)
If reset is true reset the signal handler for the specified signal to the default handler...
static const char * StripOffProto(const char *path, const char *proto)
Definition: TSystem.h:324
struct passwd * fPasswords
Definition: TWinNTSystem.h:76
const char * UnixPathName(const char *unixpathname)
Convert a pathname to a unix pathname.
Definition: TSocket.h:68
static void GetWinNTSysInfo(SysInfo_t *sysinfo)
Get system info for Windows NT.
TLine * l
Definition: textangle.C:4
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
TSubString Strip(EStripType s=kTrailing, char c= ' ') const
Return a substring of self stripped at beginning and/or end.
Definition: TString.cxx:1069
void ResetSignals()
Reset signals handlers to previous behaviour.
#define SID_GROUP
Definition: TWinNTSystem.h:46
static void GetWinNTCpuInfo(CpuInfo_t *cpuinfo, Int_t sampleTime)
Get CPU stat for Window.
Bool_t IsNull() const
Definition: TString.h:387
TString fListLibs
Definition: TSystem.h:292
static char * shellStuff
void DispatchSignals(ESignals sig)
Handle and dispatch signals.
void AddAlias(const char *alias)
Add alias to list of aliases.
virtual void FreeDirectory(void *dirp)
Free a directory.
Definition: TSystem.cxx:839
const char * GetLibraries(const char *regexp="", const char *option="", Bool_t isRegexp=kTRUE)
Return a space separated list of loaded shared libraries.
TGraphErrors * gr
Definition: legend1.C:25
#define gVirtualX
Definition: TVirtualX.h:362
const char DriveName(const char *pathname="/")
Return the drive letter in pathname.
#define Printf
Definition: TGeoToOCC.h:18
char * StrDup(const char *str)
Duplicate the string str.
Definition: TString.cxx:2513
void ExitLoop()
Exit from event loop.
virtual int SetSockOpt(int sock, int kind, int val)
Set socket option.
Definition: TSystem.cxx:2326
ULong_t gConsoleWindow
int Exec(const char *shellcmd)
Execute a command.
UserGroup_t * GetGroupInfo(Int_t gid)
Returns all group info in the UserGroup_t structure.
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
RooCmdArg Index(RooCategory &icat)
TString fPasswd
Definition: TSystem.h:154
virtual void SysError(const char *method, const char *msgfmt,...) const
Issue system error message.
Definition: TObject.cxx:932
int SendBuf(int sock, const void *buffer, int length)
Send a buffer headed by a length indicator.
virtual TSignalHandler * RemoveSignalHandler(TSignalHandler *sh)
Remove a signal handler from list of signal handlers.
Definition: TSystem.cxx:546
virtual Int_t GetSize() const
Definition: TCollection.h:95
TFdSet * fReadready
Files that should be checked for write events.
Definition: TSystem.h:269
typedef PULONG
void AddAddress(UInt_t addr)
Add alternative address to list of addresses.
R__EXTERN const char * gProgPath
Definition: TSystem.h:235
void Copy(void *source, void *dest)
static const double x1[5]
TString & Swap(TString &other)
Definition: TString.h:647
#define ClassImp(name)
Definition: Rtypes.h:279
double f(double x)
Float_t fCpuSys
Definition: TSystem.h:205
int AnnounceTcpService(int port, Bool_t reuse, int backlog, int tcpwindowsize=-1)
Announce TCP/IP service.
R__EXTERN TWin32SplashThread * gSplash
double Double_t
Definition: RtypesCore.h:55
#define INVALID_SOCKET
Definition: civetweb.c:280
TFdSet * fReadmask
Definition: TSystem.h:267
char * DynamicPathName(const char *lib, Bool_t quiet=kFALSE)
Find a dynamic library called lib using the system search paths.
Definition: TSystem.cxx:1894
int AnnounceUnixService(int port, int backlog)
Announce unix domain service.
int RecvBuf(int sock, void *buffer, int length)
Receive a buffer headed by a length indicator.
int Chmod(const char *file, UInt_t mode)
Set the file permission bits.
Int_t GetFamily() const
Definition: TInetAddress.h:76
Bool_t fGroupsInitDone
Definition: TWinNTSystem.h:80
int type
Definition: TGX11.cxx:120
R__EXTERN TEnv * gEnv
Definition: TEnv.h:174
virtual const char * ExpandFileName(const char *fname)
Expand a pathname getting rid of special shell characters like ~.
Definition: TSystem.cxx:1055
TString fCpuType
Definition: TSystem.h:164
TNamed()
Definition: TNamed.h:40
__int64 __rdtsc()
unsigned long ULong_t
Definition: RtypesCore.h:51
double func(double *x, double *p)
Definition: stressTF1.cxx:213
int AnnounceUdpService(int port, int backlog)
Announce UDP service.
void TimerThread()
Special Thread to check asynchronous timers.
TFdSet * fSignals
Files with writes waiting.
Definition: TSystem.h:271
void Beep(Int_t freq=-1, Int_t duration=-1, Bool_t setDefault=kFALSE)
Beep for duration milliseconds with a tone of frequency freq.
Definition: TSystem.cxx:328
Bool_t IsSync() const
Definition: TTimer.h:86
__inline BOOL DBL_BSLASH(LPCTSTR psz)
Inline function to check for a double-backslash at the beginning of a string.
int Symlink(const char *from, const char *to)
Create a symlink from file1 to file2.
void Gl_setwidth(int width)
void * OpenDirectory(const char *name)
Open a directory. Returns 0 if directory does not exist.
Definition: TSocket.h:67
EAccessMode
Definition: TSystem.h:54
int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
void Reset()
Definition: TSystem.h:223
static Vc_ALWAYS_INLINE int_v max(const int_v &x, const int_v &y)
Definition: vector.h:440
int mkdir(const char *name, Bool_t recursive=kFALSE)
Make a file system directory.
TInetAddress GetPeerName(int sock)
Get Internet Protocol (IP) address of remote host and port #.
#define name(a, b)
Definition: linkTestLib0.cpp:5
TFileHandler * RemoveFileHandler(TFileHandler *fh)
Remove a file handler from the list of file handlers.
Bool_t ExpandPathName(TString &patbuf)
Expand a pathname getting rid of special shell characaters like ~.$, etc.
Binding & operator=(OUT(*fun)(void))
Int_t fMemTotal
Definition: TSystem.h:191
int pw_gid
Definition: TWinNTSystem.h:53
void Throw(int code)
If an exception context has been set (using the TRY and RETRY macros) jump back to where it was set...
Definition: TException.cxx:27
void FreeDirectory(void *dirp)
Close a WinNT file system directory.
Int_t Select(TList *active, Long_t timeout)
Select on file descriptors. The timeout to is in millisec.
Double_t GetCPUTime()
int SetSockOpt(int sock, int opt, int val)
Set socket option.
TInetAddress GetSockName(int sock)
Get Internet Protocol (IP) address of host and port #.
typedef void((*Func_t)())
Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
TSeqCollection * fTimers
Definition: TSystem.h:286
TInetAddress GetHostByName(const char *server)
Get Internet Protocol (IP) address of host.
Bool_t CountMembers(const char *lpszGroupName)
Bool_t(* ThreadMsgFunc_t)(MSG *)
Definition: TWinNTSystem.h:72
Int_t GetUid(const char *user=0)
Returns the user&#39;s id. If user = 0, returns current user&#39;s id.
virtual void Add(TObject *obj)
Definition: TList.h:81
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
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
ESignals GetSignal() const
virtual void Exit(int code, Bool_t mode=kTRUE)
Exit the application.
Definition: TSystem.cxx:720
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:567
Int_t fMemUsed
Definition: TSystem.h:192
int SetNonBlock(int fd)
Make descriptor fd non-blocking.
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.
Int_t fCpuSpeed
Definition: TSystem.h:166
Double_t GetRealTime()
#define NULL
Definition: Rtypes.h:82
FILE * TempFileName(TString &base, const char *dir=0)
Create a secure temporary file by appending a unique 6 letter string to base.
Long_t fIno
Definition: TSystem.h:137
Long_t LookupSID(const char *lpszAccountName, int what, int &groupIdx, int &memberIdx)
Take the name and look up a SID so that we can get full domain/user information.
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.
virtual Bool_t ReadNotify()
Notify when something can be read from the descriptor associated with this handler.
Bool_t CollectMembers(const char *lpszGroupName, int &groupIdx, int &memberIdx)
TSystem * FindHelper(const char *path, void *dirptr=0)
Create helper TSystem to handle file and directory operations that might be special for remote file a...
Definition: TSystem.cxx:748
virtual void AddFileHandler(TFileHandler *fh)
Add a file handler to the list of system file handlers.
Definition: TSystem.cxx:558
static void ResetErrno()
Static function resetting system error number.
Definition: TSystem.cxx:280
static const TString & GetBinDir()
Get the binary directory in the installation. Static utility function.
Definition: TROOT.cxx:2537
void SetProgname(const char *name)
Set the application name (from command line, argv[0]) and copy it in gProgName.
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.
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition: TSystem.cxx:1191
void Setenv(const char *name, const char *value)
Set environment variable.
Int_t fBeepDuration
Definition: TSystem.h:280
TFdSet * fWriteready
Files with reads waiting.
Definition: TSystem.h:270
Int_t fSwapTotal
Definition: TSystem.h:194
Long_t fDev
Definition: TSystem.h:136
static void GetWinNTMemInfo(MemInfo_t *meminfo)
Get VM stat for Windows NT.
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition: TString.h:582
Abstract base class defining a generic interface to the underlying Operating System.
Definition: TSystem.h:258
const Bool_t kTRUE
Definition: Rtypes.h:91
float * q
Definition: THbookFile.cxx:87
Ordered collection.
float value
Definition: math.cpp:443
TFdSet * fWritemask
Files that should be checked for read events.
Definition: TSystem.h:268
module
Definition: ROOT.py:93
static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int64_t len)
Definition: civetweb.c:1917
Float_t fIdle
Definition: TSystem.h:183
const Int_t n
Definition: legend1.C:16
void StackTrace()
Print a stack trace, if gEnv entry "Root.Stacktrace" is unset or 1, and if the image helper functions...
TString fFile
Definition: TSystem.h:215
TList * GetVolumes(Option_t *opt="") const
Get list of volumes (drives) mounted on the system.
Ssiz_t First(char c) const
Find first occurrence of a character c.
Definition: TString.cxx:466
Long_t fMemResident
Definition: TSystem.h:206
const char * Getenv(const char *name)
Get environment variable.
Bool_t IsAsync() const
Definition: TTimer.h:87
void SetGUIThreadMsgHandler(ThreadMsgFunc_t func)
Set the (static part of) the event handler func for GUI messages.
Int_t RedirectOutput(const char *name, const char *mode="a", RedirectHandle_t *h=0)
Redirect standard output (stdout, stderr) to the specified file.
char * fDirNameBuffer
Definition: TWinNTSystem.h:86
int Rename(const char *from, const char *to)
Rename a file. Returns 0 when successful, -1 in case of failure.
virtual Bool_t HasReadInterest()
True if handler is interested in read events.
char ** gr_mem
Definition: TWinNTSystem.h:65
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:904