summaryrefslogtreecommitdiff
path: root/elf.c
blob: 2219d5fc74edec61fae064ae2bd211fa3b2bb1fb (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
#include "elf.h"
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include <arpa/inet.h>

static inline bool IsBigEndian(void);

/* Elf Header for Little Endian Machines */
const uint8_t e_ident_le[EI_NIDENT] = {
	0x7f, 0x45, 0x4c, 0x46,	// ELF Magic Number
	BIT_WIDTH,				// 32-bit format
	_LITTLE_ENDIAN_,		// Little Endian
	ELF_VERSION,			// ELF Version
	0x00,					// Target OS
	0x00,					// Target ABI
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00	// Padding
};

/* Elf Header for Big Endian Machines */
const uint8_t e_ident_be[EI_NIDENT] = {
	0x7f, 0x45, 0x4c, 0x46,	// ELF Magic Number
	BIT_WIDTH,				// 32-bit format
	_BIG_ENDIAN_,			// Big Endian
	ELF_VERSION,			// ELF Version
	0x00,					// Target OS
	0x00,					// Target ABI
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00	// Padding
};

/* ReadElf: Read the elf header into e from file fp */
ElfHeader_t ReadElf(FILE *fp) {
	ElfHeader_t e;
	fread(&e, sizeof(e), 1, fp);
	if (ferror(fp)) {
		perror("ReadElf");
	}
	return e;
}

/* ValidateElf: Validate the elf header for the given system */
bool ValidateElf(ElfHeader_t e) {
	const uint8_t * const e_ident = IsBigEndian() ? e_ident_be : e_ident_le;
	for (size_t i = 0; i < EI_NIDENT; i++) {
		if (e.e_ident[i] != e_ident[i]) {
			return false;
		}
	}
	if (e.e_machine != MIPS || e.e_version != ELF_VERSION ||
			e.e_type != ET_EXEC || e.e_phentsize != sizeof(ProgramHeader_t)) {
		return false;
	}
	return true;
}

/* ReadProgramHeader: Read n program headers into array p of size n from file
 * fp */
void ReadProgramHeader(size_t n, ProgramHeader_t p[n], FILE *fp) {
	fread(p, sizeof(ProgramHeader_t), n, fp);
	if (ferror(fp)) {
		perror("ReadElf");
	}
}

static inline bool IsBigEndian(void) {
	int32_t x = 10;
	return x == htonl(x);
}