-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcwrap.pl
executable file
·1972 lines (1710 loc) · 104 KB
/
cwrap.pl
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
# Copyright (c) 2012 Simon Hardy-Francis.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
sub BEGIN {
my $module = "List::MoreUtils" ; eval sprintf "use %s", $module; if($@) { printf "ERROR: cwrap cannot detect Perl module %s; install using e.g. cpanm %s!\n", $module, $module; exit(1); }
my $module = "FFI::Platypus::Lang::CPP::Demangle::XS"; eval sprintf "use %s", $module; if($@) { printf "ERROR: cwrap cannot detect Perl module %s; install using e.g. cpanm %s!\n", $module, $module; exit(1); }
my $exe = "c++filt" ; if(`which $exe` =~ m~^\s*$~s) { printf "ERROR: cwrap cannot detect external executable %s; please install!\n", $exe; exit(1); }
my $exe = "llvm-cxxfilt" ; if(`which $exe` =~ m~^\s*$~s) { printf "ERROR: cwrap cannot detect external executable %s; please install!\n", $exe; exit(1); }
}
use strict;
use Cwd;
use Time::HiRes;
use List::MoreUtils qw(first_index indexes);
use File::Basename; # for fileparse()
use Test::More;
use FFI::Platypus::Lang::CPP::Demangle::XS;
if ($0 =~ m~test~) {
# come here if required by cwrap-test.pl
goto ONLY_REQUIRED_FOR_SUBS;
}
$| ++;
my $log;
my $cwd = getcwd;
my $ts = Time::HiRes::time();
my $arguments = "";
for ( my $c = 0; $c < @ARGV; $c++ ) {
my $tmp = $ARGV[$c];
$tmp =~ s~"~\\"~g;
$arguments .= ' ' . $tmp;
}
$arguments =~ s~^\s+~~; # e.g. gcc -O0 -g -o c---example.via-1-line.exe c---example.1.c c---example.2.c
if ($arguments =~ m~\.(cc|cpp|cxx|hpp|hxx)~ ) { $arguments = "g++ " . $arguments; } # e.g. compile line
elsif ($arguments =~ m~\+\+~ ) { $arguments = "g++ " . $arguments; } # e.g. -std=c++17 or gnu++ or -nostdinc++ etc on link line
else { $arguments = "gcc " . $arguments; }
my ($gcc_out_file) = $arguments =~ m~-o\s+([^\s]+)~;
my ($gcc_out_path,
$gcc_out_name,
$gcc_out_ext ) = get_path_name_and_ext($gcc_out_file) if (defined $gcc_out_file);
chomp(my $os_release = `cat /etc/os-release 2>&1 | egrep PRETTY`);
$log .= sprintf qq[%f - cwrap: timestamp : %s AKA %f\n], Time::HiRes::time() - $ts, scalar localtime, Time::HiRes::time();
$log .= sprintf qq[%f - cwrap: os_release : %s\n] , Time::HiRes::time() - $ts, $os_release;
$log .= sprintf qq[%f - cwrap: arguments : %s\n] , Time::HiRes::time() - $ts, $arguments;
$log .= sprintf qq[%f - cwrap: cwd : %s\n] , Time::HiRes::time() - $ts, $cwd;
$log .= sprintf qq[%f - cwrap: gcc_out_file: %s\n] , Time::HiRes::time() - $ts, $gcc_out_file;
$log .= sprintf qq[%f - cwrap: gcc_out_path: %s\n] , Time::HiRes::time() - $ts, $gcc_out_path;
$log .= sprintf qq[%f - cwrap: gcc_out_name: %s\n] , Time::HiRes::time() - $ts, $gcc_out_name;
$log .= sprintf qq[%f - cwrap: gcc_out_ext : %s\n] , Time::HiRes::time() - $ts, $gcc_out_ext ;
my $cwrap_c = sprintf "%s.cwrap.c", $gcc_out_name; # generate one unique .cwrap.c file per binary output
if ($cwd =~ m~(/CMakeFiles/CMakeTmp|/CMakeFiles/.*/CompilerIdC)~) {
# come here to compile cmake test programs without modifying the gcc command line
my $gcc = $arguments;
$log .= sprintf qq[%f - cwrap: unchanged: running: %s\n], Time::HiRes::time() - $ts, $gcc;
my $output = `$gcc 2>&1`;
my $exit_code = $? >> 8; # perldoc perlvar: the exit value of the subprocess is really ("$? >> 8")
my $output_2_log = $output;
$output_2_log = "<no output>\n" if ($output =~ m~^\s*$~s);
$output_2_log .= sprintf "<exit(%d)>\n", $exit_code if ($output =~ m~^\s*$~s);
$output_2_log =~ s~^(.*)$~> $1~gm;
$log .= $output_2_log;
$log .= sprintf qq[%f - cwrap: done with exit(%d)\n], Time::HiRes::time() - $ts, $exit_code;
printf qq[%s], $output;
exit($exit_code);
}
cwrap_die(sprintf qq[%f ERROR: cwrap cannot detect gcc -o command line option in arguments!\n], Time::HiRes::time() - $ts) if ($gcc_out_file =~ m~^$~);
my @argument_array = split(m~\s+~, $arguments);
my @source_file_arguments;
foreach my $argument (@argument_array) {
if ($argument =~ m~\.(cpp|cxx|cc|hpp|hxx|h|c)$~) {
push @source_file_arguments, $argument;
}
}
my @exe_file_arguments;
if ($gcc_out_file !~ m~\.o$~) {
push @exe_file_arguments, $gcc_out_file;
}
$log .= sprintf qq[%f - cwrap: source file arguments: %d (@source_file_arguments)\n], Time::HiRes::time() - $ts, scalar @source_file_arguments;
$log .= sprintf qq[%f - cwrap: exe file arguments: %d (@exe_file_arguments)\n] , Time::HiRes::time() - $ts, scalar @exe_file_arguments;
if (scalar @source_file_arguments > 0) {
source_to_assembler_to_object_or_executable();
}
if ($gcc_out_ext =~ m~\.o~) {
#$log .= sprintf qq[%f - cwrap: gcc arguments create object\n], Time::HiRes::time() - $ts;
}
else {
if (0 == scalar @source_file_arguments) {
$log .= sprintf qq[%f - cwrap: gcc arguments create executable\n], Time::HiRes::time() - $ts;
my $gcc_4_exe = $arguments;
assembler_to_object_or_executable_via_command($gcc_4_exe);
}
}
sub END {
# come here when Perl exits to write log file
if ($gcc_out_name !~ m~^\s*$~) {
$log .= sprintf qq[%f - cwrap: todo: implement cwrap_log_quiet_until_cw in manual instrumantation macros\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: move call count to function open line\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: figure out building with ninja instead of make\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: integrate home-grown, non-assembler corountines with cwrap\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: integrate third party, assembler coroutines with cwrap via generic API\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: mechanism to exclude arbitrary functions from instrumentation at compile time\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: logging to memory buffer to file\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: logging to memory buffer and only to file at exit\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: options to auto switch off function instrumentation if calls become too high at run-time\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: multi-threaded has been neglected up until now; finish off\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: try out cwrap with other open source C/C++ code bases\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: auto detect if trying to build without gcc and abort\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: implement cwrap for gcc for ARM\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: consider cloning __PRETTY_FUNCTION__ in gcc, to implement __MANGLED_FUNCTION__\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: consider building if(verbosity){..} mechanism into gcc -finstrument-functions option\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: consider adding performance option to replace if(verbosity){..} mechanism with jump switch\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: consider adding HTML run-time interface for easier browsing of run-time call-tree\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: consider keeping run-time performance stats\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: consider colored output to stdout\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: consider extra cwrap_log_init() functionality such as dump instrumentation info\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: add more scenarios to cwrap test, e.g. static and shared libraries\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: todo: do not remove -flto if file being ignored\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: done in %f seconds\n], Time::HiRes::time() - $ts, Time::HiRes::time() - $ts;
my $log_file = sprintf "%s%s.cwrap.log", $gcc_out_name, $gcc_out_ext;
open(my $out, '>', $log_file) || cwrap_die(sprintf qq[%s ERROR: cwrap: cannot open file for writing: %s\n], Time::HiRes::time() - $ts, $log_file);
syswrite($out, $log, length($log));
close $out;
}
}
sub cwrap_die {
my ($format) = shift @_;
my $die_message = sprintf $format, @_;
$log .= $die_message;
die $die_message;
}
sub source_to_assembler_to_object_or_executable {
my ($o_file) = $arguments =~ m~-o ([^\s]+)~;
my $gcc_2_s = $arguments;
$gcc_2_s =~ s~-o [^\s]+~-S -fPIC~; # fPIC needed if objects put into shared object?
$gcc_2_s .= qq[ -finstrument-functions -I. --include cwrap.h];
create_cwrap_h_if_necessary();
if ($gcc_2_s =~ s~\s+-flto(\s+)~$1~g) { # https://stackoverflow.com/questions/29972192/how-does-gccs-linktime-optimisation-flto-flag-work
$log .= sprintf qq[%f - cwrap: c/cpp to assembler: note:: removed any -flto instances otherwise assembler output optimized\n], Time::HiRes::time() - $ts;
}
$log .= sprintf qq[%f - cwrap: c/cpp to assembler: running: %s\n], Time::HiRes::time() - $ts, $gcc_2_s;
my $t1 = Time::HiRes::time();
my $output = `$gcc_2_s 2>&1`;
my $t2 = Time::HiRes::time();
my $exit_code = $? >> 8; # perldoc perlvar: the exit value of the subprocess is really ("$? >> 8")
my $output_2_log = $output;
$output_2_log = "<no output>\n" if ($output =~ m~^\s*$~s);
$output_2_log .= sprintf "<exit(%d)> in %f seconds building assembler for %s\n", $exit_code, $t2 - $t1, $o_file;
$output_2_log =~ s~^(.*)$~> $1~gm;
$log .= $output_2_log;
if ($exit_code != 0) {
$log .= sprintf qq[%f ERROR: cwrap: compilation to assembler has unexpected errors\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: done with exit(%d)\n], Time::HiRes::time() - $ts, $exit_code;
printf qq[%s], $output;
exit($exit_code);
}
$log .= sprintf qq[%f - cwrap: munging assembler files\n], Time::HiRes::time() - $ts;
foreach my $source_file_argument (@source_file_arguments) {
my ($path, $name, $exit) = get_path_name_and_ext($source_file_argument);
my $s_file = $cwd . '/' . $name . '.s';
read_modify_rewrite_assembler_file($s_file);
} # foreach my $source_file_argument
my $gcc_4_s = $arguments;
foreach my $source_file_argument (@source_file_arguments) {
my ($path, $name, $exit) = get_path_name_and_ext($source_file_argument);
my $s_file = $cwd . '/' . $name . '.s';
$gcc_4_s =~ s~$source_file_argument~$s_file.2.s~;
} # foreach my $source_file_argument
assembler_to_object_or_executable_via_command($gcc_4_s);
} # source_to_assembler_to_object_or_executable()
sub assembler_to_object_or_executable_via_command {
my ($gcc_command) = @_;
my ($o_file ) = $gcc_command =~ m~-o ([^\s]+)~;
my $output;
my $output_2_log;
if ((0 == scalar @exe_file_arguments) # if no undefined cwrap_data_* because assembling to object files, or
|| ($gcc_command =~ m~\-shared~ )) { # if no undefined cwrap_data_* because creating a shared object
# come here if gxx operation results in no undefined cwrap_data_*
if ($gcc_command =~ m~\-shared~) { # if .so loaded at run-time, this might happen before the regular call to cwrap_log_init(); this helps call cwrap_log_init() as early as possible
# See https://gcc.gnu.org/legacy-ml/gcc-help/1999-11n/msg00029.html <-- example using "__attribute__((constructor))" mechanism
# See https://groups.google.com/forum/#!topic/gnu.gcc.help/Fit5UOU9UNs <-- why NOT to use "-Wl,-init,<function>" mechanism for shared object
my $cwrap_so_c_file = $gcc_out_file . ".cwrap.c"; # e.g. "lib/libbroker.so.1.3"
$log .= sprintf qq[%f - cwrap: creating cwrap constructor for .so file: %s\n], Time::HiRes::time() - $ts, $cwrap_so_c_file;
my $new_file_contents = sprintf <<EOF;
#ifdef __cplusplus
extern "C" {
#endif
extern int cwrap_log_init(void);
extern int cwrap_log_init_so(void) __attribute__ ((constructor));
int cwrap_log_init_so(void) {
return cwrap_log_init();
}
#ifdef __cplusplus
}
#endif
EOF
open(my $out, '>', $cwrap_so_c_file) || cwrap_die(sprintf qq[%f ERROR: cwrap: cannot open file for writing: %s\n], Time::HiRes::time() - $ts, $cwrap_so_c_file);
syswrite($out, $new_file_contents);
close $out;
my $cc_command = sprintf qq[gcc -c -fPIC -o %s.o %s], $cwrap_so_c_file, $cwrap_so_c_file;
$log .= sprintf qq[%f - cwrap: compile cwrap so constructor: running: %s\n], Time::HiRes::time() - $ts, $cc_command;
my $t1 = Time::HiRes::time();
$output = `$cc_command 2>&1`;
my $t2 = Time::HiRes::time();
my $exit_code = $? >> 8; # perldoc perlvar: the exit value of the subprocess is really ("$? >> 8")
$output_2_log = $output;
$output_2_log = "<no output>\n" if ($output =~ m~^\s*$~s);
$output_2_log .= sprintf "<exit(%d)> in %f seconds building object for %s\n", $exit_code, $t2 - $t1, $cwrap_c;
$output_2_log =~ s~^(.*)$~> $1~gm;
if ($exit_code != 0) {
$log .= $output_2_log;
$log .= sprintf qq[%f ERROR: cwrap: compilation to object or executable has unexpected errors\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: done with exit(%d)\n], Time::HiRes::time() - $ts, $exit_code;
printf qq[%s], $output;
exit($exit_code);
}
$log .= $output_2_log;
$gcc_command =~ s~^([^ ]+) ~$1 $cwrap_so_c_file.o ~; # order important: insert as the very first file to be linked! so that the cwrap constructor is the first to be called at run-time!
}
$log .= sprintf qq[%f - cwrap: no undefined cwrap_data_*: running: %s\n], Time::HiRes::time() - $ts, $gcc_command;
my $t1 = Time::HiRes::time();
$output = `$gcc_command 2>&1`;
my $t2 = Time::HiRes::time();
my $exit_code = $? >> 8; # perldoc perlvar: the exit value of the subprocess is really ("$? >> 8")
$output_2_log = $output;
$output_2_log = "<no output>\n" if ($output =~ m~^\s*$~s);
$output_2_log .= sprintf "<exit(%d)> in %f seconds building object or shared object for %s\n", $exit_code, $t2 - $t1, $o_file;
$output_2_log =~ s~^(.*)$~> $1~gm;
}
else {
# come here if linking object files into a binary causing undefined cwrap_data_*
my $output_type;
if (scalar @source_file_arguments > 0) { # if compiling to binary directly from source files
$log .= sprintf qq[%f - cwrap: object to binary #1: running via gxx (because source files detected): %s\n], Time::HiRes::time() - $ts, $gcc_command;
$output = `$gcc_command 2>&1`;
$output_type = 'gxx';
cwrap_die(sprintf qq[%f ERROR: detected errors in gxx output:\n%s\n], Time::HiRes::time() - $ts, $output) if ($output =~ m~:\d+: Error: ~is);
}
else {
# use nm instead of gcc/g++ because nm takes about 0.07 seconds instead of over 75 seconds for gcc/g++ !!!
$log .= sprintf qq[%f - cwrap: constructing two nm commands from gcc command\n], Time::HiRes::time() - $ts;
# Why two nm commands? Because second one uses --dynamic option:
# https://stackoverflow.com/questions/54052534/why-nm-libc-so-reports-no-symbols
# https://stackoverflow.com/questions/15345543/when-to-use-dynamic-option-in-nm
undef $output;
foreach my $nm_command_number (1..2) {
my $nm_command = qq[nm --print-file-name --no-sort --undefined-only];
$nm_command .= qq[ --dynamic] if (2 == $nm_command_number);
my @gcc_command_parts = split(m~\s+~, $gcc_command);
foreach my $gcc_command_part (@gcc_command_parts) {
if ($gcc_command_part =~ m~^\@~) { # e.g. @CMakeFiles/zeek.dir/objects1.rsp <-- hopefully containing lots of object files
# fall thru to append
}
elsif (($gcc_command_part =~ m~^\-~ ) # e.g. -Wl,-soname,libcaf_core.so.0.17.3
|| ($gcc_command_part !~ m~\.(o|a|so[\.0-9]*)$~)) { # e.g. logging/writers/sqlite/CMakeFiles/plugin-Zeek-SQLiteWriter.dir/sqlite.bif.init.cc.o ../aux/paraglob/src/ahocorasick/libahocorasick.a ../aux/broker/lib/./libcaf_openssl.so ../aux/broker/lib/libbroker.so.1.2
$log .= sprintf qq[%f - cwrap: discarding gcc command line option: %s\n], Time::HiRes::time() - $ts, $gcc_command_part;
goto SKIP_APPEND;
}
# come here to append gcc command part to nm command
$nm_command .= ' ' . $gcc_command_part;
SKIP_APPEND:;
}
$nm_command .= qq[ 2>&1 | egrep cwrap_data_];
$log .= sprintf qq[%f - cwrap: object to binary #1: running via nm #%d (because no source files detected and nm faster than gxx): %s\n], Time::HiRes::time() - $ts, $nm_command_number, $nm_command;
$output .= `$nm_command 2>&1`;
}
$output_type = 'nm';
}
$log .= sprintf qq[%f - cwrap: using undefines from %s; auto generating: %s\n], Time::HiRes::time() - $ts, $output_type, $cwrap_c;
using_undefind_error_write_cwrap_c($output, $output_type);
my $cc_command = sprintf qq[gcc -c -fPIC -o %s.o %s -Wl,--undefined,cwrap_log_init], $cwrap_c, $cwrap_c; # todo: consider using -Wl,--whole-archive
my @gcc_command_parts = split(m~\s+~, $gcc_command);
foreach my $gcc_command_part (@gcc_command_parts) {
$cc_command .= ' ' . $gcc_command_part if ($gcc_command_part =~ m~-DCWRAP~); # append any CWRAP compile defaults
}
$log .= sprintf qq[%f - cwrap: compile cwrap: running: %s\n], Time::HiRes::time() - $ts, $cc_command;
my $t1 = Time::HiRes::time();
$output = `$cc_command 2>&1`;
my $t2 = Time::HiRes::time();
my $exit_code = $? >> 8; # perldoc perlvar: the exit value of the subprocess is really ("$? >> 8")
$output_2_log = $output;
$output_2_log = "<no output>\n" if ($output =~ m~^\s*$~s);
$output_2_log .= sprintf "<exit(%d)> in %f seconds building object for %s\n", $exit_code, $t2 - $t1, $cwrap_c;
$output_2_log =~ s~^(.*)$~> $1~gm;
if ($exit_code != 0) {
$log .= $output_2_log;
$log .= sprintf qq[%f ERROR: cwrap: compilation to object or executable has unexpected errors\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: done with exit(%d)\n], Time::HiRes::time() - $ts, $exit_code;
printf qq[%s], $output;
exit($exit_code);
}
$log .= $output_2_log;
# see https://en.wikipedia.org/wiki/Gold_%28linker%29
$gcc_command .= sprintf qq[ %s.o -Wl,--undefined,cwrap_log_init -fPIC -lunwind], $cwrap_c;
$gcc_command .= qq[ -fuse-ld=gold] if ($os_release !~ m~Alpine~i); # gold linker seems dodgy on Alpine Linux
$log .= sprintf qq[%f - cwrap: object to binary #2: running: %s\n], Time::HiRes::time() - $ts, $gcc_command;
my $t1 = Time::HiRes::time();
$output = `$gcc_command 2>&1`;
my $t2 = Time::HiRes::time();
my $exit_code = $? >> 8; # perldoc perlvar: the exit value of the subprocess is really ("$? >> 8")
$output_2_log = $output;
$output_2_log = "<no output>\n" if ($output =~ m~^\s*$~s);
$output_2_log .= sprintf "<exit(%d)> in %f seconds building binary for %s\n", $exit_code, $t2 - $t1, $o_file;
$output_2_log =~ s~^(.*)$~> $1~gm;
if ($exit_code != 0) {
$log .= $output_2_log;
$log .= sprintf qq[%f ERROR: cwrap: compilation to object or executable has unexpected errors\n], Time::HiRes::time() - $ts;
$log .= sprintf qq[%f - cwrap: done with exit(%d)\n], Time::HiRes::time() - $ts, $exit_code;
printf qq[%s], $output;
exit($exit_code);
}
}
$log .= $output_2_log;
printf qq[%s], $output;
} # assembler_to_object_or_executable_via_command()
sub get_path_name_and_ext {
my ($path_name_ext) = @_;
#debug $log .= sprintf qq[debug: (?, ?, ?)=fileparse(%s)\n], $path_name_ext;
my ($f, $path, $s) = fileparse($path_name_ext, "", qr/\.[^.]*/); # suffix maybe nothing or .something
$path = '' if ($path eq './');
my $name = $f ; # e.g. 'connection' in 'connection.o'
my $ext = $s ; # e.g. '.o' in 'connection.o'
#debug $log .= sprintf qq[debug: ($f, $d, $s)=fileparse(%s) // %s=path %s=name %s=ext\n], $path_name_ext, $folder, $name, $ext;
return ($path, $name, $ext);
} # get_path_name_and_ext()
sub pretty_asm {
my ($asm_line) = @_;
$asm_line =~ s~\t~ ~gs;
$asm_line =~ s~^\s+~~s;
$asm_line =~ s~\s+$~~s;
return $asm_line;
}
# e.g. these types are the same but out of order:
# my_func(const unsigned char*, long unsigned int, unsigned char*)
# my_func(unsigned char const*, unsigned long, unsigned char*)
sub demangle_name_sanitize_type_order {
my ($demangled_name) = @_;
$demangled_name =~ s~(char|short|int|long|float|double) (unsigned|signed)~$2 $1~g; # todo: figure out a better way to order types
while ($demangled_name =~ s~(unsigned|signed|char|short|int|long|float|double) const~const $1~g) {} # todo: figure out a better way to order types
$demangled_name =~ s~(long) int\s*~$1~g; # 'long int' same as 'long'; see: https://stackoverflow.com/questions/17287957/is-long-unsigned-as-valid-as-unsigned-long-in-c
$demangled_name =~ s~u_char~unsigned char~g; # hack for e.g. const u_char * --> const unsigned char*
$demangled_name =~ s~uint64_t~unsigned long~g;
# note: below we sanitize function parameters, i.e. inside (...)
while($demangled_name =~ s~(\(.*)<[^<>]+>~$1~gs) {} # e.g. std::map* from std::map<int, std::set<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, std::greater<int>, std::allocator<std::pair<const int, std::set<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > > >*
# This next quick and dirty hack means both of these cases will match:
# case 1: RuleMatcher::MIME_Matches*
# case 2: std::map*
while($demangled_name =~ s~(\(\s*|\,\s*)[^\,\*\s\:]+\:\:[^\,\*\s\)]+~$1c_o_m_p_l_e_x_t_y_p_e~gs) {} # e.g. c_o_m_p_l_e_x_t_y_p_e* from std::map*
return $demangled_name;
}
sub demangle_name {
my ( $mangled_name) = @_;
my $demangled_name;
if ( $mangled_name =~ m~^_Z~) {
# first try with Perl inline demangler which only seems to work on 99%+ mangled names, but it's fast :-)
$demangled_name = FFI::Platypus::Lang::CPP::Demangle::XS::demangle($mangled_name) if($mangled_name =~ m~^_Z~); # faster and more scalable than c++filt or llvm-cppfilt
goto GOT_DEMANGLED_NAME if (($mangled_name ne $demangled_name) && (length($demangled_name) > 0));
# try with c++filt which has the command line option --no-recursion-limit:
my $cxx_filt_command = sprintf qq[c++filt --no-recursion-limit %s], $mangled_name;
$demangled_name = `$cxx_filt_command`;
chomp $demangled_name;
$log .= sprintf qq[%f - cwrap: ran %s giving %s\n], Time::HiRes::time() - $ts, $cxx_filt_command, $demangled_name;
goto GOT_DEMANGLED_NAME if (($mangled_name ne $demangled_name) && (length($demangled_name) > 0));
# try with llvm-cxxfilt which seems a little more reliable and consistent than c++filt from gcc:
my $llvm_cxx_filt_command = sprintf qq[llvm-cxxfilt %s], $mangled_name;
$demangled_name = `$llvm_cxx_filt_command`;
chomp $demangled_name;
$log .= sprintf qq[%f - cwrap: ran %s giving %s\n], Time::HiRes::time() - $ts, $llvm_cxx_filt_command, $demangled_name;
goto GOT_DEMANGLED_NAME if (($mangled_name ne $demangled_name) && (length($demangled_name) > 0));
# own KISS demangling... obviously this is not good... why can CXX simply not demangle properly?!
my ($len, $rest);
$rest = $mangled_name;
$rest =~ s~^[^\d]+~~;
my @name_parts;
push @name_parts, 'CWRAP_DEMANGLE_FAIL';
while ($rest =~ m~^(\d+)(.*)$~) {
($len, $rest) = ($1, $2);
my $name_part = substr($rest, 0, $len);
push @name_parts, $name_part;
#debug printf qq[- %d bytes: %s in %s\n\n], $len, $name_part, $rest;
substr($rest, 0, $len) = '';
}
$demangled_name = join('::', @name_parts);
$log .= sprintf qq[%f WARNING: internal: failed to demangle name using c++filt or llvm-cxxfilt: %s\n], Time::HiRes::time() - $ts, $mangled_name;
GOT_DEMANGLED_NAME:;
$demangled_name = demangle_name_sanitize_type_order($demangled_name);
}
else {
$demangled_name = $mangled_name;
}
cwrap_die sprintf qq[%f ERROR: internal: unexpected zero length demangled name from mangled name: %s\n], Time::HiRes::time() - $ts, $mangled_name if (0 == length($demangled_name));
return $demangled_name;
}
sub match_enter_exit_with_mangled_names {
my $a = shift;
my $z = shift;
my $func_lines_ref = shift;
$log .= sprintf qq[%f - cwrap: match_enter_exit_with_mangled_names: searching in %d lines %d to %d of %d lines in file\n], Time::HiRes::time() - $ts, $z - $a + 1, $a, $z, scalar @$func_lines_ref;
# movq my_private@GOTPCREL(%rip), %rax
my @func_lines_min = grep(m~^\s*(\.L\d+|j[^\s]+\s+\.L\d+|(call|jmp)\s+__cyg_|leaq\s+[^\.\s].*rip|movq.*rip|ret\s+|movq\s+.*r.., %rdi)~, @$func_lines_ref[$a..$z]);
unshift @func_lines_min, ".L000:\n";
$log .= sprintf qq[%f - cwrap: match_enter_exit_with_mangled_names: squashed down to %d lines\n], Time::HiRes::time() - $ts, scalar @func_lines_min;
my $h;
my $jump_to;
my $label;
my $instruction;
my $function;
my $register;
my $register_assign_value;
my @enter_exit_functions;
my $enter_exit_number = 0;
foreach (@func_lines_min) {
if (m~cwrap_(log|data)_~) {
next;
}
elsif (m~^(\.L\d+)\:~) {
$label = $1;
$log .= sprintf qq[%f - cwrap: match_enter_exit_with_mangled_names: found %s:\n], Time::HiRes::time() - $ts, $label;
$register = 'rdi';
}
elsif (m~^\s+movq\s+\%(r..),\s*\%rdi~) {
$register = $1;
$log .= sprintf qq[%f - cwrap: match_enter_exit_with_mangled_names: found \tmovq rdi <-- %s\n], Time::HiRes::time() - $ts, $register;
}
elsif (m~^\s+(j[^\s]+)\s+(\.L\d+)~) {
my ($jump, $label_to) = ($1, $2);
$log .= sprintf qq[%f - cwrap: match_enter_exit_with_mangled_names: found \t%s %s\n], Time::HiRes::time() - $ts, $jump, $label_to;
foreach my $register (keys %{ $h->{$label}{register} }) {
#printf qq[ - copying register %s = %s\n], $register, $h->{$label}{register}{$register};
$jump_to->{$label_to}{register}{$register} = $h->{$label}{register}{$register};
}
}
elsif (m~^\s+(leaq|movq)\s+([^\(]+)\(\%rip\), \%(r..)~) {
($instruction, $function, $register) = ($1, $2, $3);
$function =~ s~\@GOTPCREL~~;
$register_assign_value->{$register}{$function} ++;
$log .= sprintf qq[%f - cwrap: match_enter_exit_with_mangled_names: found \t%s %s <-- &%s\n], Time::HiRes::time() - $ts, $instruction, $register, $function;
$h->{$label}{register}{$register} = $function;
}
elsif (m~^\s+(call|jmp)\s+(__cyg_profile_func_(enter|exit))\@PLT~) {
my ($call_or_jump, $enter_exit) = ($1, $2);
my $enter_exit_name = "?";
my $hint;
if (exists $h->{$label}{register}{$register}) {
$enter_exit_name = $h->{$label}{register}{$register};
push @enter_exit_functions, $enter_exit_name;
}
elsif (exists $jump_to->{$label}{register}{$register}) {
$enter_exit_name = $jump_to->{$label}{register}{$register};
$hint = sprintf ' indirect via jump via %s and register %s', $label, $register;
push @enter_exit_functions, $enter_exit_name;
}
else {
# come here if no register found probably because label not scanned yet?
push @enter_exit_functions, sprintf qq[label=%s register=%s], $label, $register;
}
$enter_exit_number ++;
$log .= sprintf qq[%f - cwrap: match_enter_exit_with_mangled_names: found \t%s(%s) #%d%s\n], Time::HiRes::time() - $ts, $enter_exit, $enter_exit_name, $enter_exit_number, $hint;
}
#printf qq[%s], $_;
} # foreach (@func_lines_min)
#fixme printf qq[- found enter exit functions: %d\n], scalar @enter_exit_functions;
$log .= sprintf qq[%f - cwrap: match_enter_exit_with_mangled_names: found enter exit functions: %d\n], Time::HiRes::time() - $ts, scalar @enter_exit_functions;
my $enter_exit_number = 0;
foreach (@enter_exit_functions) {
my $hint;
if (m~^label=([^ ]+) register=(.*)$~) {
my ($label, $register) = ($1, $2);
my @unique_register_assignments = keys %{ $register_assign_value->{$register} };
if (1 == scalar @unique_register_assignments) {
$_ = $unique_register_assignments[0];
$hint = sprintf " <-- assigned because unique register %s value", $register;
}
elsif (exists $jump_to->{$label}{register}{$register}) {
$_ = $jump_to->{$label}{register}{$register};
$hint = sprintf " <-- indirect via jump via %s and register %s", $label, $register;
}
}
$enter_exit_number ++;
$log .= sprintf qq[%f - cwrap: match_enter_exit_with_mangled_names: enter exit function: #%d %s%s%s\n], Time::HiRes::time() - $ts, $enter_exit_number, $_, m~^label=~ ? "" : "()", $hint;
cwrap_die(sprintf qq[%f ERROR: internal: cwrap: match_enter_exit_with_mangled_names: failed to match enter exit function!\n], Time::HiRes::time() - $ts) if (m~^label=~);
}
return @enter_exit_functions;
} # sub match_enter_exit_with_mangled_names()
sub read_modify_rewrite_assembler_file {
my ($s_file) = @_;
cwrap_die(sprintf qq[%f ERROR: internal: cwrap: expected assembler file does not exist: %s\n], Time::HiRes::time() - $ts, $s_file) if (not -e $s_file);
my $s_file_line = `cat $s_file`;
my @s_file_lines = split(m~\n~, $s_file_line);
$log .= sprintf qq[%f - cwrap: assembler file: name : < %s <-- %d lines\n], Time::HiRes::time() - $ts, $s_file, scalar @s_file_lines;
#
# 1. search for __cyg_profile_func_(enter|exit)
# 2. work backwards to the correct leaq <unique mangled function name> and replace with leaq cwrap_data_<unique mangled function name>
#
# leaq main(%rip), %rdi
# leaq inc_a(%rip), %rbp
# ...
# call __cyg_profile_func_enter@PLT
# ...
# movq %rbp, %rdi
# call __cyg_profile_func_enter@PLT <-- inline function #1 enter via rbp
# ...
# movq %rbp, %rdi
# call __cyg_profile_func_exit@PLT <-- inline function #1 leave via rbp
# ...
# leaq inc_b(%rip), %rdi
# call __cyg_profile_func_enter@PLT <-- inline function #2 enter
# ...
# leaq inc_b(%rip), %rdi
# call __cyg_profile_func_exit@PLT <-- inline function #2 enter
# ...
# leaq main(%rip), %rdi
# call __cyg_profile_func_exit@PLT
# movq _ZN6binpac9ExceptionC2EPKc@GOTPCREL(%rip), %rax
# movq %rax, %rdi
# call __cyg_profile_func_enter@PLT
my $debug_search = 1; # fixme
my $h_labels_to_rewrite;
my $h_mangled_2_demangled;
my $h_demangled_2_mangled;
my $h_demangled_2_mangled_no_params;
my $h_demangled_2_mangled_unique;
my $t1 = Time::HiRes::time();
my @s_file_line_index_start = indexes { m~\s+\.type\s+([^,]+),\s*\@function~ } @s_file_lines; # e.g. .type next_entry, @function
my $t2 = Time::HiRes::time();
$log .= sprintf qq[%f - cwrap: assembler file: found '.type <function name>, \@function' instances: %d in %fs\n], Time::HiRes::time() - $ts, scalar @s_file_line_index_start, $t2 - $t1;
my $t1 = Time::HiRes::time();
my @s_file_line_index_end = indexes { m~\s+\.cfi_endproc~ } @s_file_lines; # e.g. .cfi_endproc
my $t2 = Time::HiRes::time();
$log .= sprintf qq[%f - cwrap: assembler file: found '.cfi_endproc' instances: %d in %fs\n], Time::HiRes::time() - $ts, scalar @s_file_line_index_end, $t2 - $t1;
$log .= sprintf qq[%f - cwrap: assembler file: finding function name associated with each enter|exit\n], Time::HiRes::time() - $ts;
cwrap_die(sprintf qq[%f ERROR: internal: cwrap: assembler file: found %d function starts but %d function ends!\n], Time::HiRes::time() - $ts, scalar @s_file_line_index_start, scalar @s_file_line_index_end) if (scalar(@s_file_line_index_start) != scalar(@s_file_line_index_end));
foreach my $i (0..$#s_file_line_index_start) {
my $a = $s_file_line_index_start[0 + $i];
my $z = $s_file_line_index_end[0 + $i];
my ($mangled_name) = $s_file_lines[$a] =~ m~\s+\.type\s+([^,]+),\s*\@function~;
next if ($mangled_name =~ m~\.cold~); # skip this section on its own because the previous section will have 'enlarged' into this section
my $next_a = $s_file_line_index_start[1 + $i];
my $next_z = $s_file_line_index_end[1 + $i];
my ($next_mangled_name) = $s_file_lines[$next_a] =~ m~\s+\.type\s+([^,]+),\s*\@function~;
if ($next_mangled_name =~ m~\.cold~) {
$log .= sprintf qq[%f - cwrap: assembler file: line %d to %d for function %s() expanded to .cold function; line %d to %d\n], Time::HiRes::time() - $ts, $a, $z, $mangled_name, $a, $next_z if($debug_search);
$z = $next_z; # if next section is '.cold' then merge it into this section
}
my $t1 = Time::HiRes::time();
my @s_file_line_index_cyg = indexes { m~(call|jmp)\s+__cyg_profile_func_(enter|exit)~ } @s_file_lines[$a..$z]; # (call|jmp) __cyg_profile_func_exit
my $t2 = Time::HiRes::time();
$log .= sprintf qq[%f - cwrap: assembler file: line %d to %d for function with %d enter|exits: %s()\n], Time::HiRes::time() - $ts, $a, $z, scalar @s_file_line_index_cyg, $mangled_name if($debug_search);
my @enter_exit_functions;
if (1 == scalar @s_file_line_index_cyg) {
# come here if only 1 enter|exit calls, therefore no embedded functions to complicate things; typically this is <function name>.cold
$mangled_name =~ s~\.cold~~;
push @enter_exit_functions, $mangled_name;
}
elsif (2 == scalar @s_file_line_index_cyg) {
# come here if only 2 enter|exit calls, therefore no embedded functions to complicate things
push @enter_exit_functions, $mangled_name;
push @enter_exit_functions, $mangled_name;
}
else {
# come here if an odd number of enter|exit calls, therefore need to analyse names for potential embedded functions
@enter_exit_functions = match_enter_exit_with_mangled_names($a, $z, \@s_file_lines);
}
cwrap_die(sprintf qq[%f ERROR: internal: cwrap: assembler file: found %d enter exit functions but %d function names!\n], Time::HiRes::time() - $ts, scalar @s_file_line_index_cyg, scalar @enter_exit_functions) if (scalar(@s_file_line_index_cyg) != scalar(@enter_exit_functions));
foreach my $n (0..$#s_file_line_index_cyg) {
my $p = $s_file_line_index_cyg[$n];
my $mangled_name = $enter_exit_functions[$n];
my $note;
if ($mangled_name =~ m~\.~) {
# note: unbelievably, some labels can have dots in them, e.g.: _GLOBAL__sub_I_cpp_example_1.b.cpp <-- bug in gcc ?
my $mangled_name_with_dot = $mangled_name;
my $mangled_name_no___dot = $mangled_name;
$mangled_name_no___dot =~ s~\.~_~g;
$h_labels_to_rewrite->{$mangled_name_with_dot} = $mangled_name_no___dot;
$note = " (converted dots to underscores)";
}
if (not exists $h_mangled_2_demangled->{$mangled_name}) {
my $demangled_name = demangle_name($mangled_name);
my $demangled_name_no_params = $demangled_name;
$demangled_name_no_params =~ s~\(.*$~~; # strip (<params>) from e.g. main()
$h_mangled_2_demangled->{$mangled_name } = $demangled_name;
$h_demangled_2_mangled->{$demangled_name} = $mangled_name;
$h_demangled_2_mangled_no_params->{$demangled_name_no_params} = $mangled_name;
$h_demangled_2_mangled_unique->{$demangled_name_no_params} ++;
}
$s_file_lines[$a + $p] .= sprintf qq[ # <-- rdi=&%s, rsi=&cwrap_data_%s], $mangled_name, $mangled_name;
# use edx below because call __cyg_profile_func_(enter|exit) only uses 2 parameters, RDI & RSI, therefore use 3rd parameter RDX for comparison; see https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI
my $skip_label = sprintf qq[.L_cwrap_skip_%s_%d], "cyg_profile_func", $a + $p;
my $original_enter_exit_call = $s_file_lines[$a + $p];
my $optional_ret_if_jmp_enter_exit = sprintf qq[\tret\n] if ($original_enter_exit_call =~ m~jmp~);
# todo: consider eliminating cwrap_log_verbosity and just testing cwrap_data_$mangled_name as zero or non-zero? faster?
# non -fPIC code: movl cwrap_data_$mangled_name(%rip), %edx
# non -fPIC code: cmpl cwrap_log_verbosity(%rip), %edx
# non -fPIC code: jg $skip_label
$s_file_lines[$a + $p] = <<EOF;
movq cwrap_log_verbosity\@GOTPCREL(%rip), %rax
movl (%rax), %edx
movq cwrap_data_$mangled_name\@GOTPCREL(%rip), %rsi
movl (%rsi), %eax
cmpl %eax, %edx
jl $skip_label
$original_enter_exit_call
$skip_label:
$optional_ret_if_jmp_enter_exit
EOF
$log .= sprintf qq[%f - cwrap: assembler file: line %d: %s%s\n], Time::HiRes::time() - $ts, $a + $p, pretty_asm($original_enter_exit_call), $note if($debug_search);
} # foreach my $p
} # foreach my $i
#
# 1. search for pushsection / asciz / popsection,
# 2. determine unique unmangled function name containing if(...)
# 3. replace movl cwrap_log_verbosity_dummy with cwrap_data_<unique mangled function name>...
# 4. todo: delete pushsection / asciz / popsection and ascii name
#
# C: .type __PRETTY_FUNCTION__.3193, @object
# C: .size __PRETTY_FUNCTION__.3193, 5
# C:__PRETTY_FUNCTION__.3193:
# C: .string "main"
# C:...
# C:#APP
# C:# 41 "cpp-example-1.a.cpp" 1
# C: .pushsection __cwrap, "S", @note; .int 9; .asciz "$__PRETTY_FUNCTION__.3193"; .popsection
# C:
# C:# 0 "" 2
# C: .loc 1 41 5 view .LVU77
# C:#NO_APP
# C: movl cwrap_log_verbosity(%rip), %eax
# C: cmpl %eax, 36+cwrap_log_verbosity_dummy(%rip)
# C: jle .L21
# CPP:.LC13:
# CPP: .string "int main()"
# CPP:...
# CPP:#APP
# CPP:# 41 "cpp-example-1.a.cpp" 1
# CPP: .pushsection __cwrap, "S", @note; .int 9; .asciz "$.LC13"; .popsection
# CPP:
# CPP:# 0 "" 2
# CPP: .loc 1 41 5 view .LVU190
# CPP:#NO_APP
# CPP: movl cwrap_log_verbosity(%rip), %eax
# CPP: cmpl %eax, 36+cwrap_log_verbosity_dummy(%rip)
# CPP: jle .L51
my $t1 = Time::HiRes::time();
my @s_file_line_index = indexes { m~pushsection __cwrap.*\.int.*\.asciz "\$([^"]+)"~ } @s_file_lines;
my $t2 = Time::HiRes::time();
$log .= sprintf qq[%f - cwrap: found pushsection __cwrap instances: %d in %fs\n], Time::HiRes::time() - $ts, scalar @s_file_line_index, $t2 - $t1;
my $s_file_line = join("\n", @s_file_lines);
my $unique_dummies_found;
foreach my $i (@s_file_line_index) {
my ($line, $label) = $s_file_lines[$i -0] =~ m~pushsection __cwrap.*\.int (\d+); \.asciz "\$([^"]+)"~;
my ($pretty_function) = $s_file_line =~ m~$label\:\s+\.string\s+"([^"]+)"~s;
$log .= sprintf qq[%f - cwrap: pretty_function=%s\n], Time::HiRes::time() - $ts, $pretty_function if($debug_search);
cwrap_die(sprintf qq[%f ERROR: cwrap: cannot find pretty_function via label: %s!\n], Time::HiRes::time() - $ts, $label) if (not defined $pretty_function);
my $demangled = $pretty_function;
if ($demangled =~ m~ \[with ([^\s]+)\s*=\s*(.*)]~) { # e.g. my_type get_max(my_type, my_type) [with my_type = int]
# come here to make this e.g. int get_max<int>(int, int)
my ($my_var, $my_type) = ($1, $2);
$log .= sprintf qq[%f - cwrap: converting assembler to pretty function demangled function: %s\n], Time::HiRes::time() - $ts, $demangled if (not exists $h_demangled_2_mangled->{$demangled});
$demangled =~ s~$my_var~$my_type~g;
$demangled =~ s~\(~<$my_type>(~;
$demangled =~ s~ \[with .*~~; # stip [with ...] part
}
else {
while ($demangled =~ s~^[^\s\(]+\s+~~) {} # strip return type from e.g. unsigned char * my_func()
}
$log .= sprintf qq[%f - cwrap: demangled=%s\n], Time::HiRes::time() - $ts, $demangled if($debug_search);
$demangled = demangle_name_sanitize_type_order($demangled);
$log .= sprintf qq[%f - cwrap: demangled=%s <-- after type sanitization\n], Time::HiRes::time() - $ts, $demangled if($debug_search);
if (not exists $h_demangled_2_mangled->{$demangled}) {
# example $demangled: BroFunc::Call(val_list*, Frame*) const
# example in hash : BroFunc::Call(List<Val*>*, Frame*) const
$log .= sprintf qq[%f - cwrap: removing parameters (...) because cannot find demangled function: %s\n], Time::HiRes::time() - $ts, $demangled;
$demangled =~ s~\(.*$~~; # strip (<params>) from e.g. int main()
}
my $mangled;
if (exists $h_demangled_2_mangled->{$demangled}) {
# come here if found demangled name with parameters
$mangled = $h_demangled_2_mangled->{$demangled};
}
elsif ((exists $h_demangled_2_mangled_unique->{$demangled})
&& (1 == $h_demangled_2_mangled_unique->{$demangled})) {
# come here if found demangled name without parameters and only one such name exists
$mangled = $h_demangled_2_mangled_no_params->{$demangled};
}
else {
# come here if failed to find demangled name
foreach my $demangled_key (sort keys %{$h_demangled_2_mangled}) {
$log .= sprintf qq[%f - cwrap: non-matching demangled key: %d bytes: %s\n], Time::HiRes::time() - $ts, length($demangled_key), $demangled_key;
}
cwrap_die(sprintf qq[%f ERROR: cwrap: cannot find mangled function via demangled function: %s // via pretty function %s\n], Time::HiRes::time() - $ts, $demangled, $pretty_function);
}
$log .= sprintf qq[%f - cwrap: starting at line %d: %s; line=%d label=%s pretty_function=%s AKA %s mangled\n], Time::HiRes::time() - $ts, $i, pretty_asm($s_file_lines[$i -0]), $line, $label, $pretty_function, $mangled if($debug_search);
my $unique_dummy = sprintf qq[cwrap_data_verbosity_dummy_%u], $line;
if ($s_file_line =~ s~(\s+)[^\s\n\r]*$unique_dummy[^\s\n\r\@\,]*([\@\,])~$1cwrap_data_$mangled$2~) {
# e.g. movq cwrap_data_verbosity_dummy_8@GOTPCREL(%rip), %rax
# e.g. movq _ZN3Bro28cwrap_data_verbosity_dummy_0E@GOTPCREL(%rip), %rax
$unique_dummies_found->{$unique_dummy} ++;
}
else {
if (not exists $unique_dummies_found->{$unique_dummy}) {
# come here if no dummy references for this pushsection ever found
# note: if there is a pushsection then there need to be at least 1 dummy refenence!
my $short_s_file = $s_file;
$short_s_file =~ s~^.*/~~;
cwrap_die(sprintf qq[%f ERROR: internal: cwrap: cannot find %s in assembler file %s referenced by line %d!\n], Time::HiRes::time() - $ts, $unique_dummy, $short_s_file, $i);
}
else {
# note: sometimes there are more pushsections then dummy references, e.g.:
#
# c---example-1.a.s:40: .pushsection __cwrap, "S", @note; .int 4; .asciz "$__PRETTY_FUNCTION__.3212"; .popsection
# c---example-1.a.s:637: .pushsection __cwrap, "S", @note; .int 4; .asciz "$__PRETTY_FUNCTION__.3212"; .popsection
# c---example-1.a.s:1023: .pushsection __cwrap, "S", @note; .int 4; .asciz "$__PRETTY_FUNCTION__.3212"; .popsection
# c---example-1.a.s:1138: .pushsection __cwrap, "S", @note; .int 4; .asciz "$__PRETTY_FUNCTION__.3212"; .popsection
#
# c---example-1.a.s:46: movq cwrap_data_verbosity_dummy_4@GOTPCREL(%rip), %rax
# c---example-1.a.s:643: movq cwrap_data_verbosity_dummy_4@GOTPCREL(%rip), %rax
# c---example-1.a.s:1007: movq cwrap_data_verbosity_dummy_4@GOTPCREL(%rip), %r14
#
# c---example-1.a.s:4576: .string "cwrap_data_verbosity_dummy_4"
}
}
} # foreach my $i
#
# re-write any labels with dots!
#
if (scalar keys %{$h_labels_to_rewrite} > 0) {
$log .= sprintf qq[%f - cwrap: rewriting %d dodgy dot labels\n], Time::HiRes::time() - $ts, scalar keys %{$h_labels_to_rewrite};
foreach my $mangled_name_with_dot (keys %{$h_labels_to_rewrite}) {
my $mangled_name = $h_labels_to_rewrite->{$mangled_name_with_dot};
$log .= sprintf qq[%f - cwrap: rewriting dodgy dot label %s to %s\n], Time::HiRes::time() - $ts, $mangled_name_with_dot, $mangled_name;
$s_file_line =~ s~$mangled_name_with_dot~$mangled_name~gs;
}
}
$s_file_line =~ s~(\.string\s+)"[^ \n\r]*cwrap_data_verbosity_dummy_\d+[^ \n\r]*"~#$1 <-- cwrap string was here!~gs; # .string "cwrap_data_verbosity_dummy_10" or .string "_ZN3Bro28cwrap_data_verbosity_dummy_10E"
#
# write out modified assembler file
#
my $s_file_out = sprintf qq[%s.2.s], $s_file;
$log .= sprintf qq[%f - cwrap: assembler file: name : > %s\n], Time::HiRes::time() - $ts, $s_file_out;
open(my $out, '>', $s_file_out) || cwrap_die(sprintf qq[%f ERROR: cwrap cannot open file for writing: %s; $1\n], Time::HiRes::time() - $ts, $s_file_out);
$s_file_line .= "\n";
syswrite($out, $s_file_line, length($s_file_line));
close $out;
if ($s_file_line =~ m~(cwrap_data_verbosity_dummy_\d+)~s) {
cwrap_die(sprintf qq[%f ERROR: internal: cwrap: detected at least one unsubstituted temporary label: %s!\n], Time::HiRes::time() - $ts, $1);
}
} # read_modify_rewrite_assembler_file()
sub using_undefind_error_write_cwrap_c {
my ($output, $output_type) = @_; # output lines from nm or gxx command
my @output = split(m~\n~, $output);
$log .= sprintf qq[%f - cwrap: examining lines of %s output: %d\n], Time::HiRes::time() - $ts, $output_type, scalar @output;
if (0) { foreach my $line (@output) { $log .= sprintf qq[%f - cwrap: debug output: %s\n], Time::HiRes::time() - $ts, $line; } }
my $h;
if ($output_type eq 'nm') {
# come here to process output with undefineds from nm
foreach my $undefined (@output) {
chomp $undefined; # e.g. ../aux/paraglob/src/ahocorasick/libahocorasick.a:AhoCorasickPlus.cpp.o: U cwrap_data__ZNK9__gnu_cxx13new_allocatorIiE8max_sizeEv
next if ($undefined =~ m~cwrap_log_~); # do not generate cwrap_data structs for cwrap_log_*() functions
if ($undefined =~ m~^(.+?):\s+U\s+(.*)~) {
my ($file, $undefined_cwrap_data) = ($1, $2);
$h->{$undefined_cwrap_data} = $file if (not exists $h->{$undefined_cwrap_data});
}
else {
cwrap_die(sprintf qq[%f ERROR: internal: cwrap: do not understand nm output line: %s\n], Time::HiRes::time() - $ts, $undefined);
}
}
}
else {
# come here to process output with undefineds from gxx
my @undefined_errors = grep(m~undefined reference to .cwrap_data_~, @output); # e.g. cpp-example-1.cpp:5: undefined reference to `cwrap__Z8clean_upPi'
# first grab all the undefined error; note: gcc appears to spit them out in a random order!
foreach my $undefined_error (@undefined_errors) { # e.g. /usr/bin/ld: testCXXCompiler.cxx:(.text+0x1d): undefined reference to `cwrap_data_main'
next if ($undefined_error =~ m~cwrap_log_~);
chomp $undefined_error;
my ($source_file, $source_line, $missing_ref) = $undefined_error =~ m~([^/]+):([^\:]+): undefined reference to .(cwrap_[_A-Za-z0-9]+)~;
$h->{$missing_ref} = $source_file if (not exists $h->{$missing_ref});
}
}
$log .= sprintf qq[%f - cwrap: unique undefined cwrap_data_* symbols in nm output: %d\n], Time::HiRes::time() - $ts, scalar keys %{$h};
my @demangled_names; # e.g. int get_max<int>(int, int)
my @mangled_names; # e.g. _Z7get_maxIiET_S0_S0_
my @source_files;
foreach my $missing_ref (sort keys %{ $h }) { # sort because always want names in same order for test scripts
my $source_file = $h->{$missing_ref};
my ($mangled_name) = $missing_ref =~ m~cwrap_data_(.*)~;
push @source_files, $source_file;
push @mangled_names, $mangled_name; # e.g. _Z7get_maxIiET_S0_S0_
my $demangled_name = demangle_name($mangled_name);
push @demangled_names, $demangled_name; # e.g. int get_max<int>(int, int)
}
#todo: consider sorting the function names by demangled name instead of mangled name!
$log .= sprintf qq[%f - cwrap: writing %d missing cwrap structs to: %s\n], Time::HiRes::time() - $ts, scalar keys %{ $h }, $cwrap_c;
cwrap_die(sprintf qq[%f ERROR: internal: cwrap: zero cwrap structs; should never be zero\n], Time::HiRes::time() - $ts) if (0 == scalar keys %{ $h });
open(my $out, '>', $cwrap_c) || cwrap_die(sprintf qq[%f ERROR: cwrap: cannot open file for writing: %s\n], Time::HiRes::time() - $ts, $cwrap_c);
printf $out <<EOF;
#ifndef _GNU_SOURCE
#define _GNU_SOURCE /* See feature_test_macros(7) */
#endif
#include <unistd.h>
#include <sys/syscall.h> /* for syscall(), SYS_gettid */
#include <signal.h> /* for raise() */
#include <stdlib.h> /* for exit() */
#include <string.h> /* for memcmp() */
#include <stdio.h>
#include <stdarg.h>
#include <sys/time.h>
#include <locale.h>
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#ifdef COR_XXHASH_STACK
#define XXH_INLINE_ALL
#define XXH_STATIC_LINKING_ONLY
#include "xxhash.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
__attribute__ ((no_instrument_function)) void __cyg_profile_func_enter(void *func, void *callsite);
__attribute__ ((no_instrument_function)) void __cyg_profile_func_exit (void *func, void *callsite);
#define CWRAP_MAGIC (0x12345678)
typedef struct CWRAP_DATA CWRAP_DATA;
struct CWRAP_DATA {
int verbosity; // must be 1st structure member!
int magic;
int calls;
int variation_x;
int of_y_variations;
int bytes___mangled_name;
int bytes_demangled_name;
const char * name; int len_name; // generic demangled name
const char * file; int len_file;
void * func_addr;
CWRAP_DATA * next;
} __attribute__((packed));
#define CWRAP_LOG_LINE_MAX (256)
#ifndef CWRAP_LOG_NUM
#define CWRAP_LOG_NUM (0)
#endif
#ifndef CWRAP_LOG_CURT
#define CWRAP_LOG_CURT (0)
#endif
#ifndef CWRAP_LOG_FILE
#define CWRAP_LOG_FILE (0)
#endif
#ifndef CWRAP_LOG_COR_ID
#define CWRAP_LOG_COR_ID (1)
#endif
#ifndef CWRAP_LOG_LIMIT
#define CWRAP_LOG_LIMIT (10000)
#endif
#ifndef CWRAP_LOG_UNWIND
#define CWRAP_LOG_UNWIND (0)
#endif
#ifndef CWRAP_LOG_THREAD_ID
#define CWRAP_LOG_THREAD_ID (0)
#endif
#ifndef CWRAP_LOG_STACK_PTR
#define CWRAP_LOG_STACK_PTR (0)
#endif
#ifndef CWRAP_LOG_TIMESTAMP
#define CWRAP_LOG_TIMESTAMP (0)
#endif
#ifndef CWRAP_LOG_ON_VALGRIND
#define CWRAP_LOG_ON_VALGRIND (0)
#endif
#define COR_ID_MAX (1000)