void parse_elf (char* file_name) { init_elf_parser (file_name); if (architecture == ELFCLASS32) { get_num_sections (); get_section_names (); parse_sections (); get_entry_point (); find_main (); } else { get_num_sections64 (); get_section_names64 (); parse_sections64 (); get_entry_point64 (); find_main64 (); } }
//Initialize some globals that have to deal with the ELF we're reading //Note: this must be called whether or not you're actually using the parser void init_elf_parser (char* file_name) { init_file_buf (file_name); Elf32_Ehdr* header = (Elf32_Ehdr*)file_buf; Elf64_Ehdr* header64 = (Elf64_Ehdr*)file_buf; //Sanity check header = (Elf32_Ehdr*)file_buf; if (header->e_ident [EI_MAG0] != 0x7f || header->e_ident [EI_MAG1] != 'E' || header->e_ident [EI_MAG2] != 'L' || header->e_ident [EI_MAG3] != 'F') { elf_parser_cleanup (); printf ("CRITICAL ERROR: Not an ELF file.\n"); exit (-1); } if (header->e_shoff > file_size) { elf_parser_cleanup (); printf ("ERROR: ELF file is corrupt. Invalid section header offset. Sections have probably been stripped, please specify a starting address.\n"); exit (-1); } if (header->e_phoff > file_size) { elf_parser_cleanup (); printf ("CRITICAL ERROR: ELF file is corrupt Invalid program header offset.\n"); exit (-1); } architecture = header->e_ident [EI_CLASS]; if (architecture == ELFCLASSNONE) { printf ("CRITICAL ERROR: Invalid architecture"); exit (-1); } else if (architecture == ELFCLASS32) { Elf32_Phdr* program_headers = (Elf32_Phdr*)(file_buf + header->e_phoff); int i; for (i = 0; i < header->e_phnum; i ++) { if (program_headers [i].p_type == PT_LOAD) { base_addr = program_headers [i].p_vaddr; executable_segment_size = program_headers [i].p_filesz; break; } } if (i == header->e_phnum) { printf ("CRITICAL ERROR: No loadable segments\n"); exit (-1); } symbol_table.arch1 = NULL; symbol_table_end.arch1 = NULL; num_relocs = 0; string_table = NULL; get_dyn_syms (); get_entry_point (); get_text (); } else if (architecture == ELFCLASS64) { Elf64_Phdr* program_headers = (Elf64_Phdr*)(file_buf + header64->e_phoff); int i; for (i = 0; i < header64->e_phnum; i ++) { if (program_headers [i].p_type == PT_LOAD) { base_addr = program_headers [i].p_vaddr; executable_segment_size = program_headers [i].p_filesz; break; } } if (i == header64->e_phnum) { printf ("CRITICAL ERROR: No loadable segments\n"); exit (-1); } symbol_table.arch2 = NULL; symbol_table_end.arch2 = NULL; num_relocs = 0; string_table = NULL; get_dyn_syms64 (); get_entry_point64 (); get_text64 (); } else { printf ("CRITICAL ERROR: Invalid ELF class %d", architecture); exit (-1); } }