elf.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <stdint.h>
  4. #include <sys/mman.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <unistd.h>
  8. #include <fcntl.h>
  9. #include "elf.h"
  10. #include "dwarf.h"
  11. void main(int argc, char* argv[]) {
  12. ELF elf = {0};
  13. struct stat st;
  14. elf.fd = open(argv[1], O_RDONLY);
  15. fstat(elf.fd, &st);
  16. elf.m = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, elf.fd, 0);
  17. elf.h1 = elf.m;
  18. elf.h2 = elf.m + sizeof(*elf.h1);
  19. // read the main header
  20. // check the magic bytes, 7F 45 4c 46
  21. if(elf.h1->magic[0] != 0x7f || elf.h1->magic[1] != 0x45 ||
  22. elf.h1->magic[2] != 0x4c || elf.h1->magic[3] != 0x46) {
  23. printf("not an ELF file\n");
  24. }
  25. else {
  26. printf("more magic\n");
  27. }
  28. // check address size/machine type
  29. if(elf.h1->class == 2) {
  30. printf("64 bit address size\n");
  31. }
  32. else if(elf.h1->class == 1) {
  33. printf("32 bit address size\n");
  34. }
  35. else {
  36. printf("unknown architecture\n");
  37. }
  38. // check endianness
  39. if(elf.h1->endianness == 1) {
  40. printf("little endian\n");
  41. }
  42. else if(elf.h1->endianness == 2) {
  43. printf("big endian\n");
  44. }
  45. else {
  46. printf("invalid endian byte\n");
  47. }
  48. // read the next header segment
  49. if(elf.h2->machine == 0x3E) {
  50. printf("amd64 architecture\n");
  51. }
  52. else {
  53. printf("unknown architecture\n");
  54. }
  55. // read the section header list
  56. elf.shl_cnt = elf.h2->section_h_num;
  57. elf.shl = elf.m + elf.h2->section_h_off;
  58. // section name pointers
  59. elf.names = elf.m + elf.shl[elf.h2->section_name_index].file_offset;
  60. for(int i = 0; i < elf.shl_cnt; i++) {
  61. char* name = elf.names + elf.shl[i].name;
  62. printf("%d: %s type: 0x%x, off: %d, sz: %d \n", i,
  63. name,
  64. elf.shl[i].type, elf.shl[i].file_offset, elf.shl[i].size);
  65. if(0 == strcmp(name, ".debug_line")) {
  66. elf.dw_line = elf.m + elf.shl[i].file_offset;
  67. elf.dw_line_sz = elf.shl[i].size;
  68. }
  69. else if(0 == strcmp(name, ".debug_info")) {
  70. elf.dw_info = elf.m + elf.shl[i].file_offset;
  71. elf.dw_info_sz = elf.shl[i].size;
  72. }
  73. }
  74. // line_num_machine(elf.dw_line, elf.dw_line_sz);
  75. debug_info_parse(elf.dw_info, elf.dw_info_sz);
  76. }