xref: /linux/scripts/kernel-doc (revision 03699f271de1f4df6369cd379506539cd7d590d3)
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    print "**Parameters**\n\n";
870    $lineprefix = "  ";
871    foreach $parameter (@{$args{'parameterlist'}}) {
872	my $parameter_name = $parameter;
873	$parameter_name =~ s/\[.*//;
874	$type = $args{'parametertypes'}{$parameter};
875
876	if ($type ne "") {
877	    print "``$type``\n";
878	} else {
879	    print "``$parameter``\n";
880	}
881
882        print_lineno($parameterdesc_start_lines{$parameter_name});
883
884	if (defined($args{'parameterdescs'}{$parameter_name}) &&
885	    $args{'parameterdescs'}{$parameter_name} ne $undescribed) {
886	    output_highlight_rst($args{'parameterdescs'}{$parameter_name});
887	} else {
888	    print "  *undescribed*\n";
889	}
890	print "\n";
891    }
892
893    $lineprefix = $oldprefix;
894    output_section_rst(@_);
895}
896
897sub output_section_rst(%) {
898    my %args = %{$_[0]};
899    my $section;
900    my $oldprefix = $lineprefix;
901    $lineprefix = "";
902
903    foreach $section (@{$args{'sectionlist'}}) {
904	print "**$section**\n\n";
905        print_lineno($section_start_lines{$section});
906	output_highlight_rst($args{'sections'}{$section});
907	print "\n";
908    }
909    print "\n";
910    $lineprefix = $oldprefix;
911}
912
913sub output_enum_rst(%) {
914    my %args = %{$_[0]};
915    my ($parameter);
916    my $oldprefix = $lineprefix;
917    my $count;
918
919    if ($sphinx_major < 3) {
920	my $name = "enum " . $args{'enum'};
921	print "\n\n.. c:type:: " . $name . "\n\n";
922    } else {
923	my $name = $args{'enum'};
924	print "\n\n.. c:enum:: " . $name . "\n\n";
925    }
926    print_lineno($declaration_start_line);
927    $lineprefix = "   ";
928    output_highlight_rst($args{'purpose'});
929    print "\n";
930
931    print "**Constants**\n\n";
932    $lineprefix = "  ";
933    foreach $parameter (@{$args{'parameterlist'}}) {
934	print "``$parameter``\n";
935	if ($args{'parameterdescs'}{$parameter} ne $undescribed) {
936	    output_highlight_rst($args{'parameterdescs'}{$parameter});
937	} else {
938	    print "  *undescribed*\n";
939	}
940	print "\n";
941    }
942
943    $lineprefix = $oldprefix;
944    output_section_rst(@_);
945}
946
947sub output_typedef_rst(%) {
948    my %args = %{$_[0]};
949    my ($parameter);
950    my $oldprefix = $lineprefix;
951    my $name;
952
953    if ($sphinx_major < 3) {
954	$name = "typedef " . $args{'typedef'};
955    } else {
956	$name = $args{'typedef'};
957    }
958    print "\n\n.. c:type:: " . $name . "\n\n";
959    print_lineno($declaration_start_line);
960    $lineprefix = "   ";
961    output_highlight_rst($args{'purpose'});
962    print "\n";
963
964    $lineprefix = $oldprefix;
965    output_section_rst(@_);
966}
967
968sub output_struct_rst(%) {
969    my %args = %{$_[0]};
970    my ($parameter);
971    my $oldprefix = $lineprefix;
972
973    if ($sphinx_major < 3) {
974	my $name = $args{'type'} . " " . $args{'struct'};
975	print "\n\n.. c:type:: " . $name . "\n\n";
976    } else {
977	my $name = $args{'struct'};
978	if ($args{'type'} eq 'union') {
979	    print "\n\n.. c:union:: " . $name . "\n\n";
980	} else {
981	    print "\n\n.. c:struct:: " . $name . "\n\n";
982	}
983    }
984    print_lineno($declaration_start_line);
985    $lineprefix = "   ";
986    output_highlight_rst($args{'purpose'});
987    print "\n";
988
989    print "**Definition**\n\n";
990    print "::\n\n";
991    my $declaration = $args{'definition'};
992    $declaration =~ s/\t/  /g;
993    print "  " . $args{'type'} . " " . $args{'struct'} . " {\n$declaration  };\n\n";
994
995    print "**Members**\n\n";
996    $lineprefix = "  ";
997    foreach $parameter (@{$args{'parameterlist'}}) {
998	($parameter =~ /^#/) && next;
999
1000	my $parameter_name = $parameter;
1001	$parameter_name =~ s/\[.*//;
1002
1003	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
1004	$type = $args{'parametertypes'}{$parameter};
1005        print_lineno($parameterdesc_start_lines{$parameter_name});
1006	print "``" . $parameter . "``\n";
1007	output_highlight_rst($args{'parameterdescs'}{$parameter_name});
1008	print "\n";
1009    }
1010    print "\n";
1011
1012    $lineprefix = $oldprefix;
1013    output_section_rst(@_);
1014}
1015
1016## none mode output functions
1017
1018sub output_function_none(%) {
1019}
1020
1021sub output_enum_none(%) {
1022}
1023
1024sub output_typedef_none(%) {
1025}
1026
1027sub output_struct_none(%) {
1028}
1029
1030sub output_blockhead_none(%) {
1031}
1032
1033##
1034# generic output function for all types (function, struct/union, typedef, enum);
1035# calls the generated, variable output_ function name based on
1036# functype and output_mode
1037sub output_declaration {
1038    no strict 'refs';
1039    my $name = shift;
1040    my $functype = shift;
1041    my $func = "output_${functype}_$output_mode";
1042
1043    return if (defined($nosymbol_table{$name}));
1044
1045    if (($output_selection == OUTPUT_ALL) ||
1046	(($output_selection == OUTPUT_INCLUDE ||
1047	  $output_selection == OUTPUT_EXPORTED) &&
1048	 defined($function_table{$name})) ||
1049	($output_selection == OUTPUT_INTERNAL &&
1050	 !($functype eq "function" && defined($function_table{$name}))))
1051    {
1052	&$func(@_);
1053	$section_counter++;
1054    }
1055}
1056
1057##
1058# generic output function - calls the right one based on current output mode.
1059sub output_blockhead {
1060    no strict 'refs';
1061    my $func = "output_blockhead_" . $output_mode;
1062    &$func(@_);
1063    $section_counter++;
1064}
1065
1066##
1067# takes a declaration (struct, union, enum, typedef) and
1068# invokes the right handler. NOT called for functions.
1069sub dump_declaration($$) {
1070    no strict 'refs';
1071    my ($prototype, $file) = @_;
1072    my $func = "dump_" . $decl_type;
1073    &$func(@_);
1074}
1075
1076sub dump_union($$) {
1077    dump_struct(@_);
1078}
1079
1080sub dump_struct($$) {
1081    my $x = shift;
1082    my $file = shift;
1083    my $decl_type;
1084    my $members;
1085    my $type = qr{struct|union};
1086    # For capturing struct/union definition body, i.e. "{members*}qualifiers*"
1087    my $qualifiers = qr{$attribute|__packed|__aligned|____cacheline_aligned_in_smp|____cacheline_aligned};
1088    my $definition_body = qr{\{(.*)\}\s*$qualifiers*};
1089    my $struct_members = qr{($type)([^\{\};]+)\{([^\{\}]*)\}([^\{\}\;]*)\;};
1090
1091    if ($x =~ /($type)\s+(\w+)\s*$definition_body/) {
1092	$decl_type = $1;
1093	$declaration_name = $2;
1094	$members = $3;
1095    } elsif ($x =~ /typedef\s+($type)\s*$definition_body\s*(\w+)\s*;/) {
1096	$decl_type = $1;
1097	$declaration_name = $3;
1098	$members = $2;
1099    }
1100
1101    if ($members) {
1102	if ($identifier ne $declaration_name) {
1103	    emit_warning("${file}:$.", "expecting prototype for $decl_type $identifier. Prototype was for $decl_type $declaration_name instead\n");
1104	    return;
1105	}
1106
1107	# ignore members marked private:
1108	$members =~ s/\/\*\s*private:.*?\/\*\s*public:.*?\*\///gosi;
1109	$members =~ s/\/\*\s*private:.*//gosi;
1110	# strip comments:
1111	$members =~ s/\/\*.*?\*\///gos;
1112	# strip attributes
1113	$members =~ s/\s*$attribute/ /gi;
1114	$members =~ s/\s*__aligned\s*\([^;]*\)/ /gos;
1115	$members =~ s/\s*__packed\s*/ /gos;
1116	$members =~ s/\s*CRYPTO_MINALIGN_ATTR/ /gos;
1117	$members =~ s/\s*____cacheline_aligned_in_smp/ /gos;
1118	$members =~ s/\s*____cacheline_aligned/ /gos;
1119	# unwrap struct_group():
1120	# - first eat non-declaration parameters and rewrite for final match
1121	# - then remove macro, outer parens, and trailing semicolon
1122	$members =~ s/\bstruct_group\s*\(([^,]*,)/STRUCT_GROUP(/gos;
1123	$members =~ s/\bstruct_group_(attr|tagged)\s*\(([^,]*,){2}/STRUCT_GROUP(/gos;
1124	$members =~ s/\b__struct_group\s*\(([^,]*,){3}/STRUCT_GROUP(/gos;
1125	$members =~ s/\bSTRUCT_GROUP(\(((?:(?>[^)(]+)|(?1))*)\))[^;]*;/$2/gos;
1126
1127	my $args = qr{([^,)]+)};
1128	# replace DECLARE_BITMAP
1129	$members =~ s/__ETHTOOL_DECLARE_LINK_MODE_MASK\s*\(([^\)]+)\)/DECLARE_BITMAP($1, __ETHTOOL_LINK_MODE_MASK_NBITS)/gos;
1130	$members =~ s/DECLARE_PHY_INTERFACE_MASK\s*\(([^\)]+)\)/DECLARE_BITMAP($1, PHY_INTERFACE_MODE_MAX)/gos;
1131	$members =~ s/DECLARE_BITMAP\s*\($args,\s*$args\)/unsigned long $1\[BITS_TO_LONGS($2)\]/gos;
1132	# replace DECLARE_HASHTABLE
1133	$members =~ s/DECLARE_HASHTABLE\s*\($args,\s*$args\)/unsigned long $1\[1 << (($2) - 1)\]/gos;
1134	# replace DECLARE_KFIFO
1135	$members =~ s/DECLARE_KFIFO\s*\($args,\s*$args,\s*$args\)/$2 \*$1/gos;
1136	# replace DECLARE_KFIFO_PTR
1137	$members =~ s/DECLARE_KFIFO_PTR\s*\($args,\s*$args\)/$2 \*$1/gos;
1138	# replace DECLARE_FLEX_ARRAY
1139	$members =~ s/(?:__)?DECLARE_FLEX_ARRAY\s*\($args,\s*$args\)/$1 $2\[\]/gos;
1140	my $declaration = $members;
1141
1142	# Split nested struct/union elements as newer ones
1143	while ($members =~ m/$struct_members/) {
1144		my $newmember;
1145		my $maintype = $1;
1146		my $ids = $4;
1147		my $content = $3;
1148		foreach my $id(split /,/, $ids) {
1149			$newmember .= "$maintype $id; ";
1150
1151			$id =~ s/[:\[].*//;
1152			$id =~ s/^\s*\**(\S+)\s*/$1/;
1153			foreach my $arg (split /;/, $content) {
1154				next if ($arg =~ m/^\s*$/);
1155				if ($arg =~ m/^([^\(]+\(\*?\s*)([\w\.]*)(\s*\).*)/) {
1156					# pointer-to-function
1157					my $type = $1;
1158					my $name = $2;
1159					my $extra = $3;
1160					next if (!$name);
1161					if ($id =~ m/^\s*$/) {
1162						# anonymous struct/union
1163						$newmember .= "$type$name$extra; ";
1164					} else {
1165						$newmember .= "$type$id.$name$extra; ";
1166					}
1167				} else {
1168					my $type;
1169					my $names;
1170					$arg =~ s/^\s+//;
1171					$arg =~ s/\s+$//;
1172					# Handle bitmaps
1173					$arg =~ s/:\s*\d+\s*//g;
1174					# Handle arrays
1175					$arg =~ s/\[.*\]//g;
1176					# The type may have multiple words,
1177					# and multiple IDs can be defined, like:
1178					#	const struct foo, *bar, foobar
1179					# So, we remove spaces when parsing the
1180					# names, in order to match just names
1181					# and commas for the names
1182					$arg =~ s/\s*,\s*/,/g;
1183					if ($arg =~ m/(.*)\s+([\S+,]+)/) {
1184						$type = $1;
1185						$names = $2;
1186					} else {
1187						$newmember .= "$arg; ";
1188						next;
1189					}
1190					foreach my $name (split /,/, $names) {
1191						$name =~ s/^\s*\**(\S+)\s*/$1/;
1192						next if (($name =~ m/^\s*$/));
1193						if ($id =~ m/^\s*$/) {
1194							# anonymous struct/union
1195							$newmember .= "$type $name; ";
1196						} else {
1197							$newmember .= "$type $id.$name; ";
1198						}
1199					}
1200				}
1201			}
1202		}
1203		$members =~ s/$struct_members/$newmember/;
1204	}
1205
1206	# Ignore other nested elements, like enums
1207	$members =~ s/(\{[^\{\}]*\})//g;
1208
1209	create_parameterlist($members, ';', $file, $declaration_name);
1210	check_sections($file, $declaration_name, $decl_type, $sectcheck, $struct_actual);
1211
1212	# Adjust declaration for better display
1213	$declaration =~ s/([\{;])/$1\n/g;
1214	$declaration =~ s/\}\s+;/};/g;
1215	# Better handle inlined enums
1216	do {} while ($declaration =~ s/(enum\s+\{[^\}]+),([^\n])/$1,\n$2/);
1217
1218	my @def_args = split /\n/, $declaration;
1219	my $level = 1;
1220	$declaration = "";
1221	foreach my $clause (@def_args) {
1222		$clause =~ s/^\s+//;
1223		$clause =~ s/\s+$//;
1224		$clause =~ s/\s+/ /;
1225		next if (!$clause);
1226		$level-- if ($clause =~ m/(\})/ && $level > 1);
1227		if (!($clause =~ m/^\s*#/)) {
1228			$declaration .= "\t" x $level;
1229		}
1230		$declaration .= "\t" . $clause . "\n";
1231		$level++ if ($clause =~ m/(\{)/ && !($clause =~m/\}/));
1232	}
1233	output_declaration($declaration_name,
1234			   'struct',
1235			   {'struct' => $declaration_name,
1236			    'module' => $modulename,
1237			    'definition' => $declaration,
1238			    'parameterlist' => \@parameterlist,
1239			    'parameterdescs' => \%parameterdescs,
1240			    'parametertypes' => \%parametertypes,
1241			    'sectionlist' => \@sectionlist,
1242			    'sections' => \%sections,
1243			    'purpose' => $declaration_purpose,
1244			    'type' => $decl_type
1245			   });
1246    }
1247    else {
1248	print STDERR "${file}:$.: error: Cannot parse struct or union!\n";
1249	++$errors;
1250    }
1251}
1252
1253
1254sub show_warnings($$) {
1255	my $functype = shift;
1256	my $name = shift;
1257
1258	return 0 if (defined($nosymbol_table{$name}));
1259
1260	return 1 if ($output_selection == OUTPUT_ALL);
1261
1262	if ($output_selection == OUTPUT_EXPORTED) {
1263		if (defined($function_table{$name})) {
1264			return 1;
1265		} else {
1266			return 0;
1267		}
1268	}
1269        if ($output_selection == OUTPUT_INTERNAL) {
1270		if (!($functype eq "function" && defined($function_table{$name}))) {
1271			return 1;
1272		} else {
1273			return 0;
1274		}
1275	}
1276	if ($output_selection == OUTPUT_INCLUDE) {
1277		if (defined($function_table{$name})) {
1278			return 1;
1279		} else {
1280			return 0;
1281		}
1282	}
1283	die("Please add the new output type at show_warnings()");
1284}
1285
1286sub dump_enum($$) {
1287    my $x = shift;
1288    my $file = shift;
1289    my $members;
1290
1291
1292    $x =~ s@/\*.*?\*/@@gos;	# strip comments.
1293    # strip #define macros inside enums
1294    $x =~ s@#\s*((define|ifdef)\s+|endif)[^;]*;@@gos;
1295
1296    if ($x =~ /typedef\s+enum\s*\{(.*)\}\s*(\w*)\s*;/) {
1297	$declaration_name = $2;
1298	$members = $1;
1299    } elsif ($x =~ /enum\s+(\w*)\s*\{(.*)\}/) {
1300	$declaration_name = $1;
1301	$members = $2;
1302    }
1303
1304    if ($members) {
1305	if ($identifier ne $declaration_name) {
1306	    if ($identifier eq "") {
1307		emit_warning("${file}:$.", "wrong kernel-doc identifier on line:\n");
1308	    } else {
1309		emit_warning("${file}:$.", "expecting prototype for enum $identifier. Prototype was for enum $declaration_name instead\n");
1310	    }
1311	    return;
1312	}
1313	$declaration_name = "(anonymous)" if ($declaration_name eq "");
1314
1315	my %_members;
1316
1317	$members =~ s/\s+$//;
1318
1319	foreach my $arg (split ',', $members) {
1320	    $arg =~ s/^\s*(\w+).*/$1/;
1321	    push @parameterlist, $arg;
1322	    if (!$parameterdescs{$arg}) {
1323		$parameterdescs{$arg} = $undescribed;
1324	        if (show_warnings("enum", $declaration_name)) {
1325			emit_warning("${file}:$.", "Enum value '$arg' not described in enum '$declaration_name'\n");
1326		}
1327	    }
1328	    $_members{$arg} = 1;
1329	}
1330
1331	while (my ($k, $v) = each %parameterdescs) {
1332	    if (!exists($_members{$k})) {
1333	        if (show_warnings("enum", $declaration_name)) {
1334		     emit_warning("${file}:$.", "Excess enum value '$k' description in '$declaration_name'\n");
1335		}
1336	    }
1337        }
1338
1339	output_declaration($declaration_name,
1340			   'enum',
1341			   {'enum' => $declaration_name,
1342			    'module' => $modulename,
1343			    'parameterlist' => \@parameterlist,
1344			    'parameterdescs' => \%parameterdescs,
1345			    'sectionlist' => \@sectionlist,
1346			    'sections' => \%sections,
1347			    'purpose' => $declaration_purpose
1348			   });
1349    } else {
1350	print STDERR "${file}:$.: error: Cannot parse enum!\n";
1351	++$errors;
1352    }
1353}
1354
1355my $typedef_type = qr { ((?:\s+[\w\*]+\b){1,8})\s* }x;
1356my $typedef_ident = qr { \*?\s*(\w\S+)\s* }x;
1357my $typedef_args = qr { \s*\((.*)\); }x;
1358
1359my $typedef1 = qr { typedef$typedef_type\($typedef_ident\)$typedef_args }x;
1360my $typedef2 = qr { typedef$typedef_type$typedef_ident$typedef_args }x;
1361
1362sub dump_typedef($$) {
1363    my $x = shift;
1364    my $file = shift;
1365
1366    $x =~ s@/\*.*?\*/@@gos;	# strip comments.
1367
1368    # Parse function typedef prototypes
1369    if ($x =~ $typedef1 || $x =~ $typedef2) {
1370	$return_type = $1;
1371	$declaration_name = $2;
1372	my $args = $3;
1373	$return_type =~ s/^\s+//;
1374
1375	if ($identifier ne $declaration_name) {
1376	    emit_warning("${file}:$.", "expecting prototype for typedef $identifier. Prototype was for typedef $declaration_name instead\n");
1377	    return;
1378	}
1379
1380	create_parameterlist($args, ',', $file, $declaration_name);
1381
1382	output_declaration($declaration_name,
1383			   'function',
1384			   {'function' => $declaration_name,
1385			    'typedef' => 1,
1386			    'module' => $modulename,
1387			    'functiontype' => $return_type,
1388			    'parameterlist' => \@parameterlist,
1389			    'parameterdescs' => \%parameterdescs,
1390			    'parametertypes' => \%parametertypes,
1391			    'sectionlist' => \@sectionlist,
1392			    'sections' => \%sections,
1393			    'purpose' => $declaration_purpose
1394			   });
1395	return;
1396    }
1397
1398    while (($x =~ /\(*.\)\s*;$/) || ($x =~ /\[*.\]\s*;$/)) {
1399	$x =~ s/\(*.\)\s*;$/;/;
1400	$x =~ s/\[*.\]\s*;$/;/;
1401    }
1402
1403    if ($x =~ /typedef.*\s+(\w+)\s*;/) {
1404	$declaration_name = $1;
1405
1406	if ($identifier ne $declaration_name) {
1407	    emit_warning("${file}:$.", "expecting prototype for typedef $identifier. Prototype was for typedef $declaration_name instead\n");
1408	    return;
1409	}
1410
1411	output_declaration($declaration_name,
1412			   'typedef',
1413			   {'typedef' => $declaration_name,
1414			    'module' => $modulename,
1415			    'sectionlist' => \@sectionlist,
1416			    'sections' => \%sections,
1417			    'purpose' => $declaration_purpose
1418			   });
1419    }
1420    else {
1421	print STDERR "${file}:$.: error: Cannot parse typedef!\n";
1422	++$errors;
1423    }
1424}
1425
1426sub save_struct_actual($) {
1427    my $actual = shift;
1428
1429    # strip all spaces from the actual param so that it looks like one string item
1430    $actual =~ s/\s*//g;
1431    $struct_actual = $struct_actual . $actual . " ";
1432}
1433
1434sub create_parameterlist($$$$) {
1435    my $args = shift;
1436    my $splitter = shift;
1437    my $file = shift;
1438    my $declaration_name = shift;
1439    my $type;
1440    my $param;
1441
1442    # temporarily replace commas inside function pointer definition
1443    my $arg_expr = qr{\([^\),]+};
1444    while ($args =~ /$arg_expr,/) {
1445	$args =~ s/($arg_expr),/$1#/g;
1446    }
1447
1448    foreach my $arg (split($splitter, $args)) {
1449	# strip comments
1450	$arg =~ s/\/\*.*\*\///;
1451	# ignore argument attributes
1452	$arg =~ s/\sPOS0?\s/ /;
1453	# strip leading/trailing spaces
1454	$arg =~ s/^\s*//;
1455	$arg =~ s/\s*$//;
1456	$arg =~ s/\s+/ /;
1457
1458	if ($arg =~ /^#/) {
1459	    # Treat preprocessor directive as a typeless variable just to fill
1460	    # corresponding data structures "correctly". Catch it later in
1461	    # output_* subs.
1462	    push_parameter($arg, "", "", $file);
1463	} elsif ($arg =~ m/\(.+\)\s*\(/) {
1464	    # pointer-to-function
1465	    $arg =~ tr/#/,/;
1466	    $arg =~ m/[^\(]+\(\*?\s*([\w\[\]\.]*)\s*\)/;
1467	    $param = $1;
1468	    $type = $arg;
1469	    $type =~ s/([^\(]+\(\*?)\s*$param/$1/;
1470	    save_struct_actual($param);
1471	    push_parameter($param, $type, $arg, $file, $declaration_name);
1472	} elsif ($arg) {
1473	    $arg =~ s/\s*:\s*/:/g;
1474	    $arg =~ s/\s*\[/\[/g;
1475
1476	    my @args = split('\s*,\s*', $arg);
1477	    if ($args[0] =~ m/\*/) {
1478		$args[0] =~ s/(\*+)\s*/ $1/;
1479	    }
1480
1481	    my @first_arg;
1482	    if ($args[0] =~ /^(.*\s+)(.*?\[.*\].*)$/) {
1483		    shift @args;
1484		    push(@first_arg, split('\s+', $1));
1485		    push(@first_arg, $2);
1486	    } else {
1487		    @first_arg = split('\s+', shift @args);
1488	    }
1489
1490	    unshift(@args, pop @first_arg);
1491	    $type = join " ", @first_arg;
1492
1493	    foreach $param (@args) {
1494		if ($param =~ m/^(\*+)\s*(.*)/) {
1495		    save_struct_actual($2);
1496
1497		    push_parameter($2, "$type $1", $arg, $file, $declaration_name);
1498		}
1499		elsif ($param =~ m/(.*?):(\d+)/) {
1500		    if ($type ne "") { # skip unnamed bit-fields
1501			save_struct_actual($1);
1502			push_parameter($1, "$type:$2", $arg, $file, $declaration_name)
1503		    }
1504		}
1505		else {
1506		    save_struct_actual($param);
1507		    push_parameter($param, $type, $arg, $file, $declaration_name);
1508		}
1509	    }
1510	}
1511    }
1512}
1513
1514sub push_parameter($$$$$) {
1515	my $param = shift;
1516	my $type = shift;
1517	my $org_arg = shift;
1518	my $file = shift;
1519	my $declaration_name = shift;
1520
1521	if (($anon_struct_union == 1) && ($type eq "") &&
1522	    ($param eq "}")) {
1523		return;		# ignore the ending }; from anon. struct/union
1524	}
1525
1526	$anon_struct_union = 0;
1527	$param =~ s/[\[\)].*//;
1528
1529	if ($type eq "" && $param =~ /\.\.\.$/)
1530	{
1531	    if (!$param =~ /\w\.\.\.$/) {
1532	      # handles unnamed variable parameters
1533	      $param = "...";
1534	    }
1535	    elsif ($param =~ /\w\.\.\.$/) {
1536	      # for named variable parameters of the form `x...`, remove the dots
1537	      $param =~ s/\.\.\.$//;
1538	    }
1539	    if (!defined $parameterdescs{$param} || $parameterdescs{$param} eq "") {
1540		$parameterdescs{$param} = "variable arguments";
1541	    }
1542	}
1543	elsif ($type eq "" && ($param eq "" or $param eq "void"))
1544	{
1545	    $param="void";
1546	    $parameterdescs{void} = "no arguments";
1547	}
1548	elsif ($type eq "" && ($param eq "struct" or $param eq "union"))
1549	# handle unnamed (anonymous) union or struct:
1550	{
1551		$type = $param;
1552		$param = "{unnamed_" . $param . "}";
1553		$parameterdescs{$param} = "anonymous\n";
1554		$anon_struct_union = 1;
1555	}
1556
1557	# warn if parameter has no description
1558	# (but ignore ones starting with # as these are not parameters
1559	# but inline preprocessor statements);
1560	# Note: It will also ignore void params and unnamed structs/unions
1561	if (!defined $parameterdescs{$param} && $param !~ /^#/) {
1562		$parameterdescs{$param} = $undescribed;
1563
1564	        if (show_warnings($type, $declaration_name) && $param !~ /\./) {
1565			emit_warning("${file}:$.", "Function parameter or member '$param' not described in '$declaration_name'\n");
1566		}
1567	}
1568
1569	# strip spaces from $param so that it is one continuous string
1570	# on @parameterlist;
1571	# this fixes a problem where check_sections() cannot find
1572	# a parameter like "addr[6 + 2]" because it actually appears
1573	# as "addr[6", "+", "2]" on the parameter list;
1574	# but it's better to maintain the param string unchanged for output,
1575	# so just weaken the string compare in check_sections() to ignore
1576	# "[blah" in a parameter string;
1577	###$param =~ s/\s*//g;
1578	push @parameterlist, $param;
1579	$org_arg =~ s/\s\s+/ /g;
1580	$parametertypes{$param} = $org_arg;
1581}
1582
1583sub check_sections($$$$$) {
1584	my ($file, $decl_name, $decl_type, $sectcheck, $prmscheck) = @_;
1585	my @sects = split ' ', $sectcheck;
1586	my @prms = split ' ', $prmscheck;
1587	my $err;
1588	my ($px, $sx);
1589	my $prm_clean;		# strip trailing "[array size]" and/or beginning "*"
1590
1591	foreach $sx (0 .. $#sects) {
1592		$err = 1;
1593		foreach $px (0 .. $#prms) {
1594			$prm_clean = $prms[$px];
1595			$prm_clean =~ s/\[.*\]//;
1596			$prm_clean =~ s/$attribute//i;
1597			# ignore array size in a parameter string;
1598			# however, the original param string may contain
1599			# spaces, e.g.:  addr[6 + 2]
1600			# and this appears in @prms as "addr[6" since the
1601			# parameter list is split at spaces;
1602			# hence just ignore "[..." for the sections check;
1603			$prm_clean =~ s/\[.*//;
1604
1605			##$prm_clean =~ s/^\**//;
1606			if ($prm_clean eq $sects[$sx]) {
1607				$err = 0;
1608				last;
1609			}
1610		}
1611		if ($err) {
1612			if ($decl_type eq "function") {
1613				emit_warning("${file}:$.",
1614					"Excess function parameter " .
1615					"'$sects[$sx]' " .
1616					"description in '$decl_name'\n");
1617			}
1618		}
1619	}
1620}
1621
1622##
1623# Checks the section describing the return value of a function.
1624sub check_return_section {
1625        my $file = shift;
1626        my $declaration_name = shift;
1627        my $return_type = shift;
1628
1629        # Ignore an empty return type (It's a macro)
1630        # Ignore functions with a "void" return type. (But don't ignore "void *")
1631        if (($return_type eq "") || ($return_type =~ /void\s*\w*\s*$/)) {
1632                return;
1633        }
1634
1635        if (!defined($sections{$section_return}) ||
1636            $sections{$section_return} eq "") {
1637                emit_warning("${file}:$.",
1638                        "No description found for return value of " .
1639                        "'$declaration_name'\n");
1640        }
1641}
1642
1643##
1644# takes a function prototype and the name of the current file being
1645# processed and spits out all the details stored in the global
1646# arrays/hashes.
1647sub dump_function($$) {
1648    my $prototype = shift;
1649    my $file = shift;
1650    my $noret = 0;
1651
1652    print_lineno($new_start_line);
1653
1654    $prototype =~ s/^static +//;
1655    $prototype =~ s/^extern +//;
1656    $prototype =~ s/^asmlinkage +//;
1657    $prototype =~ s/^inline +//;
1658    $prototype =~ s/^__inline__ +//;
1659    $prototype =~ s/^__inline +//;
1660    $prototype =~ s/^__always_inline +//;
1661    $prototype =~ s/^noinline +//;
1662    $prototype =~ s/^__FORTIFY_INLINE +//;
1663    $prototype =~ s/__init +//;
1664    $prototype =~ s/__init_or_module +//;
1665    $prototype =~ s/__deprecated +//;
1666    $prototype =~ s/__flatten +//;
1667    $prototype =~ s/__meminit +//;
1668    $prototype =~ s/__must_check +//;
1669    $prototype =~ s/__weak +//;
1670    $prototype =~ s/__sched +//;
1671    $prototype =~ s/__printf\s*\(\s*\d*\s*,\s*\d*\s*\) +//;
1672    $prototype =~ s/__(?:re)?alloc_size\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\) +//;
1673    $prototype =~ s/__diagnose_as\s*\(\s*\S+\s*(?:,\s*\d+\s*)*\) +//;
1674    my $define = $prototype =~ s/^#\s*define\s+//; #ak added
1675    $prototype =~ s/__attribute_const__ +//;
1676    $prototype =~ s/__attribute__\s*\(\(
1677            (?:
1678                 [\w\s]++          # attribute name
1679                 (?:\([^)]*+\))?   # attribute arguments
1680                 \s*+,?            # optional comma at the end
1681            )+
1682          \)\)\s+//x;
1683
1684    # Yes, this truly is vile.  We are looking for:
1685    # 1. Return type (may be nothing if we're looking at a macro)
1686    # 2. Function name
1687    # 3. Function parameters.
1688    #
1689    # All the while we have to watch out for function pointer parameters
1690    # (which IIRC is what the two sections are for), C types (these
1691    # regexps don't even start to express all the possibilities), and
1692    # so on.
1693    #
1694    # If you mess with these regexps, it's a good idea to check that
1695    # the following functions' documentation still comes out right:
1696    # - parport_register_device (function pointer parameters)
1697    # - atomic_set (macro)
1698    # - pci_match_device, __copy_to_user (long return type)
1699    my $name = qr{[a-zA-Z0-9_~:]+};
1700    my $prototype_end1 = qr{[^\(]*};
1701    my $prototype_end2 = qr{[^\{]*};
1702    my $prototype_end = qr{\(($prototype_end1|$prototype_end2)\)};
1703    my $type1 = qr{[\w\s]+};
1704    my $type2 = qr{$type1\*+};
1705
1706    if ($define && $prototype =~ m/^()($name)\s+/) {
1707        # This is an object-like macro, it has no return type and no parameter
1708        # list.
1709        # Function-like macros are not allowed to have spaces between
1710        # declaration_name and opening parenthesis (notice the \s+).
1711        $return_type = $1;
1712        $declaration_name = $2;
1713        $noret = 1;
1714    } elsif ($prototype =~ m/^()($name)\s*$prototype_end/ ||
1715	$prototype =~ m/^($type1)\s+($name)\s*$prototype_end/ ||
1716	$prototype =~ m/^($type2+)\s*($name)\s*$prototype_end/)  {
1717	$return_type = $1;
1718	$declaration_name = $2;
1719	my $args = $3;
1720
1721	create_parameterlist($args, ',', $file, $declaration_name);
1722    } else {
1723	emit_warning("${file}:$.", "cannot understand function prototype: '$prototype'\n");
1724	return;
1725    }
1726
1727    if ($identifier ne $declaration_name) {
1728	emit_warning("${file}:$.", "expecting prototype for $identifier(). Prototype was for $declaration_name() instead\n");
1729	return;
1730    }
1731
1732    my $prms = join " ", @parameterlist;
1733    check_sections($file, $declaration_name, "function", $sectcheck, $prms);
1734
1735    # This check emits a lot of warnings at the moment, because many
1736    # functions don't have a 'Return' doc section. So until the number
1737    # of warnings goes sufficiently down, the check is only performed in
1738    # verbose mode.
1739    # TODO: always perform the check.
1740    if ($verbose && !$noret) {
1741	    check_return_section($file, $declaration_name, $return_type);
1742    }
1743
1744    # The function parser can be called with a typedef parameter.
1745    # Handle it.
1746    if ($return_type =~ /typedef/) {
1747	output_declaration($declaration_name,
1748			   'function',
1749			   {'function' => $declaration_name,
1750			    'typedef' => 1,
1751			    'module' => $modulename,
1752			    'functiontype' => $return_type,
1753			    'parameterlist' => \@parameterlist,
1754			    'parameterdescs' => \%parameterdescs,
1755			    'parametertypes' => \%parametertypes,
1756			    'sectionlist' => \@sectionlist,
1757			    'sections' => \%sections,
1758			    'purpose' => $declaration_purpose
1759			   });
1760    } else {
1761	output_declaration($declaration_name,
1762			   'function',
1763			   {'function' => $declaration_name,
1764			    'module' => $modulename,
1765			    'functiontype' => $return_type,
1766			    'parameterlist' => \@parameterlist,
1767			    'parameterdescs' => \%parameterdescs,
1768			    'parametertypes' => \%parametertypes,
1769			    'sectionlist' => \@sectionlist,
1770			    'sections' => \%sections,
1771			    'purpose' => $declaration_purpose
1772			   });
1773    }
1774}
1775
1776sub reset_state {
1777    $function = "";
1778    %parameterdescs = ();
1779    %parametertypes = ();
1780    @parameterlist = ();
1781    %sections = ();
1782    @sectionlist = ();
1783    $sectcheck = "";
1784    $struct_actual = "";
1785    $prototype = "";
1786
1787    $state = STATE_NORMAL;
1788    $inline_doc_state = STATE_INLINE_NA;
1789}
1790
1791sub tracepoint_munge($) {
1792	my $file = shift;
1793	my $tracepointname = 0;
1794	my $tracepointargs = 0;
1795
1796	if ($prototype =~ m/TRACE_EVENT\((.*?),/) {
1797		$tracepointname = $1;
1798	}
1799	if ($prototype =~ m/DEFINE_SINGLE_EVENT\((.*?),/) {
1800		$tracepointname = $1;
1801	}
1802	if ($prototype =~ m/DEFINE_EVENT\((.*?),(.*?),/) {
1803		$tracepointname = $2;
1804	}
1805	$tracepointname =~ s/^\s+//; #strip leading whitespace
1806	if ($prototype =~ m/TP_PROTO\((.*?)\)/) {
1807		$tracepointargs = $1;
1808	}
1809	if (($tracepointname eq 0) || ($tracepointargs eq 0)) {
1810		emit_warning("${file}:$.", "Unrecognized tracepoint format: \n".
1811			     "$prototype\n");
1812	} else {
1813		$prototype = "static inline void trace_$tracepointname($tracepointargs)";
1814		$identifier = "trace_$identifier";
1815	}
1816}
1817
1818sub syscall_munge() {
1819	my $void = 0;
1820
1821	$prototype =~ s@[\r\n]+@ @gos; # strip newlines/CR's
1822##	if ($prototype =~ m/SYSCALL_DEFINE0\s*\(\s*(a-zA-Z0-9_)*\s*\)/) {
1823	if ($prototype =~ m/SYSCALL_DEFINE0/) {
1824		$void = 1;
1825##		$prototype = "long sys_$1(void)";
1826	}
1827
1828	$prototype =~ s/SYSCALL_DEFINE.*\(/long sys_/; # fix return type & func name
1829	if ($prototype =~ m/long (sys_.*?),/) {
1830		$prototype =~ s/,/\(/;
1831	} elsif ($void) {
1832		$prototype =~ s/\)/\(void\)/;
1833	}
1834
1835	# now delete all of the odd-number commas in $prototype
1836	# so that arg types & arg names don't have a comma between them
1837	my $count = 0;
1838	my $len = length($prototype);
1839	if ($void) {
1840		$len = 0;	# skip the for-loop
1841	}
1842	for (my $ix = 0; $ix < $len; $ix++) {
1843		if (substr($prototype, $ix, 1) eq ',') {
1844			$count++;
1845			if ($count % 2 == 1) {
1846				substr($prototype, $ix, 1) = ' ';
1847			}
1848		}
1849	}
1850}
1851
1852sub process_proto_function($$) {
1853    my $x = shift;
1854    my $file = shift;
1855
1856    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line
1857
1858    if ($x =~ m#\s*/\*\s+MACDOC\s*#io || ($x =~ /^#/ && $x !~ /^#\s*define/)) {
1859	# do nothing
1860    }
1861    elsif ($x =~ /([^\{]*)/) {
1862	$prototype .= $1;
1863    }
1864
1865    if (($x =~ /\{/) || ($x =~ /\#\s*define/) || ($x =~ /;/)) {
1866	$prototype =~ s@/\*.*?\*/@@gos;	# strip comments.
1867	$prototype =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
1868	$prototype =~ s@^\s+@@gos; # strip leading spaces
1869
1870	 # Handle prototypes for function pointers like:
1871	 # int (*pcs_config)(struct foo)
1872	$prototype =~ s@^(\S+\s+)\(\s*\*(\S+)\)@$1$2@gos;
1873
1874	if ($prototype =~ /SYSCALL_DEFINE/) {
1875		syscall_munge();
1876	}
1877	if ($prototype =~ /TRACE_EVENT/ || $prototype =~ /DEFINE_EVENT/ ||
1878	    $prototype =~ /DEFINE_SINGLE_EVENT/)
1879	{
1880		tracepoint_munge($file);
1881	}
1882	dump_function($prototype, $file);
1883	reset_state();
1884    }
1885}
1886
1887sub process_proto_type($$) {
1888    my $x = shift;
1889    my $file = shift;
1890
1891    $x =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
1892    $x =~ s@^\s+@@gos; # strip leading spaces
1893    $x =~ s@\s+$@@gos; # strip trailing spaces
1894    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line
1895
1896    if ($x =~ /^#/) {
1897	# To distinguish preprocessor directive from regular declaration later.
1898	$x .= ";";
1899    }
1900
1901    while (1) {
1902	if ( $x =~ /([^\{\};]*)([\{\};])(.*)/ ) {
1903            if( length $prototype ) {
1904                $prototype .= " "
1905            }
1906	    $prototype .= $1 . $2;
1907	    ($2 eq '{') && $brcount++;
1908	    ($2 eq '}') && $brcount--;
1909	    if (($2 eq ';') && ($brcount == 0)) {
1910		dump_declaration($prototype, $file);
1911		reset_state();
1912		last;
1913	    }
1914	    $x = $3;
1915	} else {
1916	    $prototype .= $x;
1917	    last;
1918	}
1919    }
1920}
1921
1922
1923sub map_filename($) {
1924    my $file;
1925    my ($orig_file) = @_;
1926
1927    if (defined($ENV{'SRCTREE'})) {
1928	$file = "$ENV{'SRCTREE'}" . "/" . $orig_file;
1929    } else {
1930	$file = $orig_file;
1931    }
1932
1933    if (defined($source_map{$file})) {
1934	$file = $source_map{$file};
1935    }
1936
1937    return $file;
1938}
1939
1940sub process_export_file($) {
1941    my ($orig_file) = @_;
1942    my $file = map_filename($orig_file);
1943
1944    if (!open(IN,"<$file")) {
1945	print STDERR "Error: Cannot open file $file\n";
1946	++$errors;
1947	return;
1948    }
1949
1950    while (<IN>) {
1951	if (/$export_symbol/) {
1952	    next if (defined($nosymbol_table{$2}));
1953	    $function_table{$2} = 1;
1954	}
1955    }
1956
1957    close(IN);
1958}
1959
1960#
1961# Parsers for the various processing states.
1962#
1963# STATE_NORMAL: looking for the /** to begin everything.
1964#
1965sub process_normal() {
1966    if (/$doc_start/o) {
1967	$state = STATE_NAME;	# next line is always the function name
1968	$in_doc_sect = 0;
1969	$declaration_start_line = $. + 1;
1970    }
1971}
1972
1973#
1974# STATE_NAME: Looking for the "name - description" line
1975#
1976sub process_name($$) {
1977    my $file = shift;
1978    my $descr;
1979
1980    if (/$doc_block/o) {
1981	$state = STATE_DOCBLOCK;
1982	$contents = "";
1983	$new_start_line = $.;
1984
1985	if ( $1 eq "" ) {
1986	    $section = $section_intro;
1987	} else {
1988	    $section = $1;
1989	}
1990    } elsif (/$doc_decl/o) {
1991	$identifier = $1;
1992	my $is_kernel_comment = 0;
1993	my $decl_start = qr{$doc_com};
1994	# test for pointer declaration type, foo * bar() - desc
1995	my $fn_type = qr{\w+\s*\*\s*};
1996	my $parenthesis = qr{\(\w*\)};
1997	my $decl_end = qr{[-:].*};
1998	if (/^$decl_start([\w\s]+?)$parenthesis?\s*$decl_end?$/) {
1999	    $identifier = $1;
2000	}
2001	if ($identifier =~ m/^(struct|union|enum|typedef)\b\s*(\S*)/) {
2002	    $decl_type = $1;
2003	    $identifier = $2;
2004	    $is_kernel_comment = 1;
2005	}
2006	# Look for foo() or static void foo() - description; or misspelt
2007	# identifier
2008	elsif (/^$decl_start$fn_type?(\w+)\s*$parenthesis?\s*$decl_end?$/ ||
2009	    /^$decl_start$fn_type?(\w+.*)$parenthesis?\s*$decl_end$/) {
2010	    $identifier = $1;
2011	    $decl_type = 'function';
2012	    $identifier =~ s/^define\s+//;
2013	    $is_kernel_comment = 1;
2014	}
2015	$identifier =~ s/\s+$//;
2016
2017	$state = STATE_BODY;
2018	# if there's no @param blocks need to set up default section
2019	# here
2020	$contents = "";
2021	$section = $section_default;
2022	$new_start_line = $. + 1;
2023	if (/[-:](.*)/) {
2024	    # strip leading/trailing/multiple spaces
2025	    $descr= $1;
2026	    $descr =~ s/^\s*//;
2027	    $descr =~ s/\s*$//;
2028	    $descr =~ s/\s+/ /g;
2029	    $declaration_purpose = $descr;
2030	    $state = STATE_BODY_MAYBE;
2031	} else {
2032	    $declaration_purpose = "";
2033	}
2034
2035	if (!$is_kernel_comment) {
2036	    emit_warning("${file}:$.", "This comment starts with '/**', but isn't a kernel-doc comment. Refer Documentation/doc-guide/kernel-doc.rst\n$_");
2037	    $state = STATE_NORMAL;
2038	}
2039
2040	if (($declaration_purpose eq "") && $verbose) {
2041	    emit_warning("${file}:$.", "missing initial short description on line:\n$_");
2042	}
2043
2044	if ($identifier eq "" && $decl_type ne "enum") {
2045	    emit_warning("${file}:$.", "wrong kernel-doc identifier on line:\n$_");
2046	    $state = STATE_NORMAL;
2047	}
2048
2049	if ($verbose) {
2050	    print STDERR "${file}:$.: info: Scanning doc for $decl_type $identifier\n";
2051	}
2052    } else {
2053	emit_warning("${file}:$.", "Cannot understand $_ on line $. - I thought it was a doc line\n");
2054	$state = STATE_NORMAL;
2055    }
2056}
2057
2058
2059#
2060# STATE_BODY and STATE_BODY_MAYBE: the bulk of a kerneldoc comment.
2061#
2062sub process_body($$) {
2063    my $file = shift;
2064
2065    # Until all named variable macro parameters are
2066    # documented using the bare name (`x`) rather than with
2067    # dots (`x...`), strip the dots:
2068    if ($section =~ /\w\.\.\.$/) {
2069	$section =~ s/\.\.\.$//;
2070
2071	if ($verbose) {
2072	    emit_warning("${file}:$.", "Variable macro arguments should be documented without dots\n");
2073	}
2074    }
2075
2076    if ($state == STATE_BODY_WITH_BLANK_LINE && /^\s*\*\s?\S/) {
2077	dump_section($file, $section, $contents);
2078	$section = $section_default;
2079	$new_start_line = $.;
2080	$contents = "";
2081    }
2082
2083    if (/$doc_sect/i) { # case insensitive for supported section names
2084	$newsection = $1;
2085	$newcontents = $2;
2086
2087	# map the supported section names to the canonical names
2088	if ($newsection =~ m/^description$/i) {
2089	    $newsection = $section_default;
2090	} elsif ($newsection =~ m/^context$/i) {
2091	    $newsection = $section_context;
2092	} elsif ($newsection =~ m/^returns?$/i) {
2093	    $newsection = $section_return;
2094	} elsif ($newsection =~ m/^\@return$/) {
2095	    # special: @return is a section, not a param description
2096	    $newsection = $section_return;
2097	}
2098
2099	if (($contents ne "") && ($contents ne "\n")) {
2100	    if (!$in_doc_sect && $verbose) {
2101		emit_warning("${file}:$.", "contents before sections\n");
2102	    }
2103	    dump_section($file, $section, $contents);
2104	    $section = $section_default;
2105	}
2106
2107	$in_doc_sect = 1;
2108	$state = STATE_BODY;
2109	$contents = $newcontents;
2110	$new_start_line = $.;
2111	while (substr($contents, 0, 1) eq " ") {
2112	    $contents = substr($contents, 1);
2113	}
2114	if ($contents ne "") {
2115	    $contents .= "\n";
2116	}
2117	$section = $newsection;
2118	$leading_space = undef;
2119    } elsif (/$doc_end/) {
2120	if (($contents ne "") && ($contents ne "\n")) {
2121	    dump_section($file, $section, $contents);
2122	    $section = $section_default;
2123	    $contents = "";
2124	}
2125	# look for doc_com + <text> + doc_end:
2126	if ($_ =~ m'\s*\*\s*[a-zA-Z_0-9:\.]+\*/') {
2127	    emit_warning("${file}:$.", "suspicious ending line: $_");
2128	}
2129
2130	$prototype = "";
2131	$state = STATE_PROTO;
2132	$brcount = 0;
2133        $new_start_line = $. + 1;
2134    } elsif (/$doc_content/) {
2135	if ($1 eq "") {
2136	    if ($section eq $section_context) {
2137		dump_section($file, $section, $contents);
2138		$section = $section_default;
2139		$contents = "";
2140		$new_start_line = $.;
2141		$state = STATE_BODY;
2142	    } else {
2143		if ($section ne $section_default) {
2144		    $state = STATE_BODY_WITH_BLANK_LINE;
2145		} else {
2146		    $state = STATE_BODY;
2147		}
2148		$contents .= "\n";
2149	    }
2150	} elsif ($state == STATE_BODY_MAYBE) {
2151	    # Continued declaration purpose
2152	    chomp($declaration_purpose);
2153	    $declaration_purpose .= " " . $1;
2154	    $declaration_purpose =~ s/\s+/ /g;
2155	} else {
2156	    my $cont = $1;
2157	    if ($section =~ m/^@/ || $section eq $section_context) {
2158		if (!defined $leading_space) {
2159		    if ($cont =~ m/^(\s+)/) {
2160			$leading_space = $1;
2161		    } else {
2162			$leading_space = "";
2163		    }
2164		}
2165		$cont =~ s/^$leading_space//;
2166	    }
2167	    $contents .= $cont . "\n";
2168	}
2169    } else {
2170	# i dont know - bad line?  ignore.
2171	emit_warning("${file}:$.", "bad line: $_");
2172    }
2173}
2174
2175
2176#
2177# STATE_PROTO: reading a function/whatever prototype.
2178#
2179sub process_proto($$) {
2180    my $file = shift;
2181
2182    if (/$doc_inline_oneline/) {
2183	$section = $1;
2184	$contents = $2;
2185	if ($contents ne "") {
2186	    $contents .= "\n";
2187	    dump_section($file, $section, $contents);
2188	    $section = $section_default;
2189	    $contents = "";
2190	}
2191    } elsif (/$doc_inline_start/) {
2192	$state = STATE_INLINE;
2193	$inline_doc_state = STATE_INLINE_NAME;
2194    } elsif ($decl_type eq 'function') {
2195	process_proto_function($_, $file);
2196    } else {
2197	process_proto_type($_, $file);
2198    }
2199}
2200
2201#
2202# STATE_DOCBLOCK: within a DOC: block.
2203#
2204sub process_docblock($$) {
2205    my $file = shift;
2206
2207    if (/$doc_end/) {
2208	dump_doc_section($file, $section, $contents);
2209	$section = $section_default;
2210	$contents = "";
2211	$function = "";
2212	%parameterdescs = ();
2213	%parametertypes = ();
2214	@parameterlist = ();
2215	%sections = ();
2216	@sectionlist = ();
2217	$prototype = "";
2218	$state = STATE_NORMAL;
2219    } elsif (/$doc_content/) {
2220	if ( $1 eq "" )	{
2221	    $contents .= $blankline;
2222	} else {
2223	    $contents .= $1 . "\n";
2224	}
2225    }
2226}
2227
2228#
2229# STATE_INLINE: docbook comments within a prototype.
2230#
2231sub process_inline($$) {
2232    my $file = shift;
2233
2234    # First line (state 1) needs to be a @parameter
2235    if ($inline_doc_state == STATE_INLINE_NAME && /$doc_inline_sect/o) {
2236	$section = $1;
2237	$contents = $2;
2238	$new_start_line = $.;
2239	if ($contents ne "") {
2240	    while (substr($contents, 0, 1) eq " ") {
2241		$contents = substr($contents, 1);
2242	    }
2243	    $contents .= "\n";
2244	}
2245	$inline_doc_state = STATE_INLINE_TEXT;
2246	# Documentation block end */
2247    } elsif (/$doc_inline_end/) {
2248	if (($contents ne "") && ($contents ne "\n")) {
2249	    dump_section($file, $section, $contents);
2250	    $section = $section_default;
2251	    $contents = "";
2252	}
2253	$state = STATE_PROTO;
2254	$inline_doc_state = STATE_INLINE_NA;
2255	# Regular text
2256    } elsif (/$doc_content/) {
2257	if ($inline_doc_state == STATE_INLINE_TEXT) {
2258	    $contents .= $1 . "\n";
2259	    # nuke leading blank lines
2260	    if ($contents =~ /^\s*$/) {
2261		$contents = "";
2262	    }
2263	} elsif ($inline_doc_state == STATE_INLINE_NAME) {
2264	    $inline_doc_state = STATE_INLINE_ERROR;
2265	    emit_warning("${file}:$.", "Incorrect use of kernel-doc format: $_");
2266	}
2267    }
2268}
2269
2270
2271sub process_file($) {
2272    my $file;
2273    my $initial_section_counter = $section_counter;
2274    my ($orig_file) = @_;
2275
2276    $file = map_filename($orig_file);
2277
2278    if (!open(IN_FILE,"<$file")) {
2279	print STDERR "Error: Cannot open file $file\n";
2280	++$errors;
2281	return;
2282    }
2283
2284    $. = 1;
2285
2286    $section_counter = 0;
2287    while (<IN_FILE>) {
2288	while (s/\\\s*$//) {
2289	    $_ .= <IN_FILE>;
2290	}
2291	# Replace tabs by spaces
2292        while ($_ =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e) {};
2293	# Hand this line to the appropriate state handler
2294	if ($state == STATE_NORMAL) {
2295	    process_normal();
2296	} elsif ($state == STATE_NAME) {
2297	    process_name($file, $_);
2298	} elsif ($state == STATE_BODY || $state == STATE_BODY_MAYBE ||
2299		 $state == STATE_BODY_WITH_BLANK_LINE) {
2300	    process_body($file, $_);
2301	} elsif ($state == STATE_INLINE) { # scanning for inline parameters
2302	    process_inline($file, $_);
2303	} elsif ($state == STATE_PROTO) {
2304	    process_proto($file, $_);
2305	} elsif ($state == STATE_DOCBLOCK) {
2306	    process_docblock($file, $_);
2307	}
2308    }
2309
2310    # Make sure we got something interesting.
2311    if ($initial_section_counter == $section_counter && $
2312	output_mode ne "none") {
2313	if ($output_selection == OUTPUT_INCLUDE) {
2314	    emit_warning("${file}:1", "'$_' not found\n")
2315		for keys %function_table;
2316	}
2317	else {
2318	    emit_warning("${file}:1", "no structured comments found\n");
2319	}
2320    }
2321    close IN_FILE;
2322}
2323
2324
2325if ($output_mode eq "rst") {
2326	get_sphinx_version() if (!$sphinx_major);
2327}
2328
2329$kernelversion = get_kernel_version();
2330
2331# generate a sequence of code that will splice in highlighting information
2332# using the s// operator.
2333for (my $k = 0; $k < @highlights; $k++) {
2334    my $pattern = $highlights[$k][0];
2335    my $result = $highlights[$k][1];
2336#   print STDERR "scanning pattern:$pattern, highlight:($result)\n";
2337    $dohighlight .=  "\$contents =~ s:$pattern:$result:gs;\n";
2338}
2339
2340# Read the file that maps relative names to absolute names for
2341# separate source and object directories and for shadow trees.
2342if (open(SOURCE_MAP, "<.tmp_filelist.txt")) {
2343	my ($relname, $absname);
2344	while(<SOURCE_MAP>) {
2345		chop();
2346		($relname, $absname) = (split())[0..1];
2347		$relname =~ s:^/+::;
2348		$source_map{$relname} = $absname;
2349	}
2350	close(SOURCE_MAP);
2351}
2352
2353if ($output_selection == OUTPUT_EXPORTED ||
2354    $output_selection == OUTPUT_INTERNAL) {
2355
2356    push(@export_file_list, @ARGV);
2357
2358    foreach (@export_file_list) {
2359	chomp;
2360	process_export_file($_);
2361    }
2362}
2363
2364foreach (@ARGV) {
2365    chomp;
2366    process_file($_);
2367}
2368if ($verbose && $errors) {
2369  print STDERR "$errors errors\n";
2370}
2371if ($verbose && $warnings) {
2372  print STDERR "$warnings warnings\n";
2373}
2374
2375if ($Werror && $warnings) {
2376    print STDERR "$warnings warnings as Errors\n";
2377    exit($warnings);
2378} else {
2379    exit($output_mode eq "none" ? 0 : $errors)
2380}
2381
2382__END__
2383
2384=head1 OPTIONS
2385
2386=head2 Output format selection (mutually exclusive):
2387
2388=over 8
2389
2390=item -man
2391
2392Output troff manual page format.
2393
2394=item -rst
2395
2396Output reStructuredText format. This is the default.
2397
2398=item -none
2399
2400Do not output documentation, only warnings.
2401
2402=back
2403
2404=head2 Output format modifiers
2405
2406=head3 reStructuredText only
2407
2408=over 8
2409
2410=item -sphinx-version VERSION
2411
2412Use the ReST C domain dialect compatible with a specific Sphinx Version.
2413
2414If not specified, kernel-doc will auto-detect using the sphinx-build version
2415found on PATH.
2416
2417=back
2418
2419=head2 Output selection (mutually exclusive):
2420
2421=over 8
2422
2423=item -export
2424
2425Only output documentation for the symbols that have been exported using
2426EXPORT_SYMBOL() or EXPORT_SYMBOL_GPL() in any input FILE or -export-file FILE.
2427
2428=item -internal
2429
2430Only output documentation for the symbols that have NOT been exported using
2431EXPORT_SYMBOL() or EXPORT_SYMBOL_GPL() in any input FILE or -export-file FILE.
2432
2433=item -function NAME
2434
2435Only output documentation for the given function or DOC: section title.
2436All other functions and DOC: sections are ignored.
2437
2438May be specified multiple times.
2439
2440=item -nosymbol NAME
2441
2442Exclude the specified symbol from the output documentation.
2443
2444May be specified multiple times.
2445
2446=back
2447
2448=head2 Output selection modifiers:
2449
2450=over 8
2451
2452=item -no-doc-sections
2453
2454Do not output DOC: sections.
2455
2456=item -export-file FILE
2457
2458Specify an additional FILE in which to look for EXPORT_SYMBOL() and
2459EXPORT_SYMBOL_GPL().
2460
2461To be used with -export or -internal.
2462
2463May be specified multiple times.
2464
2465=back
2466
2467=head3 reStructuredText only
2468
2469=over 8
2470
2471=item -enable-lineno
2472
2473Enable output of .. LINENO lines.
2474
2475=back
2476
2477=head2 Other parameters:
2478
2479=over 8
2480
2481=item -h, -help
2482
2483Print this help.
2484
2485=item -v
2486
2487Verbose output, more warnings and other information.
2488
2489=item -Werror
2490
2491Treat warnings as errors.
2492
2493=back
2494
2495=cut
2496