summaryrefslogtreecommitdiffhomepage
path: root/src/modules/pe_get_kernel32_module_handle.c
blob: 9cd0c182bd4d886e3e32375af4e093186943ebcc (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
/*****************************************************************************/
/*  pemagination: a (virtual) tour into portable bits and executable bytes   */
/*  Copyright (C) 2013,2014,2015  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

	int32_t		kernel32_base_name_le[4];
	char *		kernel32_base_name_ansi;

	intptr_t *	addr;
	char *		ch;
	size_t 		match;

	/* avoid scan-based false positives */
	kernel32_base_name_le[0] = 0x6E72656B; /* 'kern' */
	kernel32_base_name_le[1] = 0x32336C65; /* 'el32' */
	kernel32_base_name_le[2] = 0x6C6C642E; /* '.dll' */
	kernel32_base_name_le[3] = 0;

	kernel32_base_name_ansi = (char *)&kernel32_base_name_le;

	match = 0;
	addr = (intptr_t *)context;

	if (reason == PE_CALLBACK_REASON_ITEM)
		if (ldr_tbl_entry->base_dll_name.strlen == KERNEL32_UTF16_STRLEN) {
			ch	= (char *)ldr_tbl_entry->base_dll_name.buffer;
			match	= 0;

			while ((match < sizeof(kernel32_base_name_ansi))
				&& ((*ch == kernel32_base_name_ansi[match])
					|| (*ch == (kernel32_base_name_ansi[match] + 'A' - 'a')))
				&& (*(ch + 1) == 0)) {
					ch+=sizeof(uint16_t);
					match++;
				}
		}

	if (match == sizeof(kernel32_base_name_ansi)) {
		*addr = (intptr_t)ldr_tbl_entry->dll_base;
		return 0;
	}
	else
		return 1;
}


pe_api
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;
}