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