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