Blame src/ldso/pe_open_image_from_addr.c

6d58d9
/*****************************************************************************/
6d58d9
/*  pemagination: a (virtual) tour into portable bits and executable bytes   */
6d58d9
/*  Copyright (C) 2013--2017  Z. Gilboa                                      */
6d58d9
/*  Released under GPLv2 and GPLv3; see COPYING.PEMAGINE.                    */
6d58d9
/*****************************************************************************/
6d58d9
6d58d9
#include <psxtypes/psxtypes.h>
6d58d9
#include <pemagine/pemagine.h>
6d58d9
#include <pemagine/pe_structs.h>
6d58d9
#include "pe_os.h"
6d58d9
6d58d9
struct os_memory_section_name {
6d58d9
	struct pe_unicode_str	section_name;
6d58d9
	wchar16_t		section_name_buffer[];
6d58d9
};
6d58d9
6d58d9
pe_api int32_t pe_open_image_from_addr(
6d58d9
	__out	void **			himage,
6d58d9
	__in	void *			addr,
6d58d9
	__out	uintptr_t *		buffer,
6d58d9
	__in	uint32_t		buffer_size,
6d58d9
	__in	uint32_t		desired_access,
6d58d9
	__in	uint32_t		open_options)
6d58d9
{
6d58d9
	int32_t				status;
6d58d9
	struct os_oa			oa;
6d58d9
	struct os_iosb			iosb;
6d58d9
	struct os_memory_section_name *	path;
6d58d9
	uint32_t			len;
6d58d9
	void *				hntdll;
6d58d9
	os_zw_query_virtual_memory *	zw_query_virtual_memory;
6d58d9
	os_zw_open_file *		zw_open_file;
6d58d9
6d58d9
6d58d9
	/* init */
6d58d9
	path = (struct os_memory_section_name *)buffer;
6d58d9
	path->section_name.strlen = 0;
6d58d9
	path->section_name.maxlen = (uint16_t)(buffer_size - sizeof(struct pe_unicode_str));
6d58d9
	path->section_name.buffer = path->section_name_buffer;
6d58d9
6d58d9
	if (!(hntdll = pe_get_ntdll_module_handle()))
6d58d9
		return OS_STATUS_INTERNAL_ERROR;
6d58d9
6d58d9
	if (!(zw_query_virtual_memory = (os_zw_query_virtual_memory *)pe_get_procedure_address(
6d58d9
			hntdll,"ZwQueryVirtualMemory")))
6d58d9
		return OS_STATUS_INTERNAL_ERROR;
6d58d9
6d58d9
	if (!(zw_open_file = (os_zw_open_file *)pe_get_procedure_address(
6d58d9
			hntdll,"ZwOpenFile")))
6d58d9
		return OS_STATUS_INTERNAL_ERROR;
6d58d9
6d58d9
	/* native path of image containing addr */
6d58d9
	if ((status = zw_query_virtual_memory(
6d58d9
			OS_CURRENT_PROCESS_HANDLE,
6d58d9
			addr,
6d58d9
			OS_MEMORY_SECTION_NAME,
6d58d9
			buffer,
6d58d9
			buffer_size,
6d58d9
			&len)))
6d58d9
		return status;
6d58d9
6d58d9
	/* oa */
6d58d9
	oa.len      = sizeof(struct os_oa);
6d58d9
	oa.root_dir = 0;
6d58d9
	oa.obj_name = &path->section_name;
6d58d9
	oa.obj_attr = 0;
6d58d9
	oa.sec_desc = 0;
6d58d9
	oa.sec_qos  = 0;
6d58d9
6d58d9
	/* default access */
6d58d9
	desired_access = desired_access
6d58d9
		? desired_access
6d58d9
		: OS_SEC_SYNCHRONIZE | OS_FILE_READ_ATTRIBUTES | OS_FILE_READ_ACCESS;
6d58d9
6d58d9
	/* open image */
6d58d9
	return zw_open_file(
6d58d9
		himage,
6d58d9
		desired_access,
6d58d9
		&oa,
6d58d9
		&iosb,
6d58d9
		OS_FILE_SHARE_READ | OS_FILE_SHARE_WRITE,
6d58d9
		open_options | OS_FILE_NON_DIRECTORY_FILE);
6d58d9
}