xref: /original-bsd/lib/libc/gen/nlist.c (revision a0a7d8f4)
1 /* @(#)nlist.c	4.7 (Berkeley) 01/22/85 */
2 
3 #include <sys/types.h>
4 #include <a.out.h>
5 #include <stdio.h>
6 
7 /*
8  * nlist - retreive attributes from name list (string table version)
9  */
10 nlist(name, list)
11 	char *name;
12 	struct nlist *list;
13 {
14 	register struct nlist *p, *q;
15 	register char *s1, *s2;
16 	register n, m;
17 	int maxlen, nreq;
18 	FILE *f;
19 	FILE *sf;
20 	off_t sa;		/* symbol address */
21 	off_t ss;		/* start of strings */
22 	struct exec buf;
23 	struct nlist space[BUFSIZ/sizeof (struct nlist)];
24 
25 	maxlen = 0;
26 	for (q = list, nreq = 0; q->n_un.n_name && q->n_un.n_name[0]; q++, nreq++) {
27 		q->n_type = 0;
28 		q->n_value = 0;
29 		q->n_desc = 0;
30 		q->n_other = 0;
31 		n = strlen(q->n_un.n_name);
32 		if (n > maxlen)
33 			maxlen = n;
34 	}
35 	f = fopen(name, "r");
36 	if (f == NULL)
37 		return (-1);
38 	fread((char *)&buf, sizeof buf, 1, f);
39 	if (N_BADMAG(buf)) {
40 		fclose(f);
41 		return (-1);
42 	}
43 	sf = fopen(name, "r");
44 	if (sf == NULL) {
45 		/* ??? */
46 		fclose(f);
47 		return(-1);
48 	}
49 	sa = N_SYMOFF(buf);
50 	ss = sa + buf.a_syms;
51 	n = buf.a_syms;
52 	fseek(f, sa, 0);
53 	while (n) {
54 		m = sizeof (space);
55 		if (n < m)
56 			m = n;
57 		if (fread((char *)space, m, 1, f) != 1)
58 			break;
59 		n -= m;
60 		for (q = space; (m -= sizeof(struct nlist)) >= 0; q++) {
61 			char nambuf[BUFSIZ];
62 
63 			if (q->n_un.n_strx == 0 || q->n_type & N_STAB)
64 				continue;
65 			fseek(sf, ss+q->n_un.n_strx, 0);
66 			fread(nambuf, maxlen+1, 1, sf);
67 			for (p = list; p->n_un.n_name && p->n_un.n_name[0]; p++) {
68 				s1 = p->n_un.n_name;
69 				s2 = nambuf;
70 				while (*s1) {
71 					if (*s1++ != *s2++)
72 						goto cont;
73 				}
74 				if (*s2)
75 					goto cont;
76 				p->n_value = q->n_value;
77 				p->n_type = q->n_type;
78 				p->n_desc = q->n_desc;
79 				p->n_other = q->n_other;
80 				if (--nreq == 0)
81 					goto alldone;
82 				break;
83 		cont:		;
84 			}
85 		}
86 	}
87 alldone:
88 	fclose(f);
89 	fclose(sf);
90 	return (nreq);
91 }
92