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