xref: /openbsd-src/usr.bin/mandoc/main.c (revision 824adb5411e4389b29bae28eba5c2c2bbd147f34)
1 /* $OpenBSD: main.c,v 1.262 2021/10/04 21:28:50 schwarze Exp $ */
2 /*
3  * Copyright (c) 2010-2012, 2014-2021 Ingo Schwarze <schwarze@openbsd.org>
4  * Copyright (c) 2008-2012 Kristaps Dzonsons <kristaps@bsd.lv>
5  * Copyright (c) 2010 Joerg Sonnenberger <joerg@netbsd.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  * Main program for mandoc(1), man(1), apropos(1), whatis(1), and help(1).
20  */
21 #include <sys/types.h>
22 #include <sys/ioctl.h>
23 #include <sys/param.h>	/* MACHINE */
24 #include <sys/stat.h>
25 #include <sys/wait.h>
26 
27 #include <assert.h>
28 #include <ctype.h>
29 #include <err.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <glob.h>
33 #include <limits.h>
34 #include <signal.h>
35 #include <stdio.h>
36 #include <stdint.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <termios.h>
40 #include <time.h>
41 #include <unistd.h>
42 
43 #include "mandoc_aux.h"
44 #include "mandoc.h"
45 #include "mandoc_xr.h"
46 #include "roff.h"
47 #include "mdoc.h"
48 #include "man.h"
49 #include "mandoc_parse.h"
50 #include "tag.h"
51 #include "term_tag.h"
52 #include "main.h"
53 #include "manconf.h"
54 #include "mansearch.h"
55 
56 #define BINM_APROPOS	"apropos"
57 #define BINM_MAN	"man"
58 #define BINM_MAKEWHATIS	"makewhatis"
59 #define BINM_WHATIS	"whatis"
60 #define OSENUM		MANDOC_OS_OPENBSD
61 
62 enum	outmode {
63 	OUTMODE_DEF = 0,
64 	OUTMODE_FLN,
65 	OUTMODE_LST,
66 	OUTMODE_ALL,
67 	OUTMODE_ONE
68 };
69 
70 enum	outt {
71 	OUTT_ASCII = 0,	/* -Tascii */
72 	OUTT_LOCALE,	/* -Tlocale */
73 	OUTT_UTF8,	/* -Tutf8 */
74 	OUTT_TREE,	/* -Ttree */
75 	OUTT_MAN,	/* -Tman */
76 	OUTT_HTML,	/* -Thtml */
77 	OUTT_MARKDOWN,	/* -Tmarkdown */
78 	OUTT_LINT,	/* -Tlint */
79 	OUTT_PS,	/* -Tps */
80 	OUTT_PDF	/* -Tpdf */
81 };
82 
83 struct	outstate {
84 	struct tag_files *tag_files;	/* Tagging state variables. */
85 	void		 *outdata;	/* data for output */
86 	int		  use_pager;
87 	int		  wstop;	/* stop after a file with a warning */
88 	int		  had_output;	/* Some output was generated. */
89 	enum outt	  outtype;	/* which output to use */
90 };
91 
92 
93 int			  mandocdb(int, char *[]);
94 
95 static	void		  check_xr(struct manpaths *);
96 static	void		  fs_append(char **, size_t, int,
97 				size_t, const char *, enum form,
98 				struct manpage **, size_t *);
99 static	int		  fs_lookup(const struct manpaths *, size_t,
100 				const char *, const char *, const char *,
101 				struct manpage **, size_t *);
102 static	int		  fs_search(const struct mansearch *,
103 				const struct manpaths *, const char *,
104 				struct manpage **, size_t *);
105 static	void		  glob_esc(char **, const char *, const char *);
106 static	void		  outdata_alloc(struct outstate *, struct manoutput *);
107 static	void		  parse(struct mparse *, int, const char *,
108 				struct outstate *, struct manconf *);
109 static	void		  passthrough(int, int);
110 static	void		  process_onefile(struct mparse *, struct manpage *,
111 				int, struct outstate *, struct manconf *);
112 static	void		  run_pager(struct outstate *, char *);
113 static	pid_t		  spawn_pager(struct outstate *, char *);
114 static	void		  usage(enum argmode) __attribute__((__noreturn__));
115 static	int		  woptions(char *, enum mandoc_os *, int *);
116 
117 static	const int sec_prios[] = {1, 4, 5, 8, 6, 3, 7, 2, 9};
118 static	char		  help_arg[] = "help";
119 static	char		 *help_argv[] = {help_arg, NULL};
120 
121 
122 int
123 main(int argc, char *argv[])
124 {
125 	struct manconf	 conf;		/* Manpaths and output options. */
126 	struct outstate	 outst;		/* Output state. */
127 	struct winsize	 ws;		/* Result of ioctl(TIOCGWINSZ). */
128 	struct mansearch search;	/* Search options. */
129 	struct manpage	*res;		/* Complete list of search results. */
130 	struct manpage	*resn;		/* Search results for one name. */
131 	struct mparse	*mp;		/* Opaque parser object. */
132 	const char	*conf_file;	/* -C: alternate config file. */
133 	const char	*os_s;		/* -I: Operating system for display. */
134 	const char	*progname, *sec, *ep;
135 	char		*defpaths;	/* -M: override manpaths. */
136 	char		*auxpaths;	/* -m: additional manpaths. */
137 	char		*oarg;		/* -O: output option string. */
138 	char		*tagarg;	/* -O tag: default value. */
139 	unsigned char	*uc;
140 	size_t		 ressz;		/* Number of elements in res[]. */
141 	size_t		 resnsz;	/* Number of elements in resn[]. */
142 	size_t		 i, ib, ssz;
143 	int		 options;	/* Parser options. */
144 	int		 show_usage;	/* Invalid argument: give up. */
145 	int		 prio, best_prio;
146 	int		 startdir;
147 	int		 c;
148 	enum mandoc_os	 os_e;		/* Check base system conventions. */
149 	enum outmode	 outmode;	/* According to command line. */
150 
151 	progname = getprogname();
152 	mandoc_msg_setoutfile(stderr);
153 	if (strncmp(progname, "mandocdb", 8) == 0 ||
154 	    strcmp(progname, BINM_MAKEWHATIS) == 0)
155 		return mandocdb(argc, argv);
156 
157 	if (pledge("stdio rpath wpath cpath tmppath tty proc exec", NULL) == -1) {
158 		mandoc_msg(MANDOCERR_PLEDGE, 0, 0, "%s", strerror(errno));
159 		return mandoc_msg_getrc();
160 	}
161 
162 	/* Search options. */
163 
164 	memset(&conf, 0, sizeof(conf));
165 	conf_file = NULL;
166 	defpaths = auxpaths = NULL;
167 
168 	memset(&search, 0, sizeof(struct mansearch));
169 	search.outkey = "Nd";
170 	oarg = NULL;
171 
172 	if (strcmp(progname, BINM_MAN) == 0)
173 		search.argmode = ARG_NAME;
174 	else if (strcmp(progname, BINM_APROPOS) == 0)
175 		search.argmode = ARG_EXPR;
176 	else if (strcmp(progname, BINM_WHATIS) == 0)
177 		search.argmode = ARG_WORD;
178 	else if (strncmp(progname, "help", 4) == 0)
179 		search.argmode = ARG_NAME;
180 	else
181 		search.argmode = ARG_FILE;
182 
183 	/* Parser options. */
184 
185 	options = MPARSE_SO | MPARSE_UTF8 | MPARSE_LATIN1;
186 	os_e = MANDOC_OS_OTHER;
187 	os_s = NULL;
188 
189 	/* Formatter options. */
190 
191 	memset(&outst, 0, sizeof(outst));
192 	outst.tag_files = NULL;
193 	outst.outtype = OUTT_LOCALE;
194 	outst.use_pager = 1;
195 
196 	show_usage = 0;
197 	outmode = OUTMODE_DEF;
198 
199 	while ((c = getopt(argc, argv,
200 	    "aC:cfhI:iK:klM:m:O:S:s:T:VW:w")) != -1) {
201 		if (c == 'i' && search.argmode == ARG_EXPR) {
202 			optind--;
203 			break;
204 		}
205 		switch (c) {
206 		case 'a':
207 			outmode = OUTMODE_ALL;
208 			break;
209 		case 'C':
210 			conf_file = optarg;
211 			break;
212 		case 'c':
213 			outst.use_pager = 0;
214 			break;
215 		case 'f':
216 			search.argmode = ARG_WORD;
217 			break;
218 		case 'h':
219 			conf.output.synopsisonly = 1;
220 			outst.use_pager = 0;
221 			outmode = OUTMODE_ALL;
222 			break;
223 		case 'I':
224 			if (strncmp(optarg, "os=", 3) != 0) {
225 				mandoc_msg(MANDOCERR_BADARG_BAD, 0, 0,
226 				    "-I %s", optarg);
227 				return mandoc_msg_getrc();
228 			}
229 			if (os_s != NULL) {
230 				mandoc_msg(MANDOCERR_BADARG_DUPE, 0, 0,
231 				    "-I %s", optarg);
232 				return mandoc_msg_getrc();
233 			}
234 			os_s = optarg + 3;
235 			break;
236 		case 'K':
237 			options &= ~(MPARSE_UTF8 | MPARSE_LATIN1);
238 			if (strcmp(optarg, "utf-8") == 0)
239 				options |=  MPARSE_UTF8;
240 			else if (strcmp(optarg, "iso-8859-1") == 0)
241 				options |=  MPARSE_LATIN1;
242 			else if (strcmp(optarg, "us-ascii") != 0) {
243 				mandoc_msg(MANDOCERR_BADARG_BAD, 0, 0,
244 				    "-K %s", optarg);
245 				return mandoc_msg_getrc();
246 			}
247 			break;
248 		case 'k':
249 			search.argmode = ARG_EXPR;
250 			break;
251 		case 'l':
252 			search.argmode = ARG_FILE;
253 			outmode = OUTMODE_ALL;
254 			break;
255 		case 'M':
256 			defpaths = optarg;
257 			break;
258 		case 'm':
259 			auxpaths = optarg;
260 			break;
261 		case 'O':
262 			oarg = optarg;
263 			break;
264 		case 'S':
265 			search.arch = optarg;
266 			break;
267 		case 's':
268 			search.sec = optarg;
269 			break;
270 		case 'T':
271 			if (strcmp(optarg, "ascii") == 0)
272 				outst.outtype = OUTT_ASCII;
273 			else if (strcmp(optarg, "lint") == 0) {
274 				outst.outtype = OUTT_LINT;
275 				mandoc_msg_setoutfile(stdout);
276 				mandoc_msg_setmin(MANDOCERR_BASE);
277 			} else if (strcmp(optarg, "tree") == 0)
278 				outst.outtype = OUTT_TREE;
279 			else if (strcmp(optarg, "man") == 0)
280 				outst.outtype = OUTT_MAN;
281 			else if (strcmp(optarg, "html") == 0)
282 				outst.outtype = OUTT_HTML;
283 			else if (strcmp(optarg, "markdown") == 0)
284 				outst.outtype = OUTT_MARKDOWN;
285 			else if (strcmp(optarg, "utf8") == 0)
286 				outst.outtype = OUTT_UTF8;
287 			else if (strcmp(optarg, "locale") == 0)
288 				outst.outtype = OUTT_LOCALE;
289 			else if (strcmp(optarg, "ps") == 0)
290 				outst.outtype = OUTT_PS;
291 			else if (strcmp(optarg, "pdf") == 0)
292 				outst.outtype = OUTT_PDF;
293 			else {
294 				mandoc_msg(MANDOCERR_BADARG_BAD, 0, 0,
295 				    "-T %s", optarg);
296 				return mandoc_msg_getrc();
297 			}
298 			break;
299 		case 'W':
300 			if (woptions(optarg, &os_e, &outst.wstop) == -1)
301 				return mandoc_msg_getrc();
302 			break;
303 		case 'w':
304 			outmode = OUTMODE_FLN;
305 			break;
306 		default:
307 			show_usage = 1;
308 			break;
309 		}
310 	}
311 
312 	if (show_usage)
313 		usage(search.argmode);
314 
315 	/* Postprocess options. */
316 
317 	switch (outmode) {
318 	case OUTMODE_DEF:
319 		switch (search.argmode) {
320 		case ARG_FILE:
321 			outmode = OUTMODE_ALL;
322 			outst.use_pager = 0;
323 			break;
324 		case ARG_NAME:
325 			outmode = OUTMODE_ONE;
326 			break;
327 		default:
328 			outmode = OUTMODE_LST;
329 			break;
330 		}
331 		break;
332 	case OUTMODE_FLN:
333 		if (search.argmode == ARG_FILE)
334 			outmode = OUTMODE_ALL;
335 		break;
336 	case OUTMODE_ALL:
337 		break;
338 	case OUTMODE_LST:
339 	case OUTMODE_ONE:
340 		abort();
341 	}
342 
343 	if (oarg != NULL) {
344 		if (outmode == OUTMODE_LST)
345 			search.outkey = oarg;
346 		else {
347 			while (oarg != NULL) {
348 				if (manconf_output(&conf.output,
349 				    strsep(&oarg, ","), 0) == -1)
350 					return mandoc_msg_getrc();
351 			}
352 		}
353 	}
354 
355 	if (outst.outtype != OUTT_TREE || conf.output.noval == 0)
356 		options |= MPARSE_VALIDATE;
357 
358 	if (outmode == OUTMODE_FLN ||
359 	    outmode == OUTMODE_LST ||
360 	    (conf.output.outfilename == NULL &&
361 	     conf.output.tagfilename == NULL &&
362 	     isatty(STDOUT_FILENO) == 0))
363 		outst.use_pager = 0;
364 
365 	if (outst.use_pager &&
366 	    (conf.output.width == 0 || conf.output.indent == 0) &&
367 	    ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) != -1 &&
368 	    ws.ws_col > 1) {
369 		if (conf.output.width == 0 && ws.ws_col < 79)
370 			conf.output.width = ws.ws_col - 1;
371 		if (conf.output.indent == 0 && ws.ws_col < 66)
372 			conf.output.indent = 3;
373 	}
374 
375 	if (outst.use_pager == 0)
376 		c = pledge("stdio rpath", NULL);
377 	else if (conf.output.outfilename != NULL ||
378 	    conf.output.tagfilename != NULL)
379 		c = pledge("stdio rpath wpath cpath", NULL);
380 	else
381 		c = pledge("stdio rpath tmppath tty proc exec", NULL);
382 	if (c == -1) {
383 		mandoc_msg(MANDOCERR_PLEDGE, 0, 0, "%s", strerror(errno));
384 		return mandoc_msg_getrc();
385 	}
386 
387 	/* Parse arguments. */
388 
389 	if (argc > 0) {
390 		argc -= optind;
391 		argv += optind;
392 	}
393 
394 	/*
395 	 * Quirks for help(1) and man(1),
396 	 * in particular for a section argument without -s.
397 	 */
398 
399 	if (search.argmode == ARG_NAME) {
400 		if (*progname == 'h') {
401 			if (argc == 0) {
402 				argv = help_argv;
403 				argc = 1;
404 			}
405 		} else if (argc > 1 &&
406 		    ((uc = (unsigned char *)argv[0]) != NULL) &&
407 		    ((isdigit(uc[0]) && (uc[1] == '\0' ||
408 		      isalpha(uc[1]))) ||
409 		     (uc[0] == 'n' && uc[1] == '\0'))) {
410 			search.sec = (char *)uc;
411 			argv++;
412 			argc--;
413 		}
414 		if (search.arch == NULL)
415 			search.arch = getenv("MACHINE");
416 		if (search.arch == NULL)
417 			search.arch = MACHINE;
418 		if (outmode == OUTMODE_ONE)
419 			search.firstmatch = 1;
420 	}
421 
422 	/*
423 	 * Use the first argument for -O tag in addition to
424 	 * using it as a search term for man(1) or apropos(1).
425 	 */
426 
427 	if (conf.output.tag != NULL && *conf.output.tag == '\0') {
428 		tagarg = argc > 0 && search.argmode == ARG_EXPR ?
429 		    strchr(*argv, '=') : NULL;
430 		conf.output.tag = tagarg == NULL ? *argv : tagarg + 1;
431 	}
432 
433 	/* Read the configuration file. */
434 
435 	if (search.argmode != ARG_FILE ||
436 	    mandoc_msg_getmin() == MANDOCERR_STYLE)
437 		manconf_parse(&conf, conf_file, defpaths, auxpaths);
438 
439 	/* man(1): Resolve each name individually. */
440 
441 	if (search.argmode == ARG_NAME) {
442 		if (argc < 1) {
443 			if (outmode != OUTMODE_FLN)
444 				usage(ARG_NAME);
445 			if (conf.manpath.sz == 0) {
446 				warnx("The manpath is empty.");
447 				mandoc_msg_setrc(MANDOCLEVEL_BADARG);
448 			} else {
449 				for (i = 0; i + 1 < conf.manpath.sz; i++)
450 					printf("%s:", conf.manpath.paths[i]);
451 				printf("%s\n", conf.manpath.paths[i]);
452 			}
453 			manconf_free(&conf);
454 			return (int)mandoc_msg_getrc();
455 		}
456 		for (res = NULL, ressz = 0; argc > 0; argc--, argv++) {
457 			(void)mansearch(&search, &conf.manpath,
458 			    1, argv, &resn, &resnsz);
459 			if (resnsz == 0)
460 				(void)fs_search(&search, &conf.manpath,
461 				    *argv, &resn, &resnsz);
462 			if (resnsz == 0 && strchr(*argv, '/') == NULL) {
463 				if (search.arch != NULL &&
464 				    arch_valid(search.arch, OSENUM) == 0)
465 					warnx("Unknown architecture \"%s\".",
466 					    search.arch);
467 				else if (search.sec != NULL)
468 					warnx("No entry for %s in "
469 					    "section %s of the manual.",
470 					    *argv, search.sec);
471 				else
472 					warnx("No entry for %s in "
473 					    "the manual.", *argv);
474 				mandoc_msg_setrc(MANDOCLEVEL_BADARG);
475 				continue;
476 			}
477 			if (resnsz == 0) {
478 				if (access(*argv, R_OK) == -1) {
479 					mandoc_msg_setinfilename(*argv);
480 					mandoc_msg(MANDOCERR_BADARG_BAD,
481 					    0, 0, "%s", strerror(errno));
482 					mandoc_msg_setinfilename(NULL);
483 					continue;
484 				}
485 				resnsz = 1;
486 				resn = mandoc_calloc(resnsz, sizeof(*res));
487 				resn->file = mandoc_strdup(*argv);
488 				resn->ipath = SIZE_MAX;
489 				resn->form = FORM_SRC;
490 			}
491 			if (outmode != OUTMODE_ONE || resnsz == 1) {
492 				res = mandoc_reallocarray(res,
493 				    ressz + resnsz, sizeof(*res));
494 				memcpy(res + ressz, resn,
495 				    sizeof(*resn) * resnsz);
496 				ressz += resnsz;
497 				free(resn);
498 				resn = NULL;
499 				resnsz = 0;
500 				continue;
501 			}
502 
503 			/* Search for the best section. */
504 
505 			best_prio = 40;
506 			for (ib = i = 0; i < resnsz; i++) {
507 				sec = resn[i].file;
508 				sec += strcspn(sec, "123456789");
509 				if (sec[0] == '\0')
510 					continue; /* No section at all. */
511 				prio = sec_prios[sec[0] - '1'];
512 				if (search.sec != NULL) {
513 					ssz = strlen(search.sec);
514 					if (strncmp(sec, search.sec, ssz) == 0)
515 						sec += ssz;
516 				} else
517 					sec++; /* Prefer without suffix. */
518 				if (*sec != '/')
519 					prio += 10; /* Wrong dir name. */
520 				if (search.sec != NULL) {
521 					ep = strchr(sec, '\0');
522 					if (ep - sec > 3 &&
523 					    strncmp(ep - 3, ".gz", 3) == 0)
524 						ep -= 3;
525 					if ((size_t)(ep - sec) < ssz + 3 ||
526 					    strncmp(ep - ssz, search.sec,
527 					     ssz) != 0)      /* Wrong file */
528 						prio += 20;  /* extension. */
529 				}
530 				if (prio >= best_prio)
531 					continue;
532 				best_prio = prio;
533 				ib = i;
534 			}
535 			res = mandoc_reallocarray(res, ressz + 1,
536 			    sizeof(*res));
537 			memcpy(res + ressz++, resn + ib, sizeof(*resn));
538 			memset(resn + ib, 0, sizeof(*resn));
539 			mansearch_free(resn, resnsz);
540 			resn = NULL;
541 			resnsz = 0;
542 		}
543 
544 	/* apropos(1), whatis(1): Process the full search expression. */
545 
546 	} else if (search.argmode != ARG_FILE) {
547 		if (mansearch(&search, &conf.manpath,
548 		    argc, argv, &res, &ressz) == 0)
549 			usage(search.argmode);
550 
551 		if (ressz == 0) {
552 			warnx("nothing appropriate");
553 			mandoc_msg_setrc(MANDOCLEVEL_BADARG);
554 			goto out;
555 		}
556 
557 	/* mandoc(1): Take command line arguments as file names. */
558 
559 	} else {
560 		ressz = argc > 0 ? argc : 1;
561 		res = mandoc_calloc(ressz, sizeof(*res));
562 		for (i = 0; i < ressz; i++) {
563 			if (argc > 0)
564 				res[i].file = mandoc_strdup(argv[i]);
565 			res[i].ipath = SIZE_MAX;
566 			res[i].form = FORM_SRC;
567 		}
568 	}
569 
570 	switch (outmode) {
571 	case OUTMODE_FLN:
572 		for (i = 0; i < ressz; i++)
573 			puts(res[i].file);
574 		goto out;
575 	case OUTMODE_LST:
576 		for (i = 0; i < ressz; i++)
577 			printf("%s - %s\n", res[i].names,
578 			    res[i].output == NULL ? "" :
579 			    res[i].output);
580 		goto out;
581 	default:
582 		break;
583 	}
584 
585 	if (search.argmode == ARG_FILE && auxpaths != NULL) {
586 		if (strcmp(auxpaths, "doc") == 0)
587 			options |= MPARSE_MDOC;
588 		else if (strcmp(auxpaths, "an") == 0)
589 			options |= MPARSE_MAN;
590 	}
591 
592 	mchars_alloc();
593 	mp = mparse_alloc(options, os_e, os_s);
594 
595 	/*
596 	 * Remember the original working directory, if possible.
597 	 * This will be needed if some names on the command line
598 	 * are page names and some are relative file names.
599 	 * Do not error out if the current directory is not
600 	 * readable: Maybe it won't be needed after all.
601 	 */
602 	startdir = open(".", O_RDONLY | O_DIRECTORY);
603 	for (i = 0; i < ressz; i++) {
604 		process_onefile(mp, res + i, startdir, &outst, &conf);
605 		if (outst.wstop && mandoc_msg_getrc() != MANDOCLEVEL_OK)
606 			break;
607 	}
608 	if (startdir != -1) {
609 		(void)fchdir(startdir);
610 		close(startdir);
611 	}
612 	if (conf.output.tag != NULL && conf.output.tag_found == 0) {
613 		mandoc_msg(MANDOCERR_TAG, 0, 0, "%s", conf.output.tag);
614 		conf.output.tag = NULL;
615 	}
616 	if (outst.outdata != NULL) {
617 		switch (outst.outtype) {
618 		case OUTT_HTML:
619 			html_free(outst.outdata);
620 			break;
621 		case OUTT_UTF8:
622 		case OUTT_LOCALE:
623 		case OUTT_ASCII:
624 			ascii_free(outst.outdata);
625 			break;
626 		case OUTT_PDF:
627 		case OUTT_PS:
628 			pspdf_free(outst.outdata);
629 			break;
630 		default:
631 			break;
632 		}
633 	}
634 	mandoc_xr_free();
635 	mparse_free(mp);
636 	mchars_free();
637 
638 out:
639 	mansearch_free(res, ressz);
640 	if (search.argmode != ARG_FILE)
641 		manconf_free(&conf);
642 
643 	if (outst.tag_files != NULL) {
644 		if (term_tag_close() != -1 &&
645 		    conf.output.outfilename == NULL &&
646 		    conf.output.tagfilename == NULL)
647 			run_pager(&outst, conf.output.tag);
648 		term_tag_unlink();
649 	} else if (outst.had_output && outst.outtype != OUTT_LINT)
650 		mandoc_msg_summary();
651 
652 	return (int)mandoc_msg_getrc();
653 }
654 
655 static void
656 usage(enum argmode argmode)
657 {
658 	switch (argmode) {
659 	case ARG_FILE:
660 		fputs("usage: mandoc [-ac] [-I os=name] "
661 		    "[-K encoding] [-mdoc | -man] [-O options]\n"
662 		    "\t      [-T output] [-W level] [file ...]\n", stderr);
663 		break;
664 	case ARG_NAME:
665 		fputs("usage: man [-acfhklw] [-C file] [-M path] "
666 		    "[-m path] [-S subsection]\n"
667 		    "\t   [[-s] section] name ...\n", stderr);
668 		break;
669 	case ARG_WORD:
670 		fputs("usage: whatis [-afk] [-C file] "
671 		    "[-M path] [-m path] [-O outkey] [-S arch]\n"
672 		    "\t      [-s section] name ...\n", stderr);
673 		break;
674 	case ARG_EXPR:
675 		fputs("usage: apropos [-afk] [-C file] "
676 		    "[-M path] [-m path] [-O outkey] [-S arch]\n"
677 		    "\t       [-s section] expression ...\n", stderr);
678 		break;
679 	}
680 	exit((int)MANDOCLEVEL_BADARG);
681 }
682 
683 static void
684 glob_esc(char **dst, const char *src, const char *suffix)
685 {
686 	while (*src != '\0') {
687 		if (strchr("*?[", *src) != NULL)
688 			*(*dst)++ = '\\';
689 		*(*dst)++ = *src++;
690 	}
691 	while (*suffix != '\0')
692 		*(*dst)++ = *suffix++;
693 }
694 
695 static void
696 fs_append(char **file, size_t filesz, int copy, size_t ipath,
697     const char *sec, enum form form, struct manpage **res, size_t *ressz)
698 {
699 	struct manpage	*page;
700 
701 	*res = mandoc_reallocarray(*res, *ressz + filesz, sizeof(**res));
702 	page = *res + *ressz;
703 	*ressz += filesz;
704 	for (;;) {
705 		page->file = copy ? mandoc_strdup(*file) : *file;
706 		page->names = NULL;
707 		page->output = NULL;
708 		page->bits = NAME_FILE & NAME_MASK;
709 		page->ipath = ipath;
710 		page->sec = (*sec >= '1' && *sec <= '9') ? *sec - '1' + 1 : 10;
711 		page->form = form;
712 		if (--filesz == 0)
713 			break;
714 		file++;
715 		page++;
716 	}
717 }
718 
719 static int
720 fs_lookup(const struct manpaths *paths, size_t ipath,
721 	const char *sec, const char *arch, const char *name,
722 	struct manpage **res, size_t *ressz)
723 {
724 	struct stat	 sb;
725 	glob_t		 globinfo;
726 	char		*file, *cp, secnum[2];
727 	int		 globres;
728 	enum form	 form;
729 
730 	const char *const slman = "/man";
731 	const char *const slash = "/";
732 	const char *const sglob = ".[01-9]*";
733 	const char *const dot   = ".";
734 	const char *const aster = "*";
735 
736 	memset(&globinfo, 0, sizeof(globinfo));
737 	form = FORM_SRC;
738 
739 	mandoc_asprintf(&file, "%s/man%s/%s.%s",
740 	    paths->paths[ipath], sec, name, sec);
741 	if (stat(file, &sb) != -1)
742 		goto found;
743 	free(file);
744 
745 	mandoc_asprintf(&file, "%s/cat%s/%s.0",
746 	    paths->paths[ipath], sec, name);
747 	if (stat(file, &sb) != -1) {
748 		form = FORM_CAT;
749 		goto found;
750 	}
751 	free(file);
752 
753 	if (arch != NULL) {
754 		mandoc_asprintf(&file, "%s/man%s/%s/%s.%s",
755 		    paths->paths[ipath], sec, arch, name, sec);
756 		if (stat(file, &sb) != -1)
757 			goto found;
758 		free(file);
759 	}
760 
761 	cp = file = mandoc_malloc(strlen(paths->paths[ipath]) * 2 +
762 	    strlen(slman) + strlen(sec) * 2 + strlen(slash) +
763 	    strlen(name) * 2 + strlen(sglob) + 1);
764 	glob_esc(&cp, paths->paths[ipath], slman);
765 	glob_esc(&cp, sec, slash);
766 	glob_esc(&cp, name, sglob);
767 	*cp = '\0';
768 	globres = glob(file, 0, NULL, &globinfo);
769 	if (globres != 0 && globres != GLOB_NOMATCH)
770 		mandoc_msg(MANDOCERR_GLOB, 0, 0,
771 		    "%s: %s", file, strerror(errno));
772 	free(file);
773 	file = NULL;
774 	if (globres == 0)
775 		goto found;
776 	globfree(&globinfo);
777 
778 	if (sec[1] != '\0' && *ressz == 0) {
779 		secnum[0] = sec[0];
780 		secnum[1] = '\0';
781 		cp = file = mandoc_malloc(strlen(paths->paths[ipath]) * 2 +
782 		    strlen(slman) + strlen(secnum) * 2 + strlen(slash) +
783 		    strlen(name) * 2 + strlen(dot) +
784 		    strlen(sec) * 2 + strlen(aster) + 1);
785 		glob_esc(&cp, paths->paths[ipath], slman);
786 		glob_esc(&cp, secnum, slash);
787 		glob_esc(&cp, name, dot);
788 		glob_esc(&cp, sec, aster);
789 		*cp = '\0';
790 		globres = glob(file, 0, NULL, &globinfo);
791 		if (globres != 0 && globres != GLOB_NOMATCH)
792 			mandoc_msg(MANDOCERR_GLOB, 0, 0,
793 			    "%s: %s", file, strerror(errno));
794 		free(file);
795 		file = NULL;
796 		if (globres == 0)
797 			goto found;
798 		globfree(&globinfo);
799 	}
800 
801 	if (res != NULL || ipath + 1 != paths->sz)
802 		return -1;
803 
804 	mandoc_asprintf(&file, "%s.%s", name, sec);
805 	globres = stat(file, &sb);
806 	free(file);
807 	return globres;
808 
809 found:
810 	warnx("outdated mandoc.db lacks %s(%s) entry, run %s %s",
811 	    name, sec, BINM_MAKEWHATIS, paths->paths[ipath]);
812 	if (res == NULL)
813 		free(file);
814 	else if (file == NULL)
815 		fs_append(globinfo.gl_pathv, globinfo.gl_pathc, 1,
816 		    ipath, sec, form, res, ressz);
817 	else
818 		fs_append(&file, 1, 0, ipath, sec, form, res, ressz);
819 	globfree(&globinfo);
820 	return 0;
821 }
822 
823 static int
824 fs_search(const struct mansearch *cfg, const struct manpaths *paths,
825 	const char *name, struct manpage **res, size_t *ressz)
826 {
827 	const char *const sections[] =
828 	    {"1", "8", "6", "2", "3", "5", "7", "4", "9", "3p"};
829 	const size_t nsec = sizeof(sections)/sizeof(sections[0]);
830 
831 	size_t		 ipath, isec;
832 
833 	assert(cfg->argmode == ARG_NAME);
834 	if (res != NULL)
835 		*res = NULL;
836 	*ressz = 0;
837 	for (ipath = 0; ipath < paths->sz; ipath++) {
838 		if (cfg->sec != NULL) {
839 			if (fs_lookup(paths, ipath, cfg->sec, cfg->arch,
840 			    name, res, ressz) != -1 && cfg->firstmatch)
841 				return 0;
842 		} else {
843 			for (isec = 0; isec < nsec; isec++)
844 				if (fs_lookup(paths, ipath, sections[isec],
845 				    cfg->arch, name, res, ressz) != -1 &&
846 				    cfg->firstmatch)
847 					return 0;
848 		}
849 	}
850 	return -1;
851 }
852 
853 static void
854 process_onefile(struct mparse *mp, struct manpage *resp, int startdir,
855     struct outstate *outst, struct manconf *conf)
856 {
857 	int	 fd;
858 
859 	/*
860 	 * Changing directories is not needed in ARG_FILE mode.
861 	 * Do it on a best-effort basis.  Even in case of
862 	 * failure, some functionality may still work.
863 	 */
864 	if (resp->ipath != SIZE_MAX)
865 		(void)chdir(conf->manpath.paths[resp->ipath]);
866 	else if (startdir != -1)
867 		(void)fchdir(startdir);
868 
869 	mandoc_msg_setinfilename(resp->file);
870 	if (resp->file != NULL) {
871 		if ((fd = mparse_open(mp, resp->file)) == -1) {
872 			mandoc_msg(resp->ipath == SIZE_MAX ?
873 			    MANDOCERR_BADARG_BAD : MANDOCERR_OPEN,
874 			    0, 0, "%s", strerror(errno));
875 			mandoc_msg_setinfilename(NULL);
876 			return;
877 		}
878 	} else
879 		fd = STDIN_FILENO;
880 
881 	if (outst->use_pager) {
882 		outst->use_pager = 0;
883 		outst->tag_files = term_tag_init(conf->output.outfilename,
884 		    outst->outtype == OUTT_HTML ? ".html" : "",
885 		    conf->output.tagfilename);
886 		if ((conf->output.outfilename != NULL ||
887 		     conf->output.tagfilename != NULL) &&
888 		    pledge("stdio rpath cpath", NULL) == -1) {
889 			mandoc_msg(MANDOCERR_PLEDGE, 0, 0,
890 			    "%s", strerror(errno));
891 			exit(mandoc_msg_getrc());
892 		}
893 	}
894 	if (outst->had_output && outst->outtype <= OUTT_UTF8) {
895 		if (outst->outdata == NULL)
896 			outdata_alloc(outst, &conf->output);
897 		terminal_sepline(outst->outdata);
898 	}
899 
900 	if (resp->form == FORM_SRC)
901 		parse(mp, fd, resp->file, outst, conf);
902 	else {
903 		passthrough(fd, conf->output.synopsisonly);
904 		outst->had_output = 1;
905 	}
906 
907 	if (ferror(stdout)) {
908 		if (outst->tag_files != NULL) {
909 			mandoc_msg(MANDOCERR_WRITE, 0, 0, "%s: %s",
910 			    outst->tag_files->ofn, strerror(errno));
911 			term_tag_unlink();
912 			outst->tag_files = NULL;
913 		} else
914 			mandoc_msg(MANDOCERR_WRITE, 0, 0, "%s",
915 			    strerror(errno));
916 	}
917 	mandoc_msg_setinfilename(NULL);
918 }
919 
920 static void
921 parse(struct mparse *mp, int fd, const char *file,
922     struct outstate *outst, struct manconf *conf)
923 {
924 	static struct manpaths	 basepaths;
925 	static int		 previous;
926 	struct roff_meta	*meta;
927 
928 	assert(fd >= 0);
929 	if (file == NULL)
930 		file = "<stdin>";
931 
932 	if (previous)
933 		mparse_reset(mp);
934 	else
935 		previous = 1;
936 
937 	mparse_readfd(mp, fd, file);
938 	if (fd != STDIN_FILENO)
939 		close(fd);
940 
941 	/*
942 	 * With -Wstop and warnings or errors of at least the requested
943 	 * level, do not produce output.
944 	 */
945 
946 	if (outst->wstop && mandoc_msg_getrc() != MANDOCLEVEL_OK)
947 		return;
948 
949 	if (outst->outdata == NULL)
950 		outdata_alloc(outst, &conf->output);
951 	else if (outst->outtype == OUTT_HTML)
952 		html_reset(outst->outdata);
953 
954 	mandoc_xr_reset();
955 	meta = mparse_result(mp);
956 
957 	/* Execute the out device, if it exists. */
958 
959 	outst->had_output = 1;
960 	if (meta->macroset == MACROSET_MDOC) {
961 		switch (outst->outtype) {
962 		case OUTT_HTML:
963 			html_mdoc(outst->outdata, meta);
964 			break;
965 		case OUTT_TREE:
966 			tree_mdoc(outst->outdata, meta);
967 			break;
968 		case OUTT_MAN:
969 			man_mdoc(outst->outdata, meta);
970 			break;
971 		case OUTT_PDF:
972 		case OUTT_ASCII:
973 		case OUTT_UTF8:
974 		case OUTT_LOCALE:
975 		case OUTT_PS:
976 			terminal_mdoc(outst->outdata, meta);
977 			break;
978 		case OUTT_MARKDOWN:
979 			markdown_mdoc(outst->outdata, meta);
980 			break;
981 		default:
982 			break;
983 		}
984 	}
985 	if (meta->macroset == MACROSET_MAN) {
986 		switch (outst->outtype) {
987 		case OUTT_HTML:
988 			html_man(outst->outdata, meta);
989 			break;
990 		case OUTT_TREE:
991 			tree_man(outst->outdata, meta);
992 			break;
993 		case OUTT_MAN:
994 			mparse_copy(mp);
995 			break;
996 		case OUTT_PDF:
997 		case OUTT_ASCII:
998 		case OUTT_UTF8:
999 		case OUTT_LOCALE:
1000 		case OUTT_PS:
1001 			terminal_man(outst->outdata, meta);
1002 			break;
1003 		case OUTT_MARKDOWN:
1004 			mandoc_msg(MANDOCERR_MAN_TMARKDOWN, 0, 0, NULL);
1005 			break;
1006 		default:
1007 			break;
1008 		}
1009 	}
1010 	if (conf->output.tag != NULL && conf->output.tag_found == 0 &&
1011 	    tag_exists(conf->output.tag))
1012 		conf->output.tag_found = 1;
1013 
1014 	if (mandoc_msg_getmin() < MANDOCERR_STYLE) {
1015 		if (basepaths.sz == 0)
1016 			manpath_base(&basepaths);
1017 		check_xr(&basepaths);
1018 	} else if (mandoc_msg_getmin() < MANDOCERR_WARNING)
1019 		check_xr(&conf->manpath);
1020 }
1021 
1022 static void
1023 check_xr(struct manpaths *paths)
1024 {
1025 	struct mansearch	 search;
1026 	struct mandoc_xr	*xr;
1027 	size_t			 sz;
1028 
1029 	for (xr = mandoc_xr_get(); xr != NULL; xr = xr->next) {
1030 		if (xr->line == -1)
1031 			continue;
1032 		search.arch = NULL;
1033 		search.sec = xr->sec;
1034 		search.outkey = NULL;
1035 		search.argmode = ARG_NAME;
1036 		search.firstmatch = 1;
1037 		if (mansearch(&search, paths, 1, &xr->name, NULL, &sz))
1038 			continue;
1039 		if (fs_search(&search, paths, xr->name, NULL, &sz) != -1)
1040 			continue;
1041 		if (xr->count == 1)
1042 			mandoc_msg(MANDOCERR_XR_BAD, xr->line,
1043 			    xr->pos + 1, "Xr %s %s", xr->name, xr->sec);
1044 		else
1045 			mandoc_msg(MANDOCERR_XR_BAD, xr->line,
1046 			    xr->pos + 1, "Xr %s %s (%d times)",
1047 			    xr->name, xr->sec, xr->count);
1048 	}
1049 }
1050 
1051 static void
1052 outdata_alloc(struct outstate *outst, struct manoutput *outconf)
1053 {
1054 	switch (outst->outtype) {
1055 	case OUTT_HTML:
1056 		outst->outdata = html_alloc(outconf);
1057 		break;
1058 	case OUTT_UTF8:
1059 		outst->outdata = utf8_alloc(outconf);
1060 		break;
1061 	case OUTT_LOCALE:
1062 		outst->outdata = locale_alloc(outconf);
1063 		break;
1064 	case OUTT_ASCII:
1065 		outst->outdata = ascii_alloc(outconf);
1066 		break;
1067 	case OUTT_PDF:
1068 		outst->outdata = pdf_alloc(outconf);
1069 		break;
1070 	case OUTT_PS:
1071 		outst->outdata = ps_alloc(outconf);
1072 		break;
1073 	default:
1074 		break;
1075 	}
1076 }
1077 
1078 static void
1079 passthrough(int fd, int synopsis_only)
1080 {
1081 	const char	 synb[] = "S\bSY\bYN\bNO\bOP\bPS\bSI\bIS\bS";
1082 	const char	 synr[] = "SYNOPSIS";
1083 
1084 	FILE		*stream;
1085 	char		*line, *cp;
1086 	size_t		 linesz;
1087 	ssize_t		 len, written;
1088 	int		 lno, print;
1089 
1090 	stream = NULL;
1091 	line = NULL;
1092 	linesz = 0;
1093 
1094 	if (fflush(stdout) == EOF) {
1095 		mandoc_msg(MANDOCERR_FFLUSH, 0, 0, "%s", strerror(errno));
1096 		goto done;
1097 	}
1098 	if ((stream = fdopen(fd, "r")) == NULL) {
1099 		close(fd);
1100 		mandoc_msg(MANDOCERR_FDOPEN, 0, 0, "%s", strerror(errno));
1101 		goto done;
1102 	}
1103 
1104 	lno = print = 0;
1105 	while ((len = getline(&line, &linesz, stream)) != -1) {
1106 		lno++;
1107 		cp = line;
1108 		if (synopsis_only) {
1109 			if (print) {
1110 				if ( ! isspace((unsigned char)*cp))
1111 					goto done;
1112 				while (isspace((unsigned char)*cp)) {
1113 					cp++;
1114 					len--;
1115 				}
1116 			} else {
1117 				if (strcmp(cp, synb) == 0 ||
1118 				    strcmp(cp, synr) == 0)
1119 					print = 1;
1120 				continue;
1121 			}
1122 		}
1123 		for (; len > 0; len -= written) {
1124 			if ((written = write(STDOUT_FILENO, cp, len)) == -1) {
1125 				mandoc_msg(MANDOCERR_WRITE, 0, 0,
1126 				    "%s", strerror(errno));
1127 				goto done;
1128 			}
1129 		}
1130 	}
1131 	if (ferror(stream))
1132 		mandoc_msg(MANDOCERR_GETLINE, lno, 0, "%s", strerror(errno));
1133 
1134 done:
1135 	free(line);
1136 	if (stream != NULL)
1137 		fclose(stream);
1138 }
1139 
1140 static int
1141 woptions(char *arg, enum mandoc_os *os_e, int *wstop)
1142 {
1143 	char		*v, *o;
1144 	const char	*toks[11];
1145 
1146 	toks[0] = "stop";
1147 	toks[1] = "all";
1148 	toks[2] = "base";
1149 	toks[3] = "style";
1150 	toks[4] = "warning";
1151 	toks[5] = "error";
1152 	toks[6] = "unsupp";
1153 	toks[7] = "fatal";
1154 	toks[8] = "openbsd";
1155 	toks[9] = "netbsd";
1156 	toks[10] = NULL;
1157 
1158 	while (*arg) {
1159 		o = arg;
1160 		switch (getsubopt(&arg, (char * const *)toks, &v)) {
1161 		case 0:
1162 			*wstop = 1;
1163 			break;
1164 		case 1:
1165 		case 2:
1166 			mandoc_msg_setmin(MANDOCERR_BASE);
1167 			break;
1168 		case 3:
1169 			mandoc_msg_setmin(MANDOCERR_STYLE);
1170 			break;
1171 		case 4:
1172 			mandoc_msg_setmin(MANDOCERR_WARNING);
1173 			break;
1174 		case 5:
1175 			mandoc_msg_setmin(MANDOCERR_ERROR);
1176 			break;
1177 		case 6:
1178 			mandoc_msg_setmin(MANDOCERR_UNSUPP);
1179 			break;
1180 		case 7:
1181 			mandoc_msg_setmin(MANDOCERR_BADARG);
1182 			break;
1183 		case 8:
1184 			mandoc_msg_setmin(MANDOCERR_BASE);
1185 			*os_e = MANDOC_OS_OPENBSD;
1186 			break;
1187 		case 9:
1188 			mandoc_msg_setmin(MANDOCERR_BASE);
1189 			*os_e = MANDOC_OS_NETBSD;
1190 			break;
1191 		default:
1192 			mandoc_msg(MANDOCERR_BADARG_BAD, 0, 0, "-W %s", o);
1193 			return -1;
1194 		}
1195 	}
1196 	return 0;
1197 }
1198 
1199 /*
1200  * Wait until moved to the foreground,
1201  * then fork the pager and wait for the user to close it.
1202  */
1203 static void
1204 run_pager(struct outstate *outst, char *tag_target)
1205 {
1206 	int	 signum, status;
1207 	pid_t	 man_pgid, tc_pgid;
1208 	pid_t	 pager_pid, wait_pid;
1209 
1210 	man_pgid = getpgid(0);
1211 	outst->tag_files->tcpgid =
1212 	    man_pgid == getpid() ? getpgid(getppid()) : man_pgid;
1213 	pager_pid = 0;
1214 	signum = SIGSTOP;
1215 
1216 	for (;;) {
1217 		/* Stop here until moved to the foreground. */
1218 
1219 		tc_pgid = tcgetpgrp(STDOUT_FILENO);
1220 		if (tc_pgid != man_pgid) {
1221 			if (tc_pgid == pager_pid) {
1222 				(void)tcsetpgrp(STDOUT_FILENO, man_pgid);
1223 				if (signum == SIGTTIN)
1224 					continue;
1225 			} else
1226 				outst->tag_files->tcpgid = tc_pgid;
1227 			kill(0, signum);
1228 			continue;
1229 		}
1230 
1231 		/* Once in the foreground, activate the pager. */
1232 
1233 		if (pager_pid) {
1234 			(void)tcsetpgrp(STDOUT_FILENO, pager_pid);
1235 			kill(pager_pid, SIGCONT);
1236 		} else
1237 			pager_pid = spawn_pager(outst, tag_target);
1238 
1239 		/* Wait for the pager to stop or exit. */
1240 
1241 		while ((wait_pid = waitpid(pager_pid, &status,
1242 		    WUNTRACED)) == -1 && errno == EINTR)
1243 			continue;
1244 
1245 		if (wait_pid == -1) {
1246 			mandoc_msg(MANDOCERR_WAIT, 0, 0,
1247 			    "%s", strerror(errno));
1248 			break;
1249 		}
1250 		if (!WIFSTOPPED(status))
1251 			break;
1252 
1253 		signum = WSTOPSIG(status);
1254 	}
1255 }
1256 
1257 static pid_t
1258 spawn_pager(struct outstate *outst, char *tag_target)
1259 {
1260 	const struct timespec timeout = { 0, 100000000 };  /* 0.1s */
1261 #define MAX_PAGER_ARGS 16
1262 	char		*argv[MAX_PAGER_ARGS];
1263 	const char	*pager;
1264 	char		*cp;
1265 	size_t		 wordlen;
1266 	size_t		 cmdlen;
1267 	int		 argc, use_ofn;
1268 	pid_t		 pager_pid;
1269 
1270 	assert(outst->tag_files->ofd == -1);
1271 	assert(outst->tag_files->tfs == NULL);
1272 
1273 	pager = getenv("MANPAGER");
1274 	if (pager == NULL || *pager == '\0')
1275 		pager = getenv("PAGER");
1276 	if (pager == NULL || *pager == '\0')
1277 		pager = "less";
1278 
1279 	/*
1280 	 * Parse the pager command into words.
1281 	 * Intentionally do not do anything fancy here.
1282 	 */
1283 
1284 	argc = 0;
1285 	while (*pager != '\0' && argc + 5 < MAX_PAGER_ARGS) {
1286 		wordlen = strcspn(pager, " ");
1287 		argv[argc++] = mandoc_strndup(pager, wordlen);
1288 		pager += wordlen;
1289 		while (*pager == ' ')
1290 			pager++;
1291 	}
1292 
1293 	/* For more(1) and less(1), use the tag file. */
1294 
1295 	use_ofn = 1;
1296 	if (*outst->tag_files->tfn != '\0' &&
1297 	    (cmdlen = strlen(argv[0])) >= 4) {
1298 		cp = argv[0] + cmdlen - 4;
1299 		if (strcmp(cp, "less") == 0 || strcmp(cp, "more") == 0) {
1300 			argv[argc++] = mandoc_strdup("-T");
1301 			argv[argc++] = mandoc_strdup(outst->tag_files->tfn);
1302 			if (tag_target != NULL) {
1303 				argv[argc++] = mandoc_strdup("-t");
1304 				argv[argc++] = mandoc_strdup(tag_target);
1305 				use_ofn = 0;
1306 			}
1307 		}
1308 	}
1309 	if (use_ofn) {
1310 		if (outst->outtype == OUTT_HTML && tag_target != NULL)
1311 			mandoc_asprintf(&argv[argc], "file://%s#%s",
1312 			    outst->tag_files->ofn, tag_target);
1313 		else
1314 			argv[argc] = mandoc_strdup(outst->tag_files->ofn);
1315 		argc++;
1316 	}
1317 	argv[argc] = NULL;
1318 
1319 	switch (pager_pid = fork()) {
1320 	case -1:
1321 		mandoc_msg(MANDOCERR_FORK, 0, 0, "%s", strerror(errno));
1322 		exit(mandoc_msg_getrc());
1323 	case 0:
1324 		break;
1325 	default:
1326 		while (argc > 0)
1327 			free(argv[--argc]);
1328 		(void)setpgid(pager_pid, 0);
1329 		(void)tcsetpgrp(STDOUT_FILENO, pager_pid);
1330 		if (pledge("stdio rpath tmppath tty proc", NULL) == -1) {
1331 			mandoc_msg(MANDOCERR_PLEDGE, 0, 0,
1332 			    "%s", strerror(errno));
1333 			exit(mandoc_msg_getrc());
1334 		}
1335 		outst->tag_files->pager_pid = pager_pid;
1336 		return pager_pid;
1337 	}
1338 
1339 	/*
1340 	 * The child process becomes the pager.
1341 	 * Do not start it before controlling the terminal.
1342 	 */
1343 
1344 	while (tcgetpgrp(STDOUT_FILENO) != getpid())
1345 		nanosleep(&timeout, NULL);
1346 
1347 	execvp(argv[0], argv);
1348 	mandoc_msg(MANDOCERR_EXEC, 0, 0, "%s: %s", argv[0], strerror(errno));
1349 	_exit(mandoc_msg_getrc());
1350 }
1351