1/*	$NetBSD: crunchide.c,v 1.8 1997/11/01 06:51:45 lukem Exp $	*/
2/*
3 * Copyright (c) 1997 Christopher G. Demetriou.  All rights reserved.
4 * Copyright (c) 1994 University of Maryland
5 * All Rights Reserved.
6 *
7 * Permission to use, copy, modify, distribute, and sell this software and its
8 * documentation for any purpose is hereby granted without fee, provided that
9 * the above copyright notice appear in all copies and that both that
10 * copyright notice and this permission notice appear in supporting
11 * documentation, and that the name of U.M. not be used in advertising or
12 * publicity pertaining to distribution of the software without specific,
13 * written prior permission.  U.M. makes no representations about the
14 * suitability of this software for any purpose.  It is provided "as is"
15 * without express or implied warranty.
16 *
17 * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
19 * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
20 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
21 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
22 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 *
24 * Author: James da Silva, Systems Design and Analysis Group
25 *			   Computer Science Department
26 *			   University of Maryland at College Park
27 */
28/*
29 * crunchide.c - tiptoes through an a.out symbol table, hiding all defined
30 *	global symbols.  Allows the user to supply a "keep list" of symbols
31 *	that are not to be hidden.  This program relies on the use of the
32 * 	linker's -dc flag to actually put global bss data into the file's
33 * 	bss segment (rather than leaving it as undefined "common" data).
34 *
35 * 	The point of all this is to allow multiple programs to be linked
36 *	together without getting multiple-defined errors.
37 *
38 *	For example, consider a program "foo.c".  It can be linked with a
39 *	small stub routine, called "foostub.c", eg:
40 *	    int foo_main(int argc, char **argv){ return main(argc, argv); }
41 *      like so:
42 *	    cc -c foo.c foostub.c
43 *	    ld -dc -r foo.o foostub.o -o foo.combined.o
44 *	    crunchide -k _foo_main foo.combined.o
45 *	at this point, foo.combined.o can be linked with another program
46 * 	and invoked with "foo_main(argc, argv)".  foo's main() and any
47 * 	other globals are hidden and will not conflict with other symbols.
48 *
49 * TODO:
50 *	- resolve the theoretical hanging reloc problem (see check_reloc()
51 *	  below). I have yet to see this problem actually occur in any real
52 *	  program. In what cases will gcc/gas generate code that needs a
53 *	  relative reloc from a global symbol, other than PIC?  The
54 *	  solution is to not hide the symbol from the linker in this case,
55 *	  but to generate some random name for it so that it doesn't link
56 *	  with anything but holds the place for the reloc.
57 *      - arrange that all the BSS segments start at the same address, so
58 *	  that the final crunched binary BSS size is the max of all the
59 *	  component programs' BSS sizes, rather than their sum.
60 */
61
62#include <sys/cdefs.h>
63#ifndef lint
64__RCSID("$NetBSD: crunchide.c,v 1.8 1997/11/01 06:51:45 lukem Exp $");
65#endif
66__FBSDID("$FreeBSD$");
67
68#include <sys/types.h>
69#include <sys/stat.h>
70#include <sys/errno.h>
71#include <unistd.h>
72#include <stdio.h>
73#include <stdlib.h>
74#include <string.h>
75#include <fcntl.h>
76#include <a.out.h>
77
78#include "extern.h"
79
80char *pname = "crunchide";
81
82void usage(void);
83
84void add_to_keep_list(char *symbol);
85void add_file_to_keep_list(char *filename);
86
87int hide_syms(const char *filename);
88
89int verbose;
90
91int main(int, char *[]);
92
93int
94main(int argc, char **argv)
95{
96    int ch, errors;
97
98    if(argc > 0) pname = argv[0];
99
100    while ((ch = getopt(argc, argv, "k:f:v")) != -1)
101	switch(ch) {
102	case 'k':
103	    add_to_keep_list(optarg);
104	    break;
105	case 'f':
106	    add_file_to_keep_list(optarg);
107	    break;
108	case 'v':
109	    verbose = 1;
110	    break;
111	default:
112	    usage();
113	}
114
115    argc -= optind;
116    argv += optind;
117
118    if(argc == 0) usage();
119
120    errors = 0;
121    while(argc) {
122	if (hide_syms(*argv))
123		errors = 1;
124	argc--, argv++;
125    }
126
127    return errors;
128}
129
130void
131usage(void)
132{
133    fprintf(stderr,
134	    "usage: %s [-k <symbol-name>] [-f <keep-list-file>] <files> ...\n",
135	    pname);
136    exit(1);
137}
138
139/* ---------------------------- */
140
141struct keep {
142    struct keep *next;
143    char *sym;
144} *keep_list;
145
146void
147add_to_keep_list(char *symbol)
148{
149    struct keep *newp, *prevp, *curp;
150    int cmp;
151
152    cmp = 0;
153
154    for(curp = keep_list, prevp = NULL; curp; prevp = curp, curp = curp->next)
155	if((cmp = strcmp(symbol, curp->sym)) <= 0) break;
156
157    if(curp && cmp == 0)
158	return;	/* already in table */
159
160    newp = (struct keep *) malloc(sizeof(struct keep));
161    if(newp) newp->sym = strdup(symbol);
162    if(newp == NULL || newp->sym == NULL) {
163	fprintf(stderr, "%s: out of memory for keep list\n", pname);
164	exit(1);
165    }
166
167    newp->next = curp;
168    if(prevp) prevp->next = newp;
169    else keep_list = newp;
170}
171
172int
173in_keep_list(const char *symbol)
174{
175    struct keep *curp;
176    int cmp;
177
178    cmp = 0;
179
180    for(curp = keep_list; curp; curp = curp->next)
181	if((cmp = strcmp(symbol, curp->sym)) <= 0) break;
182
183    return curp && cmp == 0;
184}
185
186void
187add_file_to_keep_list(char *filename)
188{
189    FILE *keepf;
190    char symbol[1024];
191    int len;
192
193    if((keepf = fopen(filename, "r")) == NULL) {
194	perror(filename);
195	usage();
196    }
197
198    while(fgets(symbol, sizeof(symbol), keepf)) {
199	len = strlen(symbol);
200	if(len && symbol[len-1] == '\n')
201	    symbol[len-1] = '\0';
202
203	add_to_keep_list(symbol);
204    }
205    fclose(keepf);
206}
207
208/* ---------------------------- */
209
210struct {
211	const char *name;
212	int	(*check)(int, const char *);	/* 1 if match, zero if not */
213	int	(*hide)(int, const char *);	/* non-zero if error */
214} exec_formats[] = {
215#ifdef NLIST_AOUT
216	{	"a.out",	check_aout,	hide_aout,	},
217#endif
218#ifdef NLIST_ECOFF
219	{	"ECOFF",	check_elf64,	hide_elf64,	},
220#endif
221#ifdef NLIST_ELF32
222	{	"ELF32",	check_elf32,	hide_elf32,	},
223#endif
224#ifdef NLIST_ELF64
225	{	"ELF64",	check_elf64,	hide_elf64,	},
226#endif
227};
228
229int
230hide_syms(const char *filename)
231{
232	int fd, i, n, rv;
233
234	fd = open(filename, O_RDWR, 0);
235	if (fd == -1) {
236		perror(filename);
237		return 1;
238	}
239
240	rv = 0;
241
242        n = sizeof exec_formats / sizeof exec_formats[0];
243        for (i = 0; i < n; i++) {
244		if (lseek(fd, 0, SEEK_SET) != 0) {
245			perror(filename);
246			goto err;
247		}
248                if ((*exec_formats[i].check)(fd, filename) != 0)
249                        break;
250	}
251	if (i == n) {
252		fprintf(stderr, "%s: unknown executable format\n", filename);
253		goto err;
254	}
255
256	if (verbose)
257		fprintf(stderr, "%s is an %s binary\n", filename,
258		    exec_formats[i].name);
259
260	if (lseek(fd, 0, SEEK_SET) != 0) {
261		perror(filename);
262		goto err;
263	}
264	rv = (*exec_formats[i].hide)(fd, filename);
265
266out:
267	close (fd);
268	return (rv);
269
270err:
271	rv = 1;
272	goto out;
273}
274