summaryrefslogtreecommitdiffhomepage
path: root/src/modules/pe_get_kernel32_module_handle.c
blob: 1af03bfe3f5a54546fca2d2d0da53ee1883d6b86 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*****************************************************************************/
/*  pemagination: a (virtual) tour into portable bits and executable bytes   */
/*  Copyright (C) 2013--2016  Z. Gilboa                                      */
/*  Released under GPLv2 and GPLv3; see COPYING.PEMAGINE.                    */
/*****************************************************************************/

#include <psxtypes/psxtypes.h>
#include <pemagine/pe_consts.h>
#include <pemagine/pe_structs.h>
#include <pemagine/pemagine.h>
#include "pe_impl.h"

static int pe_get_kernel32_handle_callback(
	struct pe_ldr_tbl_entry *	ldr_tbl_entry,
	enum pe_callback_reason		reason,
	void *				context)
{
	#define KERNEL32_UTF16_STRLEN	24

	intptr_t *		addr;
	const wchar16_t *	wch;

	/* not an item? */
	if (reason != PE_CALLBACK_REASON_ITEM)
		return 1;

	/* wrong length? */
	if (ldr_tbl_entry->base_dll_name.strlen != KERNEL32_UTF16_STRLEN)
		return 1;

	/* avoid scan-based false positives */
	wch = ldr_tbl_entry->base_dll_name.buffer;

	if (pe_impl_utf16_char_to_lower(wch[4]) != 'e')
		return 1;

	else if (pe_impl_utf16_char_to_lower(wch[1]) != 'e')
		return 1;

	else if (pe_impl_utf16_char_to_lower(wch[3]) != 'n')
		return 1;

	else if (pe_impl_utf16_char_to_lower(wch[2]) != 'r')
		return 1;

	else if (pe_impl_utf16_char_to_lower(wch[5]) != 'l')
		return 1;

	else if (pe_impl_utf16_char_to_lower(wch[0]) != 'k')
		return 1;

	else if (pe_impl_utf16_char_to_lower(wch[7]) != '2')
		return 1;

	else if (pe_impl_utf16_char_to_lower(wch[6]) != '3')
		return 1;

	else if (pe_impl_utf16_char_to_lower(wch[11]) != 'l')
		return 1;

	else if (pe_impl_utf16_char_to_lower(wch[10]) != 'l')
		return 1;

	else if (pe_impl_utf16_char_to_lower(wch[9]) != 'd')
		return 1;

	else if (pe_impl_utf16_char_to_lower(wch[8]) != '.')
		return 1;

	/* match */
	addr  = (intptr_t *)context;
	*addr = (intptr_t)ldr_tbl_entry->dll_base;
	return 0;
}

void * pe_get_kernel32_module_handle(void)
{

	intptr_t kernel32_base_addr = 0;
	void * ptr_to_callback = &kernel32_base_addr;

	pe_enum_modules_in_init_order(
		&pe_get_kernel32_handle_callback,
		ptr_to_callback);

	return (void *)kernel32_base_addr;
}