Skip to content

Commit

Permalink
fix: resolve code issues
Browse files Browse the repository at this point in the history
  • Loading branch information
tautcony committed Feb 1, 2024
1 parent 0b5dfd8 commit d9d568f
Show file tree
Hide file tree
Showing 12 changed files with 62 additions and 40 deletions.
6 changes: 3 additions & 3 deletions ISTA-Patcher/Core/Patch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public static void PatchISTA(IPatcher patcher, ProgramArgs.PatchOptions options)
)
);

Task.WaitAll(tasks.ToArray());
Task.WaitAll(tasks.ToArray(), cts.Token);
}

foreach (var line in BuildIndicator(patcher.Patches, patchAppliedCount))
Expand Down Expand Up @@ -94,7 +94,7 @@ private static void PatchSingleFile(string pendingPatchItem, IList<int> patchApp
if (options.Restore && File.Exists(bakFileFullPath))
{
Log.Debug("Backup detected, restoring {Item}", pendingPatchItem);
File.Copy(bakFileFullPath, pendingPatchItemFullPath, true);
File.Copy(bakFileFullPath, pendingPatchItemFullPath, overwrite: true);
}

var module = PatchUtils.LoadModule(pendingPatchItemFullPath);
Expand Down Expand Up @@ -129,7 +129,7 @@ private static void PatchSingleFile(string pendingPatchItem, IList<int> patchApp
if (!File.Exists(bakFileFullPath))
{
Log.Debug("Bakup file {BakFileFullPath} does not exist, copy...", bakFileFullPath);
File.Copy(pendingPatchItemFullPath, bakFileFullPath, false);
File.Copy(pendingPatchItemFullPath, bakFileFullPath, overwrite: false);
}

PatchUtils.SetPatchedMark(module);
Expand Down
8 changes: 4 additions & 4 deletions ISTA-Patcher/Core/PatchUtils.Base.cs
Original file line number Diff line number Diff line change
Expand Up @@ -273,14 +273,14 @@ public static void GenerateMockRegFile(string basePath)
};
var value = licenseInfo.Serialize();
const string template = "Windows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\\u0042\u004d\u0057group\\ISPI\\Rheingold]\n\"License\"=\"{}\"";
File.WriteAllText(licenseFile, template.Replace("{}", ToLiteral(value)));
File.WriteAllText(licenseFile, template.Replace("{}", ToLiteral(value), StringComparison.Ordinal));
}

private static string ToLiteral(string valueTextForCompiler)
{
return valueTextForCompiler
.Replace("\r", "\\r")
.Replace("\n", "\\n")
.Replace("\"", "\\\"");
.Replace("\r", "\\r", StringComparison.Ordinal)
.Replace("\n", "\\n", StringComparison.Ordinal)
.Replace("\"", "\\\"", StringComparison.Ordinal);
}
}
2 changes: 1 addition & 1 deletion ISTA-Patcher/Core/Patcher/IPatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public static List<Func<ModuleDefMD, int>> GetPatches(params Type[] attributes)
{
return typeof(PatchUtils)
.GetMethods()
.Where(m => Array.Exists(attributes, attribute => m.GetCustomAttributes(attribute, false).Length > 0))
.Where(m => Array.Exists(attributes, attribute => m.GetCustomAttributes(attribute, inherit: false).Length > 0))
.Select(m => (Func<ModuleDefMD, int>)Delegate.CreateDelegate(typeof(Func<ModuleDefMD, int>), m))
.ToList();
}
Expand Down
1 change: 1 addition & 0 deletions ISTA-Patcher/ISTA-Patcher.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Released under the GNU GPLv3+.</Copyright>
<ApplicationIcon>patcher-icon.ico</ApplicationIcon>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<StripSymbols>false</StripSymbols>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
Expand Down
10 changes: 5 additions & 5 deletions ISTA-Patcher/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ private static async Task<KeyValuePair<string, string>> CheckFileIntegrity(strin

var wasVerified = false;

var bChecked = NativeMethods.StrongNameSignatureVerificationEx(filePath, true, ref wasVerified);
var bChecked = NativeMethods.StrongNameSignatureVerificationEx(filePath, fForceVerification: true, ref wasVerified);
if (bChecked)
{
checkResult += wasVerified ? "[S:OK]" : "[S:NG]";
Expand Down Expand Up @@ -192,7 +192,7 @@ private static async Task<int> RunLicenseOperationAndReturnExitCode(LicenseOptio
var fs = File.OpenRead(opts.KeyPairPath);
await using (fs.ConfigureAwait(false))
{
using var sr = new StreamReader(fs, new UTF8Encoding(false));
using var sr = new StreamReader(fs, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
keyPairXml = await sr.ReadToEndAsync().ConfigureAwait(false);
Log.Debug("Loaded private key from {KeyPairPath}", opts.KeyPairPath);
}
Expand Down Expand Up @@ -226,7 +226,7 @@ private static async Task<int> RunLicenseOperationAndReturnExitCode(LicenseOptio
var fs = File.OpenRead(opts.LicenseRequestPath);
await using (fs.ConfigureAwait(false))
{
using var sr = new StreamReader(fs, new UTF8Encoding(false));
using var sr = new StreamReader(fs, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
licenseXml = await sr.ReadToEndAsync().ConfigureAwait(false);
Log.Debug("Loaded license request from {LicensePath}", opts.LicenseRequestPath);
}
Expand Down Expand Up @@ -259,7 +259,7 @@ private static async Task<int> RunLicenseOperationAndReturnExitCode(LicenseOptio
var rsaCryptoServiceProvider = new RSACryptoServiceProvider(opts.dwKeySize);
rsaCryptoServiceProvider.FromXmlString(keyPairXml);

var parameters = rsaCryptoServiceProvider.ExportParameters(true);
var parameters = rsaCryptoServiceProvider.ExportParameters(includePrivateParameters: true);

var modulus = Convert.ToBase64String(parameters.Modulus);
var exponent = Convert.ToBase64String(parameters.Exponent);
Expand All @@ -285,7 +285,7 @@ private static async Task GenerateKeyPair(string privateKeyPath, int dwKeySize)
using var rsa = new RSACryptoServiceProvider(dwKeySize);
try
{
var privateKey = rsa.ToXmlString(true);
var privateKey = rsa.ToXmlString(includePrivateParameters: true);

var fs = new FileStream(privateKeyPath, FileMode.Create);
await using (fs.ConfigureAwait(false))
Expand Down
18 changes: 9 additions & 9 deletions ISTA-Patcher/Utils/AttributeUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,24 @@ namespace ISTA_Patcher.Utils;
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
internal class ISTAPatch : Attribute;

internal class ValidationPatch : ISTAPatch;
internal sealed class ValidationPatch : ISTAPatch;

internal class EssentialPatch : ISTAPatch;
internal sealed class EssentialPatch : ISTAPatch;

internal class SignaturePatch : ISTAPatch;
internal sealed class SignaturePatch : ISTAPatch;

internal class ToyotaPatch : ISTAPatch;
internal sealed class ToyotaPatch : ISTAPatch;

internal class ENETPatch : ISTAPatch;
internal sealed class ENETPatch : ISTAPatch;

internal class RequirementsPatch : ISTAPatch;
internal sealed class RequirementsPatch : ISTAPatch;

internal class NotSendPatch : ISTAPatch;
internal sealed class NotSendPatch : ISTAPatch;

internal class UserAuthPatch : ISTAPatch;
internal sealed class UserAuthPatch : ISTAPatch;

[AttributeUsage(AttributeTargets.Method, Inherited = false)]
internal class FromVersion(string version) : Attribute
internal sealed class FromVersion(string version) : Attribute
{
public string? Version { get; set; } = version;
}
40 changes: 31 additions & 9 deletions ISTA-Patcher/Utils/DnlibUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

namespace ISTA_Patcher.Utils;

using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text;
using dnlib.DotNet;
Expand Down Expand Up @@ -61,15 +62,27 @@ public static string DescriptionOf(MethodDef md)
/// </returns>
public static MethodDef? GetMethod(this ModuleDefMD module, string type, string name, string desc)
{
return module.GetType(type)?.Methods.FirstOrDefault(m => m.Name.Equals(name) && DescriptionOf(m).Equals(desc));
return module.GetType(type)?.Methods.FirstOrDefault(m => m.Name.Equals(name) && DescriptionOf(m).Equals(desc, StringComparison.Ordinal));
}

/// <summary>
/// Empties the given method.
/// </summary>
/// <param name="method">The <see cref="MethodDef"/> whose body will be emptied.</param>
/// <exception cref="ArgumentNullException">Thrown if the body of the method is null.</exception>
public static void EmptyingMethod(this MethodDef method) => method.ReturningWithValue();
public static void EmptyingMethod(this MethodDef method)
{
var body = method.Body;
if (body == null)
{
throw new ArgumentNullException($"{method.FullName}.Body null!");
}

body.Variables.Clear();
body.ExceptionHandlers.Clear();
body.Instructions.Clear();
body.Instructions.Add(Instruction.Create(OpCodes.Ret));
}

/// <summary>
/// Modifies the body of the <see cref="MethodDef"/> to return zero.
Expand Down Expand Up @@ -101,14 +114,14 @@ public static Action<MethodDef> ReturnUInt32Method(uint value)
/// </summary>
/// <param name="method">The <see cref="MethodDef"/> to modify.</param>
/// <exception cref="ArgumentNullException">Thrown if the body of the method is null.</exception>
public static void ReturnFalseMethod(this MethodDef method) => method.ReturningWithValue(false);
public static void ReturnFalseMethod(this MethodDef method) => method.ReturningWithValue(value: false);

/// <summary>
/// Modifies the body of the <see cref="MethodDef"/> to return true.
/// </summary>
/// <param name="method">The <see cref="MethodDef"/> to modify.</param>
/// <exception cref="ArgumentNullException">Thrown if the body of the method is null.</exception>
public static void ReturnTrueMethod(this MethodDef method) => method.ReturningWithValue(true);
public static void ReturnTrueMethod(this MethodDef method) => method.ReturningWithValue(value: true);

/// <summary>
/// Modifies the body of the <see cref="MethodDef"/> to return the specified string.
Expand Down Expand Up @@ -179,17 +192,26 @@ public static void ReplaceWith(this MethodDef method, IEnumerable<Instruction> i
/// <param name="returnType">The return type of the method.</param>
/// <param name="parameters">The array of parameter types.</param>
/// <returns>An instance of the <see cref="IMethod"/> interface representing the method call, or null if the method was not found.</returns>
public static IMethod? BuildCall(ModuleDef module, Type type, string method, Type returnType, Type[]? parameters)
public static IMethod? BuildCall(
ModuleDef module,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods)] Type type,
string method,
Type returnType,
Type[]? parameters)
{
var importer = new Importer(module);

// ReSharper disable once ConvertIfStatementToReturnStatement
MethodBase mb;
if (string.Equals(method, ".ctor", StringComparison.Ordinal))
{
return (from m in type.GetConstructors() where CheckParametersByType(m, parameters) select importer.Import(m)).FirstOrDefault();
mb = Array.Find(type.GetConstructors(), m => CheckParametersByType(m, parameters));
}
else
{
mb = Array.Find(type.GetMethods(), m => string.Equals(m.Name, method, StringComparison.Ordinal) && m.ReturnType == returnType && CheckParametersByType(m, parameters));
}

return (from m in type.GetMethods().Where(m => string.Equals(m.Name, method, StringComparison.Ordinal) && m.ReturnType == returnType) where CheckParametersByType(m, parameters) select importer.Import(m)).FirstOrDefault();
return importer.Import(mb);
}

/// <summary>
Expand All @@ -198,7 +220,7 @@ public static void ReplaceWith(this MethodDef method, IEnumerable<Instruction> i
/// <param name="method">The <see cref="MethodDef"/> to modify.</param>
/// <param name="value">The value to return.</param>
/// <exception cref="ArgumentNullException">Thrown if the body of the method is null or if the type of the value is not supported.</exception>
private static void ReturningWithValue(this MethodDef method, object? value = null)
private static void ReturningWithValue<T>(this MethodDef method, T? value)
{
var body = method.Body;
if (body == null)
Expand Down
4 changes: 2 additions & 2 deletions ISTA-Patcher/Utils/HashFileInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public string Hash
{
var bytes = Convert.FromBase64String(this._hash);
var hex = BitConverter.ToString(bytes);
this._hash = hex.Replace("-", string.Empty);
this._hash = hex.Replace("-", string.Empty, StringComparison.Ordinal);
}
catch (FormatException ex)
{
Expand All @@ -45,7 +45,7 @@ public string Hash

protected internal HashFileInfo(IReadOnlyList<string> fileInfos)
{
this.FilePath = fileInfos[0].Trim('\uFEFF').Replace("\\", "/");
this.FilePath = fileInfos[0].Trim('\uFEFF').Replace('\\', '/');
this.FileName = Path.GetFileName(this.FilePath);
this._hash = fileInfos[1];
}
Expand Down
2 changes: 1 addition & 1 deletion ISTA-Patcher/Utils/IntegrityUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public static class IntegrityUtils
[
0x33, 0x2f, 0x33, 0x48, 0x65, 0x78, 0x62, 0x4b, 0x4b, 0x46, 0x73, 0x34, 0x4c, 0x71, 0x70, 0x69,
0x43, 0x53, 0x67, 0x4b, 0x41, 0x58, 0x47, 0x55, 0x59, 0x43, 0x74, 0x71, 0x6a, 0x6f, 0x46, 0x63,
0x68, 0x66, 0x50, 0x69, 0x74, 0x41, 0x6d, 0x49, 0x38, 0x77, 0x45, 0x3d
0x68, 0x66, 0x50, 0x69, 0x74, 0x41, 0x6d, 0x49, 0x38, 0x77, 0x45, 0x3d,
];

public static IList<HashFileInfo>? DecryptFile(string sourceFilename)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static byte[] ToByteArray<T>(T licInfo)
var serializer = new XmlSerializer(typeof(T));
var ws = new XmlWriterSettings
{
Encoding = new UTF8Encoding(false),
Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false),
Indent = true,
IndentChars = " ",
OmitXmlDeclaration = true,
Expand Down
8 changes: 3 additions & 5 deletions ISTA-Patcher/Utils/LimitedConcurrencyLevelTaskScheduler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ private void NotifyThreadPoolOfPendingWork()
_currentThreadIsProcessingItems = false;
}
},
null);
state: null);
}

// Attempts to execute the specified task on the current thread.
Expand Down Expand Up @@ -134,10 +134,8 @@ protected sealed override IEnumerable<Task> GetScheduledTasks()
{
return this._tasks;
}
else
{
throw new NotSupportedException();
}

throw new NotSupportedException();
}
finally
{
Expand Down
1 change: 1 addition & 0 deletions ISTA-Patcher/patch-config.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
"System.Threading.Channels.dll",
"System.Threading.Tasks.Extensions.dll",
"System.ValueTuple.dll",
"WebView2Loader.dll",
"xmlunit-core.dll"
],
"toyota.include": [
Expand Down

0 comments on commit d9d568f

Please sign in to comment.