summaryrefslogtreecommitdiffstats
path: root/tester/covoar/covoar.cc
blob: 84d883ae33b5083a674cee8cc66e55538d3725ee (plain) (blame)
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
#include <iostream>
#include <iomanip>

#include <cxxabi.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <list>

#include <rld.h>
#include <rld-process.h>

#include "app_common.h"
#include "CoverageFactory.h"
#include "CoverageMap.h"
#include "DesiredSymbols.h"
#include "ExecutableInfo.h"
#include "Explanations.h"
#include "ObjdumpProcessor.h"
#include "ReportsBase.h"
#include "TargetFactory.h"
#include "GcovData.h"

#if defined(_WIN32) || defined(__CYGWIN__)
  #define kill(p,s) raise(s)
#endif

typedef std::list<std::string> CoverageNames;
typedef std::list<Coverage::ExecutableInfo*> Executables;
typedef std::string option_error;

/*
 * Create a build path from the executable paths. Also extract the build prefix
 * and BSP names.
 */
static void createBuildPath(Executables& executablesToAnalyze,
                            std::string& buildPath,
                            std::string& buildPrefix,
                            std::string& buildBSP)
{
  for (const auto& exe : executablesToAnalyze) {
    rld::strings eparts;
    rld::split(eparts, rld::path::path_abs(exe->getFileName()), RLD_PATH_SEPARATOR);
    std::string fail; // empty means all is OK else an error string
    for (rld::path::paths::reverse_iterator pri = eparts.rbegin();
         pri != eparts.rend();
         ++pri) {
      if (*pri == "testsuites") {
        ++pri;
        if (pri == eparts.rend()) {
          fail = "invalid executable path, no BSP";
          break;
        }
        if (buildBSP.empty()) {
          buildBSP = *pri;
        } else {
          if (buildBSP != *pri) {
            fail = "executable BSP does not match: " + buildBSP;
            break;
          }
        }
        ++pri;
        if (pri == eparts.rend() || *pri != "c") {
          fail = "invalid executable path, no 'c'";
          break;
        }
        ++pri;
        if (pri == eparts.rend()) {
          fail = "invalid executable path, no arch prefix";
          break;
        }
        if (buildPrefix.empty()) {
          buildPrefix = *pri;
        } else {
          if (buildPrefix != *pri) {
            fail = "executable build prefix does not match: " + buildPrefix;
            break;
          }
        }
        ++pri;
        if (pri == eparts.rend()) {
          fail = "invalid executable path, no build top";
          break;
        }
        //
        // The remaining parts of the path is the build path. Iterator over them
        // and collect into a new paths variable to join to make a path.
        //
        rld::path::paths bparts;
        for (; pri != eparts.rend(); ++pri)
          bparts.insert(bparts.begin(), *pri);
        std::string thisBuildPath;
        rld::path::path_join(thisBuildPath, bparts, thisBuildPath);
        if (buildPath.empty()) {
          buildPath = thisBuildPath;
        } else {
          if (buildPath != thisBuildPath) {
            fail = "executable build path does not match: " + buildPath;
          }
        }
        break;
      }
    }
    if (!fail.empty()) {
      throw rld::error( fail, "createBuildPath" );
    }
  }
}

/*
 *  Print program usage message
 */
void usage(const std::string& progname)
{
  std::cerr <<"Usage: " << progname
            <<" [-v] -T TARGET -f FORMAT [-E EXPLANATIONS] -1 EXECUTABLE coverage1 ... coverageN" << std::endl
            << "--OR--" << std::endl
            << "Usage: " << progname
            << " [-v] -T TARGET -f FORMAT [-E EXPLANATIONS] -e EXE_EXTENSION -c COVERAGEFILE_EXTENSION EXECUTABLE1 ... EXECUTABLE2" << std::endl
            << std::endl
            << "  -v                        - verbose at initialization" << std::endl
            << "  -T TARGET                 - target name" << std::endl
            << "  -f FORMAT                 - coverage file format (RTEMS, QEMU, TSIM or Skyeye)" << std::endl
            << "  -E EXPLANATIONS           - name of file with explanations" << std::endl
            << "  -S SYMBOL_SET_FILE        - path to the INI format symbol sets" << std::endl
            << "  -1 EXECUTABLE             - name of executable to get symbols from" << std::endl
            << "  -e EXE_EXTENSION          - extension of the executables to analyze" << std::endl
            << "  -c COVERAGEFILE_EXTENSION - extension of the coverage files to analyze" << std::endl
            << "  -g GCNOS_LIST             - name of file with list of *.gcno files" << std::endl
            << "  -p PROJECT_NAME           - name of the project" << std::endl
            << "  -C ConfigurationFileName  - name of configuration file" << std::endl
            << "  -O Output_Directory       - name of output directory (default=." << std::endl
            << "  -d debug                  - disable cleaning of tempfile" << std::endl
            << std::endl;
}

int covoar(
  int    argc,
  char** argv
)
{
  CoverageNames                 coverageFileNames;
  std::string                   coverageFileName;
  Executables                   executablesToAnalyze;
  Coverage::ExecutableInfo*     executableInfo = NULL;
  std::string                   executableExtension = "exe";
  std::string                   coverageExtension = "cov";
  Coverage::CoverageFormats_t   coverageFormat = Coverage::COVERAGE_FORMAT_QEMU;
  Coverage::CoverageReaderBase* coverageReader = NULL;
  char*                         executable = NULL;
  const char*                   explanations = NULL;
  const char*                   gcnosFileName = NULL;
  char                          gcnoFileName[FILE_NAME_LENGTH];
  char                          gcdaFileName[FILE_NAME_LENGTH];
  char                          gcovBashCommand[256];
  std::string                   target;
  const char*                   format = "QEMU";
  FILE*                         gcnosFile = NULL;
  Gcov::GcovData*               gcovFile;
  const char*                   singleExecutable = NULL;
  rld::process::tempfile        objdumpFile( ".dmp" );
  rld::process::tempfile        err( ".err" );
  rld::process::tempfile        syms( ".syms" );
  bool                          debug = false;
  std::string                   symbolSet;
  std::string                   option;
  int                           opt;

  //
  // Process command line options.
  //

  while ((opt = getopt(argc, argv, "1:L:e:c:g:E:f:s:S:T:O:p:vd")) != -1) {
    switch (opt) {
      case '1': singleExecutable    = optarg; break;
      case 'L': dynamicLibrary      = optarg; break;
      case 'e': executableExtension = optarg; break;
      case 'c': coverageExtension   = optarg; break;
      case 'g': gcnosFileName       = optarg; break;
      case 'E': explanations        = optarg; break;
      case 'f': format              = optarg; break;
      case 'S': symbolSet           = optarg; break;
      case 'T': target              = optarg; break;
      case 'O': outputDirectory     = optarg; break;
      case 'v': Verbose             = true;
                rld::verbose_inc ();          break;
      case 'p': projectName         = optarg; break;
      case 'd': debug               = true;   break;
      default: /* '?' */
        throw option_error( "unknown option" );
    }
  }

  /*
   * Validate inputs.
   */

  /*
   * Validate that we have a symbols of interest file.
   */
  if ( symbolSet.empty() )
    throw option_error( "symbol set file -S" );

  /*
   * Has path to explanations.txt been specified.
   */
  if ( !explanations )
    throw option_error( "explanations -E" );

  /*
   * Check for project name.
   */
  if ( !projectName )
    throw option_error( "project name -p" );

  //
  // Find the top of the BSP's build tree and if we have found the top
  // check the executable is under the same path and BSP.
  //
  std::string buildPath;
  std::string buildTarget;
  std::string buildBSP;
  createBuildPath(executablesToAnalyze,
                  buildPath,
                  buildTarget,
                  buildBSP);

  //
  // Use a command line target if provided.
  //
  if (!target.empty()) {
    buildTarget = target;
  }

  if (Verbose) {
    if (singleExecutable) {
      std::cerr << "Processing a single executable and multiple coverage files"
                << std::endl;
    } else {
      std::cerr << "Processing multiple executable/coverage file pairs" << std::endl;
    }
    std::cerr << "Coverage Format : " << format << std::endl
              << "Target          : " << buildTarget.c_str() << std::endl
              << std::endl;

    // Process each executable/coverage file pair.
    Executables::iterator eitr = executablesToAnalyze.begin();
    for (const auto& cname : coverageFileNames) {
      std::cerr << "Coverage file " << cname
                << " for executable: " << (*eitr)->getFileName() << std::endl;
      if (!singleExecutable)
        eitr++;
    }
  }

  //
  // Create data to support analysis.
  //

  // Create data based on target.
  TargetInfo = Target::TargetFactory( buildTarget );

  // Create the set of desired symbols.
  SymbolsToAnalyze = new Coverage::DesiredSymbols();

  //
  // Read symbol configuration file and load needed symbols.
  //
  SymbolsToAnalyze->load( symbolSet, buildTarget, buildBSP, Verbose );

  // If a single executable was specified, process the remaining
  // arguments as coverage file names.
  if (singleExecutable) {

    // Ensure that the executable is readable.
    if (!FileIsReadable( singleExecutable )) {
      std::cerr << "warning: Unable to read executable: " << singleExecutable
                << std::endl;
    } else {

      for (int i = optind; i < argc; i++) {
        // Ensure that the coverage file is readable.
        if (!FileIsReadable( argv[i] )) {
          std::cerr << "warning: Unable to read coverage file: " << argv[i]
                    << std::endl;
        } else {
          coverageFileNames.push_back( argv[i] );
        }
      }

      // If there was at least one coverage file, create the
      // executable information.
      if (!coverageFileNames.empty()) {
        if (dynamicLibrary) {
          executableInfo = new Coverage::ExecutableInfo(
            singleExecutable, dynamicLibrary, Verbose
          );
        } else {
          executableInfo = new Coverage::ExecutableInfo(
            singleExecutable, nullptr, Verbose
          );
        }

        executablesToAnalyze.push_back( executableInfo );
      }
    }
  }
  else {
    // If not invoked with a single executable, process the remaining
    // arguments as executables and derive the coverage file names.
    for (int i = optind; i < argc; i++) {
      // Ensure that the executable is readable.
      if (!FileIsReadable( argv[i] )) {
        std::cerr << "warning: Unable to read executable: " << argv[i] << std::endl;
      } else {
        coverageFileName = argv[i];
        coverageFileName.append( "." + coverageExtension );

        if (!FileIsReadable( coverageFileName.c_str() )) {
          std::cerr << "warning: Unable to read coverage file: " << coverageFileName
                    << std::endl;
        } else {
          executableInfo = new Coverage::ExecutableInfo(
            argv[i], nullptr, Verbose
          );
          executablesToAnalyze.push_back( executableInfo );
          coverageFileNames.push_back( coverageFileName );
        }
      }
    }
  }

  // Ensure that there is at least one executable to process.
  if (executablesToAnalyze.empty())
    throw rld::error( "No information to analyze", "covoar" );

  // The executablesToAnalyze and coverageFileNames containers need
  // to be the name size of some of the code below breaks. Lets
  // check and make sure.
  if (executablesToAnalyze.size() != coverageFileNames.size())
    throw rld::error( "executables and coverage name size mismatch", "covoar" );

  if ( Verbose )
    std::cerr << "Analyzing " << SymbolsToAnalyze->set.size()
              << " symbols" << std::endl;

  // Create explanations.
  AllExplanations = new Coverage::Explanations();
  if ( explanations )
    AllExplanations->load( explanations );

  // Create coverage map reader.
  coverageFormat = Coverage::CoverageFormatToEnum(format);
  coverageReader = Coverage::CreateCoverageReader(coverageFormat);
  if (!coverageReader)
    throw rld::error( "Unable to create coverage file reader", "covoar" );

  // Create the objdump processor.
  objdumpProcessor = new Coverage::ObjdumpProcessor();

  // Prepare each executable for analysis.
  for (auto& exe : executablesToAnalyze) {
    if (Verbose)
      std::cerr << "Extracting information from: " << exe->getFileName()
                << std::endl;

    // If a dynamic library was specified, determine the load address.
    if (dynamicLibrary) {
      exe->setLoadAddress( objdumpProcessor->determineLoadAddress( exe ) );
    }

    // Load the objdump for the symbols in this executable.
    objdumpProcessor->load( exe, objdumpFile, err );
  }

  //
  // Analyze the coverage data.
  //

  // Process each executable/coverage file pair.
  Executables::iterator eitr = executablesToAnalyze.begin();
  for (const auto& cname : coverageFileNames) {
    Coverage::ExecutableInfo* exe = *eitr;
    if (Verbose)
      std::cerr << "Processing coverage file " << cname
                << " for executable " << exe->getFileName()
                << std::endl;

    // Process its coverage file.
    coverageReader->processFile( cname.c_str(), exe );

    // Merge each symbols coverage map into a unified coverage map.
    exe->mergeCoverage();

    // DEBUG Print ExecutableInfo content
    //exe->dumpExecutableInfo();

    if (!singleExecutable) {
      eitr++;
    }
  }

  // Do necessary preprocessing of uncovered ranges and branches
  if (Verbose)
    std::cerr << "Preprocess uncovered ranges and branches" << std::endl;

  SymbolsToAnalyze->preprocess();

  //
  // Generate Gcov reports
  //
  if (gcnosFileName) {
    if (Verbose)
      std::cerr << "Generating Gcov reports..." << std::endl;

    gcnosFile = fopen ( gcnosFileName , "r" );

    if ( !gcnosFile )
      std::cerr << "Unable to open " << gcnosFileName << std::endl;
    else {
      while ( fscanf( gcnosFile, "%s", inputBuffer ) != EOF) {
        gcovFile = new Gcov::GcovData();
        strcpy( gcnoFileName, inputBuffer );

        if ( Verbose )
          std::cerr << "Processing file: " << gcnoFileName << std::endl;

        if ( gcovFile->readGcnoFile( gcnoFileName ) ) {
          // Those need to be in this order
          gcovFile->processCounters();
          gcovFile->writeReportFile();
          gcovFile->writeGcdaFile();
          gcovFile->writeGcovFile();
        }

        delete gcovFile;
      }
      fclose( gcnosFile );
    }
  }

  // Determine the uncovered ranges and branches.
  if (Verbose)
    std::cerr << "Computing uncovered ranges and branches" << std::endl;

  SymbolsToAnalyze->computeUncovered();

  // Calculate remainder of statistics.
  if (Verbose)
    std::cerr << "Calculate statistics" << std::endl;

  SymbolsToAnalyze->calculateStatistics();

  // Look up the source lines for any uncovered ranges and branches.
  if (Verbose)
    std::cerr << "Looking up source lines for uncovered ranges and branches"
              << std::endl;

  SymbolsToAnalyze->findSourceForUncovered();

  //
  // Report the coverage data.
  //
  if (Verbose)
    std::cerr << "Generate Reports" << std::endl;

  Coverage::GenerateReports();

  // Write explanations that were not found.
  if ( explanations ) {
    std::string notFound;

    notFound = outputDirectory;
    notFound += "/";
    notFound += "ExplanationsNotFound.txt";

    if (Verbose)
      std::cerr << "Writing Not Found Report (" << notFound<< ')' << std::endl;

    AllExplanations->writeNotFound( notFound.c_str() );
  }

  //Leave tempfiles around if debug flag (-d) is enabled.
  if ( debug ) {
    objdumpFile.override( "objdump_file" );
    objdumpFile.keep();
    err.override( "objdump_exec_log" );
    err.keep();
    syms.override( "symbols_list" );
    syms.keep();
  }

  return 0;
}

#define PrintableString(_s) \
((!(_s)) ? "NOT SET" : (_s))

static void
fatal_signal( int signum )
{
  signal( signum, SIG_DFL );

  rld::process::temporaries_clean_up();

  /*
   * Get the same signal again, this time not handled, so its normal effect
   * occurs.
   */
  kill( getpid(), signum );
}

static void
setup_signals( void )
{
  if ( signal( SIGINT, SIG_IGN ) != SIG_IGN )
    signal( SIGINT, fatal_signal );
#ifdef SIGHUP
  if ( signal( SIGHUP, SIG_IGN ) != SIG_IGN )
    signal( SIGHUP, fatal_signal );
#endif
  if ( signal( SIGTERM, SIG_IGN ) != SIG_IGN )
    signal( SIGTERM, fatal_signal );
#ifdef SIGPIPE
  if ( signal( SIGPIPE, SIG_IGN ) != SIG_IGN )
    signal( SIGPIPE, fatal_signal );
#endif
#ifdef SIGCHLD
  signal( SIGCHLD, SIG_DFL );
#endif
}

void
unhandled_exception (void)
{
  std::cerr << "error: exception handling error, please report" << std::endl;
  exit (1);
}

int main(
  int    argc,
  char** argv
)
{
  std::string progname( argv[0] );
  int         ec = 0;

  setup_signals();

  std::set_terminate(unhandled_exception);

  try
  {
    progname = rld::path::basename(argv[0]);
    covoar( argc, argv );
  }
  catch ( option_error oe )
  {
    std::cerr << "error: missing option: " + oe << std::endl;
    usage(progname);
    ec = EXIT_FAILURE;
  }
  catch (rld::error re)
  {
    std::cerr << "error: "
              << re.where << ": " << re.what
              << std::endl;
    ec = 10;
  }
  catch (std::exception e)
  {
    rld::output_std_exception(e, std::cerr);
    ec = 11;
  }
  catch (...)
  {
    /*
     * Helps to know if this happens.
     */
    std::cerr << "error: unhandled exception" << std::endl;
    ec = 12;
  }

  return ec;
}