Esempio n. 1
0
        } // GenStruct()

        void GenCommands()
        {
            string tpmComment =
                "The Tpm class provides Java functions to program a TPM.\n" +
                "<P>\n" +
                "The TPM spec defines TPM command with names like TPM2_PCR_Read().\n" +
                "The Java rendering of the spec drops the 'TPM2_' prefix: e.g. PCR_Read().\n" +
                "The Tpm and TpmBase classes also provide a few helper-functions: for example,\n" +
                "the command _allowErrors() tells to not throw an exception if the next\n" +
                "TPM command returns an error. Such helpers have names beginning with underscore '_'.\n" +
                "<P>\n" +
                "Tpm objects must be \"connected\" to a physical TPM or TPM simulator using the _setDevice()\n" +
                "method.  Some devices (like the TPM simulator) need to be configured before they can be used.\n" +
                "See the sample code that is part of the TSS.Java distribution for more information.";

            WriteComment(tpmComment);
            Write($"public class Tpm extends TpmBase");
            TabIn("{");
            foreach (var req in TpmTypes.Get <TpmStruct>().Where(s => s.Info.IsRequest()))
            {
                GenCommand(req);
            }

            InsertSnip("Tpm");
            TabOut("}", false);
        } // GenCommands()
Esempio n. 2
0
        } // GenStruct()

        void GenerateTpmCommandPrototypes()
        {
            // Command prototypes
            var commands = TpmTypes.Get <TpmStruct>().Where(s => s.Info.IsRequest());

            TabIn();
            foreach (TpmStruct s in commands)
            {
                GenCommand(s, CommandFlavor.Synch);
            }

            Write("class _DLLEXP_ AsyncMethods");
            Write("{");
            Write("protected: Tpm2& theTpm;");
            Write("public: AsyncMethods(Tpm2& _tpm) : theTpm(_tpm) {}");
            TabIn("public:");
            foreach (TpmStruct s in commands)
            {
                GenCommand(s, CommandFlavor.AsyncCommand);
            }
            foreach (TpmStruct s in commands)
            {
                GenCommand(s, CommandFlavor.AsyncResponse);
            }
            TabOut("};");

            TabOut("public:");
            TabIn();
            Write("AsyncMethods Async;");
            TabOut("};");
            Write("_TPMCPP_END");
        } // GenCommands()
Esempio n. 3
0
        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();
        }
Esempio n. 4
0
 static void FixTpm2bStructs()
 {
     foreach (var s in TpmTypes.Get <TpmStruct>().Where(s => s.Fields.Count == 2 && s.StripTypedefs().SpecName.StartsWith("TPM2B_")))
     {
         var tagField  = s.Fields[0];
         var dataField = s.Fields[1];
         if (tagField.MarshalType == MarshalType.ArrayCount)
         {
             // A TPM2B struct has a byte count as the first member that contains the size of the second member.
             // The second member can be either a byte buffer or a data structure. In the latter case the type
             // of the data structure can be obtained from the name of the TPM2B struct.
             string structName = s.SpecName.Replace("TPM2B_", "TPMS_");
             if (!TpmTypes.Contains(structName))
             {
                 continue;
             }
             dataField = s.Fields[1] =
                 new StructField(structName, dataField.Name, dataField.Comment);
         }
         tagField.MarshalType   = MarshalType.LengthOfStruct;
         dataField.MarshalType  = MarshalType.SizedStruct;
         tagField.SizedField    = dataField;
         dataField.SizeTagField = tagField;
         dataField.Domain       = tagField.Domain;
     }
 }
Esempio n. 5
0
        internal override void Generate()
        {
            WriteAutoGeneratedSourceHeader();
            Write("from .TpmStructure import *");
            Write("from .TpmEnum import *");
            Write("");

            // First generate enums
            foreach (var e in TpmTypes.Get <TpmEnum>())
            {
                GenEnum(e);
            }
            foreach (var b in TpmTypes.Get <TpmBitfield>())
            {
                GenBitfield(b);
            }

            Write("from .Crypt import *" + "\r\n");

            // Then generate unions and structures
            GenUnions();
            foreach (var s in TpmTypes.Get <TpmStruct>())
            {
                GenStruct(s);
            }

            File.WriteAllText(RootDir + "TpmTypes.py", GeneratedCode.ToString());
            GeneratedCode.Clear();

            // Now generate the TPM methods
            GenCommands();
            File.WriteAllText(RootDir + "Tpm.py", GeneratedCode.ToString());
            GeneratedCode.Clear();
        }
Esempio n. 6
0
        void GenerateTpmTypesHdr()
        {
            foreach (var e in TpmTypes.Get <TpmEnum>())
            {
                GenEnum(e);
            }

            foreach (var bf in TpmTypes.Get <TpmBitfield>())
            {
                GenBitfield(bf);
            }

            WriteComment(AsSummary("Base class for TPM union interfaces"));
            Write("class _DLLEXP_ TpmUnion: public virtual TpmStructure {};");

            foreach (var u in TpmTypes.Get <TpmUnion>())
            {
                GenUnion(u);
            }

            foreach (var s in TpmTypes.Get <TpmStruct>())
            {
                GenStructDecl(s);
            }

            Write("_TPMCPP_END");
        } // GenerateHeader()
Esempio n. 7
0
        void GenUnionFactory()
        {
            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("@SuppressWarnings(\"unchecked\")");
            Write("public static <U extends TpmUnion, S extends TpmEnum<S>>");
            Write("U create(String unionType, S selector) // S = TPM_ALG_ID | TPM_CAP | TPM_ST");
            TabIn("{");
            string elsePref = "";

            foreach (TpmUnion u in TpmTypes.Get <TpmUnion>())
            {
                TabIn($"{elsePref}if (unionType == \"{u.Name}\")");
                elsePref = "else ";
                TabIn($"switch ((({GetUnionSelectorType(u)})selector).asEnum()) {{");
                foreach (UnionMember m in u.Members)
                {
                    string newObj = m.Type.IsElementary() ? TargetLang.Null : $"new {m.Type.Name}()";
                    Write($"case {m.SelectorValue.Name}: return (U) {newObj};");
                }
                Write("default:");
                TabOut("}", false); // switch (selector)
                TabOut();           // if / else if
            }
            TabIn("else");
            Write("throw new RuntimeException(\"UnionFactory::Create(): Unknown union type \" + unionType);");
            TabOut("throw new RuntimeException(\"Unknown selector value \" + selector.toString() + \" for union \" + unionType);");
            TabOut("} // create()");
            TabOut("}; // class UnionFactory");
        }
Esempio n. 8
0
        /// <summary> This method is called before code generation for the given target
        /// language begins </summary>
        public static void SetTargetLang(Lang lang)
        {
            // This assertion will fail if a new target language is added to the Lang enum
            // without also adding the corresponding
            Debug.Assert(Enum.GetValues(typeof(Lang)).Length == CodeGenerators.Length + 2);

            _curLang    = lang;
            _thisQual   = DotNet || Cpp || Java ? "" : This + ".";
            _null       = Py ? "None" : Cpp ? "nullptr" : "null";
            _new        = DotNet || Java || Node ? "new " : "";
            _quote      = Py || Node ? "'" : "\"";
            _digestSize = Cpp ? "TPMT_HA::DigestSize" : "Crypto.digestSize";

            GeneratedEnums = new HashSet <TpmEnum>();

            // First translate names
            foreach (var t in TpmTypes.TheTypes)
            {
                t.Name = TranslateTypeName(t);
                if (t is TpmEnum)
                {
                    var e = t as TpmEnum;
                    foreach (var c in e.Members)
                    {
                        c.Name         = TransConstantName(c.SpecName, c.EnclosingEnum);
                        c.OldStyleName = TransConstantName(c.SpecName, c.EnclosingEnum, true);
                    }
                }
            }

            // Then translate expressions specifying enum member values.
            // Note that we cannot simply iterate TpmTypes.Constants, as in many languages
            // the order of enum definitions is important (tracked by GeneratedEnums()/IsGenerated()).
            foreach (var e in TpmTypes.Get <TpmEnum>())
            {
                // Take care
                Debug.Assert(!GeneratedEnums.Contains(e));
                GeneratedEnums.Add(e);
                foreach (var c in e.Members)
                {
                    c.Value = TranslateConstExpr(c.SpecValue, c.EnclosingEnum);
                }
            }

            // At last translate
            foreach (var s in TpmTypes.Get <TpmStruct>())
            {
                foreach (var f in s.Fields)
                {
                    f.TypeName = TranslateFieldType(f);
                }
            }
        }
Esempio n. 9
0
        /// <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()
Esempio n. 10
0
        } // GenStruct()

        void GenCommands()
        {
            WriteAutoGeneratedSourceHeader();
            Write("from .TpmBase import *" + "\r\n");

            Write($"class Tpm(TpmBase):");
            TabIn();
            foreach (var req in TpmTypes.Get <TpmStruct>().Where(s => s.Info.IsRequest()))
            {
                GenCommand(req);
            }
            TabOut();
            Write("# class Tpm");
        }
Esempio n. 11
0
        /// <summary>
        /// C unions of the TPM spec are translated into Python classes implementing
        /// an interface defining the union
        /// </summary>
        void GenUnions()
        {
            // Base class for union interfaces
            TabIn("class TpmUnion(TpmMarshaller):");
            WriteComment("TPM union interface");
            Write("@abc.abstractmethod");
            Write($"def GetUnionSelector({This}): pass  # returns TPM_ALG_ID | TPM_CAP | TPM_ST");
            TabOut("");

            // Union interfaces definitions
            var unions = TpmTypes.Get <TpmUnion>();

            foreach (TpmUnion u in unions)
            {
                TabIn($"class {u.Name}(TpmUnion):");
                WriteComment(u);
                Write("pass");
                TabOut("");
            }

            // Union factory
            TabIn("class UnionFactory:");
            Write("@staticmethod");
            TabIn("def create(unionType, selector):");
            WriteComment("Args:\n" +
                         "    unionType (string): union type name\n" +
                         "    selector (TPM_ALG_ID|TPM_CAP|TPM_ST): enum value\n" +
                         "        specifying the union member to instantiate");
            string elIf = "if";

            foreach (TpmUnion u in unions)
            {
                Write($"{elIf} unionType == '{u.Name}':");
                elIf = "elif";

                TabIn();
                foreach (UnionMember m in u.Members)
                {
                    string newObject = m.Type.IsElementary() ? TargetLang.Null : $"{m.Type.Name}()";
                    Write($"if selector == {m.SelectorValue.QualifiedName}: return {newObject}");
                }
                TabOut();
            }
            TabIn("else:");
            Write("raise(Exception('UnionFactory.create(): Unrecognized union type \"{}\"'.format(unionType)))");
            TabOut("raise(Exception('UnionFactory.create(): Unknown selector value \"{s}\" for union \"{u}\"'.format(s = str(selector), u = unionType)))");
            TabOut("# create()", false);
            TabOut("# class UnionFactory()");
        }
Esempio n. 12
0
        void GenUnions()
        {
            TpmUnion[] unions = TpmTypes.Get <TpmUnion>().ToArray();

            foreach (TpmUnion t in unions)
            {
                string selectorType = t.Members[0].SelectorValue.EnclosingEnum.Name;
                WriteComment(t);
                Write("public interface " + t.Name);
                TabIn("{");
                Write($"{selectorType} GetUnionSelector();");
                TabOut("}");
            }

            Write("public abstract partial class TpmStructureBase");
            TabIn("{");
            Write("Type UnionElementFromSelector(Type unionInterface, object selector)");
            TabIn("{");

            string elseClause = "";

            foreach (TpmUnion t in unions)
            {
                Write($"{elseClause}if (unionInterface == typeof({t.Name}))");
                TabIn("{");
                TpmEnum selectorType = null;
                foreach (UnionMember m in t.Members)
                {
                    if (selectorType == null)
                    {
                        selectorType = m.SelectorValue.EnclosingEnum;
                        Write($"switch (({selectorType.Name})selector)");
                        TabIn("{");
                    }
                    Debug.Assert(selectorType == m.SelectorValue.EnclosingEnum);
                    Write($"case {m.SelectorValue.QualifiedName}: return typeof({m.Type.Name});");
                }
                TabOut("}", false);     // switch
                TabOut("}", false);     // else if
                elseClause = "else ";
            }
            Write("else");
            TabIn("{");
            Write("throw new Exception(\"Unknown union interface type \" + unionInterface.Name);");
            TabOut("}", false); // else
            Write("throw new Exception(\"Unknown selector value\" + selector + \" for \" + unionInterface.Name +  \" union\");");
            TabOut("}", false); // UnionElementFromSelector
            TabOut("}");        // TpmStructureBase
        } // GenUnions()
Esempio n. 13
0
        } // 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()
Esempio n. 14
0
        static List <TpmStruct> GetUnionMemberStructures(UnionField uf)
        {
            var unionList = new List <TpmStruct>();

            foreach (var s in TpmTypes.Get <TpmStruct>().Where(s => !s.IsCmdStruct()))
            {
                foreach (TpmUnion u in s.ContainingUnions)
                {
                    if (u.Name == uf.TypeName)
                    {
                        unionList.Add(s);
                    }
                }
            }
            return(unionList);
        }
Esempio n. 15
0
        } // GenMarshalingMethod()

        // Generates implementation of the TPM structures methods
        void GenStructsCpp()
        {
            foreach (var s in TpmTypes.Get <TpmStruct>())
            {
                if (IsTypedefStruct(s))
                {
                    continue;
                }

                // Marshaling
                GenMarshalingMethod(true, s);
                GenMarshalingMethod(false, s);
                GenMarshalingMethod(true, s, false, true);
                GenMarshalingMethod(false, s, false, true);
            }
        } // GenStructsCpp()
Esempio n. 16
0
        public static void DoFixups()
        {
            // Many TPM structs represent a length-prefixed array or structure.
            // When such struct is a fields of another (enclosing) structure, get rid of the struct
            // wrapper and place the payload array/struct directly as the member of the enclosing struct.
            FixTpm2bStructs();
            FlattenTaggedStructures();
            FixStructsWithEncryptedBuffer();
            FlattenLists();

            // This command allows session based encryption.
            foreach (var s in TpmTypes.Get <TpmStruct>().Where(s => s.IsCmdStruct()))
            {
                if (s.Fields.Count > s.NumHandles &&
                    s.Fields[s.NumHandles].MarshalType.IsOneOf(MarshalType.ArrayCount, MarshalType.LengthOfStruct))
                {
                    // This command allows session based encryption.
                    Debug.Assert(s.Fields.Count > s.NumHandles + 1);
                    var sizeField  = s.Fields[s.NumHandles];
                    var sizedField = s.Fields[s.NumHandles + 1];
                    var cmdInfo    = s.Info as CmdStructInfo;
                    cmdInfo.SessEncSizeLen = sizeField.Type.GetSize();
                    cmdInfo.SessEncValLen  = sizeField.MarshalType == MarshalType.LengthOfStruct
                                          ? 1 : sizedField.Type.GetSize();
                }
            }

            TpmStruct[] symDefs = { (TpmStruct)TpmTypes.Lookup("TPMT_SYM_DEF"),
                                    (TpmStruct)TpmTypes.Lookup("TPMT_SYM_DEF_OBJECT") };
            var         fieldTypes = new string[] { "TPM_ALG_ID", "UINT16", "TPM_ALG_ID" };

            Debug.Assert(symDefs[0].Fields.Count == symDefs[1].Fields.Count &&
                         symDefs[0].Fields.Count == fieldTypes.Length);

            for (int i = 0; i < fieldTypes.Length; ++i)
            {
                foreach (var sd in symDefs)
                {
                    sd.Fields[i].MarshalType = MarshalType.Normal;
                    sd.Fields[i].Type        = TpmTypes.Lookup(fieldTypes[i]);
                }
            }
            symDefs[0].Fields[0].Attrs = symDefs[1].Fields[0].Attrs |= StructFieldAttr.TermOnNull;

            FixEnumTypeCollisions();
        }
Esempio n. 17
0
        } // GenStructsCpp()

        void GenCommandDispatchers()
        {
            var cmdRequestStructs = TpmTypes.Get <TpmStruct>().Where(s => s.Info.IsRequest());

            foreach (var s in cmdRequestStructs)
            {
                GenCommandDispatcher(s, CommandFlavor.Synch);
            }
            foreach (var s in cmdRequestStructs)
            {
                GenCommandDispatcher(s, CommandFlavor.AsyncCommand);
            }
            foreach (var s in cmdRequestStructs)
            {
                GenCommandDispatcher(s, CommandFlavor.AsyncResponse);
            }
        } // GenCommandDispatchers()
Esempio n. 18
0
        internal override void Generate()
        {
            // Go through the types generating code
            foreach (var t in TpmTypes.Get <TpmType>())
            {
                if (t is TpmEnum)
                {
                    GenEnum(t as TpmEnum);
                }
                else if (t is TpmBitfield)
                {
                    GenBitfield(t as TpmBitfield);
                }
                else if (t is TpmUnion)
                {
                    GenUnion(t as TpmUnion);
                }
                else if (t is TpmStruct)
                {
                    GenStruct(t as TpmStruct);
                }
                else
                {
                    continue;
                }

                string typeName = t.Name;
                WriteDef(GetJavaFileName(typeName), null, false);
            }

            GenUnionFactory();
            WriteDef(GetJavaFileName("UnionFactory"), null, false);

            // Now generate the TPM methods
            GenCommands();
            WriteDef(GetJavaFileName(), null, true);

            foreach (var t in TpmTypes.TheTypes.Where(t => !t.Implement))
            {
                string typeName = t.Name;
                File.Delete(GetJavaFileName(typeName));
            }
        }
Esempio n. 19
0
        } // GenEnumMap()

        void GenUnionFactory()
        {
            var unions = TpmTypes.Get <TpmUnion>();

            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("struct UnionFactory");
            TabIn("{");
            WriteComment("Creates specific TPM union member based on the union type and selector (tag) value");
            Write("template<class U, typename S>");
            Write("static void Create(shared_ptr<U>& u, S selector) // S = TPM_ALG_ID | TPM_CAP | TPM_ST");
            TabIn("{");
            Write("size_t unionType = typeid(U).hash_code();");

            string elsePref = "";

            foreach (TpmUnion u in unions)
            {
                TabIn($"{elsePref}if (unionType == typeid({u.Name}).hash_code())");
                elsePref = "else ";
                TabIn("switch (selector) {");
                foreach (UnionMember m in u.Members)
                {
                    //if (m.SelectorValue.Name.StartsWith("TPM_ALG_ANY")) continue;
                    string newObj = m.Type.IsElementary() ? "nullptr" : $"new {m.Type.Name}()";
                    Write($"case {m.SelectorValue.QualifiedName}: new (&u) shared_ptr<{u.Name}>({newObj}); return;");
                }
                TabOut("}", false); // switch (selector)
                TabOut();           // if / else if
            }
            TabIn("else");
            Write("throw runtime_error(\"UnionFactory::Create(): Unknown union type \" + string(typeid(U).name()));");
            TabOut("throw runtime_error(\"Unknown selector value\" + to_string(selector) + \" for union \" + string(typeid(U).name()));");
            TabOut("} // Create()");
            TabOut("}; // class UnionFactory");
        }
Esempio n. 20
0
        internal override void Generate()
        {
            // Order of the next two calls is important!
            TweakSymDefStructFieldNames(true);

            Write("using System;");
            Write("using System.Runtime.Serialization;");
            Write("using System.Diagnostics.CodeAnalysis;");
            Write("");
            Write("namespace Tpm2Lib");
            TabIn("{");

            foreach (var e in TpmTypes.Get <TpmEnum>())
            {
                GenEnum(e);
            }
            foreach (var bf in TpmTypes.Get <TpmBitfield>())
            {
                GenBitfield(bf);
            }
            GenUnions();
            foreach (var s in TpmTypes.Get <TpmStruct>())
            {
                GenStructure(s);
            }

            GenCommands();
            GenHandleTable();

            TabOut("}");

            File.WriteAllText(FileName, GeneratedCode.ToString(), Encoding.ASCII);

            // Write custom dictionary (for FxCop)
            StreamWriter dict = new StreamWriter("CustomDictionary.xml");

            dict.WriteLine("<Dictionary>\n<Words>\n<Recognized>");
            foreach (TpmType tp in TpmTypes.TheTypes)
            {
                dict.WriteLine($"<Word>\"{tp.Name}\"</Word>");
            }
            foreach (var s in TpmTypes.Get <TpmStruct>())
            {
                foreach (var f in s.Fields)
                {
                    dict.WriteLine($"<Word>{f.Name}</Word>");
                }
            }
            foreach (var c in TpmTypes.Constants)
            {
                dict.WriteLine($"<Word>{c.Name}</Word>");
            }
            dict.WriteLine("</Recognized>\n</Words>\n");

            dict.WriteLine("<Acronyms>\n<CasingExceptions>\n");
            foreach (var s in TpmTypes.Get <TpmStruct>())
            {
                foreach (var f in s.Fields.Where(f => char.IsLower(f.Name[0])))
                {
                    dict.WriteLine($"<Acronym>{f.Name}</Acronym>");
                }
            }
            foreach (var c in TpmTypes.Constants)
            {
                string constName = c.Name;
                if (char.IsUpper(constName[0]))
                {
                    continue;
                }
                dict.WriteLine($"<Acronym>{constName}</Acronym>");
            }
            foreach (string bf in autoGenBitfieldNames)
            {
                if (char.IsUpper(bf[0]))
                {
                    continue;
                }
                dict.WriteLine($"<Acronym>{bf}</Acronym>");
            }

            // extra acronyms
            var ea = new string[] { "TPM", "Nv", "Hr", "Pt", "Ht", "Cc", "Se", "Rc", "Eo", "Pt", "St", "Rh", "Ex", "Cp",
                                    "Eh", "Sh", "Ph", "Id", "nv", "Eo", "Gt", "Ge", "Lt", "Le", "Cp", "id", "KDFa" };

            foreach (string a in ea)
            {
                dict.WriteLine($"<Acronym>{a}</Acronym>");
            }
            dict.WriteLine("</CasingExceptions>\n</Acronyms>\n");
            dict.WriteLine("</Dictionary>");
            dict.Flush();
            dict.Close();

            // Undo DotNet specific tweaks
            TweakSymDefStructFieldNames(false);
        }
Esempio n. 21
0
        void GenCommands()
        {
            Write("//-----------------------------------------------------------------------------");
            Write("//------------------------- COMMANDS -----------------------------------------");
            Write("//-----------------------------------------------------------------------------");
            Write("");
            Write("public partial class Tpm2");
            TabIn("{");

            foreach (var req in TpmTypes.Get <TpmStruct>().Where(s => s.Info.IsRequest()))
            {
                string cmdName    = GetCommandName(req);
                var    resp       = GetRespStruct(req);
                var    reqFields  = req.NonTagFields;
                var    respFields = resp.NonTagFields;

                string outputType    = "void";
                int    numRespParams = respFields.Count();
                if (respFields.Count() != 0)
                {
                    if (respFields.Last().Name == "name")
                    {
                        --numRespParams;
                    }

                    outputType = respFields[0].TypeName;
                }

                string annotation = req.Comment + "\n\n";
                foreach (var f in reqFields)
                {
                    annotation += GetParamComment(f) + "\n";
                }
                annotation += GetReturnComment(respFields);
                WriteComment(annotation, false);

                // commmand prototype + parameters

                string transCmdName = TargetLang.NameToDotNet(cmdName);

                Write("[TpmCommand]");
                TabIn($"public {outputType} {transCmdName}(");
                bool printComma = false;
                foreach (StructField f in reqFields)
                {
                    WriteComma(ref printComma);
                    Write($"{f.TypeName} {f.Name}", false);
                }
                for (int i = 1; i < numRespParams; ++i)
                {
                    var f = respFields[i];
                    WriteComma(ref printComma);
                    Write($"out {f.TypeName} {f.Name}", false);
                }
                TabOut(")");
                TabIn("{");

                // Create input struct
                string reqStructInitList = string.Join(", ", reqFields.Select(f => f.Name));
                Write($"var req = new {req.Name}({reqStructInitList});");

                // Dispatch the command
                string respType = !resp.Implement ? "EmptyResponse" : resp.Name;
                Write($"var resp = new {respType}();");
                Write($"DispatchMethod(TpmCc.{transCmdName}, req, resp, {req.NumHandles}, {resp.NumHandles});");

                if (numRespParams > 0)
                {
                    if (numRespParams == 1)
                    {
                        Write($"return resp.{respFields[0].Name};");
                    }
                    else
                    {
                        // Set the return parameters
                        for (int i = 1; i < numRespParams; ++i)
                        {
                            string rfName = respFields[i].Name;
                            Write($"{rfName} = resp.{rfName};");
                        }
                        Write($"return resp.{respFields[0].Name};");
                    }
                }
                TabOut("}");
                continue;
            }
            TabOut("}");
        } // GenCommands()
Esempio n. 22
0
        void GenHandleTable()
        {
            Write("//-----------------------------------------------------------------------------");
            Write("//------------------------- COMMAND INFO -----------------------------------");
            Write("//-----------------------------------------------------------------------------");
            Write("public static class CommandInformation");
            TabIn("{");
            Write("public static CommandInfo[] Info = new CommandInfo[]");
            TabIn("{");
            bool printComma = false;

            foreach (var req in TpmTypes.Get <TpmStruct>().Where(s => s.Info.IsRequest()))
            {
                TpmStruct resp          = GetRespStruct(req);
                string    cmdName       = GetCommandName(req);
                string    transCmdName  = TargetLang.TypeToDotNet(cmdName);
                string    reqStructName = "Tpm2" + transCmdName + "Request";

                // encryptable parms?
                ParmCryptInfo cryptInfo = 0;

                if (req.Fields.Count > req.NumHandles)
                {
                    // find the first field that is not a handle
                    StructField parm0 = req.Fields[req.NumHandles];
                    if (parm0.MarshalType.IsOneOf(MarshalType.LengthOfStruct, MarshalType.ArrayCount))
                    {
                        string typeName = parm0.Type.StripTypedefs().Name;
                        if (typeName == "uint")
                        {
                            cryptInfo |= ParmCryptInfo.EncIn4;
                        }
                        else if (typeName == "ushort")
                        {
                            cryptInfo |= ParmCryptInfo.Enc2In2;
                        }
                    }
                }
                if (resp.Fields.Count > resp.NumHandles)
                {
                    // find the first field that is not a handle
                    StructField parm0 = resp.Fields[resp.NumHandles];
                    if (parm0.MarshalType.IsOneOf(MarshalType.LengthOfStruct, MarshalType.ArrayCount))
                    {
                        string typeName = parm0.Type.StripTypedefs().Name;
                        if (typeName == "uint")
                        {
                            cryptInfo |= ParmCryptInfo.DecOut4;
                        }
                        else if (typeName == "ushort")
                        {
                            cryptInfo |= ParmCryptInfo.DecOut2;
                        }
                    }
                }

                string handleTypeNames = "";
                // types of input handles
                if (req.NumHandles > 0)
                {
                    for (int j = 0; j < req.NumHandles; j++)
                    {
                        StructField hField         = req.Fields[j];
                        string      origHandleType = hField.Type.SpecName;
                        handleTypeNames += origHandleType + " ";
                        TpmType tpx = TpmTypes.Lookup(origHandleType);
                    }
                }
                handleTypeNames = handleTypeNames.TrimEnd(new char[] { ' ' });
                handleTypeNames = "\"" + handleTypeNames + "\"";

                string respTypeId = !resp.Implement ? "EmptyResponse"
                                  : resp.Name;

                WriteComma(ref printComma);
                Write($"new CommandInfo(TpmCc.{transCmdName}, {req.NumHandles}, {resp.NumHandles}, {req.NumAuthHandles}, " +
                      $"typeof({reqStructName}), typeof({respTypeId}), {(uint)cryptInfo}, {handleTypeNames})", false);
            }
            TabOut("};");
            TabOut("}");
        }