summaryrefslogtreecommitdiff
path: root/python-elf-diff.spec
blob: ebb47a8df7a1df0871c99aa5ad0f7154b7fc4186 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
%global _empty_manifest_terminate_build 0
Name:		python-elf-diff
Version:	0.6.0
Release:	1
Summary:	A tool to compare elf binaries
License:	GPL 3
URL:		https://github.com/noseglasses/elf_diff
Source0:	https://mirrors.nju.edu.cn/pypi/web/packages/71/1e/09611cbc8660836c9f0de403eafcfb349f607a51311919b8db72bdfc241c/elf_diff-0.6.0.tar.gz
BuildArch:	noarch

Requires:	python3-setuptools-git
Requires:	python3-jinja2
Requires:	python3-pyyaml
Requires:	python3-progressbar2
Requires:	python3-GitPython
Requires:	python3-weasyprint
Requires:	python3-anytree
Requires:	python3-dict2xml

%description
[![PyPi version](https://badgen.net/pypi/v/elf_diff/)](https://pypi.org/project/elf_diff)
[![PyPi license](https://badgen.net/pypi/license/elf_diff/)](https://pypi.org/project/elf_diff/)
![Python Versions](https://img.shields.io/pypi/pyversions/elf_diff.svg?style=flat)
![Code style black](https://img.shields.io/badge/code%20style-black-black)
[![codecov](https://codecov.io/gh/noseglasses/elf_diff/branch/master/graph/badge.svg?token=4A71C5ZYM9)](https://codecov.io/gh/noseglasses/elf_diff)
[![Codacy Badge](https://app.codacy.com/project/badge/Grade/08f1e1dd9e3240799be5470e86ad5a58)](https://www.codacy.com/gh/noseglasses/elf_diff/dashboard?utm_source=github.com&utm_medium=referral&utm_content=noseglasses/elf_diff&utm_campaign=Badge_Grade)

![check code formatting](https://github.com/noseglasses/elf_diff/actions/workflows/black_code_formatting.yml/badge.svg)
![type checking](https://github.com/noseglasses/elf_diff/actions/workflows/type_checking_mypy.yml/badge.svg)
![CodeQL analysis](https://github.com/noseglasses/elf_diff/actions/workflows/codeql-analysis.yml/badge.svg)
![lint generated html](https://github.com/noseglasses/elf_diff/actions/workflows/lint_generated_html.yml/badge.svg)
![lint python](https://github.com/noseglasses/elf_diff/actions/workflows/lint_python_flake8.yml/badge.svg)
![lint documentation](https://github.com/noseglasses/elf_diff/actions/workflows/lint_README.yml/badge.svg)
![build](https://github.com/noseglasses/elf_diff/actions/workflows/local_package_build.yml/badge.svg)
![package installation](https://github.com/noseglasses/elf_diff/actions/workflows/venv_local_package_install.yml/badge.svg)
![test](https://github.com/noseglasses/elf_diff/actions/workflows/run_tests.yml/badge.svg)
![deploy](https://github.com/noseglasses/elf_diff/actions/workflows/package_deploy.yml/badge.svg)

<h1><img style="vertical-align:middle" src="https://github.com/noseglasses/elf_diff/blob/bb703f85ea24c7ee27998bb6b3e554843f31248c/images/favicon.png"> elf_diff - A Tool to Compare Elf Binaries</h1>

## Introduction

This tool compares pairs of ELF binary files and provides information about differences in the contained symbols with respect to the space that they occupy in program memory (functions and global data) and in RAM (global data). Binary pairs that are passed to _elf_diff_ are typically two versions of the same program/library/firmware. _elf_diff_ can help you to find out about the impact of your changes on your code's resource consumption.

The differences between the binaries are summarized in tables that contain information about persisting, disappeared and new symbols. _elf_diff_ also attempts to find pairs of matching symbols that might have been subject to renaming or signature changes (modified function arguments). Please be warned that the means to determine such symbol relations are very limited when working with binaries. False positives will result.

For all those symbols that have been subject to changes and also for the new and disappeared symbols, the tool provides diff-like comparisons of the disassembly.

The following types of output files are currently supported: HTML, PDF, YAML, JSON, XML, TXT.

HTML documents are cross-linked to conveniently allow jumping back and forth between bits of information, e.g. tabular information and symbol disassemblies. Du to the potentially large amount of information, some parts of the HTML reports are ommitted in the pdf files.

_elf_diff_ has two modes of operation, pair-reports and mass-reports. While the former compares two binaries, the latter generates an overview-report for a set of binary-pairs. Such overview-reports list only the changes in terms of symbol sizes and the amount of symbols, no disassembly is provided to gain feasible document sizes.

### Example

Assume you have two compiled versions of a software and you might be interested in the most prominent differences (and possibly the similarities) between both.

One way of comparing binaries is looking at the contained [symbols](https://en.wikipedia.org/wiki/Symbol_table). This is what _elf_diff_ does.

Let's start with exploring how differences in source code reflect in the symbols being created. 

For example, the following two C++ code snippets come with some subtle differences:

<table>
<tr>
<th> Version 1 (old) </th>
<th> Version 2 (new) </th>
</tr>
<tr>
<td>

```cpp
int func(int a) {
   return 42;
}

int var = 17;

class Test {
   public:
      
      static int f(int a, int b);
      int g(float a, float b);
      
   protected:
      
      static int m_;
};

int Test::f(int a, int b) { return 42; }
int Test::g(float a, float b) { return 1; }

int Test::m_ = 13;

int persisting1(int a) { return 43; }
int persisting2(int a) { return 43; }
```

</td>
<td>

```cpp
int func(double a) {
   return 42;
}

int var = 17;

class Test1 {
   public:
      
      static int f(int a, int b);
      int g(float a, float b);
      
   protected:
      
      static int m_;
};

int Test1::f(int a, int b) { return 42; }
int Test1::g(float a, float b) { return 1; }

int Test1::m_ = 13;

int persisting1(int a) { return 42; }
int persisting2(int a) { return 42; }
```

</td>
</tr>
</table>

Compiled and linked version of the two above code snippets can be found in the plaform specific subdirectories of the `tests` subdirectory of _elf_diff_ git repository. To generate a multi page pair report from these files, please install the _elf_diff_ Python packages as described in the installation section of this document. Then enter the following in a console on a Linux system. Please replace the placeholder `<elf_diff sandbox>` with the absolute path of your local _elf_diff_ sandbox.

```sh
python3 -m elf_diff --html_dir report <elf_diff sandbox>/tests/x86_64/libelf_diff_test_debug_old.a <elf_diff sandbox>/tests/x86_64/libelf_diff_test_debug_new.a
```

By means of its self contained HTML reports _elf_diff_ allows for conveniently analyzing the similarities and differences between the symbols contained
in [elf](https://en.wikipedia.org/wiki/Executable_and_Linkable_Format) files.

Please click on the table headers to proceed to the HTML pages that _elf_diff_ generated based on the above code example.

[Multi Page](https://noseglasses.github.io/elf_diff/examples/simple/pair_report_multi_page/index.html)                 |  [Single Page](https://noseglasses.github.io/elf_diff/examples/simple/pair_report_output.html)
:-------------------------:|:-------------------------:
![](https://github.com/noseglasses/elf_diff/blob/119a0b62c5d7faf2d0b7a958b46f7daf4ee8bcc7/examples/multi_page_pair_report.png)  |  ![](https://github.com/noseglasses/elf_diff/blob/119a0b62c5d7faf2d0b7a958b46f7daf4ee8bcc7/examples/single_page_pair_report.png)

To allow for convenient exchange and archiving, single page reports may also be generated in [pdf](https://github.com/noseglasses/elf_diff/blob/master/examples/elf_diff_test_static_1.pdf) format.

__Please__ __note__: If you are familiar with _elf_ _files_, the terms _symbol_ and _name_ _mangling_, you know how compilers and linkers transform 
high level language code into binary code and how this code is stored in elf files, you might want to skip the remaining parts of the introduction section.

### Content of Reports

Now, after you had a look at the different types of reports that _elf_diff_ generates, you might be interested in how the contained information is established.

As already mentioned, _elf_diff_ compares binaries based on the contained symbols.

#### Symbols

Symbols resulting from functions and variables like

```cpp
int Test1::f(int a, int b) { return 42; }

double a = 0.3;
``` 

have the following properties:

* a unique name (possibly including a namespace), e.g. `Test1::f`,
* a signature (functions), e.g. `(int a, int b)->int`,
* a symbol type (variable/constant/function and subtle variants of those),
* an extension (the amount of RAM or program memory that the symbol occupies, the latter only when compiled for [harvard architectures](https://en.wikipedia.org/wiki/Harvard_architecture)) and
* associated code/data.

__Please note:__ There are several other properties but those are not important for understanding what _elf_diff_ does.

#### A Brief Excursion About Name Mangling

You might be surprised that the _data_ _type_ of variables is not part of the above list.

This is because the variable data type is actually not stored in elf files. They are simply no more required after
the end of the compile process. At that point all variables have become named addresses of a memory areas of known extension.

It is simply sufficient that the compiled code knows what to do with such addresses and memory extensions.

Next, you might frown and ask why the same argument apparently does not apply to function signatures? Those are very well listed above.
Can't the compiler treat function parameters in the same way as variables?

There are several answers to that question. We will concentrate on the one that is, subjectively, most related to the current topic. The answer is: _function_ _overloading_.

Many high level languages (as e.g. C++) allow functions with idential names but different call signatures 
to be used in the same program, e.g.

```cpp
void f(double)
```
and 
```cpp
void f(int)
```

To avoid name clashes, compilers and linkers use an approach called [name mangling](https://en.wikipedia.org/wiki/Name_mangling) 
to convert names and signatures into so called _mangled_ _symbol_ _names_. 

The mangled names are what is actually stored in the elf files (unless [stripped](https://en.wikipedia.org/wiki/Strip_(Unix)).

Name mangling is, however, a reversible process. Compilers typically come with utilities that allow restoring name and signature from mangled names,
a process commonly called _demangling_ (e.g. by means of the tool [c++filt](https://sourceware.org/binutils/docs/binutils/c_002b_002bfilt.html) that is part of the GNU binutils suite).

We still haven't answered the question how symbols, or rather their properties can be used to find the differences between compiled binaries. So let's get back on track.

#### Comparing Symbols

When comparing two binaries one may group symbols based on their names and signatures (or their mangled names) as

* symbols present in both versions (persisting),
* symbols that are only found in version 2 (new) and
* those that are only present in version 1 (disappeared).

The code snippets initially presented are deliberatly written in a way that eases identifying related pairs of symbols in both versions.

Typically, software is subject to incremental transitions that affect only a quite limited number of symbols.

Symbols might be

* renamed or
* moved to another namespace (which includes being turned from a free function to a class method and vice versa).

Also, their

* signature (functions),
* implementation (functions) or
* data type (variables/constants)

might be changed.

#### Symbol Similarities

_elf_diff_ automatically detects and visualizes pairs of similar symbols. 

Unfortunatelly, in some cases the relations between symbols are not unique.

To help the user finding the most relevant symbol relations, _elf_diff_ displays the level of lexicographic similarity for every pair of similar symbols. 
For functions the level of lexicographic similarity of the two implementations is also displayed.

#### Highlighted Differences

To allow for conveniently analyzing implementation changes at the assembly level, the disassembled code is displayed side-by-side with differences being highlighted.

If debug information is contained in the binaries (flag `-g` of the gcc compiler),
the original high level language code annotates the assembly.

If you want to find out about other applications of _elf_diff_, please keep on reading.

Don't forget to have a look at the examples section at the end of this document.

## Purpose

* resource/performance optimization
* debugging
* learning/teaching

The main purpose of _elf_diff_ is to determine how specific changes to a piece of software affect resource consumption and performance. The tool may also serve to compare two independent change sets or just to have fun and learn how changes reflect in the generated assembly code.

The following information is part of _elf_diff_'s report pages:

* differences in the amount of program storage and static RAM usage
* symbols that are only present in one of the two versions
* symbols whose naming or call signature is similar in both versions, e.g. as a result of symbol renaming or subtly changing call signatures
* assembly code discrepancies of functions with identical names and call signatures

As _elf_diff_ operates on elf-files, it is fairly language and platform agnostic. All it requires to work is a suitable set of [GNU Binutils](https://en.wikipedia.org/wiki/GNU_Binutils) for the target platform.

## Requirements

_elf_diff_ is a Python script. It mostly uses standard libraries but also some non-standard packages (see the file `requirements.txt`) for more information.

_elf_diff_ works and is automatically tested with Python 3.

The following setup guide assumes Python 3 to be installed on your computer. Python setup tutorials can easily be found by googling "install python 3".

## Installing

Install the elf_diff Python package via one of the following commands

* `python3 -m pip install elf_diff` (Linux)
* `py -m pip install elf_diff` (Windows)
	 
__Please note:__ [PyPI](https://pypi.org/) the Python package index traditionally uses hyphens instead of underscores in package names. _pip_, however, happily supports both versions _elf_diff_ and _elf-diff_.

Alternatively when developing _elf_diff_, the following steps are required:

1. Clone the [_elf_diff_](https://github.com/noseglasses/elf_diff) repo from github.
2. Install any required packages via one of the following commands
   * `python3 -m pip install -r requirements.txt` (Linux)
   * `py -m pip install -r requirements.txt` (Windows)
3. Add the `bin` subdirectory of the _elf_diff_ repo to your platform search path (environment variable, e.g. `PATH`)

To run _elf_diff_ from the local git-sandbox, please use the script `bin/elf_diff` that is part of the source code repo, e.g. as `bin/elf_diff -h` to display the help string.

## Usage

There is a small difference between running Python on Linux and Windows. While the command to run Python 3 from a console window under Linux is `python3`, on Windows there is a so called _Python runner_ (command `py`) that invokes the most suitable Python interpreter installed.

To display _elf_diff_'s help page in a console window, type the following in a Linux console
```sh
python3 -m elf_diff -h
```
or
```sh
py -m elf_diff -h
```
in a Windows console.

In the examples provided below, we prefer the Linux syntax. Please replace the keyword `python3` with `py` when running the respective examples in a Windows environment.

### Generating Pair-Reports

To generate a pair report, two binary files need to be passed to _elf_diff_ via the command line. Let's assume those files are named `my_old_binary.elf` and `my_new_binary.elf`. 

The following command will generate a multipage html report in a subdirectory of your current working directory.
```sh
python3 -m elf_diff my_old_binary.elf my_new_binary.elf
```

### Generating Mass-Reports

__Please note:__ Mass reports have been deprecated and are likely removed from further versions of the software.

Mass reports require a driver file (yaml syntax) that specifies a list of binaries to compare pair-wise. 

Let's assume you have two pairs of binaries that reside in a directory `/home/my_user`.
```txt
binary_a_old.elf <-> binary_a_new.elf
binary_b_old.elf <-> binary_b_new.elf
```

A driver file (named `my_elf_diff_driver.yaml`) would then contain the following information:
```yaml
binary_pairs:
    - old_binary: "/home/my_user/binary_a_old.elf"
      new_binary: "/home/my_user/binary_a_new.elf"
      short_name: "A short name"
    - old_binary: "/home/my_user/binary_b_old.elf"
      new_binary: "/home/my_user/binary_b_new.elf"
      short_name: "B short name"
```

The `short_name` parameters are used in the result tables to reference the respective binary pairs.

By using the driver file, we can now run a mass-report as 
```sh
python3 -m elf_diff --mass_report --driver_file my_elf_diff_driver.yaml
```

This will generate a HTML file `elf_diff_mass_report.html` in your current working directory.

### Generating pdf-Files

The generation of pdf reports with _elf_diff_ requires the Python package [weasyprint](https://weasyprint.org). See the [weasyprint installation guide](https://doc.courtbouillon.org/weasyprint/stable/first_steps.html#installation) for more information.

__Please note:__ _elf_diff_ generates both types of html reports even without weasyprint being installed.

pdf files are generated by supplying the output file name using the parameter `pdf_file` either at the command line 

```sh
python3 -m elf_diff --pdf_file my_pair_report.pdf my_old_binary.elf my_new_binary.elf
```
or from within a driver file, e.g.
```yaml
pdf_file: "my_pair_report.pdf"
```

### Specifying an Alternative HTML File Location

Similar to specifying an explicit filename for pdf files, the same can be done for our HTML output files, either via the command line
```sh
python3 -m elf_diff --html_file my_pair_report.hmtl my_old_binary.elf my_new_binary.elf
```
or from within a driver file, e.g.
```yaml
html_file: "my_pair_report.html"
```
this will create a single file HTML report (with the exact same content as generated pdf files).

### Specifying an Alternative HTML Directory

To generate a multi-page HTML report use the command line flag `--html_dir` to generate the HTML files e.g. in directory `my_target_dir`.
```sh
python3 -m elf_diff --html_dir my_target_dir my_pair_report.hmtl my_old_binary.elf my_new_binary.elf
```

### Using Driver Files

The driver files that we already met when generating mass-reports can also generally be used to run _elf_diff_. Any parameters that can be passed as command line arguments to _elf_diff_ can also occur in a driver file, e.g.
```sh
python3 -m elf_diff --mass_report --pdf_file my_file.pdf ...
```
In `my_elf_diff_driver.yaml`
```yaml
mass_report: True
pdf_file: my_file.pdf
...
```
### Supplying a Project Title

A project title could e.g. be a short name that summarizes the changes that you applied between the old and the new version of the compared binaries. Supply a title via the parameter `project_title`.

### Adding Background Information

Additional information about the compared binaries can be added to pair-reports. Use the parameters `old_info_file` and `new_info_file` to supply filenames of text files whose content is supposed to be added to the report.

It is also possible to add general information to reports, e.g. about programming language or compiler version or about the build-system. This is supported through the `build_info` parameter which enables supplying a string that is added to the report. For longer strings, this can be conveniently done via the driver-file.

Everything that follows after `build_info: >` in the example will be added to the report.
```yaml
build_info: >
  This build
  info is added to the report.
  The whitespaces in front of these lines are removed, the line breaks are
  preserved.
```

### Using Alias Strings

If you want to obtain anonymized reports, it is not desirable to reveile details about your user name (home directory) or the directory structure. In such a case, the binary filenames can be replaced by alias wherever they would appear in the reports. 

Supply alias names using the `old_alias` and `new_alias` parameters for the old or the new version of the binaries, respectively.

### Working with Cross-Build Binaries

When working on firmware projects for embedded devices, you typically will be using a cross-build environment. If based on GNU gcc, such an environment usually not only ships with the necessary compilers but also with a set of additional tools called [GNU Binutils](https://en.wikipedia.org/wiki/GNU_Binutils).

_elf_diff_ uses some of these tools to inspect binaries, namely `nm`, `objdump` and `size`. Although some information about binaries can be determined even with the host-version of these tools, it is e.g. not possible to retreive disassemblies.

In a cross-build environment, Binutils executable are usually bundled in a specific directory. They also often have a platform-specific prefix, to make them distinguishabel from their host-platform siblings. For the [avr](https://en.wikipedia.org/wiki/AVR_microcontrollers)-version of Binutils e.g., that is shipped with the [Arduino](https://en.wikipedia.org/wiki/Arduino) development suite, the prefix `avr-` is used. The respective commands are, thus, named `avr-nm`, `avr-objdump` and `avr-size`.

To make those dedicated binaries known to _elf_diff_, please add the binutils directory to the PATH environment variable, use the parameters `bin_dir` and `bin_prefix` or explicitly define the 
commands e.g. `objdump_command` (see command help).

A pair-report generation command for the avr-plattform would e.g. read

```sh
python3 -m elf_diff --bin_dir <path_to_avr_binaries> --bin_prefix "avr-" my_old_binary.elf my_new_binary.elf
```
The string `<path_to_avr_binaries>` in the above example would of course be replaced by the actual directory path where the binaries live.

### Generating a Template Driver File

To generate a template driver file that can serve as a basis for your own
driver files, just run _elf_diff_ with the `driver_template_file` parameter, e.g. as
```sh
python3 -m elf_diff --driver_template_file my_template.yaml
```

Template files contain the default values of all available parameters, or - if the temple file is generated in the same session where a report was created - the template file will contain the actual settings used for the report generation.

### Selecting and Excluding Symbols

By means of the command line arguments `symbol_selection_regex` and `symbol_exclusion_regex`, symbols can be explicitly selected and excluded.
The specified regular expressions are applied to both the old and the old binary. For more fine grained selection, please used the `*_old` and `*_new` versions of the 
respective command line arguments.

### Skip Similar Symbols Detection

Similar symbol detection can be a very useful tool but it is a quite costly operation as it requires comparing all symbol names from one binary with all symbols from the other.
Assuming that both binaries contain `n` symbols this is a `O(n^2)` operation. Therefore it is up to the user to disabe similar symbol detection and output via the command
line argument `--skip_symbol_similarities`.

### Assembly Code

For most developers who are used to program in high level languages, assembly code is a mystery.
Still, there is some information that an assembly-novice can gather from observing assembly code. Starting with the number of assembly code statements. Normally less means good. The more assembly statements there are representing a high level language statement, the more time the processor needs to process them. On the contrary, sometimes there may be a suspiciously low number of assembly statements which might indicate that the compiler has optimized away something that it shouldn't have.

All this, of course, relies on the knowledge about what assembly code is associated with which line of source.
This information is not included in compiled binaries by default. The compiler must explicitly be told to export additional debugging information. For the gcc-compiler the flag `-g`, e.g., will cause this information to be emitted. But careful, some build systems when building debug versions replace optimization flags like `-O3` with the debug flag `-g`. This is not what you want when looking at the performance of your code. Instead you want to add the `-g` flag and keep the optimization flag(s) in place. CMake, e.g. has a configuration variable `CMAKE_BUILD_TYPE` that can be set to the value `RelWithDebInfo` to enable a release build (with optimization enabled) that also comes with debug symbols.

For binaries with debug symbols included, elf_diff will annotate the assembly code by adding the high level language statements that it was generated from.

### Dwarf Debug Info

If compiled with appropriate compiler flags (e.g. gcc's `-g`) generated binaries contain debug information in Dwarf-format that can be extracted
by using GNU binutils. If present, this debug information enables `elf_diff` to e.g. determine the location of definition of symbols in the
source code (file, line, column).

### Migrated Symbols

Debugging information available in elf files' Dwarf debug sections can be used to identify migrated symbols, i.e. those symbols that have been moved from one source file to another.

A symbol is identified as _migrated_ if it is a persisting symbol and if it's source file changed when comparing old and new binary.
If both binaries where compiled from different source trees, all persisting symbols will be identified as migrated. This is because
_elf_diff_ does a lexicographic comparison of source file paths.
In that case the configuration parameters _source_prefix_, _old_source_prefix_ or _new_source_prefix_ may be used to eliminate erroneously identified migratred symbols. This works by stripping path prefix from source file paths.

Example:

A symbol with new and old source files `/dir1/some/source_file.cpp` and `/dir2/some/source_file.cpp` is identified as migrated unless
the path prefix `/dir1/` and `/dir2/` are stripped off.

### Document Structure and Plugin System

When analyzing elf binaries and processing output, _elf_diff_ relies on a intermediate datastructure that it establishes after all symbols have been parsed
from the elf files. This data structure, called _elf_diff_ document, is the basis for the actual file export.

File export relies on dedicated data export plugins for (html, pdf, yaml, json, txt, ...). Plugins receive the _elf_diff_ document and can easily extract
and process its data to generate output of arbitrary type.

### User Defined Plugins

_elf_diff_'s plugin system enables developing user plugins, e.g. for custom output based on the _elf_diff_ document.
Custom plugins are registered via the command line flag `--load_plugin`, specifying the plugin's Python module path and the name of the plugin class
that is supposed to be loaded. Optionally the loaded plugin object can be parametrized by supplying parameter name value pairs.

The following example demonstrates how to load a plugin class `MyPluginClass` from a used defined module `my_plugin_module.py`.

```sh
python3 -m elf_diff --load_plugin "~/some/dir/my_plugin_module.py;MyPluginClass;my_arg1=42;my_arg2=bla" libfoo_old.a libfoo_new.a
```

This example of course assumes that the user plugin knows how to interpret the two parameters `my_arg1` and `my_arg2`.

Plugin classes must be derived from one of the plugin classes defined in elf_diff's module `plugin.py`. Please see elf_diff's default plugins
in the subdirectories of `<elf_diff_sandbox>/src/elf_diff/plugins` as a reference on how to implement custom plugins.

## Running the Tests

_elf_diff_ comes with a number of tests in the `tests` subdirectory of its git repository.
Some tests are unit tests others integration tests that run _elf_diff_ through
its CLI by supplying different command line parameter sets.

To run the entire test bench do the following.

```sh
cd <repo root>
python3 ./tests/test_main.py
```

### Running Individual Test Cases

Test cases reside in the directory `tests/test_cases` of _elf_diff_'s git repository.

To run individual tests, run the test driver and submit one or more tests using the command line arguments `-t`. To run e.g. the test case `test_command_line_args`, do as follows:

```sh
cd <repo root>
python3 ./tests/test_main.py -t test_command_line_args
```

## Examples

### Examples Page

See the [examples page](https://noseglasses.github.io/elf_diff/).

### libstdc++

[Comparison of two versions of libstdc++](https://github.com/noseglasses/elf_diff/blob/master/examples/libstdc++_std_string_diff.pdf) shipping with gcc 4.8 and 5. There are vast differences between those two library versions which result in a great number of symbols being reported. The following command demonstrates how report generation can be resticted to a subset of symbols by using regular expressions.
In the example we select only those symbols related to class `std::string`.

```sh
## Generated on Ubuntu 20.04 LTS
python3 -m elf_diff \
   --symbol_selection_regex "^std::string::.*"   # select any symbol name starting with std::string:: \
   --pdf_file libstdc++_std_string_diff.pdf      # generate a pdf file \
   /usr/lib/gcc/x86_64-linux-gnu/4.8/libstdc++.a # path to old binary \
   /usr/lib/gcc/x86_64-linux-gnu/5/libstdc++.a   # path to new binary
```

## Contributing

Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process
for submitting pull requests to us.

## Versioning

We use [SemVer](https://semver.org/) for versioning. For the versions available,
see the tags on this repository.

## Authors

* noseglasses - Initial work

## License

This project is licensed under the GNU General Public License Version 3
see the LICENSE.md file for details




%package -n python3-elf-diff
Summary:	A tool to compare elf binaries
Provides:	python-elf-diff
BuildRequires:	python3-devel
BuildRequires:	python3-setuptools
BuildRequires:	python3-pip
%description -n python3-elf-diff
[![PyPi version](https://badgen.net/pypi/v/elf_diff/)](https://pypi.org/project/elf_diff)
[![PyPi license](https://badgen.net/pypi/license/elf_diff/)](https://pypi.org/project/elf_diff/)
![Python Versions](https://img.shields.io/pypi/pyversions/elf_diff.svg?style=flat)
![Code style black](https://img.shields.io/badge/code%20style-black-black)
[![codecov](https://codecov.io/gh/noseglasses/elf_diff/branch/master/graph/badge.svg?token=4A71C5ZYM9)](https://codecov.io/gh/noseglasses/elf_diff)
[![Codacy Badge](https://app.codacy.com/project/badge/Grade/08f1e1dd9e3240799be5470e86ad5a58)](https://www.codacy.com/gh/noseglasses/elf_diff/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=noseglasses/elf_diff&amp;utm_campaign=Badge_Grade)

![check code formatting](https://github.com/noseglasses/elf_diff/actions/workflows/black_code_formatting.yml/badge.svg)
![type checking](https://github.com/noseglasses/elf_diff/actions/workflows/type_checking_mypy.yml/badge.svg)
![CodeQL analysis](https://github.com/noseglasses/elf_diff/actions/workflows/codeql-analysis.yml/badge.svg)
![lint generated html](https://github.com/noseglasses/elf_diff/actions/workflows/lint_generated_html.yml/badge.svg)
![lint python](https://github.com/noseglasses/elf_diff/actions/workflows/lint_python_flake8.yml/badge.svg)
![lint documentation](https://github.com/noseglasses/elf_diff/actions/workflows/lint_README.yml/badge.svg)
![build](https://github.com/noseglasses/elf_diff/actions/workflows/local_package_build.yml/badge.svg)
![package installation](https://github.com/noseglasses/elf_diff/actions/workflows/venv_local_package_install.yml/badge.svg)
![test](https://github.com/noseglasses/elf_diff/actions/workflows/run_tests.yml/badge.svg)
![deploy](https://github.com/noseglasses/elf_diff/actions/workflows/package_deploy.yml/badge.svg)

<h1><img style="vertical-align:middle" src="https://github.com/noseglasses/elf_diff/blob/bb703f85ea24c7ee27998bb6b3e554843f31248c/images/favicon.png"> elf_diff - A Tool to Compare Elf Binaries</h1>

## Introduction

This tool compares pairs of ELF binary files and provides information about differences in the contained symbols with respect to the space that they occupy in program memory (functions and global data) and in RAM (global data). Binary pairs that are passed to _elf_diff_ are typically two versions of the same program/library/firmware. _elf_diff_ can help you to find out about the impact of your changes on your code's resource consumption.

The differences between the binaries are summarized in tables that contain information about persisting, disappeared and new symbols. _elf_diff_ also attempts to find pairs of matching symbols that might have been subject to renaming or signature changes (modified function arguments). Please be warned that the means to determine such symbol relations are very limited when working with binaries. False positives will result.

For all those symbols that have been subject to changes and also for the new and disappeared symbols, the tool provides diff-like comparisons of the disassembly.

The following types of output files are currently supported: HTML, PDF, YAML, JSON, XML, TXT.

HTML documents are cross-linked to conveniently allow jumping back and forth between bits of information, e.g. tabular information and symbol disassemblies. Du to the potentially large amount of information, some parts of the HTML reports are ommitted in the pdf files.

_elf_diff_ has two modes of operation, pair-reports and mass-reports. While the former compares two binaries, the latter generates an overview-report for a set of binary-pairs. Such overview-reports list only the changes in terms of symbol sizes and the amount of symbols, no disassembly is provided to gain feasible document sizes.

### Example

Assume you have two compiled versions of a software and you might be interested in the most prominent differences (and possibly the similarities) between both.

One way of comparing binaries is looking at the contained [symbols](https://en.wikipedia.org/wiki/Symbol_table). This is what _elf_diff_ does.

Let's start with exploring how differences in source code reflect in the symbols being created. 

For example, the following two C++ code snippets come with some subtle differences:

<table>
<tr>
<th> Version 1 (old) </th>
<th> Version 2 (new) </th>
</tr>
<tr>
<td>

```cpp
int func(int a) {
   return 42;
}

int var = 17;

class Test {
   public:
      
      static int f(int a, int b);
      int g(float a, float b);
      
   protected:
      
      static int m_;
};

int Test::f(int a, int b) { return 42; }
int Test::g(float a, float b) { return 1; }

int Test::m_ = 13;

int persisting1(int a) { return 43; }
int persisting2(int a) { return 43; }
```

</td>
<td>

```cpp
int func(double a) {
   return 42;
}

int var = 17;

class Test1 {
   public:
      
      static int f(int a, int b);
      int g(float a, float b);
      
   protected:
      
      static int m_;
};

int Test1::f(int a, int b) { return 42; }
int Test1::g(float a, float b) { return 1; }

int Test1::m_ = 13;

int persisting1(int a) { return 42; }
int persisting2(int a) { return 42; }
```

</td>
</tr>
</table>

Compiled and linked version of the two above code snippets can be found in the plaform specific subdirectories of the `tests` subdirectory of _elf_diff_ git repository. To generate a multi page pair report from these files, please install the _elf_diff_ Python packages as described in the installation section of this document. Then enter the following in a console on a Linux system. Please replace the placeholder `<elf_diff sandbox>` with the absolute path of your local _elf_diff_ sandbox.

```sh
python3 -m elf_diff --html_dir report <elf_diff sandbox>/tests/x86_64/libelf_diff_test_debug_old.a <elf_diff sandbox>/tests/x86_64/libelf_diff_test_debug_new.a
```

By means of its self contained HTML reports _elf_diff_ allows for conveniently analyzing the similarities and differences between the symbols contained
in [elf](https://en.wikipedia.org/wiki/Executable_and_Linkable_Format) files.

Please click on the table headers to proceed to the HTML pages that _elf_diff_ generated based on the above code example.

[Multi Page](https://noseglasses.github.io/elf_diff/examples/simple/pair_report_multi_page/index.html)                 |  [Single Page](https://noseglasses.github.io/elf_diff/examples/simple/pair_report_output.html)
:-------------------------:|:-------------------------:
![](https://github.com/noseglasses/elf_diff/blob/119a0b62c5d7faf2d0b7a958b46f7daf4ee8bcc7/examples/multi_page_pair_report.png)  |  ![](https://github.com/noseglasses/elf_diff/blob/119a0b62c5d7faf2d0b7a958b46f7daf4ee8bcc7/examples/single_page_pair_report.png)

To allow for convenient exchange and archiving, single page reports may also be generated in [pdf](https://github.com/noseglasses/elf_diff/blob/master/examples/elf_diff_test_static_1.pdf) format.

__Please__ __note__: If you are familiar with _elf_ _files_, the terms _symbol_ and _name_ _mangling_, you know how compilers and linkers transform 
high level language code into binary code and how this code is stored in elf files, you might want to skip the remaining parts of the introduction section.

### Content of Reports

Now, after you had a look at the different types of reports that _elf_diff_ generates, you might be interested in how the contained information is established.

As already mentioned, _elf_diff_ compares binaries based on the contained symbols.

#### Symbols

Symbols resulting from functions and variables like

```cpp
int Test1::f(int a, int b) { return 42; }

double a = 0.3;
``` 

have the following properties:

* a unique name (possibly including a namespace), e.g. `Test1::f`,
* a signature (functions), e.g. `(int a, int b)->int`,
* a symbol type (variable/constant/function and subtle variants of those),
* an extension (the amount of RAM or program memory that the symbol occupies, the latter only when compiled for [harvard architectures](https://en.wikipedia.org/wiki/Harvard_architecture)) and
* associated code/data.

__Please note:__ There are several other properties but those are not important for understanding what _elf_diff_ does.

#### A Brief Excursion About Name Mangling

You might be surprised that the _data_ _type_ of variables is not part of the above list.

This is because the variable data type is actually not stored in elf files. They are simply no more required after
the end of the compile process. At that point all variables have become named addresses of a memory areas of known extension.

It is simply sufficient that the compiled code knows what to do with such addresses and memory extensions.

Next, you might frown and ask why the same argument apparently does not apply to function signatures? Those are very well listed above.
Can't the compiler treat function parameters in the same way as variables?

There are several answers to that question. We will concentrate on the one that is, subjectively, most related to the current topic. The answer is: _function_ _overloading_.

Many high level languages (as e.g. C++) allow functions with idential names but different call signatures 
to be used in the same program, e.g.

```cpp
void f(double)
```
and 
```cpp
void f(int)
```

To avoid name clashes, compilers and linkers use an approach called [name mangling](https://en.wikipedia.org/wiki/Name_mangling) 
to convert names and signatures into so called _mangled_ _symbol_ _names_. 

The mangled names are what is actually stored in the elf files (unless [stripped](https://en.wikipedia.org/wiki/Strip_(Unix)).

Name mangling is, however, a reversible process. Compilers typically come with utilities that allow restoring name and signature from mangled names,
a process commonly called _demangling_ (e.g. by means of the tool [c++filt](https://sourceware.org/binutils/docs/binutils/c_002b_002bfilt.html) that is part of the GNU binutils suite).

We still haven't answered the question how symbols, or rather their properties can be used to find the differences between compiled binaries. So let's get back on track.

#### Comparing Symbols

When comparing two binaries one may group symbols based on their names and signatures (or their mangled names) as

* symbols present in both versions (persisting),
* symbols that are only found in version 2 (new) and
* those that are only present in version 1 (disappeared).

The code snippets initially presented are deliberatly written in a way that eases identifying related pairs of symbols in both versions.

Typically, software is subject to incremental transitions that affect only a quite limited number of symbols.

Symbols might be

* renamed or
* moved to another namespace (which includes being turned from a free function to a class method and vice versa).

Also, their

* signature (functions),
* implementation (functions) or
* data type (variables/constants)

might be changed.

#### Symbol Similarities

_elf_diff_ automatically detects and visualizes pairs of similar symbols. 

Unfortunatelly, in some cases the relations between symbols are not unique.

To help the user finding the most relevant symbol relations, _elf_diff_ displays the level of lexicographic similarity for every pair of similar symbols. 
For functions the level of lexicographic similarity of the two implementations is also displayed.

#### Highlighted Differences

To allow for conveniently analyzing implementation changes at the assembly level, the disassembled code is displayed side-by-side with differences being highlighted.

If debug information is contained in the binaries (flag `-g` of the gcc compiler),
the original high level language code annotates the assembly.

If you want to find out about other applications of _elf_diff_, please keep on reading.

Don't forget to have a look at the examples section at the end of this document.

## Purpose

* resource/performance optimization
* debugging
* learning/teaching

The main purpose of _elf_diff_ is to determine how specific changes to a piece of software affect resource consumption and performance. The tool may also serve to compare two independent change sets or just to have fun and learn how changes reflect in the generated assembly code.

The following information is part of _elf_diff_'s report pages:

* differences in the amount of program storage and static RAM usage
* symbols that are only present in one of the two versions
* symbols whose naming or call signature is similar in both versions, e.g. as a result of symbol renaming or subtly changing call signatures
* assembly code discrepancies of functions with identical names and call signatures

As _elf_diff_ operates on elf-files, it is fairly language and platform agnostic. All it requires to work is a suitable set of [GNU Binutils](https://en.wikipedia.org/wiki/GNU_Binutils) for the target platform.

## Requirements

_elf_diff_ is a Python script. It mostly uses standard libraries but also some non-standard packages (see the file `requirements.txt`) for more information.

_elf_diff_ works and is automatically tested with Python 3.

The following setup guide assumes Python 3 to be installed on your computer. Python setup tutorials can easily be found by googling "install python 3".

## Installing

Install the elf_diff Python package via one of the following commands

* `python3 -m pip install elf_diff` (Linux)
* `py -m pip install elf_diff` (Windows)
	 
__Please note:__ [PyPI](https://pypi.org/) the Python package index traditionally uses hyphens instead of underscores in package names. _pip_, however, happily supports both versions _elf_diff_ and _elf-diff_.

Alternatively when developing _elf_diff_, the following steps are required:

1. Clone the [_elf_diff_](https://github.com/noseglasses/elf_diff) repo from github.
2. Install any required packages via one of the following commands
   * `python3 -m pip install -r requirements.txt` (Linux)
   * `py -m pip install -r requirements.txt` (Windows)
3. Add the `bin` subdirectory of the _elf_diff_ repo to your platform search path (environment variable, e.g. `PATH`)

To run _elf_diff_ from the local git-sandbox, please use the script `bin/elf_diff` that is part of the source code repo, e.g. as `bin/elf_diff -h` to display the help string.

## Usage

There is a small difference between running Python on Linux and Windows. While the command to run Python 3 from a console window under Linux is `python3`, on Windows there is a so called _Python runner_ (command `py`) that invokes the most suitable Python interpreter installed.

To display _elf_diff_'s help page in a console window, type the following in a Linux console
```sh
python3 -m elf_diff -h
```
or
```sh
py -m elf_diff -h
```
in a Windows console.

In the examples provided below, we prefer the Linux syntax. Please replace the keyword `python3` with `py` when running the respective examples in a Windows environment.

### Generating Pair-Reports

To generate a pair report, two binary files need to be passed to _elf_diff_ via the command line. Let's assume those files are named `my_old_binary.elf` and `my_new_binary.elf`. 

The following command will generate a multipage html report in a subdirectory of your current working directory.
```sh
python3 -m elf_diff my_old_binary.elf my_new_binary.elf
```

### Generating Mass-Reports

__Please note:__ Mass reports have been deprecated and are likely removed from further versions of the software.

Mass reports require a driver file (yaml syntax) that specifies a list of binaries to compare pair-wise. 

Let's assume you have two pairs of binaries that reside in a directory `/home/my_user`.
```txt
binary_a_old.elf <-> binary_a_new.elf
binary_b_old.elf <-> binary_b_new.elf
```

A driver file (named `my_elf_diff_driver.yaml`) would then contain the following information:
```yaml
binary_pairs:
    - old_binary: "/home/my_user/binary_a_old.elf"
      new_binary: "/home/my_user/binary_a_new.elf"
      short_name: "A short name"
    - old_binary: "/home/my_user/binary_b_old.elf"
      new_binary: "/home/my_user/binary_b_new.elf"
      short_name: "B short name"
```

The `short_name` parameters are used in the result tables to reference the respective binary pairs.

By using the driver file, we can now run a mass-report as 
```sh
python3 -m elf_diff --mass_report --driver_file my_elf_diff_driver.yaml
```

This will generate a HTML file `elf_diff_mass_report.html` in your current working directory.

### Generating pdf-Files

The generation of pdf reports with _elf_diff_ requires the Python package [weasyprint](https://weasyprint.org). See the [weasyprint installation guide](https://doc.courtbouillon.org/weasyprint/stable/first_steps.html#installation) for more information.

__Please note:__ _elf_diff_ generates both types of html reports even without weasyprint being installed.

pdf files are generated by supplying the output file name using the parameter `pdf_file` either at the command line 

```sh
python3 -m elf_diff --pdf_file my_pair_report.pdf my_old_binary.elf my_new_binary.elf
```
or from within a driver file, e.g.
```yaml
pdf_file: "my_pair_report.pdf"
```

### Specifying an Alternative HTML File Location

Similar to specifying an explicit filename for pdf files, the same can be done for our HTML output files, either via the command line
```sh
python3 -m elf_diff --html_file my_pair_report.hmtl my_old_binary.elf my_new_binary.elf
```
or from within a driver file, e.g.
```yaml
html_file: "my_pair_report.html"
```
this will create a single file HTML report (with the exact same content as generated pdf files).

### Specifying an Alternative HTML Directory

To generate a multi-page HTML report use the command line flag `--html_dir` to generate the HTML files e.g. in directory `my_target_dir`.
```sh
python3 -m elf_diff --html_dir my_target_dir my_pair_report.hmtl my_old_binary.elf my_new_binary.elf
```

### Using Driver Files

The driver files that we already met when generating mass-reports can also generally be used to run _elf_diff_. Any parameters that can be passed as command line arguments to _elf_diff_ can also occur in a driver file, e.g.
```sh
python3 -m elf_diff --mass_report --pdf_file my_file.pdf ...
```
In `my_elf_diff_driver.yaml`
```yaml
mass_report: True
pdf_file: my_file.pdf
...
```
### Supplying a Project Title

A project title could e.g. be a short name that summarizes the changes that you applied between the old and the new version of the compared binaries. Supply a title via the parameter `project_title`.

### Adding Background Information

Additional information about the compared binaries can be added to pair-reports. Use the parameters `old_info_file` and `new_info_file` to supply filenames of text files whose content is supposed to be added to the report.

It is also possible to add general information to reports, e.g. about programming language or compiler version or about the build-system. This is supported through the `build_info` parameter which enables supplying a string that is added to the report. For longer strings, this can be conveniently done via the driver-file.

Everything that follows after `build_info: >` in the example will be added to the report.
```yaml
build_info: >
  This build
  info is added to the report.
  The whitespaces in front of these lines are removed, the line breaks are
  preserved.
```

### Using Alias Strings

If you want to obtain anonymized reports, it is not desirable to reveile details about your user name (home directory) or the directory structure. In such a case, the binary filenames can be replaced by alias wherever they would appear in the reports. 

Supply alias names using the `old_alias` and `new_alias` parameters for the old or the new version of the binaries, respectively.

### Working with Cross-Build Binaries

When working on firmware projects for embedded devices, you typically will be using a cross-build environment. If based on GNU gcc, such an environment usually not only ships with the necessary compilers but also with a set of additional tools called [GNU Binutils](https://en.wikipedia.org/wiki/GNU_Binutils).

_elf_diff_ uses some of these tools to inspect binaries, namely `nm`, `objdump` and `size`. Although some information about binaries can be determined even with the host-version of these tools, it is e.g. not possible to retreive disassemblies.

In a cross-build environment, Binutils executable are usually bundled in a specific directory. They also often have a platform-specific prefix, to make them distinguishabel from their host-platform siblings. For the [avr](https://en.wikipedia.org/wiki/AVR_microcontrollers)-version of Binutils e.g., that is shipped with the [Arduino](https://en.wikipedia.org/wiki/Arduino) development suite, the prefix `avr-` is used. The respective commands are, thus, named `avr-nm`, `avr-objdump` and `avr-size`.

To make those dedicated binaries known to _elf_diff_, please add the binutils directory to the PATH environment variable, use the parameters `bin_dir` and `bin_prefix` or explicitly define the 
commands e.g. `objdump_command` (see command help).

A pair-report generation command for the avr-plattform would e.g. read

```sh
python3 -m elf_diff --bin_dir <path_to_avr_binaries> --bin_prefix "avr-" my_old_binary.elf my_new_binary.elf
```
The string `<path_to_avr_binaries>` in the above example would of course be replaced by the actual directory path where the binaries live.

### Generating a Template Driver File

To generate a template driver file that can serve as a basis for your own
driver files, just run _elf_diff_ with the `driver_template_file` parameter, e.g. as
```sh
python3 -m elf_diff --driver_template_file my_template.yaml
```

Template files contain the default values of all available parameters, or - if the temple file is generated in the same session where a report was created - the template file will contain the actual settings used for the report generation.

### Selecting and Excluding Symbols

By means of the command line arguments `symbol_selection_regex` and `symbol_exclusion_regex`, symbols can be explicitly selected and excluded.
The specified regular expressions are applied to both the old and the old binary. For more fine grained selection, please used the `*_old` and `*_new` versions of the 
respective command line arguments.

### Skip Similar Symbols Detection

Similar symbol detection can be a very useful tool but it is a quite costly operation as it requires comparing all symbol names from one binary with all symbols from the other.
Assuming that both binaries contain `n` symbols this is a `O(n^2)` operation. Therefore it is up to the user to disabe similar symbol detection and output via the command
line argument `--skip_symbol_similarities`.

### Assembly Code

For most developers who are used to program in high level languages, assembly code is a mystery.
Still, there is some information that an assembly-novice can gather from observing assembly code. Starting with the number of assembly code statements. Normally less means good. The more assembly statements there are representing a high level language statement, the more time the processor needs to process them. On the contrary, sometimes there may be a suspiciously low number of assembly statements which might indicate that the compiler has optimized away something that it shouldn't have.

All this, of course, relies on the knowledge about what assembly code is associated with which line of source.
This information is not included in compiled binaries by default. The compiler must explicitly be told to export additional debugging information. For the gcc-compiler the flag `-g`, e.g., will cause this information to be emitted. But careful, some build systems when building debug versions replace optimization flags like `-O3` with the debug flag `-g`. This is not what you want when looking at the performance of your code. Instead you want to add the `-g` flag and keep the optimization flag(s) in place. CMake, e.g. has a configuration variable `CMAKE_BUILD_TYPE` that can be set to the value `RelWithDebInfo` to enable a release build (with optimization enabled) that also comes with debug symbols.

For binaries with debug symbols included, elf_diff will annotate the assembly code by adding the high level language statements that it was generated from.

### Dwarf Debug Info

If compiled with appropriate compiler flags (e.g. gcc's `-g`) generated binaries contain debug information in Dwarf-format that can be extracted
by using GNU binutils. If present, this debug information enables `elf_diff` to e.g. determine the location of definition of symbols in the
source code (file, line, column).

### Migrated Symbols

Debugging information available in elf files' Dwarf debug sections can be used to identify migrated symbols, i.e. those symbols that have been moved from one source file to another.

A symbol is identified as _migrated_ if it is a persisting symbol and if it's source file changed when comparing old and new binary.
If both binaries where compiled from different source trees, all persisting symbols will be identified as migrated. This is because
_elf_diff_ does a lexicographic comparison of source file paths.
In that case the configuration parameters _source_prefix_, _old_source_prefix_ or _new_source_prefix_ may be used to eliminate erroneously identified migratred symbols. This works by stripping path prefix from source file paths.

Example:

A symbol with new and old source files `/dir1/some/source_file.cpp` and `/dir2/some/source_file.cpp` is identified as migrated unless
the path prefix `/dir1/` and `/dir2/` are stripped off.

### Document Structure and Plugin System

When analyzing elf binaries and processing output, _elf_diff_ relies on a intermediate datastructure that it establishes after all symbols have been parsed
from the elf files. This data structure, called _elf_diff_ document, is the basis for the actual file export.

File export relies on dedicated data export plugins for (html, pdf, yaml, json, txt, ...). Plugins receive the _elf_diff_ document and can easily extract
and process its data to generate output of arbitrary type.

### User Defined Plugins

_elf_diff_'s plugin system enables developing user plugins, e.g. for custom output based on the _elf_diff_ document.
Custom plugins are registered via the command line flag `--load_plugin`, specifying the plugin's Python module path and the name of the plugin class
that is supposed to be loaded. Optionally the loaded plugin object can be parametrized by supplying parameter name value pairs.

The following example demonstrates how to load a plugin class `MyPluginClass` from a used defined module `my_plugin_module.py`.

```sh
python3 -m elf_diff --load_plugin "~/some/dir/my_plugin_module.py;MyPluginClass;my_arg1=42;my_arg2=bla" libfoo_old.a libfoo_new.a
```

This example of course assumes that the user plugin knows how to interpret the two parameters `my_arg1` and `my_arg2`.

Plugin classes must be derived from one of the plugin classes defined in elf_diff's module `plugin.py`. Please see elf_diff's default plugins
in the subdirectories of `<elf_diff_sandbox>/src/elf_diff/plugins` as a reference on how to implement custom plugins.

## Running the Tests

_elf_diff_ comes with a number of tests in the `tests` subdirectory of its git repository.
Some tests are unit tests others integration tests that run _elf_diff_ through
its CLI by supplying different command line parameter sets.

To run the entire test bench do the following.

```sh
cd <repo root>
python3 ./tests/test_main.py
```

### Running Individual Test Cases

Test cases reside in the directory `tests/test_cases` of _elf_diff_'s git repository.

To run individual tests, run the test driver and submit one or more tests using the command line arguments `-t`. To run e.g. the test case `test_command_line_args`, do as follows:

```sh
cd <repo root>
python3 ./tests/test_main.py -t test_command_line_args
```

## Examples

### Examples Page

See the [examples page](https://noseglasses.github.io/elf_diff/).

### libstdc++

[Comparison of two versions of libstdc++](https://github.com/noseglasses/elf_diff/blob/master/examples/libstdc++_std_string_diff.pdf) shipping with gcc 4.8 and 5. There are vast differences between those two library versions which result in a great number of symbols being reported. The following command demonstrates how report generation can be resticted to a subset of symbols by using regular expressions.
In the example we select only those symbols related to class `std::string`.

```sh
## Generated on Ubuntu 20.04 LTS
python3 -m elf_diff \
   --symbol_selection_regex "^std::string::.*"   # select any symbol name starting with std::string:: \
   --pdf_file libstdc++_std_string_diff.pdf      # generate a pdf file \
   /usr/lib/gcc/x86_64-linux-gnu/4.8/libstdc++.a # path to old binary \
   /usr/lib/gcc/x86_64-linux-gnu/5/libstdc++.a   # path to new binary
```

## Contributing

Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process
for submitting pull requests to us.

## Versioning

We use [SemVer](https://semver.org/) for versioning. For the versions available,
see the tags on this repository.

## Authors

* noseglasses - Initial work

## License

This project is licensed under the GNU General Public License Version 3
see the LICENSE.md file for details




%package help
Summary:	Development documents and examples for elf-diff
Provides:	python3-elf-diff-doc
%description help
[![PyPi version](https://badgen.net/pypi/v/elf_diff/)](https://pypi.org/project/elf_diff)
[![PyPi license](https://badgen.net/pypi/license/elf_diff/)](https://pypi.org/project/elf_diff/)
![Python Versions](https://img.shields.io/pypi/pyversions/elf_diff.svg?style=flat)
![Code style black](https://img.shields.io/badge/code%20style-black-black)
[![codecov](https://codecov.io/gh/noseglasses/elf_diff/branch/master/graph/badge.svg?token=4A71C5ZYM9)](https://codecov.io/gh/noseglasses/elf_diff)
[![Codacy Badge](https://app.codacy.com/project/badge/Grade/08f1e1dd9e3240799be5470e86ad5a58)](https://www.codacy.com/gh/noseglasses/elf_diff/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=noseglasses/elf_diff&amp;utm_campaign=Badge_Grade)

![check code formatting](https://github.com/noseglasses/elf_diff/actions/workflows/black_code_formatting.yml/badge.svg)
![type checking](https://github.com/noseglasses/elf_diff/actions/workflows/type_checking_mypy.yml/badge.svg)
![CodeQL analysis](https://github.com/noseglasses/elf_diff/actions/workflows/codeql-analysis.yml/badge.svg)
![lint generated html](https://github.com/noseglasses/elf_diff/actions/workflows/lint_generated_html.yml/badge.svg)
![lint python](https://github.com/noseglasses/elf_diff/actions/workflows/lint_python_flake8.yml/badge.svg)
![lint documentation](https://github.com/noseglasses/elf_diff/actions/workflows/lint_README.yml/badge.svg)
![build](https://github.com/noseglasses/elf_diff/actions/workflows/local_package_build.yml/badge.svg)
![package installation](https://github.com/noseglasses/elf_diff/actions/workflows/venv_local_package_install.yml/badge.svg)
![test](https://github.com/noseglasses/elf_diff/actions/workflows/run_tests.yml/badge.svg)
![deploy](https://github.com/noseglasses/elf_diff/actions/workflows/package_deploy.yml/badge.svg)

<h1><img style="vertical-align:middle" src="https://github.com/noseglasses/elf_diff/blob/bb703f85ea24c7ee27998bb6b3e554843f31248c/images/favicon.png"> elf_diff - A Tool to Compare Elf Binaries</h1>

## Introduction

This tool compares pairs of ELF binary files and provides information about differences in the contained symbols with respect to the space that they occupy in program memory (functions and global data) and in RAM (global data). Binary pairs that are passed to _elf_diff_ are typically two versions of the same program/library/firmware. _elf_diff_ can help you to find out about the impact of your changes on your code's resource consumption.

The differences between the binaries are summarized in tables that contain information about persisting, disappeared and new symbols. _elf_diff_ also attempts to find pairs of matching symbols that might have been subject to renaming or signature changes (modified function arguments). Please be warned that the means to determine such symbol relations are very limited when working with binaries. False positives will result.

For all those symbols that have been subject to changes and also for the new and disappeared symbols, the tool provides diff-like comparisons of the disassembly.

The following types of output files are currently supported: HTML, PDF, YAML, JSON, XML, TXT.

HTML documents are cross-linked to conveniently allow jumping back and forth between bits of information, e.g. tabular information and symbol disassemblies. Du to the potentially large amount of information, some parts of the HTML reports are ommitted in the pdf files.

_elf_diff_ has two modes of operation, pair-reports and mass-reports. While the former compares two binaries, the latter generates an overview-report for a set of binary-pairs. Such overview-reports list only the changes in terms of symbol sizes and the amount of symbols, no disassembly is provided to gain feasible document sizes.

### Example

Assume you have two compiled versions of a software and you might be interested in the most prominent differences (and possibly the similarities) between both.

One way of comparing binaries is looking at the contained [symbols](https://en.wikipedia.org/wiki/Symbol_table). This is what _elf_diff_ does.

Let's start with exploring how differences in source code reflect in the symbols being created. 

For example, the following two C++ code snippets come with some subtle differences:

<table>
<tr>
<th> Version 1 (old) </th>
<th> Version 2 (new) </th>
</tr>
<tr>
<td>

```cpp
int func(int a) {
   return 42;
}

int var = 17;

class Test {
   public:
      
      static int f(int a, int b);
      int g(float a, float b);
      
   protected:
      
      static int m_;
};

int Test::f(int a, int b) { return 42; }
int Test::g(float a, float b) { return 1; }

int Test::m_ = 13;

int persisting1(int a) { return 43; }
int persisting2(int a) { return 43; }
```

</td>
<td>

```cpp
int func(double a) {
   return 42;
}

int var = 17;

class Test1 {
   public:
      
      static int f(int a, int b);
      int g(float a, float b);
      
   protected:
      
      static int m_;
};

int Test1::f(int a, int b) { return 42; }
int Test1::g(float a, float b) { return 1; }

int Test1::m_ = 13;

int persisting1(int a) { return 42; }
int persisting2(int a) { return 42; }
```

</td>
</tr>
</table>

Compiled and linked version of the two above code snippets can be found in the plaform specific subdirectories of the `tests` subdirectory of _elf_diff_ git repository. To generate a multi page pair report from these files, please install the _elf_diff_ Python packages as described in the installation section of this document. Then enter the following in a console on a Linux system. Please replace the placeholder `<elf_diff sandbox>` with the absolute path of your local _elf_diff_ sandbox.

```sh
python3 -m elf_diff --html_dir report <elf_diff sandbox>/tests/x86_64/libelf_diff_test_debug_old.a <elf_diff sandbox>/tests/x86_64/libelf_diff_test_debug_new.a
```

By means of its self contained HTML reports _elf_diff_ allows for conveniently analyzing the similarities and differences between the symbols contained
in [elf](https://en.wikipedia.org/wiki/Executable_and_Linkable_Format) files.

Please click on the table headers to proceed to the HTML pages that _elf_diff_ generated based on the above code example.

[Multi Page](https://noseglasses.github.io/elf_diff/examples/simple/pair_report_multi_page/index.html)                 |  [Single Page](https://noseglasses.github.io/elf_diff/examples/simple/pair_report_output.html)
:-------------------------:|:-------------------------:
![](https://github.com/noseglasses/elf_diff/blob/119a0b62c5d7faf2d0b7a958b46f7daf4ee8bcc7/examples/multi_page_pair_report.png)  |  ![](https://github.com/noseglasses/elf_diff/blob/119a0b62c5d7faf2d0b7a958b46f7daf4ee8bcc7/examples/single_page_pair_report.png)

To allow for convenient exchange and archiving, single page reports may also be generated in [pdf](https://github.com/noseglasses/elf_diff/blob/master/examples/elf_diff_test_static_1.pdf) format.

__Please__ __note__: If you are familiar with _elf_ _files_, the terms _symbol_ and _name_ _mangling_, you know how compilers and linkers transform 
high level language code into binary code and how this code is stored in elf files, you might want to skip the remaining parts of the introduction section.

### Content of Reports

Now, after you had a look at the different types of reports that _elf_diff_ generates, you might be interested in how the contained information is established.

As already mentioned, _elf_diff_ compares binaries based on the contained symbols.

#### Symbols

Symbols resulting from functions and variables like

```cpp
int Test1::f(int a, int b) { return 42; }

double a = 0.3;
``` 

have the following properties:

* a unique name (possibly including a namespace), e.g. `Test1::f`,
* a signature (functions), e.g. `(int a, int b)->int`,
* a symbol type (variable/constant/function and subtle variants of those),
* an extension (the amount of RAM or program memory that the symbol occupies, the latter only when compiled for [harvard architectures](https://en.wikipedia.org/wiki/Harvard_architecture)) and
* associated code/data.

__Please note:__ There are several other properties but those are not important for understanding what _elf_diff_ does.

#### A Brief Excursion About Name Mangling

You might be surprised that the _data_ _type_ of variables is not part of the above list.

This is because the variable data type is actually not stored in elf files. They are simply no more required after
the end of the compile process. At that point all variables have become named addresses of a memory areas of known extension.

It is simply sufficient that the compiled code knows what to do with such addresses and memory extensions.

Next, you might frown and ask why the same argument apparently does not apply to function signatures? Those are very well listed above.
Can't the compiler treat function parameters in the same way as variables?

There are several answers to that question. We will concentrate on the one that is, subjectively, most related to the current topic. The answer is: _function_ _overloading_.

Many high level languages (as e.g. C++) allow functions with idential names but different call signatures 
to be used in the same program, e.g.

```cpp
void f(double)
```
and 
```cpp
void f(int)
```

To avoid name clashes, compilers and linkers use an approach called [name mangling](https://en.wikipedia.org/wiki/Name_mangling) 
to convert names and signatures into so called _mangled_ _symbol_ _names_. 

The mangled names are what is actually stored in the elf files (unless [stripped](https://en.wikipedia.org/wiki/Strip_(Unix)).

Name mangling is, however, a reversible process. Compilers typically come with utilities that allow restoring name and signature from mangled names,
a process commonly called _demangling_ (e.g. by means of the tool [c++filt](https://sourceware.org/binutils/docs/binutils/c_002b_002bfilt.html) that is part of the GNU binutils suite).

We still haven't answered the question how symbols, or rather their properties can be used to find the differences between compiled binaries. So let's get back on track.

#### Comparing Symbols

When comparing two binaries one may group symbols based on their names and signatures (or their mangled names) as

* symbols present in both versions (persisting),
* symbols that are only found in version 2 (new) and
* those that are only present in version 1 (disappeared).

The code snippets initially presented are deliberatly written in a way that eases identifying related pairs of symbols in both versions.

Typically, software is subject to incremental transitions that affect only a quite limited number of symbols.

Symbols might be

* renamed or
* moved to another namespace (which includes being turned from a free function to a class method and vice versa).

Also, their

* signature (functions),
* implementation (functions) or
* data type (variables/constants)

might be changed.

#### Symbol Similarities

_elf_diff_ automatically detects and visualizes pairs of similar symbols. 

Unfortunatelly, in some cases the relations between symbols are not unique.

To help the user finding the most relevant symbol relations, _elf_diff_ displays the level of lexicographic similarity for every pair of similar symbols. 
For functions the level of lexicographic similarity of the two implementations is also displayed.

#### Highlighted Differences

To allow for conveniently analyzing implementation changes at the assembly level, the disassembled code is displayed side-by-side with differences being highlighted.

If debug information is contained in the binaries (flag `-g` of the gcc compiler),
the original high level language code annotates the assembly.

If you want to find out about other applications of _elf_diff_, please keep on reading.

Don't forget to have a look at the examples section at the end of this document.

## Purpose

* resource/performance optimization
* debugging
* learning/teaching

The main purpose of _elf_diff_ is to determine how specific changes to a piece of software affect resource consumption and performance. The tool may also serve to compare two independent change sets or just to have fun and learn how changes reflect in the generated assembly code.

The following information is part of _elf_diff_'s report pages:

* differences in the amount of program storage and static RAM usage
* symbols that are only present in one of the two versions
* symbols whose naming or call signature is similar in both versions, e.g. as a result of symbol renaming or subtly changing call signatures
* assembly code discrepancies of functions with identical names and call signatures

As _elf_diff_ operates on elf-files, it is fairly language and platform agnostic. All it requires to work is a suitable set of [GNU Binutils](https://en.wikipedia.org/wiki/GNU_Binutils) for the target platform.

## Requirements

_elf_diff_ is a Python script. It mostly uses standard libraries but also some non-standard packages (see the file `requirements.txt`) for more information.

_elf_diff_ works and is automatically tested with Python 3.

The following setup guide assumes Python 3 to be installed on your computer. Python setup tutorials can easily be found by googling "install python 3".

## Installing

Install the elf_diff Python package via one of the following commands

* `python3 -m pip install elf_diff` (Linux)
* `py -m pip install elf_diff` (Windows)
	 
__Please note:__ [PyPI](https://pypi.org/) the Python package index traditionally uses hyphens instead of underscores in package names. _pip_, however, happily supports both versions _elf_diff_ and _elf-diff_.

Alternatively when developing _elf_diff_, the following steps are required:

1. Clone the [_elf_diff_](https://github.com/noseglasses/elf_diff) repo from github.
2. Install any required packages via one of the following commands
   * `python3 -m pip install -r requirements.txt` (Linux)
   * `py -m pip install -r requirements.txt` (Windows)
3. Add the `bin` subdirectory of the _elf_diff_ repo to your platform search path (environment variable, e.g. `PATH`)

To run _elf_diff_ from the local git-sandbox, please use the script `bin/elf_diff` that is part of the source code repo, e.g. as `bin/elf_diff -h` to display the help string.

## Usage

There is a small difference between running Python on Linux and Windows. While the command to run Python 3 from a console window under Linux is `python3`, on Windows there is a so called _Python runner_ (command `py`) that invokes the most suitable Python interpreter installed.

To display _elf_diff_'s help page in a console window, type the following in a Linux console
```sh
python3 -m elf_diff -h
```
or
```sh
py -m elf_diff -h
```
in a Windows console.

In the examples provided below, we prefer the Linux syntax. Please replace the keyword `python3` with `py` when running the respective examples in a Windows environment.

### Generating Pair-Reports

To generate a pair report, two binary files need to be passed to _elf_diff_ via the command line. Let's assume those files are named `my_old_binary.elf` and `my_new_binary.elf`. 

The following command will generate a multipage html report in a subdirectory of your current working directory.
```sh
python3 -m elf_diff my_old_binary.elf my_new_binary.elf
```

### Generating Mass-Reports

__Please note:__ Mass reports have been deprecated and are likely removed from further versions of the software.

Mass reports require a driver file (yaml syntax) that specifies a list of binaries to compare pair-wise. 

Let's assume you have two pairs of binaries that reside in a directory `/home/my_user`.
```txt
binary_a_old.elf <-> binary_a_new.elf
binary_b_old.elf <-> binary_b_new.elf
```

A driver file (named `my_elf_diff_driver.yaml`) would then contain the following information:
```yaml
binary_pairs:
    - old_binary: "/home/my_user/binary_a_old.elf"
      new_binary: "/home/my_user/binary_a_new.elf"
      short_name: "A short name"
    - old_binary: "/home/my_user/binary_b_old.elf"
      new_binary: "/home/my_user/binary_b_new.elf"
      short_name: "B short name"
```

The `short_name` parameters are used in the result tables to reference the respective binary pairs.

By using the driver file, we can now run a mass-report as 
```sh
python3 -m elf_diff --mass_report --driver_file my_elf_diff_driver.yaml
```

This will generate a HTML file `elf_diff_mass_report.html` in your current working directory.

### Generating pdf-Files

The generation of pdf reports with _elf_diff_ requires the Python package [weasyprint](https://weasyprint.org). See the [weasyprint installation guide](https://doc.courtbouillon.org/weasyprint/stable/first_steps.html#installation) for more information.

__Please note:__ _elf_diff_ generates both types of html reports even without weasyprint being installed.

pdf files are generated by supplying the output file name using the parameter `pdf_file` either at the command line 

```sh
python3 -m elf_diff --pdf_file my_pair_report.pdf my_old_binary.elf my_new_binary.elf
```
or from within a driver file, e.g.
```yaml
pdf_file: "my_pair_report.pdf"
```

### Specifying an Alternative HTML File Location

Similar to specifying an explicit filename for pdf files, the same can be done for our HTML output files, either via the command line
```sh
python3 -m elf_diff --html_file my_pair_report.hmtl my_old_binary.elf my_new_binary.elf
```
or from within a driver file, e.g.
```yaml
html_file: "my_pair_report.html"
```
this will create a single file HTML report (with the exact same content as generated pdf files).

### Specifying an Alternative HTML Directory

To generate a multi-page HTML report use the command line flag `--html_dir` to generate the HTML files e.g. in directory `my_target_dir`.
```sh
python3 -m elf_diff --html_dir my_target_dir my_pair_report.hmtl my_old_binary.elf my_new_binary.elf
```

### Using Driver Files

The driver files that we already met when generating mass-reports can also generally be used to run _elf_diff_. Any parameters that can be passed as command line arguments to _elf_diff_ can also occur in a driver file, e.g.
```sh
python3 -m elf_diff --mass_report --pdf_file my_file.pdf ...
```
In `my_elf_diff_driver.yaml`
```yaml
mass_report: True
pdf_file: my_file.pdf
...
```
### Supplying a Project Title

A project title could e.g. be a short name that summarizes the changes that you applied between the old and the new version of the compared binaries. Supply a title via the parameter `project_title`.

### Adding Background Information

Additional information about the compared binaries can be added to pair-reports. Use the parameters `old_info_file` and `new_info_file` to supply filenames of text files whose content is supposed to be added to the report.

It is also possible to add general information to reports, e.g. about programming language or compiler version or about the build-system. This is supported through the `build_info` parameter which enables supplying a string that is added to the report. For longer strings, this can be conveniently done via the driver-file.

Everything that follows after `build_info: >` in the example will be added to the report.
```yaml
build_info: >
  This build
  info is added to the report.
  The whitespaces in front of these lines are removed, the line breaks are
  preserved.
```

### Using Alias Strings

If you want to obtain anonymized reports, it is not desirable to reveile details about your user name (home directory) or the directory structure. In such a case, the binary filenames can be replaced by alias wherever they would appear in the reports. 

Supply alias names using the `old_alias` and `new_alias` parameters for the old or the new version of the binaries, respectively.

### Working with Cross-Build Binaries

When working on firmware projects for embedded devices, you typically will be using a cross-build environment. If based on GNU gcc, such an environment usually not only ships with the necessary compilers but also with a set of additional tools called [GNU Binutils](https://en.wikipedia.org/wiki/GNU_Binutils).

_elf_diff_ uses some of these tools to inspect binaries, namely `nm`, `objdump` and `size`. Although some information about binaries can be determined even with the host-version of these tools, it is e.g. not possible to retreive disassemblies.

In a cross-build environment, Binutils executable are usually bundled in a specific directory. They also often have a platform-specific prefix, to make them distinguishabel from their host-platform siblings. For the [avr](https://en.wikipedia.org/wiki/AVR_microcontrollers)-version of Binutils e.g., that is shipped with the [Arduino](https://en.wikipedia.org/wiki/Arduino) development suite, the prefix `avr-` is used. The respective commands are, thus, named `avr-nm`, `avr-objdump` and `avr-size`.

To make those dedicated binaries known to _elf_diff_, please add the binutils directory to the PATH environment variable, use the parameters `bin_dir` and `bin_prefix` or explicitly define the 
commands e.g. `objdump_command` (see command help).

A pair-report generation command for the avr-plattform would e.g. read

```sh
python3 -m elf_diff --bin_dir <path_to_avr_binaries> --bin_prefix "avr-" my_old_binary.elf my_new_binary.elf
```
The string `<path_to_avr_binaries>` in the above example would of course be replaced by the actual directory path where the binaries live.

### Generating a Template Driver File

To generate a template driver file that can serve as a basis for your own
driver files, just run _elf_diff_ with the `driver_template_file` parameter, e.g. as
```sh
python3 -m elf_diff --driver_template_file my_template.yaml
```

Template files contain the default values of all available parameters, or - if the temple file is generated in the same session where a report was created - the template file will contain the actual settings used for the report generation.

### Selecting and Excluding Symbols

By means of the command line arguments `symbol_selection_regex` and `symbol_exclusion_regex`, symbols can be explicitly selected and excluded.
The specified regular expressions are applied to both the old and the old binary. For more fine grained selection, please used the `*_old` and `*_new` versions of the 
respective command line arguments.

### Skip Similar Symbols Detection

Similar symbol detection can be a very useful tool but it is a quite costly operation as it requires comparing all symbol names from one binary with all symbols from the other.
Assuming that both binaries contain `n` symbols this is a `O(n^2)` operation. Therefore it is up to the user to disabe similar symbol detection and output via the command
line argument `--skip_symbol_similarities`.

### Assembly Code

For most developers who are used to program in high level languages, assembly code is a mystery.
Still, there is some information that an assembly-novice can gather from observing assembly code. Starting with the number of assembly code statements. Normally less means good. The more assembly statements there are representing a high level language statement, the more time the processor needs to process them. On the contrary, sometimes there may be a suspiciously low number of assembly statements which might indicate that the compiler has optimized away something that it shouldn't have.

All this, of course, relies on the knowledge about what assembly code is associated with which line of source.
This information is not included in compiled binaries by default. The compiler must explicitly be told to export additional debugging information. For the gcc-compiler the flag `-g`, e.g., will cause this information to be emitted. But careful, some build systems when building debug versions replace optimization flags like `-O3` with the debug flag `-g`. This is not what you want when looking at the performance of your code. Instead you want to add the `-g` flag and keep the optimization flag(s) in place. CMake, e.g. has a configuration variable `CMAKE_BUILD_TYPE` that can be set to the value `RelWithDebInfo` to enable a release build (with optimization enabled) that also comes with debug symbols.

For binaries with debug symbols included, elf_diff will annotate the assembly code by adding the high level language statements that it was generated from.

### Dwarf Debug Info

If compiled with appropriate compiler flags (e.g. gcc's `-g`) generated binaries contain debug information in Dwarf-format that can be extracted
by using GNU binutils. If present, this debug information enables `elf_diff` to e.g. determine the location of definition of symbols in the
source code (file, line, column).

### Migrated Symbols

Debugging information available in elf files' Dwarf debug sections can be used to identify migrated symbols, i.e. those symbols that have been moved from one source file to another.

A symbol is identified as _migrated_ if it is a persisting symbol and if it's source file changed when comparing old and new binary.
If both binaries where compiled from different source trees, all persisting symbols will be identified as migrated. This is because
_elf_diff_ does a lexicographic comparison of source file paths.
In that case the configuration parameters _source_prefix_, _old_source_prefix_ or _new_source_prefix_ may be used to eliminate erroneously identified migratred symbols. This works by stripping path prefix from source file paths.

Example:

A symbol with new and old source files `/dir1/some/source_file.cpp` and `/dir2/some/source_file.cpp` is identified as migrated unless
the path prefix `/dir1/` and `/dir2/` are stripped off.

### Document Structure and Plugin System

When analyzing elf binaries and processing output, _elf_diff_ relies on a intermediate datastructure that it establishes after all symbols have been parsed
from the elf files. This data structure, called _elf_diff_ document, is the basis for the actual file export.

File export relies on dedicated data export plugins for (html, pdf, yaml, json, txt, ...). Plugins receive the _elf_diff_ document and can easily extract
and process its data to generate output of arbitrary type.

### User Defined Plugins

_elf_diff_'s plugin system enables developing user plugins, e.g. for custom output based on the _elf_diff_ document.
Custom plugins are registered via the command line flag `--load_plugin`, specifying the plugin's Python module path and the name of the plugin class
that is supposed to be loaded. Optionally the loaded plugin object can be parametrized by supplying parameter name value pairs.

The following example demonstrates how to load a plugin class `MyPluginClass` from a used defined module `my_plugin_module.py`.

```sh
python3 -m elf_diff --load_plugin "~/some/dir/my_plugin_module.py;MyPluginClass;my_arg1=42;my_arg2=bla" libfoo_old.a libfoo_new.a
```

This example of course assumes that the user plugin knows how to interpret the two parameters `my_arg1` and `my_arg2`.

Plugin classes must be derived from one of the plugin classes defined in elf_diff's module `plugin.py`. Please see elf_diff's default plugins
in the subdirectories of `<elf_diff_sandbox>/src/elf_diff/plugins` as a reference on how to implement custom plugins.

## Running the Tests

_elf_diff_ comes with a number of tests in the `tests` subdirectory of its git repository.
Some tests are unit tests others integration tests that run _elf_diff_ through
its CLI by supplying different command line parameter sets.

To run the entire test bench do the following.

```sh
cd <repo root>
python3 ./tests/test_main.py
```

### Running Individual Test Cases

Test cases reside in the directory `tests/test_cases` of _elf_diff_'s git repository.

To run individual tests, run the test driver and submit one or more tests using the command line arguments `-t`. To run e.g. the test case `test_command_line_args`, do as follows:

```sh
cd <repo root>
python3 ./tests/test_main.py -t test_command_line_args
```

## Examples

### Examples Page

See the [examples page](https://noseglasses.github.io/elf_diff/).

### libstdc++

[Comparison of two versions of libstdc++](https://github.com/noseglasses/elf_diff/blob/master/examples/libstdc++_std_string_diff.pdf) shipping with gcc 4.8 and 5. There are vast differences between those two library versions which result in a great number of symbols being reported. The following command demonstrates how report generation can be resticted to a subset of symbols by using regular expressions.
In the example we select only those symbols related to class `std::string`.

```sh
## Generated on Ubuntu 20.04 LTS
python3 -m elf_diff \
   --symbol_selection_regex "^std::string::.*"   # select any symbol name starting with std::string:: \
   --pdf_file libstdc++_std_string_diff.pdf      # generate a pdf file \
   /usr/lib/gcc/x86_64-linux-gnu/4.8/libstdc++.a # path to old binary \
   /usr/lib/gcc/x86_64-linux-gnu/5/libstdc++.a   # path to new binary
```

## Contributing

Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process
for submitting pull requests to us.

## Versioning

We use [SemVer](https://semver.org/) for versioning. For the versions available,
see the tags on this repository.

## Authors

* noseglasses - Initial work

## License

This project is licensed under the GNU General Public License Version 3
see the LICENSE.md file for details




%prep
%autosetup -n elf-diff-0.6.0

%build
%py3_build

%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
	find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
	find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
	find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
	find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
	find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .

%files -n python3-elf-diff -f filelist.lst
%dir %{python3_sitelib}/*

%files help -f doclist.lst
%{_docdir}/*

%changelog
* Fri May 05 2023 Python_Bot <Python_Bot@openeuler.org> - 0.6.0-1
- Package Spec generated