예제 #1
0
        internal static string GetParamsList(object[] parms, string eol)
        {
            if (parms == null)
            {
                return("");
            }

            string parmsText = "";

            foreach (Object o in parms)
            {
                if (o is TestCaseInfo)
                {
                    // Formerly this parameter contained an exception object,
                    // information from which is now encapsulated in 'c'.
                    continue;
                }
                else if (o is byte[])
                {
                    parmsText += Globs.HexFromByteArray((byte[])o);
                }
                else
                {
                    parmsText += o;
                }
                parmsText += eol;
            }

            return(parmsText);
        }
예제 #2
0
        internal void NotifyData(TcpTpmDevice.CommsSort sort,
                                 TcpTpmDevice.Channel channel, byte[] inOrOutData)
        {
            // Note - a complexity is that there can be two NotifyData per TCP read,
            // because we need to do a Read(len) followed by a Read(data)

            if (!logging || !PhaseToLog)
            {
                return;
            }

            lock (notifyLock)
            {
                if ((sort != lastSort) || (channel != lastChannel))
                {
                    log.WriteLine("");
                    string t = channel.ToString()[0] + " ";
                    t += (sort == TcpTpmDevice.CommsSort.ByteSent) ? "S" : "R";
                    t += " ";
                    log.Write(t);
                }
                lastSort    = sort;
                lastChannel = channel;
                log.Write(Globs.HexFromByteArray(inOrOutData));
            }
        }
예제 #3
0
        internal void GenerateWLKReport(ref int Run, ref int Fail, ref int Success, bool PassFailedTests)
        {
            foreach (TestCaseInfo c in CumulativeFailures)
            {
                string parmsText = "";

                // >>> write parms
                if (c.Parms != null)
                {
                    foreach (Object o in c.Parms)
                    {
                        if (o is TestCaseInfo)
                        {
                            // Formerly this parameter contained an exception object,
                            // information from which is now encapsulated in 'c'.
                            continue;
                        }
                        else if (o is Enum)
                        {
                            parmsText += Enum.GetName(o.GetType(), o) + " : ";

                            bool  first  = true;
                            Enum  e      = o as Enum;
                            Array values = Enum.GetValues(o.GetType());

                            foreach (Enum v in values)
                            {
                                if (e.HasFlag(v))
                                {
                                    if (!first)
                                    {
                                        parmsText += " | ";
                                    }
                                    else
                                    {
                                        first = false;
                                    }
                                    parmsText += Enum.GetName(o.GetType(), v);
                                }
                            }
                        }
                        else if (o is byte[])
                        {
                            parmsText += Globs.HexFromByteArray((byte[])o);
                        }
                        else
                        {
                            parmsText += o.ToString();
                        }
                        parmsText += "<p>";
                    }
                }
                else
                {
                    parmsText = "<br>";
                }

                string details = c.Message + "\n"
                                 + c.Location + "\n"
                                 + "Parameters:\n" + parmsText
                                 + (string.IsNullOrEmpty(c.RngSeed) ? ""
                                    : "To reproduce use option: -seed " + c.RngSeed + "\n");
                details.Replace("\r", "");

                string errorText = c.TestCase.Replace(":", " : ") + ";\n" + details;
                // c.StackTrace.Replace("\r", "");

                WriteToWLKLog(errorText, TestResult.Failed, PassFailedTests);
            }

            // ================  ABORTED CASES SECTION ==========================
            foreach (var item in AbortedTests)
            {
                string errorText = "TestCaseInfo:" + item.Key + " aborted because: "
                                   + GetAbortReasonMessage(item.Value);
                if (item.Value.reason == AbortReason.BlockedCommand)
                {
                    WriteToWLKLog(errorText, TestResult.NotRun, PassFailedTests);
                }
                else
                {
                    WriteToWLKLog(errorText, TestResult.Failed, PassFailedTests);
                }
            }

            // ================  COMMAND STATS SECTION ==========================
            Log.Comment(string.Format("Total TPM command count: {0}", TotalNumCommands));

            string successfulCommands = "Commands executed: ";
            var    sortedStats        = CumulativeCmdStats.OrderBy(item => item.Key.ToString());

            //var sortedStats = CumulativeCmdStats;
            foreach (var item in sortedStats)
            {
                CommandStats stat = item.Value;
                successfulCommands += item.Key + " (" + stat.NumSuccess + ") ";
            }
            Log.Comment(successfulCommands);
            WriteToLog(successfulCommands);

            // commands not executed -
            List <TpmCc> notExecuted = new List <TpmCc>();

            foreach (var c in CommandInformation.Info)
            {
                int num = sortedStats.Sum(y => (y.Key == c.CommandCode) ? 1 : 0);
                if (num == 0 && TestCategorizer.CommandDefinedForMinTpm(c.CommandCode))
                {
                    Log.Comment("Command " + c.CommandCode + " not executed.");
                }
            }

            // ================  TEST ROUTINE STATS SECTION ==========================
            int totalTestRoutineCount = this.TestRoutinesStats.Sum(item =>
                                                                   item.Value.NumAborted + item.Value.NumFailed + item.Value.NumSuccess);
            var sortedTestStats = TestRoutinesStats.OrderByDescending(item => item.Value.NumFailed);

            foreach (var item in sortedTestStats)
            {
                if (item.Value.NumFailed == 0)
                {
                    break;  // no more failures
                }
                WriteToWLKLog(string.Format("{0} failed.", item.Key),
                              TestResult.Failed, PassFailedTests);
                Fail++;
            }
            sortedTestStats = TestRoutinesStats.OrderByDescending(item => item.Value.NumSuccess);
            foreach (var item in sortedTestStats)
            {
                if (item.Value.NumSuccess == 0)
                {
                    break;  // no more failures
                }
                Verify.IsTrue(true, item.Key);
                WriteToLog("{0} passed.", item.Key);
                Success++;
            }
            foreach (var item in sortedTestStats)
            {
                TestStats stat = item.Value;
                if (stat.NumSuccess == 0 && stat.NumFailed == 0)
                {
                    Log.Result(TestResult.NotRun, string.Format("{0} not run.", item.Key));
                    Run++;
                }
            }
        }
예제 #4
0
        // This is installed as the raw command callback handler on the underlying TPM.
        // It is used to generate low-level test statistics (number of commands executed,
        // etc.), dumps of the conversation with the TPM and to keep a record of all
        // command sequences seen that contain types that we haven't seen before.
        // In the case of a multi-context TPM this will be called on different threads,
        // but locking should be handled safely by MainTestLogger.
        void ICommandCallbacks.PostCallback(byte[] inBuf, byte[] outBuf)
        {
            TimeSpan cmdExecutionTime = DateTime.Now - CurCmdStartTime;

            if (inBuf.Length < 10)
            {
                return;
            }
            Marshaller m           = new Marshaller(inBuf);
            TpmSt      sessionTag  = m.Get <TpmSt>();
            uint       parmSize    = m.Get <UInt32>();
            TpmCc      commandCode = m.Get <TpmCc>();

            if (commandCode == TpmCc.Clear)
            {
                ClearWasExecuted = true;
            }

            Marshaller mOut              = new Marshaller(outBuf);
            TpmSt      responseTag       = mOut.Get <TpmSt>();
            uint       responseParamSize = mOut.Get <uint>();
            TpmRc      responseCode      = mOut.Get <TpmRc>();

            if (ValidateTestAttributes)
            {
                // ValidateTestAttributes should not be set for a stress run
                LogTestAttributes(sessionTag, commandCode);
                try
                {
                    if (responseCode == TpmRc.Success)
                    {
                        ValidateHandleUsage(commandCode, inBuf);
                    }
                }
                catch (Exception)
                {
                    // Invalid command buffer can mess this up
                }
            }

            if (sessionTag.Equals(TpmSt.Null))
            {
                return;
            }

            // There are two encoding for errors - formats 0 and 1. Decode the error type
            uint resultCodeValue    = (uint)responseCode;
            bool formatOneErrorType = ((resultCodeValue & 0x80) != 0);
            uint resultCodeMask     = formatOneErrorType ? 0xBFU : 0x97FU;

            TpmRc maskedError = (TpmRc)((uint)responseCode & resultCodeMask);

            lock (this)
            {
                // log the command info to the test logger so that it can collect stats
                LogCommandExecution(commandCode, maskedError, cmdExecutionTime);
            }

#if false
            // Keep a copy of successfully executed commands that contain types we have
            // not seen so far. This is for tests that need good-command candidate strings,
            // like TestCommandDispatcherCoverage.
            // Code 0x80280400 is returned by TBS when the command is blocked by Windows.
            if (maskedError == TpmRc.Success && !Tpm2.IsTbsError(resultCodeValue))
            {
                // look at all types in command string.  If we have a new type we keep it
                CrackedCommand cc   = CommandProcessor.CrackCommand(inBuf);
                CommandInfo    info = CommandInformation.Info.First(x =>
                                                                    x.CommandCode == cc.Header.CommandCode);
                byte[] inStructBytes = Globs.Concatenate(
                    Globs.GetZeroBytes((int)info.HandleCountIn * 4),
                    cc.CommandParms);
                Marshaller mx = new Marshaller(inStructBytes);

                TpmStructureBase bb = (TpmStructureBase)mx.Get(info.InStructType, "");

                // If a new type is contained, save this command for testing in
                // TestDispatcherCoverage.
                if (HasNewTypes(bb))
                {
                    ExecutedCommandInfo.Add(inBuf);
                }
            }
            else
#else
            if (maskedError != TpmRc.Success)
#endif
            {
                // If a command failed, we can get here only if the corresponding
                // expected error assertion was specified.
                ++NumAsserts;
            }
            ReportProgress();

            // output TPM IO to a text file for later processing
            if (Logger.LogTpmIo)
            {
                while (TpmIoWriter == null)
                {
                    try
                    {
                        string ioLogPath;
                        if (Logger.LogPath != null)
                        {
                            ioLogPath = System.IO.Path.Combine(Logger.LogPath, "tpm_io.txt");
                        }
                        else
                        {
                            string fileName;
                            lock (this)
                            {
                                fileName = "tpm_io-" + DateTime.Now.ToString("yyyy-MMM-dd-HH");
                                if (PrevLogName == fileName)
                                {
                                    fileName += "(" + ++PrevLogInstance + ")";
                                }
                                else
                                {
                                    PrevLogName     = fileName;
                                    PrevLogInstance = 1;
                                }
                            }
                            fileName += ".txt";

#if TSS_MIN_API
                            ioLogPath = fileName;
#else
                            string docsPath = Environment.GetFolderPath(
                                Environment.SpecialFolder.MyDocuments);
                            ioLogPath = System.IO.Path.Combine(docsPath, fileName);
#endif
                        }

                        TpmIoWriter = new StreamWriter(new FileStream(ioLogPath,
                                                                      FileMode.Create));
                        Logger.WriteToLog("Dumping TPM I/O to " + ioLogPath);
                    }
                    catch (Exception e)
                    {
                        string message = "Failed to open the tpm_io.txt file for writing.\n" +
                                         "Error: " + e.Message;
                        Logger.WriteErrorToLog(message);
                    }
                }

                // get the test source code line that initiated the command
                string caller = "unknown";
#if !TSS_NO_STACK
                StackTrace   trace      = new StackTrace(true);
                StackFrame[] frames     = trace.GetFrames();
                int          frameCount = frames.Length;
                StackFrame   f          = null;
                // start at 1 to not count the currently executing function
                for (int j = 1; j < frameCount; j++)
                {
                    f = frames[j];
                    if (f.GetMethod().DeclaringType.Assembly == Logger.TestAssembly)
                    {
                        caller = f.GetFileName() + ":" + f.GetFileLineNumber();
                        break;
                    }
                }
#endif
                string commandCodeString = Enum.GetName(typeof(TpmCc), commandCode);
                string inString          = "{MALFORMED COMMAND BUFFER}";
                string outString         = "{MALFORMED RESPONSE BUFFER}";

                try { inString = CommandProcessor.ParseCommand(inBuf); }
                catch (Exception) { }
                try { outString = CommandProcessor.ParseResponse(commandCodeString, outBuf); }
                catch (Exception) { }

                lock (this)
                {
                    TpmIoWriter.WriteLine(commandCode);
                    TpmIoWriter.WriteLine(caller);

                    TpmIoWriter.WriteLine(">>>> Raw input");
                    TpmIoWriter.WriteLine(Globs.HexFromByteArray(inBuf));
                    TpmIoWriter.WriteLine(">>>> Raw output");
                    TpmIoWriter.WriteLine(Globs.HexFromByteArray(outBuf));

                    TpmIoWriter.WriteLine(">>>> Parsed input");
                    TpmIoWriter.WriteLine(inString);
                    TpmIoWriter.WriteLine(">>>> Parsed output");
                    TpmIoWriter.WriteLine(outString);

                    TpmIoWriter.WriteLine("-----------------------------------------");
                    TpmIoWriter.Flush();
                }
            }

            if (ChainedCallbacks != null)
            {
                ChainedCallbacks.PostCallback(inBuf, outBuf);
            }
        } // ICommandCallbacks.PostCallback