This file is indexed.

/usr/bin/blhc is in blhc 0.07+20161116+gitbf41976-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   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
#!/usr/bin/perl 

# Build log hardening check, checks build logs for missing hardening flags.

# Copyright (C) 2012-2016  Simon Ruderich
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


use strict;
use warnings;

use Getopt::Long ();
use Text::ParseWords ();

our $VERSION = '0.07';


# CONSTANTS/VARIABLES

# Regex to catch compiler commands.
my $cc_regex = qr/
    (?<!\s-)               # ignore options, e.g. "-c++" [sic!] (used by swig)
    (?<!\.)                # ignore file names, e.g. "test.gcc"
    (?:cc|gcc|g\+\+|c\+\+)
    (?:-[\d.]+)?           # version suffix, e.g. "gcc-4.6"
    /x;
# Full regex which matches the complete compiler name. Used in a few places to
# prevent false negatives.
my $cc_regex_full_prefix = qr/
    [a-z0-9_]+-(?:linux-|kfreebsd-)?gnu(?:eabi|eabihf)?
    /x;
my $cc_regex_full = qr/
    (?:$cc_regex_full_prefix-)?
    $cc_regex
    /x;
# Regex to check if a line contains a compiler command.
my $cc_regex_normal = qr/
    \b$cc_regex(?:\s|\\)
    /x;
# Regex to catch (GCC) compiler warnings.
my $warning_regex = qr/^(.+?):(\d+):\d+: warning: (.+?) \[(.+?)\]$/;
# Regex to catch libtool commands and not lines which show commands executed
# by libtool (e.g. libtool: link: ...).
my $libtool_regex = qr/\blibtool\s.*--mode=/;
my $libtool_link_regex = qr/\blibtool: link: /;

# List of source file extensions which require preprocessing.
my @source_preprocess_compile_cpp = (
    # C++
    qw( cc cp cxx cpp CPP c++ C ),
    # Objective-C++
    qw( mm M ),
);
my @source_preprocess_compile = (
    # C
    qw( c ),
    # Objective-C
    qw( m ),
    # (Objective-)C++
    @source_preprocess_compile_cpp,
    # Fortran
    qw( F FOR fpp FPP FTN F90 F95 F03 F08 ),
);
my @source_preprocess_no_compile = (
    # Assembly
    qw( S sx ),
);
my @source_preprocess = (
    @source_preprocess_compile,
    @source_preprocess_no_compile,
);
# List of source file extensions which don't require preprocessing.
my @source_no_preprocess_compile_cpp = (
    # C++
    qw( ii ),
    # Objective-C++
    qw( mii ),
);
my @source_no_preprocess_compile_ada = (
    # Ada source
    qw( ada ),
    # Ada body
    qw( adb ),
);
my @source_no_preprocess_compile = (
    # C
    qw( i ),
    # (Objective-)C++
    @source_no_preprocess_compile_cpp,
    # Objective-C
    qw( mi ),
    # Fortran
    qw( f for ftn f90 f95 f03 f08 ),
    # Ada
    @source_no_preprocess_compile_ada,
);
my @source_no_preprocess_no_compile_ada = (
    # Ada specification
    qw( ads ),
);
my @source_no_preprocess_no_compile = (
    # Assembly
    qw( s ),
    # Ada
    @source_no_preprocess_no_compile_ada,
);
my @source_no_preprocess = (
    @source_no_preprocess_compile,
    @source_no_preprocess_no_compile,
);
# List of header file extensions which require preprocessing.
my @header_preprocess = (
    # C, C++, Objective-C, Objective-C++
    qw( h ),
    # C++
    qw( hh H hp hxx hpp HPP h++ tcc ),
);
# Object files.
my @object = (
    # Normal object files.
    qw ( o ),
    # Libtool object files.
    qw ( lo la ),
    # Dynamic libraries. bzip2 uses .sho.
    qw ( so sho ),
    # Static libraries.
    qw ( a ),
);

# Hashes for fast extensions lookup to check if a file falls in one of these
# categories.
my %extensions_no_preprocess = map { $_ => 1 } (
    # There's no @header_no_preprocess.
    @source_no_preprocess,
);
my %extensions_preprocess = map { $_ => 1 } (
    @header_preprocess,
    @source_preprocess,
);
my %extensions_compile_link = map { $_ => 1 } (
    @source_preprocess,
    @source_no_preprocess,
);
my %extensions_compile = map { $_ => 1 } (
    @source_preprocess_compile,
    @source_no_preprocess_compile,
);
my %extensions_no_compile = map { $_ => 1 } (
    @source_preprocess_no_compile,
    @source_no_preprocess_no_compile,
);
my %extensions_compile_cpp = map { $_ => 1 } (
    @source_preprocess_compile_cpp,
    @source_no_preprocess_compile_cpp,
);
my %extensions_ada = map { $_ => 1 } (
    @source_no_preprocess_compile_ada,
    @source_no_preprocess_no_compile_ada,
);
my %extensions_object = map { $_ => 1 } (
    @object,
);
my %extension = map { $_ => 1 } (
    @source_no_preprocess,
    @header_preprocess,
    @source_preprocess,
    @object,
);

# Regexp to match file extensions.
my $file_extension_regex = qr/
    \s
    \S+             # Filename without extension.
    \.
    ([^\/\\.,;:\s]+)# File extension.
    (?=\s|\\)       # At end of word. Can't use \b because some files have non
                    # word characters at the end and because \b matches double
                    # extensions (like .cpp.o). Works always as all lines are
                    # terminated with "\n".
    /x;

# Expected (hardening) flags. All flags are used as regexps (and compiled to
# real regexps below for better execution speed).
my @def_cflags = (
    '-g',
    '-O(?:2|3)', # keep at index 1, search for @def_cflags_debug to change it
);
my @def_cflags_debug = (
    # These flags indicate a debug build which disables checks for -O2.
    '-O0',
    '-Og',
);
my @def_cflags_format = (
    '-Wformat(?:=2)?', # -Wformat=2 implies -Wformat, accept it too
    '-Werror=format-security', # implies -Wformat-security
);
my @def_cflags_fortify = (
    # fortify needs at least -O1, but -O2 is recommended anyway
);
my @def_cflags_stack = (
    '-fstack-protector',
    '--param[= ]ssp-buffer-size=4',
);
my @def_cflags_stack_strong = (
    '-fstack-protector-strong',
);
my @def_cflags_pie = (
    '-fPIE',
);
my @def_cxxflags = (
    @def_cflags,
);
# @def_cxxflags_* is the same as @def_cflags_*.
my @def_cppflags = ();
my @def_cppflags_fortify = (
    '-D_FORTIFY_SOURCE=2', # must be first, see cppflags_fortify_broken()
    # If you add another flag fix hack below (search for "Hack to fix") and
    # $def_cppflags_fortify[0].
);
my @def_cppflags_fortify_bad = (
    # These flags may overwrite -D_FORTIFY_SOURCE=2.
    '-U_FORTIFY_SOURCE',
    '-D_FORTIFY_SOURCE=0',
    '-D_FORTIFY_SOURCE=1',
);
my @def_ldflags = ();
my @def_ldflags_relro = (
    '-Wl,(?:-z,)?relro',
);
my @def_ldflags_bindnow = (
    '-Wl,(?:-z,)?now',
);
my @def_ldflags_pie = (
    '-fPIE',
    '-pie',
);
my @def_ldflags_pic = (
    '-fPIC',
    '-fpic',
    '-shared',
);
# References to all flags checked by the flag checker.
my @flag_refs = (
    \@def_cflags,
    \@def_cflags_format,
    \@def_cflags_fortify,
    \@def_cflags_stack,
    \@def_cflags_stack_strong,
    \@def_cflags_pie,
    \@def_cxxflags,
    \@def_cppflags,
    \@def_cppflags_fortify,
    \@def_ldflags,
    \@def_ldflags_relro,
    \@def_ldflags_bindnow,
    \@def_ldflags_pie,
);
# References to all used flags.
my @flag_refs_all = (
    @flag_refs,
    \@def_cflags_debug,
    \@def_cppflags_fortify_bad,
    \@def_ldflags_pic,
);
# Renaming rules for the output so the regex parts are not visible. Also
# stores string values of flag regexps above, see compile_flag_regexp().
my %flag_renames = (
    '-O(?:2|3)'                    => '-O2',
    '-Wformat(?:=2)?'              => '-Wformat',
    '--param[= ]ssp-buffer-size=4' => '--param=ssp-buffer-size=4',
    '-Wl,(?:-z,)?relro'            => '-Wl,-z,relro',
    '-Wl,(?:-z,)?now'              => '-Wl,-z,now',
);

my %exit_code = (
    no_compiler_commands => 1 << 0,
    # used by POD::Usage => 1 << 1,
    non_verbose_build    => 1 << 2,
    flags_missing        => 1 << 3,
    hardening_wrapper    => 1 << 4,
    invalid_cmake        => 1 << 5,
);

my %buildd_tag = (
    no_compiler_commands => 'I-no-compiler-commands',
    non_verbose_build    => 'W-compiler-flags-hidden',
    flags_missing        => 'W-dpkg-buildflags-missing',
    hardening_wrapper    => 'I-hardening-wrapper-used',
    invalid_cmake        => 'I-invalid-cmake-used',
);

# Statistics of missing flags and non-verbose build commands. Used for
# $option_buildd.
my %statistics = (
    preprocess          => 0,
    preprocess_missing  => 0,
    compile             => 0,
    compile_missing     => 0,
    compile_cpp         => 0,
    compile_cpp_missing => 0,
    link                => 0,
    link_missing        => 0,
    commands            => 0,
    commands_nonverbose => 0,
);

# Use colored (ANSI) output?
my $option_color;


# FUNCTIONS

# Only works for single-level arrays with no undef values. Thanks to perlfaq4.
sub array_equal {
    my ($first_ref, $second_ref) = @_;

    return 0 if scalar @{$first_ref} != scalar @{$second_ref};

    my $length = scalar @{$first_ref};
    for (my $i = 0; $i < $length; $i++) {
        return 0 if $first_ref->[$i] ne $second_ref->[$i];
    }

    return 1;
}

sub error_flags {
    my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;

    # Get string value of qr//-escaped regexps and if requested rename them.
    my @missing_flags = map {
            $flag_renames_ref->{$_}
        } @{$missing_flags_ref};

    my $flags = join ' ', @missing_flags;
    printf '%s (%s)%s %s',
           error_color($message, 'red'), $flags, error_color(':', 'yellow'),
           $line;

    return;
}
sub error_non_verbose_build {
    my ($line) = @_;

    printf '%s%s %s',
           error_color('NONVERBOSE BUILD', 'red'),
           error_color(':', 'yellow'),
           $line;

    return;
}
sub error_invalid_cmake {
    my ($version) = @_;

    printf "%s%s %s\n",
            error_color('INVALID CMAKE', 'red'),
            error_color(':', 'yellow'),
            $version;

    return;
}
sub error_hardening_wrapper {
    printf "%s%s %s\n",
            error_color('HARDENING WRAPPER', 'red'),
            error_color(':', 'yellow'),
            'no checks possible, aborting';

    return;
}
sub error_color {
    my ($message, $color) = @_;

    if ($option_color) {
        return Term::ANSIColor::colored($message, $color);
    } else {
        return $message;
    }
}

sub any_flags_used {
    my ($line, @flags) = @_;

    foreach my $flag (@flags) {
        return 1 if $line =~ /$flag/;
    }

    return 0;
}
sub all_flags_used {
    my ($line, $missing_flags_ref, @flags) = @_;

    my @missing_flags = ();
    foreach my $flag (@flags) {
        if (not $line =~ /$flag/) {
            push @missing_flags, $flag;
        }
    }

    return 1 if scalar @missing_flags == 0;

    @{$missing_flags_ref} = @missing_flags;
    return 0;
}

sub cppflags_fortify_broken {
    my ($line, $missing_flags) = @_;

    # This doesn't take the position into account, but is a simple solution.
    # And if the build system tries to force -D_FORTIFY_SOURCE=0/1, something
    # is wrong anyway.

    if (any_flags_used($line, @def_cppflags_fortify_bad)) {
        # $def_cppflags_fortify[0] must be -D_FORTIFY_SOURCE=2!
        push @{$missing_flags}, $def_cppflags_fortify[0];
        return 1;
    }

    return 0;
}

# Modifies $missing_flags_ref array.
sub pic_pie_conflict {
    my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;

    return 0 if not $pie;
    return 0 if not any_flags_used($line, @def_ldflags_pic);

    my %flags = map { $_ => 1 } @flags_pie;

    # Remove all PIE flags from @missing_flags as they are not required with
    # -fPIC.
    my @result = grep {
        not exists $flags{$_}
    } @{$missing_flags_ref};
    @{$missing_flags_ref} = @result;

    # We got a conflict when no flags are left, thus only PIE flags were
    # missing. If other flags were missing abort because the conflict is not
    # the problem.
    return scalar @result == 0;
}

sub is_non_verbose_build {
    my ($line, $skip_ref, $input_ref, $line_offset, $line_count) = @_;

    if ($line =~ /$libtool_regex/o) {
        # libtool's --silent hides the real compiler flags.
        if ($line =~ /\s--silent/) {
            return 1;
        # If --silent is not present, skip this line as some compiler flags
        # might be missing (e.g. -fPIE) which are handled correctly by libtool
        # internally. libtool displays the real compiler command on the next
        # line, so the flags are checked as usual.
        } else {
            ${$skip_ref} = 1;
            return 0;
        }
    }

    if (not (index($line, 'checking if you want to see long compiling messages... no') == 0
                or $line =~ /^\s*\[?(?:CC|CCLD|C\+\+|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
                or $line =~ /^\s*[Cc]ompiling\s+(.+?)(?:\.\.\.)?$/
                or $line =~ /^\s*[Bb]uilding (?:program|shared library)\s+(.+?)$/
                or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
        return 0;
    }

    # False positives.
    #
    # C++ compiler setting.
    return 0 if $line =~ /^\s*C\+\+.+?:\s+(?:yes|no)\s*$/;
    return 0 if $line =~ /^\s*C\+\+ Library: stdc\+\+$/;
    # "Compiling" non binary files.
    return 0 if $line =~ /^\s*Compiling \S+\.(?:py|el)['"]?\s*(?:\.\.\.)?$/;
    # "Compiling" with no file name.
    if ($line =~ /^\s*[Cc]ompiling\s+(.+?)(?:\.\.\.)?$/) {
        # $file_extension_regex may need spaces around the filename.
        return 0 if not " $1 " =~ /$file_extension_regex/o;
    }

    my $file = $1;

    # On the first pass we only check if this line is verbose or not.
    return 1 if not defined $input_ref;

    # Second pass, we have access to the next lines.
    ${$skip_ref} = 0;

    # CMake and other build systems print the non-verbose messages also when
    # building verbose. If a compiler and the file name occurs in the next
    # lines, treat it as verbose build.
    if (defined $file) {
        # Get filename, we can't use the complete path as only parts of it are
        # used in the real compiler command.
        $file =~ m{/([^/\s]+)$};
        $file = $1;

        for (my $i = 1; $i <= $line_count; $i++) {
            my $next_line = $input_ref->[$line_offset + $i];
            last unless defined $next_line;

            if (index($next_line, $file) != -1 and $next_line =~ /$cc_regex/o) {
                # Not a non-verbose line, but we still have to skip the
                # current line as it doesn't contain any compiler commands.
                ${$skip_ref} = 1;
                return 0;
            }
        }
    }

    return 1;
}

# Remove @flags from $flag_refs_ref, uses $flag_renames_ref as reference.
sub remove_flags {
    my ($flag_refs_ref, $flag_renames_ref, @flags) = @_;

    my %removes = map { $_ => 1 } @flags;
    foreach my $flags (@{$flag_refs_ref}) {
        @{$flags} = grep {
            # Flag found as string.
            not exists $removes{$_}
            # Flag found as string representation of regexp.
                and (not defined $flag_renames_ref->{$_}
                        or not exists $removes{$flag_renames_ref->{$_}})
        } @{$flags};
    }

    return;
}

# Modifies $flag_renames_ref hash.
sub compile_flag_regexp {
    my ($flag_renames_ref, @flags) = @_;

    my @result = ();
    foreach my $flag (@flags) {
        # Compile flag regexp for faster execution.
        my $regex = qr/\s$flag(?:\s|\\)/;

        # Store flag name in replacement string for correct flags in messages
        # with qr//ed flag regexps.
        $flag_renames_ref->{$regex}
            = (exists $flag_renames_ref->{$flag})
                ? $flag_renames_ref->{$flag}
                : $flag;

        push @result, $regex;
    }
    return @result;
}

# Does any extension in @extensions exist in %{$extensions_ref}?
sub extension_found {
    my ($extensions_ref, @extensions) = @_;

    foreach my $extension (@extensions) {
        if (exists $extensions_ref->{$extension}) {
            return 1;
        }
    }
    return 0;
}


# MAIN

# Parse command line arguments.
my $option_help             = 0;
my $option_version          = 0;
my $option_pie              = 0;
my $option_bindnow          = 0;
my @option_ignore_arch      = ();
my @option_ignore_flag      = ();
my @option_ignore_arch_flag = ();
my @option_ignore_line      = ();
my @option_ignore_arch_line = ();
my $option_all              = 0;
my $option_arch             = undef;
my $option_buildd           = 0;
   $option_color            = 0;
if (not Getopt::Long::GetOptions(
            'help|h|?'           => \$option_help,
            'version'            => \$option_version,
            # Hardening options.
            'pie'                => \$option_pie,
            'bindnow'            => \$option_bindnow,
            'all'                => \$option_all,
            # Ignore.
            'ignore-arch=s'      => \@option_ignore_arch,
            'ignore-flag=s'      => \@option_ignore_flag,
            'ignore-arch-flag=s' => \@option_ignore_arch_flag,
            'ignore-line=s'      => \@option_ignore_line,
            'ignore-arch-line=s' => \@option_ignore_arch_line,
            # Misc.
            'color'              => \$option_color,
            'arch=s'             => \$option_arch,
            'buildd'             => \$option_buildd,
        )) {
    require Pod::Usage;
    Pod::Usage::pod2usage(2);
}
if ($option_help) {
    require Pod::Usage;
    Pod::Usage::pod2usage(1);
}
if ($option_version) {
    print <<"EOF";
blhc $VERSION  Copyright (C) 2012-2016  Simon Ruderich

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
EOF
    exit 0;
}

# Arguments missing.
if (scalar @ARGV == 0) {
    require Pod::Usage;
    Pod::Usage::pod2usage(2);
}

# Don't load Term::ANSIColor in buildd mode because Term::ANSIColor is not
# installed on Debian's buildds.
if (not $option_buildd) {
    require Term::ANSIColor;
}

if ($option_all) {
    $option_pie     = 1;
    $option_bindnow = 1;
}

# Precompiled ignores for faster lookup.
my %option_ignore_arch_flag = ();
my %option_ignore_arch_line = ();

# Strip flags which should be ignored.
if (scalar @option_ignore_flag > 0) {
    remove_flags(\@flag_refs, \%flag_renames, @option_ignore_flag);
}
# Same for arch specific ignore flags, but only prepare here.
if (scalar @option_ignore_arch_flag > 0) {
    foreach my $ignore (@option_ignore_arch_flag) {
        my ($ignore_arch, $ignore_flag) = split /:/, $ignore, 2;

        if (not $ignore_arch or not $ignore_flag) {
            printf STDERR 'Value "%s" invalid for option ignore-arch-flag '
                        . '("arch:flag" expected)' . "\n", $ignore;
            require Pod::Usage;
            Pod::Usage::pod2usage(2);
        }

        push @{$option_ignore_arch_flag{$ignore_arch}}, $ignore_flag;
    }
}

# Precompile all flag regexps. any_flags_used(), all_flags_used() get a lot
# faster with this.
foreach my $flags (@flag_refs_all) {
    @{$flags} = compile_flag_regexp(\%flag_renames, @{$flags});
}

# Precompile ignore line regexps, also anchor at beginning and end of line.
foreach my $ignore (@option_ignore_line) {
    $ignore = qr/^$ignore$/;
}
# Same for arch specific ignore lines.
if (scalar @option_ignore_arch_line > 0) {
    foreach my $ignore (@option_ignore_arch_line) {
        my ($ignore_arch, $ignore_line) = split /:/, $ignore, 2;

        if (not $ignore_arch or not $ignore_line) {
            printf STDERR 'Value "%s" invalid for option ignore-arch-line '
                        . '("arch:line" expected)' . "\n", $ignore;
            require Pod::Usage;
            Pod::Usage::pod2usage(2);
        }

        push @{$option_ignore_arch_line{$ignore_arch}}, qr/^$ignore_line$/;
    }
}

# Final exit code.
my $exit = 0;

FILE:
foreach my $file (@ARGV) {
    print "checking '$file'...\n" if scalar @ARGV > 1;

    -f $file or die "No such file: $file";

    open my $fh, '<', $file or die $!;

    # Architecture of this file.
    my $arch = $option_arch;

    # Hardening options. Not all architectures support all hardening options.
    my $harden_format  = 1;
    my $harden_fortify = 1;
    my $harden_stack   = 1;
    my $harden_stack_strong = 1;
    my $harden_relro   = 1;
    my $harden_bindnow = $option_bindnow; # defaults to 0
    my $harden_pie     = $option_pie;     # defaults to 0

    # Does this build log use ada? Ada also uses gcc as compiler but uses
    # different CFLAGS. But only perform ada checks if an ada compiler is used
    # for performance reasons.
    my $ada = 0;

    # Number of parallel jobs to prevent false positives when detecting
    # non-verbose builds. As not all jobs declare the number of parallel jobs
    # use a large enough default.
    my $parallel = 10;

    while (my $line = <$fh>) {
        # Detect architecture automatically unless overridden. For buildd logs
        # only, doesn't use the dpkg-buildpackage header. Necessary to ignore
        # build logs which aren't built (wrong architecture, build error,
        # etc.).
        if (not $arch) {
            if (index($line, 'Build Architecture: ') == 0) {
                $arch = substr $line, 20, -1; # -1 to ignore '\n' at the end
            # For old logs (sbuild << 0.63.0-1).
            } elsif (index($line, 'Architecture: ') == 0) {
                $arch = substr $line, 14, -1; # -1 to ignore '\n' at the end
            }
        }

        # dpkg-buildflags only provides hardening flags since 1.16.1, don't
        # check for hardening flags in buildd mode if an older dpkg-dev is
        # used. Default flags (-g -O2) are still checked.
        #
        # Packages which were built before 1.16.1 but used their own hardening
        # flags are not checked.
        #
        # Strong stack protector is used since dpkg 1.17.11.
        if ($option_buildd
                and index($line, 'Toolchain package versions: ') == 0) {
            require Dpkg::Version;

            my $disable = 1;
            my $disable_strong = 1;

            if ($line =~ /\bdpkg-dev_(\S+)/) {
                if (Dpkg::Version::version_compare($1, '1.16.1') >= 0) {
                    $disable = 0;
                }
                if (Dpkg::Version::version_compare($1, '1.17.11') >= 0) {
                    $disable_strong = 0;
                }
            }

            if ($disable) {
                $harden_format  = 0;
                $harden_fortify = 0;
                $harden_stack   = 0;
                $harden_relro   = 0;
                $harden_bindnow = 0;
                $harden_pie     = 0;
            }
            if ($disable_strong) {
                $harden_stack_strong = 0;
            }
        }

        # The following two versions of CMake in Debian obeyed CPPFLAGS, but
        # this was later dropped because upstream rejected the patch. Thus
        # build logs with these versions will have fortify hardening flags
        # enabled, even though they may be not correctly set and are missing
        # when build with later CMake versions. Thanks to Aron Xu for letting
        # me know.
        if (index($line, 'Package versions: ') == 0
                and $line =~ /\bcmake_(\S+)/
                and ($1 eq '2.8.7-1' or $1 eq '2.8.7-2')) {
            if (not $option_buildd) {
                error_invalid_cmake($1);
                $exit |= $exit_code{invalid_cmake};
            } else {
                print "$buildd_tag{invalid_cmake}|$1|\n";
            }
        }

        # Debian's build daemons use "Filtered Build-Depends:" (or just
        # "Build-Depends:" in older versions) for the build dependencies, but
        # pbuilder uses "Depends:"; support both.
        if (index($line, 'Filtered Build-Depends: ') == 0
                or index($line, 'Build-Depends: ') == 0
                or index($line, 'Depends: ') == 0) {
            # If hardening wrapper is used (wraps calls to gcc and adds
            # hardening flags automatically) we can't perform any checks,
            # abort.
            if ($line =~ /\bhardening-wrapper\b/) {
                if (not $option_buildd) {
                    error_hardening_wrapper();
                    $exit |= $exit_code{hardening_wrapper};
                } else {
                    print "$buildd_tag{hardening_wrapper}||\n";
                }
                next FILE;
            }

            # Ada compiler.
            if ($line =~ /\bgnat\b/) {
                $ada = 1;
            }
        }

        # This flags is not always available, but if it is use it.
        if ($line =~ /^DEB_BUILD_OPTIONS=.*\bparallel=(\d+)/) {
            $parallel = $1;
        }

        # We skip over unimportant lines at the beginning of the log to
        # prevent false positives.
        last if index($line, 'dpkg-buildpackage: ') == 0;
    }

    # Input lines, contain only the lines with compiler commands.
    my @input = ();
    # Non-verbose lines in the input. Used to reduce calls to
    # is_non_verbose_build() (which is quite slow) in the second loop when
    # it's already clear if a line is non-verbose or not.
    my @input_nonverbose = ();

    my $continuation = 0;
    my $complete_line = undef;
    my $non_verbose;
    while (my $line = <$fh>) {
        # And stop at the end of the build log. Package details (reported by
        # the buildd logs) are not important for us. This also prevents false
        # positives.
        last if index($line, 'Build finished at ') == 0
                and $line =~ /^Build finished at \d{8}-\d{4}$/;

        if (not $continuation) {
            $non_verbose = 0;
        }

        # Detect architecture automatically unless overridden.
        if (not $arch
                and index($line, 'dpkg-buildpackage: host architecture ') == 0) {
            $arch = substr $line, 37, -1; # -1 to ignore '\n' at the end

            # Old buildd logs use e.g. "host architecture is alpha", remove
            # the "is", otherwise debarch_to_debtriplet() will not detect the
            # architecture.
            if (index($arch, 'is ') == 0) {
                $arch = substr $arch, 3;
            }
        }

        next if $line =~ /^\s*#/;
        # Ignore compiler warnings for now.
        next if $line =~ /$warning_regex/o;

        if (not $option_buildd and index($line, "\033") != -1) { # \033 = esc
            # Remove all ANSI color sequences which are sometimes used in
            # non-verbose builds.
            $line = Term::ANSIColor::colorstrip($line);
            # Also strip '\0xf' (delete previous character), used by Elinks'
            # build system.
            $line =~ s/\x0f//g;
            # And "ESC(B" which seems to be used on armhf and hurd (not sure
            # what it does).
            $line =~ s/\033\(B//g;
        }

        # Check if this line indicates a non verbose build.
        my $skip = 0;
        $non_verbose |= is_non_verbose_build($line, \$skip);
        next if $skip;

        # One line may contain multiple commands (";"). Treat each one as
        # single line. parse_line() is slow, only use it when necessary.
        my @line = (index($line, ';') == -1)
                 ? ($line)
                 : map {
                       # Ensure newline at the line end - necessary for
                       # correct parsing later.
                       $_ =~ s/\s+$//;
                       $_ .= "\n";
                   } Text::ParseWords::parse_line(';', 1, $line);
        foreach my $line (@line) {
            if ($continuation) {
                $continuation = 0;

                # Join lines, but leave the "\" in place so it's clear where
                # the original line break was.
                chomp $complete_line;
                $complete_line .= ' ' . $line;
            }
            # Line continuation, line ends with "\".
            if ($line =~ /\\$/) {
                $continuation = 1;
                # Start line continuation.
                if (not defined $complete_line) {
                    $complete_line = $line;
                }
                next;
            }

            # Use the complete line if a line continuation occurred.
            if (defined $complete_line) {
                $line = $complete_line;
                $complete_line = undef;
            }

            # Ignore lines with no compiler commands.
            next if not $non_verbose
                    and not $line =~ /$cc_regex_normal/o;
            # Ignore lines with no filenames with extensions. May miss some
            # non-verbose builds (e.g. "gcc -o test" [sic!]), but shouldn't be
            # a problem as the log will most likely contain other non-verbose
            # commands which are detected.
            next if not $non_verbose
                    and not $line =~ /$file_extension_regex/o;

            # Ignore false positives.
            #
            # `./configure` output.
            next if not $non_verbose
                    and $line =~ /^(?:checking|[Cc]onfigure:) /;
            next if $line =~ /^\s*(?:Host\s+)?(?:C(?:\+\+)?\s+)?
                                [Cc]ompiler[\s.]*:?\s+
                                /x;
            next if $line =~ m{^\s*(?:-\s)?(?:HOST_)?(?:CC|CXX)
                                \s*=\s*$cc_regex_full
                                # optional compiler options, don't allow
                                # "everything" here to prevent false negatives
                                \s*(?:\s-\S+)*\s*$}xo;
            # `moc-qt4`/`moc-qt5` contain '-I.../linux-g++' in their command
            # line (or similar for other architectures) which gets recognized
            # as a compiler line, but `moc-qt*` is only a preprocessor for Qt
            # C++ files. No hardening flags are relevant during this step,
            # thus ignore `moc-qt*` lines. The resulting files will be
            # compiled in a separate step (and therefore checked).
            next if $line =~ m{^\S+/bin/moc(?:-qt[45])?
                               \s.+\s
                               -I\S+/mkspecs/[a-z]+-g\++(?:-64)?
                               \s}x;
            # Ignore false positives when the line contains only CC=gcc but no
            # other gcc command.
            if ($line =~ /(.*)CC=$cc_regex_full(.*)/o) {
                my $before = $1;
                my $after  = $2;
                next if     not $before =~ /$cc_regex_normal/o
                        and not $after  =~ /$cc_regex_normal/o;
            }
            # Ignore false positives caused by gcc -v. It outputs a line
            # looking like a normal compiler line but which is sometimes
            # missing hardening flags, although the normal compiler line
            # contains them.
            next if $line =~ m{^\s+/usr/lib/gcc/$cc_regex_full_prefix/
                                   [0-9.]+/cc1(?:plus)?}xo;
            # Ignore false positive with `rm` which may remove files which
            # look like a compiler executable thus causing the line to be
            # treated as a normal compiler line.
            next if $line =~ m{^\s*rm\s+};
            # Some build systems emit "gcc > file".
            next if $line =~ m{$cc_regex_normal\s*>\s*\S+};

            # Check if additional hardening options were used. Used to ensure
            # they are used for the complete build.
            $harden_pie     = 1 if any_flags_used($line, @def_cflags_pie,
                                                         @def_ldflags_pie);
            $harden_bindnow = 1 if any_flags_used($line, @def_ldflags_bindnow);

            push @input, $line;
            push @input_nonverbose, $non_verbose;
        }
    }

    close $fh or die $!;

    # Ignore arch if requested.
    if (scalar @option_ignore_arch > 0 and $arch) {
        foreach my $ignore (@option_ignore_arch) {
            if ($arch eq $ignore) {
                print "ignoring architecture '$arch'\n";
                next FILE;
            }
        }
    }

    if (scalar @input == 0) {
        if (not $option_buildd) {
            print "No compiler commands!\n";
            $exit |= $exit_code{no_compiler_commands};
        } else {
            print "$buildd_tag{no_compiler_commands}||\n";
        }
        next FILE;
    }

    if ($option_buildd) {
        $statistics{commands} += scalar @input;
    }

    # Option or auto detected.
    if ($arch) {
        # The following was partially copied from dpkg-dev 1.18.15
        # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, _add_hardening_flags()),
        # copyright Raphaƫl Hertzog <hertzog@debian.org>, Kees Cook
        # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
        # later. Keep it in sync.

        require Dpkg::Arch;
        my ($os, $cpu);
        # Recent dpkg versions use a quadruplet for arch. Support both.
        eval {
            (undef, undef, $os, $cpu) = Dpkg::Arch::debarch_to_debtuple($arch);
        };
        if ($@) {
            (undef, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($arch);
        }

        # Disable unsupported hardening options.
        if ($os !~ /^(?:linux|kfreebsd|knetbsd|hurd)$/
                or $cpu =~ /^(?:hppa|avr32)$/) {
            $harden_pie = 0;
        }
        if ($cpu =~ /^(?:ia64|alpha|hppa|nios2)$/ or $arch eq 'arm') {
            $harden_stack = 0;
            $harden_stack_strong = 0;
        }
        if ($cpu =~ /^(?:ia64|hppa|avr32)$/) {
            $harden_relro   = 0;
            $harden_bindnow = 0;
        }
    }

    # Default values.
    my @cflags   = @def_cflags;
    my @cxxflags = @def_cxxflags;
    my @cppflags = @def_cppflags;
    my @ldflags  = @def_ldflags;
    # Check the specified hardening options, same order as dpkg-buildflags.
    if ($harden_pie) {
        @cflags   = (@cflags,   @def_cflags_pie);
        @cxxflags = (@cxxflags, @def_cflags_pie);
        @ldflags  = (@ldflags,  @def_ldflags_pie);
    }
    if ($harden_stack_strong) {
        @cflags   = (@cflags,   @def_cflags_stack_strong);
        @cxxflags = (@cxxflags, @def_cflags_stack_strong);
    } elsif ($harden_stack) {
        @cflags   = (@cflags,   @def_cflags_stack);
        @cxxflags = (@cxxflags, @def_cflags_stack);
    }
    if ($harden_fortify) {
        @cflags   = (@cflags,   @def_cflags_fortify);
        @cxxflags = (@cxxflags, @def_cflags_fortify);
        @cppflags = (@cppflags, @def_cppflags_fortify);
    }
    if ($harden_format) {
        @cflags   = (@cflags,   @def_cflags_format);
        @cxxflags = (@cxxflags, @def_cflags_format);
    }
    if ($harden_relro) {
        @ldflags = (@ldflags, @def_ldflags_relro);
    }
    if ($harden_bindnow) {
        @ldflags = (@ldflags, @def_ldflags_bindnow);
    }

    # Stores normal CFLAGS when @cflags_ada are temporarily used.
    my @cflags_backup;
    # Ada CFLAGS, only set if ada is used.
    my @cflags_ada;
    # Ada doesn't support format hardening flags, see #680117 for more
    # information. Filter them out if ada is used.
    if ($ada and $harden_format) {
        @cflags_ada = grep {
            my $ok = 1;
            foreach my $flag (@def_cflags_format) {
                $ok = 0 if $_ eq $flag;
            }
            $ok;
        } @cflags;
    }

    # Hack to fix cppflags_fortify_broken() if --ignore-flag
    # -D_FORTIFY_SOURCE=2 is used to ignore missing fortification. Only works
    # as long as @def_cppflags_fortify contains only one variable.
    if (scalar @def_cppflags_fortify == 0) {
        $harden_fortify = 0;
    }

    # Ignore flags for this arch if requested.
    if ($arch and exists $option_ignore_arch_flag{$arch}) {
        my @local_flag_refs = (\@cflags, \@cxxflags, \@cppflags, \@ldflags);

        remove_flags(\@local_flag_refs,
                     \%flag_renames,
                     @{$option_ignore_arch_flag{$arch}});
    }

    my @ignore_line = @option_ignore_line;
    # Ignore lines for this arch if requested.
    if ($arch and exists $option_ignore_arch_line{$arch}) {
        @ignore_line = (@ignore_line, @{$option_ignore_arch_line{$arch}});
    }

LINE:
    for (my $i = 0; $i < scalar @input; $i++) {
        my $line = $input[$i];

        # Ignore line if requested.
        foreach my $ignore (@ignore_line) {
            next LINE if $line =~ /$ignore/;
        }

        my $skip = 0;
        if ($input_nonverbose[$i]
                and is_non_verbose_build($line, \$skip,
                                         \@input, $i, $parallel)) {
            if (not $option_buildd) {
                error_non_verbose_build($line);
                $exit |= $exit_code{non_verbose_build};
            } else {
                $statistics{commands_nonverbose}++;
            }
            next;
        }
        # Even if it's a verbose build, we might have to skip this line (see
        # is_non_verbose_build()).
        next if $skip;

        my $orig_line = $line;

        # Remove everything until and including the compiler command. Makes
        # checks easier and faster.
        $line =~ s/^.*?$cc_regex//o;
        # "([...] test.c)" is not detected as 'test.c' - fix this by removing
        # the brace and similar characters at the line end.
        $line =~ s/['")]+$//;

        # Skip unnecessary tests when only preprocessing.
        my $flag_preprocess = 0;

        my $dependency = 0;
        my $preprocess = 0;
        my $compile    = 0;
        my $link       = 0;

        # Preprocess, compile, assemble.
        if ($line =~ /\s(-E|-S|-c)\b/) {
            $preprocess      = 1;
            $flag_preprocess = 1 if $1 eq '-E';
            $compile         = 1 if $1 eq '-S' or $1 eq '-c';
        # Dependency generation for Makefiles. The other flags (-MF -MG -MP
        # -MT -MQ) are always used with -M/-MM.
        } elsif ($line =~ /\s(?:-M|-MM)\b/) {
            $dependency = 1;
        # Otherwise assume we are linking.
        } else {
            $link = 1;
        }

        # -MD/-MMD also cause dependency generation, but they don't imply -E!
        if ($line =~ /\s(?:-MD|-MMD)\b/) {
            $dependency      = 0;
            $flag_preprocess = 0;
        }

        # Dependency generation for Makefiles, no preprocessing or other flags
        # needed.
        next if $dependency;

        # Get all file extensions on this line.
        my @extensions = $line =~ /$file_extension_regex/go;
        # Ignore all unknown extensions to speedup the search below.
        @extensions = grep { exists $extension{$_} } @extensions;

        # These file types don't require preprocessing.
        if (extension_found(\%extensions_no_preprocess, @extensions)) {
            $preprocess = 0;
        }
        # These file types require preprocessing.
        if (extension_found(\%extensions_preprocess, @extensions)) {
            # Prevent false positives with "libtool: link: g++ -include test.h
            # .." compiler lines.
            if ($orig_line !~ /$libtool_link_regex/o) {
                $preprocess = 1;
            }
        }

        if (not $flag_preprocess) {
            # If there are source files then it's compiling/linking in one
            # step and we must check both. We only check for source files
            # here, because header files cause too many false positives.
            if (extension_found(\%extensions_compile_link, @extensions)) {
                # Assembly files don't need CFLAGS.
                if (not extension_found(\%extensions_compile, @extensions)
                        and extension_found(\%extensions_no_compile, @extensions)) {
                    $compile = 0;
                # But the rest does.
                } else {
                    $compile = 1;
                }
            # No compilable extensions found, either linking or compiling
            # header flags.
            #
            # If there are also no object files we are just compiling headers
            # (.h -> .h.gch). Don't check for linker flags in this case. Due
            # to our liberal checks for compiler lines, this also reduces the
            # number of false positives considerably.
            } elsif ($link
                    and not extension_found(\%extensions_object, @extensions)) {
                $link = 0;
            }
        }

        my $compile_cpp = 0;
        my $compile_ada = 0;
        # Assume CXXFLAGS are required when a C++ file is specified in the
        # compiler line.
        if ($compile
                and extension_found(\%extensions_compile_cpp, @extensions)) {
            $compile     = 0;
            $compile_cpp = 1;
        # Ada needs special CFLAGS, use them if only ada files are compiled.
        } elsif ($ada
                and extension_found(\%extensions_ada, @extensions)) {
            $compile_ada = 1;
            $preprocess = 0; # Ada uses no CPPFLAGS
            @cflags_backup = @cflags;
            @cflags        = @cflags_ada;
        }

        if ($option_buildd) {
            $statistics{preprocess}++  if $preprocess;
            $statistics{compile}++     if $compile;
            $statistics{compile_cpp}++ if $compile_cpp;
            $statistics{link}++        if $link;
        }

        # Check if there are flags indicating a debug build. If that's true,
        # skip the check for -O2. This prevents fortification, but that's fine
        # for a debug build.
        if (any_flags_used($line, @def_cflags_debug)) {
            remove_flags([\@cflags], \%flag_renames, $def_cflags[1]);
            remove_flags([\@cppflags], \%flag_renames, $def_cppflags_fortify[0]);
        }

        # Check hardening flags.
        my @missing;
        if ($compile and not all_flags_used($line, \@missing, @cflags)
                # Libraries linked with -fPIC don't have to (and can't) be
                # linked with -fPIE as well. It's no error if only PIE flags
                # are missing.
                and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
                # Assume dpkg-buildflags returns the correct flags.
                and index($line, '`dpkg-buildflags --get CFLAGS`') == -1) {
            if (not $option_buildd) {
                error_flags('CFLAGS missing', \@missing, \%flag_renames, $input[$i]);
                $exit |= $exit_code{flags_missing};
            } else {
                $statistics{compile_missing}++;
            }
        } elsif ($compile_cpp and not all_flags_used($line, \@missing, @cflags)
                # Libraries linked with -fPIC don't have to (and can't) be
                # linked with -fPIE as well. It's no error if only PIE flags
                # are missing.
                and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
                # Assume dpkg-buildflags returns the correct flags.
                and index($line, '`dpkg-buildflags --get CXXFLAGS`') == -1) {
            if (not $option_buildd) {
                error_flags('CXXFLAGS missing', \@missing, \%flag_renames, $input[$i]);
                $exit |= $exit_code{flags_missing};
            } else {
                $statistics{compile_cpp_missing}++;
            }
        }
        if ($preprocess
                and (not all_flags_used($line, \@missing, @cppflags)
                    # The fortify flag might be overwritten, detect that.
                     or ($harden_fortify
                         and cppflags_fortify_broken($line, \@missing)))
                # Assume dpkg-buildflags returns the correct flags.
                and index($line, '`dpkg-buildflags --get CPPFLAGS`') == -1) {
            if (not $option_buildd) {
                error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $input[$i]);
                $exit |= $exit_code{flags_missing};
            } else {
                $statistics{preprocess_missing}++;
            }
        }
        if ($link and not all_flags_used($line, \@missing, @ldflags)
                # Same here, -fPIC conflicts with -fPIE.
                and not pic_pie_conflict($line, $harden_pie, \@missing, @def_ldflags_pie)
                # Assume dpkg-buildflags returns the correct flags.
                and index($line, '`dpkg-buildflags --get LDFLAGS`') == -1) {
            if (not $option_buildd) {
                error_flags('LDFLAGS missing', \@missing, \%flag_renames, $input[$i]);
                $exit |= $exit_code{flags_missing};
            } else {
                $statistics{link_missing}++;
            }
        }

        # Restore normal CFLAGS.
        if ($compile_ada) {
            @cflags = @cflags_backup;
        }
    }
}

# Print statistics for buildd mode, only output in this mode.
if ($option_buildd) {
    my @warning;

    if ($statistics{preprocess_missing}) {
        push @warning, sprintf 'CPPFLAGS %d (of %d)',
                               $statistics{preprocess_missing},
                               $statistics{preprocess};
    }
    if ($statistics{compile_missing}) {
        push @warning, sprintf 'CFLAGS %d (of %d)',
                               $statistics{compile_missing},
                               $statistics{compile};
    }
    if ($statistics{compile_cpp_missing}) {
        push @warning, sprintf 'CXXFLAGS %d (of %d)',
                               $statistics{compile_cpp_missing},
                               $statistics{compile_cpp};
    }
    if ($statistics{link_missing}) {
        push @warning, sprintf 'LDFLAGS %d (of %d)',
                               $statistics{link_missing},
                               $statistics{link};
    }
    if (scalar @warning) {
        local $" = ', '; # array join string
        print "$buildd_tag{flags_missing}|@warning missing|\n";
    }

    if ($statistics{commands_nonverbose}) {
        printf "$buildd_tag{non_verbose_build}|%d (of %d) hidden|\n",
               $statistics{commands_nonverbose},
               $statistics{commands},
    }
}


exit $exit;


__END__

=head1 NAME

blhc - build log hardening check, checks build logs for missing hardening flags

=head1 SYNOPSIS

B<blhc> [I<options>] I<< <dpkg-buildpackage build log file>.. >>

=head1 DESCRIPTION

blhc is a small tool which checks build logs for missing hardening flags. It's
licensed under the GPL 3 or later.

It's designed to check build logs generated by Debian's dpkg-buildpackage (or
tools using dpkg-buildpackage like pbuilder or sbuild (which is used for the
official buildd build logs)) to help maintainers detect missing hardening
flags in their packages.

Only gcc is detected as compiler at the moment. If other compilers support
hardening flags as well, please report them.

If there's no output, no flags are missing and the build log is fine.

See F<README> for details about performed checks, auto-detection and
limitations.

=head1 OPTIONS

=over 8

=item B<--all>

Force check for all +all (+pie, +bindnow) hardening flags. By default it's
auto detected.

=item B<--arch> I<architecture>

Set the specific architecture (e.g. amd64, armel, etc.), automatically
disables hardening flags not available on this architecture. Is detected
automatically if dpkg-buildpackage is used.

=item B<--bindnow>

Force check for all +bindnow hardening flags. By default it's auto detected.

=item B<--buildd>

Special mode for buildds when automatically parsing log files. The following
changes are in effect:

=over 2

=item *

Print tags instead of normal warnings, see L</"BUILDD TAGS"> for a list of
possible tags.

=item *

Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
detected).

=item *

Don't require Term::ANSIColor.

=item *

Return exit code 0, unless there was a error (-I, -W messages don't count as
error).

=back

=item B<--color>

Use colored (ANSI) output for warning messages.

=item B<--ignore-arch> I<arch>

Ignore build logs from architectures matching I<arch>. I<arch> is a string.

Used to prevent false positives. This option can be specified multiple times.

=item B<--ignore-arch-flag> I<arch>:I<flag>

Like B<--ignore-flag>, but only ignore flag on I<arch>.

=item B<--ignore-arch-line> I<arch>:I<line>

Like B<--ignore-line>, but only ignore line on I<arch>.

=item B<--ignore-flag> I<flag>

Don't print an error when the specific flag is missing in a compiler line.
I<flag> is a string.

Used to prevent false positives. This option can be specified multiple times.

=item B<--ignore-line> I<regex>

Ignore lines matching the given Perl regex. I<regex> is automatically anchored
at the beginning and end of the line to prevent false negatives.

B<NOTE>: Not the input lines are checked, but the lines which are displayed in
warnings (which have line continuation resolved).

Used to prevent false positives. This option can be specified multiple times.

=item B<--pie>

Force check for all +pie hardening flags. By default it's auto detected.

=item B<-h -? --help>

Print available options.

=item B<--version>

Print version number and license.

=back

Auto detection for B<--pie> and B<--bindnow> only works if at least one
command uses the required hardening flag (e.g. -fPIE). Then it's required for
all other commands as well.

=head1 EXAMPLES

Normal usage, parse a single log file.

    blhc path/to/log/file

If there's no output, no flags are missing and the build log is fine.

Parse multiple log files. The exit code is ORed over all files.

    blhc path/to/directory/with/log/files/*

Don't treat missing C<-g> as error:

    blhc --ignore-flag -g path/to/log/file

Don't treat missing C<-pie> on kfreebsd-amd64 as error:

    blhc --ignore-arch-flag kfreebsd-amd64:-pie path/to/log/file

Ignore lines consisting exactly of C<./script gcc file> which would cause a
false positive.

    blhc --ignore-line '\./script gcc file' path/to/log/file

Ignore lines matching C<./script gcc file> somewhere in the line.

    blhc --ignore-line '.*\./script gcc file.*' path/to/log/file

Use blhc with pbuilder.

    pbuilder path/to/package.dsc | tee path/log/file
    blhc path/to/file || echo flags missing

=head1 BUILDD TAGS

The following tags are used in I<--buildd> mode. In braces the additional data
which is displayed.

=over 2

=item B<I-hardening-wrapper-used>

The package uses hardening-wrapper which intercepts calls to gcc and adds
hardening flags. The build log doesn't contain any hardening flags and thus
can't be checked by blhc.

=item B<W-compiler-flags-hidden> (summary of hidden lines)

Build log contains lines which hide the real compiler flags. For example:

    CC test-a.c
    CC test-b.c
    CC test-c.c
    LD test

Most of the time either C<export V=1> or C<export verbose=1> in
F<debian/rules> fixes builds with hidden compiler flags. Sometimes C<.SILENT>
in a F<Makefile> must be removed. And as last resort the F<Makefile> must be
patched to remove the C<@>s hiding the real compiler commands.

=item B<W-dpkg-buildflags-missing> (summary of missing flags)

CPPFLAGS, CFLAGS, CXXFLAGS, LDFLAGS missing.

=item B<I-invalid-cmake-used> (version)

By default CMake ignores CPPFLAGS thus missing those hardening flags. Debian
patched CMake in versions 2.8.7-1 and 2.8.7-2 to respect CPPFLAGS, but this
patch was rejected by upstream and later reverted in Debian. Thus those two
versions show correct usage of CPPFLAGS even if the package doesn't correctly
handle them (for example by passing them to CFLAGS). To prevent false
negatives just blacklist those two versions.

=item B<I-no-compiler-commands>

No compiler commands were detected. Either the log contains none or they were
not correctly detected by blhc (please report the bug in this case).

=back

=head1 EXIT STATUS

The exit status is a "bit mask", each listed status is ORed when the error
condition occurs to get the result.

=over 4

=item B<0>

Success.

=item B<1>

No compiler commands were found.

=item B<2>

Invalid arguments/options given to blhc.

=item B<4>

Non verbose build.

=item B<8>

Missing hardening flags.

=item B<16>

Hardening wrapper detected, no tests performed.

=item B<32>

Invalid CMake version used. See B<I-invalid-cmake-used> under L</"BUILDD
TAGS"> for a detailed explanation.

=back

=head1 AUTHOR

Simon Ruderich, E<lt>simon@ruderich.orgE<gt>

Thanks to to Bernhard R. Link E<lt>brlink@debian.orgE<gt> and Jaria Alto
E<lt>jari.aalto@cante.netE<gt> for their valuable input and suggestions.

=head1 LICENSE AND COPYRIGHT

Copyright (C) 2012-2016 by Simon Ruderich

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

=head1 SEE ALSO

L<hardening-check(1)>, L<dpkg-buildflags(1)>

=cut