Exemple #1
1
int getCpuNum(){
	SYSTEM_INFO si;
	GetSystemInfo(&si);
	return (int)si.dwNumberOfProcessors;
}
Exemple #2
0
static
VOID
InitializeSystemPage(HWND hwndDlg)
{
    WCHAR szTime[200];
    DWORD Length;
    DWORDLONG AvailableBytes, UsedBytes;
    MEMORYSTATUSEX mem;
    WCHAR szFormat[40];
    WCHAR szDesc[50];
    SYSTEM_INFO SysInfo;

    /* set date/time */
    szTime[0] = L'\0';
    Length = GetDateFormat(LOCALE_SYSTEM_DEFAULT, DATE_LONGDATE, NULL, NULL, szTime, sizeof(szTime) / sizeof(WCHAR));
    if (Length)
    {
        szTime[Length-1] = L',';
        szTime[Length++] = L' ';
    }
    Length = GetTimeFormatW(LOCALE_SYSTEM_DEFAULT, TIME_FORCE24HOURFORMAT|LOCALE_NOUSEROVERRIDE, NULL, NULL, &szTime[Length], (sizeof(szTime) / sizeof(WCHAR)));
    szTime[199] = L'\0';
    SendDlgItemMessageW(hwndDlg, IDC_STATIC_TIME, WM_SETTEXT, 0, (LPARAM)szTime);

    /* set computer name */
    szTime[0] = L'\0';
    Length = sizeof(szTime) / sizeof(WCHAR);
    if (GetComputerNameW(szTime, &Length))
        SendDlgItemMessageW(hwndDlg, IDC_STATIC_COMPUTER, WM_SETTEXT, 0, (LPARAM)szTime);

    /* set product name */
    if (GetOSVersion(szTime))
    {
        SendDlgItemMessage(hwndDlg, IDC_STATIC_OS, WM_SETTEXT, 0, (LPARAM)szTime);
    }
    else
    {
        if (LoadStringW(hInst, IDS_VERSION_UNKNOWN, szTime, sizeof(szTime) / sizeof(WCHAR)))
        {
            szTime[(sizeof(szTime) / sizeof(WCHAR))-1] = L'\0';
            SendDlgItemMessage(hwndDlg, IDC_STATIC_VERSION, WM_SETTEXT, 0, (LPARAM)szTime);
        }
    }

    /* FIXME set product language/local language */
    if (GetLocaleInfo(LOCALE_SYSTEM_DEFAULT,LOCALE_SLANGUAGE , szTime, sizeof(szTime) / sizeof(WCHAR)))
        SendDlgItemMessageW(hwndDlg, IDC_STATIC_LANG, WM_SETTEXT, 0, (LPARAM)szTime);

    /* set system manufacturer */
    szTime[0] = L'\0';
    if (GetRegValue(HKEY_LOCAL_MACHINE, L"Hardware\\Description\\System\\BIOS", L"SystemManufacturer", REG_SZ, szTime, sizeof(szTime)))
    {
        szTime[199] = L'\0';
        SendDlgItemMessageW(hwndDlg, IDC_STATIC_MANU, WM_SETTEXT, 0, (LPARAM)szTime);
    }

    /* set motherboard model */
    szTime[0] = L'\0';
    if (GetRegValue(HKEY_LOCAL_MACHINE, L"Hardware\\Description\\System\\BIOS", L"SystemProductName", REG_SZ, szTime, sizeof(szTime)))
    {
        SendDlgItemMessageW(hwndDlg, IDC_STATIC_MODEL, WM_SETTEXT, 0, (LPARAM)szTime);
    }

    /* set bios model */
    szTime[0] = L'\0';
    if (GetRegValue(HKEY_LOCAL_MACHINE, L"Hardware\\Description\\System\\BIOS", L"BIOSVendor", REG_SZ, szTime, sizeof(szTime)))
    {
        DWORD Index;
        DWORD StrLength = (sizeof(szTime) / sizeof(WCHAR));

        Index = wcslen(szTime);
        StrLength -= Index;

        if (GetRegValue(HKEY_LOCAL_MACHINE, L"Hardware\\Description\\System\\BIOS", L"BIOSReleaseDate", REG_SZ, &szTime[Index], StrLength))
        {
            if (Index + StrLength > (sizeof(szTime)/sizeof(WCHAR))- 15)
            {
                //FIXME  retrieve BiosMajorRelease, BiosMinorRelease
                //StrLength = wcslen(&szTime[Index]);
                //szTime[Index+StrLength] = L' ';
                //wcscpy(&szTime[Index+StrLength], L"Ver: "); //FIXME NON-NLS
                //szTime[(sizeof(szTime)/sizeof(WCHAR))-1] = L'\0';
            }
            SendDlgItemMessageW(hwndDlg, IDC_STATIC_BIOS, WM_SETTEXT, 0, (LPARAM)szTime);
        }
    }
    /* set processor string */
    if (GetRegValue(HKEY_LOCAL_MACHINE, L"Hardware\\Description\\System\\CentralProcessor\\0", L"ProcessorNameString", REG_SZ, szDesc, sizeof(szDesc)))
    {
        /* FIXME retrieve current speed */
        szFormat[0] = L'\0';
        GetSystemInfo(&SysInfo);
        if (SysInfo.dwNumberOfProcessors > 1)
            LoadStringW(hInst, IDS_FORMAT_MPPROC, szFormat, sizeof(szFormat) / sizeof(WCHAR));
        else
            LoadStringW(hInst, IDS_FORMAT_UNIPROC, szFormat, sizeof(szFormat) / sizeof(WCHAR));

        szFormat[(sizeof(szFormat)/sizeof(WCHAR))-1] = L'\0';
        wsprintfW(szTime, szFormat, szDesc, SysInfo.dwNumberOfProcessors);
        SendDlgItemMessageW(hwndDlg, IDC_STATIC_PROC, WM_SETTEXT, 0, (LPARAM)szTime);
    }

    /* retrieve available memory */
    ZeroMemory(&mem, sizeof(mem));
    mem.dwLength = sizeof(mem);
    if (GlobalMemoryStatusEx(&mem))
    {
        if (LoadStringW(hInst, IDS_FORMAT_MB, szFormat, sizeof(szFormat) / sizeof(WCHAR)))
        {
            /* set total mem string */
            szFormat[(sizeof(szFormat) / sizeof(WCHAR))-1] = L'\0';
            wsprintfW(szTime, szFormat, (mem.ullTotalPhys/1048576));
            SendDlgItemMessageW(hwndDlg, IDC_STATIC_MEM, WM_SETTEXT, 0, (LPARAM)szTime);
        }

        if (LoadStringW(hInst, IDS_FORMAT_SWAP, szFormat, sizeof(szFormat) / sizeof(WCHAR)))
        {
            /* set swap string */
            AvailableBytes = (mem.ullTotalPageFile-mem.ullTotalPhys)/1048576;
            UsedBytes = (mem.ullTotalPageFile-mem.ullAvailPageFile)/1048576;

            szFormat[(sizeof(szFormat) / sizeof(WCHAR))-1] = L'\0';
            wsprintfW(szTime, szFormat, (UsedBytes), (AvailableBytes));
            SendDlgItemMessageW(hwndDlg, IDC_STATIC_SWAP, WM_SETTEXT, 0, (LPARAM)szTime);
        }
    }
    /* set directx version string */
    wcscpy(szTime, L"ReactX ");
    if (GetDirectXVersion(&szTime[7]))
    {
        SendDlgItemMessage(hwndDlg, IDC_STATIC_VERSION, WM_SETTEXT, 0, (LPARAM)szTime);
    }
    else
    {
        if (LoadStringW(hInst, IDS_VERSION_UNKNOWN, szTime, sizeof(szTime) / sizeof(WCHAR)))
        {
            szTime[(sizeof(szTime) / sizeof(WCHAR))-1] = L'\0';
            SendDlgItemMessage(hwndDlg, IDC_STATIC_VERSION, WM_SETTEXT, 0, (LPARAM)szTime);
        }
    }
}
Exemple #3
0
/* base::Sys.info */
SEXP do_sysinfo(SEXP call, SEXP op, SEXP args, SEXP rho)
{
    SEXP ans, ansnames;
    OSVERSIONINFOEX osvi;
    char ver[256], buf[1000];
    wchar_t name[MAX_COMPUTERNAME_LENGTH + 1], user[UNLEN+1];
    DWORD namelen = MAX_COMPUTERNAME_LENGTH + 1, userlen = UNLEN+1;

    checkArity(op, args);
    PROTECT(ans = allocVector(STRSXP, 8));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
    if(!GetVersionEx((OSVERSIONINFO *)&osvi))
	error(_("unsupported version of Windows"));

    SET_STRING_ELT(ans, 0, mkChar("Windows"));

    /* Here for unknown future versions */
    snprintf(ver, 256, "%d.%d", 
	     (int)osvi.dwMajorVersion, (int)osvi.dwMinorVersion);

    if((int)osvi.dwMajorVersion >= 5) {
	PGNSI pGNSI;
	SYSTEM_INFO si;
	if(osvi.dwMajorVersion == 6) {
	    if(osvi.wProductType == VER_NT_WORKSTATION) {
		if(osvi.dwMinorVersion == 0)
		    strcpy(ver, "Vista");
		else strcpy(ver, "7");
	    } else
		strcpy(ver, "Server 2008");
	}
	if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
	    strcpy(ver, "2000");
	if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
	    strcpy(ver, "XP");
	if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) {
	    if(osvi.wProductType == VER_NT_WORKSTATION)
		strcpy(ver, "XP Professional");
	    else strcpy(ver, "Server 2003");
	}
	/* GetNativeSystemInfo is XP or later */
	pGNSI = (PGNSI)
	    GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")),
			   "GetNativeSystemInfo");
	if(NULL != pGNSI) pGNSI(&si); else GetSystemInfo(&si);
	if(si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
	    strcat(ver, " x64");
    }
    SET_STRING_ELT(ans, 1, mkChar(ver));

    if((int)osvi.dwMajorVersion >= 5) {
	if(osvi.wServicePackMajor > 0)
	    snprintf(ver, 256, "build %d, Service Pack %d",
		     LOWORD(osvi.dwBuildNumber),
		     (int) osvi.wServicePackMajor);
	else snprintf(ver, 256, "build %d", LOWORD(osvi.dwBuildNumber));
    } else
	snprintf(ver, 256, "build %d, %s",
		 LOWORD(osvi.dwBuildNumber), osvi.szCSDVersion);
    SET_STRING_ELT(ans, 2, mkChar(ver));
    GetComputerNameW(name, &namelen);
    wcstoutf8(buf, name, 1000);
    SET_STRING_ELT(ans, 3, mkCharCE(buf, CE_UTF8));
#ifdef _WIN64
    SET_STRING_ELT(ans, 4, mkChar("x86-64"));
#else
    SET_STRING_ELT(ans, 4, mkChar("x86"));
#endif
    GetUserNameW(user, &userlen);
    wcstoutf8(buf, user, 1000);
    SET_STRING_ELT(ans, 5, mkCharCE(buf, CE_UTF8));
    SET_STRING_ELT(ans, 6, STRING_ELT(ans, 5));
    SET_STRING_ELT(ans, 7, STRING_ELT(ans, 5));
    PROTECT(ansnames = allocVector(STRSXP, 8));
    SET_STRING_ELT(ansnames, 0, mkChar("sysname"));
    SET_STRING_ELT(ansnames, 1, mkChar("release"));
    SET_STRING_ELT(ansnames, 2, mkChar("version"));
    SET_STRING_ELT(ansnames, 3, mkChar("nodename"));
    SET_STRING_ELT(ansnames, 4, mkChar("machine"));
    SET_STRING_ELT(ansnames, 5, mkChar("login"));
    SET_STRING_ELT(ansnames, 6, mkChar("user"));
    SET_STRING_ELT(ansnames, 7, mkChar("effective_user"));
    setAttrib(ans, R_NamesSymbol, ansnames);
    UNPROTECT(2);
    return ans;
}
Exemple #4
0
/**
 @brief 
 @param numWorkThread 0이면 시스템 코어에 맞춰 자동
*/
void XEWinSocketSvr::Create( WORD port, int numWorkThread )
{
	XBREAK( port == 0 );
	if( XWinNetwork::sStartUp() == false ) {
		XALERT( "WSAStartup failed" );
		return;
	}
	//
//	m_Socket = socket( AF_INET, SOCK_STREAM, 0 );
	m_Socket = WSASocket( PF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED );
	if( m_Socket == INVALID_SOCKET ) {
		XALERT( "create socket failed" );
		return;
	}
	SOCKADDR_IN addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons( port );
	addr.sin_addr.S_un.S_addr = htonl( INADDR_ANY );
	if( bind( m_Socket, ( struct sockaddr * )&addr, sizeof( addr ) ) == SOCKET_ERROR ) {
		XBREAK(1);
		XALERT( "Network bind error" );
		Destroy();
		return;
	}
	//
	m_Port = port;
	// 클라로부터 접속을 받을 준비
	if( listen( m_Socket, SOMAXCONN ) == SOCKET_ERROR ) {
		XALERT( "Network::listen error" );
		Destroy();
		return;
	}
	//
	m_pUserMng = CreateUserMng( m_maxConnect );
	XBREAK( m_pUserMng == NULL );
	// 유저 커스텀 create
	OnCreate(); // virtual
	// IOCP 객체 생성
	m_hIOCP = CreateIoCompletionPort( INVALID_HANDLE_VALUE, NULL, 0, 0 ); 
	// 워커 스레드 생성
	SYSTEM_INFO si;
	memset( &si, 0, sizeof(si));
	GetSystemInfo( &si );
#if defined(_DEBUG) && !defined(_XBOT)
	const int numThread = 4;		// 개발중엔 편의상 스레드 적게쓴다.
#else
	const int numThread = (numWorkThread == 0)? 
														(int)(si.dwNumberOfProcessors * 2)
													: numWorkThread;
#endif
	XBREAK( numThread <= 0 || numThread > 32 );
	for( int i = 0; i < numThread; ++i ) {
		m_aryThreadWork.push_back( CreateWorkThread() );
	}
	// accept( 클라이언트로부터의 접속대기 ) 스레드 생성
	m_thAccept = CreateAcceptThread();
	//
#if _DEV_LEVEL <= DLV_OPEN_BETA
	m_timerSec.Set( 1.f );
#endif
}
Exemple #5
0
void FeedbackDialog::GenerateSpecs()
{
    // Gather some information about the system and embed it into the report
    QDesktopWidget* screen = QApplication::desktop();
    QString os_version = "Operating system: ";
    QString qt_version = QString("Qt version: ") + QT_VERSION_STR + QString("\n");
    QString total_ram = "Total RAM: ";
    QString number_of_cores = "Number of cores: ";
    QString compiler_bits = "Compiler architecture: ";
    QString compiler_version = "Compiler version: ";
    QString kernel_line = "Kernel: ";
    QString screen_size = "Size of the screen(s): " +
        QString::number(screen->width()) + "x" + QString::number(screen->height()) + "\n";
    QString number_of_screens = "Number of screens: " + QString::number(screen->screenCount()) + "\n";
    QString processor_name = "Processor: ";

    // platform specific code
#ifdef Q_OS_MACX
    number_of_cores += QString::number(sysconf(_SC_NPROCESSORS_ONLN)) + "\n";

    uint64_t memsize;
    size_t len = sizeof(memsize);
    static int mib_s[2] = { CTL_HW, HW_MEMSIZE };
    if (sysctl (mib_s, 2, &memsize, &len, NULL, 0) == 0)
        total_ram += QString::number(memsize/1024/1024) + " MB\n";
    else
        total_ram += "Error getting total RAM information\n";

    int mib[] = {CTL_KERN, KERN_OSRELEASE};
    sysctl(mib, sizeof mib / sizeof(int), NULL, &len, NULL, 0);

    char *kernelVersion = (char *)malloc(sizeof(char)*len);
    sysctl(mib, sizeof mib / sizeof(int), kernelVersion, &len, NULL, 0);

    QString kernelVersionStr = QString(kernelVersion);
    free(kernelVersion);
    int major_version = kernelVersionStr.split(".").first().toUInt() - 4;
    int minor_version = kernelVersionStr.split(".").at(1).toUInt();
    os_version += QString("Mac OS X 10.%1.%2").arg(major_version).arg(minor_version) + " ";

    switch(major_version)
    {
        case 4:  os_version += "\"Tiger\"\n"; break;
        case 5:  os_version += "\"Leopard\"\n"; break;
        case 6:  os_version += "\"Snow Leopard\"\n"; break;
        case 7:  os_version += "\"Lion\"\n"; break;
        case 8:  os_version += "\"Mountain Lion\"\n"; break;
        default: os_version += "\"Unknown version\"\n"; break;
    }
#endif
#ifdef Q_OS_WIN
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    number_of_cores += QString::number(sysinfo.dwNumberOfProcessors) + "\n";
    MEMORYSTATUSEX status;
    status.dwLength = sizeof(status);
    GlobalMemoryStatusEx(&status);
    total_ram += QString::number(status.ullTotalPhys/1024/1024) + " MB\n";

    switch(QSysInfo::windowsVersion())
    {
        case QSysInfo::WV_NT: os_version += "Windows NT\n"; break;
        case QSysInfo::WV_2000: os_version += "Windows 2000\n"; break;
        case QSysInfo::WV_XP: os_version += "Windows XP\n"; break;
        case QSysInfo::WV_2003: os_version += "Windows Server 2003\n"; break;
        case QSysInfo::WV_VISTA: os_version += "Windows Vista\n"; break;
        case QSysInfo::WV_WINDOWS7: os_version += "Windows 7\n"; break;
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
        case QSysInfo::WV_WINDOWS8: os_version += "Windows 8\n"; break;
#endif
        default: os_version += "Windows (Unknown version)\n"; break;
    }
    kernel_line += "Windows kernel\n";
#endif
#ifdef Q_OS_LINUX
    number_of_cores += QString::number(sysconf(_SC_NPROCESSORS_ONLN)) + "\n";
    quint32 pages = sysconf(_SC_PHYS_PAGES);
    quint32 page_size = sysconf(_SC_PAGE_SIZE);
    quint32 total = pages * page_size / 1024 / 1024;
    total_ram += QString::number(total) + " MB\n";
    os_version += "GNU/Linux or BSD\n";
#endif

    // uname -a
#if defined(Q_OS_LINUX) || defined(Q_OS_MAC)
    QProcess *process = new QProcess();
    QStringList arguments = QStringList("-a");
    process->start("uname", arguments);
    if (process->waitForFinished())
        kernel_line += QString(process->readAll());
    delete process;
#endif

#if (defined(Q_OS_WIN) && defined(__i386__)) || defined(__x86_64__)
    // cpu info
    quint32 registers[4];
    quint32 i;

    i = 0x80000002;
    asm volatile
      ("cpuid" : "=a" (registers[0]), "=b" (registers[1]), "=c" (registers[2]), "=d" (registers[3])
       : "a" (i), "c" (0));
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[0]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[1]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[2]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[3]), 4);
    i = 0x80000003;
    asm volatile
      ("cpuid" : "=a" (registers[0]), "=b" (registers[1]), "=c" (registers[2]), "=d" (registers[3])
       : "a" (i), "c" (0));
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[0]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[1]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[2]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[3]), 4);
    i = 0x80000004;
    asm volatile
      ("cpuid" : "=a" (registers[0]), "=b" (registers[1]), "=c" (registers[2]), "=d" (registers[3])
       : "a" (i), "c" (0));
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[0]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[1]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[2]), 4);
    processor_name += QByteArray(reinterpret_cast<char*>(&registers[3]), 4);
    processor_name += "\n";
#else
    processor_name += "Unknown";
#endif

    // compiler
#ifdef __GNUC__
    compiler_version += "GCC " + QString(__VERSION__) + "\n";
#else
    compiler_version += "Unknown\n";
#endif

    if(sizeof(void*) == 4)
        compiler_bits += "i386\n";
    else if(sizeof(void*) == 8)
        compiler_bits += "x86_64\n";

    // concat system info
    specs = qt_version
        + os_version
        + total_ram
        + screen_size
        + number_of_screens
        + processor_name
        + number_of_cores
        + compiler_version
        + compiler_bits
        + kernel_line;
}
Exemple #6
0
APR_DECLARE(apr_status_t) apr_shm_create_ex(apr_shm_t **m,
                                            apr_size_t reqsize,
                                            const char *file,
                                            apr_pool_t *pool,
                                            apr_int32_t flags)
{
    static apr_size_t memblock = 0;
    HANDLE hMap, hFile;
    apr_status_t rv;
    apr_size_t size;
    apr_file_t *f;
    void *base;
    void *mapkey;
    DWORD err, sizelo, sizehi;

    reqsize += sizeof(memblock_t);

    if (!memblock)
    {
        SYSTEM_INFO si;
        GetSystemInfo(&si);
        memblock = si.dwAllocationGranularity;
    }   

    /* Compute the granualar multiple of the pagesize */
    size = memblock * (1 + (reqsize - 1) / memblock);
    sizelo = (DWORD)size;
#ifdef _WIN64
    sizehi = (DWORD)(size >> 32);
#else
    sizehi = 0;
#endif

    if (!file) {
        /* Do Anonymous, which must be passed as a duplicated handle */
#ifndef _WIN32_WCE
        hFile = INVALID_HANDLE_VALUE;
#endif
        mapkey = NULL;
    }
    else {
        int global;

        /* Do file backed, which is not an inherited handle 
         * While we could open APR_FOPEN_EXCL, it doesn't seem that Unix
         * ever did.  Ignore that error here, but fail later when
         * we discover we aren't the creator of the file map object.
         */
        rv = apr_file_open(&f, file,
                           APR_FOPEN_READ | APR_FOPEN_WRITE | APR_FOPEN_BINARY | APR_FOPEN_CREATE,
                           APR_FPROT_UREAD | APR_FPROT_UWRITE, pool);
        if ((rv != APR_SUCCESS)
                || ((rv = apr_os_file_get(&hFile, f)) != APR_SUCCESS)) {
            return rv;
        }
        rv = apr_file_trunc(f, size);

        /* res_name_from_filename turns file into a pseudo-name
         * without slashes or backslashes, and prepends the \global
         * or \local prefix on Win2K and later
         */
        if (flags & APR_SHM_NS_GLOBAL) {
            global = 1;
        }
        else if (flags & APR_SHM_NS_LOCAL) {
            global = 0;
        }
        else {
            global = can_create_global_maps();
        }
        mapkey = res_name_from_filename(file, global, pool);
    }

#if APR_HAS_UNICODE_FS
    IF_WIN_OS_IS_UNICODE
    {
        hMap = CreateFileMappingW(hFile, NULL, PAGE_READWRITE, 
                                  sizehi, sizelo, mapkey);
    }
#endif
#if APR_HAS_ANSI_FS
    ELSE_WIN_OS_IS_ANSI
    {
        hMap = CreateFileMappingA(hFile, NULL, PAGE_READWRITE, 
                                  sizehi, sizelo, mapkey);
    }
#endif
    err = apr_get_os_error();

    if (file) {
        apr_file_close(f);
    }

    if (hMap && APR_STATUS_IS_EEXIST(err)) {
        CloseHandle(hMap);
        return APR_EEXIST;
    }
    if (!hMap) {
        return err;
    }
    
    base = MapViewOfFile(hMap, FILE_MAP_READ | FILE_MAP_WRITE,
                         0, 0, size);
    if (!base) {
        CloseHandle(hMap);
        return apr_get_os_error();
    }
    
    *m = (apr_shm_t *) apr_palloc(pool, sizeof(apr_shm_t));
    (*m)->pool = pool;
    (*m)->hMap = hMap;
    (*m)->memblk = base;
    (*m)->size = size;

    (*m)->usrmem = (char*)base + sizeof(memblock_t);
    (*m)->length = reqsize - sizeof(memblock_t);;
    
    (*m)->memblk->length = (*m)->length;
    (*m)->memblk->size = (*m)->size;
    (*m)->filename = file ? apr_pstrdup(pool, file) : NULL;

    apr_pool_cleanup_register((*m)->pool, *m, 
                              shm_cleanup, apr_pool_cleanup_null);
    return APR_SUCCESS;
}
void MarkStack::initializePagesize()
{
    SYSTEM_INFO system_info;
    GetSystemInfo(&system_info);
    MarkStack::s_pageSize = system_info.dwPageSize;
}
Exemple #8
0
// Проверить, валиден ли модуль?
bool IsModuleValid(HMODULE module, BOOL abTestVirtual /*= TRUE*/)
{
	if ((module == NULL) || (module == INVALID_HANDLE_VALUE))
		return false;
	if (LDR_IS_RESOURCE(module))
		return false;

	bool lbValid = true;
	#ifdef USE_SEH
	IMAGE_DOS_HEADER dos;
	IMAGE_NT_HEADERS nt;
	#endif

	static bool bSysInfoRetrieved = false;
	static SYSTEM_INFO si = {};
	if (!bSysInfoRetrieved)
	{
		GetSystemInfo(&si);
		bSysInfoRetrieved = true;
	}

	LPBYTE lpTest;
	SIZE_T cbCommitSize = max(max(4096,sizeof(IMAGE_DOS_HEADER)),si.dwPageSize);

	// If module is hooked by ConEmuHk, we get excess debug "assertion" from ConEmu.dll (Far plugin)
	if (abTestVirtual)
	{
		// Issue 881
		lpTest = (LPBYTE)VirtualAlloc((LPVOID)module, cbCommitSize, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
		if (lpTest)
		{
			// If we can lock mem region with (IMAGE_DOS_HEADER) of checking module
			if ((lpTest <= (LPBYTE)module) && ((lpTest + cbCommitSize) >= (((LPBYTE)module) + sizeof(IMAGE_DOS_HEADER))))
			{
				// That means, it was unloaded
				lbValid = false;
			}
			VirtualFree(lpTest, 0, MEM_RELEASE);

			if (!lbValid)
				goto wrap;
		}
		else
		{
			// Memory is used (supposing by module)
		}
	}

#ifdef USE_SEH
	SAFETRY
	{
		memmove(&dos, (void*)module, sizeof(dos));
		if (dos.e_magic != IMAGE_DOS_SIGNATURE /*'ZM'*/)
		{
			lbValid = false;
		}
		else
		{
			memmove(&nt, (IMAGE_NT_HEADERS*)((char*)module + ((IMAGE_DOS_HEADER*)module)->e_lfanew), sizeof(nt));
			if (nt.Signature != 0x004550)
				lbValid = false;
		}
	}
	SAFECATCH
	{
		lbValid = false;
	}

#else
	if (IsBadReadPtr((void*)module, sizeof(IMAGE_DOS_HEADER)))
	{
		lbValid = false;
	}
	else if (((IMAGE_DOS_HEADER*)module)->e_magic != IMAGE_DOS_SIGNATURE /*'ZM'*/)
	{
		lbValid = false;
	}
	else
	{
		IMAGE_NT_HEADERS* nt_header = (IMAGE_NT_HEADERS*)((char*)module + ((IMAGE_DOS_HEADER*)module)->e_lfanew);
		if (IsBadReadPtr(nt_header, sizeof(IMAGE_NT_HEADERS)))
		{
			lbValid = false;
		}
		else if (nt_header->Signature != 0x004550)
		{
			return false;
		}
	}
#endif

wrap:
	return lbValid;
}
Exemple #9
0
CAMLprim value caml_ba_map_file(value vfd, value vkind, value vlayout,
                                value vshared, value vdim, value vstart)
{
  HANDLE fd, fmap;
  int flags, major_dim, mode, perm;
  intnat num_dims, i;
  intnat dim[MAX_NUM_DIMS];
  __int64 currpos, startpos, file_size, data_size;
  uintnat array_size, page, delta;
  char c;
  void * addr;
  LARGE_INTEGER li;
  SYSTEM_INFO sysinfo;

  fd = Handle_val(vfd);
  flags = Int_val(vkind) | Int_val(vlayout);
  startpos = Int64_val(vstart);
  num_dims = Wosize_val(vdim);
  major_dim = flags & BIGARRAY_FORTRAN_LAYOUT ? num_dims - 1 : 0;
  /* Extract dimensions from Caml array */
  num_dims = Wosize_val(vdim);
  if (num_dims < 1 || num_dims > MAX_NUM_DIMS)
    invalid_argument("Bigarray.mmap: bad number of dimensions");
  for (i = 0; i < num_dims; i++) {
    dim[i] = Long_val(Field(vdim, i));
    if (dim[i] == -1 && i == major_dim) continue;
    if (dim[i] < 0 || dim[i] > 0x7FFFFFFFL)
      invalid_argument("Bigarray.create: negative dimension");
  }
  /* Determine file size */
  currpos = caml_ba_set_file_pointer(fd, 0, FILE_CURRENT);
  if (currpos == -1) caml_ba_sys_error();
  file_size = caml_ba_set_file_pointer(fd, 0, FILE_END);
  if (file_size == -1) caml_ba_sys_error();
  /* Determine array size in bytes (or size of array without the major
     dimension if that dimension wasn't specified) */
  array_size = bigarray_element_size[flags & BIGARRAY_KIND_MASK];
  for (i = 0; i < num_dims; i++)
    if (dim[i] != -1) array_size *= dim[i];
  /* Check if the first/last dimension is unknown */
  if (dim[major_dim] == -1) {
    /* Determine first/last dimension from file size */
    if (file_size < startpos)
      failwith("Bigarray.mmap: file position exceeds file size");
    data_size = file_size - startpos;
    dim[major_dim] = (uintnat) (data_size / array_size);
    array_size = dim[major_dim] * array_size;
    if (array_size != data_size)
      failwith("Bigarray.mmap: file size doesn't match array dimensions");
  }
  /* Restore original file position */
  caml_ba_set_file_pointer(fd, currpos, FILE_BEGIN);
  /* Create the file mapping */
  if (Bool_val(vshared)) {
    perm = PAGE_READWRITE;
    mode = FILE_MAP_WRITE;
  } else {
    perm = PAGE_READONLY;       /* doesn't work under Win98 */
    mode = FILE_MAP_COPY;
  }
  li.QuadPart = startpos + array_size;
  fmap = CreateFileMapping(fd, NULL, perm, li.HighPart, li.LowPart, NULL);
  if (fmap == NULL) caml_ba_sys_error();
  /* Determine offset so that the mapping starts at the given file pos */
  GetSystemInfo(&sysinfo);
  delta = (uintnat) (startpos % sysinfo.dwPageSize);
  /* Map the mapping in memory */
  li.QuadPart = startpos - delta;
  addr = 
    MapViewOfFile(fmap, mode, li.HighPart, li.LowPart, array_size + delta);
  if (addr == NULL) caml_ba_sys_error();
  addr = (void *) ((uintnat) addr + delta);
  /* Close the file mapping */
  CloseHandle(fmap);
  /* Build and return the Caml bigarray */
  return alloc_bigarray(flags | BIGARRAY_MAPPED_FILE, num_dims, addr, dim);
}
Exemple #10
0
void
TclpSetVariables(
    Tcl_Interp *interp)		/* Interp to initialize. */
{
    const char *ptr;
    char buffer[TCL_INTEGER_SPACE * 2];
    SYSTEM_INFO sysInfo, *sysInfoPtr = &sysInfo;
    OemId *oemId;
    OSVERSIONINFOA osInfo;
    Tcl_DString ds;
    WCHAR szUserName[UNLEN+1];
    DWORD cchUserNameLen = UNLEN;

    Tcl_SetVar2Ex(interp, "tclDefaultLibrary", NULL,
	    TclGetProcessGlobalValue(&defaultLibraryDir), TCL_GLOBAL_ONLY);

    osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
    GetVersionExA(&osInfo);

    oemId = (OemId *) sysInfoPtr;
    GetSystemInfo(&sysInfo);

    /*
     * Define the tcl_platform array.
     */

    Tcl_SetVar2(interp, "tcl_platform", "platform", "windows",
	    TCL_GLOBAL_ONLY);
    if (osInfo.dwPlatformId < NUMPLATFORMS) {
	Tcl_SetVar2(interp, "tcl_platform", "os",
		platforms[osInfo.dwPlatformId], TCL_GLOBAL_ONLY);
    }
    wsprintfA(buffer, "%d.%d", osInfo.dwMajorVersion, osInfo.dwMinorVersion);
    Tcl_SetVar2(interp, "tcl_platform", "osVersion", buffer, TCL_GLOBAL_ONLY);
    if (oemId->wProcessorArchitecture < NUMPROCESSORS) {
	Tcl_SetVar2(interp, "tcl_platform", "machine",
		processors[oemId->wProcessorArchitecture],
		TCL_GLOBAL_ONLY);
    }

#ifdef _DEBUG
    /*
     * The existence of the "debug" element of the tcl_platform array
     * indicates that this particular Tcl shell has been compiled with debug
     * information. Using "info exists tcl_platform(debug)" a Tcl script can
     * direct the interpreter to load debug versions of DLLs with the load
     * command.
     */

    Tcl_SetVar2(interp, "tcl_platform", "debug", "1",
	    TCL_GLOBAL_ONLY);
#endif

    /*
     * Set up the HOME environment variable from the HOMEDRIVE & HOMEPATH
     * environment variables, if necessary.
     */

    Tcl_DStringInit(&ds);
    ptr = Tcl_GetVar2(interp, "env", "HOME", TCL_GLOBAL_ONLY);
    if (ptr == NULL) {
	ptr = Tcl_GetVar2(interp, "env", "HOMEDRIVE", TCL_GLOBAL_ONLY);
	if (ptr != NULL) {
	    Tcl_DStringAppend(&ds, ptr, -1);
	}
	ptr = Tcl_GetVar2(interp, "env", "HOMEPATH", TCL_GLOBAL_ONLY);
	if (ptr != NULL) {
	    Tcl_DStringAppend(&ds, ptr, -1);
	}
	if (Tcl_DStringLength(&ds) > 0) {
	    Tcl_SetVar2(interp, "env", "HOME", Tcl_DStringValue(&ds),
		    TCL_GLOBAL_ONLY);
	} else {
	    Tcl_SetVar2(interp, "env", "HOME", "c:\\", TCL_GLOBAL_ONLY);
	}
    }

    /*
     * Initialize the user name from the environment first, since this is much
     * faster than asking the system.
     * Note: cchUserNameLen is number of characters including nul terminator.
     */

    Tcl_DStringInit(&ds);
    if (TclGetEnv("USERNAME", &ds) == NULL) {
	if (tclWinProcs->getUserName((LPTSTR)szUserName, &cchUserNameLen) != 0) {
	    int cbUserNameLen = cchUserNameLen - 1;
	    if (tclWinProcs->useWide) cbUserNameLen *= sizeof(WCHAR);
	    Tcl_WinTCharToUtf((LPTSTR)szUserName, cbUserNameLen, &ds);
	}
    }
    Tcl_SetVar2(interp, "tcl_platform", "user", Tcl_DStringValue(&ds),
	    TCL_GLOBAL_ONLY);
    Tcl_DStringFree(&ds);

    /*
     * Define what the platform PATH separator is. [TIP #315]
     */

    Tcl_SetVar2(interp, "tcl_platform","pathSeparator", ";", TCL_GLOBAL_ONLY);
}
// static
int Thread::GetCPUCount()
{
    SYSTEM_INFO sysInfo;
    GetSystemInfo(&sysInfo);
    return (int) sysInfo.dwNumberOfProcessors;
}
Exemple #12
0
/**
 * Print out the Windows version information
 * @return A string with the windows version, this needs to be free'd
 */
char *GetWindowsVersion(void)
{
    OSVERSIONINFOEX osvi;
    BOOL bOsVersionInfoEx;
    char buf[BUFSIZE];
    char *extra;
    char *cputype;
    SYSTEM_INFO si;

    ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
    ZeroMemory(&si, sizeof(SYSTEM_INFO));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

    if (!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *) & osvi))) {
        osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
        if (!GetVersionEx((OSVERSIONINFO *) & osvi)) {
            return sstrdup("");
        }
    }
    GetSystemInfo(&si);

    /* Determine CPU type 32 or 64 */
    if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {
        cputype = sstrdup(" 64-bit");
    } else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL) {
        cputype = sstrdup(" 32-bit");
    } else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) {
        cputype = sstrdup(" Itanium 64-bit");
    } else {
        cputype = sstrdup(" ");
    }

    switch (osvi.dwPlatformId) {
        /* test for the Windows NT product family. */
    case VER_PLATFORM_WIN32_NT:
        /* Windows Vista or Windows Server 2008 */
        if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0) {
            if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
                extra = sstrdup("Enterprise Edition");
            } else if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
                extra = sstrdup("Datacenter Edition");
            } else if (osvi.wSuiteMask & VER_SUITE_PERSONAL) {
                extra = sstrdup("Home Premium/Basic");
            } else {
                extra = sstrdup(" ");
            }
            if (osvi.wProductType & VER_NT_WORKSTATION) {
                ircsnprintf(buf, sizeof(buf),
                            "Microsoft Windows Vista %s%s", cputype,
                            extra);
            } else {
                ircsnprintf(buf, sizeof(buf),
                            "Microsoft Windows Server 2008 %s%s", cputype,
                            extra);
            }
            free(extra);
        }
        /* Windows 2003 or Windows XP Pro 64 */
        if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) {
            if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
                extra = sstrdup("Datacenter Edition");
            } else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
                extra = sstrdup("Enterprise Edition");
            } else if (osvi.wSuiteMask & VER_SUITE_COMPUTE_SERVER) {
                extra = sstrdup("Compute Cluster Edition");
            } else if (osvi.wSuiteMask == VER_SUITE_BLADE) {
                extra = sstrdup("Web Edition");
            } else {
                extra = sstrdup("Standard Edition");
            }
            if (osvi.wProductType & VER_NT_WORKSTATION
                && si.wProcessorArchitecture ==
                PROCESSOR_ARCHITECTURE_AMD64) {
                ircsnprintf(buf, sizeof(buf),
                            "Windows XP Professional x64 Edition %s",
                            extra);
            } else {
                ircsnprintf(buf, sizeof(buf),
                            "Microsoft Windows Server 2003 Family %s%s",
                            cputype, extra);
            }
            free(extra);
        }
        if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
            if (osvi.wSuiteMask & VER_SUITE_EMBEDDEDNT) {
                extra = sstrdup("Embedded");
            } else if (osvi.wSuiteMask & VER_SUITE_PERSONAL) {
                extra = sstrdup("Home Edition");
#ifdef SM_MEDIACENTER
            } else if (GetSystemMetrics(SM_MEDIACENTER)) {
                extra = sstrdup("Media Center Edition");
#endif
#ifdef SM_TABLETPC
            } else if (GetSystemMetrics(SM_TABLETPC)) {
                extra = sstrdup("Tablet Edition");
#endif
            } else {
                extra = sstrdup(" ");
            }
            ircsnprintf(buf, sizeof(buf), "Microsoft Windows XP %s",
                        extra);
            free(extra);
        }
        if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) {
            if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
                extra = sstrdup("Datacenter Server");
            } else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
                extra = sstrdup("Advanced Server");
            } else {
                extra = sstrdup("Server");
            }
            ircsnprintf(buf, sizeof(buf), "Microsoft Windows 2000 %s",
                        extra);
            free(extra);
        }
        if (osvi.dwMajorVersion <= 4) {
            if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
                extra = sstrdup("Server 4.0, Enterprise Edition");
            } else {
                extra = sstrdup("Server 4.0");
            }
            ircsnprintf(buf, sizeof(buf), "Microsoft Windows NT %s",
                        extra);
            free(extra);
        }
    case VER_PLATFORM_WIN32_WINDOWS:
        if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) {
            if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B') {
                extra = sstrdup("OSR2");
            } else {
                extra = sstrdup(" ");
            }
            ircsnprintf(buf, sizeof(buf), "Microsoft Windows 95 %s",
                        extra);
            free(extra);
        }
        if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) {
            if (osvi.szCSDVersion[1] == 'A') {
                extra = sstrdup("SE");
            } else {
                extra = sstrdup(" ");
            }
            ircsnprintf(buf, sizeof(buf), "Microsoft Windows 98 %s",
                        extra);
            free(extra);
        }
        if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) {
            ircsnprintf(buf, sizeof(buf),
                        "Microsoft Windows Millennium Edition");
        }
    }
    free(cputype);
    return sstrdup(buf);
}
Exemple #13
0
/*---------------------------------------------------------------------------*/
hg_return_t
hg_proc_set_size(hg_proc_t proc, hg_size_t req_buf_size)
{
    struct hg_proc *hg_proc = (struct hg_proc *) proc;
    hg_size_t new_buf_size;
    hg_size_t page_size;
    ptrdiff_t current_pos;
    hg_return_t ret = HG_SUCCESS;

#ifdef _WIN32
    SYSTEM_INFO system_info;
    GetSystemInfo(&system_info);
    page_size = system_info.dwPageSize;
#else
    page_size = sysconf(_SC_PAGE_SIZE);
#endif
    new_buf_size = ((hg_size_t)(req_buf_size / page_size) + 1) * page_size;

    if (new_buf_size <= hg_proc_get_size(proc)) {
        HG_LOG_ERROR("Buffer is already of the size requested");
        ret = HG_SIZE_ERROR;
        goto done;
    }

    /* If was not using extra buffer init extra buffer */
    if (!hg_proc->extra_buf.buf) {
        /* Save current position */
        current_pos = (char *) hg_proc->proc_buf.buf_ptr -
                (char *) hg_proc->proc_buf.buf;

        /* Allocate buffer */
        hg_proc->extra_buf.buf = malloc(new_buf_size);
        if (!hg_proc->extra_buf.buf) {
            HG_LOG_ERROR("Could not allocate buffer");
            ret = HG_NOMEM_ERROR;
            goto done;
        }

        /* Copy proc_buf (should be small) */
        memcpy(hg_proc->extra_buf.buf, hg_proc->proc_buf.buf, current_pos);
        hg_proc->extra_buf.size = new_buf_size;
        hg_proc->extra_buf.buf_ptr = (char *) hg_proc->extra_buf.buf + current_pos;
        hg_proc->extra_buf.size_left = hg_proc->extra_buf.size - current_pos;
        hg_proc->extra_buf.is_mine = 1;

        /* Switch buffer */
        hg_proc->current_buf = &hg_proc->extra_buf;
    } else {
        void *new_buf = NULL;

        /* Save current position */
        current_pos = (char *) hg_proc->extra_buf.buf_ptr - (char *) hg_proc->extra_buf.buf;

        /* Reallocate buffer */
        new_buf = realloc(hg_proc->extra_buf.buf, new_buf_size);
        if (!new_buf) {
            HG_LOG_ERROR("Could not reallocate buffer");
            ret = HG_NOMEM_ERROR;
            goto done;
        }
        hg_proc->extra_buf.buf = new_buf;
        hg_proc->extra_buf.size = new_buf_size;
        hg_proc->extra_buf.buf_ptr = (char *) hg_proc->extra_buf.buf + current_pos;
        hg_proc->extra_buf.size_left = hg_proc->extra_buf.size - current_pos;
    }

done:
    return ret;
}
QString DiagnosticsDialog::getProcessor() const
{
	SYSTEM_INFO sysinfo;
	GetSystemInfo( &sysinfo );
	return QString::number( sysinfo.dwProcessorType );
}
Exemple #15
0
int my_getpagesize(void)
{
    SYSTEM_INFO si;
    GetSystemInfo(&si);
    return si.dwPageSize;
}
Exemple #16
0
uv_err_t uv_cpu_info(uv_cpu_info_t** cpu_infos_ptr, int* cpu_count_ptr) {
  uv_cpu_info_t* cpu_infos;
  SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* sppi;
  DWORD sppi_size;
  SYSTEM_INFO system_info;
  DWORD cpu_count, r, i;
  NTSTATUS status;
  ULONG result_size;
  uv_err_t err;
  uv_cpu_info_t* cpu_info;

  cpu_infos = NULL;
  cpu_count = 0;
  sppi = NULL;


  GetSystemInfo(&system_info);
  cpu_count = system_info.dwNumberOfProcessors;

  cpu_infos = calloc(cpu_count, sizeof *cpu_infos);
  if (cpu_infos == NULL) {
    err = 0;
    goto error;
  }

  sppi_size = cpu_count * sizeof(*sppi);
  sppi = malloc(sppi_size);
  if (sppi == NULL) {
    err = 0;
    goto error;
  }

  status = pNtQuerySystemInformation(SystemProcessorPerformanceInformation,
                                     sppi,
                                     sppi_size,
                                     &result_size);
  if (!NT_SUCCESS(status)) {
    err = 0;
    goto error;
  }

  assert(result_size == sppi_size);

  for (i = 0; i < cpu_count; i++) {
    WCHAR key_name[128];
    HKEY processor_key;
    DWORD cpu_speed;
    DWORD cpu_speed_size = sizeof(cpu_speed);
    WCHAR cpu_brand[256];
    DWORD cpu_brand_size = sizeof(cpu_brand);
    int len;

    len = _snwprintf(key_name,
                     ARRAY_SIZE(key_name),
                     L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\%d",
                     i);

    assert(len > 0 && len < ARRAY_SIZE(key_name));

    r = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                      key_name,
                      0,
                      KEY_QUERY_VALUE,
                      &processor_key);
    if (r != ERROR_SUCCESS) {
      err = 0;
      goto error;
    }

    if (RegQueryValueExW(processor_key,
                         L"~MHz",
                         NULL,
                         NULL,
                         (BYTE*) &cpu_speed,
                         &cpu_speed_size) != ERROR_SUCCESS) {
      err = 0;
      RegCloseKey(processor_key);
      goto error;
    }

    if (RegQueryValueExW(processor_key,
                         L"ProcessorNameString",
                         NULL,
                         NULL,
                         (BYTE*) &cpu_brand,
                         &cpu_brand_size) != ERROR_SUCCESS) {
      err = 0;
      RegCloseKey(processor_key);
      goto error;
    }

    RegCloseKey(processor_key);

    cpu_info = &cpu_infos[i];
    cpu_info->speed = cpu_speed;
    cpu_info->cpu_times.user = sppi[i].UserTime.QuadPart / 10000;
    cpu_info->cpu_times.sys = (sppi[i].KernelTime.QuadPart -
        sppi[i].IdleTime.QuadPart) / 10000;
    cpu_info->cpu_times.idle = sppi[i].IdleTime.QuadPart / 10000;
    cpu_info->cpu_times.irq = sppi[i].InterruptTime.QuadPart / 10000;
    cpu_info->cpu_times.nice = 0;


    len = WideCharToMultiByte(CP_UTF8,
                              0,
                              cpu_brand,
                              cpu_brand_size / sizeof(WCHAR),
                              NULL,
                              0,
                              NULL,
                              NULL);
    if (len == 0) {
      err = 0;
      goto error;
    }

    assert(len > 0);

    /* Allocate 1 extra byte for the null terminator. */
    cpu_info->model = malloc(len + 1);
    if (cpu_info->model == NULL) {
      err = 0;
      goto error;
    }

    if (WideCharToMultiByte(CP_UTF8,
                            0,
                            cpu_brand,
                            cpu_brand_size / sizeof(WCHAR),
                            cpu_info->model,
                            len,
                            NULL,
                            NULL) == 0) {
      err = 0;
      goto error;
    }

    /* Ensure that cpu_info->model is null terminated. */
    cpu_info->model[len] = '\0';
  }

  free(sppi);

  *cpu_count_ptr = cpu_count;
  *cpu_infos_ptr = cpu_infos;

  return 1;

 error:
  /* This is safe because the cpu_infos array is zeroed on allocation. */
  for (i = 0; i < cpu_count; i++)
    free(cpu_infos[i].model);

  free(cpu_infos);
  free(sppi);

  return err;
}
Exemple #17
0
int _tmain(int /*argc*/, _TCHAR* /*argv*/[])
{
#ifdef _WIN64
	_tprintf( _T("Platform : 64-bit\n") );
#else
	_tprintf( _T("Platform : 32-bit\n") );
#endif

#ifdef _DEBUG
	_tprintf( _T("Build    : Debug\n") );
#else
	_tprintf( _T("Build    : Release\n") );
#endif

	SYSTEM_INFO si = {};
	GetSystemInfo( &si );
	_tprintf( _T("CPUs     : %u\n"), si.dwNumberOfProcessors );

	_tprintf( _T("\nHashWord() function tests:\n\n") );
	_tprintf( _T("Hash test 1... %s\n"),
		( HashWord( L"\x30a2\x30cb\x30e1", 0,  3, 10 ) ==  46 ) ? _T("OK") : _T("FAIL") );
	_tprintf( _T("Hash test 2... %s\n"),
		( HashWord( L"\x58f0\x512a",       0,  2, 10 ) == 731 ) ? _T("OK") : _T("FAIL") );
	_tprintf( _T("Hash test 3... %s\n"),
		( HashWord( L"\x0001\x0028",       0,  2, 10 ) == 658 ) ? _T("OK") : _T("FAIL") );
	_tprintf( _T("Hash test 4... %s\n"),
		( HashWord( L"\xff01\x9428",       0,  2, 10 ) == 658 ) ? _T("OK") : _T("FAIL") );
	_tprintf( _T("Hash test 5... %s\n"),
		( HashWord( L"\x0000",             0,  1, 10 ) ==   0 ) ? _T("OK") : _T("FAIL") );
	_tprintf( _T("Hash test 6... %s\n"),
		( HashWord( L"\x0001",             0,  1, 10 ) == 316 ) ? _T("OK") : _T("FAIL") );
	_tprintf( _T("Hash test 7... %s\n"),
		( HashWord( L"0123456789",         0, 10, 10 ) == 551 ) ? _T("OK") : _T("FAIL") );
// No UTF-32 support for unmanaged C++
//	_tprintf( _T("Hash test 8... %s\n"),
//		( HashWord( L"\x10400",            0,  1, 10 ) == 316 ) ? _T("OK") : _T("FAIL") );
//	_tprintf( _T("Hash test 9... %s\n"),
//		( HashWord( L"\x10428",            0,  1, 10 ) == 658 ) ? _T("OK") : _T("FAIL") );

	_tprintf( _T("\nMeasuring performance:\n\n") );

	const int nCount = 10;
	const __int64 nBlock = 100 * 1024 * 1024;	// 100 MB
	LPVOID pBuffer = VirtualAlloc( NULL, nBlock, MEM_COMMIT, PAGE_READWRITE );
	memset( pBuffer, 'A', nBlock );

	SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_HIGHEST );

	{
		__int64 nBest = -1, nError = 0, nFast = 0, n = 0;
		do
		{
			__int64 nWorst = 0;
			_tprintf( _T("HashWord : %I64d MB by "), nBlock / 1024 / 1024 );
			DWORD foo;
			for ( int i = 0; i < nCount; ++i )
			{
				const __int64 nBegin = GetMicroCount();
				foo = HashWord( (LPCTSTR)pBuffer, 0, nBlock / sizeof( TCHAR ) - 1, 20 );
				__int64 nTime = GetMicroCount() - nBegin;
				if ( nBest < 0 || nTime < nBest )
					nBest = nTime;
				if ( i == 0 || nTime > nWorst )
					nWorst = nTime;
				if ( foo != 901120 )
				{
					_tprintf( _T("FAILED! ") );
					break;
				}
			}
			nError = ( 100 * ( nWorst - nBest ) ) / nWorst;
			const __int64 nSpeed = ( nBlock * 1000000 ) / nBest;
			if ( nFast < nSpeed )
				nFast = nSpeed;
			_tprintf( _T("%3I64d ms (inaccuracy %2I64d%%), %3I64d MB/s        \r"),
				nBest / 1000, nError, nFast / ( 1024 * 1024 ) );
		} while ( nError > 5 && n++ < 10 );
	}
	_tprintf( _T("\n") );

	{
		__int64 nBest = -1, nError = 0, nFast = 0, n = 0;
		do
		{
			__int64 nWorst = 0;
			_tprintf( _T("MD4  hash: %I64d MB by "), nBlock / 1024 / 1024 );
			for ( int i = 0; i < nCount; ++i )
			{
				const __int64 nBegin = GetMicroCount();
				CMD4 pMD4;
				pMD4.Add( pBuffer, nBlock );
				pMD4.Finish();
				__int64 nTime = GetMicroCount() - nBegin;
				if ( nBest < 0 || nTime < nBest )
					nBest = nTime;
				if ( i == 0 || nTime > nWorst )
					nWorst = nTime;
			}
			nError = ( 100 * ( nWorst - nBest ) ) / nWorst;
			const __int64 nSpeed = ( nBlock * 1000000 ) / nBest;
			if ( nFast < nSpeed )
				nFast = nSpeed;
			_tprintf( _T("%3I64d ms (inaccuracy %2I64d%%), %3I64d MB/s        \r"),
				nBest / 1000, nError, nFast / ( 1024 * 1024 ) );
		} while ( nError > 5 && n++ < 10 );
	}
	_tprintf( _T("\n") );

	{
		__int64 nBest = -1, nError = 0, nFast = 0, n = 0;
		do
		{
			__int64 nWorst = 0;
			_tprintf( _T("MD5  hash: %I64d MB by "), nBlock / 1024 / 1024 );
			for ( int i = 0; i < nCount; ++i )
			{
				const __int64 nBegin = GetMicroCount();
				CMD5 pMD5;
				pMD5.Add( pBuffer, nBlock );
				pMD5.Finish();
				__int64 nTime = GetMicroCount() - nBegin;
				if ( nBest < 0 || nTime < nBest )
					nBest = nTime;
				if ( i == 0 || nTime > nWorst )
					nWorst = nTime;
			}
			nError = ( 100 * ( nWorst - nBest ) ) / nWorst;
			const __int64 nSpeed = ( nBlock * 1000000 ) / nBest;
			if ( nFast < nSpeed )
				nFast = nSpeed;
			_tprintf( _T("%3I64d ms (inaccuracy %2I64d%%), %3I64d MB/s        \r"),
				nBest / 1000, nError, nFast / ( 1024 * 1024 ) );
		} while ( nError > 5 && n++ < 10 );
	}
	_tprintf( _T("\n") );

	{
		__int64 nBest = -1, nError = 0, nFast = 0, n = 0;
		do
		{
			__int64 nWorst = 0;
			_tprintf( _T("SHA1 hash: %I64d MB by "), nBlock / 1024 / 1024 );
			for ( int i = 0; i < nCount; ++i )
			{
				const __int64 nBegin = GetMicroCount();
				CSHA pSHA;
				pSHA.Add( pBuffer, nBlock );
				pSHA.Finish();
				__int64 nTime = GetMicroCount() - nBegin;
				if ( nBest < 0 || nTime < nBest )
					nBest = nTime;
				if ( i == 0 || nTime > nWorst )
					nWorst = nTime;
			}
			nError = ( 100 * ( nWorst - nBest ) ) / nWorst;
			const __int64 nSpeed = ( nBlock * 1000000 ) / nBest;
			if ( nFast < nSpeed )
				nFast = nSpeed;
			_tprintf( _T("%3I64d ms (inaccuracy %2I64d%%), %3I64d MB/s        \r"),
				nBest / 1000, nError, nFast / ( 1024 * 1024 ) );
		} while ( nError > 5 && n++ < 10 );
	}
	_tprintf( _T("\n") );

	VirtualFree( pBuffer, 0, MEM_RELEASE );

	_tprintf( _T("\nPress ENTER to exit") );
	getchar();

	return 0;
}
ngx_int_t
ngx_os_init(ngx_log_t *log)
{
    DWORD        bytes;
    SOCKET       s;
    WSADATA      wsd;
    ngx_err_t    err;
    ngx_uint_t   n;
    SYSTEM_INFO  si;
    /* get Windows version */
    ngx_memzero(&osvi, sizeof(OSVERSIONINFOEX));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
#ifdef _MSC_VER
#pragma warning(disable:4996)
#endif
    osviex = GetVersionEx((OSVERSIONINFO *) &osvi);
    if (osviex == 0)
    {
        osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
        if (GetVersionEx((OSVERSIONINFO *) &osvi) == 0)
        {
            ngx_log_error(NGX_LOG_EMERG, log, ngx_errno,
                          "GetVersionEx() failed");
            return NGX_ERROR;
        }
    }
#ifdef _MSC_VER
#pragma warning(default:4996)
#endif
    /*
     *  Windows 3.1 Win32s   0xxxxx
     *
     *  Windows 95           140000
     *  Windows 98           141000
     *  Windows ME           149000
     *  Windows NT 3.51      235100
     *  Windows NT 4.0       240000
     *  Windows NT 4.0 SP5   240050
     *  Windows 2000         250000
     *  Windows XP           250100
     *  Windows 2003         250200
     *  Windows Vista/2008   260000
     *
     *  Windows CE x.x       3xxxxx
     */
    ngx_win32_version = osvi.dwPlatformId * 100000
                        + osvi.dwMajorVersion * 10000
                        + osvi.dwMinorVersion * 100;
    if (osviex)
    {
        ngx_win32_version += osvi.wServicePackMajor * 10
                             + osvi.wServicePackMinor;
    }
    GetSystemInfo(&si);
    ngx_pagesize = si.dwPageSize;
    ngx_allocation_granularity = si.dwAllocationGranularity;
    ngx_ncpu = si.dwNumberOfProcessors;
    ngx_cacheline_size = NGX_CPU_CACHE_LINE;
    for (n = ngx_pagesize; n >>= 1; ngx_pagesize_shift++)
    {
        /* void */
    }
    /* delete default "C" locale for _wcsicmp() */
    setlocale(LC_ALL, "");
    /* init Winsock */
    if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
    {
        ngx_log_error(NGX_LOG_EMERG, log, ngx_socket_errno,
                      "WSAStartup() failed");
        return NGX_ERROR;
    }
    if (ngx_win32_version < NGX_WIN_NT)
    {
        ngx_max_wsabufs = 16;
        return NGX_OK;
    }
    /* STUB: ngx_uint_t max */
    ngx_max_wsabufs = 1024 * 1024;
    /*
     * get AcceptEx(), GetAcceptExSockAddrs(), TransmitFile(),
     * TransmitPackets(), ConnectEx(), and DisconnectEx() addresses
     */
    s = ngx_socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    if (s == (ngx_socket_t) - 1)
    {
        ngx_log_error(NGX_LOG_EMERG, log, ngx_socket_errno,
                      ngx_socket_n " falied");
        return NGX_ERROR;
    }
    if (WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &ax_guid, sizeof(GUID),
                 &ngx_acceptex, sizeof(LPFN_ACCEPTEX), &bytes, NULL, NULL)
            == -1)
    {
        ngx_log_error(NGX_LOG_NOTICE, log, ngx_socket_errno,
                      "WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER, "
                      "WSAID_ACCEPTEX) failed");
    }
    if (WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &as_guid, sizeof(GUID),
                 &ngx_getacceptexsockaddrs, sizeof(LPFN_GETACCEPTEXSOCKADDRS),
                 &bytes, NULL, NULL)
            == -1)
    {
        ngx_log_error(NGX_LOG_NOTICE, log, ngx_socket_errno,
                      "WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER, "
                      "WSAID_GETACCEPTEXSOCKADDRS) failed");
    }
    if (WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &tf_guid, sizeof(GUID),
                 &ngx_transmitfile, sizeof(LPFN_TRANSMITFILE), &bytes,
                 NULL, NULL)
            == -1)
    {
        ngx_log_error(NGX_LOG_NOTICE, log, ngx_socket_errno,
                      "WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER, "
                      "WSAID_TRANSMITFILE) failed");
    }
    if (WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &tp_guid, sizeof(GUID),
                 &ngx_transmitpackets, sizeof(LPFN_TRANSMITPACKETS), &bytes,
                 NULL, NULL)
            == -1)
    {
        ngx_log_error(NGX_LOG_NOTICE, log, ngx_socket_errno,
                      "WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER, "
                      "WSAID_TRANSMITPACKETS) failed");
    }
    if (WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &cx_guid, sizeof(GUID),
                 &ngx_connectex, sizeof(LPFN_CONNECTEX), &bytes,
                 NULL, NULL)
            == -1)
    {
        ngx_log_error(NGX_LOG_NOTICE, log, ngx_socket_errno,
                      "WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER, "
                      "WSAID_CONNECTEX) failed");
    }
    if (WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &dx_guid, sizeof(GUID),
                 &ngx_disconnectex, sizeof(LPFN_DISCONNECTEX), &bytes,
                 NULL, NULL)
            == -1)
    {
        ngx_log_error(NGX_LOG_NOTICE, log, ngx_socket_errno,
                      "WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER, "
                      "WSAID_DISCONNECTEX) failed");
    }
    if (ngx_close_socket(s) == -1)
    {
        ngx_log_error(NGX_LOG_ALERT, log, ngx_socket_errno,
                      ngx_close_socket_n " failed");
    }
    if (GetEnvironmentVariable("ngx_unique", ngx_unique, NGX_INT32_LEN + 1)
            != 0)
    {
        ngx_process = NGX_PROCESS_WORKER;
    }
    else
    {
        err = ngx_errno;
        if (err != ERROR_ENVVAR_NOT_FOUND)
        {
            ngx_log_error(NGX_LOG_EMERG, log, err,
                          "GetEnvironmentVariable(\"ngx_unique\") failed");
            return NGX_ERROR;
        }
        ngx_sprintf((u_char *) ngx_unique, "%P%Z", ngx_pid);
    }
    srand((ngx_pid << 16) ^ (unsigned) ngx_time());
    return NGX_OK;
}
int Utils::get_device_processor_count() {
  SYSTEM_INFO sysinfo;
  GetSystemInfo(&sysinfo);

  return sysinfo.dwNumberOfProcessors;
}
Exemple #20
0
void TaskManager_OnTabWndSelChange(void)
{
    int    i;
    HMENU  hMenu;
    HMENU  hOptionsMenu;
    HMENU  hViewMenu;
    HMENU  hSubMenu;
    WCHAR  szTemp[256];
    SYSTEM_INFO sysInfo;

    hMenu = GetMenu(hMainWnd);
    hViewMenu = GetSubMenu(hMenu, 2);
    hOptionsMenu = GetSubMenu(hMenu, 1);
    TaskManagerSettings.ActiveTabPage = TabCtrl_GetCurSel(hTabWnd);
    for (i = GetMenuItemCount(hViewMenu) - 1; i > 2; i--) {
        hSubMenu = GetSubMenu(hViewMenu, i);
        if (hSubMenu)
            DestroyMenu(hSubMenu);
        RemoveMenu(hViewMenu, i, MF_BYPOSITION);
    }
    RemoveMenu(hOptionsMenu, 3, MF_BYPOSITION);
    if (hWindowMenu)
        DestroyMenu(hWindowMenu);
    switch (TaskManagerSettings.ActiveTabPage) {
    case 0:
        ShowWindow(hApplicationPage, SW_SHOW);
        ShowWindow(hProcessPage, SW_HIDE);
        ShowWindow(hPerformancePage, SW_HIDE);
        BringWindowToTop(hApplicationPage);

        LoadStringW(hInst, IDS_MENU_LARGEICONS, szTemp, 256);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_LARGE, szTemp);

        LoadStringW(hInst, IDS_MENU_SMALLICONS, szTemp, 256);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_SMALL, szTemp);

        LoadStringW(hInst, IDS_MENU_DETAILS, szTemp, 256);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_DETAILS, szTemp);

        if (GetMenuItemCount(hMenu) <= 5) {
            hWindowMenu = LoadMenuW(hInst, MAKEINTRESOURCEW(IDR_WINDOWSMENU));

            LoadStringW(hInst, IDS_MENU_WINDOWS, szTemp, 256);
            InsertMenuW(hMenu, 3, MF_BYPOSITION|MF_POPUP, (UINT_PTR) hWindowMenu, szTemp);

            DrawMenuBar(hMainWnd);
        }
        CheckMenuRadioItem(hViewMenu, ID_VIEW_LARGE, ID_VIEW_DETAILS, TaskManagerSettings.ViewMode, MF_BYCOMMAND);

        /*
         * Give the application list control focus
         */
        if (!bWasKeyboardInput)
            SetFocus(hApplicationPageListCtrl);
        break;

    case 1:
        ShowWindow(hApplicationPage, SW_HIDE);
        ShowWindow(hProcessPage, SW_SHOW);
        ShowWindow(hPerformancePage, SW_HIDE);
        BringWindowToTop(hProcessPage);

        LoadStringW(hInst, IDS_MENU_SELECTCOLUMNS, szTemp, 256);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_SELECTCOLUMNS, szTemp);

        LoadStringW(hInst, IDS_MENU_16BITTASK, szTemp, 256);
        AppendMenuW(hOptionsMenu, MF_STRING, ID_OPTIONS_SHOW16BITTASKS, szTemp);

        if (TaskManagerSettings.Show16BitTasks)
            CheckMenuItem(hOptionsMenu, ID_OPTIONS_SHOW16BITTASKS, MF_BYCOMMAND|MF_CHECKED);
        if (GetMenuItemCount(hMenu) > 5)
        {
            DeleteMenu(hMenu, 3, MF_BYPOSITION);
            DrawMenuBar(hMainWnd);
        }
        /*
         * Give the process list control focus
         */
        if (!bWasKeyboardInput)
            SetFocus(hProcessPageListCtrl);
        break;

    case 2:
        ShowWindow(hApplicationPage, SW_HIDE);
        ShowWindow(hProcessPage, SW_HIDE);
        ShowWindow(hPerformancePage, SW_SHOW);
        BringWindowToTop(hPerformancePage);
        if (GetMenuItemCount(hMenu) > 5) {
            DeleteMenu(hMenu, 3, MF_BYPOSITION);
            DrawMenuBar(hMainWnd);
        }

        GetSystemInfo(&sysInfo);

        /* Hide CPU graph options on single CPU systems */
        if (sysInfo.dwNumberOfProcessors > 1)
        {
            hSubMenu = CreatePopupMenu();

            LoadStringW(hInst, IDS_MENU_ONEGRAPHALLCPUS, szTemp, 256);
            AppendMenuW(hSubMenu, MF_STRING, ID_VIEW_CPUHISTORY_ONEGRAPHALL, szTemp);

            LoadStringW(hInst, IDS_MENU_ONEGRAPHPERCPU, szTemp, 256);
            AppendMenuW(hSubMenu, MF_STRING, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, szTemp);

            LoadStringW(hInst, IDS_MENU_CPUHISTORY, szTemp, 256);
            AppendMenuW(hViewMenu, MF_STRING|MF_POPUP, (UINT_PTR) hSubMenu, szTemp);

            if (TaskManagerSettings.CPUHistory_OneGraphPerCPU)
                CheckMenuRadioItem(hSubMenu, ID_VIEW_CPUHISTORY_ONEGRAPHALL, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, MF_BYCOMMAND);
            else
                CheckMenuRadioItem(hSubMenu, ID_VIEW_CPUHISTORY_ONEGRAPHALL, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, ID_VIEW_CPUHISTORY_ONEGRAPHALL, MF_BYCOMMAND);
        }

        LoadStringW(hInst, IDS_MENU_SHOWKERNELTIMES, szTemp, 256);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_SHOWKERNELTIMES, szTemp);

        if (TaskManagerSettings.ShowKernelTimes)
            CheckMenuItem(hViewMenu, ID_VIEW_SHOWKERNELTIMES, MF_BYCOMMAND|MF_CHECKED);
        else
            CheckMenuItem(hViewMenu, ID_VIEW_SHOWKERNELTIMES, MF_BYCOMMAND|MF_UNCHECKED);

        /*
         * Give the tab control focus
         */
        if (!bWasKeyboardInput)
            SetFocus(hTabWnd);
        break;
    }
}
Exemple #21
0
inline int pagesize()
{
  SYSTEM_INFO si;
  GetSystemInfo(&si);
  return si.dwPageSize;
}
Exemple #22
0
size_t GetProcessorNum()
{
    SYSTEM_INFO info;
    GetSystemInfo(&info);
    return info.dwNumberOfProcessors;
}
Exemple #23
0
AXIS2_EXTERN axis2_char_t* AXIS2_CALL
service_admin_util_get_uname(axutil_env_t *env,char mode)
{
	char *unameval;
	char tmp_uname[256];
#ifdef WIN32
	DWORD dwBuild=0;
	DWORD dwVersion = GetVersion();
	DWORD dwWindowsMajorVersion =  (DWORD)(LOBYTE(LOWORD(dwVersion)));
	DWORD dwWindowsMinorVersion =  (DWORD)(HIBYTE(LOWORD(dwVersion)));
	DWORD dwSize = MAX_COMPUTERNAME_LENGTH + 1;
	TCHAR ComputerName[MAX_COMPUTERNAME_LENGTH + 1];
	SYSTEM_INFO SysInfo;

	GetComputerName(ComputerName, &dwSize);
	GetSystemInfo(&SysInfo);

	if (mode == 's') {
		if (dwVersion < 0x80000000) {
			unameval = "Windows NT";
		} else {
			unameval = "Windows 9x";
		}
	} else if (mode == 'r') {
		snprintf(tmp_uname, sizeof(tmp_uname), "%d.%d", dwWindowsMajorVersion, dwWindowsMinorVersion);
		unameval = tmp_uname;
	} else if (mode == 'n') {
		unameval = ComputerName;
	} else if (mode == 'v') {
		dwBuild = (DWORD)(HIWORD(dwVersion));
		snprintf(tmp_uname, sizeof(tmp_uname), "build %d", dwBuild);
		unameval = tmp_uname;
	} else if (mode == 'm') {
		switch (SysInfo.wProcessorArchitecture) {
			case PROCESSOR_ARCHITECTURE_INTEL :
				snprintf(tmp_uname, sizeof(tmp_uname), "i%d", SysInfo.dwProcessorType);
				unameval = tmp_uname;
				break;
			case PROCESSOR_ARCHITECTURE_MIPS :
				snprintf(tmp_uname, sizeof(tmp_uname), "MIPS R%d000", SysInfo.wProcessorLevel);
				unameval = tmp_uname;
				break;
			case PROCESSOR_ARCHITECTURE_ALPHA :
				snprintf(tmp_uname, sizeof(tmp_uname), "Alpha %d", SysInfo.wProcessorLevel);
				unameval = tmp_uname;
				break;
			case PROCESSOR_ARCHITECTURE_PPC :
				snprintf(tmp_uname, sizeof(tmp_uname), "PPC 6%02d", SysInfo.wProcessorLevel);
				unameval = tmp_uname;
				break;
			case PROCESSOR_ARCHITECTURE_IA64 :
				unameval = "IA64";
				break;
#if defined(PROCESSOR_ARCHITECTURE_IA32_ON_WIN64)
			case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 :
				unameval = "IA32";
				break;
#endif
#if defined(PROCESSOR_ARCHITECTURE_AMD64)
			case PROCESSOR_ARCHITECTURE_AMD64 :
				unameval = "AMD64";
				break;
#endif
			case PROCESSOR_ARCHITECTURE_UNKNOWN :
			default :
				unameval = "Unknown";
				break;
		}
	} else { /* assume mode == 'a' */
		/* Get build numbers for Windows NT or Win95 */
		if (dwVersion < 0x80000000){
			dwBuild = (DWORD)(HIWORD(dwVersion));
			snprintf(tmp_uname, sizeof(tmp_uname), "%s %d.%d build %d",
					 "Windows NT", 
					 dwWindowsMajorVersion, dwWindowsMinorVersion, dwBuild);
		} else {
			snprintf(tmp_uname, sizeof(tmp_uname), "%s %s %d.%d",
					 "Windows 9x",
					 dwWindowsMajorVersion, dwWindowsMinorVersion);
		}
		unameval = tmp_uname;
	}
#else
#ifdef HAVE_SYS_UTSNAME_H
	struct utsname buf;
	if (uname((struct utsname *)&buf) == -1) {
		unameval = "Linux";
	} else {
		if (mode == 's') {
			unameval = buf.sysname;
		} else if (mode == 'r') {
			unameval = buf.release;
		} else if (mode == 'n') {
			unameval = buf.nodename;
		} else if (mode == 'v') {
			unameval = buf.version;
		} else if (mode == 'm') {
			unameval = buf.machine;
		} else { /* assume mode == 'a' */
			snprintf(tmp_uname, sizeof(tmp_uname), "%s %s %s %s %s",
					 buf.sysname, buf.nodename, buf.release, buf.version,
					 buf.machine);
			unameval = tmp_uname;
		}

	}
#endif
#endif
	return axutil_strdup(env,unameval);

}
Exemple #24
0
void*
mapfile_map(MapFile* handle,
            size_t offset,
            size_t size,
            int prot,
            void** mapped_offset,
            size_t* mapped_size)
{
    void* mapped_at = NULL;
    size_t align_mask;
    size_t map_offset;
    size_t map_size;

  /* Get the mask for mapping offset alignment. */
#ifdef  WIN32
    DWORD win32_prot;
    DWORD win32_map;
    HANDLE map_handle;
    LARGE_INTEGER converter;
    SYSTEM_INFO sys_info;
    GetSystemInfo(&sys_info);
    align_mask = sys_info.dwAllocationGranularity - 1;
#else   // WIN32
    align_mask = getpagesize() - 1;
#endif  // WIN32

    /* Adjust mapping offset and mapping size accordingly to
     * the mapping alignment requirements. */
    map_offset = offset & ~align_mask;
    map_size = (size_t)(offset - map_offset + size);

    /* Make sure mapping size doesn't exceed 4G. */
    if (map_size < size) {
        errno = EFBIG;
        return NULL;
    }

    /* Map the section. */
#ifdef  WIN32
    /* Convert to Win32 page protection and mapping type. */
    win32_prot = PAGE_READONLY;
    win32_map = FILE_MAP_READ;
    if (prot != PROT_NONE) {
        if ((prot & (PROT_WRITE | PROT_EXEC)) == 0) {
            win32_prot = PAGE_READONLY;
            win32_map = FILE_MAP_READ;
        } else if ((prot & (PROT_WRITE | PROT_EXEC)) ==
                   (PROT_WRITE | PROT_EXEC)) {
            win32_prot = PAGE_EXECUTE_READWRITE;
            win32_map = FILE_MAP_WRITE;
        } else if ((prot & PROT_WRITE) == PROT_WRITE) {
            win32_prot = PAGE_READWRITE;
            win32_map = FILE_MAP_WRITE;
        } else if ((prot & PROT_EXEC) == PROT_EXEC) {
            win32_prot = PAGE_EXECUTE_READ;
            win32_map = FILE_MAP_READ;
        }
    }

    converter.QuadPart = map_offset + map_size;
    map_handle = CreateFileMapping(handle, NULL, win32_prot,
                                   converter.HighPart, converter.LowPart, NULL);
    if (map_handle != NULL) {
        converter.QuadPart = map_offset;
        mapped_at = MapViewOfFile(map_handle, win32_map, converter.HighPart,
                                  converter.LowPart, map_size);
        /* Memory mapping (if successful) will hold extra references to the
        * mapping, so we can close it right after we mapped file view. */
        CloseHandle(map_handle);
    }
    if (mapped_at == NULL) {
        errno = GetLastError();
        return NULL;
    }
#else   // WIN32
    mapped_at =
        mmap(0, map_size, PROT_READ, MAP_SHARED, (int)handle, map_offset);
    if (mapped_at == MAP_FAILED) {
        return NULL;
    }
#endif  // WIN32

    *mapped_offset = (char*)mapped_at + (offset - map_offset);
    *mapped_size = size;

    return mapped_at;
}
Exemple #25
0
BOOL
SockInitialize (
    IN PVOID DllHandle,
    IN ULONG Reason,
    IN PVOID Context OPTIONAL
    )
{
    NTSTATUS status;
    SYSTEM_INFO systemInfo;

    //
    // On a thread detach, set up the context param so that all
    // necessary deallocations will occur.
    //

    if ( Reason == DLL_THREAD_DETACH ) {
        Context = NULL;
    }

    switch ( Reason ) {

    case DLL_PROCESS_ATTACH:

        SockModuleHandle = (HMODULE)DllHandle;

#if DBG
        //
        // If there is a file in the current directory called "wsdebug"
        // open it and read the first line to set the debugging flags.
        //

        {
            HANDLE handle;

            handle = CreateFile(
                         "WsDebug",
                         GENERIC_READ,
                         FILE_SHARE_READ | FILE_SHARE_WRITE,
                         NULL,
                         OPEN_EXISTING,
                         0,
                         NULL
                         );

            if( handle == INVALID_HANDLE_VALUE ) {

                //
                // Set default value.
                //

                WsDebug = WINSOCK_DEBUG_DEBUGGER;

            } else {

                CHAR buffer[11];
                DWORD bytesRead;

                RtlZeroMemory( buffer, sizeof(buffer) );

                if ( ReadFile( handle, buffer, 10, &bytesRead, NULL ) ) {

                    buffer[bytesRead] = '\0';

                    WsDebug = strtoul( buffer, NULL, 16 );

                } else {

                    WS_PRINT(( "read file failed: %ld\n", GetLastError( ) ));
                }

                CloseHandle( handle );
            }
        }
#endif

        IF_DEBUG(INIT) {
            WS_PRINT(( "SockInitialize: process attach, PEB = %lx\n",
                           NtCurrentPeb( ) ));
        }

        //
        // Initialize the lists of sockets and helper DLLs.
        //

        InitializeListHead( &SockHelperDllListHead );
        InitializeListHead( &SocketListHead );

        //
        // Initialize the global post routine pointer.  We have to do it
        // here rather than statically because it otherwise won't be
        // thunked correctly.
        //

        SockPostRoutine = PostMessage;

        //
        // *** lock acquisition order: it is legal to acquire SocketLock
        // while holding an individual socket lock, but not the other way
        // around!
        //

        InitializeCriticalSection( &SocketLock );
        InitializeCriticalSection( &csRnRLock);

#if !defined(USE_TEB_FIELD)
        //
        // Allocate space in TLS so that we can convert global variables
        // to thread variables.
        //

        SockTlsSlot = TlsAlloc( );

        if ( SockTlsSlot == 0xFFFFFFFF ) {

            WS_PRINT(( "SockInitialize: TlsAlloc failed: %ld\n", GetLastError( ) ));
            DeleteCriticalSection( &SocketLock );
            DeleteCriticalSection( &csRnRLock );
            return FALSE;
        }
#endif  // !USE_TEB_FIELD

        //
        // Create private WinSock heap on MP machines.  UP machines
        // just use the process heap.
        //

        GetSystemInfo( &systemInfo );

        if( systemInfo.dwNumberOfProcessors > 1 ) {

            SockPrivateHeap = RtlCreateHeap( HEAP_GROWABLE |    // Flags
                                             HEAP_CLASS_1,
                                             NULL,              // HeapBase
                                             0,                 // ReserveSize
                                             0,                 // CommitSize
                                             NULL,              // Lock
                                             NULL );            // Parameters

        } else {

            WS_ASSERT( SockPrivateHeap == NULL );

        }

        if ( SockPrivateHeap == NULL ) {

            //
            // This is either a UP box, or RtlCreateHeap() failed.  In
            // either case, just use the process heap.
            //

            SockPrivateHeap = RtlProcessHeap();

        }

        break;

    case DLL_PROCESS_DETACH:

        IF_DEBUG(INIT) {
            WS_PRINT(( "SockInitialize: process detach, PEB = %lx\n",
                           NtCurrentPeb( ) ));
        }

        //
        // Only clean up resources if we're being called because of a
        // FreeLibrary().  If this is because of process termination,
        // do not clean up, as the system will do it for us.  Also,
        // if we get called at process termination, it is likely that
        // a thread was terminated while it held a winsock lock, which
        // would cause a deadlock if we then tried to grab the lock.
        //

        if ( Context == NULL ) {
            WSACleanup( );
            GetHostCleanup();
            DeleteCriticalSection( &SocketLock );
            DeleteCriticalSection( &csRnRLock );
        }

        SockProcessTerminating = TRUE;

        // *** lack of break is intentional!

    case DLL_THREAD_DETACH:

        IF_DEBUG(INIT) {
            WS_PRINT(( "SockInitialize: thread detach, TEB = %lx\n",
                           NtCurrentTeb( ) ));
        }

        //
        // If the TLS information for this thread has been initialized,
        // free the thread data buffer.
        //

        if ( Context == NULL &&
             GET_THREAD_DATA() != NULL ) {

            FREE_HEAP( GET_THREAD_DATA() );
            SET_THREAD_DATA( NULL );
        }

        //
        // If this is a process detach, free the TLS slot we're using.
        //

        if ( Reason == DLL_PROCESS_DETACH && Context == NULL ) {

#if !defined(USE_TEB_FIELD)
            if ( SockTlsSlot != 0xFFFFFFFF ) {

                BOOLEAN ret;

                ret = TlsFree( SockTlsSlot );
                WS_ASSERT( ret );

                SockTlsSlot = 0xFFFFFFFF;
            }
#endif  // !USE_TEB_FIELD

            //
            //  Also destroy any private WinSock heap.
            //

            if ( SockPrivateHeap != RtlProcessHeap() ) {

                WS_ASSERT( SockPrivateHeap != NULL );
                RtlDestroyHeap( SockPrivateHeap );
                SockPrivateHeap = NULL;

            }
        }

        break;

    case DLL_THREAD_ATTACH:
        break;

    default:

        WS_ASSERT( FALSE );
        break;
    }

    return TRUE;

} // SockInitialize
HRESULT
FxInterruptThreadpool::UpdateThreadPoolThreadLimits(
    _In_ ULONG InterruptCount
    )
{
    BOOL bRet;
    HRESULT hr = S_OK;
    SYSTEM_INFO sysInfo;
    ULONG minThreadCount = 0;
    ULONG procs;
    DWORD error;
    
    FX_VERIFY(INTERNAL, CHECK_NOT_NULL(m_Pool));

    //
    // if there are more than one interrupts then we need to update minimum
    // thread count. 
    //
    if (m_MinimumThreadCount >= InterruptCount) {
        //
        // nothing to do 
        //
        return S_OK;
    }

    //
    // We want to have number of minimum persistent threads 
    // = Min(number of interrupts, number of processors). 
    // See comments in Initialize routine for details. 
    //
    GetSystemInfo(&sysInfo); 
    procs = sysInfo.dwNumberOfProcessors;

    minThreadCount = min(InterruptCount, procs);

    if (m_MinimumThreadCount < minThreadCount) {
        //
        // Set threadpool min  
        //
        bRet = SetThreadpoolThreadMinimum(m_Pool, minThreadCount);
        if (bRet == FALSE) {
            error = GetLastError();
            hr = HRESULT_FROM_WIN32(error);
            DoTraceLevelMessage(GetDriverGlobals(), 
                        TRACE_LEVEL_ERROR, TRACINGPNP,
                        "Failed to set minimum threads in threadpool,"
                        " TP_POOL 0x%p to %d %!winerr!", m_Pool, minThreadCount, 
                        error);           
            return hr;
        }
        
        m_MinimumThreadCount = minThreadCount;
    }

    //
    // set thread pool max to max number of interrupts 
    //
    SetThreadpoolThreadMaximum(m_Pool, InterruptCount);
    
    DoTraceLevelMessage(GetDriverGlobals(), 
                TRACE_LEVEL_ERROR, TRACINGPNP,
                "Threads in thread pool TP_POOL 0x%p updated" 
                " to Max %d Min %d threads", m_Pool, 
                InterruptCount, minThreadCount);

    return hr;
}
Exemple #27
0
/**
 * @brief
 * Internal session memory usage decoding routine.
 * Accepts a job pointer.  Returns the sum of all memory
 * consumed for all tasks executed by the job, in kilo bytes.
 *
 * NOTE: To retrieve a handle to any process in the system,
 *       the calling process should have a privilege "SeDebugPrivilege".
 *       A Win32 API OpenProcess() can be used in a calling process
 *       to obtain any desired process handle in the system.
 *
 *       In PBS, ena_privilege() function can be used to enable
 *       SeDebugPrivilege for calling process. For pbs_mom process,
 *       ena_privilege() has been used in it's main_thread() function.
 *
 * @param[in]	pjob - pointer to job
 *
 * @return      u_Long
 * @retval      0 - failure
 * @retval      memory usage of all the processes of a job - failure
 */
static u_Long
mem_sum(job *pjob)
{
	u_Long			mem = 0;
	int			nps = 0;
	DWORD			i;
	HANDLE			hProcess;
	DWORD			pidlistsize;
	DWORD			nwspages;
	SYSTEM_INFO		si;
	PJOBOBJECT_BASIC_PROCESS_ID_LIST	pProcessList;
	JOBOBJECT_BASIC_ACCOUNTING_INFORMATION	ji;
	pbs_task                *ptask = NULL;
	BOOL                    is_process_in_job = FALSE;

	/* Get the system info */
	GetSystemInfo(&si);

	/* Get the number of processes embedded in the job */
	if (pjob->ji_hJob != NULL &&
		QueryInformationJobObject(pjob->ji_hJob,
		JobObjectBasicAccountingInformation,
		&ji, sizeof(ji), NULL)) {
		nps = ji.TotalProcesses;
	}

	if (nps == 0) {
		pjob->ji_flags |= MOM_NO_PROC;
		return 0;
	}


	/* Compute the size of pid list */
	pidlistsize = sizeof(JOBOBJECT_BASIC_PROCESS_ID_LIST) +
		(nps-1) * sizeof(DWORD);

	pProcessList = (PJOBOBJECT_BASIC_PROCESS_ID_LIST) malloc(pidlistsize);
	if (pProcessList == NULL) {
		log_err(-1, "mem_sum:", "memory allocation failed");
		return (0);
	}

	pProcessList->NumberOfAssignedProcesses = nps;
	pProcessList->NumberOfProcessIdsInList = 0;

	/* Get the pid list */
	if (pjob->ji_hJob != NULL)
		QueryInformationJobObject(pjob->ji_hJob,
			JobObjectBasicProcessIdList,
			pProcessList, pidlistsize, NULL);

	/*
	 * Traverse through each process and find the
	 * memory used by that process during its execution.
	 */
	for (i = 0; i < (pProcessList->NumberOfProcessIdsInList); i++) {
		hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
			PROCESS_VM_READ,
			FALSE, pProcessList->ProcessIdList[i]);
		if (hProcess != NULL) {
			(void)QueryWorkingSet(hProcess, &nwspages, sizeof(nwspages));
			mem += nwspages * (si.dwPageSize >> 10);
			CloseHandle(hProcess);

		}
	}
//----------------------------------------------------------------//
void MOAIEnvironment::DetectEnvironment () {

	RTTI_SINGLE ( MOAIGlobalEventSource )
	
	#if defined( MOAI_OS_WINDOWS )
	
		//printf ( "Env Windows\n" );
		this->SetValue ( MOAI_ENV_osBrand, "Windows" );
		
		UUID uuid;
		UuidCreateSequential ( &uuid );
		
		// For now, we'll just use the MAC address which is the last 6 bytes of the uuid.
		char buf[13];
		sprintf ( buf, "%02X%02X%02X%02X%02X%02X", uuid.Data4[2], uuid.Data4[3], uuid.Data4[4], uuid.Data4[5], uuid.Data4[6], uuid.Data4[7]);
		this->SetValue ( MOAI_ENV_udid, buf );
		
		char path[MAX_PATH];
		//HRESULT hr = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, path);
		SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, path);
		this->SetValue ( MOAI_ENV_documentDirectory, path );
		
		const int BUFSIZE = 256;
		TCHAR pszOS[BUFSIZE];

		OSVERSIONINFOEX osvi;
		SYSTEM_INFO si;
		PGNSI pGNSI;				

		ZeroMemory(&si, sizeof(SYSTEM_INFO));
		ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));

		osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
		GetVersionEx((OSVERSIONINFO*) &osvi);
		
		pGNSI = (PGNSI) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo");
		if(NULL != pGNSI) {
			pGNSI(&si);
		}
		else {
			GetSystemInfo(&si);
		}

		if ( VER_PLATFORM_WIN32_NT==osvi.dwPlatformId && osvi.dwMajorVersion > 4 ) {
		
			strcpy ( pszOS, TEXT ( "Win" ));			
			if ( osvi.dwMajorVersion == 6 ) {
				if ( osvi.dwMinorVersion == 1 ) {
					if( osvi.wProductType == VER_NT_WORKSTATION )
						strcat(pszOS, TEXT("7"));
					else strcat(pszOS, TEXT("2008R2" ));
				}
				else if( osvi.dwMinorVersion == 0 ) {
					if( osvi.wProductType == VER_NT_WORKSTATION )
						strcat(pszOS, TEXT("Vista"));
					else strcat(pszOS, TEXT("Server2008" ));
				}
			}
			else if ( osvi.dwMajorVersion == 5 ) {
				if (osvi.dwMinorVersion == 2) {				
					if( osvi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64) {
						strcat(pszOS, TEXT( "XPx64"));
					}
					else {
						strcat(pszOS, TEXT("Server2003"));
					}
				}
				else if ( osvi.dwMinorVersion == 1 ) {
					strcat(pszOS, TEXT("XP"));					
				}
				else if ( osvi.dwMinorVersion == 0 ) {
					strcat(pszOS, TEXT("2000"));
				}
			}
			
			this->SetValue ( MOAI_ENV_osVersion, pszOS );
		}
		else {
			this->SetValue ( MOAI_ENV_osVersion, "WinUnknown" );
		}
		
	#elif defined( MOAI_OS_LINUX )
	
		//printf ( "Env Linux\n" );
		this->SetValue ( MOAI_ENV_osBrand, "Linux" );

	#elif defined ( MOAI_OS_OSX )
	
		//printf ( "Env OSX\n" );
		this->SetValue ( MOAI_ENV_osBrand, "OSX" );
	  #if 0 /* doesn't compile yet */
		// OS Version
		SInt32 majorVersion,minorVersion,bugFixVersion;

		Gestalt(gestaltSystemVersionMajor, &majorVersion);
		Gestalt(gestaltSystemVersionMinor, &minorVersion);
		Gestalt(gestaltSystemVersionBugFix, &bugFixVersion);

		char buffer[256];
		sprintf(buffer, "%d.%d.%d",majorVersion,minorVersion,bugFixVersion);
		this->SetValue ( MOAI_ENV_osVersion, buffer );
	  #endif
	#else
		//printf ( "No environment detected\n" );
	#endif
}
Exemple #29
0
int _cdecl main(int argc, char** argv)
{
  BOOL bResult;                   // generic Boolean value
  ULONG_PTR NumberOfPages;        // number of pages to request
  ULONG_PTR NumberOfPagesInitial; // initial number of pages requested
  ULONG_PTR *aPFNs;               // page info; holds opaque data
  PVOID lpMemReserved;            // AWE window
  SYSTEM_INFO sSysInfo;           // useful system information
  int PFNArraySize;               // memory to request for PFN array
  int i;						  // iterator
  int bytes;					  // Number of bytes to request

  if (argc != 2) {
	  printf ("Usage: %s <number_of_bytes_to_allocate>\n", argv[0]);
	  return 1;
  }

  bytes = atoi(argv[1]);

  printf("Attempting to allocate %d bytes.\n", bytes);

  GetSystemInfo(&sSysInfo);  // fill the system information structure

  printf("This computer has page size %d.\n", sSysInfo.dwPageSize);

  // Calculate the number of pages of memory to request.

  NumberOfPages = bytes/sSysInfo.dwPageSize;
  printf ("Requesting %d pages of memory.\n", NumberOfPages);

  // Calculate the size of the user PFN array.

  PFNArraySize = NumberOfPages * sizeof (ULONG_PTR);

  printf ("Requesting a PFN array of %d bytes.\n", PFNArraySize);

  aPFNs = (ULONG_PTR *) HeapAlloc(GetProcessHeap(), 0, PFNArraySize);

  if (aPFNs == NULL)
  {
    printf ("Failed to allocate on heap.\n");
    return 1;
  }

  // Enable the privilege.

  if( ! LoggedSetLockPagesPrivilege( GetCurrentProcess(), TRUE ) )
  {
    return 1;
  }

  // Allocate the physical memory.

  NumberOfPagesInitial = NumberOfPages;
  bResult = AllocateUserPhysicalPages( GetCurrentProcess(),
                                       &NumberOfPages,
                                       aPFNs );

  if( bResult != TRUE )
  {
    printf("Cannot allocate physical pages (%u)\n", GetLastError() );
    return 1;
  }

  if( NumberOfPagesInitial != NumberOfPages )
  {
    printf("Allocated only %p pages.\n", NumberOfPages );
    return 1;
  }

  // Reserve the virtual memory.

  lpMemReserved = VirtualAlloc( NULL,
                                bytes,
                                MEM_RESERVE | MEM_PHYSICAL,
                                PAGE_READWRITE );

  if( lpMemReserved == NULL )
  {
    printf("Cannot reserve memory.\n");
    return 1;
  }

  // Map the physical memory into the window.

  bResult = MapUserPhysicalPages( lpMemReserved,
                                  NumberOfPages,
                                  aPFNs );

  if( bResult != TRUE )
  {
    printf("MapUserPhysicalPages failed (%u)\n", GetLastError() );
    return 1;
  }

  while (1)
	  Sleep(30);

  return 0;

}
Exemple #30
0
int main(int argc, char **argv) {
    char **base_paths = NULL;
    char **paths = NULL;
    int i;
    int pcre_opts = PCRE_MULTILINE;
    int study_opts = 0;
    double time_diff;
    worker_t *workers = NULL;
    int workers_len;
    int num_cores;

    set_log_level(LOG_LEVEL_WARN);

    work_queue = NULL;
    work_queue_tail = NULL;
    memset(&stats, 0, sizeof(stats));
    root_ignores = init_ignore(NULL, "", 0);
    out_fd = stdout;
#ifdef USE_PCRE_JIT
    int has_jit = 0;
    pcre_config(PCRE_CONFIG_JIT, &has_jit);
    if (has_jit) {
        study_opts |= PCRE_STUDY_JIT_COMPILE;
    }
#endif

    gettimeofday(&(stats.time_start), NULL);

    parse_options(argc, argv, &base_paths, &paths);
    log_debug("PCRE Version: %s", pcre_version());

#ifdef _WIN32
    {
        SYSTEM_INFO si;
        GetSystemInfo(&si);
        num_cores = si.dwNumberOfProcessors;
    }
#else
    num_cores = (int)sysconf(_SC_NPROCESSORS_ONLN);
#endif

    workers_len = num_cores;
    if (opts.literal) {
        workers_len--;
    }
    if (opts.workers) {
        workers_len = opts.workers;
    }
    if (workers_len < 1) {
        workers_len = 1;
    }

    log_debug("Using %i workers", workers_len);
    done_adding_files = FALSE;
    workers = ag_calloc(workers_len, sizeof(worker_t));
    if (pthread_cond_init(&files_ready, NULL)) {
        die("pthread_cond_init failed!");
    }
    if (pthread_mutex_init(&print_mtx, NULL)) {
        die("pthread_mutex_init failed!");
    }
    if (pthread_mutex_init(&stats_mtx, NULL)) {
        die("pthread_mutex_init failed!");
    }
    if (pthread_mutex_init(&work_queue_mtx, NULL)) {
        die("pthread_mutex_init failed!");
    }

    if (opts.casing == CASE_SMART) {
        opts.casing = is_lowercase(opts.query) ? CASE_INSENSITIVE : CASE_SENSITIVE;
    }

    if (opts.literal) {
        if (opts.casing == CASE_INSENSITIVE) {
            /* Search routine needs the query to be lowercase */
            char *c = opts.query;
            for (; *c != '\0'; ++c) {
                *c = (char)tolower(*c);
            }
        }
        generate_alpha_skip(opts.query, opts.query_len, alpha_skip_lookup, opts.casing == CASE_SENSITIVE);
        find_skip_lookup = NULL;
        generate_find_skip(opts.query, opts.query_len, &find_skip_lookup, opts.casing == CASE_SENSITIVE);
        if (opts.word_regexp) {
            init_wordchar_table();
            opts.literal_starts_wordchar = is_wordchar(opts.query[0]);
            opts.literal_ends_wordchar = is_wordchar(opts.query[opts.query_len - 1]);
        }
    } else {
        if (opts.casing == CASE_INSENSITIVE) {
            pcre_opts |= PCRE_CASELESS;
        }
        if (opts.word_regexp) {
            char *word_regexp_query;
            ag_asprintf(&word_regexp_query, "\\b%s\\b", opts.query);
            free(opts.query);
            opts.query = word_regexp_query;
            opts.query_len = strlen(opts.query);
        }
        compile_study(&opts.re, &opts.re_extra, opts.query, pcre_opts, study_opts);
    }

    if (opts.search_stream) {
        search_stream(stdin, "");
    } else {
        for (i = 0; i < workers_len; i++) {
            workers[i].id = i;
            int rv = pthread_create(&(workers[i].thread), NULL, &search_file_worker, &(workers[i].id));
            if (rv != 0) {
                die("error in pthread_create(): %s", strerror(rv));
            }
#if defined(HAVE_PTHREAD_SETAFFINITY_NP) && defined(USE_CPU_SET)
            if (opts.use_thread_affinity) {
                cpu_set_t cpu_set;
                CPU_ZERO(&cpu_set);
                CPU_SET(i % num_cores, &cpu_set);
                rv = pthread_setaffinity_np(workers[i].thread, sizeof(cpu_set), &cpu_set);
                if (rv != 0) {
                    die("error in pthread_setaffinity_np(): %s", strerror(rv));
                }
                log_debug("Thread %i set to CPU %i", i, i);
            } else {
                log_debug("Thread affinity disabled.");
            }
#else
            log_debug("No CPU affinity support.");
#endif
        }
        for (i = 0; paths[i] != NULL; i++) {
            log_debug("searching path %s for %s", paths[i], opts.query);
            symhash = NULL;
            ignores *ig = init_ignore(root_ignores, "", 0);
            struct stat s = {.st_dev = 0 };
#ifndef _WIN32
            /* The device is ignored if opts.one_dev is false, so it's fine
             * to leave it at the default 0
             */
            if (opts.one_dev && lstat(paths[i], &s) == -1) {
                log_err("Failed to get device information for path %s. Skipping...", paths[i]);
            }
#endif
            search_dir(ig, base_paths[i], paths[i], 0, s.st_dev);
            cleanup_ignore(ig);
        }
        pthread_mutex_lock(&work_queue_mtx);
        done_adding_files = TRUE;
        pthread_cond_broadcast(&files_ready);
        pthread_mutex_unlock(&work_queue_mtx);
        for (i = 0; i < workers_len; i++) {
            if (pthread_join(workers[i].thread, NULL)) {
                die("pthread_join failed!");
            }
        }
    }

    if (opts.stats) {
        gettimeofday(&(stats.time_end), NULL);
        time_diff = ((long)stats.time_end.tv_sec * 1000000 + stats.time_end.tv_usec) -
                    ((long)stats.time_start.tv_sec * 1000000 + stats.time_start.tv_usec);
        time_diff /= 1000000;

        printf("%ld matches\n%ld files searched\n%ld bytes searched\n%f seconds\n", stats.total_matches, stats.total_files, stats.total_bytes, time_diff);
    }

    if (opts.pager) {
        pclose(out_fd);
    }
    cleanup_options();
    pthread_cond_destroy(&files_ready);
    pthread_mutex_destroy(&work_queue_mtx);
    pthread_mutex_destroy(&stats_mtx);
    pthread_mutex_destroy(&print_mtx);
    cleanup_ignore(root_ignores);
    free(workers);
    for (i = 0; paths[i] != NULL; i++) {
        free(paths[i]);
        free(base_paths[i]);
    }
    free(base_paths);
    free(paths);
    if (find_skip_lookup) {
        free(find_skip_lookup);
    }
    return !opts.match_found;
}