forked from microsoft/TSS.MSR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCGenNode.cs
421 lines (371 loc) · 16.2 KB
/
CGenNode.cs
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
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See the LICENSE file in the project root for full license information.
*/
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
namespace CodeGen
{
/// <summary> Node.js TSS code generator </summary>
class CGenNode : CodeGenBase
{
public CGenNode(string rootDir) : base(rootDir + @"src\", "TpmExtensions.js.snips") {}
void WriteAutoGeneratedSourceHeader()
{
TpmNamedConstant ver = TpmTypes.LookupConstant("TPM_SPEC_VERSION");
Write("/* \r\n" +
" * Copyright(c) Microsoft Corporation. All rights reserved. \r\n" +
" * Licensed under the MIT License. \r\n" +
" * See the LICENSE file in the project root for full license information. \r\n" +
" */\r\n" +
"\r\n" +
"/*\r\n" +
" * This file is automatically generated from the TPM 2.0 rev. " +
(ver.NumericValue / 100.0).ToString("0.00") + " specification documents.\r\n" +
" * Do not edit it directly.\r\n" +
" */\r\n" +
"\r\n");
}
internal override void Generate()
{
WriteAutoGeneratedSourceHeader();
Write("import { TpmMarshaller, TpmBuffer } from \"./TpmMarshaller.js\";\r\n" +
"import { TpmStructure, ReqStructure, RespStructure, SessEncInfo } from \"./TpmStructure.js\";\r\n" +
"\r\n" +
"import { Crypto } from \"./Crypt.js\";\r\n" +
"\r\n");
// First generate enums
foreach (var e in TpmTypes.Get<TpmEnum>())
GenEnum(e);
foreach (var b in TpmTypes.Get<TpmBitfield>())
GenBitfield(b);
// Then generate unions and structures
GenUnions();
foreach (var s in TpmTypes.Get<TpmStruct>())
GenStruct(s);
File.WriteAllText(RootDir + "TpmTypes.ts", GeneratedCode.ToString());
GeneratedCode.Clear();
// Now generate the TPM methods
GenCommands();
File.WriteAllText(RootDir + "Tpm.ts", GeneratedCode.ToString());
GeneratedCode.Clear();
}
void GenEnum(TpmType e, List<TpmNamedConstant> elements)
{
WriteComment(e);
Write($"export enum {e.Name} // {e.UnderlyingType.SpecName}");
TabIn("{");
foreach (var elt in elements)
{
// Skip TPM_RC.H enumerator (an alias hiding SUCCESS value)
if (elt.Name == "H")
continue;
string sep = Separator(elt, elements);
WriteComment(elt);
Write($"{elt.Name} = {elt.Value}{sep}");
// Backward compat
if (elt.Name == "PW")
{
WriteComment("@deprecated Use TPM_RH.PW instead");
Write($"RS_PW = {elt.Value},");
}
if (sep != "")
Write("");
}
string type = e is TpmEnum ? "enum" : "bitfield";
TabOut($"}}; // {type} {e.Name}");
} // GenEnum()
void GenEnum(TpmEnum e)
{
GenEnum(e, e.Members);
}
void GenBitfield(TpmBitfield bf)
{
GenEnum(bf, GetBifieldElements(bf));
}
/// <summary>
/// C unions of the TPM spec are translated into TypeScript classes implementing
/// an interface defining the union
/// </summary>
void GenUnions()
{
var unions = TpmTypes.Get<TpmUnion>();
WriteComment("Base class for TPM union interfaces");
Write("export interface TpmUnion extends TpmMarshaller {}");
//
// Union interfaces definitions
//
foreach (TpmUnion u in unions)
{
WriteComment(u);
Write($"export interface {u.Name} extends TpmUnion");
TabIn("{");
Write($"GetUnionSelector(): {GetUnionSelectorType(u)};");
TabOut("}");
}
//
// Union factory
//
WriteComment("Holds static factory method for instantiating TPM unions.\n" +
"Note: A wrapper class is used instead of simply static function solely " +
"for the sake of uniformity with languages like C# and Java.");
Write("class UnionFactory");
TabIn("{");
WriteComment("Creates specific TPM union member based on the union type and selector (tag) value");
Write("public static create(unionType: string, selector: TPM_ALG_ID | TPM_CAP | TPM_ST): any");
TabIn("{");
Write("switch (unionType) {");
foreach (TpmUnion u in unions)
{
TabIn($"case '{u.Name}':");
TabIn("switch (selector) {");
foreach (UnionMember m in u.Members)
{
string newObject = m.Type.IsElementary() ? TargetLang.Null : $"new {m.Type.Name}()";
Write($"case {m.SelectorValue.QualifiedName}: return {newObject};");
}
TabOut("}", false); // inner switch
Write("break;");
TabOut();
}
TabIn("default:");
Write("throw new Error('UnionFactory.create(): Unknown union type ' + unionType);");
TabOut("}"); // outer switch
Write("throw new Error('Unknown selector value ' + selector + ' for union ' + unionType);");
TabOut("} // create()", false);
TabOut("} // class UnionFactory");
} // GenUnions()
void GenGetUnionSelector(TpmStruct s)
{
string selType = GetUnionMemberSelectorInfo(s, out string selVal);
if (selType != null)
{
WriteComment("TpmUnion method");
Write($"GetUnionSelector(): {selType} {{ return {selVal}; }}");
}
}
public void GenMarshalingMethod(bool dirTo, TpmStruct s)
{
var fields = s.MarshalFields;
if (s.DerivedFrom != null || fields.Count() == 0)
return;
string dir = dirTo ? "to" : "initFrom",
proto = $"{dir}Tpm(buf: TpmBuffer): void";
var marshalOps = dirTo ? GetToTpmFieldsMarshalOps(fields)
: GetFromTpmFieldsMarshalOps(fields);
WriteComment("TpmMarshaller method");
if (marshalOps.Count == 1)
{
// Lay it out in a single line
Write($"{proto} {{ {marshalOps[0]}; }}");
}
else
{
Write(proto);
TabIn("{");
foreach (var op in marshalOps)
Write($"{op};");
TabOut("}", false);
}
} // GenMarshalingMethod()
/// <summary>
/// Structures in C are classes in TypeScript
/// </summary>
/// <param name="s"></param>
void GenStruct(TpmStruct s)
{
bool hasBase = s.DerivedFrom != null;
string className = s.Name;
string classBases = hasBase ? s.DerivedFrom.Name
: !s.IsCmdStruct() ? "TpmStructure"
: s.Info.IsRequest() ? "ReqStructure" : "RespStructure";
// If this struct is not derived from another one and is a member of one or more unions,
// it must implement the corresponding union interfaces
if (!s.IsCmdStruct() && !hasBase)
{
string unionInterfaces = string.Join(", ", s.ContainingUnions.Select(u => u.Name));
if (unionInterfaces != "")
classBases += " implements " + unionInterfaces;
}
// Javadoc comment for the data structure
WriteComment(s);
// Class header
Write($"export class {className} extends {classBases}");
TabIn("{");
// In TypeScript, member fields declaration is melded with member-wise constructor
// that also playe the role of the default one
//
// Field defining constructor
//
var fields = s.FieldHolder.NonTagFields;
if (fields.Count() == 0)
Write("constructor() { super(); }");
else
{
Write("constructor(");
TabIn();
// If a non-trivial base class is present, all member fields are contained there,
// so just pass through the initialization parameters
string ctrParamQualifier = hasBase ? "" : "public ";
string baseIntializers = "";
foreach (var f in fields)
{
// Javadoc comment for the member/constructor parameter.
// Add a list of data structures implementing the interface of a union parameters.
WriteComment(f);
string comma = Separator(f, fields, ", ");
Write($"{ctrParamQualifier}{f.Name}: {f.TypeName} = {f.GetInitVal()}{comma}");
if (hasBase)
baseIntializers += f.Name + comma;
}
TabOut($") {{ super({baseIntializers}); }}");
//
// Named union tag getters (instead of the corresponding fields in the TPM 2.0 spec)
//
foreach (var sel in s.TagFields)
{
if (sel.MarshalType != MarshalType.UnionSelector)
continue;
var u = (TpmUnion)sel.RelatedUnion.Type;
string unionField = ThisMember + sel.RelatedUnion.Name;
WriteComment(sel);
Write($"get {sel.Name}(): {sel.TypeName} {{ ", false);
if (u.NullSelector == null)
Write($"return {unionField}.GetUnionSelector(); }}");
else
{
Write($"return {unionField} ? {unionField}.GetUnionSelector()" +
$" : {u.NullSelector.QualifiedName}; }}");
}
}
}
//
// Union interface: TpmUnion.GetUnionSelector()
//
GenGetUnionSelector(s);
//
// Marshaling
//
GenMarshalingMethod(true, s);
GenMarshalingMethod(false, s);
WriteComment("Static marshaling helper");
Write($"public static fromTpm(buf: TpmBuffer) : {className}");
TabIn("{");
Write($"return buf.createObj({className});");
TabOut("}");
WriteComment("Static marshaling helper");
Write($"public static fromBytes(buffer: any) : {className}");
TabIn("{");
Write($"return new TpmBuffer(buffer).createObj({className});");
TabOut("}");
var info = s.IsCmdStruct() ? s.Info as CmdStructInfo : null;
if (info != null && (info.NumHandles != 0 || info.SessEncSizeLen != 0))
{
if (info.NumHandles != 0)
{
Write($"numHandles(): number {{ return {info.NumHandles}; }}");
if (info.IsRequest())
{
string handles = string.Join(", ", s.Fields.Take(info.NumHandles).Select(f => ThisMember + f.Name));
Write($"numAuthHandles(): number {{ return {info.NumAuthHandles}; }}");
Write($"getHandles(): TPM_HANDLE[] {{ return [{handles}]; }}");
}
else
{
Debug.Assert(info.NumHandles == 1 && info.NumAuthHandles == 0);
Write($"getHandle(): TPM_HANDLE {{ return {ThisMember}{s.Fields[0].Name}; }}");
Write($"setHandle(h: TPM_HANDLE): void {{ {ThisMember}{s.Fields[0].Name} = h; }}");
}
}
if (info.SessEncSizeLen != 0)
{
Debug.Assert(info.SessEncValLen != 0);
Write("");
Write($"sessEncInfo(): SessEncInfo {{ return new SessEncInfo({info.SessEncSizeLen}, {info.SessEncValLen}); }}");
}
}
//
// Custom members
//
InsertSnip(s.Name);
TabOut($"}} // {className}");
} // GenStruct()
void GenCommands()
{
WriteAutoGeneratedSourceHeader();
Write( "import * as tt from \"./TpmTypes.js\";\r\n" +
"import { TpmBase, TpmError } from \"./TpmBase.js\";\r\n" +
"import { TpmBuffer } from \"./TpmMarshaller.js\";\r\n" +
"\r\n");
Write($"export class Tpm extends TpmBase");
TabIn("{");
foreach (var req in TpmTypes.Get<TpmStruct>().Where(s => s.Info.IsRequest()))
{
GenCommand(req);
}
TabOut("} // class Tpm", false);
} // GenCommands()
void GenCommand(TpmStruct req)
{
const string NS = "tt.";
var resp = GetRespStruct(req);
var cmdName = GetCommandName(req);
string respType = NS + resp.Name;
string cmdCode = NS + "TPM_CC." + cmdName;
var fields = req.NonTagFields;
var respFields = resp.NonTagFields;
if (ForceJustOneReturnParm.Contains(cmdName))
respFields = respFields.Take(1).ToArray();
int numOutParms = respFields.Count();
string returnType = numOutParms == 1 ? NsQualifiedType(respFields[0], NS)
: numOutParms == 0 ? "void" : respType;
// javadoc annotation
string annotation = req.Comment + eol + eol;
foreach (var f in fields)
annotation += GetParamComment(f) + eol;
annotation += GetReturnComment(respFields);
WriteComment(annotation);
// method definition
string paramList = "";
string reqStructInitList = "";
foreach (var f in fields)
{
string parmTypeName = NsQualifiedType(f, NS);
string comma = Separator(f, fields, ", ");
paramList += f.Name + ": " + parmTypeName + ", ";
reqStructInitList += f.Name + comma;
}
var indent = new string(' ', cmdName.Length + 2);
string respParams = returnType == null ? "" : "res?: " + returnType;
if (paramList != "")
{
Write($"{cmdName}({paramList}");
Write($"{indent}continuation: (err: TpmError, {respParams}) => void)");
}
else
Write($"{cmdName}(continuation: (err: TpmError, {respParams}) => void)");
Write("{");
TabIn();
Write($"let req = new {NS}{req.Name}({reqStructInitList});");
Write($"{ThisMember}dispatchCommand({cmdCode}, req, (respBuf: TpmBuffer): void => {{");
respType = numOutParms > 0 ? ", " + respType : "";
Write($"let res = {ThisMember}processResponse(respBuf{respType});");
string res = "",
resField = "";
if (numOutParms > 0)
{
res = ", res";
if (numOutParms == 1)
resField = $"?.{respFields[0].Name}";
}
Write($"setImmediate(continuation, {ThisMember}lastError{res}{resField}); }});");
TabOut($"}} // {cmdName}()");
} // GenCommand()
protected override void WriteComment(string comment, bool wrap = true)
{
WriteComment(comment, "/** ", " * ", "\n */", wrap);
}
} // class CGenNode
}