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