summaryrefslogtreecommitdiff
path: root/trunks/generator/generator.py
blob: 990956acd05f4fe493710b8791d4536891f1ec0d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
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
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
#!/usr/bin/python2

#
# Copyright (C) 2014 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""A code generator for TPM 2.0 structures and commands.

The generator takes as input a structures file as emitted by the
extract_structures.sh script and a commands file as emitted by the
extract_commands.sh script.  It outputs valid C++ into tpm_generated.{h,cc}.

The input grammar is documented in the extract_* scripts. Sample input for
structures looks like this:
_BEGIN_TYPES
_OLD_TYPE UINT32
_NEW_TYPE TPM_HANDLE
_END
_BEGIN_CONSTANTS
_CONSTANTS (UINT32) TPM_SPEC
_TYPE UINT32
_NAME TPM_SPEC_FAMILY
_VALUE 0x322E3000
_NAME TPM_SPEC_LEVEL
_VALUE 00
_END
_BEGIN_STRUCTURES
_STRUCTURE TPMS_TIME_INFO
_TYPE UINT64
_NAME time
_TYPE TPMS_CLOCK_INFO
_NAME clockInfo
_END

Sample input for commands looks like this:
_BEGIN
_INPUT_START TPM2_Startup
_TYPE TPMI_ST_COMMAND_TAG
_NAME tag
_COMMENT TPM_ST_NO_SESSIONS
_TYPE UINT32
_NAME commandSize
_TYPE TPM_CC
_NAME commandCode
_COMMENT TPM_CC_Startup {NV}
_TYPE TPM_SU
_NAME startupType
_COMMENT TPM_SU_CLEAR or TPM_SU_STATE
_OUTPUT_START TPM2_Startup
_TYPE TPM_ST
_NAME tag
_COMMENT see clause 8
_TYPE UINT32
_NAME responseSize
_TYPE TPM_RC
_NAME responseCode
_END
"""

from __future__ import print_function

import argparse
import re
import subprocess

import union_selectors

_BASIC_TYPES = ['uint8_t', 'int8_t', 'int', 'uint16_t', 'int16_t',
                'uint32_t', 'int32_t', 'uint64_t', 'int64_t']
_OUTPUT_FILE_H = 'tpm_generated.h'
_OUTPUT_FILE_CC = 'tpm_generated.cc'
_COPYRIGHT_HEADER = (
    '//\n'
    '// Copyright (C) 2015 The Android Open Source Project\n'
    '//\n'
    '// Licensed under the Apache License, Version 2.0 (the "License");\n'
    '// you may not use this file except in compliance with the License.\n'
    '// You may obtain a copy of the License at\n'
    '//\n'
    '//      http://www.apache.org/licenses/LICENSE-2.0\n'
    '//\n'
    '// Unless required by applicable law or agreed to in writing, software\n'
    '// distributed under the License is distributed on an "AS IS" BASIS,\n'
    '// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or '
    'implied.\n'
    '// See the License for the specific language governing permissions and\n'
    '// limitations under the License.\n'
    '//\n\n'
    '// THIS CODE IS GENERATED - DO NOT MODIFY!\n')
_HEADER_FILE_GUARD_HEADER = """
#ifndef %(name)s
#define %(name)s
"""
_HEADER_FILE_GUARD_FOOTER = """
#endif  // %(name)s
"""
_HEADER_FILE_INCLUDES = """
#include <string>

#include <base/callback_forward.h>
#include <base/macros.h>

#include "trunks/trunks_export.h"
"""
_IMPLEMENTATION_FILE_INCLUDES = """
#include <memory>
#include <string>

#include <base/bind.h>
#include <base/callback.h>
#include <base/logging.h>
#include <base/macros.h>
#include <base/stl_util.h>
#include <base/strings/string_number_conversions.h>
#include <base/sys_byteorder.h>
#include <crypto/secure_hash.h>

#include "trunks/authorization_delegate.h"
#include "trunks/command_transceiver.h"
#include "trunks/error_codes.h"

"""
_LOCAL_INCLUDE = """
#include "trunks/%(filename)s"
"""
_NAMESPACE_BEGIN = """
namespace trunks {
"""
_NAMESPACE_END = """
}  // namespace trunks
"""
_FORWARD_DECLARATIONS = """
class AuthorizationDelegate;
class CommandTransceiver;
"""
_FUNCTION_DECLARATIONS = """
TRUNKS_EXPORT size_t GetNumberOfRequestHandles(TPM_CC command_code);
TRUNKS_EXPORT size_t GetNumberOfResponseHandles(TPM_CC command_code);
"""
_CLASS_BEGIN = """
class TRUNKS_EXPORT Tpm {
 public:
  // Does not take ownership of |transceiver|.
  explicit Tpm(CommandTransceiver* transceiver) : transceiver_(transceiver) {}
  virtual ~Tpm() {}

"""
_CLASS_END = """
 private:
  CommandTransceiver* transceiver_;

  DISALLOW_COPY_AND_ASSIGN(Tpm);
};
"""
_SERIALIZE_BASIC_TYPE = """
TPM_RC Serialize_%(type)s(const %(type)s& value, std::string* buffer) {
  VLOG(3) << __func__;
  %(type)s value_net = value;
  switch (sizeof(%(type)s)) {
    case 2:
      value_net = base::HostToNet16(value);
      break;
    case 4:
      value_net = base::HostToNet32(value);
      break;
    case 8:
      value_net = base::HostToNet64(value);
      break;
    default:
      break;
  }
  const char* value_bytes = reinterpret_cast<const char*>(&value_net);
  buffer->append(value_bytes, sizeof(%(type)s));
  return TPM_RC_SUCCESS;
}

TPM_RC Parse_%(type)s(
    std::string* buffer,
    %(type)s* value,
    std::string* value_bytes) {
  VLOG(3) << __func__;
  if (buffer->size() < sizeof(%(type)s))
    return TPM_RC_INSUFFICIENT;
  %(type)s value_net = 0;
  memcpy(&value_net, buffer->data(), sizeof(%(type)s));
  switch (sizeof(%(type)s)) {
    case 2:
      *value = base::NetToHost16(value_net);
      break;
    case 4:
      *value = base::NetToHost32(value_net);
      break;
    case 8:
      *value = base::NetToHost64(value_net);
      break;
    default:
      *value = value_net;
  }
  if (value_bytes) {
    value_bytes->append(buffer->substr(0, sizeof(%(type)s)));
  }
  buffer->erase(0, sizeof(%(type)s));
  return TPM_RC_SUCCESS;
}
"""
_SERIALIZE_DECLARATION = """
TRUNKS_EXPORT TPM_RC Serialize_%(type)s(
    const %(type)s& value,
    std::string* buffer);

TRUNKS_EXPORT TPM_RC Parse_%(type)s(
    std::string* buffer,
    %(type)s* value,
    std::string* value_bytes);
"""

_SIMPLE_TPM2B_HELPERS_DECLARATION = """
TRUNKS_EXPORT %(type)s Make_%(type)s(
    const std::string& bytes);
TRUNKS_EXPORT std::string StringFrom_%(type)s(
    const %(type)s& tpm2b);
"""
_COMPLEX_TPM2B_HELPERS_DECLARATION = """
TRUNKS_EXPORT %(type)s Make_%(type)s(
    const %(inner_type)s& inner);
"""

_HANDLE_COUNT_FUNCTION_START = """
size_t GetNumberOf%(handle_type)sHandles(TPM_CC command_code) {
  switch (command_code) {"""
_HANDLE_COUNT_FUNCTION_CASE = """
    case %(command_code)s: return %(handle_count)s;"""
_HANDLE_COUNT_FUNCTION_END = """
    default: LOG(WARNING) << "Unknown command code: " << command_code;
  }
  return 0;
}
"""

def FixName(name):
  """Fixes names to conform to Chromium style."""
  # Handle names with array notation. E.g. 'myVar[10]' is grouped as 'myVar' and
  # '[10]'.
  match = re.search(r'([^\[]*)(\[.*\])*', name)
  # Transform the name to Chromium style. E.g. 'myVarAgain' becomes
  # 'my_var_again'.
  fixed_name = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', match.group(1)).lower()
  return fixed_name + match.group(2) if match.group(2) else fixed_name


def IsTPM2B(name):
  return name.startswith('TPM2B_')


def GetCppBool(condition):
  if condition:
    return 'true'
  return 'false'


class Typedef(object):
  """Represents a TPM typedef.

  Attributes:
    old_type: The existing type in a typedef statement.
    new_type: The new type in a typedef statement.
  """

  _TYPEDEF = 'typedef %(old_type)s %(new_type)s;\n'
  _SERIALIZE_FUNCTION = """
TPM_RC Serialize_%(new)s(
    const %(new)s& value,
    std::string* buffer) {
  VLOG(3) << __func__;
  return Serialize_%(old)s(value, buffer);
}
"""
  _PARSE_FUNCTION = """
TPM_RC Parse_%(new)s(
    std::string* buffer,
    %(new)s* value,
    std::string* value_bytes) {
  VLOG(3) << __func__;
  return Parse_%(old)s(buffer, value, value_bytes);
}
"""

  def __init__(self, old_type, new_type):
    """Initializes a Typedef instance.

    Args:
      old_type: The existing type in a typedef statement.
      new_type: The new type in a typedef statement.
    """
    self.old_type = old_type
    self.new_type = new_type

  def OutputForward(self, out_file, defined_types, typemap):
    """Writes a typedef definition to |out_file|.

    Any outstanding dependencies will be forward declared. This method is the
    same as Output() because forward declarations do not apply for typedefs.

    Args:
      out_file: The output file.
      defined_types: A set of types for which definitions have already been
          generated.
      typemap: A dict mapping type names to the corresponding object.
    """
    self.Output(out_file, defined_types, typemap)

  def Output(self, out_file, defined_types, typemap):
    """Writes a typedef definition to |out_file|.

    Any outstanding dependencies will be forward declared.

    Args:
      out_file: The output file.
      defined_types: A set of types for which definitions have already been
          generated.
      typemap: A dict mapping type names to the corresponding object.
    """
    if self.new_type in defined_types:
      return
    # Make sure the dependency is already defined.
    if self.old_type not in defined_types:
      typemap[self.old_type].OutputForward(out_file, defined_types, typemap)
    out_file.write(self._TYPEDEF % {'old_type': self.old_type,
                                    'new_type': self.new_type})
    defined_types.add(self.new_type)

  def OutputSerialize(self, out_file, serialized_types, typemap):
    """Writes a serialize and parse function for the typedef to |out_file|.

    Args:
      out_file: The output file.
      serialized_types: A set of types for which serialize and parse functions
        have already been generated.
      typemap: A dict mapping type names to the corresponding object.
    """
    if self.new_type in serialized_types:
      return
    if self.old_type not in serialized_types:
      typemap[self.old_type].OutputSerialize(out_file, serialized_types,
                                             typemap)
    out_file.write(self._SERIALIZE_FUNCTION % {'old': self.old_type,
                                               'new': self.new_type})
    out_file.write(self._PARSE_FUNCTION % {'old': self.old_type,
                                           'new': self.new_type})
    serialized_types.add(self.new_type)


class Constant(object):
  """Represents a TPM constant.

  Attributes:
    const_type: The type of the constant (e.g. 'int').
    name: The name of the constant (e.g. 'kMyConstant').
    value: The value of the constant (e.g. '7').
  """

  _CONSTANT = 'constexpr %(type)s %(name)s = %(value)s;\n'

  def __init__(self, const_type, name, value):
    """Initializes a Constant instance.

    Args:
      const_type: The type of the constant (e.g. 'int').
      name: The name of the constant (e.g. 'kMyConstant').
      value: The value of the constant (e.g. '7').
    """
    self.const_type = const_type
    self.name = name
    self.value = value

  def Output(self, out_file, defined_types, typemap):
    """Writes a constant definition to |out_file|.

    Any outstanding dependencies will be forward declared.

    Args:
      out_file: The output file.
      defined_types: A set of types for which definitions have already been
          generated.
      typemap: A dict mapping type names to the corresponding object.
    """
    # Make sure the dependency is already defined.
    if self.const_type not in defined_types:
      typemap[self.const_type].OutputForward(out_file, defined_types, typemap)
    out_file.write(self._CONSTANT % {'type': self.const_type,
                                     'name': self.name,
                                     'value': self.value})


class Structure(object):
  """Represents a TPM structure or union.

  Attributes:
    name: The name of the structure.
    is_union: A boolean indicating whether this is a union.
    fields: A list of (type, name) tuples representing the struct fields.
    depends_on: A list of strings for types this struct depends on other than
        field types. See AddDependency() for more details.
  """

  _STRUCTURE = 'struct %(name)s {\n'
  _STRUCTURE_FORWARD = 'struct %(name)s;\n'
  _UNION = 'union %(name)s {\n'
  _UNION_FORWARD = 'union %(name)s;\n'
  _STRUCTURE_END = '};\n\n'
  _STRUCTURE_FIELD = '  %(type)s %(name)s;\n'
  _SERIALIZE_FUNCTION_START = """
TPM_RC Serialize_%(type)s(
    const %(type)s& value,
    std::string* buffer) {
  TPM_RC result = TPM_RC_SUCCESS;
  VLOG(3) << __func__;
"""
  _SERIALIZE_FIELD = """
  result = Serialize_%(type)s(value.%(name)s, buffer);
  if (result) {
    return result;
  }
"""
  _SERIALIZE_FIELD_ARRAY = """
  if (arraysize(value.%(name)s) < value.%(count)s) {
    return TPM_RC_INSUFFICIENT;
  }
  for (uint32_t i = 0; i < value.%(count)s; ++i) {
    result = Serialize_%(type)s(value.%(name)s[i], buffer);
    if (result) {
      return result;
    }
  }
"""
  _SERIALIZE_FIELD_WITH_SELECTOR = """
  result = Serialize_%(type)s(
      value.%(name)s,
      value.%(selector_name)s,
      buffer);
  if (result) {
    return result;
  }
"""
  _SERIALIZE_COMPLEX_TPM2B = """
  std::string field_bytes;
  result = Serialize_%(type)s(value.%(name)s, &field_bytes);
  if (result) {
    return result;
  }
  std::string size_bytes;
  result = Serialize_UINT16(field_bytes.size(), &size_bytes);
  if (result) {
    return result;
  }
  buffer->append(size_bytes + field_bytes);
"""
  _PARSE_FUNCTION_START = """
TPM_RC Parse_%(type)s(
    std::string* buffer,
    %(type)s* value,
    std::string* value_bytes) {
  TPM_RC result = TPM_RC_SUCCESS;
  VLOG(3) << __func__;
"""
  _PARSE_FIELD = """
  result = Parse_%(type)s(
      buffer,
      &value->%(name)s,
      value_bytes);
  if (result) {
    return result;
  }
"""
  _PARSE_FIELD_ARRAY = """
  if (arraysize(value->%(name)s) < value->%(count)s) {
    return TPM_RC_INSUFFICIENT;
  }
  for (uint32_t i = 0; i < value->%(count)s; ++i) {
    result = Parse_%(type)s(
        buffer,
        &value->%(name)s[i],
        value_bytes);
    if (result) {
      return result;
    }
  }
"""
  _PARSE_FIELD_WITH_SELECTOR = """
  result = Parse_%(type)s(
      buffer,
      value->%(selector_name)s,
      &value->%(name)s,
      value_bytes);
  if (result) {
    return result;
  }
"""
  _SERIALIZE_FUNCTION_END = '  return result;\n}\n'
  _ARRAY_FIELD_RE = re.compile(r'(.*)\[(.*)\]')
  _ARRAY_FIELD_SIZE_RE = re.compile(r'^(count|size)')
  _UNION_TYPE_RE = re.compile(r'^TPMU_.*')
  _SERIALIZE_UNION_FUNCTION_START = """
TPM_RC Serialize_%(union_type)s(
    const %(union_type)s& value,
    %(selector_type)s selector,
    std::string* buffer) {
  TPM_RC result = TPM_RC_SUCCESS;
  VLOG(3) << __func__;
"""
  _SERIALIZE_UNION_FIELD = """
  if (selector == %(selector_value)s) {
    result = Serialize_%(field_type)s(value.%(field_name)s, buffer);
    if (result) {
      return result;
    }
  }
"""
  _SERIALIZE_UNION_FIELD_ARRAY = """
  if (selector == %(selector_value)s) {
    if (arraysize(value.%(field_name)s) < %(count)s) {
      return TPM_RC_INSUFFICIENT;
    }
    for (uint32_t i = 0; i < %(count)s; ++i) {
      result = Serialize_%(field_type)s(value.%(field_name)s[i], buffer);
      if (result) {
        return result;
      }
    }
  }
"""
  _PARSE_UNION_FUNCTION_START = """
TPM_RC Parse_%(union_type)s(
    std::string* buffer,
    %(selector_type)s selector,
    %(union_type)s* value,
    std::string* value_bytes) {
  TPM_RC result = TPM_RC_SUCCESS;
  VLOG(3) << __func__;
"""
  _PARSE_UNION_FIELD = """
  if (selector == %(selector_value)s) {
    result = Parse_%(field_type)s(
        buffer,
        &value->%(field_name)s,
        value_bytes);
    if (result) {
      return result;
    }
  }
"""
  _PARSE_UNION_FIELD_ARRAY = """
  if (selector == %(selector_value)s) {
    if (arraysize(value->%(field_name)s) < %(count)s) {
      return TPM_RC_INSUFFICIENT;
    }
    for (uint32_t i = 0; i < %(count)s; ++i) {
      result = Parse_%(field_type)s(
          buffer,
          &value->%(field_name)s[i],
          value_bytes);
      if (result) {
        return result;
      }
    }
  }
"""
  _EMPTY_UNION_CASE = """
  if (selector == %(selector_value)s) {
    // Do nothing.
  }
"""
  _SIMPLE_TPM2B_HELPERS = """
%(type)s Make_%(type)s(
    const std::string& bytes) {
  %(type)s tpm2b;
  CHECK(bytes.size() <= sizeof(tpm2b.%(buffer_name)s));
  memset(&tpm2b, 0, sizeof(%(type)s));
  tpm2b.size = bytes.size();
  memcpy(tpm2b.%(buffer_name)s, bytes.data(), bytes.size());
  return tpm2b;
}

std::string StringFrom_%(type)s(
    const %(type)s& tpm2b) {
  const char* char_buffer = reinterpret_cast<const char*>(
      tpm2b.%(buffer_name)s);
  return std::string(char_buffer, tpm2b.size);
}
"""
  _COMPLEX_TPM2B_HELPERS = """
%(type)s Make_%(type)s(
    const %(inner_type)s& inner) {
  %(type)s tpm2b;
  tpm2b.size = sizeof(%(inner_type)s);
  tpm2b.%(inner_name)s = inner;
  return tpm2b;
}
"""

  def __init__(self, name, is_union):
    """Initializes a Structure instance.

    Initially the instance will have no fields and no dependencies. Those can be
    added with the AddField() and AddDependency() methods.

    Args:
      name: The name of the structure.
      is_union: A boolean indicating whether this is a union.
    """
    self.name = name
    self.is_union = is_union
    self.fields = []
    self.depends_on = []
    self._forwarded = False

  def AddField(self, field_type, field_name):
    """Adds a field for this struct.

    Args:
      field_type: The type of the field.
      field_name: The name of the field.
    """
    self.fields.append((field_type, FixName(field_name)))

  def AddDependency(self, required_type):
    """Adds an explicit dependency on another type.

    This is used in cases where there is an additional dependency other than the
    field types, which are implicit dependencies.  For example, a field like
    FIELD_TYPE value[sizeof(OTHER_TYPE)] would need OTHER_TYPE to be already
    declared.

    Args:
      required_type: The type this structure depends on.
    """
    self.depends_on.append(required_type)

  def IsSimpleTPM2B(self):
    """Returns whether this struct is a TPM2B structure with raw bytes."""
    return self.name.startswith('TPM2B_') and self.fields[1][0] == 'BYTE'

  def IsComplexTPM2B(self):
    """Returns whether this struct is a TPM2B structure with an inner struct."""
    return self.name.startswith('TPM2B_') and self.fields[1][0] != 'BYTE'

  def _GetFieldTypes(self):
    """Creates a set which holds all current field types.

    Returns:
      A set of field types.
    """
    return set([field[0] for field in self.fields])

  def OutputForward(self, out_file, unused_defined_types, unused_typemap):
    """Writes a structure forward declaration to |out_file|.

    This method needs to match the OutputForward method in other type classes
    (e.g. Typedef) which is why the unused_* args exist.

    Args:
      out_file: The output file.
      unused_defined_types: Not used.
      unused_typemap: Not used.
    """
    if self._forwarded:
      return
    if self.is_union:
      out_file.write(self._UNION_FORWARD % {'name': self.name})
    else:
      out_file.write(self._STRUCTURE_FORWARD % {'name': self.name})
    self._forwarded = True

  def Output(self, out_file, defined_types, typemap):
    """Writes a structure definition to |out_file|.

    Any outstanding dependencies will be defined.

    Args:
      out_file: The output file.
      defined_types: A set of types for which definitions have already been
        generated.
      typemap: A dict mapping type names to the corresponding object.
    """
    if self.name in defined_types:
      return
    # Make sure any dependencies are already defined.
    for field_type in self._GetFieldTypes():
      if field_type not in defined_types:
        typemap[field_type].Output(out_file, defined_types, typemap)
    for required_type in self.depends_on:
      if required_type not in defined_types:
        typemap[required_type].Output(out_file, defined_types, typemap)
    if self.is_union:
      out_file.write(self._UNION % {'name': self.name})
    else:
      out_file.write(self._STRUCTURE % {'name': self.name})
    for field in self.fields:
      out_file.write(self._STRUCTURE_FIELD % {'type': field[0],
                                              'name': field[1]})
    out_file.write(self._STRUCTURE_END)
    defined_types.add(self.name)

  def OutputSerialize(self, out_file, serialized_types, typemap):
    """Writes serialize and parse functions for a structure to |out_file|.

    Args:
      out_file: The output file.
      serialized_types: A set of types for which serialize and parse functions
        have already been generated.  This type name of this structure will be
        added on success.
      typemap: A dict mapping type names to the corresponding object.
    """
    if (self.name in serialized_types or
        self.name == 'TPMU_NAME' or
        self.name == 'TPMU_ENCRYPTED_SECRET'):
      return
    # Make sure any dependencies already have serialize functions defined.
    for field_type in self._GetFieldTypes():
      if field_type not in serialized_types:
        typemap[field_type].OutputSerialize(out_file, serialized_types, typemap)
    if self.is_union:
      self._OutputUnionSerialize(out_file)
      serialized_types.add(self.name)
      return
    out_file.write(self._SERIALIZE_FUNCTION_START % {'type': self.name})
    if self.IsComplexTPM2B():
      field_type = self.fields[1][0]
      field_name = self.fields[1][1]
      out_file.write(self._SERIALIZE_COMPLEX_TPM2B % {'type': field_type,
                                                      'name': field_name})
    else:
      for field in self.fields:
        if self._ARRAY_FIELD_RE.search(field[1]):
          self._OutputArrayField(out_file, field, self._SERIALIZE_FIELD_ARRAY)
        elif self._UNION_TYPE_RE.search(field[0]):
          self._OutputUnionField(out_file, field,
                                 self._SERIALIZE_FIELD_WITH_SELECTOR)
        else:
          out_file.write(self._SERIALIZE_FIELD % {'type': field[0],
                                                  'name': field[1]})
    out_file.write(self._SERIALIZE_FUNCTION_END)
    out_file.write(self._PARSE_FUNCTION_START % {'type': self.name})
    for field in self.fields:
      if self._ARRAY_FIELD_RE.search(field[1]):
        self._OutputArrayField(out_file, field, self._PARSE_FIELD_ARRAY)
      elif self._UNION_TYPE_RE.search(field[0]):
        self._OutputUnionField(out_file, field, self._PARSE_FIELD_WITH_SELECTOR)
      else:
        out_file.write(self._PARSE_FIELD % {'type': field[0],
                                            'name': field[1]})
    out_file.write(self._SERIALIZE_FUNCTION_END)
    # If this is a TPM2B structure throw in a few convenience functions.
    if self.IsSimpleTPM2B():
      field_name = self._ARRAY_FIELD_RE.search(self.fields[1][1]).group(1)
      out_file.write(self._SIMPLE_TPM2B_HELPERS % {'type': self.name,
                                                   'buffer_name': field_name})
    elif self.IsComplexTPM2B():
      field_type = self.fields[1][0]
      field_name = self.fields[1][1]
      out_file.write(self._COMPLEX_TPM2B_HELPERS % {'type': self.name,
                                                    'inner_type': field_type,
                                                    'inner_name': field_name})
    serialized_types.add(self.name)

  def _OutputUnionSerialize(self, out_file):
    """Writes serialize and parse functions for a union to |out_file|.

    This is more complex than the struct case because only one field of the
    union is serialized / parsed based on the value of a selector.  Arrays are
    also handled differently: the full size of the array is serialized instead
    of looking for a field which specifies the count.

    Args:
      out_file: The output file
    """
    selector_type = union_selectors.GetUnionSelectorType(self.name)
    selector_values = union_selectors.GetUnionSelectorValues(self.name)
    field_types = {f[1]: f[0] for f in self.fields}
    out_file.write(self._SERIALIZE_UNION_FUNCTION_START %
                   {'union_type': self.name, 'selector_type': selector_type})
    for selector in selector_values:
      field_name = FixName(union_selectors.GetUnionSelectorField(self.name,
                                                                 selector))
      if not field_name:
        out_file.write(self._EMPTY_UNION_CASE % {'selector_value': selector})
        continue
      field_type = field_types[field_name]
      array_match = self._ARRAY_FIELD_RE.search(field_name)
      if array_match:
        field_name = array_match.group(1)
        count = array_match.group(2)
        out_file.write(self._SERIALIZE_UNION_FIELD_ARRAY %
                       {'selector_value': selector,
                        'count': count,
                        'field_type': field_type,
                        'field_name': field_name})
      else:
        out_file.write(self._SERIALIZE_UNION_FIELD %
                       {'selector_value': selector,
                        'field_type': field_type,
                        'field_name': field_name})
    out_file.write(self._SERIALIZE_FUNCTION_END)
    out_file.write(self._PARSE_UNION_FUNCTION_START %
                   {'union_type': self.name, 'selector_type': selector_type})
    for selector in selector_values:
      field_name = FixName(union_selectors.GetUnionSelectorField(self.name,
                                                                 selector))
      if not field_name:
        out_file.write(self._EMPTY_UNION_CASE % {'selector_value': selector})
        continue
      field_type = field_types[field_name]
      array_match = self._ARRAY_FIELD_RE.search(field_name)
      if array_match:
        field_name = array_match.group(1)
        count = array_match.group(2)
        out_file.write(self._PARSE_UNION_FIELD_ARRAY %
                       {'selector_value': selector,
                        'count': count,
                        'field_type': field_type,
                        'field_name': field_name})
      else:
        out_file.write(self._PARSE_UNION_FIELD %
                       {'selector_value': selector,
                        'field_type': field_type,
                        'field_name': field_name})
    out_file.write(self._SERIALIZE_FUNCTION_END)

  def _OutputUnionField(self, out_file, field, code_format):
    """Writes serialize / parse code for a union field.

    In this case |self| may not necessarily represent a union but |field| does.
    This requires that a field of an acceptable selector type appear somewhere
    in the struct.  The value of this field is used as the selector value when
    calling the serialize / parse function for the union.

    Args:
      out_file: The output file.
      field: The union field to be processed as a (type, name) tuple.
      code_format: Must be (_SERIALIZE|_PARSE)_FIELD_WITH_SELECTOR
    """
    selector_types = union_selectors.GetUnionSelectorTypes(field[0])
    selector_name = ''
    for tmp in self.fields:
      if tmp[0] in selector_types:
        selector_name = tmp[1]
        break
    assert selector_name, 'Missing selector for %s in %s!' % (field[1],
                                                              self.name)
    out_file.write(code_format % {'type': field[0],
                                  'selector_name': selector_name,
                                  'name': field[1]})

  def _OutputArrayField(self, out_file, field, code_format):
    """Writes serialize / parse code for an array field.

    The allocated size of the array is ignored and a field which holds the
    actual count of items in the array must exist.  Only the number of items
    represented by the value of that count field are serialized / parsed.

    Args:
      out_file: The output file.
      field: The array field to be processed as a (type, name) tuple.
      code_format: Must be (_SERIALIZE|_PARSE)_FIELD_ARRAY
    """
    field_name = self._ARRAY_FIELD_RE.search(field[1]).group(1)
    for count_field in self.fields:
      assert count_field != field, ('Missing count field for %s in %s!' %
                                    (field[1], self.name))
      if self._ARRAY_FIELD_SIZE_RE.search(count_field[1]):
        out_file.write(code_format % {'count': count_field[1],
                                      'type': field[0],
                                      'name': field_name})
        break


class Define(object):
  """Represents a preprocessor define.

  Attributes:
    name: The name being defined.
    value: The value being assigned to the name.
  """

  _DEFINE = '#if !defined(%(name)s)\n#define %(name)s %(value)s\n#endif\n'

  def __init__(self, name, value):
    """Initializes a Define instance.

    Args:
      name: The name being defined.
      value: The value being assigned to the name.
    """
    self.name = name
    # Prepend 'trunks::' to types.
    self.value = re.sub(r'(TPM.?_|U?INT[0-9]{2})', r'trunks::\1', value)

  def Output(self, out_file):
    """Writes a preprocessor define to |out_file|.

    Args:
      out_file: The output file.
    """
    out_file.write(self._DEFINE % {'name': self.name, 'value': self.value})


class StructureParser(object):
  """Structure definition parser.

  The input text file is extracted from the PDF file containing the TPM
  structures specification from the Trusted Computing Group. The syntax
  of the text file is defined by extract_structures.sh.

  - Parses typedefs to a list of Typedef objects.
  - Parses constants to a list of Constant objects.
  - Parses structs and unions to a list of Structure objects.
  - Parses defines to a list of Define objects.

  The parser also creates 'typemap' dict which maps every type to its generator
  object.  This typemap helps manage type dependencies.

  Example usage:
  parser = StructureParser(open('myfile'))
  types, constants, structs, defines, typemap = parser.Parse()
  """

  # Compile regular expressions.
  _BEGIN_TYPES_TOKEN = '_BEGIN_TYPES'
  _BEGIN_CONSTANTS_TOKEN = '_BEGIN_CONSTANTS'
  _BEGIN_STRUCTURES_TOKEN = '_BEGIN_STRUCTURES'
  _BEGIN_UNIONS_TOKEN = '_BEGIN_UNIONS'
  _BEGIN_DEFINES_TOKEN = '_BEGIN_DEFINES'
  _END_TOKEN = '_END'
  _OLD_TYPE_RE = re.compile(r'^_OLD_TYPE\s+(\w+)$')
  _NEW_TYPE_RE = re.compile(r'^_NEW_TYPE\s+(\w+)$')
  _CONSTANTS_SECTION_RE = re.compile(r'^_CONSTANTS.* (\w+)$')
  _STRUCTURE_SECTION_RE = re.compile(r'^_STRUCTURE\s+(\w+)$')
  _UNION_SECTION_RE = re.compile(r'^_UNION\s+(\w+)$')
  _TYPE_RE = re.compile(r'^_TYPE\s+(\w+)$')
  _NAME_RE = re.compile(r'^_NAME\s+([a-zA-Z0-9_()\[\]/\*\+\-]+)$')
  _VALUE_RE = re.compile(r'^_VALUE\s+(.+)$')
  _SIZEOF_RE = re.compile(r'^.*sizeof\(([a-zA-Z0-9_]*)\).*$')

  def __init__(self, in_file):
    """Initializes a StructureParser instance.

    Args:
      in_file: A file as returned by open() which has been opened for reading.
    """
    self._line = None
    self._in_file = in_file

  def _NextLine(self):
    """Gets the next input line.

    Returns:
      The next input line if another line is available, None otherwise.
    """
    try:
      self._line = self._in_file.next()
    except StopIteration:
      self._line = None

  def Parse(self):
    """Parse everything in a structures file.

    Returns:
      Lists of objects and a type-map as described in the class documentation.
      Returns these in the following order: types, constants, structs, defines,
      typemap.
    """
    self._NextLine()
    types = []
    constants = []
    structs = []
    defines = []
    typemap = {}
    while self._line:
      if self._BEGIN_TYPES_TOKEN == self._line.rstrip():
        types += self._ParseTypes(typemap)
      elif self._BEGIN_CONSTANTS_TOKEN == self._line.rstrip():
        constants += self._ParseConstants(types, typemap)
      elif self._BEGIN_STRUCTURES_TOKEN == self._line.rstrip():
        structs += self._ParseStructures(self._STRUCTURE_SECTION_RE, typemap)
      elif self._BEGIN_UNIONS_TOKEN == self._line.rstrip():
        structs += self._ParseStructures(self._UNION_SECTION_RE, typemap)
      elif self._BEGIN_DEFINES_TOKEN == self._line.rstrip():
        defines += self._ParseDefines()
      else:
        print('Invalid file format: %s' % self._line)
        break
      self._NextLine()
    # Empty structs not handled by the extractor.
    self._AddEmptyStruct('TPMU_SYM_DETAILS', True, structs, typemap)
    # Defines which are used in TPM 2.0 Part 2 but not defined there.
    defines.append(Define(
        'MAX_CAP_DATA', '(MAX_CAP_BUFFER-sizeof(TPM_CAP)-sizeof(UINT32))'))
    defines.append(Define(
        'MAX_CAP_ALGS', '(TPM_ALG_LAST - TPM_ALG_FIRST + 1)'))
    defines.append(Define(
        'MAX_CAP_HANDLES', '(MAX_CAP_DATA/sizeof(TPM_HANDLE))'))
    defines.append(Define(
        'MAX_CAP_CC', '((TPM_CC_LAST - TPM_CC_FIRST) + 1)'))
    defines.append(Define(
        'MAX_TPM_PROPERTIES', '(MAX_CAP_DATA/sizeof(TPMS_TAGGED_PROPERTY))'))
    defines.append(Define(
        'MAX_PCR_PROPERTIES', '(MAX_CAP_DATA/sizeof(TPMS_TAGGED_PCR_SELECT))'))
    defines.append(Define(
        'MAX_ECC_CURVES', '(MAX_CAP_DATA/sizeof(TPM_ECC_CURVE))'))
    defines.append(Define('HASH_COUNT', '3'))
    return types, constants, structs, defines, typemap

  def _AddEmptyStruct(self, name, is_union, structs, typemap):
    """Adds an empty Structure object to |structs| and |typemap|.

    Args:
      name: The name to assign the new structure.
      is_union: A boolean indicating whether the new structure is a union.
      structs: A list of structures to which the new object is appended.
      typemap: A map of type names to objects to which the new name and object
          are added.
    """
    s = Structure(name, is_union)
    structs.append(s)
    typemap[name] = s
    return

  def _ParseTypes(self, typemap):
    """Parses a typedefs section.

    The current line should be _BEGIN_TYPES and the method will stop parsing
    when an _END line is found.

    Args:
      typemap: A dictionary to which parsed types are added.

    Returns:
      A list of Typedef objects.
    """
    types = []
    self._NextLine()
    while self._END_TOKEN != self._line.rstrip():
      match = self._OLD_TYPE_RE.search(self._line)
      if not match:
        print('Invalid old type: %s' % self._line)
        return types
      old_type = match.group(1)
      self._NextLine()
      match = self._NEW_TYPE_RE.search(self._line)
      if not match:
        print('Invalid new type: %s' % self._line)
        return types
      new_type = match.group(1)
      t = Typedef(old_type, new_type)
      types.append(t)
      typemap[new_type] = t
      self._NextLine()
    return types

  def _ParseConstants(self, types, typemap):
    """Parses a constants section.

    The current line should be _BEGIN_CONSTANTS and the method will stop parsing
    when an _END line is found. Each group of constants has an associated type
    alias. A Typedef object is created for each of these aliases and added to
    both |types| and |typemap|.

    Args:
      types: A list of Typedef objects.
      typemap: A dictionary to which parsed types are added.

    Returns:
      A list of Constant objects.
    """
    constants = []
    self._NextLine()
    while self._END_TOKEN != self._line.rstrip():
      match = self._CONSTANTS_SECTION_RE.search(self._line)
      if not match:
        print('Invalid constants section: %s' % self._line)
        return constants
      constant_typename = match.group(1)
      self._NextLine()
      match = self._TYPE_RE.search(self._line)
      if not match:
        print('Invalid constants type: %s' % self._line)
        return constants
      constant_type = match.group(1)
      # Create a typedef for the constant group name (e.g. TPM_RC).
      typedef = Typedef(constant_type, constant_typename)
      typemap[constant_typename] = typedef
      types.append(typedef)
      self._NextLine()
      match = self._NAME_RE.search(self._line)
      if not match:
        print('Invalid constant name: %s' % self._line)
        return constants
      while match:
        name = match.group(1)
        self._NextLine()
        match = self._VALUE_RE.search(self._line)
        if not match:
          print('Invalid constant value: %s' % self._line)
          return constants
        value = match.group(1)
        constants.append(Constant(constant_typename, name, value))
        self._NextLine()
        match = self._NAME_RE.search(self._line)
    return constants

  def _ParseStructures(self, section_re, typemap):
    """Parses structures and unions.

    The current line should be _BEGIN_STRUCTURES or _BEGIN_UNIONS and the method
    will stop parsing when an _END line is found.

    Args:
      section_re: The regular expression to use for matching section tokens.
      typemap: A dictionary to which parsed types are added.

    Returns:
      A list of Structure objects.
    """
    structures = []
    is_union = section_re == self._UNION_SECTION_RE
    self._NextLine()
    while self._END_TOKEN != self._line.rstrip():
      match = section_re.search(self._line)
      if not match:
        print('Invalid structure section: %s' % self._line)
        return structures
      current_structure_name = match.group(1)
      current_structure = Structure(current_structure_name, is_union)
      self._NextLine()
      match = self._TYPE_RE.search(self._line)
      if not match:
        print('Invalid field type: %s' % self._line)
        return structures
      while match:
        field_type = match.group(1)
        self._NextLine()
        match = self._NAME_RE.search(self._line)
        if not match:
          print('Invalid field name: %s' % self._line)
          return structures
        field_name = match.group(1)
        # If the field name includes 'sizeof(SOME_TYPE)', record the dependency
        # on SOME_TYPE.
        match = self._SIZEOF_RE.search(field_name)
        if match:
          current_structure.AddDependency(match.group(1))
        # Manually change unfortunate names.
        if field_name == 'xor':
          field_name = 'xor_'
        current_structure.AddField(field_type, field_name)
        self._NextLine()
        match = self._TYPE_RE.search(self._line)
      structures.append(current_structure)
      typemap[current_structure_name] = current_structure
    return structures

  def _ParseDefines(self):
    """Parses preprocessor defines.

    The current line should be _BEGIN_DEFINES and the method will stop parsing
    when an _END line is found.

    Returns:
      A list of Define objects.
    """
    defines = []
    self._NextLine()
    while self._END_TOKEN != self._line.rstrip():
      match = self._NAME_RE.search(self._line)
      if not match:
        print('Invalid name: %s' % self._line)
        return defines
      name = match.group(1)
      self._NextLine()
      match = self._VALUE_RE.search(self._line)
      if not match:
        print('Invalid value: %s' % self._line)
        return defines
      value = match.group(1)
      defines.append(Define(name, value))
      self._NextLine()
    return defines


class Command(object):
  """Represents a TPM command.

  Attributes:
    name: The command name (e.g. 'TPM2_Startup').
    command_code: The name of the command code constant (e.g. TPM2_CC_Startup).
    request_args: A list to hold command input arguments. Each element is a dict
        and has these keys:
            'type': The argument type.
            'name': The argument name.
            'command_code': The optional value of the command code constant.
            'description': Optional descriptive text for the argument.
    response_args: A list identical in form to request_args but to hold command
        output arguments.
  """

  _HANDLE_RE = re.compile(r'TPMI_.H_.*')
  _CALLBACK_ARG = """
      const %(method_name)sResponse& callback"""
  _DELEGATE_ARG = """
      AuthorizationDelegate* authorization_delegate"""
  _SERIALIZE_ARG = """
      std::string* serialized_command"""
  _PARSE_ARG = """
      const std::string& response"""
  _SERIALIZE_FUNCTION_START = """
TPM_RC Tpm::SerializeCommand_%(method_name)s(%(method_args)s) {
  VLOG(3) << __func__;
  TPM_RC rc = TPM_RC_SUCCESS;
  TPMI_ST_COMMAND_TAG tag = TPM_ST_NO_SESSIONS;
  UINT32 command_size = 10;  // Header size.
  std::string handle_section_bytes;
  std::string parameter_section_bytes;"""
  _DECLARE_COMMAND_CODE = """
  TPM_CC command_code = %(command_code)s;"""
  _DECLARE_BOOLEAN = """
  bool %(var_name)s = %(value)s;"""
  _SERIALIZE_LOCAL_VAR = """
  std::string %(var_name)s_bytes;
  rc = Serialize_%(var_type)s(
      %(var_name)s,
      &%(var_name)s_bytes);
  if (rc != TPM_RC_SUCCESS) {
    return rc;
  }"""
  _ENCRYPT_PARAMETER = """
  if (authorization_delegate) {
    // Encrypt just the parameter data, not the size.
    std::string tmp = %(var_name)s_bytes.substr(2);
    if (!authorization_delegate->EncryptCommandParameter(&tmp)) {
      return TRUNKS_RC_ENCRYPTION_FAILED;
    }
    %(var_name)s_bytes.replace(2, std::string::npos, tmp);
  }"""
  _HASH_START = """
  std::unique_ptr<crypto::SecureHash> hash(crypto::SecureHash::Create(
      crypto::SecureHash::SHA256));"""
  _HASH_UPDATE = """
  hash->Update(%(var_name)s.data(),
               %(var_name)s.size());"""
  _APPEND_COMMAND_HANDLE = """
  handle_section_bytes += %(var_name)s_bytes;
  command_size += %(var_name)s_bytes.size();"""
  _APPEND_COMMAND_PARAMETER = """
  parameter_section_bytes += %(var_name)s_bytes;
  command_size += %(var_name)s_bytes.size();"""
  _AUTHORIZE_COMMAND = """
  std::string command_hash(32, 0);
  hash->Finish(base::string_as_array(&command_hash), command_hash.size());
  std::string authorization_section_bytes;
  std::string authorization_size_bytes;
  if (authorization_delegate) {
    if (!authorization_delegate->GetCommandAuthorization(
        command_hash,
        is_command_parameter_encryption_possible,
        is_response_parameter_encryption_possible,
        &authorization_section_bytes)) {
      return TRUNKS_RC_AUTHORIZATION_FAILED;
    }
    if (!authorization_section_bytes.empty()) {
      tag = TPM_ST_SESSIONS;
      std::string tmp;
      rc = Serialize_UINT32(authorization_section_bytes.size(),
                            &authorization_size_bytes);
      if (rc != TPM_RC_SUCCESS) {
        return rc;
      }
      command_size += authorization_size_bytes.size() +
                      authorization_section_bytes.size();
    }
  }"""
  _SERIALIZE_FUNCTION_END = """
  *serialized_command = tag_bytes +
                        command_size_bytes +
                        command_code_bytes +
                        handle_section_bytes +
                        authorization_size_bytes +
                        authorization_section_bytes +
                        parameter_section_bytes;
  CHECK(serialized_command->size() == command_size) << "Command size mismatch!";
  VLOG(2) << "Command: " << base::HexEncode(serialized_command->data(),
                                            serialized_command->size());
  return TPM_RC_SUCCESS;
}
"""
  _RESPONSE_PARSER_START = """
TPM_RC Tpm::ParseResponse_%(method_name)s(%(method_args)s) {
  VLOG(3) << __func__;
  VLOG(2) << "Response: " << base::HexEncode(response.data(), response.size());
  TPM_RC rc = TPM_RC_SUCCESS;
  std::string buffer(response);"""
  _PARSE_LOCAL_VAR = """
  %(var_type)s %(var_name)s;
  std::string %(var_name)s_bytes;
  rc = Parse_%(var_type)s(
      &buffer,
      &%(var_name)s,
      &%(var_name)s_bytes);
  if (rc != TPM_RC_SUCCESS) {
    return rc;
  }"""
  _PARSE_ARG_VAR = """
  std::string %(var_name)s_bytes;
  rc = Parse_%(var_type)s(
      &buffer,
      %(var_name)s,
      &%(var_name)s_bytes);
  if (rc != TPM_RC_SUCCESS) {
    return rc;
  }"""
  _RESPONSE_ERROR_CHECK = """
  if (response_size != response.size()) {
    return TPM_RC_SIZE;
  }
  if (response_code != TPM_RC_SUCCESS) {
    return response_code;
  }"""
  _RESPONSE_SECTION_SPLIT = """
  std::string authorization_section_bytes;
  if (tag == TPM_ST_SESSIONS) {
    UINT32 parameter_section_size = buffer.size();
    rc = Parse_UINT32(&buffer, &parameter_section_size, nullptr);
    if (rc != TPM_RC_SUCCESS) {
      return rc;
    }
    if (parameter_section_size > buffer.size()) {
      return TPM_RC_INSUFFICIENT;
    }
    authorization_section_bytes = buffer.substr(parameter_section_size);
    // Keep the parameter section in |buffer|.
    buffer.erase(parameter_section_size);
  }"""
  _AUTHORIZE_RESPONSE = """
  std::string response_hash(32, 0);
  hash->Finish(base::string_as_array(&response_hash), response_hash.size());
  if (tag == TPM_ST_SESSIONS) {
    CHECK(authorization_delegate) << "Authorization delegate missing!";
    if (!authorization_delegate->CheckResponseAuthorization(
        response_hash,
        authorization_section_bytes)) {
      return TRUNKS_RC_AUTHORIZATION_FAILED;
    }
  }"""
  _DECRYPT_PARAMETER = """
  if (tag == TPM_ST_SESSIONS) {
    CHECK(authorization_delegate) << "Authorization delegate missing!";
    // Decrypt just the parameter data, not the size.
    std::string tmp = %(var_name)s_bytes.substr(2);
    if (!authorization_delegate->DecryptResponseParameter(&tmp)) {
      return TRUNKS_RC_ENCRYPTION_FAILED;
    }
    %(var_name)s_bytes.replace(2, std::string::npos, tmp);
    rc = Parse_%(var_type)s(
        &%(var_name)s_bytes,
        %(var_name)s,
        nullptr);
    if (rc != TPM_RC_SUCCESS) {
      return rc;
    }
  }"""
  _RESPONSE_PARSER_END = """
  return TPM_RC_SUCCESS;
}
"""
  _ERROR_CALLBACK_START = """
void %(method_name)sErrorCallback(
    const Tpm::%(method_name)sResponse& callback,
    TPM_RC response_code) {
  VLOG(1) << __func__;
  callback.Run(response_code"""
  _ERROR_CALLBACK_ARG = """,
               %(arg_type)s()"""
  _ERROR_CALLBACK_END = """);
}
"""
  _RESPONSE_CALLBACK_START = """
void %(method_name)sResponseParser(
    const Tpm::%(method_name)sResponse& callback,
    AuthorizationDelegate* authorization_delegate,
    const std::string& response) {
  VLOG(1) << __func__;
  base::Callback<void(TPM_RC)> error_reporter =
      base::Bind(%(method_name)sErrorCallback, callback);"""
  _DECLARE_ARG_VAR = """
  %(var_type)s %(var_name)s;"""
  _RESPONSE_CALLBACK_END = """
  TPM_RC rc = Tpm::ParseResponse_%(method_name)s(
      response,%(method_arg_names_out)s
      authorization_delegate);
  if (rc != TPM_RC_SUCCESS) {
    error_reporter.Run(rc);
    return;
  }
  callback.Run(
      rc%(method_arg_names_in)s);
}
"""
  _ASYNC_METHOD = """
void Tpm::%(method_name)s(%(method_args)s) {
  VLOG(1) << __func__;
  base::Callback<void(TPM_RC)> error_reporter =
      base::Bind(%(method_name)sErrorCallback, callback);
  base::Callback<void(const std::string&)> parser =
      base::Bind(%(method_name)sResponseParser,
                 callback,
                 authorization_delegate);
  std::string command;
  TPM_RC rc = SerializeCommand_%(method_name)s(%(method_arg_names)s
      &command,
      authorization_delegate);
  if (rc != TPM_RC_SUCCESS) {
    error_reporter.Run(rc);
    return;
  }
  transceiver_->SendCommand(command, parser);
}
"""
  _SYNC_METHOD = """
TPM_RC Tpm::%(method_name)sSync(%(method_args)s) {
  VLOG(1) << __func__;
  std::string command;
  TPM_RC rc = SerializeCommand_%(method_name)s(%(method_arg_names_in)s
      &command,
      authorization_delegate);
  if (rc != TPM_RC_SUCCESS) {
    return rc;
  }
  std::string response = transceiver_->SendCommandAndWait(command);
  rc = ParseResponse_%(method_name)s(
      response,%(method_arg_names_out)s
      authorization_delegate);
  return rc;
}
"""

  def __init__(self, name):
    """Initializes a Command instance.

    Initially the request_args and response_args attributes are not set.

    Args:
      name: The command name (e.g. 'TPM2_Startup').
    """
    self.name = name
    self.command_code = ''
    self.request_args = None
    self.response_args = None

  def OutputDeclarations(self, out_file):
    """Prints method and callback declaration statements for this command.

    Args:
      out_file: The output file.
    """
    self._OutputCallbackSignature(out_file)
    self._OutputMethodSignatures(out_file)

  def OutputSerializeFunction(self, out_file):
    """Generates a serialize function for the command inputs.

    Args:
      out_file: Generated code is written to this file.
    """
    # Categorize arguments as either handles or parameters.
    handles, parameters = self._SplitArgs(self.request_args)
    response_parameters = self._SplitArgs(self.response_args)[1]
    out_file.write(self._SERIALIZE_FUNCTION_START % {
        'method_name': self._MethodName(),
        'method_args': self._SerializeArgs()})
    out_file.write(self._DECLARE_COMMAND_CODE % {'command_code':
                                                 self.command_code})
    out_file.write(self._DECLARE_BOOLEAN % {
        'var_name': 'is_command_parameter_encryption_possible',
        'value': GetCppBool(parameters and IsTPM2B(parameters[0]['type']))})
    out_file.write(self._DECLARE_BOOLEAN % {
        'var_name': 'is_response_parameter_encryption_possible',
        'value': GetCppBool(response_parameters and
                            IsTPM2B(response_parameters[0]['type']))})
    # Serialize the command code and all the handles and parameters.
    out_file.write(self._SERIALIZE_LOCAL_VAR % {'var_name': 'command_code',
                                                'var_type': 'TPM_CC'})
    for arg in self.request_args:
      out_file.write(self._SERIALIZE_LOCAL_VAR % {'var_name': arg['name'],
                                                  'var_type': arg['type']})
    # Encrypt the first parameter (before doing authorization) if necessary.
    if parameters and IsTPM2B(parameters[0]['type']):
      out_file.write(self._ENCRYPT_PARAMETER % {'var_name':
                                                parameters[0]['name']})
    # Compute the command hash and construct handle and parameter sections.
    out_file.write(self._HASH_START)
    out_file.write(self._HASH_UPDATE % {'var_name': 'command_code_bytes'})
    for handle in handles:
      out_file.write(self._HASH_UPDATE % {'var_name':
                                          '%s_name' % handle['name']})
      out_file.write(self._APPEND_COMMAND_HANDLE % {'var_name':
                                                    handle['name']})
    for parameter in parameters:
      out_file.write(self._HASH_UPDATE % {'var_name':
                                          '%s_bytes' % parameter['name']})
      out_file.write(self._APPEND_COMMAND_PARAMETER % {'var_name':
                                                       parameter['name']})
    # Do authorization based on the hash.
    out_file.write(self._AUTHORIZE_COMMAND)
    # Now that the tag and size are finalized, serialize those.
    out_file.write(self._SERIALIZE_LOCAL_VAR %
                   {'var_name': 'tag',
                    'var_type': 'TPMI_ST_COMMAND_TAG'})
    out_file.write(self._SERIALIZE_LOCAL_VAR % {'var_name': 'command_size',
                                                'var_type': 'UINT32'})
    out_file.write(self._SERIALIZE_FUNCTION_END)

  def OutputParseFunction(self, out_file):
    """Generates a parse function for the command outputs.

    Args:
      out_file: Generated code is written to this file.
    """
    out_file.write(self._RESPONSE_PARSER_START % {
        'method_name': self._MethodName(),
        'method_args': self._ParseArgs()})
    # Parse the header -- this should always exist.
    out_file.write(self._PARSE_LOCAL_VAR % {'var_name': 'tag',
                                            'var_type': 'TPM_ST'})
    out_file.write(self._PARSE_LOCAL_VAR % {'var_name': 'response_size',
                                            'var_type': 'UINT32'})
    out_file.write(self._PARSE_LOCAL_VAR % {'var_name': 'response_code',
                                            'var_type': 'TPM_RC'})
    # Handle the error case.
    out_file.write(self._RESPONSE_ERROR_CHECK)
    # Categorize arguments as either handles or parameters.
    handles, parameters = self._SplitArgs(self.response_args)
    # Parse any handles.
    for handle in handles:
      out_file.write(self._PARSE_ARG_VAR % {'var_name': handle['name'],
                                            'var_type': handle['type']})
    # Setup a serialized command code which is needed for the response hash.
    out_file.write(self._DECLARE_COMMAND_CODE % {'command_code':
                                                 self.command_code})
    out_file.write(self._SERIALIZE_LOCAL_VAR % {'var_name': 'command_code',
                                                'var_type': 'TPM_CC'})
    # Split out the authorization section.
    out_file.write(self._RESPONSE_SECTION_SPLIT)
    # Compute the response hash.
    out_file.write(self._HASH_START)
    out_file.write(self._HASH_UPDATE % {'var_name': 'response_code_bytes'})
    out_file.write(self._HASH_UPDATE % {'var_name': 'command_code_bytes'})
    out_file.write(self._HASH_UPDATE % {'var_name': 'buffer'})
    # Do authorization related stuff.
    out_file.write(self._AUTHORIZE_RESPONSE)
    # Parse response parameters.
    for arg in parameters:
      out_file.write(self._PARSE_ARG_VAR % {'var_name': arg['name'],
                                            'var_type': arg['type']})
    if parameters and IsTPM2B(parameters[0]['type']):
      out_file.write(self._DECRYPT_PARAMETER % {'var_name':
                                                parameters[0]['name'],
                                                'var_type':
                                                parameters[0]['type']})
    out_file.write(self._RESPONSE_PARSER_END)

  def OutputMethodImplementation(self, out_file):
    """Generates the implementation of a Tpm class method for this command.

    The method assembles a command to be sent unmodified to the TPM and invokes
    the CommandTransceiver with the command. Errors are reported directly to the
    response callback via the error callback (see OutputErrorCallback).

    Args:
      out_file: Generated code is written to this file.
    """
    out_file.write(self._ASYNC_METHOD % {
        'method_name': self._MethodName(),
        'method_args': self._AsyncArgs(),
        'method_arg_names': self._ArgNameList(self._RequestArgs(),
                                              trailing_comma=True)})
    out_file.write(self._SYNC_METHOD % {
        'method_name': self._MethodName(),
        'method_args': self._SyncArgs(),
        'method_arg_names_in': self._ArgNameList(self._RequestArgs(),
                                                 trailing_comma=True),
        'method_arg_names_out': self._ArgNameList(self.response_args,
                                                  trailing_comma=True)})

  def OutputErrorCallback(self, out_file):
    """Generates the implementation of an error callback for this command.

    The error callback simply calls the command response callback with the error
    as the first argument and default values for all other arguments.

    Args:
      out_file: Generated code is written to this file.
    """
    out_file.write(self._ERROR_CALLBACK_START % {'method_name':
                                                 self._MethodName()})
    for arg in self.response_args:
      out_file.write(self._ERROR_CALLBACK_ARG % {'arg_type': arg['type']})
    out_file.write(self._ERROR_CALLBACK_END)

  def OutputResponseCallback(self, out_file):
    """Generates the implementation of a response callback for this command.

    The response callback takes the unmodified response from the TPM, parses it,
    and invokes the original response callback with the parsed response args.
    Errors during parsing or from the TPM are reported directly to the response
    callback via the error callback (see OutputErrorCallback).

    Args:
      out_file: Generated code is written to this file.
    """
    out_file.write(self._RESPONSE_CALLBACK_START % {'method_name':
                                                    self._MethodName()})
    for arg in self.response_args:
      out_file.write(self._DECLARE_ARG_VAR % {'var_type': arg['type'],
                                              'var_name': arg['name']})
    out_file.write(self._RESPONSE_CALLBACK_END % {
        'method_name': self._MethodName(),
        'method_arg_names_in': self._ArgNameList(self.response_args,
                                                 leading_comma=True),
        'method_arg_names_out': self._ArgNameList(self.response_args,
                                                  prefix='&',
                                                  trailing_comma=True)})

  def GetNumberOfRequestHandles(self):
    """Returns the number of input handles for this command."""
    return len(self._SplitArgs(self.request_args)[0])

  def GetNumberOfResponseHandles(self):
    """Returns the number of output handles for this command."""
    return len(self._SplitArgs(self.response_args)[0])

  def _OutputMethodSignatures(self, out_file):
    """Prints method declaration statements for this command.

    This includes a method to serialize a request, a method to parse a response,
    and methods for synchronous and asynchronous calls.

    Args:
      out_file: The output file.
    """
    out_file.write('  static TPM_RC SerializeCommand_%s(%s);\n' % (
        self._MethodName(), self._SerializeArgs()))
    out_file.write('  static TPM_RC ParseResponse_%s(%s);\n' % (
        self._MethodName(), self._ParseArgs()))
    out_file.write('  virtual void %s(%s);\n' % (self._MethodName(),
                                                 self._AsyncArgs()))
    out_file.write('  virtual TPM_RC %sSync(%s);\n' % (self._MethodName(),
                                                       self._SyncArgs()))

  def _OutputCallbackSignature(self, out_file):
    """Prints a callback typedef for this command.

    Args:
      out_file: The output file.
    """
    args = self._InputArgList(self.response_args)
    if args:
      args = ',' + args
    args = '\n      TPM_RC response_code' + args
    out_file.write('  typedef base::Callback<void(%s)> %sResponse;\n' %
                   (args, self._MethodName()))

  def _MethodName(self):
    """Creates an appropriate generated method name for the command.

    We use the command name without the TPM2_ prefix.

    Returns:
      The method name.
    """
    if not self.name.startswith('TPM2_'):
      return self.name
    return self.name[5:]

  def _InputArgList(self, args):
    """Formats a list of input arguments for use in a function declaration.

    Args:
      args: An argument list in the same form as the request_args and
          response_args attributes.

    Returns:
      A string which can be used in a function declaration.
    """
    if args:
      arg_list = ['const %(type)s& %(name)s' % a for a in args]
      return '\n      ' + ',\n      '.join(arg_list)
    return ''

  def _OutputArgList(self, args):
    """Formats a list of output arguments for use in a function declaration.

    Args:
      args: An argument list in the same form as the request_args and
          response_args attributes.

    Returns:
      A string which can be used in a function declaration.
    """
    if args:
      arg_list = ['%(type)s* %(name)s' % a for a in args]
      return '\n      ' + ',\n      '.join(arg_list)
    return ''

  def _ArgNameList(self, args, prefix='', leading_comma=False,
                   trailing_comma=False):
    """Formats a list of arguments for use in a function call statement.

    Args:
      args: An argument list in the same form as the request_args and
          response_args attributes.
      prefix: A prefix to be prepended to each argument.
      leading_comma: Whether to include a comma before the first argument.
      trailing_comma: Whether to include a comma after the last argument.

    Returns:
      A string which can be used in a function call statement.
    """
    if args:
      arg_list = [(prefix + a['name']) for a in args]
      header = ''
      if leading_comma:
        header = ','
      trailer = ''
      if trailing_comma:
        trailer = ','
      return header + '\n      ' + ',\n      '.join(arg_list) + trailer
    return ''

  def _SplitArgs(self, args):
    """Splits a list of args into handles and parameters."""
    handles = []
    parameters = []
    # These commands have handles that are serialized into the parameter
    # section.
    command_handle_parameters = {
        'TPM_CC_FlushContext': 'TPMI_DH_CONTEXT',
        'TPM_CC_Hash': 'TPMI_RH_HIERARCHY',
        'TPM_CC_LoadExternal': 'TPMI_RH_HIERARCHY',
        'TPM_CC_SequenceComplete': 'TPMI_RH_HIERARCHY',
    }
    # Handle type that appears in the handle section.
    always_handle = set(['TPM_HANDLE'])
    # Handle types that always appear as command parameters.
    always_parameter = set(['TPMI_RH_ENABLES', 'TPMI_DH_PERSISTENT'])
    if self.command_code in command_handle_parameters:
      always_parameter.add(command_handle_parameters[self.command_code])
    for arg in args:
      if (arg['type'] in always_handle or
          (self._HANDLE_RE.search(arg['type']) and
           arg['type'] not in always_parameter)):
        handles.append(arg)
      else:
        parameters.append(arg)
    return handles, parameters

  def _RequestArgs(self):
    """Computes the argument list for a Tpm request.

    For every handle argument a handle name argument is added.
    """
    handles, parameters = self._SplitArgs(self.request_args)
    args = []
    # Add a name argument for every handle.  We'll need it to compute cpHash.
    for handle in handles:
      args.append(handle)
      args.append({'type': 'std::string',
                   'name': '%s_name' % handle['name']})
    for parameter in parameters:
      args.append(parameter)
    return args

  def _AsyncArgs(self):
    """Returns a formatted argument list for an asynchronous method."""
    args = self._InputArgList(self._RequestArgs())
    if args:
      args += ','
    return (args + self._DELEGATE_ARG + ',' +
            self._CALLBACK_ARG % {'method_name': self._MethodName()})

  def _SyncArgs(self):
    """Returns a formatted argument list for a synchronous method."""
    request_arg_list = self._InputArgList(self._RequestArgs())
    if request_arg_list:
      request_arg_list += ','
    response_arg_list = self._OutputArgList(self.response_args)
    if response_arg_list:
      response_arg_list += ','
    return request_arg_list + response_arg_list + self._DELEGATE_ARG

  def _SerializeArgs(self):
    """Returns a formatted argument list for a request-serialize method."""
    args = self._InputArgList(self._RequestArgs())
    if args:
      args += ','
    return args + self._SERIALIZE_ARG + ',' + self._DELEGATE_ARG

  def _ParseArgs(self):
    """Returns a formatted argument list for a response-parse method."""
    args = self._OutputArgList(self.response_args)
    if args:
      args = ',' + args
    return self._PARSE_ARG + args + ',' + self._DELEGATE_ARG


class CommandParser(object):
  """Command definition parser.

  The input text file is extracted from the PDF file containing the TPM
  command specification from the Trusted Computing Group. The syntax
  of the text file is defined by extract_commands.sh.
  """

  # Regular expressions to pull relevant bits from annotated lines.
  _INPUT_START_RE = re.compile(r'^_INPUT_START\s+(\w+)$')
  _OUTPUT_START_RE = re.compile(r'^_OUTPUT_START\s+(\w+)$')
  _TYPE_RE = re.compile(r'^_TYPE\s+(\w+)$')
  _NAME_RE = re.compile(r'^_NAME\s+(\w+)$')
  # Pull the command code from a comment like: _COMMENT TPM_CC_Startup {NV}.
  _COMMENT_CC_RE = re.compile(r'^_COMMENT\s+(TPM_CC_\w+).*$')
  _COMMENT_RE = re.compile(r'^_COMMENT\s+(.*)')
  # Args which are handled internally by the generated method.
  _INTERNAL_ARGS = ('tag', 'Tag', 'commandSize', 'commandCode', 'responseSize',
                    'responseCode', 'returnCode')

  def __init__(self, in_file):
    """Initializes a CommandParser instance.

    Args:
      in_file: A file as returned by open() which has been opened for reading.
    """
    self._line = None
    self._in_file = in_file

  def _NextLine(self):
    """Gets the next input line.

    Returns:
      The next input line if another line is available, None otherwise.
    """
    try:
      self._line = self._in_file.next()
    except StopIteration:
      self._line = None

  def Parse(self):
    """Parses everything in a commands file.

    Returns:
      A list of extracted Command objects.
    """
    commands = []
    self._NextLine()
    if self._line != '_BEGIN\n':
      print('Invalid format for first line: %s\n' % self._line)
      return commands
    self._NextLine()

    while self._line != '_END\n':
      cmd = self._ParseCommand()
      if not cmd:
        break
      commands.append(cmd)
    return commands

  def _ParseCommand(self):
    """Parses inputs and outputs for a single TPM command.

    Returns:
      A single Command object.
    """
    match = self._INPUT_START_RE.search(self._line)
    if not match:
      print('Cannot match command input from line: %s\n' % self._line)
      return None
    name = match.group(1)
    cmd = Command(name)
    self._NextLine()
    cmd.request_args = self._ParseCommandArgs(cmd)
    match = self._OUTPUT_START_RE.search(self._line)
    if not match or match.group(1) != name:
      print('Cannot match command output from line: %s\n' % self._line)
      return None
    self._NextLine()
    cmd.response_args = self._ParseCommandArgs(cmd)
    request_var_names = set([arg['name'] for arg in cmd.request_args])
    for arg in cmd.response_args:
      if arg['name'] in request_var_names:
        arg['name'] += '_out'
    if not cmd.command_code:
      print('Command code not found for %s' % name)
      return None
    return cmd

  def _ParseCommandArgs(self, cmd):
    """Parses a set of arguments for a command.

    The arguments may be input or output arguments.

    Args:
      cmd: The current Command object. The command_code attribute will be set if
          such a constant is parsed.

    Returns:
      A list of arguments in the same form as the Command.request_args and
      Command.response_args attributes.
    """
    args = []
    match = self._TYPE_RE.search(self._line)
    while match:
      arg_type = match.group(1)
      self._NextLine()
      match = self._NAME_RE.search(self._line)
      if not match:
        print('Cannot match argument name from line: %s\n' % self._line)
        break
      arg_name = match.group(1)
      self._NextLine()
      match = self._COMMENT_CC_RE.search(self._line)
      if match:
        cmd.command_code = match.group(1)
      match = self._COMMENT_RE.search(self._line)
      if match:
        self._NextLine()
      if arg_name not in self._INTERNAL_ARGS:
        args.append({'type': arg_type,
                     'name': FixName(arg_name)})
      match = self._TYPE_RE.search(self._line)
    return args


def GenerateHandleCountFunctions(commands, out_file):
  """Generates the GetNumberOf*Handles functions given a list of commands.

  Args:
    commands: A list of Command objects.
    out_file: The output file.
  """
  out_file.write(_HANDLE_COUNT_FUNCTION_START % {'handle_type': 'Request'})
  for command in commands:
    out_file.write(_HANDLE_COUNT_FUNCTION_CASE %
                   {'command_code': command.command_code,
                    'handle_count': command.GetNumberOfRequestHandles()})
  out_file.write(_HANDLE_COUNT_FUNCTION_END)
  out_file.write(_HANDLE_COUNT_FUNCTION_START % {'handle_type': 'Response'})
  for command in commands:
    out_file.write(_HANDLE_COUNT_FUNCTION_CASE %
                   {'command_code': command.command_code,
                    'handle_count': command.GetNumberOfResponseHandles()})
  out_file.write(_HANDLE_COUNT_FUNCTION_END)


def GenerateHeader(types, constants, structs, defines, typemap, commands):
  """Generates a header file with declarations for all given generator objects.

  Args:
    types: A list of Typedef objects.
    constants: A list of Constant objects.
    structs: A list of Structure objects.
    defines: A list of Define objects.
    typemap: A dict mapping type names to the corresponding object.
    commands: A list of Command objects.
  """
  out_file = open(_OUTPUT_FILE_H, 'w')
  out_file.write(_COPYRIGHT_HEADER)
  guard_name = 'TRUNKS_%s_' % _OUTPUT_FILE_H.upper().replace('.', '_')
  out_file.write(_HEADER_FILE_GUARD_HEADER % {'name': guard_name})
  out_file.write(_HEADER_FILE_INCLUDES)
  out_file.write(_NAMESPACE_BEGIN)
  out_file.write(_FORWARD_DECLARATIONS)
  out_file.write('\n')
  # These types are built-in or defined by <stdint.h>; they serve as base cases
  # when defining type dependencies.
  defined_types = set(_BASIC_TYPES)
  # Generate defines.  These must be generated before any other code.
  for define in defines:
    define.Output(out_file)
  out_file.write('\n')
  # Generate typedefs.  These are declared before structs because they are not
  # likely to depend on structs and when they do a simple forward declaration
  # for the struct can be generated.  This improves the readability of the
  # generated code.
  for typedef in types:
    typedef.Output(out_file, defined_types, typemap)
  out_file.write('\n')
  # Generate constant definitions.  Again, generated before structs to improve
  # readability.
  for constant in constants:
    constant.Output(out_file, defined_types, typemap)
  out_file.write('\n')
  # Generate structs.  All non-struct dependencies should be already declared.
  for struct in structs:
    struct.Output(out_file, defined_types, typemap)
  # Helper function declarations.
  out_file.write(_FUNCTION_DECLARATIONS)
  # Generate serialize / parse function declarations.
  for basic_type in _BASIC_TYPES:
    out_file.write(_SERIALIZE_DECLARATION % {'type': basic_type})
  for typedef in types:
    out_file.write(_SERIALIZE_DECLARATION % {'type': typedef.new_type})
  for struct in structs:
    out_file.write(_SERIALIZE_DECLARATION % {'type': struct.name})
    if struct.IsSimpleTPM2B():
      out_file.write(_SIMPLE_TPM2B_HELPERS_DECLARATION % {'type': struct.name})
    elif struct.IsComplexTPM2B():
      out_file.write(_COMPLEX_TPM2B_HELPERS_DECLARATION % {
          'type': struct.name,
          'inner_type': struct.fields[1][0]})
  # Generate a declaration for a 'Tpm' class, which includes one method for
  # every TPM 2.0 command.
  out_file.write(_CLASS_BEGIN)
  for command in commands:
    command.OutputDeclarations(out_file)
  out_file.write(_CLASS_END)
  out_file.write(_NAMESPACE_END)
  out_file.write(_HEADER_FILE_GUARD_FOOTER % {'name': guard_name})
  out_file.close()


def GenerateImplementation(types, structs, typemap, commands):
  """Generates implementation code for each command.

  Args:
    types: A list of Typedef objects.
    structs: A list of Structure objects.
    typemap: A dict mapping type names to the corresponding object.
    commands: A list of Command objects.
  """
  out_file = open(_OUTPUT_FILE_CC, 'w')
  out_file.write(_COPYRIGHT_HEADER)
  out_file.write(_LOCAL_INCLUDE % {'filename': _OUTPUT_FILE_H})
  out_file.write(_IMPLEMENTATION_FILE_INCLUDES)
  out_file.write(_NAMESPACE_BEGIN)
  GenerateHandleCountFunctions(commands, out_file)
  serialized_types = set(_BASIC_TYPES)
  for basic_type in _BASIC_TYPES:
    out_file.write(_SERIALIZE_BASIC_TYPE % {'type': basic_type})
  for typedef in types:
    typedef.OutputSerialize(out_file, serialized_types, typemap)
  for struct in structs:
    struct.OutputSerialize(out_file, serialized_types, typemap)
  for command in commands:
    command.OutputSerializeFunction(out_file)
    command.OutputParseFunction(out_file)
    command.OutputErrorCallback(out_file)
    command.OutputResponseCallback(out_file)
    command.OutputMethodImplementation(out_file)
  out_file.write(_NAMESPACE_END)
  out_file.close()


def FormatFile(filename):
    subprocess.call(['clang-format', '-i', '-style=file', filename])


def main():
  """A main function.

  Both a TPM structures file and commands file are parsed and C++ header and C++
  implementation file are generated.

  Positional Args:
    structures_file: The extracted TPM structures file.
    commands_file: The extracted TPM commands file.
  """
  parser = argparse.ArgumentParser(description='TPM 2.0 code generator')
  parser.add_argument('structures_file')
  parser.add_argument('commands_file')
  args = parser.parse_args()
  structure_parser = StructureParser(open(args.structures_file))
  types, constants, structs, defines, typemap = structure_parser.Parse()
  command_parser = CommandParser(open(args.commands_file))
  commands = command_parser.Parse()
  GenerateHeader(types, constants, structs, defines, typemap, commands)
  GenerateImplementation(types, structs, typemap, commands)
  FormatFile(_OUTPUT_FILE_H)
  FormatFile(_OUTPUT_FILE_CC)
  print('Processed %d commands.' % len(commands))


if __name__ == '__main__':
  main()