/*
 *  syminfo by Davide Libenzi (extract library symbols info)
 *  Copyright (C) 2002  Davide Libenzi
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *  Davide Libenzi <davidel@xmailserver.org>
 *
 *  Build with:
 *
 *    gcc -o syminfo syminfo.c -ldl
 *
 */

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#define __USE_GNU
#include <dlfcn.h>


static void usage(char const *prg) {

	fprintf(stderr, "use: %s [-h] [-l LIBPATH] SYMBOL ...\n", prg);
}

int main(int ac, char **av) {
	int i;
	void *lib = RTLD_NEXT, *symaddr;
	Dl_info syminf;

	for (i = 1; i < ac; i++) {
		if (strcmp(av[i], "-l") == 0) {
			i++;
			if (i < ac &&
			    (lib = dlopen(av[i], RTLD_NOW)) == NULL) {
				perror(av[i]);
				return 2;
			}
		} else if (strcmp(av[i], "-h") == 0) {
			usage(av[0]);
			return 1;
		} else {
			break;
		}
	}
	fprintf(stdout, "%16s%16s%24s%16s%16s%16s\n",
		"SYM", "ADDR", "FILE", "BASE", "RSYM", "RADDR");

	for (; i < ac; i++) {
		symaddr = dlsym(lib, av[i]);
		fprintf(stdout, "%16s%16p", av[i], symaddr);
		if (dladdr(symaddr, &syminf)) {
			fprintf(stdout, "%24s%16p%16s%16p",
				syminf.dli_fname, syminf.dli_fbase,
				syminf.dli_sname, syminf.dli_saddr);
		}
		fprintf(stdout, "\n");
	}

	return 0;
}

