b9c72803a1c3c283a4c5e32af4acd45b421d6f65
[openssl.git] / util / find-doc-nits
1 #! /usr/bin/env perl
2 # Copyright 2002-2019 The OpenSSL Project Authors. All Rights Reserved.
3 #
4 # Licensed under the Apache License 2.0 (the "License").  You may not use
5 # this file except in compliance with the License.  You can obtain a copy
6 # in the file LICENSE in the source distribution or at
7 # https://www.openssl.org/source/license.html
8
9
10 require 5.10.0;
11 use warnings;
12 use strict;
13
14 use Pod::Checker;
15 use File::Find;
16 use File::Basename;
17 use File::Spec::Functions;
18 use Getopt::Std;
19 use lib catdir(dirname($0), "perl");
20 use OpenSSL::Util::Pod;
21
22 # Set to 1 for debug output
23 my $debug = 0;
24
25 # Options.
26 our($opt_d);
27 our($opt_e);
28 our($opt_s);
29 our($opt_o);
30 our($opt_h);
31 our($opt_l);
32 our($opt_n);
33 our($opt_p);
34 our($opt_u);
35 our($opt_v);
36 our($opt_c);
37
38 # Print usage message and exit.
39 sub help {
40     print <<EOF;
41 Find small errors (nits) in documentation.  Options:
42     -c List undocumented commands and options
43     -d Detailed list of undocumented (implies -u)
44     -e Detailed list of new undocumented (implies -v)
45     -h Print this help message
46     -l Print bogus links
47     -n Print nits in POD pages
48     -o Causes -e/-v to count symbols added since 1.1.1 as new (implies -v)
49     -u Count undocumented functions
50     -v Count new undocumented functions
51 EOF
52     exit;
53 }
54
55 getopts('cdehlnouv');
56
57 help() if $opt_h;
58 $opt_u = 1 if $opt_d;
59 $opt_v = 1 if $opt_o || $opt_e;
60 die "Cannot use both -u and -v"
61     if $opt_u && $opt_v;
62 die "Cannot use both -d and -e"
63     if $opt_d && $opt_e;
64
65 # We only need to check c, l, n, u and v.
66 # Options d, e, o imply one of the above.
67 die "Need one of -[cdehlnouv] flags.\n"
68     unless $opt_c or $opt_l or $opt_n or $opt_u or $opt_v;
69
70
71 my $temp = '/tmp/docnits.txt';
72 my $OUT;
73 my %public;
74 my $status = 0;
75
76 my %mandatory_sections = (
77     '*' => [ 'NAME', 'DESCRIPTION', 'COPYRIGHT' ],
78     1   => [ 'SYNOPSIS', 'OPTIONS' ],
79     3   => [ 'SYNOPSIS', 'RETURN VALUES' ],
80     5   => [ ],
81     7   => [ ]
82 );
83
84
85 # Print error message, set $status.
86 sub err {
87     print join(" ", @_), "\n";
88     $status = 1
89 }
90
91 # Cross-check functions in the NAME and SYNOPSIS section.
92 sub name_synopsis {
93     my $id = shift;
94     my $filename = shift;
95     my $contents = shift;
96
97     # Get NAME section and all words in it.
98     return unless $contents =~ /=head1 NAME(.*)=head1 SYNOPSIS/ms;
99     my $tmp = $1;
100     $tmp =~ tr/\n/ /;
101     err($id, "trailing comma before - in NAME")
102         if $tmp =~ /, *-/;
103     $tmp =~ s/ -.*//g;
104     err($id, "POD markup among the names in NAME")
105         if $tmp =~ /[<>]/;
106     $tmp =~ s/  */ /g;
107     err($id, "missing comma in NAME")
108         if $tmp =~ /[^,] /;
109
110     my $dirname = dirname($filename);
111     my $simplename = basename(basename($filename, ".in"), ".pod");
112     my $foundfilename = 0;
113     my %foundfilenames = ();
114     my %names;
115     foreach my $n ( split ',', $tmp ) {
116         $n =~ s/^\s+//;
117         $n =~ s/\s+$//;
118         err($id, "the name '$n' contains white-space")
119             if $n =~ /\s/;
120         $names{$n} = 1;
121         $foundfilename++ if $n eq $simplename;
122         $foundfilenames{$n} = 1
123             if -f "$dirname/$n.pod" && $n ne $simplename;
124     }
125     err($id, "the following exist as other .pod files:",
126          sort keys %foundfilenames)
127         if %foundfilenames;
128     err($id, "$simplename (filename) missing from NAME section")
129         unless $foundfilename;
130     if ( $filename !~ /internal/ ) {
131         foreach my $n ( keys %names ) {
132             err($id, "$n is not public")
133                 if !defined $public{$n};
134         }
135     }
136
137     # Find all functions in SYNOPSIS
138     return unless $contents =~ /=head1 SYNOPSIS(.*)=head1 DESCRIPTION/ms;
139     my $syn = $1;
140     foreach my $line ( split /\n+/, $syn ) {
141         next unless $line =~ /^\s/;
142         my $sym;
143         my $is_prototype = 1;
144         $line =~ s/STACK_OF\([^)]+\)/int/g;
145         $line =~ s/SPARSE_ARRAY_OF\([^)]+\)/int/g;
146         $line =~ s/__declspec\([^)]+\)//;
147         if ( $line =~ /env (\S*)=/ ) {
148             # environment variable env NAME=...
149             $sym = $1;
150         } elsif ( $line =~ /typedef.*\(\*(\S+)\)\s*\(/ ) {
151             # a callback function pointer: typedef ... (*NAME)(...
152             $sym = $1;
153         } elsif ( $line =~ /typedef.* (\S+)\(/ ) {
154             # a callback function signature: typedef ... NAME(...
155             $sym = $1;
156         } elsif ( $line =~ /typedef.* (\S+);/ ) {
157             # a simple typedef: typedef ... NAME;
158             $is_prototype = 0;
159             $sym = $1;
160         } elsif ( $line =~ /enum (\S*) \{/ ) {
161             # an enumeration: enum ... {
162             $sym = $1;
163         } elsif ( $line =~ /#(?:define|undef) ([A-Za-z0-9_]+)/ ) {
164             $is_prototype = 0;
165             $sym = $1;
166         } elsif ( $line =~ /([A-Za-z0-9_]+)\(/ ) {
167             $sym = $1;
168         }
169         else {
170             next;
171         }
172         err($id, "$sym missing from NAME section")
173             unless defined $names{$sym};
174         $names{$sym} = 2;
175
176         # Do some sanity checks on the prototype.
177         err($id, "prototype missing spaces around commas: $line")
178             if $is_prototype && $line =~ /[a-z0-9],[^ ]/;
179     }
180
181     foreach my $n ( keys %names ) {
182         next if $names{$n} == 2;
183         err($id, "$n missing from SYNOPSIS")
184     }
185 }
186
187 # Check if SECTION ($3) is located before BEFORE ($4)
188 sub check_section_location {
189     my $id = shift;
190     my $contents = shift;
191     my $section = shift;
192     my $before = shift;
193
194     return unless $contents =~ /=head1 $section/
195         and $contents =~ /=head1 $before/;
196     err($id, "$section should appear before $before section")
197         if $contents =~ /=head1 $before.*=head1 $section/ms;
198 }
199
200 # Check if a =head1 is duplicated, or a =headX is duplicated within a
201 # =head1.  Treats =head2 =head3 as equivalent -- it doesn't reset the head3
202 # sets if it finds a =head2 -- but that is good enough for now. Also check
203 # for proper capitalization, trailing periods, etc.
204 sub check_head_style {
205     my $id = shift;
206     my $contents = shift;
207     my %head1;
208     my %subheads;
209
210     foreach my $line ( split /\n+/, $contents ) {
211         next unless $line =~ /^=head/;
212         if ( $line =~ /head1/ ) {
213             err($id, "duplicate section $line")
214                 if defined $head1{$line};
215             $head1{$line} = 1;
216             %subheads = ();
217         } else {
218             err($id, "duplicate subsection $line")
219                 if defined $subheads{$line};
220             $subheads{$line} = 1;
221         }
222         err($id, "period in =head")
223             if $line =~ /\.[^\w]/ or $line =~ /\.$/;
224         err($id, "not all uppercase in =head1")
225             if $line =~ /head1.*[a-z]/;
226         err($id, "all uppercase in subhead")
227             if $line =~ /head[234][ A-Z0-9]+$/;
228     }
229 }
230
231 # Because we have options and symbols with extra markup, we need
232 # to take that into account, so we need a regexp that extracts
233 # markup chunks, including recursive markup.
234 # please read up on /(?R)/ in perlre(1)
235 # (note: order is important, (?R) needs to come before .)
236 # (note: non-greedy is important, or something like 'B<foo> and B<bar>'
237 # will be captured as one item)
238 my $markup_re =
239     qr/(                        # Capture group
240            [BIL]<               # The start of what we recurse on
241            (?:(?-1)|.)*?        # recurse the whole regexp (referring to
242                                 # the last opened capture group, i.e. the
243                                 # start of this regexp), or pick next
244                                 # character.  Do NOT be greedy!
245            >                    # The end of what we recurse on
246        )/x;                     # (the x allows this sort of split up regexp)
247
248 # Options must start with a dash, followed by a letter, possibly
249 # followed by letters, digits, dashes and underscores, and the last
250 # character must be a letter or a digit.
251 # We do also accept the single -? or -n, where n is a digit
252 my $option_re =
253     qr/(?:
254             \?                  # Single question mark
255             |
256             \d                  # Single digit
257             |
258             -                   # Single dash (--)
259             |
260             [[:alpha:]](?:[-_[:alnum:]]*?[[:alnum:]])?
261        )/x;
262
263 # Helper function to check if a given $thing is properly marked up
264 # option.  It returns one of these values:
265 #     undef         if it's not an option
266 #     ""            if it's a malformed option
267 #     $unwrapped    the option with the outermost B<> wrapping removed.
268 sub normalise_option {
269     my $id = shift;
270     my $filename = shift;
271     my $thing = shift;
272
273     my $unwrapped = $thing;
274     my $unmarked = $thing;
275
276     # $unwrapped is the option with the outer B<> markup removed
277     $unwrapped =~ s/^B<//;
278     $unwrapped =~ s/>$//;
279     # $unmarked is the option with *all* markup removed
280     $unmarked =~ s/[BIL]<|>//msg;
281
282
283     # If we found an option, check it, collect it
284     if ( $unwrapped =~ /^\s*-/ ) {
285         return $unwrapped       # return option with outer B<> removed
286             if $unmarked =~ /^-${option_re}$/;
287         return "";              # Malformed option
288     }
289     return undef;               # Something else
290 }
291
292 # Checks of command option (man1) formatting.  The man1 checks are
293 # restricted to the SYNOPSIS and OPTIONS sections, the rest is too
294 # free form, we simply cannot be too strict there.
295
296 sub option_check {
297     my $id = shift;
298     my $filename = shift;
299     my $contents = shift;
300
301     my $synopsis = ($contents =~ /=head1\s+SYNOPSIS(.*?)=head1/s, $1);
302
303     # Some pages have more than one OPTIONS section, let's make sure
304     # to get them all
305     my $options = '';
306     while ( $contents =~ /=head1\s+[A-Z ]*?OPTIONS$(.*?)(?==head1)/msg ) {
307         $options .= $1;
308     }
309
310     # Look for options with no or incorrect markup
311     while ( $synopsis =~
312             /(?<![-<[:alnum:]])-(?:$markup_re|.)*(?![->[:alnum:]])/msg ) {
313         err($id, "Malformed option [1] in SYNOPSIS: $&");
314     }
315
316     while ( $synopsis =~ /$markup_re/msg ) {
317         my $found = $&;
318         print STDERR "$id:DEBUG[option_check] SYNOPSIS: found $found\n"
319             if $debug;
320         my $option_uw = normalise_option($id, $filename, $found);
321         err($id, "Malformed option [2] in SYNOPSIS: $found")
322             if defined $option_uw && $option_uw eq '';
323     }
324
325     # In OPTIONS, we look for =item paragraphs.
326     # (?=^\s*$) detects an empty line.
327     while ( $options =~ /=item\s+(.*?)(?=^\s*$)/msg ) {
328         my $item = $&;
329
330         while ( $item =~ /(\[\s*)?($markup_re)/msg ) {
331             my $found = $2;
332             print STDERR "$id:DEBUG[option_check] OPTIONS: found $&\n"
333                 if $debug;
334             err($id, "Unexpected bracket in OPTIONS =item: $item")
335                 if ($1 // '') ne '' && $found =~ /^B<\s*-/;
336
337             my $option_uw = normalise_option($id, $filename, $found);
338             err($id, "Malformed option in OPTIONS: $found")
339                 if defined $option_uw && $option_uw eq '';
340         }
341     }
342 }
343
344 # Normal symbol form
345 my $symbol_re = qr/[[:alpha:]_][_[:alnum:]]*?/;
346
347 # Checks of function name (man3) formatting.  The man3 checks are
348 # easier than the man1 checks, we only check the names followed by (),
349 # and only the names that have POD markup.
350 sub functionname_check {
351     my $id = shift;
352     my $filename = shift;
353     my $contents = shift;
354
355     while ( $contents =~ /($markup_re)\(\)/msg ) {
356         print STDERR "$id:DEBUG[functionname_check] SYNOPSIS: found $&\n"
357             if $debug;
358
359         my $symbol = $1;
360         my $unmarked = $symbol;
361         $unmarked =~ s/[BIL]<|>//msg;
362
363         err($id, "Malformed symbol: $symbol")
364             unless $symbol =~ /^B<.*>$/ && $unmarked =~ /^${symbol_re}$/
365     }
366
367     # We can't do the kind of collecting coolness that option_check()
368     # does, because there are too many things that can't be found in
369     # name repositories like the NAME sections, such as symbol names
370     # with a variable part (typically marked up as B<foo_I<TYPE>_bar>
371 }
372
373 # This is from http://man7.org/linux/man-pages/man7/man-pages.7.html
374 my %preferred_words = (
375     'bitmask'       => 'bit mask',
376     'builtin'       => 'built-in',
377    #'epoch'         => 'Epoch', # handled specially, below
378     'file name'     => 'filename',
379     'file system'   => 'filesystem',
380     'host name'     => 'hostname',
381     'i-node'        => 'inode',
382     'lower case'    => 'lowercase',
383     'lower-case'    => 'lowercase',
384     'non-zero'      => 'nonzero',
385     'path name'     => 'pathname',
386     'pseudo-terminal' => 'pseudoterminal',
387     'reserved port' => 'privileged port',
388     'system port'   => 'privileged port',
389     'realtime'      => 'real-time',
390     'real time'     => 'real-time',
391     'runtime'       => 'run time',
392     'saved group ID'=> 'saved set-group-ID',
393     'saved set-GID' => 'saved set-group-ID',
394     'saved user ID' => 'saved set-user-ID',
395     'saved set-UID' => 'saved set-user-ID',
396     'set-GID'       => 'set-group-ID',
397     'setgid'        => 'set-group-ID',
398     'set-UID'       => 'set-user-ID',
399     'setuid'        => 'set-user-ID',
400     'super user'    => 'superuser',
401     'super-user'    => 'superuser',
402     'super block'   => 'superblock',
403     'super-block'   => 'superblock',
404     'time stamp'    => 'timestamp',
405     'time zone'     => 'timezone',
406     'upper case'    => 'uppercase',
407     'upper-case'    => 'uppercase',
408     'useable'       => 'usable',
409     'userspace'     => 'user space',
410     'user name'     => 'username',
411     'zeroes'        => 'zeros'
412 );
413
414 # Search manpage for words that have a different preferred use.
415 sub wording {
416     my $id = shift;
417     my $contents = shift;
418
419     foreach my $k ( keys %preferred_words ) {
420         # Sigh, trademark
421         next if $k eq 'file system'
422             and $contents =~ /Microsoft Encrypted File System/;
423         err($id, "found '$k' should use '$preferred_words{$k}'")
424             if $contents =~ /\b\Q$k\E\b/i;
425     }
426     err($id, "found 'epoch' should use 'Epoch'")
427         if $contents =~ /\bepoch\b/;
428 }
429
430 # Perform all sorts of nit/error checks on a manpage
431 sub check {
432     my $filename = shift;
433     my $dirname = basename(dirname($filename));
434
435     my $contents = '';
436     {
437         local $/ = undef;
438         open POD, $filename or die "Couldn't open $filename, $!";
439         $contents = <POD>;
440         close POD;
441     }
442
443     my $id = "${filename}:1:";
444     check_head_style($id, $contents);
445
446     # Check ordering of some sections in man3
447     if ( $filename =~ m|man3/| ) {
448         check_section_location($id, $contents, "RETURN VALUES", "EXAMPLES");
449         check_section_location($id, $contents, "SEE ALSO", "HISTORY");
450         check_section_location($id, $contents, "EXAMPLES", "SEE ALSO");
451     }
452
453     # Make sure every link has a section.
454     while ( $contents =~ /$markup_re/msg ) {
455         my $target = $1;
456         next unless $target =~ /^L<(.*)>$/;     # Skip if not L<...>
457         $target = $1;                           # Peal away L< and >
458         $target =~ s/\/[^\/]*$//;               # Peal away possible anchor
459         $target =~ s/.*\|//g;                   # Peal away possible link text
460         next if $target eq '';                  # Skip if links within page, or
461         next if $target =~ /::/;                #   links to a Perl module, or
462         next if $target =~ /^https?:/;          #   is a URL link, or
463         next if $target =~ /\([1357]\)$/;       #   it has a section
464         err($id, "Section missing in $target")
465     }
466     # Check for proper links to commands.
467     while ( $contents =~ /L<([^>]*)\(1\)(?:\/.*)?>/g ) {
468         my $target = $1;
469         next if $target =~ /openssl-?/;
470         next if -f "doc/man1/$target.pod";
471         # TODO: Filter out "foreign manual" links.
472         next if $target =~ /ps|apropos|sha1sum|procmail|perl/;
473         err($id, "Bad command link L<$target(1)>");
474     }
475     # Check for proper in-man-3 API links.
476     while ( $contents =~ /L<([^>]*)\(3\)(?:\/.*)?>/g ) {
477         my $target = $1;
478         err($id, "Bad L<$target>")
479             unless $target =~ /^[_[:alpha:]][_[:alnum:]]*$/
480     }
481
482     unless ( $contents =~ /=for openssl generic/ ) {
483         if ( $filename =~ m|man3/| ) {
484             name_synopsis($id, $filename, $contents);
485             functionname_check($id, $filename, $contents);
486         } elsif ( $filename =~ m|man1/| ) {
487             option_check($id, $filename, $contents)
488         }
489     }
490
491     wording($id, $contents);
492
493     err($id, "doesn't start with =pod")
494         if $contents !~ /^=pod/;
495     err($id, "doesn't end with =cut")
496         if $contents !~ /=cut\n$/;
497     err($id, "more than one cut line.")
498         if $contents =~ /=cut.*=cut/ms;
499     err($id, "EXAMPLE not EXAMPLES section.")
500         if $contents =~ /=head1 EXAMPLE[^S]/;
501     err($id, "WARNING not WARNINGS section.")
502         if $contents =~ /=head1 WARNING[^S]/;
503     err($id, "missing copyright")
504         if $contents !~ /Copyright .* The OpenSSL Project Authors/;
505     err($id, "copyright not last")
506         if $contents =~ /head1 COPYRIGHT.*=head/ms;
507     err($id, "head2 in All uppercase")
508         if $contents =~ /head2\s+[A-Z ]+\n/;
509     err($id, "extra space after head")
510         if $contents =~ /=head\d\s\s+/;
511     err($id, "period in NAME section")
512         if $contents =~ /=head1 NAME.*\.\n.*=head1 SYNOPSIS/ms;
513     err($id, "Duplicate $1 in L<>")
514         if $contents =~ /L<([^>]*)\|([^>]*)>/ && $1 eq $2;
515     err($id, "Bad =over $1")
516         if $contents =~ /=over([^ ][^24])/;
517     err($id, "Possible version style issue")
518         if $contents =~ /OpenSSL version [019]/;
519
520     if ( $contents !~ /=for openssl multiple includes/ ) {
521         # Look for multiple consecutive openssl #include lines
522         # (non-consecutive lines are okay; see man3/MD5.pod).
523         if ( $contents =~ /=head1 SYNOPSIS(.*)=head1 DESCRIPTION/ms ) {
524             my $count = 0;
525             foreach my $line ( split /\n+/, $1 ) {
526                 if ( $line =~ m@include <openssl/@ ) {
527                     err($id, "has multiple includes")
528                         if ++$count == 2;
529                 } else {
530                     $count = 0;
531                 }
532             }
533         }
534     }
535
536     open my $OUT, '>', $temp
537         or die "Can't open $temp, $!";
538     podchecker($filename, $OUT);
539     close $OUT;
540     open $OUT, '<', $temp
541         or die "Can't read $temp, $!";
542     while ( <$OUT> ) {
543         next if /\(section\) in.*deprecated/;
544         print;
545     }
546     close $OUT;
547     unlink $temp || warn "Can't remove $temp, $!";
548
549     # Find what section this page is in; assume 3.
550     my $section = 3;
551     $section = $1 if $dirname =~ /man([1-9])/;
552
553     foreach ( (@{$mandatory_sections{'*'}}, @{$mandatory_sections{$section}}) ) {
554         err($id, "missing $_ head1 section")
555             if $contents !~ /^=head1\s+${_}\s*$/m;
556     }
557 }
558
559 # Parse libcrypto.num, etc., and return sorted list of what's there.
560 sub parsenum {
561     my $file = shift;
562     my @apis;
563
564     open my $IN, '<', $file
565         or die "Can't open $file, $!, stopped";
566
567     while ( <$IN> ) {
568         next if /^#/;
569         next if /\bNOEXIST\b/;
570         my @fields = split();
571         die "Malformed line $_"
572             if scalar @fields != 2 && scalar @fields != 4;
573         push @apis, $fields[0];
574     }
575
576     close $IN;
577
578     return sort @apis;
579 }
580
581 # Parse all the manpages, getting return map of what they document
582 # (by looking at their NAME sections).
583 # Map of links in each POD file; filename => [ "foo(1)", "bar(3)", ... ]
584 my %link_map = ();
585 # Map of names in each POD file; "name(s)" => filename
586 my %name_map = ();
587
588 # Load file of symbol names that we know aren't documented.
589 sub loadmissing($)
590 {
591     my $missingfile = shift;
592     my @missing;
593
594     open FH, $missingfile
595         || die "Can't open $missingfile";
596     while ( <FH> ) {
597         chomp;
598         next if /^#/;
599         push @missing, $_;
600     }
601     close FH;
602
603     for (@missing) {
604         err("$missingfile:", "$_ is documented in $name_map{$_}")
605             if exists $name_map{$_} && defined $name_map{$_};
606     }
607
608     return @missing;
609 }
610
611 # Check for undocumented macros; ignore those in the "missing" file
612 # and do simple check for #define in our header files.
613 sub checkmacros {
614     my $count = 0;
615     my %seen;
616     my @missing;
617
618     if ( $opt_o ) {
619         @missing = loadmissing('util/missingmacro111.txt');
620     } elsif ( $opt_v ) {
621         @missing = loadmissing('util/missingmacro.txt');
622     }
623
624     foreach my $f ( glob('include/openssl/*.h') ) {
625         # Skip some internals we don't want to document yet.
626         next if $f eq 'include/openssl/asn1.h';
627         next if $f eq 'include/openssl/asn1t.h';
628         next if $f eq 'include/openssl/err.h';
629         open(IN, $f) || die "Can't open $f, $!";
630         while ( <IN> ) {
631             next unless /^#\s*define\s*(\S+)\(/;
632             my $macro = "$1(3)"; # We know they're all in section 3
633             next if exists $name_map{$macro} || defined $seen{$macro};
634             next if $macro =~ /^i2d_/
635                 || $macro =~ /^d2i_/
636                 || $macro =~ /^DEPRECATEDIN/
637                 || $macro =~ /\Q_fnsig(3)\E$/
638                 || $macro =~ /^IMPLEMENT_/
639                 || $macro =~ /^_?DECLARE_/;
640
641             # Skip macros known to be missing
642             next if $opt_v && grep( /^\Q$macro\E$/, @missing);
643
644             err("$f:", "macro $macro undocumented")
645                 if $opt_d || $opt_e;
646             $count++;
647             $seen{$macro} = 1;
648         }
649         close(IN);
650     }
651     err("# $count macros undocumented (count is approximate)")
652         if $count > 0;
653 }
654
655 # Find out what is undocumented (filtering out the known missing ones)
656 # and display them.
657 sub printem {
658     my $libname = shift;
659     my $numfile = shift;
660     my $missingfile = shift;
661     my $count = 0;
662     my %seen;
663
664     my @missing = loadmissing($missingfile) if ( $opt_v );
665
666     foreach my $func ( parsenum($numfile) ) {
667         $func .= '(3)';         # We know they're all in section 3
668         next if exists $name_map{$func} || defined $seen{$func};
669
670         # Skip ASN1 utilities
671         next if $func =~ /^ASN1_/;
672
673         # Skip functions known to be missing.
674         next if $opt_v && grep( /^\Q$func\E$/, @missing);
675
676         err("$libname:", "function $func undocumented")
677             if $opt_d || $opt_e;
678         $count++;
679         $seen{$func} = 1;
680     }
681     err("# $count in $numfile are not documented")
682         if $count > 0;
683 }
684
685 # Collect all the names in a manpage.
686 sub collectnames {
687     my $filename = shift;
688     $filename =~ m|man(\d)/|;
689     my $section = $1;
690     my $simplename = basename($filename, ".pod");
691     my $id = "${filename}:1:";
692     my %podinfo = extract_pod_info($filename, { debug => $debug });
693
694     unless ( grep { $simplename eq $_ } @{$podinfo{names}} ) {
695         err($id, "$simplename not in NAME section");
696         push @{$podinfo{names}}, $simplename;
697     }
698     foreach my $name (@{$podinfo{names}}) {
699         next if $name eq "";
700         err($id, "'$name' contains white space")
701             if $name =~ /\s/;
702         my $name_sec = "$name($section)";
703         if ( !exists $name_map{$name_sec} ) {
704             $name_map{$name_sec} = $filename;
705         } elsif ( $filename eq $name_map{$name_sec} ) {
706             err($id, "$name_sec duplicated in NAME section of",
707                  $name_map{$name_sec});
708         } else {
709             err($id, "$name_sec also in NAME section of",
710                  $name_map{$name_sec});
711         }
712     }
713
714     my @foreign_names =
715         map { map { s/\s+//g; $_ } split(/,/, $_) }
716         $podinfo{contents} =~ /=for\s+openssl\s+foreign\s+manuals:\s*(.*)\n\n/;
717     foreach ( @foreign_names ) {
718         $name_map{$_} = undef; # It still exists!
719     }
720
721     my @links =
722         $podinfo{contents} =~ /L<
723                               # if the link is of the form L<something|name(s)>,
724                               # then remove 'something'.  Note that 'something'
725                               # may contain POD codes as well...
726                               (?:(?:[^\|]|<[^>]*>)*\|)?
727                               # we're only interested in references that have
728                               # a one digit section number
729                               ([^\/>\(]+\(\d\))
730                              /gx;
731     $link_map{$filename} = [ @links ];
732 }
733
734 # Look for L<> ("link") references that point to files that do not exist.
735 sub checklinks {
736     foreach my $filename (sort keys %link_map) {
737         foreach my $link (@{$link_map{$filename}}) {
738             err("${filename}:1:", "reference to non-existing $link")
739                 unless exists $name_map{$link};
740         }
741     }
742 }
743
744 # Load the public symbol/macro names
745 sub publicize {
746     foreach my $name ( parsenum('util/libcrypto.num') ) {
747         $public{$name} = 1;
748     }
749     foreach my $name ( parsenum('util/libssl.num') ) {
750         $public{$name} = 1;
751     }
752     foreach my $name ( parsenum('util/other.syms') ) {
753         $public{$name} = 1;
754     }
755 }
756
757 # Cipher/digests to skip if they show up as "not implemented"
758 # because they are, via the "-*" construct.
759 my %skips = (
760     'aes128' => 1,
761     'aes192' => 1,
762     'aes256' => 1,
763     'aria128' => 1,
764     'aria192' => 1,
765     'aria256' => 1,
766     'camellia128' => 1,
767     'camellia192' => 1,
768     'camellia256' => 1,
769     'des' => 1,
770     'des3' => 1,
771     'idea' => 1,
772     'cipher' => 1,
773     'digest' => 1,
774 );
775
776 # Check the flags of a command and see if everything is in the manpage
777 sub checkflags {
778     my $cmd = shift;
779     my $doc = shift;
780     my %cmdopts;
781     my %docopts;
782     my %localskips;
783
784     # Get the list of options in the command.
785     open CFH, "./apps/openssl list --options $cmd|"
786         || die "Can list options for $cmd, $!";
787     while ( <CFH> ) {
788         chop;
789         s/ .$//;
790         $cmdopts{$_} = 1;
791     }
792     close CFH;
793
794     # Get the list of flags from the synopsis
795     open CFH, "<$doc"
796         || die "Can't open $doc, $!";
797     while ( <CFH> ) {
798         chop;
799         last if /DESCRIPTION/;
800         if ( /=for openssl ifdef (.*)/ ) {
801             foreach my $f ( split / /, $1 ) {
802                 $localskips{$f} = 1;
803             }
804             next;
805         }
806         next unless /\[B<-([^ >]+)/;
807         my $opt = $1;
808         $opt = $1 if $opt =~ /I<(.*)/;
809         $docopts{$1} = 1;
810     }
811     close CFH;
812
813     # See what's in the command not the manpage.
814     my @undocced = sort grep { !defined $docopts{$_} } keys %cmdopts;
815     foreach ( @undocced ) {
816         next if /-/; # Skip the -- end-of-flags marker
817         err("$doc: undocumented option -$_");
818     }
819
820     # See what's in the command not the manpage.
821     my @unimpl = sort grep { !defined $cmdopts{$_} } keys %docopts;
822     foreach ( @unimpl ) {
823         next if defined $skips{$_} || defined $localskips{$_};
824         err("$cmd documented but not implemented -$_");
825     }
826 }
827
828 ##
829 ##  MAIN()
830 ##  Do the work requested by the various getopt flags.
831 ##  The flags are parsed in alphabetical order, just because we have
832 ##  to have *some way* of listing them.
833 ##
834
835 if ( $opt_c ) {
836     my @commands = ();
837
838     # Get list of commands.
839     open FH, "./apps/openssl list -1 -commands|"
840         || die "Can't list commands, $!";
841     while ( <FH> ) {
842         chop;
843         push @commands, $_;
844     }
845     close FH;
846
847     # See if each has a manpage.
848     foreach my $cmd ( @commands ) {
849         next if $cmd eq 'help' || $cmd eq 'exit';
850         my $doc = "doc/man1/$cmd.pod";
851         $doc = "doc/man1/openssl-$cmd.pod" if -f "doc/man1/openssl-$cmd.pod";
852         if ( ! -f "$doc" ) {
853             err("$doc does not exist");
854         } else {
855             checkflags($cmd, $doc);
856         }
857     }
858
859     # See what help is missing.
860     open FH, "./apps/openssl list --missing-help |"
861         || die "Can't list missing help, $!";
862     while ( <FH> ) {
863         chop;
864         my ($cmd, $flag) = split;
865         err("$cmd has no help for -$flag");
866     }
867     close FH;
868
869     exit $status;
870 }
871
872 # Preparation for some options, populate %name_map and %link_map
873 if ( $opt_l || $opt_u || $opt_v ) {
874     foreach ( glob('doc/*/*.pod doc/internal/*/*.pod') ) {
875         collectnames($_);
876     }
877 }
878
879 if ( $opt_l ) {
880     checklinks();
881 }
882
883 if ( $opt_n ) {
884     publicize();
885     foreach ( @ARGV ? @ARGV : glob('doc/*/*.pod doc/internal/*/*.pod') ) {
886         check($_);
887     }
888
889     # If not given args, check that all man1 commands are named properly.
890     if ( scalar @ARGV == 0 ) {
891         foreach (glob('doc/man1/*.pod')) {
892             next if /CA.pl/ || /openssl\.pod/ || /tsget\.pod/;
893             err("$_ doesn't start with openssl-") unless /openssl-/;
894         }
895     }
896 }
897
898 if ( $opt_u || $opt_v) {
899     if ( $opt_o ) {
900         printem('crypto', 'util/libcrypto.num', 'util/missingcrypto111.txt');
901         printem('ssl', 'util/libssl.num', 'util/missingssl111.txt');
902     } else {
903         printem('crypto', 'util/libcrypto.num', 'util/missingcrypto.txt');
904         printem('ssl', 'util/libssl.num', 'util/missingssl.txt');
905     }
906     checkmacros();
907 }
908
909 exit $status;