#ifndef __ELF_H__
#define __ELF_H__

#ifdef _WIN32

/* Type for a 16-bit quantity.  */
typedef unsigned short Elf32_Half;

/* Types for signed and unsigned 32-bit quantities.  */
typedef unsigned long Elf32_Word;

/* Type of addresses.  */
typedef unsigned long Elf32_Addr;

/* Type of file offsets.  */
typedef unsigned long Elf32_Off;

#define EI_NIDENT (16)

struct Elf32_Ehdr
{
  unsigned char	e_ident[EI_NIDENT];	/* Magic number and other info */
  Elf32_Half	e_type;			/* Object file type */
  Elf32_Half	e_machine;		/* Architecture */
  Elf32_Word	e_version;		/* Object file version */
  Elf32_Addr	e_entry;		/* Entry point virtual address */
  Elf32_Off	e_phoff;		/* Program header table file offset */
  Elf32_Off	e_shoff;		/* Section header table file offset */
  Elf32_Word	e_flags;		/* Processor-specific flags */
  Elf32_Half	e_ehsize;		/* ELF header size in bytes */
  Elf32_Half	e_phentsize;		/* Program header table entry size */
  Elf32_Half	e_phnum;		/* Program header table entry count */
  Elf32_Half	e_shentsize;		/* Section header table entry size */
  Elf32_Half	e_shnum;		/* Section header table entry count */
  Elf32_Half	e_shstrndx;		/* Section header string table index */
};

#define	ELFMAG		"\177ELF"

#define EI_CLASS	4		/* File class byte index */
#define ELFCLASS32	1		/* 32-bit objects */
#define EI_DATA		5		/* Data encoding byte index */
#define ELFDATA2LSB	1		/* 2's complement, little endian */
#define EI_VERSION	6		/* File version byte index */
					/* Value must be EV_CURRENT */
#define EI_OSABI	7		/* OS ABI identification */
#define ELFOSABI_ARM	97		/* ARM */
#define EI_ABIVERSION	8		/* ABI version */
#define ET_EXEC		2		/* Executable file */
#define EM_ARM		40		/* ARM */
#define EV_CURRENT	1		/* Current version */


/* Program segment header.  */

struct Elf32_Phdr
{
  Elf32_Word	p_type;			/* Segment type */
  Elf32_Off	p_offset;		/* Segment file offset */
  Elf32_Addr	p_vaddr;		/* Segment virtual address */
  Elf32_Addr	p_paddr;		/* Segment physical address */
  Elf32_Word	p_filesz;		/* Segment size in file */
  Elf32_Word	p_memsz;		/* Segment size in memory */
  Elf32_Word	p_flags;		/* Segment flags */
  Elf32_Word	p_align;		/* Segment alignment */
};

#define PT_LOAD		1		/* Loadable program segment */

/* ARM specific declarations */

/* Processor specific flags for the ELF header e_flags field.  */
#define EF_ARM_RELEXEC     0x01
#define EF_ARM_PIC         0x20

#else
#include <elf.h>
#endif

class ELF_READER
{
 private:
    Elf32_Ehdr ehdr;
    Elf32_Phdr* phdr;

    int idx;

    void cleanup() {
	if (phdr != NULL)
	    free(phdr);
	phdr = NULL;
    }

 public:

    ELF_READER(int fd);

    ~ELF_READER() { cleanup(); }

    const Elf32_Phdr* get_next_segment();

    bool is_valid() const { return phdr != NULL; }
    
}; // ELF_READER

#endif // __ELF_H__
