xref: /openbsd/usr.bin/mandoc/mandocdb.c (revision 09467b48)
1 /* $OpenBSD: mandocdb.c,v 1.216 2020/04/03 11:34:19 schwarze Exp $ */
2 /*
3  * Copyright (c) 2011-2020 Ingo Schwarze <schwarze@openbsd.org>
4  * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
5  * Copyright (c) 2016 Ed Maste <emaste@freebsd.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  *
19  * Implementation of the makewhatis(8) program.
20  */
21 #include <sys/types.h>
22 #include <sys/mman.h>
23 #include <sys/stat.h>
24 
25 #include <assert.h>
26 #include <ctype.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <fts.h>
31 #include <limits.h>
32 #include <stdarg.h>
33 #include <stddef.h>
34 #include <stdio.h>
35 #include <stdint.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 
40 #include "mandoc_aux.h"
41 #include "mandoc_ohash.h"
42 #include "mandoc.h"
43 #include "roff.h"
44 #include "mdoc.h"
45 #include "man.h"
46 #include "mandoc_parse.h"
47 #include "manconf.h"
48 #include "mansearch.h"
49 #include "dba_array.h"
50 #include "dba.h"
51 
52 extern const char *const mansearch_keynames[];
53 
54 enum	op {
55 	OP_DEFAULT = 0, /* new dbs from dir list or default config */
56 	OP_CONFFILE, /* new databases from custom config file */
57 	OP_UPDATE, /* delete/add entries in existing database */
58 	OP_DELETE, /* delete entries from existing database */
59 	OP_TEST /* change no databases, report potential problems */
60 };
61 
62 struct	str {
63 	const struct mpage *mpage; /* if set, the owning parse */
64 	uint64_t	 mask; /* bitmask in sequence */
65 	char		 key[]; /* rendered text */
66 };
67 
68 struct	inodev {
69 	ino_t		 st_ino;
70 	dev_t		 st_dev;
71 };
72 
73 struct	mpage {
74 	struct inodev	 inodev;  /* used for hashing routine */
75 	struct dba_array *dba;
76 	char		*sec;     /* section from file content */
77 	char		*arch;    /* architecture from file content */
78 	char		*title;   /* title from file content */
79 	char		*desc;    /* description from file content */
80 	struct mpage	*next;    /* singly linked list */
81 	struct mlink	*mlinks;  /* singly linked list */
82 	int		 name_head_done;
83 	enum form	 form;    /* format from file content */
84 };
85 
86 struct	mlink {
87 	char		 file[PATH_MAX]; /* filename rel. to manpath */
88 	char		*dsec;    /* section from directory */
89 	char		*arch;    /* architecture from directory */
90 	char		*name;    /* name from file name (not empty) */
91 	char		*fsec;    /* section from file name suffix */
92 	struct mlink	*next;    /* singly linked list */
93 	struct mpage	*mpage;   /* parent */
94 	int		 gzip;	  /* filename has a .gz suffix */
95 	enum form	 dform;   /* format from directory */
96 	enum form	 fform;   /* format from file name suffix */
97 };
98 
99 typedef	int (*mdoc_fp)(struct mpage *, const struct roff_meta *,
100 			const struct roff_node *);
101 
102 struct	mdoc_handler {
103 	mdoc_fp		 fp; /* optional handler */
104 	uint64_t	 mask;  /* set unless handler returns 0 */
105 	int		 taboo;  /* node flags that must not be set */
106 };
107 
108 
109 int		 mandocdb(int, char *[]);
110 
111 static	void	 dbadd(struct dba *, struct mpage *);
112 static	void	 dbadd_mlink(const struct mlink *);
113 static	void	 dbprune(struct dba *);
114 static	void	 dbwrite(struct dba *);
115 static	void	 filescan(const char *);
116 static	int	 fts_compare(const FTSENT **, const FTSENT **);
117 static	void	 mlink_add(struct mlink *, const struct stat *);
118 static	void	 mlink_check(struct mpage *, struct mlink *);
119 static	void	 mlink_free(struct mlink *);
120 static	void	 mlinks_undupe(struct mpage *);
121 static	void	 mpages_free(void);
122 static	void	 mpages_merge(struct dba *, struct mparse *);
123 static	void	 parse_cat(struct mpage *, int);
124 static	void	 parse_man(struct mpage *, const struct roff_meta *,
125 			const struct roff_node *);
126 static	void	 parse_mdoc(struct mpage *, const struct roff_meta *,
127 			const struct roff_node *);
128 static	int	 parse_mdoc_head(struct mpage *, const struct roff_meta *,
129 			const struct roff_node *);
130 static	int	 parse_mdoc_Fa(struct mpage *, const struct roff_meta *,
131 			const struct roff_node *);
132 static	int	 parse_mdoc_Fd(struct mpage *, const struct roff_meta *,
133 			const struct roff_node *);
134 static	void	 parse_mdoc_fname(struct mpage *, const struct roff_node *);
135 static	int	 parse_mdoc_Fn(struct mpage *, const struct roff_meta *,
136 			const struct roff_node *);
137 static	int	 parse_mdoc_Fo(struct mpage *, const struct roff_meta *,
138 			const struct roff_node *);
139 static	int	 parse_mdoc_Nd(struct mpage *, const struct roff_meta *,
140 			const struct roff_node *);
141 static	int	 parse_mdoc_Nm(struct mpage *, const struct roff_meta *,
142 			const struct roff_node *);
143 static	int	 parse_mdoc_Sh(struct mpage *, const struct roff_meta *,
144 			const struct roff_node *);
145 static	int	 parse_mdoc_Va(struct mpage *, const struct roff_meta *,
146 			const struct roff_node *);
147 static	int	 parse_mdoc_Xr(struct mpage *, const struct roff_meta *,
148 			const struct roff_node *);
149 static	void	 putkey(const struct mpage *, char *, uint64_t);
150 static	void	 putkeys(const struct mpage *, char *, size_t, uint64_t);
151 static	void	 putmdockey(const struct mpage *,
152 			const struct roff_node *, uint64_t, int);
153 static	int	 render_string(char **, size_t *);
154 static	void	 say(const char *, const char *, ...)
155 			__attribute__((__format__ (__printf__, 2, 3)));
156 static	int	 set_basedir(const char *, int);
157 static	int	 treescan(void);
158 static	size_t	 utf8(unsigned int, char [7]);
159 
160 static	int		 nodb; /* no database changes */
161 static	int		 mparse_options; /* abort the parse early */
162 static	int		 use_all; /* use all found files */
163 static	int		 debug; /* print what we're doing */
164 static	int		 warnings; /* warn about crap */
165 static	int		 write_utf8; /* write UTF-8 output; else ASCII */
166 static	int		 exitcode; /* to be returned by main */
167 static	enum op		 op; /* operational mode */
168 static	char		 basedir[PATH_MAX]; /* current base directory */
169 static	size_t		 basedir_len; /* strlen(basedir) */
170 static	struct mpage	*mpage_head; /* list of distinct manual pages */
171 static	struct ohash	 mpages; /* table of distinct manual pages */
172 static	struct ohash	 mlinks; /* table of directory entries */
173 static	struct ohash	 names; /* table of all names */
174 static	struct ohash	 strings; /* table of all strings */
175 static	uint64_t	 name_mask;
176 
177 static	const struct mdoc_handler mdoc_handlers[MDOC_MAX - MDOC_Dd] = {
178 	{ NULL, 0, NODE_NOPRT },  /* Dd */
179 	{ NULL, 0, NODE_NOPRT },  /* Dt */
180 	{ NULL, 0, NODE_NOPRT },  /* Os */
181 	{ parse_mdoc_Sh, TYPE_Sh, 0 }, /* Sh */
182 	{ parse_mdoc_head, TYPE_Ss, 0 }, /* Ss */
183 	{ NULL, 0, 0 },  /* Pp */
184 	{ NULL, 0, 0 },  /* D1 */
185 	{ NULL, 0, 0 },  /* Dl */
186 	{ NULL, 0, 0 },  /* Bd */
187 	{ NULL, 0, 0 },  /* Ed */
188 	{ NULL, 0, 0 },  /* Bl */
189 	{ NULL, 0, 0 },  /* El */
190 	{ NULL, 0, 0 },  /* It */
191 	{ NULL, 0, 0 },  /* Ad */
192 	{ NULL, TYPE_An, 0 },  /* An */
193 	{ NULL, 0, 0 },  /* Ap */
194 	{ NULL, TYPE_Ar, 0 },  /* Ar */
195 	{ NULL, TYPE_Cd, 0 },  /* Cd */
196 	{ NULL, TYPE_Cm, 0 },  /* Cm */
197 	{ NULL, TYPE_Dv, 0 },  /* Dv */
198 	{ NULL, TYPE_Er, 0 },  /* Er */
199 	{ NULL, TYPE_Ev, 0 },  /* Ev */
200 	{ NULL, 0, 0 },  /* Ex */
201 	{ parse_mdoc_Fa, 0, 0 },  /* Fa */
202 	{ parse_mdoc_Fd, 0, 0 },  /* Fd */
203 	{ NULL, TYPE_Fl, 0 },  /* Fl */
204 	{ parse_mdoc_Fn, 0, 0 },  /* Fn */
205 	{ NULL, TYPE_Ft | TYPE_Vt, 0 },  /* Ft */
206 	{ NULL, TYPE_Ic, 0 },  /* Ic */
207 	{ NULL, TYPE_In, 0 },  /* In */
208 	{ NULL, TYPE_Li, 0 },  /* Li */
209 	{ parse_mdoc_Nd, 0, 0 },  /* Nd */
210 	{ parse_mdoc_Nm, 0, 0 },  /* Nm */
211 	{ NULL, 0, 0 },  /* Op */
212 	{ NULL, 0, 0 },  /* Ot */
213 	{ NULL, TYPE_Pa, NODE_NOSRC },  /* Pa */
214 	{ NULL, 0, 0 },  /* Rv */
215 	{ NULL, TYPE_St, 0 },  /* St */
216 	{ parse_mdoc_Va, TYPE_Va, 0 },  /* Va */
217 	{ parse_mdoc_Va, TYPE_Vt, 0 },  /* Vt */
218 	{ parse_mdoc_Xr, 0, 0 },  /* Xr */
219 	{ NULL, 0, 0 },  /* %A */
220 	{ NULL, 0, 0 },  /* %B */
221 	{ NULL, 0, 0 },  /* %D */
222 	{ NULL, 0, 0 },  /* %I */
223 	{ NULL, 0, 0 },  /* %J */
224 	{ NULL, 0, 0 },  /* %N */
225 	{ NULL, 0, 0 },  /* %O */
226 	{ NULL, 0, 0 },  /* %P */
227 	{ NULL, 0, 0 },  /* %R */
228 	{ NULL, 0, 0 },  /* %T */
229 	{ NULL, 0, 0 },  /* %V */
230 	{ NULL, 0, 0 },  /* Ac */
231 	{ NULL, 0, 0 },  /* Ao */
232 	{ NULL, 0, 0 },  /* Aq */
233 	{ NULL, TYPE_At, 0 },  /* At */
234 	{ NULL, 0, 0 },  /* Bc */
235 	{ NULL, 0, 0 },  /* Bf */
236 	{ NULL, 0, 0 },  /* Bo */
237 	{ NULL, 0, 0 },  /* Bq */
238 	{ NULL, TYPE_Bsx, NODE_NOSRC },  /* Bsx */
239 	{ NULL, TYPE_Bx, NODE_NOSRC },  /* Bx */
240 	{ NULL, 0, 0 },  /* Db */
241 	{ NULL, 0, 0 },  /* Dc */
242 	{ NULL, 0, 0 },  /* Do */
243 	{ NULL, 0, 0 },  /* Dq */
244 	{ NULL, 0, 0 },  /* Ec */
245 	{ NULL, 0, 0 },  /* Ef */
246 	{ NULL, TYPE_Em, 0 },  /* Em */
247 	{ NULL, 0, 0 },  /* Eo */
248 	{ NULL, TYPE_Fx, NODE_NOSRC },  /* Fx */
249 	{ NULL, TYPE_Ms, 0 },  /* Ms */
250 	{ NULL, 0, 0 },  /* No */
251 	{ NULL, 0, 0 },  /* Ns */
252 	{ NULL, TYPE_Nx, NODE_NOSRC },  /* Nx */
253 	{ NULL, TYPE_Ox, NODE_NOSRC },  /* Ox */
254 	{ NULL, 0, 0 },  /* Pc */
255 	{ NULL, 0, 0 },  /* Pf */
256 	{ NULL, 0, 0 },  /* Po */
257 	{ NULL, 0, 0 },  /* Pq */
258 	{ NULL, 0, 0 },  /* Qc */
259 	{ NULL, 0, 0 },  /* Ql */
260 	{ NULL, 0, 0 },  /* Qo */
261 	{ NULL, 0, 0 },  /* Qq */
262 	{ NULL, 0, 0 },  /* Re */
263 	{ NULL, 0, 0 },  /* Rs */
264 	{ NULL, 0, 0 },  /* Sc */
265 	{ NULL, 0, 0 },  /* So */
266 	{ NULL, 0, 0 },  /* Sq */
267 	{ NULL, 0, 0 },  /* Sm */
268 	{ NULL, 0, 0 },  /* Sx */
269 	{ NULL, TYPE_Sy, 0 },  /* Sy */
270 	{ NULL, TYPE_Tn, 0 },  /* Tn */
271 	{ NULL, 0, NODE_NOSRC },  /* Ux */
272 	{ NULL, 0, 0 },  /* Xc */
273 	{ NULL, 0, 0 },  /* Xo */
274 	{ parse_mdoc_Fo, 0, 0 },  /* Fo */
275 	{ NULL, 0, 0 },  /* Fc */
276 	{ NULL, 0, 0 },  /* Oo */
277 	{ NULL, 0, 0 },  /* Oc */
278 	{ NULL, 0, 0 },  /* Bk */
279 	{ NULL, 0, 0 },  /* Ek */
280 	{ NULL, 0, 0 },  /* Bt */
281 	{ NULL, 0, 0 },  /* Hf */
282 	{ NULL, 0, 0 },  /* Fr */
283 	{ NULL, 0, 0 },  /* Ud */
284 	{ NULL, TYPE_Lb, NODE_NOSRC },  /* Lb */
285 	{ NULL, 0, 0 },  /* Lp */
286 	{ NULL, TYPE_Lk, 0 },  /* Lk */
287 	{ NULL, TYPE_Mt, NODE_NOSRC },  /* Mt */
288 	{ NULL, 0, 0 },  /* Brq */
289 	{ NULL, 0, 0 },  /* Bro */
290 	{ NULL, 0, 0 },  /* Brc */
291 	{ NULL, 0, 0 },  /* %C */
292 	{ NULL, 0, 0 },  /* Es */
293 	{ NULL, 0, 0 },  /* En */
294 	{ NULL, TYPE_Dx, NODE_NOSRC },  /* Dx */
295 	{ NULL, 0, 0 },  /* %Q */
296 	{ NULL, 0, 0 },  /* %U */
297 	{ NULL, 0, 0 },  /* Ta */
298 };
299 
300 
301 int
302 mandocdb(int argc, char *argv[])
303 {
304 	struct manconf	  conf;
305 	struct mparse	 *mp;
306 	struct dba	 *dba;
307 	const char	 *path_arg, *progname;
308 	size_t		  j, sz;
309 	int		  ch, i;
310 
311 	if (pledge("stdio rpath wpath cpath", NULL) == -1) {
312 		warn("pledge");
313 		return (int)MANDOCLEVEL_SYSERR;
314 	}
315 
316 	memset(&conf, 0, sizeof(conf));
317 
318 	/*
319 	 * We accept a few different invocations.
320 	 * The CHECKOP macro makes sure that invocation styles don't
321 	 * clobber each other.
322 	 */
323 #define	CHECKOP(_op, _ch) do \
324 	if ((_op) != OP_DEFAULT) { \
325 		warnx("-%c: Conflicting option", (_ch)); \
326 		goto usage; \
327 	} while (/*CONSTCOND*/0)
328 
329 	mparse_options = MPARSE_VALIDATE;
330 	path_arg = NULL;
331 	op = OP_DEFAULT;
332 
333 	while ((ch = getopt(argc, argv, "aC:Dd:npQT:tu:v")) != -1)
334 		switch (ch) {
335 		case 'a':
336 			use_all = 1;
337 			break;
338 		case 'C':
339 			CHECKOP(op, ch);
340 			path_arg = optarg;
341 			op = OP_CONFFILE;
342 			break;
343 		case 'D':
344 			debug++;
345 			break;
346 		case 'd':
347 			CHECKOP(op, ch);
348 			path_arg = optarg;
349 			op = OP_UPDATE;
350 			break;
351 		case 'n':
352 			nodb = 1;
353 			break;
354 		case 'p':
355 			warnings = 1;
356 			break;
357 		case 'Q':
358 			mparse_options |= MPARSE_QUICK;
359 			break;
360 		case 'T':
361 			if (strcmp(optarg, "utf8") != 0) {
362 				warnx("-T%s: Unsupported output format",
363 				    optarg);
364 				goto usage;
365 			}
366 			write_utf8 = 1;
367 			break;
368 		case 't':
369 			CHECKOP(op, ch);
370 			dup2(STDOUT_FILENO, STDERR_FILENO);
371 			op = OP_TEST;
372 			nodb = warnings = 1;
373 			break;
374 		case 'u':
375 			CHECKOP(op, ch);
376 			path_arg = optarg;
377 			op = OP_DELETE;
378 			break;
379 		case 'v':
380 			/* Compatibility with espie@'s makewhatis. */
381 			break;
382 		default:
383 			goto usage;
384 		}
385 
386 	argc -= optind;
387 	argv += optind;
388 
389 	if (nodb) {
390 		if (pledge("stdio rpath", NULL) == -1) {
391 			warn("pledge");
392 			return (int)MANDOCLEVEL_SYSERR;
393 		}
394 	}
395 
396 	if (op == OP_CONFFILE && argc > 0) {
397 		warnx("-C: Too many arguments");
398 		goto usage;
399 	}
400 
401 	exitcode = (int)MANDOCLEVEL_OK;
402 	mchars_alloc();
403 	mp = mparse_alloc(mparse_options, MANDOC_OS_OTHER, NULL);
404 	mandoc_ohash_init(&mpages, 6, offsetof(struct mpage, inodev));
405 	mandoc_ohash_init(&mlinks, 6, offsetof(struct mlink, file));
406 
407 	if (op == OP_UPDATE || op == OP_DELETE || op == OP_TEST) {
408 
409 		/*
410 		 * Most of these deal with a specific directory.
411 		 * Jump into that directory first.
412 		 */
413 		if (op != OP_TEST && set_basedir(path_arg, 1) == 0)
414 			goto out;
415 
416 		dba = nodb ? dba_new(128) : dba_read(MANDOC_DB);
417 		if (dba != NULL) {
418 			/*
419 			 * The existing database is usable.  Process
420 			 * all files specified on the command-line.
421 			 */
422 			use_all = 1;
423 			for (i = 0; i < argc; i++)
424 				filescan(argv[i]);
425 			if (nodb == 0)
426 				dbprune(dba);
427 		} else {
428 			/* Database missing or corrupt. */
429 			if (op != OP_UPDATE || errno != ENOENT)
430 				say(MANDOC_DB, "%s: Automatically recreating"
431 				    " from scratch", strerror(errno));
432 			exitcode = (int)MANDOCLEVEL_OK;
433 			op = OP_DEFAULT;
434 			if (treescan() == 0)
435 				goto out;
436 			dba = dba_new(128);
437 		}
438 		if (op != OP_DELETE)
439 			mpages_merge(dba, mp);
440 		if (nodb == 0)
441 			dbwrite(dba);
442 		dba_free(dba);
443 	} else {
444 		/*
445 		 * If we have arguments, use them as our manpaths.
446 		 * If we don't, use man.conf(5).
447 		 */
448 		if (argc > 0) {
449 			conf.manpath.paths = mandoc_reallocarray(NULL,
450 			    argc, sizeof(char *));
451 			conf.manpath.sz = (size_t)argc;
452 			for (i = 0; i < argc; i++)
453 				conf.manpath.paths[i] = mandoc_strdup(argv[i]);
454 		} else
455 			manconf_parse(&conf, path_arg, NULL, NULL);
456 
457 		if (conf.manpath.sz == 0) {
458 			exitcode = (int)MANDOCLEVEL_BADARG;
459 			say("", "Empty manpath");
460 		}
461 
462 		/*
463 		 * First scan the tree rooted at a base directory, then
464 		 * build a new database and finally move it into place.
465 		 * Ignore zero-length directories and strip trailing
466 		 * slashes.
467 		 */
468 		for (j = 0; j < conf.manpath.sz; j++) {
469 			sz = strlen(conf.manpath.paths[j]);
470 			if (sz && conf.manpath.paths[j][sz - 1] == '/')
471 				conf.manpath.paths[j][--sz] = '\0';
472 			if (sz == 0)
473 				continue;
474 
475 			if (j) {
476 				mandoc_ohash_init(&mpages, 6,
477 				    offsetof(struct mpage, inodev));
478 				mandoc_ohash_init(&mlinks, 6,
479 				    offsetof(struct mlink, file));
480 			}
481 
482 			if (set_basedir(conf.manpath.paths[j], argc > 0) == 0)
483 				continue;
484 			if (treescan() == 0)
485 				continue;
486 			dba = dba_new(128);
487 			mpages_merge(dba, mp);
488 			if (nodb == 0)
489 				dbwrite(dba);
490 			dba_free(dba);
491 
492 			if (j + 1 < conf.manpath.sz) {
493 				mpages_free();
494 				ohash_delete(&mpages);
495 				ohash_delete(&mlinks);
496 			}
497 		}
498 	}
499 out:
500 	manconf_free(&conf);
501 	mparse_free(mp);
502 	mchars_free();
503 	mpages_free();
504 	ohash_delete(&mpages);
505 	ohash_delete(&mlinks);
506 	return exitcode;
507 usage:
508 	progname = getprogname();
509 	fprintf(stderr, "usage: %s [-aDnpQ] [-C file] [-Tutf8]\n"
510 			"       %s [-aDnpQ] [-Tutf8] dir ...\n"
511 			"       %s [-DnpQ] [-Tutf8] -d dir [file ...]\n"
512 			"       %s [-Dnp] -u dir [file ...]\n"
513 			"       %s [-Q] -t file ...\n",
514 		        progname, progname, progname, progname, progname);
515 
516 	return (int)MANDOCLEVEL_BADARG;
517 }
518 
519 /*
520  * To get a singly linked list in alpha order while inserting entries
521  * at the beginning, process directory entries in reverse alpha order.
522  */
523 static int
524 fts_compare(const FTSENT **a, const FTSENT **b)
525 {
526 	return -strcmp((*a)->fts_name, (*b)->fts_name);
527 }
528 
529 /*
530  * Scan a directory tree rooted at "basedir" for manpages.
531  * We use fts(), scanning directory parts along the way for clues to our
532  * section and architecture.
533  *
534  * If use_all has been specified, grok all files.
535  * If not, sanitise paths to the following:
536  *
537  *   [./]man*[/<arch>]/<name>.<section>
538  *   or
539  *   [./]cat<section>[/<arch>]/<name>.0
540  *
541  * TODO: accommodate for multi-language directories.
542  */
543 static int
544 treescan(void)
545 {
546 	char		 buf[PATH_MAX];
547 	FTS		*f;
548 	FTSENT		*ff;
549 	struct mlink	*mlink;
550 	int		 gzip;
551 	enum form	 dform;
552 	char		*dsec, *arch, *fsec, *cp;
553 	const char	*path;
554 	const char	*argv[2];
555 
556 	argv[0] = ".";
557 	argv[1] = NULL;
558 
559 	f = fts_open((char * const *)argv, FTS_PHYSICAL | FTS_NOCHDIR,
560 	    fts_compare);
561 	if (f == NULL) {
562 		exitcode = (int)MANDOCLEVEL_SYSERR;
563 		say("", "&fts_open");
564 		return 0;
565 	}
566 
567 	dsec = arch = NULL;
568 	dform = FORM_NONE;
569 
570 	while ((ff = fts_read(f)) != NULL) {
571 		path = ff->fts_path + 2;
572 		switch (ff->fts_info) {
573 
574 		/*
575 		 * Symbolic links require various sanity checks,
576 		 * then get handled just like regular files.
577 		 */
578 		case FTS_SL:
579 			if (realpath(path, buf) == NULL) {
580 				if (warnings)
581 					say(path, "&realpath");
582 				continue;
583 			}
584 			if (strncmp(buf, basedir, basedir_len) != 0) {
585 				if (warnings) say("",
586 				    "%s: outside base directory", buf);
587 				continue;
588 			}
589 			/* Use logical inode to avoid mpages dupe. */
590 			if (stat(path, ff->fts_statp) == -1) {
591 				if (warnings)
592 					say(path, "&stat");
593 				continue;
594 			}
595 			/* FALLTHROUGH */
596 
597 		/*
598 		 * If we're a regular file, add an mlink by using the
599 		 * stored directory data and handling the filename.
600 		 */
601 		case FTS_F:
602 			if ( ! strcmp(path, MANDOC_DB))
603 				continue;
604 			if ( ! use_all && ff->fts_level < 2) {
605 				if (warnings)
606 					say(path, "Extraneous file");
607 				continue;
608 			}
609 			gzip = 0;
610 			fsec = NULL;
611 			while (fsec == NULL) {
612 				fsec = strrchr(ff->fts_name, '.');
613 				if (fsec == NULL || strcmp(fsec+1, "gz"))
614 					break;
615 				gzip = 1;
616 				*fsec = '\0';
617 				fsec = NULL;
618 			}
619 			if (fsec == NULL) {
620 				if ( ! use_all) {
621 					if (warnings)
622 						say(path,
623 						    "No filename suffix");
624 					continue;
625 				}
626 			} else if ( ! strcmp(++fsec, "html")) {
627 				if (warnings)
628 					say(path, "Skip html");
629 				continue;
630 			} else if ( ! strcmp(fsec, "ps")) {
631 				if (warnings)
632 					say(path, "Skip ps");
633 				continue;
634 			} else if ( ! strcmp(fsec, "pdf")) {
635 				if (warnings)
636 					say(path, "Skip pdf");
637 				continue;
638 			} else if ( ! use_all &&
639 			    ((dform == FORM_SRC &&
640 			      strncmp(fsec, dsec, strlen(dsec))) ||
641 			     (dform == FORM_CAT && strcmp(fsec, "0")))) {
642 				if (warnings)
643 					say(path, "Wrong filename suffix");
644 				continue;
645 			} else
646 				fsec[-1] = '\0';
647 
648 			mlink = mandoc_calloc(1, sizeof(struct mlink));
649 			if (strlcpy(mlink->file, path,
650 			    sizeof(mlink->file)) >=
651 			    sizeof(mlink->file)) {
652 				say(path, "Filename too long");
653 				free(mlink);
654 				continue;
655 			}
656 			mlink->dform = dform;
657 			mlink->dsec = dsec;
658 			mlink->arch = arch;
659 			mlink->name = ff->fts_name;
660 			mlink->fsec = fsec;
661 			mlink->gzip = gzip;
662 			mlink_add(mlink, ff->fts_statp);
663 			continue;
664 
665 		case FTS_D:
666 		case FTS_DP:
667 			break;
668 
669 		default:
670 			if (warnings)
671 				say(path, "Not a regular file");
672 			continue;
673 		}
674 
675 		switch (ff->fts_level) {
676 		case 0:
677 			/* Ignore the root directory. */
678 			break;
679 		case 1:
680 			/*
681 			 * This might contain manX/ or catX/.
682 			 * Try to infer this from the name.
683 			 * If we're not in use_all, enforce it.
684 			 */
685 			cp = ff->fts_name;
686 			if (ff->fts_info == FTS_DP) {
687 				dform = FORM_NONE;
688 				dsec = NULL;
689 				break;
690 			}
691 
692 			if ( ! strncmp(cp, "man", 3)) {
693 				dform = FORM_SRC;
694 				dsec = cp + 3;
695 			} else if ( ! strncmp(cp, "cat", 3)) {
696 				dform = FORM_CAT;
697 				dsec = cp + 3;
698 			} else {
699 				dform = FORM_NONE;
700 				dsec = NULL;
701 			}
702 
703 			if (dsec != NULL || use_all)
704 				break;
705 
706 			if (warnings)
707 				say(path, "Unknown directory part");
708 			fts_set(f, ff, FTS_SKIP);
709 			break;
710 		case 2:
711 			/*
712 			 * Possibly our architecture.
713 			 * If we're descending, keep tabs on it.
714 			 */
715 			if (ff->fts_info != FTS_DP && dsec != NULL)
716 				arch = ff->fts_name;
717 			else
718 				arch = NULL;
719 			break;
720 		default:
721 			if (ff->fts_info == FTS_DP || use_all)
722 				break;
723 			if (warnings)
724 				say(path, "Extraneous directory part");
725 			fts_set(f, ff, FTS_SKIP);
726 			break;
727 		}
728 	}
729 
730 	fts_close(f);
731 	return 1;
732 }
733 
734 /*
735  * Add a file to the mlinks table.
736  * Do not verify that it's a "valid" looking manpage (we'll do that
737  * later).
738  *
739  * Try to infer the manual section, architecture, and page name from the
740  * path, assuming it looks like
741  *
742  *   [./]man*[/<arch>]/<name>.<section>
743  *   or
744  *   [./]cat<section>[/<arch>]/<name>.0
745  *
746  * See treescan() for the fts(3) version of this.
747  */
748 static void
749 filescan(const char *infile)
750 {
751 	struct stat	 st;
752 	struct mlink	*mlink;
753 	char		*linkfile, *p, *realdir, *start, *usefile;
754 	size_t		 realdir_len;
755 
756 	assert(use_all);
757 
758 	if (strncmp(infile, "./", 2) == 0)
759 		infile += 2;
760 
761 	/*
762 	 * We have to do lstat(2) before realpath(3) loses
763 	 * the information whether this is a symbolic link.
764 	 * We need to know that because for symbolic links,
765 	 * we want to use the orginal file name, while for
766 	 * regular files, we want to use the real path.
767 	 */
768 	if (lstat(infile, &st) == -1) {
769 		exitcode = (int)MANDOCLEVEL_BADARG;
770 		say(infile, "&lstat");
771 		return;
772 	} else if (S_ISREG(st.st_mode) == 0 && S_ISLNK(st.st_mode) == 0) {
773 		exitcode = (int)MANDOCLEVEL_BADARG;
774 		say(infile, "Not a regular file");
775 		return;
776 	}
777 
778 	/*
779 	 * We have to resolve the file name to the real path
780 	 * in any case for the base directory check.
781 	 */
782 	if ((usefile = realpath(infile, NULL)) == NULL) {
783 		exitcode = (int)MANDOCLEVEL_BADARG;
784 		say(infile, "&realpath");
785 		return;
786 	}
787 
788 	if (op == OP_TEST)
789 		start = usefile;
790 	else if (strncmp(usefile, basedir, basedir_len) == 0)
791 		start = usefile + basedir_len;
792 	else {
793 		exitcode = (int)MANDOCLEVEL_BADARG;
794 		say("", "%s: outside base directory", infile);
795 		free(usefile);
796 		return;
797 	}
798 
799 	/*
800 	 * Now we are sure the file is inside our tree.
801 	 * If it is a symbolic link, ignore the real path
802 	 * and use the original name.
803 	 */
804 	do {
805 		if (S_ISLNK(st.st_mode) == 0)
806 			break;
807 
808 		/*
809 		 * Some implementations of realpath(3) may succeed
810 		 * even if the target of the link does not exist,
811 		 * so check again for extra safety.
812 		 */
813 		if (stat(usefile, &st) == -1) {
814 			exitcode = (int)MANDOCLEVEL_BADARG;
815 			say(infile, "&stat");
816 			free(usefile);
817 			return;
818 		}
819 		linkfile = mandoc_strdup(infile);
820 		if (op == OP_TEST) {
821 			free(usefile);
822 			start = usefile = linkfile;
823 			break;
824 		}
825 		if (strncmp(infile, basedir, basedir_len) == 0) {
826 			free(usefile);
827 			usefile = linkfile;
828 			start = usefile + basedir_len;
829 			break;
830 		}
831 
832 		/*
833 		 * This symbolic link points into the basedir
834 		 * from the outside.  Let's see whether any of
835 		 * the parent directories resolve to the basedir.
836 		 */
837 		p = strchr(linkfile, '\0');
838 		do {
839 			while (*--p != '/')
840 				continue;
841 			*p = '\0';
842 			if ((realdir = realpath(linkfile, NULL)) == NULL) {
843 				exitcode = (int)MANDOCLEVEL_BADARG;
844 				say(infile, "&realpath");
845 				free(linkfile);
846 				free(usefile);
847 				return;
848 			}
849 			realdir_len = strlen(realdir) + 1;
850 			free(realdir);
851 			*p = '/';
852 		} while (realdir_len > basedir_len);
853 
854 		/*
855 		 * If one of the directories resolves to the basedir,
856 		 * use the rest of the original name.
857 		 * Otherwise, the best we can do
858 		 * is to use the filename pointed to.
859 		 */
860 		if (realdir_len == basedir_len) {
861 			free(usefile);
862 			usefile = linkfile;
863 			start = p + 1;
864 		} else {
865 			free(linkfile);
866 			start = usefile + basedir_len;
867 		}
868 	} while (/* CONSTCOND */ 0);
869 
870 	mlink = mandoc_calloc(1, sizeof(struct mlink));
871 	mlink->dform = FORM_NONE;
872 	if (strlcpy(mlink->file, start, sizeof(mlink->file)) >=
873 	    sizeof(mlink->file)) {
874 		say(start, "Filename too long");
875 		free(mlink);
876 		free(usefile);
877 		return;
878 	}
879 
880 	/*
881 	 * In test mode or when the original name is absolute
882 	 * but outside our tree, guess the base directory.
883 	 */
884 
885 	if (op == OP_TEST || (start == usefile && *start == '/')) {
886 		if (strncmp(usefile, "man/", 4) == 0)
887 			start = usefile + 4;
888 		else if ((start = strstr(usefile, "/man/")) != NULL)
889 			start += 5;
890 		else
891 			start = usefile;
892 	}
893 
894 	/*
895 	 * First try to guess our directory structure.
896 	 * If we find a separator, try to look for man* or cat*.
897 	 * If we find one of these and what's underneath is a directory,
898 	 * assume it's an architecture.
899 	 */
900 	if ((p = strchr(start, '/')) != NULL) {
901 		*p++ = '\0';
902 		if (strncmp(start, "man", 3) == 0) {
903 			mlink->dform = FORM_SRC;
904 			mlink->dsec = start + 3;
905 		} else if (strncmp(start, "cat", 3) == 0) {
906 			mlink->dform = FORM_CAT;
907 			mlink->dsec = start + 3;
908 		}
909 
910 		start = p;
911 		if (mlink->dsec != NULL && (p = strchr(start, '/')) != NULL) {
912 			*p++ = '\0';
913 			mlink->arch = start;
914 			start = p;
915 		}
916 	}
917 
918 	/*
919 	 * Now check the file suffix.
920 	 * Suffix of `.0' indicates a catpage, `.1-9' is a manpage.
921 	 */
922 	p = strrchr(start, '\0');
923 	while (p-- > start && *p != '/' && *p != '.')
924 		continue;
925 
926 	if (*p == '.') {
927 		*p++ = '\0';
928 		mlink->fsec = p;
929 	}
930 
931 	/*
932 	 * Now try to parse the name.
933 	 * Use the filename portion of the path.
934 	 */
935 	mlink->name = start;
936 	if ((p = strrchr(start, '/')) != NULL) {
937 		mlink->name = p + 1;
938 		*p = '\0';
939 	}
940 	mlink_add(mlink, &st);
941 	free(usefile);
942 }
943 
944 static void
945 mlink_add(struct mlink *mlink, const struct stat *st)
946 {
947 	struct inodev	 inodev;
948 	struct mpage	*mpage;
949 	unsigned int	 slot;
950 
951 	assert(NULL != mlink->file);
952 
953 	mlink->dsec = mandoc_strdup(mlink->dsec ? mlink->dsec : "");
954 	mlink->arch = mandoc_strdup(mlink->arch ? mlink->arch : "");
955 	mlink->name = mandoc_strdup(mlink->name ? mlink->name : "");
956 	mlink->fsec = mandoc_strdup(mlink->fsec ? mlink->fsec : "");
957 
958 	if ('0' == *mlink->fsec) {
959 		free(mlink->fsec);
960 		mlink->fsec = mandoc_strdup(mlink->dsec);
961 		mlink->fform = FORM_CAT;
962 	} else if ('1' <= *mlink->fsec && '9' >= *mlink->fsec)
963 		mlink->fform = FORM_SRC;
964 	else
965 		mlink->fform = FORM_NONE;
966 
967 	slot = ohash_qlookup(&mlinks, mlink->file);
968 	assert(NULL == ohash_find(&mlinks, slot));
969 	ohash_insert(&mlinks, slot, mlink);
970 
971 	memset(&inodev, 0, sizeof(inodev));  /* Clear padding. */
972 	inodev.st_ino = st->st_ino;
973 	inodev.st_dev = st->st_dev;
974 	slot = ohash_lookup_memory(&mpages, (char *)&inodev,
975 	    sizeof(struct inodev), inodev.st_ino);
976 	mpage = ohash_find(&mpages, slot);
977 	if (NULL == mpage) {
978 		mpage = mandoc_calloc(1, sizeof(struct mpage));
979 		mpage->inodev.st_ino = inodev.st_ino;
980 		mpage->inodev.st_dev = inodev.st_dev;
981 		mpage->form = FORM_NONE;
982 		mpage->next = mpage_head;
983 		mpage_head = mpage;
984 		ohash_insert(&mpages, slot, mpage);
985 	} else
986 		mlink->next = mpage->mlinks;
987 	mpage->mlinks = mlink;
988 	mlink->mpage = mpage;
989 }
990 
991 static void
992 mlink_free(struct mlink *mlink)
993 {
994 
995 	free(mlink->dsec);
996 	free(mlink->arch);
997 	free(mlink->name);
998 	free(mlink->fsec);
999 	free(mlink);
1000 }
1001 
1002 static void
1003 mpages_free(void)
1004 {
1005 	struct mpage	*mpage;
1006 	struct mlink	*mlink;
1007 
1008 	while ((mpage = mpage_head) != NULL) {
1009 		while ((mlink = mpage->mlinks) != NULL) {
1010 			mpage->mlinks = mlink->next;
1011 			mlink_free(mlink);
1012 		}
1013 		mpage_head = mpage->next;
1014 		free(mpage->sec);
1015 		free(mpage->arch);
1016 		free(mpage->title);
1017 		free(mpage->desc);
1018 		free(mpage);
1019 	}
1020 }
1021 
1022 /*
1023  * For each mlink to the mpage, check whether the path looks like
1024  * it is formatted, and if it does, check whether a source manual
1025  * exists by the same name, ignoring the suffix.
1026  * If both conditions hold, drop the mlink.
1027  */
1028 static void
1029 mlinks_undupe(struct mpage *mpage)
1030 {
1031 	char		  buf[PATH_MAX];
1032 	struct mlink	**prev;
1033 	struct mlink	 *mlink;
1034 	char		 *bufp;
1035 
1036 	mpage->form = FORM_CAT;
1037 	prev = &mpage->mlinks;
1038 	while (NULL != (mlink = *prev)) {
1039 		if (FORM_CAT != mlink->dform) {
1040 			mpage->form = FORM_NONE;
1041 			goto nextlink;
1042 		}
1043 		(void)strlcpy(buf, mlink->file, sizeof(buf));
1044 		bufp = strstr(buf, "cat");
1045 		assert(NULL != bufp);
1046 		memcpy(bufp, "man", 3);
1047 		if (NULL != (bufp = strrchr(buf, '.')))
1048 			*++bufp = '\0';
1049 		(void)strlcat(buf, mlink->dsec, sizeof(buf));
1050 		if (NULL == ohash_find(&mlinks,
1051 		    ohash_qlookup(&mlinks, buf)))
1052 			goto nextlink;
1053 		if (warnings)
1054 			say(mlink->file, "Man source exists: %s", buf);
1055 		if (use_all)
1056 			goto nextlink;
1057 		*prev = mlink->next;
1058 		mlink_free(mlink);
1059 		continue;
1060 nextlink:
1061 		prev = &(*prev)->next;
1062 	}
1063 }
1064 
1065 static void
1066 mlink_check(struct mpage *mpage, struct mlink *mlink)
1067 {
1068 	struct str	*str;
1069 	unsigned int	 slot;
1070 
1071 	/*
1072 	 * Check whether the manual section given in a file
1073 	 * agrees with the directory where the file is located.
1074 	 * Some manuals have suffixes like (3p) on their
1075 	 * section number either inside the file or in the
1076 	 * directory name, some are linked into more than one
1077 	 * section, like encrypt(1) = makekey(8).
1078 	 */
1079 
1080 	if (FORM_SRC == mpage->form &&
1081 	    strcasecmp(mpage->sec, mlink->dsec))
1082 		say(mlink->file, "Section \"%s\" manual in %s directory",
1083 		    mpage->sec, mlink->dsec);
1084 
1085 	/*
1086 	 * Manual page directories exist for each kernel
1087 	 * architecture as returned by machine(1).
1088 	 * However, many manuals only depend on the
1089 	 * application architecture as returned by arch(1).
1090 	 * For example, some (2/ARM) manuals are shared
1091 	 * across the "armish" and "zaurus" kernel
1092 	 * architectures.
1093 	 * A few manuals are even shared across completely
1094 	 * different architectures, for example fdformat(1)
1095 	 * on amd64, i386, and sparc64.
1096 	 */
1097 
1098 	if (strcasecmp(mpage->arch, mlink->arch))
1099 		say(mlink->file, "Architecture \"%s\" manual in "
1100 		    "\"%s\" directory", mpage->arch, mlink->arch);
1101 
1102 	/*
1103 	 * XXX
1104 	 * parse_cat() doesn't set NAME_TITLE yet.
1105 	 */
1106 
1107 	if (FORM_CAT == mpage->form)
1108 		return;
1109 
1110 	/*
1111 	 * Check whether this mlink
1112 	 * appears as a name in the NAME section.
1113 	 */
1114 
1115 	slot = ohash_qlookup(&names, mlink->name);
1116 	str = ohash_find(&names, slot);
1117 	assert(NULL != str);
1118 	if ( ! (NAME_TITLE & str->mask))
1119 		say(mlink->file, "Name missing in NAME section");
1120 }
1121 
1122 /*
1123  * Run through the files in the global vector "mpages"
1124  * and add them to the database specified in "basedir".
1125  *
1126  * This handles the parsing scheme itself, using the cues of directory
1127  * and filename to determine whether the file is parsable or not.
1128  */
1129 static void
1130 mpages_merge(struct dba *dba, struct mparse *mp)
1131 {
1132 	struct mpage		*mpage, *mpage_dest;
1133 	struct mlink		*mlink, *mlink_dest;
1134 	struct roff_meta	*meta;
1135 	char			*cp;
1136 	int			 fd;
1137 
1138 	for (mpage = mpage_head; mpage != NULL; mpage = mpage->next) {
1139 		mlinks_undupe(mpage);
1140 		if ((mlink = mpage->mlinks) == NULL)
1141 			continue;
1142 
1143 		name_mask = NAME_MASK;
1144 		mandoc_ohash_init(&names, 4, offsetof(struct str, key));
1145 		mandoc_ohash_init(&strings, 6, offsetof(struct str, key));
1146 		mparse_reset(mp);
1147 		meta = NULL;
1148 
1149 		if ((fd = mparse_open(mp, mlink->file)) == -1) {
1150 			say(mlink->file, "&open");
1151 			goto nextpage;
1152 		}
1153 
1154 		/*
1155 		 * Interpret the file as mdoc(7) or man(7) source
1156 		 * code, unless it is known to be formatted.
1157 		 */
1158 		if (mlink->dform != FORM_CAT || mlink->fform != FORM_CAT) {
1159 			mparse_readfd(mp, fd, mlink->file);
1160 			close(fd);
1161 			fd = -1;
1162 			meta = mparse_result(mp);
1163 		}
1164 
1165 		if (meta != NULL && meta->sodest != NULL) {
1166 			mlink_dest = ohash_find(&mlinks,
1167 			    ohash_qlookup(&mlinks, meta->sodest));
1168 			if (mlink_dest == NULL) {
1169 				mandoc_asprintf(&cp, "%s.gz", meta->sodest);
1170 				mlink_dest = ohash_find(&mlinks,
1171 				    ohash_qlookup(&mlinks, cp));
1172 				free(cp);
1173 			}
1174 			if (mlink_dest != NULL) {
1175 
1176 				/* The .so target exists. */
1177 
1178 				mpage_dest = mlink_dest->mpage;
1179 				while (1) {
1180 					mlink->mpage = mpage_dest;
1181 
1182 					/*
1183 					 * If the target was already
1184 					 * processed, add the links
1185 					 * to the database now.
1186 					 * Otherwise, this will
1187 					 * happen when we come
1188 					 * to the target.
1189 					 */
1190 
1191 					if (mpage_dest->dba != NULL)
1192 						dbadd_mlink(mlink);
1193 
1194 					if (mlink->next == NULL)
1195 						break;
1196 					mlink = mlink->next;
1197 				}
1198 
1199 				/* Move all links to the target. */
1200 
1201 				mlink->next = mlink_dest->next;
1202 				mlink_dest->next = mpage->mlinks;
1203 				mpage->mlinks = NULL;
1204 				goto nextpage;
1205 			}
1206 			meta->macroset = MACROSET_NONE;
1207 		}
1208 		if (meta != NULL && meta->macroset == MACROSET_MDOC) {
1209 			mpage->form = FORM_SRC;
1210 			mpage->sec = meta->msec;
1211 			mpage->sec = mandoc_strdup(
1212 			    mpage->sec == NULL ? "" : mpage->sec);
1213 			mpage->arch = meta->arch;
1214 			mpage->arch = mandoc_strdup(
1215 			    mpage->arch == NULL ? "" : mpage->arch);
1216 			mpage->title = mandoc_strdup(meta->title);
1217 		} else if (meta != NULL && meta->macroset == MACROSET_MAN) {
1218 			if (*meta->msec != '\0' || *meta->title != '\0') {
1219 				mpage->form = FORM_SRC;
1220 				mpage->sec = mandoc_strdup(meta->msec);
1221 				mpage->arch = mandoc_strdup(mlink->arch);
1222 				mpage->title = mandoc_strdup(meta->title);
1223 			} else
1224 				meta = NULL;
1225 		}
1226 
1227 		assert(mpage->desc == NULL);
1228 		if (meta == NULL || meta->sodest != NULL) {
1229 			mpage->sec = mandoc_strdup(mlink->dsec);
1230 			mpage->arch = mandoc_strdup(mlink->arch);
1231 			mpage->title = mandoc_strdup(mlink->name);
1232 			if (meta == NULL) {
1233 				mpage->form = FORM_CAT;
1234 				parse_cat(mpage, fd);
1235 			} else
1236 				mpage->form = FORM_SRC;
1237 		} else if (meta->macroset == MACROSET_MDOC)
1238 			parse_mdoc(mpage, meta, meta->first);
1239 		else
1240 			parse_man(mpage, meta, meta->first);
1241 		if (mpage->desc == NULL) {
1242 			mpage->desc = mandoc_strdup(mlink->name);
1243 			if (warnings)
1244 				say(mlink->file, "No one-line description, "
1245 				    "using filename \"%s\"", mlink->name);
1246 		}
1247 
1248 		for (mlink = mpage->mlinks;
1249 		     mlink != NULL;
1250 		     mlink = mlink->next) {
1251 			putkey(mpage, mlink->name, NAME_FILE);
1252 			if (warnings && !use_all)
1253 				mlink_check(mpage, mlink);
1254 		}
1255 
1256 		dbadd(dba, mpage);
1257 
1258 nextpage:
1259 		ohash_delete(&strings);
1260 		ohash_delete(&names);
1261 	}
1262 }
1263 
1264 static void
1265 parse_cat(struct mpage *mpage, int fd)
1266 {
1267 	FILE		*stream;
1268 	struct mlink	*mlink;
1269 	char		*line, *p, *title, *sec;
1270 	size_t		 linesz, plen, titlesz;
1271 	ssize_t		 len;
1272 	int		 offs;
1273 
1274 	mlink = mpage->mlinks;
1275 	stream = fd == -1 ? fopen(mlink->file, "r") : fdopen(fd, "r");
1276 	if (stream == NULL) {
1277 		if (fd != -1)
1278 			close(fd);
1279 		if (warnings)
1280 			say(mlink->file, "&fopen");
1281 		return;
1282 	}
1283 
1284 	line = NULL;
1285 	linesz = 0;
1286 
1287 	/* Parse the section number from the header line. */
1288 
1289 	while (getline(&line, &linesz, stream) != -1) {
1290 		if (*line == '\n')
1291 			continue;
1292 		if ((sec = strchr(line, '(')) == NULL)
1293 			break;
1294 		if ((p = strchr(++sec, ')')) == NULL)
1295 			break;
1296 		free(mpage->sec);
1297 		mpage->sec = mandoc_strndup(sec, p - sec);
1298 		if (warnings && *mlink->dsec != '\0' &&
1299 		    strcasecmp(mpage->sec, mlink->dsec))
1300 			say(mlink->file,
1301 			    "Section \"%s\" manual in %s directory",
1302 			    mpage->sec, mlink->dsec);
1303 		break;
1304 	}
1305 
1306 	/* Skip to first blank line. */
1307 
1308 	while (line == NULL || *line != '\n')
1309 		if (getline(&line, &linesz, stream) == -1)
1310 			break;
1311 
1312 	/*
1313 	 * Assume the first line that is not indented
1314 	 * is the first section header.  Skip to it.
1315 	 */
1316 
1317 	while (getline(&line, &linesz, stream) != -1)
1318 		if (*line != '\n' && *line != ' ')
1319 			break;
1320 
1321 	/*
1322 	 * Read up until the next section into a buffer.
1323 	 * Strip the leading and trailing newline from each read line,
1324 	 * appending a trailing space.
1325 	 * Ignore empty (whitespace-only) lines.
1326 	 */
1327 
1328 	titlesz = 0;
1329 	title = NULL;
1330 
1331 	while ((len = getline(&line, &linesz, stream)) != -1) {
1332 		if (*line != ' ')
1333 			break;
1334 		offs = 0;
1335 		while (isspace((unsigned char)line[offs]))
1336 			offs++;
1337 		if (line[offs] == '\0')
1338 			continue;
1339 		title = mandoc_realloc(title, titlesz + len - offs);
1340 		memcpy(title + titlesz, line + offs, len - offs);
1341 		titlesz += len - offs;
1342 		title[titlesz - 1] = ' ';
1343 	}
1344 	free(line);
1345 
1346 	/*
1347 	 * If no page content can be found, or the input line
1348 	 * is already the next section header, or there is no
1349 	 * trailing newline, reuse the page title as the page
1350 	 * description.
1351 	 */
1352 
1353 	if (NULL == title || '\0' == *title) {
1354 		if (warnings)
1355 			say(mlink->file, "Cannot find NAME section");
1356 		fclose(stream);
1357 		free(title);
1358 		return;
1359 	}
1360 
1361 	title[titlesz - 1] = '\0';
1362 
1363 	/*
1364 	 * Skip to the first dash.
1365 	 * Use the remaining line as the description (no more than 70
1366 	 * bytes).
1367 	 */
1368 
1369 	if (NULL != (p = strstr(title, "- "))) {
1370 		for (p += 2; ' ' == *p || '\b' == *p; p++)
1371 			/* Skip to next word. */ ;
1372 	} else {
1373 		if (warnings)
1374 			say(mlink->file, "No dash in title line, "
1375 			    "reusing \"%s\" as one-line description", title);
1376 		p = title;
1377 	}
1378 
1379 	plen = strlen(p);
1380 
1381 	/* Strip backspace-encoding from line. */
1382 
1383 	while (NULL != (line = memchr(p, '\b', plen))) {
1384 		len = line - p;
1385 		if (0 == len) {
1386 			memmove(line, line + 1, plen--);
1387 			continue;
1388 		}
1389 		memmove(line - 1, line + 1, plen - len);
1390 		plen -= 2;
1391 	}
1392 
1393 	/*
1394 	 * Cut off excessive one-line descriptions.
1395 	 * Bad pages are not worth better heuristics.
1396 	 */
1397 
1398 	mpage->desc = mandoc_strndup(p, 150);
1399 	fclose(stream);
1400 	free(title);
1401 }
1402 
1403 /*
1404  * Put a type/word pair into the word database for this particular file.
1405  */
1406 static void
1407 putkey(const struct mpage *mpage, char *value, uint64_t type)
1408 {
1409 	putkeys(mpage, value, strlen(value), type);
1410 }
1411 
1412 /*
1413  * Grok all nodes at or below a certain mdoc node into putkey().
1414  */
1415 static void
1416 putmdockey(const struct mpage *mpage,
1417 	const struct roff_node *n, uint64_t m, int taboo)
1418 {
1419 
1420 	for ( ; NULL != n; n = n->next) {
1421 		if (n->flags & taboo)
1422 			continue;
1423 		if (NULL != n->child)
1424 			putmdockey(mpage, n->child, m, taboo);
1425 		if (n->type == ROFFT_TEXT)
1426 			putkey(mpage, n->string, m);
1427 	}
1428 }
1429 
1430 static void
1431 parse_man(struct mpage *mpage, const struct roff_meta *meta,
1432 	const struct roff_node *n)
1433 {
1434 	const struct roff_node *head, *body;
1435 	char		*start, *title;
1436 	char		 byte;
1437 	size_t		 sz;
1438 
1439 	if (n == NULL)
1440 		return;
1441 
1442 	/*
1443 	 * We're only searching for one thing: the first text child in
1444 	 * the BODY of a NAME section.  Since we don't keep track of
1445 	 * sections in -man, run some hoops to find out whether we're in
1446 	 * the correct section or not.
1447 	 */
1448 
1449 	if (n->type == ROFFT_BODY && n->tok == MAN_SH) {
1450 		body = n;
1451 		if ((head = body->parent->head) != NULL &&
1452 		    (head = head->child) != NULL &&
1453 		    head->next == NULL &&
1454 		    head->type == ROFFT_TEXT &&
1455 		    strcmp(head->string, "NAME") == 0 &&
1456 		    body->child != NULL) {
1457 
1458 			/*
1459 			 * Suck the entire NAME section into memory.
1460 			 * Yes, we might run away.
1461 			 * But too many manuals have big, spread-out
1462 			 * NAME sections over many lines.
1463 			 */
1464 
1465 			title = NULL;
1466 			deroff(&title, body);
1467 			if (NULL == title)
1468 				return;
1469 
1470 			/*
1471 			 * Go through a special heuristic dance here.
1472 			 * Conventionally, one or more manual names are
1473 			 * comma-specified prior to a whitespace, then a
1474 			 * dash, then a description.  Try to puzzle out
1475 			 * the name parts here.
1476 			 */
1477 
1478 			start = title;
1479 			for ( ;; ) {
1480 				sz = strcspn(start, " ,");
1481 				if ('\0' == start[sz])
1482 					break;
1483 
1484 				byte = start[sz];
1485 				start[sz] = '\0';
1486 
1487 				/*
1488 				 * Assume a stray trailing comma in the
1489 				 * name list if a name begins with a dash.
1490 				 */
1491 
1492 				if ('-' == start[0] ||
1493 				    ('\\' == start[0] && '-' == start[1]))
1494 					break;
1495 
1496 				putkey(mpage, start, NAME_TITLE);
1497 				if ( ! (mpage->name_head_done ||
1498 				    strcasecmp(start, meta->title))) {
1499 					putkey(mpage, start, NAME_HEAD);
1500 					mpage->name_head_done = 1;
1501 				}
1502 
1503 				if (' ' == byte) {
1504 					start += sz + 1;
1505 					break;
1506 				}
1507 
1508 				assert(',' == byte);
1509 				start += sz + 1;
1510 				while (' ' == *start)
1511 					start++;
1512 			}
1513 
1514 			if (start == title) {
1515 				putkey(mpage, start, NAME_TITLE);
1516 				if ( ! (mpage->name_head_done ||
1517 				    strcasecmp(start, meta->title))) {
1518 					putkey(mpage, start, NAME_HEAD);
1519 					mpage->name_head_done = 1;
1520 				}
1521 				free(title);
1522 				return;
1523 			}
1524 
1525 			while (isspace((unsigned char)*start))
1526 				start++;
1527 
1528 			if (0 == strncmp(start, "-", 1))
1529 				start += 1;
1530 			else if (0 == strncmp(start, "\\-\\-", 4))
1531 				start += 4;
1532 			else if (0 == strncmp(start, "\\-", 2))
1533 				start += 2;
1534 			else if (0 == strncmp(start, "\\(en", 4))
1535 				start += 4;
1536 			else if (0 == strncmp(start, "\\(em", 4))
1537 				start += 4;
1538 
1539 			while (' ' == *start)
1540 				start++;
1541 
1542 			/*
1543 			 * Cut off excessive one-line descriptions.
1544 			 * Bad pages are not worth better heuristics.
1545 			 */
1546 
1547 			mpage->desc = mandoc_strndup(start, 150);
1548 			free(title);
1549 			return;
1550 		}
1551 	}
1552 
1553 	for (n = n->child; n; n = n->next) {
1554 		if (NULL != mpage->desc)
1555 			break;
1556 		parse_man(mpage, meta, n);
1557 	}
1558 }
1559 
1560 static void
1561 parse_mdoc(struct mpage *mpage, const struct roff_meta *meta,
1562 	const struct roff_node *n)
1563 {
1564 	const struct mdoc_handler *handler;
1565 
1566 	for (n = n->child; n != NULL; n = n->next) {
1567 		if (n->tok == TOKEN_NONE || n->tok < ROFF_MAX)
1568 			continue;
1569 		assert(n->tok >= MDOC_Dd && n->tok < MDOC_MAX);
1570 		handler = mdoc_handlers + (n->tok - MDOC_Dd);
1571 		if (n->flags & handler->taboo)
1572 			continue;
1573 
1574 		switch (n->type) {
1575 		case ROFFT_ELEM:
1576 		case ROFFT_BLOCK:
1577 		case ROFFT_HEAD:
1578 		case ROFFT_BODY:
1579 		case ROFFT_TAIL:
1580 			if (handler->fp != NULL &&
1581 			    (*handler->fp)(mpage, meta, n) == 0)
1582 				break;
1583 			if (handler->mask)
1584 				putmdockey(mpage, n->child,
1585 				    handler->mask, handler->taboo);
1586 			break;
1587 		default:
1588 			continue;
1589 		}
1590 		if (NULL != n->child)
1591 			parse_mdoc(mpage, meta, n);
1592 	}
1593 }
1594 
1595 static int
1596 parse_mdoc_Fa(struct mpage *mpage, const struct roff_meta *meta,
1597 	const struct roff_node *n)
1598 {
1599 	uint64_t mask;
1600 
1601 	mask = TYPE_Fa;
1602 	if (n->sec == SEC_SYNOPSIS)
1603 		mask |= TYPE_Vt;
1604 
1605 	putmdockey(mpage, n->child, mask, 0);
1606 	return 0;
1607 }
1608 
1609 static int
1610 parse_mdoc_Fd(struct mpage *mpage, const struct roff_meta *meta,
1611 	const struct roff_node *n)
1612 {
1613 	char		*start, *end;
1614 	size_t		 sz;
1615 
1616 	if (SEC_SYNOPSIS != n->sec ||
1617 	    NULL == (n = n->child) ||
1618 	    n->type != ROFFT_TEXT)
1619 		return 0;
1620 
1621 	/*
1622 	 * Only consider those `Fd' macro fields that begin with an
1623 	 * "inclusion" token (versus, e.g., #define).
1624 	 */
1625 
1626 	if (strcmp("#include", n->string))
1627 		return 0;
1628 
1629 	if ((n = n->next) == NULL || n->type != ROFFT_TEXT)
1630 		return 0;
1631 
1632 	/*
1633 	 * Strip away the enclosing angle brackets and make sure we're
1634 	 * not zero-length.
1635 	 */
1636 
1637 	start = n->string;
1638 	if ('<' == *start || '"' == *start)
1639 		start++;
1640 
1641 	if (0 == (sz = strlen(start)))
1642 		return 0;
1643 
1644 	end = &start[(int)sz - 1];
1645 	if ('>' == *end || '"' == *end)
1646 		end--;
1647 
1648 	if (end > start)
1649 		putkeys(mpage, start, end - start + 1, TYPE_In);
1650 	return 0;
1651 }
1652 
1653 static void
1654 parse_mdoc_fname(struct mpage *mpage, const struct roff_node *n)
1655 {
1656 	char	*cp;
1657 	size_t	 sz;
1658 
1659 	if (n->type != ROFFT_TEXT)
1660 		return;
1661 
1662 	/* Skip function pointer punctuation. */
1663 
1664 	cp = n->string;
1665 	while (*cp == '(' || *cp == '*')
1666 		cp++;
1667 	sz = strcspn(cp, "()");
1668 
1669 	putkeys(mpage, cp, sz, TYPE_Fn);
1670 	if (n->sec == SEC_SYNOPSIS)
1671 		putkeys(mpage, cp, sz, NAME_SYN);
1672 }
1673 
1674 static int
1675 parse_mdoc_Fn(struct mpage *mpage, const struct roff_meta *meta,
1676 	const struct roff_node *n)
1677 {
1678 	uint64_t mask;
1679 
1680 	if (n->child == NULL)
1681 		return 0;
1682 
1683 	parse_mdoc_fname(mpage, n->child);
1684 
1685 	n = n->child->next;
1686 	if (n != NULL && n->type == ROFFT_TEXT) {
1687 		mask = TYPE_Fa;
1688 		if (n->sec == SEC_SYNOPSIS)
1689 			mask |= TYPE_Vt;
1690 		putmdockey(mpage, n, mask, 0);
1691 	}
1692 
1693 	return 0;
1694 }
1695 
1696 static int
1697 parse_mdoc_Fo(struct mpage *mpage, const struct roff_meta *meta,
1698 	const struct roff_node *n)
1699 {
1700 
1701 	if (n->type != ROFFT_HEAD)
1702 		return 1;
1703 
1704 	if (n->child != NULL)
1705 		parse_mdoc_fname(mpage, n->child);
1706 
1707 	return 0;
1708 }
1709 
1710 static int
1711 parse_mdoc_Va(struct mpage *mpage, const struct roff_meta *meta,
1712 	const struct roff_node *n)
1713 {
1714 	char *cp;
1715 
1716 	if (n->type != ROFFT_ELEM && n->type != ROFFT_BODY)
1717 		return 0;
1718 
1719 	if (n->child != NULL &&
1720 	    n->child->next == NULL &&
1721 	    n->child->type == ROFFT_TEXT)
1722 		return 1;
1723 
1724 	cp = NULL;
1725 	deroff(&cp, n);
1726 	if (cp != NULL) {
1727 		putkey(mpage, cp, TYPE_Vt | (n->tok == MDOC_Va ||
1728 		    n->type == ROFFT_BODY ? TYPE_Va : 0));
1729 		free(cp);
1730 	}
1731 
1732 	return 0;
1733 }
1734 
1735 static int
1736 parse_mdoc_Xr(struct mpage *mpage, const struct roff_meta *meta,
1737 	const struct roff_node *n)
1738 {
1739 	char	*cp;
1740 
1741 	if (NULL == (n = n->child))
1742 		return 0;
1743 
1744 	if (NULL == n->next) {
1745 		putkey(mpage, n->string, TYPE_Xr);
1746 		return 0;
1747 	}
1748 
1749 	mandoc_asprintf(&cp, "%s(%s)", n->string, n->next->string);
1750 	putkey(mpage, cp, TYPE_Xr);
1751 	free(cp);
1752 	return 0;
1753 }
1754 
1755 static int
1756 parse_mdoc_Nd(struct mpage *mpage, const struct roff_meta *meta,
1757 	const struct roff_node *n)
1758 {
1759 
1760 	if (n->type == ROFFT_BODY)
1761 		deroff(&mpage->desc, n);
1762 	return 0;
1763 }
1764 
1765 static int
1766 parse_mdoc_Nm(struct mpage *mpage, const struct roff_meta *meta,
1767 	const struct roff_node *n)
1768 {
1769 
1770 	if (SEC_NAME == n->sec)
1771 		putmdockey(mpage, n->child, NAME_TITLE, 0);
1772 	else if (n->sec == SEC_SYNOPSIS && n->type == ROFFT_HEAD) {
1773 		if (n->child == NULL)
1774 			putkey(mpage, meta->name, NAME_SYN);
1775 		else
1776 			putmdockey(mpage, n->child, NAME_SYN, 0);
1777 	}
1778 	if ( ! (mpage->name_head_done ||
1779 	    n->child == NULL || n->child->string == NULL ||
1780 	    strcasecmp(n->child->string, meta->title))) {
1781 		putkey(mpage, n->child->string, NAME_HEAD);
1782 		mpage->name_head_done = 1;
1783 	}
1784 	return 0;
1785 }
1786 
1787 static int
1788 parse_mdoc_Sh(struct mpage *mpage, const struct roff_meta *meta,
1789 	const struct roff_node *n)
1790 {
1791 
1792 	return n->sec == SEC_CUSTOM && n->type == ROFFT_HEAD;
1793 }
1794 
1795 static int
1796 parse_mdoc_head(struct mpage *mpage, const struct roff_meta *meta,
1797 	const struct roff_node *n)
1798 {
1799 
1800 	return n->type == ROFFT_HEAD;
1801 }
1802 
1803 /*
1804  * Add a string to the hash table for the current manual.
1805  * Each string has a bitmask telling which macros it belongs to.
1806  * When we finish the manual, we'll dump the table.
1807  */
1808 static void
1809 putkeys(const struct mpage *mpage, char *cp, size_t sz, uint64_t v)
1810 {
1811 	struct ohash	*htab;
1812 	struct str	*s;
1813 	const char	*end;
1814 	unsigned int	 slot;
1815 	int		 i, mustfree;
1816 
1817 	if (0 == sz)
1818 		return;
1819 
1820 	mustfree = render_string(&cp, &sz);
1821 
1822 	if (TYPE_Nm & v) {
1823 		htab = &names;
1824 		v &= name_mask;
1825 		if (v & NAME_FIRST)
1826 			name_mask &= ~NAME_FIRST;
1827 		if (debug > 1)
1828 			say(mpage->mlinks->file,
1829 			    "Adding name %*s, bits=0x%llx", (int)sz, cp,
1830 			    (unsigned long long)v);
1831 	} else {
1832 		htab = &strings;
1833 		if (debug > 1)
1834 		    for (i = 0; i < KEY_MAX; i++)
1835 			if ((uint64_t)1 << i & v)
1836 			    say(mpage->mlinks->file,
1837 				"Adding key %s=%*s",
1838 				mansearch_keynames[i], (int)sz, cp);
1839 	}
1840 
1841 	end = cp + sz;
1842 	slot = ohash_qlookupi(htab, cp, &end);
1843 	s = ohash_find(htab, slot);
1844 
1845 	if (NULL != s && mpage == s->mpage) {
1846 		s->mask |= v;
1847 		return;
1848 	} else if (NULL == s) {
1849 		s = mandoc_calloc(1, sizeof(struct str) + sz + 1);
1850 		memcpy(s->key, cp, sz);
1851 		ohash_insert(htab, slot, s);
1852 	}
1853 	s->mpage = mpage;
1854 	s->mask = v;
1855 
1856 	if (mustfree)
1857 		free(cp);
1858 }
1859 
1860 /*
1861  * Take a Unicode codepoint and produce its UTF-8 encoding.
1862  * This isn't the best way to do this, but it works.
1863  * The magic numbers are from the UTF-8 packaging.
1864  * They're not as scary as they seem: read the UTF-8 spec for details.
1865  */
1866 static size_t
1867 utf8(unsigned int cp, char out[7])
1868 {
1869 	size_t		 rc;
1870 
1871 	rc = 0;
1872 	if (cp <= 0x0000007F) {
1873 		rc = 1;
1874 		out[0] = (char)cp;
1875 	} else if (cp <= 0x000007FF) {
1876 		rc = 2;
1877 		out[0] = (cp >> 6  & 31) | 192;
1878 		out[1] = (cp       & 63) | 128;
1879 	} else if (cp <= 0x0000FFFF) {
1880 		rc = 3;
1881 		out[0] = (cp >> 12 & 15) | 224;
1882 		out[1] = (cp >> 6  & 63) | 128;
1883 		out[2] = (cp       & 63) | 128;
1884 	} else if (cp <= 0x001FFFFF) {
1885 		rc = 4;
1886 		out[0] = (cp >> 18 &  7) | 240;
1887 		out[1] = (cp >> 12 & 63) | 128;
1888 		out[2] = (cp >> 6  & 63) | 128;
1889 		out[3] = (cp       & 63) | 128;
1890 	} else if (cp <= 0x03FFFFFF) {
1891 		rc = 5;
1892 		out[0] = (cp >> 24 &  3) | 248;
1893 		out[1] = (cp >> 18 & 63) | 128;
1894 		out[2] = (cp >> 12 & 63) | 128;
1895 		out[3] = (cp >> 6  & 63) | 128;
1896 		out[4] = (cp       & 63) | 128;
1897 	} else if (cp <= 0x7FFFFFFF) {
1898 		rc = 6;
1899 		out[0] = (cp >> 30 &  1) | 252;
1900 		out[1] = (cp >> 24 & 63) | 128;
1901 		out[2] = (cp >> 18 & 63) | 128;
1902 		out[3] = (cp >> 12 & 63) | 128;
1903 		out[4] = (cp >> 6  & 63) | 128;
1904 		out[5] = (cp       & 63) | 128;
1905 	} else
1906 		return 0;
1907 
1908 	out[rc] = '\0';
1909 	return rc;
1910 }
1911 
1912 /*
1913  * If the string contains escape sequences,
1914  * replace it with an allocated rendering and return 1,
1915  * such that the caller can free it after use.
1916  * Otherwise, do nothing and return 0.
1917  */
1918 static int
1919 render_string(char **public, size_t *psz)
1920 {
1921 	const char	*src, *scp, *addcp, *seq;
1922 	char		*dst;
1923 	size_t		 ssz, dsz, addsz;
1924 	char		 utfbuf[7], res[6];
1925 	int		 seqlen, unicode;
1926 
1927 	res[0] = '\\';
1928 	res[1] = '\t';
1929 	res[2] = ASCII_NBRSP;
1930 	res[3] = ASCII_HYPH;
1931 	res[4] = ASCII_BREAK;
1932 	res[5] = '\0';
1933 
1934 	src = scp = *public;
1935 	ssz = *psz;
1936 	dst = NULL;
1937 	dsz = 0;
1938 
1939 	while (scp < src + *psz) {
1940 
1941 		/* Leave normal characters unchanged. */
1942 
1943 		if (strchr(res, *scp) == NULL) {
1944 			if (dst != NULL)
1945 				dst[dsz++] = *scp;
1946 			scp++;
1947 			continue;
1948 		}
1949 
1950 		/*
1951 		 * Found something that requires replacing,
1952 		 * make sure we have a destination buffer.
1953 		 */
1954 
1955 		if (dst == NULL) {
1956 			dst = mandoc_malloc(ssz + 1);
1957 			dsz = scp - src;
1958 			memcpy(dst, src, dsz);
1959 		}
1960 
1961 		/* Handle single-char special characters. */
1962 
1963 		switch (*scp) {
1964 		case '\\':
1965 			break;
1966 		case '\t':
1967 		case ASCII_NBRSP:
1968 			dst[dsz++] = ' ';
1969 			scp++;
1970 			continue;
1971 		case ASCII_HYPH:
1972 			dst[dsz++] = '-';
1973 			/* FALLTHROUGH */
1974 		case ASCII_BREAK:
1975 			scp++;
1976 			continue;
1977 		default:
1978 			abort();
1979 		}
1980 
1981 		/*
1982 		 * Found an escape sequence.
1983 		 * Read past the slash, then parse it.
1984 		 * Ignore everything except characters.
1985 		 */
1986 
1987 		scp++;
1988 		if (mandoc_escape(&scp, &seq, &seqlen) != ESCAPE_SPECIAL)
1989 			continue;
1990 
1991 		/*
1992 		 * Render the special character
1993 		 * as either UTF-8 or ASCII.
1994 		 */
1995 
1996 		if (write_utf8) {
1997 			unicode = mchars_spec2cp(seq, seqlen);
1998 			if (unicode <= 0)
1999 				continue;
2000 			addsz = utf8(unicode, utfbuf);
2001 			if (addsz == 0)
2002 				continue;
2003 			addcp = utfbuf;
2004 		} else {
2005 			addcp = mchars_spec2str(seq, seqlen, &addsz);
2006 			if (addcp == NULL)
2007 				continue;
2008 			if (*addcp == ASCII_NBRSP) {
2009 				addcp = " ";
2010 				addsz = 1;
2011 			}
2012 		}
2013 
2014 		/* Copy the rendered glyph into the stream. */
2015 
2016 		ssz += addsz;
2017 		dst = mandoc_realloc(dst, ssz + 1);
2018 		memcpy(dst + dsz, addcp, addsz);
2019 		dsz += addsz;
2020 	}
2021 	if (dst != NULL) {
2022 		*public = dst;
2023 		*psz = dsz;
2024 	}
2025 
2026 	/* Trim trailing whitespace and NUL-terminate. */
2027 
2028 	while (*psz > 0 && (*public)[*psz - 1] == ' ')
2029 		--*psz;
2030 	if (dst != NULL) {
2031 		(*public)[*psz] = '\0';
2032 		return 1;
2033 	} else
2034 		return 0;
2035 }
2036 
2037 static void
2038 dbadd_mlink(const struct mlink *mlink)
2039 {
2040 	dba_page_alias(mlink->mpage->dba, mlink->name, NAME_FILE);
2041 	dba_page_add(mlink->mpage->dba, DBP_SECT, mlink->dsec);
2042 	dba_page_add(mlink->mpage->dba, DBP_SECT, mlink->fsec);
2043 	dba_page_add(mlink->mpage->dba, DBP_ARCH, mlink->arch);
2044 	dba_page_add(mlink->mpage->dba, DBP_FILE, mlink->file);
2045 }
2046 
2047 /*
2048  * Flush the current page's terms (and their bits) into the database.
2049  * Also, handle escape sequences at the last possible moment.
2050  */
2051 static void
2052 dbadd(struct dba *dba, struct mpage *mpage)
2053 {
2054 	struct mlink	*mlink;
2055 	struct str	*key;
2056 	char		*cp;
2057 	uint64_t	 mask;
2058 	size_t		 i;
2059 	unsigned int	 slot;
2060 	int		 mustfree;
2061 
2062 	mlink = mpage->mlinks;
2063 
2064 	if (nodb) {
2065 		for (key = ohash_first(&names, &slot); NULL != key;
2066 		     key = ohash_next(&names, &slot))
2067 			free(key);
2068 		for (key = ohash_first(&strings, &slot); NULL != key;
2069 		     key = ohash_next(&strings, &slot))
2070 			free(key);
2071 		if (0 == debug)
2072 			return;
2073 		while (NULL != mlink) {
2074 			fputs(mlink->name, stdout);
2075 			if (NULL == mlink->next ||
2076 			    strcmp(mlink->dsec, mlink->next->dsec) ||
2077 			    strcmp(mlink->fsec, mlink->next->fsec) ||
2078 			    strcmp(mlink->arch, mlink->next->arch)) {
2079 				putchar('(');
2080 				if ('\0' == *mlink->dsec)
2081 					fputs(mlink->fsec, stdout);
2082 				else
2083 					fputs(mlink->dsec, stdout);
2084 				if ('\0' != *mlink->arch)
2085 					printf("/%s", mlink->arch);
2086 				putchar(')');
2087 			}
2088 			mlink = mlink->next;
2089 			if (NULL != mlink)
2090 				fputs(", ", stdout);
2091 		}
2092 		printf(" - %s\n", mpage->desc);
2093 		return;
2094 	}
2095 
2096 	if (debug)
2097 		say(mlink->file, "Adding to database");
2098 
2099 	cp = mpage->desc;
2100 	i = strlen(cp);
2101 	mustfree = render_string(&cp, &i);
2102 	mpage->dba = dba_page_new(dba->pages,
2103 	    *mpage->arch == '\0' ? mlink->arch : mpage->arch,
2104 	    cp, mlink->file, mpage->form);
2105 	if (mustfree)
2106 		free(cp);
2107 	dba_page_add(mpage->dba, DBP_SECT, mpage->sec);
2108 
2109 	while (mlink != NULL) {
2110 		dbadd_mlink(mlink);
2111 		mlink = mlink->next;
2112 	}
2113 
2114 	for (key = ohash_first(&names, &slot); NULL != key;
2115 	     key = ohash_next(&names, &slot)) {
2116 		assert(key->mpage == mpage);
2117 		dba_page_alias(mpage->dba, key->key, key->mask);
2118 		free(key);
2119 	}
2120 	for (key = ohash_first(&strings, &slot); NULL != key;
2121 	     key = ohash_next(&strings, &slot)) {
2122 		assert(key->mpage == mpage);
2123 		i = 0;
2124 		for (mask = TYPE_Xr; mask <= TYPE_Lb; mask *= 2) {
2125 			if (key->mask & mask)
2126 				dba_macro_add(dba->macros, i,
2127 				    key->key, mpage->dba);
2128 			i++;
2129 		}
2130 		free(key);
2131 	}
2132 }
2133 
2134 static void
2135 dbprune(struct dba *dba)
2136 {
2137 	struct dba_array	*page, *files;
2138 	char			*file;
2139 
2140 	dba_array_FOREACH(dba->pages, page) {
2141 		files = dba_array_get(page, DBP_FILE);
2142 		dba_array_FOREACH(files, file) {
2143 			if (*file < ' ')
2144 				file++;
2145 			if (ohash_find(&mlinks, ohash_qlookup(&mlinks,
2146 			    file)) != NULL) {
2147 				if (debug)
2148 					say(file, "Deleting from database");
2149 				dba_array_del(dba->pages);
2150 				break;
2151 			}
2152 		}
2153 	}
2154 }
2155 
2156 /*
2157  * Write the database from memory to disk.
2158  */
2159 static void
2160 dbwrite(struct dba *dba)
2161 {
2162 	struct stat	 sb1, sb2;
2163 	char		 tfn[33], *cp1, *cp2;
2164 	off_t		 i;
2165 	int		 fd1, fd2;
2166 
2167 	/*
2168 	 * Do not write empty databases, and delete existing ones
2169 	 * when makewhatis -u causes them to become empty.
2170 	 */
2171 
2172 	dba_array_start(dba->pages);
2173 	if (dba_array_next(dba->pages) == NULL) {
2174 		if (unlink(MANDOC_DB) == -1 && errno != ENOENT)
2175 			say(MANDOC_DB, "&unlink");
2176 		return;
2177 	}
2178 
2179 	/*
2180 	 * Build the database in a temporary file,
2181 	 * then atomically move it into place.
2182 	 */
2183 
2184 	if (dba_write(MANDOC_DB "~", dba) != -1) {
2185 		if (rename(MANDOC_DB "~", MANDOC_DB) == -1) {
2186 			exitcode = (int)MANDOCLEVEL_SYSERR;
2187 			say(MANDOC_DB, "&rename");
2188 			unlink(MANDOC_DB "~");
2189 		}
2190 		return;
2191 	}
2192 
2193 	/*
2194 	 * We lack write permission and cannot replace the database
2195 	 * file, but let's at least check whether the data changed.
2196 	 */
2197 
2198 	(void)strlcpy(tfn, "/tmp/mandocdb.XXXXXXXX", sizeof(tfn));
2199 	if (mkdtemp(tfn) == NULL) {
2200 		exitcode = (int)MANDOCLEVEL_SYSERR;
2201 		say("", "&%s", tfn);
2202 		return;
2203 	}
2204 	cp1 = cp2 = MAP_FAILED;
2205 	fd1 = fd2 = -1;
2206 	(void)strlcat(tfn, "/" MANDOC_DB, sizeof(tfn));
2207 	if (dba_write(tfn, dba) == -1) {
2208 		say(tfn, "&dba_write");
2209 		goto err;
2210 	}
2211 	if ((fd1 = open(MANDOC_DB, O_RDONLY, 0)) == -1) {
2212 		say(MANDOC_DB, "&open");
2213 		goto err;
2214 	}
2215 	if ((fd2 = open(tfn, O_RDONLY, 0)) == -1) {
2216 		say(tfn, "&open");
2217 		goto err;
2218 	}
2219 	if (fstat(fd1, &sb1) == -1) {
2220 		say(MANDOC_DB, "&fstat");
2221 		goto err;
2222 	}
2223 	if (fstat(fd2, &sb2) == -1) {
2224 		say(tfn, "&fstat");
2225 		goto err;
2226 	}
2227 	if (sb1.st_size != sb2.st_size)
2228 		goto err;
2229 	if ((cp1 = mmap(NULL, sb1.st_size, PROT_READ, MAP_PRIVATE,
2230 	    fd1, 0)) == MAP_FAILED) {
2231 		say(MANDOC_DB, "&mmap");
2232 		goto err;
2233 	}
2234 	if ((cp2 = mmap(NULL, sb2.st_size, PROT_READ, MAP_PRIVATE,
2235 	    fd2, 0)) == MAP_FAILED) {
2236 		say(tfn, "&mmap");
2237 		goto err;
2238 	}
2239 	for (i = 0; i < sb1.st_size; i++)
2240 		if (cp1[i] != cp2[i])
2241 			goto err;
2242 	goto out;
2243 
2244 err:
2245 	exitcode = (int)MANDOCLEVEL_SYSERR;
2246 	say(MANDOC_DB, "Data changed, but cannot replace database");
2247 
2248 out:
2249 	if (cp1 != MAP_FAILED)
2250 		munmap(cp1, sb1.st_size);
2251 	if (cp2 != MAP_FAILED)
2252 		munmap(cp2, sb2.st_size);
2253 	if (fd1 != -1)
2254 		close(fd1);
2255 	if (fd2 != -1)
2256 		close(fd2);
2257 	unlink(tfn);
2258 	*strrchr(tfn, '/') = '\0';
2259 	rmdir(tfn);
2260 }
2261 
2262 static int
2263 set_basedir(const char *targetdir, int report_baddir)
2264 {
2265 	static char	 startdir[PATH_MAX];
2266 	static int	 getcwd_status;  /* 1 = ok, 2 = failure */
2267 	static int	 chdir_status;  /* 1 = changed directory */
2268 
2269 	/*
2270 	 * Remember the original working directory, if possible.
2271 	 * This will be needed if the second or a later directory
2272 	 * on the command line is given as a relative path.
2273 	 * Do not error out if the current directory is not
2274 	 * searchable: Maybe it won't be needed after all.
2275 	 */
2276 	if (getcwd_status == 0) {
2277 		if (getcwd(startdir, sizeof(startdir)) == NULL) {
2278 			getcwd_status = 2;
2279 			(void)strlcpy(startdir, strerror(errno),
2280 			    sizeof(startdir));
2281 		} else
2282 			getcwd_status = 1;
2283 	}
2284 
2285 	/*
2286 	 * We are leaving the old base directory.
2287 	 * Do not use it any longer, not even for messages.
2288 	 */
2289 	*basedir = '\0';
2290 	basedir_len = 0;
2291 
2292 	/*
2293 	 * If and only if the directory was changed earlier and
2294 	 * the next directory to process is given as a relative path,
2295 	 * first go back, or bail out if that is impossible.
2296 	 */
2297 	if (chdir_status && *targetdir != '/') {
2298 		if (getcwd_status == 2) {
2299 			exitcode = (int)MANDOCLEVEL_SYSERR;
2300 			say("", "getcwd: %s", startdir);
2301 			return 0;
2302 		}
2303 		if (chdir(startdir) == -1) {
2304 			exitcode = (int)MANDOCLEVEL_SYSERR;
2305 			say("", "&chdir %s", startdir);
2306 			return 0;
2307 		}
2308 	}
2309 
2310 	/*
2311 	 * Always resolve basedir to the canonicalized absolute
2312 	 * pathname and append a trailing slash, such that
2313 	 * we can reliably check whether files are inside.
2314 	 */
2315 	if (realpath(targetdir, basedir) == NULL) {
2316 		if (report_baddir || errno != ENOENT) {
2317 			exitcode = (int)MANDOCLEVEL_BADARG;
2318 			say("", "&%s: realpath", targetdir);
2319 		}
2320 		*basedir = '\0';
2321 		return 0;
2322 	} else if (chdir(basedir) == -1) {
2323 		if (report_baddir || errno != ENOENT) {
2324 			exitcode = (int)MANDOCLEVEL_BADARG;
2325 			say("", "&chdir");
2326 		}
2327 		*basedir = '\0';
2328 		return 0;
2329 	}
2330 	chdir_status = 1;
2331 	basedir_len = strlen(basedir);
2332 	if (basedir[basedir_len - 1] != '/') {
2333 		if (basedir_len >= PATH_MAX - 1) {
2334 			exitcode = (int)MANDOCLEVEL_SYSERR;
2335 			say("", "Filename too long");
2336 			*basedir = '\0';
2337 			basedir_len = 0;
2338 			return 0;
2339 		}
2340 		basedir[basedir_len++] = '/';
2341 		basedir[basedir_len] = '\0';
2342 	}
2343 	return 1;
2344 }
2345 
2346 static void
2347 say(const char *file, const char *format, ...)
2348 {
2349 	va_list		 ap;
2350 	int		 use_errno;
2351 
2352 	if (*basedir != '\0')
2353 		fprintf(stderr, "%s", basedir);
2354 	if (*basedir != '\0' && *file != '\0')
2355 		fputc('/', stderr);
2356 	if (*file != '\0')
2357 		fprintf(stderr, "%s", file);
2358 
2359 	use_errno = 1;
2360 	if (format != NULL) {
2361 		switch (*format) {
2362 		case '&':
2363 			format++;
2364 			break;
2365 		case '\0':
2366 			format = NULL;
2367 			break;
2368 		default:
2369 			use_errno = 0;
2370 			break;
2371 		}
2372 	}
2373 	if (format != NULL) {
2374 		if (*basedir != '\0' || *file != '\0')
2375 			fputs(": ", stderr);
2376 		va_start(ap, format);
2377 		vfprintf(stderr, format, ap);
2378 		va_end(ap);
2379 	}
2380 	if (use_errno) {
2381 		if (*basedir != '\0' || *file != '\0' || format != NULL)
2382 			fputs(": ", stderr);
2383 		perror(NULL);
2384 	} else
2385 		fputc('\n', stderr);
2386 }
2387