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