#pragma once
#include "loader/binary.hpp"
#include <vector>
#include <string>
#include <map>

class ELFLoader : public Binary
{
    public:
        ELFLoader();
        ~ELFLoader() override;

        bool load(const string& path) override;
        BinaryFormat getFormat() const override { return BinaryFormat::ELF; }
        Arch getArch() const override { return m_arch; }
        addr_t getEntryPoint() const override { return m_entry; }
        addr_t getImageBase() const override { return 0; }
        vector<uint8_t> readBytes(addr_t vaddr, size_t size) const override;
        vector<pair<addr_t, addr_t>> getDataRanges() const override;
        vector<pair<addr_t, addr_t>> getExecutableRanges() const override;
        vector<pair<addr_t, string>> getExportedFunctions() const override;
        vector<ImportEntry> getImportedFunctions() const override;
        const string& getPath() const override { return m_path; }

        addr_t getInitArray() const { return m_init_array; }
        addr_t getFiniArray() const { return m_fini_array; }
        size_t getInitArraySize() const { return m_init_array_size; }
        size_t getFiniArraySize() const { return m_fini_array_size; }
        addr_t getInit() const { return m_init; }
        addr_t getFini() const { return m_fini; }

    private:
        bool parseHeader();
        bool parseDynamic();
        bool parseSections();
        bool parseSymbols();

        string m_path;
        Arch m_arch;
        addr_t m_entry;
        vector<uint8_t> m_data;
        vector<pair<addr_t, addr_t>> m_exec_ranges;
        vector<pair<addr_t, addr_t>> m_data_ranges;
        vector<tuple<uint64_t, addr_t, uint64_t>> m_file_map;
        vector<pair<addr_t, string>> m_exports;
        vector<ImportEntry> m_imports;
        map<addr_t, string> m_symbols;
        string m_needed_libs;

        addr_t m_init_array;
        size_t m_init_array_size;
        addr_t m_fini_array;
        size_t m_fini_array_size;
        addr_t m_init;
        addr_t m_fini;
};
