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