summaryrefslogtreecommitdiff
path: root/src/elfhandle.c
blob: c90bff2a9a3a7ec11c4b0a49946fd8c26b14c375 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <libelf.h>

#include "elfhandle.h"


void openElf(ELFHandles *h, char *fn, Elf_Cmd elfmode)
{
  int openflags = 0;
  int openmode = 0;

  h->e = NULL;

  switch(elfmode) {
    case ELF_C_READ:
      openflags = O_RDONLY;
      break;
    case ELF_C_WRITE:
      openflags = O_WRONLY | O_CREAT;
      openmode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
      break;
    case ELF_C_RDWR:
      openflags = O_RDWR;
      break;
    default:
      return;
  }


  h->fd = open(fn, openflags, openmode);
  if (h->fd < 0) {
    fprintf(stderr, "Cannot open %s: %s\n", fn, strerror(errno));
    return;
  }

  h->e = elf_begin(h->fd, elfmode, NULL);
  if (!h->e) {
    fprintf(stderr, "elf_begin() failed on %s: %s\n", fn, elf_errmsg(-1));
    goto ERR;
  }

  if (elfmode == ELF_C_READ || elfmode == ELF_C_RDWR) {
    if (elf_kind(h->e) != ELF_K_ELF) {
      fprintf(stderr, "Not an ELF object: %s", fn);
      goto ERR;
    }
  }

  return;

ERR:
  if (h->e) {
    elf_end(h->e);
    h->e = NULL;
  }
  close(h->fd);
}


void closeElf(ELFHandles *h)
{
  if (h->e) {
    elf_end(h->e);
    close(h->fd);
    h->e = NULL;
  }
}