1/*
2 * Copyright 2009-2010, Ingo Weinhold, ingo_weinhold@gmx.de.
3 * Distributed under the terms of the MIT License.
4 */
5#ifndef ELF_FILE_H
6#define ELF_FILE_H
7
8#include <sys/types.h>
9
10#include <SupportDefs.h>
11
12#include <elf32.h>
13#include <elf64.h>
14#include <util/DoublyLinkedList.h>
15
16#include "Types.h"
17
18
19class ElfSection : public DoublyLinkedListLinkImpl<ElfSection> {
20public:
21								ElfSection(const char* name, int fd,
22									off_t offset, off_t size,
23									target_addr_t loadAddress, uint32 flags);
24								~ElfSection();
25
26			const char*			Name() const	{ return fName; }
27			off_t				Offset() const	{ return fOffset; }
28			off_t				Size() const	{ return fSize; }
29			const void*			Data() const	{ return fData; }
30			target_addr_t		LoadAddress() const
31									{ return fLoadAddress; }
32			bool				IsWritable() const
33									{ return (fFlags & SHF_WRITE) != 0; }
34
35			status_t			Load();
36			void				Unload();
37			bool				IsLoaded() const { return fLoadCount > 0; }
38
39private:
40			const char*			fName;
41			int					fFD;
42			off_t				fOffset;
43			off_t				fSize;
44			void*				fData;
45			target_addr_t		fLoadAddress;
46			uint32				fFlags;
47			int32				fLoadCount;
48};
49
50
51class ElfSegment : public DoublyLinkedListLinkImpl<ElfSegment> {
52public:
53								ElfSegment(off_t fileOffset, off_t fileSize,
54									target_addr_t loadAddress,
55									target_size_t loadSize, bool writable);
56								~ElfSegment();
57
58			off_t				FileOffset() const	{ return fFileOffset; }
59			off_t				FileSize() const	{ return fFileSize; }
60			target_addr_t		LoadAddress() const	{ return fLoadAddress; }
61			target_size_t		LoadSize() const	{ return fLoadSize; }
62			bool				IsWritable() const	{ return fWritable; }
63
64private:
65			off_t				fFileOffset;
66			off_t				fFileSize;
67			target_addr_t		fLoadAddress;
68			target_size_t		fLoadSize;
69			bool				fWritable;
70};
71
72
73class ElfFile {
74public:
75								ElfFile();
76								~ElfFile();
77
78			status_t			Init(const char* fileName);
79
80			int					FD() const	{ return fFD; }
81
82			ElfSection*			GetSection(const char* name);
83			void				PutSection(ElfSection* section);
84			ElfSection*			FindSection(const char* name) const;
85
86			ElfSegment*			TextSegment() const;
87			ElfSegment*			DataSegment() const;
88
89private:
90			typedef DoublyLinkedList<ElfSection> SectionList;
91			typedef DoublyLinkedList<ElfSegment> SegmentList;
92
93private:
94			template<typename Ehdr, typename Phdr, typename Shdr>
95			status_t			_LoadFile(const char* fileName);
96
97			bool				_CheckRange(off_t offset, off_t size) const;
98			static bool			_CheckElfHeader(Elf32_Ehdr& elfHeader);
99			static bool			_CheckElfHeader(Elf64_Ehdr& elfHeader);
100
101private:
102			off_t				fFileSize;
103			int					fFD;
104			SectionList			fSections;
105			SegmentList			fSegments;
106};
107
108
109#endif	// ELF_FILE_H
110