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