|
| 1 | +#nullable enable |
| 2 | + |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.IO; |
| 5 | +using System.Linq; |
| 6 | +using Mono.Cecil; |
| 7 | +using Mono.Cecil.Cil; |
| 8 | +using Serilog; |
| 9 | +using Unity.CompilationPipeline.Common.Diagnostics; |
| 10 | +using Unity.CompilationPipeline.Common.ILPostProcessing; |
| 11 | +using Unity.Netcode.Editor.CodeGen; |
| 12 | + |
| 13 | +namespace NetcodePatcher.CodeGen; |
| 14 | + |
| 15 | +public class ReplacePatcherReferencesILPP : ILPostProcessor |
| 16 | +{ |
| 17 | + private readonly List<DiagnosticMessage> m_Diagnostics = []; |
| 18 | + private PostProcessorAssemblyResolver m_AssemblyResolver; |
| 19 | + |
| 20 | + public override ILPostProcessor GetInstance() |
| 21 | + { |
| 22 | + return this; |
| 23 | + } |
| 24 | + |
| 25 | + public override bool WillProcess(ICompiledAssembly compiledAssembly) |
| 26 | + { |
| 27 | + return true; |
| 28 | + } |
| 29 | + |
| 30 | + public override ILPostProcessResult? Process(ICompiledAssembly compiledAssembly) |
| 31 | + { |
| 32 | + if (!WillProcess(compiledAssembly)) return null; |
| 33 | + |
| 34 | + m_Diagnostics.Clear(); |
| 35 | + |
| 36 | + #region Read |
| 37 | + |
| 38 | + var assemblyDefinition = CodeGenHelpers.AssemblyDefinitionFor(compiledAssembly, out m_AssemblyResolver); |
| 39 | + if (assemblyDefinition is null) |
| 40 | + { |
| 41 | + m_Diagnostics.AddError($"Cannot read assembly definition: {compiledAssembly.Name}"); |
| 42 | + return null; |
| 43 | + } |
| 44 | + |
| 45 | + #endregion |
| 46 | + |
| 47 | + #region Process |
| 48 | + |
| 49 | + Log.Information("Now processing"); |
| 50 | + |
| 51 | + var thisReference = assemblyDefinition.MainModule.AssemblyReferences |
| 52 | + .FirstOrDefault(reference => reference.Name == GetType().Assembly.GetName().Name); |
| 53 | + |
| 54 | + if (thisReference is not null) |
| 55 | + { |
| 56 | + assemblyDefinition.MainModule.AssemblyReferences.Remove(thisReference); |
| 57 | + Log.Information("Removed shit reference"); |
| 58 | + } |
| 59 | + |
| 60 | + #endregion |
| 61 | + |
| 62 | + #region Write |
| 63 | + |
| 64 | + var pe = new MemoryStream(); |
| 65 | + var pdb = new MemoryStream(); |
| 66 | + |
| 67 | + var writerParameters = new WriterParameters |
| 68 | + { |
| 69 | + SymbolWriterProvider = new PortablePdbWriterProvider(), |
| 70 | + SymbolStream = pdb, |
| 71 | + WriteSymbols = true |
| 72 | + }; |
| 73 | + |
| 74 | + assemblyDefinition.Write(pe, writerParameters); |
| 75 | + |
| 76 | + return new ILPostProcessResult(new InMemoryAssembly(pe.ToArray(), pdb.ToArray()), m_Diagnostics); |
| 77 | + |
| 78 | + #endregion |
| 79 | + } |
| 80 | +} |
0 commit comments