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
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
###############################################################################
# Copyright (c) 2019-2024 by Altair Engineering, Inc.
# All rights reserved.
#
# Altair Engineering, Inc. makes this software available as part of the Vision
# tool platform.  As long as you are a licensee of the Vision tool platform
# you may make copies of the software and modify it to be used within the
# Vision tool platform, but you must include all of this notice on any copy.
# Redistribution without written permission to any third party, with or
# without modification, is not permitted.
# Altair Engineering, Inc. does not warrant that this software is error free
# or fit for any purpose.  Altair Engineering, Inc. disclaims any liability for
# all claims, expenses, losses, damages and costs any user may incur as a
# result of using, copying or modifying the software.
# =============================================================================
#   @plugin
#       ObfuscateVerilog
#   @namespace
#       Obfuscate
#   @section
#       Miscellaneous Userware Examples
#   @description
#       Obfuscates all names of the loaded design and writes Verilog code to
#       obfuscated directory structure. Generates obfuscated filesets and an
#       corresponding map to reverse the obfuscation (e.g. in a NanoTime
#       report).
#   @test
#       ModuleTest
#   @configuration
#   @files
#       obfuscate/obfuscate.tcl
#       obfuscate/obfuscatedNanoTimeReport_aquarius.rpt
#       obfuscate/hash.tcl
#       obfuscate/keywords.tcl
#   @example
#       demo/rtl/aquarius/aquarius.f
#   @cmdline
#       -compact off
#       -F @example[0]
#       -userware @files[0]
#   @tag
#       verilog rtl
###############################################################################


set path [file dirname [info script]]
source   [file join $path hash.tcl]
source   [file join $path keywords.tcl]

##
# Word separators.
#
set     ObfuscateWordSep [list " "]
lappend ObfuscateWordSep "(" ")"
lappend ObfuscateWordSep "\{"
lappend ObfuscateWordSep "\}"
lappend ObfuscateWordSep "\[" "\]"
lappend ObfuscateWordSep ":" "," ";" "." "\t"
lappend ObfuscateWordSep "&" "~" "!" "-" "+" "|" "^" "?"
lappend ObfuscateWordSep "=" "<" ">" "\"" "#" "'" "\\" "`"
lappend ObfuscateWordSep "/" "\*"
set     ObfuscateWordSep [join $ObfuscateWordSep ""]

##
# Pragma definitions.
#
set ObfuscatePragmaKeyword {"synopsys"}

##
# Ignore word after these tokens.
#
array set ObfuscateIgnoreAfter {$ 1}

##
# Declarations of variables.
#
array set ObfuscateMap           {}

set Obfuscate(forceWordHashLine) 0
set Obfuscate(isComment)         0
set Obfuscate(exportPath)        ""

##
# Keyword which has arguments which should be obfuscated.
# Modes:
# 1 - hash all names till line ends.
# 2 - next argument is a path.
# 3 - hash all names till command end with ;
# 4 - ignore all word till line ends.
# 5 - no argument
#
# Macro keyword
# 0 - no
# 1 - yes
#
array set ObfuscateKeywordWithArgument {}
set ObfuscateKeywordWithArgument(timescale)       {4 1}
set ObfuscateKeywordWithArgument(ifdef)           {1 1}
set ObfuscateKeywordWithArgument(ifndef)          {1 1}
set ObfuscateKeywordWithArgument(else)            {5 1}
set ObfuscateKeywordWithArgument(endif)           {5 1}
set ObfuscateKeywordWithArgument(celldefine)      {5 1}
set ObfuscateKeywordWithArgument(endcelldefine)   {5 1}
set ObfuscateKeywordWithArgument(define)          {1 1}
set ObfuscateKeywordWithArgument(undef)           {1 1}
set ObfuscateKeywordWithArgument(include)         {2 1}
set ObfuscateKeywordWithArgument(parameter)       {3 0}
set ObfuscateKeywordWithArgument(localparam)      {3 0}
set ObfuscateKeywordWithArgument(reg)             {3 0}
set ObfuscateKeywordWithArgument(defparam)        {3 0}
set ObfuscateKeywordWithArgument(function)        {3 0}
set ObfuscateKeywordWithArgument(typedef)         {3 0}


##
# Verilog keyword map to ignore all of them.
#
array set ObfuscateKeywords $verilogKeywords


##
# Menu Entries
#
set Obfuscate(menu) {
    {"Userware" "Obfuscate Design"}         {Obfuscate:Start {}}
    {"Userware" "Load Obfuscated NanoTime"} {Obfuscate:LoadNanoTime}
}


# -----------------------------------------------------------------------------
# _deObfuscateNanoTime - De-obfuscate NanoTime report.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_deObfuscateNanoTime {file map} {
    set filename             [file tail $file]
    set pid                  [pid]
    set obfuscatedNanoTime   [open $file rb]
    set fileIndex            0
    set deObfuscatedPath [file join [zos tempdir] "$filename.deobfuscated_$pid"]

    ##
    # Avoid duplicate names.
    #
    while {[file exists $deObfuscatedPath]} {
        set deObfuscatedPath ${deObfuscatedPath}_$fileIndex
        incr fileIndex
    }

    set deObfuscatedNanoTime [open $deObfuscatedPath wb]

    zmessage print INF "Creating $deObfuscatedNanoTime."

    gui console print $deObfuscatedPath

    ##
    # Replace all hashes by the origin word.
    #
    while {[gets $obfuscatedNanoTime line] >= 0} {
        set newline [string map $map $line]
        puts $deObfuscatedNanoTime $newline
    }

    close $obfuscatedNanoTime
    close $deObfuscatedNanoTime

    return $deObfuscatedPath
}


# =============================================================================
# LoadNanoTime - Load obfuscated nano time report.
# =============================================================================
#
proc Obfuscate:LoadNanoTime {{db {}}} {
    global NanoTime

    if {![info exists NanoTime(db)]} {
        NanoTime:initDB $db
    }

    if {$NanoTime(db) == {}} {
        set msg "No database loaded."
        zmessage print ERR $msg
        tk_messageBox -message $msg -icon error -parent . -title "Error:"
        return
    }

    ##
    # Get NanoTime report file.
    #
    set f [gui window fileDialog openFile "Open a NanoTime report file" \
        {{"NanoTime report" {"*"}}}]
    if {$f == ""} {
        return
    }

    ##
    # Get Map file.
    #
    set mapFile [gui window fileDialog openFile "Open an ObfuscateMap file" \
        {{"tcl-file" {"*.tcl"}}}]
    if {$mapFile == ""} {
        return
    }

    ##
    # Load Obfuscation map and create de-obfuscated file.
    #
    set map [Obfuscate:_obfuscateReadHashWordMap $mapFile]
    set deObfuscatedNanoTime [Obfuscate:_deObfuscateNanoTime $f $map]

    NanoTime:showFile $deObfuscatedNanoTime
}


# -----------------------------------------------------------------------------
# _getBasePath - Get the common paths of all files.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_getBasePath {fileList} {
    set commonPath ""
    set isCommon 1
    set splittedPaths {}

    if {[llength $fileList] < 1} {
        error "File list is empty"
    }

    if {[llength $fileList] == 1} {
        zmessage print DBG \
            "File list contains 1 file: $fileList "
        return [expr {[llength [file split [lindex $fileList 0]]] - 2}]
    }

    ##
    # Split path of all files and get shortest path.
    #
    set maxLength inf
    foreach file $fileList {
        set splittedPath [file split $file]
        set pathLength [llength $splittedPath]
        lappend splittedPaths $splittedPath

        if {$pathLength < $maxLength} {
            set maxLength $pathLength
        }
    }

    set depth 0

    ##
    # dive down until path is not common.
    #
    while {$isCommon} {
        set currentCommonDir ""
        foreach file $splittedPaths {
            set currentDir [lindex $file $depth]
            if {$currentCommonDir == ""} {
                set currentCommonDir $currentDir
            } elseif {($currentCommonDir != $currentDir) ||
                ($depth == $maxLength)
            } {
                incr depth -1
                set isCommon 0
                break
            }
        }
        if {$isCommon} {
            incr depth
        }
    }

    return $depth
}


# -----------------------------------------------------------------------------
# _processFFileLine - Process the line of the f file. All variables and file
#                     paths will be obfuscated.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_processFFileLine {line currentPath} {
    set newLine ""

    set words [split $line]
    if {[string match "//*" $line]} {
        return
    }
    set hashNextAsString 0
    set wordIndex 0
    set ignoreNextWord 0
    foreach word $words {
        zmessage print INF $word
        if {$ignoreNextWord} {
            append newLine $word
        } elseif {$hashNextAsString} {
            append newLine [Obfuscate:_addHashString $word]
        } elseif {[string match "-*" $word]} {
            zmessage print DBG \
                "found keyword $word"

            if {$word == "-top"} {
                set hashNextAsString 1
            }
            if {($word == "-define")} {
                if {[Obfuscate:_getConfigValue obfuscateMacro]} {
                    set hashNextAsString 1
                } else {
                    set ignoreNextWord 1
                }
            }

            append newLine "$word "
        } elseif {[string match "+*" $word]} {
            zmessage print DBG \
                "found keyword $word"
            set dirs    [split  $word +]
            set keyword [lindex $dirs 1]
            append newLine "+$keyword"
            if {[llength $dirs] > 2} {
                set arguments [lrange $dirs 2 end]
            } else {
                set arguments {}
            }

            switch -- $keyword {
                "define" {
                    foreach dir $arguments {
                        if {[Obfuscate:_getConfigValue obfuscateMacro]} {
                            append newLine "+[Obfuscate:_addHashString $dir]"
                        } else {
                            append newLine "+$dir"
                        }
                    }
                }
                "incdir" {
                    foreach dir $arguments {
                        append newLine "+[Obfuscate:_obfuscatePath $dir]"
                    }
                }
                default {
                    append newLine $arguments
                }
            }
        } else {
            append newLine [Obfuscate:_obfuscatePath $word]
        }
        incr wordIndex
    }

    set newLine [string trim $newLine]

    return $newLine
}


# -----------------------------------------------------------------------------
# _processFFile - Process the given F-file.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_processFFile {fname commonDepth} {
    ##
    # Open the input file in binary mode.
    #
    set in  [open $fname "rb"]

    set obfuscatedFname [Obfuscate:_createObfuscatedFile $fname $commonDepth]
    set currentPath     [file dirname $fname]

    ##
    # Open file and set mode.
    #
    set out [open $obfuscatedFname "wb"]

    ##
    # Read until the end of the input file.
    #
    while {![eof $in]} {
        ##
        # Read the next line of the input file.
        #
        set bytes [gets $in line]
        if {$bytes < 0} {
            break
        }

        set newLine [Obfuscate:_processFFileLine $line $currentPath]

        ##
        # Print the new line to the output file.
        #
        puts $out $newLine
    }

    ##
    # Close the in/output file.
    #
    close $out
    close $in
}


# -----------------------------------------------------------------------------
# _processFFiles - Find all f files in the base dir and process them.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_processFFiles {basePath commonDepth} {
    foreach file [glob -nocomplain -directory $basePath *.f] {
        Obfuscate:_processFFile $file $commonDepth
    }
    foreach directory [glob -nocomplain -directory $basePath -types d *] {
        Obfuscate:_processFFiles $directory $commonDepth
    }
}


# -----------------------------------------------------------------------------
# _createObfuscatedFile - Create the obfuscated file of fname and create all
#                         dirs beginning at commonDepth.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_createObfuscatedFile {fname commonDepth} {
    global Obfuscate

    ##
    # Get the file name and clone the folder structure.
    #
    set     splittedFname  [file split $fname]
    set     splittedPath   [lrange $splittedFname $commonDepth end]
    set     parentDir      [lindex $splittedFname [expr {$commonDepth - 1}]]
    append  parentDir      "_obfuscated"
    set     obfuscatedPath [list $parentDir]
    lappend obfuscatedPath \
        {*}[file split [Obfuscate:_obfuscatePath [file join {*}$splittedPath]]]

    ##
    # Create sub directories.
    #
    set index 0
    set end [llength $splittedPath]
    if {[llength $obfuscatedPath] > 1} {
        foreach dir [lrange $obfuscatedPath 0 end-1] {
            file mkdir [file join $Obfuscate(exportPath) \
                {*}[lrange $obfuscatedPath 0 $index]]
            incr index
        }
    }

    set obfuscatedFname [file join $Obfuscate(exportPath) {*}$obfuscatedPath]
    zmessage print DBG \
        "creating file $obfuscatedFname"
    return $obfuscatedFname
}


# -----------------------------------------------------------------------------
# _dumpRegisterMap - Dump a map of original register paths to the obfuscated
#                    ones.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_dumpRegisterMap {registerMapPath db} {
    set hiersep [$db oper hiersep get]

    set mapFile [open $registerMapPath "wb"]

    ##
    # Check each top module for instances which are clocked.
    #
    $db foreach top topmodule {
        $db flat foreach instOfCell clock $topmodule inst {
            set origPathString       ""
            set obfuscatedPathString ""
            set path                 [$db oid path $inst]

            ##
            # Hash each element in path.
            #
            foreach p $path {
                set hash [Obfuscate:_addHashString $p]
                append origPathString       "$p$hiersep"
                append obfuscatedPathString "$hash$hiersep"
            }

            set name       [$db oid oname $inst]
            set hashedName [Obfuscate:_addHashString $name]

            append origPathString       $name
            append obfuscatedPathString $hashedName

            puts -nonewline $mapFile "$origPathString $obfuscatedPathString"
        }
    }
    close $mapFile
}


# -----------------------------------------------------------------------------
# _dumpMapFile - Dump a map of the original names to the obfuscated ones.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_dumpMapFile {mapFilePath} {
    global ObfuscateMap

    set mapFile [open $mapFilePath "wb"]
    foreach {word hash} [array get ObfuscateMap] {
        if {$word == ""} {
            continue
        }
        set word [lindex [split $word ","] end]
        puts -nonewline $mapFile "$hash $word "
    }
    close $mapFile
}


# =============================================================================
# Start - Start the RTL code obfuscation.
# =============================================================================
#
proc Obfuscate:Start {db} {
    global Obfuscate ObfuscateMap

    ##
    # Clear Obfuscation Map
    #
    array unset ObfuscateMap
    zprogress begin

    ##
    # Only get the loaded database if running in interactive more. If running
    # in batch mode the database is already given to this procedure.
    #
    if {!$Obfuscate(config:runInBatchMode)} {
        set db [gui database get]
    }

    ##
    # Return if the database is empty.
    #
    if {$db == {}} {
        return
    }

    if {!$Obfuscate(config:runInBatchMode)} {
        set Obfuscate(exportPath) \
            [gui window fileDialog chooseDir "Chose Directory for Export" ""]
    }

    if {$Obfuscate(exportPath) eq ""} {
        return
    }

    set Obfuscate(exportPath) [file nativename $Obfuscate(exportPath)]

    zprogress push "Initializing: " 0.1

    ##
    # Initialize global variables.
    #
    Obfuscate:_initialize $db
    if {[zprogress pop]} {
        return
    }

    zprogress push "Process FFiles: " 0.2

    ##
    # Loop over all files loaded to the spos DB.
    #
    set fileList {}
    $db spos foreachfile fname modtime {
        lappend fileList [file normalize $fname]
    }

    ##
    # Get the base path of the project.
    #
    zmessage print DBG \
        "file list $fileList"
    set depth [Obfuscate:_getBasePath $fileList]
    set basePath [lrange [file split [lindex $fileList 0]] 0 $depth]
    incr depth

    zmessage print DBG \
        "basepath [file join {*}$basePath]"

    ##
    # Process all f-files.
    #
    if {[Obfuscate:_getConfigValue obfuscateFileset]} {
        Obfuscate:_processFFiles [file join {*}$basePath] $depth
    }

    if {[zprogress pop]} {
        return
    }

    ##
    # Process all used verilog files. !Important! verific does not return files
    # without used content (e.g. unused ifdef block)
    #
    zprogress push "Obfuscating file " 1.0

    Obfuscate:_processVerilogFiles $db $fileList $depth

    zprogress pop
    zprogress end

    ##
    # Dump a mapping file.
    #
    set     mapPath [list $Obfuscate(exportPath)]
    lappend mapPath "[lindex $basePath end]_obfuscated"
    Obfuscate:_dumpMapFile [file join {*}$mapPath obfuscateMap.tcl]

    ##
    # Dump a register map file.
    #
    Obfuscate:_dumpRegisterMap [file join {*}$mapPath registerMap.tcl] $db

    ##
    # Quit if we are in batch mode.
    #
    if {$Obfuscate(config:runInBatchMode)} {
        gui quit
    }
}


# -----------------------------------------------------------------------------
# _processVerilogFiles - Process all given verilog files.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_processVerilogFiles {db fileList depth} {
    set thisFile 0
    set fileCount [llength $fileList]

    foreach fname $fileList {
        ##
        # Update the progress bar.
        #
        set percent [expr {[incr thisFile] / double($fileCount) * 0.4}]
        zprogress push $fname $percent

        set obfuscatedFname [Obfuscate:_createObfuscatedFile $fname $depth]

        zmessage print DBG \
            "Processing file $fname -> $obfuscatedFname"


        ##
        # Call '_processFile' to obfuscate this source file.
        #
        Obfuscate:_processVerilogFile $db $fname {}

        ##
        # If the operation was interrupted delete the output file.
        #
        if {[zprogress pop]} {
            return
        }
    }

    set thisFile 0
    foreach fname $fileList {
        ##
        # Update the progress bar.
        #
        set percent [expr {[incr thisFile] / double($fileCount) * 0.4}]
        zprogress push $fname $percent

        set method "wb"
        set obfuscatedFname [Obfuscate:_createObfuscatedFile $fname $depth]

        zmessage print DBG \
            "Processing file $fname -> $obfuscatedFname"

        ##
        # Open file and set mode.
        #
        set out [open $obfuscatedFname $method]

        ##
        # Call '_processFile' to obfuscate this source file.
        #
        Obfuscate:_processVerilogFile $db $fname $out
        close $out

        ##
        # If the operation was interrupted delete the output file.
        #
        if {[zprogress pop]} {
            file delete -force -- $obfuscatedFname
            return
        }
    }
}


# -----------------------------------------------------------------------------
# _obfuscateReadHashWordMap - Read the given reverse map file.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_obfuscateReadHashWordMap {filename} {
    set hashWordFile [open $filename "rb"]
    set size [gets $hashWordFile line]
    if {$size < 0} {
        error "Reading empty hash word map file."
    }
    set size [gets $hashWordFile fileend]
    if {$size > 0} {
        error "File contains more then 1 line"
    }

    return $line
}


# -----------------------------------------------------------------------------
# _addHashString - Generate and add hash of the given string to the hash map.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_addHashString {name {cell {}}} {
    global ObfuscateMap

    ##
    # Check for forbidden brackets.
    #
    set nameIndex [string first "\[" $name]
    if {$nameIndex >= 0} {
        set name [string range $name 0 $nameIndex-1]
    }

    if {$cell == {}} {
        set key $name
    } else {
        set key "$cell,$name"
    }


    if {[info exists ObfuscateMap($key)]} {
        return $ObfuscateMap($key)
    }

    set hash [Obfuscate:HashName $name]
    set ObfuscateMap($key) $hash

    zmessage print DBG \
        "HashMap: $key $hash"

    return $ObfuscateMap($key)
}


# -----------------------------------------------------------------------------
# _addHash - Generate and add hash of the name of the given oid to the hash map.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_addHash {db cell oid} {
    set name [$db oid oname $oid]

    set rtlName [$db attr $oid getValue RTL_Name]
    if {$rtlName != {}} {
        set name $rtlName
    }

    if {([$db flag $oid supported autogen] && [$db flag $oid is autogen])} {
        return
    }

    Obfuscate:_addHashString $name $cell
}


# -----------------------------------------------------------------------------
# _initialize - Initialize global variables used by this Userware.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_initialize {db} {
    set count [$db count cell]
    set currentCell 1

    zprogress push "Generating hashes of cell" 1.0

    ##
    # Generate hash for all names of the database.
    #
    $db foreach cell cell {
        zprogress update "[$db oid oname $cell]" $currentCell $count
        incr currentCell

        ##
        # Ignore auto generated cells.
        #
        if {([$db flag $cell supported autogen] &&
            [$db flag $cell is autogen])
        } {
            continue
        }

        Obfuscate:_addHash $db $cell $cell
        zmessage print DBG \
            "add hash for cell $cell"

        $db foreach port $cell port {
            if {([$db oid type $cell] eq "module") &&
                ![Obfuscate:_getConfigValue obfuscateTopLevelPorts] &&
                [$db isTop $cell]
            } {
                zmessage print DBG \
                    "Top module - ignoring ports"
                break
            }
            Obfuscate:_addHash $db $cell $port
            if {[$db isBusMember $port]} {
                set portBus [$db busOf $port]
                Obfuscate:_addHash $db $cell $portBus
            }
        }

        if {![$db isModule $cell]} {
            continue
        }

        $db foreach inst $cell inst {
            if {([$db flag $inst is autogen])} {
                continue
            }

            Obfuscate:_addHash $db $cell $inst
            if {[$db isModule $inst]} {
                set oid [$db oid createModBased [$db moduleOf $inst]]
                Obfuscate:_addHash $db $oid $inst
                Obfuscate:_addHash $db $cell $oid
            }
        }

        $db foreach net $cell net {
            Obfuscate:_addHash $db $cell $net
            if {[$db isBusMember $net]} {
                set netBus [$db busOf $net]
                Obfuscate:_addHash $db $cell $netBus
            }
        }
    }

    zprogress pop
}


# -----------------------------------------------------------------------------
# _processVerilogFile - Read the input file line by line, update the progress
#                       bar and call _processVerilogLine for further
#                       obfuscation tasks.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_processVerilogFile {db fname out} {
    global Obfuscate

    ##
    # Open the input file in binary mode.
    #
    set in  [open $fname "r"]

    ##
    # Initialize variables for the file size, the current file position,
    # the actual line number and to indicate if inside a comment block.
    #
    set size    [file size $fname]
    set filePos 0
    set lineno  0
    set Obfuscate(forceWordHashSeparator) 0
    set Obfuscate(isMultiLineComment)     0
    set Obfuscate(isPragma)               0

    ##
    # Read until the end of the input file.
    #
    while {![eof $in]} {
        ##
        # Read the next line of the input file.
        #
        set bytes [gets $in line]
        if {$bytes < 0} {
            break
        }

        ##
        # Update the progress bar.
        #
        incr filePos $bytes
        if {[zprogress update "" $filePos $size]} {
            break
        }

        ##
        # Call _processVerilogLine to perform the actual obfuscation.
        #
        set newLine \
            [Obfuscate:_processVerilogLine $db $fname $line [incr lineno]]

        ##
        # Print the new line to the output file.
        #
        if {[Obfuscate:_getConfigValue removeEmptyLines]
            && ($newLine == "")
        } {
            zmessage print DBG \
                "Removing empty line"
        } elseif {$out != {}} {
            puts $out $newLine
        }
    }

    ##
    # Close the input file.
    #
    close $in
}


# -----------------------------------------------------------------------------
# _getConfigValue - Get the given configuration value.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_getConfigValue {name} {
    global Obfuscate

    if {[info exists Obfuscate($name)]} {
        set value $Obfuscate($name)
    } elseif {!$Obfuscate(config:runInBatchMode)} {
        set value [gui plugin getConfigValue Obfuscate $name]
    } else {
        set value 0
    }
    return $value
}


# -----------------------------------------------------------------------------
# _isWordIgnored - Check if given word should be ignored.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_isWordIgnored {word} {
    global ObfuscateKeywordWithArgument

    if {[info exists ObfuscateKeywordWithArgument($word)]} {
        return 1
    } else {
        return 0
    }
}


# -----------------------------------------------------------------------------
# _isWordMacroKeyword - Check if given word is a macro keyword.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_isWordMacroKeyword {word} {
    global ObfuscateKeywordWithArgument

    if {[info exists ObfuscateKeywordWithArgument($word)]} {
        set config $ObfuscateKeywordWithArgument($word)
        return [lindex $config 1]
    } else {
        return 0
    }
}


# -----------------------------------------------------------------------------
# _hasArgument - Check if given keyword has a argument which should be hashed.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_hasArgument {word} {
    global ObfuscateKeywordWithArgument

    if {[info exists ObfuscateKeywordWithArgument($word)]} {
        set config $ObfuscateKeywordWithArgument($word)
        return [lindex $config 0]
    } else {
        return 0
    }
}


# -----------------------------------------------------------------------------
# _obfuscatePath - Obfuscate the given path.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_obfuscatePath {path} {
    if {![Obfuscate:_getConfigValue obfuscateFileStructure]} {
        return $path
    }

    ##
    # Special case "."
    #
    if {$path eq "."} {
        return $path
    }

    ##
    # Split path and obfuscate every directory.
    #
    set splittedPath [lrange [file split $path] 0 end-1]
    set obfuscatedPath {}
    zmessage print DBG $splittedPath
    foreach dir $splittedPath {
        if {$dir == "/"} {
            lappend obfuscatedPath $dir
        } elseif {[regexp {^\$} $dir]} {
            lappend obfuscatedPath $dir
        } else {
            lappend obfuscatedPath [Obfuscate:_addHashString $dir]
        }
    }
    set fileExtension [file extension $path]
    set fileName      [file rootname [file tail $path]]
    lappend obfuscatedPath "[Obfuscate:_addHashString $fileName]$fileExtension"

    zmessage print DBG \
        "newPath: $path -> [file join {*}$obfuscatedPath]"
    return [file join {*}$obfuscatedPath]
}


# -----------------------------------------------------------------------------
# _isOidTypeIgnored - check if a oid of the given list is an ignored type.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_isOidTypeIgnored {db oidList} {
    if {$oidList == {}} {
        return 0
    }

    foreach oid $oidList {
        set type [$db oid type $oid]
        zmessage print DBG \
            "checking type $type"
        if {![$db hasParentMod $oid]} {
            continue
        }
        set parentModule [$db parentModule $oid]

        ##
        # Check for top level port.
        #
        if {(![$db isTop $parentModule]) ||
            ([$db isTop $parentModule] &&
            [Obfuscate:_getConfigValue obfuscateTopLevelPorts])
        } {
            return 0
        }

        switch -- $type {
            "netBus" {
                ##
                # Check if any net of the netbus is connected to a port.
                #
                $db foreach net $oid net {
                    $db foreach portCon $net port {
                        return 1
                    }
                }
            }
            "net" {
                ##
                # Check if net is connected to a port.
                #
                $db foreach portCon $oid port {
                    return 1
                }
            }
            "portBus" -
            "port" {
                return 1
            }
            default {
            }
        }
    }
    return 0
}


# -----------------------------------------------------------------------------
# _getModuleFromList - Get the first module oid from list.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_getModuleFromList {db oidList} {
    foreach oid $oidList {
        if {$oid == {}} {
            continue
        }
        set type [$db oid type $oid]
        if {$type eq "module"} {
            return $oid
        }
    }
    return {}
}


# -----------------------------------------------------------------------------
# _isOnlyBaseDefinition - Check if word contains only the base definition of
#                         an integer literal constant.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_isOnlyBaseDefinition {word} {
    if {[regexp {^[sS]?[dDhHoObB]$} $word]} {
        return 1
    }
    return 0
}


# -----------------------------------------------------------------------------
# _processVerilogWord - obfuscate the given word.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_processVerilogWord {db word oidList} {
    global Obfuscate ObfuscateKeywords

    zmessage print DBG \
        "### Checking word |$word|"
    zmessage print DBG \
        [array get Obfuscate]

    ##
    # Init vars.
    #
    set oid            {}
    set module         {}

    ##
    # ignore overwrites force.
    #
    set ignoreThisWord 0
    set forceWordHash  0
    set removeThisWord 0

    ##
    # Do checks on oidList if it is available.
    #
    if {$oidList!= {}} {
        set ignoreThisWord [Obfuscate:_isOidTypeIgnored $db $oidList]
        set module         [Obfuscate:_getModuleFromList $db $oidList]
        set oid            [lindex $oidList 0]
    }

    ##
    # Check if this word should be ignored.
    #
    if {$Obfuscate(ignoreNextWord)} {
        zmessage print DBG \
            "this word is ignored (triggered by ignore next word)"
        incr Obfuscate(ignoreNextWord) -1
        set ignoreThisWord 1
    }

    if {$Obfuscate(ignoreAllWords)} {
        zmessage print DBG \
            "this word is ignored (triggered by ignore all words)"
        set ignoreThisWord 1
    }

    ##
    # Check if word is a verilog keyword.
    #
    if {[info exists ObfuscateKeywords($word)]} {
        zmessage print DBG \
            "verilog keyword $word"
        set ignoreThisWord 1
    }

    ##
    # Check if word is a number.
    #
    if {[string is digit $word]} {
        zmessage print DBG \
            "word is digit"
        set ignoreThisWord 1
    }

    ##
    # Ignore this word if it is a integer literal constant.
    #
    if {$Obfuscate(isIntLiteral)} {
        zmessage print DBG \
            "word is in integer literal"
        set ignoreThisWord 1
        if {[Obfuscate:_isOnlyBaseDefinition $word]} {
            zmessage print DBG \
                "word is only base definition"
            set Obfuscate(ignoreNextWord) 1
        } else {
            set Obfuscate(isIntLiteral) 0
        }
    }

    ##
    # Check if word is a macro.
    #
    if {$Obfuscate(isMacro)} {
        ##
        # If macro should be obfuscated, force all words in macro to be hashed.
        #
        if {[Obfuscate:_getConfigValue obfuscateMacro]} {
            zmessage print DBG \
                "word is macro and will be obfuscated"
            set forceWordHash 1
            set ignoreThisWord 0
        } else {
            zmessage print DBG \
                "word is macro, but macros are not being obfuscated"
            set ignoreThisWord 1
        }
    }

    ##
    # Check if word is on ignore list
    #
    if {[Obfuscate:_isWordIgnored $word]} {
        zmessage print DBG \
            "word is on ignore list"
        set ignoreThisWord 1
    }

    ##
    # Check if word is comment.
    #
    if {$Obfuscate(isComment) && (!$Obfuscate(isPragma))} {
        zmessage print DBG \
            "word is comment"
        set removeThisWord 1
    }

    ##
    # Check if word is forced to be hashed.
    #
    if {$Obfuscate(forceWordHashLine) || $Obfuscate(forceWordHashSeparator)} {
        zmessage print DBG \
            "word is forced to be hashed"
        set forceWordHash 1
    }

    ##
    # Check if word is path and obfuscate it with special function.
    #
    if {$Obfuscate(wordIsPath)} {
        zmessage print DBG \
            "word is path"
        set word                      [Obfuscate:_obfuscatePath $word]
        set ignoreThisWord            1
        set Obfuscate(ignoreAllWords) 1
    }

    zmessage print DBG \
        "Applying to word ignoreThisWord: $ignoreThisWord, \
        forceWordHash: $forceWordHash, removeThisWord: $removeThisWord"

    ##
    # If word is forced to be hashed, add it to the map.
    #
    if {(!$ignoreThisWord) && $forceWordHash} {
        Obfuscate:_addHashString $word
        Obfuscate:_addHashString $word $module
    }

    ##
    # If this word is not ignored, obfuscate it.
    #
    if {!$ignoreThisWord} {
        set word [Obfuscate:_obfuscateVerilogWord $db $module $oid $word]
    }

    ##
    # If this word should be remove set return value to empty string.
    #
    if {$removeThisWord} {
        set word ""
    }

    ##
    # Check if it is a keyword which has an argument and changes the mode of the
    # next word.
    #
    if {[Obfuscate:_isWordMacroKeyword $word] &&
        (![Obfuscate:_getConfigValue obfuscateMacro])
    } {
        set wordMode 0
    } else {
        set wordMode [Obfuscate:_hasArgument $word]
    }
    zmessage print DBG \
        "Setting mode for next word $wordMode"

    switch -- $wordMode {
        1 {
            set Obfuscate(forceWordHashLine) 1
        }
        2 {
            set Obfuscate(wordIsPath) 1
        }
        3 {
            set Obfuscate(forceWordHashSeparator) 1
        }
        4 {
            set Obfuscate(ignoreAllWords) 1
        }
        default {
        }
    }

    zmessage print DBG \
        "### end: |$word|"
    return $word
}


# -----------------------------------------------------------------------------
# _obfuscateVerilogWord - Obfuscate the given word.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_obfuscateVerilogWord {db module oid word} {
    global ObfuscateMap

    set key {}
    if {($oid != {})                    &&
        ([$db oid type $oid] eq "inst") &&
        [$db isModule $oid]
    } {
        set module2 [$db oid createModBased [$db moduleOf $oid]]
        set key "$module2,$word"
    }

    if {($module != {} ) &&
        (($key == {}) || (![info exists ObfuscateMap($key)]))
    } {
        set key "$module,$word"
    } elseif {($key == {})} {
        set key $word
    }

    if {(![info exists ObfuscateMap($key)]) &&
        [info exists ObfuscateMap($word)]
    } {
        set key $word
    }

    zmessage print DBG \
        "using key $key"
    if {[info exists ObfuscateMap($key)]} {
        set word $ObfuscateMap($key)
    } else {
        zmessage print DBG \
            "no hash map entry"
    }
    return $word
}


# -----------------------------------------------------------------------------
# _checkForComment - Check if comment starts or ends.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_checkForComment {nextTwoChars} {
    global Obfuscate

    ##
    # Check if we are at the beginning of a comment.
    #
    if {$Obfuscate(commentEnded) || ($Obfuscate(commentStarted) == 2)} {
        return
    }

    ##
    # Check if the given chars are comment begin are end.
    #
    if {($nextTwoChars == "//") && !($Obfuscate(isComment))} {
        set Obfuscate(commentStarted)     1
        set Obfuscate(lastComment)        "line"
        set Obfuscate(isComment)          1
        zmessage print DBG \
            "start line comment"
    } elseif {($nextTwoChars == "/\*") && !($Obfuscate(isComment))} {
        set Obfuscate(isMultiLineComment) 1
        set Obfuscate(commentStarted)     1
        set Obfuscate(lastComment)        "block"
        set Obfuscate(isComment)          1
        zmessage print DBG \
            "start block comment"
    } elseif {($nextTwoChars == "\*/") && $Obfuscate(isMultiLineComment)} {
        zmessage print DBG \
            "end block comment"
        set Obfuscate(isMultiLineComment) 0

        ##
        # If comment is pragma, write block comment off.
        #
        if {$Obfuscate(isPragma)} {
            set Obfuscate(isPragma)       0
            set Obfuscate(ignoreAllWords) 0
            zmessage print DBG \
                "pragma end"
        } else {
            set Obfuscate(commentEnded)       1
        }
    }
}


# -----------------------------------------------------------------------------
# _processVerilogLine - Process the given line and obfuscate all requested
#                       items.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_processVerilogLine {db fname line lineno} {
    global Obfuscate ObfuscateWordSep ObfuscateIgnoreAfter

    set Obfuscate(lastComment)  ""
    set newLine                 ""
    set length                  [string length $line]
    set inWord                  0
    set startWord               0
    set separator               ""
    set lastSeparator           ""

    ##
    # Check if spos exists for the given file.
    #
    if {[$db spos exists $fname]} {
        set filePos      [$db spos filepos $fname $lineno]
        set startLinePos [lindex $filePos 0]
    } else {
        set startLinePos ""
    }

    ##
    # If we are still in a comment and if it is not a pragma set variable again.
    #
    if {$Obfuscate(isMultiLineComment) && (!$Obfuscate(isPragma))} {
        set Obfuscate(isComment)       1
    } else {
        set Obfuscate(isComment)       0
    }

    ##
    # Reset all the global indicator variables.
    #
    set Obfuscate(ignoreAllWords)      0
    set Obfuscate(ignoreNextWord)      0
    set Obfuscate(wordIsPath)          0
    set Obfuscate(isMacro)             0
    set Obfuscate(forceWordHashLine)   0
    set Obfuscate(commentStarted)      0
    set Obfuscate(commentEnded)        0
    set Obfuscate(isIntLiteral)        0
    set wordSep                        $ObfuscateWordSep
    set isInPath                       0
    set commentStart                   0

    zmessage print DBG \
        "=== start processing line ==="
    zmessage print DBG \
        [array get Obfuscate]

    ##
    # Process characters in line.
    #
    for {set pos 0} {$pos <= $length} {incr pos} {
        ##
        # Check for word separator.
        #
        set currentChar    [string index $line $pos]
        set separatorIndex [string first $currentChar $wordSep]
        set word           ""

        zmessage print DBG \
            "--- processing current char $currentChar ---"

        ##
        # Check if we reached end of line.
        #
        if {$pos == $length} {
            set lastSeparator $separator
        }

        ##
        # Check if current char is word separator or if we are at the end of
        # the line
        #
        if {($separatorIndex != -1) || ($pos == $length)} {
            if {$inWord} {
                ##
                # Reset last separator.
                #
                set lastSeparator       $separator
                set separator           ""
                set inWord              0

                ##
                # Get the current word.
                #
                set word [string range $line $startWord [expr {$pos - 1}]]
            }

            ##
            # Ignore all separators in the comments.
            #
            if {!$Obfuscate(isComment)} {
                zmessage print DBG \
                    "appending $currentChar to separator"
                append separator $currentChar
            }
        } elseif {!$inWord} {
            set startWord $pos
            set inWord 1
        }

        if {($word != "") || ($pos == $length)} {
            ##
            # Check if word is a macro.
            #
            if {[string match "*`" $lastSeparator]} {
                set Obfuscate(isMacro) 1
            } else {
                set Obfuscate(isMacro) 0
            }

            ##
            # If we are not in a comment or the separator is forced, append it
            # to the current line.
            #
            append newLine $lastSeparator
            zmessage print DBG \
                "appending separator $lastSeparator"
        }

        ##
        # If word is completed process it.
        #
        if {$word != ""} {
            ##
            # Check if spos are available and get oid list.
            #
            if {$startLinePos != ""} {
                set currentFilePos [expr {$startLinePos + $startWord}]
                set oidList        [$db spos picklist $fname $currentFilePos]
            } else {
                set oidList        {}
            }

            ##
            # If comment began before this word, check if word is a pragma
            # keyword.
            #
            if {$Obfuscate(commentStarted)} {
                set Obfuscate(isPragma) [Obfuscate:_isPragmaKeyword $word]
                set Obfuscate(commentStarted) 0

                zmessage print DBG \
                    "Checking for pragma keyword: $Obfuscate(isPragma)"

                ##
                # If word is a pragma disable comment handling.
                #
                if {$Obfuscate(isPragma)} {
                    set Obfuscate(isComment) 0
                    set Obfuscate(ignoreAllWords) 1

                    if {$Obfuscate(lastComment) eq "block"} {
                        append newLine "/\* "
                    } elseif {$Obfuscate(lastComment) eq "line"} {
                        append newLine "// "
                    }
                    append separator $currentChar
                }
            }

            ##
            # Process word and append result to the current line.
            #
            zmessage print DBG \
                "checking oid: $oidList"
            append newLine \
                [Obfuscate:_processVerilogWord \
                    $db            \
                    $word          \
                    $oidList       \
                ]
            set word ""
        }

        ##
        # Check if we are in path parse mode and waiting for " to end.
        #
        if {$Obfuscate(wordIsPath) && ($currentChar == "\"") } {
            if {$isInPath} {
                set isInPath 0
                set Obfuscate(wordIsPath) 0
                set wordSep $ObfuscateWordSep
                zmessage print DBG \
                    "!! Path parse DISabled !! $isInPath, $currentChar"
            } else {
                set isInPath 1
                set wordSep "\""
                zmessage print DBG \
                    "!! Path parse enabled !! $isInPath, $currentChar"
            }
        }

        ##
        # Check if separator requires to ignore next word.
        #
        if {[info exists ObfuscateIgnoreAfter($currentChar)]} {
            set Obfuscate(ignoreNextWord) 1
        }

        if {$currentChar == "'"} {
            set Obfuscate(isIntLiteral) 1
        }

        ##
        # Check if current char is colon to reset forced hashing.
        #
        if {$currentChar == ";"} {
            set Obfuscate(forceWordHashSeparator) 0
        }

        ##
        # Checking for comment start/end.
        #
        if {($pos < ($length - 1))} {
            set nextTwoChars [string range $line $pos $pos+1]
            Obfuscate:_checkForComment $nextTwoChars
        }

        ##
        # If comment started the start character of the comment is already
        # added to the separator list, so we have to remove it. Count to avoid
        # misinterpreting of comment start sequences.
        #
        if {$Obfuscate(commentStarted) == 1} {
            set separator [string range $separator 0 end-1]
            incr Obfuscate(commentStarted)
        } elseif {$Obfuscate(commentStarted) == 2} {
            incr Obfuscate(commentStarted)
        }

        ##
        # If block comment ended, next char belongs to the comment, because
        # we are doing a look ahead for comment detection.
        #
        if {$Obfuscate(commentEnded) == 2} {
            set Obfuscate(commentEnded) 0
            set Obfuscate(isComment)    0
        } elseif {$Obfuscate(commentEnded)} {
            incr Obfuscate(commentEnded)
        }

        zmessage print DBG \
            "--- processing done ---"
    }

    if {[Obfuscate:_getConfigValue removeWhiteSpace]} {
        set newLine [string trim $newLine]
    }

    ##
    # Check if pragma ended.
    #
    if {$Obfuscate(isPragma) && (!$Obfuscate(isMultiLineComment))} {
        set Obfuscate(isPragma) 0
    }


    zmessage print DBG \
        "=== end processing line ==="
    return $newLine
}


# -----------------------------------------------------------------------------
# _isPragmaKeyword - Check if given word is a pragma keyword.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_isPragmaKeyword {word} {
    global ObfuscatePragmaKeyword

    set pragmaIndex [lsearch $ObfuscatePragmaKeyword $word]

    if {$pragmaIndex > -1} {
        return 1
    }
    return 0
}


# -----------------------------------------------------------------------------
# _addMenuEntries - Add the entries to the menu.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_addMenuEntries {} {
    global Obfuscate

    foreach {menuPath cmd} $Obfuscate(menu) {
        gui menu command $menuPath $cmd
    }
}


# -----------------------------------------------------------------------------
# _removeMenuEntries - Remove the entries to the menu.
# -----------------------------------------------------------------------------
#
proc Obfuscate:_removeMenuEntries {} {
    global Obfuscate

    foreach {menuPath cmd} $Obfuscate(menu) {
        gui menu removeEntry $menuPath
    }
}


# -----------------------------------------------------------------------------
# _addPluginToGui - Add
# -----------------------------------------------------------------------------
#
proc Obfuscate:_addPluginToGui {} {
    ##
    # Extend the main menu and add an 'Obfuscate RTL' entry.
    #
    Obfuscate:_addMenuEntries

    gui plugin addConfig Obfuscate removeWhiteSpace False bool \
        "Remove whitespace"

    gui plugin addConfig Obfuscate removeEmptyLines False bool \
        "Remove empty lines"

    gui plugin addConfig Obfuscate obfuscateFileStructure False bool \
        "Obfuscate File Structure  (experimental)"

    gui plugin addConfig Obfuscate obfuscateFileset False bool \
        "Process Filesets (experimental)"

    gui plugin addConfig Obfuscate obfuscateMacro False bool \
        "Obfuscate Macro (experimental)"

    gui plugin addConfig Obfuscate obfuscateTopLevelPorts False bool \
        "Obfuscate Top Level Ports"
}


# =============================================================================
# SetValue - Set the given value at the $Obfuscate($name) variable.
# =============================================================================
#
proc Obfuscate:SetValue {name value} {
    global Obfuscate

    set Obfuscate($name) $value
}


# =============================================================================
# GetValue - Get the value of the given $Obfuscate($name) variable.
# =============================================================================
#
proc Obfuscate:GetValue {name} {
    global Obfuscate

    if {![info exists Obfuscate($name)]} {
        error "Variable Obfuscate($name) does not exist"
    }

    return $Obfuscate($name)
}


# =============================================================================
# ResetMap - Set the given value at the $Obfuscate($name) variable.
# =============================================================================
#
proc Obfuscate:ResetMap {} {
    global ObfuscateMap

    array unset ObfuscateMap
}


# =============================================================================
# Init - initialize plugin.
# =============================================================================
#
proc Obfuscate:Init {} {
    global Obfuscate

    if {$Obfuscate(config:runInBatchMode)} {
        gui database registerChangedCallback "Obfuscate:Start"
    } else {
        Obfuscate:_addPluginToGui
    }
}


# =============================================================================
# Finit - Clean up.
# =============================================================================
#
proc Obfuscate:Finit {} {
    Obfuscate:_removeMenuEntries
}


# =============================================================================
# CheckCmdLine - Check the commandline arguments.
# =============================================================================
#
proc Obfuscate:CheckCmdLine {argc argv} {
    global Obfuscate path

    if {$argc == 0} {
        set Obfuscate(config:runInBatchMode) 0
        return 1
    } elseif {$argc > 1} {
        zmessage print ERR "Usage of plugin: $path \$exportPath"
        return 0
    }
    set Obfuscate(exportPath) [lindex $argv 0]
    set Obfuscate(config:runInBatchMode) 1

    return 1
}


##
# Run plugin and check cmdline arguments.
#
if {[Obfuscate:CheckCmdLine $argc $argv]} {
    Obfuscate:Init
}