69#if defined (_MSC_VER) && (_MSC_VER >= 1400)
71#elif defined (_M_IX86)
72 static void __cpuid(
int* cpuid_data,
int info_type)
99 static void __cpuid(
int* cpuid_data,
int) {
100 cpuid_data[0] = 0x00000000;
101 cpuid_data[1] = 0x00000000;
102 cpuid_data[2] = 0x00000000;
103 cpuid_data[3] = 0x00000000;
126 if (
fds_bits->fd_count < FD_SETSIZE-1)
129 ::SysError(
"TFdSet::Set",
"fd_count will exeed FD_SETSIZE");
134 for (i=0; i<
fds_bits->fd_count; i++) {
136 while (i<fds_bits->fd_count-1) {
156 static HANDLE gGlobalEvent;
157 static HANDLE gTimerThreadHandle;
158 typedef NET_API_STATUS (WINAPI *pfn1)(LPVOID);
159 typedef NET_API_STATUS (WINAPI *pfn2)(LPCWSTR, LPCWSTR, DWORD, LPBYTE*);
160 typedef NET_API_STATUS (WINAPI *pfn3)(LPCWSTR, LPCWSTR, DWORD, LPBYTE*,
161 DWORD, LPDWORD, LPDWORD, PDWORD_PTR);
162 typedef NET_API_STATUS (WINAPI *pfn4)(LPCWSTR, DWORD, LPBYTE*, DWORD, LPDWORD,
163 LPDWORD, PDWORD_PTR);
164 static pfn1 p2NetApiBufferFree;
165 static pfn2 p2NetUserGetInfo;
166 static pfn3 p2NetLocalGroupGetMembers;
167 static pfn4 p2NetLocalGroupEnum;
169 static struct signal_map {
175 SIGSEGV, 0,
"segmentation violation",
176 -1 , 0,
"bad argument to system call",
177 -1 , 0,
"write on a pipe with no one to read it",
178 SIGILL, 0,
"illegal instruction",
181 SIGINT, 0,
"interrupt",
182 -1 , 0,
"window size change",
183 -1 , 0,
"alarm clock",
184 -1 , 0,
"death of a child",
185 -1 , 0,
"urgent data arrived on an I/O channel",
186 SIGFPE, 0,
"floating point exception",
187 SIGTERM, 0,
"termination signal",
188 -1 , 0,
"user-defined signal 1",
189 -1 , 0,
"user-defined signal 2"
210 static int WinNTRecv(
int socket,
void *buffer,
int length,
int flag)
212 if (
socket == -1)
return -1;
220 if (flag == MSG_PEEK) {
225 char *buf = (
char *)buffer;
228 if ((nrecv = ::recv(sock, buf+
n,
length-
n, flag)) <= 0) {
232 if (flag == MSG_OOB) {
233 if (::WSAGetLastError() == WSAEWOULDBLOCK) {
235 }
else if (::WSAGetLastError() == WSAEINVAL) {
239 if (::WSAGetLastError() == WSAEWOULDBLOCK) {
242 if (::WSAGetLastError() != WSAEINTR)
243 ::SysError(
"TWinNTSystem::WinNTRecv",
"recv");
244 if (::WSAGetLastError() == EPIPE ||
245 ::WSAGetLastError() == WSAECONNRESET)
264 static int WinNTSend(
int socket,
const void *buffer,
int length,
int flag)
266 if (
socket < 0)
return -1;
276 const char *buf = (
const char *)buffer;
279 if ((nsent = ::send(sock, buf+
n,
length-
n, flag)) <= 0) {
283 if (::WSAGetLastError() == WSAEWOULDBLOCK) {
286 if (::WSAGetLastError() != WSAEINTR)
287 ::SysError(
"TWinNTSystem::WinNTSend",
"send");
288 if (::WSAGetLastError() == EPIPE ||
289 ::WSAGetLastError() == WSAECONNRESET)
309 fd_set* rbits = readready ? (fd_set*)readready->
GetBits() : 0;
310 fd_set* wbits = writeready ? (fd_set*)writeready->
GetBits() : 0;
314 tv.tv_sec = timeout / 1000;
315 tv.tv_usec = (timeout % 1000) * 1000;
317 retcode = ::select(0, rbits, wbits, 0, &tv);
319 retcode = ::select(0, rbits, wbits, 0, 0);
322 if (retcode == SOCKET_ERROR) {
323 int errcode = ::WSAGetLastError();
327 if (errcode == WSAENOTSOCK) {
329 int result = _fstat64( readready->
GetFd(0), &buf );
337 ::WaitForSingleObject(gGlobalEvent, 1);
338 ::ResetEvent(gGlobalEvent);
343 if ( errcode == WSAEINTR) {
347 if (errcode == EBADF) {
362 if (reset || newpath) {
367 }
else if (dynpath ==
"") {
371 if (rdynpath ==
"") {
399 if (signal_map[i].code == sig) {
400 (*signal_map[i].handler)((
ESignals)i);
411 signal_map[sig].handler = handler;
412 if (signal_map[sig].code != -1)
419 static const char *WinNTSigname(
ESignals sig)
421 return signal_map[sig].signame;
427 static BOOL ConsoleSigHandler(DWORD sig)
435 Break(
"TInterruptHandler::Notify",
"keyboard interrupt");
441 case CTRL_BREAK_EVENT:
442 case CTRL_LOGOFF_EVENT:
443 case CTRL_SHUTDOWN_EVENT:
444 case CTRL_CLOSE_EVENT:
446 printf(
"\n *** Break *** keyboard interrupt - ROOT is terminated\n");
452 static CONTEXT *fgXcptContext = 0;
466 LONG WINAPI ExceptionFilter(LPEXCEPTION_POINTERS pXcp)
468 fgXcptContext = pXcp->ContextRecord;
470 return EXCEPTION_CONTINUE_SEARCH;
474#pragma intrinsic(_ReturnAddress)
475#pragma auto_inline(off)
476 DWORD_PTR GetProgramCounter()
481#pragma auto_inline(on)
492 static DWORD WINAPI GUIThreadMessageProcessingLoop(
void *
p)
497 ::PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
502 if (gGlobalEvent) ::SetEvent(gGlobalEvent);
503 erret = ::GetMessage(&msg, NULL, NULL, NULL);
504 if (erret <= 0) endLoop =
kTRUE;
505 if (gGUIThreadMsgFunc)
506 endLoop = (*gGUIThreadMsgFunc)(&msg);
513 erret = ::GetLastError();
514 Error(
"MsgLoop",
"Error in GetMessage");
528 typedef BOOL (__stdcall *SYMINITIALIZEPROC)( HANDLE, LPSTR,
BOOL );
529 typedef BOOL (__stdcall *SYMCLEANUPPROC)( HANDLE );
530 typedef BOOL (__stdcall *STACKWALK64PROC)
531 ( DWORD, HANDLE, HANDLE, LPSTACKFRAME64, LPVOID,
532 PREAD_PROCESS_MEMORY_ROUTINE,PFUNCTION_TABLE_ACCESS_ROUTINE,
533 PGET_MODULE_BASE_ROUTINE, PTRANSLATE_ADDRESS_ROUTINE );
534 typedef LPVOID (__stdcall *SYMFUNCTIONTABLEACCESS64PROC)( HANDLE, DWORD64 );
535 typedef DWORD (__stdcall *SYMGETMODULEBASE64PROC)( HANDLE, DWORD64 );
536 typedef BOOL (__stdcall *SYMGETMODULEINFO64PROC)(HANDLE, DWORD64, PIMAGEHLP_MODULE64);
537 typedef BOOL (__stdcall *SYMGETSYMFROMADDR64PROC)( HANDLE, DWORD64, PDWORD64, PIMAGEHLP_SYMBOL64);
538 typedef BOOL (__stdcall *SYMGETLINEFROMADDR64PROC)(HANDLE, DWORD64, PDWORD, PIMAGEHLP_LINE64);
539 typedef DWORD (__stdcall *UNDECORATESYMBOLNAMEPROC)(PCSTR, PSTR, DWORD, DWORD);
542 static SYMINITIALIZEPROC _SymInitialize = 0;
543 static SYMCLEANUPPROC _SymCleanup = 0;
544 static STACKWALK64PROC _StackWalk64 = 0;
545 static SYMFUNCTIONTABLEACCESS64PROC _SymFunctionTableAccess64 = 0;
546 static SYMGETMODULEBASE64PROC _SymGetModuleBase64 = 0;
547 static SYMGETMODULEINFO64PROC _SymGetModuleInfo64 = 0;
548 static SYMGETSYMFROMADDR64PROC _SymGetSymFromAddr64 = 0;
549 static SYMGETLINEFROMADDR64PROC _SymGetLineFromAddr64 = 0;
550 static UNDECORATESYMBOLNAMEPROC _UnDecorateSymbolName = 0;
552 BOOL InitImagehlpFunctions()
560 HMODULE hModImagehlp = LoadLibrary(
"IMAGEHLP.DLL" );
564 _SymInitialize = (SYMINITIALIZEPROC) GetProcAddress( hModImagehlp,
"SymInitialize" );
568 _SymCleanup = (SYMCLEANUPPROC) GetProcAddress( hModImagehlp,
"SymCleanup" );
572 _StackWalk64 = (STACKWALK64PROC) GetProcAddress( hModImagehlp,
"StackWalk64" );
576 _SymFunctionTableAccess64 = (SYMFUNCTIONTABLEACCESS64PROC) GetProcAddress(hModImagehlp,
"SymFunctionTableAccess64" );
577 if (!_SymFunctionTableAccess64)
580 _SymGetModuleBase64=(SYMGETMODULEBASE64PROC)GetProcAddress(hModImagehlp,
"SymGetModuleBase64");
581 if (!_SymGetModuleBase64)
584 _SymGetModuleInfo64=(SYMGETMODULEINFO64PROC)GetProcAddress(hModImagehlp,
"SymGetModuleInfo64");
585 if (!_SymGetModuleInfo64)
588 _SymGetSymFromAddr64=(SYMGETSYMFROMADDR64PROC)GetProcAddress(hModImagehlp,
"SymGetSymFromAddr64");
589 if (!_SymGetSymFromAddr64)
592 _SymGetLineFromAddr64=(SYMGETLINEFROMADDR64PROC)GetProcAddress(hModImagehlp,
"SymGetLineFromAddr64");
593 if (!_SymGetLineFromAddr64)
596 _UnDecorateSymbolName=(UNDECORATESYMBOLNAMEPROC)GetProcAddress(hModImagehlp,
"UnDecorateSymbolName");
597 if (!_UnDecorateSymbolName)
600 if (!_SymInitialize(GetCurrentProcess(), 0,
TRUE ))
616 std::string GetModuleName(DWORD64 address)
620 std::ostringstream
out;
621 HANDLE process = ::GetCurrentProcess();
623 DWORD lineDisplacement = 0;
624 IMAGEHLP_LINE64
line;
627 if(_SymGetLineFromAddr64(process, address, &lineDisplacement, &
line)) {
628 out <<
line.FileName <<
"(" <<
line.LineNumber <<
"): ";
630 IMAGEHLP_MODULE64 module;
631 ::ZeroMemory(&module,
sizeof(module));
632 module.SizeOfStruct =
sizeof(module);
633 if(_SymGetModuleInfo64(process, address, &module)) {
634 out << module.ModuleName <<
"!";
636 out <<
"0x" << std::hex << address << std::dec <<
" ";
643 std::string GetFunctionName(DWORD64 address)
647 DWORD64 symbolDisplacement = 0;
648 HANDLE process = ::GetCurrentProcess();
650 const unsigned int SYMBOL_BUFFER_SIZE = 8192;
651 char symbolBuffer[SYMBOL_BUFFER_SIZE];
652 PIMAGEHLP_SYMBOL64 symbol =
reinterpret_cast<PIMAGEHLP_SYMBOL64
>(symbolBuffer);
653 ::ZeroMemory(symbol, SYMBOL_BUFFER_SIZE);
654 symbol->SizeOfStruct = SYMBOL_BUFFER_SIZE;
655 symbol->MaxNameLength = SYMBOL_BUFFER_SIZE -
sizeof(IMAGEHLP_SYMBOL64);
657 if(_SymGetSymFromAddr64(process, address, &symbolDisplacement, symbol)) {
659 const unsigned int NAME_SIZE = 8192;
660 char name[NAME_SIZE];
661 _UnDecorateSymbolName(
666 UNDNAME_NO_THISTYPE |
667 UNDNAME_NO_SPECIAL_SYMS |
668 UNDNAME_NO_MEMBER_TYPE |
669 UNDNAME_NO_MS_KEYWORDS |
670 UNDNAME_NO_ACCESS_SPECIFIERS
691 const char *extLnk =
".lnk";
695 if (strfilename.EndsWith(extLnk))
704 static BOOL ResolveShortCut(LPCSTR pszShortcutFile,
char *pszPath,
int maxbuf)
708 char szGotPath[MAX_PATH];
715 typedef HRESULT (__stdcall *COINITIALIZEPROC)( LPVOID );
716 static COINITIALIZEPROC _CoInitialize = 0;
717 typedef void (__stdcall *COUNINITIALIZEPROC)(
void );
718 static COUNINITIALIZEPROC _CoUninitialize = 0;
719 typedef HRESULT (__stdcall *COCREATEINSTANCEPROC)( REFCLSID, LPUNKNOWN,
720 DWORD, REFIID, LPVOID );
721 static COCREATEINSTANCEPROC _CoCreateInstance = 0;
723 HMODULE hModImagehlp = LoadLibrary(
"ole32.dll" );
727 _CoInitialize = (COINITIALIZEPROC) GetProcAddress( hModImagehlp,
"CoInitialize" );
730 _CoUninitialize = (COUNINITIALIZEPROC) GetProcAddress( hModImagehlp,
"CoUninitialize");
731 if (!_CoUninitialize)
733 _CoCreateInstance = (COCREATEINSTANCEPROC) GetProcAddress( hModImagehlp,
"CoCreateInstance" );
734 if (!_CoCreateInstance)
739 hres = _CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
740 IID_IShellLink, (
void **) &psl);
741 if (SUCCEEDED(hres)) {
744 hres = psl->QueryInterface(IID_IPersistFile, (
void **) &ppf);
745 if (SUCCEEDED(hres)) {
747 MultiByteToWideChar(CP_ACP, 0, pszShortcutFile, -1, wsz, MAX_PATH);
749 hres = ppf->Load(wsz, STGM_READ);
750 if (SUCCEEDED(hres)) {
751 hres = psl->Resolve(HWND_DESKTOP, SLR_ANY_MATCH | SLR_NO_UI | SLR_UPDATE);
752 if (SUCCEEDED(hres)) {
753 strlcpy(szGotPath, pszShortcutFile,MAX_PATH);
754 hres = psl->GetPath(szGotPath, MAX_PATH, (WIN32_FIND_DATA *)&wfd,
755 SLGP_UNCPRIORITY | SLGP_RAWPATH);
756 strlcpy(pszPath,szGotPath, maxbuf);
757 if (maxbuf) pszPath[maxbuf-1] = 0;
766 return SUCCEEDED(hres);
772 if (strcmp(sys->TWinNTSystem::BaseName(buf),
"root.exe"))
775 if (!::RegOpenKeyEx(HKEY_CURRENT_USER,
"Software", 0, KEY_READ, ®CUS) == ERROR_SUCCESS)
778 if (!::RegOpenKeyEx(regCUS,
"Classes", 0, KEY_READ, ®CUSC) == ERROR_SUCCESS) {
779 ::RegCloseKey(regCUS);
784 bool regROOTwrite =
false;
788 if (::RegOpenKeyEx(regCUSC,
"ROOTDEV.ROOT", 0, KEY_READ, ®ROOT) != ERROR_SUCCESS) {
789 ::RegCloseKey(regCUSC);
790 if (::RegOpenKeyEx(regCUS,
"Classes", 0, KEY_READ | KEY_WRITE, ®CUSC) == ERROR_SUCCESS &&
791 ::RegCreateKeyEx(regCUSC,
"ROOTDEV.ROOT", 0, NULL, 0, KEY_READ | KEY_WRITE,
792 NULL, ®ROOT, NULL) == ERROR_SUCCESS) {
797 if (::RegOpenKeyEx(regROOT,
"DefaultIcon", 0, KEY_READ, ®ROOTIcon) == ERROR_SUCCESS) {
798 char bufIconLoc[1024];
800 DWORD dwSize =
sizeof(bufIconLoc);
802 if (::RegQueryValueEx(regROOTIcon, NULL, NULL, &dwType, (BYTE*)bufIconLoc, &dwSize) == ERROR_SUCCESS)
803 regROOTwrite = (iconloc != bufIconLoc);
806 ::RegCloseKey(regROOTIcon);
811 ::RegCloseKey(regCUSC);
812 ::RegCloseKey(regROOT);
813 if (::RegOpenKeyEx(regCUS,
"Classes", 0, KEY_READ | KEY_WRITE, ®CUSC) != ERROR_SUCCESS) {
815 regROOTwrite =
false;
817 if (::RegOpenKeyEx(regCUSC,
"ROOTDEV.ROOT", 0, KEY_WRITE, ®ROOT) != ERROR_SUCCESS) {
819 regROOTwrite =
false;
820 ::RegCloseKey(regCUSC);
827 TString fileopen =
"fileopen.C";
828 TString rootmacrodir =
"macros";
838 ::RegCloseKey(regROOT);
839 ::RegCloseKey(regCUSC);
840 ::RegCloseKey(regCUS);
844 static const char apptitle[] =
"ROOT data file";
845 ::RegSetValueEx(regROOT, NULL, 0, REG_SZ, (BYTE*)apptitle,
sizeof(apptitle));
846 DWORD editflags = 0x00010000;
847 ::RegSetValueEx(regROOT,
"EditFlags", 0, REG_DWORD, (BYTE*)&editflags,
sizeof(editflags));
850 if (::RegCreateKeyEx(regROOT,
"DefaultIcon", 0, NULL, 0, KEY_READ | KEY_WRITE,
851 NULL, ®ROOTIcon, NULL) == ERROR_SUCCESS) {
854 ::RegSetValueEx(regROOTIcon, NULL, 0, REG_SZ, (BYTE*)iconloc.Data(), iconloc.Length() + 1);
855 ::RegCloseKey(regROOTIcon);
860 if (::RegCreateKeyEx(regROOT,
"shell", 0, NULL, 0, KEY_READ | KEY_WRITE,
861 NULL, ®ROOTshell, NULL) == ERROR_SUCCESS) {
863 if (::RegCreateKeyEx(regROOTshell,
"open", 0, NULL, 0, KEY_READ | KEY_WRITE,
864 NULL, ®ShellOpen, NULL) == ERROR_SUCCESS) {
865 HKEY regShellOpenCmd;
866 if (::RegCreateKeyEx(regShellOpen,
"command", 0, NULL, 0, KEY_READ | KEY_WRITE,
867 NULL, ®ShellOpenCmd, NULL) == ERROR_SUCCESS) {
869 cmd +=
" -l \"%1\" \"";
872 ::RegSetValueEx(regShellOpenCmd, NULL, 0, REG_SZ, (BYTE*)cmd.Data(), cmd.Length() + 1);
873 ::RegCloseKey(regShellOpenCmd);
875 ::RegCloseKey(regShellOpen);
877 ::RegCloseKey(regROOTshell);
879 ::RegCloseKey(regROOT);
881 if (::RegCreateKeyEx(regCUSC,
".root", 0, NULL, 0, KEY_READ | KEY_WRITE,
882 NULL, ®ROOT, NULL) == ERROR_SUCCESS) {
883 static const char appname[] =
"ROOTDEV.ROOT";
884 ::RegSetValueEx(regROOT, NULL, 0, REG_SZ, (BYTE*)appname,
sizeof(appname));
886 ::RegCloseKey(regCUSC);
887 ::RegCloseKey(regCUS);
890 ::SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
898 static bool once =
true;
901 if (!once ||
gROOT->IsBatch())
return false;
902 TString cmdline(::GetCommandLine());
903 Int_t i = 0, from = 0;
904 while (cmdline.Tokenize(arg, from,
" ")) {
906 if (i == 0 && ((arg !=
"root") && (arg !=
"rootn") &&
907 (arg !=
"root.exe") && (arg !=
"rootn.exe")))
return false;
908 else if ((arg ==
"-l") || (arg ==
"-b"))
return false;
920 static void SetConsoleWindowName()
922 char pszNewWindowTitle[1024];
923 char pszOldWindowTitle[1024];
925 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
927 if (!::GetConsoleTitle(pszOldWindowTitle, 1024))
930 wsprintf(pszNewWindowTitle,
"%d/%d", ::GetTickCount(), ::GetCurrentProcessId());
932 if (!::SetConsoleTitle(pszNewWindowTitle))
942 ::SetConsoleTitle(
"ROOT session");
944 hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
947 ::SetConsoleMode(hStdout, ENABLE_PROCESSED_OUTPUT |
948 ENABLE_WRAP_AT_EOL_OUTPUT);
949 if (!::GetConsoleScreenBufferInfo(hStdout, &csbiInfo))
992 if (initwinsock = ::WSAStartup(MAKEWORD(2, 0), &WSAData)) {
993 Error(
"TWinNTSystem()",
"Starting sockets failed");
1004 char *buf =
new char[MAX_MODULE_NAME32 + 1];
1010 HMODULE hModCore = ::GetModuleHandle(
"libCore.dll");
1012 ::GetModuleFileName(hModCore, buf, MAX_MODULE_NAME32 + 1);
1013 char *pLibName = strstr(buf,
"libCore.dll");
1016 while (--pLibName >= buf && *pLibName !=
'\\' && *pLibName !=
'/');
1019 check_path +=
"\\etc";
1021 while (buf[0] && GetFileAttributes(check_path.
Data()) == INVALID_FILE_ATTRIBUTES) {
1022 while (--pLibName >= buf && *pLibName !=
'\\' && *pLibName !=
'/');
1025 check_path +=
"\\etc";
1040 UpdateRegistry(
this, buf);
1051 typedef UINT (WINAPI* LPTIMEENDPERIOD)( UINT uPeriod );
1052 HINSTANCE hInstWinMM = LoadLibrary(
"winmm.dll" );
1054 LPTIMEENDPERIOD pTimeEndPeriod = (LPTIMEENDPERIOD)GetProcAddress( hInstWinMM,
"timeEndPeriod" );
1055 if( NULL != pTimeEndPeriod )
1057 FreeLibrary(hInstWinMM);
1063 ::ResetEvent(gGlobalEvent);
1064 ::CloseHandle(gGlobalEvent);
1067 if (gTimerThreadHandle) {
1068 ::TerminateThread(gTimerThreadHandle, 0);
1069 ::CloseHandle(gTimerThreadHandle);
1102 ::SetUnhandledExceptionFilter(ExceptionFilter);
1110 typedef UINT (WINAPI* LPTIMEBEGINPERIOD)( UINT uPeriod );
1111 HINSTANCE hInstWinMM = LoadLibrary(
"winmm.dll" );
1113 LPTIMEBEGINPERIOD pTimeBeginPeriod = (LPTIMEBEGINPERIOD)GetProcAddress( hInstWinMM,
"timeBeginPeriod" );
1114 if( NULL != pTimeBeginPeriod )
1115 pTimeBeginPeriod(1);
1116 FreeLibrary(hInstWinMM);
1118 gTimerThreadHandle = ::CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)
ThreadStub,
1121 gGlobalEvent = ::CreateEvent(NULL,
TRUE,
FALSE, NULL);
1124 char *buf =
new char[MAX_MODULE_NAME32 + 1];
1125 HMODULE hModCore = ::GetModuleHandle(
"libCore.dll");
1127 ::GetModuleFileName(hModCore, buf, MAX_MODULE_NAME32 + 1);
1128 char *pLibName = strstr(buf,
"libCore.dll");
1135 std::this_thread::sleep_for(std::chrono::duration<double, std::nano>(10));
1136 SetConsoleWindowName();
1159 const char *symbol=
name;
1162 while ( (*symbol ==
' ' || *symbol ==
'\t') && *symbol) symbol++;
1165 if (isalpha(symbol[idx]) && symbol[idx+1] ==
':') idx = 2;
1166 if ( (symbol[idx] ==
'/' || symbol[idx] ==
'\\') && symbol[idx+1] ==
'\0') {
1171 Error(
"BaseName",
"name = 0");
1175 char *bslash = (
char *)strrchr(&symbol[idx],
'\\');
1176 char *rslash = (
char *)strrchr(&symbol[idx],
'/');
1177 if (cp = (std::max)(rslash, bslash)) {
1182 return &symbol[idx];
1184 Error(
"BaseName",
"name = 0");
1195 char *dot =
nullptr;
1197 char *fullname =
nullptr;
1200 size_t namelen =
name ? strlen(
name) : 0;
1201 if (
name && namelen > 0) {
1203 fullname =
new char[namelen+5];
1204 strlcpy(fullname,
name,namelen+5);
1205 if ( !strrchr(fullname,
'.') )
1206 strlcat(fullname,
".exe",namelen+5);
1209 dot = strrchr(progname,
'.');
1210 idot = dot ? (size_t)(dot - progname) : strlen(progname);
1212 char *which =
nullptr;
1215 which =
StrDup(fullname);
1226 dirname.
Form(
"%c:%s", driveletter,
d.Data());
1241 progname[idot] =
'\0';
1243 if (which)
delete [] which;
1247 if (::NeedSplash()) {
1260 if (err < 0 || err >= sys_nerr) {
1262 error_msg.
Form(
"errno out of range %d", err);
1265 return sys_errlist[err];
1275 auto res = BCryptGenRandom((BCRYPT_ALG_HANDLE) NULL, (PUCHAR) buf, (ULONG)
len, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
1276 return !res ?
len : -1;
1289 DWORD il =
sizeof(hn);
1290 ::GetComputerName(hn, &il);
1306 if (freq < 37) freq = 440;
1307 if (duration < 0) duration = 100;
1316 gGUIThreadMsgFunc = func;
1339 int fd =
h->GetFd();
1342 if (
h->HasReadInterest()) {
1345 if (
h->HasWriteInterest()) {
1357 if (!
h)
return nullptr;
1377 set_console =
kTRUE;
1390 ::SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleSigHandler,
TRUE);
1401 if (!
h)
return nullptr;
1416 ::SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleSigHandler,
FALSE);
1460 HANDLE snapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD,::GetCurrentProcessId());
1465 if (!InitImagehlpFunctions()) {
1466 std::cerr <<
"No stack trace: cannot find (functions in) dbghelp.dll!" << std::endl;
1471 SYSTEM_INFO sysInfo;
1472 ::GetSystemInfo(&sysInfo);
1473 DWORD machineType = IMAGE_FILE_MACHINE_I386;
1474 switch (sysInfo.wProcessorArchitecture) {
1475 case PROCESSOR_ARCHITECTURE_AMD64:
1476 machineType = IMAGE_FILE_MACHINE_AMD64;
1478 case PROCESSOR_ARCHITECTURE_IA64:
1479 machineType = IMAGE_FILE_MACHINE_IA64;
1483 DWORD currentThreadID = ::GetCurrentThreadId();
1484 DWORD currentProcessID = ::GetCurrentProcessId();
1488 THREADENTRY32 threadentry;
1489 threadentry.dwSize =
sizeof(THREADENTRY32);
1490 if (!::Thread32First(snapshot, &threadentry))
return;
1492 std::cerr << std::endl <<
"==========================================" << std::endl;
1493 std::cerr <<
"=============== STACKTRACE ===============" << std::endl;
1494 std::cerr <<
"==========================================" << std::endl << std::endl;
1497 if (threadentry.th32OwnerProcessID != currentProcessID)
1499 HANDLE thread = ::OpenThread(THREAD_GET_CONTEXT|THREAD_SUSPEND_RESUME|THREAD_QUERY_INFORMATION,
1500 FALSE, threadentry.th32ThreadID);
1502 memset(&context, 0,
sizeof(CONTEXT));
1504 if (threadentry.th32ThreadID != currentThreadID) {
1505 ::SuspendThread(thread);
1506 context.ContextFlags = CONTEXT_ALL;
1507 ::GetThreadContext(thread, &context);
1508 ::ResumeThread(thread);
1510 if (fgXcptContext) {
1511 context = *fgXcptContext;
1513 typedef void (WINAPI *RTLCCTXT)(PCONTEXT);
1514 RTLCCTXT p2RtlCCtxt = (RTLCCTXT) ::GetProcAddress(
1515 GetModuleHandle(
"kernel32.dll"),
"RtlCaptureContext");
1517 context.ContextFlags = CONTEXT_ALL;
1518 p2RtlCCtxt(&context);
1524 ::ZeroMemory(&frame,
sizeof(frame));
1526 frame.AddrPC.Mode = AddrModeFlat;
1527 frame.AddrFrame.Mode = AddrModeFlat;
1528 frame.AddrStack.Mode = AddrModeFlat;
1530 frame.AddrPC.Offset = context.Eip;
1531 frame.AddrFrame.Offset = context.Ebp;
1532 frame.AddrStack.Offset = context.Esp;
1533#elif defined(_M_X64)
1534 frame.AddrPC.Offset = context.Rip;
1535 frame.AddrFrame.Offset = context.Rsp;
1536 frame.AddrStack.Offset = context.Rsp;
1537#elif defined(_M_IA64)
1538 frame.AddrPC.Offset = context.StIIP;
1539 frame.AddrFrame.Offset = context.IntSp;
1540 frame.AddrStack.Offset = context.IntSp;
1541 frame.AddrBStore.Offset= context.RsBSP;
1543 std::cerr <<
"Stack traces not supported on your architecture yet." << std::endl;
1548 while (_StackWalk64(machineType, (HANDLE)::GetCurrentProcess(), thread, (LPSTACKFRAME64)&frame,
1549 (LPVOID)&context, (PREAD_PROCESS_MEMORY_ROUTINE)NULL, (PFUNCTION_TABLE_ACCESS_ROUTINE)_SymFunctionTableAccess64,
1550 (PGET_MODULE_BASE_ROUTINE)_SymGetModuleBase64, NULL)) {
1552 std::cerr << std::endl <<
"================ Thread " << iThread++ <<
" ================" << std::endl;
1553 if (!bFirst || threadentry.th32ThreadID != currentThreadID) {
1554 const std::string moduleName = GetModuleName(frame.AddrPC.Offset);
1555 const std::string functionName = GetFunctionName(frame.AddrPC.Offset);
1556 std::cerr <<
" " << moduleName << functionName << std::endl;
1560 ::CloseHandle(thread);
1561 }
while (::Thread32Next(snapshot, &threadentry));
1563 std::cerr << std::endl <<
"==========================================" << std::endl;
1564 std::cerr <<
"============= END STACKTRACE =============" << std::endl;
1565 std::cerr <<
"==========================================" << std::endl << std::endl;
1566 ::CloseHandle(snapshot);
1567 _SymCleanup(GetCurrentProcess());
1576 UInt_t oldmask = _statusfp( );
1602 UInt_t cm = ::_statusfp();
1604 ::_controlfp(cm , _MCW_EM);
1623 if (pendingOnly && gGlobalEvent) ::SetEvent(gGlobalEvent);
1625 Bool_t pollOnce = pendingOnly;
1629 if (
gROOT->GetApplication()) {
1645 ::WaitForSingleObject(gGlobalEvent, 1);
1646 ::ResetEvent(gGlobalEvent);
1672 if (pendingOnly && !pollOnce)
1711 if (!pendingOnly && gGlobalEvent) {
1712 ::WaitForSingleObject(gGlobalEvent, 1);
1713 ::ResetEvent(gGlobalEvent);
1732 rc = WinNTSelect(&t, 0, 0);
1733 if (rc < 0 && rc != -2) {
1734 ::SysError(
"DispatchOneEvent",
"select: read error on %d\n", fd);
1746 rc = WinNTSelect(0, &t, 0);
1747 if (rc < 0 && rc != -2) {
1748 ::SysError(
"DispatchOneEvent",
"select: write error on %d\n", fd);
1810 if (sync == sh->
IsSync()) {
1812 if ((
fSignals->
IsSet(sig) && sigdone == -1) || sigdone == sig) {
1813 if (sigdone == -1) {
1823 if (sigdone != -1)
return kTRUE;
1845 (fddone == fd && read)) {
1855 (fddone == fd && !read)) {
1865 if (fddone != -1)
return kTRUE;
1882 if (dirname.
Length() == 0) {
1899 if (res)
return res;
1919 const char *
proto = (strstr(
name,
"file:///")) ?
"file://" :
"file:";
1922 if (!
name)
return 0;
1926 if (!
name)
return 0;
1949 helper->FreeDirectory(dirp);
1953 ::FindClose(tsfd->fSearchFile);
1965 return helper->GetDirEntry(dirp);
1968 if (tsfd->fFirstFile) {
1973 return (
const char *)tsfd->fFindFileData.cFileName;
1975 if (::FindNextFile(tsfd->fSearchFile, &tsfd->fFindFileData)) {
1976 return (
const char *)tsfd->fFindFileData.cFileName;
2000 return (psz[0] == TEXT(
'\\') && psz[1] == TEXT(
'\\'));
2020#pragma data_seg(".text", "CODE")
2035 if (!IsDBCSLeadByte(*pPath)) {
2040 if ((*pPath == TEXT(
'\\')) && (*(pPath + 1) == 0))
2046 int cBackslashes = 0;
2047 for (
p = pPath + 2; *
p;
p = CharNext(
p)) {
2048 if (*
p == TEXT(
'\\') && (++cBackslashes > 1))
2068 const char *
proto = (strstr(fdir,
"file:///")) ?
"file://" :
"file:";
2071 char *dir =
new char[MAX_PATH];
2072 if (IsShortcut(sdir)) {
2073 if (!ResolveShortCut(sdir, dir, MAX_PATH))
2074 strlcpy(dir, sdir,MAX_PATH);
2077 strlcpy(dir, sdir,MAX_PATH);
2079 size_t nche = strlen(dir)+3;
2080 char *entry =
new char[nche];
2081 struct _stati64 finfo;
2084 strlcpy(entry, dir,nche);
2085 if ((entry[strlen(dir)-1] ==
'/') || (entry[strlen(dir)-1] ==
'\\' )) {
2086 entry[strlen(dir)-1] =
'\0';
2089 strlcat(entry,
"\\",nche);
2091 if (_stati64(entry, &finfo) < 0) {
2097 strlcpy(entry, dir,nche);
2098 if ((entry[strlen(dir)-1] ==
'/') || (entry[strlen(dir)-1] ==
'\\' )) {
2100 entry[strlen(dir)-1] =
'\0';
2102 if (_stati64(entry, &finfo) < 0) {
2109 if (finfo.st_mode & S_IFDIR) {
2110 strlcpy(entry, dir,nche);
2111 if (!(entry[strlen(dir)-1] ==
'/' || entry[strlen(dir)-1] ==
'\\' )) {
2112 strlcat(entry,
"\\",nche);
2114 if (entry[strlen(dir)-1] ==
' ')
2115 entry[strlen(dir)-1] =
'\0';
2116 strlcat(entry,
"*",nche);
2185 char *wdpath =
nullptr;
2186 char drive = driveletter ? toupper( driveletter ) -
'A' + 1 : 0;
2192 if (!(wdpath = ::_getdcwd( (
int)drive, wdpath,
kMAXPATHLEN))) {
2194 Warning(
"WorkingDirectory",
"getcwd() failed");
2218 return std::string(mydir);
2226 const char *
h =
nullptr;
2227 if (!(
h = ::getenv(
"home")))
h = ::getenv(
"HOME");
2234 h = ::getenv(
"HOMESHARE");
2235 if (!
h)
h = ::getenv(
"HOMEDRIVE");
2238 h = ::getenv(
"HOMEPATH");
2243 h = ::getenv(
"USERPROFILE");
2248 if (mydir[1] ==
':')
2249 mydir[0] = toupper(mydir[0]);
2265 if (!dir) dir =
"c:\\";
2283 char tmpName[MAX_PATH];
2285 auto res = ::GetTempFileName(dir ? dir :
TempDirectory(), base.
Data(), 0, tmpName);
2287 ::SysError(
"TempFileName",
"Fail to generate temporary file name");
2292 if (suffix && *suffix) {
2296 ::SysError(
"TempFileName",
"Temporary file %s already exists", base.
Data());
2303 ::SysError(
"TempFileName",
"Fail to rename temporary file to %s", base.
Data());
2309 FILE *fp = fopen(base.
Data(),
"w+");
2311 if (!fp)
::SysError(
"TempFileName",
"error opening %s", base.
Data());
2329 if (!opt || !opt[0]) {
2334 UINT nOldErrorMode = ::SetErrorMode(SEM_FAILCRITICALERRORS);
2338 curdrive = _getdrive();
2339 if (strstr(opt,
"cur")) {
2341 sDrive.
Form(
"%c:", (curdrive +
'A' - 1));
2342 sType.
Form(
"Unknown Drive (%s)", sDrive.
Data());
2343 ::GetVolumeInformation(
Form(
"%s\\", sDrive.
Data()), NULL, 0, NULL, NULL,
2344 NULL, (LPSTR)szFs, 32);
2345 type = ::GetDriveType(sDrive.
Data());
2348 case DRIVE_NO_ROOT_DIR:
2350 case DRIVE_REMOVABLE:
2351 sType.
Form(
"Removable Disk (%s)", sDrive.
Data());
2354 sType.
Form(
"Local Disk (%s)", sDrive.
Data());
2357 sType.
Form(
"Network Drive (%s) (%s)", szFs, sDrive.
Data());
2360 sType.
Form(
"CD/DVD Drive (%s)", sDrive.
Data());
2363 sType.
Form(
"RAM Disk (%s)", sDrive.
Data());
2368 else if (strstr(opt,
"all")) {
2371 if (::GetLogicalDriveStrings(511, szTemp)) {
2372 TCHAR szDrive[3] = TEXT(
" :");
2378 sDrive.
Form(
"%s", szDrive);
2380 if ((sDrive ==
"A:") || (sDrive ==
"B:")) {
2384 sType.
Form(
"Unknown Drive (%s)", sDrive.
Data());
2385 ::GetVolumeInformation(
Form(
"%s\\", sDrive.
Data()), NULL, 0, NULL,
2386 NULL, NULL, (LPSTR)szFs, 32);
2387 type = ::GetDriveType(sDrive.
Data());
2390 case DRIVE_NO_ROOT_DIR:
2392 case DRIVE_REMOVABLE:
2393 sType.
Form(
"Removable Disk (%s)", sDrive.
Data());
2396 sType.
Form(
"Local Disk (%s)", sDrive.
Data());
2399 sType.
Form(
"Network Drive (%s) (%s)", szFs, sDrive.
Data());
2402 sType.
Form(
"CD/DVD Drive (%s)", sDrive.
Data());
2405 sType.
Form(
"RAM Disk (%s)", sDrive.
Data());
2415 ::SetErrorMode(nOldErrorMode);
2438 if (strchr(pathname,
'/') || strchr(pathname,
'\\')) {
2439 const char *rslash = strrchr(pathname,
'/');
2440 const char *bslash = strrchr(pathname,
'\\');
2441 const char *
r = std::max(rslash, bslash);
2442 const char *ptr = pathname;
2452 int len =
r - pathname;
2477 if (!pathname)
return 0;
2478 if (!pathname[0])
return 0;
2484 while(*lpchar ==
' ') lpchar++;
2486 if (isalpha((
int)*lpchar) && *(lpchar+1) ==
':') {
2490 if ( (*lpchar ==
'\\' || *lpchar ==
'/' ) &&
2491 (*(lpchar+1) ==
'\\' || *(lpchar+1) ==
'/') )
return 0;
2504 if (strchr(dir,
':')) idx = 2;
2505 return (dir[idx] ==
'/' || dir[idx] ==
'\\');
2538 const int kBufSize = 1024;
2539 TTHREAD_TLS_ARRAY(
char, kBufSize, temp);
2541 strlcpy(temp,
name, kBufSize);
2542 char *currentChar = temp;
2545 while (*currentChar !=
'\0') {
2546 if (*currentChar ==
'\\') *currentChar =
'/';
2564 UINT nOldErrorMode = ::SetErrorMode(SEM_FAILCRITICALERRORS);
2568 const char *
proto = (strstr(path,
"file:///")) ?
"file://" :
"file:";
2571 ::SetErrorMode(nOldErrorMode);
2576 ::SetErrorMode(nOldErrorMode);
2599 if (dir && dir[0]) {
2601 char last = dir[strlen(dir) - 1];
2602 if (last !=
'/' && last !=
'\\') {
2606 name.ReplaceAll(
"/",
"\\");
2623 if (!ret)
return -1;
2632 int ret = ::rename(
f, t);
2649 struct _stati64 sbuf;
2652 const char *
proto = (strstr(path,
"file:///")) ?
"file://" :
"file:";
2654 size_t l = strlen(newpath);
2656 if (newpath[--
l] !=
'\\' || newpath[--
l] !=
'/') {
2662 if (newpath && ::_stati64(newpath, &sbuf) >= 0) {
2664 buf.
fDev = sbuf.st_dev;
2665 buf.
fIno = sbuf.st_ino;
2666 buf.
fMode = sbuf.st_mode;
2667 buf.
fUid = sbuf.st_uid;
2668 buf.
fGid = sbuf.st_gid;
2669 buf.
fSize = sbuf.st_size;
2670 buf.
fMtime = sbuf.st_mtime;
2671 buf.
fIsLink = IsShortcut(newpath);
2673 char *lpath =
new char[MAX_PATH];
2674 if (IsShortcut(newpath)) {
2675 struct _stati64 sbuf2;
2676 if (ResolveShortCut(newpath, lpath, MAX_PATH)) {
2677 if (::_stati64(lpath, &sbuf2) >= 0) {
2678 buf.
fMode = sbuf2.st_mode;
2704 LPCTSTR lpRootPathName = path;
2707 LPTSTR lpVolumeNameBuffer = 0;
2708 DWORD nVolumeNameSize = 0;
2710 DWORD volumeSerialNumber;
2711 DWORD maximumComponentLength;
2714 DWORD fileSystemFlags;
2717 char fileSystemNameBuffer[512];
2718 DWORD nFileSystemNameSize =
sizeof(fileSystemNameBuffer);
2721 UINT nOldErrorMode = ::SetErrorMode(SEM_FAILCRITICALERRORS);
2722 if (!::GetVolumeInformation(lpRootPathName,
2723 lpVolumeNameBuffer, nVolumeNameSize,
2724 &volumeSerialNumber,
2725 &maximumComponentLength,
2727 fileSystemNameBuffer, nFileSystemNameSize)) {
2729 ::SetErrorMode(nOldErrorMode);
2733 const char *fsNames[] = {
"FAT",
"NTFS" };
2735 for (i = 0; i < 2; i++) {
2736 if (!strncmp(fileSystemNameBuffer, fsNames[i], nFileSystemNameSize))
2741 DWORD sectorsPerCluster;
2742 DWORD bytesPerSector;
2743 DWORD numberOfFreeClusters;
2744 DWORD totalNumberOfClusters;
2746 if (!::GetDiskFreeSpace(lpRootPathName,
2749 &numberOfFreeClusters,
2750 &totalNumberOfClusters)) {
2752 ::SetErrorMode(nOldErrorMode);
2756 ::SetErrorMode(nOldErrorMode);
2758 *bsize = sectorsPerCluster * bytesPerSector;
2759 *blocks = totalNumberOfClusters;
2760 *bfree = numberOfFreeClusters;
2770 struct _stati64 finfo;
2775 char linkname[1024];
2776 LPTSTR lpszFilePart;
2777 TCHAR szPath[MAX_PATH];
2780 typedef BOOL (__stdcall *CREATEHARDLINKPROC)( LPCTSTR, LPCTSTR, LPSECURITY_ATTRIBUTES );
2781 static CREATEHARDLINKPROC _CreateHardLink = 0;
2783 HMODULE hModImagehlp = LoadLibrary(
"Kernel32.dll" );
2788 _CreateHardLink = (CREATEHARDLINKPROC) GetProcAddress( hModImagehlp,
"CreateHardLinkW" );
2790 _CreateHardLink = (CREATEHARDLINKPROC) GetProcAddress( hModImagehlp,
"CreateHardLinkA" );
2792 if (!_CreateHardLink)
2795 dwRet = GetFullPathName(from,
sizeof(szPath) /
sizeof(TCHAR),
2796 szPath, &lpszFilePart);
2798 if (_stati64(szPath, &finfo) < 0)
2801 if (finfo.st_mode & S_IFDIR)
2805 _splitpath(linkname,winDrive,winDir,winName,winExt);
2806 if ((!winDrive[0] ) &&
2808 _splitpath(szPath,winDrive,winDir,winName,winExt);
2809 snprintf(linkname,1024,
"%s\\%s\\%s", winDrive, winDir, to);
2811 else if (!winDrive[0]) {
2812 _splitpath(szPath,winDrive,winDir,winName,winExt);
2813 snprintf(linkname,1024,
"%s\\%s", winDrive, to);
2816 if (!_CreateHardLink(linkname, szPath, NULL))
2829 IShellLink* pShellLink;
2830 IPersistFile* pPersistFile;
2831 WCHAR wszLinkfile[MAX_PATH];
2832 int iWideCharsWritten;
2834 LPTSTR lpszFilePart;
2835 TCHAR szPath[MAX_PATH];
2837 hRes = E_INVALIDARG;
2838 if ((from == NULL) || (!from[0]) || (to == NULL) ||
2844 typedef HRESULT (__stdcall *COINITIALIZEPROC)( LPVOID );
2845 static COINITIALIZEPROC _CoInitialize = 0;
2846 typedef void (__stdcall *COUNINITIALIZEPROC)( void );
2847 static COUNINITIALIZEPROC _CoUninitialize = 0;
2848 typedef HRESULT (__stdcall *COCREATEINSTANCEPROC)( REFCLSID, LPUNKNOWN, DWORD, REFIID, LPVOID );
2849 static COCREATEINSTANCEPROC _CoCreateInstance = 0;
2851 HMODULE hModImagehlp = LoadLibrary(
"ole32.dll" );
2855 _CoInitialize = (COINITIALIZEPROC) GetProcAddress( hModImagehlp,
"CoInitialize" );
2858 _CoUninitialize = (COUNINITIALIZEPROC) GetProcAddress( hModImagehlp,
"CoUninitialize" );
2859 if (!_CoUninitialize)
2861 _CoCreateInstance = (COCREATEINSTANCEPROC) GetProcAddress( hModImagehlp,
"CoCreateInstance" );
2862 if (!_CoCreateInstance)
2869 _CoInitialize(NULL);
2872 dwRet = GetFullPathName(from,
sizeof(szPath) /
sizeof(TCHAR),
2873 szPath, &lpszFilePart);
2874 hRes = _CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2875 IID_IShellLink, (LPVOID *)&pShellLink);
2876 if (SUCCEEDED(hRes)) {
2878 hRes = pShellLink->SetPath(szPath);
2880 hRes = pShellLink->QueryInterface(IID_IPersistFile, (
void **)&pPersistFile);
2881 if (SUCCEEDED(hRes)){
2882 iWideCharsWritten = MultiByteToWideChar(CP_ACP, 0, linkname.
Data(), -1,
2883 wszLinkfile, MAX_PATH);
2884 hRes = pPersistFile->Save(wszLinkfile,
TRUE);
2885 pPersistFile->Release();
2887 pShellLink->Release();
2905 struct _stati64 finfo;
2907 if (_stati64(
name, &finfo) < 0) {
2911 if (finfo.st_mode & S_IFDIR) {
2912 return ::_rmdir(
name);
2914 return ::_unlink(
name);
2923 if (::ioctlsocket(fd, FIONBIO, (u_long *)1) == SOCKET_ERROR) {
2942 const char *patbuf = (
const char *)patbuf0;
2944 char *cmd =
nullptr;
2950 const char driveletter =
DriveName(patbuf);
2959 if (!
proto.EqualTo(
"file"))
2967 while (*patbuf ==
' ') {
2972 while (*patbuf ==
':') {
2977 while (*patbuf ==
';') {
2983 for (
q = (
char*)patbuf; *
q;
q++) {
2987 if ( (((
q-2)>patbuf) && ( (*(
q-2)!=
';') || !isalpha(*(
q-1)) )) &&
2994 for (
p = patbuf; *
p;
p++) {
3011 char replacement[4];
3014 for (
int k = 0; k<3; k++) replacement[k] = 0x1;
3016 replacement[3] = 0x0;
3020 while ( (pos = patbuf0.
Index(TildaNum,pos)) !=
kNPOS ) {
3021 patbuf0.
Replace(pos, 1, replacement);
3027 Int_t lbuf = ::ExpandEnvironmentStrings(
3033 cmd =
new char[lbuf+1];
3034 ::ExpandEnvironmentStrings(
3053 char newpath[MAX_PATH];
3054 if (IsShortcut(path)) {
3055 if (!ResolveShortCut(path, newpath, MAX_PATH))
3056 strlcpy(newpath, path, MAX_PATH);
3059 strlcpy(newpath, path, MAX_PATH);
3075 return ::_chmod(file,
mode);
3083 return ::umask(
mask);
3093 Error(
"Utime",
"need write permission for %s to change utime", file);
3096 if (!actime) actime = modtime;
3099 t.actime = (time_t)actime;
3100 t.modtime = (time_t)modtime;
3101 return ::utime(file, &t);
3120 return infile.
Data();
3128 Int_t lastDelim = -1;
3129 for(
int i=0; i < exsearch.
Length(); ++i) {
3130 switch( exsearch[i] ) {
3133 if (i-lastDelim!=2) exsearch[i] =
';';
3136 case ';': lastDelim = i;
break;
3143 char *lpFilePart =
nullptr;
3145 ::access(
name,
mode) == 0 && stat(
name, &finfo) == 0 &&
3146 finfo.st_mode & S_IFREG) {
3151 return infile.
Data();
3165 if ((
gEnv->
GetValue(
"WinNT.UseNetAPI", 0)) && (::GetVersion() < 0x80000000)) {
3168 HINSTANCE netapi = ::LoadLibrary(
"netapi32.DLL");
3169 if (!netapi)
return kFALSE;
3171 p2NetApiBufferFree = (pfn1)::GetProcAddress(netapi,
"NetApiBufferFree");
3172 p2NetUserGetInfo = (pfn2)::GetProcAddress(netapi,
"NetUserGetInfo");
3173 p2NetLocalGroupGetMembers = (pfn3)::GetProcAddress(netapi,
"NetLocalGroupGetMembers");
3174 p2NetLocalGroupEnum = (pfn4)::GetProcAddress(netapi,
"NetLocalGroupEnum");
3176 if (!p2NetApiBufferFree || !p2NetUserGetInfo ||
3177 !p2NetLocalGroupGetMembers || !p2NetLocalGroupEnum)
return kFALSE;
3188 ::FreeLibrary(netapi);
3198 NET_API_STATUS NetStatus = NERR_Success;
3200 DWORD Index = 0, Total = 0;
3201 DWORD_PTR ResumeHandle = 0;
3202 LOCALGROUP_MEMBERS_INFO_1 *MemberInfo;
3203 WCHAR wszGroupName[256];
3205 DWORD dwLastError = 0;
3207 iRetOp = MultiByteToWideChar (
3209 (DWORD)MB_PRECOMPOSED,
3210 (LPCSTR)lpszGroupName,
3212 (LPWSTR)wszGroupName,
3213 (
int)
sizeof(wszGroupName) );
3216 dwLastError = GetLastError();
3218 p2NetApiBufferFree(Data);
3224 NetStatus = p2NetLocalGroupGetMembers (NULL, wszGroupName, 1,
3225 &Data, 8192, &Index, &Total, &ResumeHandle );
3227 if (NetStatus != NERR_Success || Data == NULL) {
3228 dwLastError = GetLastError();
3230 if (dwLastError == ERROR_ENVVAR_NOT_FOUND) {
3236 NetStatus = p2NetLocalGroupGetMembers ( NULL, wszGroupName, 0,
3237 &Data, 8192, &Index, &Total, &ResumeHandle );
3241 p2NetApiBufferFree(Data);
3246 MemberInfo = (LOCALGROUP_MEMBERS_INFO_1 *)Data;
3249 p2NetApiBufferFree(Data);
3258 NET_API_STATUS NetStatus = NERR_Success;
3260 DWORD Index = 0, Total = 0, i;
3261 DWORD_PTR ResumeHandle = 0;
3262 LOCALGROUP_INFO_0 *GroupInfo;
3263 char szAnsiName[256];
3264 DWORD dwLastError = 0;
3267 NetStatus = p2NetLocalGroupEnum(NULL, 0, &Data, 8192, &Index,
3268 &Total, &ResumeHandle );
3270 if (NetStatus != NERR_Success || Data == NULL) {
3271 dwLastError = GetLastError();
3273 p2NetApiBufferFree(Data);
3278 GroupInfo = (LOCALGROUP_INFO_0 *)Data;
3279 for (i=0; i < Total; i++) {
3281 iRetOp = WideCharToMultiByte (
3284 (LPCWSTR)(GroupInfo->lgrpi0_name),
3287 (
int)(
sizeof(szAnsiName)),
3299 p2NetApiBufferFree(Data);
3311 int &groupIdx,
int &memberIdx)
3313 BOOL bRetOp =
FALSE;
3315 DWORD dwSidSize, dwDomainNameSize;
3318 SID_NAME_USE sidType;
3319 PUCHAR puchar_SubAuthCount = NULL;
3320 SID_IDENTIFIER_AUTHORITY sid_identifier_authority;
3321 PSID_IDENTIFIER_AUTHORITY psid_identifier_authority = NULL;
3322 unsigned char j = 0;
3323 DWORD dwLastError = 0;
3325 pSid = (PSID)bySidBuffer;
3326 dwSidSize =
sizeof(bySidBuffer);
3327 dwDomainNameSize =
sizeof(szDomainName);
3329 bRetOp = LookupAccountName (
3331 (LPCTSTR)lpszAccountName,
3333 (LPDWORD)&dwSidSize,
3334 (LPTSTR)szDomainName,
3335 (LPDWORD)&dwDomainNameSize,
3336 (PSID_NAME_USE)&sidType );
3338 if (bRetOp ==
FALSE) {
3339 dwLastError = GetLastError();
3343 bRetOp = IsValidSid((PSID)pSid);
3345 if (bRetOp ==
FALSE) {
3346 dwLastError = GetLastError();
3351 psid_identifier_authority = GetSidIdentifierAuthority ((PSID)pSid);
3354 memcpy (&sid_identifier_authority, psid_identifier_authority,
3355 sizeof(SID_IDENTIFIER_AUTHORITY));
3358 puchar_SubAuthCount = (PUCHAR)GetSidSubAuthorityCount((PSID)pSid);
3360 j = (
unsigned char)(*puchar_SubAuthCount);
3362 DWORD dwSubAuth = 0;
3363 PDWORD pdwSubAuth = NULL;
3365 pdwSubAuth = (PDWORD)GetSidSubAuthority (
3368 dwSubAuth = *pdwSubAuth;
3387 NET_API_STATUS NetStatus = NERR_Success;
3389 DWORD Index = 0, Total = 0, i;
3390 DWORD_PTR ResumeHandle = 0;
3391 LOCALGROUP_MEMBERS_INFO_1 *MemberInfo;
3392 char szAnsiMemberName[256];
3393 char szFullMemberName[256];
3394 char szMemberHomeDir[256];
3395 WCHAR wszGroupName[256];
3398 DWORD
length =
sizeof (act_name);
3399 DWORD dwLastError = 0;
3400 LPUSER_INFO_11 pUI11Buf = NULL;
3401 NET_API_STATUS nStatus;
3403 iRetOp = MultiByteToWideChar (
3405 (DWORD)MB_PRECOMPOSED,
3406 (LPCSTR)lpszGroupName,
3408 (LPWSTR)wszGroupName,
3409 (
int)
sizeof(wszGroupName) );
3412 dwLastError = GetLastError();
3414 p2NetApiBufferFree(Data);
3418 GetUserName (act_name, &
length);
3422 NetStatus = p2NetLocalGroupGetMembers (NULL, wszGroupName, 1,
3423 &Data, 8192, &Index, &Total, &ResumeHandle );
3425 if (NetStatus != NERR_Success || Data == NULL) {
3426 dwLastError = GetLastError();
3428 if (dwLastError == ERROR_ENVVAR_NOT_FOUND) {
3434 NetStatus = p2NetLocalGroupGetMembers ( NULL, wszGroupName, 0,
3435 &Data, 8192, &Index, &Total, &ResumeHandle );
3439 p2NetApiBufferFree(Data);
3443 MemberInfo = (LOCALGROUP_MEMBERS_INFO_1 *)Data;
3444 for (i=0; i < Total; i++) {
3445 iRetOp = WideCharToMultiByte (
3448 (LPCWSTR)(MemberInfo->lgrmi1_name),
3450 (LPSTR)szAnsiMemberName,
3451 (
int)(
sizeof(szAnsiMemberName)),
3456 dwLastError = GetLastError();
3467 TCHAR szUserName[255]=TEXT(
"");
3468 MultiByteToWideChar(CP_ACP, 0, szAnsiMemberName, -1, (LPWSTR)szUserName, 255);
3472 nStatus = p2NetUserGetInfo(NULL, (LPCWSTR)szUserName, 11, (LPBYTE *)&pUI11Buf);
3476 if (nStatus == NERR_Success) {
3477 if (pUI11Buf != NULL) {
3478 wsprintf(szFullMemberName,
"%S",pUI11Buf->usri11_full_name);
3480 wsprintf(szMemberHomeDir,
"%S",pUI11Buf->usri11_home_dir);
3491 if (pUI11Buf != NULL) {
3492 p2NetApiBufferFree(pUI11Buf);
3497 if (getenv(
"SHELL") == NULL)
3498 putenv ((GetVersion () & 0x80000000) ?
"SHELL=command" :
"SHELL=cmd");
3511 p2NetApiBufferFree(Data);
3521 NET_API_STATUS NetStatus = NERR_Success;
3523 DWORD Index = 0, Total = 0, i;
3524 DWORD_PTR ResumeHandle = 0;
3525 LOCALGROUP_INFO_0 *GroupInfo;
3526 char szAnsiName[256];
3527 DWORD dwLastError = 0;
3528 int iRetOp = 0, iGroupIdx = 0, iMemberIdx = 0;
3530 NetStatus = p2NetLocalGroupEnum(NULL, 0, &Data, 8192, &Index,
3531 &Total, &ResumeHandle );
3533 if (NetStatus != NERR_Success || Data == NULL) {
3534 dwLastError = GetLastError();
3536 p2NetApiBufferFree(Data);
3540 GroupInfo = (LOCALGROUP_INFO_0 *)Data;
3541 for (i=0; i < Total; i++) {
3543 iRetOp = WideCharToMultiByte (
3546 (LPCWSTR)(GroupInfo->lgrpi0_name),
3549 (
int)(
sizeof(szAnsiName)),
3567 p2NetApiBufferFree(Data);
3581 if ((!
gEnv->
GetValue(
"WinNT.UseNetAPI", 0)) || (::GetVersion() >= 0x80000000)) {
3586 if (stricmp (
"administrator",
name) == 0)
3596 if (!user || !user[0])
3601 if (!stricmp (user,
fPasswords[i].pw_name)) {
3622 if ((!
gEnv->
GetValue(
"WinNT.UseNetAPI", 0)) || (::GetVersion() >= 0x80000000)) {
3627 if (stricmp (
"administrator",
name) == 0)
3649 if ((!
gEnv->
GetValue(
"WinNT.UseNetAPI", 0)) || (::GetVersion() >= 0x80000000)) {
3654 if (stricmp (
"administrator",
name) == 0)
3667 struct group *grp =
nullptr;
3690 if ((!
gEnv->
GetValue(
"WinNT.UseNetAPI", 0)) || (::GetVersion() >= 0x80000000)) {
3695 if (stricmp (
"administrator",
name) == 0)
3718 if ((!
gEnv->
GetValue(
"WinNT.UseNetAPI", 0)) || (::GetVersion() >= 0x80000000)) {
3724 if (stricmp (
"administrator",
name) == 0) {
3726 ug->
fGroup =
"administrators";
3735 ug->
fUser =
"unknown";
3748 for (
int i = 0; i <
fNbUsers; i++) {
3792 if ((!
gEnv->
GetValue(
"WinNT.UseNetAPI", 0)) || (::GetVersion() >= 0x80000000)) {
3797 if (stricmp (
"administrator",
name) == 0) {
3798 gr->fGroup =
"administrators";
3802 gr->fGroup =
"users";
3807 gr->fGroup =
"unknown";
3813 struct group *grp =
nullptr;
3815 if (gid ==
fGroups[i].gr_gid) {
3857 const char *env = ::getenv(
name);
3859 if (::_stricmp(
name,
"home") == 0 ) {
3861 }
else if (::_stricmp(
name,
"rootsys") == 0 ) {
3875 return ::system(shellcmd);
3883 return ::_popen(command,
mode);
3891 return ::_pclose(pipe);
3919 gROOT->CloseFiles();
3920 if (
gROOT->GetListOfBrowsers()) {
3923 if (
gROOT->IsBatch())
3924 gROOT->GetListOfBrowsers()->Delete();
3929 if (
b->GetBrowserImp() &&
b->GetBrowserImp()->GetMainFrame())
3931 (((TBrowser*)0x%zx)->GetBrowserImp()->GetMainFrame()->CloseWindow();",
3973 static int fd1=0, fd2=0;
3974 static fpos_t pos1=0, pos2=0;
3984 const char *
m = (
mode[0] ==
'a' ||
mode[0] ==
'w') ?
mode :
"a";
3997 fgetpos(stdout, &pos1);
3998 fd1 = _dup(fileno(stdout));
4000 if ((fout = freopen(file,
m, stdout)) == 0) {
4001 SysError(
"RedirectOutput",
"could not freopen stdout");
4003 _dup2(fd1, fileno(stdout));
4007 fsetpos(stdout, &pos1);
4012 fgetpos(stderr, &pos2);
4013 fd2 = _dup(fileno(stderr));
4014 if ((ferr = freopen(file,
m, stderr)) == 0) {
4015 SysError(
"RedirectOutput",
"could not freopen stderr");
4017 _dup2(fd1, fileno(stdout));
4021 fsetpos(stdout, &pos1);
4023 _dup2(fd2, fileno(stderr));
4027 fsetpos(stderr, &pos2);
4032 fseek(fout, 0, SEEK_END);
4033 fseek(ferr, 0, SEEK_END);
4040 if (_dup2(fd1, fileno(stdout))) {
4041 SysError(
"RedirectOutput",
"could not restore stdout");
4047 fsetpos(stdout, &pos1);
4054 if (_dup2(fd2, fileno(stderr))) {
4055 SysError(
"RedirectOutput",
"could not restore stderr");
4061 fsetpos(stderr, &pos2);
4116 if (
len > 4 && (!stricmp(sLib.
Data()+
len-4,
".dll"))) {
4129 Error(
"DynamicPathName",
4130 "%s does not exist in %s,\nor has wrong file extension (.dll)",
4147#pragma warning(push)
4148#pragma warning(disable:4200)
4165 if (!linkedLibs.
IsNull())
4178 HANDLE hFile, hMapping;
4181 if((hFile = CreateFile(exe,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,0))==
INVALID_HANDLE_VALUE) {
4185 if(!(hMapping = CreateFileMapping(hFile,0,PAGE_READONLY|SEC_COMMIT,0,0,0))) {
4190 if(!(basepointer = MapViewOfFile(hMapping,FILE_MAP_READ,0,0,0))) {
4191 CloseHandle(hMapping);
4198 IMAGE_DOS_HEADER *dos_head = (IMAGE_DOS_HEADER *)basepointer;
4201 IMAGE_FILE_HEADER _head;
4202 IMAGE_OPTIONAL_HEADER opt_head;
4203 IMAGE_SECTION_HEADER section_header[];
4205 struct header *pheader;
4206 const IMAGE_SECTION_HEADER * section_header;
4208 if(dos_head->e_magic!=
'ZM') {
4213 pheader = (
struct header *)((
char*)dos_head + dos_head->e_lfanew);
4215 if(IsBadReadPtr(pheader,
sizeof(
struct header))) {
4219 if(pheader->signature!=IMAGE_NT_SIGNATURE) {
4220 switch((
unsigned short)pheader->signature) {
4221 case IMAGE_DOS_SIGNATURE:
4224 case IMAGE_OS2_SIGNATURE:
4227 case IMAGE_OS2_SIGNATURE_LE:
4235#define isin(address,start,length) ((address)>=(start) && (address)<(start)+(length))
4238 for(sect=0,section_header=pheader->section_header;
4239 sect<pheader->_head.NumberOfSections;sect++,section_header++) {
4241 const void *
const section_data =
4242 (
char*)basepointer + section_header->PointerToRawData;
4243 for(directory=0;directory<IMAGE_NUMBEROF_DIRECTORY_ENTRIES;directory++) {
4244 if(
isin(pheader->opt_head.DataDirectory[directory].VirtualAddress,
4245 section_header->VirtualAddress,
4246 section_header->SizeOfRawData)) {
4247 const IMAGE_IMPORT_DESCRIPTOR *stuff_start =
4248 (IMAGE_IMPORT_DESCRIPTOR *)((
char*)section_data +
4249 (pheader->opt_head.DataDirectory[directory].VirtualAddress -
4250 section_header->VirtualAddress));
4253 const unsigned stuff_length =
4254 pheader->opt_head.DataDirectory[directory].Size;
4255 if(directory == IMAGE_DIRECTORY_ENTRY_IMPORT) {
4256 while(!IsBadReadPtr(stuff_start,
sizeof(*stuff_start)) &&
4257 stuff_start->Name) {
4258 TString dll = (
char*)section_data +
4259 ((DWORD)(stuff_start->Name)) -
4260 section_header->VirtualAddress;
4264 char *winPath = getenv(
"windir");
4265 _splitpath(winPath,winDrive,winDir,winName,winExt);
4266 if(!strstr(dllPath, winDir)) {
4267 if (!linkedLibs.
IsNull())
4269 linkedLibs += dllPath;
4281 UnmapViewOfFile(basepointer);
4282 CloseHandle(hMapping);
4313 char drive[_MAX_DRIVE], dir[_MAX_DIR], fname[_MAX_FNAME], ext[_MAX_EXT];
4316 std::vector<std::string> all_libs, libpaths;
4322 while (getline(libenv, str,
';')) {
4323 libpaths.push_back(str);
4326 std::stringstream libraries(libs.
Data());
4327 while (getline(libraries, str,
' ')) {
4328 std::string::size_type first, last;
4331 if (str.rfind(
"-L", 0) == 0) {
4332 first = str.find_first_of(
'%');
4333 last = str.find_last_of(
'%');
4334 if ((first != std::string::npos) && (last != std::string::npos) &&
4339 std::string var = str.substr(first+1, last-first-1);
4344 env += str.substr(last+1);
4345 libpaths.push_back(env);
4349 ntlibs.
Append(str.c_str());
4354 last = str.rfind(
".dll");
4355 if (last != std::string::npos)
4356 str.replace(last, 4,
".lib");
4357 last = str.rfind(
".DLL");
4358 if (last != std::string::npos)
4359 str.replace(last, 4,
".lib");
4360 if (str.rfind(
".lib") != std::string::npos ||
4361 str.rfind(
".LIB") != std::string::npos) {
4363 if (_stat( str.c_str(), &buf ) == 0) {
4365 ntlibs.
Append(str.c_str());
4375 size_t requiredSize;
4376 getenv_s( &requiredSize, NULL, 0,
"WinDir");
4377 if (requiredSize == 0) {
4378 windir = strdup(
":\\WINDOWS");
4380 windir = (
char*)
malloc(requiredSize *
sizeof(
char));
4382 windir = strdup(
":\\WINDOWS");
4384 getenv_s( &requiredSize, windir, requiredSize,
"WinDir" );
4387 if (str.find(windir) == std::string::npos) {
4388 _splitpath(str.c_str(), drive, dir, fname, ext);
4389 std::string libname(fname);
4391 all_libs.push_back(libname);
4395 for (
auto lib : all_libs) {
4397 for (
auto libpath : libpaths) {
4399 std::string path_lib(libpath);
4402 if (_stat( path_lib.c_str(), &buf ) == 0) {
4404 ntlibs.
Append(lib.c_str());
4433 if (!ti)
return nullptr;
4490 FILETIME ftFileTime;
4494 ::GetSystemTimeAsFileTime(&ftRealTime.ftFileTime);
4503 OSVERSIONINFO OsVersionInfo;
4512 OsVersionInfo.dwOSVersionInfoSize =
sizeof(OSVERSIONINFO);
4513 GetVersionEx(&OsVersionInfo);
4514 if (OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) {
4520 FILETIME ftFileTime;
4525 FILETIME ftFileTime;
4529 HANDLE hThread = GetCurrentThread();
4530 ret = GetThreadTimes (hThread, &ftCreate, &ftExit,
4531 &ftKernel.ftFileTime,
4532 &ftUser.ftFileTime);
4534 ret = ::GetLastError();
4535 ::Error(
"GetCPUTime",
" Error on GetProcessTimes 0x%lx", (
int)ret);
4555 static time_t jan95 = 0;
4566 jan95 = mktime(&tp);
4567 if ((
int)jan95 == -1) {
4568 ::SysError(
"TWinNTSystem::Now",
"error converting 950001 0:00 to time_t");
4575 return TTime((now.time-(
Long_t)jan95)*1000 + now.millitm);
4585 std::this_thread::sleep_for(std::chrono::milliseconds(milliSec));
4601 if (
h->HasReadInterest())
4603 if (
h->HasWriteInterest())
4605 h->ResetReadyMask();
4607 rc = WinNTSelect(&rd, &wr, to);
4636 if (
h->HasReadInterest())
4638 if (
h->HasWriteInterest())
4640 h->ResetReadyMask();
4641 rc = WinNTSelect(&rd, &wr, to);
4663 if ((sp = ::getservbyname(servicename,
kProtocolName)) == 0) {
4664 Error(
"GetServiceByName",
"no service \"%s\" with protocol \"%s\"\n",
4668 return ::ntohs(sp->s_port);
4679 if ((sp = ::getservbyport(::htons(port),
kProtocolName)) == 0) {
4680 return Form(
"%d", port);
4690 struct hostent *host_ptr;
4695 if ((addr = ::inet_addr(hostname)) != INADDR_NONE) {
4697 if ((host_ptr = ::gethostbyaddr((
const char *)&addr,
4698 sizeof(addr), AF_INET))) {
4699 host = host_ptr->h_name;
4703 for (i = 1; host_ptr->h_addr_list[i]; i++) {
4704 memcpy(&addr2, host_ptr->h_addr_list[i], host_ptr->h_length);
4705 a.AddAddress(ntohl(addr2));
4707 for (i = 0; host_ptr->h_aliases[i]; i++)
4708 a.AddAlias(host_ptr->h_aliases[i]);
4711 host =
"UnNamedHost";
4713 }
else if ((host_ptr = ::gethostbyname(hostname))) {
4715 if (host_ptr->h_addrtype != AF_INET) {
4716 Error(
"GetHostByName",
"%s is not an internet host\n", hostname);
4719 memcpy(&addr, host_ptr->h_addr, host_ptr->h_length);
4720 host = host_ptr->h_name;
4721 type = host_ptr->h_addrtype;
4725 for (i = 1; host_ptr->h_addr_list[i]; i++) {
4726 memcpy(&addr2, host_ptr->h_addr_list[i], host_ptr->h_length);
4727 a.AddAddress(ntohl(addr2));
4729 for (i = 0; host_ptr->h_aliases[i]; i++)
4730 a.AddAlias(host_ptr->h_aliases[i]);
4733 if (
gDebug > 0)
Error(
"GetHostByName",
"unknown host %s", hostname);
4746 struct sockaddr_in addr;
4747 int len =
sizeof(addr);
4749 if (::getpeername(sock, (
struct sockaddr *)&addr, &
len) == SOCKET_ERROR) {
4754 struct hostent *host_ptr;
4755 const char *hostname;
4759 if ((host_ptr = ::gethostbyaddr((
const char *)&addr.sin_addr,
4760 sizeof(addr.sin_addr), AF_INET))) {
4761 memcpy(&iaddr, host_ptr->h_addr, host_ptr->h_length);
4762 hostname = host_ptr->h_name;
4763 family = host_ptr->h_addrtype;
4765 memcpy(&iaddr, &addr.sin_addr,
sizeof(addr.sin_addr));
4770 return TInetAddress(hostname, ::ntohl(iaddr), family, ::ntohs(addr.sin_port));
4779 struct sockaddr_in addr;
4780 int len =
sizeof(addr);
4782 if (::getsockname(sock, (
struct sockaddr *)&addr, &
len) == SOCKET_ERROR) {
4787 struct hostent *host_ptr;
4788 const char *hostname;
4792 if ((host_ptr = ::gethostbyaddr((
const char *)&addr.sin_addr,
4793 sizeof(addr.sin_addr), AF_INET))) {
4794 memcpy(&iaddr, host_ptr->h_addr, host_ptr->h_length);
4795 hostname = host_ptr->h_name;
4796 family = host_ptr->h_addrtype;
4798 memcpy(&iaddr, &addr.sin_addr,
sizeof(addr.sin_addr));
4803 return TInetAddress(hostname, ::ntohl(iaddr), family, ::ntohs(addr.sin_port));
4815 ::SysError(
"TWinNTSystem::AnnounceUnixService",
"socket");
4819 struct sockaddr_in inserver;
4820 memset(&inserver, 0,
sizeof(inserver));
4821 inserver.sin_family = AF_INET;
4822 inserver.sin_addr.s_addr = ::htonl(INADDR_LOOPBACK);
4823 inserver.sin_port = port;
4827 if (::bind(sock, (
struct sockaddr*) &inserver,
sizeof(inserver)) == SOCKET_ERROR) {
4828 ::SysError(
"TWinNTSystem::AnnounceUnixService",
"bind");
4833 if (::listen(sock, backlog)) {
4834 ::SysError(
"TWinNTSystem::AnnounceUnixService",
"listen");
4846 if (!sockpath || strlen(sockpath) <= 0) {
4847 ::SysError(
"TWinNTSystem::AnnounceUnixService",
"socket path undefined");
4851 struct sockaddr_in myaddr;
4853 int len =
sizeof myaddr;
4858 if ((sock =
socket(AF_INET, SOCK_STREAM, 0)) < 0) {
4859 ::SysError(
"TWinNTSystem::AnnounceUnixService",
"socket");
4863 memset(&myaddr, 0,
sizeof(myaddr));
4864 myaddr.sin_port = 0;
4865 myaddr.sin_family = AF_INET;
4866 myaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4868 rc = bind(sock, (
struct sockaddr *)&myaddr,
len);
4870 ::SysError(
"TWinNTSystem::AnnounceUnixService",
"bind");
4873 rc = getsockname(sock, (
struct sockaddr *)&myaddr, &
len);
4875 ::SysError(
"TWinNTSystem::AnnounceUnixService",
"getsockname");
4878 TString socketpath = sockpath;
4880 fp = fopen(socketpath,
"wb");
4882 ::SysError(
"TWinNTSystem::AnnounceUnixService",
"fopen");
4885 fprintf(fp,
"%d", myaddr.sin_port);
4889 if (listen(sock, backlog)) {
4890 ::SysError(
"TWinNTSystem::AnnounceUnixService",
"listen");
4902 if (
socket == -1)
return;
4906 ::shutdown(sock, 2);
4908 struct linger linger = {0, 0};
4909 ::setsockopt(sock, SOL_SOCKET, SO_LINGER, (
char *) &linger,
sizeof(linger));
4910 while (
::closesocket(sock) == SOCKET_ERROR && WSAGetLastError() == WSAEINTR) {
4924 if (WinNTRecv(sock, &header,
sizeof(header), 0) > 0) {
4925 int count = ::ntohl(header);
4928 Error(
"RecvBuf",
"record header exceeds buffer size");
4930 }
else if (count > 0) {
4931 if (WinNTRecv(sock, buf, count, 0) < 0) {
4932 Error(
"RecvBuf",
"cannot receive buffer");
4949 if (WinNTSend(sock, &header,
sizeof(header), 0) < 0) {
4950 Error(
"SendBuf",
"cannot send header");
4954 if (WinNTSend(sock, buf,
length, 0) < 0) {
4955 Error(
"SendBuf",
"cannot send buffer");
4995 if ((
n = WinNTRecv(sock, buf,
length, flag)) <= 0) {
4997 Error(
"RecvRaw",
"cannot receive buffer");
5031 if ((
n = WinNTSend(sock, buf,
length, flag)) <= 0) {
5033 Error(
"SendRaw",
"cannot send buffer");
5046 if (
socket == -1)
return -1;
5051 if (::setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (
char*)&val,
sizeof(val)) == SOCKET_ERROR) {
5052 ::SysError(
"SetSockOpt",
"setsockopt(SO_SNDBUF)");
5057 if (::setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (
char*)&val,
sizeof(val)) == SOCKET_ERROR) {
5058 ::SysError(
"SetSockOpt",
"setsockopt(SO_RCVBUF)");
5063 if (::setsockopt(sock, SOL_SOCKET, SO_OOBINLINE, (
char*)&val,
sizeof(val)) == SOCKET_ERROR) {
5064 SysError(
"SetSockOpt",
"setsockopt(SO_OOBINLINE)");
5069 if (::setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (
char*)&val,
sizeof(val)) == SOCKET_ERROR) {
5070 ::SysError(
"SetSockOpt",
"setsockopt(SO_KEEPALIVE)");
5075 if (::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (
char*)&val,
sizeof(val)) == SOCKET_ERROR) {
5076 ::SysError(
"SetSockOpt",
"setsockopt(SO_REUSEADDR)");
5081 if (::setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (
char*)&val,
sizeof(val)) == SOCKET_ERROR) {
5082 ::SysError(
"SetSockOpt",
"setsockopt(TCP_NODELAY)");
5087 if (::ioctlsocket(sock, FIONBIO, &val) == SOCKET_ERROR) {
5094 if (::ioctl(sock, SIOCSPGRP, &val) == -1) {
5095 ::SysError(
"SetSockOpt",
"ioctl(SIOCSPGRP)");
5103 Error(
"SetSockOpt",
"illegal option (%d)", opt);
5115 if (
socket == -1)
return -1;
5118 int optlen =
sizeof(*val);
5122 if (::getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (
char*)val, &optlen) == SOCKET_ERROR) {
5123 ::SysError(
"GetSockOpt",
"getsockopt(SO_SNDBUF)");
5128 if (::getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (
char*)val, &optlen) == SOCKET_ERROR) {
5129 ::SysError(
"GetSockOpt",
"getsockopt(SO_RCVBUF)");
5134 if (::getsockopt(sock, SOL_SOCKET, SO_OOBINLINE, (
char*)val, &optlen) == SOCKET_ERROR) {
5135 ::SysError(
"GetSockOpt",
"getsockopt(SO_OOBINLINE)");
5140 if (::getsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (
char*)val, &optlen) == SOCKET_ERROR) {
5141 ::SysError(
"GetSockOpt",
"getsockopt(SO_KEEPALIVE)");
5146 if (::getsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (
char*)val, &optlen) == SOCKET_ERROR) {
5147 ::SysError(
"GetSockOpt",
"getsockopt(SO_REUSEADDR)");
5152 if (::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (
char*)val, &optlen) == SOCKET_ERROR) {
5153 ::SysError(
"GetSockOpt",
"getsockopt(TCP_NODELAY)");
5169 if (::ioctlsocket(sock, SIOCGPGRP, (u_long*)val) == SOCKET_ERROR) {
5170 ::SysError(
"GetSockOpt",
"ioctl(SIOCGPGRP)");
5176 if (::ioctlsocket(sock, SIOCATMARK, (u_long*)val) == SOCKET_ERROR) {
5177 ::SysError(
"GetSockOpt",
"ioctl(SIOCATMARK)");
5182 if (::ioctlsocket(sock, FIONREAD, (u_long*)val) == SOCKET_ERROR) {
5188 Error(
"GetSockOpt",
"illegal option (%d)", opt);
5200 int tcpwindowsize,
const char *protocol)
5205 if (!strcmp(servername,
"unix")) {
5209 (servername[1] ==
':' && servername[2] ==
'/')) {
5213 if (!strcmp(protocol,
"udp")){
5220 sport = ::htons(port);
5224 if (!addr.
IsValid())
return -1;
5227 struct sockaddr_in server;
5228 memset(&server, 0,
sizeof(server));
5229 memcpy(&server.sin_addr, &adr,
sizeof(adr));
5231 server.sin_port = sport;
5236 ::SysError(
"TWinNTSystem::WinNTConnectTcp",
"socket");
5240 if (tcpwindowsize > 0) {
5245 if (::connect(sock, (
struct sockaddr*) &server,
sizeof(server)) ==
INVALID_SOCKET) {
5258 struct sockaddr_in myaddr;
5261 memset(&myaddr, 0,
sizeof(myaddr));
5262 myaddr.sin_family = AF_INET;
5263 myaddr.sin_port = port;
5264 myaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
5267 if ((sock =
socket(AF_INET, SOCK_STREAM, 0)) < 0) {
5268 ::SysError(
"TWinNTSystem::WinNTUnixConnect",
"socket");
5272 while ((connect(sock, (
struct sockaddr *)&myaddr,
sizeof myaddr)) == -1) {
5276 ::SysError(
"TWinNTSystem::WinNTUnixConnect",
"connect");
5292 if (!sockpath || strlen(sockpath) <= 0) {
5293 ::SysError(
"TWinNTSystem::WinNTUnixConnect",
"socket path undefined");
5296 TString socketpath = sockpath;
5298 fp = fopen(socketpath.
Data(),
"rb");
5300 ::SysError(
"TWinNTSystem::WinNTUnixConnect",
"fopen");
5303 fscanf(fp,
"%d", &port);
5306 if (port < 0 || port > 65535) {
5307 ::SysError(
"TWinNTSystem::WinNTUnixConnect",
"invalid port");
5325 sport = htons(port);
5328 if (!addr.
IsValid())
return -1;
5331 struct sockaddr_in server;
5332 memset(&server, 0,
sizeof(server));
5333 memcpy(&server.sin_addr, &adr,
sizeof(adr));
5335 server.sin_port = sport;
5339 if ((sock =
socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
5340 ::SysError(
"TWinNTSystem::WinNTUdpConnect",
"socket (%s:%d)",
5345 while (connect(sock, (
struct sockaddr*) &server,
sizeof(server)) == -1) {
5349 ::SysError(
"TWinNTSystem::WinNTUdpConnect",
"connect (%s:%d)",
5367 const char *protocol)
5388 const short kSOCKET_MINPORT = 5000, kSOCKET_MAXPORT = 15000;
5389 short tryport = kSOCKET_MINPORT;
5394 sport = ::htons(port);
5397 if (port == 0 && reuse) {
5398 ::Error(
"TWinNTSystem::WinNTTcpService",
"cannot do a port scan while reuse is true");
5405 sport = ::htons(port);
5410 if ((sock =
::socket(AF_INET, SOCK_STREAM, 0)) < 0) {
5411 ::SysError(
"TWinNTSystem::WinNTTcpService",
"socket");
5419 if (tcpwindowsize > 0) {
5424 struct sockaddr_in inserver;
5425 memset(&inserver, 0,
sizeof(inserver));
5426 inserver.sin_family = AF_INET;
5427 inserver.sin_addr.s_addr = ::htonl(INADDR_ANY);
5428 inserver.sin_port = sport;
5432 if (::bind(sock, (
struct sockaddr*) &inserver,
sizeof(inserver)) == SOCKET_ERROR) {
5433 ::SysError(
"TWinNTSystem::WinNTTcpService",
"bind");
5439 inserver.sin_port = ::htons(tryport);
5440 bret = ::bind(sock, (
struct sockaddr*) &inserver,
sizeof(inserver));
5442 }
while (bret == SOCKET_ERROR && WSAGetLastError() == WSAEADDRINUSE &&
5443 tryport < kSOCKET_MAXPORT);
5444 if (bret == SOCKET_ERROR) {
5445 ::SysError(
"TWinNTSystem::WinNTTcpService",
"bind (port scan)");
5451 if (::listen(sock, backlog) == SOCKET_ERROR) {
5452 ::SysError(
"TWinNTSystem::WinNTTcpService",
"listen");
5469 const short kSOCKET_MINPORT = 5000, kSOCKET_MAXPORT = 15000;
5470 short sport, tryport = kSOCKET_MINPORT;
5476 sport = htons(port);
5480 if ((sock =
socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
5481 ::SysError(
"TUnixSystem::UnixUdpService",
"socket");
5485 struct sockaddr_in inserver;
5486 memset(&inserver, 0,
sizeof(inserver));
5487 inserver.sin_family = AF_INET;
5488 inserver.sin_addr.s_addr = htonl(INADDR_ANY);
5489 inserver.sin_port = sport;
5493 if (bind(sock, (
struct sockaddr*) &inserver,
sizeof(inserver))) {
5494 ::SysError(
"TWinNTSystem::AnnounceUdpService",
"bind");
5500 inserver.sin_port = htons(tryport);
5501 bret = bind(sock, (
struct sockaddr*) &inserver,
sizeof(inserver));
5503 }
while (bret == SOCKET_ERROR && WSAGetLastError() == WSAEADDRINUSE &&
5504 tryport < kSOCKET_MAXPORT);
5506 ::SysError(
"TWinNTSystem::AnnounceUdpService",
"bind (port scan)");
5512 if (listen(sock, backlog)) {
5513 ::SysError(
"TWinNTSystem::AnnounceUdpService",
"listen");
5531 (::WSAGetLastError() == WSAEINTR)) {
5536 if (::WSAGetLastError() == WSAEWOULDBLOCK) {
5550#define SystemBasicInformation 0
5551#define SystemPerformanceInformation 2
5591#define Li2Double(x) ((double)((x).HighPart) * 4.294967296E9 + (double)((x).LowPart))
5599 LARGE_INTEGER ulFreq, ulTicks, ulValue, ulStartCounter;
5603 if (QueryPerformanceFrequency(&ulFreq)) {
5605 QueryPerformanceCounter(&ulTicks);
5608 ulValue.QuadPart = ulTicks.QuadPart + ulFreq.QuadPart/10;
5609 ulStartCounter.QuadPart =
__rdtsc();
5613 QueryPerformanceCounter(&ulTicks);
5614 }
while (ulTicks.QuadPart <= ulValue.QuadPart);
5616 return (DWORD)((
__rdtsc() - ulStartCounter.QuadPart)/100000);
5624#define SM_SERVERR2 89
5625typedef void (WINAPI *
PGNSI)(LPSYSTEM_INFO);
5631 OSVERSIONINFOEX osvi;
5634 BOOL bOsVersionInfoEx;
5635 static char *strReturn =
nullptr;
5639 strReturn =
new char[2048];
5643 ZeroMemory(&si,
sizeof(SYSTEM_INFO));
5644 ZeroMemory(&osvi,
sizeof(OSVERSIONINFOEX));
5649 osvi.dwOSVersionInfoSize =
sizeof(OSVERSIONINFOEX);
5651 if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) )
5653 osvi.dwOSVersionInfoSize =
sizeof (OSVERSIONINFO);
5654 if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) )
5659 pGNSI = (
PGNSI) GetProcAddress( GetModuleHandle(
"kernel32.dll"),
5660 "GetNativeSystemInfo");
5663 else GetSystemInfo(&si);
5665 switch (osvi.dwPlatformId)
5668 case VER_PLATFORM_WIN32_NT:
5671 if ( osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0 )
5673 if( osvi.wProductType == VER_NT_WORKSTATION )
5674 strlcpy(strReturn,
"Microsoft Windows Vista ",2048);
5675 else strlcpy(strReturn,
"Windows Server \"Longhorn\" " ,2048);
5677 if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2 )
5680 strlcpy(strReturn,
"Microsoft Windows Server 2003 \"R2\" ",2048);
5681 else if( osvi.wProductType == VER_NT_WORKSTATION &&
5682 si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64)
5684 strlcpy(strReturn,
"Microsoft Windows XP Professional x64 Edition ",2048);
5686 else strlcpy(strReturn,
"Microsoft Windows Server 2003, ",2048);
5688 if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 )
5689 strlcpy(strReturn,
"Microsoft Windows XP ",2048);
5691 if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0 )
5692 strlcpy(strReturn,
"Microsoft Windows 2000 ",2048);
5694 if ( osvi.dwMajorVersion <= 4 )
5695 strlcpy(strReturn,
"Microsoft Windows NT ",2048);
5698 if( bOsVersionInfoEx )
5701 if ( osvi.wProductType == VER_NT_WORKSTATION &&
5702 si.wProcessorArchitecture!=PROCESSOR_ARCHITECTURE_AMD64)
5704 if( osvi.dwMajorVersion == 4 )
5705 strlcat(strReturn,
"Workstation 4.0 ",2048 );
5706 else if( osvi.wSuiteMask & VER_SUITE_PERSONAL )
5707 strlcat(strReturn,
"Home Edition " ,2048);
5708 else strlcat(strReturn,
"Professional " ,2048);
5711 else if ( osvi.wProductType == VER_NT_SERVER ||
5712 osvi.wProductType == VER_NT_DOMAIN_CONTROLLER )
5714 if(osvi.dwMajorVersion==5 && osvi.dwMinorVersion==2)
5716 if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_IA64 )
5718 if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
5719 strlcat(strReturn,
"Datacenter Edition for Itanium-based Systems",2048 );
5720 else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
5721 strlcat(strReturn,
"Enterprise Edition for Itanium-based Systems" ,2048);
5723 else if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64 )
5725 if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
5726 strlcat(strReturn,
"Datacenter x64 Edition ",2048 );
5727 else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
5728 strlcat(strReturn,
"Enterprise x64 Edition ",2048 );
5729 else strlcat(strReturn,
"Standard x64 Edition ",2048 );
5733 if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
5734 strlcat(strReturn,
"Datacenter Edition ",2048 );
5735 else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
5736 strlcat(strReturn,
"Enterprise Edition ",2048 );
5737 else if ( osvi.wSuiteMask == VER_SUITE_BLADE