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
f270f5
	intptr_t *		addr;
f270f5
	const wchar16_t *	wch;
feffc7
f270f5
	/* not an item? */
f270f5
	if (reason != PE_CALLBACK_REASON_ITEM)
f270f5
		return 1;
f270f5
f270f5
	/* wrong length? */
f270f5
	if (ldr_tbl_entry->base_dll_name.strlen != KERNEL32_UTF16_STRLEN)
f270f5
		return 1;
feffc7
feffc7
	/* avoid scan-based false positives */
f270f5
	wch = ldr_tbl_entry->base_dll_name.buffer;
f270f5
f270f5
	if (pe_impl_utf16_char_to_lower(wch[4] != 'e'))
f270f5
		return 1;
f270f5
f270f5
	else if (pe_impl_utf16_char_to_lower(wch[1] != 'e'))
f270f5
		return 1;
f270f5
f270f5
	else if (pe_impl_utf16_char_to_lower(wch[3] != 'n'))
f270f5
		return 1;
f270f5
f270f5
	else if (pe_impl_utf16_char_to_lower(wch[2] != 'r'))
f270f5
		return 1;
f270f5
f270f5
	else if (pe_impl_utf16_char_to_lower(wch[5] != 'l'))
f270f5
		return 1;
f270f5
f270f5
	else if (pe_impl_utf16_char_to_lower(wch[0] != 'k'))
f270f5
		return 1;
f270f5
f270f5
	else if (pe_impl_utf16_char_to_lower(wch[7] != '2'))
f270f5
		return 1;
f270f5
f270f5
	else if (pe_impl_utf16_char_to_lower(wch[6] != '3'))
f270f5
		return 1;
f270f5
f270f5
	else if (pe_impl_utf16_char_to_lower(wch[11] != 'l'))
feffc7
		return 1;
feffc7
f270f5
	else if (pe_impl_utf16_char_to_lower(wch[10] != 'l'))
f270f5
		return 1;
f270f5
f270f5
	else if (pe_impl_utf16_char_to_lower(wch[9] != 'd'))
f270f5
		return 1;
f270f5
f270f5
	else if (pe_impl_utf16_char_to_lower(wch[8] != '.'))
f270f5
		return 1;
f270f5
f270f5
	/* match */
f270f5
	addr  = (intptr_t *)context;
f270f5
	*addr = (intptr_t)ldr_tbl_entry->dll_base;
f270f5
	return 0;
f270f5
}
feffc7
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
}