Пример #1
0
static int OnNtCreateSectionClick(HWND hDlg, UINT nIDCtrl)
{
    TFileTestData * pData = GetDialogData(hDlg);
    POBJECT_ATTRIBUTES pObjectAttributes = NULL;
    OBJECT_ATTRIBUTES ObjAttr;
    UNICODE_STRING SectionName;
    NTSTATUS Status;
    HANDLE FileHandle = NULL;

    // Close the section, if already open
    if(IsHandleValid(pData->hSection))
        OnNtCloseClick(hDlg);

    // Get the values from dialog controls to the dialog data
    if(SaveDialog1(hDlg) != ERROR_SUCCESS)
        return FALSE;

    // Format the object attributes
    if(pData->szSectionName[0] != 0)
    {
        InitializeObjectAttributes(&ObjAttr, &SectionName, OBJ_CASE_INSENSITIVE, NULL, NULL);
        RtlInitUnicodeString(&SectionName, pData->szSectionName);
        pObjectAttributes = &ObjAttr;
    }

    // Get the file handle for it
    if(IsHandleValid(pData->hFile))
        FileHandle = pData->hFile;

    // Either create a section or open one
    if(nIDCtrl == IDC_NTCREATE_SECTION)
    {
        Status = NtCreateSection(&pData->hSection,
                                  pData->dwSectDesiredAccess,
                                  pObjectAttributes,
                                 &pData->MaximumSize,
                                  pData->dwSectPageProtection,
                                  pData->dwSectAllocAttributes,
                                  FileHandle);
    }
    else
    {
        Status = NtOpenSection(&pData->hSection,
                                pData->dwSectDesiredAccess,
                                pObjectAttributes);
    }

    // Set the result info
    SetResultInfo(hDlg, Status, pData->hSection);
    UpdateDialog(hDlg, pData);
    return TRUE;
}
Пример #2
0
/*
* SfuCreateFileMappingNoExec
*
* Purpose:
*
* Map file as non executable image.
*
*/
PVOID SfuCreateFileMappingNoExec(
	_In_ LPWSTR lpFileName
	)
{
	BOOL                   cond = FALSE;
	NTSTATUS               status;
	UNICODE_STRING         usFileName;
	HANDLE                 hFile = NULL, hSection = NULL;
	OBJECT_ATTRIBUTES      obja;
	IO_STATUS_BLOCK        iost;
	SIZE_T                 ViewSize = 0;
	PVOID                  Data = NULL;

	RtlSecureZeroMemory(&usFileName, sizeof(usFileName));

	do {

		if (RtlDosPathNameToNtPathName_U(lpFileName, &usFileName, NULL, NULL) == FALSE)
			break;

		InitializeObjectAttributes(&obja, &usFileName, OBJ_CASE_INSENSITIVE, NULL, NULL);

		status = NtOpenFile(&hFile, FILE_READ_ACCESS | SYNCHRONIZE,
			&obja, &iost, FILE_SHARE_READ,
			FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT);
		if (!NT_SUCCESS(status))
			break;

		status = NtCreateSection(&hSection, SECTION_ALL_ACCESS, NULL,
			NULL, PAGE_READONLY, SEC_IMAGE_NO_EXECUTE, hFile);
		if (!NT_SUCCESS(status))
			break;

		status = NtMapViewOfSection(hSection, NtCurrentProcess(),
			(PVOID)&Data, 0, 0, NULL, &ViewSize, ViewUnmap, 0, PAGE_READONLY);
		if (!NT_SUCCESS(status))
			break;

	} while (cond);

	if (hFile != NULL) {
		NtClose(hFile);
	}
	if (hSection != NULL) {
		NtClose(hSection);
	}
	if (usFileName.Buffer != NULL) {
		RtlFreeUnicodeString(&usFileName);
	}
	return Data;
}
Пример #3
0
NTSTATUS
GRAPHICS_BUFFER_Initialize(OUT PCONSOLE_SCREEN_BUFFER* Buffer,
                           IN OUT PCONSOLE Console,
                           IN PGRAPHICS_BUFFER_INFO GraphicsInfo)
{
    NTSTATUS Status = STATUS_SUCCESS;
    PGRAPHICS_SCREEN_BUFFER NewBuffer = NULL;

    LARGE_INTEGER SectionSize;
    ULONG ViewSize = 0;
    HANDLE ProcessHandle;

    if (Buffer == NULL || Console == NULL || GraphicsInfo == NULL)
        return STATUS_INVALID_PARAMETER;

    *Buffer = NULL;

    Status = CONSOLE_SCREEN_BUFFER_Initialize((PCONSOLE_SCREEN_BUFFER*)&NewBuffer,
                                              Console,
                                              sizeof(GRAPHICS_SCREEN_BUFFER));
    if (!NT_SUCCESS(Status)) return Status;
    NewBuffer->Header.Type = GRAPHICS_BUFFER;
    NewBuffer->Vtbl = &GraphicsVtbl;

    /*
     * Remember the handle to the process so that we can close or unmap
     * correctly the allocated resources when the client releases the
     * screen buffer.
     */
    ProcessHandle = CsrGetClientThread()->Process->ProcessHandle;
    NewBuffer->ClientProcess = ProcessHandle;

    /* Get infos from the graphics buffer information structure */
    NewBuffer->BitMapInfoLength = GraphicsInfo->Info.dwBitMapInfoLength;

    NewBuffer->BitMapInfo = ConsoleAllocHeap(HEAP_ZERO_MEMORY, NewBuffer->BitMapInfoLength);
    if (NewBuffer->BitMapInfo == NULL)
    {
        CONSOLE_SCREEN_BUFFER_Destroy((PCONSOLE_SCREEN_BUFFER)NewBuffer);
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    /* Adjust the bitmap height if needed (bottom-top vs. top-bottom). Use always bottom-up. */
    if (GraphicsInfo->Info.lpBitMapInfo->bmiHeader.biHeight > 0)
        GraphicsInfo->Info.lpBitMapInfo->bmiHeader.biHeight = -GraphicsInfo->Info.lpBitMapInfo->bmiHeader.biHeight;

    /* We do not use anything else than uncompressed bitmaps */
    if (GraphicsInfo->Info.lpBitMapInfo->bmiHeader.biCompression != BI_RGB)
    {
        DPRINT1("biCompression == %d != BI_RGB, correct that!\n", GraphicsInfo->Info.lpBitMapInfo->bmiHeader.biCompression);
        GraphicsInfo->Info.lpBitMapInfo->bmiHeader.biCompression = BI_RGB;
    }

    RtlCopyMemory(NewBuffer->BitMapInfo,
                  GraphicsInfo->Info.lpBitMapInfo,
                  GraphicsInfo->Info.dwBitMapInfoLength);

    NewBuffer->BitMapUsage = GraphicsInfo->Info.dwUsage;

    /* Set the screen buffer size. Fight against overflows. */
    if ( GraphicsInfo->Info.lpBitMapInfo->bmiHeader.biWidth  <= 0xFFFF &&
        -GraphicsInfo->Info.lpBitMapInfo->bmiHeader.biHeight <= 0xFFFF )
    {
        /* Be careful about the sign of biHeight */
        NewBuffer->ScreenBufferSize.X =  (SHORT)GraphicsInfo->Info.lpBitMapInfo->bmiHeader.biWidth ;
        NewBuffer->ScreenBufferSize.Y = (SHORT)-GraphicsInfo->Info.lpBitMapInfo->bmiHeader.biHeight;

        NewBuffer->OldViewSize = NewBuffer->ViewSize = 
            NewBuffer->OldScreenBufferSize = NewBuffer->ScreenBufferSize;
    }
    else
    {
        Status = STATUS_INSUFFICIENT_RESOURCES;
        ConsoleFreeHeap(NewBuffer->BitMapInfo);
        CONSOLE_SCREEN_BUFFER_Destroy((PCONSOLE_SCREEN_BUFFER)NewBuffer);
        goto Quit;
    }

    /*
     * Create a mutex to synchronize bitmap memory access
     * between ourselves and the client.
     */
    Status = NtCreateMutant(&NewBuffer->Mutex, MUTANT_ALL_ACCESS, NULL, FALSE);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtCreateMutant() failed: %lu\n", Status);
        ConsoleFreeHeap(NewBuffer->BitMapInfo);
        CONSOLE_SCREEN_BUFFER_Destroy((PCONSOLE_SCREEN_BUFFER)NewBuffer);
        goto Quit;
    }

    /*
     * Duplicate the Mutex for the client. We must keep a trace of it
     * so that we can close it when the client releases the screen buffer.
     */
    Status = NtDuplicateObject(NtCurrentProcess(),
                               NewBuffer->Mutex,
                               ProcessHandle,
                               &NewBuffer->ClientMutex,
                               0, 0, DUPLICATE_SAME_ACCESS);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtDuplicateObject() failed: %lu\n", Status);
        NtClose(NewBuffer->Mutex);
        ConsoleFreeHeap(NewBuffer->BitMapInfo);
        CONSOLE_SCREEN_BUFFER_Destroy((PCONSOLE_SCREEN_BUFFER)NewBuffer);
        goto Quit;
    }

    /*
     * Create a memory section for the bitmap area, to share with the client.
     */
    SectionSize.QuadPart = NewBuffer->BitMapInfo->bmiHeader.biSizeImage;
    Status = NtCreateSection(&NewBuffer->hSection,
                             SECTION_ALL_ACCESS,
                             NULL,
                             &SectionSize,
                             PAGE_READWRITE,
                             SEC_COMMIT,
                             NULL);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Error: Impossible to create a shared section ; Status = %lu\n", Status);
        NtClose(NewBuffer->ClientMutex);
        NtClose(NewBuffer->Mutex);
        ConsoleFreeHeap(NewBuffer->BitMapInfo);
        CONSOLE_SCREEN_BUFFER_Destroy((PCONSOLE_SCREEN_BUFFER)NewBuffer);
        goto Quit;
    }

    /*
     * Create a view for our needs.
     */
    ViewSize = 0;
    NewBuffer->BitMap = NULL;
    Status = NtMapViewOfSection(NewBuffer->hSection,
                                NtCurrentProcess(),
                                (PVOID*)&NewBuffer->BitMap,
                                0,
                                0,
                                NULL,
                                &ViewSize,
                                ViewUnmap,
                                0,
                                PAGE_READWRITE);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Error: Impossible to map the shared section ; Status = %lu\n", Status);
        NtClose(NewBuffer->hSection);
        NtClose(NewBuffer->ClientMutex);
        NtClose(NewBuffer->Mutex);
        ConsoleFreeHeap(NewBuffer->BitMapInfo);
        CONSOLE_SCREEN_BUFFER_Destroy((PCONSOLE_SCREEN_BUFFER)NewBuffer);
        goto Quit;
    }

    /*
     * Create a view for the client. We must keep a trace of it so that
     * we can unmap it when the client releases the screen buffer.
     */
    ViewSize = 0;
    NewBuffer->ClientBitMap = NULL;
    Status = NtMapViewOfSection(NewBuffer->hSection,
                                ProcessHandle,
                                (PVOID*)&NewBuffer->ClientBitMap,
                                0,
                                0,
                                NULL,
                                &ViewSize,
                                ViewUnmap,
                                0,
                                PAGE_READWRITE);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Error: Impossible to map the shared section ; Status = %lu\n", Status);
        NtUnmapViewOfSection(NtCurrentProcess(), NewBuffer->BitMap);
        NtClose(NewBuffer->hSection);
        NtClose(NewBuffer->ClientMutex);
        NtClose(NewBuffer->Mutex);
        ConsoleFreeHeap(NewBuffer->BitMapInfo);
        CONSOLE_SCREEN_BUFFER_Destroy((PCONSOLE_SCREEN_BUFFER)NewBuffer);
        goto Quit;
    }

    NewBuffer->ViewOrigin.X = NewBuffer->ViewOrigin.Y = 0;
    NewBuffer->VirtualY = 0;

    NewBuffer->CursorBlinkOn  = FALSE;
    NewBuffer->ForceCursorOff = TRUE;
    NewBuffer->CursorInfo.bVisible = FALSE;
    NewBuffer->CursorInfo.dwSize   = 0;
    NewBuffer->CursorPosition.X = NewBuffer->CursorPosition.Y = 0;

    NewBuffer->Mode = 0;

    *Buffer = (PCONSOLE_SCREEN_BUFFER)NewBuffer;
    Status = STATUS_SUCCESS;

Quit:
    return Status;
}
Пример #4
0
/*
 * Maps an image file into a section
 */
NTSTATUS
WINAPI
BasepMapFile(IN LPCWSTR lpApplicationName,
             OUT PHANDLE hSection,
             IN PUNICODE_STRING ApplicationName)
{
    RTL_RELATIVE_NAME_U RelativeName;
    OBJECT_ATTRIBUTES ObjectAttributes;
    NTSTATUS Status;
    HANDLE hFile = NULL;
    IO_STATUS_BLOCK IoStatusBlock;

    DPRINT("BasepMapFile\n");

    /* Zero out the Relative Directory */
    RelativeName.ContainingDirectory = NULL;

    /* Find the application name */
    if (!RtlDosPathNameToNtPathName_U(lpApplicationName,
                                      ApplicationName,
                                      NULL,
                                      &RelativeName))
    {
        return STATUS_OBJECT_PATH_NOT_FOUND;
    }

    DPRINT("ApplicationName %wZ\n", ApplicationName);
    DPRINT("RelativeName %wZ\n", &RelativeName.RelativeName);

    /* Did we get a relative name? */
    if (RelativeName.RelativeName.Length)
    {
        ApplicationName = &RelativeName.RelativeName;
    }

    /* Initialize the Object Attributes */
    InitializeObjectAttributes(&ObjectAttributes,
                               ApplicationName,
                               OBJ_CASE_INSENSITIVE,
                               RelativeName.ContainingDirectory,
                               NULL);

    /* Try to open the executable */
    Status = NtOpenFile(&hFile,
                        SYNCHRONIZE | FILE_EXECUTE | FILE_READ_DATA,
                        &ObjectAttributes,
                        &IoStatusBlock,
                        FILE_SHARE_DELETE | FILE_SHARE_READ,
                        FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Failed to open file\n");
        BaseSetLastNTError(Status);
        return Status;
    }

    /* Create a section for this file */
    Status = NtCreateSection(hSection,
                             SECTION_ALL_ACCESS,
                             NULL,
                             NULL,
                             PAGE_EXECUTE,
                             SEC_IMAGE,
                             hFile);
    NtClose(hFile);

    /* Return status */
    DPRINT("Section: %p for file: %p\n", *hSection, hFile);
    return Status;
}
Пример #5
0
NTSTATUS PhMapViewOfEntireFile(
    _In_opt_ PWSTR FileName,
    _In_opt_ HANDLE FileHandle,
    _In_ BOOLEAN ReadOnly,
    _Out_ PVOID *ViewBase,
    _Out_ PSIZE_T Size
    )
{
    NTSTATUS status;
    BOOLEAN openedFile = FALSE;
    LARGE_INTEGER size;
    HANDLE sectionHandle = NULL;
    SIZE_T viewSize;
    PVOID viewBase;

    if (!FileName && !FileHandle)
        return STATUS_INVALID_PARAMETER_MIX;

    // Open the file if we weren't supplied a file handle.
    if (!FileHandle)
    {
        status = PhCreateFileWin32(
            &FileHandle,
            FileName,
            ((FILE_EXECUTE | FILE_READ_ATTRIBUTES | FILE_READ_DATA) |
            (!ReadOnly ? (FILE_APPEND_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_DATA) : 0)) | SYNCHRONIZE,
            0,
            FILE_SHARE_READ,
            FILE_OPEN,
            FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT
            );

        if (!NT_SUCCESS(status))
            return status;

        openedFile = TRUE;
    }

    // Get the file size and create the section.

    status = PhGetFileSize(FileHandle, &size);

    if (!NT_SUCCESS(status))
        goto CleanupExit;

    status = NtCreateSection(
        &sectionHandle,
        SECTION_ALL_ACCESS,
        NULL,
        &size,
        ReadOnly ? PAGE_EXECUTE_READ : PAGE_EXECUTE_READWRITE,
        SEC_COMMIT,
        FileHandle
        );

    if (!NT_SUCCESS(status))
        goto CleanupExit;

    // Map the section.

    viewSize = (SIZE_T)size.QuadPart;
    viewBase = NULL;

    status = NtMapViewOfSection(
        sectionHandle,
        NtCurrentProcess(),
        &viewBase,
        0,
        0,
        NULL,
        &viewSize,
        ViewShare,
        0,
        ReadOnly ? PAGE_EXECUTE_READ : PAGE_EXECUTE_READWRITE
        );

    if (!NT_SUCCESS(status))
        goto CleanupExit;

    *ViewBase = viewBase;
    *Size = (SIZE_T)size.QuadPart;

CleanupExit:
    if (sectionHandle)
        NtClose(sectionHandle);
    if (openedFile)
        NtClose(FileHandle);

    return status;
}
Пример #6
0
NTSTATUS ApfCreateDataSection(PAPFCONTROL *ApfDataSectionPointer)
{
    NTSTATUS Status;
    STRING ApfDataSectionName;
    UNICODE_STRING ApfDataSectionUnicodeName;
    OBJECT_ATTRIBUTES ObjectAttributes;
    LARGE_INTEGER AllocationSize;
    ULONG ViewSize;
    PAPFCONTROL DataSectionPointer;
	
    //
    // Initialize object attributes
    //
    RtlInitString(&ApfDataSectionName, DATA_SEC_NAME);
	
    Status = RtlAnsiStringToUnicodeString(
		&ApfDataSectionUnicodeName,
		&ApfDataSectionName,
		TRUE);

    if (NT_SUCCESS(Status)) {
	InitializeObjectAttributes(
		&ObjectAttributes,
		&ApfDataSectionUnicodeName,
		OBJ_OPENIF | OBJ_CASE_INSENSITIVE,
		NULL,
		&SecDescriptor);
    }
#ifdef ERRORDBG
    else {
	KdPrint (("WAP: RtlAnsiStringToUnicodeString() failed in "
	    "ApfCreateDataSection, %lx\n", Status));
    }
#endif
	
    AllocationSize.HighPart = 0;

    // Need a slot to account for calibration data
    //
    AllocationSize.LowPart = (API_COUNT + 1) * sizeof(APFDATA);
	
    // Create a read-write section
    //
    Status = NtCreateSection(&ApfDataSectionHandle,
		 SECTION_MAP_READ | SECTION_MAP_WRITE,
		 &ObjectAttributes,
		 &AllocationSize,
		 PAGE_READWRITE,
		 SEC_COMMIT,
		 NULL);
    if (NT_SUCCESS(Status)) {
	ViewSize = AllocationSize.LowPart;
	DataSectionPointer = NULL;
		
	// Map the section
	//
	Status = NtMapViewOfSection(ApfDataSectionHandle,
			MyProcess,
			(PVOID *)&DataSectionPointer,
			0,
			AllocationSize.LowPart,
			NULL,
			&ViewSize,
			ViewUnmap,
			0L,
			PAGE_READWRITE);
#ifdef ERRORDBG
    	if (!NT_SUCCESS(Status)) {
	    KdPrint (("WAP: NtMapViewOfSection() failed in ApfCreateDataSection,"
		" %lx\n", Status));
        }
#endif
	*ApfDataSectionPointer = DataSectionPointer;
    }
#ifdef ERRORDBG
    else {
	KdPrint (("WAP: NtCreateSection() failed in ApfCreateDataSection "
	    "%lx\n", Status));
    }
#endif
	
    return(Status);

} /* ApfCreateDataSection () */
Пример #7
0
NTSTATUS
CsrpConnectToServer(
    IN PWSTR ObjectDirectory
    )
{
    NTSTATUS Status;
    REMOTE_PORT_VIEW ServerView;
    ULONG MaxMessageLength;
    ULONG ConnectionInformationLength;
    CSR_API_CONNECTINFO ConnectionInformation;
    SECURITY_QUALITY_OF_SERVICE DynamicQos;
    HANDLE PortSection;
    PORT_VIEW ClientView;
    ULONG n;
    LARGE_INTEGER SectionSize;

    //
    // Create the port name string by combining the passed in object directory
    // name with the port name.
    //

    n = ((wcslen( ObjectDirectory ) + 1) * sizeof( WCHAR )) +
        sizeof( CSR_API_PORT_NAME );
    CsrPortName.Length = 0;
    CsrPortName.MaximumLength = (USHORT)n;
    CsrPortName.Buffer = RtlAllocateHeap( CsrHeap, MAKE_TAG( CSR_TAG ), n );
    if (CsrPortName.Buffer == NULL) {
        return( STATUS_NO_MEMORY );
        }
    RtlAppendUnicodeToString( &CsrPortName, ObjectDirectory );
    RtlAppendUnicodeToString( &CsrPortName, L"\\" );
    RtlAppendUnicodeToString( &CsrPortName, CSR_API_PORT_NAME );

    //
    // Set up the security quality of service parameters to use over the
    // port.  Use the most efficient (least overhead) - which is dynamic
    // rather than static tracking.
    //

    DynamicQos.ImpersonationLevel = SecurityImpersonation;
    DynamicQos.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
    DynamicQos.EffectiveOnly = TRUE;


    //
    // Create a section to contain the Port Memory.  Port Memory is private
    // memory that is shared between the client and server processes.
    // This allows data that is too large to fit into an API request message
    // to be passed to the server.
    //

    SectionSize.LowPart = CSR_PORT_MEMORY_SIZE;
    SectionSize.HighPart = 0;

    Status = NtCreateSection( &PortSection,
                              SECTION_ALL_ACCESS,
                              NULL,
                              &SectionSize,
                              PAGE_READWRITE,
                              SEC_RESERVE,
                              NULL
                            );
    if (!NT_SUCCESS( Status )) {
        return( Status );
        }

    //
    // Connect to the server.  This includes a description of the Port Memory
    // section so that the LPC connection logic can make the section visible
    // to both the client and server processes.  Also pass information the
    // server needs in the connection information structure.
    //

    ClientView.Length = sizeof( ClientView );
    ClientView.SectionHandle = PortSection;
    ClientView.SectionOffset = 0;
    ClientView.ViewSize = SectionSize.LowPart;
    ClientView.ViewBase = 0;
    ClientView.ViewRemoteBase = 0;

    ServerView.Length = sizeof( ServerView );
    ServerView.ViewSize = 0;
    ServerView.ViewBase = 0;

    ConnectionInformationLength = sizeof( ConnectionInformation );
    ConnectionInformation.ExpectedVersion = CSR_VERSION;

    Status = NtConnectPort( &CsrPortHandle,
                            &CsrPortName,
                            &DynamicQos,
                            &ClientView,
                            &ServerView,
                            (PULONG)&MaxMessageLength,
                            (PVOID)&ConnectionInformation,
                            (PULONG)&ConnectionInformationLength
                          );
    NtClose( PortSection );
    if (!NT_SUCCESS( Status )) {
        IF_DEBUG {
            DbgPrint( "CSRDLL: Unable to connect to %wZ Server - Status == %X\n",
                      &CsrPortName,
                      Status
                    );
            }

        return( Status );
        }
Пример #8
0
static NTSTATUS
TH32CreateSnapshotSectionInitialize(DWORD dwFlags,
                                    DWORD th32ProcessID,
                                    PRTL_DEBUG_INFORMATION HeapDebug,
                                    PRTL_DEBUG_INFORMATION ModuleDebug,
                                    PVOID ProcThrdInfo,
                                    HANDLE *SectionHandle)
{
  PSYSTEM_PROCESS_INFORMATION ProcessInfo;
  LPHEAPLIST32 HeapListEntry;
  LPMODULEENTRY32W ModuleListEntry;
  LPPROCESSENTRY32W ProcessListEntry;
  LPTHREADENTRY32 ThreadListEntry;
  OBJECT_ATTRIBUTES ObjectAttributes;
  LARGE_INTEGER SSize, SOffset;
  HANDLE hSection;
  PTH32SNAPSHOT Snapshot;
  ULONG_PTR DataOffset;
  SIZE_T ViewSize;
  ULONG i, nProcesses = 0, nThreads = 0, nHeaps = 0, nModules = 0;
  ULONG RequiredSnapshotSize = sizeof(TH32SNAPSHOT);
  PRTL_PROCESS_HEAPS hi = NULL;
  PRTL_PROCESS_MODULES mi = NULL;
  NTSTATUS Status = STATUS_SUCCESS;

  /*
   * Determine the required size for the heap snapshot
   */
  if(dwFlags & TH32CS_SNAPHEAPLIST)
  {
    hi = (PRTL_PROCESS_HEAPS)HeapDebug->Heaps;
    nHeaps = hi->NumberOfHeaps;
    RequiredSnapshotSize += nHeaps * sizeof(HEAPLIST32);
  }

  /*
   * Determine the required size for the module snapshot
   */
  if(dwFlags & TH32CS_SNAPMODULE)
  {
    mi = (PRTL_PROCESS_MODULES)ModuleDebug->Modules;
    nModules = mi->NumberOfModules;
    RequiredSnapshotSize += nModules * sizeof(MODULEENTRY32W);
  }

  /*
   * Determine the required size for the processes and threads snapshot
   */
  if(dwFlags & (TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD))
  {
    ULONG ProcOffset = 0;

    ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)ProcThrdInfo;
    do
    {
      ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)((ULONG_PTR)ProcessInfo + ProcOffset);
      nProcesses++;
      nThreads += ProcessInfo->NumberOfThreads;
      ProcOffset = ProcessInfo->NextEntryOffset;
    } while(ProcOffset != 0);

    if(dwFlags & TH32CS_SNAPPROCESS)
    {
      RequiredSnapshotSize += nProcesses * sizeof(PROCESSENTRY32W);
    }
    if(dwFlags & TH32CS_SNAPTHREAD)
    {
      RequiredSnapshotSize += nThreads * sizeof(THREADENTRY32);
    }
  }

  /*
   * Create and map the section
   */

  SSize.QuadPart = RequiredSnapshotSize;

  InitializeObjectAttributes(&ObjectAttributes,
                             NULL,
                             ((dwFlags & TH32CS_INHERIT) ? OBJ_INHERIT : 0),
			     NULL,
			     NULL);

  Status = NtCreateSection(&hSection,
                           SECTION_ALL_ACCESS,
                           &ObjectAttributes,
                           &SSize,
                           PAGE_READWRITE,
                           SEC_COMMIT,
                           NULL);
  if(!NT_SUCCESS(Status))
  {
    return Status;
  }

  SOffset.QuadPart = 0;
  ViewSize = 0;
  Snapshot = NULL;

  Status = NtMapViewOfSection(hSection,
                              NtCurrentProcess(),
                              (PVOID*)&Snapshot,
                              0,
                              0,
                              &SOffset,
                              &ViewSize,
                              ViewShare,
                              0,
                              PAGE_READWRITE);
  if(!NT_SUCCESS(Status))
  {
    NtClose(hSection);
    return Status;
  }

  RtlZeroMemory(Snapshot, sizeof(TH32SNAPSHOT));
  DataOffset = 0;

  /*
   * Initialize the section data and fill it with all the data we collected
   */

  /* initialize the heap list */
  if(dwFlags & TH32CS_SNAPHEAPLIST)
  {
    Snapshot->HeapListCount = nHeaps;
    Snapshot->HeapListOffset = DataOffset;
    HeapListEntry = (LPHEAPLIST32)OffsetToPtr(Snapshot, DataOffset);
    for(i = 0; i < nHeaps; i++)
    {
      HeapListEntry->dwSize = sizeof(HEAPLIST32);
      HeapListEntry->th32ProcessID = th32ProcessID;
      HeapListEntry->th32HeapID = (ULONG_PTR)hi->Heaps[i].BaseAddress;
      HeapListEntry->dwFlags = hi->Heaps[i].Flags;

      HeapListEntry++;
    }

    DataOffset += hi->NumberOfHeaps * sizeof(HEAPLIST32);
  }

  /* initialize the module list */
  if(dwFlags & TH32CS_SNAPMODULE)
  {
    Snapshot->ModuleListCount = nModules;
    Snapshot->ModuleListOffset = DataOffset;
    ModuleListEntry = (LPMODULEENTRY32W)OffsetToPtr(Snapshot, DataOffset);
    for(i = 0; i < nModules; i++)
    {
      ModuleListEntry->dwSize = sizeof(MODULEENTRY32W);
      ModuleListEntry->th32ModuleID = 1; /* no longer used, always set to one! */
      ModuleListEntry->th32ProcessID = th32ProcessID;
      ModuleListEntry->GlblcntUsage = mi->Modules[i].LoadCount;
      ModuleListEntry->ProccntUsage = mi->Modules[i].LoadCount;
      ModuleListEntry->modBaseAddr = (BYTE*)mi->Modules[i].ImageBase;
      ModuleListEntry->modBaseSize = mi->Modules[i].ImageSize;
      ModuleListEntry->hModule = (HMODULE)mi->Modules[i].ImageBase;

      MultiByteToWideChar(CP_ACP,
                          0,
                          &mi->Modules[i].FullPathName[mi->Modules[i].OffsetToFileName],
                          -1,
                          ModuleListEntry->szModule,
                          sizeof(ModuleListEntry->szModule) / sizeof(ModuleListEntry->szModule[0]));

      MultiByteToWideChar(CP_ACP,
                          0,
                          mi->Modules[i].FullPathName,
                          -1,
                          ModuleListEntry->szExePath,
                          sizeof(ModuleListEntry->szExePath) / sizeof(ModuleListEntry->szExePath[0]));

      ModuleListEntry++;
    }

    DataOffset += mi->NumberOfModules * sizeof(MODULEENTRY32W);
  }

  /* initialize the process list */
  if(dwFlags & TH32CS_SNAPPROCESS)
  {
    ULONG ProcOffset = 0;

    Snapshot->ProcessListCount = nProcesses;
    Snapshot->ProcessListOffset = DataOffset;
    ProcessListEntry = (LPPROCESSENTRY32W)OffsetToPtr(Snapshot, DataOffset);
    ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)ProcThrdInfo;
    do
    {
      ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)((ULONG_PTR)ProcessInfo + ProcOffset);

      ProcessListEntry->dwSize = sizeof(PROCESSENTRY32W);
      ProcessListEntry->cntUsage = 0; /* no longer used */
      ProcessListEntry->th32ProcessID = (ULONG_PTR)ProcessInfo->UniqueProcessId;
      ProcessListEntry->th32DefaultHeapID = 0; /* no longer used */
      ProcessListEntry->th32ModuleID = 0; /* no longer used */
      ProcessListEntry->cntThreads = ProcessInfo->NumberOfThreads;
      ProcessListEntry->th32ParentProcessID = (ULONG_PTR)ProcessInfo->InheritedFromUniqueProcessId;
      ProcessListEntry->pcPriClassBase = ProcessInfo->BasePriority;
      ProcessListEntry->dwFlags = 0; /* no longer used */
      if(ProcessInfo->ImageName.Buffer != NULL)
      {
        lstrcpynW(ProcessListEntry->szExeFile,
                  ProcessInfo->ImageName.Buffer,
                  min(ProcessInfo->ImageName.Length / sizeof(WCHAR), sizeof(ProcessListEntry->szExeFile) / sizeof(ProcessListEntry->szExeFile[0])));
      }
      else
      {
        lstrcpyW(ProcessListEntry->szExeFile, L"[System Process]");
      }

      ProcessListEntry++;

      ProcOffset = ProcessInfo->NextEntryOffset;
    } while(ProcOffset != 0);

    DataOffset += nProcesses * sizeof(PROCESSENTRY32W);
  }

  /* initialize the thread list */
  if(dwFlags & TH32CS_SNAPTHREAD)
  {
    ULONG ProcOffset = 0;

    Snapshot->ThreadListCount = nThreads;
    Snapshot->ThreadListOffset = DataOffset;
    ThreadListEntry = (LPTHREADENTRY32)OffsetToPtr(Snapshot, DataOffset);
    ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)ProcThrdInfo;
    do
    {
      PSYSTEM_THREAD_INFORMATION ThreadInfo;
      ULONG n;

      ProcessInfo = (PSYSTEM_PROCESS_INFORMATION)((ULONG_PTR)ProcessInfo + ProcOffset);
      ThreadInfo = (PSYSTEM_THREAD_INFORMATION)(ProcessInfo + 1);

      for(n = 0; n < ProcessInfo->NumberOfThreads; n++)
      {
        ThreadListEntry->dwSize = sizeof(THREADENTRY32);
        ThreadListEntry->cntUsage = 0; /* no longer used */
        ThreadListEntry->th32ThreadID = (ULONG_PTR)ThreadInfo->ClientId.UniqueThread;
        ThreadListEntry->th32OwnerProcessID = (ULONG_PTR)ThreadInfo->ClientId.UniqueProcess;
        ThreadListEntry->tpBasePri = ThreadInfo->BasePriority;
        ThreadListEntry->tpDeltaPri = 0; /* no longer used */
        ThreadListEntry->dwFlags = 0; /* no longer used */

        ThreadInfo++;
        ThreadListEntry++;
      }

      ProcOffset = ProcessInfo->NextEntryOffset;
    } while(ProcOffset != 0);
  }

  /*
   * We're done, unmap the view and return the section handle
   */

  Status = NtUnmapViewOfSection(NtCurrentProcess(), (PVOID)Snapshot);

  if(NT_SUCCESS(Status))
  {
    *SectionHandle = hSection;
  }
  else
  {
    NtClose(hSection);
  }

  return Status;
}
Пример #9
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;
}
Пример #10
0
NTSTATUS
SrvValidateSlmStatus(
    IN HANDLE StatusFile,
    OUT PULONG FileOffsetOfInvalidData
    )
{
    NTSTATUS Status;
    IO_STATUS_BLOCK IoStatus;
    FILE_STANDARD_INFORMATION FileInformation;
    HANDLE Section;
    PVOID ViewBase;
    ULONG ViewSize;

    *FileOffsetOfInvalidData = -1;

    if ( !SrvDisallowSlmAccessEnabled ) {
        return STATUS_SUCCESS;
    }

    Status = NtQueryInformationFile( StatusFile,
                                     &IoStatus,
                                     (PVOID) &FileInformation,
                                     sizeof( FileInformation ),
                                     FileStandardInformation
                                   );
    if (!NT_SUCCESS( Status )) {
        return( Status );
        }

    Status = NtCreateSection( &Section,
                              SECTION_ALL_ACCESS,
                              NULL,
                              NULL,
                              PAGE_READONLY,
                              SEC_COMMIT,
                              StatusFile
                            );
    if (!NT_SUCCESS( Status )) {
        if (Status == STATUS_MAPPED_FILE_SIZE_ZERO) {
            return( STATUS_SUCCESS );
            }
        return( Status );
        }

    ViewBase = NULL;
    ViewSize = 0;
    Status = NtMapViewOfSection( Section,
                                 NtCurrentProcess(),
                                 &ViewBase,
                                 0L,
                                 0L,
                                 NULL,
                                 &ViewSize,
                                 ViewShare,
                                 0L,
                                 PAGE_READONLY
                               );
    NtClose( Section );

    if (!NT_SUCCESS( Status )) {
	if (Status == STATUS_MAPPED_FILE_SIZE_ZERO) {
	    return( STATUS_SUCCESS );
	    }
	else {
	    return( Status );
	    }
        }

    Status = SrvpValidateStatusFile( ViewBase,
                                     FileInformation.EndOfFile.LowPart,
                                     FileOffsetOfInvalidData
                                   );

    (VOID)NtUnmapViewOfSection( NtCurrentProcess(),
                                ViewBase
                              );

    return( Status );
}
Пример #11
0
ULONG
BaseSrvNlsCreateSortSection(
    IN OUT PCSR_API_MSG m,
    IN OUT PCSR_REPLY_STATUS ReplyStatus)
{
    PBASE_NLS_CREATE_SORT_SECTION_MSG a =
        (PBASE_NLS_CREATE_SORT_SECTION_MSG)&m->u.ApiMessageData;

    HANDLE hNewSec = (HANDLE)0;              /* new section handle */
    HANDLE hProcess = (HANDLE)0;             /* process handle */
    OBJECT_ATTRIBUTES ObjA;                  /* object attributes structure */
    NTSTATUS rc = 0L;                        /* return code */
    ULONG pSecurityDescriptor[MAX_PATH_LEN]; /* security descriptor buffer */
    PSID pWorldSid;                          /* ptr to world SID */


    /*
     *  Set the handles to null.
     */
    a->hNewSection = NULL;

    /*
     *  Create the NEW Section for Read and Write access.
     *  Add a ReadOnly security descriptor so that only the
     *  initial creating process may write to the section.
     */
    if (rc = CreateSecurityDescriptor(pSecurityDescriptor,
                                      &pWorldSid,
                                      GENERIC_READ))
    {
        return (rc);
    }

    InitializeObjectAttributes(&ObjA,
                               &(a->SectionName),
                               OBJ_PERMANENT | OBJ_CASE_INSENSITIVE,
                               NULL,
                               pSecurityDescriptor);

    rc = NtCreateSection(&hNewSec,
                         SECTION_MAP_READ | SECTION_MAP_WRITE,
                         &ObjA,
                         &(a->SectionSize),
                         PAGE_READWRITE,
                         SEC_COMMIT,
                         NULL);

    /*
     *  Check for error from NtCreateSection.
     */
    if (!NT_SUCCESS(rc))
    {
        /*
         *  If the name has already been created, ignore the error.
         */
        if (rc != STATUS_OBJECT_NAME_COLLISION)
        {
            KdPrint(("NLSAPI (BaseSrv): Could NOT Create Section %wZ - %lx.\n",
                     &(a->SectionName), rc));
            return (rc);
        }
    }

    /*
     *  Duplicate the new section handle for the client.
     *  The client will map a view of the section and fill in the data.
     */
    InitializeObjectAttributes(&ObjA,
                               NULL,
                               0,
                               NULL,
                               NULL);

    rc = NtOpenProcess(&hProcess,
                       PROCESS_DUP_HANDLE,
                       &ObjA,
                       &m->h.ClientId);

    if (!NT_SUCCESS(rc))
    {
        KdPrint(("NLSAPI (BaseSrv): Could NOT Open Process - %lx.\n", rc));
        return (rc);
    }

    rc = NtDuplicateObject(NtCurrentProcess(),
                           hNewSec,
                           hProcess,
                           &(a->hNewSection),
                           0L,
                           0L,
                           DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);

    /*
     *  Return the return value from NtDuplicateObject.
     */
    return (rc);

    ReplyStatus;    // get rid of unreferenced parameter warning message
}
Пример #12
0
_CRTAPI1 main()
{
    LONG i, j;
    PULONG p4, p3, p2, p1, oldp1, vp1;
    ULONG Size1, Size2, Size3;
    NTSTATUS status, alstatus;
    HANDLE CurrentProcessHandle;
    HANDLE GiantSection;
    HANDLE Section2, Section4;
    MEMORY_BASIC_INFORMATION MemInfo;
    ULONG OldProtect;
    STRING Name3;
    HANDLE Section1;
    OBJECT_ATTRIBUTES ObjectAttributes;
    OBJECT_ATTRIBUTES Object1Attributes;
    ULONG ViewSize;
    LARGE_INTEGER Offset;
    LARGE_INTEGER SectionSize;
    UNICODE_STRING Unicode;

    CurrentProcessHandle = NtCurrentProcess();

    DbgPrint(" Memory Management Tests - AllocVm, FreeVm, ProtectVm, QueryVm\n");

    p1 = (PULONG)0x20020000;
    Size1 = 0xbc0000;

    alstatus = NtAllocateVirtualMemory (CurrentProcessHandle, (PVOID *)&p1,
                        0, &Size1, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);

    if (!NT_SUCCESS(alstatus)) {
        DbgPrint("failed first created vm status %X start %lx size %lx\n",
            alstatus, (ULONG)p1, Size1);
        DbgPrint("******** FAILED TEST 1 **************\n");
    }

    status = NtQueryVirtualMemory (CurrentProcessHandle, p1,
                                    MemoryBasicInformation,
                                    &MemInfo, sizeof (MEMORY_BASIC_INFORMATION),
                                    NULL);

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 2 **************\n");
        DbgPrint("FAILURE query vm status %X address %lx Base %lx size %lx\n",
             status,
             p1,
             MemInfo.BaseAddress,
             MemInfo.RegionSize);
        DbgPrint("     state %lx protect %lx type %lx\n",
             MemInfo.State,
             MemInfo.Protect,
             MemInfo.Type);
    }
    if ((MemInfo.RegionSize != Size1) || (MemInfo.BaseAddress != p1) ||
        (MemInfo.Protect != PAGE_READWRITE) || (MemInfo.Type != MEM_PRIVATE) ||
        (MemInfo.State != MEM_COMMIT)) {

        DbgPrint("******** FAILED TEST 3 **************\n");
        DbgPrint("FAILURE query vm status %X address %lx Base %lx size %lx\n",
             status,
             p1,
             MemInfo.BaseAddress,
             MemInfo.RegionSize);
        DbgPrint("     state %lx protect %lx type %lx\n",
             MemInfo.State,
             MemInfo.Protect,
             MemInfo.Type);
    }

    p2 = (PULONG)NULL;
    Size2 = 0x100000;

    alstatus = NtAllocateVirtualMemory (CurrentProcessHandle,
                                      (PVOID *)&p2,
                                       3,
                                       &Size2,
                                       MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT,
                                       PAGE_READWRITE);

    if (!NT_SUCCESS(alstatus)) {
        DbgPrint("failed first created vm status %lC start %lx size %lx\n",
            status, (ULONG)p1, Size1);
        DbgPrint("******** FAILED TEST 3a.1 **************\n");
        NtTerminateProcess(NtCurrentProcess(),status);

    }

    //
    // Touch every other page.
    //

    vp1 = p2 + 3000;
    while (vp1 < (PULONG)((PCHAR)p2 + Size2)) {
        *vp1 = 938;
        vp1 += 3000;
    }

    //
    // Decommit pages.
    //

    Size3 = Size2 - 5044;
    vp1 = p2 + 3000;

    status = NtFreeVirtualMemory (CurrentProcessHandle,
                                      (PVOID *)&p2,
                                      &Size3,
                                      MEM_DECOMMIT);

    if (!(NT_SUCCESS(status))) {
        DbgPrint(" free vm failed - status %lx\n",status);
        DbgPrint("******** FAILED TEST 3a.4 **************\n");
        NtTerminateProcess(NtCurrentProcess(),status);
    }

    //
    // Split the memory block using MEM_RELEASE.
    //


    vp1 = p2 + 5000;
    Size3 = Size2 - 50000;

    status = NtFreeVirtualMemory (CurrentProcessHandle,
                                      (PVOID *)&vp1,
                                      &Size3,
                                      MEM_RELEASE);

    if (!(NT_SUCCESS(status))) {
        DbgPrint(" free vm failed - status %lx\n",status);
        DbgPrint("******** FAILED TEST 3a.b **************\n");
        NtTerminateProcess(NtCurrentProcess(),status);
    }

    vp1 = p2 + 3000;
    Size3 = 41;

    status = NtFreeVirtualMemory (CurrentProcessHandle,
                                      (PVOID *)&vp1,
                                      &Size3,
                                      MEM_RELEASE);

    if (!(NT_SUCCESS(status))) {
        DbgPrint(" free vm failed - status %lx\n",status);
        DbgPrint("******** FAILED TEST 3a.5 **************\n");
        NtTerminateProcess(NtCurrentProcess(),status);
    }

    //
    // free every page, ignore the status.
    //

    vp1 = p2;
    Size3 = 30;
    while (vp1 < (PULONG)((PCHAR)p2 + Size2)) {

        status = NtFreeVirtualMemory (CurrentProcessHandle,
                                      (PVOID *)&vp1,
                                      &Size3,
                                      MEM_RELEASE);
        vp1 += 128;
    }

    p2 = (PULONG)NULL;
    Size2 = 0x10000;

    status = NtAllocateVirtualMemory (CurrentProcessHandle,
                                      (PVOID *)&p2,
                                       3,
                                       &Size2,
                                       MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT,
                                       PAGE_READWRITE);

    if (!NT_SUCCESS(status)) {
        DbgPrint("failed first created vm status %X start %lx size %lx\n",
            status, (ULONG)p1, Size1);
        DbgPrint("******** FAILED TEST 3.1 **************\n");
    } else {
        if (p2 != (PVOID)0x1fff0000) {
            DbgPrint("******** FAILED TEST 3.2 **************\n");
            DbgPrint("p2 = %lx\n",p2);
        }
        status = NtFreeVirtualMemory (CurrentProcessHandle,
                                      (PVOID *)&p2,
                                      &Size2,
                                      MEM_RELEASE);

        if (!(NT_SUCCESS(status))) {
            DbgPrint(" free vm failed - status %lx\n",status);
            DbgPrint("******** FAILED TEST 3.3 **************\n");
            NtTerminateProcess(NtCurrentProcess(),status);
        }
    }

    if (NT_SUCCESS(alstatus)) {
        status = NtFreeVirtualMemory (CurrentProcessHandle,
                                      (PVOID *)&p1,
                                      &Size1,
                                      MEM_RELEASE);
    }

    if (!(NT_SUCCESS(status))) {
        DbgPrint(" free vm failed - status %lx\n",status);
        DbgPrint("******** FAILED TEST 4 **************\n");
        NtTerminateProcess(NtCurrentProcess(),status);
    }

    p1 = (PULONG)NULL;
    Size1 = 16 * 4096;
    status = NtAllocateVirtualMemory (CurrentProcessHandle, (PVOID *)&p1,
                        0, &Size1, MEM_RESERVE, PAGE_READWRITE | PAGE_GUARD);

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 5 **************\n");

        DbgPrint("created vm status %X start %lx size %lx\n",
            status, (ULONG)p1, Size1);
    }
    status = NtQueryVirtualMemory (CurrentProcessHandle, p1,
                                    MemoryBasicInformation,
                                    &MemInfo, sizeof (MEMORY_BASIC_INFORMATION),
                                    NULL);

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 6 **************\n");
        DbgPrint("query vm status %X address %lx Base %lx size %lx\n",
             status,
             p1,
             MemInfo.BaseAddress,
             MemInfo.RegionSize);
        DbgPrint("     state %lx protect %lx alloc_protect %lx type %lx\n",
             MemInfo.State,
             MemInfo.Protect,
             MemInfo.AllocationProtect,
             MemInfo.Type);
    }

    if ((MemInfo.RegionSize != Size1) || (MemInfo.BaseAddress != p1) ||
        (MemInfo.AllocationProtect != (PAGE_READWRITE | PAGE_GUARD)) ||
        (MemInfo.Protect != 0) ||
        (MemInfo.Type != MEM_PRIVATE) ||
        (MemInfo.State != MEM_RESERVE)) {

        DbgPrint("******** FAILED TEST 7 **************\n");
        DbgPrint("query vm status %X address %lx Base %lx size %lx\n",
             status,
             p1,
             MemInfo.BaseAddress,
             MemInfo.RegionSize);
        DbgPrint("     state %lx protect %lx alloc_protect %lx type %lx\n",
             MemInfo.State,
             MemInfo.Protect,
             MemInfo.AllocationProtect,
             MemInfo.Type);
    }

    Size2 = 8192;

    oldp1 = p1;
    p1 = p1 + 14336;  // 64k -8k /4

    status = NtAllocateVirtualMemory (CurrentProcessHandle, (PVOID *)&p1,
                        0, &Size2, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 8 **************\n");
        DbgPrint("created vm status %X start %lx size %lx\n",
            status, (ULONG)p1, Size1);
    }
    status = NtQueryVirtualMemory (CurrentProcessHandle, oldp1,
                                    MemoryBasicInformation,
                                    &MemInfo, sizeof (MEMORY_BASIC_INFORMATION),
                                    NULL);

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 9 **************\n");
        DbgPrint("query vm status %X address %lx Base %lx size %lx\n",
             status,
             oldp1,
             MemInfo.BaseAddress,
             MemInfo.RegionSize);
        DbgPrint("     state %lx protect %lx type %lx\n",
             MemInfo.State,
             MemInfo.Protect,
             MemInfo.Type);
    }

    if ((MemInfo.RegionSize != 56*1024) || (MemInfo.BaseAddress != oldp1) ||
        (MemInfo.AllocationProtect != (PAGE_READWRITE | PAGE_GUARD)) ||
        (MemInfo.Protect != 0) ||
        (MemInfo.Type != MEM_PRIVATE) ||
        (MemInfo.State != MEM_RESERVE)) {

        DbgPrint("******** FAILED TEST 10 **************\n");
        DbgPrint("query vm status %X address %lx Base %lx size %lx\n",
             status,
             oldp1,
             MemInfo.BaseAddress,
             MemInfo.RegionSize);
        DbgPrint("     state %lx protect %lx alloc_protect %lx type %lx\n",
             MemInfo.State,
             MemInfo.Protect,
             MemInfo.AllocationProtect,
             MemInfo.Type);
    }

    status = NtQueryVirtualMemory (CurrentProcessHandle, p1,
                                    MemoryBasicInformation,
                                    &MemInfo, sizeof (MEMORY_BASIC_INFORMATION),
                                    NULL);

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 11 **************\n");
        DbgPrint("query vm status %X address %lx Base %lx size %lx\n",
             status,
             p1,
             MemInfo.BaseAddress,
             MemInfo.RegionSize);
        DbgPrint("     state %lx protect %lx type %lx\n",
             MemInfo.State,
             MemInfo.Protect,
             MemInfo.Type);
    }
    if ((MemInfo.RegionSize != Size2) || (MemInfo.BaseAddress != p1) ||
        (MemInfo.Protect != PAGE_EXECUTE_READWRITE) || (MemInfo.Type != MEM_PRIVATE) ||
        (MemInfo.State != MEM_COMMIT)
        || (MemInfo.AllocationBase != oldp1)) {

        DbgPrint("******** FAILED TEST 12 **************\n");
        DbgPrint("query vm status %X address %lx Base %lx size %lx\n",
             status,
             oldp1,
             MemInfo.BaseAddress,
             MemInfo.RegionSize);
        DbgPrint("     state %lx protect %lx type %lx\n",
             MemInfo.State,
             MemInfo.Protect,
             MemInfo.Type);
    }

    Size1 = Size2;

    status = NtProtectVirtualMemory (CurrentProcessHandle, (PVOID *)&p1,
                        &Size1, PAGE_READONLY | PAGE_NOCACHE, &OldProtect);

    if ((!NT_SUCCESS(status)) || (OldProtect != PAGE_EXECUTE_READWRITE)) {
        DbgPrint("******** FAILED TEST 13 **************\n");
        DbgPrint("protected VM status %X, base %lx, size %lx, old protect %lx\n",
                    status, p1, Size1, OldProtect);
    }
    status = NtQueryVirtualMemory (CurrentProcessHandle, p1,
                                    MemoryBasicInformation,
                                    &MemInfo, sizeof (MEMORY_BASIC_INFORMATION),
                                    NULL);

    if ((!NT_SUCCESS(status)) ||
        MemInfo.Protect != (PAGE_NOCACHE | PAGE_READONLY)) {

        DbgPrint("******** FAILED TEST 14 **************\n");

        DbgPrint("query vm status %X address %lx Base %lx size %lx\n",
                 status,
                 p1,
                 MemInfo.BaseAddress,
                 MemInfo.RegionSize);
        DbgPrint("     state %lx protect %lx type %lx\n",
                 MemInfo.State,
                 MemInfo.Protect,
             MemInfo.Type);
    }
    i = *p1;

    status = NtProtectVirtualMemory (CurrentProcessHandle, (PVOID *)&p1,
                        &Size1, PAGE_NOACCESS | PAGE_NOCACHE, &OldProtect);

    if (status != STATUS_INVALID_PAGE_PROTECTION) {
        DbgPrint("******** FAILED TEST 15 **************\n");
        DbgPrint("protected VM status %X, base %lx, size %lx, old protect %lx\n",
                    status, p1, Size1, OldProtect, i);
    }
    status = NtProtectVirtualMemory (CurrentProcessHandle, (PVOID *)&p1,
                        &Size1, PAGE_READONLY, &OldProtect);

    if ((!NT_SUCCESS(status)) || (OldProtect != (PAGE_NOCACHE | PAGE_READONLY))) {
        DbgPrint("******** FAILED TEST 16 **************\n");
        DbgPrint("protected VM status %X, base %lx, size %lx, old protect %lx\n",
                    status, p1, Size1, OldProtect);
    }
    status = NtProtectVirtualMemory (CurrentProcessHandle, (PVOID *)&p1,
                        &Size1, PAGE_READWRITE, &OldProtect);

    if ((!NT_SUCCESS(status)) || (OldProtect != (PAGE_READONLY))) {
        DbgPrint("******** FAILED TEST 17 **************\n");
        DbgPrint("protected VM status %X, base %lx, size %lx, old protect %lx\n",
                    status, p1, Size1, OldProtect);
    }

    for (i = 1; i < 12; i++) {

        p2 = (PULONG)NULL;
        Size2 = i * 4096;

        status = NtAllocateVirtualMemory (CurrentProcessHandle, (PVOID *)&p2,
                        0, &Size2, MEM_COMMIT, PAGE_READWRITE);

        if (!NT_SUCCESS(status)) {
            DbgPrint("******** FAILED TEST 18 **************\n");
            DbgPrint("created vm status %X start %lx size %lx\n",
                status, (ULONG)p2, Size2);
        }
        if (i==4) {
            p3 = p2;
        }
        if (i == 8) {
            Size3 = 12000;
            status = NtFreeVirtualMemory (CurrentProcessHandle,(PVOID *)&p3, &Size3,
                                  MEM_RELEASE);

            if (!NT_SUCCESS(status)) {
                DbgPrint("******** FAILED TEST 19 **************\n");
                DbgPrint("free vm status %X start %lx size %lx\n",
                    status, (ULONG)p3, Size3);
            }
        }

    }

    p3 = p1 + 8 * 1024;

    status = NtQueryVirtualMemory (CurrentProcessHandle, p3,
                                    MemoryBasicInformation,
                                    &MemInfo, sizeof (MEMORY_BASIC_INFORMATION),
                                    NULL);

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 20 **************\n");

        DbgPrint("query vm status %X address %lx Base %lx size %lx\n",
             status,
             p3,
             MemInfo.BaseAddress,
             MemInfo.RegionSize);
        DbgPrint("     state %lx protect %lx type %lx\n",
             MemInfo.State,
             MemInfo.Protect,
             MemInfo.Type);
    }
    p3 = p1 - 8 * 1024;

    status = NtQueryVirtualMemory (CurrentProcessHandle, p3,
                                    MemoryBasicInformation,
                                    &MemInfo, sizeof (MEMORY_BASIC_INFORMATION),
                                    NULL);

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 21 **************\n");
        DbgPrint("query vm status %X address %lx Base %lx size %lx\n",
             status,
             p3,
             MemInfo.BaseAddress,
             MemInfo.RegionSize);
        DbgPrint("     state %lx protect %lx type %lx\n",
             MemInfo.State,
             MemInfo.Protect,
             MemInfo.Type);
    }

    Size3 = 16 * 4096;
    status = NtFreeVirtualMemory (CurrentProcessHandle, (PVOID *)&p3, &Size3,
                                  MEM_RELEASE);

    if (status != STATUS_UNABLE_TO_FREE_VM) {
        DbgPrint("******** FAILED TEST 22 **************\n");
        DbgPrint("free vm status %X start %lx size %lx\n",
            status, (ULONG)p3, Size3);
    }

    Size3 = 1 * 4096;
    status = NtFreeVirtualMemory (CurrentProcessHandle, (PVOID *)&p3, &Size3,
                                    MEM_RELEASE);

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 23 **************\n");
        DbgPrint("free vm status %X start %lx size %lx\n",
            status, (ULONG)p3, Size3);
    }

    p3 = (PULONG)NULL;
    Size3 = 300 * 4096;

    status = NtAllocateVirtualMemory (CurrentProcessHandle, (PVOID *)&p3,
                        0, &Size3, MEM_COMMIT, PAGE_READWRITE);

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 24 **************\n");
        DbgPrint("created vm status %X start %lx size %lx\n",
            status, (ULONG)p3, Size3);
    }

    p1 = p3;

    p2 = ((PULONG)((PUCHAR)p3 + Size3));
    p4 = p1;
    j = 0;

    while (p3 < p2) {
        j += 1;
        if (j % 8 == 0) {
            if (*p4 != (ULONG)p4) {
                DbgPrint("bad value in xcell %lx value is %lx\n",p4, *p4);

            }
            p4 += 1;
            *p4 = (ULONG)p4;
            p4 = p4 + 1026;
        }

        *p3 = (ULONG)p3;
        p3 += 1027;
    }

    DbgPrint("checking values\n");

    status = NtQueryVirtualMemory (CurrentProcessHandle, p3,
                                    MemoryBasicInformation,
                                    &MemInfo, sizeof (MEMORY_BASIC_INFORMATION),
                                    NULL);

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 25 **************\n");

        DbgPrint("query vm status %X address %lx Base %lx size %lx\n",
             status,
             p3,
             MemInfo.BaseAddress,
             MemInfo.RegionSize);
        DbgPrint("     state %lx protect %lx type %lx\n",
             MemInfo.State,
             MemInfo.Protect,
             MemInfo.Type);
    }

    p3 = p1;

    while (p3 < p2) {

        if (*p3 != (ULONG)p3) {
            DbgPrint("bad value in 1cell %lx value is %lx\n",p3, *p3);
        }
        p3 += 1027;

    }
    p3 = p1;

    while (p3 < p2) {

        if (*p3 != (ULONG)p3) {
            DbgPrint("bad value in 2cell %lx value is %lx\n",p3, *p3);
        }
        p3 += 1027;

    }
    p3 = p1;

    while (p3 < p2) {

        if (*p3 != (ULONG)p3) {
            DbgPrint("bad value in 3cell %lx value is %lx\n",p3, *p3);
        }
        p3 += 1027;

    }
    p3 = p1;

    while (p3 < p2) {

        if (*p3 != (ULONG)p3) {
            DbgPrint("bad value in 4cell %lx value is %lx\n",p3, *p3);
        }
        p3 += 1027;

    }
    p3 = p1;

    while (p3 < p2) {

        if (*p3 != (ULONG)p3) {
            DbgPrint("bad value in 5cell %lx value is %lx\n",p3, *p3);
        }
        p3 += 1027;

    }
    p3 = p1;

    while (p3 < p2) {

        if (*p3 != (ULONG)p3) {
            DbgPrint("bad value in cell %lx value is %lx\n",p3, *p3);
        }
        p3 += 1027;

    }

    //
    // Check physical frame mapping.
    //

    //
    // Check physical frame mapping.
    //

    RtlInitAnsiString (&Name3, "\\Device\\PhysicalMemory");

    status = RtlAnsiStringToUnicodeString(&Unicode,&Name3,TRUE);
    if (!NT_SUCCESS(status)) {
        printf("string conversion failed status %lx\n", status);
        ExitProcess (status);
    }
    InitializeObjectAttributes( &ObjectAttributes,
                                &Unicode,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL );

    status = NtOpenSection ( &Section1,
                             SECTION_MAP_READ | SECTION_MAP_WRITE,
                             &ObjectAttributes );

    RtlFreeUnicodeString(&Unicode);

    if (status != 0) {
        DbgPrint("******** FAILED TEST 26 **************\n");
        DbgPrint("open physical section failed %lx\n", status);
    }

    p1 = NULL;
    Offset.LowPart = 0x810ff033;
    Offset.HighPart = 0;
    ViewSize = 300*4096;

    status = NtMapViewOfSection (Section1,
                                 NtCurrentProcess(),
                                 (PVOID *)&p1,
                                 0,
                                 ViewSize,
                                 &Offset,
                                 &ViewSize,
                                 ViewUnmap,
                                 0,
                                 PAGE_READWRITE
                                 );
    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 27 **************\n");
        DbgPrint ("map physical section %X offset = %lx, base %lx\n",status,
                Offset.LowPart, p1);
    }



    p1 = NULL;
    Size1 = 8 * 1024 * 1024;

    alstatus = NtAllocateVirtualMemory (CurrentProcessHandle, (PVOID *)&p1,
                        0, &Size1, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);

    if (!NT_SUCCESS(alstatus)) {
        DbgPrint("failed first created vm status %X start %lx size %lx\n",
            alstatus, (ULONG)p1, Size1);
        DbgPrint("******** FAILED TEST 28 **************\n");
    }

    RtlZeroMemory (p1, Size1);

    Size1 -= 20000;
    (PUCHAR)p1 += 5000;
    status = NtFreeVirtualMemory (CurrentProcessHandle,
                                      (PVOID *)&p1,
                                      &Size1 ,
                                      MEM_DECOMMIT);

    if (!(NT_SUCCESS(status))) {
        DbgPrint(" free vm failed - status %lx\n",status);
        DbgPrint("******** FAILED TEST 29 **************\n");
        NtTerminateProcess(NtCurrentProcess(),status);
    }

    Size1 -= 20000;
    (PUCHAR)p1 += 5000;
    alstatus = NtAllocateVirtualMemory (CurrentProcessHandle, (PVOID *)&p1,
                        0, &Size1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);


    if (!NT_SUCCESS(alstatus)) {
        DbgPrint("failed first created vm status %X start %lx size %lx\n",
            alstatus, (ULONG)p1, Size1);
        DbgPrint("******** FAILED TEST 30 **************\n");
    }

    RtlZeroMemory (p1, Size1);


    Size1 = 28 * 4096;
    p1 = NULL;

    status = NtAllocateVirtualMemory (CurrentProcessHandle, (PVOID *)&p1,
                        0, &Size1, MEM_COMMIT, PAGE_READWRITE | PAGE_GUARD);

    if (!NT_SUCCESS(status)) {
        DbgPrint("failed first created vm status %X start %lx size %lx\n",
            status, (ULONG)p1, Size1);
        DbgPrint("******** FAILED TEST 31 **************\n");
    }

    try {

        //
        // attempt to write the guard page.
        //

        *p1 = 973;
        DbgPrint("************ FAILURE TEST 31.3 guard page exception did not occur\n");

    } except (EXCEPTION_EXECUTE_HANDLER) {
        status = GetExceptionCode();
        if (status != STATUS_GUARD_PAGE_VIOLATION) {
            DbgPrint("******** FAILED TEST 32 ******\n");
        }
    }

    p2 = NULL;
    Size2 = 200*1024*1024;  //200MB

    status = NtAllocateVirtualMemory (CurrentProcessHandle, (PVOID *)&p2,
                    0, &Size2, MEM_COMMIT, PAGE_READWRITE);

    if (NT_SUCCESS(status)) {
        status = NtFreeVirtualMemory (CurrentProcessHandle,
                                          (PVOID *)&p2,
                                          &Size2,
                                          MEM_RELEASE);
    } else {
        if ((status != STATUS_COMMITMENT_LIMIT) &&
             (status != STATUS_PAGEFILE_QUOTA_EXCEEDED)) {
            DbgPrint("******** FAILED TEST 33 ************** %lx\n",status);
        }
    }

    //
    // Create a giant section (2gb)
    //

    InitializeObjectAttributes( &Object1Attributes,
                                NULL,
                                0,
                                NULL,
                                NULL );

    SectionSize.LowPart = 0x7f000000;
    SectionSize.HighPart = 0;

    status = NtCreateSection (&GiantSection,
                              SECTION_MAP_READ | SECTION_MAP_WRITE,
                              &Object1Attributes,
                              &SectionSize,
                              PAGE_READWRITE,
                              SEC_RESERVE,
                              NULL);

    if (!NT_SUCCESS(status)) {
        DbgPrint("failed create big section status %X\n",
            status);
        DbgPrint("******** FAILED TEST 41 **************\n");
    }

    //
    // Attempt to map the section (this should fail).
    //

    p1 = NULL;
    ViewSize = 0;

    status = NtMapViewOfSection (GiantSection,
                                 CurrentProcessHandle,
                                 (PVOID *)&p1,
                                 0L,
                                 0,
                                 0,
                                 &ViewSize,
                                 ViewUnmap,
                                 0,
                                 PAGE_READWRITE );

    if (status != STATUS_NO_MEMORY) {
        DbgPrint("failed map big section status %X\n",
            status);
        DbgPrint("******** FAILED TEST 42 **************\n");
    }

#ifdef i386
    //
    // Test MEM_DOS_LIM support.
    //

    InitializeObjectAttributes( &Object1Attributes,
                                NULL,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL );
    SectionSize.LowPart = 1575757,
    SectionSize.HighPart = 0;
    status = NtCreateSection (&Section4,
                              SECTION_MAP_READ | SECTION_MAP_WRITE,
                              &Object1Attributes,
                              &SectionSize,
                              PAGE_READWRITE,
                              SEC_COMMIT,
                              NULL);

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 42 **************\n");
        DbgPrint("t1 create section  status %X section handle %lx\n", status,
        (ULONG)Section4);
    }

    p3 = (PVOID)0x9001000;
    ViewSize = 8000;

    status = NtMapViewOfSection (Section4,
                                 CurrentProcessHandle,
                                 (PVOID *)&p3,
                                 0L,
                                 0,
                                 0,
                                 &ViewSize,
                                 ViewUnmap,
                                 MEM_DOS_LIM,
                                 PAGE_READWRITE );

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 43 **************\n");
        DbgPrint("t1 map section status %X base %lx size %lx\n", status, (ULONG)p3,
            ViewSize);
        NtTerminateProcess(NtCurrentProcess(),STATUS_SUCCESS);
    }

    p2 = (PVOID)0x9003000;
    ViewSize = 8000;

    status = NtMapViewOfSection (Section4,
                                 CurrentProcessHandle,
                                 (PVOID *)&p2,
                                 0L,
                                 0,
                                 0,
                                 &ViewSize,
                                 ViewUnmap,
                                 MEM_DOS_LIM,
                                 PAGE_READWRITE );

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 44 **************\n");
        DbgPrint("t1 map section status %X base %lx size %lx\n", status, (ULONG)p3,
            ViewSize);
        NtTerminateProcess(NtCurrentProcess(),STATUS_SUCCESS);
    }

    status = NtQueryVirtualMemory (CurrentProcessHandle, p3,
                                    MemoryBasicInformation,
                                    &MemInfo, sizeof (MEMORY_BASIC_INFORMATION),
                                    NULL);

    if (!NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 44 **************\n");
        DbgPrint("FAILURE query vm status %X address %lx Base %lx size %lx\n",
             status,
             p1,
             MemInfo.BaseAddress,
             MemInfo.RegionSize);
        DbgPrint("     state %lx protect %lx type %lx\n",
             MemInfo.State,
             MemInfo.Protect,
             MemInfo.Type);
    }

    *p3 = 98;
    if (*p3 != *p2) {
        DbgPrint("******** FAILED TEST 45 **************\n");
    }


    Size2 = 8;

    p1 = (PVOID)((ULONG)p2 - 0x3000);
    status = NtAllocateVirtualMemory (CurrentProcessHandle, (PVOID *)&p1,
                        0, &Size2, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

    if (NT_SUCCESS(status)) {
        DbgPrint("******** FAILED TEST 46 **************\n");
        DbgPrint("created vm status %X start %lx size %lx\n",
            status, (ULONG)p1, Size1);
    }
#endif

    DbgPrint(" End of Memory Management Tests - CreateSection, MapView\n");


    DbgPrint("creating too much virtual address space\n");
    i = 0;

    do {
        p2 = NULL;
        Size2 = 8*1024*1024 + 9938;
        i += 1;

        status = NtAllocateVirtualMemory (CurrentProcessHandle, (PVOID *)&p2,
                        0, &Size2, MEM_RESERVE, PAGE_READWRITE);

    } while (NT_SUCCESS (status));

    if (status != STATUS_NO_MEMORY) {
        DbgPrint("******** FAILED TEST 46 **************\n");
    }

    DbgPrint("created vm done (successfully) status %X, number of allocs %ld\n",
            status, i);
    DbgPrint(" End of Memory Management Tests - AllocVm, FreeVm, ProtectVm, QueryVm\n");

{
    ULONG size, Size;
    PVOID BaseAddress;
    NTSTATUS Status;

    Size = 50*1024;
    size = Size - 1;
    BaseAddress = (PVOID)1;

    // we pass an address of 1, so mm will round it down to 0.  if we
    // passed 0, it looks like a not present argument

    // N.B.  We have to make two separate calls to allocatevm, because
    //       we want a specific virtual address.  If we don't first reserve
    //       the address, the mm fails the commit call.

    Status = NtAllocateVirtualMemory( NtCurrentProcess(),
                                      &BaseAddress,
                                      0L,
                                      &size,
                                      MEM_RESERVE,
                                      PAGE_READWRITE );

    if (!NT_SUCCESS(Status)) {
        DbgPrint("NtReserveVirtualMemory failed !!!! Status = %lx\n",
          Status);
    }

    size = Size - 1;
    BaseAddress = (PVOID)1;
    Status = NtAllocateVirtualMemory( NtCurrentProcess(),
                                      &BaseAddress,
                                      0L,
                                      &size,
                                      MEM_COMMIT,
                                      PAGE_READWRITE );

    if (!NT_SUCCESS(Status)) {
        DbgPrint("NtCommitVirtualMemory failed !!!! Status = %lx\n",
          Status);
    }
}

    ExitProcess (0);
}
Пример #13
0
NTSTATUS
SetupCopyFile(
    PWCHAR SourceFileName,
    PWCHAR DestinationFileName)
{
    OBJECT_ATTRIBUTES ObjectAttributes;
    HANDLE FileHandleSource;
    HANDLE FileHandleDest;
    static IO_STATUS_BLOCK IoStatusBlock;
    FILE_STANDARD_INFORMATION FileStandard;
    FILE_BASIC_INFORMATION FileBasic;
    ULONG RegionSize;
    UNICODE_STRING FileName;
    NTSTATUS Status;
    PVOID SourceFileMap = 0;
    HANDLE SourceFileSection;
    SIZE_T SourceSectionSize = 0;
    LARGE_INTEGER ByteOffset;

#ifdef __REACTOS__
    RtlInitUnicodeString(&FileName,
                         SourceFileName);

    InitializeObjectAttributes(&ObjectAttributes,
                               &FileName,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);

    Status = NtOpenFile(&FileHandleSource,
                        GENERIC_READ,
                        &ObjectAttributes,
                        &IoStatusBlock,
                        FILE_SHARE_READ,
                        FILE_SEQUENTIAL_ONLY);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtOpenFile failed: %x, %wZ\n", Status, &FileName);
        goto done;
    }
#else
    FileHandleSource = CreateFileW(SourceFileName,
                                   GENERIC_READ,
                                   FILE_SHARE_READ,
                                   NULL,
                                   OPEN_EXISTING,
                                   0,
                                   NULL);
    if (FileHandleSource == INVALID_HANDLE_VALUE)
    {
        Status = STATUS_UNSUCCESSFUL;
        goto done;
    }
#endif

    Status = NtQueryInformationFile(FileHandleSource,
                                    &IoStatusBlock,
                                    &FileStandard,
                                    sizeof(FILE_STANDARD_INFORMATION),
                                    FileStandardInformation);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtQueryInformationFile failed: %x\n", Status);
        goto closesrc;
    }

    Status = NtQueryInformationFile(FileHandleSource,
                                    &IoStatusBlock,&FileBasic,
                                    sizeof(FILE_BASIC_INFORMATION),
                                    FileBasicInformation);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtQueryInformationFile failed: %x\n", Status);
        goto closesrc;
    }

    Status = NtCreateSection(&SourceFileSection,
                             SECTION_MAP_READ,
                             NULL,
                             NULL,
                             PAGE_READONLY,
                             SEC_COMMIT,
                             FileHandleSource);
    if (!NT_SUCCESS(Status))
    {
      DPRINT1("NtCreateSection failed: %x, %S\n", Status, SourceFileName);
      goto closesrc;
    }

    Status = NtMapViewOfSection(SourceFileSection,
                                NtCurrentProcess(),
                                &SourceFileMap,
                                0,
                                0,
                                NULL,
                                &SourceSectionSize,
                                ViewUnmap,
                                0,
                                PAGE_READONLY );
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtMapViewOfSection failed: %x, %S\n", Status, SourceFileName);
        goto closesrcsec;
    }

    RtlInitUnicodeString(&FileName,
                         DestinationFileName);

    InitializeObjectAttributes(&ObjectAttributes,
                               &FileName,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);

    Status = NtCreateFile(&FileHandleDest,
                          GENERIC_WRITE | SYNCHRONIZE,
                          &ObjectAttributes,
                          &IoStatusBlock,
                          NULL,
                          FILE_ATTRIBUTE_NORMAL,
                          0,
                          FILE_OVERWRITE_IF,
                          FILE_NO_INTERMEDIATE_BUFFERING |
                          FILE_SEQUENTIAL_ONLY |
                          FILE_SYNCHRONOUS_IO_NONALERT,
                          NULL,
                          0);
    if (!NT_SUCCESS(Status))
    {
        /* Open may have failed because the file to overwrite
         * is in readonly mode
         */
        if (Status == STATUS_ACCESS_DENIED)
        {
            FILE_BASIC_INFORMATION FileBasicInfo;

            /* Reattempt to open it with limited access */
            Status = NtCreateFile(&FileHandleDest,
                                  FILE_WRITE_ATTRIBUTES | SYNCHRONIZE,
                                  &ObjectAttributes,
                                  &IoStatusBlock,
                                  NULL,
                                  FILE_ATTRIBUTE_NORMAL,
                                  0,
                                  FILE_OPEN,
                                  FILE_NO_INTERMEDIATE_BUFFERING |
                                  FILE_SEQUENTIAL_ONLY |
                                  FILE_SYNCHRONOUS_IO_NONALERT,
                                  NULL,
                                  0);
            /* Fail for real if we cannot open it that way */
            if (!NT_SUCCESS(Status))
            {
                DPRINT1("NtCreateFile failed: %x, %wZ\n", Status, &FileName);
                goto unmapsrcsec;
            }

            /* Zero our basic info, just to set attributes */
            RtlZeroMemory(&FileBasicInfo, sizeof(FileBasicInfo));
            /* Reset attributes to normal, no read-only */
            FileBasicInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
            /* We basically don't care about whether it succeed:
             * if it didn't, later open will fail
             */
            NtSetInformationFile(FileHandleDest, &IoStatusBlock, &FileBasicInfo,
                                 sizeof(FileBasicInfo), FileBasicInformation);

            /* Close file */
            NtClose(FileHandleDest);

            /* And re-attempt overwrite */
            Status = NtCreateFile(&FileHandleDest,
                                  GENERIC_WRITE | SYNCHRONIZE,
                                  &ObjectAttributes,
                                  &IoStatusBlock,
                                  NULL,
                                  FILE_ATTRIBUTE_NORMAL,
                                  0,
                                  FILE_OVERWRITE_IF,
                                  FILE_NO_INTERMEDIATE_BUFFERING |
                                  FILE_SEQUENTIAL_ONLY |
                                  FILE_SYNCHRONOUS_IO_NONALERT,
                                  NULL,
                                  0);
        }

        /* We failed */
        if (!NT_SUCCESS(Status))
        {
            DPRINT1("NtCreateFile failed: %x, %wZ\n", Status, &FileName);
            goto unmapsrcsec;
        }
    }

    RegionSize = (ULONG)PAGE_ROUND_UP(FileStandard.EndOfFile.u.LowPart);
    IoStatusBlock.Status = 0;
    ByteOffset.QuadPart = 0ULL;
    Status = NtWriteFile(FileHandleDest,
                         NULL,
                         NULL,
                         NULL,
                         &IoStatusBlock,
                         SourceFileMap,
                         RegionSize,
                         &ByteOffset,
                         NULL);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtWriteFile failed: %x:%x, iosb: %p src: %p, size: %x\n", Status, IoStatusBlock.Status, &IoStatusBlock, SourceFileMap, RegionSize);
        goto closedest;
    }

    /* Copy file date/time from source file */
    Status = NtSetInformationFile(FileHandleDest,
                                  &IoStatusBlock,
                                  &FileBasic,
                                  sizeof(FILE_BASIC_INFORMATION),
                                  FileBasicInformation);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtSetInformationFile failed: %x\n", Status);
        goto closedest;
    }

    /* shorten the file back to it's real size after completing the write */
    Status = NtSetInformationFile(FileHandleDest,
                                  &IoStatusBlock,
                                  &FileStandard.EndOfFile,
                                  sizeof(FILE_END_OF_FILE_INFORMATION),
                                  FileEndOfFileInformation);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtSetInformationFile failed: %x\n", Status);
    }

closedest:
    NtClose(FileHandleDest);

unmapsrcsec:
    NtUnmapViewOfSection(NtCurrentProcess(), SourceFileMap);

closesrcsec:
    NtClose(SourceFileSection);

closesrc:
    NtClose(FileHandleSource);

done:
    return Status;
}
Пример #14
0
void
Test_ImageSection(void)
{
    UNICODE_STRING FileName;
    NTSTATUS Status;
    OBJECT_ATTRIBUTES FileObjectAttributes;
    IO_STATUS_BLOCK IoStatusBlock;
    HANDLE FileHandle, DataSectionHandle, ImageSectionHandle;
    PVOID DataBase, ImageBase;
    SIZE_T ViewSize;

    if (!RtlDosPathNameToNtPathName_U(L"testdata\\test.dll",
                                      &FileName,
                                      NULL,
                                      NULL))
    {
        ok(0, "RtlDosPathNameToNtPathName_U failed\n");
        return;
    }

    InitializeObjectAttributes(&FileObjectAttributes,
                               &FileName,
                               0,
                               NULL,
                               NULL);

    Status = NtOpenFile(&FileHandle,
                        GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE,
                        &FileObjectAttributes,
                        &IoStatusBlock,
                        FILE_SHARE_READ,
                        FILE_SYNCHRONOUS_IO_NONALERT);
    ok(Status == STATUS_SUCCESS, "NtOpenFile failed, Status 0x%lx\n", Status);

    /* Create a data section with write access */
    Status = NtCreateSection(&DataSectionHandle,
                             SECTION_ALL_ACCESS, // DesiredAccess
                             NULL, // ObjectAttributes
                             NULL, // MaximumSize
                             PAGE_READWRITE, // SectionPageProtection
                             SEC_COMMIT, // AllocationAttributes
                             FileHandle);
    ok(Status == STATUS_SUCCESS, "NtCreateSection failed, Status 0x%lx\n", Status);

    /* Map the data section */
    DataBase = NULL;
    ViewSize = 0;
    Status = NtMapViewOfSection(DataSectionHandle,
                                NtCurrentProcess(),
                                &DataBase,
                                0,
                                0,
                                NULL,
                                &ViewSize,
                                ViewShare,
                                0,
                                PAGE_READWRITE);
    ok(Status == STATUS_SUCCESS, "NtMapViewOfSection failed, Status 0x%lx\n", Status);

    /* Check the original data */
    ok(*(ULONG*)DataBase == 0x00905a4d, "Header not ok\n");

    /* Modify the PE header (but do not flush!) */
    *(ULONG*)DataBase = 0xdeadbabe;
    ok(*(ULONG*)DataBase == 0xdeadbabe, "Header not ok\n");

    /* Modify data in the .data section (but do not flush!) */
    ok(*(ULONG*)((PUCHAR)DataBase + 0x800) == 0x12345678,
       "Data in .data section invalid: 0x%lx!\n", *(ULONG*)((PUCHAR)DataBase + 0x800));
    *(ULONG*)((PUCHAR)DataBase + 0x800) = 0x87654321;

    /* Now try to create an image section (should fail) */
    Status = NtCreateSection(&ImageSectionHandle,
                             SECTION_ALL_ACCESS, // DesiredAccess
                             NULL, // ObjectAttributes
                             NULL, // MaximumSize
                             PAGE_READWRITE, // SectionPageProtection
                             SEC_IMAGE, // AllocationAttributes
                             FileHandle);
    ok(Status == STATUS_INVALID_IMAGE_NOT_MZ, "NtCreateSection failed, Status 0x%lx\n", Status);

    /* Restore the original header */
    *(ULONG*)DataBase = 0x00905a4d;

    /* Modify data in the .data section (but do not flush!) */
    ok_hex(*(ULONG*)((PUCHAR)DataBase + 0x800), 0x87654321);
    *(ULONG*)((PUCHAR)DataBase + 0x800) = 0xdeadbabe;

    /* Try to create an image section again */
    Status = NtCreateSection(&ImageSectionHandle,
                             SECTION_ALL_ACCESS, // DesiredAccess
                             NULL, // ObjectAttributes
                             NULL, // MaximumSize
                             PAGE_READWRITE, // SectionPageProtection
                             SEC_IMAGE, // AllocationAttributes
                             FileHandle);
    ok(Status == STATUS_SUCCESS, "NtCreateSection failed, Status 0x%lx\n", Status);

    /* Map the image section */
    ImageBase = NULL;
    ViewSize = 0;
    Status = NtMapViewOfSection(ImageSectionHandle,
                                NtCurrentProcess(),
                                &ImageBase,
                                0,
                                0,
                                NULL,
                                &ViewSize,
                                ViewShare,
                                0,
                                PAGE_READONLY);
#ifdef _M_IX86
    ok(Status == STATUS_SUCCESS, "NtMapViewOfSection failed, Status 0x%lx\n", Status);
#else
    ok(Status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH, "NtMapViewOfSection failed, Status 0x%lx\n", Status);
#endif

    /* Check the header */
    ok(*(ULONG*)DataBase == 0x00905a4d, "Header not ok\n");
    ok(*(ULONG*)ImageBase == 0x00905a4d, "Header not ok\n");

    /* Check the data section. Either of these can be present! */
    ok((*(ULONG*)((PUCHAR)ImageBase + 0x80000) == 0x87654321) ||
       (*(ULONG*)((PUCHAR)ImageBase + 0x80000) == 0x12345678),
       "Wrong value in data section: 0x%lx!\n", *(ULONG*)((PUCHAR)ImageBase + 0x80000));

    /* Now modify the data again */
    *(ULONG*)DataBase = 0xdeadbabe;
    *(ULONG*)((PUCHAR)DataBase + 0x800) = 0xf00dada;

    /* Check the data */
    ok(*(ULONG*)DataBase == 0xdeadbabe, "Header not ok\n");
    ok(*(ULONG*)ImageBase == 0x00905a4d, "Data should not be synced!\n");
    ok((*(ULONG*)((PUCHAR)ImageBase + 0x80000) == 0x87654321) ||
       (*(ULONG*)((PUCHAR)ImageBase + 0x80000) == 0x12345678),
       "Wrong value in data section: 0x%lx!\n", *(ULONG*)((PUCHAR)ImageBase + 0x80000));

    /* Flush the view */
    ViewSize = 0x1000;
    Status = NtFlushVirtualMemory(NtCurrentProcess(),
                                  &DataBase,
                                  &ViewSize,
                                  &IoStatusBlock);
    ok(Status == STATUS_SUCCESS, "NtFlushVirtualMemory failed, Status 0x%lx\n", Status);

    /* Check the data again */
    ok(*(ULONG*)ImageBase == 0x00905a4d, "Data should not be synced!\n");
    ok((*(ULONG*)((PUCHAR)ImageBase + 0x80000) == 0x87654321) ||
       (*(ULONG*)((PUCHAR)ImageBase + 0x80000) == 0x12345678),
       "Wrong value in data section: 0x%lx!\n", *(ULONG*)((PUCHAR)ImageBase + 0x80000));

    /* Restore the original header */
    *(ULONG*)DataBase = 0x00905a4d;
    ok(*(ULONG*)DataBase == 0x00905a4d, "Header not ok\n");

    /* Close the image mapping */
    NtUnmapViewOfSection(NtCurrentProcess(), ImageBase);
    NtClose(ImageSectionHandle);

    /* Create an image section again */
    Status = NtCreateSection(&ImageSectionHandle,
                             SECTION_ALL_ACCESS, // DesiredAccess
                             NULL, // ObjectAttributes
                             NULL, // MaximumSize
                             PAGE_READWRITE, // SectionPageProtection
                             SEC_IMAGE, // AllocationAttributes
                             FileHandle);
    ok(Status == STATUS_SUCCESS, "NtCreateSection failed, Status 0x%lx\n", Status);

    /* Map the image section again */
    ImageBase = NULL;
    ViewSize = 0;
    Status = NtMapViewOfSection(ImageSectionHandle,
                                NtCurrentProcess(),
                                &ImageBase,
                                0,
                                0,
                                NULL,
                                &ViewSize,
                                ViewShare,
                                0,
                                PAGE_READONLY);
#ifdef _M_IX86
    ok(Status == STATUS_SUCCESS, "NtMapViewOfSection failed, Status 0x%lx\n", Status);
#else
    ok(Status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH, "NtMapViewOfSection failed, Status 0x%lx\n", Status);
#endif

    /* Check the .data section again */
    ok(*(ULONG*)((PUCHAR)ImageBase + 0x80000) == 0xf00dada,
       "Data should be synced: 0x%lx!\n", *(ULONG*)((PUCHAR)ImageBase + 0x80000));

    /* Restore the original data */
    *(ULONG*)((PUCHAR)DataBase + 0x800) = 0x12345678;

    /* Close the data mapping */
    NtUnmapViewOfSection(NtCurrentProcess(), DataBase);

    NtClose(DataSectionHandle);

    /* Try to allocate memory inside the image mapping */
    DataBase = (PUCHAR)ImageBase + 0x20000;
    ViewSize = 0x1000;
    Status = NtAllocateVirtualMemory(NtCurrentProcess(), &DataBase, 0, &ViewSize, MEM_RESERVE, PAGE_NOACCESS);
    ok(Status ==  STATUS_CONFLICTING_ADDRESSES, "Wrong Status: 0x%lx\n", Status);

    /* Cleanup */
    NtClose(FileHandle);
    NtClose(ImageSectionHandle);
    NtUnmapViewOfSection(NtCurrentProcess(), ImageBase);
}
Пример #15
0
void
Test_PageFileSection(void)
{
    NTSTATUS Status;
    HANDLE SectionHandle;
    LARGE_INTEGER MaximumSize, SectionOffset;
    PVOID BaseAddress;
    SIZE_T ViewSize;

    /* Create a page file backed section */
    MaximumSize.QuadPart = 0x20000;
    Status = NtCreateSection(&SectionHandle,
                             SECTION_ALL_ACCESS,
                             NULL,
                             &MaximumSize,
                             PAGE_READWRITE,
                             SEC_COMMIT,
                             NULL);
    ok(NT_SUCCESS(Status), "NtCreateSection failed with Status %lx\n", Status);
    if (!NT_SUCCESS(Status))
        return;

    /* Try to map a page at an address that is not 64k aligned */
    BaseAddress = (PVOID)0x30001000;
    SectionOffset.QuadPart = 0;
    ViewSize = 0x1000;
    Status = NtMapViewOfSection(SectionHandle,
                                NtCurrentProcess(),
                                &BaseAddress,
                                0,
                                0,
                                &SectionOffset,
                                &ViewSize,
                                ViewShare,
                                0,
                                PAGE_READWRITE);
    ok(Status == STATUS_MAPPED_ALIGNMENT,
       "NtMapViewOfSection returned wrong Status %lx\n", Status);

    /* Try to map a page with execute rights */
    BaseAddress = (PVOID)0x30000000;
    SectionOffset.QuadPart = 0;
    ViewSize = 0x1000;
    Status = NtMapViewOfSection(SectionHandle,
                                NtCurrentProcess(),
                                &BaseAddress,
                                0,
                                0,
                                &SectionOffset,
                                &ViewSize,
                                ViewShare,
                                0,
                                PAGE_EXECUTE_READWRITE);
    ok(Status == STATUS_SECTION_PROTECTION,
       "NtMapViewOfSection returned wrong Status %lx\n", Status);

    /* Map 2 pages, not comitting them */
    BaseAddress = (PVOID)0x30000000;
    SectionOffset.QuadPart = 0;
    ViewSize = 0x2000;
    Status = NtMapViewOfSection(SectionHandle,
                                NtCurrentProcess(),
                                &BaseAddress,
                                0,
                                0,
                                &SectionOffset,
                                &ViewSize,
                                ViewShare,
                                0,
                                PAGE_READWRITE);
    ok(NT_SUCCESS(Status), "NtMapViewOfSection failed with Status %lx\n", Status);
    if (!NT_SUCCESS(Status))
        return;

    /* Commit a page in the section */
    BaseAddress = (PVOID)0x30000000;
    ViewSize = 0x1000;
    Status = NtAllocateVirtualMemory(NtCurrentProcess(),
                                     &BaseAddress,
                                     0,
                                     &ViewSize,
                                     MEM_COMMIT,
                                     PAGE_READWRITE);
    ok(NT_SUCCESS(Status), "NtAllocateVirtualMemory failed with Status %lx\n", Status);
    Status = NtFreeVirtualMemory(NtCurrentProcess(),
                                 &BaseAddress,
                                 &ViewSize,
                                 MEM_DECOMMIT);
    ok(Status == STATUS_UNABLE_TO_DELETE_SECTION, "NtFreeVirtualMemory returned wrong Status %lx\n", Status);
    /* Try to commit a range larger than the section */
    BaseAddress = (PVOID)0x30000000;
    ViewSize = 0x3000;
    Status = NtAllocateVirtualMemory(NtCurrentProcess(),
                                     &BaseAddress,
                                     0,
                                     &ViewSize,
                                     MEM_COMMIT,
                                     PAGE_READWRITE);
    ok(Status == STATUS_CONFLICTING_ADDRESSES,
       "NtAllocateVirtualMemory failed with wrong Status %lx\n", Status);

    /* Try to commit a page after the section */
    BaseAddress = (PVOID)0x30002000;
    ViewSize = 0x1000;
    Status = NtAllocateVirtualMemory(NtCurrentProcess(),
                                     &BaseAddress,
                                     0,
                                     &ViewSize,
                                     MEM_COMMIT,
                                     PAGE_READWRITE);
    ok(!NT_SUCCESS(Status), "NtAllocateVirtualMemory Should fail\n");

    /* Try to allocate a page after the section */
    BaseAddress = (PVOID)0x30002000;
    ViewSize = 0x1000;
    Status = NtAllocateVirtualMemory(NtCurrentProcess(),
                                     &BaseAddress,
                                     0,
                                     &ViewSize,
                                     MEM_RESERVE | MEM_COMMIT,
                                     PAGE_READWRITE);
    ok(!NT_SUCCESS(Status), "NtAllocateVirtualMemory should fail\n");

    /* Need to go to next 64k boundary */
    BaseAddress = (PVOID)0x30010000;
    ViewSize = 0x1000;
    Status = NtAllocateVirtualMemory(NtCurrentProcess(),
                                     &BaseAddress,
                                     0,
                                     &ViewSize,
                                     MEM_RESERVE | MEM_COMMIT,
                                     PAGE_READWRITE);
    ok(NT_SUCCESS(Status), "NtAllocateVirtualMemory failed with Status %lx\n", Status);
    if (!NT_SUCCESS(Status))
        return;

    /* Free the allocation */
    BaseAddress = (PVOID)0x30010000;
    ViewSize = 0x1000;
    Status = NtFreeVirtualMemory(NtCurrentProcess(),
                                 &BaseAddress,
                                 &ViewSize,
                                 MEM_RELEASE);
    ok(NT_SUCCESS(Status), "NtFreeVirtualMemory failed with Status %lx\n", Status);

    /* Free the section mapping */
    BaseAddress = (PVOID)0x30000000;
    ViewSize = 0x1000;
    Status = NtFreeVirtualMemory(NtCurrentProcess(),
                                 &BaseAddress,
                                 &ViewSize,
                                 MEM_RELEASE);
    ok(Status == STATUS_UNABLE_TO_DELETE_SECTION,
       "NtFreeVirtualMemory failed with wrong Status %lx\n", Status);

    /* Commit a page in the section */
    BaseAddress = (PVOID)0x30001000;
    ViewSize = 0x1000;
    Status = NtAllocateVirtualMemory(NtCurrentProcess(),
                                     &BaseAddress,
                                     0,
                                     &ViewSize,
                                     MEM_COMMIT,
                                     PAGE_READWRITE);
    ok(NT_SUCCESS(Status), "NtAllocateVirtualMemory failed with Status %lx\n", Status);

    /* Try to decommit the page */
    BaseAddress = (PVOID)0x30001000;
    ViewSize = 0x1000;
    Status = NtFreeVirtualMemory(NtCurrentProcess(),
                                 &BaseAddress,
                                 &ViewSize,
                                 MEM_DECOMMIT);
    ok(Status == STATUS_UNABLE_TO_DELETE_SECTION,
       "NtFreeVirtualMemory failed with wrong Status %lx\n", Status);

    BaseAddress = UlongToPtr(0x40000000);
    SectionOffset.QuadPart = 0;
    ViewSize = 0x1000;
    Status = NtMapViewOfSection(SectionHandle,
                                NtCurrentProcess(),
                                &BaseAddress,
                                0,
                                0,
                                &SectionOffset,
                                &ViewSize,
                                ViewShare,
                                0,
                                PAGE_READWRITE);
    ok(NT_SUCCESS(Status), "NtMapViewOfSection failed with Status %lx\n", Status);
    if (!NT_SUCCESS(Status))
        return;

    ok(BaseAddress == UlongToPtr(0x40000000), "Invalid BaseAddress: %p", BaseAddress);

    BaseAddress = (PVOID)0x40080000;
    SectionOffset.QuadPart = 0x10000;
    ViewSize = 0x1000;
    Status = NtMapViewOfSection(SectionHandle,
                                NtCurrentProcess(),
                                &BaseAddress,
                                0,
                                0,
                                &SectionOffset,
                                &ViewSize,
                                ViewShare,
                                0,
                                PAGE_READWRITE);
    ok(NT_SUCCESS(Status), "NtMapViewOfSection failed with Status %lx\n", Status);
    if (!NT_SUCCESS(Status))
        return;

    ok(BaseAddress == (PVOID)0x40080000, "Invalid BaseAddress: %p", BaseAddress);

    /* Commit a page in the section */
    BaseAddress = (PVOID)0x40000000;
    Status = NtAllocateVirtualMemory(NtCurrentProcess(),
                                     &BaseAddress,
                                     0,
                                     &ViewSize,
                                     MEM_COMMIT,
                                     PAGE_READWRITE);
    ok(NT_SUCCESS(Status), "NtAllocateVirtualMemory failed with Status %lx\n", Status);
    if (!NT_SUCCESS(Status))
        return;

}
Пример #16
0
/*
 * FUNCTION: Opens a cabinet file
 * RETURNS:
 *     Status of operation
 */
ULONG
CabinetOpen(VOID)
{
    PUCHAR Buffer;
    UNICODE_STRING ustring;
    ANSI_STRING astring;

    if (!FileOpen)
    {
        OBJECT_ATTRIBUTES ObjectAttributes;
        IO_STATUS_BLOCK IoStatusBlock;
        UNICODE_STRING FileName;
        NTSTATUS NtStatus;
        ULONG Size;

        RtlInitUnicodeString(&FileName, CabinetName);

        InitializeObjectAttributes(&ObjectAttributes,
                                   &FileName,
                                   OBJ_CASE_INSENSITIVE,
                                   NULL, NULL);

        NtStatus = NtOpenFile(&FileHandle,
                              GENERIC_READ | SYNCHRONIZE,
                              &ObjectAttributes,
                              &IoStatusBlock,
                              FILE_SHARE_READ,
                              FILE_SYNCHRONOUS_IO_NONALERT);

        if (!NT_SUCCESS(NtStatus))
        {
            DPRINT("Cannot open file (%S) (%x)\n", CabinetName, NtStatus);
            return CAB_STATUS_CANNOT_OPEN;
        }

        FileOpen = TRUE;

        NtStatus = NtCreateSection(&FileSectionHandle,
                                   SECTION_ALL_ACCESS,
                                   0, 0,
                                   PAGE_READONLY,
                                   SEC_COMMIT,
                                   FileHandle);

        if (!NT_SUCCESS(NtStatus))
        {
            DPRINT("NtCreateSection failed: %x\n", NtStatus);
            return CAB_STATUS_NOMEMORY;
        }

        FileBuffer = 0;
        FileSize = 0;

        NtStatus = NtMapViewOfSection(FileSectionHandle,
                                      NtCurrentProcess(),
                                      (PVOID *)&FileBuffer,
                                      0, 0, 0,
                                      &FileSize,
                                      ViewUnmap,
                                      0,
                                      PAGE_READONLY);

        if (!NT_SUCCESS(NtStatus))
        {
            DPRINT("NtMapViewOfSection failed: %x\n", NtStatus);
            return CAB_STATUS_NOMEMORY;
        }

        DPRINT("Cabinet file %S opened and mapped to %x\n", CabinetName, FileBuffer);
        PCABHeader = (PCFHEADER) FileBuffer;

        /* Check header */
        if (FileSize <= sizeof(CFHEADER) ||
            PCABHeader->Signature != CAB_SIGNATURE ||
            PCABHeader->Version != CAB_VERSION ||
            PCABHeader->FolderCount == 0 ||
            PCABHeader->FileCount == 0 ||
            PCABHeader->FileTableOffset < sizeof(CFHEADER))
        {
            CloseCabinet();
            DPRINT("File has invalid header\n");
            return CAB_STATUS_INVALID_CAB;
        }

        Size = 0;
        Buffer = (PUCHAR)(PCABHeader + 1);

        /* Read/skip any reserved bytes */
        if (PCABHeader->Flags & CAB_FLAG_RESERVE)
        {
            CabinetReserved = *(PUSHORT)Buffer;
            Buffer += 2;
            FolderReserved = *Buffer;
            Buffer++;
            DataReserved = *Buffer;
            Buffer++;

            if (CabinetReserved > 0)
            {
                CabinetReservedArea = Buffer;
                Buffer += CabinetReserved;
            }
        }

        if (PCABHeader->Flags & CAB_FLAG_HASPREV)
        {
            /* The previous cabinet file is in
               the same directory as the current */
            wcscpy(CabinetPrev, CabinetName);
            RemoveFileName(CabinetPrev);
            CabinetNormalizePath(CabinetPrev, 256);
            RtlInitAnsiString(&astring, (LPSTR)Buffer);
            ustring.Length = wcslen(CabinetPrev);
            ustring.Buffer = CabinetPrev + ustring.Length;
            ustring.MaximumLength = sizeof(CabinetPrev) - ustring.Length;
            RtlAnsiStringToUnicodeString(&ustring, &astring, FALSE);
            Buffer += astring.Length + 1;

            /* Read label of prev disk */
            RtlInitAnsiString(&astring, (LPSTR)Buffer);
            ustring.Length = 0;
            ustring.Buffer = DiskPrev;
            ustring.MaximumLength = sizeof(DiskPrev);
            RtlAnsiStringToUnicodeString(&ustring, &astring, FALSE);
            Buffer += astring.Length + 1;
        }
        else
        {
            wcscpy(CabinetPrev, L"");
            wcscpy(DiskPrev, L"");
        }

        if (PCABHeader->Flags & CAB_FLAG_HASNEXT)
        {
            /* The next cabinet file is in
               the same directory as the previous */
            wcscpy(CabinetNext, CabinetName);
            RemoveFileName(CabinetNext);
            CabinetNormalizePath(CabinetNext, 256);
            RtlInitAnsiString(&astring, (LPSTR)Buffer);
            ustring.Length = wcslen(CabinetNext);
            ustring.Buffer = CabinetNext + ustring.Length;
            ustring.MaximumLength = sizeof(CabinetNext) - ustring.Length;
            RtlAnsiStringToUnicodeString(&ustring, &astring, FALSE);
            Buffer += astring.Length + 1;

            /* Read label of next disk */
            RtlInitAnsiString(&astring, (LPSTR)Buffer);
            ustring.Length = 0;
            ustring.Buffer = DiskNext;
            ustring.MaximumLength = sizeof(DiskNext);
            RtlAnsiStringToUnicodeString(&ustring, &astring, FALSE);
            Buffer += astring.Length + 1;
        }
        else
        {
            wcscpy(CabinetNext, L"");
            wcscpy(DiskNext, L"");
        }
        CabinetFolders = (PCFFOLDER)Buffer;
    }

    DPRINT("CabinetOpen returning SUCCESS\n");
    return CAB_STATUS_SUCCESS;
}
Пример #17
0
/*
 * FUNCTION: Extracts a file from the cabinet
 * ARGUMENTS:
 *     Search = Pointer to PCAB_SEARCH structure used to locate the file
 * RETURNS
 *     Status of operation
 */
ULONG
CabinetExtractFile(PCAB_SEARCH Search)
{
    ULONG Size;                 // remaining file bytes to decompress
    ULONG CurrentOffset;        // current uncompressed offset within the folder
    PUCHAR CurrentBuffer;       // current pointer to compressed data in the block
    LONG RemainingBlock;        // remaining comp data in the block
    HANDLE DestFile;
    HANDLE DestFileSection;
    PVOID DestFileBuffer;       // mapped view of dest file
    PVOID CurrentDestBuffer;    // pointer to the current position in the dest view
    PCFDATA CFData;             // current data block
    ULONG Status;
    FILETIME FileTime;
    WCHAR DestName[MAX_PATH];
    NTSTATUS NtStatus;
    UNICODE_STRING UnicodeString;
    ANSI_STRING AnsiString;
    IO_STATUS_BLOCK IoStatusBlock;
    OBJECT_ATTRIBUTES ObjectAttributes;
    FILE_BASIC_INFORMATION FileBasic;
    PCFFOLDER CurrentFolder;
    LARGE_INTEGER MaxDestFileSize;
    LONG InputLength, OutputLength;
    char Junk[512];

    if (wcscmp(Search->Cabinet, CabinetName) != 0)
    {
        /* the file is not in the current cabinet */
        DPRINT("File is not in this cabinet (%S != %S)\n",
               Search->Cabinet, CabinetName);
        return CAB_STATUS_NOFILE;
    }

    /* look up the folder that the file specifies */
    if (Search->File->FolderIndex == 0xFFFD ||
        Search->File->FolderIndex == 0xFFFF)
    {
        /* folder is continued from previous cabinet,
           that shouldn't happen here */
        return CAB_STATUS_NOFILE;
    }
    else if (Search->File->FolderIndex == 0xFFFE)
    {
        /* folder is the last in this cabinet and continues into next */
        CurrentFolder = &CabinetFolders[PCABHeader->FolderCount - 1];
    }
    else
    {
        /* folder is completely contained within this cabinet */
        CurrentFolder = &CabinetFolders[Search->File->FolderIndex];
    }

    switch (CurrentFolder->CompressionType & CAB_COMP_MASK)
    {
        case CAB_COMP_NONE:
            CabinetSelectCodec(CAB_CODEC_RAW);
            break;
        case CAB_COMP_MSZIP:
            CabinetSelectCodec(CAB_CODEC_MSZIP);
            break;
        default:
            return CAB_STATUS_UNSUPPCOMP;
    }

    DPRINT("Extracting file at uncompressed offset (0x%X) Size (%d bytes)\n",
           (UINT)Search->File->FileOffset, (UINT)Search->File->FileSize);

    RtlInitAnsiString(&AnsiString, Search->File->FileName);
    wcscpy(DestName, DestPath);
    UnicodeString.MaximumLength = sizeof(DestName) - wcslen(DestName) * sizeof(WCHAR);
    UnicodeString.Buffer = DestName + wcslen(DestName);
    UnicodeString.Length = 0;
    RtlAnsiStringToUnicodeString(&UnicodeString, &AnsiString, FALSE);

    /* Create destination file, fail if it already exists */
    RtlInitUnicodeString(&UnicodeString, DestName);

    InitializeObjectAttributes(&ObjectAttributes,
                               &UnicodeString,
                               OBJ_CASE_INSENSITIVE,
                               NULL, NULL);

    NtStatus = NtCreateFile(&DestFile,
                            GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE,
                            &ObjectAttributes,
                            &IoStatusBlock,
                            NULL,
                            FILE_ATTRIBUTE_NORMAL,
                            0,
                            FILE_CREATE,
                            FILE_SYNCHRONOUS_IO_NONALERT,
                            NULL, 0);

    if (!NT_SUCCESS(NtStatus))
    {
        DPRINT("NtCreateFile() failed (%S) (%x)\n", DestName, NtStatus);

        /* If file exists, ask to overwrite file */
        if (OverwriteHandler == NULL || OverwriteHandler(Search->File, DestName))
        {
            /* Create destination file, overwrite if it already exists */
            NtStatus = NtCreateFile(&DestFile,
                                    GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE,
                                    &ObjectAttributes,
                                    &IoStatusBlock,
                                    NULL,
                                    FILE_ATTRIBUTE_NORMAL,
                                    0,
                                    FILE_OVERWRITE,
                                    FILE_SYNCHRONOUS_IO_ALERT,
                                    NULL, 0);

            if (!NT_SUCCESS(NtStatus))
            {
                DPRINT("NtCreateFile() failed (%S) (%x)\n", DestName, NtStatus);
                return CAB_STATUS_CANNOT_CREATE;
            }
        }
        else
        {
            DPRINT("File (%S) exists\n", DestName);
            return CAB_STATUS_FILE_EXISTS;
        }
    }

    MaxDestFileSize.QuadPart = Search->File->FileSize;
    NtStatus = NtCreateSection(&DestFileSection,
                               SECTION_ALL_ACCESS,
                               0,
                               &MaxDestFileSize,
                               PAGE_READWRITE,
                               SEC_COMMIT,
                               DestFile);

    if (!NT_SUCCESS(NtStatus))
    {
        DPRINT("NtCreateSection failed: %x\n", NtStatus);
        Status = CAB_STATUS_NOMEMORY;
        goto CloseDestFile;
    }

    DestFileBuffer = 0;
    DestFileSize = 0;
    NtStatus = NtMapViewOfSection(DestFileSection,
                                  NtCurrentProcess(),
                                  &DestFileBuffer,
                                  0, 0, 0,
                                  &DestFileSize,
                                  ViewUnmap,
                                  0,
                                  PAGE_READWRITE);

    if (!NT_SUCCESS(NtStatus))
    {
        DPRINT("NtMapViewOfSection failed: %x\n", NtStatus);
        Status = CAB_STATUS_NOMEMORY;
        goto CloseDestFileSection;
    }

    CurrentDestBuffer = DestFileBuffer;
    if (!ConvertDosDateTimeToFileTime(Search->File->FileDate,
                                      Search->File->FileTime,
                                      &FileTime))
    {
        DPRINT("DosDateTimeToFileTime() failed\n");
        Status = CAB_STATUS_CANNOT_WRITE;
        goto UnmapDestFile;
    }

    NtStatus = NtQueryInformationFile(DestFile,
                                      &IoStatusBlock,
                                      &FileBasic,
                                      sizeof(FILE_BASIC_INFORMATION),
                                      FileBasicInformation);
    if (!NT_SUCCESS(NtStatus))
    {
        DPRINT("NtQueryInformationFile() failed (%x)\n", NtStatus);
    }
    else
    {
        memcpy(&FileBasic.LastAccessTime, &FileTime, sizeof(FILETIME));

        NtStatus = NtSetInformationFile(DestFile,
                                        &IoStatusBlock,
                                        &FileBasic,
                                        sizeof(FILE_BASIC_INFORMATION),
                                        FileBasicInformation);
        if (!NT_SUCCESS(NtStatus))
        {
            DPRINT("NtSetInformationFile() failed (%x)\n", NtStatus);
        }
    }

    SetAttributesOnFile(Search->File, DestFile);

    /* Call extract event handler */
    if (ExtractHandler != NULL)
    {
        ExtractHandler(Search->File, DestName);
    }

    /* find the starting block of the file
       start with the first data block of the folder */
    CFData = (PCFDATA)(CabinetFolders[Search->File->FolderIndex].DataOffset + FileBuffer);
    CurrentOffset = 0;
    while (CurrentOffset + CFData->UncompSize <= Search->File->FileOffset)
    {
        /* walk the data blocks until we reach
           the one containing the start of the file */
        CurrentOffset += CFData->UncompSize;
        CFData = (PCFDATA)((char *)(CFData + 1) + DataReserved + CFData->CompSize);
    }

    /* now decompress and discard any data in
       the block before the start of the file */

    /* start of comp data */
    CurrentBuffer = ((unsigned char *)(CFData + 1)) + DataReserved;
    RemainingBlock = CFData->CompSize;
    InputLength = RemainingBlock;

    while (CurrentOffset < Search->File->FileOffset)
    {
        /* compute remaining uncomp bytes to start
           of file, bounded by sizeof junk */
        OutputLength = Search->File->FileOffset - CurrentOffset;
        if (OutputLength > (LONG)sizeof(Junk))
            OutputLength = sizeof (Junk);

        /* negate to signal NOT end of block */
        OutputLength = -OutputLength;
        CodecUncompress(Junk, CurrentBuffer, &InputLength, &OutputLength);
        /* add the uncomp bytes extracted to current folder offset */
        CurrentOffset += OutputLength;
        /* add comp bytes consumed to CurrentBuffer */
        CurrentBuffer += InputLength;
        /* subtract bytes consumed from bytes remaining in block */
        RemainingBlock -= InputLength;
        /* neg for resume decompression of the same block */
        InputLength = -RemainingBlock;
    }

    /* now CurrentBuffer points to the first comp byte
       of the file, so we can begin decompressing */

    /* Size = remaining uncomp bytes of the file to decompress */
    Size = Search->File->FileSize;
    while (Size > 0)
    {
        OutputLength = Size;
        DPRINT("Decompressing block at %x with RemainingBlock = %d, Size = %d\n",
               CurrentBuffer, RemainingBlock, Size);

        Status = CodecUncompress(CurrentDestBuffer,
                                 CurrentBuffer,
                                 &InputLength,
                                 &OutputLength);

        if (Status != CS_SUCCESS)
        {
            DPRINT("Cannot uncompress block\n");
            if (Status == CS_NOMEMORY)
                Status = CAB_STATUS_NOMEMORY;
            Status = CAB_STATUS_INVALID_CAB;
            goto UnmapDestFile;
        }

        /* advance dest buffer by bytes produced */
        CurrentDestBuffer = (PVOID)((ULONG_PTR)CurrentDestBuffer + OutputLength);
        /* advance src buffer by bytes consumed */
        CurrentBuffer += InputLength;
        /* reduce remaining file bytes by bytes produced */
        Size -= OutputLength;
        /* reduce remaining block size by bytes consumed */
        RemainingBlock -= InputLength;
        if (RemainingBlock == 0)
        {
            /* used up this block, move on to the next */
            DPRINT("Out of block data\n");
            CFData = (PCFDATA)CurrentBuffer;
            RemainingBlock = CFData->CompSize;
            CurrentBuffer = (unsigned char *)(CFData + 1) + DataReserved;
            InputLength = RemainingBlock;
        }
    }

    Status = CAB_STATUS_SUCCESS;

UnmapDestFile:
    NtUnmapViewOfSection(NtCurrentProcess(), DestFileBuffer);

CloseDestFileSection:
    NtClose(DestFileSection);

CloseDestFile:
    NtClose(DestFile);

    return Status;
}
Пример #18
0
/*
 * @implemented
 */
HANDLE
NTAPI
CreateFileMappingW(HANDLE hFile,
                   LPSECURITY_ATTRIBUTES lpFileMappingAttributes,
                   DWORD flProtect,
                   DWORD dwMaximumSizeHigh,
                   DWORD dwMaximumSizeLow,
                   LPCWSTR lpName)
{
    NTSTATUS Status;
    HANDLE SectionHandle;
    OBJECT_ATTRIBUTES LocalAttributes;
    POBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING SectionName;
    ACCESS_MASK DesiredAccess;
    LARGE_INTEGER LocalSize;
    PLARGE_INTEGER SectionSize = NULL;
    ULONG Attributes;

    /* Set default access */
    DesiredAccess = STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ;

    /* Get the attributes for the actual allocation and cleanup flProtect */
    Attributes = flProtect & (SEC_FILE | SEC_IMAGE | SEC_RESERVE | SEC_NOCACHE | SEC_COMMIT | SEC_LARGE_PAGES);
    flProtect ^= Attributes;

    /* If the caller didn't say anything, assume SEC_COMMIT */
    if (!Attributes) Attributes = SEC_COMMIT;

    /* Now check if the caller wanted write access */
    if (flProtect == PAGE_READWRITE)
    {
        /* Give it */
        DesiredAccess |= (SECTION_MAP_WRITE | SECTION_MAP_READ);
    }

    /* Now check if we got a name */
    if (lpName) RtlInitUnicodeString(&SectionName, lpName);

    /* Now convert the object attributes */
    ObjectAttributes = BasepConvertObjectAttributes(&LocalAttributes,
                                                    lpFileMappingAttributes,
                                                    lpName ? &SectionName : NULL);

    /* Check if we got a size */
    if (dwMaximumSizeLow || dwMaximumSizeHigh)
    {
        /* Use a LARGE_INTEGER and convert */
        SectionSize = &LocalSize;
        SectionSize->LowPart = dwMaximumSizeLow;
        SectionSize->HighPart = dwMaximumSizeHigh;
    }

    /* Make sure the handle is valid */
    if (hFile == INVALID_HANDLE_VALUE)
    {
        /* It's not, we'll only go on if we have a size */
        hFile = NULL;
        if (!SectionSize)
        {
            /* No size, so this isn't a valid non-mapped section */
            SetLastError(ERROR_INVALID_PARAMETER);
            return NULL;
        }
    }

    /* Now create the actual section */
    Status = NtCreateSection(&SectionHandle,
                             DesiredAccess,
                             ObjectAttributes,
                             SectionSize,
                             flProtect,
                             Attributes,
                             hFile);
    
    if (Status == STATUS_OBJECT_NAME_EXISTS)
    {
        SetLastError(ERROR_ALREADY_EXISTS);
        return SectionHandle;
    }

    if (!NT_SUCCESS(Status))
    {
        /* We failed */
        BaseSetLastNTError(Status);
        return NULL;
    }

    SetLastError(ERROR_SUCCESS);
    /* Return the section */
    return SectionHandle;
}
Пример #19
0
HANDLE
APIENTRY
CreateFileMappingW(
    HANDLE hFile,
    LPSECURITY_ATTRIBUTES lpFileMappingAttributes,
    DWORD flProtect,
    DWORD dwMaximumSizeHigh,
    DWORD dwMaximumSizeLow,
    LPCWSTR lpName
    )
/*++

Routine Description:

    A file mapping object can be created using CreateFileMapping

    Creating a file mapping object creates the potential for mapping a
    view of the file into an address space.  File mapping objects may be
    shared either through process creation or handle duplication.
    Having a handle to a file mapping object allows for mapping of the
    file.  It does not mean that the file is actually mapped.

    A file mapping object has a maximum size.  This is used to size the
    file.  A file may not grow beyond the size specified in the mapping
    object.  While not required, it is recommended that when opening a
    file that you intend to map, the file should be opened for exclusive
    access.  Win32 does not require that a mapped file and a file
    accessed via the IO primitives (ReadFile/WriteFile) are coherent.

    In addition to the STANDARD_RIGHTS_REQUIRED access flags, the
    following object type specific access flags are valid for file
    mapping objects:

      - FILE_MAP_WRITE - Write map access to the file mapping object is
            desired.  This allows a writable view of the file to be
            mapped.  Note that if flProtect does not include
            PAGE_READWRITE, this access type does not allow writing the
            mapped file.

      - FILE_MAP_READ - Read map access to the file mapping object is
            desired.  This allows a readablee view of the file to be
            mapped.

      - FILE_MAP_ALL_ACCESS - This set of access flags specifies all of
            the possible access flags for a file mapping object.

Arguments:

    hFile - Supplies an open handle to a file that a mapping object is
        to be created for.  The file must be opened with an access mode
        that is compatible with the specified pretection flags. A value
        of INVALID_HANDLE_VALUE specifies that the mapping object is
        backed by the system paging file.  If this is the case, a size
        must be specified.

    lpFileMappingAttributes - An optional parameter that may be used to
        specify the attributes of the new file mapping object.  If the
        parameter is not specified, then the file mapping object is
        created without a security descriptor, and the resulting handle
        is not inherited on process creation:

    flProtect - The protection desired for mapping object when the file
        is mapped.

        flProtect Values

        PAGE_READONLY - Read access to the committed region of pages is
            allowed.  An attempt to write or execute the committed
            region results in an access violation.  The specified hFile
            must have been created with GENERIC_READ access.

        PAGE_READWRITE - Read and write access to the committed region
            of pages is allowed.  The specified hFile must have been
            created with GENERIC_READ and GENERIC_WRITE access.

        PAGE_WRITECOPY - Read and copy on write access to the committed
            region of pages is allowed.  The specified hFile must have been
            created with GENERIC_READ access.

    dwMaximumSizeHigh - Supplies the high order 32-bits of the maximum
        size of the file mapping object.

    dwMaximumSizeLow - Supplies the low order 32-bits of the maximum
        size of the file mapping object.  A value of zero along with a
        value of zero in dwMaximumSizeHigh indicates that the size of
        the file mapping object is equal to the current size of the file
        specified by hFile.

    lpName - Supplies the name ofthe file mapping object.

Return Value:

    NON-NULL - Returns a handle to the new file mapping object.  The
        handle has full access to the new file mapping object and may be
        used in any API that requires a handle to a file mapping object.

    FALSE/NULL - The operation failed. Extended error status is available
        using GetLastError.

--*/

{
    HANDLE Section;
    NTSTATUS Status;
    LARGE_INTEGER SectionSizeData;
    PLARGE_INTEGER SectionSize;
    OBJECT_ATTRIBUTES Obja;
    POBJECT_ATTRIBUTES pObja;
    ACCESS_MASK DesiredAccess;
    UNICODE_STRING ObjectName;
    ULONG AllocationAttributes;

    DesiredAccess = STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ;
    AllocationAttributes = flProtect & (SEC_FILE | SEC_IMAGE | SEC_RESERVE | SEC_COMMIT | SEC_NOCACHE);
    flProtect ^= AllocationAttributes;
    if (AllocationAttributes == 0) {
        AllocationAttributes = SEC_COMMIT;
        }

    if ( flProtect == PAGE_READWRITE ) {
        DesiredAccess |= (SECTION_MAP_READ | SECTION_MAP_WRITE);
        }
    else
    if ( flProtect != PAGE_READONLY && flProtect != PAGE_WRITECOPY ) {
        SetLastError(ERROR_INVALID_PARAMETER);
        return NULL;
        }

    if ( ARGUMENT_PRESENT(lpName) ) {
        RtlInitUnicodeString(&ObjectName,lpName);
        pObja = BaseFormatObjectAttributes(&Obja,lpFileMappingAttributes,&ObjectName);
        }
    else {
        pObja = BaseFormatObjectAttributes(&Obja,lpFileMappingAttributes,NULL);
        }

    if ( dwMaximumSizeLow || dwMaximumSizeHigh ) {
        SectionSize = &SectionSizeData;
        SectionSize->LowPart = dwMaximumSizeLow;
        SectionSize->HighPart = dwMaximumSizeHigh;
        }
    else {
        SectionSize = NULL;
        }

    if (hFile == INVALID_HANDLE_VALUE) {
        hFile = NULL;
        if ( !SectionSize ) {
            SetLastError(ERROR_INVALID_PARAMETER);
            return NULL;
            }
        }

    Status = NtCreateSection(
                &Section,
                DesiredAccess,
                pObja,
                SectionSize,
                flProtect,
                AllocationAttributes,
                hFile
                );
    if ( !NT_SUCCESS(Status) ) {
        BaseSetLastNTError(Status);
        return Section = NULL;
        }
    else {
        if ( Status == STATUS_OBJECT_NAME_EXISTS ) {
            SetLastError(ERROR_ALREADY_EXISTS);
            }
        else {
            SetLastError(0);
            }
        }
    return Section;
}
Пример #20
0
BOOLEAN WepCreateServerObjects(
    VOID
    )
{
    OBJECT_ATTRIBUTES objectAttributes;
    WCHAR buffer[256];
    UNICODE_STRING objectName;

    if (!WeServerSharedSection)
    {
        LARGE_INTEGER maximumSize;

        WeFormatLocalObjectName(WE_SERVER_SHARED_SECTION_NAME, buffer, &objectName);
        InitializeObjectAttributes(&objectAttributes, &objectName, OBJ_CASE_INSENSITIVE, NULL, NULL);
        maximumSize.QuadPart = sizeof(WE_HOOK_SHARED_DATA);

        if (!NT_SUCCESS(NtCreateSection(
            &WeServerSharedSection,
            SECTION_ALL_ACCESS,
            &objectAttributes,
            &maximumSize,
            PAGE_READWRITE,
            SEC_COMMIT,
            NULL
            )))
        {
            return FALSE;
        }
    }

    if (!WeServerSharedData)
    {
        PVOID viewBase;
        SIZE_T viewSize;

        viewBase = NULL;
        viewSize = sizeof(WE_HOOK_SHARED_DATA);

        if (!NT_SUCCESS(NtMapViewOfSection(
            WeServerSharedSection,
            NtCurrentProcess(),
            &viewBase,
            0,
            0,
            NULL,
            &viewSize,
            ViewShare,
            0,
            PAGE_READWRITE
            )))
        {
            WepCloseServerObjects();
            return FALSE;
        }

        WeServerSharedData = viewBase;
    }

    if (!WeServerSharedSectionLock)
    {
        WeFormatLocalObjectName(WE_SERVER_SHARED_SECTION_LOCK_NAME, buffer, &objectName);
        InitializeObjectAttributes(&objectAttributes, &objectName, OBJ_CASE_INSENSITIVE, NULL, NULL);

        if (!NT_SUCCESS(NtCreateMutant(
            &WeServerSharedSectionLock,
            MUTANT_ALL_ACCESS,
            &objectAttributes,
            FALSE
            )))
        {
            WepCloseServerObjects();
            return FALSE;
        }
    }

    if (!WeServerSharedSectionEvent)
    {
        WeFormatLocalObjectName(WE_SERVER_SHARED_SECTION_EVENT_NAME, buffer, &objectName);
        InitializeObjectAttributes(&objectAttributes, &objectName, OBJ_CASE_INSENSITIVE, NULL, NULL);

        if (!NT_SUCCESS(NtCreateEvent(
            &WeServerSharedSectionEvent,
            EVENT_ALL_ACCESS,
            &objectAttributes,
            NotificationEvent,
            FALSE
            )))
        {
            WepCloseServerObjects();
            return FALSE;
        }
    }

    return TRUE;
}
Пример #21
0
VOID
GuiConsoleShowConsoleProperties(PGUI_CONSOLE_DATA GuiData,
                                BOOL Defaults)
{
    NTSTATUS Status;
    PCONSRV_CONSOLE Console = GuiData->Console;
    PCONSOLE_PROCESS_DATA ProcessData;
    HANDLE hSection = NULL, hClientSection = NULL;
    PVOID ThreadParameter = NULL; // Is either hClientSection or the console window handle,
                                  // depending on whether we display the default settings or
                                  // the settings of a particular console.

    DPRINT("GuiConsoleShowConsoleProperties entered\n");

    if (!ConDrvValidateConsoleUnsafe((PCONSOLE)Console, CONSOLE_RUNNING, TRUE)) return;

    /* Get the console leader process, our client */
    ProcessData = ConSrvGetConsoleLeaderProcess(Console);

    /*
     * Be sure we effectively have a properties dialog routine (that launches
     * the console control panel applet). It resides in kernel32.dll (client).
     */
    if (ProcessData->PropRoutine == NULL) goto Quit;

    /*
     * Create a memory section to be shared with the console control panel applet
     * in the case we are displaying the settings of a particular console.
     * In that case the ThreadParameter is the hClientSection handle.
     * In the case we display the default console parameters, we don't need to
     * create a memory section. We just need to open the applet, and in this case
     * the ThreadParameter is the parent window handle of the applet's window,
     * that is, the console window.
     */
    if (!Defaults)
    {
        PCONSOLE_SCREEN_BUFFER ActiveBuffer = GuiData->ActiveBuffer;
        LARGE_INTEGER SectionSize;
        ULONG ViewSize = 0;
        PCONSOLE_STATE_INFO pSharedInfo = NULL;

        /*
         * Create a memory section to share with the applet, and map it.
         */
        SectionSize.QuadPart  = sizeof(CONSOLE_STATE_INFO);    // Standard size
        SectionSize.QuadPart += Console->OriginalTitle.Length; // Add the length in bytes of the console title string

        Status = NtCreateSection(&hSection,
                                 SECTION_ALL_ACCESS,
                                 NULL,
                                 &SectionSize,
                                 PAGE_READWRITE,
                                 SEC_COMMIT,
                                 NULL);
        if (!NT_SUCCESS(Status))
        {
            DPRINT1("Error: Impossible to create a shared section, Status = 0x%08lx\n", Status);
            goto Quit;
        }

        Status = NtMapViewOfSection(hSection,
                                    NtCurrentProcess(),
                                    (PVOID*)&pSharedInfo,
                                    0,
                                    0,
                                    NULL,
                                    &ViewSize,
                                    ViewUnmap,
                                    0,
                                    PAGE_READWRITE);
        if (!NT_SUCCESS(Status))
        {
            DPRINT1("Error: Impossible to map the shared section, Status = 0x%08lx\n", Status);
            goto Quit;
        }


        /*
         * Setup the shared console properties structure.
         */

        /* Store the real size of the structure */
        pSharedInfo->cbSize = SectionSize.QuadPart;

        /*
         * When we setup the settings of a particular console, the parent window
         * of the applet's window is the console window, and it is given via the
         * hWnd member of the shared console info structure.
         */
        pSharedInfo->hWnd = GuiData->hWindow;

        /* Console information */
        pSharedInfo->HistoryBufferSize = Console->HistoryBufferSize;
        pSharedInfo->NumberOfHistoryBuffers = Console->NumberOfHistoryBuffers;
        pSharedInfo->HistoryNoDup = Console->HistoryNoDup;
        pSharedInfo->QuickEdit = Console->QuickEdit;
        pSharedInfo->InsertMode = Console->InsertMode;
        /// pSharedInfo->InputBufferSize = 0;
        pSharedInfo->ScreenBufferSize = ActiveBuffer->ScreenBufferSize;
        pSharedInfo->WindowSize = ActiveBuffer->ViewSize;
        pSharedInfo->CursorSize = ActiveBuffer->CursorInfo.dwSize;
        if (GetType(ActiveBuffer) == TEXTMODE_BUFFER)
        {
            PTEXTMODE_SCREEN_BUFFER Buffer = (PTEXTMODE_SCREEN_BUFFER)ActiveBuffer;

            pSharedInfo->ScreenAttributes = Buffer->ScreenDefaultAttrib;
            pSharedInfo->PopupAttributes  = Buffer->PopupDefaultAttrib;
        }
        else // if (GetType(ActiveBuffer) == GRAPHICS_BUFFER)
        {
            // PGRAPHICS_SCREEN_BUFFER Buffer = (PGRAPHICS_SCREEN_BUFFER)ActiveBuffer;
            DPRINT1("GuiConsoleShowConsoleProperties - Graphics buffer\n");

            // FIXME: Gather defaults from the registry ?
            pSharedInfo->ScreenAttributes = DEFAULT_SCREEN_ATTRIB;
            pSharedInfo->PopupAttributes  = DEFAULT_POPUP_ATTRIB ;
        }
        /// pSharedInfo->CodePage;

        /* GUI Information */
        wcsncpy(pSharedInfo->FaceName, GuiData->GuiInfo.FaceName, LF_FACESIZE);
        pSharedInfo->FaceName[LF_FACESIZE - 1] = UNICODE_NULL;
        pSharedInfo->FontFamily = GuiData->GuiInfo.FontFamily;
        pSharedInfo->FontSize   = GuiData->GuiInfo.FontSize;
        pSharedInfo->FontWeight = GuiData->GuiInfo.FontWeight;
        pSharedInfo->FullScreen = GuiData->GuiInfo.FullScreen;
        pSharedInfo->AutoPosition   = GuiData->GuiInfo.AutoPosition;
        pSharedInfo->WindowPosition = GuiData->GuiInfo.WindowOrigin;

        /* Palette */
        RtlCopyMemory(pSharedInfo->ColorTable,
                      Console->Colors, sizeof(Console->Colors));

        /* Copy the original title of the console and null-terminate it */
        RtlCopyMemory(pSharedInfo->ConsoleTitle,
                      Console->OriginalTitle.Buffer,
                      Console->OriginalTitle.Length);

        pSharedInfo->ConsoleTitle[Console->OriginalTitle.Length / sizeof(WCHAR)] = UNICODE_NULL;


        /* Unmap the view */
        NtUnmapViewOfSection(NtCurrentProcess(), pSharedInfo);

        /* Duplicate the section handle for the client */
        Status = NtDuplicateObject(NtCurrentProcess(),
                                   hSection,
                                   ProcessData->Process->ProcessHandle,
                                   &hClientSection,
                                   0, 0, DUPLICATE_SAME_ACCESS);
        if (!NT_SUCCESS(Status))
        {
            DPRINT1("Error: Impossible to duplicate section handle for client, Status = 0x%08lx\n", Status);
            goto Quit;
        }

        /* For the settings of a particular console, use the shared client section handle as the thread parameter */
        ThreadParameter = (PVOID)hClientSection;
    }
    else
    {
        /* For the default settings, use the console window handle as the thread parameter */
        ThreadParameter = (PVOID)GuiData->hWindow;
    }

    /* Start the console control panel applet */
    _SEH2_TRY
    {
        HANDLE Thread = NULL;

        _SEH2_TRY
        {
            Thread = CreateRemoteThread(ProcessData->Process->ProcessHandle, NULL, 0,
                                        ProcessData->PropRoutine,
                                        ThreadParameter, 0, NULL);
            if (NULL == Thread)
            {
                DPRINT1("Failed thread creation (Error: 0x%x)\n", GetLastError());
            }
            else
            {
                DPRINT("ProcessData->PropRoutine remote thread creation succeeded, ProcessId = %x, Process = 0x%p\n",
                       ProcessData->Process->ClientId.UniqueProcess, ProcessData->Process);
            }
        }
        _SEH2_FINALLY
        {
            CloseHandle(Thread);
        }
        _SEH2_END;
    }
    _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
    {
        Status = _SEH2_GetExceptionCode();
        DPRINT1("GuiConsoleShowConsoleProperties - Caught an exception, Status = 0x%08lx\n", Status);
    }
    _SEH2_END;

Quit:
    /* We have finished, close the section handle if any */
    if (hSection) NtClose(hSection);

    LeaveCriticalSection(&Console->Lock);
    return;
}
Пример #22
0
VOID
TestParent( VOID )
{
    NTSTATUS Status;
    STRING DirectoryName;
    STRING LinkName;
    STRING LinkTarget;
    STRING SectionName;
    OBJECT_ATTRIBUTES ObjectAttributes;
    HANDLE DirectoryHandle, LinkHandle, SectionHandle;
    ULONG ReturnedLength;
    CHAR ObjectInfoBuffer[ 512 ];
    OBJECT_BASIC_INFORMATION ObjectBasicInfo;
    POBJECT_NAME_INFORMATION ObjectNameInfo;
    POBJECT_TYPE_INFORMATION ObjectTypeInfo;
    LARGE_INTEGER SectionSize;

    Status = STATUS_SUCCESS;

    DbgPrint( "Entering Object Manager User Mode Test Program\n" );

    RtlInitString( &SectionName, "\\A:\\OSO001.MSG" );
    InitializeObjectAttributes( &ObjectAttributes,
                                &SectionName,
                                OBJ_OPENIF | OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL
                              );

    SectionSize.LowPart = 0x1000;
    SectiinSize.HighPart = 0;
    Status = NtCreateSection( &SectionHandle,
                              GENERIC_READ,
                              &ObjectAttributes,
                              &SectionSize,
                              PAGE_READONLY,
                              SEC_RESERVE,
                              NULL
                            );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to create %Z section object (%X) [OK]\n", &SectionName, Status );
        }

    RtlInitString( &DirectoryName, "\\Drives" );
    InitializeObjectAttributes( &ObjectAttributes,
                                &DirectoryName,
                                OBJ_CASE_INSENSITIVE | OBJ_PERMANENT,
                                NULL,
                                (PSECURITY_DESCRIPTOR)1

                              );
    ObjectAttributes.Length = 0;
    Status = NtCreateDirectoryObject( &DirectoryHandle,
                                      -1,
                                      &ObjectAttributes
                                    );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to create %Z directory object (%X) [OK]\n",
                 &DirectoryName, Status );
        }

    RtlInitString( &DirectoryName, "\\Drives" );
    InitializeObjectAttributes( &ObjectAttributes,
                                &DirectoryName,
                                OBJ_CASE_INSENSITIVE | OBJ_PERMANENT,
                                NULL,
                                (PSECURITY_DESCRIPTOR)1

                              );
    ObjectAttributes.Length = 0;
    Status = NtCreateDirectoryObject( &DirectoryHandle,
                                      DIRECTORY_ALL_ACCESS,
                                      &ObjectAttributes
                                    );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to create %Z directory object (%X) [OK]\n",
                 &DirectoryName, Status );
        }

    InitializeObjectAttributes( &ObjectAttributes,
                                &DirectoryName,
                                -1,
                                NULL,
                                (PSECURITY_DESCRIPTOR)1

                              );
    Status = NtCreateDirectoryObject( &DirectoryHandle,
                                      DIRECTORY_ALL_ACCESS,
                                      &ObjectAttributes
                                    );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to create %Z directory object (%X) [OK]\n",
                 &DirectoryName, Status );
        }

    InitializeObjectAttributes( &ObjectAttributes,
                                &DirectoryName,
                                OBJ_CASE_INSENSITIVE | OBJ_PERMANENT,
                                NULL,
                                (PSECURITY_DESCRIPTOR)1

                              );
    Status = NtCreateDirectoryObject( &DirectoryHandle,
                                      DIRECTORY_ALL_ACCESS,
                                      &ObjectAttributes
                                    );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to create %Z directory object (%X) [OK]\n",
                 &DirectoryName, Status );
        }

    InitializeObjectAttributes( &ObjectAttributes,
                                &DirectoryName,
                                OBJ_CASE_INSENSITIVE | OBJ_PERMANENT,
                                NULL,
                                NULL

                              );
    Status = NtCreateDirectoryObject( &DirectoryHandle,
                                      DIRECTORY_ALL_ACCESS,
                                      &ObjectAttributes
                                    );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to create %Z directory object (%X)\n",
                 &DirectoryName, Status );
        NtTerminateProcess( NtCurrentProcess(), Status );
        }

    Status = NtClose( DirectoryHandle );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to close %Z directory object handle - %lx (%X)\n",
                 &DirectoryName,
                 DirectoryHandle,
                 Status
                 );
        NtTerminateProcess( NtCurrentProcess(), Status );
        }

    InitializeObjectAttributes( &ObjectAttributes,
                                &DirectoryName,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL
                              );
    Status = NtOpenDirectoryObject( &DirectoryHandle,
                                    DIRECTORY_ALL_ACCESS,
                                    &ObjectAttributes
                                  );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to open %Z directory object (%X)\n",
                 &DirectoryName, Status );
        NtTerminateProcess( NtCurrentProcess(), Status );
        }

    Status = NtQueryObject( DirectoryHandle,
                            ObjectBasicInformation,
                            &ObjectBasicInfo,
                            sizeof( ObjectBasicInfo ),
                            &ReturnedLength
                          );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "NtQueryObject( %lx, ObjectBasicInfo ) failed - Status == %X\n",
                 DirectoryHandle,
                 Status
                 );
        NtTerminateProcess( NtCurrentProcess(), Status );
        }
    DbgPrint( "NtQueryObject( %lx, ObjectBasicInfo ) returned %lx bytes\n",
             DirectoryHandle,
             ReturnedLength
             );
    DbgPrint( "    Attributes = %lx\n",          ObjectBasicInfo.Attributes );
    DbgPrint( "    GrantedAccess = %lx\n",       ObjectBasicInfo.GrantedAccess );
    DbgPrint( "    HandleCount = %lx\n",         ObjectBasicInfo.HandleCount );
    DbgPrint( "    PointerCount = %lx\n",        ObjectBasicInfo.PointerCount );
    DbgPrint( "    PagedPoolCharge = %lx\n",     ObjectBasicInfo.PagedPoolCharge );
    DbgPrint( "    NonPagedPoolCharge = %lx\n",  ObjectBasicInfo.NonPagedPoolCharge );
    DbgPrint( "    NameInfoSize = %lx\n",        ObjectBasicInfo.NameInfoSize );
    DbgPrint( "    TypeInfoSize = %lx\n",        ObjectBasicInfo.TypeInfoSize );
    DbgPrint( "    SecurityDescriptorSize = %lx\n", ObjectBasicInfo.SecurityDescriptorSize );

    ObjectNameInfo = (POBJECT_NAME_INFORMATION)ObjectInfoBuffer;
    Status = NtQueryObject( DirectoryHandle,
                            ObjectNameInformation,
                            ObjectNameInfo,
                            sizeof( ObjectInfoBuffer ),
                            &ReturnedLength
                          );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "NtQueryObject( %lx, ObjectNameInfo ) failed - Status == %X\n",
                 DirectoryHandle,
                 Status
                 );
        NtTerminateProcess( NtCurrentProcess(), Status );
        }
    DbgPrint( "NtQueryObject( %lx, ObjectNameInfo ) returned %lx bytes\n",
             DirectoryHandle,
             ReturnedLength
             );
    DbgPrint( "    Name = (%ld,%ld) '%Z'\n",
             ObjectNameInfo->Name.MaximumLength,
             ObjectNameInfo->Name.Length,
             &ObjectNameInfo->Name
           );


    ObjectTypeInfo = (POBJECT_TYPE_INFORMATION)ObjectInfoBuffer;
    Status = NtQueryObject( DirectoryHandle,
                            ObjectTypeInformation,
                            ObjectTypeInfo,
                            sizeof( ObjectInfoBuffer ),
                            &ReturnedLength
                          );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "NtQueryObject( %lx, ObjectTypeInfo ) failed - Status == %X\n",
                 DirectoryHandle,
                 Status
                 );
        NtTerminateProcess( NtCurrentProcess(), Status );
        }
    DbgPrint( "NtQueryObject( %lx, ObjectTypeInfo ) returned %lx bytes\n",
             DirectoryHandle,
             ReturnedLength
             );
    DbgPrint( "    TypeName = (%ld,%ld) '%Z'\n",
             ObjectTypeInfo->TypeName.MaximumLength,
             ObjectTypeInfo->TypeName.Length,
             &ObjectTypeInfo->TypeName
           );

    RtlInitString( &LinkName, "TestSymbolicLink" );
    InitializeObjectAttributes( &ObjectAttributes,
                                &LinkName,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL
                              );
    ObjectAttributes.RootDirectory = DirectoryHandle;
    RtlInitString( &LinkTarget, "\\Device\\FileSystem" );
    Status = NtCreateSymbolicLinkObject( &LinkHandle,
                                         SYMBOLIC_LINK_ALL_ACCESS,
                                         &ObjectAttributes,
                                         &LinkTarget
                                       );

    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to create %Z => %Z symbolic link object (%X)\n",
                 &LinkName, &LinkTarget, Status );
        NtTerminateProcess( NtCurrentProcess(), Status );
        }

    Status = NtClose( DirectoryHandle );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to close %Z directory object handle - %lx (%X)\n",
                 &DirectoryName,
                 DirectoryHandle,
                 Status
                 );
        NtTerminateProcess( NtCurrentProcess(), Status );
        }

    RtlInitString( &DirTypeName, "Directory" );
    RtlInitString( &LinkTypeName, "SymbolicLink" );
    DumpObjectDirs( "\\", 0 );

    RtlInitString( &LinkName, "TestSymbolicLink" );
    InitializeObjectAttributes( &ObjectAttributes,
                                &LinkName,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL
                              );
    ObjectAttributes.RootDirectory = LinkHandle;
    Status = NtOpenDirectoryObject( &DirectoryHandle,
                                    DIRECTORY_ALL_ACCESS,
                                    &ObjectAttributes
                                  );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to open %Z directory object (%X) [OK]\n", &DirectoryName, Status );
        }

    Status = NtClose( LinkHandle );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to close %Z symbolic link handle - %lx (%X)\n",
                 &LinkName,
                 LinkHandle,
                 Status
                 );
        NtTerminateProcess( NtCurrentProcess(), Status );
        }

    InitializeObjectAttributes( &ObjectAttributes,
                                &DirectoryName,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL
                              );
    Status = NtOpenDirectoryObject( &DirectoryHandle,
                                    DIRECTORY_ALL_ACCESS,
                                    &ObjectAttributes
                                  );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to open %Z directory object (%X)\n", &DirectoryName, Status );
        NtTerminateProcess( NtCurrentProcess(), Status );
        }

    Status = NtMakeTemporaryObject( DirectoryHandle );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "NtMakeTemporaryObject( %lx ) failed - Status == %X\n",
                 DirectoryHandle,
                 Status
               );
        NtTerminateProcess( NtCurrentProcess(), Status );
        }

    Status = NtClose( DirectoryHandle );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to close %Z directory object handle - %lx (%X)\n",
                 &DirectoryName,
                 DirectoryHandle,
                 Status
                 );
        NtTerminateProcess( NtCurrentProcess(), Status );
        }

    InitializeObjectAttributes( &ObjectAttributes,
                                &DirectoryName,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL
                              );
    Status = NtOpenDirectoryObject( &DirectoryHandle,
                                    DIRECTORY_ALL_ACCESS,
                                    &ObjectAttributes
                                  );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to open %Z directory object (%X) [OK]\n", &DirectoryName, Status );
        }

    RtlInitString( &DirectoryName, "\\ExclusiveDir" );
    InitializeObjectAttributes( &ObjectAttributes,
                                &DirectoryName,
                                OBJ_CASE_INSENSITIVE | OBJ_EXCLUSIVE,
                                NULL,
                                NULL

                              );
    Status = NtCreateDirectoryObject( &DirectoryHandle,
                                      DIRECTORY_ALL_ACCESS,
                                      &ObjectAttributes
                                    );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to create %Z directory object (%X)\n",
                 &DirectoryName, Status );
        NtTerminateProcess( NtCurrentProcess(), Status );
        }

    InitializeObjectAttributes( &ObjectAttributes,
                                &DirectoryName,
                                OBJ_CASE_INSENSITIVE | OBJ_EXCLUSIVE,
                                NULL,
                                NULL
                              );
    Status = NtOpenDirectoryObject( &DirectoryHandle,
                                    DIRECTORY_ALL_ACCESS,
                                    &ObjectAttributes
                                  );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to open %Z directory object (%X)\n",
                 &DirectoryName, Status );
        NtTerminateProcess( NtCurrentProcess(), Status );
        }

    InitializeObjectAttributes( &ObjectAttributes,
                                &DirectoryName,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL
                              );
    Status = NtOpenDirectoryObject( &DirectoryHandle,
                                    DIRECTORY_ALL_ACCESS,
                                    &ObjectAttributes
                                  );
    if (!NT_SUCCESS( Status )) {
        DbgPrint( "Unable to open %Z directory object (%X) [OK]\n",
                 &DirectoryName, Status );
        }

    DbgPrint( "Exiting Object Manager User Mode Test Program with Status = %X\n", Status );
}
Пример #23
0
VOID
GuiConsoleShowConsoleProperties(PGUI_CONSOLE_DATA GuiData,
                                BOOL Defaults)
{
    NTSTATUS Status;
    PCONSRV_CONSOLE Console = GuiData->Console;
    PCONSOLE_SCREEN_BUFFER ActiveBuffer = GuiData->ActiveBuffer;
    PCONSOLE_PROCESS_DATA ProcessData;
    HANDLE hSection = NULL, hClientSection = NULL;
    LARGE_INTEGER SectionSize;
    ULONG ViewSize = 0;
    SIZE_T Length = 0;
    PCONSOLE_PROPS pSharedInfo = NULL;
    PGUI_CONSOLE_INFO GuiInfo = NULL;

    DPRINT("GuiConsoleShowConsoleProperties entered\n");

    if (!ConDrvValidateConsoleUnsafe((PCONSOLE)Console, CONSOLE_RUNNING, TRUE)) return;

    /*
     * Create a memory section to share with the applet, and map it.
     */
    /* Holds data for console.dll + console info + terminal-specific info */
    SectionSize.QuadPart = sizeof(CONSOLE_PROPS) + sizeof(GUI_CONSOLE_INFO);
    Status = NtCreateSection(&hSection,
                             SECTION_ALL_ACCESS,
                             NULL,
                             &SectionSize,
                             PAGE_READWRITE,
                             SEC_COMMIT,
                             NULL);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Error: Impossible to create a shared section, Status = 0x%08lx\n", Status);
        goto Quit;
    }

    Status = NtMapViewOfSection(hSection,
                                NtCurrentProcess(),
                                (PVOID*)&pSharedInfo,
                                0,
                                0,
                                NULL,
                                &ViewSize,
                                ViewUnmap,
                                0,
                                PAGE_READWRITE);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Error: Impossible to map the shared section, Status = 0x%08lx\n", Status);
        goto Quit;
    }


    /*
     * Setup the shared console properties structure.
     */

    /* Header */
    pSharedInfo->hConsoleWindow = GuiData->hWindow;
    pSharedInfo->ShowDefaultParams = Defaults;

    /*
     * We fill-in the fields only if we display
     * our properties, not the default ones.
     */
    if (!Defaults)
    {
        /* Console information */
        pSharedInfo->ci.HistoryBufferSize = Console->HistoryBufferSize;
        pSharedInfo->ci.NumberOfHistoryBuffers = Console->NumberOfHistoryBuffers;
        pSharedInfo->ci.HistoryNoDup = Console->HistoryNoDup;
        pSharedInfo->ci.QuickEdit = Console->QuickEdit;
        pSharedInfo->ci.InsertMode = Console->InsertMode;
        /////////////pSharedInfo->ci.InputBufferSize = 0;
        pSharedInfo->ci.ScreenBufferSize = ActiveBuffer->ScreenBufferSize;
        pSharedInfo->ci.ConsoleSize = ActiveBuffer->ViewSize;
        pSharedInfo->ci.CursorBlinkOn;
        pSharedInfo->ci.ForceCursorOff;
        pSharedInfo->ci.CursorSize = ActiveBuffer->CursorInfo.dwSize;
        if (GetType(ActiveBuffer) == TEXTMODE_BUFFER)
        {
            PTEXTMODE_SCREEN_BUFFER Buffer = (PTEXTMODE_SCREEN_BUFFER)ActiveBuffer;

            pSharedInfo->ci.ScreenAttrib = Buffer->ScreenDefaultAttrib;
            pSharedInfo->ci.PopupAttrib  = Buffer->PopupDefaultAttrib;
        }
        else // if (GetType(ActiveBuffer) == GRAPHICS_BUFFER)
        {
            // PGRAPHICS_SCREEN_BUFFER Buffer = (PGRAPHICS_SCREEN_BUFFER)ActiveBuffer;
            DPRINT1("GuiConsoleShowConsoleProperties - Graphics buffer\n");

            // FIXME: Gather defaults from the registry ?
            pSharedInfo->ci.ScreenAttrib = DEFAULT_SCREEN_ATTRIB;
            pSharedInfo->ci.PopupAttrib  = DEFAULT_POPUP_ATTRIB ;
        }
        pSharedInfo->ci.CodePage;

        /* GUI Information */
        pSharedInfo->TerminalInfo.Size = sizeof(GUI_CONSOLE_INFO);
        GuiInfo = pSharedInfo->TerminalInfo.TermInfo = (PGUI_CONSOLE_INFO)(pSharedInfo + 1);
        wcsncpy(GuiInfo->FaceName, GuiData->GuiInfo.FaceName, LF_FACESIZE);
        GuiInfo->FaceName[LF_FACESIZE - 1] = UNICODE_NULL;
        GuiInfo->FontFamily = GuiData->GuiInfo.FontFamily;
        GuiInfo->FontSize   = GuiData->GuiInfo.FontSize;
        GuiInfo->FontWeight = GuiData->GuiInfo.FontWeight;
        GuiInfo->FullScreen = GuiData->GuiInfo.FullScreen;
        GuiInfo->AutoPosition = GuiData->GuiInfo.AutoPosition;
        GuiInfo->WindowOrigin = GuiData->GuiInfo.WindowOrigin;
        /* Offsetize */
        pSharedInfo->TerminalInfo.TermInfo = (PVOID)((ULONG_PTR)GuiInfo - (ULONG_PTR)pSharedInfo);

        /* Palette */
        memcpy(pSharedInfo->ci.Colors, Console->Colors, sizeof(Console->Colors));

        /* Title of the console, original one corresponding to the one set by the console leader */
        Length = min(sizeof(pSharedInfo->ci.ConsoleTitle) / sizeof(pSharedInfo->ci.ConsoleTitle[0]) - 1,
                     Console->OriginalTitle.Length / sizeof(WCHAR));
        wcsncpy(pSharedInfo->ci.ConsoleTitle, Console->OriginalTitle.Buffer, Length);
    }
    else
    {
        Length = 0;
        // FIXME: Load the default parameters from the registry.
    }

    /* Null-terminate the title */
    pSharedInfo->ci.ConsoleTitle[Length] = L'\0';


    /* Unmap the view */
    NtUnmapViewOfSection(NtCurrentProcess(), pSharedInfo);

    /* Get the console leader process, our client */
    ProcessData = ConSrvGetConsoleLeaderProcess(Console);

    /* Duplicate the section handle for the client */
    Status = NtDuplicateObject(NtCurrentProcess(),
                               hSection,
                               ProcessData->Process->ProcessHandle,
                               &hClientSection,
                               0, 0, DUPLICATE_SAME_ACCESS);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Error: Impossible to duplicate section handle for client, Status = 0x%08lx\n", Status);
        goto Quit;
    }

    /* Start the properties dialog */
    if (ProcessData->PropRoutine)
    {
        _SEH2_TRY
        {
            HANDLE Thread = NULL;

            _SEH2_TRY
            {
                Thread = CreateRemoteThread(ProcessData->Process->ProcessHandle, NULL, 0,
                                            ProcessData->PropRoutine,
                                            (PVOID)hClientSection, 0, NULL);
                if (NULL == Thread)
                {
                    DPRINT1("Failed thread creation (Error: 0x%x)\n", GetLastError());
                }
                else
                {
                    DPRINT("ProcessData->PropRoutine remote thread creation succeeded, ProcessId = %x, Process = 0x%p\n",
                           ProcessData->Process->ClientId.UniqueProcess, ProcessData->Process);
                    /// WaitForSingleObject(Thread, INFINITE);
                }
            }
            _SEH2_FINALLY
            {
                CloseHandle(Thread);
            }
            _SEH2_END;
        }
        _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
        {
            Status = _SEH2_GetExceptionCode();
            DPRINT1("GuiConsoleShowConsoleProperties - Caught an exception, Status = 0x%08lx\n", Status);
        }
        _SEH2_END;
    }
Пример #24
0
void console_init()
{
	log_info("Initializing console shared memory region.\n");
	/* TODO: mm_mmap() does not support MAP_SHARED yet */
	HANDLE section;
	LARGE_INTEGER section_size;
	section_size.QuadPart = sizeof(struct console_data);
	OBJECT_ATTRIBUTES obj_attr;
	obj_attr.Length = sizeof(OBJECT_ATTRIBUTES);
	obj_attr.RootDirectory = NULL;
	obj_attr.ObjectName = NULL;
	obj_attr.Attributes = OBJ_INHERIT;
	obj_attr.SecurityDescriptor = NULL;
	obj_attr.SecurityQualityOfService = NULL;
	NTSTATUS status;
	status = NtCreateSection(&section, SECTION_MAP_READ | SECTION_MAP_WRITE, &obj_attr, &section_size, PAGE_READWRITE, SEC_COMMIT, NULL);
	if (!NT_SUCCESS(status))
	{
		log_error("NtCreateSection() failed, status: %x\n", status);
		return;
	}
	PVOID base_addr = console;
	SIZE_T view_size = sizeof(struct console_data);
	status = NtMapViewOfSection(section, NtCurrentProcess(), &base_addr, 0, sizeof(struct console_data), NULL, &view_size, ViewUnmap, 0, PAGE_READWRITE);
	if (!NT_SUCCESS(status))
	{
		log_error("NtMapViewOfSection() failed, status: %x\n", status);
		return;
	}

	SECURITY_ATTRIBUTES attr;
	attr.nLength = sizeof(SECURITY_ATTRIBUTES);
	attr.lpSecurityDescriptor = NULL;
	attr.bInheritHandle = TRUE;

	HANDLE mutex = CreateMutexW(&attr, FALSE, NULL);
	if (mutex == NULL)
	{
		log_error("CreateMutexW() failed, error code: %d\n", GetLastError());
		return;
	}

	HANDLE in = CreateFileA("CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, &attr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (in == INVALID_HANDLE_VALUE)
	{
		log_error("CreateFile(\"CONIN$\") failed, error code: %d\n", GetLastError());
		return;
	}
	HANDLE out = CreateFileA("CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, &attr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (out == INVALID_HANDLE_VALUE)
	{
		log_error("CreateFile(\"CONOUT$\") failed, error code: %d\n", GetLastError());
		return;
	}
	console->section = section;
	console->mutex = mutex;
	console->in = in;
	console->out = out;
	console->termios.c_iflag = INLCR | ICRNL;
	console->termios.c_oflag = ONLCR | OPOST;
	console->termios.c_cflag = 0;
	console->termios.c_lflag = ICANON | ECHO | ECHOCTL;
	memset(console->termios.c_cc, 0, sizeof(console->termios.c_cc));
	console->termios.c_cc[VINTR] = 3;
	console->termios.c_cc[VERASE] = 8;
	console->termios.c_cc[VEOF] = 4;
	console->termios.c_cc[VSUSP] = 26;

	console->bright = 0;
	console->reverse = 0;
	console->foreground = 7;
	console->background = 0;
	console->insert_mode = 0;
	console->cursor_key_mode = 0;
	console->origin_mode = 0;
	console->wraparound_mode = 1;

	/* Only essential values are initialized here, others are automatically set to the correct value in console_retrieve_state() */
	console->at_right_margin = 0;
	console->top = 0;
	console->scroll_full_screen = 1;

	console->input_buffer_head = console->input_buffer_tail = 0;
	console->processor = NULL;

	SetConsoleMode(in, 0);
	SetConsoleMode(out, ENABLE_PROCESSED_OUTPUT);

	log_info("Console shared memory region successfully initialized.\n");
}
Пример #25
0
NTSTATUS
SetupCopyFile(
    PWCHAR SourceFileName,
    PWCHAR DestinationFileName)
{
    OBJECT_ATTRIBUTES ObjectAttributes;
    HANDLE FileHandleSource;
    HANDLE FileHandleDest;
    static IO_STATUS_BLOCK IoStatusBlock;
    FILE_STANDARD_INFORMATION FileStandard;
    FILE_BASIC_INFORMATION FileBasic;
    ULONG RegionSize;
    UNICODE_STRING FileName;
    NTSTATUS Status;
    PVOID SourceFileMap = 0;
    HANDLE SourceFileSection;
    SIZE_T SourceSectionSize = 0;
    LARGE_INTEGER ByteOffset;

#ifdef __REACTOS__
    RtlInitUnicodeString(&FileName,
                         SourceFileName);

    InitializeObjectAttributes(&ObjectAttributes,
                               &FileName,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);

    Status = NtOpenFile(&FileHandleSource,
                        GENERIC_READ,
                        &ObjectAttributes,
                        &IoStatusBlock,
                        FILE_SHARE_READ,
                        FILE_SEQUENTIAL_ONLY);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtOpenFile failed: %x, %wZ\n", Status, &FileName);
        goto done;
    }
#else
    FileHandleSource = CreateFileW(SourceFileName,
                                   GENERIC_READ,
                                   FILE_SHARE_READ,
                                   NULL,
                                   OPEN_EXISTING,
                                   0,
                                   NULL);
    if (FileHandleSource == INVALID_HANDLE_VALUE)
    {
        Status = STATUS_UNSUCCESSFUL;
        goto done;
    }
#endif

    Status = NtQueryInformationFile(FileHandleSource,
                                    &IoStatusBlock,
                                    &FileStandard,
                                    sizeof(FILE_STANDARD_INFORMATION),
                                    FileStandardInformation);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtQueryInformationFile failed: %x\n", Status);
        goto closesrc;
    }

    Status = NtQueryInformationFile(FileHandleSource,
                                    &IoStatusBlock,&FileBasic,
                                    sizeof(FILE_BASIC_INFORMATION),
                                    FileBasicInformation);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtQueryInformationFile failed: %x\n", Status);
        goto closesrc;
    }

    Status = NtCreateSection(&SourceFileSection,
                             SECTION_MAP_READ,
                             NULL,
                             NULL,
                             PAGE_READONLY,
                             SEC_COMMIT,
                             FileHandleSource);
    if (!NT_SUCCESS(Status))
    {
      DPRINT1("NtCreateSection failed: %x, %S\n", Status, SourceFileName);
      goto closesrc;
    }

    Status = NtMapViewOfSection(SourceFileSection,
                                NtCurrentProcess(),
                                &SourceFileMap,
                                0,
                                0,
                                NULL,
                                &SourceSectionSize,
                                ViewUnmap,
                                0,
                                PAGE_READONLY );
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtMapViewOfSection failed: %x, %S\n", Status, SourceFileName);
        goto closesrcsec;
    }

    RtlInitUnicodeString(&FileName,
                         DestinationFileName);

    InitializeObjectAttributes(&ObjectAttributes,
                               &FileName,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);

    Status = NtCreateFile(&FileHandleDest,
                          GENERIC_WRITE | SYNCHRONIZE,
                          &ObjectAttributes,
                          &IoStatusBlock,
                          NULL,
                          FILE_ATTRIBUTE_NORMAL,
                          0,
                          FILE_OVERWRITE_IF,
                          FILE_NO_INTERMEDIATE_BUFFERING |
                          FILE_SEQUENTIAL_ONLY |
                          FILE_SYNCHRONOUS_IO_NONALERT,
                          NULL,
                          0);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtCreateFile failed: %x\n", Status);
        goto unmapsrcsec;
    }

    RegionSize = (ULONG)PAGE_ROUND_UP(FileStandard.EndOfFile.u.LowPart);
    IoStatusBlock.Status = 0;
    ByteOffset.QuadPart = 0;
    Status = NtWriteFile(FileHandleDest,
                         NULL,
                         NULL,
                         NULL,
                         &IoStatusBlock,
                         SourceFileMap,
                         RegionSize,
                         &ByteOffset,
                         NULL);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtWriteFile failed: %x:%x, iosb: %p src: %p, size: %x\n", Status, IoStatusBlock.Status, &IoStatusBlock, SourceFileMap, RegionSize);
        goto closedest;
    }

    /* Copy file date/time from source file */
    Status = NtSetInformationFile(FileHandleDest,
                                  &IoStatusBlock,
                                  &FileBasic,
                                  sizeof(FILE_BASIC_INFORMATION),
                                  FileBasicInformation);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtSetInformationFile failed: %x\n", Status);
        goto closedest;
    }

    /* shorten the file back to it's real size after completing the write */
    Status = NtSetInformationFile(FileHandleDest,
                                  &IoStatusBlock,
                                  &FileStandard.EndOfFile,
                                  sizeof(FILE_END_OF_FILE_INFORMATION),
                                  FileEndOfFileInformation);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("NtSetInformationFile failed: %x\n", Status);
    }

closedest:
    NtClose(FileHandleDest);

unmapsrcsec:
    NtUnmapViewOfSection(NtCurrentProcess(), SourceFileMap);

closesrcsec:
    NtClose(SourceFileSection);

closesrc:
    NtClose(FileHandleSource);

done:
    return Status;
}
Пример #26
0
VOID
PropertiesDlgShow(
    IN PCONSOLE_INFORMATION Console
    )

/*++

    Displays the properties dialog and updates the window state,
    if necessary.

--*/

{
    HANDLE hSection = NULL;
    HANDLE hClientSection = NULL;
    HANDLE hThread;
    ULONG ulViewSize;
    LARGE_INTEGER li;
    NTSTATUS Status;
    PCONSOLE_STATE_INFO pStateInfo;
    PCONSOLE_PROCESS_HANDLE ProcessHandleRecord;
    PSCREEN_INFORMATION ScreenInfo;
    LPTHREAD_START_ROUTINE MyPropRoutine;

    /*
     * Create a shared memory block.
     */
    li.QuadPart = sizeof(CONSOLE_STATE_INFO) + Console->OriginalTitleLength;
    Status = NtCreateSection(&hSection,
                             SECTION_ALL_ACCESS,
                             NULL,
                             &li,
                             PAGE_READWRITE,
                             SEC_COMMIT,
                             NULL);
    if (!NT_SUCCESS(Status)) {
        KdPrint(("CONSRV: error %x creating file mapping\n", Status));
        return;
    }

    /*
     * Get a pointer to the shared memory block.
     */
    pStateInfo = NULL;
    ulViewSize = 0;
    Status = NtMapViewOfSection(hSection,
                                NtCurrentProcess(),
                                &pStateInfo,
                                0,
                                0,
                                NULL,
                                &ulViewSize,
                                ViewUnmap,
                                0,
                                PAGE_READWRITE);
    if (!NT_SUCCESS(Status)) {
        KdPrint(("CONSRV: error %x mapping view of file\n", Status));
        NtClose(hSection);
        return;
    }

    /*
     * Fill in the shared memory block with the current values.
     */
    ScreenInfo = Console->CurrentScreenBuffer;
    pStateInfo->Length = li.LowPart;
    pStateInfo->ScreenBufferSize = ScreenInfo->ScreenBufferSize;
    pStateInfo->WindowSize.X = CONSOLE_WINDOW_SIZE_X(ScreenInfo);
    pStateInfo->WindowSize.Y = CONSOLE_WINDOW_SIZE_Y(ScreenInfo);
    pStateInfo->WindowPosX = Console->WindowRect.left;
    pStateInfo->WindowPosY = Console->WindowRect.top;
    if (ScreenInfo->Flags & CONSOLE_TEXTMODE_BUFFER) {
        pStateInfo->FontSize = SCR_FONTSIZE(ScreenInfo);
        pStateInfo->FontFamily = SCR_FAMILY(ScreenInfo);
        pStateInfo->FontWeight = SCR_FONTWEIGHT(ScreenInfo);
        wcscpy(pStateInfo->FaceName, SCR_FACENAME(ScreenInfo));
        pStateInfo->CursorSize = ScreenInfo->BufferInfo.TextInfo.CursorSize;
    }
    pStateInfo->FullScreen = Console->FullScreenFlags & CONSOLE_FULLSCREEN;
    pStateInfo->QuickEdit = Console->Flags & CONSOLE_QUICK_EDIT_MODE;
    pStateInfo->AutoPosition = Console->Flags & CONSOLE_AUTO_POSITION;
    pStateInfo->InsertMode = Console->InsertMode;
    pStateInfo->ScreenAttributes = ScreenInfo->Attributes;
    pStateInfo->PopupAttributes = ScreenInfo->PopupAttributes;
    pStateInfo->HistoryBufferSize = Console->CommandHistorySize;
    pStateInfo->NumberOfHistoryBuffers = Console->MaxCommandHistories;
    pStateInfo->HistoryNoDup = Console->Flags & CONSOLE_HISTORY_NODUP;
    RtlCopyMemory(pStateInfo->ColorTable,
                  Console->ColorTable,
                  sizeof(Console->ColorTable));
    pStateInfo->hWnd = Console->hWnd;
    wcscpy(pStateInfo->ConsoleTitle, Console->OriginalTitle);
    NtUnmapViewOfSection(NtCurrentProcess(), pStateInfo);

    /*
     * Map the shared memory block handle into the client side process's
     * address space.
     */
    ProcessHandleRecord = CONTAINING_RECORD(Console->ProcessHandleList.Blink,
                                            CONSOLE_PROCESS_HANDLE,
                                            ListLink);
    Status = NtDuplicateObject(NtCurrentProcess(),
                               hSection,
                               ProcessHandleRecord->ProcessHandle,
                               &hClientSection,
                               0,
                               0,
                               DUPLICATE_SAME_ACCESS);
    if (!NT_SUCCESS(Status)) {
        KdPrint(("CONSRV: error %x mapping handle to client\n", Status));
        NtClose(hSection);
        return;
    }

    /*
     * Get a pointer to the client-side properties routine.
     */
    if (ProcessHandleRecord->PropRoutine) {
        MyPropRoutine = ProcessHandleRecord->PropRoutine;
    } else {
        MyPropRoutine = PropRoutine;
    }

    /*
     * Call back into the client process to spawn the properties dialog.
     */
    UnlockConsole(Console);
    hThread = InternalCreateCallbackThread(ProcessHandleRecord->ProcessHandle,
                                           (DWORD)MyPropRoutine,
                                           (DWORD)hClientSection);
    if (!hThread) {
        KdPrint(("CONSRV: CreateRemoteThread failed %d\n", GetLastError()));
    }
    LockConsole(Console);

    /*
     * Close any open handles and free allocated memory.
     */
    if (hThread)
        NtClose(hThread);
    if (hSection)
        NtClose(hSection);

    return;
}
Пример #27
0
/***********************************************************************
 *             CreateFileMappingW   (KERNEL32.@)
 *
 * See CreateFileMappingA.
 */
HANDLE WINAPI CreateFileMappingW( HANDLE hFile, LPSECURITY_ATTRIBUTES sa,
                                  DWORD protect, DWORD size_high,
                                  DWORD size_low, LPCWSTR name )
{
    static const int sec_flags = SEC_FILE | SEC_IMAGE | SEC_RESERVE | SEC_COMMIT | SEC_NOCACHE;

    HANDLE ret;
    NTSTATUS status;
    DWORD access, sec_type;
    LARGE_INTEGER size;

    sec_type = protect & sec_flags;
    protect &= ~sec_flags;
    if (!sec_type) sec_type = SEC_COMMIT;

    switch(protect)
    {
    case 0:
        protect = PAGE_READONLY;  /* Win9x compatibility */
        /* fall through */
    case PAGE_READONLY:
    case PAGE_WRITECOPY:
        access = STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_EXECUTE;
        break;
    case PAGE_READWRITE:
        access = STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE;
        break;
    case PAGE_EXECUTE:
        access = STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_EXECUTE | SECTION_MAP_EXECUTE_EXPLICIT;
        break;
    case PAGE_EXECUTE_READ:
    case PAGE_EXECUTE_WRITECOPY:
        access = STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_EXECUTE | SECTION_MAP_EXECUTE_EXPLICIT;
        break;
    case PAGE_EXECUTE_READWRITE:
        access = STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE | SECTION_MAP_EXECUTE_EXPLICIT;
        break;
    default:
        SetLastError( ERROR_INVALID_PARAMETER );
        return 0;
    }

    if (hFile == INVALID_HANDLE_VALUE)
    {
        hFile = 0;
        if (!size_low && !size_high)
        {
            SetLastError( ERROR_INVALID_PARAMETER );
            return 0;
        }
    }

    size.u.LowPart  = size_low;
    size.u.HighPart = size_high;

    if (sa || name)
    {
        OBJECT_ATTRIBUTES attr;
        UNICODE_STRING nameW;

        attr.Length                   = sizeof(attr);
        attr.RootDirectory            = 0;
        attr.ObjectName               = NULL;
        attr.Attributes               = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
        attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
        attr.SecurityQualityOfService = NULL;
        if (name)
        {
            RtlInitUnicodeString( &nameW, name );
            attr.ObjectName = &nameW;
            attr.RootDirectory = get_BaseNamedObjects_handle();
        }
        status = NtCreateSection( &ret, access, &attr, &size, protect, sec_type, hFile );
    }
    else status = NtCreateSection( &ret, access, NULL, &size, protect, sec_type, hFile );

    if (status == STATUS_OBJECT_NAME_EXISTS)
        SetLastError( ERROR_ALREADY_EXISTS );
    else
        SetLastError( RtlNtStatusToDosError(status) );
    return ret;
}
Пример #28
0
BOOLEAN WepCreateServerObjects(
    VOID
    )
{
    OBJECT_ATTRIBUTES objectAttributes;
    WCHAR buffer[256];
    UNICODE_STRING objectName;
    SECURITY_DESCRIPTOR securityDescriptor;
    UCHAR saclBuffer[sizeof(ACL) + FIELD_OFFSET(SYSTEM_MANDATORY_LABEL_ACE, SidStart) + FIELD_OFFSET(SID, SubAuthority) + sizeof(ULONG)];
    PACL sacl;
    UCHAR mandatoryLabelAceBuffer[FIELD_OFFSET(SYSTEM_MANDATORY_LABEL_ACE, SidStart) + FIELD_OFFSET(SID, SubAuthority) + sizeof(ULONG)];
    PSYSTEM_MANDATORY_LABEL_ACE mandatoryLabelAce;
    PSID sid;

    if (!WeServerSharedSection)
    {
        LARGE_INTEGER maximumSize;

        WeFormatLocalObjectName(WE_SERVER_SHARED_SECTION_NAME, buffer, &objectName);
        InitializeObjectAttributes(&objectAttributes, &objectName, OBJ_CASE_INSENSITIVE, NULL, NULL);
        maximumSize.QuadPart = sizeof(WE_HOOK_SHARED_DATA);

        if (!NT_SUCCESS(NtCreateSection(
            &WeServerSharedSection,
            SECTION_ALL_ACCESS,
            &objectAttributes,
            &maximumSize,
            PAGE_READWRITE,
            SEC_COMMIT,
            NULL
            )))
        {
            return FALSE;
        }
    }

    if (!WeServerSharedData)
    {
        PVOID viewBase;
        SIZE_T viewSize;

        viewBase = NULL;
        viewSize = sizeof(WE_HOOK_SHARED_DATA);

        if (!NT_SUCCESS(NtMapViewOfSection(
            WeServerSharedSection,
            NtCurrentProcess(),
            &viewBase,
            0,
            0,
            NULL,
            &viewSize,
            ViewShare,
            0,
            PAGE_READWRITE
            )))
        {
            WepCloseServerObjects();
            return FALSE;
        }

        WeServerSharedData = viewBase;
    }

    if (!WeServerSharedSectionLock)
    {
        WeFormatLocalObjectName(WE_SERVER_SHARED_SECTION_LOCK_NAME, buffer, &objectName);
        InitializeObjectAttributes(&objectAttributes, &objectName, OBJ_CASE_INSENSITIVE, NULL, NULL);

        if (!NT_SUCCESS(NtCreateMutant(
            &WeServerSharedSectionLock,
            MUTANT_ALL_ACCESS,
            &objectAttributes,
            FALSE
            )))
        {
            WepCloseServerObjects();
            return FALSE;
        }
    }

    if (!WeServerSharedSectionEvent)
    {
        WeFormatLocalObjectName(WE_SERVER_SHARED_SECTION_EVENT_NAME, buffer, &objectName);
        InitializeObjectAttributes(&objectAttributes, &objectName, OBJ_CASE_INSENSITIVE, NULL, NULL);

        if (!NT_SUCCESS(NtCreateEvent(
            &WeServerSharedSectionEvent,
            EVENT_ALL_ACCESS,
            &objectAttributes,
            NotificationEvent,
            FALSE
            )))
        {
            WepCloseServerObjects();
            return FALSE;
        }
    }

    // If mandatory labels are supported, set it to the lowest possible level.
    if (WE_WindowsVersion >= WINDOWS_VISTA)
    {
        static SID_IDENTIFIER_AUTHORITY mandatoryLabelAuthority = SECURITY_MANDATORY_LABEL_AUTHORITY;

        RtlCreateSecurityDescriptor(&securityDescriptor, SECURITY_DESCRIPTOR_REVISION);

        sacl = (PACL)saclBuffer;
        RtlCreateAcl(sacl, sizeof(saclBuffer), ACL_REVISION);

        mandatoryLabelAce = (PSYSTEM_MANDATORY_LABEL_ACE)mandatoryLabelAceBuffer;
        mandatoryLabelAce->Header.AceType = SYSTEM_MANDATORY_LABEL_ACE_TYPE;
        mandatoryLabelAce->Header.AceFlags = 0;
        mandatoryLabelAce->Header.AceSize = sizeof(mandatoryLabelAceBuffer);
        mandatoryLabelAce->Mask = SYSTEM_MANDATORY_LABEL_NO_WRITE_UP;

        sid = (PSID)&mandatoryLabelAce->SidStart;
        RtlInitializeSid(sid, &mandatoryLabelAuthority, 1);
        *RtlSubAuthoritySid(sid, 0) = SECURITY_MANDATORY_LOW_RID;

        if (NT_SUCCESS(RtlAddAce(sacl, ACL_REVISION, MAXULONG32, mandatoryLabelAce, sizeof(mandatoryLabelAceBuffer))))
        {
            if (NT_SUCCESS(RtlSetSaclSecurityDescriptor(&securityDescriptor, TRUE, sacl, FALSE)))
            {
                NtSetSecurityObject(WeServerSharedSection, LABEL_SECURITY_INFORMATION, &securityDescriptor);
                NtSetSecurityObject(WeServerSharedSectionLock, LABEL_SECURITY_INFORMATION, &securityDescriptor);
                NtSetSecurityObject(WeServerSharedSectionEvent, LABEL_SECURITY_INFORMATION, &securityDescriptor);
            }
        }
    }

    return TRUE;
}