elfld.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include <stdio.h>
  2. #include <elf.h>
  3. #include <fcntl.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #include <string.h>
  7. #include "elfld.h"
  8. static int eline = 0;
  9. struct _elfdata_private
  10. {
  11. union
  12. {
  13. uint8_t bytes[1];
  14. Elf32_Ehdr e32h;
  15. Elf64_Ehdr e64h;
  16. } header;
  17. union
  18. {
  19. uint8_t bytes[1];
  20. Elf32_Shdr *e32sh;
  21. Elf64_Shdr *e64sh;
  22. } sheaders; //section headers
  23. union
  24. {
  25. uint8_t bytes[1];
  26. Elf32_Phdr *e32ph;
  27. Elf64_Phdr *e64ph;
  28. } pheaders; //program headers
  29. };
  30. elf_file *elf_open(char *filename)
  31. {
  32. int in_fd;
  33. elf_file *efile;
  34. int rv;
  35. in_fd = open(filename,O_RDONLY);
  36. if(in_fd < 0)
  37. {
  38. eline = __LINE__;
  39. return NULL;
  40. }
  41. efile = malloc(sizeof(elf_file));
  42. if(efile == NULL)
  43. {
  44. eline = __LINE__;
  45. return NULL;
  46. }
  47. efile->private = malloc(sizeof(elf_file));
  48. if(efile->private == NULL)
  49. {
  50. eline = __LINE__;
  51. return NULL;
  52. }
  53. rv = read(in_fd,efile->private->header.bytes,sizeof(Elf32_Ehdr)); //read a 32 bit header first
  54. if(rv < 1)
  55. {
  56. eline = __LINE__;
  57. return NULL;
  58. }
  59. if(strncmp((char *)efile->private->header.e32h.e_ident,ELFMAG,SELFMAG)!= 0)
  60. {
  61. eline = __LINE__;
  62. return NULL;
  63. }
  64. if(efile->private->header.e32h.e_type == ELFCLASS64)
  65. {
  66. read(in_fd,efile->private->header.bytes + sizeof(Elf32_Ehdr),sizeof(Elf64_Ehdr)-sizeof(Elf32_Ehdr)); //it's 64 bit so read the rest of the header
  67. }
  68. printf("%d\n",efile->private->header.e32h.e_type);
  69. //todo: grab section and program headers
  70. return efile;
  71. }
  72. int main(int argc,char **argv)
  73. {
  74. elf_file *ef = NULL;
  75. ef = elf_open(argv[1]);
  76. if(ef == NULL)
  77. {
  78. printf("%d\n",eline);
  79. }
  80. else
  81. {
  82. printf("idk\n");
  83. }
  84. return 0;
  85. }