Ejemplo n.º 1
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            StackHashScriptResult scriptResult = this.DataContext as StackHashScriptResult;

            if (scriptResult != null)
            {
                richTextBoxResults.Document.Blocks.Clear();
                richTextBoxResults.Document.Blocks.Add(GetScriptResultParagraph(scriptResult));
            }
        }
Ejemplo n.º 2
0
        public bool CabMatchesSearchCriteria(StackHashProduct product,
                                             StackHashFile file, StackHashEvent theEvent, StackHashCab cab, StackHashSearchCriteria searchCriteria)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }
            if (theEvent == null)
            {
                throw new ArgumentNullException("theEvent");
            }
            if (cab == null)
            {
                throw new ArgumentNullException("cab");
            }
            if (searchCriteria == null)
            {
                throw new ArgumentNullException("searchCriteria");
            }

            // Get a list of script result files for this cab.
            StackHashScriptResultFiles resultFiles = GetResultFiles(product, file, theEvent, cab);

            if ((resultFiles == null) || (resultFiles.Count == 0))
            {
                return(false);
            }

            foreach (StackHashScriptResultFile resultFile in resultFiles)
            {
                try
                {
                    StackHashScriptResult resultFileData = GetResultFileData(product, file, theEvent, cab, resultFile.ScriptName);

                    if (resultFileData.Search(searchCriteria))
                    {
                        return(true);
                    }
                }
                catch (System.Exception ex)
                {
                    // Don't allow corrupt files to stop the search.
                    DiagnosticsHelper.LogException(DiagSeverity.Warning, "Corrupt or missing results file: " + resultFile.ScriptName +
                                                   " for cab " + cab.Id.ToString(CultureInfo.InvariantCulture), ex);
                }
            }

            return(false);
        }
Ejemplo n.º 3
0
        public void Contains_1Command_0Lines_NoMatch()
        {
            StackHashScriptResult scriptResult = new StackHashScriptResult();

            scriptResult.ScriptResults = new StackHashScriptLineResults();

            StackHashSearchCriteria criteria = new StackHashSearchCriteria(new StackHashSearchOptionCollection());

            criteria.SearchFieldOptions.Add(new StringSearchOption(
                                                StackHashObjectType.Script, "Script", StackHashSearchOptionType.StringContains, "Hello", "Hello", false));

            Assert.AreEqual(false, scriptResult.Search(criteria));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Gets a Paragraph containing the results of a script run
        /// </summary>
        /// <param name="scriptResult">Script result to parse</param>
        /// <returns>Paragraph</returns>
        public static Paragraph GetScriptResultParagraph(StackHashScriptResult scriptResult)
        {
            Paragraph para = new Paragraph();

            para.FontFamily = new FontFamily("Courier New");

            foreach (StackHashScriptLineResult line in scriptResult.ScriptResults)
            {
                AddResultLineToParagraph(line, ref para);
            }

            return(para);
        }
Ejemplo n.º 5
0
        public void RunAllAutoScripts()
        {
            String dumpFileName = m_TempPath + "Cucku.exe.mdmp";

            // First make a copy of the test cab file.
            File.Copy(TestSettings.TestDataFolder + @"Dumps\Cucku.exe.mdmp",
                      dumpFileName, true);
            FileAttributes attributes = File.GetAttributes(dumpFileName);

            File.SetAttributes(dumpFileName, attributes & ~FileAttributes.ReadOnly);

            ScriptManager scriptManager = new ScriptManager(m_TempPath);

            // Now execute the script.
            StackHashDebug.Windbg winDbg = new Windbg();

            try
            {
                Collection <AutoScriptBase> autoScripts = scriptManager.AutoScripts;

                foreach (AutoScriptBase autoScript in autoScripts)
                {
                    // Generate the script settings structure in memory.
                    StackHashScriptSettings scriptSettings = autoScript.GenerateScript();

                    // Those settings are now used to create a WinDbg script file (wds). This file has a command
                    // to create a log file (the resultsFileName).
                    String resultsFileName = String.Format("{0}.log", Path.Combine(m_TempPath, autoScript.ScriptName));
                    String scriptFileName  = String.Format("{0}.wds", Path.Combine(m_TempPath, autoScript.ScriptName));
                    String symPath         = null;
                    String exePath         = null;
                    String srcPath         = null;
                    scriptSettings.GenerateScriptFile(scriptFileName, resultsFileName, ref symPath, ref exePath, ref srcPath);

                    // Run the wds file through the debugger to produce the results.log file.
                    winDbg.RunScript(m_DebuggerSettings, false, scriptFileName, dumpFileName, m_TempPath, symPath, exePath, srcPath);

                    // Load the results.log file.
                    StackHashScriptResult scriptResults = new StackHashScriptResult(resultsFileName);

                    // Analyse the results.
                    StackHashDumpAnalysis analysis = new StackHashDumpAnalysis();
                    analysis = autoScript.AnalyzeScriptResults(analysis, scriptResults);
                }
            }
            finally
            {
                scriptManager.RemoveAutoScripts();
            }
        }
Ejemplo n.º 6
0
        public void Contains_1Command_1Lines_Match()
        {
            StackHashScriptResult scriptResult = new StackHashScriptResult();

            scriptResult.ScriptResults = new StackHashScriptLineResults();

            scriptResult.ScriptResults.Add(new StackHashScriptLineResult(new StackHashScriptLine("Command1", "Comment1"),
                                                                         new StackHashScriptLineOutput()));
            scriptResult.ScriptResults[0].ScriptLineOutput.Add("Output line 1");

            StackHashSearchCriteria criteria = new StackHashSearchCriteria(new StackHashSearchOptionCollection());

            criteria.SearchFieldOptions.Add(new StringSearchOption(
                                                StackHashObjectType.Script, "Script", StackHashSearchOptionType.StringContains, "line", null, false));

            Assert.AreEqual(true, scriptResult.Search(criteria));
        }
Ejemplo n.º 7
0
        private bool runAutoScripts(StackHashProduct product, StackHashFile file, StackHashEvent theEvent, StackHashCab cab, StackHashScriptDumpType dumpType)
        {
            Collection <AutoScriptBase> autoScripts  = m_TaskParameters.TheScriptManager.AutoScripts;
            ScriptResultsManager        scriptRunner = m_TaskParameters.TheScriptResultsManager;

            bool dumpAnalysisProduced = false;

            // Analyse the Unmanaged mode autoscripts first - as these determine if the dump is managed or not and hence whether
            // the managed scripts will be run. The AutoScripts property above returns the autoscripts in the correct order.
            foreach (AutoScriptBase autoScript in autoScripts)
            {
                bool dumpIsManaged = ((cab.DumpAnalysis != null) && (!String.IsNullOrEmpty(cab.DumpAnalysis.DotNetVersion)));

                if (autoScript.ScriptSettings.DumpType != dumpType)
                {
                    continue;
                }

                if ((autoScript.ScriptSettings.DumpType == StackHashScriptDumpType.ManagedOnly) && (!dumpIsManaged))
                {
                    continue;
                }

                bool forceAutoScript = false;
                if ((cab.DumpAnalysis == null) || (cab.DumpAnalysis.MachineArchitecture == null) || (cab.DumpAnalysis.OSVersion == null))
                {
                    forceAutoScript = true;
                }

                // Run the auto script on the cab if it hasn't already been run.
                StackHashScriptResult scriptResult =
                    scriptRunner.RunScript(product, file, theEvent, cab, null, autoScript.ScriptName, false, null, forceAutoScript);

                // Analyze the results.
                if (scriptResult != null)
                {
                    cab.DumpAnalysis     = autoScript.AnalyzeScriptResults(cab.DumpAnalysis, scriptResult);
                    dumpAnalysisProduced = true;
                    m_ConsecutiveErrors  = 0;
                }
            }

            return(dumpAnalysisProduced);
        }
Ejemplo n.º 8
0
        public void RunAutoScript()
        {
            String dumpFileName    = m_TempPath + "Cucku.exe.mdmp";
            String scriptFileName  = m_TempPath + "AutoScript.wds";
            String resultsFileName = m_TempPath + "AutoScript.log";

            // First make a copy of the test cab file.
            File.Copy(TestSettings.TestDataFolder + @"Dumps\Cucku.exe.mdmp",
                      dumpFileName, true);
            FileAttributes attributes = File.GetAttributes(dumpFileName);

            File.SetAttributes(dumpFileName, attributes & ~FileAttributes.ReadOnly);

            AutoScript autoScript = new AutoScript(m_TempPath);
            StackHashScriptSettings scriptSettings = autoScript.GenerateScript();
            String symPath = null;
            String exePath = null;
            String srcPath = null;

            scriptSettings.GenerateScriptFile(scriptFileName, resultsFileName, ref symPath, ref exePath, ref srcPath);

            Assert.AreEqual(null, symPath);
            Assert.AreEqual(null, exePath);
            Assert.AreEqual(null, srcPath);

            // Now execute the script.
            StackHashDebug.Windbg winDbg = new Windbg();
            winDbg.RunScript(m_DebuggerSettings, false, scriptFileName, dumpFileName, m_TempPath, symPath, exePath, srcPath);

            // Load the results file.
            StackHashScriptResult scriptResults = new StackHashScriptResult(resultsFileName);

            // Analyse the results.
            StackHashDumpAnalysis analysis = new StackHashDumpAnalysis();

            analysis = autoScript.AnalyzeScriptResults(analysis, scriptResults);

            Assert.AreEqual("not available", analysis.SystemUpTime);
            Assert.AreEqual("0 days 0:02:20.000", analysis.ProcessUpTime);

            Assert.AreEqual("2.0.50727.3603", analysis.DotNetVersion);
        }
Ejemplo n.º 9
0
        public void DoesNotContain_2Command_1Lines_SecondCmdMatch()
        {
            StackHashScriptResult scriptResult = new StackHashScriptResult();

            scriptResult.ScriptResults = new StackHashScriptLineResults();

            scriptResult.ScriptResults.Add(new StackHashScriptLineResult(new StackHashScriptLine("Command1", "Comment1"),
                                                                         new StackHashScriptLineOutput()));
            scriptResult.ScriptResults[0].ScriptLineOutput.Add("Output line 1");

            scriptResult.ScriptResults.Add(new StackHashScriptLineResult(new StackHashScriptLine("Command2", "Comment2"),
                                                                         new StackHashScriptLineOutput()));
            scriptResult.ScriptResults[0].ScriptLineOutput.Add("Output line 2");

            StackHashSearchCriteria criteria = new StackHashSearchCriteria(new StackHashSearchOptionCollection());

            criteria.SearchFieldOptions.Add(new StringSearchOption(
                                                StackHashObjectType.Script, "Script", StackHashSearchOptionType.StringDoesNotContain, "2", null, false));

            Assert.AreEqual(false, scriptResult.Search(criteria));
        }
Ejemplo n.º 10
0
        public StackHashScriptResult GetResultFileData(StackHashProduct product,
                                                       StackHashFile file, StackHashEvent theEvent, StackHashCab cab, String scriptName)
        {
            if (scriptName == null)
            {
                throw new ArgumentNullException("scriptName");
            }
            if (cab == null)
            {
                throw new ArgumentNullException("cab");
            }

            String cabFileFolder = m_ErrorIndex.GetCabFolder(product, file, theEvent, cab);

            String resultsFileName = String.Format(CultureInfo.InvariantCulture,
                                                   "{0}\\Analysis\\{1}.log", cabFileFolder, scriptName);

            if (!File.Exists(resultsFileName))
            {
                return(null);
            }

            StackHashScriptResult result = null;

            try
            {
                result = new StackHashScriptResult(resultsFileName);
            }
            catch (System.Exception ex)
            {
                // Don't allow corrupt files to stop the search.
                DiagnosticsHelper.LogException(DiagSeverity.Warning, "Corrupt or missing results file: " + scriptName +
                                               " for cab " + cab.Id.ToString(CultureInfo.InvariantCulture), ex);
            }

            return(result);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Analyzes the output generated when running the autoscript against a dump file.
        /// Various details are extracted and presented in object form in StackHashDumpAnalysis.
        /// </summary>
        /// <param name="analysis">The analysis results so far.</param>
        /// <param name="results">The results file to analyze.</param>
        /// <returns>The results of the analysis. Null fields are underined.</returns>
        public override StackHashDumpAnalysis AnalyzeScriptResults(StackHashDumpAnalysis analysis, StackHashScriptResult results)
        {
            if (analysis == null)
            {
                throw new ArgumentNullException("analysis");
            }
            if (results == null)
            {
                throw new ArgumentNullException("results");
            }

            // Work through all of the command output looking for useful data.
            foreach (StackHashScriptLineResult commandOutput in results.ScriptResults)
            {
                if (commandOutput.ScriptLine.Comment.Contains(s_VerTargetComment))
                {
                    // Get the version information.
                    processVerTargetResults(analysis, commandOutput);
                }
                else if (commandOutput.ScriptLine.Comment.Contains(s_MscoreModuleComment))
                {
                    // Get the .NET version information. For V3.5 and below the CLR version is in mscorwks.dll
                    processMscorwksResults(analysis, commandOutput);
                }
                else if (commandOutput.ScriptLine.Comment.Contains(s_MscoreModuleComment2))
                {
                    // Get the .NET version information. For V4.0 and above (so far) the CLR version is in clr.dll
                    processMscorwksResults(analysis, commandOutput);
                }
            }

            return(analysis);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Analyzes the output generated when running the script against a dump file.
        /// Various details are extracted and presented in object form in StackHashDumpAnalysis.
        /// </summary>
        /// <param name="analysis">The analysis results so far.</param>
        /// <param name="results">The results file to analyze.</param>
        /// <returns>The results of the analysis. Null fields are underined.</returns>
        public override StackHashDumpAnalysis AnalyzeScriptResults(StackHashDumpAnalysis analysis, StackHashScriptResult results)
        {
            if (analysis == null)
            {
                throw new ArgumentNullException("analysis");
            }
            if (results == null)
            {
                throw new ArgumentNullException("results");
            }

            // Work through all of the command output looking for useful data.
            foreach (StackHashScriptLineResult commandOutput in results.ScriptResults)
            {
                if (commandOutput.ScriptLine.Comment.Contains(s_VerTargetComment))
                {
                    // Get the version information.
                    processVerTargetResults(analysis, commandOutput);
                }
            }

            return(analysis);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Analyzes the output generated when running the autoscript against a dump file.
 /// Various details are extracted and presented in object form in StackHashDumpAnalysis.
 /// </summary>
 /// <param name="analysis">The analysis results so far.</param>
 /// <param name="results">The results file to analyze.</param>
 /// <returns>The results of the analysis. Null fields are underined.</returns>
 public abstract StackHashDumpAnalysis AnalyzeScriptResults(StackHashDumpAnalysis analysis, StackHashScriptResult results);
Ejemplo n.º 14
0
        /// <summary>
        /// Unpacks and runs the specified script + any automatic scripts on the file.
        /// </summary>
        /// <returns>Full dump analysis.</returns>
        private void processCab()
        {
            ScriptResultsManager scriptRunner = m_TaskParameters.TheScriptResultsManager;
            StackHashProduct     product      = m_TaskParameters.Product;
            StackHashFile        file         = m_TaskParameters.File;
            StackHashEvent       theEvent     = m_TaskParameters.TheEvent;
            StackHashCab         cab          = m_TaskParameters.Cab;

            // Unwrap the cab if it hasn't been unwrapped already.
            unpackCab(product, file, theEvent, cab, false);

            if (cab.DumpAnalysis == null)
            {
                cab.DumpAnalysis = new StackHashDumpAnalysis();
            }


            // Run the autoscripts on the cab.
            Collection <AutoScriptBase> autoScripts = m_TaskParameters.TheScriptManager.AutoScripts;

            bool dataFound = false;

            foreach (AutoScriptBase autoScript in autoScripts)
            {
                bool forceAutoScript = false;
                if ((cab.DumpAnalysis == null) || (cab.DumpAnalysis.MachineArchitecture == null) || (cab.DumpAnalysis.OSVersion == null))
                {
                    forceAutoScript = true;
                }

                // Run the auto script on the cab if it has not already been run.
                StackHashScriptResult scriptResult =
                    scriptRunner.RunScript(m_TaskParameters.Product, m_TaskParameters.File, m_TaskParameters.TheEvent,
                                           m_TaskParameters.Cab, null, autoScript.ScriptName, false, null, forceAutoScript);

                // Analyze the results.
                if (scriptResult != null)
                {
                    cab.DumpAnalysis = autoScript.AnalyzeScriptResults(cab.DumpAnalysis, scriptResult);
                    dataFound        = true;
                }
            }

            if (dataFound)
            {
                m_TaskParameters.ErrorIndex.AddCab(product, file, theEvent, cab, true);
            }

            // Now run all the specified scripts.
            foreach (String scriptName in m_TaskParameters.ScriptsToRun)
            {
                if (m_TaskParameters.TheScriptManager.IsAutoScript(scriptName))
                {
                    continue; // Will have already been run above.
                }
                if (CurrentTaskState.AbortRequested)
                {
                    throw new OperationCanceledException("Abort requested");
                }

                scriptRunner.RunScript(m_TaskParameters.Product, m_TaskParameters.File, m_TaskParameters.TheEvent,
                                       m_TaskParameters.Cab, m_TaskParameters.DumpFileName, scriptName, false,
                                       m_TaskParameters.ClientData, true);
            }
        }
Ejemplo n.º 15
0
        public void AutoScriptOnOneCabAlreadyRunButNewerVersion()
        {
            // If the auto task sees the AutoScript.log file exists and has the same
            // version as the current AutoScript.xml then it shouldn't run it again.
            // Determine this by checking the file time after a second run.

            // Create an index with 1 cab file.
            XmlErrorIndex errorIndex = new XmlErrorIndex(m_TempPath, "ErrorIndex");

            errorIndex.Activate();

            StackHashTestIndexData testData = new StackHashTestIndexData();

            testData.NumberOfProducts   = 1;
            testData.NumberOfFiles      = 1;
            testData.NumberOfEvents     = 1;
            testData.NumberOfEventInfos = 1;
            testData.NumberOfCabs       = 1;
            testData.UseLargeCab        = false;
            TestManager.CreateTestIndex(errorIndex, testData);



            ScriptManager scriptManager = new ScriptManager(m_TempPath + "Scripts");

            Assert.AreEqual(scriptManager.NumberOfAutoScripts, scriptManager.ScriptNames.Count);

            ScriptResultsManager scriptResultsManager = new ScriptResultsManager(errorIndex, scriptManager, m_Debugger, m_DebuggerSettings);

            // Set up parameters for the task.
            AnalyzeTaskParameters analyzeParams = new AnalyzeTaskParameters();

            // Standard task parameters.
            analyzeParams.IsBackgroundTask            = true;
            analyzeParams.Name                        = "TestRunOneTask";
            analyzeParams.RunInParallel               = false;
            analyzeParams.UseSeparateThread           = true;
            analyzeParams.AnalysisSettings            = new StackHashAnalysisSettings();
            analyzeParams.AnalysisSettings.ForceRerun = true;
            analyzeParams.ContextId                   = 0;
            analyzeParams.ClientData                  = new StackHashClientData(Guid.NewGuid(), "MarkJ", 1);
            analyzeParams.Debugger                    = m_Debugger;
            analyzeParams.DebuggerSettings            = m_DebuggerSettings;
            analyzeParams.TheScriptManager            = scriptManager;
            analyzeParams.TheScriptResultsManager     = scriptResultsManager;
            int productId = 1;

            analyzeParams.ProductsToSynchronize = new StackHashProductSyncDataCollection();
            analyzeParams.ProductsToSynchronize.Add(new StackHashProductSyncData(productId));

            analyzeParams.ErrorIndex = errorIndex;

            // Create the task and run it.
            AnalyzeTask analyzeTask = new AnalyzeTask(analyzeParams);
            TaskManager taskManager = new TaskManager("Test");

            taskManager.Enqueue(analyzeTask);
            taskManager.WaitForTaskCompletion(analyzeTask, s_TaskTimeout);


            StackHashProductCollection products = errorIndex.LoadProductList();
            StackHashFileCollection    files    = errorIndex.LoadFileList(products[0]);
            StackHashEventCollection   events   = errorIndex.LoadEventList(products[0], files[0]);
            StackHashCabCollection     cabs     = errorIndex.LoadCabList(products[0], files[0], events[0]);

            StackHashScriptResult script1 = scriptResultsManager.GetResultFileData(products[0], files[0], events[0], cabs[0], "AutoScript");

            // Wait for 1 second - so file time granularity exceeded.
            Thread.Sleep(1000);

            // Change the version on the autoscript.
            StackHashScriptSettings settings = scriptManager.LoadScript("AutoScript");

            settings.LastModifiedDate = DateTime.Now;
            scriptManager.AddScript(settings, true, true);

            // Now run the task again.
            analyzeTask = new AnalyzeTask(analyzeParams);
            taskManager.Enqueue(analyzeTask);
            taskManager.WaitForTaskCompletion(analyzeTask, s_TaskTimeout);


            Assert.AreEqual(true, analyzeTask.CurrentTaskState.TaskCompleted);

            // Refresh the cab list data.
            cabs = errorIndex.LoadCabList(products[0], files[0], events[0]);

            StackHashDumpAnalysis analysis = cabs[0].DumpAnalysis;

            Assert.AreEqual("not available", analysis.SystemUpTime);
            Assert.AreEqual("0 days 0:00:15.000", analysis.ProcessUpTime);
            Assert.AreEqual("2.0.50727.3603", analysis.DotNetVersion);


            StackHashScriptResult script2 = scriptResultsManager.GetResultFileData(products[0], files[0], events[0], cabs[0], "AutoScript");

            Assert.AreEqual(true, script2.RunDate > script1.RunDate);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Process a debug script change.
        /// </summary>
        private bool processDebugScriptUpdate(StackHashBugTrackerUpdate update)
        {
            // Get the associated product and file information.
            StackHashProduct product  = m_Index.GetProduct((int)update.ProductId);
            StackHashFile    file     = m_Index.GetFile(product, (int)update.FileId);
            StackHashEvent   theEvent = m_Index.GetEvent(product, file, new StackHashEvent((int)update.EventId, update.EventTypeName));

            DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Debug Script: getting cab data1");
            StackHashCab cab = m_Index.GetCab(product, file, theEvent, (int)update.CabId);

            DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Debug Script: getting cab data2");
            StackHashNoteEntry note = m_Index.GetCabNote((int)update.ChangedObjectId);

            if ((product == null) || (file == null) || (theEvent == null) || (cab == null) || (note == null))
            {
                if (product == null)
                {
                    DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Debug Script: Inconsistent Update Table Entry : product");
                }
                if (file == null)
                {
                    DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Debug Script: Inconsistent Update Table Entry : file");
                }
                if (theEvent == null)
                {
                    DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Debug Script: Inconsistent Update Table Entry : the Event");
                }
                if (cab == null)
                {
                    DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Debug Script: Inconsistent Update Table Entry : cab: " + update.CabId.ToString(CultureInfo.InvariantCulture));
                }
                if (note == null)
                {
                    DiagnosticsHelper.LogMessage(DiagSeverity.Warning, "Processing Debug Script: Inconsistent Update Table Entry : note");
                }
                return(false);
            }

            BugTrackerProduct   btProduct      = new BugTrackerProduct(product.Name, product.Version, product.Id);
            BugTrackerFile      btFile         = new BugTrackerFile(file.Name, file.Version, file.Id);
            NameValueCollection eventSignature = new NameValueCollection();

            foreach (StackHashParameter param in theEvent.EventSignature.Parameters)
            {
                eventSignature.Add(param.Name, param.Value);
            }

            BugTrackerEvent btEvent = new BugTrackerEvent(theEvent.BugId, theEvent.PlugInBugId, theEvent.Id, theEvent.EventTypeName,
                                                          theEvent.TotalHits, eventSignature);

            NameValueCollection analysis = new NameValueCollection();

            analysis.Add("DotNetVersion", cab.DumpAnalysis.DotNetVersion);
            analysis.Add("MachineArchitecture", cab.DumpAnalysis.MachineArchitecture);
            analysis.Add("OSVersion", cab.DumpAnalysis.OSVersion);
            analysis.Add("ProcessUpTime", cab.DumpAnalysis.ProcessUpTime);
            analysis.Add("SystemUpTime", cab.DumpAnalysis.SystemUpTime);

            String        cabFileName = m_Index.GetCabFileName(product, file, theEvent, cab);
            BugTrackerCab btCab       = new BugTrackerCab(cab.Id, cab.SizeInBytes, cab.CabDownloaded, cab.Purged, analysis, cabFileName);

            BugTrackerNote btCabNote = new BugTrackerNote(note.TimeOfEntry, note.Source, note.User, note.Note);

            // A note entry will be written when a script is run. Pick out the name of the script.
            // Format is "Script {0} executed".
            int    startIndex = btCabNote.Note.IndexOf("Script ", StringComparison.OrdinalIgnoreCase) + "Script ".Length;
            int    endIndex   = btCabNote.Note.IndexOf("executed", StringComparison.OrdinalIgnoreCase) - 2;
            int    length     = endIndex - startIndex + 1;
            String scriptName = btCabNote.Note.Substring(startIndex, length);

            StackHashScriptResult stackHashScriptResult = m_TaskParameters.TheScriptResultsManager.GetResultFileData(product, file, theEvent, cab, scriptName);

            if (stackHashScriptResult == null)
            {
                return(false);
            }

            BugTrackerScriptResult btScriptResult = new BugTrackerScriptResult(stackHashScriptResult.Name, stackHashScriptResult.ScriptVersion,
                                                                               stackHashScriptResult.LastModifiedDate, stackHashScriptResult.RunDate, stackHashScriptResult.ToString());

            String newBugId = null;

            if (update.TypeOfChange == StackHashChangeType.NewEntry)
            {
                newBugId = m_TaskParameters.PlugInContext.DebugScriptExecuted(null, BugTrackerReportType.Automatic, btProduct, btFile, btEvent, btCab, btScriptResult);
            }
            setPlugInBugReference(product, file, theEvent, newBugId);

            return(true);
        }
Ejemplo n.º 17
0
        public void simpleScriptNCommands(int numCommands, bool addComment)
        {
            // Create a test script.
            String testScriptName = "ScriptName";
            String testCommand    = @"r";

            String testComment = null;

            if (addComment)
            {
                testComment = @"Just a demo";
            }

            StackHashScript script = new StackHashScript();

            for (int i = 0; i < numCommands; i++)
            {
                script.Add(new StackHashScriptLine(testCommand, testComment + i.ToString()));
            }
            StackHashScriptSettings scriptSettings = new StackHashScriptSettings(testScriptName, script);

            String scriptFileName  = m_TempPath + @"\GeneratedScript.wds";
            String resultsFileName = m_TempPath + @"\Results.log";

            String symPath = null;
            String exePath = null;
            String srcPath = null;

            scriptSettings.GenerateScriptFile(scriptFileName, resultsFileName, ref symPath, ref exePath, ref srcPath);

            Assert.AreEqual(null, symPath);
            Assert.AreEqual(null, exePath);
            Assert.AreEqual(null, srcPath);

            // Run the script with the debugger.
            Windbg debugger = new Windbg();

            String dumpFileName = TestSettings.TestDataFolder + @"Dumps\Cucku.exe.mdmp";

            DateTime startTime = DateTime.Now.ToUniversalTime();

            StackHashDebuggerSettings debuggerSettings = new StackHashDebuggerSettings();

            debuggerSettings.DebuggerPathAndFileName = StackHashDebuggerSettings.Default32BitDebuggerPathAndFileName;
            debuggerSettings.SymbolPath = StackHashSearchPath.DefaultSymbolPath;
            debuggerSettings.BinaryPath = StackHashSearchPath.DefaultBinaryPath;
            debugger.RunScript(debuggerSettings, true, scriptFileName, dumpFileName, resultsFileName, symPath, exePath, srcPath);

            DateTime endTime = DateTime.Now.ToUniversalTime();

            Assert.AreEqual(true, File.Exists(resultsFileName));

            // Now load in the test results.
            StackHashScriptResult result = new StackHashScriptResult(resultsFileName);


            Assert.AreEqual(scriptSettings.Name, result.Name);
            Assert.AreEqual(scriptSettings.LastModifiedDate.Date, result.LastModifiedDate.Date);
            Assert.AreEqual(scriptSettings.LastModifiedDate.Hour, result.LastModifiedDate.Hour);
            Assert.AreEqual(scriptSettings.LastModifiedDate.Minute, result.LastModifiedDate.Minute);
            Assert.AreEqual(scriptSettings.LastModifiedDate.Second, result.LastModifiedDate.Second);


            // Recorded time is only accurate to the second.
            long ticksInASecond = 10000000;

            startTime = new DateTime((startTime.Ticks / ticksInASecond) * ticksInASecond, DateTimeKind.Utc);
            endTime   = new DateTime((endTime.Ticks / ticksInASecond) * ticksInASecond, DateTimeKind.Utc);

            bool isGreaterEqual  = result.RunDate >= startTime;
            bool isLessThanEqual = result.RunDate <= endTime;

            long ticks1 = result.RunDate.Ticks;
            long ticks2 = startTime.Ticks;
            long ticks3 = endTime.Ticks;

            Assert.AreEqual(true, (result.RunDate >= startTime) && (result.RunDate <= endTime));

            Assert.AreEqual(numCommands, scriptSettings.Script.Count);

            for (int i = 0; i < numCommands; i++)
            {
                Assert.AreEqual(scriptSettings.Script[i].Command, result.ScriptResults[i].ScriptLine.Command);
                Assert.AreEqual(scriptSettings.Script[i].Comment, result.ScriptResults[i].ScriptLine.Comment);

                Assert.AreEqual(5, result.ScriptResults[i].ScriptLineOutput.Count);
                Assert.AreEqual(true, result.ScriptResults[i].ScriptLineOutput[0].StartsWith("eax="));
                Assert.AreEqual(true, result.ScriptResults[i].ScriptLineOutput[1].StartsWith("eip="));
                Assert.AreEqual(true, result.ScriptResults[i].ScriptLineOutput[2].StartsWith("cs="));
            }
        }
Ejemplo n.º 18
0
        private StackHashEvent processCab(StackHashBugReportData request, StackHashProduct product, StackHashFile file,
                                          StackHashEvent theEvent, StackHashCab cab, BugTrackerProduct btProduct, BugTrackerFile btFile, BugTrackerEvent btEvent)
        {
            if (this.CurrentTaskState.AbortRequested)
            {
                throw new OperationCanceledException("Reporting events to Bug Tracker plug-ins");
            }

            NameValueCollection analysis = new NameValueCollection();

            analysis.Add("DotNetVersion", cab.DumpAnalysis.DotNetVersion);
            analysis.Add("MachineArchitecture", cab.DumpAnalysis.MachineArchitecture);
            analysis.Add("OSVersion", cab.DumpAnalysis.OSVersion);
            analysis.Add("ProcessUpTime", cab.DumpAnalysis.ProcessUpTime);
            analysis.Add("SystemUpTime", cab.DumpAnalysis.SystemUpTime);

            String cabFileName = m_Index.GetCabFileName(product, file, theEvent, cab);

            BugTrackerCab btCab = new BugTrackerCab(cab.Id, cab.SizeInBytes, cab.CabDownloaded, cab.Purged, analysis, cabFileName);

            if (((request.Options & StackHashReportOptions.IncludeCabs) != 0) ||
                ((request.Options & StackHashReportOptions.IncludeAllObjects) != 0))
            {
                String newBugId = m_TaskParameters.PlugInContext.CabAdded(m_PlugIns, m_ReportType, btProduct, btFile, btEvent, btCab);
                checkPlugInStatus(m_PlugIns);
                theEvent = setPlugInBugReference(product, file, theEvent, newBugId);
                // Reset this in case it has changed.
                btEvent = new BugTrackerEvent(theEvent.BugId, theEvent.PlugInBugId, theEvent.Id, theEvent.EventTypeName, theEvent.TotalHits, btEvent.Signature);
            }

            if (((request.Options & StackHashReportOptions.IncludeCabNotes) != 0) ||
                ((request.Options & StackHashReportOptions.IncludeAllObjects) != 0))
            {
                StackHashNotes notes = m_Index.GetCabNotes(product, file, theEvent, cab);
                foreach (StackHashNoteEntry note in notes)
                {
                    if (this.CurrentTaskState.AbortRequested)
                    {
                        throw new OperationCanceledException("Reporting events to Bug Tracker plug-ins");
                    }

                    BugTrackerNote btEventNote = new BugTrackerNote(note.TimeOfEntry, note.Source, note.User, note.Note);
                    String         newBugId    = m_TaskParameters.PlugInContext.CabNoteAdded(m_PlugIns, m_ReportType, btProduct, btFile, btEvent, btCab, btEventNote);
                    checkPlugInStatus(m_PlugIns);
                    theEvent = setPlugInBugReference(product, file, theEvent, newBugId);
                    // Reset this in case it has changed.
                    btEvent = new BugTrackerEvent(theEvent.BugId, theEvent.PlugInBugId, theEvent.Id, theEvent.EventTypeName, theEvent.TotalHits, btEvent.Signature);
                }
            }

            if (((request.Options & StackHashReportOptions.IncludeScriptResults) != 0) ||
                ((request.Options & StackHashReportOptions.IncludeAllObjects) != 0))
            {
                StackHashScriptResultFiles scriptResults = m_TaskParameters.TheScriptResultsManager.GetResultFiles(product, file, theEvent, cab);

                foreach (StackHashScriptResultFile scriptResultFile in scriptResults)
                {
                    if (this.CurrentTaskState.AbortRequested)
                    {
                        throw new OperationCanceledException("Reporting events to Bug Tracker plug-ins");
                    }
                    try
                    {
                        StackHashScriptResult scriptResult = m_TaskParameters.TheScriptResultsManager.GetResultFileData(product, file, theEvent, cab, scriptResultFile.ScriptName);

                        if (scriptResult != null)
                        {
                            BugTrackerScriptResult btScriptResult = new BugTrackerScriptResult(scriptResult.Name, scriptResult.ScriptVersion,
                                                                                               scriptResult.LastModifiedDate, scriptResult.RunDate, scriptResult.ToString());

                            String newBugId = m_TaskParameters.PlugInContext.DebugScriptExecuted(m_PlugIns, m_ReportType, btProduct, btFile, btEvent, btCab, btScriptResult);
                            checkPlugInStatus(m_PlugIns);
                            theEvent = setPlugInBugReference(product, file, theEvent, newBugId);
                            // Reset this in case it has changed.
                            btEvent = new BugTrackerEvent(theEvent.BugId, theEvent.PlugInBugId, theEvent.Id, theEvent.EventTypeName, theEvent.TotalHits, btEvent.Signature);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        DiagnosticsHelper.LogException(DiagSeverity.Information,
                                                       "Failed to load script file for reporting " + cab.Id.ToString(CultureInfo.InvariantCulture) + " " + scriptResultFile.ScriptName,
                                                       ex);
                    }
                }
            }

            return(theEvent);
        }
Ejemplo n.º 19
0
        public StackHashScriptResult RunScript(StackHashProduct product, StackHashFile file, StackHashEvent theEvent, StackHashCab cab,
                                               String dumpFileName, String scriptName, bool extractCab, StackHashClientData clientData, bool forceRun)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }
            if (theEvent == null)
            {
                throw new ArgumentNullException("theEvent");
            }
            if (cab == null)
            {
                throw new ArgumentNullException("cab");
            }
            if (scriptName == null)
            {
                throw new ArgumentNullException("scriptName");
            }


            String machineArchitecture = "x86"; // Default to 32 bit.

            if ((cab.DumpAnalysis != null) && !String.IsNullOrEmpty(cab.DumpAnalysis.MachineArchitecture))
            {
                machineArchitecture = cab.DumpAnalysis.MachineArchitecture;
            }


            StackHashScriptResult result = null;
            bool use32BitDebugger        = true;

            if (machineArchitecture != null)
            {
                if ((String.Compare(machineArchitecture, "x64", StringComparison.OrdinalIgnoreCase) == 0) ||
                    (String.Compare(machineArchitecture, "X64", StringComparison.OrdinalIgnoreCase) == 0))
                {
                    use32BitDebugger = false;
                }
            }


            // Unwrap the cab if necessary.
            String cabFileName   = m_ErrorIndex.GetCabFileName(product, file, theEvent, cab);
            String cabFileFolder = Path.GetDirectoryName(cabFileName);

            if (!File.Exists(cabFileName))
            {
                throw new StackHashException("Cab file does not exist: " + cabFileName, StackHashServiceErrorCode.CabDoesNotExist);
            }

            if (extractCab)
            {
                try
                {
                    Cabs.ExtractCab(cabFileName, cabFileFolder);
                }
                catch (System.Exception ex)
                {
                    if (ex.Message.Contains("The file is not a cabinet") || ex.Message.Contains("corrupt") || ex.Message.Contains("Corrupt"))
                    {
                        // Set the downloaded flag appropriately if different.
                        StackHashCab loadedCab = m_ErrorIndex.GetCab(product, file, theEvent, cab.Id);

                        if (loadedCab != null)
                        {
                            if (loadedCab.CabDownloaded)
                            {
                                loadedCab.CabDownloaded = false;
                                m_ErrorIndex.AddCab(product, file, theEvent, loadedCab, false);
                            }
                        }
                    }

                    throw new StackHashException("Cab file cannot be unpackaged. Try downloading the file from again.", ex, StackHashServiceErrorCode.CabIsCorrupt);
                }
            }

            // Now get the dump filename - mdmp and dmp files should be returned.
            String[] allDumpFiles = Directory.GetFiles(cabFileFolder, "*.*dmp");

            if (allDumpFiles.Length == 0)
            {
                return(null);
            }

            // Choose the largest dump file to process.
            String fullDumpFilePath = null;

            long largestFileSize = 0;

            foreach (String fileName in allDumpFiles)
            {
                FileInfo fileInfo = new FileInfo(fileName);
                if (fileInfo.Length > largestFileSize)
                {
                    largestFileSize  = fileInfo.Length;
                    fullDumpFilePath = fileName;
                }
            }

            if (!String.IsNullOrEmpty(dumpFileName))
            {
                fullDumpFilePath = cabFileFolder + "\\" + dumpFileName;
            }

            // Find the script that the user wants to run.
            StackHashScriptSettings scriptSettings = m_ScriptManager.LoadScript(scriptName);

            // Auto generate the script file.
            String dumpAnalysisFolder = cabFileFolder + "\\Analysis";

            if (!Directory.Exists(dumpAnalysisFolder))
            {
                Directory.CreateDirectory(dumpAnalysisFolder);
            }

            // Check if the file has already been run.
            bool   runScript       = true;
            String resultsFileName = String.Format(CultureInfo.InvariantCulture, "{0}\\{1}.log", dumpAnalysisFolder, scriptSettings.Name);

            if (File.Exists(resultsFileName))
            {
                DateTime lastWriteTime = File.GetLastWriteTimeUtc(resultsFileName);

                if (scriptSettings.LastModifiedDate <= lastWriteTime)
                {
                    runScript = false;
                }
            }

            String installFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            if (runScript || forceRun)
            {
                String overrideSymbolPath = null;
                String overrideBinaryPath = null;
                String overrideSourcePath = null;

                if (m_Debugger.Use32BitDebugger(use32BitDebugger, m_DebuggerSettings))
                {
                    overrideSymbolPath = m_DebuggerSettings.SymbolPath.FullPath;
                    overrideBinaryPath = m_DebuggerSettings.BinaryPath.FullPath;
                    overrideSourcePath = null;

                    // Check the script for PSSCOR loading.
                    String clrVersion = String.Empty;
                    if ((cab.DumpAnalysis != null) && (!String.IsNullOrEmpty(cab.DumpAnalysis.DotNetVersion)))
                    {
                        clrVersion = cab.DumpAnalysis.DotNetVersion;
                    }
                    scriptSettings.FixUp(StackHashScriptDumpArchitecture.X86, clrVersion, installFolder);
                }
                else
                {
                    overrideSymbolPath = m_DebuggerSettings.SymbolPath64Bit.FullPath;
                    overrideBinaryPath = m_DebuggerSettings.BinaryPath64Bit.FullPath;
                    overrideSourcePath = null;

                    // Check the script for PSSCOR loading.
                    String clrVersion = String.Empty;
                    if ((cab.DumpAnalysis != null) && (!String.IsNullOrEmpty(cab.DumpAnalysis.DotNetVersion)))
                    {
                        clrVersion = cab.DumpAnalysis.DotNetVersion;
                    }
                    scriptSettings.FixUp(StackHashScriptDumpArchitecture.Amd64, clrVersion, installFolder);
                }

                String scriptFileName = Path.GetTempFileName();
                scriptSettings.GenerateScriptFile(scriptFileName, resultsFileName, ref overrideSymbolPath, ref overrideBinaryPath, ref overrideSourcePath);

                DateTime timeOfRun = DateTime.Now.ToUniversalTime();
                try
                {
                    m_Debugger.RunScript(m_DebuggerSettings, use32BitDebugger, scriptFileName, fullDumpFilePath, resultsFileName, overrideSymbolPath, overrideBinaryPath, overrideSourcePath);

                    // Check if the results were generated. If not there must be a command line error so get the output from the
                    // debugger and throw an exception.
                    if (!File.Exists(resultsFileName))
                    {
                        throw new StackHashException("Debugger Error: " + m_Debugger.StandardError, StackHashServiceErrorCode.DebuggerError);
                    }


                    // Load in the results.
                    result = StackHashScriptResult.MergeAnalysisDumpFiles(resultsFileName);

                    // Add a script run note to the error index.
                    StackHashNoteEntry note = new StackHashNoteEntry();

                    // MUST KEEP THIS TEXT THE SAME - because it is used as a search string by the BugTrackerTask.
                    note.Note = String.Format(CultureInfo.CurrentCulture, "Script {0} executed", scriptName);
                    if ((clientData == null) || (clientData.ClientName == null))
                    {
                        note.Source = "Service";
                        note.User   = "******";
                    }
                    else
                    {
                        note.Source = "StackHash Client";
                        note.User   = clientData.ClientName;
                    }

                    note.TimeOfEntry = timeOfRun;
                    int cabNoteId = m_ErrorIndex.AddCabNote(product, file, theEvent, cab, note);

                    // Report the event to bug tracking plug-ins.
                    m_ErrorIndex.AddUpdate(new StackHashBugTrackerUpdate(
                                               StackHashDataChanged.DebugScript, StackHashChangeType.NewEntry, product.Id, file.Id, theEvent.Id, theEvent.EventTypeName, cab.Id, cabNoteId));
                }
                catch (System.Exception ex)
                {
                    // Add a script run note to the error index.
                    StackHashNoteEntry note = new StackHashNoteEntry();
                    note.Note   = String.Format(CultureInfo.CurrentCulture, "Script {0} execution failed: {1}", scriptName, ex.Message);
                    note.Source = "Service";
                    if ((clientData == null) || (clientData.ClientName == null))
                    {
                        note.User = "******";
                    }
                    else
                    {
                        note.User = clientData.ClientName;
                    }
                    note.TimeOfEntry = timeOfRun;
                    m_ErrorIndex.AddCabNote(product, file, theEvent, cab, note);
                    throw;
                }
                finally
                {
                    if (File.Exists(scriptFileName))
                    {
                        File.Delete(scriptFileName);
                    }
                }
            }

            return(result);
        }