]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/kldxref/kldxref.c
Merge lldb trunk r338150, and resolve conflicts.
[FreeBSD/FreeBSD.git] / usr.sbin / kldxref / kldxref.c
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 2000, Boris Popov
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
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.
21  *
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
32  * SUCH DAMAGE.
33  *
34  * $FreeBSD$
35  */
36
37 #include <sys/types.h>
38 #include <sys/param.h>
39 #include <sys/endian.h>
40 #include <sys/exec.h>
41 #include <sys/queue.h>
42 #include <sys/kernel.h>
43 #include <sys/reboot.h>
44 #include <sys/linker.h>
45 #include <sys/stat.h>
46 #include <sys/module.h>
47 #define FREEBSD_ELF
48
49 #include <err.h>
50 #include <errno.h>
51 #include <fts.h>
52 #include <stdbool.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57 #include <machine/elf.h>
58
59 #include "ef.h"
60
61 #define MAXRECSIZE      (64 << 10)      /* 64k */
62 #define check(val)      if ((error = (val)) != 0) break
63
64 static bool dflag;      /* do not create a hint file, only write on stdout */
65 static int verbose;
66
67 static FILE *fxref;     /* current hints file */
68
69 static const char *xref_file = "linker.hints";
70
71 /*
72  * A record is stored in the static buffer recbuf before going to disk.
73  */
74 static char recbuf[MAXRECSIZE];
75 static int recpos;      /* current write position */
76 static int reccnt;      /* total record written to this file so far */
77
78 static void
79 intalign(void)
80 {
81
82         recpos = roundup2(recpos, sizeof(int));
83 }
84
85 static void
86 record_start(void)
87 {
88
89         recpos = 0;
90         memset(recbuf, 0, MAXRECSIZE);
91 }
92
93 static int
94 record_end(void)
95 {
96
97         if (recpos == 0)
98                 return (0);
99         reccnt++;
100         intalign();
101         fwrite(&recpos, sizeof(recpos), 1, fxref);
102         return (fwrite(recbuf, recpos, 1, fxref) != 1 ? errno : 0);
103 }
104
105 static int
106 record_buf(const void *buf, size_t size)
107 {
108
109         if (MAXRECSIZE - recpos < size)
110                 errx(1, "record buffer overflow");
111         memcpy(recbuf + recpos, buf, size);
112         recpos += size;
113         return (0);
114 }
115
116 /*
117  * An int is stored in host order and aligned
118  */
119 static int
120 record_int(int val)
121 {
122
123         intalign();
124         return (record_buf(&val, sizeof(val)));
125 }
126
127 /*
128  * A string is stored as 1-byte length plus data, no padding
129  */
130 static int
131 record_string(const char *str)
132 {
133         int error;
134         size_t len;
135         u_char val;
136         
137         if (dflag)
138                 return (0);
139         val = len = strlen(str);
140         if (len > 255)
141                 errx(1, "string %s too long", str);
142         error = record_buf(&val, sizeof(val));
143         if (error != 0)
144                 return (error);
145         return (record_buf(str, len));
146 }
147
148 /* From sys/isa/pnp.c */
149 static char *
150 pnp_eisaformat(uint32_t id)
151 {
152         uint8_t *data;
153         static char idbuf[8];
154         const char  hextoascii[] = "0123456789abcdef";
155
156         id = htole32(id);
157         data = (uint8_t *)&id;
158         idbuf[0] = '@' + ((data[0] & 0x7c) >> 2);
159         idbuf[1] = '@' + (((data[0] & 0x3) << 3) + ((data[1] & 0xe0) >> 5));
160         idbuf[2] = '@' + (data[1] & 0x1f);
161         idbuf[3] = hextoascii[(data[2] >> 4)];
162         idbuf[4] = hextoascii[(data[2] & 0xf)];
163         idbuf[5] = hextoascii[(data[3] >> 4)];
164         idbuf[6] = hextoascii[(data[3] & 0xf)];
165         idbuf[7] = 0;
166         return (idbuf);
167 }
168
169 struct pnp_elt
170 {
171         int     pe_kind;        /* What kind of entry */
172 #define TYPE_SZ_MASK    0x0f
173 #define TYPE_FLAGGED    0x10    /* all f's is a wildcard */
174 #define TYPE_INT        0x20    /* Is a number */
175 #define TYPE_PAIRED     0x40
176 #define TYPE_LE         0x80    /* Matches <= this value */
177 #define TYPE_GE         0x100   /* Matches >= this value */
178 #define TYPE_MASK       0x200   /* Specifies a mask to follow */
179 #define TYPE_U8         (1 | TYPE_INT)
180 #define TYPE_V8         (1 | TYPE_INT | TYPE_FLAGGED)
181 #define TYPE_G16        (2 | TYPE_INT | TYPE_GE)
182 #define TYPE_L16        (2 | TYPE_INT | TYPE_LE)
183 #define TYPE_M16        (2 | TYPE_INT | TYPE_MASK)
184 #define TYPE_U16        (2 | TYPE_INT)
185 #define TYPE_V16        (2 | TYPE_INT | TYPE_FLAGGED)
186 #define TYPE_U32        (4 | TYPE_INT)
187 #define TYPE_V32        (4 | TYPE_INT | TYPE_FLAGGED)
188 #define TYPE_W32        (4 | TYPE_INT | TYPE_PAIRED)
189 #define TYPE_D          7
190 #define TYPE_Z          8
191 #define TYPE_P          9
192 #define TYPE_E          10
193 #define TYPE_T          11
194         int     pe_offset;      /* Offset within the element */
195         char *  pe_key;         /* pnp key name */
196         TAILQ_ENTRY(pnp_elt) next; /* Link */
197 };
198 typedef TAILQ_HEAD(pnp_head, pnp_elt) pnp_list;
199
200 /*
201  * this function finds the data from the pnp table, as described by the
202  * the description and creates a new output (new_desc). This output table
203  * is a form that's easier for the agent that's automatically loading the
204  * modules.
205  *
206  * The format output is the simplified string from this routine in the
207  * same basic format as the pnp string, as documented in sys/module.h.
208  * First a string describing the format is output, the a count of the
209  * number of records, then each record. The format string also describes
210  * the length of each entry (though it isn't a fixed length when strings
211  * are present).
212  *
213  *      type    Output          Meaning
214  *      I       uint32_t        Integer equality comparison
215  *      J       uint32_t        Pair of uint16_t fields converted to native
216  *                              byte order. The two fields both must match.
217  *      G       uint32_t        Greater than or equal to
218  *      L       uint32_t        Less than or equal to
219  *      M       uint32_t        Mask of which fields to test. Fields that
220  *                              take up space increment the count. This
221  *                              field must be first, and resets the count.
222  *      D       string          Description of the device this pnp info is for
223  *      Z       string          pnp string must match this
224  *      T       nothing         T fields set pnp values that must be true for
225  *                              the entire table.
226  * Values are packed the same way that other values are packed in this file.
227  * Strings and int32_t's start on a 32-bit boundary and are padded with 0
228  * bytes. Objects that are smaller than uint32_t are converted, without
229  * sign extension to uint32_t to simplify parsing downstream.
230  */
231 static int
232 parse_pnp_list(const char *desc, char **new_desc, pnp_list *list)
233 {
234         const char *walker, *ep;
235         const char *colon, *semi;
236         struct pnp_elt *elt;
237         char *nd;
238         char type[8], key[32];
239         int off;
240
241         walker = desc;
242         ep = desc + strlen(desc);
243         off = 0;
244         nd = *new_desc = malloc(strlen(desc) + 1);
245         if (verbose > 1)
246                 printf("Converting %s into a list\n", desc);
247         while (walker < ep) {
248                 colon = strchr(walker, ':');
249                 semi = strchr(walker, ';');
250                 if (semi != NULL && semi < colon)
251                         goto err;
252                 if (colon - walker > sizeof(type))
253                         goto err;
254                 strncpy(type, walker, colon - walker);
255                 type[colon - walker] = '\0';
256                 if (semi != NULL) {
257                         if (semi - colon >= sizeof(key))
258                                 goto err;
259                         strncpy(key, colon + 1, semi - colon - 1);
260                         key[semi - colon - 1] = '\0';
261                         walker = semi + 1;
262                 } else {
263                         if (strlen(colon + 1) >= sizeof(key))
264                                 goto err;
265                         strcpy(key, colon + 1);
266                         walker = ep;
267                 }
268                 if (verbose > 1)
269                         printf("Found type %s for name %s\n", type, key);
270                 /* Skip pointer place holders */
271                 if (strcmp(type, "P") == 0) {
272                         off += sizeof(void *);
273                         continue;
274                 }
275
276                 /*
277                  * Add a node of the appropriate type
278                  */
279                 elt = malloc(sizeof(struct pnp_elt) + strlen(key) + 1);
280                 TAILQ_INSERT_TAIL(list, elt, next);
281                 elt->pe_key = (char *)(elt + 1);
282                 elt->pe_offset = off;
283                 if (strcmp(type, "U8") == 0)
284                         elt->pe_kind = TYPE_U8;
285                 else if (strcmp(type, "V8") == 0)
286                         elt->pe_kind = TYPE_V8;
287                 else if (strcmp(type, "G16") == 0)
288                         elt->pe_kind = TYPE_G16;
289                 else if (strcmp(type, "L16") == 0)
290                         elt->pe_kind = TYPE_L16;
291                 else if (strcmp(type, "M16") == 0)
292                         elt->pe_kind = TYPE_M16;
293                 else if (strcmp(type, "U16") == 0)
294                         elt->pe_kind = TYPE_U16;
295                 else if (strcmp(type, "V16") == 0)
296                         elt->pe_kind = TYPE_V16;
297                 else if (strcmp(type, "U32") == 0)
298                         elt->pe_kind = TYPE_U32;
299                 else if (strcmp(type, "V32") == 0)
300                         elt->pe_kind = TYPE_V32;
301                 else if (strcmp(type, "W32") == 0)
302                         elt->pe_kind = TYPE_W32;
303                 else if (strcmp(type, "D") == 0)        /* description char * */
304                         elt->pe_kind = TYPE_D;
305                 else if (strcmp(type, "Z") == 0)        /* char * to match */
306                         elt->pe_kind = TYPE_Z;
307                 else if (strcmp(type, "P") == 0)        /* Pointer -- ignored */
308                         elt->pe_kind = TYPE_P;
309                 else if (strcmp(type, "E") == 0)        /* EISA PNP ID, as uint32_t */
310                         elt->pe_kind = TYPE_E;
311                 else if (strcmp(type, "T") == 0)
312                         elt->pe_kind = TYPE_T;
313                 else
314                         goto err;
315                 /*
316                  * Maybe the rounding here needs to be more nuanced and/or somehow
317                  * architecture specific. Fortunately, most tables in the system
318                  * have sane ordering of types.
319                  */
320                 if (elt->pe_kind & TYPE_INT) {
321                         elt->pe_offset = roundup2(elt->pe_offset, elt->pe_kind & TYPE_SZ_MASK);
322                         off = elt->pe_offset + (elt->pe_kind & TYPE_SZ_MASK);
323                 } else if (elt->pe_kind == TYPE_E) {
324                         /* Type E stored as Int, displays as string */
325                         elt->pe_offset = roundup2(elt->pe_offset, sizeof(uint32_t));
326                         off = elt->pe_offset + sizeof(uint32_t);
327                 } else if (elt->pe_kind == TYPE_T) {
328                         /* doesn't actually consume space in the table */
329                         off = elt->pe_offset;
330                 } else {
331                         elt->pe_offset = roundup2(elt->pe_offset, sizeof(void *));
332                         off = elt->pe_offset + sizeof(void *);
333                 }
334                 if (elt->pe_kind & TYPE_PAIRED) {
335                         char *word, *ctx;
336
337                         for (word = strtok_r(key, "/", &ctx);
338                              word; word = strtok_r(NULL, "/", &ctx)) {
339                                 sprintf(nd, "%c:%s;", elt->pe_kind & TYPE_FLAGGED ? 'J' : 'I',
340                                     word);
341                                 nd += strlen(nd);
342                         }
343                         
344                 }
345                 else {
346                         if (elt->pe_kind & TYPE_FLAGGED)
347                                 *nd++ = 'J';
348                         else if (elt->pe_kind & TYPE_GE)
349                                 *nd++ = 'G';
350                         else if (elt->pe_kind & TYPE_LE)
351                                 *nd++ = 'L';
352                         else if (elt->pe_kind & TYPE_MASK)
353                                 *nd++ = 'M';
354                         else if (elt->pe_kind & TYPE_INT)
355                                 *nd++ = 'I';
356                         else if (elt->pe_kind == TYPE_D)
357                                 *nd++ = 'D';
358                         else if (elt->pe_kind == TYPE_Z || elt->pe_kind == TYPE_E)
359                                 *nd++ = 'Z';
360                         else if (elt->pe_kind == TYPE_T)
361                                 *nd++ = 'T';
362                         else
363                                 errx(1, "Impossible type %x\n", elt->pe_kind);
364                         *nd++ = ':';
365                         strcpy(nd, key);
366                         nd += strlen(nd);
367                         *nd++ = ';';
368                 }
369         }
370         *nd++ = '\0';
371         return (0);
372 err:
373         errx(1, "Parse error of description string %s", desc);
374 }
375
376 static int
377 parse_entry(struct mod_metadata *md, const char *cval,
378     struct elf_file *ef, const char *kldname)
379 {
380         struct mod_depend mdp;
381         struct mod_version mdv;
382         struct mod_pnp_match_info pnp;
383         char descr[1024];
384         Elf_Off data;
385         int error, i;
386         size_t len;
387         char *walker;
388         void *table;
389
390         data = (Elf_Off)md->md_data;
391         error = 0;
392         record_start();
393         switch (md->md_type) {
394         case MDT_DEPEND:
395                 if (!dflag)
396                         break;
397                 check(EF_SEG_READ(ef, data, sizeof(mdp), &mdp));
398                 printf("  depends on %s.%d (%d,%d)\n", cval,
399                     mdp.md_ver_preferred, mdp.md_ver_minimum, mdp.md_ver_maximum);
400                 break;
401         case MDT_VERSION:
402                 check(EF_SEG_READ(ef, data, sizeof(mdv), &mdv));
403                 if (dflag) {
404                         printf("  interface %s.%d\n", cval, mdv.mv_version);
405                 } else {
406                         record_int(MDT_VERSION);
407                         record_string(cval);
408                         record_int(mdv.mv_version);
409                         record_string(kldname);
410                 }
411                 break;
412         case MDT_MODULE:
413                 if (dflag) {
414                         printf("  module %s\n", cval);
415                 } else {
416                         record_int(MDT_MODULE);
417                         record_string(cval);
418                         record_string(kldname);
419                 }
420                 break;
421         case MDT_PNP_INFO:
422                 check(EF_SEG_READ_REL(ef, data, sizeof(pnp), &pnp));
423                 check(EF_SEG_READ_STRING(ef, (Elf_Off)pnp.descr, sizeof(descr), descr));
424                 descr[sizeof(descr) - 1] = '\0';
425                 if (dflag) {
426                         printf("  pnp info for bus %s format %s %d entries of %d bytes\n",
427                             cval, descr, pnp.num_entry, pnp.entry_len);
428                 } else {
429                         pnp_list list;
430                         struct pnp_elt *elt, *elt_tmp;
431                         char *new_descr;
432
433                         if (verbose > 1)
434                                 printf("  pnp info for bus %s format %s %d entries of %d bytes\n",
435                                     cval, descr, pnp.num_entry, pnp.entry_len);
436                         /*
437                          * Parse descr to weed out the chaff and to create a list
438                          * of offsets to output.
439                          */
440                         TAILQ_INIT(&list);
441                         parse_pnp_list(descr, &new_descr, &list);
442                         record_int(MDT_PNP_INFO);
443                         record_string(cval);
444                         record_string(new_descr);
445                         record_int(pnp.num_entry);
446                         len = pnp.num_entry * pnp.entry_len;
447                         walker = table = malloc(len);
448                         check(EF_SEG_READ_REL(ef, (Elf_Off)pnp.table, len, table));
449
450                         /*
451                          * Walk the list and output things. We've collapsed all the
452                          * variant forms of the table down to just ints and strings.
453                          */
454                         for (i = 0; i < pnp.num_entry; i++) {
455                                 TAILQ_FOREACH(elt, &list, next) {
456                                         uint8_t v1;
457                                         uint16_t v2;
458                                         uint32_t v4;
459                                         int     value;
460                                         char buffer[1024];
461
462                                         if (elt->pe_kind == TYPE_W32) {
463                                                 memcpy(&v4, walker + elt->pe_offset, sizeof(v4));
464                                                 value = v4 & 0xffff;
465                                                 record_int(value);
466                                                 if (verbose > 1)
467                                                         printf("W32:%#x", value);
468                                                 value = (v4 >> 16) & 0xffff;
469                                                 record_int(value);
470                                                 if (verbose > 1)
471                                                         printf(":%#x;", value);
472                                         } else if (elt->pe_kind & TYPE_INT) {
473                                                 switch (elt->pe_kind & TYPE_SZ_MASK) {
474                                                 case 1:
475                                                         memcpy(&v1, walker + elt->pe_offset, sizeof(v1));
476                                                         if ((elt->pe_kind & TYPE_FLAGGED) && v1 == 0xff)
477                                                                 value = -1;
478                                                         else
479                                                                 value = v1;
480                                                         break;
481                                                 case 2:
482                                                         memcpy(&v2, walker + elt->pe_offset, sizeof(v2));
483                                                         if ((elt->pe_kind & TYPE_FLAGGED) && v2 == 0xffff)
484                                                                 value = -1;
485                                                         else
486                                                                 value = v2;
487                                                         break;
488                                                 case 4:
489                                                         memcpy(&v4, walker + elt->pe_offset, sizeof(v4));
490                                                         if ((elt->pe_kind & TYPE_FLAGGED) && v4 == 0xffffffff)
491                                                                 value = -1;
492                                                         else
493                                                                 value = v4;
494                                                         break;
495                                                 default:
496                                                         errx(1, "Invalid size somehow %#x", elt->pe_kind);
497                                                 }
498                                                 if (verbose > 1)
499                                                         printf("I:%#x;", value);
500                                                 record_int(value);
501                                         } else if (elt->pe_kind == TYPE_T) {
502                                                 /* Do nothing */
503                                         } else { /* E, Z or D -- P already filtered */
504                                                 if (elt->pe_kind == TYPE_E) {
505                                                         memcpy(&v4, walker + elt->pe_offset, sizeof(v4));
506                                                         strcpy(buffer, pnp_eisaformat(v4));
507                                                 } else {
508                                                         char *ptr;
509
510                                                         ptr = *(char **)(walker + elt->pe_offset);
511                                                         buffer[0] = '\0';
512                                                         if (ptr != NULL) {
513                                                                 EF_SEG_READ_STRING(ef, (Elf_Off)ptr,
514                                                                     sizeof(buffer), buffer);
515                                                                 buffer[sizeof(buffer) - 1] = '\0';
516                                                         }
517                                                 }
518                                                 if (verbose > 1)
519                                                         printf("%c:%s;", elt->pe_kind == TYPE_E ? 'E' : (elt->pe_kind == TYPE_Z ? 'Z' : 'D'), buffer);
520                                                 record_string(buffer);
521                                         }
522                                 }
523                                 if (verbose > 1)
524                                         printf("\n");
525                                 walker += pnp.entry_len;
526                         }
527                         /* Now free it */
528                         TAILQ_FOREACH_SAFE(elt, &list, next, elt_tmp) {
529                                 TAILQ_REMOVE(&list, elt, next);
530                                 free(elt);
531                         }
532                         free(table);
533                 }
534                 break;
535         default:
536                 warnx("unknown metadata record %d in file %s", md->md_type, kldname);
537         }
538         if (!error)
539                 record_end();
540         return (error);
541 }
542
543 static int
544 read_kld(char *filename, char *kldname)
545 {
546         struct mod_metadata md;
547         struct elf_file ef;
548         void **p, **orgp;
549         int error, eftype;
550         long start, finish, entries;
551         char cval[MAXMODNAME + 1];
552
553         if (verbose || dflag)
554                 printf("%s\n", filename);
555         error = ef_open(filename, &ef, verbose);
556         if (error != 0) {
557                 error = ef_obj_open(filename, &ef, verbose);
558                 if (error != 0) {
559                         if (verbose)
560                                 warnc(error, "elf_open(%s)", filename);
561                         return (error);
562                 }
563         }
564         eftype = EF_GET_TYPE(&ef);
565         if (eftype != EFT_KLD && eftype != EFT_KERNEL)  {
566                 EF_CLOSE(&ef);
567                 return (0);
568         }
569         do {
570                 check(EF_LOOKUP_SET(&ef, MDT_SETNAME, &start, &finish,
571                     &entries));
572                 check(EF_SEG_READ_ENTRY_REL(&ef, start, sizeof(*p) * entries,
573                     (void *)&p));
574                 orgp = p;
575                 while(entries--) {
576                         check(EF_SEG_READ_REL(&ef, (Elf_Off)*p, sizeof(md),
577                             &md));
578                         p++;
579                         check(EF_SEG_READ_STRING(&ef, (Elf_Off)md.md_cval,
580                             sizeof(cval), cval));
581                         parse_entry(&md, cval, &ef, kldname);
582                 }
583                 if (error != 0)
584                         warnc(error, "error while reading %s", filename);
585                 free(orgp);
586         } while(0);
587         EF_CLOSE(&ef);
588         return (error);
589 }
590
591 /*
592  * Create a temp file in directory root, make sure we don't
593  * overflow the buffer for the destination name
594  */
595 static FILE *
596 maketempfile(char *dest, const char *root)
597 {
598         char *p;
599         int n, fd;
600
601         p = strrchr(root, '/');
602         n = p != NULL ? p - root + 1 : 0;
603         if (snprintf(dest, MAXPATHLEN, "%.*slhint.XXXXXX", n, root) >=
604             MAXPATHLEN) {
605                 errno = ENAMETOOLONG;
606                 return (NULL);
607         }
608
609         fd = mkstemp(dest);
610         if (fd < 0)
611                 return (NULL);
612         fchmod(fd, 0644);       /* nothing secret in the file */
613         return (fdopen(fd, "w+"));
614 }
615
616 static char xrefname[MAXPATHLEN], tempname[MAXPATHLEN];
617
618 static void
619 usage(void)
620 {
621
622         fprintf(stderr, "%s\n",
623             "usage: kldxref [-Rdv] [-f hintsfile] path ..."
624         );
625         exit(1);
626 }
627
628 static int
629 compare(const FTSENT *const *a, const FTSENT *const *b)
630 {
631
632         if ((*a)->fts_info == FTS_D && (*b)->fts_info != FTS_D)
633                 return (1);
634         if ((*a)->fts_info != FTS_D && (*b)->fts_info == FTS_D)
635                 return (-1);
636         return (strcmp((*a)->fts_name, (*b)->fts_name));
637 }
638
639 int
640 main(int argc, char *argv[])
641 {
642         FTS *ftsp;
643         FTSENT *p;
644         int opt, fts_options, ival;
645         struct stat sb;
646
647         fts_options = FTS_PHYSICAL;
648
649         while ((opt = getopt(argc, argv, "Rdf:v")) != -1) {
650                 switch (opt) {
651                 case 'd':       /* no hint file, only print on stdout */
652                         dflag = true;
653                         break;
654                 case 'f':       /* use this name instead of linker.hints */
655                         xref_file = optarg;
656                         break;
657                 case 'v':
658                         verbose++;
659                         break;
660                 case 'R':       /* recurse on directories */
661                         fts_options |= FTS_COMFOLLOW;
662                         break;
663                 default:
664                         usage();
665                         /* NOTREACHED */
666                 }
667         }
668         if (argc - optind < 1)
669                 usage();
670         argc -= optind;
671         argv += optind;
672
673         if (stat(argv[0], &sb) != 0)
674                 err(1, "%s", argv[0]);
675         if ((sb.st_mode & S_IFDIR) == 0) {
676                 errno = ENOTDIR;
677                 err(1, "%s", argv[0]);
678         }
679
680         ftsp = fts_open(argv, fts_options, compare);
681         if (ftsp == NULL)
682                 exit(1);
683
684         for (;;) {
685                 p = fts_read(ftsp);
686                 if ((p == NULL || p->fts_info == FTS_D) && fxref) {
687                         /* close and rename the current hint file */
688                         fclose(fxref);
689                         fxref = NULL;
690                         if (reccnt != 0) {
691                                 rename(tempname, xrefname);
692                         } else {
693                                 /* didn't find any entry, ignore this file */
694                                 unlink(tempname);
695                                 unlink(xrefname);
696                         }
697                 }
698                 if (p == NULL)
699                         break;
700                 if (p->fts_info == FTS_D && !dflag) {
701                         /* visiting a new directory, create a new hint file */
702                         snprintf(xrefname, sizeof(xrefname), "%s/%s",
703                             ftsp->fts_path, xref_file);
704                         fxref = maketempfile(tempname, ftsp->fts_path);
705                         if (fxref == NULL)
706                                 err(1, "can't create %s", tempname);
707                         ival = 1;
708                         fwrite(&ival, sizeof(ival), 1, fxref);
709                         reccnt = 0;
710                 }
711                 /* skip non-files and separate debug files */
712                 if (p->fts_info != FTS_F)
713                         continue;
714                 if (p->fts_namelen >= 6 &&
715                     strcmp(p->fts_name + p->fts_namelen - 6, ".debug") == 0)
716                         continue;
717                 if (p->fts_namelen >= 8 &&
718                     strcmp(p->fts_name + p->fts_namelen - 8, ".symbols") == 0)
719                         continue;
720                 read_kld(p->fts_path, p->fts_name);
721         }
722         fts_close(ftsp);
723         return (0);
724 }