Exemple #1
0
void log_branch(_In_ PVOID address, _In_ DWORD pid, _In_ DWORD thread_id)
{
    if (!((DWORD_PTR)address >= k32_base && (DWORD_PTR)address < k32_max))
    {
        return;
    }


    // exception address read
    PDEBUGGEE dbge = NULL;
    for (int i = 0; i < sizeof(_debuggees) / sizeof(DEBUGGEE); ++i)
    {
        if (_debuggees[i]._pid == pid)
        {
            dbge = &_debuggees[i];
        }
    }
    if (NULL == dbge) return;

    SIZE_T bytes_read = 0;
    unsigned char buf[4] = { 0 };
    ReadProcessMemory(dbge->_proc_handle,
                      address,
                      buf,
                      sizeof(buf),
                      &bytes_read);

    if (0xE8 == buf[0])
    {
        log("call at 0x%08x", address);
    }

    // single step 을 활성화

    ch_param param = { 0 };
    param.hthread = OpenThread(THREAD_ALL_ACCESS, FALSE, thread_id);
    if (NULL != param.hthread)
    {
        param.context.ContextFlags = CONTEXT_ALL;
        if (TRUE != GetThreadContext(param.hthread, &param.context))
        {
            _ASSERTE(!"oops!");
            return;
        }
        set_single_step(&param);
    }
}
Exemple #2
0
void ReadCallstackX86( HANDLE hProcess, HANDLE hThread, std::list<FrameX86>& stack )
{
    const int       MaxStackDepth = 10000;
    FrameX86        frame = { 0 };
#if _WIN64
    WOW64_CONTEXT   context = { 0 };
#else
    CONTEXT         context = { 0 };
#endif

#if _WIN64
    context.ContextFlags = WOW64_CONTEXT_CONTROL;
#else
    context.ContextFlags = CONTEXT_CONTROL;
#endif

#if _WIN64
    Wow64GetThreadContext( hThread, &context );
#else
    GetThreadContext( hThread, &context );
#endif

    DWORD   nextAddr = context.Ebp;
    DWORD   retAddr = context.Eip;

    for ( int i = 0; i < MaxStackDepth; i++ )
    {
        frame.Eip = retAddr;
        frame.Ebp = nextAddr;

        stack.push_back( frame );

        if ( nextAddr == 0 )
            break;

        BOOL    bRet = FALSE;
        SIZE_T  bytesRead = 0;

        bRet = ReadProcessMemory( hProcess, (void*) (nextAddr+sizeof nextAddr), &retAddr, sizeof retAddr, &bytesRead );
        if ( !bRet )
            break;

        bRet = ReadProcessMemory( hProcess, (void*) nextAddr, &nextAddr, sizeof nextAddr, &bytesRead );
        if ( !bRet )
            break;
    }
}
Exemple #3
0
ErrorCode Thread::readCPUState(Architecture::CPUState &state) {
  CONTEXT context;

  memset(&context, 0, sizeof(context));
  context.ContextFlags = CONTEXT_INTEGER |        // GP registers.
                         CONTEXT_CONTROL |        // Some more GP + CPSR.
                         CONTEXT_FLOATING_POINT | // FP registers.
                         CONTEXT_DEBUG_REGISTERS; // Debug registers.

  BOOL result = GetThreadContext(_handle, &context);
  if (!result) {
    return Platform::TranslateError();
  }

  // GP registers + CPSR.
  state.gp.r0 = context.R0;
  state.gp.r1 = context.R1;
  state.gp.r2 = context.R2;
  state.gp.r3 = context.R3;
  state.gp.r4 = context.R4;
  state.gp.r5 = context.R5;
  state.gp.r6 = context.R6;
  state.gp.r7 = context.R7;
  state.gp.r8 = context.R8;
  state.gp.r9 = context.R9;
  state.gp.r10 = context.R10;
  state.gp.r11 = context.R11;
  state.gp.ip = context.R12;
  state.gp.sp = context.Sp;
  state.gp.lr = context.Lr;
  state.gp.pc = context.Pc;
  state.gp.cpsr = context.Cpsr;

  if (state.isThumb()) {
    if (state.gp.pc & 1ULL) {
      DS2LOG(Debug, "removing thumb bit from pc and lr");
      state.gp.pc &= ~1ULL;
    } else {
      DS2LOG(Warning,
             "CPU is in thumb mode but doesn't have thumb bit set in pc");
    }
  }

  // TODO(sas): Handle floating point and debug registers.

  return kSuccess;
}
Exemple #4
0
BOOL CDbgHook::OnExceptionDbgEvent(DEBUG_EVENT& de, IHookWorker& Work)
{
	PVOID lpAddr;
	hsOrgOpcode::iterator it;
	hsFuncName::iterator it2;
	BYTE Int3 = 0xCC;
	CONTEXT ctx;

	if (de.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_BREAKPOINT)
		return FALSE;

	lpAddr = de.u.Exception.ExceptionRecord.ExceptionAddress;

	//Original Opcode를 구한다.
	it = OrgBytes.find(lpAddr);

	if (it == OrgBytes.end())
		return FALSE;

	//해당 함수명을 구한다.
	it2 = Funcs.find(lpAddr);

	if (it2 == Funcs.end())
		return FALSE;

	//할 일을 한다.
	Work.Worker(lpAddr, it2->second);

	//Eip조정
	ctx.ContextFlags = CONTEXT_CONTROL;
	GetThreadContext(m_cpdi.hThread, &ctx);

	ctx.Eip = (DWORD)lpAddr;
	SetThreadContext(m_cpdi.hThread, &ctx);


	//Unhook
	WriteProcessMemory(m_cpdi.hProcess, lpAddr, &it->second, sizeof(it->second), NULL);

	ContinueDebugEvent(de.dwProcessId, de.dwThreadId, DBG_CONTINUE);
	Sleep(0);

	//Hook
	WriteProcessMemory(m_cpdi.hProcess, lpAddr, &Int3, sizeof(Int3), NULL);

	return TRUE;
}
Exemple #5
0
int
main(int argc, char *argv[])
{
  HANDLE thread;
  DWORD thread_id;
  CONTEXT context;

  context.ContextFlags=CONTEXT_CONTROL;

  z=0;
  thread=CreateThread(NULL,
                      0x1000,
                      (LPTHREAD_START_ROUTINE)thread_1,
                      NULL,
                      0,
                      &thread_id);

  if(!thread)
  {
    printf("Error: could not create thread ...\n");
    ExitProcess(0);
  }

  Sleep(1000);

  SuspendThread(thread);

  for(;;)
  {
    printf("%lx ", z);
    Sleep(100);x++;
    if(x>100 && GetThreadContext(thread, &context))
    {
#if defined(_M_IX86)
      printf("EIP: %lx\n", context.Eip);
#elif defined(_M_AMD64)
      printf("RIP: %p\n", context.Rip);
#endif
      printf("Calling resumethread ... \n");
      ResumeThread(thread);
    }
  }

  ExitProcess(0);
  return(0);
}
Exemple #6
0
static u_long
get_thrpc (HANDLE thr)
{
  CONTEXT ctx;
  u_long pc;
  int res;

  res = SuspendThread (thr);
  if (res == -1)
    return (u_long) - 1;
  ctx.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
  pc = (u_long) - 1;
  if (GetThreadContext (thr, &ctx))
    pc = ctx.Eip;
  ResumeThread (thr);
  return pc;
}
bool CODebugger::GetCPUContext(HANDLE hhThread, DEBUGGER_CPU *cpu)
{
	CONTEXT		ctx;

	ctx.ContextFlags = CONTEXT_FULL;
	if (!GetThreadContext(hhThread, &ctx)) 
	{
		return false;
	}

	cpu->EAX = ctx.Eax;
	cpu->ECX = ctx.Ecx;
	cpu->EDX = ctx.Edx;
	cpu->EBX = ctx.Ebx;
	cpu->ESI = ctx.Esi;
	cpu->EDI = ctx.Edi;
	cpu->EBP = ctx.Ebp;
	cpu->ESP = ctx.Esp;
	cpu->EIP = ctx.Eip;
	cpu->CS = ctx.SegCs;
	cpu->DS = ctx.SegDs;
	cpu->ES = ctx.SegEs;
	cpu->FS = ctx.SegFs;
	cpu->GS = ctx.SegGs;
	cpu->SS = ctx.SegSs;
	cpu->EFlags = ctx.EFlags;

	memcpy(cpu->ST0,&ctx.FloatSave.RegisterArea[00],10);
	memcpy(cpu->ST1,&ctx.FloatSave.RegisterArea[10],10);
	memcpy(cpu->ST2,&ctx.FloatSave.RegisterArea[20],10);
	memcpy(cpu->ST3,&ctx.FloatSave.RegisterArea[30],10);
	memcpy(cpu->ST4,&ctx.FloatSave.RegisterArea[40],10);
	memcpy(cpu->ST5,&ctx.FloatSave.RegisterArea[50],10);
	memcpy(cpu->ST6,&ctx.FloatSave.RegisterArea[60],10);
	memcpy(cpu->ST7,&ctx.FloatSave.RegisterArea[70],10);
	
	/*cpu->XMM1 = ctx.Xmm1;
	cpu->XMM2 = ctx.Xmm2;
	cpu->XMM3 = ctx.Xmm3;
	cpu->XMM4 = ctx.Xmm4;
	cpu->XMM5 = ctx.Xmm5;
	cpu->XMM6 = ctx.Xmm6;
	cpu->XMM7 = ctx.Xmm7;*/

	return true;
}
//--------------------------------------------------------------------------
ea_t wince_debmod_t::is_hwbpt_triggered(thid_t id, bool /*is_stepping*/)
{
  if ( is_xscale )
  {
    uint32 dcsr = SetDebugControlAndStatus(0, 0);
    int moe = (dcsr >> 2) & 7;  // method of entry (exception reason)
    //    msg("moe=%d\n", moe);
    switch ( moe )
    {
    case 1: // Instruction Breakpoint Hit
    case 2: // Data Breakpoint Hit
      {
        SetDebugControlAndStatus(0, 7<<2); // clean moe
        CONTEXT Context;
        Context.ContextFlags = CONTEXT_CONTROL;
        HANDLE h = get_thread_handle(id);
        if ( GetThreadContext(h, &Context) )
        {
          ea_t ea = s0tops(Context.Pc);
          if ( s0tops(codebpts[0]) == ea || s0tops(codebpts[1]) == ea )
          {
            //              msg("HARDWARE CODE BREAKPOINT!\n");
            return ea;
          }
          // This is a data breakpoint
          // Set PC to the next instruction since the data bpts always occur
          // AFTER the instruction
#define THUMB_STATE 0x0020
          Context.Pc += (Context.Psr & THUMB_STATE)? 2 : 4;
          SetThreadContext(h, &Context);
        }
        // FIXME: determine which data bpt really caused the exception
        // Currently we just return the first active bpt
        return databpts[0] != BADADDR ? databpts[0] : databpts[1];
      }
    case 0: // Processor Reset
    case 3: // BKPT Instruction Executed
    case 4: // External Debug Event (JTAG Debug Break or SOC Debug Break)
    case 5: // Vector Trap Occurred
    case 6: // Trace Buffer Full Break
    case 7: // Reserved
      break;
    }
  }
  return BADADDR;
}
Exemple #9
0
void DumpThreads(void)
{
	HANDLE	snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, GetCurrentProcessId());
	if(snapshot != INVALID_HANDLE_VALUE)
	{
		THREADENTRY32	info;

		info.dwSize = sizeof(info);

		if(Thread32First(snapshot, &info))
		{
			do 
			{
				if(info.th32OwnerProcessID == GetCurrentProcessId())
				{
					UInt32	eip = 0xFFFFFFFF;

					HANDLE	thread = OpenThread(THREAD_GET_CONTEXT, FALSE, info.th32ThreadID);
					if(thread)
					{
						CONTEXT	ctx;

						ctx.ContextFlags = CONTEXT_CONTROL;

						GetThreadContext(thread, &ctx);

						eip = ctx.Eip;

						CloseHandle(thread);
					}

					_MESSAGE("thread %d pri %d eip %08X%s",
						info.th32ThreadID,
						info.tpBasePri,
						eip,
						(info.th32ThreadID == GetCurrentThreadId()) ? " current thread" : "");
				}

				info.dwSize = sizeof(info);
			}
			while(Thread32Next(snapshot, &info));
		}

		CloseHandle(snapshot);
	}
}
Exemple #10
0
/* BreakpointAction - Do work!
 * BreakpointAction sets the process into SINGLE_STEP mode so you can easily know when
 * the CPU finishes the instruction (Thanks to DarkStorm for this inspiration)
 * It then removes the Breakpoint and calls the callback, if present.
 */
void BreakpointAction(Breakpoint *BPX, HANDLE threadhandle)
{
   static CONTEXT context;
   memset(&context, 0, sizeof(context));

   context.ContextFlags=CONTEXT_FULL;
   GetThreadContext(threadhandle, &context);
   context.Eip=(DWORD)(LRESULT)BPX->Address;
   context.EFlags|= 0x0100; /* Single step */
   SetThreadContext(threadhandle, &context);

   RemoveBreakpoint(BPX);

   if(BPX->CallbackFunc)
      BPX->CallbackFunc(BPX->TargetProcess, BPX->dbgev, &context, BPX->type);
   return;
}
Exemple #11
0
static void
set_step_threads (int threadId, int trace)
{
  int rv, tix;
  HANDLE thread = lookup_thread_id (threadId, &tix);

  rv = GetThreadContext (thread, &context);
  if (rv != -1)
    {
      thread_step_flags[tix] = trace;
      if (trace)
	context.EFlags |= 0x100; /* TRAP (single step) flag */
      else
	context.EFlags &= ~0x100; /* TRAP (single step) flag */
      SetThreadContext (thread, &context);
    }
}
Exemple #12
0
BOOL fClearTrapFlag(CHL_HTABLE *phtThreads, DWORD dwThreadId)
{
    ASSERT(phtThreads);
    ASSERT(dwThreadId > 0);

    HANDLE hThread;
    CONTEXT stThreadContext;

    if(!fGetThreadHandle(phtThreads, dwThreadId, &hThread))
    {
        logerror(pstLogger, L"%s(): Cannot get thread handle for thread %u", __FUNCTIONW__, dwThreadId);
        goto error_return;
    }

    ZeroMemory(&stThreadContext, sizeof(CONTEXT));

    stThreadContext.ContextFlags = CONTEXT_CONTROL;
    if(!GetThreadContext(hThread, &stThreadContext))
    {
        logerror(pstLogger, L"%s(): GetThreadContext failed %u", __FUNCTIONW__, GetLastError());
        goto error_return;
    }

    dbgwprintf(L"Clearing TF...\n");

    vPrintBits(stThreadContext.EFlags);
    dbgwprintf(L" : EFLAGS before\n");

    stThreadContext.EFlags &= ~(1 << BITPOS_EFLAGS_TF);

    vPrintBits(stThreadContext.EFlags);
    dbgwprintf(L" : EFLAGS after\n");

    stThreadContext.ContextFlags = CONTEXT_CONTROL;
    if(!SetThreadContext(hThread, &stThreadContext))
    {
        logerror(pstLogger, L"%s(): SetThreadContext failed %u", __FUNCTIONW__, GetLastError());
        goto error_return;
    }

    return TRUE;

error_return:
    return FALSE;
}
Exemple #13
0
/**
*	Process session request
*
*	This service implements the OS independent API for sending requests to the environment.
*	This session is Windows specific and so will call the operating system. The NDBG executive
*	session manager would send requests over PIPE to NDBG executive debugger server instead.
*
*	\param request Session request
*	\param session Debug session
*	\param addr Optional data address
*	\param data Optional data buffer
*	\param size Optional data buffer size
*	\ret The number of bytes read or written OR TRUE on success, FALSE on failure depending on request
*
*/
unsigned long DbgProcessRequest (IN dbgProcessReq request, IN dbgSession* session,
	IN OPT void* addr, IN OUT OPT void* data, IN OPT size_t size) {

	switch(request) {
		case DBG_REQ_READ: {
			unsigned long bytesRead = 0;
			ReadProcessMemory ((HANDLE)session->process.process,(LPCVOID) addr,data,size, &bytesRead);
			if (bytesRead==0)
				DbgDisplayError("Unable to read process memory. Error code: 0x%x", GetLastError());
			return bytesRead;
		}
		case DBG_REQ_WRITE: {
			unsigned long bytesRead = 0;
			WriteProcessMemory ((HANDLE)session->process.process,(LPCVOID) addr,data,size, &bytesRead);
			if (bytesRead==0)
				DbgDisplayError("Unable to write process memory. Error code: 0x%x", GetLastError());
			return bytesRead;
		}
		case DBG_REQ_GETCONTEXT: {
			CONTEXT context;
			context.ContextFlags = CONTEXT_ALL;

			if (! GetThreadContext ((HANDLE)session->process.thread, &context))
				return FALSE;

			DbgContextFromWin32 (&context, (dbgContext*)data);
			return TRUE;
		}
		case DBG_REQ_SETCONTEXT: {
			return SetThreadContext ((HANDLE)session->process.thread, (LPCONTEXT)data);
		}
		case DBG_REQ_CONTINUE: {
			if (ResumeThread ((HANDLE)session->process.thread) == -1)
				return FALSE;
			return TRUE;
		}
		case DBG_REQ_BREAK: {
			return DebugBreakProcess ((HANDLE)session->process.process);
		}
		case DBG_REQ_STOP:
		default:
			printf ("\nDBG_REQ_STOP Not implemented");
			return 0;
	};
}
Exemple #14
0
void InitializeDLLInjection(PROCESS_INFORMATION PI)
{
	HANDLE memPage;
    UNICODE_STRING str;
	DWORD temp;
	CONTEXT ctx;
	WCHAR tapz[] = L"trace.dll";
	
	// Gets thread context
	ctx.ContextFlags = CONTEXT_FULL;
	GetThreadContext(PI.hThread, &ctx);
	
	// Gets LdrLoadDll address and patch it into the shellcode
	temp = (DWORD)GetModuleHandle("ntdll.dll");
	temp = (DWORD)GetProcAddress((HANDLE)temp, "LdrLoadDll");
	*((DWORD*)((int)bytecode + 17)) = temp;
	
	// Allocates our working page
	if( !( memPage = VirtualAllocEx(PI.hProcess, NULL, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) ) )
	{
		printf("Coudln't allocate buffer. Error code 0x%x\n", (int)GetLastError());
		exit(-1);
	}
	// Creates an unicode string
	str.Length = 18;
	str.MaximumLength = 20;
	str.Buffer = (LPVOID)(((int)memPage) + 10);
	
	// patch module handle address (returned by LdrLoadDll)
	*((DWORD*)((int)bytecode + 3)) = (DWORD)(((int)memPage) + 500);
	// patch UNICODE_STRING address
	*((DWORD*)((int)bytecode + 8)) = (DWORD)memPage;
	// Patch EIP address (used in the trick push/ret)
	*((DWORD*)((int)bytecode + 25)) = ctx.Eip;
	//Write all this sh*t
	WriteProcessMemory (PI.hProcess, (LPVOID)memPage, &str, sizeof(UNICODE_STRING), &temp);
	WriteProcessMemory (PI.hProcess, (LPVOID)(((int)memPage) + 10), (HANDLE)tapz, 20, &temp);
	WriteProcessMemory (PI.hProcess, (LPVOID)(((int)memPage) + 50), bytecode, 200, &temp);
	// Set our new eip
	ctx.Eip = (DWORD)(((int)memPage) + 50);
	
	//Set context
	SetThreadContext(PI.hThread, &ctx);	
	ResumeThread(PI.hThread);
}
Exemple #15
0
static DWORD WINAPI profile_bt( LPVOID lparam )
{
    // Note: illegal to use jl_* functions from this thread

    TIMECAPS tc;
    if (MMSYSERR_NOERROR!=timeGetDevCaps(&tc, sizeof(tc))) {
        fputs("failed to get timer resolution",stderr);
        hBtThread = 0;
        return 0;
    }
    while (1) {
        if (running && bt_size_cur < bt_size_max) {
            DWORD timeout = nsecprof/GIGA;
            timeout = min(max(timeout,tc.wPeriodMin*2),tc.wPeriodMax/2);
            Sleep(timeout);
            if ((DWORD)-1 == SuspendThread(hMainThread)) {
                fputs("failed to suspend main thread. aborting profiling.",stderr);
                break;
            }
            CONTEXT ctxThread;
            memset(&ctxThread, 0, sizeof(CONTEXT));
            ctxThread.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
            if (!GetThreadContext(hMainThread, &ctxThread)) {
                fputs("failed to get context from main thread. aborting profiling.",stderr);
                break;
            }
            // Get backtrace data
            bt_size_cur += rec_backtrace_ctx((uintptr_t*)bt_data_prof + bt_size_cur,
                bt_size_max - bt_size_cur - 1, &ctxThread);
            // Mark the end of this block with 0
            bt_data_prof[bt_size_cur] = 0;
            bt_size_cur++;
            if ((DWORD)-1 == ResumeThread(hMainThread)) {
                fputs("failed to resume main thread! aborting.",stderr);
                gc_debug_critical_error();
                abort();
            }
        }
        else {
            SuspendThread(GetCurrentThread());
        }
    }
    hBtThread = 0;
    return 0;
}
Exemple #16
0
void ExecuteDeleteTask(int i)
{    CONTEXT ctx;
     assert(taskSuspended[i]==-1);

     DBGPRINT(0x00000004, "Delete task %d - go\n", i);
     SetThreadPriority(hTaskThread[i], THREAD_PRIORITY_TIME_CRITICAL);
     ctx.ContextFlags=CONTEXT_FULL;				// Modify the deleted task's thread context in such a way, that it calls RemoteExitThread
     GetThreadContext(hTaskThread[i], &ctx);			// when it is resumed
     ctx.Eip=(DWORD) RemoteExitThread;
     SetThreadContext(hTaskThread[i], &ctx);
     ResumeThread(hTaskThread[i]);				// Resume the thread, so that it can terminate itself
     WaitForSingleObject(hTaskThread[i], INFINITE);
     CloseHandle(hTaskThread[i]);
     hTaskThread[i] = NULL;
     pTaskTcb[i]=NULL;
     taskSuspended[i] = 0;
     DBGPRINT(0x00000004, "Delete task %d - done\n", i);
}
Exemple #17
0
/* called from int1 handler, returns true if a hardware breakpoint was triggered in the current task */
int hbpCheck(THREAD *tThread)
{
    CONTEXT ctx;
    if (!tThread)
        return 0;
    ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
    GetThreadContext(tThread->hThread, &ctx);
    if (ctx.Dr6 &15)
    {
        int i;
        for (i = 0; i < 4; i++)
            if (ctx.Dr6 &(1 << i))
                ExtendedMessageBox("Hardware Breakpoint", MB_SYSTEMMODAL |
                    MB_SETFOREGROUND, "Hardware breakpoint for %s triggered",
                    hdwebp[i].name);
    }
    return ctx.Dr6 &15;
}
Exemple #18
0
void *VDThread::ThreadLocation() const {
	if (!isThreadAttached())
		return NULL;

	CONTEXT ctx;

	ctx.ContextFlags = CONTEXT_CONTROL;

	SuspendThread(mhThread);
	GetThreadContext(mhThread, &ctx);
	ResumeThread(mhThread);

#ifdef _M_AMD64
	return (void *)ctx.Rip;
#else
	return (void *)ctx.Eip;
#endif
}
Exemple #19
0
static VOID
thread_timer_expired (HANDLE thread)
{
	CONTEXT context;

	context.ContextFlags = CONTEXT_CONTROL;
	if (GetThreadContext (thread, &context)) {
		guchar *ip;

#ifdef _WIN64
		ip = (guchar *) context.Rip;
#else
		ip = (guchar *) context.Eip;
#endif

		MONO_PROFILER_RAISE (sample_hit, (ip, &context));
	}
}
Exemple #20
0
Res MutatorContextInitThread(MutatorContext context, HANDLE thread)
{
  BOOL success;

  AVER(context != NULL);

  context->var = MutatorContextTHREAD;
  /* This dumps the relevant registers into the context */
  /* .context.flags */
  context->the.context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
  success = GetThreadContext(thread, &context->the.context);
  if (!success)
    return ResFAIL;
  context->sig = MutatorContextSig;

  AVERT(MutatorContext, context);
  return ResOK;
}
void CALLBACK _papi_hwd_timer_callback(UINT wTimerID, UINT msg, 
        DWORD dwUser, DWORD dw1, DWORD dw2) 
{
	HANDLE	threadHandle;
	BOOL	error;

	// dwUser is the threadID passed by timeSetEvent
	// NOTE: This call requires W2000 or later
	threadHandle = OpenThread(THREAD_GET_CONTEXT, FALSE, dwUser);

	// retrieve the contents of the control registers only
	context.ContextFlags = CONTEXT_CONTROL;
	error = GetThreadContext(threadHandle, &context);
	CloseHandle(threadHandle);

	// pass a void pointer to cpu register data here
	_papi_hwi_dispatch_overflow_signal((void *)(&context)); 
} 
Exemple #22
0
static unsigned dbg_fetch_context(void)
{
    dbg_context.ContextFlags = CONTEXT_CONTROL
                               | CONTEXT_INTEGER | CONTEXT_FLOATING_POINT
#ifdef CONTEXT_SEGMENTS
                               | CONTEXT_SEGMENTS
#endif
#ifdef CONTEXT_DEBUG_REGISTERS
                               | CONTEXT_DEBUG_REGISTERS
#endif
                               ;
    if (!GetThreadContext(dbg_curr_thread->handle, &dbg_context))
    {
        WINE_WARN("Can't get thread's context\n");
        return FALSE;
    }
    return TRUE;
}
Exemple #23
0
gboolean
mono_threads_suspend_begin_async_resume (MonoThreadInfo *info)
{
	DWORD id = mono_thread_info_get_tid (info);
	HANDLE handle;
	DWORD result;

	handle = OpenThread (THREAD_ALL_ACCESS, FALSE, id);
	g_assert (handle);

	if (info->async_target) {
		MonoContext ctx;
		CONTEXT context;
		gboolean res;

		ctx = info->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX].ctx;
		mono_threads_get_runtime_callbacks ()->setup_async_callback (&ctx, info->async_target, info->user_data);
		info->async_target = info->user_data = NULL;

		context.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL;

		if (!GetThreadContext (handle, &context)) {
			CloseHandle (handle);
			return FALSE;
		}

		g_assert (context.ContextFlags & CONTEXT_INTEGER);
		g_assert (context.ContextFlags & CONTEXT_CONTROL);

		mono_monoctx_to_sigctx (&ctx, &context);

		context.ContextFlags = CONTEXT_INTEGER | CONTEXT_CONTROL;
		res = SetThreadContext (handle, &context);
		if (!res) {
			CloseHandle (handle);
			return FALSE;
		}
	}

	result = ResumeThread (handle);
	CloseHandle (handle);

	return result != (DWORD)-1;
}
Exemple #24
0
static BOOL WINAPI sigint_handler(DWORD wsig) //This needs winapi types to guarantee __stdcall
{
    if (exit_on_sigint) jl_exit(0);
    int sig;
    //windows signals use different numbers from unix (raise)
    switch(wsig) {
        case CTRL_C_EVENT: sig = SIGINT; break;
        //case CTRL_BREAK_EVENT: sig = SIGTERM; break;
        // etc.
        default: sig = SIGTERM; break;
    }
    if (jl_defer_signal) {
        jl_signal_pending = sig;
    }
    else {
        jl_signal_pending = 0;
        if ((DWORD)-1 == SuspendThread(hMainThread)) {
            //error
            jl_safe_printf("error: SuspendThread failed\n");
            return 0;
        }
        CONTEXT ctxThread;
        memset(&ctxThread,0,sizeof(CONTEXT));
        ctxThread.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
        if (!GetThreadContext(hMainThread, &ctxThread)) {
            //error
            jl_safe_printf("error: GetThreadContext failed\n");
            return 0;
        }
        jl_throw_in_ctx(jl_interrupt_exception, &ctxThread, 1);
        ctxThread.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
        if (!SetThreadContext(hMainThread,&ctxThread)) {
            jl_safe_printf("error: SetThreadContext failed\n");
            //error
            return 0;
        }
        if ((DWORD)-1 == ResumeThread(hMainThread)) {
            jl_safe_printf("error: ResumeThread failed\n");
            //error
            return 0;
        }
    }
    return 1;
}
void add_thread(HANDLE thread)
{
		  CONTEXT ctx = {CONTEXT_DEBUG_REGISTERS};

//DR7=d0000540 DR6=ffff0ff0 DR3=53ffa0 DR2=0 DR1=0 DR0=0

    SuspendThread(thread);
    GetThreadContext(thread,&ctx);
	ctx.Dr7=0xd0000540;
	ctx.Dr6=0xffff0ff0;
	ctx.Dr3=MAGICESPINLSA;
	ctx.Dr2=0;
	ctx.Dr1=0;
	ctx.Dr0=0;
    SetThreadContext(thread, &ctx);
    ResumeThread(thread);
//    printf("DR7=%x DR6=%x DR3=%x DR2=%x DR1=%x DR0=%x\n",ctx.Dr7,ctx.Dr6,ctx.Dr3,ctx.Dr2,ctx.Dr1,ctx.Dr0);

}
bool CODebugger::SetEIP(HANDLE hThread,unsigned int uiNewEIP) 
{
	CONTEXT	ctx;

	ctx.ContextFlags = CONTEXT_CONTROL;
	if(!GetThreadContext(hThread, &ctx)) 
	{		
		return false;
	}

	ctx.Eip = uiNewEIP;

	if(!SetThreadContext(hThread, &ctx)) 
	{		
		return false;
	}

	return true;
}
void ExerciseThread
(
    HANDLE     hThread,
    PARAMETERS myParameters
)
{

    CONTEXT Context;
    BOOL bError;

    if (myParameters.nSleepTime != 0)
    {
        Sleep(myParameters.nSleepTime);
    }

    if (myParameters.bSuspend == TRUE)
    {
        if ((SuspendThread(hThread) == -1) && (myParameters.bVerbose == TRUE))
        {
            print("Error in SuspendThread()(Code %d)\n",GetLastError());
        }
        if ((ResumeThread(hThread) == -1) && (myParameters.bVerbose == TRUE))
        {
            print("Error in ResumeThread() (Code %d)\n",GetLastError());			
        }
    }
    if (myParameters.bGetContext == TRUE)
    {
        bError = GetThreadContext(hThread, &Context);
        if ((bError == 0) && (myParameters.bVerbose == TRUE))
        {
            print("Error in GetThreadContext (Code %d)\n",GetLastError());			
        }
    }
    if ((myParameters.bSetContext == TRUE) && (myParameters.bVerbose == TRUE))
    {
        bError = SetThreadContext(hThread, &Context);
        if ((bError == 0)  && (myParameters.bVerbose == TRUE))
        {
            print("Error in SetThreadContext (Code %d)\n",GetLastError());			
        }
    }
}
Exemple #28
0
void init_scheduler()
{
	memset(&default_context, 0, sizeof(default_context));
	HANDLE CPUCore = (HANDLE)CreateThread(NULL, 0, NULL, 0, CREATE_SUSPENDED, NULL);
	if (CPUCore == NULL)
	{
		SetEvent(error_event);
		return;
	}

	default_context.ContextFlags = CONTEXT_FULL;
	GetThreadContext(CPUCore, &default_context);

	memset(core_req_pause, 0, CORE_COUNT*sizeof(bool));
	memset(core_req_resume, 0, CORE_COUNT*sizeof(bool));
	memset(core_paused, 0, CORE_COUNT*sizeof(bool));

	SetEvent(cpu_int_table_handlers[0][INT_SCHEDULER]);
}
void FWindowsPlatformStackWalk::ThreadStackWalkAndDump(ANSICHAR* HumanReadableString, SIZE_T HumanReadableStringSize, int32 IgnoreCount, uint32 ThreadId)
{
	InitStackWalking();
	HANDLE ThreadHandle = OpenThread(THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_TERMINATE | THREAD_SUSPEND_RESUME, false, ThreadId);
	if (ThreadHandle)
	{
		// Suspend the thread before grabbing its context (possible fix for incomplete callstacks)
		SuspendThread(ThreadHandle);
		// Give task scheduler some time to actually suspend the thread
		FPlatformProcess::Sleep(0.01f);
		CONTEXT ThreadContext;
		ThreadContext.ContextFlags = CONTEXT_CONTROL;
		if (GetThreadContext(ThreadHandle, &ThreadContext))
		{
			FGenericPlatformStackWalk::StackWalkAndDump(HumanReadableString, HumanReadableStringSize, IgnoreCount, &ThreadContext);
		}
		ResumeThread(ThreadHandle);
	}
}
Exemple #30
0
void CALLBACK OSTickISR(unsigned int a,unsigned int b,unsigned long c,unsigned long d,unsigned long e)
{
    if(!FlagEn)
        return;                                             //如果当前中断被屏蔽则返回

    SuspendThread(mainhandle);                          //中止主线程的运行,模拟中断产生.但没有保存寄存器
    GetThreadContext(mainhandle, &Context);             //得到主线程上下文,为切换任务做准备

    OSIntNesting++;
    if (OSIntNesting == 1)
    {
        OSTCBCur->OSTCBStkPtr = (OS_STK *)Context.Esp;  //保存当前esp
    }
    OSTimeTick();                                       //ucos内部定时
    OSIntExit();                                        //由于不能使用中断返回指令,所以此函数是要返回的

    ResumeThread(mainhandle);                           //模拟中断返回,主线程得以继续执行

}