随便记几个函数

ULONG Rav2Raw(PVOID lpFileBuffer, ULONG Rva)
{
	PIMAGE_DOS_HEADER lpDosHeader = (PIMAGE_DOS_HEADER)lpFileBuffer;
	PIMAGE_NT_HEADERS32 lpNtHeader = (PIMAGE_NT_HEADERS32)((PCHAR)lpDosHeader + lpDosHeader->e_lfanew);
	PIMAGE_SECTION_HEADER lpSecHdr = IMAGE_FIRST_SECTION(lpNtHeader);
	USHORT i;

	for (i = 0; i < lpNtHeader->FileHeader.NumberOfSections; i++)
	{
		if (Rva >= lpSecHdr[i].VirtualAddress && Rva < lpSecHdr[i].VirtualAddress + lpSecHdr[i].SizeOfRawData)
		{
			return Rva - lpSecHdr[i].VirtualAddress + lpSecHdr[i].PointerToRawData;
		}
	}
	return 0;
}
#define R2R(a, b, c)	((c)((PCHAR)a + Rav2Raw(a, b)))

ULONG KeGetFileSize(HANDLE hFile)
{
	ULONG nRet = 0;
	IO_STATUS_BLOCK StatusBlock;
	FILE_STANDARD_INFORMATION Info;

	if (NT_SUCCESS(ZwQueryInformationFile(hFile, &StatusBlock, &Info, sizeof(Info), FileStandardInformation)))
	{
		nRet = Info.EndOfFile.LowPart;
	}
	return nRet;
}

PVOID ObGetFileBuffer(PFILE_OBJECT lpFileObject)
{
	PVOID lpFileBuffer = NULL;
	POBJECT_NAME_INFORMATION lpFileName;

	if (NT_SUCCESS(IoQueryFileDosDeviceName(lpFileObject, &lpFileName)))
	{
		UNICODE_STRING FileName;
		OBJECT_ATTRIBUTES oa;
		IO_STATUS_BLOCK StatusBlock;
		HANDLE hFile;

		FileName.MaximumLength = lpFileName->Name.Length + 5 * sizeof(WCHAR);
		FileName.Buffer = ExAllocatePoolWithTag(PagedPool, FileName.MaximumLength, 0);
		FileName.Length = lpFileName->Name.Length + 4 * sizeof(WCHAR);
		RtlZeroMemory(FileName.Buffer, FileName.MaximumLength);
		wcscpy(FileName.Buffer, L"\\??\\");
		RtlCopyMemory(FileName.Buffer + 4, lpFileName->Name.Buffer, lpFileName->Name.Length);
		DbgPrint("%wZ\n", &lpFileName->Name);
		InitializeObjectAttributes(&oa, &FileName, OBJ_CASE_INSENSITIVE, NULL, NULL);
		if (NT_SUCCESS(IoCreateFile(&hFile, GENERIC_READ, &oa, &StatusBlock, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE, NULL, 0, CreateFileTypeNone, NULL, IO_NO_PARAMETER_CHECKING)))
		{
			ULONG FileSize = KeGetFileSize(hFile);

			if (FileSize)
			{
				lpFileBuffer = ExAllocatePoolWithTag(PagedPool, FileSize, 0);

				if (!NT_SUCCESS(ZwReadFile(hFile, NULL, NULL, NULL, &StatusBlock, lpFileBuffer, FileSize, NULL, NULL)))
				{
					ExFreePool(lpFileBuffer);
				}
			}
			ZwClose(hFile);
		}
		ExFreePool(FileName.Buffer);
		ExFreePool(lpFileName);
	}
	return lpFileBuffer;
}


你可能感兴趣的:(随便记几个函数)