Bug Summary

File:src/usr.bin/mandoc/main.c
Warning:line 705, column 37
Dereference of null pointer (loaded from variable 'file')

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name main.c -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 1 -pic-is-pie -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -target-feature +retpoline-indirect-calls -target-feature +retpoline-indirect-branches -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/usr.bin/mandoc/obj -resource-dir /usr/local/lib/clang/13.0.0 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -fdebug-compilation-dir=/usr/src/usr.bin/mandoc/obj -ferror-limit 19 -fwrapv -D_RET_PROTECTOR -ret-protector -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c /usr/src/usr.bin/mandoc/main.c
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(*__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" "apropos"
57#define BINM_MAN"man" "man"
58#define BINM_MAKEWHATIS"makewhatis" "makewhatis"
59#define BINM_WHATIS"whatis" "whatis"
60#define OSENUMMANDOC_OS_OPENBSD MANDOC_OS_OPENBSD
61
62enum outmode {
63 OUTMODE_DEF = 0,
64 OUTMODE_FLN,
65 OUTMODE_LST,
66 OUTMODE_ALL,
67 OUTMODE_ONE
68};
69
70enum 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
83struct 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
93int mandocdb(int, char *[]);
94
95static void check_xr(struct manpaths *);
96static void fs_append(char **, size_t, int,
97 size_t, const char *, enum form,
98 struct manpage **, size_t *);
99static int fs_lookup(const struct manpaths *, size_t,
100 const char *, const char *, const char *,
101 struct manpage **, size_t *);
102static int fs_search(const struct mansearch *,
103 const struct manpaths *, const char *,
104 struct manpage **, size_t *);
105static void glob_esc(char **, const char *, const char *);
106static void outdata_alloc(struct outstate *, struct manoutput *);
107static void parse(struct mparse *, int, const char *,
108 struct outstate *, struct manconf *);
109static void passthrough(int, int);
110static void process_onefile(struct mparse *, struct manpage *,
111 int, struct outstate *, struct manconf *);
112static void run_pager(struct outstate *, char *);
113static pid_t spawn_pager(struct outstate *, char *);
114static void usage(enum argmode) __attribute__((__noreturn__));
115static int woptions(char *, enum mandoc_os *, int *);
116
117static const int sec_prios[] = {1, 4, 5, 8, 6, 3, 7, 2, 9};
118static char help_arg[] = "help";
119static char *help_argv[] = {help_arg, NULL((void *)0)};
120
121
122int
123main(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(&__sF[2]));
153 if (strncmp(progname, "mandocdb", 8) == 0 ||
1
Assuming the condition is false
3
Taking false branch
154 strcmp(progname, BINM_MAKEWHATIS"makewhatis") == 0)
2
Assuming the condition is false
155 return mandocdb(argc, argv);
156
157 if (pledge("stdio rpath wpath cpath tmppath tty proc exec", NULL((void *)0)) == -1) {
4
Assuming the condition is false
5
Taking false branch
158 mandoc_msg(MANDOCERR_PLEDGE, 0, 0, "%s", strerror(errno(*__errno())));
159 return mandoc_msg_getrc();
160 }
161
162 /* Search options. */
163
164 memset(&conf, 0, sizeof(conf));
165 conf_file = NULL((void *)0);
166 defpaths = auxpaths = NULL((void *)0);
167
168 memset(&search, 0, sizeof(struct mansearch));
169 search.outkey = "Nd";
170 oarg = NULL((void *)0);
171
172 if (strcmp(progname, BINM_MAN"man") == 0)
6
Taking true branch
173 search.argmode = ARG_NAME;
174 else if (strcmp(progname, BINM_APROPOS"apropos") == 0)
175 search.argmode = ARG_EXPR;
176 else if (strcmp(progname, BINM_WHATIS"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(1 << 2) | MPARSE_UTF8(1 << 4) | MPARSE_LATIN1(1 << 5);
186 os_e = MANDOC_OS_OTHER;
187 os_s = NULL((void *)0);
188
189 /* Formatter options. */
190
191 memset(&outst, 0, sizeof(outst));
192 outst.tag_files = NULL((void *)0);
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,
7
Assuming the condition is false
8
Loop condition is false. Execution continues on line 312
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((void *)0)) {
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(1 << 4) | MPARSE_LATIN1(1 << 5));
238 if (strcmp(optarg, "utf-8") == 0)
239 options |= MPARSE_UTF8(1 << 4);
240 else if (strcmp(optarg, "iso-8859-1") == 0)
241 options |= MPARSE_LATIN1(1 << 5);
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(&__sF[1]));
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
8.1
'show_usage' is 0
)
9
Taking false branch
313 usage(search.argmode);
314
315 /* Postprocess options. */
316
317 switch (outmode) {
10
Control jumps to 'case OUTMODE_DEF:' at line 318
318 case OUTMODE_DEF:
319 switch (search.argmode) {
11
Control jumps to 'case ARG_NAME:' at line 324
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;
12
Execution continues on line 331
327 default:
328 outmode = OUTMODE_LST;
329 break;
330 }
331 break;
13
Execution continues on line 343
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
13.1
'oarg' is equal to NULL
!= NULL((void *)0)) {
14
Taking false branch
344 if (outmode == OUTMODE_LST)
345 search.outkey = oarg;
346 else {
347 while (oarg != NULL((void *)0)) {
348 if (manconf_output(&conf.output,
349 strsep(&oarg, ","), 0) == -1)
350 return mandoc_msg_getrc();
351 }
352 }
353 }
354
355 if (outst.outtype
14.1
Field 'outtype' is not equal to OUTT_TREE
!= OUTT_TREE || conf.output.noval == 0)
356 options |= MPARSE_VALIDATE(1 << 6);
357
358 if (outmode
14.2
'outmode' is not equal to OUTMODE_FLN
== OUTMODE_FLN ||
16
Taking false branch
359 outmode
14.3
'outmode' is not equal to OUTMODE_LST
== OUTMODE_LST ||
360 (conf.output.outfilename
14.4
Field 'outfilename' is equal to NULL
== NULL((void *)0) &&
361 conf.output.tagfilename
14.5
Field 'tagfilename' is equal to NULL
== NULL((void *)0) &&
362 isatty(STDOUT_FILENO1) == 0))
15
Assuming the condition is false
363 outst.use_pager = 0;
364
365 if (outst.use_pager
16.1
Field 'use_pager' is 1
&&
366 (conf.output.width
16.2
Field 'width' is equal to 0
== 0 || conf.output.indent == 0) &&
367 ioctl(STDOUT_FILENO1, TIOCGWINSZ((unsigned long)0x40000000 | ((sizeof(struct winsize) & 0x1fff
) << 16) | ((('t')) << 8) | ((104)))
, &ws) != -1
&&
17
Assuming the condition is false
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
17.1
Field 'use_pager' is not equal to 0
== 0)
18
Taking false branch
376 c = pledge("stdio rpath", NULL((void *)0));
377 else if (conf.output.outfilename
18.1
Field 'outfilename' is equal to NULL
!= NULL((void *)0) ||
19
Taking false branch
378 conf.output.tagfilename
18.2
Field 'tagfilename' is equal to NULL
!= NULL((void *)0))
379 c = pledge("stdio rpath wpath cpath", NULL((void *)0));
380 else
381 c = pledge("stdio rpath tmppath tty proc exec", NULL((void *)0));
382 if (c == -1) {
20
Assuming the condition is false
21
Taking false branch
383 mandoc_msg(MANDOCERR_PLEDGE, 0, 0, "%s", strerror(errno(*__errno())));
384 return mandoc_msg_getrc();
385 }
386
387 /* Parse arguments. */
388
389 if (argc
21.1
'argc' is > 0
> 0) {
22
Taking true branch
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
22.1
Field 'argmode' is equal to ARG_NAME
== ARG_NAME) {
23
Taking true branch
400 if (*progname == 'h') {
24
Assuming the condition is false
25
Taking false branch
401 if (argc == 0) {
402 argv = help_argv;
403 argc = 1;
404 }
405 } else if (argc > 1 &&
26
Assuming 'argc' is <= 1
406 ((uc = (unsigned char *)argv[0]) != NULL((void *)0)) &&
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
26.1
Field 'arch' is equal to NULL
== NULL((void *)0))
27
Taking true branch
415 search.arch = getenv("MACHINE");
416 if (search.arch == NULL((void *)0))
28
Assuming field 'arch' is not equal to NULL
29
Taking false branch
417 search.arch = MACHINE"amd64";
418 if (outmode
29.1
'outmode' is equal to OUTMODE_ONE
== OUTMODE_ONE)
30
Taking true branch
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
30.1
Field 'tag' is equal to NULL
!= NULL((void *)0) && *conf.output.tag == '\0') {
428 tagarg = argc > 0 && search.argmode == ARG_EXPR ?
429 strchr(*argv, '=') : NULL((void *)0);
430 conf.output.tag = tagarg == NULL((void *)0) ? *argv : tagarg + 1;
431 }
432
433 /* Read the configuration file. */
434
435 if (search.argmode
30.2
Field 'argmode' is not equal to ARG_FILE
!= 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
30.3
Field 'argmode' is equal to ARG_NAME
== ARG_NAME) {
31
Taking true branch
442 if (argc < 1) {
32
Assuming 'argc' is >= 1
33
Taking false branch
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((void *)0), ressz = 0; argc > 0; argc--, argv++) {
34
Loop condition is true. Entering loop body
457 (void)mansearch(&search, &conf.manpath,
458 1, argv, &resn, &resnsz);
459 if (resnsz == 0)
35
Assuming 'resnsz' is equal to 0
36
Taking true branch
460 (void)fs_search(&search, &conf.manpath,
37
Calling 'fs_search'
461 *argv, &resn, &resnsz);
462 if (resnsz == 0 && strchr(*argv, '/') == NULL((void *)0)) {
463 if (search.arch != NULL((void *)0) &&
464 arch_valid(search.arch, OSENUMMANDOC_OS_OPENBSD) == 0)
465 warnx("Unknown architecture \"%s\".",
466 search.arch);
467 else if (search.sec != NULL((void *)0))
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_OK0x04) == -1) {
479 mandoc_msg_setinfilename(*argv);
480 mandoc_msg(MANDOCERR_BADARG_BAD,
481 0, 0, "%s", strerror(errno(*__errno())));
482 mandoc_msg_setinfilename(NULL((void *)0));
483 continue;
484 }
485 resnsz = 1;
486 resn = mandoc_calloc(resnsz, sizeof(*res));
487 resn->file = mandoc_strdup(*argv);
488 resn->ipath = SIZE_MAX0xffffffffffffffffUL;
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((void *)0);
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((void *)0)) {
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((void *)0)) {
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((void *)0);
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_MAX0xffffffffffffffffUL;
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((void *)0) ? "" :
579 res[i].output);
580 goto out;
581 default:
582 break;
583 }
584
585 if (search.argmode == ARG_FILE && auxpaths != NULL((void *)0)) {
586 if (strcmp(auxpaths, "doc") == 0)
587 options |= MPARSE_MDOC(1 << 0);
588 else if (strcmp(auxpaths, "an") == 0)
589 options |= MPARSE_MAN(1 << 1);
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_RDONLY0x0000 | O_DIRECTORY0x20000);
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((void *)0) && conf.output.tag_found == 0) {
613 mandoc_msg(MANDOCERR_TAG, 0, 0, "%s", conf.output.tag);
614 conf.output.tag = NULL((void *)0);
615 }
616 if (outst.outdata != NULL((void *)0)) {
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
638out:
639 mansearch_free(res, ressz);
640 if (search.argmode != ARG_FILE)
641 manconf_free(&conf);
642
643 if (outst.tag_files != NULL((void *)0)) {
644 if (term_tag_close() != -1 &&
645 conf.output.outfilename == NULL((void *)0) &&
646 conf.output.tagfilename == NULL((void *)0))
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
655static void
656usage(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(&__sF[2]));
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(&__sF[2]));
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(&__sF[2]));
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(&__sF[2]));
678 break;
679 }
680 exit((int)MANDOCLEVEL_BADARG);
681}
682
683static void
684glob_esc(char **dst, const char *src, const char *suffix)
685{
686 while (*src != '\0') {
687 if (strchr("*?[", *src) != NULL((void *)0))
688 *(*dst)++ = '\\';
689 *(*dst)++ = *src++;
690 }
691 while (*suffix != '\0')
692 *(*dst)++ = *suffix++;
693}
694
695static void
696fs_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 (;;) {
54
Loop condition is true. Entering loop body
705 page->file = copy
54.1
'copy' is 1
? mandoc_strdup(*file) : *file;
55
'?' condition is true
56
Dereference of null pointer (loaded from variable 'file')
706 page->names = NULL((void *)0);
707 page->output = NULL((void *)0);
708 page->bits = NAME_FILE0x0000004000000010ULL & NAME_MASK0x000000000000001fULL;
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
719static int
720fs_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));
45
Null pointer value stored to 'globinfo.gl_pathv'
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)
46
Assuming the condition is true
47
Taking true branch
742 goto found;
48
Control jumps to line 810
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((void *)0)) {
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((void *)0), &globinfo);
769 if (globres != 0 && globres != GLOB_NOMATCH(-3))
770 mandoc_msg(MANDOCERR_GLOB, 0, 0,
771 "%s: %s", file, strerror(errno(*__errno())));
772 free(file);
773 file = NULL((void *)0);
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((void *)0), &globinfo);
791 if (globres != 0 && globres != GLOB_NOMATCH(-3))
792 mandoc_msg(MANDOCERR_GLOB, 0, 0,
793 "%s: %s", file, strerror(errno(*__errno())));
794 free(file);
795 file = NULL((void *)0);
796 if (globres == 0)
797 goto found;
798 globfree(&globinfo);
799 }
800
801 if (res != NULL((void *)0) || 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
809found:
810 warnx("outdated mandoc.db lacks %s(%s) entry, run %s %s",
811 name, sec, BINM_MAKEWHATIS"makewhatis", paths->paths[ipath]);
812 if (res
48.1
'res' is not equal to NULL
== NULL((void *)0))
49
Taking false branch
813 free(file);
814 else if (file == NULL((void *)0))
50
Assuming 'file' is equal to NULL
51
Taking true branch
815 fs_append(globinfo.gl_pathv, globinfo.gl_pathc, 1,
52
Passing null pointer value via 1st parameter 'file'
53
Calling 'fs_append'
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
823static int
824fs_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)((cfg->argmode == ARG_NAME) ? (void)0 : __assert2("/usr/src/usr.bin/mandoc/main.c"
, 833, __func__, "cfg->argmode == ARG_NAME"))
;
38
'?' condition is true
834 if (res
38.1
'res' is not equal to NULL
!= NULL((void *)0))
39
Taking true branch
835 *res = NULL((void *)0);
836 *ressz = 0;
837 for (ipath = 0; ipath < paths->sz; ipath++) {
40
Assuming 'ipath' is < field 'sz'
41
Loop condition is true. Entering loop body
838 if (cfg->sec
41.1
Field 'sec' is equal to NULL
!= NULL((void *)0)) {
42
Taking false branch
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++)
43
Loop condition is true. Entering loop body
844 if (fs_lookup(paths, ipath, sections[isec],
44
Calling 'fs_lookup'
845 cfg->arch, name, res, ressz) != -1 &&
846 cfg->firstmatch)
847 return 0;
848 }
849 }
850 return -1;
851}
852
853static void
854process_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_MAX0xffffffffffffffffUL)
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((void *)0)) {
871 if ((fd = mparse_open(mp, resp->file)) == -1) {
872 mandoc_msg(resp->ipath == SIZE_MAX0xffffffffffffffffUL ?
873 MANDOCERR_BADARG_BAD : MANDOCERR_OPEN,
874 0, 0, "%s", strerror(errno(*__errno())));
875 mandoc_msg_setinfilename(NULL((void *)0));
876 return;
877 }
878 } else
879 fd = STDIN_FILENO0;
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((void *)0) ||
887 conf->output.tagfilename != NULL((void *)0)) &&
888 pledge("stdio rpath cpath", NULL((void *)0)) == -1) {
889 mandoc_msg(MANDOCERR_PLEDGE, 0, 0,
890 "%s", strerror(errno(*__errno())));
891 exit(mandoc_msg_getrc());
892 }
893 }
894 if (outst->had_output && outst->outtype <= OUTT_UTF8) {
895 if (outst->outdata == NULL((void *)0))
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)(!__isthreaded ? ((((&__sF[1]))->_flags & 0x0040) !=
0) : (ferror)((&__sF[1])))
) {
908 if (outst->tag_files != NULL((void *)0)) {
909 mandoc_msg(MANDOCERR_WRITE, 0, 0, "%s: %s",
910 outst->tag_files->ofn, strerror(errno(*__errno())));
911 term_tag_unlink();
912 outst->tag_files = NULL((void *)0);
913 } else
914 mandoc_msg(MANDOCERR_WRITE, 0, 0, "%s",
915 strerror(errno(*__errno())));
916 }
917 mandoc_msg_setinfilename(NULL((void *)0));
918}
919
920static void
921parse(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)((fd >= 0) ? (void)0 : __assert2("/usr/src/usr.bin/mandoc/main.c"
, 928, __func__, "fd >= 0"))
;
929 if (file == NULL((void *)0))
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_FILENO0)
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((void *)0))
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((void *)0));
1005 break;
1006 default:
1007 break;
1008 }
1009 }
1010 if (conf->output.tag != NULL((void *)0) && 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
1022static void
1023check_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((void *)0); xr = xr->next) {
1030 if (xr->line == -1)
1031 continue;
1032 search.arch = NULL((void *)0);
1033 search.sec = xr->sec;
1034 search.outkey = NULL((void *)0);
1035 search.argmode = ARG_NAME;
1036 search.firstmatch = 1;
1037 if (mansearch(&search, paths, 1, &xr->name, NULL((void *)0), &sz))
1038 continue;
1039 if (fs_search(&search, paths, xr->name, NULL((void *)0), &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
1051static void
1052outdata_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
1078static void
1079passthrough(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((void *)0);
1091 line = NULL((void *)0);
1092 linesz = 0;
1093
1094 if (fflush(stdout(&__sF[1])) == EOF(-1)) {
1095 mandoc_msg(MANDOCERR_FFLUSH, 0, 0, "%s", strerror(errno(*__errno())));
1096 goto done;
1097 }
1098 if ((stream = fdopen(fd, "r")) == NULL((void *)0)) {
1099 close(fd);
1100 mandoc_msg(MANDOCERR_FDOPEN, 0, 0, "%s", strerror(errno(*__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_FILENO1, cp, len)) == -1) {
1125 mandoc_msg(MANDOCERR_WRITE, 0, 0,
1126 "%s", strerror(errno(*__errno())));
1127 goto done;
1128 }
1129 }
1130 }
1131 if (ferror(stream)(!__isthreaded ? (((stream)->_flags & 0x0040) != 0) : (
ferror)(stream))
)
1132 mandoc_msg(MANDOCERR_GETLINE, lno, 0, "%s", strerror(errno(*__errno())));
1133
1134done:
1135 free(line);
1136 if (stream != NULL((void *)0))
1137 fclose(stream);
1138}
1139
1140static int
1141woptions(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((void *)0);
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 */
1203static void
1204run_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 = SIGSTOP17;
1215
1216 for (;;) {
1217 /* Stop here until moved to the foreground. */
1218
1219 tc_pgid = tcgetpgrp(STDOUT_FILENO1);
1220 if (tc_pgid != man_pgid) {
1221 if (tc_pgid == pager_pid) {
1222 (void)tcsetpgrp(STDOUT_FILENO1, man_pgid);
1223 if (signum == SIGTTIN21)
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_FILENO1, pager_pid);
1235 kill(pager_pid, SIGCONT19);
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 WUNTRACED2)) == -1 && errno(*__errno()) == EINTR4)
1243 continue;
1244
1245 if (wait_pid == -1) {
1246 mandoc_msg(MANDOCERR_WAIT, 0, 0,
1247 "%s", strerror(errno(*__errno())));
1248 break;
1249 }
1250 if (!WIFSTOPPED(status)(((status) & 0xff) == 0177))
1251 break;
1252
1253 signum = WSTOPSIG(status)(int)(((unsigned)(status) >> 8) & 0xff);
1254 }
1255}
1256
1257static pid_t
1258spawn_pager(struct outstate *outst, char *tag_target)
1259{
1260 const struct timespec timeout = { 0, 100000000 }; /* 0.1s */
1261#define MAX_PAGER_ARGS16 16
1262 char *argv[MAX_PAGER_ARGS16];
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)((outst->tag_files->ofd == -1) ? (void)0 : __assert2("/usr/src/usr.bin/mandoc/main.c"
, 1270, __func__, "outst->tag_files->ofd == -1"))
;
1271 assert(outst->tag_files->tfs == NULL)((outst->tag_files->tfs == ((void *)0)) ? (void)0 : __assert2
("/usr/src/usr.bin/mandoc/main.c", 1271, __func__, "outst->tag_files->tfs == NULL"
))
;
1272
1273 pager = getenv("MANPAGER");
1274 if (pager == NULL((void *)0) || *pager == '\0')
1275 pager = getenv("PAGER");
1276 if (pager == NULL((void *)0) || *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_ARGS16) {
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((void *)0)) {
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((void *)0))
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((void *)0);
1318
1319 switch (pager_pid = fork()) {
1320 case -1:
1321 mandoc_msg(MANDOCERR_FORK, 0, 0, "%s", strerror(errno(*__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_FILENO1, pager_pid);
1330 if (pledge("stdio rpath tmppath tty proc", NULL((void *)0)) == -1) {
1331 mandoc_msg(MANDOCERR_PLEDGE, 0, 0,
1332 "%s", strerror(errno(*__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_FILENO1) != getpid())
1345 nanosleep(&timeout, NULL((void *)0));
1346
1347 execvp(argv[0], argv);
1348 mandoc_msg(MANDOCERR_EXEC, 0, 0, "%s: %s", argv[0], strerror(errno(*__errno())));
1349 _exit(mandoc_msg_getrc());
1350}