1/* Copyright (C) 2007 Red Hat, Inc.
2   This file is part of elfutils.
3
4   This file is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation; either version 3 of the License, or
7   (at your option) any later version.
8
9   elfutils is distributed in the hope that it will be useful, but
10   WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.
13
14   You should have received a copy of the GNU General Public License
15   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17#include <ar.h>
18#include <fcntl.h>
19#include <libelf.h>
20#include <stdio.h>
21#include <unistd.h>
22
23
24static int handle (const char *fname);
25
26
27int
28main (int argc, char *argv[])
29{
30  elf_version (EV_CURRENT);
31
32  int result = 0;
33  if (argc == 1)
34    result = handle ("a.out");
35  else
36    for (int i = 1; i < argc; ++i)
37      result |= handle (argv[1]);
38
39  return result;
40}
41
42
43static int
44handle (const char *fname)
45{
46  int fd = open (fname, O_RDONLY);
47  if (fd == -1)
48    {
49      printf ("cannot open '%s': %m\n", fname);
50      return 1;
51    }
52
53  Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
54  if (elf == NULL)
55    {
56      printf ("cannot get ELF handling for '%s': %s\n",
57	      fname, elf_errmsg (-1));
58      close (fd);
59      return 1;
60    }
61
62  if (elf_kind (elf) != ELF_K_AR)
63    {
64      printf ("'%s' is no archive\n", fname);
65      elf_end (elf);
66      close (fd);
67      return 1;
68    }
69
70  printf ("%s:\n", fname);
71  Elf *subelf = NULL;
72  Elf_Cmd cmd = ELF_C_READ_MMAP;
73  while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
74    {
75      Elf_Arhdr *arhdr = elf_getarhdr (subelf);
76      if (arhdr == NULL)
77	{
78	  printf ("cannot get archive header in '%s': %s\n",
79		  fname, elf_errmsg (-1));
80	  elf_end (subelf);
81	  elf_end (elf);
82	  close (fd);
83	  return 1;
84	}
85
86      off_t off = elf_getaroff (subelf);
87
88      printf ("\nOffset    %llu\n"
89	      "  Name    %s\n"
90	      "  Date    %ld\n"
91	      "  UID     %d\n"
92	      "  GID     %d\n"
93	      "  Mode    %o\n"
94	      "  Size    %lld\n",
95	      (unsigned long long int) off,
96	      arhdr->ar_name, (long int) arhdr->ar_date, (int) arhdr->ar_uid,
97	      (int) arhdr->ar_gid,
98	      (int) arhdr->ar_mode, (long long int) arhdr->ar_size);
99
100      cmd = elf_next (subelf);
101      elf_end (subelf);
102    }
103
104  close (fd);
105
106  return 0;
107}
108