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