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