Skip to content

Commit

Permalink
Rebase on Morilli's Analyzer Rule Improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
TiKevin83 committed Aug 30, 2023
1 parent 02e7de7 commit 46e988b
Show file tree
Hide file tree
Showing 1,233 changed files with 7,437 additions and 14,744 deletions.
4 changes: 3 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ csharp_indent_labels = one_less_than_current

# Style rules
# Can't be in .globalconfig because dotnet format doesn't respect that https://github.com/dotnet/format/issues/1643
dotnet_diagnostic.IDE0039.severity = none

# Globalization rules
dotnet_code_quality.CA1305.excluded_symbol_names = T:System.Byte|T:System.SByte|T:System.Int16|T:System.UInt16|T:System.Int32|T:System.UInt32|T:System.Int64|T:System.UInt64|T:System.String|T:System.Text.StringBuilder|T:System.Convert

Expand Down Expand Up @@ -52,6 +52,8 @@ dotnet_diagnostic.IDE0032.severity = suggestion
dotnet_diagnostic.IDE0034.severity = suggestion
# Use pattern matching to avoid is check followed by a cast (without variable)
dotnet_diagnostic.IDE0038.severity = warning
# Use a local function instead of a lambda
dotnet_diagnostic.IDE0039.severity = none
# Use is null check
dotnet_diagnostic.IDE0041.severity = warning
# Deconstruct variable declaration
Expand Down
4 changes: 2 additions & 2 deletions src/BizHawk.BizInvoke/BizInvokeUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,15 @@ public static TypeBuilder CreateDelegateType(MethodInfo method, CallingConventio
for (int i = 0; i < paramInfos.Length; i++)
{
var p = delegateInvoke.DefineParameter(i + 1, ParameterAttributes.None, paramInfos[i].Name);
foreach (var a in paramInfos[i].GetCustomAttributes(false))
foreach (object? a in paramInfos[i].GetCustomAttributes(false))
{
p.SetCustomAttribute(GetAttributeBuilder(a));
}
}

{
var p = delegateInvoke.DefineParameter(0, ParameterAttributes.Retval, method.ReturnParameter!.Name);
foreach (var a in method.ReturnParameter.GetCustomAttributes(false))
foreach (object? a in method.ReturnParameter.GetCustomAttributes(false))
{
p.SetCustomAttribute(GetAttributeBuilder(a));
}
Expand Down
10 changes: 5 additions & 5 deletions src/BizHawk.BizInvoke/BizInvoker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public InvokerImpl(

public object Create(IImportResolver dll, IMonitor? monitor, ICallingConventionAdapter adapter)
{
var ret = Activator.CreateInstance(_implType)!;
object ret = Activator.CreateInstance(_implType)!;
_connectCallingConventionAdapter(ret, adapter);
foreach (var f in _hooks)
{
Expand Down Expand Up @@ -109,7 +109,7 @@ static BizInvoker()
public static T GetInvoker<T>(IImportResolver dll, ICallingConventionAdapter adapter)
where T : class
{
var nonTrivialAdapter = adapter.GetType() != CallingConventionAdapters.Native.GetType();
bool nonTrivialAdapter = adapter.GetType() != CallingConventionAdapters.Native.GetType();
InvokerImpl impl;
lock (Impls) impl = Impls.GetValueOrPut(
typeof(T),
Expand All @@ -126,7 +126,7 @@ public static T GetInvoker<T>(IImportResolver dll, ICallingConventionAdapter ada
public static T GetInvoker<T>(IImportResolver dll, IMonitor monitor, ICallingConventionAdapter adapter)
where T : class
{
var nonTrivialAdapter = adapter.GetType() != CallingConventionAdapters.Native.GetType();
bool nonTrivialAdapter = adapter.GetType() != CallingConventionAdapters.Native.GetType();
InvokerImpl impl;
lock (Impls) impl = Impls.GetValueOrPut(
typeof(T),
Expand Down Expand Up @@ -184,7 +184,7 @@ private static InvokerImpl CreateProxy(Type baseType, bool monitor, bool nonTriv

foreach (var (Info, Attr) in baseMethods)
{
var entryPointName = Attr!.EntryPoint ?? Info.Name;
string entryPointName = Attr!.EntryPoint ?? Info.Name;

var hook = Attr.Compatibility
? ImplementMethodDelegate(type, Info, Attr.CallingConvention, entryPointName, monitorField, nonTrivialAdapter)
Expand Down Expand Up @@ -376,7 +376,7 @@ private static Action<object, IImportResolver, ICallingConventionAdapter> Implem

bool WantsWinAPIBool()
{
var attrs = baseMethod.ReturnTypeCustomAttributes.GetCustomAttributes(typeof(MarshalAsAttribute), false);
object[] attrs = baseMethod.ReturnTypeCustomAttributes.GetCustomAttributes(typeof(MarshalAsAttribute), false);
return attrs.Length > 0 && ((MarshalAsAttribute)attrs[0]).Value is UnmanagedType.Bool;
}

Expand Down
15 changes: 6 additions & 9 deletions src/BizHawk.BizInvoke/BizInvokerUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,20 +50,17 @@ private class CF
/// Computes the byte offset of the first field of any class relative to a class pointer.
/// </summary>
/// <returns></returns>
public static int ComputeClassFirstFieldOffset()
{
return ComputeFieldOffset(typeof(CF).GetField("FirstField"));
}
public static int ComputeClassFirstFieldOffset() => ComputeFieldOffset(typeof(CF).GetField("FirstField"));

/// <summary>
/// Compute the byte offset of the first byte of string data (UTF16) relative to a pointer to the string.
/// </summary>
/// <returns></returns>
public static int ComputeStringOffset()
{
var s = new string(Array.Empty<char>());
string s = new(Array.Empty<char>());
int ret;
fixed(char* fx = s)
fixed (char* fx = s)
{
U u = new(new U2(s));
ret = (int) ((ulong) (UIntPtr) fx - (ulong) u.First!.P);
Expand All @@ -77,7 +74,7 @@ public static int ComputeStringOffset()
/// <returns></returns>
public static int ComputeValueArrayElementOffset()
{
var arr = new int[4];
int[] arr = new int[4];
int ret;
fixed (int* p = arr)
{
Expand All @@ -94,7 +91,7 @@ public static int ComputeValueArrayElementOffset()
/// <returns></returns>
public static int ComputeObjectArrayElementOffset()
{
var obj = new object[4];
object[] obj = new object[4];
var method = new DynamicMethod("ComputeObjectArrayElementOffsetHelper", typeof(int), new[] { typeof(object[]) }, typeof(string).Module, true);
var il = method.GetILGenerator();
var local = il.DeclareLocal(typeof(object[]), true);
Expand Down Expand Up @@ -124,7 +121,7 @@ public static int ComputeFieldOffset(FieldInfo fi)
throw new NotImplementedException("Only supported for class fields right now");
}

var obj = FormatterServices.GetUninitializedObject(fi.DeclaringType);
object obj = FormatterServices.GetUninitializedObject(fi.DeclaringType);
var method = new DynamicMethod("ComputeFieldOffsetHelper", typeof(int), new[] { typeof(object) }, typeof(string).Module, true);
var il = method.GetILGenerator();
var local = il.DeclareLocal(fi.DeclaringType, true);
Expand Down
72 changes: 21 additions & 51 deletions src/BizHawk.BizInvoke/CallingConventionAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,25 +95,13 @@ public static class CallingConventionAdapters
{
private class NativeConvention : ICallingConventionAdapter
{
public IntPtr GetArrivalFunctionPointer(IntPtr p, ParameterInfo pp, object lifetime)
{
return p;
}
public IntPtr GetArrivalFunctionPointer(IntPtr p, ParameterInfo pp, object lifetime) => p;

public Delegate GetDelegateForFunctionPointer(IntPtr p, Type delegateType)
{
return Marshal.GetDelegateForFunctionPointer(p, delegateType);
}
public Delegate GetDelegateForFunctionPointer(IntPtr p, Type delegateType) => Marshal.GetDelegateForFunctionPointer(p, delegateType);

public IntPtr GetDepartureFunctionPointer(IntPtr p, ParameterInfo pp, object lifetime)
{
return p;
}
public IntPtr GetDepartureFunctionPointer(IntPtr p, ParameterInfo pp, object lifetime) => p;

public IntPtr GetFunctionPointerForDelegate(Delegate d)
{
return Marshal.GetFunctionPointerForDelegate(d);
}
public IntPtr GetFunctionPointerForDelegate(Delegate d) => Marshal.GetFunctionPointerForDelegate(d);
}

/// <summary>
Expand All @@ -124,42 +112,27 @@ public IntPtr GetFunctionPointerForDelegate(Delegate d)
/// <summary>
/// waterbox calling convention, including thunk handling for stack marshalling
/// </summary>
public static ICallingConventionAdapter MakeWaterbox(IEnumerable<Delegate> slots, ICallbackAdjuster waterboxHost)
{
return new WaterboxAdapter(slots, waterboxHost);
}
public static ICallingConventionAdapter MakeWaterbox(IEnumerable<Delegate> slots, ICallbackAdjuster waterboxHost) => new WaterboxAdapter(slots, waterboxHost);
/// <summary>
/// waterbox calling convention, including thunk handling for stack marshalling. Can only do callins, not callouts
/// </summary>
public static ICallingConventionAdapter MakeWaterboxDepartureOnly(ICallbackAdjuster waterboxHost)
{
return new WaterboxAdapter(null, waterboxHost);
}
public static ICallingConventionAdapter MakeWaterboxDepartureOnly(ICallbackAdjuster waterboxHost) => new WaterboxAdapter(null, waterboxHost);

/// <summary>
/// Get a waterbox calling convention adapater, except no wrapping is done for stack marshalling and callback support.
/// This is very unsafe; any attempts by the guest to call syscalls will crash, and stack hygiene will be all wrong.
/// DO NOT USE THIS.
/// </summary>
/// <returns></returns>
public static ICallingConventionAdapter GetWaterboxUnsafeUnwrapped()
{
return WaterboxAdapter.WaterboxWrapper;
}
public static ICallingConventionAdapter GetWaterboxUnsafeUnwrapped() => WaterboxAdapter.WaterboxWrapper;

private class WaterboxAdapter : ICallingConventionAdapter
{
private class ReferenceEqualityComparer : IEqualityComparer<Delegate>
{
public bool Equals(Delegate x, Delegate y)
{
return x == y;
}
public bool Equals(Delegate x, Delegate y) => x == y;

public int GetHashCode(Delegate obj)
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
}
public int GetHashCode(Delegate obj) => System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
}

internal static readonly ICallingConventionAdapter WaterboxWrapper;
Expand Down Expand Up @@ -190,7 +163,7 @@ public IntPtr GetArrivalFunctionPointer(IntPtr p, ParameterInfo pp, object lifet
throw new InvalidOperationException("This calling convention adapter was created for departure only! Pass known delegate slots when constructing to enable arrival");
}
if (lifetime is not Delegate d) throw new ArgumentException(message: "For this calling convention adapter, lifetimes must be delegate so guest slot can be inferred", paramName: nameof(lifetime));
if (!_slots.TryGetValue(d, out var slot))
if (!_slots.TryGetValue(d, out int slot))
{
throw new InvalidOperationException("All callback delegates must be registered at load");
}
Expand All @@ -215,7 +188,7 @@ public IntPtr GetFunctionPointerForDelegate(Delegate d)
{
throw new InvalidOperationException("This calling convention adapter was created for departure only! Pass known delegate slots when constructing to enable arrival");
}
if (!_slots.TryGetValue(d, out var slot))
if (!_slots.TryGetValue(d, out int slot))
{
throw new InvalidOperationException("All callback delegates must be registered at load");
}
Expand Down Expand Up @@ -288,8 +261,8 @@ private static int VerifyDelegateSignature(ParameterInfo pp)
VerifyParameter(pp.ReturnType);
foreach (var ppp in pp.ParameterTypes)
VerifyParameter(ppp);
var ret = pp.ParameterTypes.Count(t => t != typeof(float) && t != typeof(double));
var fargs = pp.ParameterTypes.Count - ret;
int ret = pp.ParameterTypes.Count(t => t != typeof(float) && t != typeof(double));
int fargs = pp.ParameterTypes.Count - ret;
if (ret > 6 || fargs > 4)
throw new InvalidOperationException("Too many parameters to marshal!");
// a function may only use exclusively floating point args or integer/pointer args
Expand Down Expand Up @@ -325,10 +298,7 @@ private void WriteThunk(IntPtr thunkFunctionAddress, IntPtr calleeAddress, int i
_memory.Protect(_memory.Start, _memory.Size, MemoryBlock.Protection.RX);
}

private IntPtr GetThunkAddress(int index)
{
return Z.US(_memory.Start + (ulong)index * BlockSize);
}
private IntPtr GetThunkAddress(int index) => Z.US(_memory.Start + (ulong)index * BlockSize);

private void SetLifetime(int index, object lifetime)
{
Expand All @@ -342,7 +312,7 @@ public IntPtr GetFunctionPointerForDelegate(Delegate d)
// on the same delegate and not leak extra memory, so the result has to be cached
lock (_sync)
{
var index = FindUsedIndex(d);
int index = FindUsedIndex(d);
if (index != -1)
{
return GetThunkAddress(index);
Expand All @@ -359,8 +329,8 @@ public IntPtr GetArrivalFunctionPointer(IntPtr p, ParameterInfo pp, object lifet
{
lock (_sync)
{
var index = FindFreeIndex();
var count = VerifyDelegateSignature(pp);
int index = FindFreeIndex();
int count = VerifyDelegateSignature(pp);
WriteThunk(ThunkDll.GetProcAddrOrThrow($"arrive{count}"), p, index);
SetLifetime(index, lifetime);
return GetThunkAddress(index);
Expand All @@ -371,8 +341,8 @@ public Delegate GetDelegateForFunctionPointer(IntPtr p, Type delegateType)
{
lock (_sync)
{
var index = FindFreeIndex();
var count = VerifyDelegateSignature(new(delegateType));
int index = FindFreeIndex();
int count = VerifyDelegateSignature(new(delegateType));
WriteThunk(ThunkDll.GetProcAddrOrThrow($"depart{count}"), p, index);
var ret = Marshal.GetDelegateForFunctionPointer(GetThunkAddress(index), delegateType);
SetLifetime(index, ret);
Expand All @@ -384,8 +354,8 @@ public IntPtr GetDepartureFunctionPointer(IntPtr p, ParameterInfo pp, object lif
{
lock (_sync)
{
var index = FindFreeIndex();
var count = VerifyDelegateSignature(pp);
int index = FindFreeIndex();
int count = VerifyDelegateSignature(pp);
WriteThunk(ThunkDll.GetProcAddrOrThrow($"depart{count}"), p, index);
SetLifetime(index, lifetime);
return GetThunkAddress(index);
Expand Down
6 changes: 3 additions & 3 deletions src/BizHawk.BizInvoke/MemoryBlock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ public void Protect(ulong start, ulong length, Protection prot)

// Note: asking for prot.none on memory that was not previously committed, commits it

var computedStart = WaterboxUtils.AlignDown(start);
var computedEnd = WaterboxUtils.AlignUp(start + length);
var computedLength = computedEnd - computedStart;
ulong computedStart = WaterboxUtils.AlignDown(start);
ulong computedEnd = WaterboxUtils.AlignUp(start + length);
ulong computedLength = computedEnd - computedStart;

_pal.Protect(computedStart, computedLength, prot);
}
Expand Down
4 changes: 2 additions & 2 deletions src/BizHawk.BizInvoke/MemoryBlockLinuxPal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ internal sealed class MemoryBlockLinuxPal : IMemoryBlockPal
/// </exception>
public MemoryBlockLinuxPal(ulong size)
{
var ptr = (ulong)mmap(IntPtr.Zero, Z.UU(size), MemoryProtection.None, 0x22 /* MAP_PRIVATE | MAP_ANON */, -1, IntPtr.Zero);
ulong ptr = (ulong)mmap(IntPtr.Zero, Z.UU(size), MemoryProtection.None, 0x22 /* MAP_PRIVATE | MAP_ANON */, -1, IntPtr.Zero);
if (ptr == ulong.MaxValue)
throw new InvalidOperationException($"{nameof(mmap)}() failed with error {Marshal.GetLastWin32Error()}");
_size = size;
Expand Down Expand Up @@ -55,7 +55,7 @@ private static MemoryProtection ToMemoryProtection(Protection prot)

public void Protect(ulong start, ulong size, Protection prot)
{
var errorCode = mprotect(
int errorCode = mprotect(
Z.US(start),
Z.UU(size),
ToMemoryProtection(prot)
Expand Down
2 changes: 1 addition & 1 deletion src/BizHawk.BizInvoke/MemoryBlockWindowsPal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ internal sealed unsafe class MemoryBlockWindowsPal : IMemoryBlockPal

public MemoryBlockWindowsPal(ulong size)
{
var ptr = (ulong)Kernel32.VirtualAlloc(
ulong ptr = (ulong)Kernel32.VirtualAlloc(
UIntPtr.Zero, Z.UU(size), Kernel32.AllocationType.MEM_RESERVE | Kernel32.AllocationType.MEM_COMMIT, Kernel32.MemoryProtection.NOACCESS);
if (ptr == 0)
throw new InvalidOperationException($"{nameof(Kernel32.VirtualAlloc)}() returned NULL");
Expand Down
21 changes: 6 additions & 15 deletions src/BizHawk.BizInvoke/MemoryViewStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,22 +57,19 @@ public int Read(Span<byte> buffer)
if (!_readable)
throw new IOException();
EnsureNotDisposed();
var count = (int)Math.Min(buffer.Length, _length - _pos);
int count = (int)Math.Min(buffer.Length, _length - _pos);
new ReadOnlySpan<byte>(CurrentPointer(), count).CopyTo(buffer);
_pos += count;
return count;
}

public override int Read(byte[] buffer, int offset, int count)
{
return Read(new Span<byte>(buffer, offset, count));
}
public override int Read(byte[] buffer, int offset, int count) => Read(new Span<byte>(buffer, offset, count));

public override int ReadByte()
{
if (_pos < _length)
{
var ret = *CurrentPointer();
byte ret = *CurrentPointer();
_pos++;
return ret;
}
Expand All @@ -84,7 +81,7 @@ public override int ReadByte()

public override long Seek(long offset, SeekOrigin origin)
{
var newpos = origin switch
long newpos = origin switch
{
SeekOrigin.Current => _pos + offset,
SeekOrigin.End => _length + offset,
Expand All @@ -94,10 +91,7 @@ public override long Seek(long offset, SeekOrigin origin)
return newpos;
}

public override void SetLength(long value)
{
throw new IOException();
}
public override void SetLength(long value) => throw new IOException();

public void Write(ReadOnlySpan<byte> buffer)
{
Expand All @@ -110,10 +104,7 @@ public void Write(ReadOnlySpan<byte> buffer)
_pos += buffer.Length;
}

public override void Write(byte[] buffer, int offset, int count)
{
Write(new ReadOnlySpan<byte>(buffer, offset, count));
}
public override void Write(byte[] buffer, int offset, int count) => Write(new ReadOnlySpan<byte>(buffer, offset, count));

public override void WriteByte(byte value)
{
Expand Down
Loading

0 comments on commit 46e988b

Please sign in to comment.