summaryrefslogtreecommitdiffstats
path: root/src/usr/errl/parser/scanforsrcs.pl
blob: 6c187a84831724c7262786faf10a0461579897bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
#!/usr/bin/perl
#  IBM_PROLOG_BEGIN_TAG
#  This is an automatically generated prolog.
#
#  $Source: src/usr/errl/parser/scanforsrcs.pl $
#
#  IBM CONFIDENTIAL
#
#  COPYRIGHT International Business Machines Corp. 2011
#
#  p1
#
#  Object Code Only (OCO) source materials
#  Licensed Internal Code Source Materials
#  IBM HostBoot Licensed Internal Code
#
#  The source code for this program is not published or other-
#  wise divested of its trade secrets, irrespective of what has
#  been deposited with the U.S. Copyright Office.
#
#  Origin: 30
#
#  IBM_PROLOG_END
#
# Purpose: Scan the hostboot source code to extract the doxygen like tags
#          and generate a header file for the error log parser to include.
#

use strict;
use File::Find ();
use Time::localtime;
use File::Path;

# Vairables
my $DEBUG = 0;
my $component = "VOID";
my $sandBase = $ENV{HOSTBOOTROOT};

my $arg;
my %Comps;
my $wordn = "userdata1";
my $wordnd = 1;
my $NA = 1;
my $fh;

my $argOutput = "";
my $output = "";

# Arrays
my @compHeaders;
my %namespaceList;
my @reasonCodeFiles;

while( $ARGV = shift )
{
    if( $ARGV =~ m/-b/ )
    {
        $sandBase = shift;
    }
    elsif( $ARGV =~ m/-o/i )
    {
        $argOutput = shift;
    }
    elsif( $ARGV =~ m/-h/i )
    {
        usage();
    }
    elsif( $ARGV =~ m/-d/i )
    {
        $DEBUG = 1;
    }
    else
    {
        usage();
    }
}

# Variables depending on input parameters
if( $argOutput eq "" )
{
    $output = "$sandBase/obj/genfiles";
}
else
{
    $output = $argOutput; 
}
my $comp_id = "$sandBase/src/include/usr/hbotcompid.H";

# Setup all the different paths that need to be searched
my $sourcebasePath = $sandBase."/src/usr";
my $includePath = $sandBase."/src/include/usr";
my $genfilesPath = $sandBase."/obj/genfiles";

# Get the listing of components
opendir my( $dir ), $sourcebasePath or die "Couldn't open directory $sourcebasePath, $!";
my @components = readdir $dir;
closedir $dir;

my %sourcebase;
my %sourcebaseInc;
my %sourcebaseGenfiles;

my @fileList;

################################################################
# Debug Printing
################################################################
debugMsg( "Comp id file: $comp_id" );
debugMsg( "Source Base Path: $sourcebasePath" );
debugMsg( "Sandbox Base Dir: $sandBase" );
debugMsg( "Output Dir: $output" );
################################################################

foreach( @components )
{
    # Both src/usr directories as well as src/include/usr directories
    # are done here to make sure they line up with the same "component"
    # generated files will be done after this loop under the "genfiles"
    # component name.
    $component = $_;
    debugMsg( "Component: $component" );

    # Print components for debug.
    my $compDir = "$sourcebasePath/$component";
    debugMsg( "Component Dir: $compDir" );

    # Skip files and dirs . and ..
    if( -d "$compDir" )
    {
        if( ($component eq ".") ||
            ($component eq ".." ) ||
            ($component eq "example" ) )
        {
            debugMsg( "exiting..." );
            next;
        }
    }
    else
    {
        debugMsg( "exiting-->" );
        next;
    }

    # Check to be sure the main src directory is available
    if( -e "$compDir" )
    {
        # Get a list of files to be scanned
        %sourcebase = getFiles( $compDir );
    }
    else
    {
        # Exit since the path of the user code wasn't found.
        die( "\nERROR!  Path ($compDir) does not exist.  Cannot run!\n" );
    }

    # Get the associated component include files
    my $incCompDir = "$includePath/$component";
    debugMsg( "Include Path: $incCompDir" );

    # Skip files and dirs . and ..
    if( -d "$incCompDir" )
    {
        # Do nothing, we want the directories
    }
    else
    {
        debugMsg( "exiting-->" );
        next;
    }

    # if include dir exists, get the files
    if( -e "$incCompDir" )
    {
        # Add the include files
        %sourcebaseInc = getFiles( $incCompDir );
    }
    else
    {
        # Exit since the path of the user code wasn't found.
        die( "\nERROR!  Path ($incCompDir) does not exist. Cannot run!\n" );
    }

    # Put each file on list to be scanned
    foreach( values %sourcebase )
    {
        push( @fileList, $_ );
        debugMsg( "File: $_" );

        # Delete hash entry
        delete $sourcebase{$_};
    }

    # Put each file on list to be scanned
    foreach( values %sourcebaseInc )
    {
        push( @fileList, $_ );
        debugMsg( "File (include): $_" );

        # Delete hash entry
        delete $sourcebaseInc{$_};
    }

    foreach( @fileList )
    {
        debugMsg( "Calling extractTags for file: $_" );
        extractTags( $_, $component );
    }

    # Clear the file list so we don't reuse them
    @fileList = ();
}

# Scan the generated files and add to file list
if( -e $genfilesPath )
{
    %sourcebaseGenfiles = getFiles( $genfilesPath );
    foreach( values %sourcebaseGenfiles )
    {
        push( @fileList, $_ );
        debugMsg( "File (genfiles): $_" );
        delete $sourcebaseGenfiles{$_};
    }

    foreach( @fileList )
    {
        debugMsg( "Calling extractTags for file: $_" );
        extractTags( $_, "genfiles" );
    }
}
else
{
    die( "\nERROR! Path($genfilesPath) does not exist.  Cannot continue!\n" );
}

# Get the file open
$fh = openHeaderFile();

# Start writing the main header file that will be included by errlparser.C
startMainHeaderFile( $fh );

# Write each case statement for printing
foreach my $key (sort(keys(%Comps)))
{
    writePrintStatement( $fh, $key, \@{$Comps{$key}} );
}

# Finish writing the header
finishMainHeaderFile( $fh );

exit 0;

#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#  End of Main program
#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

################################################################################
#
# Print the Usage message
#
################################################################################

sub usage
{
    print "Usage: $0 < -b base > <-d> < -o output dir >\"\n";
    print "\n";
    print "-b:     base directory ( default is pwd )\n";
    print "-o:     Used as the output directory where header file is dropped\n";
    print "-d      Enable Debug messages.\n";
    print "-h      Display usage message.\n";
    print "\n\n";
    exit 1;
}


################################################################################
#
# Print debug messages if $DEBUG is enabled.
#
################################################################################

sub debugMsg
{
    my ($msg) = @_;
    if( $DEBUG )
    {
        print "DEBUG: $msg\n";
    }
}


################################################################################
#
# Extracts each tag and description from each entry for the given file.
#
################################################################################

sub extractTags
{
    my $data;
    my ($file, $comp) = @_;
    debugMsg( "extractTags: Component: $comp" );
    local *FH;

    debugMsg( "Processing: $file" );

    open(FH, "$file") or die("Cannot open: $file: $!");
    read(FH, $data, -s FH) or die("Error reading $file: $!");
    close FH;

    # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    # Capture everything from opening '/*@' to end of tags '*/'
    #
    # Example:
    #   /*@
    #     * @errortype
    #     * @reasoncode     I2C_INVALID_OP_TYPE
    #     * @severity       ERRL_SEV_UNRECOVERABLE
    #     * @moduleid       I2C_PERFORM_OP
    #     * @userdata1      i_opType
    #     * @userdata2      addr
    #     * @devdesc        Invalid Operation type.
    #     */
    # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    while ($data =~ /\/\*\@((.|\n)+?)\*\//mgo )
    {
        debugMsg( "Found New Error Tag!" );

        my $text = $1;
        debugMsg( "Text1: $text" );
        my %hash = $text =~ /\@(\S+)(?:\s+|\.+)\b(.+?)$/gm;
        my $tmp;
        my $tmpKey;

        foreach my $key (sort keys %hash)
        {
            $tmpKey = AddSlashes( $key );
            debugMsg( "Key: $tmpKey" );
            # Extract multi-line string
            $text =~ /\@$tmpKey(?:\s+|\.+)(.+?)(?:\@|$).*/s;
            debugMsg( "Text3: $text" );
            $tmp = $1;
            debugMsg( "Tmp: $tmp" );
            $tmp =~ s/\s*\*\s*/ \n/gm;
            debugMsg( "Tmp again: $tmp" );
            $tmp = stripWhitespace( $tmp );
            debugMsg( "Tmp trimmed: $tmp" );
            $hash{$key} = $tmp;
	    debugMsg( "Assigning '$key' = '$tmp'" );
        }

        push @{$Comps{$comp}}, \%hash;
    }
}


################################################################################
#
# getFiles - find *.H or *.C files
# This recursively searches the input directory passed in for all C/H files.
#
################################################################################

sub getFiles
{
    my ($l_input_dir) = @_;
    my @dir_entry;
    my %l_input_files;
    local *DH;

    debugMsg( "Getting Files for dir: $l_input_dir" );

    # Open the directory and read all entry names.
    opendir(DH, $l_input_dir) or die("Cannot open $l_input_dir: $!");
    # skip the dots
    @dir_entry = grep { !/^\./ } readdir(DH);
    closedir(DH);
    while (@dir_entry)
    {
        my $l_entry = shift(@dir_entry);
        my $full_path = "$l_input_dir/$l_entry";

        debugMsg( "getFiles: Full Path: $full_path" );

        if ($l_entry =~ /\.[H|C]$/)
        {
            $l_input_files{$l_entry} = $full_path;
            debugMsg( "getFiles: Adding file: $full_path" );
        }
        elsif (-d $full_path)
        {
            # recursive here
            my %local_hash = getFiles($full_path);
            my @keys = keys(%local_hash);

            foreach(@keys)
            {
                $l_input_files{$_} = $local_hash{$_};
            }
        }
    }
    return(%l_input_files);
}


################################################################################
#
# Add escape characters to strings
#
################################################################################

sub AddSlashes 
{
    my ($text) = @_;
    ## Make sure to do the backslash first!
    $text =~ s/\\/\\\\/g;
    $text =~ s/'/\\'/g;
    $text =~ s/"/\\"/g;
    $text =~ s/\\0/\\\\0/g;

    $text =~ s/\[/\\[/g;
    $text =~ s/\]/\\]/g;
    return $text;
}


################################################################################
#
# Strip whitespace from beginning/end of string
#
################################################################################

sub stripWhitespace
{
    my ($text) = @_;

    $text =~ s/^\s+//;  # strip leading spaces
    $text =~ s/\s+$//;  # strip trailing spaces

    return $text;
}

################################################################################
#
# Look for the components reasoncode file and include it
#
################################################################################

sub includeReasonCodes
{
    my ( $fh,$incPath,$level ) = @_;

    debugMsg( "includeReasonCodes incpath: $incPath" );
    debugMsg( "includeReasonCodes level: $level" );

    my @incDirs = glob( $incPath );
    my $incFileName = "";

    foreach my $file( @incDirs )
    {
        debugMsg( "includeReasonCodes file: $file" );
        my @allDirs = split( '/', $file );

        if( $file =~ m/reasoncodes/i )
        {
            for( my $count = 0; $count < $level; $count++ )
            {
                my $tmpTxt = pop @allDirs;

                if( $incFileName ne "" )
                {
                    $incFileName = $tmpTxt . "/$incFileName";
                }
                else
                {
                    $incFileName = $tmpTxt;
                }
            }
            debugMsg( "ReasonCode file: $file" );
            debugMsg( "Include string: $incFileName" );

            print $fh "#include <$incFileName>\n";

            # Find the namespace of the reason codes
            findNameSpace( $file );

            # Clear out incFileName, in case there are 2 reason code files
            # in the same directory
            $incFileName = "";
        }
        elsif( -d $file )
        {
            debugMsg( "includeReasonCodes recursion" );
            # Recursion is done here.
            includeReasonCodes( $fh, $file."/*", ($level+1) );
        }
    }
}


################################################################################
#
# Build the main header file that errlparser.C will use to include all of
# the generated header files.
#
################################################################################

sub startMainHeaderFile
{
    my ($fh) = @_;
    my $timestamp = ctime();
    my $imageId = getImageId();

    print $fh <<EOF;
/*
 * Automatically generated by src/usr/errl/parser/scanforsrcs.pl
 *
 * TimeStamp:   $timestamp
 * Image Id:    $imageId
 *
*/


/*****************************************************************************/
// I n c l u d e s
/*****************************************************************************/
EOF

    # Add the includes - start in src/include/usr
    my $startDir = $sandBase."/src/include/usr/*";
    includeReasonCodes( $fh, $startDir, 1 );

    # Also include reason codes from generated files
    $startDir = $sandBase."/obj/genfiles";
    includeReasonCodes( $fh, $startDir, 0 );

    print $fh <<EOF;


/*****************************************************************************/
// N a m e s p a c e s
/*****************************************************************************/
EOF

    foreach( values %namespaceList )
    {
        my $namespace = $_;
        print $fh "using namespace $namespace;\n"
    }

    print $fh <<EOF;


static void printErrorTags (  ErrlUsrParser & i_parser,
                              uint64_t i_src,
                              uint64_t i_modId )
{
    uint64_t error = (i_src << 8) | i_modId;

    switch( error )
    {
EOF
}


################################################################################
#
# Finish writing main header file
#
################################################################################

sub finishMainHeaderFile
{
    my ($fh) = @_;

    print $fh <<EOF;

        default:
            uint32_t src = i_src & 0xFFFFFFFF;
            uint32_t modId = i_modId & 0xFFFFFFFF;
            printf( "\\nThere was not a valid Errorlog tag found for the given error combination!\\n" );
            printf( "   Reason: 0x%04x, Module Id: 0x%02x\\n\\n", src, modId );
            break;

    };
}
EOF
}


################################################################################
#
# Open generated header file
#
################################################################################

sub openHeaderFile
{
    my $filename = "$output/hostBootSrcParse.H";
    my $fh;

    if (! -e $output)
    {
        debugMsg( "Creating directory $output" );
        eval { mkpath($output) };

        if ($@)
        {
            die("Couldn't create $output: $@");
        }
    }

    if (-e $filename)
    {
        chmod(0777, $filename);
    }

    open($fh, ">$filename") or die("Cannot open $filename: $!");
    return $fh;
}


################################################################################
#
# Write the print statements to the header
#
################################################################################

sub writePrintStatement
{
    my ($fh, $compName, $aref) = @_;
    my $wordstart = "userdata1";
    my $modId;
    my $reasonCode;
    my $caseValue;
    my $line;

    my %caseHash = ();

    foreach my $href ( @$aref )
    {
        # Get the ModId and Reasoncode tags
        foreach my $tag ( sort keys %$href )
        {
            $href->{$tag} =~ s/\"/\\\"/g;
            my @lines = split /^/, $href->{$tag};

            if( scalar( @lines ) > 1 )
            {
                foreach $line( @lines )
                {
                    $line =~ s/\n//g;
                }
            }
            else
            {
                $line = $href->{$tag};
                $line =~ s/\n//g;
            }

            $line = stripWhitespace( $line );
            if( "moduleid" eq $tag )
            {
                $modId = $line;
            }
            elsif( "reasoncode" eq $tag )
            {
                $reasonCode = $line;
            }
        }
        debugMsg( "Comp Name: $compName" );
        debugMsg( "Module Id: $modId" );
        debugMsg( "Reason Code: $reasonCode" );

        # If we've got a duplicate Module Id/Reason code go, on to the
        # next one.  We can't have duplicates, and its been asked that
        # we don't have compile errors because of it.
        if( "$modId.$reasonCode" eq $caseHash{ $compName } )
        {
            debugMsg( "Hash exists, skip subsequent." );

            # Print a warning message
            print "\n#################################################################\n";
            print "  WARNING - Duplicate hash found for:\n";
            print "      component     $compName\n";
            print "      module id     $modId\n";
            print "      reason code   $reasonCode\n";
            print "#################################################################\n";
            next;
        }
        else
        {
            $caseHash{ $compName } = "$modId.$reasonCode";
        }


        # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        #
        # This check will be used to exclude module Ids which aren't set
        # in stone...  I think they should be, but ...
        # So, as more oddities show up, this will need to be modified
        # to accomodate.
        #
        # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
        if( ($modId =~ /see/i) &&
            ($modId =~ /task/i) )
        {
            # Move to the next loop if this tag is invalid.
            debugMsg( "Invalid Mod Id: $modId" );
            next;
        }
        # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

        print $fh "         case \(\($reasonCode \<\< 8\) \| $modId\) \:\n";

        foreach my $tag ( sort keys %$href )
        {
            $href->{$tag} =~ s/\"/\\\"/g;
            my $line = $href->{$tag};
            $line =~ s/\n//g;
            print $fh "             i_parser.PrintString( \"$tag\" \, \"$line\"  )\;\n";
        }
        print $fh "             break;\n\n";
    }
}


################################################################################
#
# find the namespace of the file.
#
################################################################################

sub findNameSpace
{
    my ( $file ) = @_;
    my $data;
    open(FH, "$file") or die("Cannot open: $file: $!");
    read(FH, $data, -s FH) or die("Error reading $file: $!");
    close FH;

    # get the namespace
    my $namespace = "VOID";
    while( $data =~ /^namespace(.+?\n)/gm )
    {
        $namespace = $1;
        $namespace =~ s/\;+$//;     # strip trailing semicolon
        $namespace =~ s/\{+$//;     # strip opening bracket
        $namespace = stripWhitespace( $namespace );
        $namespaceList{$namespace} = $namespace;
    }
    debugMsg( "Namespace: $namespace" );
    debugMsg( "   from File: $file" );
}


################################################################################
#
# Get the Image id
#
################################################################################
sub getImageId
{
    my $imageId = `git describe --dirty || echo Unknown-Image \`git rev-parse --short HEAD\``;
    chomp $imageId;

    if (($imageId =~ m/Unknown-Image/) ||  	# Couldn't find git describe tag.
        ($imageId =~ m/dirty/) ||	 	# Find 'dirty' commit.
        ($imageId =~ m/^.{15}-[1-9]+/))	# Found commits after a tag.
    {
        $imageId = $imageId."/".$ENV{"USER"};
    }

    return $imageId;
}
OpenPOWER on IntegriCloud