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