Git Product home page Git Product logo

cpp2il's People

Contributors

alluseri avatar bbepis avatar bookdude13 avatar dependabot[bot] avatar ds5678 avatar futuremappermydud avatar gompoc avatar knah avatar lukefz avatar mf-patino avatar mitchcapper avatar rinlovesyou avatar rinsuki avatar samboycoding avatar zingballyhoo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cpp2il's Issues

RemoveUnusedLocalsPostProcessor is very slow

The post-processor uses multiple nested LINQ queries, and therefore takes up roughly 27% of the total time spent analysing the assemblies. This is unacceptably high for such a low-impact feature.

The first set of LINQ queries could be avoided by adding all locals to an "Unused" list inside MakeLocal on the MethodAnalysis class, and removing them when calls to RegisterUsedLocal are made. This is the worst of the two top-level LINQ queries, accounting for 75% of the execution time.

The second query should probably be replaced with a sub-list, each element of which is then removed from the Actions list via a simple Remove call.

Namespaces with a reserved windows file name will cause analysis to crash

As mentioned on discord, while unlikely, if a game uses a namespace in Assembly-C-Sharp that is a Windows reserved file name (list here), it'll cause the program to crash when performing analysis.

Unhandled exception. System.IO.DirectoryNotFoundException: Could not find a part of the path '\\.\Con'.
   at System.IO.FileSystem.CreateDirectory(String , Byte[] )
   at System.IO.Directory.CreateDirectory(String )
   at Cpp2IL.Core.Cpp2IlApi.<>c__DisplayClass22_0.<AnalyseAssembly>g__ProcessType|3(TypeDefinition type)
   at System.Collections.Generic.List`1.ForEach(Action`1 )
   at Cpp2IL.Core.Cpp2IlApi.AnalyseAssembly(AnalysisLevel analysisLevel, AssemblyDefinition assembly, BaseKeyFunctionAddresses keyFunctionAddresses, String methodOutputDir, Boolean parallel, Boolean continueThroughErrors)
   at Cpp2IL.Program.DoAssemblyCSharpAnalysis(String assemblyName, AnalysisLevel analysisLevel, String rootDir, BaseKeyFunctionAddresses keyFunctionAddresses, Boolean doIlToAsm, Boolean parallel, Boolean continueThroughErrors)
   at Cpp2IL.Program.MainWithArgs(Cpp2IlRuntimeArgs runtimeArgs)
   at Cpp2IL.Program.Main(String[] args)

Value cannot be null exception

Hi, there is a null reference exception in the part where it generates the IL code.

Here is the full error:
System.ArgumentNullException: Value cannot be null. (Parameter 'parameter')
at Mono.Cecil.Cil.Instruction.Create(OpCode opcode, ParameterDefinition parameter)
at Cpp2IL.Analysis.ResultModels.LocalDefinition.GetILToLoad(MethodAnalysis context, ILProcessor processor)
at Cpp2IL.Analysis.Actions.Important.FieldToLocalAction.ToILInstructions(MethodAnalysis context, ILProcessor processor)
at Cpp2IL.Analysis.AsmDumper.AnalyzeMethod(StringBuilder typeDump, List`1& allUsedMnemonics)

The game is Among Us.

System.InvalidCastException on "CustomAttributeWriteFailedException"

Tried latest release .NET Framework version:

[Fail] [Program] Cpp2IL.Core.Exceptions.DllSaveException: Fatal Exception writing DLL F: \test\cpp2il_out\System.Xml.dll ---> 
Cpp2IL.Core .Exceptions.TypeWriteFailedException: Failed to write type System.Xml.Schema.XmlSchema due to an exception ---> 
Cpp2IL.Core.Exceptions.PropertyWriteFailedException: Failed to write property System.Xml.Schema.XmlSchemaForm System.Xml.Schema.XmlSchema :: AttributeFormDefault () due to an exception ---> 
Cpp2IL.Core.Exceptions.CustomAttributeWriteFailedException: Failed to write custom attribute System.ComponentModel.DefaultValueAttribute with arguments 0 of type System.Xml.Schema.XmlSchemaForm due to an exception --- > System.InvalidCastException: The specified cast is invalid.
   at Mono.Cecil.SignatureWriter.WriteCustomAttributeElement (TypeReference type, CustomAttributeArgument argument)
   for Mono.Cecil.SignatureWriter.WriteCustomAttributeConstructorArguments (CustomAttribute attribute)
   at DMD <Mono.Cecil.MetadataBuilder :: GetCustomAttributeSignature> (MetadataBuilder this, CustomAttribute attribute)
   --- End of internal exception stack monitoring ---
   at DMD <Mono.Cecil.MetadataBuilder :: GetCustomAttributeSignature> (MetadataBuilder this, CustomAttribute attribute)
   at Mono.Cecil.MetadataBuilder.AddCustomAttributes (ICustomAttributeProvider owner)
   at DMD <Mono.Cecil.MetadataBuilder :: AddProperty> (MetadataBuilder this, PropertyDefinition property)
   --- End of internal exception stack monitoring ---
   at DMD <Mono.Cecil.MetadataBuilder :: AddProperty> (MetadataBuilder this, PropertyDefinition property)
   at Mono.Cecil.MetadataBuilder.AddProperties (TypeDefinition type)
   at DMD <Mono.Cecil.MetadataBuilder :: AddType> (MetadataBuilder this, TypeDefinition type)
   --- End of internal exception stack monitoring ---
   at DMD <Mono.Cecil.MetadataBuilder :: AddType> (MetadataBuilder this, TypeDefinition type)
   at Mono.Cecil.MetadataBuilder.AddTypes ()
   at Mono.Cecil.MetadataBuilder.BuildTypes ()
   at Mono.Cecil.MetadataBuilder.BuildModule ()
   at Mono.Cecil.MetadataBuilder.BuildMetadata ()
   with Mono.Cecil.ModuleWriter.Write (ModuleDefinition module, Disposable`1 stream, WriterParameters parameters)
   with Mono.Cecil.ModuleWriter.WriteModule (ModuleDefinition module, Disposable`1 stream, WriterParameters parameters)
   at Cpp2IL.Core.Cpp2IlApi.SaveAssemblies (String toWhere, List`1 assemblies) in /home/runner/work/Cpp2IL/Cpp2IL/Cpp2IL.Core/Cpp2IlApi.cs:line 363.
   --- End of internal exception stack monitoring ---
   at Cpp2IL.Core.Cpp2IlApi.SaveAssemblies (String toWhere, List`1 assemblies) in /home/runner/work/Cpp2IL/Cpp2IL/Cpp2IL.Core/Cpp2IlApi.cs:line 367.
   at Cpp2IL.Program.MainWithArgs (Cpp2IlRuntimeArgs runtimeArgs) in /home/runner/work/Cpp2IL/Cpp2IL/Cpp2IL/Program.cs:line 290.
   at Cpp2IL.Program.Main (String [] args) in /home/runner/work/Cpp2IL/Cpp2IL/Cpp2IL/Program.cs:line 216.

Binary files can be found here: djkaty/Il2CppInspector#197

Metadata (and analysis?) Dumper doesn't filter out pipe (|) characters in filenames

When I was using the application on Kuboom (yet another il2cpp unity game), it crashed when processing Assembly-CSharp saying some shit about
Unhandled exception. System.IO.IOException: The filename, directory name, or volume label syntax is incorrect. : 'C:\Users\notmyname\Downloads\fuck\cpp2il_out\types\Assembly-CSharp\__LoadTexture_g___LoadTexture|4_0_d_metadata.txt' at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle) at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System.IO.StreamWriter.ValidateArgsAndOpenPath(String path, Boolean append, Encoding encoding, Int32 bufferSize) at System.IO.File.WriteAllText(String path, String contents) at Cpp2IL.AssemblyBuilder.ProcessTypeContents(Il2CppMetadata metadata, PE cppAssembly, Il2CppTypeDefinition cppTypeDefinition, TypeDefinition ilTypeDefinition, Il2CppAssemblyDefinition imageDef) at Cpp2IL.AssemblyBuilder.ProcessAssemblyTypes(Il2CppMetadata metadata, PE theDll, Il2CppAssemblyDefinition imageDef) at Cpp2IL.Program.Main(String[] args)

V29 Attribute Reader implementation isn't perfect

A log file was received in the MelonLoader discord which contained the following stacktrace:

[Info] [Program] Running processor Attribute Injector...
[ERROR]
[ERROR] Unhandled Exception: System.AggregateException: One or more errors occurred. ---> System.Exception: CustomAttributePrimitiveParameter constructed with a non-primitive type: IL2CPP_TYPE_VALUETYPE
[ERROR]    at Cpp2IL.Core.Model.CustomAttributes.CustomAttributePrimitiveParameter.ReadFromV29Blob(BinaryReader reader, ApplicationAnalysisContext context) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Model\CustomAttributes\CustomAttributePrimitiveParameter.cs:line 92
[ERROR]    at Cpp2IL.Core.Model.CustomAttributes.CustomAttributeArrayParameter.ReadFromV29Blob(BinaryReader reader, ApplicationAnalysisContext context) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Model\CustomAttributes\CustomAttributeArrayParameter.cs:line 71
[ERROR]    at Cpp2IL.Core.Utils.V29AttributeUtils.ReadAttribute(Stream stream, MethodAnalysisContext constructor, ApplicationAnalysisContext context) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Utils\V29AttributeUtils.cs:line 42
[ERROR]    at Cpp2IL.Core.Model.Contexts.HasCustomAttributes.AnalyzeCustomAttributeDataV29() in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Model\Contexts\HasCustomAttributes.cs:line 219
[ERROR]    at Cpp2IL.Core.Model.Contexts.HasCustomAttributes.AnalyzeCustomAttributeData() in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Model\Contexts\HasCustomAttributes.cs:line 199
[ERROR]    at Cpp2IL.Core.CorePlugin.AttributeInjectorProcessingLayer.ProcessCustomAttributesForContext(HasCustomAttributes context, FieldAnalysisContext nameField, FieldAnalysisContext rvaField, FieldAnalysisContext offsetField, MethodAnalysisContext ctor) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\CorePlugin\AttributeInjectorProcessingLayer.cs:line 148
[ERROR]    at Cpp2IL.Core.CorePlugin.AttributeInjectorProcessingLayer.<>c__DisplayClass8_0.<InjectAttributeAttribute>b__1(HasCustomAttributes c) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\CorePlugin\AttributeInjectorProcessingLayer.cs:line 140
[ERROR]    at System.Threading.Tasks.Parallel.<>c__DisplayClass42_0`2.<PartitionerForEachWorker>b__1()
[ERROR]    at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
[ERROR]    at System.Threading.Tasks.Task.<>c__DisplayClass176_0.<ExecuteSelfReplicating>b__0(Object <p0>)
[ERROR]    --- End of inner exception stack trace ---
[ERROR]    at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
[ERROR]    at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
[ERROR]    at System.Threading.Tasks.Parallel.PartitionerForEachWorker[TSource,TLocal](Partitioner`1 source, ParallelOptions parallelOptions, Action`1 simpleBody, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
[ERROR]    at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
[ERROR]    at System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, Action`1 body)
[ERROR]    at Cpp2IL.Core.CorePlugin.AttributeInjectorProcessingLayer.InjectAttributeAttribute(ApplicationAnalysisContext appContext) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\CorePlugin\AttributeInjectorProcessingLayer.cs:line 125
[ERROR]    at Cpp2IL.Core.CorePlugin.AttributeInjectorProcessingLayer.Process(ApplicationAnalysisContext appContext, Action`2 progressCallback) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\CorePlugin\AttributeInjectorProcessingLayer.cs:line 19
[ERROR]    at Cpp2IL.Program.MainWithArgs(Cpp2IlRuntimeArgs runtimeArgs) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL\Program.cs:line 331
[ERROR]    at Cpp2IL.Program.Main(String[] args) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL\Program.cs:line 268

Looking at the libil2cpp attribute reading code (Il2Cpp/vm-utils/BlobReader.cpp) on unity 2022.1.0b9, there is no handling for a value of type VALUETYPE, which implies that something has not been read correctly prior to this attribute.

Two things should be done here.

  • Better handling of these sorts of errors, with information about the attribute currently being read, offset into its blob, etc.
    • This can be achieved by, for example, storing the number of bytes read by each attribute prior to this one, and logging this info out in the event of a failure.
  • Fix the issue causing the exception.

Also - optionally - default the attributes to a failed state with only constructors, same as in versions < 29 when no analysis is run, allowing the injector to replace them with dummy attributes, etc. This should be possible, as constructor method indices are stored prior to any individual attribute data blobs.

The game in question was Shredders, available on steam (appid 1874171) and gamepass.

Unsupported metadata version

I think this is more of an issue with the game itself and not the program, but I'm getting the following error:

[Info] [Program] Running on Win32NT
[Warn] [Program] Fail once: Unity version of provided executable is [0, 0, 0]. This is probably not the correct version. Retrying with alternative method...
[Info] [Program] Determined game's unity version to be 2019.4.17
[Info] [Library] Initializing Metadata...
[Fail] [Program]

Cpp2IL.Core.Exceptions.LibCpp2ILInitializationException: Fatal Exception initializing LibCpp2IL!
 ---> System.FormatException: Unsupported metadata version found! We support 24-29, got 6042200
   at LibCpp2IL.Metadata.Il2CppMetadata.ReadFrom(Byte[] bytes, Int32[] unityVer)
   at LibCpp2IL.LibCpp2IlMain.Initialize(Byte[] binaryBytes, Byte[] metadataBytes, Int32[] unityVersion)
   at LibCpp2IL.LibCpp2IlMain.LoadFromFile(String pePath, String metadataPath, Int32[] unityVersion)
   at Cpp2IL.Core.Cpp2IlApi.InitializeLibCpp2Il(String assemblyPath, String metadataPath, Int32[] unityVersion, Boolean allowUserToInputAddresses)
   --- End of inner exception stack trace ---
   at Cpp2IL.Core.Cpp2IlApi.InitializeLibCpp2Il(String assemblyPath, String metadataPath, Int32[] unityVersion, Boolean allowUserToInputAddresses)
   at Cpp2IL.Program.MainWithArgs(Cpp2IlRuntimeArgs runtimeArgs)
   at Cpp2IL.Program.Main(String[] args)

Not sure why the version number is that... but HxD shows the same result:

image

I'm not very familiar with decompiling games in the first place so I don't really know where to go from here. From the research I've been able to do, it may be that the metadata is obfuscated in some way, but it has the AF 1B B1 FA header, which indicates an unobfuscated metadata file, but not necessarily guarantees. Any thoughts/suggestions?

For reference, the game is Rise of Kingdoms (originally a mobile game, ported to PC a few months ago).

Latest build fails to populate in VRChat

I see you are still working actively on this but since its been broken for a bit now I thought I'd mention that release "Commit e0bb96b" broke something and Cpp2Il fails when trying to populate assemblies for VRChat using that release and later ones

Populating 1753 types in assembly 1 of 93: mscorlib.dll...
Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'source')
   at System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
   at System.Linq.Enumerable.Where[TSource](IEnumerable`1 source, Func`2 predicate)
   at Cpp2IL.AssemblyBuilder.ProcessTypeContents(Il2CppMetadata metadata, PE cppAssembly, Il2CppTypeDefinition cppTypeDefinition, TypeDefinition ilTypeDefinition, Il2CppImageDefinition imageDef)
   at Cpp2IL.AssemblyBuilder.ProcessAssemblyTypes(Il2CppMetadata metadata, PE theDll, Il2CppImageDefinition imageDef)
   at Cpp2IL.Program.Main(String[] args)

I've attached a log file here that may (or may not) help
log.txt

x86 CallManagedFunctionAction is slow

In a profiling session on Secret Neighbour, 10% of the execution time, or 11% of analysis time - was spent inside the constructor for CallManagedFunctionAction (this is the x86 variant). Half of that time was a single LINQ query - the one on line 143, to obtain base class instance methods.

The root culprit seems to be the call to IsManagedTypeAnInstanceOfCppOne, and actually, the interaction with the cache inside CheckAssignability.

It may be worth simply resolving the declaring type of the methods at this address, and checking those against the managed instance type we have, rather than the complex behavior of WrapType (which introduces a pain point in handling that wrapped type, as we don't know it's just an Il2CppTypeDefinition until we check). Indeed, looking up the declaring type of the method - which is just an Il2CppTypeDefinition - in the unmanaged-to-managed type map should be fast.

AsmAnalyzerx86 FindInstructionWhichOverran is slow

The method is slow because it relies on the extension function to check if an array contains a value, which accounts for 9% of the total execution time of the program.

One solution would be to statically convert the AllCustomAttributeGenerators array to a list - but it must be cleared during resets of the program (i.e. when a different binary is loaded). In theory, List.Contains should be much faster than the array method.

The check itself is definitely necessary, as this same method is used during attribute restoration, which operates on custom attribute generators, but it's not always necessary. If we're running on a managed method, not a custom attribute generator (this can be determined by the presence of a MethodDefinition), the check may not be required, which could also be an alternative to fix performance.

Error loading building attribute array item of type Type.

Testing Cpp2IL on an empty URP project, in Unity 2021.2.16 (metadata v29)
Cpp2IL log file:

[23:15:20.554] ===Cpp2IL by Samboy063===
[23:15:20.555] A Tool to Reverse Unity's "il2cpp" Build Process.
[23:15:20.556] Version 2022.1.0-pre-release.3
[23:15:20.556] 
[23:15:20.557] [Warn] [Program] NO_COLOR set, disabling ANSI color codes as you requested.
[23:15:20.557] [Info] [Program] Running on Win32NT
[23:15:20.631] [Info] [Plugins] Using Plugin: Cpp2IL Built-In
[23:15:20.636] [Info] [Program] Determined game's unity version to be 2021.2.6
[23:15:20.658] [Info] [Library] Initializing Metadata...
[23:15:20.660] [Info] [Library] 	Using actual IL2CPP Metadata version 29
[23:15:20.844] [Info] [Library] Initialized Metadata in 186ms
[23:15:20.845] [Info] [Library] Using binary type Portable Executable (from LibCpp2IL)
[23:15:20.845] [Info] [Library] Searching Binary for Required Data...
[23:15:21.832] [Info] [Library] Got Binary codereg: 0x180D58B10, metareg: 0x180EEC1E0 in 987ms.
[23:15:21.833] [Info] [Library] Initializing Binary...
[23:15:21.915] [Info] [Library] Initialized Binary in 83ms
[23:15:21.944] [Info] [Library] Mapping pointers to Il2CppMethodDefinitions...Processed 40814 OK (30ms)
[23:15:22.079] [Info] [Program] Creating application model...Done.
[23:15:22.081] [Info] [Program] Running processor Attribute Injector...
[23:15:22.258] [Info] [Program] Processor Attribute Injector finished in 179.0241ms
[23:15:22.259] [Info] [Program] Outputting as Stub ("Dummy") DLL Files to C:\Users\wnp\Home\OtherProjects\Bonetech\Bonetech-Testing\Build\MelonLoader\Dependencies\Il2CppAssemblyGenerator\Cpp2IL\cpp2il_out...
[23:15:22.571] [ERROR] 
[23:15:22.578] [ERROR] Unhandled Exception: System.AggregateException: One or more errors occurred. ---> System.ArgumentException: Type is not a primitive
[23:15:22.579] [ERROR] Parameter name: type
[23:15:22.581] [ERROR]    at Cpp2IL.Core.Utils.AsmResolverUtils.GetPrimitiveTypeDef(Il2CppTypeEnum type) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Utils\AsmResolverUtils.cs:line 45
[23:15:22.582] [ERROR]    at Cpp2IL.Core.Utils.AsmResolverAssemblyPopulator.GetTypeSigFromAttributeArg(AssemblyDefinition parentAssembly, BaseCustomAttributeParameter parameter) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Utils\AsmResolverAssemblyPopulator.cs:line 84
[23:15:22.584] [ERROR]    at Cpp2IL.Core.Utils.AsmResolverAssemblyPopulator.BuildArrayArgument(AssemblyDefinition parentAssembly, CustomAttributeArrayParameter arrayParameter) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Utils\AsmResolverAssemblyPopulator.cs:line 95
[23:15:22.585] [ERROR]    at Cpp2IL.Core.Utils.AsmResolverAssemblyPopulator.FromAnalyzedAttributeArgument(AssemblyDefinition parentAssembly, BaseCustomAttributeParameter parameter) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Utils\AsmResolverAssemblyPopulator.cs:line 111
[23:15:22.586] [ERROR]    at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
[23:15:22.586] [ERROR]    at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
[23:15:22.587] [ERROR]    at AsmResolver.DotNet.Signatures.CustomAttributeSignature..ctor(IEnumerable`1 fixedArguments, IEnumerable`1 namedArguments)
[23:15:22.589] [ERROR]    at Cpp2IL.Core.Utils.AsmResolverAssemblyPopulator.CopyCustomAttributes(HasCustomAttributes source, IList`1 destination) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Utils\AsmResolverAssemblyPopulator.cs:line 139
[23:15:22.590] [ERROR]    at Cpp2IL.Core.Utils.AsmResolverAssemblyPopulator.PopulateCustomAttributes(AssemblyAnalysisContext asmContext) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Utils\AsmResolverAssemblyPopulator.cs:line 171
[23:15:22.591] [ERROR]    at Cpp2IL.Core.Utils.MiscUtils.<>c__DisplayClass13_0`1.<ExecuteParallel>b__0(T t) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Utils\MiscUtils.cs:line 262
[23:15:22.592] [ERROR]    at System.Linq.Parallel.PartitionedDataSource`1.ListContiguousIndexRangeEnumerator.MoveNext(T& currentElement, Int32& currentKey)
[23:15:22.593] [ERROR]    at System.Linq.Parallel.StopAndGoSpoolingTask`2.SpoolingWork()
[23:15:22.594] [ERROR]    at System.Linq.Parallel.SpoolingTaskBase.Work()
[23:15:22.594] [ERROR]    at System.Linq.Parallel.QueryTask.BaseWork(Object unused)
[23:15:22.595] [ERROR]    at System.Threading.Tasks.Task.Execute()
[23:15:22.596] [ERROR]    --- End of inner exception stack trace ---
[23:15:22.597] [ERROR]    at System.Linq.Parallel.QueryTaskGroupState.QueryEnd(Boolean userInitiatedDispose)
[23:15:22.599] [ERROR]    at System.Linq.Parallel.MergeExecutor`1.Execute[TKey](PartitionedStream`2 partitions, Boolean ignoreOutput, ParallelMergeOptions options, TaskScheduler taskScheduler, Boolean isOrdered, CancellationState cancellationState, Int32 queryId)
[23:15:22.600] [ERROR]    at System.Linq.Parallel.PartitionedStreamMerger`1.Receive[TKey](PartitionedStream`2 partitionedStream)
[23:15:22.601] [ERROR]    at System.Linq.Parallel.UnaryQueryOperator`2.UnaryQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient`1 recipient)
[23:15:22.603] [ERROR]    at System.Linq.Parallel.QueryOperator`1.GetOpenedEnumerator(Nullable`1 mergeOptions, Boolean suppressOrder, Boolean forEffect, QuerySettings querySettings)
[23:15:22.604] [ERROR]    at System.Linq.Parallel.QueryOpeningEnumerator`1.OpenQuery()
[23:15:22.604] [ERROR]    at System.Linq.Parallel.QueryOpeningEnumerator`1.MoveNext()
[23:15:22.605] [ERROR]    at System.Linq.ParallelEnumerable.ToList[TSource](ParallelQuery`1 source)
[23:15:22.606] [ERROR]    at Cpp2IL.Core.CorePlugin.AsmResolverDummyDllOutputFormat.DoOutput(ApplicationAnalysisContext context, String outputRoot) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\CorePlugin\AsmResolverDummyDllOutputFormat.cs:line 48
[23:15:22.607] [ERROR]    at Cpp2IL.Program.MainWithArgs(Cpp2IlRuntimeArgs runtimeArgs) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL\Program.cs:line 340
[23:15:22.609] [ERROR]    at Cpp2IL.Program.Main(String[] args) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL\Program.cs:line 268

I added some debug logs to AsmResolverAssemblyPopulator.BuildArrayArgument check what the attribute values offending were:
parentAssembly: Unity.RenderPipelines.Universal.Runtime, Version=0.0.0.0, PublicKeyToken=null
arrayParameter: (IL2CPP_TYPE_IL2CPP_TYPE_INDEX) [typeof(UniversalRenderPipeline)]

So if I had to guess it would be it's tripping over when there's an attribute with an array of Types, entered as typeof( expressions.

I can provide the sample project files if you need it, but it is just an empty URP project.

[BUG] "Failed to perform analysis: System.OverflowException"

I am attempting to run analysis on the IL2CPP Unity game Gems of War, and encountered the following error when running:

[Warn] [Analyze] Failed to perform analysis on method System.Void ArtifactDisplayData::StopRunningCoroutines()
While analysing instruction lea eax,[esi*4+10h] at 0x10470934
Got exception: System.OverflowException: Provided address, 0x10, was less than image base, 0x10000000
   at LibCpp2IL.PE.PE.MapVirtualAddressToRaw(UInt64 uiAddr)
   at Cpp2IL.Core.Analysis.AsmAnalyzer.CheckForTwoOpInstruction(Instruction instruction)
   at Cpp2IL.Core.Analysis.AsmAnalyzer.PerformInstructionChecks(Instruction instruction)
   at Cpp2IL.Core.Analysis.AsmAnalyzer.AnalyzeMethod()

This error occurs a couple dozen times during analysis.

I am not sure what the issue is. It's possible the issue is related to the game's executable being a 32-bit build.

If needed, I can perform additional testing, provide more logs, or test development builds.

The version used is milestone Cpp2IL 2021.3.0.0.

Cpp2IL.Core.Exceptions.DllSaveException

Using Cpp2Il 2021.3.1. Running analysis on several different games ended with exceptions such as:

[Info] [Program] Saving 1 assembly to D:\Program Files (x86)\Steam\steamapps\common\BONEWORKS\BONEWORKS\cpp2il_out...
[Fail] [Program] Cpp2IL.Core.Exceptions.DllSaveException: Fatal Exception writing DLL D:\Program Files (x86)\Steam\steamapps\common\BONEWORKS\BONEWORKS\cpp2il_out\Assembly-CSharp.dll
 ---> System.NotSupportedException: Specified method is not supported.
   at Mono.Cecil.SignatureWriter.WriteTypeSignature(TypeReference type)
   at Mono.Cecil.SignatureWriter.WriteGenericInstanceSignature(IGenericInstance instance)
   at Mono.Cecil.MetadataBuilder.GetTypeSpecToken(TypeReference type)
   at Mono.Cecil.MetadataBuilder.CreateMemberRefRow(MemberReference member)
   at Mono.Cecil.MetadataBuilder.GetMemberRefToken(MemberReference member)
   at Mono.Cecil.MetadataBuilder.LookupToken(IMetadataTokenProvider provider)
   at Mono.Cecil.Cil.CodeWriter.WriteOperand(Instruction instruction)
   at Mono.Cecil.Cil.CodeWriter.WriteInstructions()
   at Mono.Cecil.Cil.CodeWriter.WriteResolvedMethodBody(MethodDefinition method)
   at Mono.Cecil.Cil.CodeWriter.WriteMethodBody(MethodDefinition method)
   at Mono.Cecil.MetadataBuilder.AddMethod(MethodDefinition method)
   at Mono.Cecil.MetadataBuilder.AddMethods(TypeDefinition type)
   at Mono.Cecil.MetadataBuilder.AddType(TypeDefinition type)
   at Mono.Cecil.MetadataBuilder.AddTypes()
   at Mono.Cecil.MetadataBuilder.BuildTypes()
   at Mono.Cecil.MetadataBuilder.BuildModule()
   at Mono.Cecil.MetadataBuilder.BuildMetadata()
   at Mono.Cecil.ModuleWriter.Write(ModuleDefinition module, Disposable`1 stream, WriterParameters parameters)
   at Mono.Cecil.ModuleWriter.WriteModule(ModuleDefinition module, Disposable`1 stream, WriterParameters parameters)
   at Cpp2IL.Core.Cpp2IlApi.SaveAssemblies(String toWhere, List`1 assemblies)
   --- End of inner exception stack trace ---
   at Cpp2IL.Core.Cpp2IlApi.SaveAssemblies(String toWhere, List`1 assemblies)
   at Cpp2IL.Program.DoAssemblyCSharpAnalysis(String assemblyName, AnalysisLevel analysisLevel, String rootDir, KeyFunctionAddresses keyFunctionAddresses, Boolean doIlToAsm, Boolean parallel)
   at Cpp2IL.Program.MainWithArgs(Cpp2IlRuntimeArgs runtimeArgs)
   at Cpp2IL.Program.Main(String[] args)```

Exception handling

Not sure how much you've looked into this but I made a standalone prototype that attempts reconstructs exception handling semantics from x64 binaries compiled with vs2019. Seems to work pretty good except for some jank at the end where the compiler inserts the code for explicit null throwers and the like.

Code is here: https://github.com/ZingBallyhoo/Cpp2IL/blob/read-exception-info/ReadExceptionInfo/Program.cs

good resources:
https://www.youtube.com/watch?v=COEv2kq_Ht8
https://devblogs.microsoft.com/cppblog/making-cpp-exception-handling-smaller-x64/
ehdata4_export.h from MSVC includes
https://reactos.org/wiki/Techwiki:SEH64 for vs2017 abi and earlier
http://www.uninformed.org/?v=4&a=1&t=pdf
https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64?view=msvc-160


public int TryCatchTwo()
{
    try
    {
        throw new Exception();
        return 1;
    } catch (ArgumentException)
    {
        return 100;
    } catch (Exception)
    {
        return 0;
    }
}

https://gist.github.com/ZingBallyhoo/f1162fa0b14d5abb47c6eaba22807ae7#file-trycatchtwo-asm


public int TryCatchThree()
{
    try
    {
        throw new Exception();
        return 1;
    } catch (ArgumentException)
    {
        return 100;
    } catch (ObjectDisposedException)
    {
        return 101;
    } catch (Exception)
    {
        return 0;
    }
}

https://gist.github.com/ZingBallyhoo/f1162fa0b14d5abb47c6eaba22807ae7#file-trycatchthree-asm


public int TryCatchFilter()
{
    try
    {
        throw new Exception("msg");
    } catch (Exception e) when (e.Message == "msg2")
    {
        return 100;
    } catch (Exception)
    {
        return 101;
    }
    // should be unreachable
    return 102;
}

https://gist.github.com/ZingBallyhoo/f1162fa0b14d5abb47c6eaba22807ae7#file-trycatchfilter-asm
the translator can't deal with mixing filtered and non-filtered handlers
https://forum.unity.com/threads/catching-exception-with-when-clause-will-not-work-as-expected-when-using-il2cpp.989260/
https://www.jacksondunstan.com/articles/4702


public int TryCatchFinally()
{
    int myLocal = 100;
    try
    {
        throw new Exception("msg");
    } catch (Exception e)
    {
        return myLocal;
    } finally
    {
        myLocal = 5;
    }
}

https://gist.github.com/ZingBallyhoo/f1162fa0b14d5abb47c6eaba22807ae7#file-trycatchfinally-asm


public int TryCatchNested()
{
    try
    {
        try
        {
            throw new Exception();
            return 1;
        } catch
        {
            throw new ArgumentException();
            return 2;
        }
    } catch
    {
        return 3;
    }
}

https://gist.github.com/ZingBallyhoo/f1162fa0b14d5abb47c6eaba22807ae7#file-trycatchnested-asm


public void TryMultiple()
{
    try
    {
        Console.Out.WriteLine("one");
    } catch
    {
    }
    Console.Out.WriteLine("inbetween");
    try
    {
        Console.Out.WriteLine("two");
    } catch
    {
        Console.Out.WriteLine("caught two");
    }
}

https://gist.github.com/ZingBallyhoo/f1162fa0b14d5abb47c6eaba22807ae7#file-trymultiple-asm


public int TryCatchMultipleNested()
{
    try
    {
        try
        {
            Console.Out.WriteLine("one");
        } catch
        {
        }
        Console.Out.WriteLine("inbetween");
        try
        {
            Console.Out.WriteLine("two");
        } catch
        {
            Console.Out.WriteLine("caught two");
        }
        return 59;
    } catch
    {
        return 3;
    }
}

https://gist.github.com/ZingBallyhoo/f1162fa0b14d5abb47c6eaba22807ae7#file-trycatchmultiplenested-asm

Missing CodeRegistration for Maze by Liveoverflow

CodeRegistration is 180a10e10 according to il2cppdumper. Would be nice if we can input manually in case if automation fails
Game is called Maze http://maze.liveoverflow.com/

PS F:\Portable Apps\Cpp2IL> ./Cpp2IL-Win  --game-path F:\Games\Maze
===Cpp2IL by Samboy063===
A Tool to Reverse Unity's "il2cpp" Build Process.
Running on Win32NT
Using path: F:\Games\Maze
Auto-detected game name: Maze
Located game EXE: F:\Games\Maze\Maze.exe
Located global-metadata: F:\Games\Maze\Maze_Data\il2cpp_data\Metadata\global-metadata.dat

Attempting to determine Unity version...
This game is built with Unity version 2020.1.0
Reading metadata...
Using IL2CPP Metadata version 24,2
        Reading image definitions...OK (4,891 ms)
        Reading type definitions...OK (51,9857 ms)
        Reading interface offsets...OK (3,2079 ms)
        Reading method definitions...OK (244,3624 ms)
        Reading method parameter definitions...OK (57,5712 ms)
        Reading field definitions...OK (38,2857 ms)
        Reading default field values...OK (5,2318 ms)
        Reading default parameter values...OK (0,3921 ms)
        Reading property definitions...OK (10,2972 ms)
        Reading interface definitions...OK (1,3729 ms)
        Reading nested type definitions...OK (0,0326 ms)
        Reading event definitions...OK (0,2592 ms)
        Reading generic container definitions...OK (0,5913 ms)
        Reading generic parameter definitions...OK (1,0578 ms)
        Reading string definitions...OK (3,5195 ms)
        Reading usage data...OK (70,0406 ms)
        Reading field references...OK (0,1969 ms)
        Reading attribute types...OK (5,1614 ms)
Reading binary / game assembly...
        -Initializing MemoryStream of 11832832 bytes, parsing sections, and initializing with auto+ mode.
Reading PE File Header...OK (0,4604 ms)
        Image Base at 0x180000000
        DLL is 64-bit
Looking for registration functions...
        Identified execute section .text
        Identified execute section il2cpp
        Identified data section .rdata
        Identified data section .data
        Identified data section .pdata
        Identified data section _RDATA
Attempting to locate code and metadata registration functions...
        (64-bit PE)
        Failed to find code and metadata registration functions using primary location method (probably because we're post-2019), checking if we can use the fallback...
        Found il2cpp_init export (resolves to virtual addr 0x18002F820), using fallback method to find Code and Metadata registration...
        Located probable Runtime::Init function at virtual addr 0x18006B4B0
        Located probable ExecuteInitializations function at virt addr 0x18006B551
        Missing or invalid second instruction in ExecuteInitializations, fallback failed!
Initializing with located addresses:
        CodeRegistration : 0x0
        MetadataRegistration : 0x180a10e80
Initialize failed. Aborting.

Failed to find exe file.

[Fail] [Program] Execution Failed:Invalid game-path or exe-name specified.

System: Win 10 x64
Build :Unity 2017.2.1 f1 Standalone

[x86] Test instruction is not handled correctly

A test instruction is not handled correctly when both operands are the same. For example,

test eax, eax
jle short 0xABCDEF

Should be checking if eax > 0, but instead it outputs as eax > eax.

Creates empty functions

I was decompiling some game. It dumped the dlls. When viewing with sply or dnSpy it shows all function but their bodies are empty.

System.OverflowException: Arithmetic operation resulted in an overflow

Hello. I am currently trying to use Cpp2Il on a game that uses 2019.4.22. However when attempting to use the tool, it gives out an overflow exception. I am currently using "commit_d02ef41b68755d6b39807131ffe135749a3644f5"

This is the command I am using: .\Cpp2IL-Win.exe --game-path "C:\Program Files (x86)\Steam\steamapps\common*GAME NAME*"

This is the full log:
`===Cpp2IL by Samboy063===
A Tool to Reverse Unity's "il2cpp" Build Process.
Running on Win32NT
Determined game's unity version to be 2019.4.22
Initializing Metadata...
Using IL2CPP Metadata version 24.3
Reading image definitions...OK (6.1843 ms)
Reading type definitions...10504 OK (255.7858 ms)
Reading interface offsets...OK (18.076 ms)
Reading vtable indices...OK (25.7729 ms)
Reading method definitions...OK (588.1665 ms)
Reading method parameter definitions...OK (185.2095 ms)
Reading field definitions...OK (154.8536 ms)
Reading default field values...OK (43.1683 ms)
Reading default parameter values...OK (8.7643 ms)
Reading property definitions...OK (80.0201 ms)
Reading interface definitions...OK (4.0538 ms)
Reading nested type definitions...OK (0.227 ms)
Reading event definitions...OK (0.4746 ms)
Reading generic container definitions...OK (2.3406 ms)
Reading generic parameter definitions...OK (3.5391 ms)
Reading string definitions...OK (60.9883 ms)
Reading usage data...OK (604.3421 ms)
Reading field references...OK (1.3127 ms)
Reading attribute types...OK (13.3477 ms)
Building Lookup Table for field defaults...OK (9.2839 ms)
Initialized Metadata in 2267ms
Searching Binary for Required Data...
Reading PE File Header...OK (12.1218 ms)
Image Base at 0x180000000
DLL is 64-bit
Attempting to locate code and metadata registration functions...
-Searching for MetadataReg...
-Searching for CodeReg...
Using mscorlib full-disassembly approach to get codereg, this may take a while...
Got Binary codereg: 0x18247BFE8, metareg: 0x18247F860 in 431ms.
Initializing Binary...
Reading generic instances...OK (40.8275 ms)
Reading generic method pointers...

Fatal Exception initializing LibCpp2IL!
System.OverflowException: Arithmetic operation resulted in an overflow.
at LibCpp2IL.ClassReadingBinaryReader.ReadClassArrayAtRawAddr[T](Int64 offset, Int64 count)
at LibCpp2IL.Il2CppBinary.Init(UInt64 pCodeRegistration, UInt64 pMetadataRegistration)
at LibCpp2IL.LibCpp2IlMain.Initialize(Byte[] binaryBytes, Byte[] metadataBytes, Int32[] unityVersion)
at LibCpp2IL.LibCpp2IlMain.LoadFromFile(String pePath, String metadataPath, Int32[] unityVersion)
at Cpp2IL.Cpp2IlTasks.InitializeLibCpp2Il(Cpp2IlRuntimeArgs runtimeArgs)

Waiting for you to press enter - feel free to copy the error...`

How would I go around fixing this. Is there another argument that is needed? Also, thank you for making this tool. Sadly, I haven't been able to use it fully yet, but I appreciate your work.

Compiler generated methods without a body can cause issues with certain decompilers

Older decompilers such as dnSpy will throw an exception when decompiling methods that make use of compiler generated methods without method bodies. In the case that cpp2il succeeds in analyzing the compiler generated method it'll decompile fine. A solution to this could possibly be to emit method bodies that are similar to the bodies that are emitted for dummy dlls with analysis turned off and then adding a "FailedToAnalyse" attribute or something onto the method.

Weird errors during analysis when running latest error

I get alot of analysis errors when running the latest version

[Warn] [Program] Failed to generate synopsis for method System.Void GarbageBehaviour::EPKJEAPPPOJ(), instruction mov byte ptr ds:[129BA1EBh],1 at 0x11386F5C - got exception System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at LibCpp2IL.Metadata.Il2CppMetadata.GetStringLiteralFromIndex(UInt32 index)
   at LibCpp2IL.MetadataUsage.AsLiteral()
   at LibCpp2IL.MetadataUsage.ToString()
   at System.Text.ValueStringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at Cpp2IL.Analysis.Actions.ConstantToGlobalAction.ToTextSummary()
   at Cpp2IL.Analysis.Actions.BaseAction.GetSynopsisEntry()
   at Cpp2IL.Analysis.AsmAnalyzer.BuildMethodFunctionality()

Game: Among Us

Potential null type in dummy assembly attribute construction

Seen on a V29 game, specifically "Kill The King" by Quantum Lion Labs.

Stacktrace:

Unhandled Exception: System.AggregateException: One or more errors occurred. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: il2CppType
   at Cpp2IL.Core.Utils.AsmResolverUtils.GetTypeSignatureFromIl2CppType(ModuleDefinition module, Il2CppType il2CppType) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Utils\AsmResolverUtils.cs:line 114
   at Cpp2IL.Core.Utils.AsmResolverAssemblyPopulator.FromAnalyzedAttributeArgument(AssemblyDefinition parentAssembly, BaseCustomAttributeParameter parameter) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Utils\AsmResolverAssemblyPopulator.cs:line 108
   at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at AsmResolver.DotNet.Signatures.CustomAttributeSignature..ctor(IEnumerable`1 fixedArguments, IEnumerable`1 namedArguments)
   at Cpp2IL.Core.Utils.AsmResolverAssemblyPopulator.CopyCustomAttributes(HasCustomAttributes source, IList`1 destination) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Utils\AsmResolverAssemblyPopulator.cs:line 139
   at Cpp2IL.Core.Utils.AsmResolverAssemblyPopulator.PopulateCustomAttributes(AssemblyAnalysisContext asmContext) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Utils\AsmResolverAssemblyPopulator.cs:line 171
   at Cpp2IL.Core.Utils.MiscUtils.<>c__DisplayClass13_0`1.<ExecuteParallel>b__0(T t) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Utils\MiscUtils.cs:line 262
   at System.Linq.Parallel.PartitionedDataSource`1.ListContiguousIndexRangeEnumerator.MoveNext(T& currentElement, Int32& currentKey)
   at System.Linq.Parallel.StopAndGoSpoolingTask`2.SpoolingWork()
   at System.Linq.Parallel.SpoolingTaskBase.Work()
   at System.Linq.Parallel.QueryTask.BaseWork(Object unused)
   at System.Threading.Tasks.Task.Execute()
   --- End of inner exception stack trace ---
   at System.Linq.Parallel.QueryTaskGroupState.QueryEnd(Boolean userInitiatedDispose)
   at System.Linq.Parallel.MergeExecutor`1.Execute[TKey](PartitionedStream`2 partitions, Boolean ignoreOutput, ParallelMergeOptions options, TaskScheduler taskScheduler, Boolean isOrdered, CancellationState cancellationState, Int32 queryId)
   at System.Linq.Parallel.PartitionedStreamMerger`1.Receive[TKey](PartitionedStream`2 partitionedStream)
   at System.Linq.Parallel.UnaryQueryOperator`2.UnaryQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient`1 recipient)
   at System.Linq.Parallel.QueryOperator`1.GetOpenedEnumerator(Nullable`1 mergeOptions, Boolean suppressOrder, Boolean forEffect, QuerySettings querySettings)
   at System.Linq.Parallel.QueryOpeningEnumerator`1.OpenQuery()
   at System.Linq.Parallel.QueryOpeningEnumerator`1.MoveNext()
   at System.Linq.ParallelEnumerable.ToList[TSource](ParallelQuery`1 source)
   at Cpp2IL.Core.CorePlugin.AsmResolverDummyDllOutputFormat.DoOutput(ApplicationAnalysisContext context, String outputRoot) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\CorePlugin\AsmResolverDummyDllOutputFormat.cs:line 48
   at Cpp2IL.Program.MainWithArgs(Cpp2IlRuntimeArgs runtimeArgs) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL\Program.cs:line 340
   at Cpp2IL.Program.Main(String[] args) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL\Program.cs:line 268

Stack implies an Enum parameter with either null enum type or null underlying primitive type.

Note that some cleanup to this code has been implemented in 454c729, which may have reduced the issue.

Failed to initialize LibCpp2IL: Failed to find pCodegenModules

I am using MelonLoader to inject mod to an il2cpp game, and when it comes to initalize MelonLoader, it throws out the following error.

[00:27:17.211]    at LibCpp2IL.BinarySearcher.FindCodeRegistrationPost2019() in C:\Users\Sam\RiderProjects\Cpp2IL\LibCpp2IL\BinarySearcher.cs:line 174
[00:27:17.212]    at LibCpp2IL.Il2CppBinary.FindCodeAndMetadataReg(Int32 methodCount, Int32 typeDefinitionsCount) in C:\Users\Sam\RiderProjects\Cpp2IL\LibCpp2IL\Il2CppBinary.cs:line 417
[00:27:17.213]    at LibCpp2IL.LibCpp2IlBinaryRegistry.CreateAndInit(Byte[] buffer, Il2CppMetadata metadata) in C:\Users\Sam\RiderProjects\Cpp2IL\LibCpp2IL\LibCpp2IlBinaryRegistry.cs:line 62
[00:27:17.214]    at LibCpp2IL.LibCpp2IlMain.Initialize(Byte[] binaryBytes, Byte[] metadataBytes, Int32[] unityVersion) in C:\Users\Sam\RiderProjects\Cpp2IL\LibCpp2IL\LibCpp2IlMain.cs:line 150
[00:27:17.215]    at Cpp2IL.Core.Cpp2IlApi.InitializeLibCpp2Il(String assemblyPath, String metadataPath, Int32[] unityVersion, Boolean allowUserToInputAddresses) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Cpp2IlApi.cs:line 159
[00:27:17.216]    --- End of internal exception stack monitoring ---
[00:27:17.216]    at Cpp2IL.Core.Cpp2IlApi.InitializeLibCpp2Il(String assemblyPath, String metadataPath, Int32[] unityVersion, Boolean allowUserToInputAddresses) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL.Core\Cpp2IlApi.cs:line 171
[00:27:17.217]    at Cpp2IL.Program.MainWithArgs(Cpp2IlRuntimeArgs runtimeArgs) line C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL\Program.cs:line 324
[00:27:17.218]    at Cpp2IL.Program.Main(String[] args) in C:\Users\Sam\RiderProjects\Cpp2IL\Cpp2IL\Program.cs:line 268```

Unhandled exception in Arm64 disassembler

I've tried to run Cpp2IL on this apk and got following exception

[Info] [Program] Running Scan for Known Functions...
[Info] [Program]        Running entire .text section through Arm64 disassembler, this might take up to several minutes for large games, and may fail on large games if you have <16GB ram...
Unhandled exception. System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
   at System.Collections.Generic.List`1.get_Item(Int32 )
   at Cpp2IL.Core.Arm64KeyFunctionAddresses..ctor()
   at Cpp2IL.Core.Cpp2IlApi.ScanForKeyFunctionAddresses()
   at Cpp2IL.Program.MainWithArgs(Cpp2IlRuntimeArgs runtimeArgs)
   at Cpp2IL.Program.Main(String[] args)

Then I've made slight change in the code so it can proceed past above problematic part and now it just spams following Exception in console and never finishes:

[Warn] [Analyze] Failed to perform analysis on method
While analysing instruction ldr q0, [x8, #0x240] at 0xD03314
Got exception: System.ArgumentException: Owner is null but reflection data T is a generic parameter, so needs an owner context. (Parameter 'owner')
   at Cpp2IL.Core.Utils.MiscUtils.TryResolveTypeReflectionData(Il2CppTypeReflectionData typeData, IGenericParameterProvider owner, IGenericParameterProvider[] extra) in e:\Cpp2IL\Cpp2IL.Core\Utils\MiscUtils.cs:line 582
   at Cpp2IL.Core.Utils.MiscUtils.TryResolveTypeReflectionData(Il2CppTypeReflectionData typeData) in e:\Dev\WoW\tools\Cpp2IL\Cpp2IL.Core\Utils\MiscUtils.cs:line 549
   at Cpp2IL.Core.Analysis.Actions.ARM64.Arm64MetadataUsageTypeToRegisterAction..ctor(MethodAnalysis`1 context, Arm64Instruction instruction) in e:\Cpp2IL\Cpp2IL.Core\Analysis\Actions\ARM64\Arm64MetadataUsageTypeToRegisterAction.cs:line 44
   at Cpp2IL.Core.Analysis.AsmAnalyzerArmV8A.CheckForTwoOpInstruction(Arm64Instruction instruction) in e:\Cpp2IL\Cpp2IL.Core\Analysis\AsmAnalyzerArmV8A.InstructionChecks.cs:line 231
   at Cpp2IL.Core.Analysis.AsmAnalyzerArmV8A.PerformInstructionChecks(Arm64Instruction instruction) in e:\Cpp2IL\Cpp2IL.Core\Analysis\AsmAnalyzerArmV8A.InstructionChecks.cs:line 28   at Cpp2IL.Core.Analysis.AsmAnalyzerBase`1.AnalyzeMethod() in e:\Cpp2IL\Cpp2IL.Core\Analysis\AsmAnalyzerBase.cs:line 374

Cpp2IL.Core.Exceptions.DllSaveException

Tried to use this on a Nintendo Switch build of a game made with Unity using the force- options with --experimental-enable-il-to-assembly-please and --throw-safety-out-the-window.

I'm using the latest windows build from https://github.com/SamboyCoding/Cpp2IL/actions/runs/1450922865

At the end I get the following exception:

[Fail] [Program] Cpp2IL.Core.Exceptions.DllSaveException: Fatal Exception writing DLL E:\Downloads\Cpp2IL-Windows (1)\cpp2il_out\Assembly-CSharp.dll
 ---> Cpp2IL.Core.Exceptions.TypeWriteFailedException: Failed to write type Dpr.Battle.View.TaskSealEffects due to an exception
 ---> Cpp2IL.Core.Exceptions.MethodWriteFailedException: Failed to write body for method System.Void Dpr.Battle.View.TaskSealEffects::.ctor(Dpr.ObjectEntity,System.Collections.Generic.List`1<Dpr.Battle.View.Objects.BtlvEffectInstance>,System.Single,System.Int32) due to an exception
 ---> Cpp2IL.Core.Exceptions.InstructionWriteFailedException: Failed to write operand for instruction IL_003d: ldtoken Dpr.Battle.View.FromToPair`1<UnityEngine.Vector3>[] due to an exception
 ---> System.ArgumentException: Member 'UnityEngine.Vector3' is declared in another module and needs to be imported
   at Mono.Cecil.MetadataBuilder.LookupToken(IMetadataTokenProvider provider)
   at Mono.Cecil.SignatureWriter.WriteTypeSignature(TypeReference type)
   at Mono.Cecil.SignatureWriter.WriteGenericInstanceSignature(IGenericInstance instance)
   at Mono.Cecil.MetadataBuilder.GetTypeSpecToken(TypeReference type)
   at Mono.Cecil.MetadataBuilder.LookupToken(IMetadataTokenProvider provider)
   at DMD<Mono.Cecil.Cil.CodeWriter::WriteOperand>(CodeWriter this, Instruction instruction)
   --- End of inner exception stack trace ---
   at DMD<Mono.Cecil.Cil.CodeWriter::WriteOperand>(CodeWriter this, Instruction instruction)
   at Mono.Cecil.Cil.CodeWriter.WriteInstructions()
   at Mono.Cecil.Cil.CodeWriter.WriteResolvedMethodBody(MethodDefinition method)
   at DMD<Mono.Cecil.Cil.CodeWriter::WriteMethodBody>(CodeWriter this, MethodDefinition method)
   --- End of inner exception stack trace ---
   at DMD<Mono.Cecil.Cil.CodeWriter::WriteMethodBody>(CodeWriter this, MethodDefinition method)
   at Mono.Cecil.MetadataBuilder.AddMethod(MethodDefinition method)
   at Mono.Cecil.MetadataBuilder.AddMethods(TypeDefinition type)
   at DMD<Mono.Cecil.MetadataBuilder::AddType>(MetadataBuilder this, TypeDefinition type)
   --- End of inner exception stack trace ---
   at DMD<Mono.Cecil.MetadataBuilder::AddType>(MetadataBuilder this, TypeDefinition type)
   at Mono.Cecil.MetadataBuilder.AddTypes()
   at Mono.Cecil.MetadataBuilder.BuildTypes()
   at Mono.Cecil.MetadataBuilder.BuildModule()
   at Mono.Cecil.MetadataBuilder.BuildMetadata()
   at Mono.Cecil.ModuleWriter.Write(ModuleDefinition module, Disposable`1 stream, WriterParameters parameters)
   at Mono.Cecil.ModuleWriter.WriteModule(ModuleDefinition module, Disposable`1 stream, WriterParameters parameters)
   at Cpp2IL.Core.Cpp2IlApi.SaveAssemblies(String toWhere, List`1 assemblies)
   --- End of inner exception stack trace ---
   at Cpp2IL.Core.Cpp2IlApi.SaveAssemblies(String toWhere, List`1 assemblies)
   at Cpp2IL.Program.DoAnalysisForAssembly(String assemblyName, AnalysisLevel analysisLevel, String rootDir, BaseKeyFunctionAddresses keyFunctionAddresses, Boolean doIlToAsm, Boolean parallel, Boolean continueThroughErrors)
   at Cpp2IL.Program.MainWithArgs(Cpp2IlRuntimeArgs runtimeArgs)
   at Cpp2IL.Program.Main(String[] args)

There are also more (seemingly non-fatal) errors throughout the process; I've attached the full log in case they're relevant.
log.txt

Possible issue with --parallel arg

Note: I don't have the file open in notepad or any such thing. Haven't touched the text files at all. Only happens when using the --parallel arg

Unhandled exception. System.AggregateException: One or more errors occurred. (The process cannot access the file 'E:\Windows\Programs\Software\SteamLibrary\steamapps\common\VRChatCopy\cpp2il_out\types\Assembly-CSharp\__c_methods.txt' because it is being used by another process.) (The process cannot access the file 'E:\Windows\Programs\Software\SteamLibrary\steamapps\common\VRChatCopy\cpp2il_out\types\Assembly-CSharp\__c_methods.txt' because it is being used by another process.) (The process cannot access the file 'E:\Windows\Programs\Software\SteamLibrary\steamapps\common\VRChatCopy\cpp2il_out\types\Assembly-CSharp\__c_methods.txt' because it is being used by another process.)
 ---> System.IO.IOException: The process cannot access the file 'E:\Windows\Programs\Software\SteamLibrary\steamapps\common\VRChatCopy\cpp2il_out\types\Assembly-CSharp\__c_methods.txt' because it is being used by another process.
   at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
   at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.StreamWriter.ValidateArgsAndOpenPath(String path, Boolean append, Encoding encoding, Int32 bufferSize)
   at System.IO.File.WriteAllText(String path, String contents)
   at Cpp2IL.Core.Cpp2IlApi.<>c__DisplayClass17_0.<AnalyseAssembly>g__ProcessType|3(TypeDefinition type)
   at System.Linq.Parallel.ForAllOperator`1.ForAllEnumerator`1.MoveNext(TInput& currentElement, Int32& currentKey)
   at System.Linq.Parallel.ForAllSpoolingTask`2.SpoolingWork()
   at System.Linq.Parallel.SpoolingTaskBase.Work()
   at System.Linq.Parallel.QueryTask.BaseWork(Object unused)
   at System.Linq.Parallel.QueryTask.<>c.<.cctor>b__10_0(Object o)
   at System.Threading.Tasks.Task.InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__277_0(Object obj)
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
   --- End of inner exception stack trace ---
   at System.Linq.Parallel.QueryTaskGroupState.QueryEnd(Boolean userInitiatedDispose)
   at System.Linq.Parallel.SpoolingTask.SpoolForAll[TInputOutput,TIgnoreKey](QueryTaskGroupState groupState, PartitionedStream`2 partitions, TaskScheduler taskScheduler)
   at System.Linq.Parallel.DefaultMergeHelper`2.System.Linq.Parallel.IMergeHelper<TInputOutput>.Execute()
   at System.Linq.Parallel.MergeExecutor`1.Execute()
   at System.Linq.Parallel.MergeExecutor`1.Execute[TKey](PartitionedStream`2 partitions, Boolean ignoreOutput, ParallelMergeOptions options, TaskScheduler taskScheduler, Boolean isOrdered, CancellationState cancellationState, Int32 queryId)
   at System.Linq.Parallel.PartitionedStreamMerger`1.Receive[TKey](PartitionedStream`2 partitionedStream)
   at System.Linq.Parallel.UnaryQueryOperator`2.UnaryQueryOperatorResults.ChildResultsRecipient.Receive[TKey](PartitionedStream`2 inputStream)
   at System.Linq.Parallel.ListQueryResults`1.GivePartitionedStream(IPartitionedStreamRecipient`1 recipient)
   at System.Linq.Parallel.UnaryQueryOperator`2.UnaryQueryOperatorResults.GivePartitionedStream(IPartitionedStreamRecipient`1 recipient)
   at System.Linq.Parallel.QueryOperator`1.GetOpenedEnumerator(Nullable`1 mergeOptions, Boolean suppressOrder, Boolean forEffect, QuerySettings querySettings)
   at System.Linq.Parallel.ForAllOperator`1.RunSynchronously()
   at System.Linq.ParallelEnumerable.ForAll[TSource](ParallelQuery`1 source, Action`1 action)
   at Cpp2IL.Core.Cpp2IlApi.AnalyseAssembly(AnalysisLevel analysisLevel, AssemblyDefinition assembly, KeyFunctionAddresses keyFunctionAddresses, String methodOutputDir, Boolean parallel)
   at Cpp2IL.Program.DoAssemblyCSharpAnalysis(String assemblyName, AnalysisLevel analysisLevel, String rootDir, KeyFunctionAddresses keyFunctionAddresses, Boolean doIlToAsm, Boolean parallel)
   at Cpp2IL.Program.MainWithArgs(Cpp2IlRuntimeArgs runtimeArgs)
   at Cpp2IL.Program.Main(String[] args)
 ---> (Inner Exception #1) System.IO.IOException: The process cannot access the file 'E:\Windows\Programs\Software\SteamLibrary\steamapps\common\VRChatCopy\cpp2il_out\types\Assembly-CSharp\__c_methods.txt' because it is being used by another process.
   at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
   at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.StreamWriter.ValidateArgsAndOpenPath(String path, Boolean append, Encoding encoding, Int32 bufferSize)
   at System.IO.File.WriteAllText(String path, String contents)
   at Cpp2IL.Core.Cpp2IlApi.<>c__DisplayClass17_0.<AnalyseAssembly>g__ProcessType|3(TypeDefinition type)
   at System.Linq.Parallel.ForAllOperator`1.ForAllEnumerator`1.MoveNext(TInput& currentElement, Int32& currentKey)
   at System.Linq.Parallel.ForAllSpoolingTask`2.SpoolingWork()
   at System.Linq.Parallel.SpoolingTaskBase.Work()
   at System.Linq.Parallel.QueryTask.BaseWork(Object unused)
   at System.Linq.Parallel.QueryTask.RunTaskSynchronously(Object o)
   at System.Threading.Tasks.Task.InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__277_0(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)<---

 ---> (Inner Exception #2) System.IO.IOException: The process cannot access the file 'E:\Windows\Programs\Software\SteamLibrary\steamapps\common\VRChatCopy\cpp2il_out\types\Assembly-CSharp\__c_methods.txt' because it is being used by another process.
   at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
   at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.StreamWriter.ValidateArgsAndOpenPath(String path, Boolean append, Encoding encoding, Int32 bufferSize)
   at System.IO.File.WriteAllText(String path, String contents)
   at Cpp2IL.Core.Cpp2IlApi.<>c__DisplayClass17_0.<AnalyseAssembly>g__ProcessType|3(TypeDefinition type)
   at System.Linq.Parallel.ForAllOperator`1.ForAllEnumerator`1.MoveNext(TInput& currentElement, Int32& currentKey)
   at System.Linq.Parallel.ForAllSpoolingTask`2.SpoolingWork()
   at System.Linq.Parallel.SpoolingTaskBase.Work()
   at System.Linq.Parallel.QueryTask.BaseWork(Object unused)
   at System.Linq.Parallel.QueryTask.<>c.<.cctor>b__10_0(Object o)
   at System.Threading.Tasks.Task.InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__277_0(Object obj)
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)

Implement analysis context for method parameters

Method parameters can and often do have custom attributes. Most notably, System.ParamArrayAttribute indicates that an array parameter is actually params, meaning no explicit array construction is required from the caller side, but also Jetbrains nullability attributes, optional attributes, etc. could be present. At the moment, both the legacy new-analysis branch of Cpp2IL and the rewrite have no support for reading CAs on parameters.

Getting the custom attribute data should be simple - like other members with custom attributes, a simple binary search for the token is sufficient, or on v24 a simple indexed lookup - however a rework of the data structure will likely be required in order to add a ParameterAnalysisContext, as well as a rework of the DummyDLL output format to actually use it.

While we're creating analysis contexts for these, adding some sort of specifier to determine what register the parameter starts in could be useful, as all ApplicationAnalysisContext objects have an InstructionSet.

Equally, the data for parameters is somewhat fragmented - the default value, if present, is dependent on the absolute index of the parameter in the metadata array, the parameter type is separate, etc, so caching these in the context could be useful, though whether these are best exposed as raw libcpp2il types or something else is worth discussion. At the very least, they should be added as (cache-backed) getters to the parameter definition.

Finally, the ability to inject parameters must be maintained (and this is a good opportunity to allow for named injected parameters)

IndexOutOfRange Exception

Hi, there is a null reference exception in the part where it reads the generic methods.

Stack trace:
        Reading generic methods...Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at LibCpp2IL.Il2CppBinary.GetMethodSpec(Int32 index)
   at LibCpp2IL.Il2CppBinary.GetGenericMethodFromIndex(Int32 genericMethodIndex, Int32 genericMethodPointerIndex, Il2CppConcreteGenericMethod& concreteMethod)
   at LibCpp2IL.Il2CppBinary.Init(UInt64 pCodeRegistration, UInt64 pMetadataRegistration)
   at LibCpp2IL.PE.PE.AutoInit(UInt64 pCodeRegistration, UInt64 pMetadataRegistration)
   at LibCpp2IL.PE.PE.PlusSearch(Int32 methodCount, Int32 typeDefinitionsCount)
   at LibCpp2IL.LibCpp2IlMain.Initialize(Byte[] binaryBytes, Byte[] metadataBytes, Int32[] unityVersion)
   at LibCpp2IL.LibCpp2IlMain.LoadFromFile(String pePath, String metadataPath, Int32[] unityVersion)
   at Cpp2IL.Cpp2IlTasks.InitializeLibCpp2Il(Cpp2IlRuntimeArgs runtimeArgs)
   at Cpp2IL.Program.MainWithArgs(Cpp2IlRuntimeArgs runtimeArgs)
   at Cpp2IL.Program.Main(String[] args)

The game is Among Us. (again)

DllSaveException Invalid Cast

I get the following exception when trying to analyse my dll.
Any help would be appreciated

[Fail] [Program] Cpp2IL.Core.Exceptions.DllSaveException: Fatal Exception writing DLL D:\Dev\WotwBepInExTest\Cpp2IL\cpp2il_out\System.dll
 ---> System.InvalidCastException: Specified cast is not valid.
   at Mono.Cecil.SignatureWriter.WriteCustomAttributeElement(TypeReference type, CustomAttributeArgument argument)
   at Mono.Cecil.SignatureWriter.WriteCustomAttributeConstructorArguments(CustomAttribute attribute)
   at Mono.Cecil.MetadataBuilder.GetCustomAttributeSignature(CustomAttribute attribute)
   at Mono.Cecil.MetadataBuilder.AddCustomAttributes(ICustomAttributeProvider owner)
   at Mono.Cecil.MetadataBuilder.AddProperty(PropertyDefinition property)
   at Mono.Cecil.MetadataBuilder.AddProperties(TypeDefinition type)
   at Mono.Cecil.MetadataBuilder.AddType(TypeDefinition type)
   at Mono.Cecil.MetadataBuilder.AddTypes()
   at Mono.Cecil.MetadataBuilder.BuildTypes()
   at Mono.Cecil.MetadataBuilder.BuildModule()
   at Mono.Cecil.MetadataBuilder.BuildMetadata()
   at Mono.Cecil.ModuleWriter.BuildMetadata(ModuleDefinition module, MetadataBuilder metadata)
   at Mono.Cecil.ModuleWriter.Write(ModuleDefinition module, Disposable`1 stream, WriterParameters parameters)
   at Mono.Cecil.ModuleWriter.WriteModule(ModuleDefinition module, Disposable`1 stream, WriterParameters parameters)
   at Cpp2IL.Core.Cpp2IlApi.SaveAssemblies(String toWhere, List`1 assemblies)
   --- End of inner exception stack trace ---
   at Cpp2IL.Core.Cpp2IlApi.SaveAssemblies(String toWhere, List`1 assemblies)
   at Cpp2IL.Core.Cpp2IlApi.SaveAssemblies(String toWhere)
   at Cpp2IL.Program.MainWithArgs(Cpp2IlRuntimeArgs runtimeArgs)
   at Cpp2IL.Program.Main(String[] args)

Managed Function calls pick IDisposable#Dispose a lot

Most noticeable with IEnumerator instances being created - instead of a call to the constructor being emitted, it's often replaced with a call to IDisposable.Dispose, because IEnumerator implements IDisposable.

When there are multiple methods sharing an empty body, we have to use context clues. For example in this case, it's just after a newobj instruction, so it's obviously going to be a constructor call.

Blockade 3D is unsupported

Well this is the first time I try this tool
I try the game called Blockade3D but it gets stuck:

PS F:\Portable Apps\Cpp2IL> ./Cpp2IL-Win --game-path D:\Steam\steamapps\common\Blockade3d\
===Cpp2IL by Samboy063===
A Tool to Reverse Unity's "il2cpp" Build Process.
Running on Win32NT
Using path: D:\Steam\steamapps\common\Blockade3d\
Auto-detected game name: Blockade3D
Located game EXE: D:\Steam\steamapps\common\Blockade3d\Blockade3D.exe
Located global-metadata: D:\Steam\steamapps\common\Blockade3d\Blockade3D_Data\il2cpp_data\Metadata\global-metadata.dat

Attempting to determine Unity version...
This game is built with Unity version 2019.2.0
Reading metadata...
Using IL2CPP Metadata version 24,2
        Reading image definitions...OK (4,9696 ms)
        Reading type definitions...OK (105,2784 ms)
        Reading interface offsets...OK (5,5931 ms)
        Reading method definitions...OK (511,8608 ms)
        Reading method parameter definitions...OK (127,8583 ms)
        Reading field definitions...OK (76,0681 ms)
        Reading default field values...OK (9,5117 ms)
        Reading default parameter values...OK (0,5215 ms)
        Reading property definitions...OK (25,2022 ms)
        Reading interface definitions...OK (1,461 ms)
        Reading nested type definitions...OK (0,0653 ms)
        Reading event definitions...OK (0,3029 ms)
        Reading generic container definitions...OK (0,6818 ms)
        Reading generic parameter definitions...OK (1,2739 ms)
        Reading string definitions...OK (7,301 ms)
        Reading usage data...OK (135,5431 ms)
        Reading field references...OK (0,5184 ms)
        Reading attribute types...OK (27,2076 ms)
Reading binary / game assembly...
        -Initializing MemoryStream of 16517120 bytes, parsing sections, and initializing with auto+ mode.
Reading PE File Header...OK (0,2667 ms)
        Image Base at 0x10000000
        DLL is 32-bit
Looking for registration functions...
        Identified execute section .text
        Identified execute section il2cpp
        Identified data section .rdata
        Identified data section .data
Attempting to locate code and metadata registration functions...
        (32-bit PE)
        Failed to find code and metadata registration functions using primary location method (probably because we're post-2019), checking if we can use the fallback...
        Found il2cpp_init export (resolves to virtual addr 0x100264A0), using fallback method to find Code and Metadata registration...
        Located probable Runtime::Init function at virtual addr 0x10055AE0

--version argument displays an error message.

The following message occurs when running the --version command.

.\Cpp2IL-2021.3.0-Windows.exe --version
===Cpp2IL by Samboy063===
A Tool to Reverse Unity's "il2cpp" Build Process.

[Info] [Program] Running on Win32NT
Cpp2IL 2021.3.0.0
[Fail] [Program] Execution Failed: Failed to parse command line arguments

It displays the version but also an error message. The error message should not display.

High memory usage when building AsmResolver outputs due to no sharing

When building AsmResolver assemblies, Constant objects are not shared (realistically we only need one of each type-value pair), resulting in thousands of duplicate objects being created and massively increasing memory usage.

E.g. a method with 64 parameters (which does happen with VRC!) each of which has a default value, may result in 64 constants being created, even if most of those constants are the same (e.g. the null constant, Class/00 00 00 00).

This could probably be alleviated, at least for the null constant, and some common other ones like integer zero, boolean values, etc, by caching these constant values, significantly reducing memory pressure. Sharing between assemblies should not be a problem.

[BUG] Coroutines cannot be created as IL.

Application version: 2021.3.4
Target application: Gems of War (32-bit)

Displayed error:

Generated IL:
    Action of type Cpp2IL.Core.Analysis.Actions.Important.CallManagedFunctionAction at (0x102645C2) is corrupt (Don't know what method is being called) and cannot be created as IL. Aborting here.

Part of the generated pseudocode includes:

    [instruction error - managed method being called is null]
    return
    throw new System.NullReferenceException()

This error appears when attempting to reverse a function which calls MonoBehavior.StartCoroutine. See Unity's documentation on Coroutines, which follow an abnormal execution flow, utilizing yield calls to pause execution, resuming execution during the next frame of the game loop. These types of functions are tricky for .NET decompilation too, (ILSpy and dnSpy can reverse them now but weren't able to a couple of years ago).

Please let me know if anything else would be helpful in resolving this issue (such as the full method dump file, or the log output from the reversing process). Your hard work and excellent understanding of reverse engineering is greatly appreciated.

As an aside, the application I am reversing is a unique case in which very similar versions of the application binaries exist just before and just after the switch to IL2CPP.

Support arm64 on unix

===Cpp2IL by Samboy063===
A Tool to Reverse Unity's "il2cpp" Build Process.

[Info] [Program] Running on Unix
[Warn] [Program] Using force options, I sure hope you know what you're doing!
[Info] [Program] Detected that Capstone's Managed assembly is missing. Attempting to copy the windows one...
[Warn] [Program] Couldn't find it at /home/mart/Downloads/Cpp2Il/runtimes/win-x64/lib/netstandard2.0/Gee.External.Capstone.dll. Your application will probably now throw an exception due to it being missing.
[Info] [Library] Initializing Metadata...
[Info] [Library] 	Using actual IL2CPP Metadata version 24.5
[Info] [Library] Initialized Metadata in 924ms
[Info] [Library] Searching Binary for Required Data...
[Info] [Library] Got Binary codereg: 0x4AC9F18, metareg: 0x4ACA5D8 in 2150ms.
[Info] [Library] Initializing Binary...
[Info] [Library] Initialized Binary in 344ms
[Info] [Library] Mapping Globals...OK (15ms)
[Info] [Library] Mapping pointers to Il2CppMethodDefinitions...Processed 70903 OK (37ms)
[Info] [Program] Building assemblies...This may take some time.
[Info] [Program] Finished Building Assemblies in 2435ms
[Info] [Program] Fixing up explicit overrides. Any warnings you see here aren't errors - they usually indicate improperly stripped or obfuscated types, but this is not a big deal. This should only take a second...
[Info] [Program] Fixup complete (102ms)
[Warn] [Program] Unable to hook native library resolving for Capstone. If you're not on windows and analysing an ARM or ARM64 binary, expect this to crash!
[Info] [Program] Running Scan for Known Functions...
Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'Gee.External.Capstone, Version=2.0.2.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

File name: 'Gee.External.Capstone, Version=2.0.2.0, Culture=neutral, PublicKeyToken=null'
   at Cpp2IL.Core.Arm64KeyFunctionAddresses..ctor()
   at Cpp2IL.Core.Cpp2IlApi.ScanForKeyFunctionAddresses()
   at Cpp2IL.Program.MainWithArgs(Cpp2IlRuntimeArgs runtimeArgs)
   at Cpp2IL.Program.Main(String[] args)

Failed to perform analysis on method (Vacation Simulator)

Trying to get some basic idea on how scripts in Vacation Simulator work but when trying to run the latest commit (commit_06f6ecc658c6378f90266e7e51b8672abab6c467 as of now) it is giving out many errors relating to "Failed to perform analysis on method" which causes it to not create method files for many of the scripts (including the one I needed Cpp2IL for in the first place). Vacation Simulator is currently on 2018.4.14 with IL2CPP version 24.1 in case you need to know.

cpp2il-output.txt

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.