xref: /openbmc/qemu/scripts/kernel-doc (revision 53ba2eee)
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	print ".. c:function:: ";
843    }
844    if ($args{'functiontype'} ne "") {
845	$start .= $args{'functiontype'} . " " . $args{'function'} . " (";
846    } else {
847	$start .= $args{'function'} . " (";
848    }
849    print $start;
850
851    my $count = 0;
852    foreach my $parameter (@{$args{'parameterlist'}}) {
853	if ($count ne 0) {
854	    print ", ";
855	}
856	$count++;
857	$type = $args{'parametertypes'}{$parameter};
858
859	if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
860	    # pointer-to-function
861	    print $1 . $parameter . ") (" . $2 . ")";
862	} else {
863	    print $type . " " . $parameter;
864	}
865    }
866    if ($args{'typedef'}) {
867	print ");``\n\n";
868    } else {
869	print ")\n\n";
870	print_lineno($declaration_start_line);
871	$lineprefix = "   ";
872	output_highlight_rst($args{'purpose'});
873	print "\n";
874    }
875
876    print "**Parameters**\n\n";
877    $lineprefix = "  ";
878    foreach $parameter (@{$args{'parameterlist'}}) {
879	my $parameter_name = $parameter;
880	$parameter_name =~ s/\[.*//;
881	$type = $args{'parametertypes'}{$parameter};
882
883	if ($type ne "") {
884	    print "``$type $parameter``\n";
885	} else {
886	    print "``$parameter``\n";
887	}
888
889        print_lineno($parameterdesc_start_lines{$parameter_name});
890
891	if (defined($args{'parameterdescs'}{$parameter_name}) &&
892	    $args{'parameterdescs'}{$parameter_name} ne $undescribed) {
893	    output_highlight_rst($args{'parameterdescs'}{$parameter_name});
894	} else {
895	    print "  *undescribed*\n";
896	}
897	print "\n";
898    }
899
900    $lineprefix = $oldprefix;
901    output_section_rst(@_);
902}
903
904sub output_section_rst(%) {
905    my %args = %{$_[0]};
906    my $section;
907    my $oldprefix = $lineprefix;
908    $lineprefix = "";
909
910    foreach $section (@{$args{'sectionlist'}}) {
911	print "**$section**\n\n";
912        print_lineno($section_start_lines{$section});
913	output_highlight_rst($args{'sections'}{$section});
914	print "\n";
915    }
916    print "\n";
917    $lineprefix = $oldprefix;
918}
919
920sub output_enum_rst(%) {
921    my %args = %{$_[0]};
922    my ($parameter);
923    my $oldprefix = $lineprefix;
924    my $count;
925    my $name = "enum " . $args{'enum'};
926
927    print "\n\n.. c:type:: " . $name . "\n\n";
928    print_lineno($declaration_start_line);
929    $lineprefix = "   ";
930    output_highlight_rst($args{'purpose'});
931    print "\n";
932
933    print "**Constants**\n\n";
934    $lineprefix = "  ";
935    foreach $parameter (@{$args{'parameterlist'}}) {
936	print "``$parameter``\n";
937	if ($args{'parameterdescs'}{$parameter} ne $undescribed) {
938	    output_highlight_rst($args{'parameterdescs'}{$parameter});
939	} else {
940	    print "  *undescribed*\n";
941	}
942	print "\n";
943    }
944
945    $lineprefix = $oldprefix;
946    output_section_rst(@_);
947}
948
949sub output_typedef_rst(%) {
950    my %args = %{$_[0]};
951    my ($parameter);
952    my $oldprefix = $lineprefix;
953    my $name = "typedef " . $args{'typedef'};
954
955    print "\n\n.. c:type:: " . $name . "\n\n";
956    print_lineno($declaration_start_line);
957    $lineprefix = "   ";
958    output_highlight_rst($args{'purpose'});
959    print "\n";
960
961    $lineprefix = $oldprefix;
962    output_section_rst(@_);
963}
964
965sub output_struct_rst(%) {
966    my %args = %{$_[0]};
967    my ($parameter);
968    my $oldprefix = $lineprefix;
969    my $name = $args{'type'} . " " . $args{'struct'};
970
971    # Sphinx 3.0 and up will emit warnings for "c:type:: struct Foo".
972    # It wants to see "c:struct:: Foo" (and will add the word 'struct' in
973    # the rendered output).
974    if ((split(/\./, $sphinx_version))[0] >= 3) {
975        my $sname = $name;
976        $sname =~ s/^struct //;
977        print "\n\n.. c:struct:: " . $sname . "\n\n";
978    } else {
979        print "\n\n.. c:type:: " . $name . "\n\n";
980    }
981    print_lineno($declaration_start_line);
982    $lineprefix = "   ";
983    output_highlight_rst($args{'purpose'});
984    print "\n";
985
986    print "**Definition**\n\n";
987    print "::\n\n";
988    my $declaration = $args{'definition'};
989    $declaration =~ s/\t/  /g;
990    print "  " . $args{'type'} . " " . $args{'struct'} . " {\n$declaration  };\n\n";
991
992    print "**Members**\n\n";
993    $lineprefix = "  ";
994    foreach $parameter (@{$args{'parameterlist'}}) {
995	($parameter =~ /^#/) && next;
996
997	my $parameter_name = $parameter;
998	$parameter_name =~ s/\[.*//;
999
1000	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
1001	$type = $args{'parametertypes'}{$parameter};
1002        print_lineno($parameterdesc_start_lines{$parameter_name});
1003	print "``" . $parameter . "``\n";
1004	output_highlight_rst($args{'parameterdescs'}{$parameter_name});
1005	print "\n";
1006    }
1007    print "\n";
1008
1009    $lineprefix = $oldprefix;
1010    output_section_rst(@_);
1011}
1012
1013## none mode output functions
1014
1015sub output_function_none(%) {
1016}
1017
1018sub output_enum_none(%) {
1019}
1020
1021sub output_typedef_none(%) {
1022}
1023
1024sub output_struct_none(%) {
1025}
1026
1027sub output_blockhead_none(%) {
1028}
1029
1030##
1031# generic output function for all types (function, struct/union, typedef, enum);
1032# calls the generated, variable output_ function name based on
1033# functype and output_mode
1034sub output_declaration {
1035    no strict 'refs';
1036    my $name = shift;
1037    my $functype = shift;
1038    my $func = "output_${functype}_$output_mode";
1039    if (($output_selection == OUTPUT_ALL) ||
1040	(($output_selection == OUTPUT_INCLUDE ||
1041	  $output_selection == OUTPUT_EXPORTED) &&
1042	 defined($function_table{$name})) ||
1043	(($output_selection == OUTPUT_EXCLUDE ||
1044	  $output_selection == OUTPUT_INTERNAL) &&
1045	 !($functype eq "function" && defined($function_table{$name}))))
1046    {
1047	&$func(@_);
1048	$section_counter++;
1049    }
1050}
1051
1052##
1053# generic output function - calls the right one based on current output mode.
1054sub output_blockhead {
1055    no strict 'refs';
1056    my $func = "output_blockhead_" . $output_mode;
1057    &$func(@_);
1058    $section_counter++;
1059}
1060
1061##
1062# takes a declaration (struct, union, enum, typedef) and
1063# invokes the right handler. NOT called for functions.
1064sub dump_declaration($$) {
1065    no strict 'refs';
1066    my ($prototype, $file) = @_;
1067    my $func = "dump_" . $decl_type;
1068    &$func(@_);
1069}
1070
1071sub dump_union($$) {
1072    dump_struct(@_);
1073}
1074
1075sub dump_struct($$) {
1076    my $x = shift;
1077    my $file = shift;
1078
1079    if ($x =~ /(struct|union)\s+(\w+)\s*\{(.*)\}(\s*(__packed|__aligned|__attribute__\s*\(\([a-z0-9,_\s\(\)]*\)\)))*/) {
1080	my $decl_type = $1;
1081	$declaration_name = $2;
1082	my $members = $3;
1083
1084	# ignore members marked private:
1085	$members =~ s/\/\*\s*private:.*?\/\*\s*public:.*?\*\///gosi;
1086	$members =~ s/\/\*\s*private:.*//gosi;
1087	# strip comments:
1088	$members =~ s/\/\*.*?\*\///gos;
1089	# strip attributes
1090	$members =~ s/\s*__attribute__\s*\(\([a-z0-9,_\*\s\(\)]*\)\)//gi;
1091	$members =~ s/\s*__aligned\s*\([^;]*\)//gos;
1092	$members =~ s/\s*__packed\s*//gos;
1093	$members =~ s/\s*CRYPTO_MINALIGN_ATTR//gos;
1094	# replace DECLARE_BITMAP
1095	$members =~ s/DECLARE_BITMAP\s*\(([^,)]+),\s*([^,)]+)\)/unsigned long $1\[BITS_TO_LONGS($2)\]/gos;
1096	# replace DECLARE_HASHTABLE
1097	$members =~ s/DECLARE_HASHTABLE\s*\(([^,)]+),\s*([^,)]+)\)/unsigned long $1\[1 << (($2) - 1)\]/gos;
1098	# replace DECLARE_KFIFO
1099	$members =~ s/DECLARE_KFIFO\s*\(([^,)]+),\s*([^,)]+),\s*([^,)]+)\)/$2 \*$1/gos;
1100	# replace DECLARE_KFIFO_PTR
1101	$members =~ s/DECLARE_KFIFO_PTR\s*\(([^,)]+),\s*([^,)]+)\)/$2 \*$1/gos;
1102
1103	my $declaration = $members;
1104
1105	# Split nested struct/union elements as newer ones
1106	while ($members =~ m/(struct|union)([^\{\};]+)\{([^\{\}]*)\}([^\{\}\;]*)\;/) {
1107		my $newmember;
1108		my $maintype = $1;
1109		my $ids = $4;
1110		my $content = $3;
1111		foreach my $id(split /,/, $ids) {
1112			$newmember .= "$maintype $id; ";
1113
1114			$id =~ s/[:\[].*//;
1115			$id =~ s/^\s*\**(\S+)\s*/$1/;
1116			foreach my $arg (split /;/, $content) {
1117				next if ($arg =~ m/^\s*$/);
1118				if ($arg =~ m/^([^\(]+\(\*?\s*)([\w\.]*)(\s*\).*)/) {
1119					# pointer-to-function
1120					my $type = $1;
1121					my $name = $2;
1122					my $extra = $3;
1123					next if (!$name);
1124					if ($id =~ m/^\s*$/) {
1125						# anonymous struct/union
1126						$newmember .= "$type$name$extra; ";
1127					} else {
1128						$newmember .= "$type$id.$name$extra; ";
1129					}
1130				} else {
1131					my $type;
1132					my $names;
1133					$arg =~ s/^\s+//;
1134					$arg =~ s/\s+$//;
1135					# Handle bitmaps
1136					$arg =~ s/:\s*\d+\s*//g;
1137					# Handle arrays
1138					$arg =~ s/\[.*\]//g;
1139					# The type may have multiple words,
1140					# and multiple IDs can be defined, like:
1141					#	const struct foo, *bar, foobar
1142					# So, we remove spaces when parsing the
1143					# names, in order to match just names
1144					# and commas for the names
1145					$arg =~ s/\s*,\s*/,/g;
1146					if ($arg =~ m/(.*)\s+([\S+,]+)/) {
1147						$type = $1;
1148						$names = $2;
1149					} else {
1150						$newmember .= "$arg; ";
1151						next;
1152					}
1153					foreach my $name (split /,/, $names) {
1154						$name =~ s/^\s*\**(\S+)\s*/$1/;
1155						next if (($name =~ m/^\s*$/));
1156						if ($id =~ m/^\s*$/) {
1157							# anonymous struct/union
1158							$newmember .= "$type $name; ";
1159						} else {
1160							$newmember .= "$type $id.$name; ";
1161						}
1162					}
1163				}
1164			}
1165		}
1166		$members =~ s/(struct|union)([^\{\};]+)\{([^\{\}]*)\}([^\{\}\;]*)\;/$newmember/;
1167	}
1168
1169	# Ignore other nested elements, like enums
1170	$members =~ s/(\{[^\{\}]*\})//g;
1171
1172	create_parameterlist($members, ';', $file, $declaration_name);
1173	check_sections($file, $declaration_name, $decl_type, $sectcheck, $struct_actual);
1174
1175	# Adjust declaration for better display
1176	$declaration =~ s/([\{;])/$1\n/g;
1177	$declaration =~ s/\}\s+;/};/g;
1178	# Better handle inlined enums
1179	do {} while ($declaration =~ s/(enum\s+\{[^\}]+),([^\n])/$1,\n$2/);
1180
1181	my @def_args = split /\n/, $declaration;
1182	my $level = 1;
1183	$declaration = "";
1184	foreach my $clause (@def_args) {
1185		$clause =~ s/^\s+//;
1186		$clause =~ s/\s+$//;
1187		$clause =~ s/\s+/ /;
1188		next if (!$clause);
1189		$level-- if ($clause =~ m/(\})/ && $level > 1);
1190		if (!($clause =~ m/^\s*#/)) {
1191			$declaration .= "\t" x $level;
1192		}
1193		$declaration .= "\t" . $clause . "\n";
1194		$level++ if ($clause =~ m/(\{)/ && !($clause =~m/\}/));
1195	}
1196	output_declaration($declaration_name,
1197			   'struct',
1198			   {'struct' => $declaration_name,
1199			    'module' => $modulename,
1200			    'definition' => $declaration,
1201			    'parameterlist' => \@parameterlist,
1202			    'parameterdescs' => \%parameterdescs,
1203			    'parametertypes' => \%parametertypes,
1204			    'sectionlist' => \@sectionlist,
1205			    'sections' => \%sections,
1206			    'purpose' => $declaration_purpose,
1207			    'type' => $decl_type
1208			   });
1209    }
1210    else {
1211	print STDERR "${file}:$.: error: Cannot parse struct or union!\n";
1212	++$errors;
1213    }
1214}
1215
1216
1217sub show_warnings($$) {
1218	my $functype = shift;
1219	my $name = shift;
1220
1221	return 1 if ($output_selection == OUTPUT_ALL);
1222
1223	if ($output_selection == OUTPUT_EXPORTED) {
1224		if (defined($function_table{$name})) {
1225			return 1;
1226		} else {
1227			return 0;
1228		}
1229	}
1230        if ($output_selection == OUTPUT_INTERNAL) {
1231		if (!($functype eq "function" && defined($function_table{$name}))) {
1232			return 1;
1233		} else {
1234			return 0;
1235		}
1236	}
1237	if ($output_selection == OUTPUT_INCLUDE) {
1238		if (defined($function_table{$name})) {
1239			return 1;
1240		} else {
1241			return 0;
1242		}
1243	}
1244	if ($output_selection == OUTPUT_EXCLUDE) {
1245		if (!defined($function_table{$name})) {
1246			return 1;
1247		} else {
1248			return 0;
1249		}
1250	}
1251	die("Please add the new output type at show_warnings()");
1252}
1253
1254sub dump_enum($$) {
1255    my $x = shift;
1256    my $file = shift;
1257
1258    $x =~ s@/\*.*?\*/@@gos;	# strip comments.
1259    # strip #define macros inside enums
1260    $x =~ s@#\s*((define|ifdef)\s+|endif)[^;]*;@@gos;
1261
1262    if ($x =~ /enum\s+(\w*)\s*\{(.*)\}/) {
1263	$declaration_name = $1;
1264	my $members = $2;
1265	my %_members;
1266
1267	$members =~ s/\s+$//;
1268
1269	foreach my $arg (split ',', $members) {
1270	    $arg =~ s/^\s*(\w+).*/$1/;
1271	    push @parameterlist, $arg;
1272	    if (!$parameterdescs{$arg}) {
1273		$parameterdescs{$arg} = $undescribed;
1274	        if (show_warnings("enum", $declaration_name)) {
1275			print STDERR "${file}:$.: warning: Enum value '$arg' not described in enum '$declaration_name'\n";
1276		}
1277	    }
1278	    $_members{$arg} = 1;
1279	}
1280
1281	while (my ($k, $v) = each %parameterdescs) {
1282	    if (!exists($_members{$k})) {
1283	        if (show_warnings("enum", $declaration_name)) {
1284		     print STDERR "${file}:$.: warning: Excess enum value '$k' description in '$declaration_name'\n";
1285		}
1286	    }
1287        }
1288
1289	output_declaration($declaration_name,
1290			   'enum',
1291			   {'enum' => $declaration_name,
1292			    'module' => $modulename,
1293			    'parameterlist' => \@parameterlist,
1294			    'parameterdescs' => \%parameterdescs,
1295			    'sectionlist' => \@sectionlist,
1296			    'sections' => \%sections,
1297			    'purpose' => $declaration_purpose
1298			   });
1299    }
1300    else {
1301	print STDERR "${file}:$.: error: Cannot parse enum!\n";
1302	++$errors;
1303    }
1304}
1305
1306sub dump_typedef($$) {
1307    my $x = shift;
1308    my $file = shift;
1309
1310    $x =~ s@/\*.*?\*/@@gos;	# strip comments.
1311
1312    # Parse function prototypes
1313    if ($x =~ /typedef\s+(\w+\s*\**)\s*\(\*?\s*(\w\S+)\s*\)\s*\((.*)\);/ ||
1314	$x =~ /typedef\s+(\w+\s*\**)\s*(\w\S+)\s*\s*\((.*)\);/) {
1315
1316	# Function typedefs
1317	$return_type = $1;
1318	$declaration_name = $2;
1319	my $args = $3;
1320
1321	create_parameterlist($args, ',', $file, $declaration_name);
1322
1323	output_declaration($declaration_name,
1324			   'function',
1325			   {'function' => $declaration_name,
1326			    'typedef' => 1,
1327			    'module' => $modulename,
1328			    'functiontype' => $return_type,
1329			    'parameterlist' => \@parameterlist,
1330			    'parameterdescs' => \%parameterdescs,
1331			    'parametertypes' => \%parametertypes,
1332			    'sectionlist' => \@sectionlist,
1333			    'sections' => \%sections,
1334			    'purpose' => $declaration_purpose
1335			   });
1336	return;
1337    }
1338
1339    while (($x =~ /\(*.\)\s*;$/) || ($x =~ /\[*.\]\s*;$/)) {
1340	$x =~ s/\(*.\)\s*;$/;/;
1341	$x =~ s/\[*.\]\s*;$/;/;
1342    }
1343
1344    if ($x =~ /typedef.*\s+(\w+)\s*;/) {
1345	$declaration_name = $1;
1346
1347	output_declaration($declaration_name,
1348			   'typedef',
1349			   {'typedef' => $declaration_name,
1350			    'module' => $modulename,
1351			    'sectionlist' => \@sectionlist,
1352			    'sections' => \%sections,
1353			    'purpose' => $declaration_purpose
1354			   });
1355    }
1356    else {
1357	print STDERR "${file}:$.: error: Cannot parse typedef!\n";
1358	++$errors;
1359    }
1360}
1361
1362sub save_struct_actual($) {
1363    my $actual = shift;
1364
1365    # strip all spaces from the actual param so that it looks like one string item
1366    $actual =~ s/\s*//g;
1367    $struct_actual = $struct_actual . $actual . " ";
1368}
1369
1370sub create_parameterlist($$$$) {
1371    my $args = shift;
1372    my $splitter = shift;
1373    my $file = shift;
1374    my $declaration_name = shift;
1375    my $type;
1376    my $param;
1377
1378    # temporarily replace commas inside function pointer definition
1379    while ($args =~ /(\([^\),]+),/) {
1380	$args =~ s/(\([^\),]+),/$1#/g;
1381    }
1382
1383    foreach my $arg (split($splitter, $args)) {
1384	# strip comments
1385	$arg =~ s/\/\*.*\*\///;
1386	# strip leading/trailing spaces
1387	$arg =~ s/^\s*//;
1388	$arg =~ s/\s*$//;
1389	$arg =~ s/\s+/ /;
1390
1391	if ($arg =~ /^#/) {
1392	    # Treat preprocessor directive as a typeless variable just to fill
1393	    # corresponding data structures "correctly". Catch it later in
1394	    # output_* subs.
1395	    push_parameter($arg, "", $file);
1396	} elsif ($arg =~ m/\(.+\)\s*\(/) {
1397	    # pointer-to-function
1398	    $arg =~ tr/#/,/;
1399	    $arg =~ m/[^\(]+\(\*?\s*([\w\.]*)\s*\)/;
1400	    $param = $1;
1401	    $type = $arg;
1402	    $type =~ s/([^\(]+\(\*?)\s*$param/$1/;
1403	    save_struct_actual($param);
1404	    push_parameter($param, $type, $file, $declaration_name);
1405	} elsif ($arg) {
1406	    $arg =~ s/\s*:\s*/:/g;
1407	    $arg =~ s/\s*\[/\[/g;
1408
1409	    my @args = split('\s*,\s*', $arg);
1410	    if ($args[0] =~ m/\*/) {
1411		$args[0] =~ s/(\*+)\s*/ $1/;
1412	    }
1413
1414	    my @first_arg;
1415	    if ($args[0] =~ /^(.*\s+)(.*?\[.*\].*)$/) {
1416		    shift @args;
1417		    push(@first_arg, split('\s+', $1));
1418		    push(@first_arg, $2);
1419	    } else {
1420		    @first_arg = split('\s+', shift @args);
1421	    }
1422
1423	    unshift(@args, pop @first_arg);
1424	    $type = join " ", @first_arg;
1425
1426	    foreach $param (@args) {
1427		if ($param =~ m/^(\*+)\s*(.*)/) {
1428		    save_struct_actual($2);
1429		    push_parameter($2, "$type $1", $file, $declaration_name);
1430		}
1431		elsif ($param =~ m/(.*?):(\d+)/) {
1432		    if ($type ne "") { # skip unnamed bit-fields
1433			save_struct_actual($1);
1434			push_parameter($1, "$type:$2", $file, $declaration_name)
1435		    }
1436		}
1437		else {
1438		    save_struct_actual($param);
1439		    push_parameter($param, $type, $file, $declaration_name);
1440		}
1441	    }
1442	}
1443    }
1444}
1445
1446sub push_parameter($$$$) {
1447	my $param = shift;
1448	my $type = shift;
1449	my $file = shift;
1450	my $declaration_name = shift;
1451
1452	if (($anon_struct_union == 1) && ($type eq "") &&
1453	    ($param eq "}")) {
1454		return;		# ignore the ending }; from anon. struct/union
1455	}
1456
1457	$anon_struct_union = 0;
1458	$param =~ s/[\[\)].*//;
1459
1460	if ($type eq "" && $param =~ /\.\.\.$/)
1461	{
1462	    if (!$param =~ /\w\.\.\.$/) {
1463	      # handles unnamed variable parameters
1464	      $param = "...";
1465	    }
1466	    if (!defined $parameterdescs{$param} || $parameterdescs{$param} eq "") {
1467		$parameterdescs{$param} = "variable arguments";
1468	    }
1469	}
1470	elsif ($type eq "" && ($param eq "" or $param eq "void"))
1471	{
1472	    $param="void";
1473	    $parameterdescs{void} = "no arguments";
1474	}
1475	elsif ($type eq "" && ($param eq "struct" or $param eq "union"))
1476	# handle unnamed (anonymous) union or struct:
1477	{
1478		$type = $param;
1479		$param = "{unnamed_" . $param . "}";
1480		$parameterdescs{$param} = "anonymous\n";
1481		$anon_struct_union = 1;
1482	}
1483
1484	# warn if parameter has no description
1485	# (but ignore ones starting with # as these are not parameters
1486	# but inline preprocessor statements);
1487	# Note: It will also ignore void params and unnamed structs/unions
1488	if (!defined $parameterdescs{$param} && $param !~ /^#/) {
1489		$parameterdescs{$param} = $undescribed;
1490
1491	        if (show_warnings($type, $declaration_name) && $param !~ /\./) {
1492			print STDERR
1493			      "${file}:$.: warning: Function parameter or member '$param' not described in '$declaration_name'\n";
1494			++$warnings;
1495		}
1496	}
1497
1498	# strip spaces from $param so that it is one continuous string
1499	# on @parameterlist;
1500	# this fixes a problem where check_sections() cannot find
1501	# a parameter like "addr[6 + 2]" because it actually appears
1502	# as "addr[6", "+", "2]" on the parameter list;
1503	# but it's better to maintain the param string unchanged for output,
1504	# so just weaken the string compare in check_sections() to ignore
1505	# "[blah" in a parameter string;
1506	###$param =~ s/\s*//g;
1507	push @parameterlist, $param;
1508	$type =~ s/\s\s+/ /g;
1509	$parametertypes{$param} = $type;
1510}
1511
1512sub check_sections($$$$$) {
1513	my ($file, $decl_name, $decl_type, $sectcheck, $prmscheck) = @_;
1514	my @sects = split ' ', $sectcheck;
1515	my @prms = split ' ', $prmscheck;
1516	my $err;
1517	my ($px, $sx);
1518	my $prm_clean;		# strip trailing "[array size]" and/or beginning "*"
1519
1520	foreach $sx (0 .. $#sects) {
1521		$err = 1;
1522		foreach $px (0 .. $#prms) {
1523			$prm_clean = $prms[$px];
1524			$prm_clean =~ s/\[.*\]//;
1525			$prm_clean =~ s/__attribute__\s*\(\([a-z,_\*\s\(\)]*\)\)//i;
1526			# ignore array size in a parameter string;
1527			# however, the original param string may contain
1528			# spaces, e.g.:  addr[6 + 2]
1529			# and this appears in @prms as "addr[6" since the
1530			# parameter list is split at spaces;
1531			# hence just ignore "[..." for the sections check;
1532			$prm_clean =~ s/\[.*//;
1533
1534			##$prm_clean =~ s/^\**//;
1535			if ($prm_clean eq $sects[$sx]) {
1536				$err = 0;
1537				last;
1538			}
1539		}
1540		if ($err) {
1541			if ($decl_type eq "function") {
1542				print STDERR "${file}:$.: warning: " .
1543					"Excess function parameter " .
1544					"'$sects[$sx]' " .
1545					"description in '$decl_name'\n";
1546				++$warnings;
1547			}
1548		}
1549	}
1550}
1551
1552##
1553# Checks the section describing the return value of a function.
1554sub check_return_section {
1555        my $file = shift;
1556        my $declaration_name = shift;
1557        my $return_type = shift;
1558
1559        # Ignore an empty return type (It's a macro)
1560        # Ignore functions with a "void" return type. (But don't ignore "void *")
1561        if (($return_type eq "") || ($return_type =~ /void\s*\w*\s*$/)) {
1562                return;
1563        }
1564
1565        if (!defined($sections{$section_return}) ||
1566            $sections{$section_return} eq "") {
1567                print STDERR "${file}:$.: warning: " .
1568                        "No description found for return value of " .
1569                        "'$declaration_name'\n";
1570                ++$warnings;
1571        }
1572}
1573
1574##
1575# takes a function prototype and the name of the current file being
1576# processed and spits out all the details stored in the global
1577# arrays/hashes.
1578sub dump_function($$) {
1579    my $prototype = shift;
1580    my $file = shift;
1581    my $noret = 0;
1582
1583    $prototype =~ s/^static +//;
1584    $prototype =~ s/^extern +//;
1585    $prototype =~ s/^asmlinkage +//;
1586    $prototype =~ s/^inline +//;
1587    $prototype =~ s/^__inline__ +//;
1588    $prototype =~ s/^__inline +//;
1589    $prototype =~ s/^__always_inline +//;
1590    $prototype =~ s/^noinline +//;
1591    $prototype =~ s/__init +//;
1592    $prototype =~ s/__init_or_module +//;
1593    $prototype =~ s/__meminit +//;
1594    $prototype =~ s/__must_check +//;
1595    $prototype =~ s/__weak +//;
1596    $prototype =~ s/__sched +//;
1597    $prototype =~ s/__printf\s*\(\s*\d*\s*,\s*\d*\s*\) +//;
1598    my $define = $prototype =~ s/^#\s*define\s+//; #ak added
1599    $prototype =~ s/__attribute__\s*\(\(
1600            (?:
1601                 [\w\s]++          # attribute name
1602                 (?:\([^)]*+\))?   # attribute arguments
1603                 \s*+,?            # optional comma at the end
1604            )+
1605          \)\)\s+//x;
1606
1607    # Yes, this truly is vile.  We are looking for:
1608    # 1. Return type (may be nothing if we're looking at a macro)
1609    # 2. Function name
1610    # 3. Function parameters.
1611    #
1612    # All the while we have to watch out for function pointer parameters
1613    # (which IIRC is what the two sections are for), C types (these
1614    # regexps don't even start to express all the possibilities), and
1615    # so on.
1616    #
1617    # If you mess with these regexps, it's a good idea to check that
1618    # the following functions' documentation still comes out right:
1619    # - parport_register_device (function pointer parameters)
1620    # - qatomic_set (macro)
1621    # - pci_match_device, __copy_to_user (long return type)
1622
1623    if ($define && $prototype =~ m/^()([a-zA-Z0-9_~:]+)\s+/) {
1624        # This is an object-like macro, it has no return type and no parameter
1625        # list.
1626        # Function-like macros are not allowed to have spaces between
1627        # declaration_name and opening parenthesis (notice the \s+).
1628        $return_type = $1;
1629        $declaration_name = $2;
1630        $noret = 1;
1631    } elsif ($prototype =~ m/^()([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1632	$prototype =~ m/^(\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1633	$prototype =~ m/^(\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1634	$prototype =~ m/^(\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1635	$prototype =~ m/^(\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1636	$prototype =~ m/^(\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1637	$prototype =~ m/^(\w+\s+\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1638	$prototype =~ m/^()([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1639	$prototype =~ m/^(\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1640	$prototype =~ m/^(\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1641	$prototype =~ m/^(\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1642	$prototype =~ m/^(\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1643	$prototype =~ m/^(\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1644	$prototype =~ m/^(\w+\s+\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1645	$prototype =~ m/^(\w+\s+\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1646	$prototype =~ m/^(\w+\s+\w+\s+\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1647	$prototype =~ m/^(\w+\s+\w+\s*\*+\s*\w+\s*\*+\s*)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/)  {
1648	$return_type = $1;
1649	$declaration_name = $2;
1650	my $args = $3;
1651
1652	create_parameterlist($args, ',', $file, $declaration_name);
1653    } else {
1654	print STDERR "${file}:$.: warning: cannot understand function prototype: '$prototype'\n";
1655	return;
1656    }
1657
1658	my $prms = join " ", @parameterlist;
1659	check_sections($file, $declaration_name, "function", $sectcheck, $prms);
1660
1661        # This check emits a lot of warnings at the moment, because many
1662        # functions don't have a 'Return' doc section. So until the number
1663        # of warnings goes sufficiently down, the check is only performed in
1664        # verbose mode.
1665        # TODO: always perform the check.
1666        if ($verbose && !$noret) {
1667                check_return_section($file, $declaration_name, $return_type);
1668        }
1669
1670    output_declaration($declaration_name,
1671		       'function',
1672		       {'function' => $declaration_name,
1673			'module' => $modulename,
1674			'functiontype' => $return_type,
1675			'parameterlist' => \@parameterlist,
1676			'parameterdescs' => \%parameterdescs,
1677			'parametertypes' => \%parametertypes,
1678			'sectionlist' => \@sectionlist,
1679			'sections' => \%sections,
1680			'purpose' => $declaration_purpose
1681		       });
1682}
1683
1684sub reset_state {
1685    $function = "";
1686    %parameterdescs = ();
1687    %parametertypes = ();
1688    @parameterlist = ();
1689    %sections = ();
1690    @sectionlist = ();
1691    $sectcheck = "";
1692    $struct_actual = "";
1693    $prototype = "";
1694
1695    $state = STATE_NORMAL;
1696    $inline_doc_state = STATE_INLINE_NA;
1697}
1698
1699sub tracepoint_munge($) {
1700	my $file = shift;
1701	my $tracepointname = 0;
1702	my $tracepointargs = 0;
1703
1704	if ($prototype =~ m/TRACE_EVENT\((.*?),/) {
1705		$tracepointname = $1;
1706	}
1707	if ($prototype =~ m/DEFINE_SINGLE_EVENT\((.*?),/) {
1708		$tracepointname = $1;
1709	}
1710	if ($prototype =~ m/DEFINE_EVENT\((.*?),(.*?),/) {
1711		$tracepointname = $2;
1712	}
1713	$tracepointname =~ s/^\s+//; #strip leading whitespace
1714	if ($prototype =~ m/TP_PROTO\((.*?)\)/) {
1715		$tracepointargs = $1;
1716	}
1717	if (($tracepointname eq 0) || ($tracepointargs eq 0)) {
1718		print STDERR "${file}:$.: warning: Unrecognized tracepoint format: \n".
1719			     "$prototype\n";
1720	} else {
1721		$prototype = "static inline void trace_$tracepointname($tracepointargs)";
1722	}
1723}
1724
1725sub syscall_munge() {
1726	my $void = 0;
1727
1728	$prototype =~ s@[\r\n]+@ @gos; # strip newlines/CR's
1729##	if ($prototype =~ m/SYSCALL_DEFINE0\s*\(\s*(a-zA-Z0-9_)*\s*\)/) {
1730	if ($prototype =~ m/SYSCALL_DEFINE0/) {
1731		$void = 1;
1732##		$prototype = "long sys_$1(void)";
1733	}
1734
1735	$prototype =~ s/SYSCALL_DEFINE.*\(/long sys_/; # fix return type & func name
1736	if ($prototype =~ m/long (sys_.*?),/) {
1737		$prototype =~ s/,/\(/;
1738	} elsif ($void) {
1739		$prototype =~ s/\)/\(void\)/;
1740	}
1741
1742	# now delete all of the odd-number commas in $prototype
1743	# so that arg types & arg names don't have a comma between them
1744	my $count = 0;
1745	my $len = length($prototype);
1746	if ($void) {
1747		$len = 0;	# skip the for-loop
1748	}
1749	for (my $ix = 0; $ix < $len; $ix++) {
1750		if (substr($prototype, $ix, 1) eq ',') {
1751			$count++;
1752			if ($count % 2 == 1) {
1753				substr($prototype, $ix, 1) = ' ';
1754			}
1755		}
1756	}
1757}
1758
1759sub process_proto_function($$) {
1760    my $x = shift;
1761    my $file = shift;
1762
1763    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line
1764
1765    if ($x =~ m#\s*/\*\s+MACDOC\s*#io || ($x =~ /^#/ && $x !~ /^#\s*define/)) {
1766	# do nothing
1767    }
1768    elsif ($x =~ /([^\{]*)/) {
1769	$prototype .= $1;
1770    }
1771
1772    if (($x =~ /\{/) || ($x =~ /\#\s*define/) || ($x =~ /;/)) {
1773	$prototype =~ s@/\*.*?\*/@@gos;	# strip comments.
1774	$prototype =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
1775	$prototype =~ s@^\s+@@gos; # strip leading spaces
1776	if ($prototype =~ /SYSCALL_DEFINE/) {
1777		syscall_munge();
1778	}
1779	if ($prototype =~ /TRACE_EVENT/ || $prototype =~ /DEFINE_EVENT/ ||
1780	    $prototype =~ /DEFINE_SINGLE_EVENT/)
1781	{
1782		tracepoint_munge($file);
1783	}
1784	dump_function($prototype, $file);
1785	reset_state();
1786    }
1787}
1788
1789sub process_proto_type($$) {
1790    my $x = shift;
1791    my $file = shift;
1792
1793    $x =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
1794    $x =~ s@^\s+@@gos; # strip leading spaces
1795    $x =~ s@\s+$@@gos; # strip trailing spaces
1796    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line
1797
1798    if ($x =~ /^#/) {
1799	# To distinguish preprocessor directive from regular declaration later.
1800	$x .= ";";
1801    }
1802
1803    while (1) {
1804	if ( $x =~ /([^\{\};]*)([\{\};])(.*)/ ) {
1805            if( length $prototype ) {
1806                $prototype .= " "
1807            }
1808	    $prototype .= $1 . $2;
1809	    ($2 eq '{') && $brcount++;
1810	    ($2 eq '}') && $brcount--;
1811	    if (($2 eq ';') && ($brcount == 0)) {
1812		dump_declaration($prototype, $file);
1813		reset_state();
1814		last;
1815	    }
1816	    $x = $3;
1817	} else {
1818	    $prototype .= $x;
1819	    last;
1820	}
1821    }
1822}
1823
1824
1825sub map_filename($) {
1826    my $file;
1827    my ($orig_file) = @_;
1828
1829    if (defined($ENV{'SRCTREE'})) {
1830	$file = "$ENV{'SRCTREE'}" . "/" . $orig_file;
1831    } else {
1832	$file = $orig_file;
1833    }
1834
1835    if (defined($source_map{$file})) {
1836	$file = $source_map{$file};
1837    }
1838
1839    return $file;
1840}
1841
1842sub process_export_file($) {
1843    my ($orig_file) = @_;
1844    my $file = map_filename($orig_file);
1845
1846    if (!open(IN,"<$file")) {
1847	print STDERR "Error: Cannot open file $file\n";
1848	++$errors;
1849	return;
1850    }
1851
1852    while (<IN>) {
1853	if (/$export_symbol/) {
1854	    $function_table{$2} = 1;
1855	}
1856    }
1857
1858    close(IN);
1859}
1860
1861#
1862# Parsers for the various processing states.
1863#
1864# STATE_NORMAL: looking for the /** to begin everything.
1865#
1866sub process_normal() {
1867    if (/$doc_start/o) {
1868	$state = STATE_NAME;	# next line is always the function name
1869	$in_doc_sect = 0;
1870	$declaration_start_line = $. + 1;
1871    }
1872}
1873
1874#
1875# STATE_NAME: Looking for the "name - description" line
1876#
1877sub process_name($$) {
1878    my $file = shift;
1879    my $identifier;
1880    my $descr;
1881
1882    if (/$doc_block/o) {
1883	$state = STATE_DOCBLOCK;
1884	$contents = "";
1885	$new_start_line = $. + 1;
1886
1887	if ( $1 eq "" ) {
1888	    $section = $section_intro;
1889	} else {
1890	    $section = $1;
1891	}
1892    }
1893    elsif (/$doc_decl/o) {
1894	$identifier = $1;
1895	if (/\s*([\w\s]+?)(\s*-|:)/) {
1896	    $identifier = $1;
1897	}
1898
1899	$state = STATE_BODY;
1900	# if there's no @param blocks need to set up default section
1901	# here
1902	$contents = "";
1903	$section = $section_default;
1904	$new_start_line = $. + 1;
1905	if (/[-:](.*)/) {
1906	    # strip leading/trailing/multiple spaces
1907	    $descr= $1;
1908	    $descr =~ s/^\s*//;
1909	    $descr =~ s/\s*$//;
1910	    $descr =~ s/\s+/ /g;
1911	    $declaration_purpose = $descr;
1912	    $state = STATE_BODY_MAYBE;
1913	} else {
1914	    $declaration_purpose = "";
1915	}
1916
1917	if (($declaration_purpose eq "") && $verbose) {
1918	    print STDERR "${file}:$.: warning: missing initial short description on line:\n";
1919	    print STDERR $_;
1920	    ++$warnings;
1921	}
1922
1923	if ($identifier =~ m/^struct\b/) {
1924	    $decl_type = 'struct';
1925	} elsif ($identifier =~ m/^union\b/) {
1926	    $decl_type = 'union';
1927	} elsif ($identifier =~ m/^enum\b/) {
1928	    $decl_type = 'enum';
1929	} elsif ($identifier =~ m/^typedef\b/) {
1930	    $decl_type = 'typedef';
1931	} else {
1932	    $decl_type = 'function';
1933	}
1934
1935	if ($verbose) {
1936	    print STDERR "${file}:$.: info: Scanning doc for $identifier\n";
1937	}
1938    } else {
1939	print STDERR "${file}:$.: warning: Cannot understand $_ on line $.",
1940	    " - I thought it was a doc line\n";
1941	++$warnings;
1942	$state = STATE_NORMAL;
1943    }
1944}
1945
1946
1947#
1948# STATE_BODY and STATE_BODY_MAYBE: the bulk of a kerneldoc comment.
1949#
1950sub process_body($$) {
1951    my $file = shift;
1952
1953    if (/$doc_sect/i) { # case insensitive for supported section names
1954	$newsection = $1;
1955	$newcontents = $2;
1956
1957	# map the supported section names to the canonical names
1958	if ($newsection =~ m/^description$/i) {
1959	    $newsection = $section_default;
1960	} elsif ($newsection =~ m/^context$/i) {
1961	    $newsection = $section_context;
1962	} elsif ($newsection =~ m/^returns?$/i) {
1963	    $newsection = $section_return;
1964	} elsif ($newsection =~ m/^\@return$/) {
1965	    # special: @return is a section, not a param description
1966	    $newsection = $section_return;
1967	}
1968
1969	if (($contents ne "") && ($contents ne "\n")) {
1970	    if (!$in_doc_sect && $verbose) {
1971		print STDERR "${file}:$.: warning: contents before sections\n";
1972		++$warnings;
1973	    }
1974	    dump_section($file, $section, $contents);
1975	    $section = $section_default;
1976	}
1977
1978	$in_doc_sect = 1;
1979	$state = STATE_BODY;
1980	$contents = $newcontents;
1981	$new_start_line = $.;
1982	while (substr($contents, 0, 1) eq " ") {
1983	    $contents = substr($contents, 1);
1984	}
1985	if ($contents ne "") {
1986	    $contents .= "\n";
1987	}
1988	$section = $newsection;
1989	$leading_space = undef;
1990    } elsif (/$doc_end/) {
1991	if (($contents ne "") && ($contents ne "\n")) {
1992	    dump_section($file, $section, $contents);
1993	    $section = $section_default;
1994	    $contents = "";
1995	}
1996	# look for doc_com + <text> + doc_end:
1997	if ($_ =~ m'\s*\*\s*[a-zA-Z_0-9:\.]+\*/') {
1998	    print STDERR "${file}:$.: warning: suspicious ending line: $_";
1999	    ++$warnings;
2000	}
2001
2002	$prototype = "";
2003	$state = STATE_PROTO;
2004	$brcount = 0;
2005    } elsif (/$doc_content/) {
2006	# miguel-style comment kludge, look for blank lines after
2007	# @parameter line to signify start of description
2008	if ($1 eq "") {
2009	    if ($section =~ m/^@/ || $section eq $section_context) {
2010		dump_section($file, $section, $contents);
2011		$section = $section_default;
2012		$contents = "";
2013		$new_start_line = $.;
2014	    } else {
2015		$contents .= "\n";
2016	    }
2017	    $state = STATE_BODY;
2018	} elsif ($state == STATE_BODY_MAYBE) {
2019	    # Continued declaration purpose
2020	    chomp($declaration_purpose);
2021	    $declaration_purpose .= " " . $1;
2022	    $declaration_purpose =~ s/\s+/ /g;
2023	} else {
2024	    my $cont = $1;
2025	    if ($section =~ m/^@/ || $section eq $section_context) {
2026		if (!defined $leading_space) {
2027		    if ($cont =~ m/^(\s+)/) {
2028			$leading_space = $1;
2029		    } else {
2030			$leading_space = "";
2031		    }
2032		}
2033		$cont =~ s/^$leading_space//;
2034	    }
2035	    $contents .= $cont . "\n";
2036	}
2037    } else {
2038	# i dont know - bad line?  ignore.
2039	print STDERR "${file}:$.: warning: bad line: $_";
2040	++$warnings;
2041    }
2042}
2043
2044
2045#
2046# STATE_PROTO: reading a function/whatever prototype.
2047#
2048sub process_proto($$) {
2049    my $file = shift;
2050
2051    if (/$doc_inline_oneline/) {
2052	$section = $1;
2053	$contents = $2;
2054	if ($contents ne "") {
2055	    $contents .= "\n";
2056	    dump_section($file, $section, $contents);
2057	    $section = $section_default;
2058	    $contents = "";
2059	}
2060    } elsif (/$doc_inline_start/) {
2061	$state = STATE_INLINE;
2062	$inline_doc_state = STATE_INLINE_NAME;
2063    } elsif ($decl_type eq 'function') {
2064	process_proto_function($_, $file);
2065    } else {
2066	process_proto_type($_, $file);
2067    }
2068}
2069
2070#
2071# STATE_DOCBLOCK: within a DOC: block.
2072#
2073sub process_docblock($$) {
2074    my $file = shift;
2075
2076    if (/$doc_end/) {
2077	dump_doc_section($file, $section, $contents);
2078	$section = $section_default;
2079	$contents = "";
2080	$function = "";
2081	%parameterdescs = ();
2082	%parametertypes = ();
2083	@parameterlist = ();
2084	%sections = ();
2085	@sectionlist = ();
2086	$prototype = "";
2087	$state = STATE_NORMAL;
2088    } elsif (/$doc_content/) {
2089	if ( $1 eq "" )	{
2090	    $contents .= $blankline;
2091	} else {
2092	    $contents .= $1 . "\n";
2093	}
2094    }
2095}
2096
2097#
2098# STATE_INLINE: docbook comments within a prototype.
2099#
2100sub process_inline($$) {
2101    my $file = shift;
2102
2103    # First line (state 1) needs to be a @parameter
2104    if ($inline_doc_state == STATE_INLINE_NAME && /$doc_inline_sect/o) {
2105	$section = $1;
2106	$contents = $2;
2107	$new_start_line = $.;
2108	if ($contents ne "") {
2109	    while (substr($contents, 0, 1) eq " ") {
2110		$contents = substr($contents, 1);
2111	    }
2112	    $contents .= "\n";
2113	}
2114	$inline_doc_state = STATE_INLINE_TEXT;
2115	# Documentation block end */
2116    } elsif (/$doc_inline_end/) {
2117	if (($contents ne "") && ($contents ne "\n")) {
2118	    dump_section($file, $section, $contents);
2119	    $section = $section_default;
2120	    $contents = "";
2121	}
2122	$state = STATE_PROTO;
2123	$inline_doc_state = STATE_INLINE_NA;
2124	# Regular text
2125    } elsif (/$doc_content/) {
2126	if ($inline_doc_state == STATE_INLINE_TEXT) {
2127	    $contents .= $1 . "\n";
2128	    # nuke leading blank lines
2129	    if ($contents =~ /^\s*$/) {
2130		$contents = "";
2131	    }
2132	} elsif ($inline_doc_state == STATE_INLINE_NAME) {
2133	    $inline_doc_state = STATE_INLINE_ERROR;
2134	    print STDERR "${file}:$.: warning: ";
2135	    print STDERR "Incorrect use of kernel-doc format: $_";
2136	    ++$warnings;
2137	}
2138    }
2139}
2140
2141
2142sub process_file($) {
2143    my $file;
2144    my $initial_section_counter = $section_counter;
2145    my ($orig_file) = @_;
2146
2147    $file = map_filename($orig_file);
2148
2149    if (!open(IN,"<$file")) {
2150	print STDERR "Error: Cannot open file $file\n";
2151	++$errors;
2152	return;
2153    }
2154
2155    $. = 1;
2156
2157    $section_counter = 0;
2158    while (<IN>) {
2159	while (s/\\\s*$//) {
2160	    $_ .= <IN>;
2161	}
2162	# Replace tabs by spaces
2163        while ($_ =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e) {};
2164	# Hand this line to the appropriate state handler
2165	if ($state == STATE_NORMAL) {
2166	    process_normal();
2167	} elsif ($state == STATE_NAME) {
2168	    process_name($file, $_);
2169	} elsif ($state == STATE_BODY || $state == STATE_BODY_MAYBE) {
2170	    process_body($file, $_);
2171	} elsif ($state == STATE_INLINE) { # scanning for inline parameters
2172	    process_inline($file, $_);
2173	} elsif ($state == STATE_PROTO) {
2174	    process_proto($file, $_);
2175	} elsif ($state == STATE_DOCBLOCK) {
2176	    process_docblock($file, $_);
2177	}
2178    }
2179
2180    # Make sure we got something interesting.
2181    if ($initial_section_counter == $section_counter && $
2182	output_mode ne "none") {
2183	if ($output_selection == OUTPUT_INCLUDE) {
2184	    print STDERR "${file}:1: warning: '$_' not found\n"
2185		for keys %function_table;
2186	}
2187	else {
2188	    print STDERR "${file}:1: warning: no structured comments found\n";
2189	}
2190    }
2191}
2192
2193
2194$kernelversion = get_kernel_version();
2195
2196# generate a sequence of code that will splice in highlighting information
2197# using the s// operator.
2198for (my $k = 0; $k < @highlights; $k++) {
2199    my $pattern = $highlights[$k][0];
2200    my $result = $highlights[$k][1];
2201#   print STDERR "scanning pattern:$pattern, highlight:($result)\n";
2202    $dohighlight .=  "\$contents =~ s:$pattern:$result:gs;\n";
2203}
2204
2205# Read the file that maps relative names to absolute names for
2206# separate source and object directories and for shadow trees.
2207if (open(SOURCE_MAP, "<.tmp_filelist.txt")) {
2208	my ($relname, $absname);
2209	while(<SOURCE_MAP>) {
2210		chop();
2211		($relname, $absname) = (split())[0..1];
2212		$relname =~ s:^/+::;
2213		$source_map{$relname} = $absname;
2214	}
2215	close(SOURCE_MAP);
2216}
2217
2218if ($output_selection == OUTPUT_EXPORTED ||
2219    $output_selection == OUTPUT_INTERNAL) {
2220
2221    push(@export_file_list, @ARGV);
2222
2223    foreach (@export_file_list) {
2224	chomp;
2225	process_export_file($_);
2226    }
2227}
2228
2229foreach (@ARGV) {
2230    chomp;
2231    process_file($_);
2232}
2233if ($verbose && $errors) {
2234  print STDERR "$errors errors\n";
2235}
2236if ($verbose && $warnings) {
2237  print STDERR "$warnings warnings\n";
2238}
2239
2240exit($output_mode eq "none" ? 0 : $errors);
2241