xref: /netbsd-src/sys/arch/hppa/stand/mkboot/mkboot.c (revision bcd7424575af014c909d0fce8e7ba32a73c7c9f8)
1 /*	$NetBSD: mkboot.c,v 1.5 2024/10/31 01:21:12 gutteridge Exp $	*/
2 
3 /*	$OpenBSD: mkboot.c,v 1.9 2001/05/17 00:57:55 pvalchev Exp $	*/
4 
5 /*
6  * Copyright (c) 1990, 1993
7  *	The Regents of the University of California.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)mkboot.c	8.1 (Berkeley) 7/15/93
34  */
35 
36 #if 0
37 #ifndef lint
38 static char copyright[] =
39 "@(#) Copyright (c) 1990, 1993\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #ifndef lint
44 static char rcsid[] = "$OpenBSD: mkboot.c,v 1.9 2001/05/17 00:57:55 pvalchev Exp $";
45 #endif /* not lint */
46 #endif
47 
48 #if HAVE_NBTOOL_CONFIG_H
49 #include "nbtool_config.h"
50 #include "../../sys/sys/bootblock.h"
51 #else
52 #include <sys/bootblock.h>
53 #endif
54 
55 #include <sys/param.h>
56 #include <sys/endian.h>
57 #include <sys/file.h>
58 #include <sys/stat.h>
59 #include <string.h>
60 #include <stdlib.h>
61 #include <unistd.h>
62 #include <time.h>
63 #include <err.h>
64 
65 /* BFD ELF headers */
66 #include <elf/common.h>
67 #include <elf/external.h>
68 
69 #define IS_ELF(ehdr) ((ehdr).e_ident[EI_MAG0] == ELFMAG0 && \
70 		      (ehdr).e_ident[EI_MAG1] == ELFMAG1 && \
71 		      (ehdr).e_ident[EI_MAG2] == ELFMAG2 && \
72 		      (ehdr).e_ident[EI_MAG3] == ELFMAG3)
73 
74 /*
75  * Macros to get values from multi-byte ELF header fields.  These assume
76  * a big-endian image.
77  */
78 #define ELFGET16(x)	(((x)[0] << 8) | (x)[1])
79 
80 #define ELFGET32(x)	(((x)[0] << 24) | ((x)[1] << 16) |		\
81 			 ((x)[2] <<  8) |  (x)[3])
82 
83 /*
84  * Header prepended to each a.out file.
85  */
86 struct exec {
87 	u_long	a_midmag;	/* htobe32(flags<<26 | mid<<16 | magic) */
88 	u_long	a_text;		/* text segment size */
89 	u_long	a_data;		/* initialized data size */
90 	u_long	a_bss;		/* uninitialized data size */
91 	u_long	a_syms;		/* symbol table size */
92 	u_long	a_entry;	/* entry point */
93 	u_long	a_trsize;	/* text relocation size */
94 	u_long	a_drsize;	/* data relocation size */
95 };
96 
97 /* a_magic */
98 #define	OMAGIC		0407	/* old impure format */
99 #define	NMAGIC		0410	/* read-only text */
100 #define	ZMAGIC		0413	/* demand load format */
101 #define	QMAGIC		0314	/* "compact" demand load format; deprecated */
102 
103 #define N_GETMAGIC(ex) \
104     ((((ex).a_midmag)&0xffff0000) ? \
105     (be32toh((uint32_t)((ex).a_midmag))&0xffff) : ((ex).a_midmag))
106 
107 #include <stdio.h>
108 #include <ctype.h>
109 
110 int putfile(char *, int);
111 void __dead usage(void);
112 void bcddate(char *, char *);
113 char *lifname(char *);
114 int cksum(int, int *, int);
115 
116 char *to_file;
117 int loadpoint, verbose;
118 u_long entry;
119 time_t repro_epoch = 0;
120 
121 /*
122  * Old Format:
123  *	sector 0:	LIF volume header (40 bytes)
124  *	sector 1:	<unused>
125  *	sector 2:	LIF directory (8 x 32 == 256 bytes)
126  *	sector 3-:	LIF file 0, LIF file 1, etc.
127  * where sectors are 256 bytes.
128  *
129  * New Format:
130  *	sector 0:	LIF volume header (40 bytes)
131  *	sector 1:	<unused>
132  *	sector 2:	LIF directory (8 x 32 == 256 bytes)
133  *	sector 3:	<unused>
134  *	sector 4-31:	disklabel (~300 bytes right now)
135  *	sector 32-:	LIF file 0, LIF file 1, etc.
136  */
137 int
138 main(int argc, char **argv)
139 {
140 	int to, n, pos, c;
141 	char buf[HPPA_LIF_FILESTART];
142 	struct hppa_lifvol *lifv = (struct hppa_lifvol *)buf;
143 	struct hppa_lifdir *lifd = (struct hppa_lifdir *)(buf + HPPA_LIF_DIRSTART);
144 
145 	while ((c = getopt(argc, argv, "l:t:v")) != -1) {
146 		switch (c) {
147 		case 'l':
148 			loadpoint = strtol(optarg, NULL, 0);
149 			break;
150 		case 't':
151 			repro_epoch = atoll(optarg);
152 			break;
153 		case 'v':
154 			verbose++;
155 			break;
156 		default:
157 			usage();
158 		}
159 	}
160 	if (argc - optind < 2)
161 		usage();
162 	else if (argc - optind > 8)
163 		errx(1, "too many boot programs (max 8 supported)");
164 
165 	to_file = argv[--argc];
166 	if ((to = open(to_file, O_RDWR | O_TRUNC | O_CREAT, 0644)) < 0)
167 		err(1, "%s: open", to_file);
168 
169 	memset(buf, 0, sizeof(buf));
170 
171 	/* record volume info */
172 	lifv->vol_id = htobe16(HPPA_LIF_VOL_ID);
173 	strncpy(lifv->vol_label, "MKBOOT", 6);
174 	lifv->vol_addr = htobe32(hppa_btolifs(HPPA_LIF_DIRSTART));
175 	lifv->vol_oct = htobe16(HPPA_LIF_VOL_OCT);
176 	lifv->vol_dirsize = htobe32(hppa_btolifs(HPPA_LIF_DIRSIZE));
177 	lifv->vol_version = htobe16(1);
178 	lifv->vol_number = htobe32(1);
179 	lifv->vol_lastvol = htobe32(1);
180 	lifv->vol_length = HPPA_LIF_FILESTART;	/* ... so far. */
181 	bcddate(to_file, lifv->vol_toc);
182 	lifv->ipl_addr = htobe32(HPPA_LIF_FILESTART);
183 
184 	argv += optind;
185 	argc -= optind;
186 	optind = 0;
187 	for (pos = HPPA_LIF_FILESTART; optind < argc; optind++) {
188 
189 		/* output bootfile */
190 		if (lseek(to, pos, SEEK_SET) < 0)
191 			err(1, "%s: lseek", to_file);
192 		lifd[optind].dir_addr = htobe32(hppa_btolifs(pos));
193 		n = hppa_btolifs(putfile(argv[optind], to));
194 		if (lifv->ipl_entry == 0) {
195 			lifv->ipl_entry = htobe32(loadpoint + entry);
196 			lifv->ipl_size = htobe32(hppa_lifstob(n));
197 			lifd[optind].dir_type = htobe16(HPPA_LIF_DIR_ISL);
198 			lifd[optind].dir_implement = 0;
199 		} else {
200 			lifd[optind].dir_type = htobe16(HPPA_LIF_DIR_TYPE);
201 			lifd[optind].dir_implement = htobe32(loadpoint + entry);
202 		}
203 
204 		memcpy(lifd[optind].dir_name, lifname(argv[optind]),
205 			sizeof(lifd[optind].dir_name));
206 		lifd[optind].dir_length = htobe32(n);
207 		bcddate(argv[optind], lifd[optind].dir_toc);
208 		lifd[optind].dir_flag = htobe16(HPPA_LIF_DIR_FLAG);
209 
210 		lifv->vol_length += n;
211 		pos += hppa_lifstob(n);
212 	}
213 
214 	/* terminate the directory */
215 	lifd[optind].dir_type = htobe16(0xffff);
216 
217 	/* byte-swap the length now that we're done computing it */
218 	lifv->vol_length = htobe32(lifv->vol_length);
219 
220 	/* output volume/directory header info */
221 	if (lseek(to, HPPA_LIF_VOLSTART, SEEK_SET) < 0)
222 		err(1, "%s: lseek", to_file);
223 	if (write(to, buf, sizeof(buf)) != sizeof(buf))
224 		err(1, "%s: write LIF volume", to_file);
225 	lseek(to, 0, SEEK_END);
226 
227 	if (close(to) < 0)
228 		err(1, "%s", to_file);
229 
230 	return(0);
231 }
232 
233 int
234 putfile(char *from_file, int to)
235 {
236 	struct exec ex;
237 	char buf[2048];
238 	int n, total;
239 	int from, check_sum = 0;
240 	struct hppa_lifload load;
241 	Elf32_External_Ehdr elf_header;
242 	Elf32_External_Phdr *elf_segments = NULL;
243 	int i, header_count, memory_needed, elf_load_image_segment;
244 
245 	if ((from = open(from_file, O_RDONLY)) < 0)
246 		err(1, "%s", from_file);
247 
248 	n = read(from, &ex, sizeof(ex));
249 	if (n != sizeof(ex))
250 		err(1, "%s: reading file header", from_file);
251 
252 	entry = ex.a_entry;
253 	if (N_GETMAGIC(ex) == OMAGIC || N_GETMAGIC(ex) == NMAGIC)
254 		entry += sizeof(ex);
255 	else if (IS_ELF(*(Elf32_External_Ehdr *)&ex)) {
256 
257 		if (lseek(from, 0, SEEK_SET) < 0)
258 			err(1, "lseek");
259 		n = read(from, &elf_header, sizeof (elf_header));
260 		if (n != sizeof (elf_header))
261 			err(1, "%s: reading ELF header", from_file);
262 		header_count = ELFGET16(elf_header.e_phnum);
263 		memory_needed = header_count * sizeof (Elf32_External_Phdr);
264 		elf_segments = malloc(memory_needed);
265 		if (elf_segments == NULL)
266 			err(1, "malloc");
267 		if (lseek(from, ELFGET32(elf_header.e_phoff), SEEK_SET) < 0)
268 			err(1, "lseek");
269 		n = read(from, elf_segments, memory_needed);
270 		if (n != memory_needed)
271 			err(1, "%s: reading ELF segments", from_file);
272 		elf_load_image_segment = -1;
273 		for (i = 0; i < header_count; i++) {
274 			if (ELFGET32(elf_segments[i].p_filesz) &&
275 			    ELFGET32(elf_segments[i].p_flags) & PF_X) {
276 				if (elf_load_image_segment != -1)
277 					errx(1, "%s: more than one ELF program "
278 					     "segment", from_file);
279 				elf_load_image_segment = i;
280 			}
281 		}
282 		if (elf_load_image_segment == -1)
283 			errx(1, "%s: no suitable ELF program segment",
284 			     from_file);
285 		entry = ELFGET32(elf_header.e_entry) +
286 			ELFGET32(elf_segments[elf_load_image_segment].p_offset) -
287 			ELFGET32(elf_segments[elf_load_image_segment].p_vaddr);
288 	} else if (*(uint8_t *)&ex == 0x1f && ((uint8_t *)&ex)[1] == 0x8b) {
289 		entry = 0;
290 	} else
291 		errx(1, "%s: bad magic number", from_file);
292 
293 	entry += sizeof(load);
294 	lseek(to, sizeof(load), SEEK_CUR);
295 
296 	total = 0;
297 	n = sizeof(buf) - sizeof(load);
298 	/* copy the whole file */
299 	for (lseek(from, 0, SEEK_SET); ; n = sizeof(buf)) {
300 		memset(buf, 0, sizeof(buf));
301 		if ((n = read(from, buf, n)) < 0)
302 			err(1, "%s", from_file);
303 		else if (n == 0)
304 			break;
305 
306 		if (write(to, buf, n) != n)
307 			err(1, "%s", to_file);
308 
309 		total += n;
310 		check_sum = cksum(check_sum, (int *)buf, n);
311 	}
312 
313 	/* load header */
314 	load.address = htobe32(loadpoint + sizeof(load));
315 	load.count = htobe32(4 + total);
316 	check_sum = cksum(check_sum, (int *)&load, sizeof(load));
317 
318 	if (verbose)
319 		warnx("wrote %d bytes of file \'%s\'", total, from_file);
320 
321 	total += sizeof(load);
322 	/* insert the header */
323 	lseek(to, -total, SEEK_CUR);
324 	if (write(to, &load, sizeof(load)) != sizeof(load))
325 		err(1, "%s", to_file);
326 	lseek(to, total - sizeof(load), SEEK_CUR);
327 
328 	memset(buf, 0, sizeof(buf));
329 	/* pad to int */
330 	n = sizeof(int) - total % sizeof(int);
331 	if (total % sizeof(int)) {
332 		if (write(to, buf, n) != n)
333 			err(1, "%s", to_file);
334 		else
335 			total += n;
336 	}
337 
338 	/* pad to the blocksize */
339 	n = sizeof(buf) - total % sizeof(buf);
340 
341 	if (n < sizeof(int)) {
342 		n += sizeof(buf);
343 		total += sizeof(buf);
344 	} else
345 		total += n;
346 
347 	/* TODO should pad here to the 65k boundary for tape boot */
348 
349 	if (verbose)
350 		warnx("checksum is 0x%08x", -check_sum);
351 
352 	check_sum = htobe32(-check_sum);
353 	if (write(to, &check_sum, sizeof(int)) != sizeof(int))
354 		err(1, "%s", to_file);
355 
356 	n -= sizeof(int);
357 
358 	if (write(to, buf, n) != n)
359 		err(1, "%s", to_file);
360 
361 	if (close(from) < 0)
362 		err(1, "%s", from_file);
363 
364 	free(elf_segments);
365 	return total;
366 }
367 
368 int
369 cksum(int ck, int *p, int size)
370 {
371 	/* we assume size is int-aligned */
372 	for (size = (size + sizeof(int) - 1) / sizeof(int); size--; p++ )
373 		ck += be32toh(*p);
374 
375 	return ck;
376 }
377 
378 void __dead
379 usage(void)
380 {
381 	fprintf(stderr,
382 	    "Usage: %s [-v] [-l <loadpoint>] [-t <timestamp>] prog1 {progN} outfile\n",
383 	    getprogname());
384 	exit(1);
385 }
386 
387 char *
388 lifname(char *str)
389 {
390 	static char lname[10] = "XXXXXXXXXX";
391 	char *cp;
392 	int i;
393 
394 	cp = strrchr(str, '/');
395 	if (cp != NULL) {
396 		str = cp + 1;
397 	}
398 	for (i = 0; i < 9; i++) {
399 		if (islower(*str))
400 			lname[i] = toupper(*str);
401 		else if (isalnum(*str) || *str == '_')
402 			lname[i] = *str;
403 		else
404 			break;
405 		str++;
406 	}
407 	for ( ; i < 10; i++)
408 		lname[i] = ' ';
409 	return(lname);
410 }
411 
412 
413 void
414 bcddate(char *file, char *toc)
415 {
416 	struct stat statb;
417 	struct tm *tm;
418 
419 	if (repro_epoch)
420 		tm = gmtime(&repro_epoch);
421 	else {
422 		stat(file, &statb);
423 		tm = localtime(&statb.st_ctime);
424 	}
425 	tm->tm_year %= 100;
426 	*toc = (tm->tm_year / 10) << 4;
427 	*toc++ |= tm->tm_year % 10;
428 	*toc = ((tm->tm_mon+1) / 10) << 4;
429 	*toc++ |= (tm->tm_mon+1) % 10;
430 	*toc = (tm->tm_mday / 10) << 4;
431 	*toc++ |= tm->tm_mday % 10;
432 	*toc = (tm->tm_hour / 10) << 4;
433 	*toc++ |= tm->tm_hour % 10;
434 	*toc = (tm->tm_min / 10) << 4;
435 	*toc++ |= tm->tm_min % 10;
436 	*toc = (tm->tm_sec / 10) << 4;
437 	*toc |= tm->tm_sec % 10;
438 }
439