/*
Copyright (C) 2006 Evan Teran
                   eteran@alum.rit.edu

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include "ELF32.h"
#include "Util.h"
#include <QFile>
#include <cstring>

//------------------------------------------------------------------------------
// Name: ELF32(const QString &filename)
// Desc: constructor
//------------------------------------------------------------------------------
ELF32::ELF32(const QString &filename) : BinaryInfo(filename), m_Header(0) {

}

//------------------------------------------------------------------------------
// Name: ~ELF32()
// Desc: deconstructor
//------------------------------------------------------------------------------
ELF32::~ELF32() {
	delete m_Header;
}

//------------------------------------------------------------------------------
// Name: validateHeader()
// Desc: returns true if this file matches this particular info class
//------------------------------------------------------------------------------
bool ELF32::validateHeader() {
	readHeader();
	if(std::memcmp(m_Header->e_ident, ELFMAG, SELFMAG) == 0) {
		return m_Header->e_ident[EI_CLASS] == ELFCLASS32;
	}
	return false;
}

//------------------------------------------------------------------------------
// Name: nativeBinary
// Desc: returns true if this binary is native to the arch EDB was built for
//------------------------------------------------------------------------------
bool ELF32::nativeBinary() {
#ifdef EDB_X86
	return true;
#else
	return false;
#endif
}

//------------------------------------------------------------------------------
// Name: getEntryPoint()
// Desc: returns the entry point if any of the binary
//------------------------------------------------------------------------------
edb::address_t ELF32::getEntryPoint() {
	readHeader();
	return m_Header->e_entry;
}

//------------------------------------------------------------------------------
// Name: readHeader()
// Desc: reads in enough of the file to get the header
//------------------------------------------------------------------------------
void ELF32::readHeader() {
	if(m_Header == 0) {
		m_Header = new Elf32_Ehdr;
		
		QFile file(m_Filename);
		file.open(QIODevice::ReadOnly);
		if(file.isOpen()) {
			file.read(reinterpret_cast<char *>(m_Header), sizeof(Elf32_Ehdr));
		}
	}
}
