/*
** get_nlist.c -- This file contains the routines for getting a symbol
**		  table entry when booting the Atari Linux kernel.
**
** Copyright 1993 by Hamish Macdonald
** ATARI Support by Bj”rn Brauel
**
** This file is subject to the terms and conditions of the GNU General Public
** License.  See the file README.legal in the main directory of this archive
** for more details.
**
*/


#include <osbind.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include "a.out.h"

long get_nlist(const char *fname, const char *symname)
{
    int fd = open (fname, O_RDONLY);
    int csyms;
    struct exec ex;
    struct nlist *nl, *p = NULL, *syms;
    char *strs;
    long back;
    size_t filesize;
    long strsize, numsyms;

    if (fd == -1)
	return 0;

#ifdef DEBUG
    printf ("fd is %d\n", fd);
#endif

    read (fd, &ex, sizeof(ex));
    if (!ex.a_syms) {
	close (fd);
	return 0;
    }

#ifdef DEBUG
    printf ("%ld bytes of symbol data\n", ex.a_syms);
#endif

    syms = (struct nlist *)malloc (ex.a_syms);
    if (!syms) {
	close (fd);
	return 0;
    }
    filesize=lseek (fd, N_SYMOFF(ex), SEEK_SET);
    read (fd, syms, ex.a_syms);
    numsyms = ex.a_syms / sizeof (struct nlist);
    filesize = lseek (fd, 0L, SEEK_END);
    strsize = filesize - N_STROFF(ex);
    strs = (char *)malloc (strsize);
    if (!strs) {
	free (syms);
	close (fd);
	return 0;
    }
    lseek (fd, N_STROFF(ex), SEEK_SET);
    read (fd, strs, strsize);
    nl=syms;
    back=0;
    for (csyms = 0; csyms < numsyms; csyms++) 
     {
      p=(struct nlist *)(7L+(long)(14L*(long)csyms)+(long)nl);
			if (strncmp(symname,(char *)p,8) == 0) 
       {
        csyms=(int)numsyms;
        back=p->place;
	     }
     }

    free (strs);
    free (syms);
    close (fd);
    return back;
}
