xref: /openbmc/qemu/scripts/kernel-doc (revision 57b3a7d8)
1#!/usr/bin/env perl
2# SPDX-License-Identifier: GPL-2.0
3
4use warnings;
5use strict;
6
7## Copyright (c) 1998 Michael Zucchi, All Rights Reserved        ##
8## Copyright (C) 2000, 1  Tim Waugh <twaugh@redhat.com>          ##
9## Copyright (C) 2001  Simon Huggins                             ##
10## Copyright (C) 2005-2012  Randy Dunlap                         ##
11## Copyright (C) 2012  Dan Luedtke                               ##
12## 								 ##
13## #define enhancements by Armin Kuster <akuster@mvista.com>	 ##
14## Copyright (c) 2000 MontaVista Software, Inc.			 ##
15## 								 ##
16## This software falls under the GNU General Public License.     ##
17## Please read the COPYING file for more information             ##
18
19# 18/01/2001 - 	Cleanups
20# 		Functions prototyped as foo(void) same as foo()
21# 		Stop eval'ing where we don't need to.
22# -- huggie@earth.li
23
24# 27/06/2001 -  Allowed whitespace after initial "/**" and
25#               allowed comments before function declarations.
26# -- Christian Kreibich <ck@whoop.org>
27
28# Still to do:
29# 	- add perldoc documentation
30# 	- Look more closely at some of the scarier bits :)
31
32# 26/05/2001 - 	Support for separate source and object trees.
33#		Return error code.
34# 		Keith Owens <kaos@ocs.com.au>
35
36# 23/09/2001 - Added support for typedefs, structs, enums and unions
37#              Support for Context section; can be terminated using empty line
38#              Small fixes (like spaces vs. \s in regex)
39# -- Tim Jansen <tim@tjansen.de>
40
41# 25/07/2012 - Added support for HTML5
42# -- Dan Luedtke <mail@danrl.de>
43
44sub usage {
45    my $message = <<"EOF";
46Usage: $0 [OPTION ...] FILE ...
47
48Read C language source or header FILEs, extract embedded documentation comments,
49and print formatted documentation to standard output.
50
51The documentation comments are identified by "/**" opening comment mark. See
52Documentation/doc-guide/kernel-doc.rst for the documentation comment syntax.
53
54Output format selection (mutually exclusive):
55  -man			Output troff manual page format. This is the default.
56  -rst			Output reStructuredText format.
57  -none			Do not output documentation, only warnings.
58
59Output selection (mutually exclusive):
60  -export		Only output documentation for symbols that have been
61			exported using EXPORT_SYMBOL() or EXPORT_SYMBOL_GPL()
62                        in any input FILE or -export-file FILE.
63  -internal		Only output documentation for symbols that have NOT been
64			exported using EXPORT_SYMBOL() or EXPORT_SYMBOL_GPL()
65                        in any input FILE or -export-file FILE.
66  -function NAME	Only output documentation for the given function(s)
67			or DOC: section title(s). All other functions and DOC:
68			sections are ignored. May be specified multiple times.
69  -nofunction NAME	Do NOT output documentation for the given function(s);
70			only output documentation for the other functions and
71			DOC: sections. May be specified multiple times.
72
73Output selection modifiers:
74  -sphinx-version VER   Generate rST syntax for the specified Sphinx version.
75                        Only works with reStructuredTextFormat.
76  -no-doc-sections	Do not output DOC: sections.
77  -enable-lineno        Enable output of #define LINENO lines. Only works with
78                        reStructuredText format.
79  -export-file FILE     Specify an additional FILE in which to look for
80                        EXPORT_SYMBOL() and EXPORT_SYMBOL_GPL(). To be used with
81                        -export or -internal. May be specified multiple times.
82
83Other parameters:
84  -v			Verbose output, more warnings and other information.
85  -h			Print this help.
86
87EOF
88    print $message;
89    exit 1;
90}
91
92#
93# format of comments.
94# In the following table, (...)? signifies optional structure.
95#                         (...)* signifies 0 or more structure elements
96# /**
97#  * function_name(:)? (- short description)?
98# (* @parameterx: (description of parameter x)?)*
99# (* a blank line)?
100#  * (Description:)? (Description of function)?
101#  * (section header: (section description)? )*
102#  (*)?*/
103#
104# So .. the trivial example would be:
105#
106# /**
107#  * my_function
108#  */
109#
110# If the Description: header tag is omitted, then there must be a blank line
111# after the last parameter specification.
112# e.g.
113# /**
114#  * my_function - does my stuff
115#  * @my_arg: its mine damnit
116#  *
117#  * Does my stuff explained.
118#  */
119#
120#  or, could also use:
121# /**
122#  * my_function - does my stuff
123#  * @my_arg: its mine damnit
124#  * Description: Does my stuff explained.
125#  */
126# etc.
127#
128# Besides functions you can also write documentation for structs, unions,
129# enums and typedefs. Instead of the function name you must write the name
130# of the declaration;  the struct/union/enum/typedef must always precede
131# the name. Nesting of declarations is not supported.
132# Use the argument mechanism to document members or constants.
133# e.g.
134# /**
135#  * struct my_struct - short description
136#  * @a: first member
137#  * @b: second member
138#  *
139#  * Longer description
140#  */
141# struct my_struct {
142#     int a;
143#     int b;
144# /* private: */
145#     int c;
146# };
147#
148# All descriptions can be multiline, except the short function description.
149#
150# For really longs structs, you can also describe arguments inside the
151# body of the struct.
152# eg.
153# /**
154#  * struct my_struct - short description
155#  * @a: first member
156#  * @b: second member
157#  *
158#  * Longer description
159#  */
160# struct my_struct {
161#     int a;
162#     int b;
163#     /**
164#      * @c: This is longer description of C
165#      *
166#      * You can use paragraphs to describe arguments
167#      * using this method.
168#      */
169#     int c;
170# };
171#
172# This should be use only for struct/enum members.
173#
174# You can also add additional sections. When documenting kernel functions you
175# should document the "Context:" of the function, e.g. whether the functions
176# can be called form interrupts. Unlike other sections you can end it with an
177# empty line.
178# A non-void function should have a "Return:" section describing the return
179# value(s).
180# Example-sections should contain the string EXAMPLE so that they are marked
181# appropriately in DocBook.
182#
183# Example:
184# /**
185#  * user_function - function that can only be called in user context
186#  * @a: some argument
187#  * Context: !in_interrupt()
188#  *
189#  * Some description
190#  * Example:
191#  *    user_function(22);
192#  */
193# ...
194#
195#
196# All descriptive text is further processed, scanning for the following special
197# patterns, which are highlighted appropriately.
198#
199# 'funcname()' - function
200# '$ENVVAR' - environmental variable
201# '&struct_name' - name of a structure (up to two words including 'struct')
202# '&struct_name.member' - name of a structure member
203# '@parameter' - name of a parameter
204# '%CONST' - name of a constant.
205# '``LITERAL``' - literal string without any spaces on it.
206
207## init lots of data
208
209my $errors = 0;
210my $warnings = 0;
211my $anon_struct_union = 0;
212
213# match expressions used to find embedded type information
214my $type_constant = '\b``([^\`]+)``\b';
215my $type_constant2 = '\%([-_\w]+)';
216my $type_func = '(\w+)\(\)';
217my $type_param = '\@(\w*((\.\w+)|(->\w+))*(\.\.\.)?)';
218my $type_fp_param = '\@(\w+)\(\)';  # Special RST handling for func ptr params
219my $type_env = '(\$\w+)';
220my $type_enum = '#(enum\s*([_\w]+))';
221my $type_struct = '#(struct\s*([_\w]+))';
222my $type_typedef = '#(([A-Z][_\w]*))';
223my $type_union = '#(union\s*([_\w]+))';
224my $type_member = '#([_\w]+)(\.|->)([_\w]+)';
225my $type_fallback = '(?!)';    # this never matches
226my $type_member_func = $type_member . '\(\)';
227
228# Output conversion substitutions.
229#  One for each output format
230
231# these are pretty rough
232my @highlights_man = (
233                      [$type_constant, "\$1"],
234                      [$type_constant2, "\$1"],
235                      [$type_func, "\\\\fB\$1\\\\fP"],
236                      [$type_enum, "\\\\fI\$1\\\\fP"],
237                      [$type_struct, "\\\\fI\$1\\\\fP"],
238                      [$type_typedef, "\\\\fI\$1\\\\fP"],
239                      [$type_union, "\\\\fI\$1\\\\fP"],
240                      [$type_param, "\\\\fI\$1\\\\fP"],
241                      [$type_member, "\\\\fI\$1\$2\$3\\\\fP"],
242                      [$type_fallback, "\\\\fI\$1\\\\fP"]
243		     );
244my $blankline_man = "";
245
246# rst-mode
247my @highlights_rst = (
248                       [$type_constant, "``\$1``"],
249                       [$type_constant2, "``\$1``"],
250                       # Note: need to escape () to avoid func matching later
251                       [$type_member_func, "\\:c\\:type\\:`\$1\$2\$3\\\\(\\\\) <\$1>`"],
252                       [$type_member, "\\:c\\:type\\:`\$1\$2\$3 <\$1>`"],
253		       [$type_fp_param, "**\$1\\\\(\\\\)**"],
254                       [$type_func, "\$1()"],
255                       [$type_enum, "\\:c\\:type\\:`\$1 <\$2>`"],
256                       [$type_struct, "\\:c\\:type\\:`\$1 <\$2>`"],
257                       [$type_typedef, "\\:c\\:type\\:`\$1 <\$2>`"],
258                       [$type_union, "\\:c\\:type\\:`\$1 <\$2>`"],
259                       # in rst this can refer to any type
260                       [$type_fallback, "\\:c\\:type\\:`\$1`"],
261                       [$type_param, "**\$1**"]
262		      );
263my $blankline_rst = "\n";
264
265# read arguments
266if ($#ARGV == -1) {
267    usage();
268}
269
270my $kernelversion;
271my $dohighlight = "";
272
273my $verbose = 0;
274my $output_mode = "rst";
275my $output_preformatted = 0;
276my $no_doc_sections = 0;
277my $enable_lineno = 0;
278my @highlights = @highlights_rst;
279my $blankline = $blankline_rst;
280my $modulename = "Kernel API";
281
282use constant {
283    OUTPUT_ALL          => 0, # output all symbols and doc sections
284    OUTPUT_INCLUDE      => 1, # output only specified symbols
285    OUTPUT_EXCLUDE      => 2, # output everything except specified symbols
286    OUTPUT_EXPORTED     => 3, # output exported symbols
287    OUTPUT_INTERNAL     => 4, # output non-exported symbols
288};
289my $output_selection = OUTPUT_ALL;
290my $show_not_found = 0;	# No longer used
291my $sphinx_version = "0.0"; # if not specified, assume old
292
293my @export_file_list;
294
295my @build_time;
296if (defined($ENV{'KBUILD_BUILD_TIMESTAMP'}) &&
297    (my $seconds = `date -d"${ENV{'KBUILD_BUILD_TIMESTAMP'}}" +%s`) ne '') {
298    @build_time = gmtime($seconds);
299} else {
300    @build_time = localtime;
301}
302
303my $man_date = ('January', 'February', 'March', 'April', 'May', 'June',
304		'July', 'August', 'September', 'October',
305		'November', 'December')[$build_time[4]] .
306  " " . ($build_time[5]+1900);
307
308# Essentially these are globals.
309# They probably want to be tidied up, made more localised or something.
310# CAVEAT EMPTOR!  Some of the others I localised may not want to be, which
311# could cause "use of undefined value" or other bugs.
312my ($function, %function_table, %parametertypes, $declaration_purpose);
313my $declaration_start_line;
314my ($type, $declaration_name, $return_type);
315my ($newsection, $newcontents, $prototype, $brcount, %source_map);
316
317if (defined($ENV{'KBUILD_VERBOSE'})) {
318	$verbose = "$ENV{'KBUILD_VERBOSE'}";
319}
320
321# Generated docbook code is inserted in a template at a point where
322# docbook v3.1 requires a non-zero sequence of RefEntry's; see:
323# http://www.oasis-open.org/docbook/documentation/reference/html/refentry.html
324# We keep track of number of generated entries and generate a dummy
325# if needs be to ensure the expanded template can be postprocessed
326# into html.
327my $section_counter = 0;
328
329my $lineprefix="";
330
331# Parser states
332use constant {
333    STATE_NORMAL        => 0, # normal code
334    STATE_NAME          => 1, # looking for function name
335    STATE_BODY_MAYBE    => 2, # body - or maybe more description
336    STATE_BODY          => 3, # the body of the comment
337    STATE_PROTO         => 4, # scanning prototype
338    STATE_DOCBLOCK      => 5, # documentation block
339    STATE_INLINE        => 6, # gathering documentation outside main block
340};
341my $state;
342my $in_doc_sect;
343my $leading_space;
344
345# Inline documentation state
346use constant {
347    STATE_INLINE_NA     => 0, # not applicable ($state != STATE_INLINE)
348    STATE_INLINE_NAME   => 1, # looking for member name (@foo:)
349    STATE_INLINE_TEXT   => 2, # looking for member documentation
350    STATE_INLINE_END    => 3, # done
351    STATE_INLINE_ERROR  => 4, # error - Comment without header was found.
352                              # Spit a warning as it's not
353                              # proper kernel-doc and ignore the rest.
354};
355my $inline_doc_state;
356
357#declaration types: can be
358# 'function', 'struct', 'union', 'enum', 'typedef'
359my $decl_type;
360
361my $doc_start = '^/\*\*\s*$'; # Allow whitespace at end of comment start.
362my $doc_end = '\*/';
363my $doc_com = '\s*\*\s*';
364my $doc_com_body = '\s*\* ?';
365my $doc_decl = $doc_com . '(\w+)';
366# @params and a strictly limited set of supported section names
367my $doc_sect = $doc_com .
368    '\s*(\@[.\w]+|\@\.\.\.|description|context|returns?|notes?|examples?)\s*:(.*)';
369my $doc_content = $doc_com_body . '(.*)';
370my $doc_block = $doc_com . 'DOC:\s*(.*)?';
371my $doc_inline_start = '^\s*/\*\*\s*$';
372my $doc_inline_sect = '\s*\*\s*(@\s*[\w][\w\.]*\s*):(.*)';
373my $doc_inline_end = '^\s*\*/\s*$';
374my $doc_inline_oneline = '^\s*/\*\*\s*(@[\w\s]+):\s*(.*)\s*\*/\s*$';
375my $export_symbol = '^\s*EXPORT_SYMBOL(_GPL)?\s*\(\s*(\w+)\s*\)\s*;';
376
377my %parameterdescs;
378my %parameterdesc_start_lines;
379my @parameterlist;
380my %sections;
381my @sectionlist;
382my %section_start_lines;
383my $sectcheck;
384my $struct_actual;
385
386my $contents = "";
387my $new_start_line = 0;
388
389# the canonical section names. see also $doc_sect above.
390my $section_default = "Description";	# default section
391my $section_intro = "Introduction";
392my $section = $section_default;
393my $section_context = "Context";
394my $section_return = "Return";
395
396my $undescribed = "-- undescribed --";
397
398reset_state();
399
400while ($ARGV[0] =~ m/^--?(.*)/) {
401    my $cmd = $1;
402    shift @ARGV;
403    if ($cmd eq "man") {
404	$output_mode = "man";
405	@highlights = @highlights_man;
406	$blankline = $blankline_man;
407    } elsif ($cmd eq "rst") {
408	$output_mode = "rst";
409	@highlights = @highlights_rst;
410	$blankline = $blankline_rst;
411    } elsif ($cmd eq "none") {
412	$output_mode = "none";
413    } elsif ($cmd eq "module") { # not needed for XML, inherits from calling document
414	$modulename = shift @ARGV;
415    } elsif ($cmd eq "function") { # to only output specific functions
416	$output_selection = OUTPUT_INCLUDE;
417	$function = shift @ARGV;
418	$function_table{$function} = 1;
419    } elsif ($cmd eq "nofunction") { # output all except specific functions
420	$output_selection = OUTPUT_EXCLUDE;
421	$function = shift @ARGV;
422	$function_table{$function} = 1;
423    } elsif ($cmd eq "export") { # only exported symbols
424	$output_selection = OUTPUT_EXPORTED;
425	%function_table = ();
426    } elsif ($cmd eq "internal") { # only non-exported symbols
427	$output_selection = OUTPUT_INTERNAL;
428	%function_table = ();
429    } elsif ($cmd eq "export-file") {
430	my $file = shift @ARGV;
431	push(@export_file_list, $file);
432    } elsif ($cmd eq "v") {
433	$verbose = 1;
434    } elsif (($cmd eq "h") || ($cmd eq "help")) {
435	usage();
436    } elsif ($cmd eq 'no-doc-sections') {
437	    $no_doc_sections = 1;
438    } elsif ($cmd eq 'enable-lineno') {
439	    $enable_lineno = 1;
440    } elsif ($cmd eq 'show-not-found') {
441	$show_not_found = 1;  # A no-op but don't fail
442    } elsif ($cmd eq 'sphinx-version') {
443        $sphinx_version = shift @ARGV;
444    } else {
445	# Unknown argument
446        usage();
447    }
448}
449
450# continue execution near EOF;
451
452# get kernel version from env
453sub get_kernel_version() {
454    my $version = 'unknown kernel version';
455
456    if (defined($ENV{'KERNELVERSION'})) {
457	$version = $ENV{'KERNELVERSION'};
458    }
459    return $version;
460}
461
462#
463sub print_lineno {
464    my $lineno = shift;
465    if ($enable_lineno && defined($lineno)) {
466        print "#define LINENO " . $lineno . "\n";
467    }
468}
469##
470# dumps section contents to arrays/hashes intended for that purpose.
471#
472sub dump_section {
473    my $file = shift;
474    my $name = shift;
475    my $contents = join "\n", @_;
476
477    if ($name =~ m/$type_param/) {
478	$name = $1;
479	$parameterdescs{$name} = $contents;
480	$sectcheck = $sectcheck . $name . " ";
481        $parameterdesc_start_lines{$name} = $new_start_line;
482        $new_start_line = 0;
483    } elsif ($name eq "@\.\.\.") {
484	$name = "...";
485	$parameterdescs{$name} = $contents;
486	$sectcheck = $sectcheck . $name . " ";
487        $parameterdesc_start_lines{$name} = $new_start_line;
488        $new_start_line = 0;
489    } else {
490	if (defined($sections{$name}) && ($sections{$name} ne "")) {
491	    # Only warn on user specified duplicate section names.
492	    if ($name ne $section_default) {
493		print STDERR "${file}:$.: warning: duplicate section name '$name'\n";
494		++$warnings;
495	    }
496	    $sections{$name} .= $contents;
497	} else {
498	    $sections{$name} = $contents;
499	    push @sectionlist, $name;
500            $section_start_lines{$name} = $new_start_line;
501            $new_start_line = 0;
502	}
503    }
504}
505
506##
507# dump DOC: section after checking that it should go out
508#
509sub dump_doc_section {
510    my $file = shift;
511    my $name = shift;
512    my $contents = join "\n", @_;
513
514    if ($no_doc_sections) {
515        return;
516    }
517
518    if (($output_selection == OUTPUT_ALL) ||
519	($output_selection == OUTPUT_INCLUDE &&
520	 defined($function_table{$name})) ||
521	($output_selection == OUTPUT_EXCLUDE &&
522	 !defined($function_table{$name})))
523    {
524	dump_section($file, $name, $contents);
525	output_blockhead({'sectionlist' => \@sectionlist,
526			  'sections' => \%sections,
527			  'module' => $modulename,
528			  'content-only' => ($output_selection != OUTPUT_ALL), });
529    }
530}
531
532##
533# output function
534#
535# parameterdescs, a hash.
536#  function => "function name"
537#  parameterlist => @list of parameters
538#  parameterdescs => %parameter descriptions
539#  sectionlist => @list of sections
540#  sections => %section descriptions
541#
542
543sub output_highlight {
544    my $contents = join "\n",@_;
545    my $line;
546
547#   DEBUG
548#   if (!defined $contents) {
549#	use Carp;
550#	confess "output_highlight got called with no args?\n";
551#   }
552
553#   print STDERR "contents b4:$contents\n";
554    eval $dohighlight;
555    die $@ if $@;
556#   print STDERR "contents af:$contents\n";
557
558    foreach $line (split "\n", $contents) {
559	if (! $output_preformatted) {
560	    $line =~ s/^\s*//;
561	}
562	if ($line eq ""){
563	    if (! $output_preformatted) {
564		print $lineprefix, $blankline;
565	    }
566	} else {
567	    if ($output_mode eq "man" && substr($line, 0, 1) eq ".") {
568		print "\\&$line";
569	    } else {
570		print $lineprefix, $line;
571	    }
572	}
573	print "\n";
574    }
575}
576
577##
578# output function in man
579sub output_function_man(%) {
580    my %args = %{$_[0]};
581    my ($parameter, $section);
582    my $count;
583
584    print ".TH \"$args{'function'}\" 9 \"$args{'function'}\" \"$man_date\" \"Kernel Hacker's Manual\" LINUX\n";
585
586    print ".SH NAME\n";
587    print $args{'function'} . " \\- " . $args{'purpose'} . "\n";
588
589    print ".SH SYNOPSIS\n";
590    if ($args{'functiontype'} ne "") {
591	print ".B \"" . $args{'functiontype'} . "\" " . $args{'function'} . "\n";
592    } else {
593	print ".B \"" . $args{'function'} . "\n";
594    }
595    $count = 0;
596    my $parenth = "(";
597    my $post = ",";
598    foreach my $parameter (@{$args{'parameterlist'}}) {
599	if ($count == $#{$args{'parameterlist'}}) {
600	    $post = ");";
601	}
602	$type = $args{'parametertypes'}{$parameter};
603	if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
604	    # pointer-to-function
605	    print ".BI \"" . $parenth . $1 . "\" " . $parameter . " \") (" . $2 . ")" . $post . "\"\n";
606	} else {
607	    $type =~ s/([^\*])$/$1 /;
608	    print ".BI \"" . $parenth . $type . "\" " . $parameter . " \"" . $post . "\"\n";
609	}
610	$count++;
611	$parenth = "";
612    }
613
614    print ".SH ARGUMENTS\n";
615    foreach $parameter (@{$args{'parameterlist'}}) {
616	my $parameter_name = $parameter;
617	$parameter_name =~ s/\[.*//;
618
619	print ".IP \"" . $parameter . "\" 12\n";
620	output_highlight($args{'parameterdescs'}{$parameter_name});
621    }
622    foreach $section (@{$args{'sectionlist'}}) {
623	print ".SH \"", uc $section, "\"\n";
624	output_highlight($args{'sections'}{$section});
625    }
626}
627
628##
629# output enum in man
630sub output_enum_man(%) {
631    my %args = %{$_[0]};
632    my ($parameter, $section);
633    my $count;
634
635    print ".TH \"$args{'module'}\" 9 \"enum $args{'enum'}\" \"$man_date\" \"API Manual\" LINUX\n";
636
637    print ".SH NAME\n";
638    print "enum " . $args{'enum'} . " \\- " . $args{'purpose'} . "\n";
639
640    print ".SH SYNOPSIS\n";
641    print "enum " . $args{'enum'} . " {\n";
642    $count = 0;
643    foreach my $parameter (@{$args{'parameterlist'}}) {
644	print ".br\n.BI \"    $parameter\"\n";
645	if ($count == $#{$args{'parameterlist'}}) {
646	    print "\n};\n";
647	    last;
648	}
649	else {
650	    print ", \n.br\n";
651	}
652	$count++;
653    }
654
655    print ".SH Constants\n";
656    foreach $parameter (@{$args{'parameterlist'}}) {
657	my $parameter_name = $parameter;
658	$parameter_name =~ s/\[.*//;
659
660	print ".IP \"" . $parameter . "\" 12\n";
661	output_highlight($args{'parameterdescs'}{$parameter_name});
662    }
663    foreach $section (@{$args{'sectionlist'}}) {
664	print ".SH \"$section\"\n";
665	output_highlight($args{'sections'}{$section});
666    }
667}
668
669##
670# output struct in man
671sub output_struct_man(%) {
672    my %args = %{$_[0]};
673    my ($parameter, $section);
674
675    print ".TH \"$args{'module'}\" 9 \"" . $args{'type'} . " " . $args{'struct'} . "\" \"$man_date\" \"API Manual\" LINUX\n";
676
677    print ".SH NAME\n";
678    print $args{'type'} . " " . $args{'struct'} . " \\- " . $args{'purpose'} . "\n";
679
680    my $declaration = $args{'definition'};
681    $declaration =~ s/\t/  /g;
682    $declaration =~ s/\n/"\n.br\n.BI \"/g;
683    print ".SH SYNOPSIS\n";
684    print $args{'type'} . " " . $args{'struct'} . " {\n.br\n";
685    print ".BI \"$declaration\n};\n.br\n\n";
686
687    print ".SH Members\n";
688    foreach $parameter (@{$args{'parameterlist'}}) {
689	($parameter =~ /^#/) && next;
690
691	my $parameter_name = $parameter;
692	$parameter_name =~ s/\[.*//;
693
694	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
695	print ".IP \"" . $parameter . "\" 12\n";
696	output_highlight($args{'parameterdescs'}{$parameter_name});
697    }
698    foreach $section (@{$args{'sectionlist'}}) {
699	print ".SH \"$section\"\n";
700	output_highlight($args{'sections'}{$section});
701    }
702}
703
704##
705# output typedef in man
706sub output_typedef_man(%) {
707    my %args = %{$_[0]};
708    my ($parameter, $section);
709
710    print ".TH \"$args{'module'}\" 9 \"$args{'typedef'}\" \"$man_date\" \"API Manual\" LINUX\n";
711
712    print ".SH NAME\n";
713    print "typedef " . $args{'typedef'} . " \\- " . $args{'purpose'} . "\n";
714
715    foreach $section (@{$args{'sectionlist'}}) {
716	print ".SH \"$section\"\n";
717	output_highlight($args{'sections'}{$section});
718    }
719}
720
721sub output_blockhead_man(%) {
722    my %args = %{$_[0]};
723    my ($parameter, $section);
724    my $count;
725
726    print ".TH \"$args{'module'}\" 9 \"$args{'module'}\" \"$man_date\" \"API Manual\" LINUX\n";
727
728    foreach $section (@{$args{'sectionlist'}}) {
729	print ".SH \"$section\"\n";
730	output_highlight($args{'sections'}{$section});
731    }
732}
733
734##
735# output in restructured text
736#
737
738#
739# This could use some work; it's used to output the DOC: sections, and
740# starts by putting out the name of the doc section itself, but that tends
741# to duplicate a header already in the template file.
742#
743sub output_blockhead_rst(%) {
744    my %args = %{$_[0]};
745    my ($parameter, $section);
746
747    foreach $section (@{$args{'sectionlist'}}) {
748	if ($output_selection != OUTPUT_INCLUDE) {
749	    print "**$section**\n\n";
750	}
751        print_lineno($section_start_lines{$section});
752	output_highlight_rst($args{'sections'}{$section});
753	print "\n";
754    }
755}
756
757#
758# Apply the RST highlights to a sub-block of text.
759#
760sub highlight_block($) {
761    # The dohighlight kludge requires the text be called $contents
762    my $contents = shift;
763    eval $dohighlight;
764    die $@ if $@;
765    return $contents;
766}
767
768#
769# Regexes used only here.
770#
771my $sphinx_literal = '^[^.].*::$';
772my $sphinx_cblock = '^\.\.\ +code-block::';
773
774sub output_highlight_rst {
775    my $input = join "\n",@_;
776    my $output = "";
777    my $line;
778    my $in_literal = 0;
779    my $litprefix;
780    my $block = "";
781
782    foreach $line (split "\n",$input) {
783	#
784	# If we're in a literal block, see if we should drop out
785	# of it.  Otherwise pass the line straight through unmunged.
786	#
787	if ($in_literal) {
788	    if (! ($line =~ /^\s*$/)) {
789		#
790		# If this is the first non-blank line in a literal
791		# block we need to figure out what the proper indent is.
792		#
793		if ($litprefix eq "") {
794		    $line =~ /^(\s*)/;
795		    $litprefix = '^' . $1;
796		    $output .= $line . "\n";
797		} elsif (! ($line =~ /$litprefix/)) {
798		    $in_literal = 0;
799		} else {
800		    $output .= $line . "\n";
801		}
802	    } else {
803		$output .= $line . "\n";
804	    }
805	}
806	#
807	# Not in a literal block (or just dropped out)
808	#
809	if (! $in_literal) {
810	    $block .= $line . "\n";
811	    if (($line =~ /$sphinx_literal/) || ($line =~ /$sphinx_cblock/)) {
812		$in_literal = 1;
813		$litprefix = "";
814		$output .= highlight_block($block);
815		$block = ""
816	    }
817	}
818    }
819
820    if ($block) {
821	$output .= highlight_block($block);
822    }
823    foreach $line (split "\n", $output) {
824	print $lineprefix . $line . "\n";
825    }
826}
827
828sub output_function_rst(%) {
829    my %args = %{$_[0]};
830    my ($parameter, $section);
831    my $oldprefix = $lineprefix;
832    my $start = "";
833
834    if ($args{'typedef'}) {
835	print ".. c:type:: ". $args{'function'} . "\n\n";
836	print_lineno($declaration_start_line);
837	print "   **Typedef**: ";
838	$lineprefix = "";
839	output_highlight_rst($args{'purpose'});
840	$start = "\n\n**Syntax**\n\n  ``";
841    } else {
842        if ((split(/\./, $sphinx_version))[0] >= 3) {
843            # Sphinx 3 and later distinguish macros and functions and
844            # complain if you use c:function with something that's not
845            # syntactically valid as a function declaration.
846            # We assume that anything with a return type is a function
847            # and anything without is a macro.
848            if ($args{'functiontype'} ne "") {
849                print ".. c:function:: ";
850            } else {
851                print ".. c:macro:: ";
852            }
853        } else {
854            # Older Sphinx don't support documenting macros that take
855            # arguments with c:macro, and don't complain about the use
856            # of c:function for this.
857            print ".. c:function:: ";
858        }
859    }
860    if ($args{'functiontype'} ne "") {
861	$start .= $args{'functiontype'} . " " . $args{'function'} . " (";
862    } else {
863	$start .= $args{'function'} . " (";
864    }
865    print $start;
866
867    my $count = 0;
868    foreach my $parameter (@{$args{'parameterlist'}}) {
869	if ($count ne 0) {
870	    print ", ";
871	}
872	$count++;
873	$type = $args{'parametertypes'}{$parameter};
874
875	if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
876	    # pointer-to-function
877	    print $1 . $parameter . ") (" . $2 . ")";
878	} else {
879	    print $type . " " . $parameter;
880	}
881    }
882    if ($args{'typedef'}) {
883	print ");``\n\n";
884    } else {
885	print ")\n\n";
886	print_lineno($declaration_start_line);
887	$lineprefix = "   ";
888	output_highlight_rst($args{'purpose'});
889	print "\n";
890    }
891
892    print "**Parameters**\n\n";
893    $lineprefix = "  ";
894    foreach $parameter (@{$args{'parameterlist'}}) {
895	my $parameter_name = $parameter;
896	$parameter_name =~ s/\[.*//;
897	$type = $args{'parametertypes'}{$parameter};
898
899	if ($type ne "") {
900	    print "``$type $parameter``\n";
901	} else {
902	    print "``$parameter``\n";
903	}
904
905        print_lineno($parameterdesc_start_lines{$parameter_name});
906
907	if (defined($args{'parameterdescs'}{$parameter_name}) &&
908	    $args{'parameterdescs'}{$parameter_name} ne $undescribed) {
909	    output_highlight_rst($args{'parameterdescs'}{$parameter_name});
910	} else {
911	    print "  *undescribed*\n";
912	}
913	print "\n";
914    }
915
916    $lineprefix = $oldprefix;
917    output_section_rst(@_);
918}
919
920sub output_section_rst(%) {
921    my %args = %{$_[0]};
922    my $section;
923    my $oldprefix = $lineprefix;
924    $lineprefix = "";
925
926    foreach $section (@{$args{'sectionlist'}}) {
927	print "**$section**\n\n";
928        print_lineno($section_start_lines{$section});
929	output_highlight_rst($args{'sections'}{$section});
930	print "\n";
931    }
932    print "\n";
933    $lineprefix = $oldprefix;
934}
935
936sub output_enum_rst(%) {
937    my %args = %{$_[0]};
938    my ($parameter);
939    my $oldprefix = $lineprefix;
940    my $count;
941    my $name = "enum " . $args{'enum'};
942
943    print "\n\n.. c:type:: " . $name . "\n\n";
944    print_lineno($declaration_start_line);
945    $lineprefix = "   ";
946    output_highlight_rst($args{'purpose'});
947    print "\n";
948
949    print "**Constants**\n\n";
950    $lineprefix = "  ";
951    foreach $parameter (@{$args{'parameterlist'}}) {
952	print "``$parameter``\n";
953	if ($args{'parameterdescs'}{$parameter} ne $undescribed) {
954	    output_highlight_rst($args{'parameterdescs'}{$parameter});
955	} else {
956	    print "  *undescribed*\n";
957	}
958	print "\n";
959    }
960
961    $lineprefix = $oldprefix;
962    output_section_rst(@_);
963}
964
965sub output_typedef_rst(%) {
966    my %args = %{$_[0]};
967    my ($parameter);
968    my $oldprefix = $lineprefix;
969    my $name = "typedef " . $args{'typedef'};
970
971    print "\n\n.. c:type:: " . $name . "\n\n";
972    print_lineno($declaration_start_line);
973    $lineprefix = "   ";
974    output_highlight_rst($args{'purpose'});
975    print "\n";
976
977    $lineprefix = $oldprefix;
978    output_section_rst(@_);
979}
980
981sub output_struct_rst(%) {
982    my %args = %{$_[0]};
983    my ($parameter);
984    my $oldprefix = $lineprefix;
985    my $name = $args{'type'} . " " . $args{'struct'};
986
987    # Sphinx 3.0 and up will emit warnings for "c:type:: struct Foo".
988    # It wants to see "c:struct:: Foo" (and will add the word 'struct' in
989    # the rendered output).
990    if ((split(/\./, $sphinx_version))[0] >= 3) {
991        my $sname = $name;
992        $sname =~ s/^struct //;
993        print "\n\n.. c:struct:: " . $sname . "\n\n";
994    } else {
995        print "\n\n.. c:type:: " . $name . "\n\n";
996    }
997    print_lineno($declaration_start_line);
998    $lineprefix = "   ";
999    output_highlight_rst($args{'purpose'});
1000    print "\n";
1001
1002    print "**Definition**\n\n";
1003    print "::\n\n";
1004    my $declaration = $args{'definition'};
1005    $declaration =~ s/\t/  /g;
1006    print "  " . $args{'type'} . " " . $args{'struct'} . " {\n$declaration  };\n\n";
1007
1008    print "**Members**\n\n";
1009    $lineprefix = "  ";
1010    foreach $parameter (@{$args{'parameterlist'}}) {
1011	($parameter =~ /^#/) && next;
1012
1013	my $parameter_name = $parameter;
1014	$parameter_name =~ s/\[.*//;
1015
1016	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
1017	$type = $args{'parametertypes'}{$parameter};
1018        print_lineno($parameterdesc_start_lines{$parameter_name});
1019	print "``" . $parameter . "``\n";
1020	output_highlight_rst($args{'parameterdescs'}{$parameter_name});
1021	print "\n";
1022    }
1023    print "\n";
1024
1025    $lineprefix = $oldprefix;
1026    output_section_rst(@_);
1027}
1028
1029## none mode output functions
1030
1031sub output_function_none(%) {
1032}
1033
1034sub output_enum_none(%) {
1035}
1036
1037sub output_typedef_none(%) {
1038}
1039
1040sub output_struct_none(%) {
1041}
1042
1043sub output_blockhead_none(%) {
1044}
1045
1046##
1047# generic output function for all types (function, struct/union, typedef, enum);
1048# calls the generated, variable output_ function name based on
1049# functype and output_mode
1050sub output_declaration {
1051    no strict 'refs';
1052    my $name = shift;
1053    my $functype = shift;
1054    my $func = "output_${functype}_$output_mode";
1055    if (($output_selection == OUTPUT_ALL) ||
1056	(($output_selection == OUTPUT_INCLUDE ||
1057	  $output_selection == OUTPUT_EXPORTED) &&
1058	 defined($function_table{$name})) ||
1059	(($output_selection == OUTPUT_EXCLUDE ||
1060	  $output_selection == OUTPUT_INTERNAL) &&
1061	 !($functype eq "function" && defined($function_table{$name}))))
1062    {
1063	&$func(@_);
1064	$section_counter++;
1065    }
1066}
1067
1068##
1069# generic output function - calls the right one based on current output mode.
1070sub output_blockhead {
1071    no strict 'refs';
1072    my $func = "output_blockhead_" . $output_mode;
1073    &$func(@_);
1074    $section_counter++;
1075}
1076
1077##
1078# takes a declaration (struct, union, enum, typedef) and
1079# invokes the right handler. NOT called for functions.
1080sub dump_declaration($$) {
1081    no strict 'refs';
1082    my ($prototype, $file) = @_;
1083    my $func = "dump_" . $decl_type;
1084    &$func(@_);
1085}
1086
1087sub dump_union($$) {
1088    dump_struct(@_);
1089}
1090
1091sub dump_struct($$) {
1092    my $x = shift;
1093    my $file = shift;
1094
1095    if ($x =~ /(struct|union)\s+(\w+)\s*\{(.*)\}(\s*(__packed|__aligned|__attribute__\s*\(\([a-z0-9,_\s\(\)]*\)\)))*/) {
1096	my $decl_type = $1;
1097	$declaration_name = $2;
1098	my $members = $3;
1099
1100	# ignore members marked private:
1101	$members =~ s/\/\*\s*private:.*?\/\*\s*public:.*?\*\///gosi;
1102	$members =~ s/\/\*\s*private:.*//gosi;
1103	# strip comments:
1104	$members =~ s/\/\*.*?\*\///gos;
1105	# strip attributes
1106	$members =~ s/\s*__attribute__\s*\(\([a-z0-9,_\*\s\(\)]*\)\)//gi;
1107	$members =~ s/\s*__aligned\s*\([^;]*\)//gos;
1108	$members =~ s/\s*__packed\s*//gos;
1109	$members =~ s/\s*CRYPTO_MINALIGN_ATTR//gos;
1110	# replace DECLARE_BITMAP
1111	$members =~ s/DECLARE_BITMAP\s*\(([^,)]+),\s*([^,)]+)\)/unsigned long $1\[BITS_TO_LONGS($2)\]/gos;
1112	# replace DECLARE_HASHTABLE
1113	$members =~ s/DECLARE_HASHTABLE\s*\(([^,)]+),\s*([^,)]+)\)/unsigned long $1\[1 << (($2) - 1)\]/gos;
1114	# replace DECLARE_KFIFO
1115	$members =~ s/DECLARE_KFIFO\s*\(([^,)]+),\s*([^,)]+),\s*([^,)]+)\)/$2 \*$1/gos;
1116	# replace DECLARE_KFIFO_PTR
1117	$members =~ s/DECLARE_KFIFO_PTR\s*\(([^,)]+),\s*([^,)]+)\)/$2 \*$1/gos;
1118
1119	my $declaration = $members;
1120
1121	# Split nested struct/union elements as newer ones
1122	while ($members =~ m/(struct|union)([^\{\};]+)\{([^\{\}]*)\}([^\{\}\;]*)\;/) {
1123		my $newmember;
1124		my $maintype = $1;
1125		my $ids = $4;
1126		my $content = $3;
1127		foreach my $id(split /,/, $ids) {
1128			$newmember .= "$maintype $id; ";
1129
1130			$id =~ s/[:\[].*//;
1131			$id =~ s/^\s*\**(\S+)\s*/$1/;
1132			foreach my $arg (split /;/, $content) {
1133				next if ($arg =~ m/^\s*$/);
1134				if ($arg =~ m/^([^\(]+\(\*?\s*)([\w\.]*)(\s*\).*)/) {
1135					# pointer-to-function
1136					my $type = $1;
1137					my $name = $2;
1138					my $extra = $3;
1139					next if (!$name);
1140					if ($id =~ m/^\s*$/) {
1141						# anonymous struct/union
1142						$newmember .= "$type$name$extra; ";
1143					} else {
1144						$newmember .= "$type$id.$name$extra; ";
1145					}
1146				} else {
1147					my $type;
1148					my $names;
1149					$arg =~ s/^\s+//;
1150					$arg =~ s/\s+$//;
1151					# Handle bitmaps
1152					$arg =~ s/:\s*\d+\s*//g;
1153					# Handle arrays
1154					$arg =~ s/\[.*\]//g;
1155					# The type may have multiple words,
1156					# and multiple IDs can be defined, like:
1157					#	const struct foo, *bar, foobar
1158					# So, we remove spaces when parsing the
1159					# names, in order to match just names
1160					# and commas for the names
1161					$arg =~ s/\s*,\s*/,/g;
1162					if ($arg =~ m/(.*)\s+([\S+,]+)/) {
1163						$type = $1;
1164						$names = $2;
1165					} else {
1166						$newmember .= "$arg; ";
1167						next;
1168					}
1169					foreach my $name (split /,/, $names) {
1170						$name =~ s/^\s*\**(\S+)\s*/$1/;
1171						next if (($name =~ m/^\s*$/));
1172						if ($id =~ m/^\s*$/) {
1173							# anonymous struct/union
1174							$newmember .= "$type $name; ";
1175						} else {
1176							$newmember .= "$type $id.$name; ";
1177						}
1178					}
1179				}
1180			}
1181		}
1182		$members =~ s/(struct|union)([^\{\};]+)\{([^\{\}]*)\}([^\{\}\;]*)\;/$newmember/;
1183	}
1184
1185	# Ignore other nested elements, like enums
1186	$members =~ s/(\{[^\{\}]*\})//g;
1187
1188	create_parameterlist($members, ';', $file, $declaration_name);
1189	check_sections($file, $declaration_name, $decl_type, $sectcheck, $struct_actual);
1190
1191	# Adjust declaration for better display
1192	$declaration =~ s/([\{;])/$1\n/g;
1193	$declaration =~ s/\}\s+;/};/g;
1194	# Better handle inlined enums
1195	do {} while ($declaration =~ s/(enum\s+\{[^\}]+),([^\n])/$1,\n$2/);
1196
1197	my @def_args = split /\n/, $declaration;
1198	my $level = 1;
1199	$declaration = "";
1200	foreach my $clause (@def_args) {
1201		$clause =~ s/^\s+//;
1202		$clause =~ s/\s+$//;
1203		$clause =~ s/\s+/ /;
1204		next if (!$clause);
1205		$level-- if ($clause =~ m/(\})/ && $level > 1);
1206		if (!($clause =~ m/^\s*#/)) {
1207			$declaration .= "\t" x $level;
1208		}
1209		$declaration .= "\t" . $clause . "\n";
1210		$level++ if ($clause =~ m/(\{)/ && !($clause =~m/\}/));
1211	}
1212	output_declaration($declaration_name,
1213			   'struct',
1214			   {'struct' => $declaration_name,
1215			    'module' => $modulename,
1216			    'definition' => $declaration,
1217			    'parameterlist' => \@parameterlist,
1218			    'parameterdescs' => \%parameterdescs,
1219			    'parametertypes' => \%parametertypes,
1220			    'sectionlist' => \@sectionlist,
1221			    'sections' => \%sections,
1222			    'purpose' => $declaration_purpose,
1223			    'type' => $decl_type
1224			   });
1225    }
1226    else {
1227	print STDERR "${file}:$.: error: Cannot parse struct or union!\n";
1228	++$errors;
1229    }
1230}
1231
1232
1233sub show_warnings($$) {
1234	my $functype = shift;
1235	my $name = shift;
1236
1237	return 1 if ($output_selection == OUTPUT_ALL);
1238
1239	if ($output_selection == OUTPUT_EXPORTED) {
1240		if (defined($function_table{$name})) {
1241			return 1;
1242		} else {
1243			return 0;
1244		}
1245	}
1246        if ($output_selection == OUTPUT_INTERNAL) {
1247		if (!($functype eq "function" && defined($function_table{$name}))) {
1248			return 1;
1249		} else {
1250			return 0;
1251		}
1252	}
1253	if ($output_selection == OUTPUT_INCLUDE) {
1254		if (defined($function_table{$name})) {
1255			return 1;
1256		} else {
1257			return 0;
1258		}
1259	}
1260	if ($output_selection == OUTPUT_EXCLUDE) {
1261		if (!defined($function_table{$name})) {
1262			return 1;
1263		} else {
1264			return 0;
1265		}
1266	}
1267	die("Please add the new output type at show_warnings()");
1268}
1269
1270sub dump_enum($$) {
1271    my $x = shift;
1272    my $file = shift;
1273
1274    $x =~ s@/\*.*?\*/@@gos;	# strip comments.
1275    # strip #define macros inside enums
1276    $x =~ s@#\s*((define|ifdef)\s+|endif)[^;]*;@@gos;
1277
1278    if ($x =~ /enum\s+(\w*)\s*\{(.*)\}/) {
1279	$declaration_name = $1;
1280	my $members = $2;
1281	my %_members;
1282
1283	$members =~ s/\s+$//;
1284
1285	foreach my $arg (split ',', $members) {
1286	    $arg =~ s/^\s*(\w+).*/$1/;
1287	    push @parameterlist, $arg;
1288	    if (!$parameterdescs{$arg}) {
1289		$parameterdescs{$arg} = $undescribed;
1290	        if (show_warnings("enum", $declaration_name)) {
1291			print STDERR "${file}:$.: warning: Enum value '$arg' not described in enum '$declaration_name'\n";
1292		}
1293	    }
1294	    $_members{$arg} = 1;
1295	}
1296
1297	while (my ($k, $v) = each %parameterdescs) {
1298	    if (!exists($_members{$k})) {
1299	        if (show_warnings("enum", $declaration_name)) {
1300		     print STDERR "${file}:$.: warning: Excess enum value '$k' description in '$declaration_name'\n";
1301		}
1302	    }
1303        }
1304
1305	output_declaration($declaration_name,
1306			   'enum',
1307			   {'enum' => $declaration_name,
1308			    'module' => $modulename,
1309			    'parameterlist' => \@parameterlist,
1310			    'parameterdescs' => \%parameterdescs,
1311			    'sectionlist' => \@sectionlist,
1312			    'sections' => \%sections,
1313			    'purpose' => $declaration_purpose
1314			   });
1315    }
1316    else {
1317	print STDERR "${file}:$.: error: Cannot parse enum!\n";
1318	++$errors;
1319    }
1320}
1321
1322sub dump_typedef($$) {
1323    my $x = shift;
1324    my $file = shift;
1325
1326    $x =~ s@/\*.*?\*/@@gos;	# strip comments.
1327
1328    # Parse function prototypes
1329    if ($x =~ /typedef\s+(\w+\s*\**)\s*\(\*?\s*(\w\S+)\s*\)\s*\((.*)\);/ ||
1330	$x =~ /typedef\s+(\w+\s*\**)\s*(\w\S+)\s*\s*\((.*)\);/) {
1331
1332	# Function typedefs
1333	$return_type = $1;
1334	$declaration_name = $2;
1335	my $args = $3;
1336
1337	create_parameterlist($args, ',', $file, $declaration_name);
1338
1339	output_declaration($declaration_name,
1340			   'function',
1341			   {'function' => $declaration_name,
1342			    'typedef' => 1,
1343			    'module' => $modulename,
1344			    'functiontype' => $return_type,
1345			    'parameterlist' => \@parameterlist,
1346			    'parameterdescs' => \%parameterdescs,
1347			    'parametertypes' => \%parametertypes,
1348			    'sectionlist' => \@sectionlist,
1349			    'sections' => \%sections,
1350			    'purpose' => $declaration_purpose
1351			   });
1352	return;
1353    }
1354
1355    while (($x =~ /\(*.\)\s*;$/) || ($x =~ /\[*.\]\s*;$/)) {
1356	$x =~ s/\(*.\)\s*;$/;/;
1357	$x =~ s/\[*.\]\s*;$/;/;
1358    }
1359
1360    if ($x =~ /typedef.*\s+(\w+)\s*;/) {
1361	$declaration_name = $1;
1362
1363	output_declaration($declaration_name,
1364			   'typedef',
1365			   {'typedef' => $declaration_name,
1366			    'module' => $modulename,
1367			    'sectionlist' => \@sectionlist,
1368			    'sections' => \%sections,
1369			    'purpose' => $declaration_purpose
1370			   });
1371    }
1372    else {
1373	print STDERR "${file}:$.: error: Cannot parse typedef!\n";
1374	++$errors;
1375    }
1376}
1377
1378sub save_struct_actual($) {
1379    my $actual = shift;
1380
1381    # strip all spaces from the actual param so that it looks like one string item
1382    $actual =~ s/\s*//g;
1383    $struct_actual = $struct_actual . $actual . " ";
1384}
1385
1386sub create_parameterlist($$$$) {
1387    my $args = shift;
1388    my $splitter = shift;
1389    my $file = shift;
1390    my $declaration_name = shift;
1391    my $type;
1392    my $param;
1393
1394    # temporarily replace commas inside function pointer definition
1395    while ($args =~ /(\([^\),]+),/) {
1396	$args =~ s/(\([^\),]+),/$1#/g;
1397    }
1398
1399    foreach my $arg (split($splitter, $args)) {
1400	# strip comments
1401	$arg =~ s/\/\*.*\*\///;
1402	# strip leading/trailing spaces
1403	$arg =~ s/^\s*//;
1404	$arg =~ s/\s*$//;
1405	$arg =~ s/\s+/ /;
1406
1407	if ($arg =~ /^#/) {
1408	    # Treat preprocessor directive as a typeless variable just to fill
1409	    # corresponding data structures "correctly". Catch it later in
1410	    # output_* subs.
1411	    push_parameter($arg, "", $file);
1412	} elsif ($arg =~ m/\(.+\)\s*\(/) {
1413	    # pointer-to-function
1414	    $arg =~ tr/#/,/;
1415	    $arg =~ m/[^\(]+\(\*?\s*([\w\.]*)\s*\)/;
1416	    $param = $1;
1417	    $type = $arg;
1418	    $type =~ s/([^\(]+\(\*?)\s*$param/$1/;
1419	    save_struct_actual($param);
1420	    push_parameter($param, $type, $file, $declaration_name);
1421	} elsif ($arg) {
1422	    $arg =~ s/\s*:\s*/:/g;
1423	    $arg =~ s/\s*\[/\[/g;
1424
1425	    my @args = split('\s*,\s*', $arg);
1426	    if ($args[0] =~ m/\*/) {
1427		$args[0] =~ s/(\*+)\s*/ $1/;
1428	    }
1429
1430	    my @first_arg;
1431	    if ($args[0] =~ /^(.*\s+)(.*?\[.*\].*)$/) {
1432		    shift @args;
1433		    push(@first_arg, split('\s+', $1));
1434		    push(@first_arg, $2);
1435	    } else {
1436		    @first_arg = split('\s+', shift @args);
1437	    }
1438
1439	    unshift(@args, pop @first_arg);
1440	    $type = join " ", @first_arg;
1441
1442	    foreach $param (@args) {
1443		if ($param =~ m/^(\*+)\s*(.*)/) {
1444		    save_struct_actual($2);
1445		    push_parameter($2, "$type $1", $file, $declaration_name);
1446		}
1447		elsif ($param =~ m/(.*?):(\d+)/) {
1448		    if ($type ne "") { # skip unnamed bit-fields
1449			save_struct_actual($1);
1450			push_parameter($1, "$type:$2", $file, $declaration_name)
1451		    }
1452		}
1453		else {
1454		    save_struct_actual($param);
1455		    push_parameter($param, $type, $file, $declaration_name);
1456		}
1457	    }
1458	}
1459    }
1460}
1461
1462sub push_parameter($$$$) {
1463	my $param = shift;
1464	my $type = shift;
1465	my $file = shift;
1466	my $declaration_name = shift;
1467
1468	if (($anon_struct_union == 1) && ($type eq "") &&
1469	    ($param eq "}")) {
1470		return;		# ignore the ending }; from anon. struct/union
1471	}
1472
1473	$anon_struct_union = 0;
1474	$param =~ s/[\[\)].*//;
1475
1476	if ($type eq "" && $param =~ /\.\.\.$/)
1477	{
1478	    if (!$param =~ /\w\.\.\.$/) {
1479	      # handles unnamed variable parameters
1480	      $param = "...";
1481	    }
1482	    if (!defined $parameterdescs{$param} || $parameterdescs{$param} eq "") {
1483		$parameterdescs{$param} = "variable arguments";
1484	    }
1485	}
1486	elsif ($type eq "" && ($param eq "" or $param eq "void"))
1487	{
1488	    $param="void";
1489	    $parameterdescs{void} = "no arguments";
1490	}
1491	elsif ($type eq "" && ($param eq "struct" or $param eq "union"))
1492	# handle unnamed (anonymous) union or struct:
1493	{
1494		$type = $param;
1495		$param = "{unnamed_" . $param . "}";
1496		$parameterdescs{$param} = "anonymous\n";
1497		$anon_struct_union = 1;
1498	}
1499
1500	# warn if parameter has no description
1501	# (but ignore ones starting with # as these are not parameters
1502	# but inline preprocessor statements);
1503	# Note: It will also ignore void params and unnamed structs/unions
1504	if (!defined $parameterdescs{$param} && $param !~ /^#/) {
1505		$parameterdescs{$param} = $undescribed;
1506
1507	        if (show_warnings($type, $declaration_name) && $param !~ /\./) {
1508			print STDERR
1509			      "${file}:$.: warning: Function parameter or member '$param' not described in '$declaration_name'\n";
1510			++$warnings;
1511		}
1512	}
1513
1514	# strip spaces from $param so that it is one continuous string
1515	# on @parameterlist;
1516	# this fixes a problem where check_sections() cannot find
1517	# a parameter like "addr[6 + 2]" because it actually appears
1518	# as "addr[6", "+", "2]" on the parameter list;
1519	# but it's better to maintain the param string unchanged for output,
1520	# so just weaken the string compare in check_sections() to ignore
1521	# "[blah" in a parameter string;
1522	###$param =~ s/\s*//g;
1523	push @parameterlist, $param;
1524	$type =~ s/\s\s+/ /g;
1525	$parametertypes{$param} = $type;
1526}
1527
1528sub check_sections($$$$$) {
1529	my ($file, $decl_name, $decl_type, $sectcheck, $prmscheck) = @_;
1530	my @sects = split ' ', $sectcheck;
1531	my @prms = split ' ', $prmscheck;
1532	my $err;
1533	my ($px, $sx);
1534	my $prm_clean;		# strip trailing "[array size]" and/or beginning "*"
1535
1536	foreach $sx (0 .. $#sects) {
1537		$err = 1;
1538		foreach $px (0 .. $#prms) {
1539			$prm_clean = $prms[$px];
1540			$prm_clean =~ s/\[.*\]//;
1541			$prm_clean =~ s/__attribute__\s*\(\([a-z,_\*\s\(\)]*\)\)//i;
1542			# ignore array size in a parameter string;
1543			# however, the original param string may contain
1544			# spaces, e.g.:  addr[6 + 2]
1545			# and this appears in @prms as "addr[6" since the
1546			# parameter list is split at spaces;
1547			# hence just ignore "[..." for the sections check;
1548			$prm_clean =~ s/\[.*//;
1549
1550			##$prm_clean =~ s/^\**//;
1551			if ($prm_clean eq $sects[$sx]) {
1552				$err = 0;
1553				last;
1554			}
1555		}
1556		if ($err) {
1557			if ($decl_type eq "function") {
1558				print STDERR "${file}:$.: warning: " .
1559					"Excess function parameter " .
1560					"'$sects[$sx]' " .
1561					"description in '$decl_name'\n";
1562				++$warnings;
1563			}
1564		}
1565	}
1566}
1567
1568##
1569# Checks the section describing the return value of a function.
1570sub check_return_section {
1571        my $file = shift;
1572        my $declaration_name = shift;
1573        my $return_type = shift;
1574
1575        # Ignore an empty return type (It's a macro)
1576        # Ignore functions with a "void" return type. (But don't ignore "void *")
1577        if (($return_type eq "") || ($return_type =~ /void\s*\w*\s*$/)) {
1578                return;
1579        }
1580
1581        if (!defined($sections{$section_return}) ||
1582            $sections{$section_return} eq "") {
1583                print STDERR "${file}:$.: warning: " .
1584                        "No description found for return value of " .
1585                        "'$declaration_name'\n";
1586                ++$warnings;
1587        }
1588}
1589
1590##
1591# takes a function prototype and the name of the current file being
1592# processed and spits out all the details stored in the global
1593# arrays/hashes.
1594sub dump_function($$) {
1595    my $prototype = shift;
1596    my $file = shift;
1597    my $noret = 0;
1598
1599    $prototype =~ s/^static +//;
1600    $prototype =~ s/^extern +//;
1601    $prototype =~ s/^asmlinkage +//;
1602    $prototype =~ s/^inline +//;
1603    $prototype =~ s/^__inline__ +//;
1604    $prototype =~ s/^__inline +//;
1605    $prototype =~ s/^__always_inline +//;
1606    $prototype =~ s/^noinline +//;
1607    $prototype =~ s/__init +//;
1608    $prototype =~ s/__init_or_module +//;
1609    $prototype =~ s/__meminit +//;
1610    $prototype =~ s/__must_check +//;
1611    $prototype =~ s/__weak +//;
1612    $prototype =~ s/__sched +//;
1613    $prototype =~ s/__printf\s*\(\s*\d*\s*,\s*\d*\s*\) +//;
1614    my $define = $prototype =~ s/^#\s*define\s+//; #ak added
1615    $prototype =~ s/__attribute__\s*\(\(
1616            (?:
1617                 [\w\s]++          # attribute name
1618                 (?:\([^)]*+\))?   # attribute arguments
1619                 \s*+,?            # optional comma at the end
1620            )+
1621          \)\)\s+//x;
1622
1623    # Yes, this truly is vile.  We are looking for:
1624    # 1. Return type (may be nothing if we're looking at a macro)
1625    # 2. Function name
1626    # 3. Function parameters.
1627    #
1628    # All the while we have to watch out for function pointer parameters
1629    # (which IIRC is what the two sections are for), C types (these
1630    # regexps don't even start to express all the possibilities), and
1631    # so on.
1632    #
1633    # If you mess with these regexps, it's a good idea to check that
1634    # the following functions' documentation still comes out right:
1635    # - parport_register_device (function pointer parameters)
1636    # - qatomic_set (macro)
1637    # - pci_match_device, __copy_to_user (long return type)
1638
1639    if ($define && $prototype =~ m/^()([a-zA-Z0-9_~:]+)\s+/) {
1640        # This is an object-like macro, it has no return type and no parameter
1641        # list.
1642        # Function-like macros are not allowed to have spaces between
1643        # declaration_name and opening parenthesis (notice the \s+).
1644        $return_type = $1;
1645        $declaration_name = $2;
1646        $noret = 1;
1647    } elsif ($prototype =~ m/^()([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1648	$prototype =~ m/^(\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1649	$prototype =~ m/^(\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1650	$prototype =~ m/^(\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1651	$prototype =~ m/^(\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1652	$prototype =~ m/^(\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1653	$prototype =~ m/^(\w+\s+\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1654	$prototype =~ m/^()([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1655	$prototype =~ m/^(\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1656	$prototype =~ m/^(\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1657	$prototype =~ m/^(\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1658	$prototype =~ m/^(\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1659	$prototype =~ m/^(\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1660	$prototype =~ m/^(\w+\s+\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1661	$prototype =~ m/^(\w+\s+\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1662	$prototype =~ m/^(\w+\s+\w+\s+\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1663	$prototype =~ m/^(\w+\s+\w+\s*\*+\s*\w+\s*\*+\s*)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/)  {
1664	$return_type = $1;
1665	$declaration_name = $2;
1666	my $args = $3;
1667
1668	create_parameterlist($args, ',', $file, $declaration_name);
1669    } else {
1670	print STDERR "${file}:$.: warning: cannot understand function prototype: '$prototype'\n";
1671	return;
1672    }
1673
1674	my $prms = join " ", @parameterlist;
1675	check_sections($file, $declaration_name, "function", $sectcheck, $prms);
1676
1677        # This check emits a lot of warnings at the moment, because many
1678        # functions don't have a 'Return' doc section. So until the number
1679        # of warnings goes sufficiently down, the check is only performed in
1680        # verbose mode.
1681        # TODO: always perform the check.
1682        if ($verbose && !$noret) {
1683                check_return_section($file, $declaration_name, $return_type);
1684        }
1685
1686    output_declaration($declaration_name,
1687		       'function',
1688		       {'function' => $declaration_name,
1689			'module' => $modulename,
1690			'functiontype' => $return_type,
1691			'parameterlist' => \@parameterlist,
1692			'parameterdescs' => \%parameterdescs,
1693			'parametertypes' => \%parametertypes,
1694			'sectionlist' => \@sectionlist,
1695			'sections' => \%sections,
1696			'purpose' => $declaration_purpose
1697		       });
1698}
1699
1700sub reset_state {
1701    $function = "";
1702    %parameterdescs = ();
1703    %parametertypes = ();
1704    @parameterlist = ();
1705    %sections = ();
1706    @sectionlist = ();
1707    $sectcheck = "";
1708    $struct_actual = "";
1709    $prototype = "";
1710
1711    $state = STATE_NORMAL;
1712    $inline_doc_state = STATE_INLINE_NA;
1713}
1714
1715sub tracepoint_munge($) {
1716	my $file = shift;
1717	my $tracepointname = 0;
1718	my $tracepointargs = 0;
1719
1720	if ($prototype =~ m/TRACE_EVENT\((.*?),/) {
1721		$tracepointname = $1;
1722	}
1723	if ($prototype =~ m/DEFINE_SINGLE_EVENT\((.*?),/) {
1724		$tracepointname = $1;
1725	}
1726	if ($prototype =~ m/DEFINE_EVENT\((.*?),(.*?),/) {
1727		$tracepointname = $2;
1728	}
1729	$tracepointname =~ s/^\s+//; #strip leading whitespace
1730	if ($prototype =~ m/TP_PROTO\((.*?)\)/) {
1731		$tracepointargs = $1;
1732	}
1733	if (($tracepointname eq 0) || ($tracepointargs eq 0)) {
1734		print STDERR "${file}:$.: warning: Unrecognized tracepoint format: \n".
1735			     "$prototype\n";
1736	} else {
1737		$prototype = "static inline void trace_$tracepointname($tracepointargs)";
1738	}
1739}
1740
1741sub syscall_munge() {
1742	my $void = 0;
1743
1744	$prototype =~ s@[\r\n]+@ @gos; # strip newlines/CR's
1745##	if ($prototype =~ m/SYSCALL_DEFINE0\s*\(\s*(a-zA-Z0-9_)*\s*\)/) {
1746	if ($prototype =~ m/SYSCALL_DEFINE0/) {
1747		$void = 1;
1748##		$prototype = "long sys_$1(void)";
1749	}
1750
1751	$prototype =~ s/SYSCALL_DEFINE.*\(/long sys_/; # fix return type & func name
1752	if ($prototype =~ m/long (sys_.*?),/) {
1753		$prototype =~ s/,/\(/;
1754	} elsif ($void) {
1755		$prototype =~ s/\)/\(void\)/;
1756	}
1757
1758	# now delete all of the odd-number commas in $prototype
1759	# so that arg types & arg names don't have a comma between them
1760	my $count = 0;
1761	my $len = length($prototype);
1762	if ($void) {
1763		$len = 0;	# skip the for-loop
1764	}
1765	for (my $ix = 0; $ix < $len; $ix++) {
1766		if (substr($prototype, $ix, 1) eq ',') {
1767			$count++;
1768			if ($count % 2 == 1) {
1769				substr($prototype, $ix, 1) = ' ';
1770			}
1771		}
1772	}
1773}
1774
1775sub process_proto_function($$) {
1776    my $x = shift;
1777    my $file = shift;
1778
1779    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line
1780
1781    if ($x =~ m#\s*/\*\s+MACDOC\s*#io || ($x =~ /^#/ && $x !~ /^#\s*define/)) {
1782	# do nothing
1783    }
1784    elsif ($x =~ /([^\{]*)/) {
1785	$prototype .= $1;
1786    }
1787
1788    if (($x =~ /\{/) || ($x =~ /\#\s*define/) || ($x =~ /;/)) {
1789	$prototype =~ s@/\*.*?\*/@@gos;	# strip comments.
1790	$prototype =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
1791	$prototype =~ s@^\s+@@gos; # strip leading spaces
1792	if ($prototype =~ /SYSCALL_DEFINE/) {
1793		syscall_munge();
1794	}
1795	if ($prototype =~ /TRACE_EVENT/ || $prototype =~ /DEFINE_EVENT/ ||
1796	    $prototype =~ /DEFINE_SINGLE_EVENT/)
1797	{
1798		tracepoint_munge($file);
1799	}
1800	dump_function($prototype, $file);
1801	reset_state();
1802    }
1803}
1804
1805sub process_proto_type($$) {
1806    my $x = shift;
1807    my $file = shift;
1808
1809    $x =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
1810    $x =~ s@^\s+@@gos; # strip leading spaces
1811    $x =~ s@\s+$@@gos; # strip trailing spaces
1812    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line
1813
1814    if ($x =~ /^#/) {
1815	# To distinguish preprocessor directive from regular declaration later.
1816	$x .= ";";
1817    }
1818
1819    while (1) {
1820	if ( $x =~ /([^\{\};]*)([\{\};])(.*)/ ) {
1821            if( length $prototype ) {
1822                $prototype .= " "
1823            }
1824	    $prototype .= $1 . $2;
1825	    ($2 eq '{') && $brcount++;
1826	    ($2 eq '}') && $brcount--;
1827	    if (($2 eq ';') && ($brcount == 0)) {
1828		dump_declaration($prototype, $file);
1829		reset_state();
1830		last;
1831	    }
1832	    $x = $3;
1833	} else {
1834	    $prototype .= $x;
1835	    last;
1836	}
1837    }
1838}
1839
1840
1841sub map_filename($) {
1842    my $file;
1843    my ($orig_file) = @_;
1844
1845    if (defined($ENV{'SRCTREE'})) {
1846	$file = "$ENV{'SRCTREE'}" . "/" . $orig_file;
1847    } else {
1848	$file = $orig_file;
1849    }
1850
1851    if (defined($source_map{$file})) {
1852	$file = $source_map{$file};
1853    }
1854
1855    return $file;
1856}
1857
1858sub process_export_file($) {
1859    my ($orig_file) = @_;
1860    my $file = map_filename($orig_file);
1861
1862    if (!open(IN,"<$file")) {
1863	print STDERR "Error: Cannot open file $file\n";
1864	++$errors;
1865	return;
1866    }
1867
1868    while (<IN>) {
1869	if (/$export_symbol/) {
1870	    $function_table{$2} = 1;
1871	}
1872    }
1873
1874    close(IN);
1875}
1876
1877#
1878# Parsers for the various processing states.
1879#
1880# STATE_NORMAL: looking for the /** to begin everything.
1881#
1882sub process_normal() {
1883    if (/$doc_start/o) {
1884	$state = STATE_NAME;	# next line is always the function name
1885	$in_doc_sect = 0;
1886	$declaration_start_line = $. + 1;
1887    }
1888}
1889
1890#
1891# STATE_NAME: Looking for the "name - description" line
1892#
1893sub process_name($$) {
1894    my $file = shift;
1895    my $identifier;
1896    my $descr;
1897
1898    if (/$doc_block/o) {
1899	$state = STATE_DOCBLOCK;
1900	$contents = "";
1901	$new_start_line = $. + 1;
1902
1903	if ( $1 eq "" ) {
1904	    $section = $section_intro;
1905	} else {
1906	    $section = $1;
1907	}
1908    }
1909    elsif (/$doc_decl/o) {
1910	$identifier = $1;
1911	if (/\s*([\w\s]+?)(\s*-|:)/) {
1912	    $identifier = $1;
1913	}
1914
1915	$state = STATE_BODY;
1916	# if there's no @param blocks need to set up default section
1917	# here
1918	$contents = "";
1919	$section = $section_default;
1920	$new_start_line = $. + 1;
1921	if (/[-:](.*)/) {
1922	    # strip leading/trailing/multiple spaces
1923	    $descr= $1;
1924	    $descr =~ s/^\s*//;
1925	    $descr =~ s/\s*$//;
1926	    $descr =~ s/\s+/ /g;
1927	    $declaration_purpose = $descr;
1928	    $state = STATE_BODY_MAYBE;
1929	} else {
1930	    $declaration_purpose = "";
1931	}
1932
1933	if (($declaration_purpose eq "") && $verbose) {
1934	    print STDERR "${file}:$.: warning: missing initial short description on line:\n";
1935	    print STDERR $_;
1936	    ++$warnings;
1937	}
1938
1939	if ($identifier =~ m/^struct\b/) {
1940	    $decl_type = 'struct';
1941	} elsif ($identifier =~ m/^union\b/) {
1942	    $decl_type = 'union';
1943	} elsif ($identifier =~ m/^enum\b/) {
1944	    $decl_type = 'enum';
1945	} elsif ($identifier =~ m/^typedef\b/) {
1946	    $decl_type = 'typedef';
1947	} else {
1948	    $decl_type = 'function';
1949	}
1950
1951	if ($verbose) {
1952	    print STDERR "${file}:$.: info: Scanning doc for $identifier\n";
1953	}
1954    } else {
1955	print STDERR "${file}:$.: warning: Cannot understand $_ on line $.",
1956	    " - I thought it was a doc line\n";
1957	++$warnings;
1958	$state = STATE_NORMAL;
1959    }
1960}
1961
1962
1963#
1964# STATE_BODY and STATE_BODY_MAYBE: the bulk of a kerneldoc comment.
1965#
1966sub process_body($$) {
1967    my $file = shift;
1968
1969    if (/$doc_sect/i) { # case insensitive for supported section names
1970	$newsection = $1;
1971	$newcontents = $2;
1972
1973	# map the supported section names to the canonical names
1974	if ($newsection =~ m/^description$/i) {
1975	    $newsection = $section_default;
1976	} elsif ($newsection =~ m/^context$/i) {
1977	    $newsection = $section_context;
1978	} elsif ($newsection =~ m/^returns?$/i) {
1979	    $newsection = $section_return;
1980	} elsif ($newsection =~ m/^\@return$/) {
1981	    # special: @return is a section, not a param description
1982	    $newsection = $section_return;
1983	}
1984
1985	if (($contents ne "") && ($contents ne "\n")) {
1986	    if (!$in_doc_sect && $verbose) {
1987		print STDERR "${file}:$.: warning: contents before sections\n";
1988		++$warnings;
1989	    }
1990	    dump_section($file, $section, $contents);
1991	    $section = $section_default;
1992	}
1993
1994	$in_doc_sect = 1;
1995	$state = STATE_BODY;
1996	$contents = $newcontents;
1997	$new_start_line = $.;
1998	while (substr($contents, 0, 1) eq " ") {
1999	    $contents = substr($contents, 1);
2000	}
2001	if ($contents ne "") {
2002	    $contents .= "\n";
2003	}
2004	$section = $newsection;
2005	$leading_space = undef;
2006    } elsif (/$doc_end/) {
2007	if (($contents ne "") && ($contents ne "\n")) {
2008	    dump_section($file, $section, $contents);
2009	    $section = $section_default;
2010	    $contents = "";
2011	}
2012	# look for doc_com + <text> + doc_end:
2013	if ($_ =~ m'\s*\*\s*[a-zA-Z_0-9:\.]+\*/') {
2014	    print STDERR "${file}:$.: warning: suspicious ending line: $_";
2015	    ++$warnings;
2016	}
2017
2018	$prototype = "";
2019	$state = STATE_PROTO;
2020	$brcount = 0;
2021    } elsif (/$doc_content/) {
2022	# miguel-style comment kludge, look for blank lines after
2023	# @parameter line to signify start of description
2024	if ($1 eq "") {
2025	    if ($section =~ m/^@/ || $section eq $section_context) {
2026		dump_section($file, $section, $contents);
2027		$section = $section_default;
2028		$contents = "";
2029		$new_start_line = $.;
2030	    } else {
2031		$contents .= "\n";
2032	    }
2033	    $state = STATE_BODY;
2034	} elsif ($state == STATE_BODY_MAYBE) {
2035	    # Continued declaration purpose
2036	    chomp($declaration_purpose);
2037	    $declaration_purpose .= " " . $1;
2038	    $declaration_purpose =~ s/\s+/ /g;
2039	} else {
2040	    my $cont = $1;
2041	    if ($section =~ m/^@/ || $section eq $section_context) {
2042		if (!defined $leading_space) {
2043		    if ($cont =~ m/^(\s+)/) {
2044			$leading_space = $1;
2045		    } else {
2046			$leading_space = "";
2047		    }
2048		}
2049		$cont =~ s/^$leading_space//;
2050	    }
2051	    $contents .= $cont . "\n";
2052	}
2053    } else {
2054	# i dont know - bad line?  ignore.
2055	print STDERR "${file}:$.: warning: bad line: $_";
2056	++$warnings;
2057    }
2058}
2059
2060
2061#
2062# STATE_PROTO: reading a function/whatever prototype.
2063#
2064sub process_proto($$) {
2065    my $file = shift;
2066
2067    if (/$doc_inline_oneline/) {
2068	$section = $1;
2069	$contents = $2;
2070	if ($contents ne "") {
2071	    $contents .= "\n";
2072	    dump_section($file, $section, $contents);
2073	    $section = $section_default;
2074	    $contents = "";
2075	}
2076    } elsif (/$doc_inline_start/) {
2077	$state = STATE_INLINE;
2078	$inline_doc_state = STATE_INLINE_NAME;
2079    } elsif ($decl_type eq 'function') {
2080	process_proto_function($_, $file);
2081    } else {
2082	process_proto_type($_, $file);
2083    }
2084}
2085
2086#
2087# STATE_DOCBLOCK: within a DOC: block.
2088#
2089sub process_docblock($$) {
2090    my $file = shift;
2091
2092    if (/$doc_end/) {
2093	dump_doc_section($file, $section, $contents);
2094	$section = $section_default;
2095	$contents = "";
2096	$function = "";
2097	%parameterdescs = ();
2098	%parametertypes = ();
2099	@parameterlist = ();
2100	%sections = ();
2101	@sectionlist = ();
2102	$prototype = "";
2103	$state = STATE_NORMAL;
2104    } elsif (/$doc_content/) {
2105	if ( $1 eq "" )	{
2106	    $contents .= $blankline;
2107	} else {
2108	    $contents .= $1 . "\n";
2109	}
2110    }
2111}
2112
2113#
2114# STATE_INLINE: docbook comments within a prototype.
2115#
2116sub process_inline($$) {
2117    my $file = shift;
2118
2119    # First line (state 1) needs to be a @parameter
2120    if ($inline_doc_state == STATE_INLINE_NAME && /$doc_inline_sect/o) {
2121	$section = $1;
2122	$contents = $2;
2123	$new_start_line = $.;
2124	if ($contents ne "") {
2125	    while (substr($contents, 0, 1) eq " ") {
2126		$contents = substr($contents, 1);
2127	    }
2128	    $contents .= "\n";
2129	}
2130	$inline_doc_state = STATE_INLINE_TEXT;
2131	# Documentation block end */
2132    } elsif (/$doc_inline_end/) {
2133	if (($contents ne "") && ($contents ne "\n")) {
2134	    dump_section($file, $section, $contents);
2135	    $section = $section_default;
2136	    $contents = "";
2137	}
2138	$state = STATE_PROTO;
2139	$inline_doc_state = STATE_INLINE_NA;
2140	# Regular text
2141    } elsif (/$doc_content/) {
2142	if ($inline_doc_state == STATE_INLINE_TEXT) {
2143	    $contents .= $1 . "\n";
2144	    # nuke leading blank lines
2145	    if ($contents =~ /^\s*$/) {
2146		$contents = "";
2147	    }
2148	} elsif ($inline_doc_state == STATE_INLINE_NAME) {
2149	    $inline_doc_state = STATE_INLINE_ERROR;
2150	    print STDERR "${file}:$.: warning: ";
2151	    print STDERR "Incorrect use of kernel-doc format: $_";
2152	    ++$warnings;
2153	}
2154    }
2155}
2156
2157
2158sub process_file($) {
2159    my $file;
2160    my $initial_section_counter = $section_counter;
2161    my ($orig_file) = @_;
2162
2163    $file = map_filename($orig_file);
2164
2165    if (!open(IN,"<$file")) {
2166	print STDERR "Error: Cannot open file $file\n";
2167	++$errors;
2168	return;
2169    }
2170
2171    $. = 1;
2172
2173    $section_counter = 0;
2174    while (<IN>) {
2175	while (s/\\\s*$//) {
2176	    $_ .= <IN>;
2177	}
2178	# Replace tabs by spaces
2179        while ($_ =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e) {};
2180	# Hand this line to the appropriate state handler
2181	if ($state == STATE_NORMAL) {
2182	    process_normal();
2183	} elsif ($state == STATE_NAME) {
2184	    process_name($file, $_);
2185	} elsif ($state == STATE_BODY || $state == STATE_BODY_MAYBE) {
2186	    process_body($file, $_);
2187	} elsif ($state == STATE_INLINE) { # scanning for inline parameters
2188	    process_inline($file, $_);
2189	} elsif ($state == STATE_PROTO) {
2190	    process_proto($file, $_);
2191	} elsif ($state == STATE_DOCBLOCK) {
2192	    process_docblock($file, $_);
2193	}
2194    }
2195
2196    # Make sure we got something interesting.
2197    if ($initial_section_counter == $section_counter && $
2198	output_mode ne "none") {
2199	if ($output_selection == OUTPUT_INCLUDE) {
2200	    print STDERR "${file}:1: warning: '$_' not found\n"
2201		for keys %function_table;
2202	}
2203	else {
2204	    print STDERR "${file}:1: warning: no structured comments found\n";
2205	}
2206    }
2207}
2208
2209
2210$kernelversion = get_kernel_version();
2211
2212# generate a sequence of code that will splice in highlighting information
2213# using the s// operator.
2214for (my $k = 0; $k < @highlights; $k++) {
2215    my $pattern = $highlights[$k][0];
2216    my $result = $highlights[$k][1];
2217#   print STDERR "scanning pattern:$pattern, highlight:($result)\n";
2218    $dohighlight .=  "\$contents =~ s:$pattern:$result:gs;\n";
2219}
2220
2221# Read the file that maps relative names to absolute names for
2222# separate source and object directories and for shadow trees.
2223if (open(SOURCE_MAP, "<.tmp_filelist.txt")) {
2224	my ($relname, $absname);
2225	while(<SOURCE_MAP>) {
2226		chop();
2227		($relname, $absname) = (split())[0..1];
2228		$relname =~ s:^/+::;
2229		$source_map{$relname} = $absname;
2230	}
2231	close(SOURCE_MAP);
2232}
2233
2234if ($output_selection == OUTPUT_EXPORTED ||
2235    $output_selection == OUTPUT_INTERNAL) {
2236
2237    push(@export_file_list, @ARGV);
2238
2239    foreach (@export_file_list) {
2240	chomp;
2241	process_export_file($_);
2242    }
2243}
2244
2245foreach (@ARGV) {
2246    chomp;
2247    process_file($_);
2248}
2249if ($verbose && $errors) {
2250  print STDERR "$errors errors\n";
2251}
2252if ($verbose && $warnings) {
2253  print STDERR "$warnings warnings\n";
2254}
2255
2256exit($output_mode eq "none" ? 0 : $errors);
2257