How to use RewritingEngine class of Microsoft.Coyote.Rewriting package

Best Coyote code snippet using Microsoft.Coyote.Rewriting.RewritingEngine

RewritingEngine.cs

Source:RewritingEngine.cs Github

copy

Full Screen

...23 /// </summary>24 /// <remarks>25 /// See <see href="/coyote/tools/rewriting">Coyote rewriting tool</see> for more information.26 /// </remarks>27 public class RewritingEngine28 {29 /// <summary>30 /// Temporary directory that is used to write the rewritten assemblies31 /// in the case that they are replacing the original ones.32 /// </summary>33 /// <remarks>34 /// We need this because it seems Mono.Cecil does not allow to rewrite in-place.35 /// </remarks>36 private const string TempDirectory = "__temp_coyote__";37 /// <summary>38 /// Options for rewriting assemblies.39 /// </summary>40 private readonly RewritingOptions Options;41 /// <summary>42 /// The test configuration to use when rewriting unit tests.43 /// </summary>44 private readonly Configuration Configuration;45 /// <summary>46 /// List of assemblies that are not allowed to be rewritten.47 /// </summary>48 private readonly Regex DisallowedAssemblies;49 private readonly string[] DefaultDisallowedList = new string[]50 {51 @"Newtonsoft\.Json\.dll",52 @"Microsoft\.Coyote\.dll",53 @"Microsoft\.Coyote.Test\.dll",54 @"Microsoft\.VisualStudio\.TestPlatform.*",55 @"Microsoft\.TestPlatform.*",56 @"System\.Private\.CoreLib\.dll",57 @"mscorlib\.dll"58 };59 /// <summary>60 /// List of transforms we are applying while rewriting.61 /// </summary>62 private readonly List<AssemblyTransform> Transforms;63 /// <summary>64 /// Map from assembly name to full name definition of the rewritten assemblies.65 /// </summary>66 private readonly Dictionary<string, AssemblyNameDefinition> RewrittenAssemblies;67 /// <summary>68 /// List of assemblies to be rewritten.69 /// </summary>70 private Queue<string> Pending = new Queue<string>();71 /// <summary>72 /// The installed logger.73 /// </summary>74 private readonly ILogger Logger;75 /// <summary>76 /// The profiler.77 /// </summary>78 private readonly Profiler Profiler;79 /// <summary>80 /// Initializes a new instance of the <see cref="RewritingEngine"/> class.81 /// </summary>82 /// <param name="configuration">The test configuration to use when rewriting unit tests.</param>83 /// <param name="options">The <see cref="RewritingOptions"/> for this rewriter.</param>84 private RewritingEngine(Configuration configuration, RewritingOptions options)85 {86 this.Configuration = configuration;87 this.Options = options;88 this.Logger = options.Logger ?? new ConsoleLogger() { LogLevel = options.LogLevel };89 this.Profiler = new Profiler();90 this.RewrittenAssemblies = new Dictionary<string, AssemblyNameDefinition>();91 var ignoredAssemblies = options.IgnoredAssemblies ?? Array.Empty<string>();92 StringBuilder combined = new StringBuilder();93 foreach (var e in this.DefaultDisallowedList.Concat(ignoredAssemblies))94 {95 combined.Append(combined.Length is 0 ? "(" : "|");96 combined.Append(e);97 }98 combined.Append(")");99 try100 {101 this.DisallowedAssemblies = new Regex(combined.ToString());102 }103 catch (Exception ex)104 {105 throw new Exception("DisallowedAssemblies not a valid regular expression\n" + ex.Message);106 }107 this.Transforms = new List<AssemblyTransform>()108 {109 new TaskTransform(this.Logger),110 new MonitorTransform(this.Logger),111 new ExceptionFilterTransform(this.Logger)112 };113 if (this.Options.IsRewritingThreads)114 {115 this.Transforms.Add(new ThreadTransform(this.Logger));116 }117 if (this.Options.IsRewritingUnitTests)118 {119 // We are running this pass last, as we are rewriting the original method, and120 // we need the other rewriting passes to happen before this pass.121 this.Transforms.Add(new MSTestTransform(this.Configuration, this.Logger));122 }123 this.Transforms.Add(new AssertionInjectionTransform(this.Logger));124 this.Transforms.Add(new NotSupportedInvocationTransform(this.Logger));125 // expand folder126 if (this.Options.AssemblyPaths is null || this.Options.AssemblyPaths.Count is 0)127 {128 // Expand to include all .dll files in AssemblyPaths.129 foreach (var file in Directory.GetFiles(this.Options.AssembliesDirectory, "*.dll"))130 {131 if (this.IsDisallowed(Path.GetFileName(file)))132 {133 this.Options.AssemblyPaths.Add(file);134 }135 else136 {137 Debug.WriteLine("Skipping " + file);138 }139 }140 }141 }142 /// <summary>143 /// Runs the engine using the specified rewriting options.144 /// </summary>145 public static void Run(Configuration configuration, RewritingOptions options)146 {147 if (string.IsNullOrEmpty(options.AssembliesDirectory))148 {149 throw new Exception("Please provide RewritingOptions.AssembliesDirectory");150 }151 if (string.IsNullOrEmpty(options.OutputDirectory))152 {153 throw new Exception("Please provide RewritingOptions.OutputDirectory");154 }155 if (options.AssemblyPaths is null || options.AssemblyPaths.Count is 0)156 {157 throw new Exception("Please provide RewritingOptions.AssemblyPaths");158 }159 var engine = new RewritingEngine(configuration, options);160 engine.Run();161 }162 /// <summary>163 /// Runs the engine.164 /// </summary>165 private void Run()166 {167 this.Profiler.StartMeasuringExecutionTime();168 // Create the output directory and copy any necessary files.169 string outputDirectory = this.CreateOutputDirectoryAndCopyFiles();170 this.Pending = new Queue<string>();171 int errors = 0;172 // Rewrite the assembly files to the output directory.173 foreach (string assemblyPath in this.Options.AssemblyPaths)174 {175 this.Pending.Enqueue(assemblyPath);176 }177 while (this.Pending.Count > 0)178 {179 var assemblyPath = this.Pending.Dequeue();180 try181 {182 this.RewriteAssembly(assemblyPath, outputDirectory);183 }184 catch (Exception ex)185 {186 if (!this.Options.IsReplacingAssemblies)187 {188 // Make sure to copy the original assembly to avoid any corruptions.189 CopyFile(assemblyPath, outputDirectory);190 }191 if (ex is AggregateException ae && ae.InnerException != null)192 {193 this.Logger.WriteLine(LogSeverity.Error, ae.InnerException.Message);194 }195 else196 {197 this.Logger.WriteLine(LogSeverity.Error, ex.Message);198 }199 errors++;200 }201 }202 if (errors is 0 && this.Options.IsReplacingAssemblies)203 {204 // If we are replacing the original assemblies, then delete the temporary output directory.205 Directory.Delete(outputDirectory, true);206 }207 this.Profiler.StopMeasuringExecutionTime();208 Console.WriteLine($". Done rewriting in {this.Profiler.Results()} sec");209 }210 /// <summary>211 /// Rewrites the specified assembly definition.212 /// </summary>213 private void RewriteAssembly(string assemblyPath, string outputDirectory)214 {215 string assemblyName = Path.GetFileName(assemblyPath);216 if (this.IsDisallowed(assemblyName))217 {218 throw new InvalidOperationException($"Rewriting the '{assemblyName}' assembly ({assemblyPath}) is not allowed.");219 }220 else if (this.RewrittenAssemblies.ContainsKey(Path.GetFileNameWithoutExtension(assemblyPath)))221 {222 // The assembly is already rewritten, so skip it.223 return;224 }225 string outputPath = Path.Combine(outputDirectory, assemblyName);226 using var assemblyResolver = this.GetAssemblyResolver();227 var readParams = new ReaderParameters()228 {229 AssemblyResolver = assemblyResolver,230 ReadSymbols = IsSymbolFileAvailable(assemblyPath)231 };232 using (var assembly = AssemblyDefinition.ReadAssembly(assemblyPath, readParams))233 {234 this.Logger.WriteLine($"... Rewriting the '{assemblyName}' assembly ({assembly.FullName})");235 if (this.Options.IsRewritingDependencies)236 {237 // Check for dependencies and if those are found in the same folder then rewrite them also,238 // and fix up the version numbers so the rewritten assemblies are bound to these versions.239 this.AddLocalDependencies(assemblyPath, assembly);240 }241 this.RewrittenAssemblies[assembly.Name.Name] = assembly.Name;242 if (IsAssemblyRewritten(assembly))243 {244 // The assembly has been already rewritten by this version of Coyote, so skip it.245 this.Logger.WriteLine(LogSeverity.Warning, $"..... Skipping assembly with reason: already rewritten by Coyote v{GetAssemblyRewritterVersion()}");246 return;247 }248 else if (IsMixedModeAssembly(assembly))249 {250 // Mono.Cecil does not support writing mixed-mode assemblies.251 this.Logger.WriteLine(LogSeverity.Warning, $"..... Skipping assembly with reason: rewriting a mixed-mode assembly is not supported");252 return;253 }254 this.FixAssemblyReferences(assembly);255 ApplyIsAssemblyRewrittenAttribute(assembly);256 foreach (var transform in this.Transforms)257 {258 // Traverse the assembly to apply each transformation pass.259 Debug.WriteLine($"..... Applying the '{transform.GetType().Name}' transform");260 foreach (var module in assembly.Modules)261 {262 RewriteModule(module, transform);263 }264 }265 // Write the binary in the output path with portable symbols enabled.266 this.Logger.WriteLine($"... Writing the modified '{assemblyName}' assembly to " +267 $"{(this.Options.IsReplacingAssemblies ? assemblyPath : outputPath)}");268 var writeParams = new WriterParameters()269 {270 WriteSymbols = readParams.ReadSymbols,271 SymbolWriterProvider = new PortablePdbWriterProvider()272 };273 if (!string.IsNullOrEmpty(this.Options.StrongNameKeyFile))274 {275 using FileStream fs = File.Open(this.Options.StrongNameKeyFile, FileMode.Open);276 writeParams.StrongNameKeyPair = new StrongNameKeyPair(fs);277 }278 assembly.Write(outputPath, writeParams);279 }280 if (this.Options.IsReplacingAssemblies)281 {282 string targetPath = Path.Combine(this.Options.AssembliesDirectory, assemblyName);283 this.CopyWithRetriesAsync(outputPath, assemblyPath).Wait();284 if (readParams.ReadSymbols)285 {286 string pdbFile = Path.ChangeExtension(outputPath, "pdb");287 string targetPdbFile = Path.ChangeExtension(targetPath, "pdb");288 this.CopyWithRetriesAsync(pdbFile, targetPdbFile).Wait();289 }290 }291 }292 private async Task CopyWithRetriesAsync(string srcFile, string targetFile)293 {294 for (int retries = 10; retries >= 0; retries--)295 {296 try297 {298 File.Copy(srcFile, targetFile, true);299 }300 catch (Exception)301 {302 if (retries is 0)303 {304 throw;305 }306 await Task.Delay(100);307 this.Logger.WriteLine(LogSeverity.Warning, $"... Retrying write to {targetFile}");308 }309 }310 }311 private void FixAssemblyReferences(AssemblyDefinition assembly)312 {313 foreach (var module in assembly.Modules)314 {315 for (int i = 0, n = module.AssemblyReferences.Count; i < n; i++)316 {317 var ar = module.AssemblyReferences[i];318 var name = ar.Name;319 if (this.RewrittenAssemblies.TryGetValue(name, out AssemblyNameDefinition rewrittenName))320 {321 // rewrite this reference to point to the newly rewritten assembly.322 var refName = AssemblyNameReference.Parse(rewrittenName.FullName);323 module.AssemblyReferences[i] = refName;324 }325 }326 }327 }328 /// <summary>329 /// Enqueue any dependent assemblies that also exist in the assemblyPath and have not330 /// already been rewritten.331 /// </summary>332 private void AddLocalDependencies(string assemblyPath, AssemblyDefinition assembly)333 {334 var assemblyDir = Path.GetDirectoryName(assemblyPath);335 foreach (var module in assembly.Modules)336 {337 foreach (var ar in module.AssemblyReferences)338 {339 var name = ar.Name + ".dll";340 var localName = Path.Combine(assemblyDir, name);341 if (!this.IsDisallowed(name) &&342 File.Exists(localName) && !this.Pending.Contains(localName))343 {344 this.Pending.Enqueue(localName);345 }346 }347 }348 }349 /// <summary>350 /// Rewrites the specified module definition using the specified transform.351 /// </summary>352 private static void RewriteModule(ModuleDefinition module, AssemblyTransform transform)353 {354 Debug.WriteLine($"....... Module: {module.Name} ({module.FileName})");355 transform.VisitModule(module);356 foreach (var type in module.GetTypes())357 {358 RewriteType(type, transform);359 }360 }361 /// <summary>362 /// Rewrites the specified type definition using the specified transform.363 /// </summary>364 private static void RewriteType(TypeDefinition type, AssemblyTransform transform)365 {366 Debug.WriteLine($"......... Type: {type.FullName}");367 transform.VisitType(type);368 foreach (var field in type.Fields.ToArray())369 {370 Debug.WriteLine($"........... Field: {field.FullName}");371 transform.VisitField(field);372 }373 foreach (var method in type.Methods.ToArray())374 {375 RewriteMethod(method, transform);376 }377 }378 /// <summary>379 /// Rewrites the specified method definition using the specified transform.380 /// </summary>381 private static void RewriteMethod(MethodDefinition method, AssemblyTransform transform)382 {383 if (method.Body is null)384 {385 return;386 }387 Debug.WriteLine($"........... Method {method.FullName}");388 transform.VisitMethod(method);389 }390 /// <summary>391 /// Applies the <see cref="IsAssemblyRewrittenAttribute"/> attribute to the specified assembly. This attribute392 /// indicates that the assembly has been rewritten with the current version of Coyote.393 /// </summary>394 private static void ApplyIsAssemblyRewrittenAttribute(AssemblyDefinition assembly)395 {396 CustomAttribute attribute = GetCustomAttribute(assembly, typeof(IsAssemblyRewrittenAttribute));397 var attributeArgument = new CustomAttributeArgument(398 assembly.MainModule.ImportReference(typeof(string)),399 GetAssemblyRewritterVersion().ToString());400 if (attribute is null)401 {402 MethodReference attributeConstructor = assembly.MainModule.ImportReference(403 typeof(IsAssemblyRewrittenAttribute).GetConstructor(new Type[] { typeof(string) }));404 attribute = new CustomAttribute(attributeConstructor);405 attribute.ConstructorArguments.Add(attributeArgument);406 assembly.CustomAttributes.Add(attribute);407 }408 else409 {410 attribute.ConstructorArguments[0] = attributeArgument;411 }412 }413 /// <summary>414 /// Creates the output directory, if it does not already exists, and copies all necessery files.415 /// </summary>416 /// <returns>The output directory path.</returns>417 private string CreateOutputDirectoryAndCopyFiles()418 {419 string sourceDirectory = this.Options.AssembliesDirectory;420 string outputDirectory = Directory.CreateDirectory(this.Options.IsReplacingAssemblies ?421 Path.Combine(this.Options.OutputDirectory, TempDirectory) : this.Options.OutputDirectory).FullName;422 if (!this.Options.IsReplacingAssemblies)423 {424 this.Logger.WriteLine($"... Copying all files to the '{outputDirectory}' directory");425 // Copy all files to the output directory, skipping any nested directory files.426 foreach (string filePath in Directory.GetFiles(sourceDirectory, "*"))427 {428 Debug.WriteLine($"..... Copying the '{filePath}' file");429 CopyFile(filePath, outputDirectory);430 }431 // Copy all nested directories to the output directory, while preserving directory structure.432 foreach (string directoryPath in Directory.GetDirectories(sourceDirectory, "*", SearchOption.AllDirectories))433 {434 // Avoid copying the output directory itself.435 if (!directoryPath.StartsWith(outputDirectory))436 {437 Debug.WriteLine($"..... Copying the '{directoryPath}' directory");438 string path = Path.Combine(outputDirectory, directoryPath.Remove(0, sourceDirectory.Length).TrimStart('\\', '/'));439 Directory.CreateDirectory(path);440 foreach (string filePath in Directory.GetFiles(directoryPath, "*"))441 {442 Debug.WriteLine($"....... Copying the '{filePath}' file");443 CopyFile(filePath, path);444 }445 }446 }447 }448 // Copy all the dependent assemblies449 foreach (var type in new Type[]450 {451 typeof(ControlledTask),452 typeof(RewritingEngine),453 typeof(TelemetryConfiguration),454 typeof(EventTelemetry),455 typeof(ITelemetry),456 typeof(TelemetryClient)457 })458 {459 string assemblyPath = type.Assembly.Location;460 CopyFile(assemblyPath, this.Options.OutputDirectory);461 }462 return outputDirectory;463 }464 /// <summary>465 /// Copies the specified file to the destination.466 /// </summary>...

Full Screen

Full Screen

Program.cs

Source:Program.cs Github

copy

Full Screen

...121 Task.WaitAll(tasks.ToArray());122 }123 private static void CheckRewritten()124 {125 if (!RunningMain && !Microsoft.Coyote.Rewriting.RewritingEngine.IsAssemblyRewritten(typeof(Program).Assembly))126 {127 throw new Exception(string.Format("Error: please rewrite this assembly using coyote rewrite {0}",128 typeof(Program).Assembly.Location));129 }130 }131 }132}...

Full Screen

Full Screen

BaseSystematicTest.cs

Source:BaseSystematicTest.cs Github

copy

Full Screen

...18 {19 get20 {21 var assembly = this.GetType().Assembly;22 bool result = RewritingEngine.IsAssemblyRewritten(assembly);23 Assert.True(result, $"Expected the '{assembly}' assembly to be rewritten.");24 return result;25 }26 }27 protected static void AssertSharedEntryValue(SharedEntry entry, int expected) =>28 Specification.Assert(entry.Value == expected, "Value is {0} instead of {1}.", entry.Value, expected);29 protected class SharedEntry30 {31 public volatile int Value = 0;32 public async Task<int> GetWriteResultAsync(int value)33 {34 this.Value = value;35 await Task.CompletedTask;36 return this.Value;...

Full Screen

Full Screen

RewritingEngine

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Microsoft.Coyote.Rewriting;7{8 {9 static void Main(string[] args)10 {11 var engine = new RewritingEngine();12 engine.Rewrite(args);13 }14 }15}16using System;17using System.Collections.Generic;18using System.Linq;19using System.Text;20using System.Threading.Tasks;21using Microsoft.Coyote;22{23 {24 static void Main(string[] args)25 {26 var runtime = new CoyoteRuntime();27 runtime.Run(args);28 }29 }30}

Full Screen

Full Screen

RewritingEngine

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Rewriting;2using System;3using System.Collections.Generic;4using System.Linq;5using System.Text;6using System.Threading.Tasks;7{8 {9 public static void Main(string[] args)10 {11 RewritingEngine engine = new RewritingEngine();12 engine.RewriteAssembly("ConsoleApplication1.exe", "ConsoleApplication1_rewrited.exe");13 }14 }15}

Full Screen

Full Screen

RewritingEngine

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Rewriting;2{3 static void Main(string[] args)4 {5 var rewriter = new RewritingEngine();6 rewriter.RewriteAssembly("1.exe");7 }8}9using Microsoft.Coyote.Rewriting;10{11 static void Main(string[] args)12 {13 var rewriter = new RewritingEngine();14 rewriter.RewriteAssembly("2.exe");15 }16}17using Microsoft.Coyote.Rewriting;18{19 static void Main(string[] args)20 {21 var rewriter = new RewritingEngine();22 rewriter.RewriteAssembly("3.exe");23 }24}25using Microsoft.Coyote.Rewriting;26{27 static void Main(string[] args)28 {29 var rewriter = new RewritingEngine();30 rewriter.RewriteAssembly("4.exe");31 }32}33using Microsoft.Coyote.Rewriting;34{35 static void Main(string[] args)36 {37 var rewriter = new RewritingEngine();38 rewriter.RewriteAssembly("5.exe");39 }40}41using Microsoft.Coyote.Rewriting;42{43 static void Main(string[] args)44 {45 var rewriter = new RewritingEngine();46 rewriter.RewriteAssembly("6.exe");47 }48}49using Microsoft.Coyote.Rewriting;50{51 static void Main(string[] args)52 {53 var rewriter = new RewritingEngine();54 rewriter.RewriteAssembly("7.exe");55 }56}

Full Screen

Full Screen

RewritingEngine

Using AI Code Generation

copy

Full Screen

1using System;2using Microsoft.Coyote.Rewriting;3{4 {5 public static void Main(string[] args)6 {7 RewritingEngine engine = new RewritingEngine();8 engine.RewriteAssembly("1.exe");9 }10 }11}12using System;13using Microsoft.Coyote.Rewriting;14{15 {16 public static void Main(string[] args)17 {18 RewritingEngine engine = new RewritingEngine();19 engine.RewriteAndExecuteAssembly("1.exe");20 }21 }22}

Full Screen

Full Screen

RewritingEngine

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Rewriting;2using System;3{4 static void Main(string[] args)5 {6 var engine = new RewritingEngine();7 engine.RewriteAssembly("1.exe", "1_rewritten.exe");8 }9}10using System;11{12 static void Main(string[] args)13 {14 Console.WriteLine("Hello World!");15 }16}17using System;18{19 static void Main(string[] args)20 {21 Console.WriteLine("Hello World!");22 }23}

Full Screen

Full Screen

RewritingEngine

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Rewriting;2{3 {4 static void Main(string[] args)5 {6 RewritingEngine engine = new RewritingEngine();7 engine.AddAssembly("HelloCoyote.exe");8 engine.SetOutputAssembly("HelloCoyoteRewritten.exe");9 engine.Run();10 }11 }12}13using System;14using System.Threading.Tasks;15{16 {17 static async Task Main(string[] args)18 {19 await Task.Delay(1000);20 Console.WriteLine("Hello Coyote!");21 }22 }23}24using Microsoft.Coyote.Rewriting;25{26 {27 static void Main(string[] args)28 {29 RewritingEngine engine = new RewritingEngine();30 engine.AddAssembly("HelloCoyote.exe");31 engine.SetOutputAssembly("HelloCoyoteRewritten.exe");32 engine.Run();33 engine.Build();34 }35 }36}37using Microsoft.Coyote.Rewriting;38{39 {40 static void Main(string[] args)41 {42 RewritingEngine engine = new RewritingEngine();43 engine.AddAssembly("HelloCoyote.exe");44 engine.SetOutputAssembly("HelloCoyoteRewritten.exe");

Full Screen

Full Screen

RewritingEngine

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Rewriting;2{3 public static void Main()4 {5 RewritingEngine.RewriteAndSaveAssembly("2.cs");6 }7}8using Microsoft.Coyote;9using Microsoft.Coyote.Actors;10{11 public static void Main()12 {13 var actor = Actor.CreateFromTask(async () =>14 {15 await Task.Delay(5000);16 });17 }18}19If you run the first file (1.cs) you will get the following output:20Now, if you run the second file (2.cs), you will get the following output:

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Coyote automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful