2 * SPDX-License-Identifier: BSD-4-Clause
4 * Copyright (c) 2000, Boris Popov
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by Boris Popov.
18 * 4. Neither the name of the author nor the names of any co-contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 #include <sys/types.h>
38 #include <sys/param.h>
39 #include <sys/endian.h>
41 #include <sys/queue.h>
42 #include <sys/kernel.h>
43 #include <sys/reboot.h>
44 #include <sys/linker.h>
46 #include <sys/module.h>
58 #include <machine/elf.h>
62 #define MAXRECSIZE (64 << 10) /* 64k */
63 #define check(val) if ((error = (val)) != 0) break
65 static bool dflag; /* do not create a hint file, only write on stdout */
68 static FILE *fxref; /* current hints file */
70 static const char *xref_file = "linker.hints";
73 * A record is stored in the static buffer recbuf before going to disk.
75 static char recbuf[MAXRECSIZE];
76 static int recpos; /* current write position */
77 static int reccnt; /* total record written to this file so far */
83 recpos = roundup2(recpos, sizeof(int));
91 memset(recbuf, 0, MAXRECSIZE);
102 fwrite(&recpos, sizeof(recpos), 1, fxref);
103 return (fwrite(recbuf, recpos, 1, fxref) != 1 ? errno : 0);
107 record_buf(const void *buf, size_t size)
110 if (MAXRECSIZE - recpos < size)
111 errx(1, "record buffer overflow");
112 memcpy(recbuf + recpos, buf, size);
118 * An int is stored in host order and aligned
125 return (record_buf(&val, sizeof(val)));
129 * A string is stored as 1-byte length plus data, no padding
132 record_string(const char *str)
140 val = len = strlen(str);
142 errx(1, "string %s too long", str);
143 error = record_buf(&val, sizeof(val));
146 return (record_buf(str, len));
149 /* From sys/isa/pnp.c */
151 pnp_eisaformat(uint32_t id)
154 static char idbuf[8];
155 const char hextoascii[] = "0123456789abcdef";
158 data = (uint8_t *)&id;
159 idbuf[0] = '@' + ((data[0] & 0x7c) >> 2);
160 idbuf[1] = '@' + (((data[0] & 0x3) << 3) + ((data[1] & 0xe0) >> 5));
161 idbuf[2] = '@' + (data[1] & 0x1f);
162 idbuf[3] = hextoascii[(data[2] >> 4)];
163 idbuf[4] = hextoascii[(data[2] & 0xf)];
164 idbuf[5] = hextoascii[(data[3] >> 4)];
165 idbuf[6] = hextoascii[(data[3] & 0xf)];
172 int pe_kind; /* What kind of entry */
173 #define TYPE_SZ_MASK 0x0f
174 #define TYPE_FLAGGED 0x10 /* all f's is a wildcard */
175 #define TYPE_INT 0x20 /* Is a number */
176 #define TYPE_PAIRED 0x40
177 #define TYPE_LE 0x80 /* Matches <= this value */
178 #define TYPE_GE 0x100 /* Matches >= this value */
179 #define TYPE_MASK 0x200 /* Specifies a mask to follow */
180 #define TYPE_U8 (1 | TYPE_INT)
181 #define TYPE_V8 (1 | TYPE_INT | TYPE_FLAGGED)
182 #define TYPE_G16 (2 | TYPE_INT | TYPE_GE)
183 #define TYPE_L16 (2 | TYPE_INT | TYPE_LE)
184 #define TYPE_M16 (2 | TYPE_INT | TYPE_MASK)
185 #define TYPE_U16 (2 | TYPE_INT)
186 #define TYPE_V16 (2 | TYPE_INT | TYPE_FLAGGED)
187 #define TYPE_U32 (4 | TYPE_INT)
188 #define TYPE_V32 (4 | TYPE_INT | TYPE_FLAGGED)
189 #define TYPE_W32 (4 | TYPE_INT | TYPE_PAIRED)
195 int pe_offset; /* Offset within the element */
196 char * pe_key; /* pnp key name */
197 TAILQ_ENTRY(pnp_elt) next; /* Link */
199 typedef TAILQ_HEAD(pnp_head, pnp_elt) pnp_list;
202 * this function finds the data from the pnp table, as described by the
203 * the description and creates a new output (new_desc). This output table
204 * is a form that's easier for the agent that's automatically loading the
207 * The format output is the simplified string from this routine in the
208 * same basic format as the pnp string, as documented in sys/module.h.
209 * First a string describing the format is output, the a count of the
210 * number of records, then each record. The format string also describes
211 * the length of each entry (though it isn't a fixed length when strings
214 * type Output Meaning
215 * I uint32_t Integer equality comparison
216 * J uint32_t Pair of uint16_t fields converted to native
217 * byte order. The two fields both must match.
218 * G uint32_t Greater than or equal to
219 * L uint32_t Less than or equal to
220 * M uint32_t Mask of which fields to test. Fields that
221 * take up space increment the count. This
222 * field must be first, and resets the count.
223 * D string Description of the device this pnp info is for
224 * Z string pnp string must match this
225 * T nothing T fields set pnp values that must be true for
227 * Values are packed the same way that other values are packed in this file.
228 * Strings and int32_t's start on a 32-bit boundary and are padded with 0
229 * bytes. Objects that are smaller than uint32_t are converted, without
230 * sign extension to uint32_t to simplify parsing downstream.
233 parse_pnp_list(const char *desc, char **new_desc, pnp_list *list)
235 const char *walker, *ep;
236 const char *colon, *semi;
239 char type[8], key[32];
243 ep = desc + strlen(desc);
245 nd = *new_desc = malloc(strlen(desc) + 1);
247 printf("Converting %s into a list\n", desc);
248 while (walker < ep) {
249 colon = strchr(walker, ':');
250 semi = strchr(walker, ';');
251 if (semi != NULL && semi < colon)
253 if (colon - walker > sizeof(type))
255 strncpy(type, walker, colon - walker);
256 type[colon - walker] = '\0';
258 if (semi - colon >= sizeof(key))
260 strncpy(key, colon + 1, semi - colon - 1);
261 key[semi - colon - 1] = '\0';
263 /* Fail safe if we have spaces after ; */
264 while (walker < ep && isspace(*walker))
267 if (strlen(colon + 1) >= sizeof(key))
269 strcpy(key, colon + 1);
273 printf("Found type %s for name %s\n", type, key);
274 /* Skip pointer place holders */
275 if (strcmp(type, "P") == 0) {
276 off += sizeof(void *);
281 * Add a node of the appropriate type
283 elt = malloc(sizeof(struct pnp_elt) + strlen(key) + 1);
284 TAILQ_INSERT_TAIL(list, elt, next);
285 elt->pe_key = (char *)(elt + 1);
286 elt->pe_offset = off;
287 if (strcmp(type, "U8") == 0)
288 elt->pe_kind = TYPE_U8;
289 else if (strcmp(type, "V8") == 0)
290 elt->pe_kind = TYPE_V8;
291 else if (strcmp(type, "G16") == 0)
292 elt->pe_kind = TYPE_G16;
293 else if (strcmp(type, "L16") == 0)
294 elt->pe_kind = TYPE_L16;
295 else if (strcmp(type, "M16") == 0)
296 elt->pe_kind = TYPE_M16;
297 else if (strcmp(type, "U16") == 0)
298 elt->pe_kind = TYPE_U16;
299 else if (strcmp(type, "V16") == 0)
300 elt->pe_kind = TYPE_V16;
301 else if (strcmp(type, "U32") == 0)
302 elt->pe_kind = TYPE_U32;
303 else if (strcmp(type, "V32") == 0)
304 elt->pe_kind = TYPE_V32;
305 else if (strcmp(type, "W32") == 0)
306 elt->pe_kind = TYPE_W32;
307 else if (strcmp(type, "D") == 0) /* description char * */
308 elt->pe_kind = TYPE_D;
309 else if (strcmp(type, "Z") == 0) /* char * to match */
310 elt->pe_kind = TYPE_Z;
311 else if (strcmp(type, "P") == 0) /* Pointer -- ignored */
312 elt->pe_kind = TYPE_P;
313 else if (strcmp(type, "E") == 0) /* EISA PNP ID, as uint32_t */
314 elt->pe_kind = TYPE_E;
315 else if (strcmp(type, "T") == 0)
316 elt->pe_kind = TYPE_T;
320 * Maybe the rounding here needs to be more nuanced and/or somehow
321 * architecture specific. Fortunately, most tables in the system
322 * have sane ordering of types.
324 if (elt->pe_kind & TYPE_INT) {
325 elt->pe_offset = roundup2(elt->pe_offset, elt->pe_kind & TYPE_SZ_MASK);
326 off = elt->pe_offset + (elt->pe_kind & TYPE_SZ_MASK);
327 } else if (elt->pe_kind == TYPE_E) {
328 /* Type E stored as Int, displays as string */
329 elt->pe_offset = roundup2(elt->pe_offset, sizeof(uint32_t));
330 off = elt->pe_offset + sizeof(uint32_t);
331 } else if (elt->pe_kind == TYPE_T) {
332 /* doesn't actually consume space in the table */
333 off = elt->pe_offset;
335 elt->pe_offset = roundup2(elt->pe_offset, sizeof(void *));
336 off = elt->pe_offset + sizeof(void *);
338 if (elt->pe_kind & TYPE_PAIRED) {
341 for (word = strtok_r(key, "/", &ctx);
342 word; word = strtok_r(NULL, "/", &ctx)) {
343 sprintf(nd, "%c:%s;", elt->pe_kind & TYPE_FLAGGED ? 'J' : 'I',
350 if (elt->pe_kind & TYPE_FLAGGED)
352 else if (elt->pe_kind & TYPE_GE)
354 else if (elt->pe_kind & TYPE_LE)
356 else if (elt->pe_kind & TYPE_MASK)
358 else if (elt->pe_kind & TYPE_INT)
360 else if (elt->pe_kind == TYPE_D)
362 else if (elt->pe_kind == TYPE_Z || elt->pe_kind == TYPE_E)
364 else if (elt->pe_kind == TYPE_T)
367 errx(1, "Impossible type %x\n", elt->pe_kind);
377 errx(1, "Parse error of description string %s", desc);
381 parse_entry(struct mod_metadata *md, const char *cval,
382 struct elf_file *ef, const char *kldname)
384 struct mod_depend mdp;
385 struct mod_version mdv;
386 struct mod_pnp_match_info pnp;
394 data = (Elf_Off)md->md_data;
397 switch (md->md_type) {
401 check(EF_SEG_READ(ef, data, sizeof(mdp), &mdp));
402 printf(" depends on %s.%d (%d,%d)\n", cval,
403 mdp.md_ver_preferred, mdp.md_ver_minimum, mdp.md_ver_maximum);
406 check(EF_SEG_READ(ef, data, sizeof(mdv), &mdv));
408 printf(" interface %s.%d\n", cval, mdv.mv_version);
410 record_int(MDT_VERSION);
412 record_int(mdv.mv_version);
413 record_string(kldname);
418 printf(" module %s\n", cval);
420 record_int(MDT_MODULE);
422 record_string(kldname);
426 check(EF_SEG_READ_REL(ef, data, sizeof(pnp), &pnp));
427 check(EF_SEG_READ_STRING(ef, (Elf_Off)pnp.descr, sizeof(descr), descr));
428 descr[sizeof(descr) - 1] = '\0';
430 printf(" pnp info for bus %s format %s %d entries of %d bytes\n",
431 cval, descr, pnp.num_entry, pnp.entry_len);
434 struct pnp_elt *elt, *elt_tmp;
438 printf(" pnp info for bus %s format %s %d entries of %d bytes\n",
439 cval, descr, pnp.num_entry, pnp.entry_len);
441 * Parse descr to weed out the chaff and to create a list
442 * of offsets to output.
445 parse_pnp_list(descr, &new_descr, &list);
446 record_int(MDT_PNP_INFO);
448 record_string(new_descr);
449 record_int(pnp.num_entry);
450 len = pnp.num_entry * pnp.entry_len;
451 walker = table = malloc(len);
452 check(EF_SEG_READ_REL(ef, (Elf_Off)pnp.table, len, table));
455 * Walk the list and output things. We've collapsed all the
456 * variant forms of the table down to just ints and strings.
458 for (i = 0; i < pnp.num_entry; i++) {
459 TAILQ_FOREACH(elt, &list, next) {
466 if (elt->pe_kind == TYPE_W32) {
467 memcpy(&v4, walker + elt->pe_offset, sizeof(v4));
471 printf("W32:%#x", value);
472 value = (v4 >> 16) & 0xffff;
475 printf(":%#x;", value);
476 } else if (elt->pe_kind & TYPE_INT) {
477 switch (elt->pe_kind & TYPE_SZ_MASK) {
479 memcpy(&v1, walker + elt->pe_offset, sizeof(v1));
480 if ((elt->pe_kind & TYPE_FLAGGED) && v1 == 0xff)
486 memcpy(&v2, walker + elt->pe_offset, sizeof(v2));
487 if ((elt->pe_kind & TYPE_FLAGGED) && v2 == 0xffff)
493 memcpy(&v4, walker + elt->pe_offset, sizeof(v4));
494 if ((elt->pe_kind & TYPE_FLAGGED) && v4 == 0xffffffff)
500 errx(1, "Invalid size somehow %#x", elt->pe_kind);
503 printf("I:%#x;", value);
505 } else if (elt->pe_kind == TYPE_T) {
507 } else { /* E, Z or D -- P already filtered */
508 if (elt->pe_kind == TYPE_E) {
509 memcpy(&v4, walker + elt->pe_offset, sizeof(v4));
510 strcpy(buffer, pnp_eisaformat(v4));
514 ptr = *(char **)(walker + elt->pe_offset);
517 EF_SEG_READ_STRING(ef, (Elf_Off)ptr,
518 sizeof(buffer), buffer);
519 buffer[sizeof(buffer) - 1] = '\0';
523 printf("%c:%s;", elt->pe_kind == TYPE_E ? 'E' : (elt->pe_kind == TYPE_Z ? 'Z' : 'D'), buffer);
524 record_string(buffer);
529 walker += pnp.entry_len;
532 TAILQ_FOREACH_SAFE(elt, &list, next, elt_tmp) {
533 TAILQ_REMOVE(&list, elt, next);
540 warnx("unknown metadata record %d in file %s", md->md_type, kldname);
548 read_kld(char *filename, char *kldname)
550 struct mod_metadata md;
554 long start, finish, entries, i;
555 char cval[MAXMODNAME + 1];
557 if (verbose || dflag)
558 printf("%s\n", filename);
559 error = ef_open(filename, &ef, verbose);
561 error = ef_obj_open(filename, &ef, verbose);
564 warnc(error, "elf_open(%s)", filename);
568 eftype = EF_GET_TYPE(&ef);
569 if (eftype != EFT_KLD && eftype != EFT_KERNEL) {
574 check(EF_LOOKUP_SET(&ef, MDT_SETNAME, &start, &finish,
576 check(EF_SEG_READ_ENTRY_REL(&ef, start, sizeof(*p) * entries,
579 * Do a first pass to find MDT_MODULE. It is required to be
580 * ordered first in the output linker.hints stream because it
581 * serves as an implicit record boundary between distinct klds
582 * in the stream. Other MDTs only make sense in the context of
583 * a specific MDT_MODULE.
585 * Some compilers (e.g., GCC 6.4.0 xtoolchain) or binutils
586 * (e.g., GNU binutils 2.32 objcopy/ld.bfd) can reorder
587 * MODULE_METADATA set entries relative to the source ordering.
588 * This is permitted by the C standard; memory layout of
589 * file-scope objects is left implementation-defined. There is
590 * no requirement that source code ordering is retained.
592 * Handle that here by taking two passes to ensure MDT_MODULE
593 * records are emitted to linker.hints before other MDT records
596 for (i = 0; i < entries; i++) {
597 check(EF_SEG_READ_REL(&ef, (Elf_Off)p[i], sizeof(md),
599 check(EF_SEG_READ_STRING(&ef, (Elf_Off)md.md_cval,
600 sizeof(cval), cval));
601 if (md.md_type == MDT_MODULE) {
602 parse_entry(&md, cval, &ef, kldname);
607 warnc(error, "error while reading %s", filename);
612 * Second pass for all !MDT_MODULE entries.
614 for (i = 0; i < entries; i++) {
615 check(EF_SEG_READ_REL(&ef, (Elf_Off)p[i], sizeof(md),
617 check(EF_SEG_READ_STRING(&ef, (Elf_Off)md.md_cval,
618 sizeof(cval), cval));
619 if (md.md_type != MDT_MODULE)
620 parse_entry(&md, cval, &ef, kldname);
623 warnc(error, "error while reading %s", filename);
631 * Create a temp file in directory root, make sure we don't
632 * overflow the buffer for the destination name
635 maketempfile(char *dest, const char *root)
640 p = strrchr(root, '/');
641 n = p != NULL ? p - root + 1 : 0;
642 if (snprintf(dest, MAXPATHLEN, "%.*slhint.XXXXXX", n, root) >=
644 errno = ENAMETOOLONG;
651 fchmod(fd, 0644); /* nothing secret in the file */
652 return (fdopen(fd, "w+"));
655 static char xrefname[MAXPATHLEN], tempname[MAXPATHLEN];
661 fprintf(stderr, "%s\n",
662 "usage: kldxref [-Rdv] [-f hintsfile] path ..."
668 compare(const FTSENT *const *a, const FTSENT *const *b)
671 if ((*a)->fts_info == FTS_D && (*b)->fts_info != FTS_D)
673 if ((*a)->fts_info != FTS_D && (*b)->fts_info == FTS_D)
675 return (strcmp((*a)->fts_name, (*b)->fts_name));
679 main(int argc, char *argv[])
683 int opt, fts_options, ival;
686 fts_options = FTS_PHYSICAL;
688 while ((opt = getopt(argc, argv, "Rdf:v")) != -1) {
690 case 'd': /* no hint file, only print on stdout */
693 case 'f': /* use this name instead of linker.hints */
699 case 'R': /* recurse on directories */
700 fts_options |= FTS_COMFOLLOW;
707 if (argc - optind < 1)
712 if (stat(argv[0], &sb) != 0)
713 err(1, "%s", argv[0]);
714 if ((sb.st_mode & S_IFDIR) == 0) {
716 err(1, "%s", argv[0]);
719 ftsp = fts_open(argv, fts_options, compare);
725 if ((p == NULL || p->fts_info == FTS_D) && fxref) {
726 /* close and rename the current hint file */
730 rename(tempname, xrefname);
732 /* didn't find any entry, ignore this file */
739 if (p->fts_info == FTS_D && !dflag) {
740 /* visiting a new directory, create a new hint file */
741 snprintf(xrefname, sizeof(xrefname), "%s/%s",
742 ftsp->fts_path, xref_file);
743 fxref = maketempfile(tempname, ftsp->fts_path);
745 err(1, "can't create %s", tempname);
747 fwrite(&ival, sizeof(ival), 1, fxref);
750 /* skip non-files and separate debug files */
751 if (p->fts_info != FTS_F)
753 if (p->fts_namelen >= 6 &&
754 strcmp(p->fts_name + p->fts_namelen - 6, ".debug") == 0)
756 if (p->fts_namelen >= 8 &&
757 strcmp(p->fts_name + p->fts_namelen - 8, ".symbols") == 0)
759 read_kld(p->fts_path, p->fts_name);