[0d0e60]: / pp / opannotate.cpp  Maximize  Restore  History

Download this file

695 lines (545 with data), 17.2 kB

  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
/**
* @file opannotate.cpp
* Implement opannotate utility
*
* @remark Copyright 2003 OProfile authors
* @remark Read the file COPYING
*
* @author John Levon
* @author Philippe Elie
*/
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iomanip>
#include <fstream>
#include <utility>
#include "op_exception.h"
#include "op_header.h"
#include "profile.h"
#include "populate.h"
#include "op_sample_file.h"
#include "cverb.h"
#include "string_manip.h"
#include "demangle_symbol.h"
#include "child_reader.h"
#include "op_file.h"
#include "file_manip.h"
#include "arrange_profiles.h"
#include "opannotate_options.h"
#include "profile_container.h"
#include "symbol_sort.h"
#include "image_errors.h"
using namespace std;
using namespace options;
namespace {
size_t nr_events;
scoped_ptr<profile_container> samples;
/// how opannotate was invoked
string cmdline;
/// empty annotation fill string
string annotation_fill;
/// string used as start / end comment to annotate source
string const begin_comment("/* ");
string const in_comment(" * ");
string const end_comment(" */");
/// field width for the sample count
unsigned int const count_width = 6;
string get_annotation_fill()
{
string str;
for (size_t i = 0; i < nr_events; ++i) {
str += string(count_width, ' ') + ' ';
str += string(percent_width, ' ');
}
for (size_t i = 1; i < nr_events; ++i) {
str += " ";
}
str += " :";
return str;
}
symbol_entry const * find_symbol(string const & image_name,
string const & str_vma)
{
// do not use the bfd equivalent:
// - it does not skip space at begin
// - we does not need cross architecture compile so the native
// strtoull must work, assuming unsigned long long can contain a vma
// and on 32/64 bits box bfd_vma is 64 bits
bfd_vma vma = strtoull(str_vma.c_str(), NULL, 16);
return samples->find_symbol(image_name, vma);
}
void output_info(ostream & out)
{
out << begin_comment << '\n';
out << in_comment << "Command line: " << cmdline << '\n'
<< in_comment << '\n';
out << in_comment << "Interpretation of command line:" << '\n';
if (!assembly) {
out << in_comment
<< "Output annotated source file with samples" << '\n';
if (options::threshold != 0) {
out << in_comment
<< "Output files where samples count reach "
<< options::threshold << "% of the samples\n";
} else {
out << in_comment << "Output all files" << '\n';
}
} else {
out << in_comment
<< "Output annotated assembly listing with samples"
<< '\n';
if (!objdump_params.empty()) {
out << in_comment << "Passing the following "
"additional arguments to objdump ; \"";
for (size_t i = 0 ; i < objdump_params.size() ; ++i)
out << objdump_params[i] << " ";
out << "\"" << '\n';
}
}
out << in_comment << '\n';
stringstream ss;
ss << classes.cpuinfo << endl;
if (!classes.event.empty())
ss << classes.event << endl;
for (size_t i = 0; i < classes.v.size(); ++i)
ss << classes.v[i].longname << endl;
ss.seekp(0);
string line;
while (getline(ss, line)) {
out << in_comment << line << '\n';
}
out << end_comment << '\n';
}
string count_str(count_array_t const & count,
count_array_t const & total)
{
ostringstream os;
for (size_t i = 0; i < nr_events; ++i) {
os << setw(count_width) << count[i] << ' ';
os << format_percent(op_ratio(count[i], total[i]) * 100.0,
percent_int_width, percent_fract_width);
}
return os.str();
}
string asm_line_annotation(symbol_entry const * last_symbol,
string const & value)
{
// do not use the bfd equivalent:
// - it does not skip space at begin
// - we does not need cross architecture compile so the native
// strtoull must work, assuming unsigned long long can contain a vma
// and on 32/64 bits box bfd_vma is 64 bits
// gcc 2.91.66 workaround
bfd_vma vma = 0;
vma = strtoull(value.c_str(), NULL, 16);
string str;
sample_entry const * sample = samples->find_sample(last_symbol, vma);
if (sample) {
str += count_str(sample->counts, samples->samples_count());
for (size_t i = 1; i < nr_events; ++i)
str += " ";
str += " :";
} else {
str = annotation_fill;
}
return str;
}
string symbol_annotation(symbol_entry const * symbol)
{
if (!symbol)
return string();
string annot = count_str(symbol->sample.counts,
samples->samples_count());
if (annot.empty())
return string();
string const & symname = symbol_names.demangle(symbol->name);
string str = " ";
str += begin_comment + symname + " total: ";
str += count_str(symbol->sample.counts, samples->samples_count());
str += end_comment;
return str;
}
/// return true if this line contains a symbol name in objdump formatting
/// symbol are on the form 08030434 <symbol_name>: we need to be strict
/// here to avoid any interpretation of a source line as a symbol line
bool is_symbol_line(string const & str, string::size_type pos)
{
if (str[pos] != ' ' || str[pos + 1] != '<')
return false;
return str[str.length() - 1] == ':';
}
symbol_entry const * output_objdump_asm_line(symbol_entry const * last_symbol,
string const & app_name, string const & str,
symbol_collection const & symbols,
bool & do_output)
{
// output of objdump is a human readable form and can contain some
// ambiguity so this code is dirty. It is also optimized a little bit
// so it is difficult to simplify it without breaking something ...
// line of interest are: "[:space:]*[:xdigit:]?[ :]", the last char of
// this regexp dis-ambiguate between a symbol line and an asm line. If
// source contain line of this form an ambiguity occur and we rely on
// the robustness of this code.
size_t pos = 0;
while (pos < str.length() && isspace(str[pos]))
++pos;
if (pos == str.length() || !isxdigit(str[pos])) {
if (do_output) {
cout << annotation_fill << str << '\n';
return last_symbol;
}
}
while (pos < str.length() && isxdigit(str[pos]))
++pos;
if (pos == str.length() || (!isspace(str[pos]) && str[pos] != ':')) {
if (do_output) {
cout << annotation_fill << str << '\n';
return last_symbol;
}
}
if (is_symbol_line(str, pos)) {
last_symbol = find_symbol(app_name, str);
// ! complexity: linear in number of symbol must use sorted
// by address vector and lower_bound ?
// Note this use a pointer comparison. It work because symbols
// pointer are unique
if (find(symbols.begin(), symbols.end(), last_symbol)
!= symbols.end()) {
do_output = true;
} else {
do_output = false;
}
if (do_output)
cout << str << symbol_annotation(last_symbol) << '\n';
} else {
// not a symbol, probably an asm line.
if (do_output)
cout << asm_line_annotation(last_symbol, str)
<< str << '\n';
}
return last_symbol;
}
void do_one_output_objdump(symbol_collection const & symbols,
string const & app_name, bfd_vma start, bfd_vma end)
{
vector<string> args;
args.push_back("-d");
args.push_back("--no-show-raw-insn");
if (source)
args.push_back("-S");
if (start || end != ~(bfd_vma)0) {
ostringstream arg1, arg2;
arg1 << "--start-address=" << start;
arg2 << "--stop-address=" << end;
args.push_back(arg1.str());
args.push_back(arg2.str());
}
if (!objdump_params.empty()) {
for (size_t i = 0 ; i < objdump_params.size() ; ++i)
args.push_back(objdump_params[i]);
}
args.push_back(app_name);
child_reader reader("objdump", args);
if (reader.error()) {
cerr << "An error occur during the execution of objdump:\n\n";
cerr << reader.error_str() << endl;
return;
}
// to filter output of symbols (filter based on command line options)
bool do_output = true;
symbol_entry const * last_symbol = 0;
string str;
while (reader.getline(str)) {
last_symbol = output_objdump_asm_line(last_symbol, app_name,
str, symbols, do_output);
}
// objdump always returns SUCCESS so we must rely on the stderr state
// of objdump. If objdump error message is cryptic our own error
// message will be probably also cryptic
ostringstream std_err;
ostringstream std_out;
reader.get_data(std_out, std_err);
if (std_err.str().length()) {
cerr << "An error occur during the execution of objdump:\n\n";
cerr << std_err.str() << endl;
return ;
}
reader.terminate_process(); // force error code to be acquired
// required because if objdump stop by signal all above things suceeed
// (signal error message are not output through stdout/stderr)
if (reader.error()) {
cerr << "An error occur during the execution of objdump:\n\n";
cerr << reader.error_str() << endl;
return;
}
}
void output_objdump_asm(symbol_collection const & symbols,
string const & app_name)
{
// this is only an optimisation, we can either filter output by
// directly calling objdump and rely on the symbol filtering or
// we can call objdump with the right parameter to just disassemble
// the needed part. This is a real win only when calling objdump
// a medium number of times, I dunno if the used threshold is optimal
// but it is a conservative value.
size_t const max_objdump_exec = 50;
if (symbols.size() <= max_objdump_exec) {
symbol_collection::const_iterator cit = symbols.begin();
symbol_collection::const_iterator end = symbols.end();
for (; cit != end; ++cit) {
bfd_vma start = (*cit)->sample.vma;
bfd_vma end = start + (*cit)->size;
do_one_output_objdump(symbols, app_name, start, end);
}
} else {
do_one_output_objdump(symbols, app_name, 0, ~bfd_vma(0));
}
}
bool output_asm(string const & app_name)
{
profile_container::symbol_choice choice;
choice.threshold = options::threshold;
choice.image_name = app_name;
choice.match_image = true;
symbol_collection symbols = samples->select_symbols(choice);
if (!symbols.empty()) {
sort_options options;
options.add_sort_option(sort_options::sample);
options.sort(symbols, false, false);
output_info(cout);
output_objdump_asm(symbols, app_name);
return true;
}
return false;
}
string const source_line_annotation(debug_name_id filename, size_t linenr)
{
string str;
count_array_t counts = samples->samples_count(filename, linenr);
if (!counts.zero()) {
str += count_str(counts, samples->samples_count());
for (size_t i = 1; i < nr_events; ++i)
str += " ";
str += " :";
} else {
str = annotation_fill;
}
return str;
}
string source_symbol_annotation(debug_name_id filename, size_t linenr)
{
symbol_entry const * symbol = samples->find_symbol(filename, linenr);
return symbol_annotation(symbol);
}
void output_per_file_info(ostream & out, debug_name_id filename,
count_array_t const & total_file_count)
{
out << begin_comment << '\n'
<< in_comment << "Total samples for file : "
<< '"' << debug_names.name(filename) << '"'
<< '\n';
out << in_comment << '\n' << in_comment
<< count_str(total_file_count, samples->samples_count())
<< '\n';
out << end_comment << '\n' << '\n';
}
string const line0_info(debug_name_id filename)
{
string annotation = source_line_annotation(filename, 0);
if (trim(annotation, " \t:").empty())
return string();
string str = "<credited to line zero> ";
str += annotation;
return str;
}
void do_output_one_file(ostream & out, istream & in, debug_name_id filename,
bool header)
{
count_array_t count = samples->samples_count(filename);
if (header) {
output_per_file_info(out, filename, count);
out << line0_info(filename) << '\n';
}
if (in) {
string str;
for (size_t linenr = 1 ; getline(in, str) ; ++linenr) {
out << source_line_annotation(filename, linenr) << str
<< source_symbol_annotation(filename, linenr)
<< '\n';
}
} else {
// FIXME : we have no input file : we just outputfooter
// so on user can known total nr of samples for this source
// later we must add code that iterate through symbol in this
// file to output one annotation for each symbol. To do this we
// need a select_symbol(filename); in profile_container which
// fall back to the implementation in symbol_container
// using a lazilly build symbol_map sorted by filename
// (necessary functors already exist in symbol_functors.h)
}
if (!header) {
output_per_file_info(out, filename, count);
out << line0_info(filename) << '\n';
}
}
void output_one_file(istream & in, debug_name_id filename,
string const & source)
{
if (output_dir.empty()) {
do_output_one_file(cout, in, filename, true);
return;
}
string const out_file = op_realpath(output_dir + source);
/* Just because you're paranoid doesn't mean they're not out to
* get you ... */
if (is_files_identical(out_file, source)) {
cerr << "input and output files are identical: "
<< out_file << endl;
return;
}
if (create_path(out_file.c_str())) {
cerr << "unable to create directory: "
<< '"' << op_dirname(out_file) << '"' << endl;
return;
}
ofstream out(out_file.c_str());
if (!out) {
cerr << "unable to open output file "
<< '"' << out_file << '"' << endl;
} else {
do_output_one_file(out, in, filename, false);
output_info(out);
}
}
/* Locate a source file from debug info, which may be relative */
string const locate_source_file(debug_name_id filename_id)
{
string const origfile = debug_names.name(filename_id);
string file = origfile;
if (file.empty())
return file;
/* Allow absolute paths to be relocated to a different directory */
if (file[0] == '/') {
vector<string>::const_iterator cit = base_dirs.begin();
vector<string>::const_iterator end = base_dirs.end();
for (; cit != end; ++cit) {
string path = op_realpath(*cit);
if (is_prefix(file, path)) {
file = file.substr(path.length());
break;
}
}
}
vector<string>::const_iterator cit = search_dirs.begin();
vector<string>::const_iterator end = search_dirs.end();
for (; cit != end; ++cit) {
string const absfile = op_realpath(*cit + "/" + file);
if (op_file_readable(absfile)) {
return absfile;
}
}
/* We didn't find a relocated absolute file, or a relative file,
* assume the original is correct */
return origfile;
}
void output_source(path_filter const & filter)
{
bool const separate_file = !output_dir.empty();
if (!separate_file)
output_info(cout);
vector<debug_name_id> filenames =
samples->select_filename(options::threshold);
for (size_t i = 0 ; i < filenames.size() ; ++i) {
string const & source = locate_source_file(filenames[i]);
if (!filter.match(source))
continue;
ifstream in(source.c_str());
if (!in) {
// it is common to have empty filename due to the lack
// of debug info (eg _init function) so warn only
// if the filename is non empty. The case: no debug
// info at all has already been checked.
if (source.length())
cerr << "opannotate (warning): unable to "
<< "open for reading: "
<< source << endl;
}
if (source.length()) {
output_one_file(in, filenames[i], source);
}
}
}
bool annotate_source(list<string> const & images)
{
annotation_fill = get_annotation_fill();
if (!output_dir.empty()) {
output_dir = op_realpath(output_dir);
if (output_dir.length() &&
output_dir[output_dir.length() - 1] != '/')
output_dir += '/';
/* Don't let the user stomp on their sources */
if (output_dir == "/") {
cerr << "Output path of / would over-write the "
"source files" << endl;
return false;
}
if (create_path(output_dir.c_str())) {
cerr << "unable to create " << output_dir
<< " directory: " << endl;
return false;
}
}
if (assembly) {
bool some_output = false;
list<string>::const_iterator it = images.begin();
list<string>::const_iterator const end = images.end();
for (; it != end; ++it) {
if (output_asm(*it)) {
some_output = true;
}
}
if (!some_output) {
// It's the only case we must care since we know the
// selected image set is not empty
cerr << "selected image set doesn't contain any of "
<< "the selected symbol\n";
}
} else {
output_source(file_filter);
}
return true;
}
int opannotate(vector<string> const & non_options)
{
handle_options(non_options);
nr_events = classes.v.size();
samples.reset(new profile_container(true, true));
list<string> images;
list<inverted_profile> iprofiles
= invert_profiles(classes, options::extra_found_images);
report_image_errors(iprofiles);
list<inverted_profile>::iterator it = iprofiles.begin();
list<inverted_profile>::iterator const end = iprofiles.end();
bool debug_info = false;
for (; it != end; ++it) {
debug_info |= populate_for_image(*samples, *it,
options::symbol_filter);
images.push_back(it->image);
}
if (!debug_info && !options::assembly) {
cerr << "no debug information available for any binary "
<< "selected and --assembly not requested\n";
exit(EXIT_FAILURE);
}
annotate_source(images);
return 0;
}
} // anonymous namespace
int main(int argc, char const * argv[])
{
// set the invocation, for the file headers later
for (int i = 0 ; i < argc ; ++i)
cmdline += string(argv[i]) + " ";
return run_pp_tool(argc, argv, opannotate);
}