summaryrefslogtreecommitdiffstats
path: root/tester/covoar/ObjdumpProcessor.cc
blob: 56ee2199568f5967f35768e86921774cdea6f164 (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
/*! @file ObjdumpProcessor.cc
 *  @brief ObjdumpProcessor Implementation
 *
 *  This file contains the implementation of the functions supporting
 *  the reading of an objdump output file and adding nops to a
 *  coverage map.
 */

#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <string>

#include "app_common.h"
#include "ObjdumpProcessor.h"
#include "CoverageMap.h"
#include "ExecutableInfo.h"
#include "SymbolTable.h"
#include "TargetFactory.h"

#include "rld.h"
#include "rld-process.h"

namespace Coverage {

  void finalizeSymbol(
    ExecutableInfo* const            executableInfo,
    std::string&                     symbolName,
    ObjdumpProcessor::objdumpLines_t instructions
  ) {
    // Find the symbol's coverage map.
    CoverageMapBase& coverageMap = executableInfo->findCoverageMap( symbolName );

    uint32_t lowAddress = coverageMap.getFirstLowAddress();
    uint32_t size = coverageMap.getSize();
    uint32_t highAddress = lowAddress + size - 1;

    // If there are NOT already saved instructions, save them.
    SymbolInformation* symbolInfo = SymbolsToAnalyze->find( symbolName );
    if (symbolInfo->instructions.empty()) {
      symbolInfo->sourceFile = executableInfo;
      symbolInfo->baseAddress = lowAddress;
      symbolInfo->instructions = instructions;
    }

    // Add the symbol to this executable's symbol table.
    SymbolTable* theSymbolTable = executableInfo->getSymbolTable();
    theSymbolTable->addSymbol(
      symbolName, lowAddress, highAddress - lowAddress + 1
    );

    // Mark the start of each instruction in the coverage map.
    for (auto& instruction : instructions) {
      coverageMap.setIsStartOfInstruction( instruction.address );
    }

    // Create a unified coverage map for the symbol.
    SymbolsToAnalyze->createCoverageMap(
      executableInfo->getFileName().c_str(), symbolName, size
    );
  }

  ObjdumpProcessor::ObjdumpProcessor()
  {
  }

  ObjdumpProcessor::~ObjdumpProcessor()
  {
  }

  uint32_t ObjdumpProcessor::determineLoadAddress(
    ExecutableInfo* theExecutable
  )
  {
    #define METHOD "ERROR: ObjdumpProcessor::determineLoadAddress - "
    FILE*        loadAddressFile = NULL;
    char*        cStatus;
    uint32_t     offset;

    // This method should only be call for a dynamic library.
    if (!theExecutable->hasDynamicLibrary())
      return 0;

    std::string dlinfoName = theExecutable->getFileName();
    uint32_t address;
    char inLibName[128];
    std::string Library = theExecutable->getLibraryName();

    dlinfoName += ".dlinfo";
    // Read load address.
    loadAddressFile = ::fopen( dlinfoName.c_str(), "r" );
    if (!loadAddressFile) {
      std::ostringstream what;
      what << "Unable to open " << dlinfoName;
      throw rld::error( what, METHOD );
    }

    // Process the dlinfo file.
    while ( 1 ) {

      // Get a line.
      cStatus = ::fgets( inputBuffer, MAX_LINE_LENGTH, loadAddressFile );
      if (cStatus == NULL) {
        ::fclose( loadAddressFile );
        std::ostringstream what;
        what << "library " << Library << " not found in " << dlinfoName;
        throw rld::error( what, METHOD );
      }
      sscanf( inputBuffer, "%s %x", inLibName, &offset );
      std::string tmp = inLibName;
      if ( tmp.find( Library ) != tmp.npos ) {
        // fprintf( stderr, "%s - 0x%08x\n", inLibName, offset );
        address = offset;
        break;
      }
    }

    ::fclose( loadAddressFile );
    return address;

    #undef METHOD
  }

  bool ObjdumpProcessor::IsBranch(
    const char *instruction
  )
  {
    if ( !TargetInfo ) {
      fprintf(
        stderr,
        "ERROR: ObjdumpProcessor::IsBranch - unknown architecture\n"
      );
      assert(0);
      return false;
    }

    return TargetInfo->isBranch( instruction );
  }

  bool ObjdumpProcessor::isBranchLine(
    const char* const line
  )
  {
    if ( !TargetInfo ) {
      fprintf(
        stderr,
        "ERROR: ObjdumpProcessor::isBranchLine - unknown architecture\n"
      );
      assert(0);
      return false;
    }

    return  TargetInfo->isBranchLine( line );
  }

  bool ObjdumpProcessor::isNop(
    const char* const line,
    int&              size
  )
  {
    if ( !TargetInfo ){
      fprintf(
        stderr,
        "ERROR: ObjdumpProcessor::isNop - unknown architecture\n"
      );
      assert(0);
      return false;
    }

    return TargetInfo->isNopLine( line, size );
  }

  void ObjdumpProcessor::getFile(
    std::string fileName,
    rld::process::tempfile& objdumpFile,
    rld::process::tempfile& err
    )
  {
    rld::process::status        status;
    rld::process::arg_container args = { TargetInfo->getObjdump(),
                                         "-Cda", "--section=.text", "--source",
                                         fileName };
    try
    {
      status = rld::process::execute( TargetInfo->getObjdump(),
                                      args, objdumpFile.name(), err.name() );
      if ( (status.type != rld::process::status::normal)
           || (status.code != 0) ) {
        throw rld::error( "Objdump error", "generating objdump" );
      }
    } catch( rld::error& err )
      {
        std::cout << "Error while running " << TargetInfo->getObjdump()
                  << " on " << fileName << std::endl;
        std::cout << err.what << " in " << err.where << std::endl;
        return;
      }

    objdumpFile.open( true );
  }

  uint32_t ObjdumpProcessor::getAddressAfter( uint32_t address )
  {
    objdumpFile_t::iterator itr;

    itr = find ( objdumpList.begin(), objdumpList.end(), address );
    if (itr == objdumpList.end()) {
      return 0;
    }

    itr++;
    if (itr == objdumpList.end()) {
      return 0;
    }

    return (*itr);

  }

  void ObjdumpProcessor::loadAddressTable (
    ExecutableInfo* const    executableInformation,
    rld::process::tempfile&  objdumpFile,
    rld::process::tempfile&  err
  )
  {
    int          items;
    uint32_t     offset;
    char         terminator;
    std::string  line;

    // Obtain the objdump file.
    if ( !executableInformation->hasDynamicLibrary() )
      getFile( executableInformation->getFileName(), objdumpFile, err );
    else
      getFile( executableInformation->getLibraryName(), objdumpFile, err );

    // Process all lines from the objdump file.
    while ( true ) {

      // Get the line.
      objdumpFile.read_line( line );
      if ( line.empty() ) {
        break;
      }

      // See if it is the dump of an instruction.
      items = sscanf(
        line.c_str(),
        "%x%c",
        &offset, &terminator
      );

      // If it looks like an instruction ...
      if ((items == 2) && (terminator == ':')) {
        objdumpList.push_back(
          executableInformation->getLoadAddress() + offset
        );
      }
    }
  }

  void ObjdumpProcessor::load(
    ExecutableInfo* const    executableInformation,
    rld::process::tempfile&  objdumpFile,
    rld::process::tempfile&  err
  )
  {
    std::string     currentSymbol = "";
    uint32_t        instructionOffset;
    int             items;
    int             found;
    objdumpLine_t   lineInfo;
    uint32_t        offset;
    bool            processSymbol = false;
    char            symbol[ MAX_LINE_LENGTH ];
    char            terminator1;
    char            terminatorOne;
    char            terminator2;
    objdumpLines_t  theInstructions;
    char            instruction[ MAX_LINE_LENGTH ];
    char            ID[ MAX_LINE_LENGTH ];
    std::string     call = "";
    std::string     jumpTableID = "";
    std::string     line = "";

    // Obtain the objdump file.
    if ( !executableInformation->hasDynamicLibrary() )
      getFile( executableInformation->getFileName(), objdumpFile, err );
    else
      getFile( executableInformation->getLibraryName(), objdumpFile, err );

    while ( true ) {
      // Get the line.
      objdumpFile.read_line( line );
      if ( line.empty() ) {
        // If we are currently processing a symbol, finalize it.
        if (processSymbol) {
          finalizeSymbol(
            executableInformation,
            currentSymbol,
            theInstructions
          );
          fprintf(
            stderr,
            "WARNING: ObjdumpProcessor::load - analysis of symbol %s \n"
            "         may be incorrect.  It was the last symbol in %s\n"
            "         and the length of its last instruction is assumed "
            "         to be one.\n",
            currentSymbol.c_str(),
            executableInformation->getFileName().c_str()
          );
        }
        objdumpFile.close();
        break;
      }

      lineInfo.line          = line;
      lineInfo.address       = 0xffffffff;
      lineInfo.isInstruction = false;
      lineInfo.isNop         = false;
      lineInfo.nopSize       = 0;
      lineInfo.isBranch      = false;

      instruction[0] = '\0';
      ID[0] = '\0';

      // Look for the start of a symbol's objdump and extract
      // offset and symbol (i.e. offset <symbolname>:).
      items = sscanf(
        line.c_str(),
        "%x <%[^>]>%c",
        &offset, symbol, &terminator1
      );

      // See if it is a jump table.
      found = sscanf(
        line.c_str(),
        "%x%c\t%*[^\t]%c%s %*x %*[^+]%s",
        &instructionOffset, &terminatorOne, &terminator2, instruction, ID
      );
      call = instruction;
      jumpTableID = ID;

      // If all items found, we are at the beginning of a symbol's objdump.
      if ((items == 3) && (terminator1 == ':')) {
        // If we are currently processing a symbol, finalize it.
        if (processSymbol) {
          finalizeSymbol(
            executableInformation,
            currentSymbol,
            theInstructions
          );
        }

        // Start processing of a new symbol.
        currentSymbol = "";
        processSymbol = false;
        theInstructions.clear();

        // See if the new symbol is one that we care about.
        if (SymbolsToAnalyze->isDesired( symbol )) {
          currentSymbol = symbol;
          processSymbol = true;
          theInstructions.push_back( lineInfo );
        }
      }
      // If it looks like a jump table, finalize the symbol.
      else if ( (found == 5) && (terminatorOne == ':') && (terminator2 == '\t')
               && (call.find( "call" ) != std::string::npos)
               && (jumpTableID.find( "+0x" ) != std::string::npos)
               && processSymbol )
      {
        // If we are currently processing a symbol, finalize it.
        if ( processSymbol ) {
          finalizeSymbol(
            executableInformation,
            currentSymbol,
            theInstructions
            );
        }
        processSymbol = false;
      }
      else if (processSymbol) {

        // See if it is the dump of an instruction.
        items = sscanf(
          line.c_str(),
          "%x%c\t%*[^\t]%c",
          &instructionOffset, &terminator1, &terminator2
        );

        // If it looks like an instruction ...
        if ((items == 3) && (terminator1 == ':') && (terminator2 == '\t')) {
          // update the line's information, save it and ...
          lineInfo.address =
           executableInformation->getLoadAddress() + instructionOffset;
          lineInfo.isInstruction = true;
          lineInfo.isNop         = isNop( line.c_str(), lineInfo.nopSize );
          lineInfo.isBranch      = isBranchLine( line.c_str() );
        }

        // Always save the line.
        theInstructions.push_back( lineInfo );
      }
    }
  }
}