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