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 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
|
#!/usr/bin/env python3
#===============================================================================
# Copyright 2014 NetApp, Inc. All Rights Reserved,
# contribution by Jorge Mora <mora@netapp.com>
#
# 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 2 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.
#===============================================================================
import os
import re
import sys
import time
import textwrap
import nfstest_config as c
from optparse import OptionParser, IndentedHelpFormatter
# Module constants
__author__ = "Jorge Mora (%s)" % c.NFSTEST_AUTHOR_EMAIL
__copyright__ = "Copyright (C) 2014 NetApp, Inc."
__license__ = "GPL v2"
__version__ = "1.5"
USAGE = """%prog [options] <xdrfile1.x> [<xdrfile2.x> ...]
Convert the XDR definition file into python code
================================================
Process the XDR program definition file and convert it into python code.
A couple of files are created: xdrfile1_const.py where all constant definitions
and enum dictionaries are stored and xdrfile1.py where the python code
corresponding to all structures and discriminated unions are stored.
A variable length array or opaque with a maximum length of 1 (name<1>)
is changed to a regular non-list variable to make it easier to access.
If the length is 0 then the variable will have a value of None.
Linked lists are changed into a simple list, so when the following definition
is processed:
struct entry4 {
nfs_cookie4 cookie;
component4 name;
fattr4 attrs;
entry4 *nextentry;
};
struct dirlist4 {
entry4 *entries;
bool eof;
};
The class created for entry4 will not have the nextentry attribute and the
entries attribute in class dirlist4 will be a simple list of entry4 items.
This makes it easier to access the list in python instead of traversing
the linked list.
In addition to processing the XDR definitions, it processes different tags
to change or expand the behavior of the python object being created.
These tags are given as comments in the XDR definition file and are given
using the following syntax:
COPYRIGHT: year
Add copyright information to the python modules created
VERSION: version
Add version information to the python modules created
INCLUDE: file
Include the file and add it in-line to be processed
COMMENT: comment
Include the comment in both the decoding and constants modules
IMPORT: name[ as alias]
Add import statement
INHERIT: name
Create class inheriting from the given base class name. The name is
is given as a full path including the package and class name, e.g.:
/* INHERIT: packet.nfs.nfsbase.NFSbase */
struct Obj {
int id;
opaque data;
};
Creates the following:
from packet.nfs.nfsbase import NFSbase
class Obj(NFSbase):
...
XARG: name[;disp][,...]
Add extra arguments to the object constructor __init__()
The disp modifier is to make it a displayable attribute, e.g.:
/* XARG: arg1, arg2;disp */
CLASSATTR: name[;disp]=value[,...]
Add name as a class attribute
The disp modifier is to make it a displayable attribute
OBJATTR: name[;disp]=value[,...]
Add extra attribute having the given value. If value is the name of
another attribute in the object a "self." is added to the value, e.g.:
/* OBJATTR op=argop, fh=self.nfs4_fh, id="123" */
Creates the following attributes:
self.op = self.argop
self.fh = self.nfs4_fh
self.id = "123"
If argop and nfs4_fh is an attribute for the object.
The disp modifier is to make it a displayable attribute
GLOBAL: name[=value][,...]
Set global attribute using set_global(). The value is processed the
same as OBJATTR.
If no value is given, the name given is a global defined somewhere
else so it should not be defined -- this is a reference to a global
FLATATTR: 1
Make the object attributes of the given attribute part of the
attributes of the current object, e.g.:
struct Obj2 {
int attr1;
};
struct Obj1 {
int count;
Obj2 res; /* FLATATTR: 1 */
};
An object instantiated as x = Obj1() is able to access all attributes
for "res" as part of the Obj1 object (x.attr1 is the same as x.res.attr1)
EQATTR: name
Set comparison attribute so x == x.name is True, e.g.:
/* EQATTR: id */
struct Obj {
int id;
opaque data;
};
An object instantiated as x = Obj() can use x == value,
the same as x.id == value
STRFMT1: <format>
String representation format for object when using debug_repr(1), e.g.:
/* STRFMT1 : {0#x} {1} */
Where the index points to the object attribute defined in _attrlist
{0#x} displays the first attribute in hex
{1} displays the second attribute using str()
For more information see FormatStr()
STRFMT2: <format>
String representation format for object when using debug_repr(2)
STRHEX: 1
Display attribute in hex.
If given on a typedef, any attribute defined by this typedef
will be displayed in hex.
FOPAQUE: name
The definition for a variable length opaque is broken down into its
length and data, e.g.:
opaque data<> /* FOPAQUE: count */
Converted to
unsigned int count;
opaque data[count];
FMAP: 1
Add extra dictionary table for an enum definition which maps the value
to a decoding function given by the lower case value of the key
The resulting table is created in the main python file, not in the
constants file:
/* FMAP: 1 */
enum nfs_fattr4 {
FATTR4_SUPPORTED_ATTRS = 0,
FATTR4_TYPE = 1,
};
Creates the additional dictionary:
nfs_fattr4_f = {
0: fattr4_supported_attrs,
1: fattr4_type,
};
FWRAP: attr=fname[,attr1=fname1[...]]
Add function wrapper to the given attribute definition
/* INHERIT: BaseClass */
/* FWRAP: info=infowrap,data=BaseClass.datawrap */
struct TestInfo {
stinfo info[4];
opaque data<>;
};
Creates the following:
class TestInfo(BaseClass):
def __init__(self, unpack):
self.info = infowrap(unpack.unpack_array, stinfo, 4)
self.data = self.datawrap(unpack.unpack_opaque)
BITMAP: 1
On a typedef use unpack_bitmap() to decode
/* BITMAP: 1 */
typedef uint32_t bitmap4<>;
Creates the following:
bitmap4 = Unpack.unpack_bitmap
BITLIST: attr=enum_def
Create a list of bit attributes given by the bitmap
struct fattr4 {
uint32 flags;
uint32 mask<>; /* BITLIST: attributes=nfs_fattr4 */
};
Where the mask gives which bits are set, the bit names are given
by enum_def and attr is the name of the new attribute to create
BITDICT: enum_def
Convert an object to a dictionary where the key is the bit number
and the value is given by executing the function provided by the
enum definition table specified by FMAP
Use on a structure with the following definition:
/* BITDICT: nfs_fattr4 */
struct fattr4 {
uint32 mask<>;
opaque values<>;
};
Where the mask gives which bits are encoded in the opaque given
by values. For more information see packet.utils.
BITMAPOBJ: dmask[,args]
Create a Bitmap() using the dictionary table dname. Table dname
should be created using the bitmap tag, e.g.:
typedef uint32_t access4; /* BITMAPOBJ:const.nfs4_access, sep="," */
Creates the following:
access4 = lambda unpack: Bitmap(unpack, const.nfs4_access, sep=",")
For more information see packet.utils.
TRY: 1
Add try/except block to object definition
Also, the following comment markers are processed. The marker must be in
the first line of a multi-line comment:
__DESCRIPTION__
Description for the decoding module. If it is not given a default
description is used.
__CONST__
Description for the constants module. If it is not given a default
description is used. This marker is given within the same comment
starting with the __DESCRIPTION__ marker."""
# Types to decode using unpack_int()
int32_list = ["int"]
# Types to decode using unpack_uint()
uint32_list = ["unsigned int"]
# Types to decode using unpack_int64()
int64_list = ["hyper"]
# Types to decode using unpack_uint64()
uint64_list = ["unsigned hyper"]
# Types to decode using unpack_utf8()
utf8_list = ["string"]
# Types to decode string
string_list = ["opaque"] + utf8_list
valid_tags = {
"COPYRIGHT" : 1,
"VERSION" : 1,
"INCLUDE" : 1,
"IMPORT" : 1,
"COMMENT" : 1,
"XARG" : 1,
"CLASSATTR" : 1,
"FLATATTR" : 1,
"TRY" : 1,
"STRFMT1" : 1,
"STRFMT2" : 1,
"FOPAQUE" : 1,
"STRHEX" : 1,
"FMAP" : 1,
"FWRAP" : 1,
"BITMAP" : 1,
"BITLIST" : 1,
"BITDICT" : 1,
"OBJATTR" : 1,
"GLOBAL" : 1,
"EQATTR" : 1,
"INHERIT" : 1,
"BITMAPOBJ" : 1,
}
# Constants
CONSTANT = 0
ENUM = 1
UNION = 2
STRUCT = 3
BITMAP = 4
deftypemap = {
"enum" : ENUM,
"union" : UNION,
"struct" : STRUCT,
"bitmap" : BITMAP,
}
empty_quotes = ("''", '""')
copyright_str = """
#===============================================================================
# Copyright __COPYRIGHT__ NetApp, Inc. All Rights Reserved,
# contribution by Jorge Mora <mora@netapp.com>
#
# 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 2 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.
#===============================================================================
"""
modconst_str = """
# Module constants
__author__ = "Jorge Mora (%s)" % c.NFSTEST_AUTHOR_EMAIL
__copyright__ = "Copyright (C) __COPYRIGHT__ NetApp, Inc."
__license__ = "GPL v2"
__version__ = __VERSION__
"""
# Variable definition regex
# unsigned int varname;
# int *varname;
# opaque varname<20>;
# Examples:
# unsigned int stamp;
# ("unsigned int", " int", "int", "", "stamp", "", None)
# opaque server_scope<NFS4_OPAQUE_LIMIT>;
# ("opaque", None, None, "", "server_scope", "<NFS4_OPAQUE_LIMIT>", "<NFS4_OPAQUE_LIMIT>")
vardefstr = r"\s*([\w.]+(\s+(\w+))?)\s+(\*?)\s*(\w+)(([<\[]\w*[>\]])?)"
class XDRobject:
def __init__(self, xfile):
"""Constructor which takes an XDR definition file as argument"""
# Dictionary of typedef where key is the typedef name and the value
# is a list [type declaration, pointer marker, array declaration]
self.dtypedef = {}
# List of typedef definitions where each entry is a list
# [typedef name, type declaration, array declaration, tags, comments array]
self.typedef_list = []
# Dictionary of base objects used in inheritance, use a dictionary
# instead of a list to have unique elements
self.inherit_names = {}
# Copyright and module info constants
self.copyright = None
self.modversion = None
self.description = None
self.desc_const = None
# Enum data list where each entry is a dictionary having the following keys:
# deftype, defname, deftags, defcomm, enumlist
self.enum_data = []
# FMAP dictionary where key is the definition name and the value
# is the enum entry
self.fmap_data = {}
# Constants dictionary where key is the constant name
self.dconstants = {}
# List of enum names
self.enumdef_list = []
# List of bitmap typedefs
self.bitmap_defs = []
# List of imports
self.import_list = []
# Tags dictionary
self.tags = {}
# Attributes used for processing comments
self.incomment = False
self.is_comment = False
self.blank_lines = 0
# Initialize definition variables
self.reset_defvars()
# Input file
self.xfile = xfile
(self.bfile, ext) = os.path.splitext(self.xfile)
self.bname = os.path.basename(self.bfile)
self.import_path = os.path.dirname(self.xfile).replace(os.sep, ".")
if len(self.import_path):
self.import_path += "."
# Output file for python class objects
self.pfile = self.bfile + ".py"
# Output file for python constants and mapping dictionaries
self.cfile = self.bfile + "_const.py"
if self.pfile == self.xfile:
print(" The input file has a python extension,\n" + \
" it will not be overwritten")
return
# Timestamp output files are generated
progname = os.path.basename(sys.argv[0])
stime = time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())
self.genstr = "# Generated by %s from %s on %s\n" % (progname, self.xfile, stime)
# Contents of XDR file
self.xdr_lines = []
self.read_file()
self.process_enum_and_const()
self.process_xdr()
def read_file(self):
"""Read entire contents of XDR definition file"""
for line in open(self.xfile, "r"):
self.process_comments(line)
incl_file = self.tags.pop("INCLUDE", None)
if incl_file is not None:
print(" Including file %s" % incl_file)
for incl_line in open(incl_file, "r"):
self.xdr_lines.append(incl_line)
continue
imp_str = self.tags.pop("IMPORT", None)
if imp_str is not None:
self.import_list.append("import %s\n" % imp_str)
self.xdr_lines.append(line)
def reset_defvars(self):
"""Reset all definition variables"""
# Attribute definition list for a struct, union (all vars defs)
self.item_dlist = []
# Case definition list
self.case_list = []
# In-line comment
self.inline_comment = ""
# Multi-line comment
self.multi_comment = []
# Previous comment
self.old_comment = []
def gettype(self, dtype, usetypedef=True):
"""Return real definition type
dtype:
Definition type given in XDR file
usetypedef:
If usetypedef is False the return value is just dtype except
for type of "bool" which is changed to "nfs_bool" to avoid
confusion with python's own bool keyword.
If usetypedef is True the list of typedefs is traversed
until a basic def type is found and returned, e.g.,
Giving the following typedef:
typedef opaque nfs_fh4<NFS4_FHSIZE>;
And the following code:
nfs_fh4 fh;
The call to gettype("nfs_fh4") will returned the basic type
"opaque" and its array definition:
("opaque", [["", "<NFS4_FHSIZE>"]])
"""
ret = []
while usetypedef:
item = self.dtypedef.get(dtype)
if item is None:
break
dtype = item[0]
if item[1] is not None or item[2] is not None:
ret.append(item[1:])
if dtype == "bool":
dtype = "nfs_bool"
return (dtype, ret)
def getsize(self, adef):
"""Return the size definition for an opaque or array
adef:
Array definition
"""
size = ""
if adef is not None and adef[0] in ["[", "<"]:
regex = re.search(r"[\.\w]+", adef)
if regex:
size = regex.group(0)
if self.dconstants.get(size) is not None:
# Size is given as a constant name
size = "const." + size
return size
def getunpack(self, dname, alist, compound=False, typedef=False):
"""Return the correct decoding statement for given var definition
dname:
Variable definition, e.g., opaque, string, int, etc.
alist:
Variable definition modifier: array [opaque def, array def] where
the first item is the opaque modifier (<>, [], <32>, [12], etc.)
and the second item is the array modifier (<>, [], etc.) for the
case where dname is an array of opaques
compound:
True if decoding a compound, e.g. array or list
typedef:
True if output is for a typedef, e.g.,
For dname="int"
typedef=False, output:unpack.unpack_int()
typedef=True, output:Unpack.unpack_int
"""
ret = ("", "", "")
if compound or typedef:
# Use class method
ustr = "Unpack"
else:
# Use unpack object
ustr = "unpack"
if dname in int32_list:
ret = ("%s.unpack_int" % ustr, "()", "")
elif dname in uint32_list:
ret = ("%s.unpack_uint" % ustr, "()", "")
elif dname in int64_list:
ret = ("%s.unpack_int64" % ustr, "()", "")
elif dname in uint64_list:
ret = ("%s.unpack_uint64" % ustr, "()", "")
elif dname in string_list:
if alist and alist[0][0] in ["[", "<"]:
# Opaque
fstr = ""
if alist[0][0] == "[":
fstr = "f"
if dname in utf8_list:
fstr += "utf8"
else:
fstr += "opaque"
size = self.getsize(alist[0])
if typedef and len(size):
ustr = "lambda unpack: unpack"
ltstr = ""
if len(alist) > 1:
asize = self.getsize(alist[1])
if asize is not None:
# Size for each member of an array
ltstr = ", %s" % asize
ret = ("%s.unpack_%s" % (ustr, fstr), "(%s)" % size, '%s, args={"size":%s}' % (ltstr, size))
else:
ret = ("%s.unpack_opaque" % ustr, "()", "")
elif typedef:
if alist and len(alist[0]) >= 2 and alist[0][0] in ["[", "<"]:
size = self.getsize(alist[0])
fixed = (alist[0][0] == "[")
sstr = ""
if len(size):
if fixed:
sstr = ", %s" % size
else:
sstr = ", maxcount=%s" % size
dname = "lambda unpack: unpack.unpack_array(%s%s)" % (dname, sstr)
if dname == "bool":
dname = "nfs_bool"
ret = (dname, "", "")
elif not compound and dname[:7].lower() == "unpack.":
dname = dname[:7].lower() + dname[7:]
ret = (dname, "()", "")
elif dname[-1] == ")":
ret = (dname, "", "")
else:
ret = (dname, "(unpack)", "")
if compound:
return ret[0] + ret[2]
elif typedef:
if ustr == "Unpack":
return ret[0]
else:
return ret[0] + ret[1]
else:
return ret[0] + ret[1]
def fix_comments(self, item_list, commsidx):
"""Remove old comment if the previous multi-line comment
is the same in order to avoid displaying the comment twice
item_list:
List of items
commsidx:
Index of comment in each item in item_list
"""
save_comm = []
for item in item_list:
comms = item[commsidx]
# Compare previous multi-line commnet against current old comment
# removing the multi-line comment marker from the old comment
old_comment = comms[2]
if len(old_comment) > 1 and old_comment[-1] == "":
old_comment = comms[2][:-1]
if save_comm == old_comment:
comms[2] = []
save_comm = comms[1]
def rm_multi_blanks(self, alist):
"""Remove multiple blank lines in given list of comments"""
index = 0
mlist = []
isblank = False
for item in alist:
if len(item) == 0:
if isblank:
mlist.append(index)
isblank = True
else:
isblank = False
index += 1
for index in reversed(mlist):
alist.pop(index)
return
def get_comments(self, comm_list, strline, spnam, sppre, ctype=False, newobj=False):
"""Returns a tuple of two comments to display, the first one is
the main comment to be displayed before the python code and
the second comment is the inline comment.
comm_list:
List of comments: (inline, multi, old)
strline:
Python code to be displayed. This is used for formatting the
multi-line comments going as inline comments
spnam:
Extra spaces to match the longest variable name to line up
inline comments, e.g., extra spaces are added after "id;"
int id; /* comment 1 */
data buffer; /* comment 2 */
sppre:
Extra spaces added to beginning of main comment to line up
to the start of python code
ctype:
Comment type to output. If True, this is a C-language comment
else it is a python comment
newobj:
This is a new object so add an extra new line at the beginning
"""
incommstr = ""
scomm_list = []
inlinecomm,multicomm,oldcomm = comm_list
if ctype:
csign_str = "/*"
csign_end = " */"
cmult_str = "/*"
cmult_end = " */"
else:
csign_str = "#"
csign_end = ""
cmult_str = "#"
cmult_end = ""
if len(oldcomm):
if ctype and len(oldcomm) > 1:
scomm_list.append("%s%s\n" % (sppre, csign_str))
cmult_str = " *"
cmult_end = ""
if len(oldcomm[0]) == 0:
oldcomm.pop(0) # Discard multi-line comment marker
if len(oldcomm) and len(oldcomm[-1]) == 0:
oldcomm.pop() # Discard space-before-comment marker
if not ctype:
scomm_list.insert(0, "\n")
# Remove multiple blank lines
self.rm_multi_blanks(multicomm)
self.rm_multi_blanks(oldcomm)
for mline in oldcomm:
sps = " "
if len(mline) == 0:
sps = ""
scomm_list.append("%s%s%s%s%s\n" % (sppre, cmult_str, sps, mline, cmult_end))
if len(oldcomm) and ctype and cmult_end == "":
scomm_list.append("%s%s\n" % (sppre, csign_end))
if newobj and scomm_list and scomm_list[0] != "\n":
scomm_list.insert(0, "\n")
if len(multicomm):
sps = ""
commlist = []
for mline in multicomm:
commlist.append("%s%s %s %s%s" % (sps, spnam, csign_str, mline, csign_end))
if len(sps) == 0:
sps = " " * len(strline)
incommstr = "\n".join(commlist)
elif len(inlinecomm):
incommstr = "%s %s %s%s" % (spnam, csign_str, inlinecomm, csign_end)
return ("".join(scomm_list), incommstr)
def process_comments(self, line):
"""Process comments for the given line from the XDR definition file"""
line = line.rstrip()
self.inline_comment = ""
# Process tags
regex = True
while regex:
regex = re.search(r"/\*\s*(\w+)\s*:\s*(.+)\*/", line)
if regex:
tag, tdata = regex.groups()
tag.strip()
if valid_tags.get(tag):
self.tags[tag] = tdata.strip()
# Do not include tags as comments
line = re.sub(r"/\*\s*(\w+)\s*:\s*(.+)\*/", "", line)
else:
# No valid tag was found
regex = None
# Process in-line comments
regex = re.search(r"/\*\s*(.*)\s*\*/", line)
if regex:
# Save in-line comment
self.inline_comment = regex.group(1).strip()
line = re.sub(r"/\*.*\*/", "", line)
self.multi_comment = []
if re.search(r"^\s*$", line):
# Empty line
if len(self.inline_comment):
self.old_comment += [self.inline_comment]
if self.blank_lines and len(self.old_comment) and len(self.old_comment[0]):
# Add multi-line comment marker
self.old_comment.insert(0, "")
self.inline_comment = ""
self.blank_lines = 0
self.is_comment = True
# Skip empty lines
self.blank_lines += 1
if self.incomment:
self.multi_comment.append("")
return ""
if self.incomment:
if not self.is_comment:
self.old_comment = []
if re.search(r"\*/", line):
# End of multi-line comment
if self.copyright is None or self.description is None:
out = "\n".join(self.multi_comment)
if re.search(r"(Copyright .*\d\d\d\d|__DESCRIPTION__)", out):
# Ignore any copyright and description comments in XDR file
if "__DESCRIPTION__" in self.multi_comment:
while self.multi_comment.pop(0) != "__DESCRIPTION__":
pass
d_list = ['"""']
while len(self.multi_comment) > 0:
dline = self.multi_comment.pop(0)
if dline == "__CONST__":
# The description of the decoding module
# ends on the start of the description for
# the constants module given by the
# __CONST__ marker
break
d_list.append(dline)
# Add description to decoding moule
while d_list[-1] == "":
d_list.pop()
if len(d_list) > 1:
self.description = "\n".join(d_list) + '\n"""\n'
# Add description to constants moule
d_list = ['"""'] + self.multi_comment
while d_list[-1] == "":
d_list.pop()
if len(d_list) > 1:
self.desc_const = "\n".join(d_list) + '\n"""\n'
self.multi_comment = []
self.old_comment = []
line = re.sub(r"\*/.*", "", line)
self.incomment = False
self.is_comment = True
regex = re.search(r"^\s*\*?\s?(.*)\s*(\*/)?", line)
if regex and len(regex.group(1)):
self.multi_comment.append(regex.group(1))
elif re.search(r"^\s\*$", line):
self.multi_comment.append("")
if not self.incomment:
# Reset multi-line comment list and add
# space-before-comment marker (blank line at the end)
self.old_comment += self.multi_comment + [""]
self.multi_comment = []
self.blank_lines = 0
return ""
else:
regex = re.search(r"(.*)/\*\s?(.*)", line)
if regex:
# Start of multi-line comment
comm = regex.group(2)
if re.search(r"^\s*$", comm):
self.multi_comment = []
else:
self.multi_comment = [regex.group(2)]
if self.blank_lines:
# Add multi-line comment marker
self.multi_comment.insert(0, "")
line = regex.group(1).strip()
self.incomment = True
self.blank_lines = 0
if not self.incomment:
self.is_comment = False
return line.rstrip()
def process_def(self, line):
"""Process a single line for any of the following definition types:
struct, union, enum and bitmap
"""
deftype = None
defname = None
deftags = {}
defcomments = []
regex = re.search(r"^\s*(struct|union|enum|bitmap)\s+(\w+)(\s+switch\s*\(" + vardefstr + r"\s*\))?", line)
if regex:
data = regex.groups()
defname = data[1]
deftype = deftypemap.get(data[0])
if deftype == UNION:
# Add discriminant to list of definitions
comms = [self.inline_comment, self.multi_comment, []]
self.item_dlist.append([data[7], data[3], data[6], data[8], [], {}, comms, []])
if deftype is not None:
defcomments = [self.inline_comment, self.multi_comment, self.old_comment]
self.inline_comment = ""
self.multi_comment = []
self.old_comment = []
deftags = self.tags
self.tags = {}
return (deftype, defname, deftags, defcomments)
def set_vars(self, fd, tags, dnames, indent, pre=False, post=False, vname=None, noop=False):
"""Set GLOBAL variables
fd:
File descriptor for output file
tags:
Tags dictionary for given object
dnames:
List of attribute definition names in object.
If the value of the global to be defined exists in this list
then "self." is added to the value. If it does not exist the
value is literal
indent:
Space indentation
pre:
Global variable is defined before any other attributes
post:
Global variable is defined after all other attributes
vname:
Set global variable for the given name only
noop:
No operation, do not write the global definition to the file
just return the length of the global definition. This is used
to find if an arm of a discriminated union should be created
in case its body is "void", but if there is a global to be set
then it should be created.
"""
out = ""
tag = "GLOBAL"
globalvars = tags.get(tag)
if globalvars is not None:
for item in globalvars.split(","):
data = item.split("=")
if len(data) == 2:
name,var = data
else:
continue
if vname is not None and vname != var:
continue
if pre:
# If global is set before any other attributes are set
# then it should not be in the dnames list
if var not in dnames:
out += '%sself.set_%s("%s", %s)\n' % (indent, tag.lower(), name, var)
else:
if var in dnames:
out += '%sself.set_%s("%s", self.%s)\n' % (indent, tag.lower(), name, var)
elif not post:
# Only if post is not specified, this is to avoid
# duplicates when the same global is processed with
# pre as well
out += '%sself.set_%s("%s", %s)\n' % (indent, tag.lower(), name, var)
if not noop and len(out) > 0:
fd.write(out)
return len(out)
def set_objattr(self, fd, deftags, dnames, indent, maxlen=0, namesonly=False):
"""Process the OBJATTR tag and add the attribute initialization
to the output file.
fd:
File descriptor for output file
deftags:
Tags dictionary for given object
dnames:
List of attribute definition names in object.
If the value of the attribute to be defined exists in this list
then "self." is added to the value. If it does not exist the
value is literal
indent:
Space indentation
maxlen:
Length of longest attribute name in the class to be defined.
This is used to align all attribute definitions in the class
namesonly:
Return only the list of names to be added, but do not write
the attributes to the output file. This is used to include
these names when calculating maxlen.
"""
attrs = []
nlist = []
vdnames = deftags.get("OBJATTR")
if vdnames is not None:
for vardup in vdnames.split(","):
newname, oldname = vardup.split("=")
data = newname.split(";")
newname = data[0]
nlist.append(newname)
if len(data) > 1 and data[1] == "disp":
attrs.append(newname)
if not namesonly:
sps = ""
if maxlen > 0:
sps = " " * (maxlen - len(newname))
if oldname in dnames:
# Value in attribute to be set is an attribute
# in the class
fd.write("%sself.%s %s= self.%s\n" % (indent, newname, sps, oldname))
else:
# Literal value
fd.write("%sself.%s %s= %s\n" % (indent, newname, sps, oldname))
return nlist, attrs
def get_strfmt(self, level, deftags):
"""Process the STRFMT1 and STRFMT2 tags and return the string
representation of class attribute _strfmt
deftags:
Tags dictionary for given object
"""
out = []
fmt = "STRFMT" + str(level)
strfmt = deftags.get(fmt)
if strfmt is not None:
if strfmt in empty_quotes:
strfmt = ""
return '"%s"' % strfmt
def set_strfmt(self, fd, deftags, indent):
"""Process the STRFMT1 and STRFMT2 tags and write the set_strfmt
calls to the output file
fd:
File descriptor for output file
deftags:
Tags dictionary for given object
indent:
Space indentation
"""
index = 1
for fmt in ("STRFMT1", "STRFMT2"):
strfmt = deftags.get(fmt)
if strfmt is not None:
if strfmt in empty_quotes:
strfmt = ""
fd.write('%sself.set_strfmt(%d, "%s")\n' % (indent, index, strfmt))
index += 1
def process_fopaque(self):
"""Process FOPAQUE tag"""
index = 0
for item in self.item_dlist:
vname,dname,pdef,adef,clist,tag,comms,pcomms = item
tagval = tag.get("FOPAQUE")
if tagval is not None and dname == "opaque":
self.item_dlist.pop(index)
self.item_dlist.insert(index, [tagval,"unsigned int","","",clist,{},comms,pcomms])
self.item_dlist.insert(index+1, [vname,dname,pdef,"[self.%s]"%tagval,[],{},[],[]])
index += 1
def process_linkedlist(self, defname):
"""Process linked list. If any definition name in the attribute
list is the same as the definition name of struct given,
then this is a linked list and the attribute that matches
is removed from the list.
defname:
Definition name for struct
"""
index = 0
for item in self.item_dlist:
if item[1] == defname:
# This is a linked list
if len(self.item_dlist) == 2:
# There is only one attribute (other than *next)
# so convert it to a list of this attribute type
# instead of a list of this struct
self.linkedlist[defname] = self.item_dlist[0][1]
else:
self.linkedlist[defname] = defname
self.item_dlist.pop(index)
break
index += 1
def process_bitlist(self):
"""Process BITLIST tag"""
index = 0
for item in self.item_dlist:
vname,dname,pdef,adef,clist,tag,comms,pcomms = item
tagval = tag.get("BITLIST")
if tagval is not None:
itemlist = tagval.split("=")
fnvalue = "bitmap_info(unpack, self.%s, %s)" % (item[0], itemlist[1])
self.item_dlist.insert(index+1, [itemlist[0], fnvalue, "","",[],{},[],[]])
index += 1
def process_bitdict(self, defname, deftags):
"""Process the BITDICT tag
defname:
Definition name for struct
deftags:
Tags dictionary for given object
"""
isbitdict = False
if deftags.get("BITDICT"):
# Process BITDICT
if len(self.item_dlist) == 2:
vname_mask,dname,pdef,adef,clist,tag,comms,pcomms = self.item_dlist[0]
expr = (dname in self.bitmap_defs)
dname,opts = self.gettype(dname)
if (dname in uint32_list and adef == "<>") or expr:
vname,dname,pdef,adef,clist,tag,comms,pcomms = self.item_dlist[1]
if dname == "opaque" and adef == "<>":
# Defined directly as a variable length opaque
isbitdict = True
else:
dname,opts = self.gettype(dname)
if dname == "opaque" and opts[0][1] == "<>":
# Defined indirectly as a variable length opaque
isbitdict = True
if not isbitdict:
raise Exception("BITDICT tag is used incorrectly in definition for '%s'" % defname)
return isbitdict
def process_classattr(self, deftags):
"""Process the CLASSATTR tag
deftags:
Tags dictionary for given object
"""
attrs = []
classattr = []
cattrs = deftags.get("CLASSATTR")
if cattrs is not None:
for cattr in cattrs.split(","):
attr, value = cattr.split("=")
data = attr.split(";")
classattr.append([data[0], value])
if len(data) > 1 and data[1] == "disp":
attrs.append(data[0])
return classattr, attrs
def process_fwrap(self, deftags, vname, bclass_names, astr):
"""Process the FWRAP tag"""
fwrap = deftags.get("FWRAP")
if fwrap is not None:
# Process multiple FWRAP definitions
itemlist = fwrap.split(",")
for item in itemlist:
# Get attribute name and function wrapper
fname,fvalue = item.split("=")
if fname == vname:
# Change the first segment of wrapper to "self" when it is
# specified as BaseClass.method (change to self.method)
ddlist = fvalue.split(".")
if ddlist and ddlist[0] in bclass_names:
ddlist[0] = "self"
fvalue = ".".join(ddlist)
# Get current function definition and its arguments
regex = re.search(r"(.*)\((.*)\)", astr)
if regex:
method,args = regex.groups()
# Convert arguments string to a list of arguments
ddlist = [x for x in map(str.strip, args.split(",")) if len(x)]
# Original function is now the first argument to
# the wrapper
ddlist.insert(0, method)
astr = "%s(%s)" % (fvalue, ", ".join(ddlist))
return astr
def set_copyright(self, fd):
"""Write copyright information"""
if self.copyright is not None:
copyright = copyright_str.lstrip().replace("__COPYRIGHT__", self.copyright)
fd.write(copyright)
def set_modconst(self, fd):
"""Write module constants"""
if self.modversion is not None:
if self.copyright:
year = self.copyright
else:
year = time.strftime("%Y", time.localtime())
modconst = modconst_str.replace("__COPYRIGHT__", year)
modconst = modconst.replace("__VERSION__", self.modversion)
fd.write(modconst)
def set_original_definition(self, fd, deftype, defname):
"""Write original XDR definition to the output file
fd:
File descriptor for output file
deftype:
Definition type: either a STRUCT or UNION
defname:
Definition name for struct/union
"""
fd.write(' """\n')
sppre = " " * 11
if deftype == STRUCT:
#===========================================================
# Write original definition of STRUCT
#===========================================================
fd.write(" struct %s {\n" % defname)
if self.item_dlist:
maxlennam = len(max([x[0]+x[2]+x[3] for x in self.item_dlist], key=len))
maxlendef = len(max([x[1] for x in self.item_dlist], key=len))
self.fix_comments(self.item_dlist, 6)
for item in self.item_dlist:
vname,dname,pdef,adef,clist,tag,comms,pcomms = item
spdef = " " * (maxlendef - len(dname))
spnam = " " * (maxlennam - len(vname+pdef+adef))
out = "%s%s%s %s%s%s;" % (sppre, dname, spdef, pdef, vname, adef)
mcommstr, incommstr = self.get_comments(comms, out, spnam, sppre, True)
if len(mcommstr):
fd.write(mcommstr)
fd.write("%s%s\n" % (out, incommstr))
else:
#===========================================================
# Write original definition of UNION
#===========================================================
item = self.item_dlist[0]
fd.write(" union switch %s (%s %s) {\n" % (defname, item[1], item[0]))
if self.item_dlist:
sppre_case = sppre + " "
maxlen1 = len(max([y[0] for y in [x[4][0] for x in self.item_dlist[1:]]], key=len))
maxlen2 = len(max([x[0]+x[1] for x in self.item_dlist[1:]], key=len))
maxlen = max(maxlen1+3, maxlen2+4)
for item in self.item_dlist[1:]:
vname,dname,pdef,adef,clist,tag,comms,pcomms = item
for citem in clist:
if citem[0] == "default":
if dname != "void":
# The default case does not have "void",
# so all cases must have an "elif"
# statement even if returning void
valid_default = True
out = "%sdefault:" % sppre
spnam = " " * (maxlen - 8)
else:
out = "%scase %s:" % (sppre, citem[0])
spnam = " " * (maxlen - len(citem[0]) - 5)
mcommstr, incommstr = self.get_comments(citem[1], out, spnam, sppre, True)
if len(mcommstr):
fd.write(mcommstr)
fd.write("%s%s\n" % (out, incommstr))
if dname == "void":
out = "%svoid;" % sppre_case
spnam = " " * (maxlen - len(vname) - len(dname) - 4)
else:
out = "%s%s %s%s%s;" % (sppre_case, dname, pdef, vname, adef)
spnam = " " * (maxlen - len(vname) - len(dname) - 5)
mcommstr, incommstr = self.get_comments(item[6], out, spnam, sppre_case, True)
if len(mcommstr):
fd.write(mcommstr)
fd.write("%s%s\n" % (out, incommstr))
fd.write(' };\n')
fd.write(' """\n')
def process_union_var(self, line):
"""Process variable definition on a union"""
regex = re.search(r"^\s*void;", line)
if regex:
comms = [self.inline_comment, self.multi_comment, self.old_comment]
self.item_dlist.append(["", "void", "", "", self.case_list, self.tags, comms, []])
else:
regex = re.search(vardefstr, line)
dname,atmp,btmp,pdef,vname,adef,tmp = regex.groups()
comms = [self.inline_comment, self.multi_comment, self.old_comment]
self.item_dlist.append([vname, dname, pdef, adef, self.case_list, self.tags, comms, []])
self.old_comment = []
self.case_list = []
self.tags = {}
def process_struct_union(self, fd, deftype, defname, deftags, defcomments):
"""Process a struct or a union
fd:
File descriptor for output file
deftype:
Definition type: either a STRUCT or UNION
defname:
Definition name for struct/union
deftags:
Tags dictionary for given object
defcomments:
List of comments: (inline, multi, old)
"""
prefix = "self."
valid_default = False
bclass_names = []
isbitdict = self.process_bitdict(defname, deftags)
mcommstr, incommstr = self.get_comments(defcomments, "", "", "", newobj=True)
if len(mcommstr):
fd.write(mcommstr)
else:
fd.write("\n")
if isbitdict:
fd.write("def %s(unpack):%s\n" % (defname, incommstr))
else:
# Get base classes if they exist, default is BaseObj
inherit = deftags.get("INHERIT", "BaseObj")
bclass_names = [x.strip().split(".").pop() for x in inherit.split(",")]
fd.write("class %s(%s):%s\n" % (defname, ", ".join(bclass_names), incommstr))
self.set_original_definition(fd, deftype, defname)
self.process_fopaque()
self.process_bitlist()
self.process_linkedlist(defname)
dnames = [x[0] for x in self.item_dlist]
# Process the XARG tag
extra_args = ""
xarg_list = []
tagstr = deftags.get("XARG")
if tagstr is not None:
xarg_list = re.findall(r"([\w\d_]+)\s*;?\s*(\w+)?", tagstr)
if len(xarg_list):
extra_args = ", " + ", ".join(x[0] for x in xarg_list)
# Split attributes given in XARG tag into the ones that will be
# displayed (disp flag, added to _attrlist) and those that won't
xarg_set_names = []
xarg_nodisp_names = []
if len(xarg_list):
for xarg in xarg_list:
if xarg[1] == "disp":
xarg_set_names.append(xarg[0])
else:
xarg_nodisp_names.append(xarg[0])
# Process the OBJATTR tag to get a list of names to include into
# the calculation for maxlen. Also add attributes with the ";disp"
# modifier to the attribute list
oattrlist, attr_list = self.set_objattr(fd, deftags, dnames, "", namesonly=True)
if not isbitdict:
# Process CLASSATTR
classattr, attrlist = self.process_classattr(deftags)
dnames = attrlist + dnames
dnames += attr_list
# Process _fattrs
out = []
for item in self.item_dlist:
vname,dname,pdef,adef,clist,tag,comms,pcomms = item
if tag.get("FLATATTR"):
out.append(vname)
if len(out):
cstr = ""
if len(out) == 1:
cstr = ","
classattr.append(["_fattrs", "(%s%s)" % (", ".join(['"%s"'%x for x in out]),cstr)])
# Process _eqattr
eqattr = deftags.get("EQATTR")
if eqattr is not None:
classattr.append(["_eqattr", '"%s"'%eqattr])
# Process _strfmt1 and _strfmt2
for level in (1,2):
strfmt = self.get_strfmt(level, deftags)
if strfmt is not None:
classattr.append(["_strfmt"+str(level), strfmt])
# Process _attrlist
if deftype == STRUCT:
cstr = ""
if len(dnames+xarg_set_names) == 1:
cstr = ","
classattr.append(["_attrlist", "(%s%s)" % (", ".join(['"%s"'%x for x in dnames+xarg_set_names]), cstr)])
if len(classattr):
fd.write(" # Class attributes\n")
mlen = len(max([x[0] for x in classattr], key=len))
for item in classattr:
sps = " " * (mlen - len(item[0]))
if item[0] in ("_attrlist"):
# Wrap list into multiple lines
lines = textwrap.wrap(item[1], 73-mlen)
fd.write(" %s%s =" % (item[0], sps))
xsps = 1
for line in lines:
fd.write("%s%s\n" % (" "*xsps, line))
xsps = mlen+8
else:
fd.write(" %s%s = %s\n" % (item[0], sps, item[1]))
fd.write("\n")
#===========================================================
# Create python definition of STRUCT/UNION
#===========================================================
if isbitdict:
nindent = 4
bitdict = deftags.get("BITDICT")
fd.write(" bitmap = bitmap4(unpack)\n")
fd.write(" return bitmap_info(unpack, bitmap, %s, %s_f)\n" % (bitdict, bitdict))
elif not self.item_dlist:
fd.write(" pass\n")
nindent = 4
else:
fd.write(" def __init__(self, unpack%s):\n" % extra_args)
nindent = 8
indent = " " * nindent
tindent = ""
istry = False
if deftags.get("TRY"):
# Process the TRY tag
fd.write("%stry:\n" % indent)
nindent = 4
tindent = " " * nindent
istry = True
# Get list of global names (not initialized)
global_list = []
globalvars = deftags.get("GLOBAL")
if globalvars is not None:
for item in globalvars.split(","):
data = item.split("=")
if len(data) == 1:
global_list.append(data[0])
omaxlen = 0
if oattrlist:
omaxlen = len(max(oattrlist, key=len))
if self.item_dlist:
maxlen = len(max([x[0] for x in self.item_dlist]+xarg_set_names+xarg_nodisp_names+oattrlist, key=len))
if deftype == STRUCT:
self.set_vars(fd, deftags, dnames, indent+tindent, pre=True)
if deftype == UNION and (xarg_set_names or xarg_nodisp_names):
mlen = len(max(xarg_set_names+xarg_nodisp_names, key=len))
else:
mlen = maxlen
for name in xarg_nodisp_names:
# This is an XARG variable
sps = " " * (mlen - len(name))
valname = name
for item in self.item_dlist:
vname,dname,pdef,adef,clist,tag,comms,pcomms = item
if name == vname:
valname = "%s(%s)" % (dname, name)
break
fd.write("%s%sself.%s%s = %s\n" % (indent, tindent, name, sps, valname))
if deftype == UNION:
self.set_vars(fd, deftags, dnames, indent+tindent, pre=True)
for name in xarg_set_names:
# This is an XARG variable with "disp" option
sps = " " * (mlen - len(name))
valname = name
for item in self.item_dlist:
vname,dname,pdef,adef,clist,tag,comms,pcomms = item
if name == vname:
valname = "%s(%s)" % (dname, name)
break
fd.write('%s%sself.set_attr("%s", %s%s)\n' % (indent, tindent, name, sps, valname))
#===========================================================
# Create python definition of STRUCT/UNION for all vars
#===========================================================
switch_cond = "if"
switch_var = None
if isbitdict:
dlist = []
else:
dlist = self.item_dlist
for item in dlist:
# Start of for loop {
cindent = ""
vname,dname,pdef,adef,clist,tag,comms,pcomms = item
if dname == defname:
# This is a linked list
continue
if deftype == UNION:
sps = ""
swstr = ", switch=True"
else:
sps = " " * (maxlen - len(vname))
swstr = ""
if switch_var is None:
swstr = "" # Don't use True argument for switch variable
switch_var = vname
if vname in xarg_set_names+xarg_nodisp_names:
continue
if vname in global_list:
# This is a global reference
continue
# Use option usetypedef to return the same definition name except
# for names that need to be renamed like "bool" -> "nfs_bool"
dname,opts = self.gettype(dname, usetypedef=False)
# Ignore opts from gettype() and just use the array def "adef"
alist = list(filter(None, [adef]))
isarray = False
if len(alist) > 1 or (len(alist) == 1 and dname not in string_list):
# This is an array
isarray = True
need_if = self.set_vars(fd, tag, dnames, "", noop=True)
need_if_fmt = False
if tag.get("STRFMT1") is not None or tag.get("STRFMT2") is not None:
need_if_fmt = True
if len(clist) and (valid_default or need_if or need_if_fmt or dname != "void"):
if len(clist) == 1:
if clist[0][0] == "default":
fd.write("%s%selse:\n" % (indent, tindent))
else:
fd.write("%s%s%s %s%s == %s:\n" % (indent, tindent, switch_cond, prefix, switch_var, clist[0][0]))
else:
c_list = [x[0] for x in clist]
fd.write("%s%s%s %s%s in [%s]:\n" % (indent, tindent, switch_cond, prefix, switch_var, ", ".join(c_list)))
cindent = " " * 4
switch_cond = "elif"
# Get the correct decoding statement for given var definition
astr = self.getunpack(dname, alist, compound=isarray)
for comm in pcomms:
fd.write("%s%s%s# %s\n" % (indent, tindent, cindent, comm))
# Initial set_attr string
if deftype == STRUCT:
setattr_str = "%s%s%sself.%s%s = " % (tindent, cindent, indent, vname, sps)
else:
setattr_str = '%s%s%sself.set_attr("%s", %s' % (tindent, cindent, indent, vname, sps)
swstr += ")"
if pdef == "*" and not self.linkedlist.get(dname):
# Conditional: has a pointer definition "*" but it is not a linked list
astr = "unpack.unpack_conditional(%s)" % dname
elif self.linkedlist.get(dname) and pdef == "*":
# Pointer to a linked list
astr = "unpack.unpack_list(%s)" % self.linkedlist.get(dname)
elif isarray:
cond = False
if len(adef):
regex = re.search(r"(.)(\d*)", adef)
if regex:
data = regex.groups()
if data[0] == "[":
# Fixed length array
astr += ", %s" % data[1]
elif data[0] == "<" and len(data[1]):
if data[1] == "1":
# Treat this not as an array with maxcount=1, but a conditional
cond = True
else:
# Variable length array
astr += ", maxcount=%s" % data[1]
if cond:
astr = "unpack.unpack_conditional(%s)" % astr
else:
astr = "unpack.unpack_array(%s)" % astr
elif dname[:7] == "Unpack.":
astr = "unpack.%s()" % dname[7:]
elif dname == "void":
astr = ""
swstr = ""
setattr_str = ""
if need_if:
self.set_vars(fd, tag, dnames, indent+tindent+cindent)
elif need_if_fmt:
pass
elif valid_default:
astr = "%s%s%spass;" % (indent, tindent, cindent)
if len(astr):
# Process FWRAP tag
astr = self.process_fwrap(deftags, vname, bclass_names, astr)
if tag.get("STRHEX"):
# This definition has a STRHEX tag -- display object in hex
d_name,d_opts = self.gettype(dname)
if d_name in int32_list + uint32_list:
objtype = "IntHex"
elif d_name in int64_list + uint64_list:
objtype = "LongHex"
else:
objtype = "StrHex"
astr = "%s(%s)" % (objtype, astr)
# Write the attribute definition to the file
fd.write("%s%s%s\n" % (setattr_str, astr, swstr))
self.set_vars(fd, deftags, dnames, indent+tindent, post=True, vname=vname)
self.set_objattr(fd, tag, dnames, indent+tindent+cindent)
self.set_strfmt(fd, tag, indent+tindent+cindent)
# End of for loop }
if deftype == UNION:
maxlen = omaxlen
self.set_objattr(fd, deftags, dnames, indent+tindent, maxlen=maxlen)
if deftags.get("TRY"):
# End try block
fd.write("%sexcept:\n" % indent)
fd.write("%s%spass\n" % (indent, tindent))
def process_enum_and_const(self):
"""Process enum and constants"""
buffer = ""
deftype = None
defname = None
tagcomm = None
enumlist = []
constlist = []
self.tags = {}
self.copyright = None
self.modversion = None
self.incomment = False
self.description = None
self.desc_const = None
for line in self.xdr_lines:
line = self.process_comments(line)
if tagcomm is None:
tagcomm = self.tags.pop("COMMENT", None)
if len(line) == 0:
if deftype in [ENUM, BITMAP] and self.inline_comment is not None and len(self.inline_comment):
# Save comment
comms = [self.inline_comment, self.multi_comment, self.old_comment]
enumlist.append(["", "", comms])
self.old_comment = []
# Skip empty lines
continue
if deftype is None:
deftype, defname, deftags, defcomments = self.process_def(line)
inherit = deftags.get("INHERIT")
if inherit and len(inherit) > 1:
# Save inherit class names
for bclass in [x.strip() for x in inherit.split(",")]:
self.inherit_names[bclass] = 1
copyright = deftags.get("COPYRIGHT")
if copyright is not None:
self.copyright = copyright
modversion = deftags.get("VERSION")
if modversion is not None:
self.modversion = modversion
if deftype is None:
regex = re.search(r"^\s*const\s+(\w+)(\s*)=(\s*)(\w+)", line)
if regex:
# Constants
const,sp1,sp2,value = regex.groups()
self.dconstants[const] = value
comms = [self.inline_comment, self.multi_comment, self.old_comment]
constlist.append([const, value, comms])
self.old_comment = []
else:
regex = re.search(r"^\s*typedef\s" + vardefstr, line)
if regex:
# Typedef
data = regex.groups()
self.dtypedef[data[4]] = [data[0], data[3], data[5]]
self.old_comment = []
elif deftype in [ENUM, BITMAP]:
enumlist = []
# Add to list of enum definitions
self.enumdef_list.append(defname)
if deftype is not None and len(constlist):
self.enum_data.append({"deftype":CONSTANT, "defname":None, "deftags":deftags, "defcomm":tagcomm, "enumlist":constlist})
self.old_comment = []
tagcomm = None
elif re.search(r"^\s*};", line):
# End of definition
if deftype in [ENUM, BITMAP]:
self.enum_data.append({"deftype":deftype, "defname":defname, "deftags":deftags, "defcomm":tagcomm, "enumlist":enumlist})
tagcomm = None
deftype = None
constlist = []
self.old_comment = []
elif deftype in [ENUM, BITMAP]:
regex = re.search(r"^\s*([\w\-]+)\s*=\s*([^,;\s]+),?.*", line)
ename = regex.group(1).strip()
evalue = regex.group(2).strip()
comms = [self.inline_comment, self.multi_comment, self.old_comment]
enumlist.append([ename, evalue, comms])
self.old_comment = []
if deftype == ENUM:
self.dconstants[ename] = evalue
# Save enum and constants to *_const.py file
if self.enum_data:
print(" Creating file %s" % self.cfile)
fd = open(self.cfile, "w")
self.set_copyright(fd)
fd.write(self.genstr)
if self.desc_const:
fd.write(self.desc_const)
else:
sname = re.sub(r"(\d)", r"v\1", self.bname.upper())
fd.write('"""\n%s constants module\n"""\n' % sname)
if self.modversion is not None:
fd.write("import nfstest_config as c\n")
self.set_modconst(fd)
# Save enums
for enum_item in self.enum_data:
deftype = enum_item["deftype"]
defname = enum_item["defname"]
deftags = enum_item["deftags"]
defcomm = enum_item["defcomm"]
enumlist = enum_item["enumlist"]
if defname is not None and deftags.get("FMAP"):
self.fmap_data[defname] = enum_item
if defname == "bool":
# Rename "bool" definition
defname = "nfs_bool"
if defcomm is not None:
fd.write("\n# %s\n" % defcomm)
name_maxlen = len(max([x[0] for x in enumlist], key=len))
value_maxlen = len(max([x[1] for x in enumlist], key=len))
self.fix_comments(enumlist, 2)
if deftype == ENUM:
fd.write("\n# Enum %s\n" % defname)
# Save enums constant definitions
for item in enumlist:
out = ""
spnam = " " * (value_maxlen - len(item[1]))
if len(item[0]):
sps = " " * (name_maxlen - len(item[0]))
out = "%s%s = %s" % (item[0].replace("-", "_"), sps, item[1])
mcommstr, incommstr = self.get_comments(item[2], out, spnam, "")
if len(mcommstr):
fd.write(mcommstr)
fd.write("%s%s\n" % (out, incommstr))
# Save enums dictionary definition
fd.write("\n%s = {\n" % defname)
for item in enumlist:
if item[0] == "":
continue
sps = " " * (value_maxlen - len(item[1]))
fd.write(' %s%s : "%s",\n' % (sps, item[1], item[0]))
fd.write("}\n")
elif deftype == BITMAP:
# BITMAP
fd.write("\n# Bitmap %s\n" % defname)
fd.write("%s = {\n" % defname)
for item in enumlist:
sps = " " * (name_maxlen - len(item[0]))
fd.write(" %s%s : %s,\n" % (sps, item[0], item[1]))
fd.write("}\n")
elif deftype == CONSTANT:
# CONSTANT
first_item = True
for item in enumlist:
out = ""
spnam = " " * (value_maxlen - len(item[1]))
if len(item[0]):
sps = " " * (name_maxlen - len(item[0]))
out = "%s%s = %s" % (item[0], sps, item[1])
mcommstr, incommstr = self.get_comments(item[2], out, spnam, "")
if len(mcommstr):
fd.write(mcommstr)
elif first_item:
fd.write("\n")
fd.write("%s%s\n" % (out, incommstr))
first_item = False
fd.close()
def process_xdr(self):
"""Process XDR definitions"""
print(" Creating file %s" % self.pfile)
fd = open(self.pfile, "w")
self.set_copyright(fd)
fd.write(self.genstr)
if self.description:
fd.write(self.description)
else:
sname = re.sub(r"(\d)", r"v\1", self.bname.upper())
fd.write('"""\n%s decoding module\n"""\n' % sname)
import_dict = {
"packet.utils": ["*"],
"baseobj": ["BaseObj"],
"packet.unpack": ["Unpack"],
}
for inherit in self.inherit_names:
data = inherit.split(".")
objdef = data.pop()
objpath = ".".join(data)
if len(objpath) > 0:
if not import_dict.get(objpath):
import_dict[objpath] = []
import_dict[objpath].append(objdef)
if self.modversion is not None:
self.import_list.append("import nfstest_config as c\n")
if self.enum_data:
self.import_list.append("import %s%s_const as const\n" % (self.import_path, self.bname))
for objpath in import_dict:
import_str = "from %s import %s\n" % (objpath, ", ".join(import_dict[objpath]))
self.import_list.append(import_str)
for line in sorted(self.import_list, key=len):
fd.write(line)
self.set_modconst(fd)
self.item_dlist = []
self.linkedlist = {}
self.tags = {}
deftype = None
defname = None
deftags = {}
defcomments = []
need_newline = False
self.copyright = None
self.incomment = False
self.description = None
self.desc_const = None
for line in self.xdr_lines:
line = self.process_comments(line)
tagcomm = self.tags.pop("COMMENT", None)
if tagcomm is not None:
fd.write("\n# %s\n" % tagcomm)
continue
if len(line) == 0:
continue
if deftype is None:
deftype, defname, deftags, defcomments = self.process_def(line)
# Process CLASSATTR
classattr, attrlist = self.process_classattr(deftags)
if deftype is None:
regex = re.search(r"^\s*typedef\s" + vardefstr, line)
if regex:
# Typedef
data = regex.groups()
defcomments = [self.inline_comment, self.multi_comment, self.old_comment]
self.old_comment = []
self.typedef_list.append([data[4], data[0], data[5], self.tags, defcomments])
self.tags = {}
else:
# Constants
regex = re.search(r"^\s*const\s+(\w+)(\s*)=(\s*)(\w+)", line)
if regex:
self.old_comment = []
self.tags = {}
elif len(self.typedef_list):
maxlen = len(max([x[0] for x in self.typedef_list], key=len))
first_entry = True
for item in self.typedef_list:
mcommstr, incommstr = self.get_comments(item[4], "", "", "")
if need_newline and len(mcommstr) and mcommstr[0] != "\n":
fd.write("\n")
if len(mcommstr):
fd.write(mcommstr)
elif first_entry:
fd.write("\n")
first_entry = False
need_newline = False
func = ""
if item[3].get("BITMAP"):
# This typedef has a BITMAP tag -- use unpack_bitmap() to decode
self.bitmap_defs.append(item[0])
dname,opts = self.gettype(item[1])
if len(item[3]) == 1:
# This is the only tag
func = "Unpack.unpack_bitmap"
elif item[3].get("BITMAP"):
func = "unpack.unpack_bitmap"
if item[3].get("INHERIT"):
# Process the following: typedef baseclass newclass;
# Create class inheriting from the typdedef baseclass
# so the str version of the class has the name of
# the new class instead of the base class
fd.write("class %s(%s): pass\n" % (item[0], item[1]))
continue
elif item[3].get("BITMAPOBJ"):
func = "lambda unpack: Bitmap(unpack, %s)" % item[3]["BITMAPOBJ"]
elif item[3].get("STRHEX"):
# This typedef has a STRHEX tag -- display object in hex
if len(func) > 0:
# This item has a BITMAP tag as well
dname = func
item[2] = ""
else:
dname,opts = self.gettype(item[1])
if dname in int32_list + uint32_list:
objtype = "IntHex"
elif dname in int64_list + uint64_list + ["unpack.unpack_bitmap"]:
objtype = "LongHex"
else:
objtype = "StrHex"
astr = self.getunpack(dname, [item[2]])
func = "lambda unpack: %s(%s)" % (objtype, astr)
elif len(func) == 0:
func = self.getunpack(item[1], [item[2]], typedef=True)
sps = " " * (maxlen - len(item[0]))
fd.write("%s%s = %s%s\n" % (item[0], sps, func, incommstr))
self.typedef_list = []
if deftype == ENUM and defname is not None:
if defname == "bool":
# Rename "bool" definition
defname = "nfs_bool"
objdesc = ' """enum %s"""' % defname
out = "class %s(Enum):\n%s" % (defname, objdesc)
classattr.append(["_enumdict", "const.%s" % defname])
lmax = max([len(x[0]) for x in classattr])
for cattr in classattr:
out += "\n %-*s = %s" % (lmax, cattr[0], cattr[1])
mcommstr, incommstr = self.get_comments(defcomments, out, "", "", newobj=True)
if len(mcommstr):
fd.write(mcommstr)
else:
fd.write("\n")
fd.write("%s%s\n" % (out, incommstr))
need_newline = True
enum_item = self.fmap_data.get(defname)
if enum_item is not None:
# Process FMAP
deftype = enum_item["deftype"]
defname = enum_item["defname"]
deftags = enum_item["deftags"]
defcomm = enum_item["defcomm"]
enumlist = enum_item["enumlist"]
# Save enums dictionary definition
fd.write("\n%s_f = {\n" % defname)
value_maxlen = len(max([x[1] for x in enumlist], key=len))
for item in enumlist:
if item[0] == "":
continue
sps = " " * (value_maxlen - len(item[1]))
out = " %s%s : %s," % (sps, item[1], item[0].lower())
mcommstr, incommstr = self.get_comments(item[2], out, sps, " "+sps)
if len(mcommstr):
fd.write(mcommstr)
fd.write("%s%s\n" % (out, incommstr))
fd.write("}\n")
elif re.search(r"^\s*};", line):
# End of definition
if deftype in (STRUCT, UNION):
self.process_struct_union(fd, deftype, defname, deftags, defcomments)
# Reset all variables
deftype = None
self.reset_defvars()
elif deftype == UNION:
# Process all lines inside a union
regex = re.search(r"^\s*case\s+(\w+)\s*:\s*(.*)", line)
if regex:
# CASE line
case_val = regex.group(1).strip()
if self.dconstants.get(case_val) is not None:
case_val = "const." + case_val
comms = [self.inline_comment, self.multi_comment, self.old_comment]
self.case_list.append([case_val, comms])
self.old_comment = []
if len(regex.group(2)) > 0:
# Process in-line case
# case NFS4_OK: READ4resok resok4;
self.inline_comment = ""
self.multi_comment = []
self.process_union_var(regex.group(2))
else:
regex = re.search(r"^\s*default:", line)
if regex:
# DEFAULT line
comms = [self.inline_comment, self.multi_comment, self.old_comment]
self.case_list.append(["default", comms])
self.old_comment = []
else:
# Union variable
self.process_union_var(line)
elif deftype == STRUCT:
# Process all lines inside a structure
regex = re.search(vardefstr, line)
if regex:
data = regex.groups()
comms = [self.inline_comment, self.multi_comment, list(self.old_comment)]
self.item_dlist.append([data[4], data[0], data[3], data[5], [], self.tags, comms, []])
self.old_comment = []
self.tags = {}
fd.close()
#===============================================================================
# Entry point
#===============================================================================
# Setup options to parse in the command line
opts = OptionParser(USAGE, formatter = IndentedHelpFormatter(2, 25), version = "%prog " + __version__)
# Run parse_args to get options and process dependencies
vopts, args = opts.parse_args()
if len(args) < 1:
opts.error("XDR definition file is required")
for xdrfile in args:
print("Process XDR file %s" % xdrfile)
XDRobject(xdrfile)
|