Ejemplo n.º 1
0
/*
 * @implemented
 */
LPVOID
WINAPI
ConvertThreadToFiberEx(LPVOID lpParameter, 
                       DWORD dwFlags)
{
    PTEB pTeb = NtCurrentTeb();
    PFIBER pfCurFiber;
    DPRINT1("Converting Thread to Fiber\n");

    /* the current thread is already a fiber */
    if(pTeb->HasFiberData && pTeb->NtTib.FiberData) return pTeb->NtTib.FiberData;

    /* allocate the fiber */
    pfCurFiber = (PFIBER)RtlAllocateHeap(GetProcessHeap(), 
                                         0,
                                         sizeof(FIBER));

    /* failure */
    if (pfCurFiber == NULL)
    {
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        return NULL;
    }

    /* copy some contextual data from the thread to the fiber */
    pfCurFiber->Parameter = lpParameter;
    pfCurFiber->ExceptionList = pTeb->NtTib.ExceptionList;
    pfCurFiber->StackBase = pTeb->NtTib.StackBase;
    pfCurFiber->StackLimit = pTeb->NtTib.StackLimit;
    pfCurFiber->DeallocationStack = pTeb->DeallocationStack;
    pfCurFiber->FlsData = pTeb->FlsData;
    pfCurFiber->GuaranteedStackBytes = pTeb->GuaranteedStackBytes;
    pfCurFiber->ActivationContextStack = pTeb->ActivationContextStackPointer;
    pfCurFiber->Context.ContextFlags = CONTEXT_FULL;

    /* Save FPU State if requsted */
    if (dwFlags & FIBER_FLAG_FLOAT_SWITCH)
    {
        pfCurFiber->Context.ContextFlags |= CONTEXT_FLOATING_POINT;
    }

    /* associate the fiber to the current thread */
    pTeb->NtTib.FiberData = pfCurFiber;
    pTeb->HasFiberData = TRUE;

    /* success */
    return (LPVOID)pfCurFiber;
}
Ejemplo n.º 2
0
Archivo: wdbg.cpp Proyecto: 2asoft/0ad
bool debug_IsStackPointer(void* p)
{
	uintptr_t addr = (uintptr_t)p;
	// totally invalid pointer
	if(debug_IsPointerBogus(p))
		return false;
	// not aligned
	if(addr % sizeof(void*))
		return false;
	// out of bounds (note: IA-32 stack grows downwards)
	NT_TIB* tib = (NT_TIB*)NtCurrentTeb();
	if(!(tib->StackLimit < p && p < tib->StackBase))
		return false;

	return true;
}
Ejemplo n.º 3
0
/***********************************************************************
 *           NE_InitDLL
 *
 * Call the DLL initialization code
 */
static BOOL NE_InitDLL( NE_MODULE *pModule )
{
    SEGTABLEENTRY *pSegTable;
    WORD hInst, ds, heap;
    CONTEXT context;

    pSegTable = NE_SEG_TABLE( pModule );

    if (!(pModule->ne_flags & NE_FFLAGS_LIBMODULE) ||
        (pModule->ne_flags & NE_FFLAGS_WIN32)) return TRUE; /*not a library*/

    /* Call USER signal handler for Win3.1 compatibility. */
    NE_CallUserSignalProc( pModule->self, USIG16_DLL_LOAD );

    if (!SELECTOROF(pModule->ne_csip)) return TRUE;  /* no initialization code */


    /* Registers at initialization must be:
     * cx     heap size
     * di     library instance
     * ds     data segment if any
     * es:si  command line (always 0)
     */

    memset( &context, 0, sizeof(context) );

    NE_GetDLLInitParams( pModule, &hInst, &ds, &heap );

    context.Ecx = heap;
    context.Edi = hInst;
    context.SegDs = ds;
    context.SegEs = ds;   /* who knows ... */
    context.SegFs = wine_get_fs();
    context.SegGs = wine_get_gs();
    context.SegCs = SEL(pSegTable[SELECTOROF(pModule->ne_csip)-1].hSeg);
    context.Eip   = OFFSETOF(pModule->ne_csip);
    context.Ebp   = OFFSETOF(NtCurrentTeb()->WOW32Reserved) + FIELD_OFFSET(STACK16FRAME,bp);

    pModule->ne_csip = 0;  /* Don't initialize it twice */
    TRACE_(dll)("Calling LibMain for %.*s, cs:ip=%04x:%04x ds=%04x di=%04x cx=%04x\n",
                *((BYTE*)pModule + pModule->ne_restab),
                (char *)pModule + pModule->ne_restab + 1,
                context.SegCs, context.Eip, context.SegDs,
                LOWORD(context.Edi), LOWORD(context.Ecx) );
    WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&context );
    return TRUE;
}
Ejemplo n.º 4
0
Archivo: dc.c Proyecto: GYGit/reactos
/*
 * @unimplemented
 */
int
WINAPI
SetGraphicsMode(
    _In_ HDC hdc,
    _In_ int iMode)
{
    INT iOldMode;
    PDC_ATTR pdcattr;

    /* Check parameters */
    if ((iMode < GM_COMPATIBLE) || (iMode > GM_ADVANCED))
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }

    /* Get the DC attribute */
    pdcattr = GdiGetDcAttr(hdc);
    if (pdcattr == NULL)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }

    /* Check for trivial case */
    if (iMode == pdcattr->iGraphicsMode)
        return iMode;

    if (NtCurrentTeb()->GdiTebBatch.HDC == hdc)
    {
        if (pdcattr->ulDirty_ & DC_MODE_DIRTY)
        {
            NtGdiFlush(); // Sync up pdcattr from Kernel space.
            pdcattr->ulDirty_ &= ~(DC_MODE_DIRTY|DC_FONTTEXT_DIRTY);
        }
    }

    /* One would think that setting the graphics mode to GM_COMPATIBLE
     * would also reset the world transformation matrix to the unity
     * matrix. However, in Windows, this is not the case. This doesn't
     * make a lot of sense to me, but that's the way it is.
     */
    iOldMode = pdcattr->iGraphicsMode;
    pdcattr->iGraphicsMode = iMode;

    return iOldMode;
}
Ejemplo n.º 5
0
void
__except_validate_context_record (
    _In_ PCONTEXT ContextRecord
    )

/*++

Routine Description:

    This function validates a context record for exception handling support.

Arguments:

    ContextRecord - Supplies a pointer to the context record to validate.

Return Value:

    None.  If the context record was not valid, a fast fail event is raised if
    CFG was enforced.

--*/

{
    PVOID StackPointer;
    PNT_TIB Tib;

    //
    // If guard ICall checks are enforced, then validate the stack extents of
    // the context record and raise a fast fail exception if the extents are
    // invalid.  If checks are not enforced or the jump buffer was valid, then
    // return.
    //
    if (_guard_icall_checks_enforced()) {
        Tib = (PNT_TIB)NtCurrentTeb();

        //
        // HYB-TODO: Validate both chpe and guest context.
        //

        StackPointer = (PVOID)CONTEXT_TO_STACK_POINTER(ContextRecord);
        if ((StackPointer < Tib->StackLimit) ||
            (StackPointer > Tib->StackBase)) {

            __fastfail(FAST_FAIL_INVALID_SET_OF_CONTEXT);
        }
    }
}
Ejemplo n.º 6
0
/***********************************************************************
 *           SystemHeapInfo   (TOOLHELP.71)
 */
BOOL16 WINAPI SystemHeapInfo16( SYSHEAPINFO *pHeapInfo )
{
    STACK16FRAME* stack16 = MapSL((SEGPTR)NtCurrentTeb()->WOW32Reserved);
    HANDLE16 oldDS = stack16->ds;
    WORD user = LoadLibrary16( "USER.EXE" );
    WORD gdi = LoadLibrary16( "GDI.EXE" );
    stack16->ds = user;
    pHeapInfo->wUserFreePercent = (int)LocalCountFree16() * 100 / LocalHeapSize16();
    stack16->ds = gdi;
    pHeapInfo->wGDIFreePercent  = (int)LocalCountFree16() * 100 / LocalHeapSize16();
    stack16->ds = oldDS;
    pHeapInfo->hUserSegment = user;
    pHeapInfo->hGDISegment  = gdi;
    FreeLibrary16( user );
    FreeLibrary16( gdi );
    return TRUE;
}
Ejemplo n.º 7
0
static void NE_CallDllEntryPoint( NE_MODULE *pModule, DWORD dwReason )
{
    WORD hInst, ds, heap;
    FARPROC16 entryPoint;

    if (!(pModule->ne_flags & NE_FFLAGS_LIBMODULE)) return;
    if (!(pModule->ne_flags & NE_FFLAGS_BUILTIN) && pModule->ne_expver < 0x0400) return;
    if (!(entryPoint = GetProcAddress16( pModule->self, "DllEntryPoint" ))) return;

    NE_GetDLLInitParams( pModule, &hInst, &ds, &heap );

    TRACE_(dll)( "Calling %s DllEntryPoint, cs:ip=%04x:%04x\n",
                 NE_MODULE_NAME( pModule ),
                 SELECTOROF(entryPoint), OFFSETOF(entryPoint) );

    if ( pModule->ne_flags & NE_FFLAGS_BUILTIN )
    {
        WinNEEntryProc entryProc = (WinNEEntryProc)((ENTRYPOINT16 *)MapSL( (SEGPTR)entryPoint ))->target;

        entryProc( dwReason, hInst, ds, heap, 0, 0 );
    }
    else
    {
        CONTEXT context;
        WORD args[8];

        memset( &context, 0, sizeof(context) );
        context.SegDs = ds;
        context.SegEs = ds;   /* who knows ... */
        context.SegFs = wine_get_fs();
        context.SegGs = wine_get_gs();
        context.SegCs = HIWORD(entryPoint);
        context.Eip   = LOWORD(entryPoint);
        context.Ebp   = OFFSETOF(NtCurrentTeb()->WOW32Reserved) + FIELD_OFFSET(STACK16FRAME,bp);

        args[7] = HIWORD(dwReason);
        args[6] = LOWORD(dwReason);
        args[5] = hInst;
        args[4] = ds;
        args[3] = heap;
        args[2] = 0;     /* HIWORD(dwReserved1) */
        args[1] = 0;     /* LOWORD(dwReserved1) */
        args[0] = 0;     /* wReserved2 */
        WOWCallback16Ex( 0, WCB16_REGS, sizeof(args), args, (DWORD *)&context );
    }
}
Ejemplo n.º 8
0
HANDLE
APIENTRY
CreateMutexA(
    LPSECURITY_ATTRIBUTES lpMutexAttributes,
    BOOL bInitialOwner,
    LPCSTR lpName
)

/*++

Routine Description:

    ANSI thunk to CreateMutexW

--*/

{
    PUNICODE_STRING Unicode;
    ANSI_STRING AnsiString;
    NTSTATUS Status;
    LPCWSTR NameBuffer;

    NameBuffer = NULL;
    if ( ARGUMENT_PRESENT(lpName) ) {
        Unicode = &NtCurrentTeb()->StaticUnicodeString;
        RtlInitAnsiString(&AnsiString,lpName);
        Status = RtlAnsiStringToUnicodeString(Unicode,&AnsiString,FALSE);
        if ( !NT_SUCCESS(Status) ) {
            if ( Status == STATUS_BUFFER_OVERFLOW ) {
                SetLastError(ERROR_FILENAME_EXCED_RANGE);
            }
            else {
                BaseSetLastNTError(Status);
            }
            return NULL;
        }

        NameBuffer = (LPCWSTR)Unicode->Buffer;
    }

    return CreateMutexW(
               lpMutexAttributes,
               bInitialOwner,
               NameBuffer
           );
}
Ejemplo n.º 9
0
HANDLE
APIENTRY
OpenFileMappingA(
    DWORD dwDesiredAccess,
    BOOL bInheritHandle,
    LPCSTR lpName
    )

/*++

Routine Description:

    ANSI thunk to OpenFileMappingW

--*/

{
    PUNICODE_STRING Unicode;
    ANSI_STRING AnsiString;
    NTSTATUS Status;

    if ( ARGUMENT_PRESENT(lpName) ) {
        Unicode = &NtCurrentTeb()->StaticUnicodeString;
        RtlInitAnsiString(&AnsiString,lpName);
        Status = RtlAnsiStringToUnicodeString(Unicode,&AnsiString,FALSE);
        if ( !NT_SUCCESS(Status) ) {
            if ( Status == STATUS_BUFFER_OVERFLOW ) {
                SetLastError(ERROR_FILENAME_EXCED_RANGE);
                }
            else {
                BaseSetLastNTError(Status);
                }
            return NULL;
            }
        }
    else {
        BaseSetLastNTError(STATUS_INVALID_PARAMETER);
        return NULL;
        }

    return OpenFileMappingW(
                dwDesiredAccess,
                bInheritHandle,
                (LPCWSTR)Unicode->Buffer
                );
}
Ejemplo n.º 10
0
void UserDbgAssertThreadInfo(BOOL showCaller)
{
    PTEB Teb;
    PPROCESSINFO ppi;
    PCLIENTINFO pci;
    PTHREADINFO pti;

    ppi = PsGetCurrentProcessWin32Process();
    pti = PsGetCurrentThreadWin32Thread();
    Teb = NtCurrentTeb();
    pci = GetWin32ClientInfo();

    ASSERT(Teb);
    ASSERT(pti);
    ASSERT(pti->ppi == ppi);
    ASSERT(pti->pClientInfo == pci);
    ASSERT(Teb->Win32ThreadInfo == pti);
    ASSERT(pci->ppi == ppi);
    ASSERT(pci->fsHooks == pti->fsHooks);
    ASSERT(pci->ulClientDelta == DesktopHeapGetUserDelta());
    if (pti->pcti && pci->pDeskInfo)
        ASSERT(pci->pClientThreadInfo == (PVOID)((ULONG_PTR)pti->pcti - pci->ulClientDelta));
    if (pti->pcti && IsListEmpty(&pti->SentMessagesListHead))
        ASSERT((pti->pcti->fsChangeBits & QS_SENDMESSAGE) == 0);
    if (pti->KeyboardLayout)
        ASSERT(pci->hKL == pti->KeyboardLayout->hkl);
    if(pti->rpdesk != NULL)
        ASSERT(pti->pDeskInfo == pti->rpdesk->pDeskInfo);

    /*too bad we still get this assertion*/

    // Why? Not all flags are passed to the user and doing so could crash the system........

    /* ASSERT(pci->dwTIFlags == pti->TIF_flags); */
/*    if(pci->dwTIFlags != pti->TIF_flags)
    {
        ERR("pci->dwTIFlags(0x%x) doesn't match pti->TIF_flags(0x%x)\n", pci->dwTIFlags, pti->TIF_flags);
        if(showCaller)
        {
            DbgPrint("Caller:\n");
            KeRosDumpStackFrames(NULL, 10);
        }
        pci->dwTIFlags = pti->TIF_flags;
    }
*/
}
Ejemplo n.º 11
0
/*
 * @implemented
 */
int
WINAPI
SetROP2(HDC hdc,
        int fnDrawMode)
{
    PDC_ATTR Dc_Attr;
    INT Old_ROP2;

#if 0
// Handle something other than a normal dc object.
    if (GDI_HANDLE_GET_TYPE(hdc) != GDI_OBJECT_TYPE_DC)
    {
        if (GDI_HANDLE_GET_TYPE(hdc) == GDI_OBJECT_TYPE_METADC)
            return MFDRV_SetROP2( hdc, fnDrawMode);
        else
        {
            PLDC pLDC = GdiGetLDC(hdc);
            if ( !pLDC )
            {
                SetLastError(ERROR_INVALID_HANDLE);
                return FALSE;
            }
            if (pLDC->iType == LDC_EMFLDC)
            {
                return EMFDRV_SetROP2(( hdc, fnDrawMode);
                                  }
                                  return FALSE;
        }
    }
#endif
    if (!GdiGetHandleUserData((HGDIOBJ) hdc, GDI_OBJECT_TYPE_DC, (PVOID) &Dc_Attr)) return FALSE;

    if (NtCurrentTeb()->GdiTebBatch.HDC == hdc)
    {
        if (Dc_Attr->ulDirty_ & DC_MODE_DIRTY)
        {
            NtGdiFlush();
            Dc_Attr->ulDirty_ &= ~DC_MODE_DIRTY;
        }
    }

    Old_ROP2 = Dc_Attr->jROP2;
    Dc_Attr->jROP2 = fnDrawMode;

    return Old_ROP2;
}
Ejemplo n.º 12
0
/***********************************************************************
 *           NE_InitDLL
 *
 * Call the DLL initialization code
 */
static BOOL NE_InitDLL( NE_MODULE *pModule )
{
    SEGTABLEENTRY *pSegTable;
    WORD hInst, ds, heap;
    CONTEXT86 context;

    pSegTable = NE_SEG_TABLE( pModule );

    if (!(pModule->flags & NE_FFLAGS_LIBMODULE) ||
        (pModule->flags & NE_FFLAGS_WIN32)) return TRUE; /*not a library*/

    /* Call USER signal handler for Win3.1 compatibility. */
    TASK_CallTaskSignalProc( USIG16_DLL_LOAD, pModule->self );

    if (!pModule->cs) return TRUE;  /* no initialization code */


    /* Registers at initialization must be:
     * cx     heap size
     * di     library instance
     * ds     data segment if any
     * es:si  command line (always 0)
     */

    memset( &context, 0, sizeof(context) );

    NE_GetDLLInitParams( pModule, &hInst, &ds, &heap );

    context.Ecx = heap;
    context.Edi = hInst;
    context.SegDs  = ds;
    context.SegEs  = ds;   /* who knows ... */

    context.SegCs  = SEL(pSegTable[pModule->cs-1].hSeg);
    context.Eip = pModule->ip;
    context.Ebp = OFFSETOF(NtCurrentTeb()->WOW32Reserved) + (WORD)&((STACK16FRAME*)0)->bp;


    pModule->cs = 0;  /* Don't initialize it twice */
    TRACE_(dll)("Calling LibMain, cs:ip=%04lx:%04lx ds=%04lx di=%04x cx=%04x\n",
                 context.SegCs, context.Eip, context.SegDs,
                 LOWORD(context.Edi), LOWORD(context.Ecx) );
    wine_call_to_16_regs_short( &context, 0 );
    return TRUE;
}
Ejemplo n.º 13
0
static void NE_CallDllEntryPoint( NE_MODULE *pModule, DWORD dwReason )
{
    WORD hInst, ds, heap;
    FARPROC16 entryPoint;

    if (!(pModule->flags & NE_FFLAGS_LIBMODULE)) return;
    if (!(pModule->flags & NE_FFLAGS_BUILTIN) && pModule->expected_version < 0x0400) return;
    if (!(entryPoint = GetProcAddress16( pModule->self, "DllEntryPoint" ))) return;

    NE_GetDLLInitParams( pModule, &hInst, &ds, &heap );

    TRACE_(dll)( "Calling %s DllEntryPoint, cs:ip=%04x:%04x\n",
                 NE_MODULE_NAME( pModule ),
                 SELECTOROF(entryPoint), OFFSETOF(entryPoint) );

    if ( pModule->flags & NE_FFLAGS_BUILTIN )
    {
        WinNEEntryProc entryProc = (WinNEEntryProc)((ENTRYPOINT16 *)MapSL( (SEGPTR)entryPoint ))->target;

        entryProc( dwReason, hInst, ds, heap, 0, 0 );
    }
    else
    {
        LPBYTE stack = (LPBYTE)CURRENT_STACK16;
        CONTEXT86 context;

        memset( &context, 0, sizeof(context) );
        context.SegDs = ds;
        context.SegEs = ds;   /* who knows ... */

        context.SegCs = HIWORD(entryPoint);
        context.Eip = LOWORD(entryPoint);
        context.Ebp =  OFFSETOF( NtCurrentTeb()->WOW32Reserved )
                             + (WORD)&((STACK16FRAME*)0)->bp;

        *(DWORD *)(stack -  4) = dwReason;      /* dwReason */
        *(WORD *) (stack -  6) = hInst;         /* hInst */
        *(WORD *) (stack -  8) = ds;            /* wDS */
        *(WORD *) (stack - 10) = heap;          /* wHeapSize */
        *(DWORD *)(stack - 14) = 0;             /* dwReserved1 */
        *(WORD *) (stack - 16) = 0;             /* wReserved2 */

        wine_call_to_16_regs_short( &context, 16 );
    }
}
Ejemplo n.º 14
0
/***********************************************************************
 *           exit_thread
 */
void exit_thread( int status )
{
    static void *prev_teb;
    TEB *teb;

    if (status)  /* send the exit code to the server (0 is already the default) */
    {
        SERVER_START_REQ( terminate_thread )
        {
            req->handle    = wine_server_obj_handle( GetCurrentThread() );
            req->exit_code = status;
            wine_server_call( req );
        }
        SERVER_END_REQ;
    }

    if (interlocked_xchg_add( &nb_threads, -1 ) <= 1)
    {
        LdrShutdownProcess();
        exit( status );
    }

    LdrShutdownThread();
    RtlFreeThreadActivationContextStack();

    pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );

    if ((teb = interlocked_xchg_ptr( &prev_teb, NtCurrentTeb() )))
    {
        struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;

        if (thread_data->pthread_id)
        {
            pthread_join( thread_data->pthread_id, NULL );
            signal_free_thread( teb );
        }
    }

    close( ntdll_get_thread_data()->wait_fd[0] );
    close( ntdll_get_thread_data()->wait_fd[1] );
    close( ntdll_get_thread_data()->reply_fd );
    close( ntdll_get_thread_data()->request_fd );
    pthread_exit( UIntToPtr(status) );
}
Ejemplo n.º 15
0
/*
 * @implemented
 */
BOOL
WINAPI
FlsSetValue(DWORD dwFlsIndex, PVOID lpFlsData)
{
    PVOID *ppFlsSlots;
    TEB *pTeb = NtCurrentTeb();

    if(dwFlsIndex >= 128) goto l_InvalidParam;

    ppFlsSlots = pTeb->FlsData;

    if (ppFlsSlots == NULL)
    {
        PEB *pPeb = pTeb->ProcessEnvironmentBlock;

        ppFlsSlots = RtlAllocateHeap(pPeb->ProcessHeap,
                                     HEAP_ZERO_MEMORY,
                                     (128 + 2) * sizeof(PVOID));
        if(ppFlsSlots == NULL) goto l_OutOfMemory;

        pTeb->FlsData = ppFlsSlots;

        RtlAcquirePebLock();

        /* TODO: initialization */

        RtlReleasePebLock();
    }

    ppFlsSlots[dwFlsIndex + 2] = lpFlsData;

    return TRUE;

l_OutOfMemory:
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
    goto l_Fail;

l_InvalidParam:
    SetLastError(ERROR_INVALID_PARAMETER);

l_Fail:
    return FALSE;
}
Ejemplo n.º 16
0
/*
 * @implemented
 */
VOID
WINAPI
DeleteFiber(LPVOID lpFiber)
{
    SIZE_T nSize = 0;
    PVOID pStackAllocBase = ((PFIBER)lpFiber)->DeallocationStack;

    /* free the fiber */
    RtlFreeHeap(GetProcessHeap(), 0, lpFiber);

    /* the fiber is deleting itself: let the system deallocate the stack */
    if(NtCurrentTeb()->NtTib.FiberData == lpFiber) ExitThread(1);

    /* deallocate the stack */
    NtFreeVirtualMemory(NtCurrentProcess(),
                        &pStackAllocBase,
                        &nSize,
                        MEM_RELEASE);
}
Ejemplo n.º 17
0
BOOLEAN GdiDllInitialize(
    PVOID pvDllHandle,
    ULONG ulReason,
    PCONTEXT pcontext)
{
    NTSTATUS status = 0;
    INT i;
    BOOLEAN  fServer;
    PTEB pteb = NtCurrentTeb();
    BOOL bRet = TRUE;

    switch (ulReason)
    {
    case DLL_PROCESS_ATTACH:

        //
        // force the kernel to initialize.  This should be done last
        // since ClientThreadSetup is going to get called before this returns.
        //

        if (NtGdiInit() != TRUE)
        {
            return(FALSE);
        }

        bRet = GdiProcessSetup();

    case DLL_THREAD_ATTACH:
        pteb->GdiTebBatch.Offset = 0;
        pteb->GdiBatchCount      = 0;
        break;

   case DLL_PROCESS_DETACH:
   case DLL_THREAD_DETACH:
        break;

    }

    return(bRet);

    pvDllHandle;
    pcontext;
}
Ejemplo n.º 18
0
/// <summary>
/// Single step exception handler
/// </summary>
/// <param name="excpt">Exception information</param>
/// <returns>Exception disposition</returns>
LONG NTAPI DetourBase::StepHandler( PEXCEPTION_POINTERS excpt )
{
    DWORD index = 0;
    int found = _BitScanForward( &index, static_cast<DWORD>(excpt->ContextRecord->Dr6) );

    if (found != 0 && index < 4 && _breakpoints.count( excpt->ExceptionRecord->ExceptionAddress ))
    {
        DetourBase* pInst = _breakpoints[excpt->ExceptionRecord->ExceptionAddress];

        // Disable breakpoint at current index
        BitTestAndResetT( (LONG_PTR*)&excpt->ContextRecord->Dr7, 2 * index );

        ((_NT_TIB*)NtCurrentTeb())->ArbitraryUserPointer = (void*)pInst;
        excpt->ContextRecord->NIP = (uintptr_t)pInst->_internalHandler;

        return EXCEPTION_CONTINUE_EXECUTION;
    }
    return EXCEPTION_CONTINUE_SEARCH;
}
Ejemplo n.º 19
0
/*
 * @implemented
 */
HANDLE
WINAPI
CreateSemaphoreExA(IN LPSECURITY_ATTRIBUTES lpSemaphoreAttributes  OPTIONAL,
                   IN LONG lInitialCount,
                   IN LONG lMaximumCount,
                   IN LPCSTR lpName  OPTIONAL,
                   IN DWORD dwFlags,
                   IN DWORD dwDesiredAccess)
{
    NTSTATUS Status;
    ANSI_STRING AnsiName;
    PUNICODE_STRING UnicodeCache;
    LPCWSTR UnicodeName = NULL;

    /* Check for a name */
    if (lpName)
    {
        /* Use TEB Cache */
        UnicodeCache = &NtCurrentTeb()->StaticUnicodeString;

        /* Convert to unicode */
        RtlInitAnsiString(&AnsiName, lpName);
        Status = RtlAnsiStringToUnicodeString(UnicodeCache, &AnsiName, FALSE);
        if (!NT_SUCCESS(Status))
        {
            /* Conversion failed */
            SetLastErrorByStatus(Status);
            return NULL;
        }

        /* Otherwise, save the buffer */
        UnicodeName = (LPCWSTR)UnicodeCache->Buffer;
    }

    /* Call the Unicode API */
    return CreateSemaphoreExW(lpSemaphoreAttributes,
                              lInitialCount,
                              lMaximumCount,
                              UnicodeName,
                              dwFlags,
                              dwDesiredAccess);
}
Ejemplo n.º 20
0
/*
 * @implemented
 */
BOOL
WINAPI
CallMsgFilterW(
  LPMSG lpMsg,
  int nCode)
{
  MSG Msg;
  if ( NtCurrentTeb()->Win32ThreadInfo &&
      (ISITHOOKED(WH_MSGFILTER) || ISITHOOKED(WH_SYSMSGFILTER)) )
  {
     if ( lpMsg->message & ~WM_MAXIMUM )
     {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
     }
     RtlCopyMemory(&Msg, lpMsg, sizeof(MSG));
     return  NtUserCallMsgFilter( &Msg, nCode);
  }
  return FALSE;
}
Ejemplo n.º 21
0
NTSTATUS
CsrIdentifyAlertableThread( VOID )
{
    NTSTATUS Status;
    CSR_API_MSG m;
    PCSR_IDENTIFY_ALERTABLE_MSG a = &m.u.IndentifyAlertable;

    a->ClientId = NtCurrentTeb()->ClientId;

    Status = CsrClientCallServer(
                &m,
                NULL,
                CSR_MAKE_API_NUMBER( CSRSRV_SERVERDLL_INDEX,
                                     CsrpIdentifyAlertable
                                   ),
                sizeof( *a )
                );

    return Status;
}
Ejemplo n.º 22
0
int is_wow64_fs_redirection_disabled(void)
{
#ifdef _WIN64
	return 1;
#else
	if (is_64bit_os) {
		__try {
			PCHAR teb = (PCHAR)NtCurrentTeb();
			PCHAR ptr1 = (PCHAR)(ULONG_PTR)*(DWORD *)(teb + 0xf70);
			if (ptr1 == NULL)
				return 0;
			if (*(DWORD *)(ptr1 + 0x14c0) == 1 && *(DWORD *)(ptr1 + 0x14c4) == 0)
				return 1;
		}
		__except (EXCEPTION_EXECUTE_HANDLER) {
			;
		}
	}
	return 0;
#endif
}
Ejemplo n.º 23
0
/**********************************************************************
 *          DOSVM_PrepareIRQ
 *
 */
static void DOSVM_PrepareIRQ( CONTEXT86 *context, BOOL isbuiltin )
{
    /* Disable virtual interrupts. */
    NtCurrentTeb()->dpmi_vif = 0;

    if (!isbuiltin)
    {
        DWORD *stack = CTX_SEG_OFF_TO_LIN(context, 
                                          context->SegSs,
                                          context->Esp);

        /* Push return address to stack. */
        *(--stack) = context->SegCs;
        *(--stack) = context->Eip;
        context->Esp += -8;

        /* Jump to enable interrupts stub. */
        context->SegCs = DOSVM_dpmi_segments->relay_code_sel;
        context->Eip   = 5;
    }
}
Ejemplo n.º 24
0
/* Thread function for [pthread_create]d threads. Thread may become a
   fiber later, but (as stated above) it isn't supposed to be
   reattached to other system thread, even after it happens.
*/
DWORD WINAPI Thread_Function(LPVOID param)
{
  pthread_t self = (pthread_t) param;

  self->teb = NtCurrentTeb();
  thread_or_fiber_function(param);
  CloseHandle(self->handle);
  {
    void* fiber = self->fiber;
    free(self);
    if (fiber) {
      /* If thread was converted to fiber, deleting the fiber from
         itself exits the thread. There are some rumors on possible
         memory leaks if we just ExitThread or return here, hence the
         statement below. However, no memory leaks on bare ExitThread
         were observed yet. */
      DeleteFiber(GetCurrentFiber());
    }
  }
  return 0;
}
Ejemplo n.º 25
0
BOOL WINAPI 
DllMain(HINSTANCE hinstDLL,
        DWORD     fdwReason,
        LPVOID    lpvReserved)
{
  TCR *tcr;

  switch (fdwReason) {
  case DLL_THREAD_DETACH:
    if (shutdown_thread_tcr) {
      tcr = ((TCR *)((char *)NtCurrentTeb() + TCR_BIAS))->linear;
      if (tcr && (tcr->flags & (1<<TCR_FLAG_BIT_FOREIGN))) {
        shutdown_thread_tcr((void *)tcr);
      }
    }
    break;
  default:
    break;
  }
  return true;
}
Ejemplo n.º 26
0
NTSTATUS
NTAPI
VdmpGetVdmTib(OUT PVDM_TIB *VdmTib)
{
    PVDM_TIB Tib;
    PAGED_CODE();

    /* Assume vailure */
    *VdmTib = NULL;

    /* Get the current TIB */
    Tib = NtCurrentTeb()->Vdm;
    if (!Tib) return STATUS_INVALID_SYSTEM_SERVICE;

    /* Validate the size */
    if (Tib->Size != sizeof(VDM_TIB)) return STATUS_INVALID_SYSTEM_SERVICE;

    /* Return it */
    *VdmTib = Tib;
    return STATUS_SUCCESS;
}
/***********************************************************************
 *           OutputDebugStringA   (KERNEL32.@)
 *
 *  Output by an application of an ascii string to a debugger (if attached)
 *  and program log.
 *
 * PARAMS
 *  str [I] The message to be logged and given to the debugger.
 *
 * RETURNS
 *
 *  Nothing.
 */
void WINAPI OutputDebugStringA( LPCSTR str )
{
    static HANDLE DBWinMutex = NULL;
    static BOOL mutex_inited = FALSE;
    BOOL caught_by_dbg = TRUE;

    if (!str) str = "";
    WARN("%s\n", debugstr_a(str));

    /* raise exception, WaitForDebugEvent() will generate a corresponding debug event */
    __TRY
    {
        ULONG_PTR args[2];
        args[0] = strlen(str) + 1;
        args[1] = (ULONG_PTR)str;
        RaiseException( DBG_PRINTEXCEPTION_C, 0, 2, args );
    }
    __EXCEPT(debug_exception_handler)
    {
        caught_by_dbg = FALSE;
    }
    __ENDTRY
    if (caught_by_dbg) return;

    /* for some unknown reason Windows sends the exception a second time, if a
     * debugger is attached, and the event wasn't handled in the first attempt */
    if (NtCurrentTeb()->Peb->BeingDebugged)
    {
        __TRY
        {
            ULONG_PTR args[2];
            args[0] = strlen(str) + 1;
            args[1] = (ULONG_PTR)str;
            RaiseException( DBG_PRINTEXCEPTION_C, 0, 2, args );
        }
        __EXCEPT(debug_exception_handler)
        {
        }
        __ENDTRY
    }
Ejemplo n.º 28
0
/*
 * @implemented
 */
PVOID
WINAPI
FlsGetValue(DWORD dwFlsIndex)
{
    PVOID *ppFlsSlots;
    PVOID pRetVal;

    if(dwFlsIndex >= 128) goto l_InvalidParam;

    ppFlsSlots = NtCurrentTeb()->FlsData;

    if(ppFlsSlots == NULL) goto l_InvalidParam;

    SetLastError(0);
    pRetVal = ppFlsSlots[dwFlsIndex + 2];

    return pRetVal;

l_InvalidParam:
    SetLastError(ERROR_INVALID_PARAMETER);
    return NULL;
}
Ejemplo n.º 29
0
/***********************************************************************
 *           KERNEL process initialisation routine
 */
static BOOL process_attach( HMODULE module )
{
    RTL_USER_PROCESS_PARAMETERS *params = NtCurrentTeb()->Peb->ProcessParameters;

    /* Setup registry locale information */
    LOCALE_InitRegistry();

    /* Setup computer name */
    COMPUTERNAME_Init();

    CONSOLE_Init(params);

    /* copy process information from ntdll */
    ENV_CopyStartupInformation();

    if (!(GetVersion() & 0x80000000))
    {
        /* Securom checks for this one when version is NT */
        set_entry_point( module, "FT_Thunk", 0 );
    }
    else LoadLibraryA( "krnl386.exe16" );

    /* finish the process initialisation for console bits, if needed */
    __wine_set_signal_handler(SIGINT, CONSOLE_HandleCtrlC);

    if (params->ConsoleHandle == KERNEL32_CONSOLE_ALLOC)
    {
        HMODULE mod = GetModuleHandleA(0);
        if (RtlImageNtHeader(mod)->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
            AllocConsole();
    }
    /* else TODO for DETACHED_PROCESS:
     * 1/ inherit console + handles
     * 2/ create std handles, if handles are not inherited
     * TBD when not using wineserver handles for console handles
     */

    return TRUE;
}
Ejemplo n.º 30
0
/*
 * @implemented
 */
NTSTATUS
NTAPI
DbgUiDebugActiveProcess(IN HANDLE Process)
{
    NTSTATUS Status;

    /* Tell the kernel to start debugging */
    Status = NtDebugActiveProcess(Process, NtCurrentTeb()->DbgSsReserved[1]);
    if (NT_SUCCESS(Status))
    {
        /* Now break-in the process */
        Status = DbgUiIssueRemoteBreakin(Process);
        if (!NT_SUCCESS(Status))
        {
            /* We couldn't break-in, cancel debugging */
            DbgUiStopDebugging(Process);
        }
    }

    /* Return status */
    return Status;
}