summaryrefslogtreecommitdiff
path: root/src/tools/runincontext/runincontext.cs
blob: 8b0d2ea6cea27889765c141fd06dfbe1ee8641f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;

public class ArgInput
{
    public bool Verbose = false;
    public string AsmName = null;
    public string AssemblyPath = null;
    public string[] EntryArgs;
    public StringBuilder EntryArgStr = null;
    public bool StressMode = false;
    public int StressModeCount = 2000;
    public int MaxRestarts = 10;
    public int IterationCount = 1;
    public bool MonitorMode = false;
    public int IterationsToSkip = 500;
    public string ReferencesPath = null;
    public bool BreakBeforeRun;
    public bool BreakAfterRun;
    public bool DelegateLoad;
    public bool BreakOnUnloadFailure;

    public static void DisplayUsage()
    {
        Console.WriteLine("Usage: RunInContext.exe [options ...] <Assembly file name> [assembly command line options]");
        Console.WriteLine("    /v                        Verbose mode");
        Console.WriteLine("    /collectstress:<n>        Emit in collectible assembly n times, checking for memory leaks(def:2000)");
        Console.WriteLine("    /maxstressrestarts:<n>    Maximum allowed stress run restarts when memory usage increases (def:10)");
        Console.WriteLine("    /iterationcount:<n>       Number of iterations in non-stress mode (def:1)");
        Console.WriteLine("    /memorymonitor:<skip>     Monitor memory usage closely. skip: number of iterations to skip before monitoring memory.");
        Console.WriteLine("    /referencespath:<path>    Path to resolve assemblies referenced by the main assembly");
        Console.WriteLine("    /breakbeforerun           Break into debugger before executing the assembly");
        Console.WriteLine("    /breakafterrun            Break into debugger after executing the assembly");
        Console.WriteLine("    /breakonunloadfailure     Break into debugger on unload failure");
        Console.WriteLine("    /delegateload             Delegate the AssemblyLoadContext.Load to a secondary AssemblyLoadContext");
    }

    public ArgInput(String[] args)
    {
        EntryArgStr = new StringBuilder();
        var assemblyArgs = new List<string>();

        for (int i = 0; i < args.Length; i++)
        {
            string option = args[i].ToLower();

            if (option.StartsWith("/v"))
            {
                Verbose = true;
            }
            else if (option.StartsWith("/collectstress"))
            {
                StressMode = true;
                if (option.Length > 14 && option[14] == ':')
                {
                    StressModeCount = int.Parse(option.Substring(15));
                }
            }
            else if (option.StartsWith("/iterationcount:"))
            {
                IterationCount = int.Parse(option.Substring(16));
            }
            else if (option.StartsWith("/breakbeforerun"))
            {
                BreakBeforeRun = true;
            }
            else if (option.StartsWith("/breakafterrun"))
            {
                BreakAfterRun = true;
            }
            else if (option.StartsWith("/breakonunloadfailure"))
            {
                BreakOnUnloadFailure = true;
            }
            else if (option.StartsWith("/delegateload"))
            {
                DelegateLoad = true;
            }
            else if (option.StartsWith("/maxstressrestarts:"))
            {
                MaxRestarts = int.Parse(option.Substring(19));
            }
            else if (option.StartsWith("/memorymonitor:"))
            {
                MonitorMode = true;
                IterationsToSkip = int.Parse(option.Substring(15));
            }
            else if (option.StartsWith("/referencespath:"))
            {
                ReferencesPath = Path.GetFullPath(args[i].Substring(16));
            }
            else
            {
                // The remaining arguments are the assembly name and its parameters
                AsmName = args[i];
                AssemblyPath = Path.GetDirectoryName(Path.GetFullPath(AsmName));

                for (i++; i < args.Length; i++)
                {
                    assemblyArgs.Add(args[i]);
                    if (args[i].Contains(" ") || args[i].Contains("\t"))
                    {
                        EntryArgStr.Append($"\"{args[i]}\"");
                    }
                    else
                    {
                        EntryArgStr.Append(args[i]);
                    }
                    EntryArgStr.Append(" ");
                }
            }
        }
        EntryArgs = assemblyArgs.ToArray();

        if (StressModeCount < 50)
        {
            Console.WriteLine("The number of stress runs is less that the minimum (50). Defaulting to 50");
            StressModeCount = 50;
        }
        if (!MonitorMode && (MaxRestarts < 5))
        {
            Console.WriteLine("The number of stress run restarts is less that the minimum (5). Defaulting to 5");
            MaxRestarts = 5;
        }
    }
}

abstract class TestAssemblyLoadContextBase : AssemblyLoadContext
{
    public TestAssemblyLoadContextBase() : base(true)
    {

    }
    public virtual void Cleanup()
    {

    }
}

class TestAssemblyLoadContext : TestAssemblyLoadContextBase
{
    public List<WeakReference> _assemblyReferences;
    string _assemblyDirectory;
    string _referencesDirectory;

    public TestAssemblyLoadContext(string assemblyDirectory, string referencesDirectory, List<WeakReference> assemblyReferences)
    {
        _assemblyDirectory = assemblyDirectory;
        _referencesDirectory = referencesDirectory;
        _assemblyReferences = assemblyReferences;
    }

    protected override Assembly Load(AssemblyName name)
    {
        Assembly assembly = null;
        try
        {
            assembly = LoadFromAssemblyPath(Path.Combine(_referencesDirectory, name.Name + ".dll"));
        }
        catch (Exception)
        {
            try
            {
                assembly = LoadFromAssemblyPath(Path.Combine(_assemblyDirectory, name.Name + ".dll"));
            }
            catch (Exception)
            {
                assembly = LoadFromAssemblyPath(Path.Combine(_assemblyDirectory, name.Name + ".exe"));
            }
        }

        lock(_assemblyReferences)
        {
            _assemblyReferences.Add(new WeakReference(assembly));
        }
        return assembly;
    }
}

class TestAssemblyLoadContextDelegating : TestAssemblyLoadContextBase
{
    public TestAssemblyLoadContextBase _delegateContext;

    public TestAssemblyLoadContextDelegating(TestAssemblyLoadContextBase delegateContext)
    {
        _delegateContext = delegateContext;
    }

    public override void Cleanup()
    {
        _delegateContext.Cleanup();
        _delegateContext = null;
    }

    protected override Assembly Load(AssemblyName name)
    {
        Assembly asm = _delegateContext.LoadFromAssemblyName(name);
        return asm;
    }
}

public class UnloadFailedException : Exception
{

}

public class TestRunner
{
    ArgInput _input;

    public TestRunner(ArgInput input)
    {
        _input = input;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    public int DoWorkNonStress()
    {
        int retVal = 0;

        for (int i = 0; i < _input.IterationCount; i++)
        {
            retVal = ExecuteAssembly();
            if (retVal != RunInContext.SuccessExitCode)
            {
                break;
            }
        }

        return retVal;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    public int DoWorkStress()
    {
        //Stress mode

        Process p = Process.GetCurrentProcess();
        long startMemory = p.PrivateMemorySize64;
        long currentMemory = startMemory;
        long monitorStartMem = 0;
        long startSpeed = 0;
        long currentSpeed = 0;
        int restarts = 0;
        long leak = 0;
        int i;
        int lastProgressReport = 0;
        int retVal = 0;

        for (i = 1; i <= _input.StressModeCount; i++)
        {
            if (!_input.MonitorMode && (((i * 1.0) / _input.StressModeCount) * 100 > lastProgressReport))
            {
                Console.WriteLine("Completed: {0}%...", lastProgressReport);
                lastProgressReport += 10;
            }

            Stopwatch sw = new Stopwatch();
            sw.Start();
            retVal = ExecuteAssembly();
            sw.Stop();

            if (retVal != RunInContext.SuccessExitCode)
            {
                break;
            }

            currentSpeed = sw.ElapsedMilliseconds;

            p = Process.GetCurrentProcess();
            currentMemory = p.PrivateMemorySize64;
            if (_input.MonitorMode)
            {
                if (i == _input.IterationsToSkip)
                {
                    startMemory = monitorStartMem = currentMemory;
                }

                if (currentMemory > startMemory)
                {
                    Console.WriteLine($"\n\n +++ Memory usage increased by {currentMemory - startMemory} bytes at iteration {i}!!                                                 ");
                    if (i > _input.IterationsToSkip)
                    {
                        leak = (long)((currentMemory - monitorStartMem) / ((i - _input.IterationsToSkip) * 1.0));
                    }
                    startMemory = currentMemory;
                }
                else if (currentMemory < startMemory)
                {
                    Console.WriteLine($"\n\n --- Memory usage decreased by {startMemory - currentMemory} bytes at iteration {i}                                                 ");
                    startMemory = currentMemory;
                }

                Console.Write($"Private Memory Size = {currentMemory / 1024}K after {i + 1} iterations.");

                if (i > _input.IterationsToSkip)
                {
                    Console.Write($" Average leak: {leak} bytes/iteration. speed: {(int)currentSpeed} ms/type.");
                }

                Console.WriteLine();
            }
            else
            {
                if (currentMemory > startMemory)
                {
                    leak = (currentMemory - startMemory) / i;
                    Console.WriteLine($"LOOP #{i}: Memory usage increased by {_input.MaxRestarts - restarts - 1} bytes! Restarting test... ({currentMemory - startMemory} restarts left)");
                    Console.WriteLine($"    + Average leak over the last {i} iterations: {leak} bytes\n");

                    restarts++;
                    if (restarts == _input.MaxRestarts)
                    {
                        break;
                    }
                    i = 0;
                    startMemory = currentMemory;
                    leak = 0;
                    lastProgressReport = 0;
                    continue;
                }
            }

            if ((i == 2) && (startSpeed == 0))
            {
                startSpeed = currentSpeed;
            }
        }

        //sometimes this happens (no real reason, but it's not a failure, so let's not write a "negative" leak to the output)
        if (currentMemory < startMemory)
        {
            startMemory = currentMemory;
            leak = 0;
        }
        if (_input.MonitorMode)
        {
            leak = (long)((currentMemory - monitorStartMem) / ((_input.StressModeCount * 1.0) - _input.IterationsToSkip));
            startMemory = monitorStartMem;
        }

        Console.WriteLine("\n==================================================");
        Console.WriteLine($"Starting memory size          : {startMemory / 1024} KB");
        Console.WriteLine($"Ending memory size            : {currentMemory / 1024} KB");
        Console.WriteLine();
        Console.WriteLine($"Starting emission speed       : {startSpeed} milliseconds");
        Console.WriteLine($"Ending emission speed         : {currentSpeed} milliseconds");
        Console.WriteLine();
        Console.WriteLine($"Memory leak                   : {currentMemory - startMemory} bytes ({leak} bytes per iteration).");
        if (currentMemory > startMemory)
        {
            throw new Exception("Memory leaked");
        }

        return retVal;
    }

    public int ExecuteAssemblyEntryPoint(MethodInfo entryPoint)
    {
        int result = 0;

        object res;
        object[] args = (entryPoint.GetParameters().Length != 0) ? new object[] { _input.EntryArgs } : null;
        string argsStr = (args == null) ? "" : _input.EntryArgStr.ToString();

        if (_input.Verbose)
        {
            Console.WriteLine($"Invoking Main({argsStr})\n");
        }

        res = entryPoint.Invoke(null, args);

        result = (entryPoint.ReturnType == typeof(void)) ? Environment.ExitCode : Convert.ToInt32(res);

        return result;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    public int ExecuteAndUnload(List<WeakReference> assemblyReferences, out WeakReference testAlcWeakRef, out WeakReference testAlcWeakRefInner)
    {
        int result;
        TestAssemblyLoadContextBase testAlc = new TestAssemblyLoadContext(_input.AssemblyPath, _input.ReferencesPath, assemblyReferences);

        if (_input.DelegateLoad)
        {
            testAlcWeakRefInner = new WeakReference(testAlc, trackResurrection: true);
            testAlc = new TestAssemblyLoadContextDelegating(testAlc);
        }
        else
        {
            testAlcWeakRefInner = new WeakReference(null);
        }

        testAlcWeakRef = new WeakReference(testAlc, trackResurrection: true);

        Assembly inputAssembly = null;
        try
        {
            inputAssembly = testAlc.LoadFromAssemblyPath(_input.AsmName);
        }
        catch (Exception LoadEx)
        {
            Console.WriteLine($"Failed to load assembly <{_input.AsmName}>!");
            Console.WriteLine($"Exception: {LoadEx.ToString()}");
            throw;
        }

        assemblyReferences.Add(new WeakReference(inputAssembly));

        Stopwatch sw = new Stopwatch();
        sw.Start();
        result = ExecuteAssemblyEntryPoint(inputAssembly.EntryPoint);
        sw.Stop();

        if (_input.Verbose)
        {
            Console.WriteLine($"Execution time: {sw.Elapsed}");

            foreach (WeakReference wr in assemblyReferences)
            {
                if (wr.Target != null)
                {
                    Console.WriteLine("Unloading Assembly [" + wr.Target + "]");
                }
            }
        }

        testAlc.Cleanup();
        testAlc.Unload();

        testAlc = null;
        inputAssembly = null;

        return result;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    bool VerifyAssembliesUnloaded(List<WeakReference> assemblyReferences)
    {
        bool unloadSucceeded = true;

        foreach (WeakReference wr in assemblyReferences)
        {
            if (wr.Target != null)
            {
                if (_input.Verbose)
                {
                    Console.WriteLine("FAILURE: Assembly [" + wr.Target + "] was not unloaded!");
                }
                unloadSucceeded = false;
            }
        }

        return unloadSucceeded;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    int ExecuteAssembly()
    {
        List<WeakReference> assemblyReferences = new List<WeakReference>();
        WeakReference testAlcWeakRef;
        WeakReference testAlcWeakRefInner;

        if (_input.BreakBeforeRun)
        {
            Debugger.Break();
        }

        int result = ExecuteAndUnload(assemblyReferences, out testAlcWeakRef, out testAlcWeakRefInner);

        for (int i = 0; (testAlcWeakRef.IsAlive || testAlcWeakRefInner.IsAlive) && (i < 100); i++)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Thread.Sleep(10);
        }

        if (_input.BreakAfterRun)
        {
            Debugger.Break();
        }

        bool unloadSucceeded = VerifyAssembliesUnloaded(assemblyReferences);

        if (!unloadSucceeded)
        {
            if (_input.BreakOnUnloadFailure)
            {
                Debugger.Break();
            }

            throw new UnloadFailedException();
        }

        return result;
    }
}

public class RunInContext
{
    public static int FailureExitCode = 213;
    public static int SuccessExitCode = 100;

    public static int Main(String[] args)
    {
        if (args.Length == 0)
        {
            ArgInput.DisplayUsage();
            return FailureExitCode;
        }

        ArgInput input = new ArgInput(args);
        TestRunner runner = new TestRunner(input);

        AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

        int retVal = FailureExitCode;
        try
        {
            if (!input.StressMode)
            {
                retVal = runner.DoWorkNonStress();
            }
            else
            {
                retVal = runner.DoWorkStress();
            }
        }
        catch (UnloadFailedException)
        {
            Console.WriteLine($"FAILURE: Unload failed");
        }
        catch (Exception ex)
        {
            if (input.Verbose)
            {
                Console.WriteLine($"FAILURE: Exception: {ex.ToString()}");
            }
            else
            {
                Console.WriteLine($"FAILURE: Exception: {ex.Message}");
            }
        }

        string status = (retVal == FailureExitCode) ? "FAIL" : "PASS";

        Console.WriteLine();
        Console.WriteLine($"RunInContext {status}! Exiting with code {retVal}");

        return retVal;
    }

    private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        Console.WriteLine($"RunInContext FAIL! Exiting due to unhandled exception in the test: {e.ExceptionObject}");
        Environment.Exit(FailureExitCode);
    }

}