/* elf-32.pk - 32-bit ELF definitions.  */

/* Copyright (C) 2019, 2020, 2021, 2022, 2023 Jose E. Marchesi.  */

/* 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 3 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, see <http://www.gnu.org/licenses/>.
 */

load "elf-common.pk";

/* ELF32 basic types.  */

type Elf32_Addr = offset<uint<32>,B>,
     Elf32_Off = offset<uint<32>,B>;

/* ELF32 relocation info.

   r_sym is the symbol table index with respect to which the
   relocation must be made.

   r_type is the type of relocation to apply, which is
   architecture-specific.  */

type Elf32_RelInfo =
  struct Elf_Word
  {
    uint<24> r_sym;
    uint<8> r_type;
  };

/* ELF32 REL relocation entry. */

type Elf32_Rel =
  struct
  {
    Elf32_Addr r_offset;
    Elf32_RelInfo r_info;
  };

/* ELF32 RELA relocation entry.

   r_offset holds a section offset in relocatable files, a virtual
   address in executable and shared object files.

   r_addend holds a constant value to be added to the relocation's
   value.  In architectures using Rel relocations this addend is
   somehow stored in the relocation's memory location.  */

type Elf32_Rela =
  struct
  {
    Elf32_Addr r_offset;
    Elf32_RelInfo r_info;
    Elf_Sword r_addend;
  };

/* ELF32 symbol.  */

type Elf32_Sym =
  struct
  {
    offset<Elf_Word,B> st_name;
    Elf32_Addr st_value;
    offset<Elf_Word,B> st_size;
    Elf_Sym_Info st_info;
    Elf_Sym_Other_Info st_other;
    Elf_Half st_shndx;
  };

/* ELF32 compressed section header.  */

type Elf32_Chdr =
  struct
  {
    /* This member specifies the compression algorithm.  */
    Elf_Word ch_type : elf_compress_algorithm_p (ch_type);
    /* Size and required alignment of the uncompressed data.  */
    offset<Elf_Word,B> ch_size;
    offset<Elf_Word,B> ch_addralign;
  };

/* ELF32 section flags.  */

type Elf32_SectionFlags =
  struct
  {
    Elf_Word flags;

    method _print = void:
    {
      elf_pretty_print_section_flags (flags);
    }
  };

/* ELF32 section header table entry.  */

type Elf32_Shdr =
  struct
  {
    offset<Elf_Word,B> sh_name;
    Elf_Word sh_type;
    Elf32_SectionFlags sh_flags;
    Elf32_Addr sh_addr;
    Elf32_Off sh_offset;
    offset<Elf_Word,B> sh_size;
    Elf_Word sh_link;
    Elf_Word sh_info;
    Elf_Word sh_addralign;
    offset<Elf_Word,B> sh_entsize;
  };

/* ELF32 program header table entry.  */

type Elf32_Phdr =
  struct
  {
    Elf_Word p_type;
    Elf32_Off p_offset;
    Elf32_Addr p_vaddr;
    Elf32_Addr p_paddr;
    offset<Elf_Word,B> p_filesz;
    offset<Elf_Word,B> p_memsz;
    Elf_SegmentFlags p_flags;
    offset<Elf_Word,B> p_align;
  };

/* ELF32 file header.  */

type Elf32_Ehdr =
  struct
  {
    Elf_Ident e_ident;
    Elf_Half e_type;
    Elf_Half e_machine;
    Elf_Word e_version = EV_CURRENT;

    Elf32_Addr e_entry;
    Elf32_Off e_phoff;
    Elf32_Off e_shoff;

    Elf_Word e_flags;
    offset<Elf_Half,B> e_ehsize;
    offset<Elf_Half,B> e_phentsize;
    Elf_Half e_phnum;
    offset<Elf_Half,B> e_shentsize;
    Elf_Half e_shnum;
    Elf_Half e_shstrndx : e_shnum == 0 || e_shstrndx < e_shnum;
  };

/* ELF32 file.  */

type Elf32_File =
  struct
  {
    Elf32_Ehdr ehdr;

    if (ehdr.e_shnum > 0)
      Elf32_Shdr[ehdr.e_shnum] shdr @ ehdr.e_shoff;

    if (ehdr.e_phnum > 0)
      Elf32_Phdr[ehdr.e_phnum] phdr @ ehdr.e_phoff;

    /* Given an offset into the ELF file's section string table, return
       the string.  */

    method get_section_name = (offset<Elf_Word,B> offset) string:
      {
        var strtab = ehdr.e_shstrndx;
        return string @ shdr'ios : shdr[strtab].sh_offset + offset;
      }

    /* Given a symtab and an offset into its associated symbol string
       table, return the string.  */

    method get_symbol_name = (Elf32_Shdr symtab, offset<Elf_Word,B> offset) string:
      {
        var strtab = symtab.sh_link;
        return string @ shdr'ios : shdr[strtab].sh_offset + offset;
      }

    /* Given a section name, return an array of section headers in the
       ELF file having that name.  */

    method get_sections_by_name = (string name) Elf32_Shdr[]:
      {
        var sections = Elf32_Shdr[]();

        for (s in shdr where get_section_name (s.sh_name) == name)
          apush (sections, s);

        return sections;
      }

    /* Given a section type (SHT_* value) return an array of section
       headers in the ELF file with that type.  */

    method get_sections_by_type = (Elf_Word stype) Elf32_Shdr[]:
      {
        var sections = Elf32_Shdr[]();

        for (s in shdr where s.sh_type == stype)
          apush (sections, s);

        return sections;
      }

    /* Given a section name, return whether it exists in this
       file.  */

    method section_name_p = (string name) int:
      {
        var sections = Elf32_Shdr[]();

        try sections = get_sections_by_name (name);
        catch if E_inval { return 0; }

        return sections'length;
      }

    /* Given an offset, return the string stored at that offset in the
       "default" string table of the ELF file.  This is the string table
       section named ".strtab".  If such a section doesn't exist, or it
       doesn't contain a string table, then raise E_inval.  */
    method get_string = (offset<Elf_Word,B> offset) string:
     {
       if (!section_name_p (".strtab"))
          raise E_inval;

       var strtab = get_sections_by_name (".strtab")[0];
       return string @ strtab'ios : strtab.sh_offset + offset;
     }

    /* Return the signature corresponding to a given group section.
       If the given section header doesn't correspond to a group
       section then raise E_inval.  */

    method get_group_signature = (Elf32_Shdr section) string:
      {
        if (section.sh_type != SHT_GROUP)
          raise E_inval;

        var symtab = shdr[section.sh_link];
        var symtab_data
          = Elf32_Sym [symtab.sh_size] @ shdr'ios : symtab.sh_offset;
        var symbol = symtab_data[section.sh_info];
        var symbol_name = get_symbol_name (symtab, symbol.st_name);

        return symbol_name;
      }

    /* Return an array of strings with the signatures of the section
       groups present in this ELF file.  */

    method get_group_signatures = string[]:
      {
        var signatures = string[]();

        for (section in shdr where section.sh_type == SHT_GROUP)
          apush (signatures, get_group_signature (section));

        return signatures;
      }

    /* Given the name of a section group, return an array with the
       section headers corresponding to all the sections in that
       group.  If the given name doesn't identify a section group in
       the ELF file then return an empty array.  */

    method get_section_group = (string group_name) Elf32_Shdr[]:
      {
        var section_group = Elf32_Shdr[]();

        var group_sections = get_sections_by_type (SHT_GROUP);
        for (sec in group_sections
             where get_group_signature (sec) == group_name)
          {
            var group_entries
              = (Elf_Word[sec.sh_size - sizeof (Elf_Word)]
                 @ sec'ios : sec.sh_offset + sizeof (Elf_Word));

            for (entry in group_entries)
              apush (section_group, shdr[entry]);

            break;
         }

       return section_group;
     }
  };
