CoreclrTestWrapperLib.cs 29.0 KB
Newer Older
D
dotnet-bot 已提交
1 2
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
3
//
4
#nullable disable
5

6
using System;
7 8 9
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
10
using System.Linq;
11
using System.Runtime.InteropServices;
12
using System.Text;
13 14 15
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
16
using System.Text.RegularExpressions;
17
using System.Threading;
P
Pat Gavlin 已提交
18
using System.Threading.Tasks;
19
using Microsoft.Win32.SafeHandles;
P
Pat Gavlin 已提交
20

21 22
namespace CoreclrTestLib
{
23 24 25 26
    static class Kernel32
    {
        public const int MAX_PATH = 260;
        public const int ERROR_NO_MORE_FILES = 0x12;
27
        public const long INVALID_HANDLE = -1;
28 29 30 31 32 33 34 35 36 37 38

        public enum Toolhelp32Flags : uint
        {
            TH32CS_INHERIT = 0x80000000,
            TH32CS_SNAPHEAPLIST = 0x00000001,
            TH32CS_SNAPMODULE = 0x00000008,
            TH32CS_SNAPMODULE32 = 0x00000010,
            TH32CS_SNAPPROCESS = 0x00000002,
            TH32CS_SNAPTHREAD = 0x00000004
        };

39 40
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public unsafe struct ProcessEntry32W
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
        {
            public int Size;
            public int Usage;
            public int ProcessID;
            public IntPtr DefaultHeapID;
            public int ModuleID;
            public int Threads;
            public int ParentProcessID;
            public int PriClassBase;
            public int Flags;
            public fixed char ExeFile[MAX_PATH];
        }

        [DllImport("kernel32.dll")]
        public static extern bool CloseHandle(IntPtr handle);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern IntPtr CreateToolhelp32Snapshot(Toolhelp32Flags flags, int processId);

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
61
        public static extern bool Process32FirstW(IntPtr snapshot, ref ProcessEntry32W entry);
62 63

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
64 65 66
        public static extern bool Process32NextW(IntPtr snapshot, ref ProcessEntry32W entry);
    }

S
Stephen Toub 已提交
67
    static class @libproc
68 69 70 71 72 73 74 75 76 77
    {
        [DllImport(nameof(libproc))]
        private static extern int proc_listchildpids(int ppid, int[] buffer, int byteSize);

        public static unsafe bool ListChildPids(int ppid, out int[] buffer)
        {
            int n = proc_listchildpids(ppid, null, 0);
            buffer = new int[n];
            return proc_listchildpids(ppid, buffer, buffer.Length * sizeof(int)) != -1;
        }
78 79
    }

80
    internal static class ProcessExtensions
81
    {
82
        public unsafe static IEnumerable<Process> GetChildren(this Process process)
83
        {
84
            var children = new List<Process>();
85
            if (OperatingSystem.IsWindows())
86
            {
87
                return Windows_GetChildren(process);
88
            }
89
            else if (OperatingSystem.IsLinux())
90
            {
91
                return Linux_GetChildren(process);
92
            }
93
            else if (OperatingSystem.IsMacOS())
94
            {
95 96 97 98
                return MacOS_GetChildren(process);
            }
            return children;
        }
99

100 101 102 103 104 105 106
        private unsafe static IEnumerable<Process> Windows_GetChildren(Process process)
        {
            var children = new List<Process>();
            IntPtr snapshot = Kernel32.CreateToolhelp32Snapshot(Kernel32.Toolhelp32Flags.TH32CS_SNAPPROCESS, 0);
            if (snapshot != IntPtr.Zero && snapshot.ToInt64() != Kernel32.INVALID_HANDLE)
            {
                try
107
                {
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
                    children = new List<Process>();
                    int ppid = process.Id;

                    var processEntry = new Kernel32.ProcessEntry32W { Size = sizeof(Kernel32.ProcessEntry32W) };

                    bool success = Kernel32.Process32FirstW(snapshot, ref processEntry);
                    while (success)
                    {
                        if (processEntry.ParentProcessID == ppid)
                        {
                            try
                            {
                                children.Add(Process.GetProcessById(processEntry.ProcessID));
                            }
                            catch {}
                        }

                        success = Kernel32.Process32NextW(snapshot, ref processEntry);
                    }

128
                }
129
                finally
130
                {
131
                    Kernel32.CloseHandle(snapshot);
132 133 134
                }
            }

135
            return children;
136 137
        }

138
        private static IEnumerable<Process> Linux_GetChildren(Process process)
139
        {
140 141 142 143
            var children = new List<Process>();
            List<int> childPids = null;

            try
144
            {
145 146 147 148
                childPids = File.ReadAllText($"/proc/{process.Id}/task/{process.Id}/children")
                    .Split(' ', StringSplitOptions.RemoveEmptyEntries)
                    .Select(pidString => int.Parse(pidString))
                    .ToList();
149
            }
150
            catch (IOException e)
151
            {
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
                // Some distros might not have the /proc/pid/task/tid/children entry enabled in the kernel
                // attempt to use pgrep then
                var pgrepInfo = new ProcessStartInfo("pgrep");
                pgrepInfo.RedirectStandardOutput = true;
                pgrepInfo.Arguments = $"-P {process.Id}";

                using Process pgrep = Process.Start(pgrepInfo);

                string[] pidStrings = pgrep.StandardOutput.ReadToEnd().Split('\n', StringSplitOptions.RemoveEmptyEntries);
                pgrep.WaitForExit();

                childPids = new List<int>();
                foreach (var pidString in pidStrings)
                    if (int.TryParse(pidString, out int childPid))
                        childPids.Add(childPid);
167
            }
168 169

            foreach (var pid in childPids)
170
            {
171 172 173 174 175 176 177 178
                try
                {
                    children.Add(Process.GetProcessById(pid));
                }
                catch (ArgumentException)
                {
                    // Ignore failure to get process, the process may have exited
                }
179
            }
180 181

            return children;
182 183
        }

184
        private static IEnumerable<Process> MacOS_GetChildren(Process process)
185
        {
186 187
            var children = new List<Process>();
            if (libproc.ListChildPids(process.Id, out int[] childPids))
188
            {
189 190 191 192
                foreach (var childPid in childPids)
                {
                    children.Add(Process.GetProcessById(childPid));
                }
193 194
            }

195 196 197
            return children;
        }
    }
198

199 200 201 202
    public class CoreclrTestWrapperLib
    {
        public const int EXIT_SUCCESS_CODE = 0;
        public const string TIMEOUT_ENVIRONMENT_VAR = "__TestTimeout";
203

204 205
        // Default timeout set to 10 minutes
        public const int DEFAULT_TIMEOUT_MS = 1000 * 60 * 10;
206

207 208
        public const string COLLECT_DUMPS_ENVIRONMENT_VAR = "__CollectDumps";
        public const string CRASH_DUMP_FOLDER_ENVIRONMENT_VAR = "__CrashDumpFolder";
209

210
        static bool CollectCrashDump(Process process, string crashDumpPath, StreamWriter outputWriter)
211 212 213
        {
            string coreRoot = Environment.GetEnvironmentVariable("CORE_ROOT");
            string createdumpPath = Path.Combine(coreRoot, "createdump");
214
            string arguments = $"--name \"{crashDumpPath}\" {process.Id} --withheap";
215
            Process createdump = new Process();
216
            bool crashReportPresent = false;
217

218
            if (OperatingSystem.IsWindows())
219 220 221
            {
                createdump.StartInfo.FileName = createdumpPath + ".exe";
                createdump.StartInfo.Arguments = arguments;
222
            }
223
            else if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
224
            {
225
                createdump.StartInfo.FileName = "sudo";
226 227
                createdump.StartInfo.Arguments = $"{createdumpPath} --crashreport {arguments}";
                crashReportPresent = true;
228 229
            }

230 231 232
            createdump.StartInfo.UseShellExecute = false;
            createdump.StartInfo.RedirectStandardOutput = true;
            createdump.StartInfo.RedirectStandardError = true;
233

234 235
            Console.WriteLine($"Invoking: {createdump.StartInfo.FileName} {createdump.StartInfo.Arguments}");
            createdump.Start();
236

237 238 239
            Task<string> copyOutput = createdump.StandardOutput.ReadToEndAsync();
            Task<string> copyError = createdump.StandardError.ReadToEndAsync();
            bool fSuccess = createdump.WaitForExit(DEFAULT_TIMEOUT_MS);
240

241 242 243 244 245 246 247 248 249 250
            if (fSuccess)
            {
                Task.WaitAll(copyError, copyOutput);
                string output = copyOutput.Result;
                string error = copyError.Result;

                Console.WriteLine("createdump stdout:");
                Console.WriteLine(output);
                Console.WriteLine("createdump stderr:");
                Console.WriteLine(error);
251 252 253 254 255

                if (crashReportPresent)
                {
                    TryPrintStackTraceFromCrashReport(crashDumpPath + ".crashreport.json", outputWriter);
                }
256 257 258 259
            }
            else
            {
                createdump.Kill(true);
260 261
            }

262
            return fSuccess && createdump.ExitCode == 0;
263 264
        }

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
        private static List<string> knownNativeModules = new List<string>() { "libcoreclr.so", "libclrjit.so" };
        private static string TO_BE_CONTINUE_TAG = "<TO_BE_CONTINUE>";
        private static string SKIP_LINE_TAG = "# <SKIP_LINE>";


        static bool RunProcess(string fileName, string arguments)
        {
            Process proc = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    FileName = fileName,
                    Arguments = arguments,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                }
            };

            Console.WriteLine($"Invoking: {proc.StartInfo.FileName} {proc.StartInfo.Arguments}");
            proc.Start();

            Task<string> stdOut = proc.StandardOutput.ReadToEndAsync();
            Task<string> stdErr = proc.StandardError.ReadToEndAsync();
            if(!proc.WaitForExit(DEFAULT_TIMEOUT_MS))
            {
                proc.Kill(true);
                Console.WriteLine($"Timedout: '{fileName} {arguments}");
                return false;
            }

            Task.WaitAll(stdOut, stdErr);
            string output = stdOut.Result;
            string error = stdErr.Result;
            if (!string.IsNullOrWhiteSpace(output))
            {
                Console.WriteLine($"stdout: {output}");
            }
            if (!string.IsNullOrWhiteSpace(error))
            {
                Console.WriteLine($"stderr: {error}");
            }
            return true;
        }

        /// <summary>
        ///     Parse crashreport.json file, use llvm-symbolizer to extract symbols
        ///     and recreate the stacktrace that is printed on the console.
        /// </summary>
        /// <param name="crashReportJsonFile">crash dump path</param>
        /// <param name="outputWriter">Stream for writing logs</param>
        /// <returns>true, if we can print the stack trace, otherwise false.</returns>
        static bool TryPrintStackTraceFromCrashReport(string crashReportJsonFile, StreamWriter outputWriter)
        {
            if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
            {
                if (!RunProcess("sudo", $"ls -l {crashReportJsonFile}"))
                {
                    return false;
                }

                Console.WriteLine("=========================================");
                string userName = Environment.GetEnvironmentVariable("USER");
                if (!string.IsNullOrEmpty(userName))
                {
                    if (!RunProcess("sudo", $"chown {userName} {crashReportJsonFile}"))
                    {
                        return false;
                    }

                    Console.WriteLine("=========================================");
                    if (!RunProcess("sudo", $"ls -l {crashReportJsonFile}"))
                    {
                        return false;
                    }

                    Console.WriteLine("=========================================");
                    if (!RunProcess("ls", $"-l {crashReportJsonFile}"))
                    {
                        return false;
                    }
                }
            }

            if (!File.Exists(crashReportJsonFile))
            {
                return false;
            }
            outputWriter.WriteLine($"Printing stacktrace from '{crashReportJsonFile}'");

355 356 357 358 359 360 361 362 363 364
            string contents;
            try
            {
                contents = File.ReadAllText(crashReportJsonFile);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error reading {crashReportJsonFile}: {ex.ToString()}");
                return false;
            }
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
            dynamic crashReport = JsonSerializer.Deserialize<JsonObject>(contents);
            var threads = crashReport["payload"]["threads"];

            // The logic happens in 3 steps:
            // 1. Read the crashReport.json file, locate all the addresses of interest and then build
            //    a string that will be passed to llvm-symbolizer. It is populated so that each address
            //    is in its separate line along with the file name, etc. Some TAGS are added in the
            //    string that is used in step 2.
            // 2. llvm-symbolizer is ran and above string is passed as input.
            // 3. After llvm-symbolizer completes, TAGS are used to format its output to print it in
            //    the way it will be printed by sos.

            StringBuilder addrBuilder = new StringBuilder();
            string coreRoot = Environment.GetEnvironmentVariable("CORE_ROOT");
            foreach (var thread in threads)
            {

                if (thread["native_thread_id"] == null)
                {
                    continue;
                }

                addrBuilder.AppendLine();
                addrBuilder.AppendLine("----------------------------------");
                addrBuilder.AppendLine($"Thread Id: {thread["native_thread_id"]}");
                addrBuilder.AppendLine("      Child SP               IP Call Site");
                var stack_frames = thread["stack_frames"];
                foreach (var frame in stack_frames)
                {
                    addrBuilder.Append($"{SKIP_LINE_TAG} {frame["stack_pointer"]} {frame["native_address"]} ");
                    bool isNative = (string)frame["is_managed"] == "false";

                    if (isNative)
                    {
                        string nativeModuleName = (string)frame["native_module"];
                        string unmanagedName = (string)frame["unmanaged_name"];

                        if ((nativeModuleName != null) && (knownNativeModules.Contains(nativeModuleName)))
                        {
                            // Need to use llvm-symbolizer (only if module_address != 0)
                            AppendAddress(addrBuilder, coreRoot, nativeModuleName, (string)frame["native_address"], (string)frame["module_address"]);
                        }
                        else if ((nativeModuleName != null) || (unmanagedName != null))
                        {
                            if (nativeModuleName != null)
                            {
                                addrBuilder.Append($"{nativeModuleName}!");
                            }
                            if (unmanagedName != null)
                            {
                                addrBuilder.Append($"{unmanagedName}");
                            }
                        }
                    }
                    else
                    {
                        string fileName = (string)frame["filename"];
                        string methodName = (string)frame["method_name"];

                        if ((fileName != null) || (methodName != null))
                        {
                            // found the managed method name
                            if (fileName != null)
                            {
                                addrBuilder.Append($"{fileName}!");
                            }
                            if (methodName != null)
                            {
                                addrBuilder.Append($"{methodName}");
                            }
                        }
                        else
                        {
                            addrBuilder.Append($"{frame["native_address"]}");
                        }
                    }
                    addrBuilder.AppendLine();

                }
            }

            string symbolizerOutput = null;

            Process llvmSymbolizer = new Process()
            {
                StartInfo = {
                    FileName = "llvm-symbolizer",
                    Arguments = $"--pretty-print",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,
                }
            };

            outputWriter.WriteLine($"Invoking {llvmSymbolizer.StartInfo.FileName} {llvmSymbolizer.StartInfo.Arguments}");

            try
            {
                if (!llvmSymbolizer.Start())
                {
                    outputWriter.WriteLine($"Unable to start {llvmSymbolizer.StartInfo.FileName}");
                }

                using (var symbolizerWriter = llvmSymbolizer.StandardInput)
                {
                    symbolizerWriter.WriteLine(addrBuilder.ToString());
                }

                Task<string> stdout = llvmSymbolizer.StandardOutput.ReadToEndAsync();
                Task<string> stderr = llvmSymbolizer.StandardError.ReadToEndAsync();
                bool fSuccess = llvmSymbolizer.WaitForExit(DEFAULT_TIMEOUT_MS);

                Task.WaitAll(stdout, stderr);

                if (!fSuccess)
                {
                    outputWriter.WriteLine("Errors while running llvm-symbolizer --pretty-print");
                    string output = stdout.Result;
                    string error = stderr.Result;

                    Console.WriteLine("llvm-symbolizer stdout:");
                    Console.WriteLine(output);
                    Console.WriteLine("llvm-symbolizer stderr:");
                    Console.WriteLine(error);

                    llvmSymbolizer.Kill(true);

                    return false;
                }

                symbolizerOutput = stdout.Result;

            } catch (Exception e) {
                outputWriter.WriteLine("Errors while running llvm-symbolizer --pretty-print");
                outputWriter.WriteLine(e.ToString());
                return false;
            }

            // Go through the output of llvm-symbolizer and strip all the markers we added initially.
            string[] contentsToSantize = symbolizerOutput.Split(Environment.NewLine);
            StringBuilder finalBuilder = new StringBuilder();
            for (int lineNum = 0; lineNum < contentsToSantize.Length; lineNum++)
            {
                string line = contentsToSantize[lineNum].Replace(SKIP_LINE_TAG, string.Empty);
                if (string.IsNullOrWhiteSpace(line)) continue;

                if (line.EndsWith(TO_BE_CONTINUE_TAG))
                {
                    finalBuilder.Append(line.Replace(TO_BE_CONTINUE_TAG, string.Empty));
                    continue;
                }
                finalBuilder.AppendLine(line);
            }
            outputWriter.WriteLine("Stack trace:");
            outputWriter.WriteLine(finalBuilder.ToString());
            return true;
        }

        private static void AppendAddress(StringBuilder sb, string coreRoot, string nativeModuleName, string native_address, string module_address)
        {
            if (module_address != "0x0")
            {
                sb.Append($"{nativeModuleName}!");
                sb.Append(TO_BE_CONTINUE_TAG);
                sb.AppendLine();
                //addrBuilder.AppendLine(frame.native_image_offset);
                ulong nativeAddress = ulong.Parse(native_address.Substring(2), System.Globalization.NumberStyles.HexNumber);
                ulong moduleAddress = ulong.Parse(module_address.Substring(2), System.Globalization.NumberStyles.HexNumber);
                string fullPathToModule = Path.Combine(coreRoot, nativeModuleName);
                sb.AppendFormat("{0} 0x{1:x}", fullPathToModule, nativeAddress - moduleAddress);
            }
        }

539 540 541
        // Finds all children processes starting with a process named childName
        // The children are sorted in the order they should be dumped
        static unsafe IEnumerable<Process> FindChildProcessesByName(Process process, string childName)
542
        {
543 544 545
            var children = new Stack<Process>();
            Queue<Process> childrenToCheck = new Queue<Process>();
            HashSet<int> seen = new HashSet<int>();
546

547 548 549
            seen.Add(process.Id);
            foreach (var child in process.GetChildren())
                childrenToCheck.Enqueue(child);
550

551
            while (childrenToCheck.Count != 0)
552
            {
553 554 555 556 557 558 559 560 561 562
                Process child = childrenToCheck.Dequeue();
                if (seen.Contains(child.Id))
                    continue;

                seen.Add(child.Id);

                foreach (var grandchild in child.GetChildren())
                    childrenToCheck.Enqueue(grandchild);

                if (child.ProcessName.Equals(childName, StringComparison.OrdinalIgnoreCase))
563
                {
564
                    children.Push(child);
565 566 567
                }
            }

568
            return children;
569 570
        }

571
        public int RunTest(string executable, string outputFile, string errorFile, string category, string testBinaryBase, string outputDir)
572
        {
P
Pat Gavlin 已提交
573
            Debug.Assert(outputFile != errorFile);
574 575

            int exitCode = -100;
576

577 578 579
            // If a timeout was given to us by an environment variable, use it instead of the default
            // timeout.
            string environmentVar = Environment.GetEnvironmentVariable(TIMEOUT_ENVIRONMENT_VAR);
580
            int timeout = environmentVar != null ? int.Parse(environmentVar) : DEFAULT_TIMEOUT_MS;
581 582
            bool collectCrashDumps = Environment.GetEnvironmentVariable(COLLECT_DUMPS_ENVIRONMENT_VAR) != null;
            string crashDumpFolder = Environment.GetEnvironmentVariable(CRASH_DUMP_FOLDER_ENVIRONMENT_VAR);
583

P
Pat Gavlin 已提交
584 585 586 587 588
            var outputStream = new FileStream(outputFile, FileMode.Create);
            var errorStream = new FileStream(errorFile, FileMode.Create);

            using (var outputWriter = new StreamWriter(outputStream))
            using (var errorWriter = new StreamWriter(errorStream))
589 590
            using (Process process = new Process())
            {
591
                if (MobileAppHandler.IsRetryRequested(testBinaryBase))
592
                {
593
                    outputWriter.WriteLine("\nWork item retry had been requested earlier - skipping test...");
594 595 596
                }
                else
                {
597 598 599 600 601 602 603 604 605 606 607
                    // Windows can run the executable implicitly
                    if (OperatingSystem.IsWindows())
                    {
                        process.StartInfo.FileName = executable;
                    }
                    // Non-windows needs to be told explicitly to run through /bin/bash shell
                    else
                    {
                        process.StartInfo.FileName = "/bin/bash";
                        process.StartInfo.Arguments = executable;
                    }
608

609 610 611 612 613 614
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError = true;
                    process.StartInfo.EnvironmentVariables.Add("__Category", category);
                    process.StartInfo.EnvironmentVariables.Add("__TestBinaryBase", testBinaryBase);
                    process.StartInfo.EnvironmentVariables.Add("__OutputDir", outputDir);
615

616 617
                    DateTime startTime = DateTime.Now;
                    process.Start();
618

619 620 621
                    var cts = new CancellationTokenSource();
                    Task copyOutput = process.StandardOutput.BaseStream.CopyToAsync(outputStream, 4096, cts.Token);
                    Task copyError = process.StandardError.BaseStream.CopyToAsync(errorStream, 4096, cts.Token);
622

623
                    if (process.WaitForExit(timeout))
624
                    {
625 626 627 628
                        // Process completed. Check process.ExitCode here.
                        exitCode = process.ExitCode;
                        MobileAppHandler.CheckExitCode(exitCode, testBinaryBase, category, outputWriter);
                        Task.WaitAll(copyOutput, copyError);
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654

                        if (!OperatingSystem.IsWindows())
                        {
                            // crashreport is only for non-windows.
                            if (exitCode != 0)
                            {
                                // Search for dump, if created.
                                if (Directory.Exists(crashDumpFolder))
                                {
                                    outputWriter.WriteLine($"Test failed. Trying to see if dump file was created in {crashDumpFolder} since {startTime}");
                                    DirectoryInfo crashDumpFolderInfo = new DirectoryInfo(crashDumpFolder);
                                    var dmpFilesInfo = crashDumpFolderInfo.GetFiles("*.crashreport.json").OrderByDescending(f => f.CreationTime);
                                    foreach (var dmpFile in dmpFilesInfo)
                                    {
                                        if (dmpFile.CreationTime < startTime)
                                        {
                                            // No new files since test started.
                                            outputWriter.WriteLine("Finish looking for *.crashreport.json. No new files created.");
                                            break;
                                        }
                                        outputWriter.WriteLine($"Processing {dmpFile.FullName}");
                                        TryPrintStackTraceFromCrashReport(dmpFile.FullName, outputWriter);
                                    }
                                }
                            }
                        }
655
                    }
656 657 658 659
                    else
                    {
                        // Timed out.
                        DateTime endTime = DateTime.Now;
660

661 662 663 664 665
                        try
                        {
                            cts.Cancel();
                        }
                        catch {}
666

667 668 669 670 671 672 673 674
                        outputWriter.WriteLine("\ncmdLine:{0} Timed Out (timeout in milliseconds: {1}{2}{3}, start: {4}, end: {5})",
                                executable, timeout, (environmentVar != null) ? " from variable " : "", (environmentVar != null) ? TIMEOUT_ENVIRONMENT_VAR : "",
                                startTime.ToString(), endTime.ToString());
                        errorWriter.WriteLine("\ncmdLine:{0} Timed Out (timeout in milliseconds: {1}{2}{3}, start: {4}, end: {5})",
                                executable, timeout, (environmentVar != null) ? " from variable " : "", (environmentVar != null) ? TIMEOUT_ENVIRONMENT_VAR : "",
                                startTime.ToString(), endTime.ToString());

                        if (collectCrashDumps)
675
                        {
676
                            if (crashDumpFolder != null)
677
                            {
678
                                foreach (var child in FindChildProcessesByName(process, "corerun"))
679
                                {
680 681
                                    string crashDumpPath = Path.Combine(Path.GetFullPath(crashDumpFolder), string.Format("crashdump_{0}.dmp", child.Id));
                                    Console.WriteLine($"Attempting to collect crash dump: {crashDumpPath}");
682
                                    if (CollectCrashDump(child, crashDumpPath, outputWriter))
683 684 685 686 687 688 689
                                    {
                                        Console.WriteLine("Collected crash dump: {0}", crashDumpPath);
                                    }
                                    else
                                    {
                                        Console.WriteLine("Failed to collect crash dump");
                                    }
690 691 692
                                }
                            }
                        }
693

694 695 696
                        // kill the timed out processes after we've collected dumps
                        process.Kill(entireProcessTree: true);
                    }
P
Pat Gavlin 已提交
697
                }
698

699 700 701
                outputWriter.WriteLine("Test Harness Exitcode is : " + exitCode.ToString());
                outputWriter.Flush();
                errorWriter.Flush();
702 703 704 705 706 707
            }

            return exitCode;
        }
    }
}