Blame src/modules/pe_get_kernel32_module_handle.c

feffc7
/*****************************************************************************/
feffc7
/*  pemagination: a (virtual) tour into portable bits and executable bytes   */
feffc7
/*  Copyright (C) 2013,2014,2015  Z. Gilboa                                  */
feffc7
/*  Released under GPLv2 and GPLv3; see COPYING.PEMAGINE.                    */
feffc7
/*****************************************************************************/
feffc7
feffc7
#include <psxtypes/psxtypes.h>
feffc7
#include <pemagine/pe_consts.h>
feffc7
#include <pemagine/pe_structs.h>
feffc7
#include <pemagine/pemagine.h>
feffc7
#include "pe_impl.h"
feffc7
feffc7
static int pe_get_kernel32_handle_callback(
feffc7
	struct pe_ldr_tbl_entry *	ldr_tbl_entry,
feffc7
	enum pe_callback_reason		reason,
feffc7
	void *				context)
feffc7
{
feffc7
	#define KERNEL32_UTF16_STRLEN	24
feffc7
feffc7
	int32_t		kernel32_base_name_le[4];
feffc7
	char *		kernel32_base_name_ansi;
feffc7
feffc7
	intptr_t *	addr;
feffc7
	char *		ch;
feffc7
	size_t 		match;
feffc7
feffc7
	/* avoid scan-based false positives */
feffc7
	kernel32_base_name_le[0] = 0x6E72656B; /* 'kern' */
feffc7
	kernel32_base_name_le[1] = 0x32336C65; /* 'el32' */
feffc7
	kernel32_base_name_le[2] = 0x6C6C642E; /* '.dll' */
feffc7
	kernel32_base_name_le[3] = 0;
feffc7
feffc7
	kernel32_base_name_ansi = (char *)&kernel32_base_name_le;
feffc7
feffc7
	match = 0;
feffc7
	addr = (intptr_t *)context;
feffc7
feffc7
	if (reason == PE_CALLBACK_REASON_ITEM)
feffc7
		if (ldr_tbl_entry->base_dll_name.strlen == KERNEL32_UTF16_STRLEN) {
feffc7
			ch	= (char *)ldr_tbl_entry->base_dll_name.buffer;
feffc7
			match	= 0;
feffc7
feffc7
			while ((match < sizeof(kernel32_base_name_ansi))
feffc7
				&& ((*ch == kernel32_base_name_ansi[match])
feffc7
					|| (*ch == (kernel32_base_name_ansi[match] + 'A' - 'a')))
feffc7
				&& (*(ch + 1) == 0)) {
feffc7
					ch+=sizeof(uint16_t);
feffc7
					match++;
feffc7
				}
feffc7
		}
feffc7
feffc7
	if (match == sizeof(kernel32_base_name_ansi)) {
feffc7
		*addr = (intptr_t)ldr_tbl_entry->dll_base;
feffc7
		return 0;
feffc7
	}
feffc7
	else
feffc7
		return 1;
feffc7
}
feffc7
feffc7
feffc7
pe_api
feffc7
void * pe_get_kernel32_module_handle(void)
feffc7
{
feffc7
feffc7
	intptr_t kernel32_base_addr = 0;
feffc7
	void * ptr_to_callback = &kernel32_base_addr;
feffc7
feffc7
	pe_enum_modules_in_init_order(
feffc7
		&pe_get_kernel32_handle_callback,
feffc7
		ptr_to_callback);
feffc7
feffc7
	return (void *)kernel32_base_addr;
feffc7
}