Beispiel #1
0
Int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWChar lpCmdLine, Int nCmdShow)
{
    Int   Result;

    UNREFERENCED_PARAMETER(hInstance);
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);
    UNREFERENCED_PARAMETER(nCmdShow);

    g_HeapHandle = RtlCreateHeap(0, NULL, 0, 0, NULL, NULL);
//    MyLib_Initialize();
/*
    WChar end;
    lpCmdLine = GetCommandLineW();
    end = *lpCmdLine++ == '\"' ? '\"' : ' ';
    while (*lpCmdLine && *lpCmdLine != end) ++lpCmdLine;
    if (*++lpCmdLine)
    {
        while (*lpCmdLine == ' ' || *lpCmdLine == '\t') ++lpCmdLine;
    }
*/
    Result = WinMain2(/*GetModuleHandleW*/(NULL), 0, lpCmdLine, SW_SHOWDEFAULT);

    RtlDestroyHeap(g_HeapHandle);
//    MyLib_UnInitialize();

    NtTerminateProcess(NtCurrentProcess(), Result);
}
Beispiel #2
0
BOOL
WINAPI
DllMain(HINSTANCE hInstance,
        ULONG Reason,
        PVOID Reserved)
{
    switch (Reason)
    {
        case DLL_PROCESS_ATTACH:
            Secur32Heap = RtlCreateHeap(0, NULL, 0, 4096, NULL, NULL);
            if (Secur32Heap == 0)
            {
                return FALSE;
            }
            break;

        case DLL_PROCESS_DETACH:
            if (!RtlDestroyHeap(Secur32Heap))
            {
                return FALSE;
            }
            break;
    }

    return TRUE;
}
Beispiel #3
0
/***********************************************************************
 *           HEAP_CreateSystemHeap
 *
 * Create the system heap.
 */
static inline HANDLE HEAP_CreateSystemHeap(void)
{
    int created;
    void *base;
    HANDLE map, event;

    /* create the system heap event first */
    event = CreateEventA( NULL, TRUE, FALSE, "__wine_system_heap_event" );

    if (!(map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
                                    0, SYSTEM_HEAP_SIZE, "__wine_system_heap" ))) return 0;
    created = (GetLastError() != ERROR_ALREADY_EXISTS);

    if (!(base = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
    {
        /* pre-defined address not available */
        ERR( "system heap base address %p not available\n", SYSTEM_HEAP_BASE );
        return 0;
    }

    if (created)  /* newly created heap */
    {
        systemHeap = RtlCreateHeap( HEAP_SHARED, base, SYSTEM_HEAP_SIZE,
                                    SYSTEM_HEAP_SIZE, NULL, NULL );
        SetEvent( event );
    }
    else
    {
        /* wait for the heap to be initialized */
        WaitForSingleObject( event, INFINITE );
        systemHeap = base;
    }
    CloseHandle( map );
    return systemHeap;
}
Beispiel #4
0
/*
* WinObjInitGlobals
*
* Purpose:
*
* Initialize global variables.
*
*/
BOOL WinObjInitGlobals()
{
    SIZE_T cch;
    BOOL bResult = FALSE, bCond = FALSE;

    do {
        RtlSecureZeroMemory(&g_WinObj, sizeof(g_WinObj));

        //
        // Query version info.
        //
        g_WinObj.osver.dwOSVersionInfoSize = sizeof(g_WinObj.osver);
        RtlGetVersion(&g_WinObj.osver);

        //
        // Remember hInstance.
        //
        g_WinObj.hInstance = GetModuleHandle(NULL);

        //
        // Create dedicated heap.
        //
        g_WinObj.Heap = RtlCreateHeap(HEAP_GROWABLE, NULL, 0, 0, NULL, NULL);
        if (g_WinObj.Heap == NULL)
            break;

        RtlSetHeapInformation(g_WinObj.Heap, HeapEnableTerminationOnCorruption, NULL, 0);
        RtlInitializeCriticalSection(&g_WinObj.Lock);

        //
        // Remember %TEMP% directory.
        //
        cch = ExpandEnvironmentStrings(L"%temp%", g_WinObj.szTempDirectory, MAX_PATH);
        if ((cch == 0) || (cch > MAX_PATH))
            break;

        //
        // Remember Windows directory.
        //
        if (!GetWindowsDirectory(g_WinObj.szWindowsDirectory, MAX_PATH))
            break;

        //
        // Remember System32 directory.
        //
        if (!GetSystemDirectory(g_WinObj.szSystemDirectory, MAX_PATH))
            break;

        bResult = TRUE;

    } while (bCond);

    if (bResult == FALSE) {
        if (g_WinObj.Heap)
            RtlDestroyHeap(g_WinObj.Heap);
    }

    return bResult;
}
Beispiel #5
0
NTSTATUS
SmCreateHeap(VOID)
{
  /* Create our own heap */
  SmpHeap = RtlCreateHeap(HEAP_GROWABLE,
                          NULL,
                          65536,
                          65536,
                          NULL,
                          NULL);
  return (NULL == SmpHeap) ? STATUS_UNSUCCESSFUL : STATUS_SUCCESS;
}
Beispiel #6
0
static VOID
CheckHeap()
{
  if (NULL == InfpHeap)
    {
      InfpHeap = RtlCreateHeap(HEAP_GROWABLE, NULL, 0, 0, NULL, NULL);
    }
  if (0 <= InfpHeapRefCount)
    {
      InfpHeapRefCount++;
    }
}
Beispiel #7
0
BOOLEAN
NTAPI
InitializeWrapper(
	)
{
//	KdPrint(("Initializing wrapper.\n"));

	if (bWrapperInitialized)
	{
		KdPrint(("Already initialized.\n"));
		return TRUE;
	}

//	KdPrint(("Creating heap\n"));

	heap = RtlCreateHeap (HEAP_GROWABLE|HEAP_NO_SERIALIZE, 0, 0, 0, 0, 0);

	if (heap == NULL)
	{
		KdPrint(("RtlCreateHeap failed!\n"));
		return FALSE;
	}

	SetProcessHeap (heap);

//	KdPrint(("heap = %08x\n", heap));

	for (int i=0; i<10; i++)
	{
		if (hKeyboard = OpenKeyboard (i))
		{
//			KdPrint(("Found keyboard class N%u\n", i));
			break;
		}
	}

//	KdPrint(("hKeyboard = %08x\n", hKeyboard));

	if (hKeyboard == NULL)
	{
		KdPrint(("Could not open keyboard.\n"));
		return FALSE;
	}

//	KdPrint(("Initialization successful\n"));

	bWrapperInitialized = TRUE;
	return TRUE;
}
Beispiel #8
0
HANDLE WINAPI
redirect_RtlCreateHeap(ULONG flags, void *base, size_t reserve_sz,
                       size_t commit_sz, void *lock, void *params)
{
    if (IF_CLIENT_INTERFACE_ELSE(INTERNAL_OPTION(privlib_privheap), true)) {
        /* We don't want to waste space by letting a Heap be created
         * and not used so we nop this.  We need to return something
         * here, and distinguish a nop-ed from real in Destroy, so we
         * allocate a token block.
         */
        LOG(GLOBAL, LOG_LOADER, 2, "%s "PFX"\n", __FUNCTION__, base);
        return (HANDLE) global_heap_alloc(1 HEAPACCT(ACCT_LIBDUP));
    } else
        return RtlCreateHeap(flags, base, reserve_sz, commit_sz, lock, params);
}
Beispiel #9
0
/**
 * @internal
 * @brief Creates global memory heap.
 * @return Zero for success, negative value otherwise.
 */
int winx_create_global_heap(void)
{
    /* create growable heap with initial size of 100 KB */
    if(hGlobalHeap == NULL){
        hGlobalHeap = RtlCreateHeap(HEAP_GROWABLE,NULL,0,100 * 1024,NULL,NULL);
    }
    if(hGlobalHeap == NULL){
        /* trace macro cannot be used here */
        /* winx_printf cannot be used here */
        winx_print("\nCannot create global memory heap!\n");
        return (-1);
    }
    
    /* reserve 1 MB of memory for the out of memory condition handling */
    reserved_memory = (char *)winx_tmalloc(1024 * 1024);
    return 0;
}
Beispiel #10
0
PVOID UserCreateHeap(
    HANDLE hSection,
    PVOID pvBaseAddress,
    DWORD dwSize)
{
    PVOID pUserBase;
    ULONG ulViewSize;
    LARGE_INTEGER liOffset;
    PEPROCESS Process = PsGetCurrentProcess();
    RTL_HEAP_PARAMETERS HeapParams;
    NTSTATUS Status;

    /*
     * Map the section into the current process and commit the
     * first page of the section.
     */
    ulViewSize = 0;
    liOffset.QuadPart = 0;
    pUserBase = NULL;
    Status = MmMapViewOfSection(hSection, Process,
                                &pUserBase, 0, PAGE_SIZE, &liOffset, &ulViewSize, ViewUnmap,
                                SEC_NO_CHANGE, PAGE_EXECUTE_READ);
    if (!NT_SUCCESS(Status))
        return NULL;
    MmUnmapViewOfSection(Process, pUserBase);

    /*
     * We now have a committed page to create the heap in.
     */
    RtlZeroMemory(&HeapParams, sizeof(HeapParams));
    HeapParams.Length = sizeof(HeapParams);
    HeapParams.InitialCommit = PAGE_SIZE;
    HeapParams.InitialReserve = dwSize;
    HeapParams.CommitRoutine = UserCommitMemory;

    return RtlCreateHeap(
               HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY,
               pvBaseAddress,
               dwSize,
               PAGE_SIZE,
               NULL,
               &HeapParams
           );
}
Beispiel #11
0
/***********************************************************************
 *           HeapCreate   (KERNEL32.@)
 *
 * Create a heap object.
 *
 * RETURNS
 *	Handle of heap: Success
 *	NULL: Failure
 */
HANDLE WINAPI HeapCreate(
                DWORD flags,       /* [in] Heap allocation flag */
                SIZE_T initialSize, /* [in] Initial heap size */
                SIZE_T maxSize      /* [in] Maximum heap size */
) {
    HANDLE ret;

    if ( flags & HEAP_SHARED )
    {
        if (!systemHeap) HEAP_CreateSystemHeap();
        else WARN( "Shared Heap requested, returning system heap.\n" );
        ret = systemHeap;
    }
    else
    {
        ret = RtlCreateHeap( flags, NULL, maxSize, initialSize, NULL, NULL );
        if (!ret) SetLastError( ERROR_NOT_ENOUGH_MEMORY );
    }
    return ret;
}
Beispiel #12
0
NTSTATUS PhInitializePhLibEx(
    _In_ ULONG Flags,
    _In_opt_ SIZE_T HeapReserveSize,
    _In_opt_ SIZE_T HeapCommitSize
    )
{
    PhHeapHandle = RtlCreateHeap(
        HEAP_GROWABLE | HEAP_CLASS_1,
        NULL,
        HeapReserveSize ? HeapReserveSize : 2 * 1024 * 1024, // 2 MB
        HeapCommitSize ? HeapCommitSize : 1024 * 1024, // 1 MB
        NULL,
        NULL
        );

    if (!PhHeapHandle)
        return STATUS_INSUFFICIENT_RESOURCES;

    PhLibImageBase = NtCurrentPeb()->ImageBaseAddress;

    PhInitializeWindowsVersion();
    PhInitializeSystemInformation();

    if (!PhQueuedLockInitialization())
        return STATUS_UNSUCCESSFUL;

    if (!NT_SUCCESS(PhInitializeRef()))
        return STATUS_UNSUCCESSFUL;
    if (!PhInitializeBase(Flags))
        return STATUS_UNSUCCESSFUL;

    PhInitializeSecurity(Flags);

    if (!PhInitializeSystem(Flags))
        return STATUS_UNSUCCESSFUL;

    return STATUS_SUCCESS;
}
Beispiel #13
0
/***********************************************************************
 *           thread_init
 *
 * Setup the initial thread.
 *
 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
 */
HANDLE thread_init(void)
{
    TEB *teb;
    void *addr;
    SIZE_T size, info_size;
    HANDLE exe_file = 0;
    LARGE_INTEGER now;
    NTSTATUS status;
    struct ntdll_thread_data *thread_data;
    static struct debug_info debug_info;  /* debug info for initial thread */

    virtual_init();

    /* reserve space for shared user data */

    addr = (void *)0x7ffe0000;
    size = 0x10000;
    status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
                                      MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
    if (status)
    {
        MESSAGE( "wine: failed to map the shared user data: %08x\n", status );
        exit(1);
    }
    user_shared_data = addr;

    /* allocate and initialize the PEB */

    addr = NULL;
    size = sizeof(*peb);
    NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
                             MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
    peb = addr;

    peb->ProcessParameters  = &params;
    peb->TlsBitmap          = &tls_bitmap;
    peb->TlsExpansionBitmap = &tls_expansion_bitmap;
    peb->FlsBitmap          = &fls_bitmap;
    peb->LdrData            = &ldr;
    params.CurrentDirectory.DosPath.Buffer = current_dir;
    params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
    params.wShowWindow = 1; /* SW_SHOWNORMAL */
    ldr.Length = sizeof(ldr);
    RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
    RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
                         sizeof(peb->TlsExpansionBitmapBits) * 8 );
    RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
    InitializeListHead( &peb->FlsListHead );
    InitializeListHead( &ldr.InLoadOrderModuleList );
    InitializeListHead( &ldr.InMemoryOrderModuleList );
    InitializeListHead( &ldr.InInitializationOrderModuleList );
#ifdef __APPLE__
    peb->Reserved[0] = get_dyld_image_info_addr();
#endif

    /* allocate and initialize the initial TEB */

    signal_alloc_thread( &teb );
    teb->Peb = peb;
    teb->Tib.StackBase = (void *)~0UL;
    teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
    teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);

    thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
    thread_data->request_fd = -1;
    thread_data->reply_fd   = -1;
    thread_data->wait_fd[0] = -1;
    thread_data->wait_fd[1] = -1;
    thread_data->debug_info = &debug_info;
    InsertHeadList( &tls_links, &teb->TlsLinks );

    signal_init_thread( teb );
    virtual_init_threading();

    debug_info.str_pos = debug_info.strings;
    debug_info.out_pos = debug_info.output;
    debug_init();

    /* setup the server connection */
    server_init_process();
    info_size = server_init_thread( peb );

    /* create the process heap */
    if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
    {
        MESSAGE( "wine: failed to create the process heap\n" );
        exit(1);
    }

    /* allocate user parameters */
    if (info_size)
    {
        init_user_process_params( info_size, &exe_file );
    }
    else
    {
        if (isatty(0) || isatty(1) || isatty(2))
            params.ConsoleHandle = (HANDLE)2; /* see kernel32/kernel_private.h */
        if (!isatty(0))
            wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE,  OBJ_INHERIT, &params.hStdInput );
        if (!isatty(1))
            wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdOutput );
        if (!isatty(2))
            wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdError );
    }

    /* initialize time values in user_shared_data */
    NtQuerySystemTime( &now );
    user_shared_data->SystemTime.LowPart = now.u.LowPart;
    user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
    user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
    user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
    user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
    user_shared_data->TickCountMultiplier = 1 << 24;

    fill_cpu_info();

    NtCreateKeyedEvent( &keyed_event, GENERIC_READ | GENERIC_WRITE, NULL, 0 );

    return exe_file;
}
Beispiel #14
0
PyHooker::PyHooker() : MemoryAllocator(RtlCreateHeap(HEAP_CREATE_ENABLE_EXECUTE | HEAP_GROWABLE | HEAP_CREATE_ALIGN_16, nullptr, 0, 0, nullptr, nullptr))
{
    this->VehHandle = nullptr;
    RtlInitializeCriticalSectionAndSpinCount(&this->Lock, 4000);
}
Beispiel #15
0
HANDLE NTAPI
RtlDebugCreateHeap(ULONG Flags,
                   PVOID Addr,
                   SIZE_T ReserveSize,
                   SIZE_T CommitSize,
                   PVOID Lock,
                   PRTL_HEAP_PARAMETERS Parameters)
{
    MEMORY_BASIC_INFORMATION MemoryInfo;
    NTSTATUS Status;
    PHEAP Heap;

    /* Validate parameters */
    if (ReserveSize <= HEAP_ENTRY_SIZE)
    {
        DPRINT1("HEAP: Incorrect ReserveSize %x\n", ReserveSize);
        return NULL;
    }

    if (ReserveSize < CommitSize)
    {
        DPRINT1("HEAP: Incorrect CommitSize %x\n", CommitSize);
        return NULL;
    }

    if (Flags & HEAP_NO_SERIALIZE && Lock)
    {
        DPRINT1("HEAP: Can't specify Lock routine and have HEAP_NO_SERIALIZE flag set\n");
        return NULL;
    }

    /* If the address is specified, check it's virtual memory */
    if (Addr)
    {
        Status = ZwQueryVirtualMemory(NtCurrentProcess(),
                                      Addr,
                                      MemoryBasicInformation,
                                      &MemoryInfo,
                                      sizeof(MemoryInfo),
                                      NULL);

        if (!NT_SUCCESS(Status))
        {
            DPRINT1("HEAP: Specified heap base address %p is invalid, Status 0x%08X\n", Addr, Status);
            return NULL;
        }

        if (MemoryInfo.BaseAddress != Addr)
        {
            DPRINT1("HEAP: Specified heap base address %p is not really a base one %p\n", Addr, MemoryInfo.BaseAddress);
            return NULL;
        }

        if (MemoryInfo.State == MEM_FREE)
        {
            DPRINT1("HEAP: Specified heap base address %p is free\n", Addr);
            return NULL;
        }
    }

    /* All validation performed, now call the real routine with skip validation check flag */
    Flags |= HEAP_SKIP_VALIDATION_CHECKS |
             HEAP_TAIL_CHECKING_ENABLED |
             HEAP_FREE_CHECKING_ENABLED;

    Heap = RtlCreateHeap(Flags, Addr, ReserveSize, CommitSize, Lock, Parameters);
    if (!Heap) return NULL;

    // FIXME: Capture stack backtrace

    RtlpValidateHeapHeaders(Heap, TRUE);

    return Heap;
}
Beispiel #16
0
int
_cdecl
main(
    int argc,
    char *argv[]
    )
{
    PVOID Heap, AllocatedBlock;
    ULONG i, n;
    PTEST_HEAP_ENTRY p;
    BOOLEAN Result;
    NTSTATUS Status;
    RTL_HEAP_USAGE Usage;
    PRTL_HEAP_USAGE_ENTRY pEntries;
    ULONG TagBaseIndex, Tag;
    ULONG TotalAllocated;

    RtlInitializeHeapManager();
    memset( &Usage, 0, sizeof( Usage ) );

#if 0
    HeapParameters.Length = sizeof( HeapParameters );
    HeapParameters.DeCommitFreeBlockThreshold = 0x1000;
    HeapParameters.DeCommitTotalFreeThreshold = 0x4000;
    Heap = RtlCreateHeap( HEAP_GROWABLE | HEAP_NO_SERIALIZE,
                          NULL,
                          256 * 4096,
                          4096,
                          NULL,
                          &HeapParameters
                        );
#endif
    Heap = RtlCreateHeap( HEAP_GROWABLE | HEAP_NO_SERIALIZE | HEAP_CLASS_3,
                          NULL,
                          0x100000,
                          0x1000,
                          NULL,
                          NULL
                        );
    if (Heap == NULL) {
        fprintf( stderr, "THEAP: Unable to create heap.\n" );
        exit( 1 );
        }
    fprintf( stderr, "THEAP: Created heap at %x\n", Heap );
    DebugBreak();
    TagBaseIndex = RtlCreateTagHeap( Heap, 0, L"THEAP!",
                                     L"!HeapName\0"
                                     L"Tag1\0"
                                     L"Tag2\0"
                                     L"Tag3\0"
                                     L"Tag4\0"
                                     L"Tag5\0"
                                     L"Tag6\0"
                                     L"Tag7\0"
                                     L"Tag8\0"
                                     L"Tag9\0"
                                     L"Tag10\0"
                                     L"Tag11\0"
                                     L"Tag12\0"
                                     L"Tag13\0"
                                     L"Tag14\0"
                                     L"Tag15\0"
                                     L"Tag16\0"
                                     L"Tag17\0"
                                     L"Tag18\0"
                                     L"Tag19\0"
                                     L"Tag20\0"
                                     L"Tag21\0"
                                     L"Tag22\0"
                                     L"Tag23\0"
                                     L"Tag24\0"
                                     L"Tag25\0"
                                     L"Tag26\0"
                                     L"Tag27\0"
                                     L"Tag28\0"
                                     L"Tag29\0"
                                     L"Tag30\0"
                                     L"Tag31\0"
                                     L"Tag32\0"
                                     L"Tag33\0"
                                     L"Tag34\0"
                                     L"Tag35\0"
                                     L"Tag36\0"
                                     L"Tag37\0"
                                     L"Tag38\0"
                                     L"Tag39\0"
                                     L"Tag40\0"
                                     L"Tag41\0"
                                     L"Tag42\0"
                                     L"Tag43\0"
                                     L"Tag44\0"
                                     L"Tag45\0"
                                     L"Tag46\0"
                                     L"Tag47\0"
                                     L"Tag48\0"
                                     L"Tag49\0"
                                     L"Tag50\0"
                                     L"Tag51\0"
                                     L"Tag52\0"
                                     L"Tag53\0"
                                     L"Tag54\0"
                                     L"Tag55\0"
                                     L"Tag56\0"
                                     L"Tag57\0"
                                     L"Tag58\0"
                                     L"Tag59\0"
                                     L"Tag60\0"
                                   );

    NumberOfHeapEntries = 1000;
    HeapEntries = VirtualAlloc( NULL,
                                NumberOfHeapEntries * sizeof( *HeapEntries ),
                                MEM_COMMIT,
                                PAGE_READWRITE
                              );
    if (HeapEntries == NULL) {
        fprintf( stderr, "THEAP: Unable to allocate space.\n" );
        exit( 1 );
        }

    RtlpHeapValidateOnCall=TRUE;
    // RtlpHeapStopOnAllocate=0x350f88;
    // RtlpHeapStopOnReAlloc=0x710040;

    TotalAllocated = 0;
    while (TotalAllocated < (2 * 1024 * 1024)) {
        i = RtlUniform( &Seed ) % NumberOfHeapEntries;
        if (RtlUniform( &Seed ) % 100) {
            n = RtlUniform( &Seed ) % REASONABLE_HEAP_ALLOC;
            }
        else {
            n = RtlUniform( &Seed ) % MAX_HEAP_ALLOC;
            }

#if 0
        Usage.Length = sizeof( Usage );
        Status = RtlUsageHeap( Heap, HEAP_USAGE_ALLOCATED_BLOCKS , &Usage );
        if (NT_SUCCESS( Status )) {
            if (Status == STATUS_MORE_ENTRIES) {
                pEntries = Usage.AddedEntries;
                while (pEntries) {
                    fprintf( stderr,
                             "Added: %08x %06x\n",
                             pEntries->Address,
                             pEntries->Size
                           );
                    pEntries = pEntries->Next;
                    }

                pEntries = Usage.RemovedEntries;
                while (pEntries) {
                    fprintf( stderr,
                             "Freed: %08x %06x\n",
                             pEntries->Address,
                             pEntries->Size
                           );
                    pEntries = pEntries->Next;
                    }
                }

            fprintf( stderr, "%08x  %08x  %08x  %08x  ",
                             Usage.BytesAllocated, Usage.BytesCommitted,
                             Usage.BytesReserved, Usage.BytesReservedMaximum
                   );
            }
        else {
            fprintf( stderr, "RtlUsageHeap failed with status %x\n", Status );
            DebugBreak();
            }

        if (i < 60) {
            Tag = (TagBaseIndex + i + 1) << 16;
            }
        else {
            Tag = 0;
            }
#endif
        Tag = 0;
        p = &HeapEntries[ i ];
        if (p->AllocatedBlock == NULL) {
            TotalAllocated += n;
            p->AllocatedBlock = RtlAllocateHeap( Heap, Tag, n );
            fprintf( stderr, "Allocated %06x bytes at %08x\n", n, p->AllocatedBlock );
            if (p->AllocatedBlock != NULL) {
                p->Size = n;
                }
            else {
                DebugBreak();
                }
            }
        else
        if (RtlUniform( &Seed ) & 1) {
            TotalAllocated -= p->Size;
            TotalAllocated += n;
            AllocatedBlock = RtlReAllocateHeap( Heap, Tag, p->AllocatedBlock, n );
            fprintf( stderr, "ReAlloced %06x bytes at %08x to %06x bytes at %08x\n",
                     p->Size,
                     p->AllocatedBlock,
                     n,
                     AllocatedBlock
                   );
            if (AllocatedBlock != NULL) {
                p->AllocatedBlock = AllocatedBlock;
                p->Size = n;
                }
            else {
                DebugBreak();
                }
            }
        else {
            TotalAllocated -= p->Size;
            Result = RtlFreeHeap( Heap, 0, p->AllocatedBlock );
            fprintf( stderr, "Freed     %06x bytes at %08x\n",
                     p->Size,
                     p->AllocatedBlock
                   );
            if (Result) {
                p->AllocatedBlock = NULL;
                p->Size = 0;
                }
            else {
                DebugBreak();
                }
            }

        }

    RtlResetHeap( Heap, 0 );
    RtlValidateHeap( Heap, 0, NULL );

    return 0;
}
Beispiel #17
0
NTSTATUS PhSvcConnectToServer(
    _In_ PUNICODE_STRING PortName,
    _In_opt_ SIZE_T PortSectionSize
    )
{
    NTSTATUS status;
    HANDLE sectionHandle;
    LARGE_INTEGER sectionSize;
    PORT_VIEW clientView;
    REMOTE_PORT_VIEW serverView;
    SECURITY_QUALITY_OF_SERVICE securityQos;
    ULONG maxMessageLength;
    PHSVC_API_CONNECTINFO connectInfo;
    ULONG connectInfoLength;

    if (PhSvcClPortHandle)
        return STATUS_ADDRESS_ALREADY_EXISTS;

    if (PortSectionSize == 0)
        PortSectionSize = 512 * 1024;

    // Create the port section and connect to the port.

    sectionSize.QuadPart = PortSectionSize;
    status = NtCreateSection(
        &sectionHandle,
        SECTION_ALL_ACCESS,
        NULL,
        &sectionSize,
        PAGE_READWRITE,
        SEC_COMMIT,
        NULL
        );

    if (!NT_SUCCESS(status))
        return status;

    clientView.Length = sizeof(PORT_VIEW);
    clientView.SectionHandle = sectionHandle;
    clientView.SectionOffset = 0;
    clientView.ViewSize = PortSectionSize;
    clientView.ViewBase = NULL;
    clientView.ViewRemoteBase = NULL;

    serverView.Length = sizeof(REMOTE_PORT_VIEW);
    serverView.ViewSize = 0;
    serverView.ViewBase = NULL;

    securityQos.Length = sizeof(SECURITY_QUALITY_OF_SERVICE);
    securityQos.ImpersonationLevel = SecurityImpersonation;
    securityQos.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
    securityQos.EffectiveOnly = TRUE;

    connectInfoLength = sizeof(PHSVC_API_CONNECTINFO);

    status = NtConnectPort(
        &PhSvcClPortHandle,
        PortName,
        &securityQos,
        &clientView,
        &serverView,
        &maxMessageLength,
        &connectInfo,
        &connectInfoLength
        );
    NtClose(sectionHandle);

    if (!NT_SUCCESS(status))
        return status;

    PhSvcClServerProcessId = connectInfo.ServerProcessId;

    // Create the port heap.

    PhSvcClPortHeap = RtlCreateHeap(
        HEAP_CLASS_1,
        clientView.ViewBase,
        clientView.ViewSize,
        PAGE_SIZE,
        NULL,
        NULL
        );

    if (!PhSvcClPortHeap)
    {
        NtClose(PhSvcClPortHandle);
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    return status;
}
Beispiel #18
0
                  (ULONG)ClientView.ViewBase,
                  (ULONG)ClientView.ViewRemoteBase,
                  CsrPortMemoryRemoteDelta,
                  (ULONG)ClientView.ViewSize
                );
        }

    //
    // Create a sparse heap in the share memory section.  Initially
    // commit just one page.
    //

    CsrPortHeap = RtlCreateHeap( HEAP_CLASS_8,                      // Flags
                                 ClientView.ViewBase,               // HeapBase
                                 ClientView.ViewSize,               // ReserveSize
                                 CsrNtSysInfo.PageSize,             // CommitSize
                                 0,                                 // Reserved
                                 0                                  // GrowthThreshold
                               );
    if (CsrPortHeap == NULL) {
        NtClose( CsrPortHandle );
        CsrPortHandle = NULL;

        return( STATUS_NO_MEMORY );
        }

    CsrPortBaseTag = RtlCreateTagHeap( CsrPortHeap,
                                       0,
                                       L"CSRPORT!",
                                       L"!CSRPORT\0"
                                       L"CAPTURE\0"
Beispiel #19
0
BOOL
SockInitialize (
    IN PVOID DllHandle,
    IN ULONG Reason,
    IN PVOID Context OPTIONAL
    )
{
    NTSTATUS status;
    SYSTEM_INFO systemInfo;

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

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

    switch ( Reason ) {

    case DLL_PROCESS_ATTACH:

        SockModuleHandle = (HMODULE)DllHandle;

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

        {
            HANDLE handle;

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

            if( handle == INVALID_HANDLE_VALUE ) {

                //
                // Set default value.
                //

                WsDebug = WINSOCK_DEBUG_DEBUGGER;

            } else {

                CHAR buffer[11];
                DWORD bytesRead;

                RtlZeroMemory( buffer, sizeof(buffer) );

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

                    buffer[bytesRead] = '\0';

                    WsDebug = strtoul( buffer, NULL, 16 );

                } else {

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

                CloseHandle( handle );
            }
        }
#endif

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

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

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

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

        SockPostRoutine = PostMessage;

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

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

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

        SockTlsSlot = TlsAlloc( );

        if ( SockTlsSlot == 0xFFFFFFFF ) {

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

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

        GetSystemInfo( &systemInfo );

        if( systemInfo.dwNumberOfProcessors > 1 ) {

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

        } else {

            WS_ASSERT( SockPrivateHeap == NULL );

        }

        if ( SockPrivateHeap == NULL ) {

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

            SockPrivateHeap = RtlProcessHeap();

        }

        break;

    case DLL_PROCESS_DETACH:

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

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

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

        SockProcessTerminating = TRUE;

        // *** lack of break is intentional!

    case DLL_THREAD_DETACH:

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

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

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

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

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

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

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

                BOOLEAN ret;

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

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

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

            if ( SockPrivateHeap != RtlProcessHeap() ) {

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

            }
        }

        break;

    case DLL_THREAD_ATTACH:
        break;

    default:

        WS_ASSERT( FALSE );
        break;
    }

    return TRUE;

} // SockInitialize
Beispiel #20
0
/***********************************************************************
 *           thread_init
 *
 * Setup the initial thread.
 *
 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
 */
HANDLE thread_init(void)
{
    TEB *teb;
    void *addr;
    SIZE_T size, info_size;
    HANDLE exe_file = 0;
    NTSTATUS status;
    struct ntdll_thread_data *thread_data;
    static struct debug_info debug_info;  /* debug info for initial thread */
#ifdef __APPLE__
    ULONG64 dyld_image_info;
#endif

    virtual_init();
    signal_init_early();

    /* reserve space for shared user data */

    addr = (void *)0x7ffe0000;
    size = 0x10000;
    status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
                                      MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
    if (status)
    {
        MESSAGE( "wine: failed to map the shared user data: %08x\n", status );
        exit(1);
    }
    user_shared_data = addr;

    /* allocate and initialize the PEB */

    addr = NULL;
    size = sizeof(*peb);
    NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
                             MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
    peb = addr;

    peb->ProcessParameters  = &params;
    peb->TlsBitmap          = &tls_bitmap;
    peb->TlsExpansionBitmap = &tls_expansion_bitmap;
    peb->FlsBitmap          = &fls_bitmap;
    peb->LdrData            = &ldr;
    peb->OSMajorVersion     = 5;
    peb->OSMinorVersion     = 1;
    peb->OSBuildNumber      = 0xA28;
    peb->OSPlatformId       = VER_PLATFORM_WIN32_NT;
    params.CurrentDirectory.DosPath.Buffer = current_dir;
    params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
    params.wShowWindow = 1; /* SW_SHOWNORMAL */
    ldr.Length = sizeof(ldr);
    RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
    RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
                         sizeof(peb->TlsExpansionBitmapBits) * 8 );
    RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
    RtlSetBits( peb->TlsBitmap, 0, 1 ); /* TLS index 0 is reserved and should be initialized to NULL. */
    RtlSetBits( peb->FlsBitmap, 0, 1 );
    InitializeListHead( &peb->FlsListHead );
    InitializeListHead( &ldr.InLoadOrderModuleList );
    InitializeListHead( &ldr.InMemoryOrderModuleList );
    InitializeListHead( &ldr.InInitializationOrderModuleList );
#ifdef __APPLE__
    dyld_image_info = get_dyld_image_info_addr();
#ifdef __LP64__
#ifdef WORDS_BIGENDIAN
    peb->Reserved[1] = dyld_image_info & 0xFFFFFFFF;
    peb->Reserved[0] = dyld_image_info >> 32;
#else
    peb->Reserved[0] = dyld_image_info & 0xFFFFFFFF;
    peb->Reserved[1] = dyld_image_info >> 32;
#endif
#else
    peb->Reserved[0] = dyld_image_info & 0xFFFFFFFF;
#endif
#endif

    /*
     * Starting with Vista, the first user to log on has session id 1.
     * Session id 0 is for processes that don't interact with the user (like services).
     */
    peb->SessionId = 1;

    /* allocate and initialize the initial TEB */

    signal_alloc_thread( &teb );
    teb->Peb = peb;
    teb->Tib.StackBase = (void *)~0UL;
    teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
    teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);

    thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
    thread_data->request_fd = -1;
    thread_data->reply_fd   = -1;
    thread_data->wait_fd[0] = -1;
    thread_data->wait_fd[1] = -1;
    thread_data->debug_info = &debug_info;
    InsertHeadList( &tls_links, &teb->TlsLinks );

    signal_init_thread( teb );
    virtual_init_threading();

    debug_info.str_pos = debug_info.strings;
    debug_info.out_pos = debug_info.output;
    debug_init();

    /* setup the server connection */
    server_init_process();
    info_size = server_init_thread( peb );

    /* create the process heap */
    if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
    {
        MESSAGE( "wine: failed to create the process heap\n" );
        exit(1);
    }

    /* allocate user parameters */
    if (info_size)
    {
        init_user_process_params( info_size, &exe_file );
    }
    else
    {
        if (isatty(0) || isatty(1) || isatty(2))
            params.ConsoleHandle = (HANDLE)2; /* see kernel32/kernel_private.h */
        if (!isatty(0))
            wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE,  OBJ_INHERIT, &params.hStdInput );
        if (!isatty(1))
            wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdOutput );
        if (!isatty(2))
            wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdError );
    }

    /* initialize user_shared_data */
    __wine_user_shared_data();
    fill_cpu_info();

    NtCreateKeyedEvent( &keyed_event, GENERIC_READ | GENERIC_WRITE, NULL, 0 );

    return exe_file;
}