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