linux/scripts/kernel-doc
<<
>>
Prefs
   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##
 431# dumps section contents to arrays/hashes intended for that purpose.
 432#
 433sub dump_section {
 434    my $file = shift;
 435    my $name = shift;
 436    my $contents = join "\n", @_;
 437
 438    if ($name =~ m/$type_param/) {
 439        $name = $1;
 440        $parameterdescs{$name} = $contents;
 441        $sectcheck = $sectcheck . $name . " ";
 442        $parameterdesc_start_lines{$name} = $new_start_line;
 443        $new_start_line = 0;
 444    } elsif ($name eq "@\.\.\.") {
 445        $name = "...";
 446        $parameterdescs{$name} = $contents;
 447        $sectcheck = $sectcheck . $name . " ";
 448        $parameterdesc_start_lines{$name} = $new_start_line;
 449        $new_start_line = 0;
 450    } else {
 451        if (defined($sections{$name}) && ($sections{$name} ne "")) {
 452            # Only warn on user specified duplicate section names.
 453            if ($name ne $section_default) {
 454                print STDERR "${file}:$.: warning: duplicate section name '$name'\n";
 455                ++$warnings;
 456            }
 457            $sections{$name} .= $contents;
 458        } else {
 459            $sections{$name} = $contents;
 460            push @sectionlist, $name;
 461            $section_start_lines{$name} = $new_start_line;
 462            $new_start_line = 0;
 463        }
 464    }
 465}
 466
 467##
 468# dump DOC: section after checking that it should go out
 469#
 470sub dump_doc_section {
 471    my $file = shift;
 472    my $name = shift;
 473    my $contents = join "\n", @_;
 474
 475    if ($no_doc_sections) {
 476        return;
 477    }
 478
 479    return if (defined($nosymbol_table{$name}));
 480
 481    if (($output_selection == OUTPUT_ALL) ||
 482        (($output_selection == OUTPUT_INCLUDE) &&
 483         defined($function_table{$name})))
 484    {
 485        dump_section($file, $name, $contents);
 486        output_blockhead({'sectionlist' => \@sectionlist,
 487                          'sections' => \%sections,
 488                          'module' => $modulename,
 489                          'content-only' => ($output_selection != OUTPUT_ALL), });
 490    }
 491}
 492
 493##
 494# output function
 495#
 496# parameterdescs, a hash.
 497#  function => "function name"
 498#  parameterlist => @list of parameters
 499#  parameterdescs => %parameter descriptions
 500#  sectionlist => @list of sections
 501#  sections => %section descriptions
 502#
 503
 504sub output_highlight {
 505    my $contents = join "\n",@_;
 506    my $line;
 507
 508#   DEBUG
 509#   if (!defined $contents) {
 510#       use Carp;
 511#       confess "output_highlight got called with no args?\n";
 512#   }
 513
 514#   print STDERR "contents b4:$contents\n";
 515    eval $dohighlight;
 516    die $@ if $@;
 517#   print STDERR "contents af:$contents\n";
 518
 519    foreach $line (split "\n", $contents) {
 520        if (! $output_preformatted) {
 521            $line =~ s/^\s*//;
 522        }
 523        if ($line eq ""){
 524            if (! $output_preformatted) {
 525                print $lineprefix, $blankline;
 526            }
 527        } else {
 528            if ($output_mode eq "man" && substr($line, 0, 1) eq ".") {
 529                print "\\&$line";
 530            } else {
 531                print $lineprefix, $line;
 532            }
 533        }
 534        print "\n";
 535    }
 536}
 537
 538##
 539# output function in man
 540sub output_function_man(%) {
 541    my %args = %{$_[0]};
 542    my ($parameter, $section);
 543    my $count;
 544
 545    print ".TH \"$args{'function'}\" 9 \"$args{'function'}\" \"$man_date\" \"Kernel Hacker's Manual\" LINUX\n";
 546
 547    print ".SH NAME\n";
 548    print $args{'function'} . " \\- " . $args{'purpose'} . "\n";
 549
 550    print ".SH SYNOPSIS\n";
 551    if ($args{'functiontype'} ne "") {
 552        print ".B \"" . $args{'functiontype'} . "\" " . $args{'function'} . "\n";
 553    } else {
 554        print ".B \"" . $args{'function'} . "\n";
 555    }
 556    $count = 0;
 557    my $parenth = "(";
 558    my $post = ",";
 559    foreach my $parameter (@{$args{'parameterlist'}}) {
 560        if ($count == $#{$args{'parameterlist'}}) {
 561            $post = ");";
 562        }
 563        $type = $args{'parametertypes'}{$parameter};
 564        if ($type =~ m/$function_pointer/) {
 565            # pointer-to-function
 566            print ".BI \"" . $parenth . $1 . "\" " . " \") (" . $2 . ")" . $post . "\"\n";
 567        } else {
 568            $type =~ s/([^\*])$/$1 /;
 569            print ".BI \"" . $parenth . $type . "\" " . " \"" . $post . "\"\n";
 570        }
 571        $count++;
 572        $parenth = "";
 573    }
 574
 575    print ".SH ARGUMENTS\n";
 576    foreach $parameter (@{$args{'parameterlist'}}) {
 577        my $parameter_name = $parameter;
 578        $parameter_name =~ s/\[.*//;
 579
 580        print ".IP \"" . $parameter . "\" 12\n";
 581        output_highlight($args{'parameterdescs'}{$parameter_name});
 582    }
 583    foreach $section (@{$args{'sectionlist'}}) {
 584        print ".SH \"", uc $section, "\"\n";
 585        output_highlight($args{'sections'}{$section});
 586    }
 587}
 588
 589##
 590# output enum in man
 591sub output_enum_man(%) {
 592    my %args = %{$_[0]};
 593    my ($parameter, $section);
 594    my $count;
 595
 596    print ".TH \"$args{'module'}\" 9 \"enum $args{'enum'}\" \"$man_date\" \"API Manual\" LINUX\n";
 597
 598    print ".SH NAME\n";
 599    print "enum " . $args{'enum'} . " \\- " . $args{'purpose'} . "\n";
 600
 601    print ".SH SYNOPSIS\n";
 602    print "enum " . $args{'enum'} . " {\n";
 603    $count = 0;
 604    foreach my $parameter (@{$args{'parameterlist'}}) {
 605        print ".br\n.BI \"    $parameter\"\n";
 606        if ($count == $#{$args{'parameterlist'}}) {
 607            print "\n};\n";
 608            last;
 609        }
 610        else {
 611            print ", \n.br\n";
 612        }
 613        $count++;
 614    }
 615
 616    print ".SH Constants\n";
 617    foreach $parameter (@{$args{'parameterlist'}}) {
 618        my $parameter_name = $parameter;
 619        $parameter_name =~ s/\[.*//;
 620
 621        print ".IP \"" . $parameter . "\" 12\n";
 622        output_highlight($args{'parameterdescs'}{$parameter_name});
 623    }
 624    foreach $section (@{$args{'sectionlist'}}) {
 625        print ".SH \"$section\"\n";
 626        output_highlight($args{'sections'}{$section});
 627    }
 628}
 629
 630##
 631# output struct in man
 632sub output_struct_man(%) {
 633    my %args = %{$_[0]};
 634    my ($parameter, $section);
 635
 636    print ".TH \"$args{'module'}\" 9 \"" . $args{'type'} . " " . $args{'struct'} . "\" \"$man_date\" \"API Manual\" LINUX\n";
 637
 638    print ".SH NAME\n";
 639    print $args{'type'} . " " . $args{'struct'} . " \\- " . $args{'purpose'} . "\n";
 640
 641    my $declaration = $args{'definition'};
 642    $declaration =~ s/\t/  /g;
 643    $declaration =~ s/\n/"\n.br\n.BI \"/g;
 644    print ".SH SYNOPSIS\n";
 645    print $args{'type'} . " " . $args{'struct'} . " {\n.br\n";
 646    print ".BI \"$declaration\n};\n.br\n\n";
 647
 648    print ".SH Members\n";
 649    foreach $parameter (@{$args{'parameterlist'}}) {
 650        ($parameter =~ /^#/) && next;
 651
 652        my $parameter_name = $parameter;
 653        $parameter_name =~ s/\[.*//;
 654
 655        ($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
 656        print ".IP \"" . $parameter . "\" 12\n";
 657        output_highlight($args{'parameterdescs'}{$parameter_name});
 658    }
 659    foreach $section (@{$args{'sectionlist'}}) {
 660        print ".SH \"$section\"\n";
 661        output_highlight($args{'sections'}{$section});
 662    }
 663}
 664
 665##
 666# output typedef in man
 667sub output_typedef_man(%) {
 668    my %args = %{$_[0]};
 669    my ($parameter, $section);
 670
 671    print ".TH \"$args{'module'}\" 9 \"$args{'typedef'}\" \"$man_date\" \"API Manual\" LINUX\n";
 672
 673    print ".SH NAME\n";
 674    print "typedef " . $args{'typedef'} . " \\- " . $args{'purpose'} . "\n";
 675
 676    foreach $section (@{$args{'sectionlist'}}) {
 677        print ".SH \"$section\"\n";
 678        output_highlight($args{'sections'}{$section});
 679    }
 680}
 681
 682sub output_blockhead_man(%) {
 683    my %args = %{$_[0]};
 684    my ($parameter, $section);
 685    my $count;
 686
 687    print ".TH \"$args{'module'}\" 9 \"$args{'module'}\" \"$man_date\" \"API Manual\" LINUX\n";
 688
 689    foreach $section (@{$args{'sectionlist'}}) {
 690        print ".SH \"$section\"\n";
 691        output_highlight($args{'sections'}{$section});
 692    }
 693}
 694
 695##
 696# output in restructured text
 697#
 698
 699#
 700# This could use some work; it's used to output the DOC: sections, and
 701# starts by putting out the name of the doc section itself, but that tends
 702# to duplicate a header already in the template file.
 703#
 704sub output_blockhead_rst(%) {
 705    my %args = %{$_[0]};
 706    my ($parameter, $section);
 707
 708    foreach $section (@{$args{'sectionlist'}}) {
 709        next if (defined($nosymbol_table{$section}));
 710
 711        if ($output_selection != OUTPUT_INCLUDE) {
 712            print ".. _$section:\n\n";
 713            print "**$section**\n\n";
 714        }
 715        print_lineno($section_start_lines{$section});
 716        output_highlight_rst($args{'sections'}{$section});
 717        print "\n";
 718    }
 719}
 720
 721#
 722# Apply the RST highlights to a sub-block of text.
 723#
 724sub highlight_block($) {
 725    # The dohighlight kludge requires the text be called $contents
 726    my $contents = shift;
 727    eval $dohighlight;
 728    die $@ if $@;
 729    return $contents;
 730}
 731
 732#
 733# Regexes used only here.
 734#
 735my $sphinx_literal = '^[^.].*::$';
 736my $sphinx_cblock = '^\.\.\ +code-block::';
 737
 738sub output_highlight_rst {
 739    my $input = join "\n",@_;
 740    my $output = "";
 741    my $line;
 742    my $in_literal = 0;
 743    my $litprefix;
 744    my $block = "";
 745
 746    foreach $line (split "\n",$input) {
 747        #
 748        # If we're in a literal block, see if we should drop out
 749        # of it.  Otherwise pass the line straight through unmunged.
 750        #
 751        if ($in_literal) {
 752            if (! ($line =~ /^\s*$/)) {
 753                #
 754                # If this is the first non-blank line in a literal
 755                # block we need to figure out what the proper indent is.
 756                #
 757                if ($litprefix eq "") {
 758                    $line =~ /^(\s*)/;
 759                    $litprefix = '^' . $1;
 760                    $output .= $line . "\n";
 761                } elsif (! ($line =~ /$litprefix/)) {
 762                    $in_literal = 0;
 763                } else {
 764                    $output .= $line . "\n";
 765                }
 766            } else {
 767                $output .= $line . "\n";
 768            }
 769        }
 770        #
 771        # Not in a literal block (or just dropped out)
 772        #
 773        if (! $in_literal) {
 774            $block .= $line . "\n";
 775            if (($line =~ /$sphinx_literal/) || ($line =~ /$sphinx_cblock/)) {
 776                $in_literal = 1;
 777                $litprefix = "";
 778                $output .= highlight_block($block);
 779                $block = ""
 780            }
 781        }
 782    }
 783
 784    if ($block) {
 785        $output .= highlight_block($block);
 786    }
 787    foreach $line (split "\n", $output) {
 788        print $lineprefix . $line . "\n";
 789    }
 790}
 791
 792sub output_function_rst(%) {
 793    my %args = %{$_[0]};
 794    my ($parameter, $section);
 795    my $oldprefix = $lineprefix;
 796    my $start = "";
 797    my $is_macro = 0;
 798
 799    if ($sphinx_major < 3) {
 800        if ($args{'typedef'}) {
 801            print ".. c:type:: ". $args{'function'} . "\n\n";
 802            print_lineno($declaration_start_line);
 803            print "   **Typedef**: ";
 804            $lineprefix = "";
 805            output_highlight_rst($args{'purpose'});
 806            $start = "\n\n**Syntax**\n\n  ``";
 807            $is_macro = 1;
 808        } else {
 809            print ".. c:function:: ";
 810        }
 811    } else {
 812        if ($args{'typedef'} || $args{'functiontype'} eq "") {
 813            $is_macro = 1;
 814            print ".. c:macro:: ". $args{'function'} . "\n\n";
 815        } else {
 816            print ".. c:function:: ";
 817        }
 818
 819        if ($args{'typedef'}) {
 820            print_lineno($declaration_start_line);
 821            print "   **Typedef**: ";
 822            $lineprefix = "";
 823            output_highlight_rst($args{'purpose'});
 824            $start = "\n\n**Syntax**\n\n  ``";
 825        } else {
 826            print "``" if ($is_macro);
 827        }
 828    }
 829    if ($args{'functiontype'} ne "") {
 830        $start .= $args{'functiontype'} . " " . $args{'function'} . " (";
 831    } else {
 832        $start .= $args{'function'} . " (";
 833    }
 834    print $start;
 835
 836    my $count = 0;
 837    foreach my $parameter (@{$args{'parameterlist'}}) {
 838        if ($count ne 0) {
 839            print ", ";
 840        }
 841        $count++;
 842        $type = $args{'parametertypes'}{$parameter};
 843
 844        if ($type =~ m/$function_pointer/) {
 845            # pointer-to-function
 846            print $1 . $parameter . ") (" . $2 . ")";
 847        } else {
 848            print $type;
 849        }
 850    }
 851    if ($is_macro) {
 852        print ")``\n\n";
 853    } else {
 854        print ")\n\n";
 855    }
 856    if (!$args{'typedef'}) {
 857        print_lineno($declaration_start_line);
 858        $lineprefix = "   ";
 859        output_highlight_rst($args{'purpose'});
 860        print "\n";
 861    }
 862
 863    print "**Parameters**\n\n";
 864    $lineprefix = "  ";
 865    foreach $parameter (@{$args{'parameterlist'}}) {
 866        my $parameter_name = $parameter;
 867        $parameter_name =~ s/\[.*//;
 868        $type = $args{'parametertypes'}{$parameter};
 869
 870        if ($type ne "") {
 871            print "``$type``\n";
 872        } else {
 873            print "``$parameter``\n";
 874        }
 875
 876        print_lineno($parameterdesc_start_lines{$parameter_name});
 877
 878        if (defined($args{'parameterdescs'}{$parameter_name}) &&
 879            $args{'parameterdescs'}{$parameter_name} ne $undescribed) {
 880            output_highlight_rst($args{'parameterdescs'}{$parameter_name});
 881        } else {
 882            print "  *undescribed*\n";
 883        }
 884        print "\n";
 885    }
 886
 887    $lineprefix = $oldprefix;
 888    output_section_rst(@_);
 889}
 890
 891sub output_section_rst(%) {
 892    my %args = %{$_[0]};
 893    my $section;
 894    my $oldprefix = $lineprefix;
 895    $lineprefix = "";
 896
 897    foreach $section (@{$args{'sectionlist'}}) {
 898        print "**$section**\n\n";
 899        print_lineno($section_start_lines{$section});
 900        output_highlight_rst($args{'sections'}{$section});
 901        print "\n";
 902    }
 903    print "\n";
 904    $lineprefix = $oldprefix;
 905}
 906
 907sub output_enum_rst(%) {
 908    my %args = %{$_[0]};
 909    my ($parameter);
 910    my $oldprefix = $lineprefix;
 911    my $count;
 912
 913    if ($sphinx_major < 3) {
 914        my $name = "enum " . $args{'enum'};
 915        print "\n\n.. c:type:: " . $name . "\n\n";
 916    } else {
 917        my $name = $args{'enum'};
 918        print "\n\n.. c:enum:: " . $name . "\n\n";
 919    }
 920    print_lineno($declaration_start_line);
 921    $lineprefix = "   ";
 922    output_highlight_rst($args{'purpose'});
 923    print "\n";
 924
 925    print "**Constants**\n\n";
 926    $lineprefix = "  ";
 927    foreach $parameter (@{$args{'parameterlist'}}) {
 928        print "``$parameter``\n";
 929        if ($args{'parameterdescs'}{$parameter} ne $undescribed) {
 930            output_highlight_rst($args{'parameterdescs'}{$parameter});
 931        } else {
 932            print "  *undescribed*\n";
 933        }
 934        print "\n";
 935    }
 936
 937    $lineprefix = $oldprefix;
 938    output_section_rst(@_);
 939}
 940
 941sub output_typedef_rst(%) {
 942    my %args = %{$_[0]};
 943    my ($parameter);
 944    my $oldprefix = $lineprefix;
 945    my $name;
 946
 947    if ($sphinx_major < 3) {
 948        $name = "typedef " . $args{'typedef'};
 949    } else {
 950        $name = $args{'typedef'};
 951    }
 952    print "\n\n.. c:type:: " . $name . "\n\n";
 953    print_lineno($declaration_start_line);
 954    $lineprefix = "   ";
 955    output_highlight_rst($args{'purpose'});
 956    print "\n";
 957
 958    $lineprefix = $oldprefix;
 959    output_section_rst(@_);
 960}
 961
 962sub output_struct_rst(%) {
 963    my %args = %{$_[0]};
 964    my ($parameter);
 965    my $oldprefix = $lineprefix;
 966
 967    if ($sphinx_major < 3) {
 968        my $name = $args{'type'} . " " . $args{'struct'};
 969        print "\n\n.. c:type:: " . $name . "\n\n";
 970    } else {
 971        my $name = $args{'struct'};
 972        if ($args{'type'} eq 'union') {
 973            print "\n\n.. c:union:: " . $name . "\n\n";
 974        } else {
 975            print "\n\n.. c:struct:: " . $name . "\n\n";
 976        }
 977    }
 978    print_lineno($declaration_start_line);
 979    $lineprefix = "   ";
 980    output_highlight_rst($args{'purpose'});
 981    print "\n";
 982
 983    print "**Definition**\n\n";
 984    print "::\n\n";
 985    my $declaration = $args{'definition'};
 986    $declaration =~ s/\t/  /g;
 987    print "  " . $args{'type'} . " " . $args{'struct'} . " {\n$declaration  };\n\n";
 988
 989    print "**Members**\n\n";
 990    $lineprefix = "  ";
 991    foreach $parameter (@{$args{'parameterlist'}}) {
 992        ($parameter =~ /^#/) && next;
 993
 994        my $parameter_name = $parameter;
 995        $parameter_name =~ s/\[.*//;
 996
 997        ($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
 998        $type = $args{'parametertypes'}{$parameter};
 999        print_lineno($parameterdesc_start_lines{$parameter_name});
1000        print "``" . $parameter . "``\n";
1001        output_highlight_rst($args{'parameterdescs'}{$parameter_name});
1002        print "\n";
1003    }
1004    print "\n";
1005
1006    $lineprefix = $oldprefix;
1007    output_section_rst(@_);
1008}
1009
1010## none mode output functions
1011
1012sub output_function_none(%) {
1013}
1014
1015sub output_enum_none(%) {
1016}
1017
1018sub output_typedef_none(%) {
1019}
1020
1021sub output_struct_none(%) {
1022}
1023
1024sub output_blockhead_none(%) {
1025}
1026
1027##
1028# generic output function for all types (function, struct/union, typedef, enum);
1029# calls the generated, variable output_ function name based on
1030# functype and output_mode
1031sub output_declaration {
1032    no strict 'refs';
1033    my $name = shift;
1034    my $functype = shift;
1035    my $func = "output_${functype}_$output_mode";
1036
1037    return if (defined($nosymbol_table{$name}));
1038
1039    if (($output_selection == OUTPUT_ALL) ||
1040        (($output_selection == OUTPUT_INCLUDE ||
1041          $output_selection == OUTPUT_EXPORTED) &&
1042         defined($function_table{$name})) ||
1043        ($output_selection == OUTPUT_INTERNAL &&
1044         !($functype eq "function" && defined($function_table{$name}))))
1045    {
1046        &$func(@_);
1047        $section_counter++;
1048    }
1049}
1050
1051##
1052# generic output function - calls the right one based on current output mode.
1053sub output_blockhead {
1054    no strict 'refs';
1055    my $func = "output_blockhead_" . $output_mode;
1056    &$func(@_);
1057    $section_counter++;
1058}
1059
1060##
1061# takes a declaration (struct, union, enum, typedef) and
1062# invokes the right handler. NOT called for functions.
1063sub dump_declaration($$) {
1064    no strict 'refs';
1065    my ($prototype, $file) = @_;
1066    my $func = "dump_" . $decl_type;
1067    &$func(@_);
1068}
1069
1070sub dump_union($$) {
1071    dump_struct(@_);
1072}
1073
1074sub dump_struct($$) {
1075    my $x = shift;
1076    my $file = shift;
1077    my $decl_type;
1078    my $members;
1079    my $type = qr{struct|union};
1080    # For capturing struct/union definition body, i.e. "{members*}qualifiers*"
1081    my $qualifiers = qr{$attribute|__packed|__aligned|____cacheline_aligned_in_smp|____cacheline_aligned};
1082    my $definition_body = qr{\{(.*)\}\s*$qualifiers*};
1083    my $struct_members = qr{($type)([^\{\};]+)\{([^\{\}]*)\}([^\{\}\;]*)\;};
1084
1085    if ($x =~ /($type)\s+(\w+)\s*$definition_body/) {
1086        $decl_type = $1;
1087        $declaration_name = $2;
1088        $members = $3;
1089    } elsif ($x =~ /typedef\s+($type)\s*$definition_body\s*(\w+)\s*;/) {
1090        $decl_type = $1;
1091        $declaration_name = $3;
1092        $members = $2;
1093    }
1094
1095    if ($members) {
1096        if ($identifier ne $declaration_name) {
1097            print STDERR "${file}:$.: warning: expecting prototype for $decl_type $identifier. Prototype was for $decl_type $declaration_name instead\n";
1098            return;
1099        }
1100
1101        # ignore members marked private:
1102        $members =~ s/\/\*\s*private:.*?\/\*\s*public:.*?\*\///gosi;
1103        $members =~ s/\/\*\s*private:.*//gosi;
1104        # strip comments:
1105        $members =~ s/\/\*.*?\*\///gos;
1106        # strip attributes
1107        $members =~ s/\s*$attribute/ /gi;
1108        $members =~ s/\s*__aligned\s*\([^;]*\)/ /gos;
1109        $members =~ s/\s*__packed\s*/ /gos;
1110        $members =~ s/\s*CRYPTO_MINALIGN_ATTR/ /gos;
1111        $members =~ s/\s*____cacheline_aligned_in_smp/ /gos;
1112        $members =~ s/\s*____cacheline_aligned/ /gos;
1113        # unwrap struct_group():
1114        # - first eat non-declaration parameters and rewrite for final match
1115        # - then remove macro, outer parens, and trailing semicolon
1116        $members =~ s/\bstruct_group\s*\(([^,]*,)/STRUCT_GROUP(/gos;
1117        $members =~ s/\bstruct_group_(attr|tagged)\s*\(([^,]*,){2}/STRUCT_GROUP(/gos;
1118        $members =~ s/\b__struct_group\s*\(([^,]*,){3}/STRUCT_GROUP(/gos;
1119        $members =~ s/\bSTRUCT_GROUP(\(((?:(?>[^)(]+)|(?1))*)\))[^;]*;/$2/gos;
1120
1121        my $args = qr{([^,)]+)};
1122        # replace DECLARE_BITMAP
1123        $members =~ s/__ETHTOOL_DECLARE_LINK_MODE_MASK\s*\(([^\)]+)\)/DECLARE_BITMAP($1, __ETHTOOL_LINK_MODE_MASK_NBITS)/gos;
1124        $members =~ s/DECLARE_PHY_INTERFACE_MASK\s*\(([^\)]+)\)/DECLARE_BITMAP($1, PHY_INTERFACE_MODE_MAX)/gos;
1125        $members =~ s/DECLARE_BITMAP\s*\($args,\s*$args\)/unsigned long $1\[BITS_TO_LONGS($2)\]/gos;
1126        # replace DECLARE_HASHTABLE
1127        $members =~ s/DECLARE_HASHTABLE\s*\($args,\s*$args\)/unsigned long $1\[1 << (($2) - 1)\]/gos;
1128        # replace DECLARE_KFIFO
1129        $members =~ s/DECLARE_KFIFO\s*\($args,\s*$args,\s*$args\)/$2 \*$1/gos;
1130        # replace DECLARE_KFIFO_PTR
1131        $members =~ s/DECLARE_KFIFO_PTR\s*\($args,\s*$args\)/$2 \*$1/gos;
1132        # replace DECLARE_FLEX_ARRAY
1133        $members =~ s/(?:__)?DECLARE_FLEX_ARRAY\s*\($args,\s*$args\)/$1 $2\[\]/gos;
1134        my $declaration = $members;
1135
1136        # Split nested struct/union elements as newer ones
1137        while ($members =~ m/$struct_members/) {
1138                my $newmember;
1139                my $maintype = $1;
1140                my $ids = $4;
1141                my $content = $3;
1142                foreach my $id(split /,/, $ids) {
1143                        $newmember .= "$maintype $id; ";
1144
1145                        $id =~ s/[:\[].*//;
1146                        $id =~ s/^\s*\**(\S+)\s*/$1/;
1147                        foreach my $arg (split /;/, $content) {
1148                                next if ($arg =~ m/^\s*$/);
1149                                if ($arg =~ m/^([^\(]+\(\*?\s*)([\w\.]*)(\s*\).*)/) {
1150                                        # pointer-to-function
1151                                        my $type = $1;
1152                                        my $name = $2;
1153                                        my $extra = $3;
1154                                        next if (!$name);
1155                                        if ($id =~ m/^\s*$/) {
1156                                                # anonymous struct/union
1157                                                $newmember .= "$type$name$extra; ";
1158                                        } else {
1159                                                $newmember .= "$type$id.$name$extra; ";
1160                                        }
1161                                } else {
1162                                        my $type;
1163                                        my $names;
1164                                        $arg =~ s/^\s+//;
1165                                        $arg =~ s/\s+$//;
1166                                        # Handle bitmaps
1167                                        $arg =~ s/:\s*\d+\s*//g;
1168                                        # Handle arrays
1169                                        $arg =~ s/\[.*\]//g;
1170                                        # The type may have multiple words,
1171                                        # and multiple IDs can be defined, like:
1172                                        #       const struct foo, *bar, foobar
1173                                        # So, we remove spaces when parsing the
1174                                        # names, in order to match just names
1175                                        # and commas for the names
1176                                        $arg =~ s/\s*,\s*/,/g;
1177                                        if ($arg =~ m/(.*)\s+([\S+,]+)/) {
1178                                                $type = $1;
1179                                                $names = $2;
1180                                        } else {
1181                                                $newmember .= "$arg; ";
1182                                                next;
1183                                        }
1184                                        foreach my $name (split /,/, $names) {
1185                                                $name =~ s/^\s*\**(\S+)\s*/$1/;
1186                                                next if (($name =~ m/^\s*$/));
1187                                                if ($id =~ m/^\s*$/) {
1188                                                        # anonymous struct/union
1189                                                        $newmember .= "$type $name; ";
1190                                                } else {
1191                                                        $newmember .= "$type $id.$name; ";
1192                                                }
1193                                        }
1194                                }
1195                        }
1196                }
1197                $members =~ s/$struct_members/$newmember/;
1198        }
1199
1200        # Ignore other nested elements, like enums
1201        $members =~ s/(\{[^\{\}]*\})//g;
1202
1203        create_parameterlist($members, ';', $file, $declaration_name);
1204        check_sections($file, $declaration_name, $decl_type, $sectcheck, $struct_actual);
1205
1206        # Adjust declaration for better display
1207        $declaration =~ s/([\{;])/$1\n/g;
1208        $declaration =~ s/\}\s+;/};/g;
1209        # Better handle inlined enums
1210        do {} while ($declaration =~ s/(enum\s+\{[^\}]+),([^\n])/$1,\n$2/);
1211
1212        my @def_args = split /\n/, $declaration;
1213        my $level = 1;
1214        $declaration = "";
1215        foreach my $clause (@def_args) {
1216                $clause =~ s/^\s+//;
1217                $clause =~ s/\s+$//;
1218                $clause =~ s/\s+/ /;
1219                next if (!$clause);
1220                $level-- if ($clause =~ m/(\})/ && $level > 1);
1221                if (!($clause =~ m/^\s*#/)) {
1222                        $declaration .= "\t" x $level;
1223                }
1224                $declaration .= "\t" . $clause . "\n";
1225                $level++ if ($clause =~ m/(\{)/ && !($clause =~m/\}/));
1226        }
1227        output_declaration($declaration_name,
1228                           'struct',
1229                           {'struct' => $declaration_name,
1230                            'module' => $modulename,
1231                            'definition' => $declaration,
1232                            'parameterlist' => \@parameterlist,
1233                            'parameterdescs' => \%parameterdescs,
1234                            'parametertypes' => \%parametertypes,
1235                            'sectionlist' => \@sectionlist,
1236                            'sections' => \%sections,
1237                            'purpose' => $declaration_purpose,
1238                            'type' => $decl_type
1239                           });
1240    }
1241    else {
1242        print STDERR "${file}:$.: error: Cannot parse struct or union!\n";
1243        ++$errors;
1244    }
1245}
1246
1247
1248sub show_warnings($$) {
1249        my $functype = shift;
1250        my $name = shift;
1251
1252        return 0 if (defined($nosymbol_table{$name}));
1253
1254        return 1 if ($output_selection == OUTPUT_ALL);
1255
1256        if ($output_selection == OUTPUT_EXPORTED) {
1257                if (defined($function_table{$name})) {
1258                        return 1;
1259                } else {
1260                        return 0;
1261                }
1262        }
1263        if ($output_selection == OUTPUT_INTERNAL) {
1264                if (!($functype eq "function" && defined($function_table{$name}))) {
1265                        return 1;
1266                } else {
1267                        return 0;
1268                }
1269        }
1270        if ($output_selection == OUTPUT_INCLUDE) {
1271                if (defined($function_table{$name})) {
1272                        return 1;
1273                } else {
1274                        return 0;
1275                }
1276        }
1277        die("Please add the new output type at show_warnings()");
1278}
1279
1280sub dump_enum($$) {
1281    my $x = shift;
1282    my $file = shift;
1283    my $members;
1284
1285
1286    $x =~ s@/\*.*?\*/@@gos;     # strip comments.
1287    # strip #define macros inside enums
1288    $x =~ s@#\s*((define|ifdef)\s+|endif)[^;]*;@@gos;
1289
1290    if ($x =~ /typedef\s+enum\s*\{(.*)\}\s*(\w*)\s*;/) {
1291        $declaration_name = $2;
1292        $members = $1;
1293    } elsif ($x =~ /enum\s+(\w*)\s*\{(.*)\}/) {
1294        $declaration_name = $1;
1295        $members = $2;
1296    }
1297
1298    if ($members) {
1299        if ($identifier ne $declaration_name) {
1300            if ($identifier eq "") {
1301                print STDERR "${file}:$.: warning: wrong kernel-doc identifier on line:\n";
1302            } else {
1303                print STDERR "${file}:$.: warning: expecting prototype for enum $identifier. Prototype was for enum $declaration_name instead\n";
1304            }
1305            return;
1306        }
1307        $declaration_name = "(anonymous)" if ($declaration_name eq "");
1308
1309        my %_members;
1310
1311        $members =~ s/\s+$//;
1312
1313        foreach my $arg (split ',', $members) {
1314            $arg =~ s/^\s*(\w+).*/$1/;
1315            push @parameterlist, $arg;
1316            if (!$parameterdescs{$arg}) {
1317                $parameterdescs{$arg} = $undescribed;
1318                if (show_warnings("enum", $declaration_name)) {
1319                        print STDERR "${file}:$.: warning: Enum value '$arg' not described in enum '$declaration_name'\n";
1320                }
1321            }
1322            $_members{$arg} = 1;
1323        }
1324
1325        while (my ($k, $v) = each %parameterdescs) {
1326            if (!exists($_members{$k})) {
1327                if (show_warnings("enum", $declaration_name)) {
1328                     print STDERR "${file}:$.: warning: Excess enum value '$k' description in '$declaration_name'\n";
1329                }
1330            }
1331        }
1332
1333        output_declaration($declaration_name,
1334                           'enum',
1335                           {'enum' => $declaration_name,
1336                            'module' => $modulename,
1337                            'parameterlist' => \@parameterlist,
1338                            'parameterdescs' => \%parameterdescs,
1339                            'sectionlist' => \@sectionlist,
1340                            'sections' => \%sections,
1341                            'purpose' => $declaration_purpose
1342                           });
1343    } else {
1344        print STDERR "${file}:$.: error: Cannot parse enum!\n";
1345        ++$errors;
1346    }
1347}
1348
1349my $typedef_type = qr { ((?:\s+[\w\*]+\b){1,8})\s* }x;
1350my $typedef_ident = qr { \*?\s*(\w\S+)\s* }x;
1351my $typedef_args = qr { \s*\((.*)\); }x;
1352
1353my $typedef1 = qr { typedef$typedef_type\($typedef_ident\)$typedef_args }x;
1354my $typedef2 = qr { typedef$typedef_type$typedef_ident$typedef_args }x;
1355
1356sub dump_typedef($$) {
1357    my $x = shift;
1358    my $file = shift;
1359
1360    $x =~ s@/\*.*?\*/@@gos;     # strip comments.
1361
1362    # Parse function typedef prototypes
1363    if ($x =~ $typedef1 || $x =~ $typedef2) {
1364        $return_type = $1;
1365        $declaration_name = $2;
1366        my $args = $3;
1367        $return_type =~ s/^\s+//;
1368
1369        if ($identifier ne $declaration_name) {
1370            print STDERR "${file}:$.: warning: expecting prototype for typedef $identifier. Prototype was for typedef $declaration_name instead\n";
1371            return;
1372        }
1373
1374        create_parameterlist($args, ',', $file, $declaration_name);
1375
1376        output_declaration($declaration_name,
1377                           'function',
1378                           {'function' => $declaration_name,
1379                            'typedef' => 1,
1380                            'module' => $modulename,
1381                            'functiontype' => $return_type,
1382                            'parameterlist' => \@parameterlist,
1383                            'parameterdescs' => \%parameterdescs,
1384                            'parametertypes' => \%parametertypes,
1385                            'sectionlist' => \@sectionlist,
1386                            'sections' => \%sections,
1387                            'purpose' => $declaration_purpose
1388                           });
1389        return;
1390    }
1391
1392    while (($x =~ /\(*.\)\s*;$/) || ($x =~ /\[*.\]\s*;$/)) {
1393        $x =~ s/\(*.\)\s*;$/;/;
1394        $x =~ s/\[*.\]\s*;$/;/;
1395    }
1396
1397    if ($x =~ /typedef.*\s+(\w+)\s*;/) {
1398        $declaration_name = $1;
1399
1400        if ($identifier ne $declaration_name) {
1401            print STDERR "${file}:$.: warning: expecting prototype for typedef $identifier. Prototype was for typedef $declaration_name instead\n";
1402            return;
1403        }
1404
1405        output_declaration($declaration_name,
1406                           'typedef',
1407                           {'typedef' => $declaration_name,
1408                            'module' => $modulename,
1409                            'sectionlist' => \@sectionlist,
1410                            'sections' => \%sections,
1411                            'purpose' => $declaration_purpose
1412                           });
1413    }
1414    else {
1415        print STDERR "${file}:$.: error: Cannot parse typedef!\n";
1416        ++$errors;
1417    }
1418}
1419
1420sub save_struct_actual($) {
1421    my $actual = shift;
1422
1423    # strip all spaces from the actual param so that it looks like one string item
1424    $actual =~ s/\s*//g;
1425    $struct_actual = $struct_actual . $actual . " ";
1426}
1427
1428sub create_parameterlist($$$$) {
1429    my $args = shift;
1430    my $splitter = shift;
1431    my $file = shift;
1432    my $declaration_name = shift;
1433    my $type;
1434    my $param;
1435
1436    # temporarily replace commas inside function pointer definition
1437    my $arg_expr = qr{\([^\),]+};
1438    while ($args =~ /$arg_expr,/) {
1439        $args =~ s/($arg_expr),/$1#/g;
1440    }
1441
1442    foreach my $arg (split($splitter, $args)) {
1443        # strip comments
1444        $arg =~ s/\/\*.*\*\///;
1445        # strip leading/trailing spaces
1446        $arg =~ s/^\s*//;
1447        $arg =~ s/\s*$//;
1448        $arg =~ s/\s+/ /;
1449
1450        if ($arg =~ /^#/) {
1451            # Treat preprocessor directive as a typeless variable just to fill
1452            # corresponding data structures "correctly". Catch it later in
1453            # output_* subs.
1454            push_parameter($arg, "", "", $file);
1455        } elsif ($arg =~ m/\(.+\)\s*\(/) {
1456            # pointer-to-function
1457            $arg =~ tr/#/,/;
1458            $arg =~ m/[^\(]+\(\*?\s*([\w\[\]\.]*)\s*\)/;
1459            $param = $1;
1460            $type = $arg;
1461            $type =~ s/([^\(]+\(\*?)\s*$param/$1/;
1462            save_struct_actual($param);
1463            push_parameter($param, $type, $arg, $file, $declaration_name);
1464        } elsif ($arg) {
1465            $arg =~ s/\s*:\s*/:/g;
1466            $arg =~ s/\s*\[/\[/g;
1467
1468            my @args = split('\s*,\s*', $arg);
1469            if ($args[0] =~ m/\*/) {
1470                $args[0] =~ s/(\*+)\s*/ $1/;
1471            }
1472
1473            my @first_arg;
1474            if ($args[0] =~ /^(.*\s+)(.*?\[.*\].*)$/) {
1475                    shift @args;
1476                    push(@first_arg, split('\s+', $1));
1477                    push(@first_arg, $2);
1478            } else {
1479                    @first_arg = split('\s+', shift @args);
1480            }
1481
1482            unshift(@args, pop @first_arg);
1483            $type = join " ", @first_arg;
1484
1485            foreach $param (@args) {
1486                if ($param =~ m/^(\*+)\s*(.*)/) {
1487                    save_struct_actual($2);
1488
1489                    push_parameter($2, "$type $1", $arg, $file, $declaration_name);
1490                }
1491                elsif ($param =~ m/(.*?):(\d+)/) {
1492                    if ($type ne "") { # skip unnamed bit-fields
1493                        save_struct_actual($1);
1494                        push_parameter($1, "$type:$2", $arg, $file, $declaration_name)
1495                    }
1496                }
1497                else {
1498                    save_struct_actual($param);
1499                    push_parameter($param, $type, $arg, $file, $declaration_name);
1500                }
1501            }
1502        }
1503    }
1504}
1505
1506sub push_parameter($$$$$) {
1507        my $param = shift;
1508        my $type = shift;
1509        my $org_arg = shift;
1510        my $file = shift;
1511        my $declaration_name = shift;
1512
1513        if (($anon_struct_union == 1) && ($type eq "") &&
1514            ($param eq "}")) {
1515                return;         # ignore the ending }; from anon. struct/union
1516        }
1517
1518        $anon_struct_union = 0;
1519        $param =~ s/[\[\)].*//;
1520
1521        if ($type eq "" && $param =~ /\.\.\.$/)
1522        {
1523            if (!$param =~ /\w\.\.\.$/) {
1524              # handles unnamed variable parameters
1525              $param = "...";
1526            }
1527            elsif ($param =~ /\w\.\.\.$/) {
1528              # for named variable parameters of the form `x...`, remove the dots
1529              $param =~ s/\.\.\.$//;
1530            }
1531            if (!defined $parameterdescs{$param} || $parameterdescs{$param} eq "") {
1532                $parameterdescs{$param} = "variable arguments";
1533            }
1534        }
1535        elsif ($type eq "" && ($param eq "" or $param eq "void"))
1536        {
1537            $param="void";
1538            $parameterdescs{void} = "no arguments";
1539        }
1540        elsif ($type eq "" && ($param eq "struct" or $param eq "union"))
1541        # handle unnamed (anonymous) union or struct:
1542        {
1543                $type = $param;
1544                $param = "{unnamed_" . $param . "}";
1545                $parameterdescs{$param} = "anonymous\n";
1546                $anon_struct_union = 1;
1547        }
1548
1549        # warn if parameter has no description
1550        # (but ignore ones starting with # as these are not parameters
1551        # but inline preprocessor statements);
1552        # Note: It will also ignore void params and unnamed structs/unions
1553        if (!defined $parameterdescs{$param} && $param !~ /^#/) {
1554                $parameterdescs{$param} = $undescribed;
1555
1556                if (show_warnings($type, $declaration_name) && $param !~ /\./) {
1557                        print STDERR
1558                              "${file}:$.: warning: Function parameter or member '$param' not described in '$declaration_name'\n";
1559                        ++$warnings;
1560                }
1561        }
1562
1563        # strip spaces from $param so that it is one continuous string
1564        # on @parameterlist;
1565        # this fixes a problem where check_sections() cannot find
1566        # a parameter like "addr[6 + 2]" because it actually appears
1567        # as "addr[6", "+", "2]" on the parameter list;
1568        # but it's better to maintain the param string unchanged for output,
1569        # so just weaken the string compare in check_sections() to ignore
1570        # "[blah" in a parameter string;
1571        ###$param =~ s/\s*//g;
1572        push @parameterlist, $param;
1573        $org_arg =~ s/\s\s+/ /g;
1574        $parametertypes{$param} = $org_arg;
1575}
1576
1577sub check_sections($$$$$) {
1578        my ($file, $decl_name, $decl_type, $sectcheck, $prmscheck) = @_;
1579        my @sects = split ' ', $sectcheck;
1580        my @prms = split ' ', $prmscheck;
1581        my $err;
1582        my ($px, $sx);
1583        my $prm_clean;          # strip trailing "[array size]" and/or beginning "*"
1584
1585        foreach $sx (0 .. $#sects) {
1586                $err = 1;
1587                foreach $px (0 .. $#prms) {
1588                        $prm_clean = $prms[$px];
1589                        $prm_clean =~ s/\[.*\]//;
1590                        $prm_clean =~ s/$attribute//i;
1591                        # ignore array size in a parameter string;
1592                        # however, the original param string may contain
1593                        # spaces, e.g.:  addr[6 + 2]
1594                        # and this appears in @prms as "addr[6" since the
1595                        # parameter list is split at spaces;
1596                        # hence just ignore "[..." for the sections check;
1597                        $prm_clean =~ s/\[.*//;
1598
1599                        ##$prm_clean =~ s/^\**//;
1600                        if ($prm_clean eq $sects[$sx]) {
1601                                $err = 0;
1602                                last;
1603                        }
1604                }
1605                if ($err) {
1606                        if ($decl_type eq "function") {
1607                                print STDERR "${file}:$.: warning: " .
1608                                        "Excess function parameter " .
1609                                        "'$sects[$sx]' " .
1610                                        "description in '$decl_name'\n";
1611                                ++$warnings;
1612                        }
1613                }
1614        }
1615}
1616
1617##
1618# Checks the section describing the return value of a function.
1619sub check_return_section {
1620        my $file = shift;
1621        my $declaration_name = shift;
1622        my $return_type = shift;
1623
1624        # Ignore an empty return type (It's a macro)
1625        # Ignore functions with a "void" return type. (But don't ignore "void *")
1626        if (($return_type eq "") || ($return_type =~ /void\s*\w*\s*$/)) {
1627                return;
1628        }
1629
1630        if (!defined($sections{$section_return}) ||
1631            $sections{$section_return} eq "") {
1632                print STDERR "${file}:$.: warning: " .
1633                        "No description found for return value of " .
1634                        "'$declaration_name'\n";
1635                ++$warnings;
1636        }
1637}
1638
1639##
1640# takes a function prototype and the name of the current file being
1641# processed and spits out all the details stored in the global
1642# arrays/hashes.
1643sub dump_function($$) {
1644    my $prototype = shift;
1645    my $file = shift;
1646    my $noret = 0;
1647
1648    print_lineno($new_start_line);
1649
1650    $prototype =~ s/^static +//;
1651    $prototype =~ s/^extern +//;
1652    $prototype =~ s/^asmlinkage +//;
1653    $prototype =~ s/^inline +//;
1654    $prototype =~ s/^__inline__ +//;
1655    $prototype =~ s/^__inline +//;
1656    $prototype =~ s/^__always_inline +//;
1657    $prototype =~ s/^noinline +//;
1658    $prototype =~ s/__init +//;
1659    $prototype =~ s/__init_or_module +//;
1660    $prototype =~ s/__deprecated +//;
1661    $prototype =~ s/__flatten +//;
1662    $prototype =~ s/__meminit +//;
1663    $prototype =~ s/__must_check +//;
1664    $prototype =~ s/__weak +//;
1665    $prototype =~ s/__sched +//;
1666    $prototype =~ s/__printf\s*\(\s*\d*\s*,\s*\d*\s*\) +//;
1667    $prototype =~ s/__alloc_size\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\) +//;
1668    my $define = $prototype =~ s/^#\s*define\s+//; #ak added
1669    $prototype =~ s/__attribute_const__ +//;
1670    $prototype =~ s/__attribute__\s*\(\(
1671            (?:
1672                 [\w\s]++          # attribute name
1673                 (?:\([^)]*+\))?   # attribute arguments
1674                 \s*+,?            # optional comma at the end
1675            )+
1676          \)\)\s+//x;
1677
1678    # Yes, this truly is vile.  We are looking for:
1679    # 1. Return type (may be nothing if we're looking at a macro)
1680    # 2. Function name
1681    # 3. Function parameters.
1682    #
1683    # All the while we have to watch out for function pointer parameters
1684    # (which IIRC is what the two sections are for), C types (these
1685    # regexps don't even start to express all the possibilities), and
1686    # so on.
1687    #
1688    # If you mess with these regexps, it's a good idea to check that
1689    # the following functions' documentation still comes out right:
1690    # - parport_register_device (function pointer parameters)
1691    # - atomic_set (macro)
1692    # - pci_match_device, __copy_to_user (long return type)
1693    my $name = qr{[a-zA-Z0-9_~:]+};
1694    my $prototype_end1 = qr{[^\(]*};
1695    my $prototype_end2 = qr{[^\{]*};
1696    my $prototype_end = qr{\(($prototype_end1|$prototype_end2)\)};
1697    my $type1 = qr{[\w\s]+};
1698    my $type2 = qr{$type1\*+};
1699
1700    if ($define && $prototype =~ m/^()($name)\s+/) {
1701        # This is an object-like macro, it has no return type and no parameter
1702        # list.
1703        # Function-like macros are not allowed to have spaces between
1704        # declaration_name and opening parenthesis (notice the \s+).
1705        $return_type = $1;
1706        $declaration_name = $2;
1707        $noret = 1;
1708    } elsif ($prototype =~ m/^()($name)\s*$prototype_end/ ||
1709        $prototype =~ m/^($type1)\s+($name)\s*$prototype_end/ ||
1710        $prototype =~ m/^($type2+)\s*($name)\s*$prototype_end/)  {
1711        $return_type = $1;
1712        $declaration_name = $2;
1713        my $args = $3;
1714
1715        create_parameterlist($args, ',', $file, $declaration_name);
1716    } else {
1717        print STDERR "${file}:$.: warning: cannot understand function prototype: '$prototype'\n";
1718        return;
1719    }
1720
1721    if ($identifier ne $declaration_name) {
1722        print STDERR "${file}:$.: warning: expecting prototype for $identifier(). Prototype was for $declaration_name() instead\n";
1723        return;
1724    }
1725
1726    my $prms = join " ", @parameterlist;
1727    check_sections($file, $declaration_name, "function", $sectcheck, $prms);
1728
1729    # This check emits a lot of warnings at the moment, because many
1730    # functions don't have a 'Return' doc section. So until the number
1731    # of warnings goes sufficiently down, the check is only performed in
1732    # verbose mode.
1733    # TODO: always perform the check.
1734    if ($verbose && !$noret) {
1735            check_return_section($file, $declaration_name, $return_type);
1736    }
1737
1738    # The function parser can be called with a typedef parameter.
1739    # Handle it.
1740    if ($return_type =~ /typedef/) {
1741        output_declaration($declaration_name,
1742                           'function',
1743                           {'function' => $declaration_name,
1744                            'typedef' => 1,
1745                            'module' => $modulename,
1746                            'functiontype' => $return_type,
1747                            'parameterlist' => \@parameterlist,
1748                            'parameterdescs' => \%parameterdescs,
1749                            'parametertypes' => \%parametertypes,
1750                            'sectionlist' => \@sectionlist,
1751                            'sections' => \%sections,
1752                            'purpose' => $declaration_purpose
1753                           });
1754    } else {
1755        output_declaration($declaration_name,
1756                           'function',
1757                           {'function' => $declaration_name,
1758                            'module' => $modulename,
1759                            'functiontype' => $return_type,
1760                            'parameterlist' => \@parameterlist,
1761                            'parameterdescs' => \%parameterdescs,
1762                            'parametertypes' => \%parametertypes,
1763                            'sectionlist' => \@sectionlist,
1764                            'sections' => \%sections,
1765                            'purpose' => $declaration_purpose
1766                           });
1767    }
1768}
1769
1770sub reset_state {
1771    $function = "";
1772    %parameterdescs = ();
1773    %parametertypes = ();
1774    @parameterlist = ();
1775    %sections = ();
1776    @sectionlist = ();
1777    $sectcheck = "";
1778    $struct_actual = "";
1779    $prototype = "";
1780
1781    $state = STATE_NORMAL;
1782    $inline_doc_state = STATE_INLINE_NA;
1783}
1784
1785sub tracepoint_munge($) {
1786        my $file = shift;
1787        my $tracepointname = 0;
1788        my $tracepointargs = 0;
1789
1790        if ($prototype =~ m/TRACE_EVENT\((.*?),/) {
1791                $tracepointname = $1;
1792        }
1793        if ($prototype =~ m/DEFINE_SINGLE_EVENT\((.*?),/) {
1794                $tracepointname = $1;
1795        }
1796        if ($prototype =~ m/DEFINE_EVENT\((.*?),(.*?),/) {
1797                $tracepointname = $2;
1798        }
1799        $tracepointname =~ s/^\s+//; #strip leading whitespace
1800        if ($prototype =~ m/TP_PROTO\((.*?)\)/) {
1801                $tracepointargs = $1;
1802        }
1803        if (($tracepointname eq 0) || ($tracepointargs eq 0)) {
1804                print STDERR "${file}:$.: warning: Unrecognized tracepoint format: \n".
1805                             "$prototype\n";
1806        } else {
1807                $prototype = "static inline void trace_$tracepointname($tracepointargs)";
1808                $identifier = "trace_$identifier";
1809        }
1810}
1811
1812sub syscall_munge() {
1813        my $void = 0;
1814
1815        $prototype =~ s@[\r\n]+@ @gos; # strip newlines/CR's
1816##      if ($prototype =~ m/SYSCALL_DEFINE0\s*\(\s*(a-zA-Z0-9_)*\s*\)/) {
1817        if ($prototype =~ m/SYSCALL_DEFINE0/) {
1818                $void = 1;
1819##              $prototype = "long sys_$1(void)";
1820        }
1821
1822        $prototype =~ s/SYSCALL_DEFINE.*\(/long sys_/; # fix return type & func name
1823        if ($prototype =~ m/long (sys_.*?),/) {
1824                $prototype =~ s/,/\(/;
1825        } elsif ($void) {
1826                $prototype =~ s/\)/\(void\)/;
1827        }
1828
1829        # now delete all of the odd-number commas in $prototype
1830        # so that arg types & arg names don't have a comma between them
1831        my $count = 0;
1832        my $len = length($prototype);
1833        if ($void) {
1834                $len = 0;       # skip the for-loop
1835        }
1836        for (my $ix = 0; $ix < $len; $ix++) {
1837                if (substr($prototype, $ix, 1) eq ',') {
1838                        $count++;
1839                        if ($count % 2 == 1) {
1840                                substr($prototype, $ix, 1) = ' ';
1841                        }
1842                }
1843        }
1844}
1845
1846sub process_proto_function($$) {
1847    my $x = shift;
1848    my $file = shift;
1849
1850    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line
1851
1852    if ($x =~ m#\s*/\*\s+MACDOC\s*#io || ($x =~ /^#/ && $x !~ /^#\s*define/)) {
1853        # do nothing
1854    }
1855    elsif ($x =~ /([^\{]*)/) {
1856        $prototype .= $1;
1857    }
1858
1859    if (($x =~ /\{/) || ($x =~ /\#\s*define/) || ($x =~ /;/)) {
1860        $prototype =~ s@/\*.*?\*/@@gos; # strip comments.
1861        $prototype =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
1862        $prototype =~ s@^\s+@@gos; # strip leading spaces
1863
1864         # Handle prototypes for function pointers like:
1865         # int (*pcs_config)(struct foo)
1866        $prototype =~ s@^(\S+\s+)\(\s*\*(\S+)\)@$1$2@gos;
1867
1868        if ($prototype =~ /SYSCALL_DEFINE/) {
1869                syscall_munge();
1870        }
1871        if ($prototype =~ /TRACE_EVENT/ || $prototype =~ /DEFINE_EVENT/ ||
1872            $prototype =~ /DEFINE_SINGLE_EVENT/)
1873        {
1874                tracepoint_munge($file);
1875        }
1876        dump_function($prototype, $file);
1877        reset_state();
1878    }
1879}
1880
1881sub process_proto_type($$) {
1882    my $x = shift;
1883    my $file = shift;
1884
1885    $x =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
1886    $x =~ s@^\s+@@gos; # strip leading spaces
1887    $x =~ s@\s+$@@gos; # strip trailing spaces
1888    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line
1889
1890    if ($x =~ /^#/) {
1891        # To distinguish preprocessor directive from regular declaration later.
1892        $x .= ";";
1893    }
1894
1895    while (1) {
1896        if ( $x =~ /([^\{\};]*)([\{\};])(.*)/ ) {
1897            if( length $prototype ) {
1898                $prototype .= " "
1899            }
1900            $prototype .= $1 . $2;
1901            ($2 eq '{') && $brcount++;
1902            ($2 eq '}') && $brcount--;
1903            if (($2 eq ';') && ($brcount == 0)) {
1904                dump_declaration($prototype, $file);
1905                reset_state();
1906                last;
1907            }
1908            $x = $3;
1909        } else {
1910            $prototype .= $x;
1911            last;
1912        }
1913    }
1914}
1915
1916
1917sub map_filename($) {
1918    my $file;
1919    my ($orig_file) = @_;
1920
1921    if (defined($ENV{'SRCTREE'})) {
1922        $file = "$ENV{'SRCTREE'}" . "/" . $orig_file;
1923    } else {
1924        $file = $orig_file;
1925    }
1926
1927    if (defined($source_map{$file})) {
1928        $file = $source_map{$file};
1929    }
1930
1931    return $file;
1932}
1933
1934sub process_export_file($) {
1935    my ($orig_file) = @_;
1936    my $file = map_filename($orig_file);
1937
1938    if (!open(IN,"<$file")) {
1939        print STDERR "Error: Cannot open file $file\n";
1940        ++$errors;
1941        return;
1942    }
1943
1944    while (<IN>) {
1945        if (/$export_symbol/) {
1946            next if (defined($nosymbol_table{$2}));
1947            $function_table{$2} = 1;
1948        }
1949    }
1950
1951    close(IN);
1952}
1953
1954#
1955# Parsers for the various processing states.
1956#
1957# STATE_NORMAL: looking for the /** to begin everything.
1958#
1959sub process_normal() {
1960    if (/$doc_start/o) {
1961        $state = STATE_NAME;    # next line is always the function name
1962        $in_doc_sect = 0;
1963        $declaration_start_line = $. + 1;
1964    }
1965}
1966
1967#
1968# STATE_NAME: Looking for the "name - description" line
1969#
1970sub process_name($$) {
1971    my $file = shift;
1972    my $descr;
1973
1974    if (/$doc_block/o) {
1975        $state = STATE_DOCBLOCK;
1976        $contents = "";
1977        $new_start_line = $.;
1978
1979        if ( $1 eq "" ) {
1980            $section = $section_intro;
1981        } else {
1982            $section = $1;
1983        }
1984    } elsif (/$doc_decl/o) {
1985        $identifier = $1;
1986        my $is_kernel_comment = 0;
1987        my $decl_start = qr{$doc_com};
1988        # test for pointer declaration type, foo * bar() - desc
1989        my $fn_type = qr{\w+\s*\*\s*}; 
1990        my $parenthesis = qr{\(\w*\)};
1991        my $decl_end = qr{[-:].*};
1992        if (/^$decl_start([\w\s]+?)$parenthesis?\s*$decl_end?$/) {
1993            $identifier = $1;
1994        }
1995        if ($identifier =~ m/^(struct|union|enum|typedef)\b\s*(\S*)/) {
1996            $decl_type = $1;
1997            $identifier = $2;
1998            $is_kernel_comment = 1;
1999        }
2000        # Look for foo() or static void foo() - description; or misspelt
2001        # identifier
2002        elsif (/^$decl_start$fn_type?(\w+)\s*$parenthesis?\s*$decl_end?$/ ||
2003            /^$decl_start$fn_type?(\w+.*)$parenthesis?\s*$decl_end$/) {
2004            $identifier = $1;
2005            $decl_type = 'function';
2006            $identifier =~ s/^define\s+//;
2007            $is_kernel_comment = 1;
2008        }
2009        $identifier =~ s/\s+$//;
2010
2011        $state = STATE_BODY;
2012        # if there's no @param blocks need to set up default section
2013        # here
2014        $contents = "";
2015        $section = $section_default;
2016        $new_start_line = $. + 1;
2017        if (/[-:](.*)/) {
2018            # strip leading/trailing/multiple spaces
2019            $descr= $1;
2020            $descr =~ s/^\s*//;
2021            $descr =~ s/\s*$//;
2022            $descr =~ s/\s+/ /g;
2023            $declaration_purpose = $descr;
2024            $state = STATE_BODY_MAYBE;
2025        } else {
2026            $declaration_purpose = "";
2027        }
2028
2029        if (!$is_kernel_comment) {
2030            print STDERR "${file}:$.: warning: This comment starts with '/**', but isn't a kernel-doc comment. Refer Documentation/doc-guide/kernel-doc.rst\n";
2031            print STDERR $_;
2032            ++$warnings;
2033            $state = STATE_NORMAL;
2034        }
2035
2036        if (($declaration_purpose eq "") && $verbose) {
2037            print STDERR "${file}:$.: warning: missing initial short description on line:\n";
2038            print STDERR $_;
2039            ++$warnings;
2040        }
2041
2042        if ($identifier eq "" && $decl_type ne "enum") {
2043            print STDERR "${file}:$.: warning: wrong kernel-doc identifier on line:\n";
2044            print STDERR $_;
2045            ++$warnings;
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        print STDERR "${file}:$.: warning: Cannot understand $_ on line $.",
2054            " - I thought it was a doc line\n";
2055        ++$warnings;
2056        $state = STATE_NORMAL;
2057    }
2058}
2059
2060
2061#
2062# STATE_BODY and STATE_BODY_MAYBE: the bulk of a kerneldoc comment.
2063#
2064sub process_body($$) {
2065    my $file = shift;
2066
2067    # Until all named variable macro parameters are
2068    # documented using the bare name (`x`) rather than with
2069    # dots (`x...`), strip the dots:
2070    if ($section =~ /\w\.\.\.$/) {
2071        $section =~ s/\.\.\.$//;
2072
2073        if ($verbose) {
2074            print STDERR "${file}:$.: warning: Variable macro arguments should be documented without dots\n";
2075            ++$warnings;
2076        }
2077    }
2078
2079    if ($state == STATE_BODY_WITH_BLANK_LINE && /^\s*\*\s?\S/) {
2080        dump_section($file, $section, $contents);
2081        $section = $section_default;
2082        $new_start_line = $.;
2083        $contents = "";
2084    }
2085
2086    if (/$doc_sect/i) { # case insensitive for supported section names
2087        $newsection = $1;
2088        $newcontents = $2;
2089
2090        # map the supported section names to the canonical names
2091        if ($newsection =~ m/^description$/i) {
2092            $newsection = $section_default;
2093        } elsif ($newsection =~ m/^context$/i) {
2094            $newsection = $section_context;
2095        } elsif ($newsection =~ m/^returns?$/i) {
2096            $newsection = $section_return;
2097        } elsif ($newsection =~ m/^\@return$/) {
2098            # special: @return is a section, not a param description
2099            $newsection = $section_return;
2100        }
2101
2102        if (($contents ne "") && ($contents ne "\n")) {
2103            if (!$in_doc_sect && $verbose) {
2104                print STDERR "${file}:$.: warning: contents before sections\n";
2105                ++$warnings;
2106            }
2107            dump_section($file, $section, $contents);
2108            $section = $section_default;
2109        }
2110
2111        $in_doc_sect = 1;
2112        $state = STATE_BODY;
2113        $contents = $newcontents;
2114        $new_start_line = $.;
2115        while (substr($contents, 0, 1) eq " ") {
2116            $contents = substr($contents, 1);
2117        }
2118        if ($contents ne "") {
2119            $contents .= "\n";
2120        }
2121        $section = $newsection;
2122        $leading_space = undef;
2123    } elsif (/$doc_end/) {
2124        if (($contents ne "") && ($contents ne "\n")) {
2125            dump_section($file, $section, $contents);
2126            $section = $section_default;
2127            $contents = "";
2128        }
2129        # look for doc_com + <text> + doc_end:
2130        if ($_ =~ m'\s*\*\s*[a-zA-Z_0-9:\.]+\*/') {
2131            print STDERR "${file}:$.: warning: suspicious ending line: $_";
2132            ++$warnings;
2133        }
2134
2135        $prototype = "";
2136        $state = STATE_PROTO;
2137        $brcount = 0;
2138        $new_start_line = $. + 1;
2139    } elsif (/$doc_content/) {
2140        if ($1 eq "") {
2141            if ($section eq $section_context) {
2142                dump_section($file, $section, $contents);
2143                $section = $section_default;
2144                $contents = "";
2145                $new_start_line = $.;
2146                $state = STATE_BODY;
2147            } else {
2148                if ($section ne $section_default) {
2149                    $state = STATE_BODY_WITH_BLANK_LINE;
2150                } else {
2151                    $state = STATE_BODY;
2152                }
2153                $contents .= "\n";
2154            }
2155        } elsif ($state == STATE_BODY_MAYBE) {
2156            # Continued declaration purpose
2157            chomp($declaration_purpose);
2158            $declaration_purpose .= " " . $1;
2159            $declaration_purpose =~ s/\s+/ /g;
2160        } else {
2161            my $cont = $1;
2162            if ($section =~ m/^@/ || $section eq $section_context) {
2163                if (!defined $leading_space) {
2164                    if ($cont =~ m/^(\s+)/) {
2165                        $leading_space = $1;
2166                    } else {
2167                        $leading_space = "";
2168                    }
2169                }
2170                $cont =~ s/^$leading_space//;
2171            }
2172            $contents .= $cont . "\n";
2173        }
2174    } else {
2175        # i dont know - bad line?  ignore.
2176        print STDERR "${file}:$.: warning: bad line: $_";
2177        ++$warnings;
2178    }
2179}
2180
2181
2182#
2183# STATE_PROTO: reading a function/whatever prototype.
2184#
2185sub process_proto($$) {
2186    my $file = shift;
2187
2188    if (/$doc_inline_oneline/) {
2189        $section = $1;
2190        $contents = $2;
2191        if ($contents ne "") {
2192            $contents .= "\n";
2193            dump_section($file, $section, $contents);
2194            $section = $section_default;
2195            $contents = "";
2196        }
2197    } elsif (/$doc_inline_start/) {
2198        $state = STATE_INLINE;
2199        $inline_doc_state = STATE_INLINE_NAME;
2200    } elsif ($decl_type eq 'function') {
2201        process_proto_function($_, $file);
2202    } else {
2203        process_proto_type($_, $file);
2204    }
2205}
2206
2207#
2208# STATE_DOCBLOCK: within a DOC: block.
2209#
2210sub process_docblock($$) {
2211    my $file = shift;
2212
2213    if (/$doc_end/) {
2214        dump_doc_section($file, $section, $contents);
2215        $section = $section_default;
2216        $contents = "";
2217        $function = "";
2218        %parameterdescs = ();
2219        %parametertypes = ();
2220        @parameterlist = ();
2221        %sections = ();
2222        @sectionlist = ();
2223        $prototype = "";
2224        $state = STATE_NORMAL;
2225    } elsif (/$doc_content/) {
2226        if ( $1 eq "" ) {
2227            $contents .= $blankline;
2228        } else {
2229            $contents .= $1 . "\n";
2230        }
2231    }
2232}
2233
2234#
2235# STATE_INLINE: docbook comments within a prototype.
2236#
2237sub process_inline($$) {
2238    my $file = shift;
2239
2240    # First line (state 1) needs to be a @parameter
2241    if ($inline_doc_state == STATE_INLINE_NAME && /$doc_inline_sect/o) {
2242        $section = $1;
2243        $contents = $2;
2244        $new_start_line = $.;
2245        if ($contents ne "") {
2246            while (substr($contents, 0, 1) eq " ") {
2247                $contents = substr($contents, 1);
2248            }
2249            $contents .= "\n";
2250        }
2251        $inline_doc_state = STATE_INLINE_TEXT;
2252        # Documentation block end */
2253    } elsif (/$doc_inline_end/) {
2254        if (($contents ne "") && ($contents ne "\n")) {
2255            dump_section($file, $section, $contents);
2256            $section = $section_default;
2257            $contents = "";
2258        }
2259        $state = STATE_PROTO;
2260        $inline_doc_state = STATE_INLINE_NA;
2261        # Regular text
2262    } elsif (/$doc_content/) {
2263        if ($inline_doc_state == STATE_INLINE_TEXT) {
2264            $contents .= $1 . "\n";
2265            # nuke leading blank lines
2266            if ($contents =~ /^\s*$/) {
2267                $contents = "";
2268            }
2269        } elsif ($inline_doc_state == STATE_INLINE_NAME) {
2270            $inline_doc_state = STATE_INLINE_ERROR;
2271            print STDERR "${file}:$.: warning: ";
2272            print STDERR "Incorrect use of kernel-doc format: $_";
2273            ++$warnings;
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            print STDERR "${file}:1: warning: '$_' not found\n"
2323                for keys %function_table;
2324        }
2325        else {
2326            print STDERR "${file}:1: warning: 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