diff --git a/ChocolArm64/ABitUtils.cs b/ChocolArm64/ABitUtils.cs index 8109624f0a..dd2b429333 100644 --- a/ChocolArm64/ABitUtils.cs +++ b/ChocolArm64/ABitUtils.cs @@ -6,7 +6,10 @@ namespace ChocolArm64 { int count = 0; - for (int bit = 0; bit < 64; bit++) count += (int)(value >> bit) & 1; + for (int bit = 0; bit < 64; bit++) + { + count += (int)(value >> bit) & 1; + } return count; } @@ -14,7 +17,12 @@ namespace ChocolArm64 public static int HighestBitSet32(int value) { for (int bit = 31; bit >= 0; bit--) - if (((value >> bit) & 1) != 0) return bit; + { + if (((value >> bit) & 1) != 0) + { + return bit; + } + } return -1; } @@ -30,7 +38,10 @@ namespace ChocolArm64 { long output = 0; - for (int bit = 0; bit < 64; bit += size) output |= bits << bit; + for (int bit = 0; bit < 64; bit += size) + { + output |= bits << bit; + } return output; } diff --git a/ChocolArm64/AOpCodeTable.cs b/ChocolArm64/AOpCodeTable.cs index 65317e160c..af5700c791 100644 --- a/ChocolArm64/AOpCodeTable.cs +++ b/ChocolArm64/AOpCodeTable.cs @@ -530,7 +530,10 @@ namespace ChocolArm64 #region "Generate InstA64FastLookup Table (AArch64)" var tmp = new List[_fastLookupSize]; - for (int i = 0; i < _fastLookupSize; i++) tmp[i] = new List(); + for (int i = 0; i < _fastLookupSize; i++) + { + tmp[i] = new List(); + } foreach (var inst in _allInstA64) { @@ -538,10 +541,18 @@ namespace ChocolArm64 int value = ToFastLookupIndex(inst.Value); for (int i = 0; i < _fastLookupSize; i++) - if ((i & mask) == value) tmp[i].Add(inst); + { + if ((i & mask) == value) + { + tmp[i].Add(inst); + } + } } - for (int i = 0; i < _fastLookupSize; i++) _instA64FastLookup[i] = tmp[i].ToArray(); + for (int i = 0; i < _fastLookupSize; i++) + { + _instA64FastLookup[i] = tmp[i].ToArray(); + } #endregion } @@ -635,9 +646,15 @@ namespace ChocolArm64 { int mask = 0; - for (int x = 0; x < xBits; x++) mask |= ((index >> x) & 1) << xPos[x]; + for (int x = 0; x < xBits; x++) + { + mask |= ((index >> x) & 1) << xPos[x]; + } - if (mask != blacklisted) InsertInst(xMask, value | mask, inst, mode); + if (mask != blacklisted) + { + InsertInst(xMask, value | mask, inst, mode); + } } } @@ -650,9 +667,13 @@ namespace ChocolArm64 InstInfo info = new InstInfo(xMask, value, inst); if (mode == AExecutionMode.AArch64) + { _allInstA64.Add(info); + } else + { _allInstA32.Add(info); + } } public static AInst GetInstA32(int opCode) @@ -673,7 +694,12 @@ namespace ChocolArm64 private static AInst GetInstFromList(IEnumerable instList, int opCode) { foreach (var node in instList) - if ((opCode & node.Mask) == node.Value) return node.Inst; + { + if ((opCode & node.Mask) == node.Value) + { + return node.Inst; + } + } return AInst.Undefined; } diff --git a/ChocolArm64/AThread.cs b/ChocolArm64/AThread.cs index 8ac33dab13..6241e02795 100644 --- a/ChocolArm64/AThread.cs +++ b/ChocolArm64/AThread.cs @@ -41,7 +41,10 @@ namespace ChocolArm64 public bool Execute() { - if (Interlocked.Exchange(ref _isExecuting, 1) == 1) return false; + if (Interlocked.Exchange(ref _isExecuting, 1) == 1) + { + return false; + } Work.Start(); diff --git a/ChocolArm64/ATranslatedSub.cs b/ChocolArm64/ATranslatedSub.cs index 41a31cf9eb..f0a5333d7a 100644 --- a/ChocolArm64/ATranslatedSub.cs +++ b/ChocolArm64/ATranslatedSub.cs @@ -36,9 +36,15 @@ namespace ChocolArm64 public ATranslatedSub(DynamicMethod method, List Params) { - if (method == null) throw new ArgumentNullException(nameof(method)); + if (method == null) + { + throw new ArgumentNullException(nameof(method)); + } - if (Params == null) throw new ArgumentNullException(nameof(Params)); + if (Params == null) + { + throw new ArgumentNullException(nameof(Params)); + } Method = method; this.Params = Params.AsReadOnly(); @@ -63,8 +69,13 @@ namespace ChocolArm64 FixedArgTypes[index] = paramType; if (paramType == typeof(AThreadState)) + { StateArgIdx = index; - else if (paramType == typeof(AMemory)) MemoryArgIdx = index; + } + else if (paramType == typeof(AMemory)) + { + MemoryArgIdx = index; + } } } @@ -128,7 +139,10 @@ namespace ChocolArm64 { _type = type; - if (type == ATranslatedSubType.SubTier0) _needsReJit = true; + if (type == ATranslatedSubType.SubTier0) + { + _needsReJit = true; + } } public void MarkForReJit() diff --git a/ChocolArm64/ATranslator.cs b/ChocolArm64/ATranslator.cs index fdbb2689b3..7082fd8640 100644 --- a/ChocolArm64/ATranslator.cs +++ b/ChocolArm64/ATranslator.cs @@ -30,9 +30,13 @@ namespace ChocolArm64 AMemory memory = thread.Memory; if (state.ExecutionMode == AExecutionMode.AArch32) + { ExecuteSubroutineA32(state, memory); + } else + { ExecuteSubroutineA64(state, memory, position); + } } private void ExecuteSubroutineA32(AThreadState state, AMemory memory) @@ -50,11 +54,20 @@ namespace ChocolArm64 { do { - if (EnableCpuTrace) CpuTrace?.Invoke(this, new ACpuTraceEventArgs(position)); + if (EnableCpuTrace) + { + CpuTrace?.Invoke(this, new ACpuTraceEventArgs(position)); + } - if (!_cache.TryGetSubroutine(position, out ATranslatedSub sub)) sub = TranslateTier0(state, memory, position); + if (!_cache.TryGetSubroutine(position, out ATranslatedSub sub)) + { + sub = TranslateTier0(state, memory, position); + } - if (sub.ShouldReJit()) TranslateTier1(state, memory, position); + if (sub.ShouldReJit()) + { + TranslateTier1(state, memory, position); + } position = sub.Execute(state, memory); } @@ -101,7 +114,10 @@ namespace ChocolArm64 AILEmitterCtx context = new AILEmitterCtx(_cache, graph, root, subName); - if (context.CurrBlock.Position != position) context.Emit(OpCodes.Br, context.GetLabel(position)); + if (context.CurrBlock.Position != position) + { + context.Emit(OpCodes.Br, context.GetLabel(position)); + } do { @@ -112,8 +128,15 @@ namespace ChocolArm64 //Mark all methods that calls this method for ReJiting, //since we can now call it directly which is faster. if (_cache.TryGetSubroutine(position, out ATranslatedSub oldSub)) + { foreach (long callerPos in oldSub.GetCallerPositions()) - if (_cache.TryGetSubroutine(position, out ATranslatedSub callerSub)) callerSub.MarkForReJit(); + { + if (_cache.TryGetSubroutine(position, out ATranslatedSub callerSub)) + { + callerSub.MarkForReJit(); + } + } + } ATranslatedSub subroutine = context.GetSubroutine(); @@ -131,7 +154,10 @@ namespace ChocolArm64 { int size = 0; - foreach (ABlock block in graph) size += block.OpCodes.Count; + foreach (ABlock block in graph) + { + size += block.OpCodes.Count; + } return size; } diff --git a/ChocolArm64/ATranslatorCache.cs b/ChocolArm64/ATranslatorCache.cs index 571323db59..8ad550bb8e 100644 --- a/ChocolArm64/ATranslatorCache.cs +++ b/ChocolArm64/ATranslatorCache.cs @@ -92,7 +92,9 @@ namespace ChocolArm64 if (_cache.TryGetValue(position, out CacheBucket bucket)) { if (bucket.CallCount++ > MinCallCountForUpdate) + { if (Monitor.TryEnter(_sortedCache)) + { try { bucket.CallCount = 0; @@ -105,6 +107,8 @@ namespace ChocolArm64 { Monitor.Exit(_sortedCache); } + } + } subroutine = bucket.Subroutine; @@ -121,17 +125,24 @@ namespace ChocolArm64 int timestamp = Environment.TickCount; while (_totalSize > MaxTotalSize) + { lock (_sortedCache) { LinkedListNode node = _sortedCache.First; - if (node == null) break; + if (node == null) + { + break; + } CacheBucket bucket = _cache[node.Value]; int timeDelta = RingDelta(bucket.Timestamp, timestamp); - if ((uint)timeDelta <= (uint)MinTimeDelta) break; + if ((uint)timeDelta <= (uint)MinTimeDelta) + { + break; + } if (_cache.TryRemove(node.Value, out bucket)) { @@ -140,14 +151,19 @@ namespace ChocolArm64 _sortedCache.Remove(bucket.Node); } } + } } private static int RingDelta(int old, int New) { if ((uint)New < (uint)old) + { return New + ~old + 1; + } else + { return New - old; + } } } } \ No newline at end of file diff --git a/ChocolArm64/Decoder/ABlock.cs b/ChocolArm64/Decoder/ABlock.cs index 2f7d13747e..3ea6e5d021 100644 --- a/ChocolArm64/Decoder/ABlock.cs +++ b/ChocolArm64/Decoder/ABlock.cs @@ -24,7 +24,10 @@ namespace ChocolArm64.Decoder public AOpCode GetLastOp() { - if (OpCodes.Count > 0) return OpCodes[OpCodes.Count - 1]; + if (OpCodes.Count > 0) + { + return OpCodes[OpCodes.Count - 1]; + } return null; } diff --git a/ChocolArm64/Decoder/ADecoder.cs b/ChocolArm64/Decoder/ADecoder.cs index e7633302cd..310d142678 100644 --- a/ChocolArm64/Decoder/ADecoder.cs +++ b/ChocolArm64/Decoder/ADecoder.cs @@ -74,14 +74,20 @@ namespace ChocolArm64.Decoder if (lastOp is AOpCodeBImm op) { if (op.Emitter == AInstEmit.Bl) + { hasCachedSub = cache.HasSubroutine(op.Imm); + } else + { current.Branch = Enqueue(op.Imm); + } } if (!(lastOp is AOpCodeBImmAl || lastOp is AOpCodeBReg) || hasCachedSub) + { current.Next = Enqueue(current.EndPosition); + } } //If we have on the graph two blocks with the same end position, @@ -120,8 +126,12 @@ namespace ChocolArm64.Decoder ulong firstPos = ulong.MaxValue; foreach (ABlock block in visited.Values) + { if (firstPos > (ulong)block.Position) + { firstPos = (ulong)block.Position; + } + } ABlock current = visited[(long)firstPos]; @@ -180,20 +190,30 @@ namespace ChocolArm64.Decoder AInst inst; if (state.ExecutionMode == AExecutionMode.AArch64) + { inst = AOpCodeTable.GetInstA64(opCode); + } else + { inst = AOpCodeTable.GetInstA32(opCode); + } AOpCode decodedOpCode = new AOpCode(AInst.Undefined, position, opCode); - if (inst.Type != null) decodedOpCode = MakeOpCode(inst.Type, inst, position, opCode); + if (inst.Type != null) + { + decodedOpCode = MakeOpCode(inst.Type, inst, position, opCode); + } return decodedOpCode; } private static AOpCode MakeOpCode(Type type, AInst inst, long position, int opCode) { - if (type == null) throw new ArgumentNullException(nameof(type)); + if (type == null) + { + throw new ArgumentNullException(nameof(type)); + } OpActivator createInstance = _opActivators.GetOrAdd(type, CacheOpActivator); diff --git a/ChocolArm64/Decoder/ADecoderHelper.cs b/ChocolArm64/Decoder/ADecoderHelper.cs index 506689ffe3..bf041bd314 100644 --- a/ChocolArm64/Decoder/ADecoderHelper.cs +++ b/ChocolArm64/Decoder/ADecoderHelper.cs @@ -25,7 +25,10 @@ namespace ChocolArm64.Decoder int length = ABitUtils.HighestBitSet32((~immS & 0x3f) | (n << 6)); - if (length < 1 || sf == 0 && n != 0) return BitMask.Invalid; + if (length < 1 || sf == 0 && n != 0) + { + return BitMask.Invalid; + } int size = 1 << length; @@ -34,7 +37,10 @@ namespace ChocolArm64.Decoder int s = immS & levels; int r = immR & levels; - if (immediate && s == levels) return BitMask.Invalid; + if (immediate && s == levels) + { + return BitMask.Invalid; + } long wMask = ABitUtils.FillWithOnes(s + 1); long mask = ABitUtils.FillWithOnes(((s - r) & levels) + 1); @@ -72,7 +78,10 @@ namespace ChocolArm64.Decoder long eBit = (imm >> 6) & 1; long sBit = (imm >> 7) & 1; - if (eBit != 0) value |= ((1L << (e - 3)) - 1) << (f + 2); + if (eBit != 0) + { + value |= ((1L << (e - 3)) - 1) << (f + 2); + } value |= (eBit ^ 1) << (f + e - 1); value |= sBit << (f + e); diff --git a/ChocolArm64/Decoder/AOpCodeMemImm.cs b/ChocolArm64/Decoder/AOpCodeMemImm.cs index 8ba287d673..4785a4bd2a 100644 --- a/ChocolArm64/Decoder/AOpCodeMemImm.cs +++ b/ChocolArm64/Decoder/AOpCodeMemImm.cs @@ -33,12 +33,19 @@ namespace ChocolArm64.Decoder //Unscaled and Unprivileged doesn't write back, //but they do use the 9-bits Signed Immediate. - if (Unscaled) WBack = false; + if (Unscaled) + { + WBack = false; + } if (WBack || Unscaled) + { Imm = (opCode << 43) >> 55; + } else + { Imm = ((opCode >> 10) & 0xfff) << Size; + } } } } \ No newline at end of file diff --git a/ChocolArm64/Decoder/AOpCodeSimdImm.cs b/ChocolArm64/Decoder/AOpCodeSimdImm.cs index e55e801bef..26ec4e4523 100644 --- a/ChocolArm64/Decoder/AOpCodeSimdImm.cs +++ b/ChocolArm64/Decoder/AOpCodeSimdImm.cs @@ -89,9 +89,13 @@ namespace ChocolArm64.Decoder private static long ShlOnes(long value, int shift) { if (shift != 0) + { return (value << shift) | (long)(ulong.MaxValue >> (64 - shift)); + } else + { return value; + } } } } \ No newline at end of file diff --git a/ChocolArm64/Decoder/AOpCodeSimdMemImm.cs b/ChocolArm64/Decoder/AOpCodeSimdMemImm.cs index b4739b1ac4..1e39e63b8a 100644 --- a/ChocolArm64/Decoder/AOpCodeSimdMemImm.cs +++ b/ChocolArm64/Decoder/AOpCodeSimdMemImm.cs @@ -8,7 +8,10 @@ namespace ChocolArm64.Decoder { Size |= (opCode >> 21) & 4; - if (!WBack && !Unscaled && Size >= 4) Imm <<= 4; + if (!WBack && !Unscaled && Size >= 4) + { + Imm <<= 4; + } Extend64 = false; } diff --git a/ChocolArm64/Instruction/ACryptoHelper.cs b/ChocolArm64/Instruction/ACryptoHelper.cs index 350f8d7fc1..bc8c7b4f7f 100644 --- a/ChocolArm64/Instruction/ACryptoHelper.cs +++ b/ChocolArm64/Instruction/ACryptoHelper.cs @@ -208,7 +208,10 @@ namespace ChocolArm64.Instruction FromVectorToByteArray(inState, ref op); - for (int idx = 0; idx <= 15; idx++) outState[_isrPerm[idx]] = inState[idx]; + for (int idx = 0; idx <= 15; idx++) + { + outState[_isrPerm[idx]] = inState[idx]; + } FromByteArrayToVector(outState, ref op); @@ -222,7 +225,10 @@ namespace ChocolArm64.Instruction FromVectorToByteArray(inState, ref op); - for (int idx = 0; idx <= 15; idx++) outState[idx] = _invSBox[inState[idx]]; + for (int idx = 0; idx <= 15; idx++) + { + outState[idx] = _invSBox[inState[idx]]; + } FromByteArrayToVector(outState, ref op); @@ -263,7 +269,10 @@ namespace ChocolArm64.Instruction FromVectorToByteArray(inState, ref op); - for (int idx = 0; idx <= 15; idx++) outState[_srPerm[idx]] = inState[idx]; + for (int idx = 0; idx <= 15; idx++) + { + outState[_srPerm[idx]] = inState[idx]; + } FromByteArrayToVector(outState, ref op); @@ -277,7 +286,10 @@ namespace ChocolArm64.Instruction FromVectorToByteArray(inState, ref op); - for (int idx = 0; idx <= 15; idx++) outState[idx] = _sBox[inState[idx]]; + for (int idx = 0; idx <= 15; idx++) + { + outState[idx] = _sBox[inState[idx]]; + } FromByteArrayToVector(outState, ref op); @@ -301,7 +313,10 @@ namespace ChocolArm64.Instruction private static void FromByteArrayToVector(byte[] state, ref Vector128 op) { - if (!Sse2.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse2.IsSupported) + { + throw new PlatformNotSupportedException(); + } op = Sse.StaticCast(Sse2.SetVector128( state[15], state[14], state[13], state[12], diff --git a/ChocolArm64/Instruction/AInstEmitAlu.cs b/ChocolArm64/Instruction/AInstEmitAlu.cs index 5246a86eea..d5e1235451 100644 --- a/ChocolArm64/Instruction/AInstEmitAlu.cs +++ b/ChocolArm64/Instruction/AInstEmitAlu.cs @@ -36,7 +36,10 @@ namespace ChocolArm64.Instruction context.EmitCall(mthdInfo); - if (context.CurrOp.RegisterSize != ARegisterSize.Int32) context.Emit(OpCodes.Conv_U8); + if (context.CurrOp.RegisterSize != ARegisterSize.Int32) + { + context.Emit(OpCodes.Conv_U8); + } context.Emit(OpCodes.Add); @@ -230,7 +233,10 @@ namespace ChocolArm64.Instruction context.Emit(OpCodes.Xor); - if (context.CurrOp.RegisterSize != ARegisterSize.Int32) context.Emit(OpCodes.Conv_U8); + if (context.CurrOp.RegisterSize != ARegisterSize.Int32) + { + context.Emit(OpCodes.Conv_U8); + } context.Emit(OpCodes.Sub); @@ -308,9 +314,13 @@ namespace ChocolArm64.Instruction context.EmitLdintzr(op.Rn); if (op.RegisterSize == ARegisterSize.Int32) + { ASoftFallback.EmitCall(context, name32); + } else + { ASoftFallback.EmitCall(context, name64); + } context.EmitStintzr(op.Rd); } @@ -434,7 +444,10 @@ namespace ChocolArm64.Instruction //we need to cast it to a 32-bits integer. This is fine because we //AND the value and only keep the lower 5 or 6 bits anyway -- it //could very well fit on a byte. - if (context.CurrOp.RegisterSize != ARegisterSize.Int32) context.Emit(OpCodes.Conv_I4); + if (context.CurrOp.RegisterSize != ARegisterSize.Int32) + { + context.Emit(OpCodes.Conv_I4); + } } private static void EmitZeroCvFlags(AILEmitterCtx context) diff --git a/ChocolArm64/Instruction/AInstEmitAluHelper.cs b/ChocolArm64/Instruction/AInstEmitAluHelper.cs index dcb7f3c6d8..ae12363313 100644 --- a/ChocolArm64/Instruction/AInstEmitAluHelper.cs +++ b/ChocolArm64/Instruction/AInstEmitAluHelper.cs @@ -136,9 +136,13 @@ namespace ChocolArm64.Instruction IAOpCodeAlu op = (IAOpCodeAlu)context.CurrOp; if (op.DataOp == ADataOp.Logical || op is IAOpCodeAluRs) + { context.EmitLdintzr(op.Rn); + } else + { context.EmitLdint(op.Rn); + } } public static void EmitDataLoadOper2(AILEmitterCtx context) @@ -184,9 +188,13 @@ namespace ChocolArm64.Instruction IAOpCodeAlu op = (IAOpCodeAlu)context.CurrOp; if (setFlags || op is IAOpCodeAluRs) + { context.EmitStintzr(op.Rd); + } else + { context.EmitStint(op.Rd); + } } public static void EmitSetNzcv(AILEmitterCtx context, int nzcv) diff --git a/ChocolArm64/Instruction/AInstEmitBfm.cs b/ChocolArm64/Instruction/AInstEmitBfm.cs index 8807ab5791..7bf4e0dc11 100644 --- a/ChocolArm64/Instruction/AInstEmitBfm.cs +++ b/ChocolArm64/Instruction/AInstEmitBfm.cs @@ -125,9 +125,13 @@ namespace ChocolArm64.Instruction context.EmitLsl(op.GetBitsCount() - width); if (signed) + { context.EmitAsr(op.Shift - width); + } else + { context.EmitLsr(op.Shift - width); + } context.EmitStintzr(op.Rd); } @@ -151,9 +155,11 @@ namespace ChocolArm64.Instruction context.Emit(ilOp); if (op.RegisterSize != ARegisterSize.Int32) + { context.Emit(signed ? OpCodes.Conv_I8 : OpCodes.Conv_U8); + } context.EmitStintzr(op.Rd); } diff --git a/ChocolArm64/Instruction/AInstEmitHash.cs b/ChocolArm64/Instruction/AInstEmitHash.cs index 769f7d0627..cec221e804 100644 --- a/ChocolArm64/Instruction/AInstEmitHash.cs +++ b/ChocolArm64/Instruction/AInstEmitHash.cs @@ -32,33 +32,49 @@ namespace ChocolArm64.Instruction public static void Crc32Cb(AILEmitterCtx context) { if (AOptimizations.UseSse42) + { EmitSse42Crc32(context, typeof(uint), typeof(byte)); + } else + { EmitCrc32(context, nameof(ASoftFallback.Crc32Cb)); + } } public static void Crc32Ch(AILEmitterCtx context) { if (AOptimizations.UseSse42) + { EmitSse42Crc32(context, typeof(uint), typeof(ushort)); + } else + { EmitCrc32(context, nameof(ASoftFallback.Crc32Ch)); + } } public static void Crc32Cw(AILEmitterCtx context) { if (AOptimizations.UseSse42) + { EmitSse42Crc32(context, typeof(uint), typeof(uint)); + } else + { EmitCrc32(context, nameof(ASoftFallback.Crc32Cw)); + } } public static void Crc32Cx(AILEmitterCtx context) { if (AOptimizations.UseSse42) + { EmitSse42Crc32(context, typeof(ulong), typeof(ulong)); + } else + { EmitCrc32(context, nameof(ASoftFallback.Crc32Cx)); + } } private static void EmitSse42Crc32(AILEmitterCtx context, Type crc, Type data) @@ -79,13 +95,19 @@ namespace ChocolArm64.Instruction context.EmitLdintzr(op.Rn); - if (op.RegisterSize != ARegisterSize.Int32) context.Emit(OpCodes.Conv_U4); + if (op.RegisterSize != ARegisterSize.Int32) + { + context.Emit(OpCodes.Conv_U4); + } context.EmitLdintzr(op.Rm); ASoftFallback.EmitCall(context, name); - if (op.RegisterSize != ARegisterSize.Int32) context.Emit(OpCodes.Conv_U8); + if (op.RegisterSize != ARegisterSize.Int32) + { + context.Emit(OpCodes.Conv_U8); + } context.EmitStintzr(op.Rd); } diff --git a/ChocolArm64/Instruction/AInstEmitMemory.cs b/ChocolArm64/Instruction/AInstEmitMemory.cs index 228188a5fc..fd22bd2de3 100644 --- a/ChocolArm64/Instruction/AInstEmitMemory.cs +++ b/ChocolArm64/Instruction/AInstEmitMemory.cs @@ -43,16 +43,26 @@ namespace ChocolArm64.Instruction EmitLoadAddress(context); if (signed && op.Extend64) + { EmitReadSx64Call(context, op.Size); + } else if (signed) + { EmitReadSx32Call(context, op.Size); + } else + { EmitReadZxCall(context, op.Size); + } if (op is IAOpCodeSimd) + { context.EmitStvec(op.Rt); + } else + { context.EmitStintzr(op.Rt); + } EmitWBackIfNeeded(context); } @@ -61,20 +71,31 @@ namespace ChocolArm64.Instruction { IAOpCodeLit op = (IAOpCodeLit)context.CurrOp; - if (op.Prefetch) return; + if (op.Prefetch) + { + return; + } context.EmitLdarg(ATranslatedSub.MemoryArgIdx); context.EmitLdc_I8(op.Imm); if (op.Signed) + { EmitReadSx64Call(context, op.Size); + } else + { EmitReadZxCall(context, op.Size); + } if (op is IAOpCodeSimd) + { context.EmitStvec(op.Rt); + } else + { context.EmitStint(op.Rt); + } } public static void Ldp(AILEmitterCtx context) @@ -84,14 +105,22 @@ namespace ChocolArm64.Instruction void EmitReadAndStore(int rt) { if (op.Extend64) + { EmitReadSx64Call(context, op.Size); + } else + { EmitReadZxCall(context, op.Size); + } if (op is IAOpCodeSimd) + { context.EmitStvec(rt); + } else + { context.EmitStintzr(rt); + } } context.EmitLdarg(ATranslatedSub.MemoryArgIdx); @@ -120,9 +149,13 @@ namespace ChocolArm64.Instruction EmitLoadAddress(context); if (op is IAOpCodeSimd) + { context.EmitLdvec(op.Rt); + } else + { context.EmitLdintzr(op.Rt); + } EmitWriteCall(context, op.Size); @@ -138,9 +171,13 @@ namespace ChocolArm64.Instruction EmitLoadAddress(context); if (op is IAOpCodeSimd) + { context.EmitLdvec(op.Rt); + } else + { context.EmitLdintzr(op.Rt); + } EmitWriteCall(context, op.Size); @@ -151,9 +188,13 @@ namespace ChocolArm64.Instruction context.Emit(OpCodes.Add); if (op is IAOpCodeSimd) + { context.EmitLdvec(op.Rt2); + } else + { context.EmitLdintzr(op.Rt2); + } EmitWriteCall(context, op.Size); @@ -181,7 +222,10 @@ namespace ChocolArm64.Instruction context.EmitLdintzr(op.Rm); context.EmitCast(op.IntType); - if (op.Shift) context.EmitLsl(op.Size); + if (op.Shift) + { + context.EmitLsl(op.Size); + } context.Emit(OpCodes.Add); break; diff --git a/ChocolArm64/Instruction/AInstEmitMemoryEx.cs b/ChocolArm64/Instruction/AInstEmitMemoryEx.cs index 66b3b51771..68f4a9c621 100644 --- a/ChocolArm64/Instruction/AInstEmitMemoryEx.cs +++ b/ChocolArm64/Instruction/AInstEmitMemoryEx.cs @@ -78,9 +78,15 @@ namespace ChocolArm64.Instruction bool ordered = (accType & AccessType.Ordered) != 0; bool exclusive = (accType & AccessType.Exclusive) != 0; - if (ordered) EmitBarrier(context); + if (ordered) + { + EmitBarrier(context); + } - if (exclusive) EmitMemoryCall(context, nameof(AMemory.SetExclusive), op.Rn); + if (exclusive) + { + EmitMemoryCall(context, nameof(AMemory.SetExclusive), op.Rn); + } context.EmitLdint(op.Rn); context.EmitSttmp(); @@ -153,7 +159,10 @@ namespace ChocolArm64.Instruction bool ordered = (accType & AccessType.Ordered) != 0; bool exclusive = (accType & AccessType.Exclusive) != 0; - if (ordered) EmitBarrier(context); + if (ordered) + { + EmitBarrier(context); + } AILLabel lblEx = new AILLabel(); AILLabel lblEnd = new AILLabel(); @@ -209,7 +218,10 @@ namespace ChocolArm64.Instruction context.EmitCallPropGet(typeof(AThreadState), nameof(AThreadState.Core)); - if (rn != -1) context.EmitLdint(rn); + if (rn != -1) + { + context.EmitLdint(rn); + } context.EmitCall(typeof(AMemory), name); } diff --git a/ChocolArm64/Instruction/AInstEmitMemoryHelper.cs b/ChocolArm64/Instruction/AInstEmitMemoryHelper.cs index 10850174c2..c82e6b86f8 100644 --- a/ChocolArm64/Instruction/AInstEmitMemoryHelper.cs +++ b/ChocolArm64/Instruction/AInstEmitMemoryHelper.cs @@ -36,9 +36,13 @@ namespace ChocolArm64.Instruction string name = null; - if (size < 0 || size > (isSimd ? 4 : 3)) throw new ArgumentOutOfRangeException(nameof(size)); + if (size < 0 || size > (isSimd ? 4 : 3)) + { + throw new ArgumentOutOfRangeException(nameof(size)); + } if (isSimd) + { switch (size) { case 0: name = nameof(AMemory.ReadVector8); break; @@ -47,7 +51,9 @@ namespace ChocolArm64.Instruction case 3: name = nameof(AMemory.ReadVector64); break; case 4: name = nameof(AMemory.ReadVector128); break; } + } else + { switch (size) { case 0: name = nameof(AMemory.ReadByte); break; @@ -55,6 +61,7 @@ namespace ChocolArm64.Instruction case 2: name = nameof(AMemory.ReadUInt32); break; case 3: name = nameof(AMemory.ReadUInt64); break; } + } context.EmitCall(typeof(AMemory), name); @@ -62,17 +69,21 @@ namespace ChocolArm64.Instruction { if (ext == Extension.Sx32 || ext == Extension.Sx64) + { switch (size) { case 0: context.Emit(OpCodes.Conv_I1); break; case 1: context.Emit(OpCodes.Conv_I2); break; case 2: context.Emit(OpCodes.Conv_I4); break; } + } if (size < 3) + { context.Emit(ext == Extension.Sx64 ? OpCodes.Conv_I8 : OpCodes.Conv_U8); + } } } @@ -82,11 +93,18 @@ namespace ChocolArm64.Instruction string name = null; - if (size < 0 || size > (isSimd ? 4 : 3)) throw new ArgumentOutOfRangeException(nameof(size)); + if (size < 0 || size > (isSimd ? 4 : 3)) + { + throw new ArgumentOutOfRangeException(nameof(size)); + } - if (size < 3 && !isSimd) context.Emit(OpCodes.Conv_I4); + if (size < 3 && !isSimd) + { + context.Emit(OpCodes.Conv_I4); + } if (isSimd) + { switch (size) { case 0: name = nameof(AMemory.WriteVector8); break; @@ -95,7 +113,9 @@ namespace ChocolArm64.Instruction case 3: name = nameof(AMemory.WriteVector64); break; case 4: name = nameof(AMemory.WriteVector128); break; } + } else + { switch (size) { case 0: name = nameof(AMemory.WriteByte); break; @@ -103,6 +123,7 @@ namespace ChocolArm64.Instruction case 2: name = nameof(AMemory.WriteUInt32); break; case 3: name = nameof(AMemory.WriteUInt64); break; } + } context.EmitCall(typeof(AMemory), name); } diff --git a/ChocolArm64/Instruction/AInstEmitSimdArithmetic.cs b/ChocolArm64/Instruction/AInstEmitSimdArithmetic.cs index 67c4b7f20c..e32dd55d51 100644 --- a/ChocolArm64/Instruction/AInstEmitSimdArithmetic.cs +++ b/ChocolArm64/Instruction/AInstEmitSimdArithmetic.cs @@ -33,9 +33,13 @@ namespace ChocolArm64.Instruction public static void Add_V(AILEmitterCtx context) { if (AOptimizations.UseSse2) + { EmitSse2Op(context, nameof(Sse2.Add)); + } else + { EmitVectorBinaryOpZx(context, () => context.Emit(OpCodes.Add)); + } } public static void Addhn_V(AILEmitterCtx context) @@ -99,7 +103,10 @@ namespace ChocolArm64.Instruction EmitVectorInsert(context, op.Rd, index, op.Size); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void Clz_V(AILEmitterCtx context) @@ -133,7 +140,10 @@ namespace ChocolArm64.Instruction EmitVectorInsert(context, op.Rd, index, op.Size); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void Cnt_V(AILEmitterCtx context) @@ -147,14 +157,21 @@ namespace ChocolArm64.Instruction EmitVectorExtractZx(context, op.Rn, index, 0); if (Popcnt.IsSupported) + { context.EmitCall(typeof(Popcnt).GetMethod(nameof(Popcnt.PopCount), new Type[] { typeof(ulong) })); + } else + { ASoftFallback.EmitCall(context, nameof(ASoftFallback.CountSetBits8)); + } EmitVectorInsert(context, op.Rd, index, 0); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void Fabd_S(AILEmitterCtx context) @@ -187,24 +204,32 @@ namespace ChocolArm64.Instruction { if (AOptimizations.FastFp && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitScalarSseOrSse2OpF(context, nameof(Sse.AddScalar)); + } else + { EmitScalarBinaryOpF(context, () => { EmitSoftFloatCall(context, nameof(ASoftFloat_32.FpAdd)); }); + } } public static void Fadd_V(AILEmitterCtx context) { if (AOptimizations.FastFp && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitVectorSseOrSse2OpF(context, nameof(Sse.Add)); + } else + { EmitVectorBinaryOpF(context, () => { EmitSoftFloatCall(context, nameof(ASoftFloat_32.FpAdd)); }); + } } public static void Faddp_S(AILEmitterCtx context) @@ -230,24 +255,32 @@ namespace ChocolArm64.Instruction { if (AOptimizations.FastFp && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitScalarSseOrSse2OpF(context, nameof(Sse.DivideScalar)); + } else + { EmitScalarBinaryOpF(context, () => { EmitSoftFloatCall(context, nameof(ASoftFloat_32.FpDiv)); }); + } } public static void Fdiv_V(AILEmitterCtx context) { if (AOptimizations.FastFp && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitVectorSseOrSse2OpF(context, nameof(Sse.Divide)); + } else + { EmitVectorBinaryOpF(context, () => { EmitSoftFloatCall(context, nameof(ASoftFloat_32.FpDiv)); }); + } } public static void Fmadd_S(AILEmitterCtx context) @@ -300,24 +333,32 @@ namespace ChocolArm64.Instruction { if (AOptimizations.FastFp && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitScalarSseOrSse2OpF(context, nameof(Sse.MaxScalar)); + } else + { EmitScalarBinaryOpF(context, () => { EmitSoftFloatCall(context, nameof(ASoftFloat_32.FpMax)); }); + } } public static void Fmax_V(AILEmitterCtx context) { if (AOptimizations.FastFp && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitVectorSseOrSse2OpF(context, nameof(Sse.Max)); + } else + { EmitVectorBinaryOpF(context, () => { EmitSoftFloatCall(context, nameof(ASoftFloat_32.FpMax)); }); + } } public static void Fmaxnm_S(AILEmitterCtx context) @@ -348,24 +389,32 @@ namespace ChocolArm64.Instruction { if (AOptimizations.FastFp && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitScalarSseOrSse2OpF(context, nameof(Sse.MinScalar)); + } else + { EmitScalarBinaryOpF(context, () => { EmitSoftFloatCall(context, nameof(ASoftFloat_32.FpMin)); }); + } } public static void Fmin_V(AILEmitterCtx context) { if (AOptimizations.FastFp && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitVectorSseOrSse2OpF(context, nameof(Sse.Min)); + } else + { EmitVectorBinaryOpF(context, () => { EmitSoftFloatCall(context, nameof(ASoftFloat_32.FpMin)); }); + } } public static void Fminnm_S(AILEmitterCtx context) @@ -496,12 +545,16 @@ namespace ChocolArm64.Instruction { if (AOptimizations.FastFp && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitScalarSseOrSse2OpF(context, nameof(Sse.MultiplyScalar)); + } else + { EmitScalarBinaryOpF(context, () => { EmitSoftFloatCall(context, nameof(ASoftFloat_32.FpMul)); }); + } } public static void Fmul_Se(AILEmitterCtx context) @@ -513,12 +566,16 @@ namespace ChocolArm64.Instruction { if (AOptimizations.FastFp && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitVectorSseOrSse2OpF(context, nameof(Sse.Multiply)); + } else + { EmitVectorBinaryOpF(context, () => { EmitSoftFloatCall(context, nameof(ASoftFloat_32.FpMul)); }); + } } public static void Fmul_Ve(AILEmitterCtx context) @@ -710,7 +767,10 @@ namespace ChocolArm64.Instruction context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else /* if (SizeF == 1) */ { @@ -774,11 +834,17 @@ namespace ChocolArm64.Instruction context.EmitLdarg(ATranslatedSub.StateArgIdx); if (op.Size == 0) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.RoundF)); + } else if (op.Size == 1) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.Round)); + } else + { throw new InvalidOperationException(); + } }); } @@ -793,11 +859,17 @@ namespace ChocolArm64.Instruction context.EmitLdarg(ATranslatedSub.StateArgIdx); if (sizeF == 0) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.RoundF)); + } else if (sizeF == 1) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.Round)); + } else + { throw new InvalidOperationException(); + } }); } @@ -861,11 +933,17 @@ namespace ChocolArm64.Instruction context.EmitLdarg(ATranslatedSub.StateArgIdx); if (op.Size == 0) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.RoundF)); + } else if (op.Size == 1) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.Round)); + } else + { throw new InvalidOperationException(); + } }); } @@ -878,11 +956,17 @@ namespace ChocolArm64.Instruction context.EmitLdarg(ATranslatedSub.StateArgIdx); if (op.Size == 0) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.RoundF)); + } else if (op.Size == 1) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.Round)); + } else + { throw new InvalidOperationException(); + } }); } @@ -992,7 +1076,10 @@ namespace ChocolArm64.Instruction context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else /* if (SizeF == 1) */ { @@ -1028,48 +1115,64 @@ namespace ChocolArm64.Instruction { if (AOptimizations.FastFp && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitScalarSseOrSse2OpF(context, nameof(Sse.SqrtScalar)); + } else + { EmitScalarUnaryOpF(context, () => { EmitSoftFloatCall(context, nameof(ASoftFloat_32.FpSqrt)); }); + } } public static void Fsqrt_V(AILEmitterCtx context) { if (AOptimizations.FastFp && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitVectorSseOrSse2OpF(context, nameof(Sse.Sqrt)); + } else + { EmitVectorUnaryOpF(context, () => { EmitSoftFloatCall(context, nameof(ASoftFloat_32.FpSqrt)); }); + } } public static void Fsub_S(AILEmitterCtx context) { if (AOptimizations.FastFp && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitScalarSseOrSse2OpF(context, nameof(Sse.SubtractScalar)); + } else + { EmitScalarBinaryOpF(context, () => { EmitSoftFloatCall(context, nameof(ASoftFloat_32.FpSub)); }); + } } public static void Fsub_V(AILEmitterCtx context) { if (AOptimizations.FastFp && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitVectorSseOrSse2OpF(context, nameof(Sse.Subtract)); + } else + { EmitVectorBinaryOpF(context, () => { EmitSoftFloatCall(context, nameof(ASoftFloat_32.FpSub)); }); + } } public static void Mla_V(AILEmitterCtx context) @@ -1267,7 +1370,10 @@ namespace ChocolArm64.Instruction EmitStvecWithSignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -1314,7 +1420,10 @@ namespace ChocolArm64.Instruction EmitStvecWithSignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -1582,7 +1691,10 @@ namespace ChocolArm64.Instruction EmitStvecWithSignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -1653,9 +1765,13 @@ namespace ChocolArm64.Instruction public static void Sub_V(AILEmitterCtx context) { if (AOptimizations.UseSse2) + { EmitSse2Op(context, nameof(Sse2.Subtract)); + } else + { EmitVectorBinaryOpZx(context, () => context.Emit(OpCodes.Sub)); + } } public static void Subhn_V(AILEmitterCtx context) @@ -1821,7 +1937,10 @@ namespace ChocolArm64.Instruction EmitStvecWithUnsignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -1854,7 +1973,10 @@ namespace ChocolArm64.Instruction EmitStvecWithUnsignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -2056,7 +2178,10 @@ namespace ChocolArm64.Instruction EmitStvecWithUnsignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -2171,7 +2296,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } private static void EmitDoublingMultiplyHighHalf(AILEmitterCtx context, bool round) @@ -2250,7 +2378,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (part == 0) EmitVectorZeroUpper(context, op.Rd); + if (part == 0) + { + EmitVectorZeroUpper(context, op.Rd); + } } } } diff --git a/ChocolArm64/Instruction/AInstEmitSimdCmp.cs b/ChocolArm64/Instruction/AInstEmitSimdCmp.cs index e1dc65ebaa..b8896a0935 100644 --- a/ChocolArm64/Instruction/AInstEmitSimdCmp.cs +++ b/ChocolArm64/Instruction/AInstEmitSimdCmp.cs @@ -22,11 +22,17 @@ namespace ChocolArm64.Instruction if (context.CurrOp is AOpCodeSimdReg op) { if (op.Size < 3 && AOptimizations.UseSse2) + { EmitSse2Op(context, nameof(Sse2.CompareEqual)); + } else if (op.Size == 3 && AOptimizations.UseSse41) + { EmitSse41Op(context, nameof(Sse41.CompareEqual)); + } else + { EmitCmp(context, OpCodes.Beq_S, false); + } } else { @@ -54,11 +60,17 @@ namespace ChocolArm64.Instruction if (context.CurrOp is AOpCodeSimdReg op) { if (op.Size < 3 && AOptimizations.UseSse2) + { EmitSse2Op(context, nameof(Sse2.CompareGreaterThan)); + } else if (op.Size == 3 && AOptimizations.UseSse42) + { EmitSse42Op(context, nameof(Sse42.CompareGreaterThan)); + } else + { EmitCmp(context, OpCodes.Bgt_S, false); + } } else { @@ -145,54 +157,78 @@ namespace ChocolArm64.Instruction { if (context.CurrOp is AOpCodeSimdReg && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitScalarSseOrSse2OpF(context, nameof(Sse.CompareEqualScalar)); + } else + { EmitScalarFcmp(context, OpCodes.Beq_S); + } } public static void Fcmeq_V(AILEmitterCtx context) { if (context.CurrOp is AOpCodeSimdReg && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitVectorSseOrSse2OpF(context, nameof(Sse.CompareEqual)); + } else + { EmitVectorFcmp(context, OpCodes.Beq_S); + } } public static void Fcmge_S(AILEmitterCtx context) { if (context.CurrOp is AOpCodeSimdReg && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitScalarSseOrSse2OpF(context, nameof(Sse.CompareGreaterThanOrEqualScalar)); + } else + { EmitScalarFcmp(context, OpCodes.Bge_S); + } } public static void Fcmge_V(AILEmitterCtx context) { if (context.CurrOp is AOpCodeSimdReg && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitVectorSseOrSse2OpF(context, nameof(Sse.CompareGreaterThanOrEqual)); + } else + { EmitVectorFcmp(context, OpCodes.Bge_S); + } } public static void Fcmgt_S(AILEmitterCtx context) { if (context.CurrOp is AOpCodeSimdReg && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitScalarSseOrSse2OpF(context, nameof(Sse.CompareGreaterThanScalar)); + } else + { EmitScalarFcmp(context, OpCodes.Bgt_S); + } } public static void Fcmgt_V(AILEmitterCtx context) { if (context.CurrOp is AOpCodeSimdReg && AOptimizations.UseSse && AOptimizations.UseSse2) + { EmitVectorSseOrSse2OpF(context, nameof(Sse.CompareGreaterThan)); + } else + { EmitVectorFcmp(context, OpCodes.Bgt_S); + } } public static void Fcmle_S(AILEmitterCtx context) @@ -247,9 +283,13 @@ namespace ChocolArm64.Instruction if (cmpWithZero) { if (op.Size == 0) + { context.EmitLdc_R4(0f); + } else /* if (Op.Size == 1) */ + { context.EmitLdc_R8(0d); + } } else { @@ -306,11 +346,17 @@ namespace ChocolArm64.Instruction EmitVectorExtractF(context, reg, 0, op.Size); if (op.Size == 0) + { context.EmitCall(typeof(float), nameof(float.IsNaN)); + } else if (op.Size == 1) + { context.EmitCall(typeof(double), nameof(double.IsNaN)); + } else + { throw new InvalidOperationException(); + } } private static void EmitCmp(AILEmitterCtx context, OpCode ilOp, bool scalar) @@ -327,9 +373,13 @@ namespace ChocolArm64.Instruction EmitVectorExtractSx(context, op.Rn, index, op.Size); if (op is AOpCodeSimdReg binOp) + { EmitVectorExtractSx(context, binOp.Rm, index, op.Size); + } else + { context.EmitLdc_I8(0L); + } AILLabel lblTrue = new AILLabel(); AILLabel lblEnd = new AILLabel(); @@ -347,7 +397,10 @@ namespace ChocolArm64.Instruction context.MarkLabel(lblEnd); } - if (op.RegisterSize == ARegisterSize.Simd64 || scalar) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64 || scalar) + { + EmitVectorZeroUpper(context, op.Rd); + } } private static void EmitCmtst(AILEmitterCtx context, bool scalar) @@ -384,7 +437,10 @@ namespace ChocolArm64.Instruction context.MarkLabel(lblEnd); } - if (op.RegisterSize == ARegisterSize.Simd64 || scalar) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64 || scalar) + { + EmitVectorZeroUpper(context, op.Rd); + } } private static void EmitScalarFcmp(AILEmitterCtx context, OpCode ilOp) @@ -401,9 +457,15 @@ namespace ChocolArm64.Instruction int bytes = op.GetBitsCount() >> 3; int elems = bytes >> (sizeF + 2); - for (int index = 0; index < elems; index++) EmitFcmp(context, ilOp, index, false); + for (int index = 0; index < elems; index++) + { + EmitFcmp(context, ilOp, index, false); + } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } private static void EmitFcmp(AILEmitterCtx context, OpCode ilOp, int index, bool scalar) @@ -417,11 +479,17 @@ namespace ChocolArm64.Instruction EmitVectorExtractF(context, op.Rn, index, sizeF); if (op is AOpCodeSimdReg binOp) + { EmitVectorExtractF(context, binOp.Rm, index, sizeF); + } else if (sizeF == 0) + { context.EmitLdc_R4(0f); + } else /* if (SizeF == 1) */ + { context.EmitLdc_R8(0d); + } AILLabel lblTrue = new AILLabel(); AILLabel lblEnd = new AILLabel(); @@ -429,9 +497,13 @@ namespace ChocolArm64.Instruction context.Emit(ilOp, lblTrue); if (scalar) + { EmitVectorZeroAll(context, op.Rd); + } else + { EmitVectorInsert(context, op.Rd, index, sizeF + 2, 0); + } context.Emit(OpCodes.Br_S, lblEnd); diff --git a/ChocolArm64/Instruction/AInstEmitSimdCvt.cs b/ChocolArm64/Instruction/AInstEmitSimdCvt.cs index d83c6657ac..47cfe52e4b 100644 --- a/ChocolArm64/Instruction/AInstEmitSimdCvt.cs +++ b/ChocolArm64/Instruction/AInstEmitSimdCvt.cs @@ -155,7 +155,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (part == 0) EmitVectorZeroUpper(context, op.Rd); + if (part == 0) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void Fcvtns_S(AILEmitterCtx context) @@ -234,7 +237,10 @@ namespace ChocolArm64.Instruction context.EmitLdintzr(op.Rn); - if (context.CurrOp.RegisterSize == ARegisterSize.Int32) context.Emit(OpCodes.Conv_U4); + if (context.CurrOp.RegisterSize == ARegisterSize.Int32) + { + context.Emit(OpCodes.Conv_U4); + } EmitFloatCast(context, op.Size); @@ -263,7 +269,10 @@ namespace ChocolArm64.Instruction context.EmitLdintzr(op.Rn); - if (context.CurrOp.RegisterSize == ARegisterSize.Int32) context.Emit(OpCodes.Conv_U4); + if (context.CurrOp.RegisterSize == ARegisterSize.Int32) + { + context.Emit(OpCodes.Conv_U4); + } context.Emit(OpCodes.Conv_R_Un); @@ -292,7 +301,10 @@ namespace ChocolArm64.Instruction private static int GetFBits(AILEmitterCtx context) { - if (context.CurrOp is AOpCodeSimdShImm op) return GetImmShr(op); + if (context.CurrOp is AOpCodeSimdShImm op) + { + return GetImmShr(op); + } return 0; } @@ -300,11 +312,17 @@ namespace ChocolArm64.Instruction private static void EmitFloatCast(AILEmitterCtx context, int size) { if (size == 0) + { context.Emit(OpCodes.Conv_R4); + } else if (size == 1) + { context.Emit(OpCodes.Conv_R8); + } else + { throw new ArgumentOutOfRangeException(nameof(size)); + } } private static void EmitFcvtn(AILEmitterCtx context, bool signed, bool scalar) @@ -317,7 +335,10 @@ namespace ChocolArm64.Instruction int bytes = op.GetBitsCount() >> 3; int elems = !scalar ? bytes >> sizeI : 1; - if (scalar && sizeF == 0) EmitVectorZeroLowerTmp(context); + if (scalar && sizeF == 0) + { + EmitVectorZeroLowerTmp(context); + } for (int index = 0; index < elems; index++) { @@ -346,7 +367,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64 || scalar) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64 || scalar) + { + EmitVectorZeroUpper(context, op.Rd); + } } private static void EmitFcvt_s_Gp(AILEmitterCtx context, Action emit) @@ -368,11 +392,18 @@ namespace ChocolArm64.Instruction emit(); if (signed) + { EmitScalarFcvts(context, op.Size, 0); + } else + { EmitScalarFcvtu(context, op.Size, 0); + } - if (context.CurrOp.RegisterSize == ARegisterSize.Int32) context.Emit(OpCodes.Conv_U8); + if (context.CurrOp.RegisterSize == ARegisterSize.Int32) + { + context.Emit(OpCodes.Conv_U8); + } context.EmitStintzr(op.Rd); } @@ -394,11 +425,18 @@ namespace ChocolArm64.Instruction EmitVectorExtractF(context, op.Rn, 0, op.Size); if (signed) + { EmitScalarFcvts(context, op.Size, op.FBits); + } else + { EmitScalarFcvtu(context, op.Size, op.FBits); + } - if (context.CurrOp.RegisterSize == ARegisterSize.Int32) context.Emit(OpCodes.Conv_U8); + if (context.CurrOp.RegisterSize == ARegisterSize.Int32) + { + context.Emit(OpCodes.Conv_U8); + } context.EmitStintzr(op.Rd); } @@ -429,7 +467,10 @@ namespace ChocolArm64.Instruction { EmitVectorExtract(context, op.Rn, index, sizeI, signed); - if (!signed) context.Emit(OpCodes.Conv_R_Un); + if (!signed) + { + context.Emit(OpCodes.Conv_R_Un); + } context.Emit(sizeF == 0 ? OpCodes.Conv_R4 @@ -440,7 +481,10 @@ namespace ChocolArm64.Instruction EmitVectorInsertF(context, op.Rd, index, sizeF); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } private static void EmitScalarFcvtzs(AILEmitterCtx context) @@ -467,15 +511,22 @@ namespace ChocolArm64.Instruction EmitF2iFBitsMul(context, sizeF, fBits); if (sizeF == 0) + { AVectorHelper.EmitCall(context, signed ? nameof(AVectorHelper.SatF32ToS32) : nameof(AVectorHelper.SatF32ToU32)); + } else /* if (SizeF == 1) */ + { AVectorHelper.EmitCall(context, signed ? nameof(AVectorHelper.SatF64ToS64) : nameof(AVectorHelper.SatF64ToU64)); + } - if (sizeF == 0) context.Emit(OpCodes.Conv_U8); + if (sizeF == 0) + { + context.Emit(OpCodes.Conv_U8); + } EmitScalarSet(context, op.Rd, sizeI); } @@ -509,63 +560,95 @@ namespace ChocolArm64.Instruction EmitF2iFBitsMul(context, sizeF, fBits); if (sizeF == 0) + { AVectorHelper.EmitCall(context, signed ? nameof(AVectorHelper.SatF32ToS32) : nameof(AVectorHelper.SatF32ToU32)); + } else /* if (SizeF == 1) */ + { AVectorHelper.EmitCall(context, signed ? nameof(AVectorHelper.SatF64ToS64) : nameof(AVectorHelper.SatF64ToU64)); + } - if (sizeF == 0) context.Emit(OpCodes.Conv_U8); + if (sizeF == 0) + { + context.Emit(OpCodes.Conv_U8); + } EmitVectorInsert(context, op.Rd, index, sizeI); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } private static void EmitScalarFcvts(AILEmitterCtx context, int size, int fBits) { - if (size < 0 || size > 1) throw new ArgumentOutOfRangeException(nameof(size)); + if (size < 0 || size > 1) + { + throw new ArgumentOutOfRangeException(nameof(size)); + } EmitF2iFBitsMul(context, size, fBits); if (context.CurrOp.RegisterSize == ARegisterSize.Int32) { if (size == 0) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.SatF32ToS32)); + } else /* if (Size == 1) */ + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.SatF64ToS32)); + } } else { if (size == 0) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.SatF32ToS64)); + } else /* if (Size == 1) */ + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.SatF64ToS64)); + } } } private static void EmitScalarFcvtu(AILEmitterCtx context, int size, int fBits) { - if (size < 0 || size > 1) throw new ArgumentOutOfRangeException(nameof(size)); + if (size < 0 || size > 1) + { + throw new ArgumentOutOfRangeException(nameof(size)); + } EmitF2iFBitsMul(context, size, fBits); if (context.CurrOp.RegisterSize == ARegisterSize.Int32) { if (size == 0) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.SatF32ToU32)); + } else /* if (Size == 1) */ + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.SatF64ToU32)); + } } else { if (size == 0) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.SatF32ToU64)); + } else /* if (Size == 1) */ + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.SatF64ToU64)); + } } } @@ -574,11 +657,17 @@ namespace ChocolArm64.Instruction if (fBits != 0) { if (size == 0) + { context.EmitLdc_R4(MathF.Pow(2f, fBits)); + } else if (size == 1) + { context.EmitLdc_R8(Math.Pow(2d, fBits)); + } else + { throw new ArgumentOutOfRangeException(nameof(size)); + } context.Emit(OpCodes.Mul); } @@ -589,11 +678,17 @@ namespace ChocolArm64.Instruction if (fBits != 0) { if (size == 0) + { context.EmitLdc_R4(1f / MathF.Pow(2f, fBits)); + } else if (size == 1) + { context.EmitLdc_R8(1d / Math.Pow(2d, fBits)); + } else + { throw new ArgumentOutOfRangeException(nameof(size)); + } context.Emit(OpCodes.Mul); } diff --git a/ChocolArm64/Instruction/AInstEmitSimdHelper.cs b/ChocolArm64/Instruction/AInstEmitSimdHelper.cs index b5ffed770f..d874fc6e15 100644 --- a/ChocolArm64/Instruction/AInstEmitSimdHelper.cs +++ b/ChocolArm64/Instruction/AInstEmitSimdHelper.cs @@ -103,7 +103,10 @@ namespace ChocolArm64.Instruction EmitStvecWithSignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void EmitLdvecWithSignedCast(AILEmitterCtx context, int reg, int size) @@ -200,7 +203,10 @@ namespace ChocolArm64.Instruction { context.EmitLdvec(reg); - if (sizeF == 1) AVectorHelper.EmitCall(context, nameof(AVectorHelper.VectorSingleToDouble)); + if (sizeF == 1) + { + AVectorHelper.EmitCall(context, nameof(AVectorHelper.VectorSingleToDouble)); + } } Ldvec(op.Rn); @@ -230,16 +236,23 @@ namespace ChocolArm64.Instruction context.EmitCall(type.GetMethod(name, new Type[] { baseType })); } - if (sizeF == 1) AVectorHelper.EmitCall(context, nameof(AVectorHelper.VectorDoubleToSingle)); + if (sizeF == 1) + { + AVectorHelper.EmitCall(context, nameof(AVectorHelper.VectorDoubleToSingle)); + } context.EmitStvec(op.Rd); if (scalar) { if (sizeF == 0) + { EmitVectorZero32_128(context, op.Rd); + } else /* if (SizeF == 1) */ + { EmitVectorZeroUpper(context, op.Rd); + } } else if (op.RegisterSize == ARegisterSize.Simd64) { @@ -256,9 +269,13 @@ namespace ChocolArm64.Instruction MethodInfo mthdInfo; if (sizeF == 0) + { mthdInfo = typeof(MathF).GetMethod(name, new Type[] { typeof(float) }); + } else /* if (SizeF == 1) */ + { mthdInfo = typeof(Math).GetMethod(name, new Type[] { typeof(double) }); + } context.EmitCall(mthdInfo); } @@ -272,9 +289,13 @@ namespace ChocolArm64.Instruction MethodInfo mthdInfo; if (sizeF == 0) + { mthdInfo = typeof(MathF).GetMethod(name, new Type[] { typeof(float), typeof(float) }); + } else /* if (SizeF == 1) */ + { mthdInfo = typeof(Math).GetMethod(name, new Type[] { typeof(double), typeof(double) }); + } context.EmitCall(mthdInfo); } @@ -288,9 +309,13 @@ namespace ChocolArm64.Instruction MethodInfo mthdInfo; if (sizeF == 0) + { mthdInfo = typeof(MathF).GetMethod(nameof(MathF.Round), new Type[] { typeof(float), typeof(MidpointRounding) }); + } else /* if (SizeF == 1) */ + { mthdInfo = typeof(Math).GetMethod(nameof(Math.Round), new Type[] { typeof(double), typeof(MidpointRounding) }); + } context.EmitLdc_I4((int)roundMode); @@ -306,9 +331,13 @@ namespace ChocolArm64.Instruction MethodInfo mthdInfo; if (sizeF == 0) + { mthdInfo = typeof(ASoftFloat).GetMethod(name, new Type[] { typeof(float) }); + } else /* if (SizeF == 1) */ + { mthdInfo = typeof(ASoftFloat).GetMethod(name, new Type[] { typeof(double) }); + } context.EmitCall(mthdInfo); } @@ -346,7 +375,10 @@ namespace ChocolArm64.Instruction int sizeF = op.Size & 1; - if (ternary) EmitVectorExtractF(context, op.Rd, 0, sizeF); + if (ternary) + { + EmitVectorExtractF(context, op.Rd, 0, sizeF); + } EmitVectorExtractF(context, op.Rn, 0, sizeF); EmitVectorExtractF(context, op.Rm, elem, sizeF); @@ -389,11 +421,20 @@ namespace ChocolArm64.Instruction bool rn = (opers & OperFlags.Rn) != 0; bool rm = (opers & OperFlags.Rm) != 0; - if (rd) EmitVectorExtract(context, op.Rd, 0, op.Size, signed); + if (rd) + { + EmitVectorExtract(context, op.Rd, 0, op.Size, signed); + } - if (rn) EmitVectorExtract(context, op.Rn, 0, op.Size, signed); + if (rn) + { + EmitVectorExtract(context, op.Rn, 0, op.Size, signed); + } - if (rm) EmitVectorExtract(context, ((AOpCodeSimdReg)op).Rm, 0, op.Size, signed); + if (rm) + { + EmitVectorExtract(context, ((AOpCodeSimdReg)op).Rm, 0, op.Size, signed); + } emit(); @@ -425,11 +466,20 @@ namespace ChocolArm64.Instruction bool rn = (opers & OperFlags.Rn) != 0; bool rm = (opers & OperFlags.Rm) != 0; - if (ra) EmitVectorExtractF(context, ((AOpCodeSimdReg)op).Ra, 0, sizeF); + if (ra) + { + EmitVectorExtractF(context, ((AOpCodeSimdReg)op).Ra, 0, sizeF); + } - if (rn) EmitVectorExtractF(context, op.Rn, 0, sizeF); + if (rn) + { + EmitVectorExtractF(context, op.Rn, 0, sizeF); + } - if (rm) EmitVectorExtractF(context, ((AOpCodeSimdReg)op).Rm, 0, sizeF); + if (rm) + { + EmitVectorExtractF(context, ((AOpCodeSimdReg)op).Rm, 0, sizeF); + } emit(); @@ -466,18 +516,30 @@ namespace ChocolArm64.Instruction for (int index = 0; index < elems; index++) { - if (rd) EmitVectorExtractF(context, op.Rd, index, sizeF); + if (rd) + { + EmitVectorExtractF(context, op.Rd, index, sizeF); + } - if (rn) EmitVectorExtractF(context, op.Rn, index, sizeF); + if (rn) + { + EmitVectorExtractF(context, op.Rn, index, sizeF); + } - if (rm) EmitVectorExtractF(context, ((AOpCodeSimdReg)op).Rm, index, sizeF); + if (rm) + { + EmitVectorExtractF(context, ((AOpCodeSimdReg)op).Rm, index, sizeF); + } emit(); EmitVectorInsertF(context, op.Rd, index, sizeF); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void EmitVectorBinaryOpByElemF(AILEmitterCtx context, Action emit) @@ -505,7 +567,10 @@ namespace ChocolArm64.Instruction for (int index = 0; index < elems; index++) { - if (ternary) EmitVectorExtractF(context, op.Rd, index, sizeF); + if (ternary) + { + EmitVectorExtractF(context, op.Rd, index, sizeF); + } EmitVectorExtractF(context, op.Rn, index, sizeF); EmitVectorExtractF(context, op.Rm, elem, sizeF); @@ -518,7 +583,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void EmitVectorUnaryOpSx(AILEmitterCtx context, Action emit) @@ -564,18 +632,30 @@ namespace ChocolArm64.Instruction for (int index = 0; index < elems; index++) { - if (rd) EmitVectorExtract(context, op.Rd, index, op.Size, signed); + if (rd) + { + EmitVectorExtract(context, op.Rd, index, op.Size, signed); + } - if (rn) EmitVectorExtract(context, op.Rn, index, op.Size, signed); + if (rn) + { + EmitVectorExtract(context, op.Rn, index, op.Size, signed); + } - if (rm) EmitVectorExtract(context, ((AOpCodeSimdReg)op).Rm, index, op.Size, signed); + if (rm) + { + EmitVectorExtract(context, ((AOpCodeSimdReg)op).Rm, index, op.Size, signed); + } emit(); EmitVectorInsert(context, op.Rd, index, op.Size); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void EmitVectorBinaryOpByElemSx(AILEmitterCtx context, Action emit) @@ -611,7 +691,10 @@ namespace ChocolArm64.Instruction for (int index = 0; index < elems; index++) { - if (ternary) EmitVectorExtract(context, op.Rd, index, op.Size, signed); + if (ternary) + { + EmitVectorExtract(context, op.Rd, index, op.Size, signed); + } EmitVectorExtract(context, op.Rn, index, op.Size, signed); context.EmitLdtmp(); @@ -624,7 +707,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void EmitVectorImmUnaryOp(AILEmitterCtx context, Action emit) @@ -646,7 +732,10 @@ namespace ChocolArm64.Instruction for (int index = 0; index < elems; index++) { - if (binary) EmitVectorExtractZx(context, op.Rd, index, op.Size); + if (binary) + { + EmitVectorExtractZx(context, op.Rd, index, op.Size); + } context.EmitLdc_I8(op.Imm); @@ -655,7 +744,10 @@ namespace ChocolArm64.Instruction EmitVectorInsert(context, op.Rd, index, op.Size); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void EmitVectorWidenRmBinaryOpSx(AILEmitterCtx context, Action emit) @@ -720,7 +812,10 @@ namespace ChocolArm64.Instruction for (int index = 0; index < elems; index++) { - if (ternary) EmitVectorExtract(context, op.Rd, index, op.Size + 1, signed); + if (ternary) + { + EmitVectorExtract(context, op.Rd, index, op.Size + 1, signed); + } EmitVectorExtract(context, op.Rn, part + index, op.Size, signed); EmitVectorExtract(context, op.Rm, part + index, op.Size, signed); @@ -772,7 +867,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void EmitVectorPairwiseOpF(AILEmitterCtx context, Action emit) @@ -805,7 +903,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } [Flags] @@ -845,7 +946,10 @@ namespace ChocolArm64.Instruction int bytes = op.GetBitsCount() >> 3; int elems = !scalar ? bytes >> op.Size : 1; - if (scalar) EmitVectorZeroLowerTmp(context); + if (scalar) + { + EmitVectorZeroLowerTmp(context); + } for (int index = 0; index < elems; index++) { @@ -854,9 +958,13 @@ namespace ChocolArm64.Instruction emit(); if (op.Size <= 2) + { EmitSatQ(context, op.Size, true, true); + } else /* if (Op.Size == 3) */ + { EmitUnarySignedSatQAbsOrNeg(context); + } EmitVectorInsertTmp(context, index, op.Size); } @@ -864,7 +972,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64 || scalar) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64 || scalar) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void EmitScalarSaturatingBinaryOpSx(AILEmitterCtx context, SaturatingFlags flags) @@ -902,9 +1013,13 @@ namespace ChocolArm64.Instruction int bytes = op.GetBitsCount() >> 3; int elems = !scalar ? bytes >> op.Size : 1; - if (scalar) EmitVectorZeroLowerTmp(context); + if (scalar) + { + EmitVectorZeroLowerTmp(context); + } if (add || sub) + { for (int index = 0; index < elems; index++) { EmitVectorExtract(context, op.Rn, index, op.Size, signed); @@ -919,14 +1034,20 @@ namespace ChocolArm64.Instruction else /* if (Op.Size == 3) */ { if (add) + { EmitBinarySatQAdd(context, signed); + } else /* if (Sub) */ + { EmitBinarySatQSub(context, signed); + } } EmitVectorInsertTmp(context, index, op.Size); } + } else if (accumulate) + { for (int index = 0; index < elems; index++) { EmitVectorExtract(context, op.Rn, index, op.Size, !signed); @@ -945,7 +1066,9 @@ namespace ChocolArm64.Instruction EmitVectorInsertTmp(context, index, op.Size); } + } else + { for (int index = 0; index < elems; index++) { EmitVectorExtract(context, op.Rn, index, op.Size, signed); @@ -957,11 +1080,15 @@ namespace ChocolArm64.Instruction EmitVectorInsertTmp(context, index, op.Size); } + } context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64 || scalar) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64 || scalar) + { + EmitVectorZeroUpper(context, op.Rd); + } } [Flags] @@ -992,7 +1119,10 @@ namespace ChocolArm64.Instruction int part = !scalar && op.RegisterSize == ARegisterSize.Simd128 ? elems : 0; - if (scalar) EmitVectorZeroLowerTmp(context); + if (scalar) + { + EmitVectorZeroLowerTmp(context); + } if (part != 0) { @@ -1012,7 +1142,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (part == 0) EmitVectorZeroUpper(context, op.Rd); + if (part == 0) + { + EmitVectorZeroUpper(context, op.Rd); + } } // TSrc (16bit, 32bit, 64bit; signed, unsigned) > TDst (8bit, 16bit, 32bit; signed, unsigned). @@ -1022,25 +1155,35 @@ namespace ChocolArm64.Instruction bool signedSrc, bool signedDst) { - if (sizeDst > 2) throw new ArgumentOutOfRangeException(nameof(sizeDst)); + if (sizeDst > 2) + { + throw new ArgumentOutOfRangeException(nameof(sizeDst)); + } context.EmitLdc_I4(sizeDst); context.EmitLdarg(ATranslatedSub.StateArgIdx); if (signedSrc) + { ASoftFallback.EmitCall(context, signedDst ? nameof(ASoftFallback.SignedSrcSignedDstSatQ) : nameof(ASoftFallback.SignedSrcUnsignedDstSatQ)); + } else + { ASoftFallback.EmitCall(context, signedDst ? nameof(ASoftFallback.UnsignedSrcSignedDstSatQ) : nameof(ASoftFallback.UnsignedSrcUnsignedDstSatQ)); + } } // TSrc (64bit) == TDst (64bit); signed. public static void EmitUnarySignedSatQAbsOrNeg(AILEmitterCtx context) { - if (((AOpCodeSimd)context.CurrOp).Size < 3) throw new InvalidOperationException(); + if (((AOpCodeSimd)context.CurrOp).Size < 3) + { + throw new InvalidOperationException(); + } context.EmitLdarg(ATranslatedSub.StateArgIdx); @@ -1050,7 +1193,10 @@ namespace ChocolArm64.Instruction // TSrcs (64bit) == TDst (64bit); signed, unsigned. public static void EmitBinarySatQAdd(AILEmitterCtx context, bool signed) { - if (((AOpCodeSimdReg)context.CurrOp).Size < 3) throw new InvalidOperationException(); + if (((AOpCodeSimdReg)context.CurrOp).Size < 3) + { + throw new InvalidOperationException(); + } context.EmitLdarg(ATranslatedSub.StateArgIdx); @@ -1062,7 +1208,10 @@ namespace ChocolArm64.Instruction // TSrcs (64bit) == TDst (64bit); signed, unsigned. public static void EmitBinarySatQSub(AILEmitterCtx context, bool signed) { - if (((AOpCodeSimdReg)context.CurrOp).Size < 3) throw new InvalidOperationException(); + if (((AOpCodeSimdReg)context.CurrOp).Size < 3) + { + throw new InvalidOperationException(); + } context.EmitLdarg(ATranslatedSub.StateArgIdx); @@ -1074,7 +1223,10 @@ namespace ChocolArm64.Instruction // TSrcs (64bit) == TDst (64bit); signed, unsigned. public static void EmitBinarySatQAccumulate(AILEmitterCtx context, bool signed) { - if (((AOpCodeSimd)context.CurrOp).Size < 3) throw new InvalidOperationException(); + if (((AOpCodeSimd)context.CurrOp).Size < 3) + { + throw new InvalidOperationException(); + } context.EmitLdarg(ATranslatedSub.StateArgIdx); @@ -1139,11 +1291,17 @@ namespace ChocolArm64.Instruction context.EmitLdc_I4(index); if (size == 0) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.VectorExtractSingle)); + } else if (size == 1) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.VectorExtractDouble)); + } else + { throw new ArgumentOutOfRangeException(nameof(size)); + } } public static void EmitVectorZeroAll(AILEmitterCtx context, int rd) @@ -1270,11 +1428,17 @@ namespace ChocolArm64.Instruction context.EmitLdc_I4(index); if (size == 0) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.VectorInsertSingle)); + } else if (size == 1) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.VectorInsertDouble)); + } else + { throw new ArgumentOutOfRangeException(nameof(size)); + } context.EmitStvec(reg); } @@ -1287,27 +1451,45 @@ namespace ChocolArm64.Instruction context.EmitLdc_I4(index); if (size == 0) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.VectorInsertSingle)); + } else if (size == 1) + { AVectorHelper.EmitCall(context, nameof(AVectorHelper.VectorInsertDouble)); + } else + { throw new ArgumentOutOfRangeException(nameof(size)); + } context.EmitStvectmp(); } private static void ThrowIfInvalid(int index, int size) { - if ((uint)size > 3u) throw new ArgumentOutOfRangeException(nameof(size)); + if ((uint)size > 3u) + { + throw new ArgumentOutOfRangeException(nameof(size)); + } - if ((uint)index >= 16u >> size) throw new ArgumentOutOfRangeException(nameof(index)); + if ((uint)index >= 16u >> size) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } } private static void ThrowIfInvalidF(int index, int size) { - if ((uint)size > 1u) throw new ArgumentOutOfRangeException(nameof(size)); + if ((uint)size > 1u) + { + throw new ArgumentOutOfRangeException(nameof(size)); + } - if ((uint)index >= 4u >> size) throw new ArgumentOutOfRangeException(nameof(index)); + if ((uint)index >= 4u >> size) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } } } } diff --git a/ChocolArm64/Instruction/AInstEmitSimdLogical.cs b/ChocolArm64/Instruction/AInstEmitSimdLogical.cs index 780cbbf805..4c4b8635fe 100644 --- a/ChocolArm64/Instruction/AInstEmitSimdLogical.cs +++ b/ChocolArm64/Instruction/AInstEmitSimdLogical.cs @@ -14,9 +14,13 @@ namespace ChocolArm64.Instruction public static void And_V(AILEmitterCtx context) { if (AOptimizations.UseSse2) + { EmitSse2Op(context, nameof(Sse2.And)); + } else + { EmitVectorBinaryOpZx(context, () => context.Emit(OpCodes.And)); + } } public static void Bic_V(AILEmitterCtx context) @@ -38,7 +42,10 @@ namespace ChocolArm64.Instruction EmitStvecWithUnsignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -97,7 +104,10 @@ namespace ChocolArm64.Instruction EmitStvecWithUnsignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -113,7 +123,10 @@ namespace ChocolArm64.Instruction EmitVectorExtractZx(context, op.Rm, index, op.Size); - if (notRm) context.Emit(OpCodes.Not); + if (notRm) + { + context.Emit(OpCodes.Not); + } context.Emit(OpCodes.And); @@ -124,7 +137,10 @@ namespace ChocolArm64.Instruction EmitVectorInsert(context, op.Rd, index, op.Size); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } } @@ -155,7 +171,10 @@ namespace ChocolArm64.Instruction EmitStvecWithUnsignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -177,9 +196,13 @@ namespace ChocolArm64.Instruction public static void Eor_V(AILEmitterCtx context) { if (AOptimizations.UseSse2) + { EmitSse2Op(context, nameof(Sse2.Xor)); + } else + { EmitVectorBinaryOpZx(context, () => context.Emit(OpCodes.Xor)); + } } public static void Not_V(AILEmitterCtx context) @@ -199,9 +222,13 @@ namespace ChocolArm64.Instruction public static void Orr_V(AILEmitterCtx context) { if (AOptimizations.UseSse2) + { EmitSse2Op(context, nameof(Sse2.Or)); + } else + { EmitVectorBinaryOpZx(context, () => context.Emit(OpCodes.Or)); + } } public static void Orr_Vi(AILEmitterCtx context) @@ -228,7 +255,10 @@ namespace ChocolArm64.Instruction EmitVectorInsert(context, op.Rd, index, 0); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void Rev16_V(AILEmitterCtx context) @@ -250,7 +280,10 @@ namespace ChocolArm64.Instruction { AOpCodeSimd op = (AOpCodeSimd)context.CurrOp; - if (op.Size >= containerSize) throw new InvalidOperationException(); + if (op.Size >= containerSize) + { + throw new InvalidOperationException(); + } int bytes = op.GetBitsCount() >> 3; int elems = bytes >> op.Size; @@ -269,7 +302,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } } } diff --git a/ChocolArm64/Instruction/AInstEmitSimdMemory.cs b/ChocolArm64/Instruction/AInstEmitSimdMemory.cs index 17b0521631..3ffcf4cea5 100644 --- a/ChocolArm64/Instruction/AInstEmitSimdMemory.cs +++ b/ChocolArm64/Instruction/AInstEmitSimdMemory.cs @@ -38,8 +38,10 @@ namespace ChocolArm64.Instruction int offset = 0; for (int rep = 0; rep < op.Reps; rep++) - for (int elem = 0; elem < op.Elems; elem++) - for (int sElem = 0; sElem < op.SElems; sElem++) + { + for (int elem = 0; elem < op.Elems; elem++) + { + for (int sElem = 0; sElem < op.SElems; sElem++) { int rtt = (op.Rt + rep + sElem) & 0x1f; @@ -55,8 +57,11 @@ namespace ChocolArm64.Instruction EmitVectorInsert(context, rtt, elem, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64 && elem == op.Elems - 1) EmitVectorZeroUpper(context, rtt); - } + if (op.RegisterSize == ARegisterSize.Simd64 && elem == op.Elems - 1) + { + EmitVectorZeroUpper(context, rtt); + } + } else { context.EmitLdarg(ATranslatedSub.MemoryArgIdx); @@ -72,8 +77,13 @@ namespace ChocolArm64.Instruction offset += 1 << op.Size; } + } + } - if (op.WBack) EmitSimdMemWBack(context, offset); + if (op.WBack) + { + EmitSimdMemWBack(context, offset); + } } private static void EmitSimdMemSs(AILEmitterCtx context, bool isLoad) @@ -94,7 +104,10 @@ namespace ChocolArm64.Instruction if (op.Replicate) { //Only loads uses the replicate mode. - if (!isLoad) throw new InvalidOperationException(); + if (!isLoad) + { + throw new InvalidOperationException(); + } int bytes = op.GetBitsCount() >> 3; int elems = bytes >> op.Size; @@ -112,7 +125,10 @@ namespace ChocolArm64.Instruction EmitVectorInsert(context, rt, index, op.Size); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, rt); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, rt); + } offset += 1 << op.Size; } @@ -144,7 +160,10 @@ namespace ChocolArm64.Instruction } } - if (op.WBack) EmitSimdMemWBack(context, offset); + if (op.WBack) + { + EmitSimdMemWBack(context, offset); + } } private static void EmitSimdMemWBack(AILEmitterCtx context, int offset) @@ -154,9 +173,13 @@ namespace ChocolArm64.Instruction context.EmitLdint(op.Rn); if (op.Rm != AThreadState.ZrIndex) + { context.EmitLdint(op.Rm); + } else + { context.EmitLdc_I8(offset); + } context.Emit(OpCodes.Add); diff --git a/ChocolArm64/Instruction/AInstEmitSimdMove.cs b/ChocolArm64/Instruction/AInstEmitSimdMove.cs index d0c9e3c70c..26c29f5f3b 100644 --- a/ChocolArm64/Instruction/AInstEmitSimdMove.cs +++ b/ChocolArm64/Instruction/AInstEmitSimdMove.cs @@ -32,7 +32,10 @@ namespace ChocolArm64.Instruction EmitStvecWithUnsignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -46,7 +49,10 @@ namespace ChocolArm64.Instruction EmitVectorInsert(context, op.Rd, index, op.Size); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } } @@ -73,7 +79,10 @@ namespace ChocolArm64.Instruction EmitVectorInsert(context, op.Rd, index, op.Size); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void Ext_V(AILEmitterCtx context) @@ -91,7 +100,10 @@ namespace ChocolArm64.Instruction { int reg = op.Imm4 + index < bytes ? op.Rn : op.Rm; - if (position == bytes) position = 0; + if (position == bytes) + { + position = 0; + } EmitVectorExtractZx(context, reg, position++, 0); EmitVectorInsertTmp(context, index, 0); @@ -100,7 +112,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void Fcsel_S(AILEmitterCtx context) @@ -200,7 +215,10 @@ namespace ChocolArm64.Instruction EmitVectorInsert(context, op.Rd, index, op.Size + 2); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void Ins_Gp(AILEmitterCtx context) @@ -248,7 +266,10 @@ namespace ChocolArm64.Instruction context.EmitLdvec(op.Rm); - for (int index = 0; index < op.Size; index++) context.EmitLdvec((op.Rn + index) & 0x1f); + for (int index = 0; index < op.Size; index++) + { + context.EmitLdvec((op.Rn + index) & 0x1f); + } switch (op.Size) { @@ -324,7 +345,10 @@ namespace ChocolArm64.Instruction //For XTN, first operand is source, second operand is 0. //For XTN2, first operand is 0, second operand is source. - if (part != 0) EmitZeroVector(); + if (part != 0) + { + EmitZeroVector(); + } EmitLdvecWithSignedCast(context, op.Rn, op.Size + 1); @@ -345,7 +369,10 @@ namespace ChocolArm64.Instruction context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.And), wideTypes)); - if (part == 0) EmitZeroVector(); + if (part == 0) + { + EmitZeroVector(); + } //Pack values with signed saturation, the signed saturation shouldn't //saturate anything since the upper bits were masked off. @@ -386,7 +413,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (part == 0) EmitVectorZeroUpper(context, op.Rd); + if (part == 0) + { + EmitVectorZeroUpper(context, op.Rd); + } } } @@ -431,7 +461,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } private static void EmitVectorUnzip(AILEmitterCtx context, int part) @@ -455,7 +488,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } private static void EmitVectorZip(AILEmitterCtx context, int part) @@ -490,7 +526,10 @@ namespace ChocolArm64.Instruction EmitStvecWithUnsignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64 && part == 0) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64 && part == 0) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -513,7 +552,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } } } diff --git a/ChocolArm64/Instruction/AInstEmitSimdShift.cs b/ChocolArm64/Instruction/AInstEmitSimdShift.cs index c5f006c082..3d61b1b0bf 100644 --- a/ChocolArm64/Instruction/AInstEmitSimdShift.cs +++ b/ChocolArm64/Instruction/AInstEmitSimdShift.cs @@ -45,7 +45,10 @@ namespace ChocolArm64.Instruction EmitStvecWithUnsignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -101,7 +104,10 @@ namespace ChocolArm64.Instruction EmitVectorInsert(context, op.Rd, index, op.Size); } - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } public static void Sqrshrn_S(AILEmitterCtx context) @@ -182,7 +188,10 @@ namespace ChocolArm64.Instruction EmitStvecWithSignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -230,7 +239,10 @@ namespace ChocolArm64.Instruction EmitStvecWithSignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -271,7 +283,10 @@ namespace ChocolArm64.Instruction EmitStvecWithSignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -304,7 +319,10 @@ namespace ChocolArm64.Instruction EmitStvecWithSignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -369,7 +387,10 @@ namespace ChocolArm64.Instruction EmitStvecWithUnsignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -416,7 +437,10 @@ namespace ChocolArm64.Instruction EmitStvecWithUnsignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -456,7 +480,10 @@ namespace ChocolArm64.Instruction EmitStvecWithUnsignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -488,7 +515,10 @@ namespace ChocolArm64.Instruction EmitStvecWithUnsignedCast(context, op.Rd, op.Size); - if (op.RegisterSize == ARegisterSize.Simd64) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64) + { + EmitVectorZeroUpper(context, op.Rd); + } } else { @@ -550,9 +580,13 @@ namespace ChocolArm64.Instruction }; if (signed) + { EmitVectorBinaryOpSx(context, emit); + } else + { EmitVectorBinaryOpZx(context, emit); + } } [Flags] @@ -642,7 +676,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (op.RegisterSize == ARegisterSize.Simd64 || scalar) EmitVectorZeroUpper(context, op.Rd); + if (op.RegisterSize == ARegisterSize.Simd64 || scalar) + { + EmitVectorZeroUpper(context, op.Rd); + } } private static void EmitVectorShrImmNarrowOpZx(AILEmitterCtx context, bool round) @@ -684,7 +721,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (part == 0) EmitVectorZeroUpper(context, op.Rd); + if (part == 0) + { + EmitVectorZeroUpper(context, op.Rd); + } } [Flags] @@ -727,7 +767,10 @@ namespace ChocolArm64.Instruction int part = !scalar && op.RegisterSize == ARegisterSize.Simd128 ? elems : 0; - if (scalar) EmitVectorZeroLowerTmp(context); + if (scalar) + { + EmitVectorZeroLowerTmp(context); + } if (part != 0) { @@ -765,7 +808,10 @@ namespace ChocolArm64.Instruction context.EmitLdvectmp(); context.EmitStvec(op.Rd); - if (part == 0) EmitVectorZeroUpper(context, op.Rd); + if (part == 0) + { + EmitVectorZeroUpper(context, op.Rd); + } } // Dst_64 = (Int(Src_64, Signed) + RoundConst) >> Shift; diff --git a/ChocolArm64/Instruction/AInstEmitSystem.cs b/ChocolArm64/Instruction/AInstEmitSystem.cs index a336c801d9..5085adb20b 100644 --- a/ChocolArm64/Instruction/AInstEmitSystem.cs +++ b/ChocolArm64/Instruction/AInstEmitSystem.cs @@ -42,7 +42,9 @@ namespace ChocolArm64.Instruction if (propInfo.PropertyType != typeof(long) && propInfo.PropertyType != typeof(ulong)) + { context.Emit(OpCodes.Conv_U8); + } context.EmitStintzr(op.Rt); } @@ -69,7 +71,9 @@ namespace ChocolArm64.Instruction if (propInfo.PropertyType != typeof(long) && propInfo.PropertyType != typeof(ulong)) + { context.Emit(OpCodes.Conv_U4); + } context.EmitCallPropSet(typeof(AThreadState), propName); } diff --git a/ChocolArm64/Instruction/ASoftFallback.cs b/ChocolArm64/Instruction/ASoftFallback.cs index aa4e805fdf..b2563ed9a5 100644 --- a/ChocolArm64/Instruction/ASoftFallback.cs +++ b/ChocolArm64/Instruction/ASoftFallback.cs @@ -28,9 +28,13 @@ namespace ChocolArm64.Instruction else /* if (Shift == 64) */ { if (value < 0L) + { return -1L; + } else + { return 0L; + } } } else /* if (RoundConst == 1L << (Shift - 1)) */ @@ -40,9 +44,13 @@ namespace ChocolArm64.Instruction long add = value + roundConst; if ((~value & (value ^ add)) < 0L) + { return (long)((ulong)add >> shift); + } else + { return add >> shift; + } } else /* if (Shift == 64) */ { @@ -56,9 +64,13 @@ namespace ChocolArm64.Instruction if (roundConst == 0L) { if (shift <= 63) + { return value >> shift; + } else /* if (Shift == 64) */ + { return 0UL; + } } else /* if (RoundConst == 1L << (Shift - 1)) */ { @@ -67,16 +79,24 @@ namespace ChocolArm64.Instruction if (add < value && add < (ulong)roundConst) { if (shift <= 63) + { return (add >> shift) | (0x8000000000000000UL >> (shift - 1)); + } else /* if (Shift == 64) */ + { return 1UL; + } } else { if (shift <= 63) + { return add >> shift; + } else /* if (Shift == 64) */ + { return 0UL; + } } } } @@ -192,9 +212,13 @@ namespace ChocolArm64.Instruction state.SetFpsrFlag(FPSR.Qc); if (op1 < 0L) + { return long.MinValue; + } else + { return long.MaxValue; + } } else { @@ -227,9 +251,13 @@ namespace ChocolArm64.Instruction state.SetFpsrFlag(FPSR.Qc); if (op1 < 0L) + { return long.MinValue; + } else + { return long.MaxValue; + } } else { @@ -358,7 +386,12 @@ namespace ChocolArm64.Instruction int highBit = size - 2; for (int bit = highBit; bit >= 0; bit--) - if (((value >> bit) & 0b1) != 0) return (ulong)(highBit - bit); + { + if (((value >> bit) & 0b1) != 0) + { + return (ulong)(highBit - bit); + } + } return (ulong)(size - 1); } @@ -367,7 +400,10 @@ namespace ChocolArm64.Instruction public static ulong CountLeadingZeros(ulong value, int size) // Size is 8, 16, 32 or 64 (SIMD&FP or Base Inst.). { - if (value == 0ul) return (ulong)size; + if (value == 0ul) + { + return (ulong)size; + } int nibbleIdx = size; int preCount, count = 0; @@ -385,7 +421,10 @@ namespace ChocolArm64.Instruction public static ulong CountSetBits8(ulong value) // "Size" is 8 (SIMD&FP Inst.). { - if (value == 0xfful) return 8ul; + if (value == 0xfful) + { + return 8ul; + } value = ((value >> 1) & 0x55ul) + (value & 0x55ul); value = ((value >> 2) & 0x33ul) + (value & 0x33ul); @@ -489,7 +528,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 Decrypt(Vector128 value, Vector128 roundKey) { - if (!Sse.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse.IsSupported) + { + throw new PlatformNotSupportedException(); + } return ACryptoHelper.AesInvSubBytes(ACryptoHelper.AesInvShiftRows(Sse.Xor(value, roundKey))); } @@ -497,7 +539,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 Encrypt(Vector128 value, Vector128 roundKey) { - if (!Sse.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse.IsSupported) + { + throw new PlatformNotSupportedException(); + } return ACryptoHelper.AesSubBytes(ACryptoHelper.AesShiftRows(Sse.Xor(value, roundKey))); } @@ -610,7 +655,10 @@ namespace ChocolArm64.Instruction private static void Rol32_256(ref Vector128 y, ref Vector128 x) { - if (!Sse2.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse2.IsSupported) + { + throw new PlatformNotSupportedException(); + } uint yE3 = (uint)VectorExtractIntZx(y, (byte)3, 2); uint xE3 = (uint)VectorExtractIntZx(x, (byte)3, 2); @@ -726,15 +774,24 @@ namespace ChocolArm64.Instruction { value = ((value & 0xff00ff00ff00ff00) >> 8) | ((value & 0x00ff00ff00ff00ff) << 8); - if (size == RevSize.Rev16) return value; + if (size == RevSize.Rev16) + { + return value; + } value = ((value & 0xffff0000ffff0000) >> 16) | ((value & 0x0000ffff0000ffff) << 16); - if (size == RevSize.Rev32) return value; + if (size == RevSize.Rev32) + { + return value; + } value = ((value & 0xffffffff00000000) >> 32) | ((value & 0x00000000ffffffff) << 32); - if (size == RevSize.Rev64) return value; + if (size == RevSize.Rev64) + { + return value; + } throw new ArgumentException(nameof(size)); } @@ -744,8 +801,15 @@ namespace ChocolArm64.Instruction public static long SMulHi128(long lhs, long rhs) { long result = (long)UMulHi128((ulong)lhs, (ulong)rhs); - if (lhs < 0) result -= rhs; - if (rhs < 0) result -= lhs; + if (lhs < 0) + { + result -= rhs; + } + + if (rhs < 0) + { + result -= lhs; + } return result; } diff --git a/ChocolArm64/Instruction/ASoftFloat.cs b/ChocolArm64/Instruction/ASoftFloat.cs index b206825962..006cf7683d 100644 --- a/ChocolArm64/Instruction/ASoftFloat.cs +++ b/ChocolArm64/Instruction/ASoftFloat.cs @@ -39,12 +39,20 @@ namespace ChocolArm64.Instruction { ulong a = index; if (a < 256) + { a = (a << 1) + 1; + } else + { a = (a | 1) << 1; + } ulong b = 256; - while (a * (b + 1) * (b + 1) < 1ul << 28) b++; + while (a * (b + 1) * (b + 1) < 1ul << 28) + { + b++; + } + b = (b + 1) >> 1; table[index] = (byte)(b & 0xFF); @@ -67,7 +75,10 @@ namespace ChocolArm64.Instruction if (xExp >= 2045) { - if (xExp == 0x7ff && scaled != 0) return BitConverter.Int64BitsToDouble((long)(xBits | 0x0008000000000000)); + if (xExp == 0x7ff && scaled != 0) + { + return BitConverter.Int64BitsToDouble((long)(xBits | 0x0008000000000000)); + } // Infinity, or Out of range -> Zero return BitConverter.Int64BitsToDouble((long)xSign); @@ -75,7 +86,10 @@ namespace ChocolArm64.Instruction if (xExp == 0) { - if (scaled == 0) return BitConverter.Int64BitsToDouble((long)(xSign | 0x7FF0000000000000)); + if (scaled == 0) + { + return BitConverter.Int64BitsToDouble((long)(xSign | 0x7FF0000000000000)); + } // Denormal if ((scaled & (1ul << 51)) == 0) @@ -125,11 +139,17 @@ namespace ChocolArm64.Instruction long xExp = (long)((xBits >> 52) & 0x7FF); ulong scaled = xBits & ((1ul << 52) - 1); - if (xExp == 0x7FF && scaled != 0) return BitConverter.Int64BitsToDouble((long)(xBits | 0x0008000000000000)); + if (xExp == 0x7FF && scaled != 0) + { + return BitConverter.Int64BitsToDouble((long)(xBits | 0x0008000000000000)); + } if (xExp == 0) { - if (scaled == 0) return BitConverter.Int64BitsToDouble((long)(xSign | 0x7FF0000000000000)); + if (scaled == 0) + { + return BitConverter.Int64BitsToDouble((long)(xSign | 0x7FF0000000000000)); + } // Denormal while ((scaled & (1 << 51)) == 0) @@ -140,9 +160,15 @@ namespace ChocolArm64.Instruction scaled <<= 1; } - if (xSign != 0) return BitConverter.Int64BitsToDouble((long)0x7FF8000000000000); + if (xSign != 0) + { + return BitConverter.Int64BitsToDouble((long)0x7FF8000000000000); + } - if (xExp == 0x7ff && scaled == 0) return BitConverter.Int64BitsToDouble((long)xSign); + if (xExp == 0x7ff && scaled == 0) + { + return BitConverter.Int64BitsToDouble((long)xSign); + } if (((ulong)xExp & 1) == 1) { @@ -179,11 +205,18 @@ namespace ChocolArm64.Instruction if (type == FPType.SnaN || type == FPType.QnaN) { if (state.GetFpcrFlag(FPCR.Dn)) + { result = FpDefaultNaN(); + } else + { result = FpConvertNaN(valueBits); + } - if (type == FPType.SnaN) FpProcessException(FPExc.InvalidOp, state); + if (type == FPType.SnaN) + { + FpProcessException(FPExc.InvalidOp, state); + } } else if (type == FPType.Infinity) { @@ -309,12 +342,18 @@ namespace ChocolArm64.Instruction uint biasedExp = (uint)Math.Max(exponent - minimumExp + 1, 0); - if (biasedExp == 0u) mantissa /= Math.Pow(2d, minimumExp - exponent); + if (biasedExp == 0u) + { + mantissa /= Math.Pow(2d, minimumExp - exponent); + } uint intMant = (uint)Math.Floor(mantissa * Math.Pow(2d, f)); double error = mantissa * Math.Pow(2d, f) - (double)intMant; - if (biasedExp == 0u && (error != 0d || state.GetFpcrFlag(FPCR.Ufe))) FpProcessException(FPExc.Underflow, state); + if (biasedExp == 0u && (error != 0d || state.GetFpcrFlag(FPCR.Ufe))) + { + FpProcessException(FPExc.Underflow, state); + } bool overflowToInf; bool roundUp; @@ -347,7 +386,10 @@ namespace ChocolArm64.Instruction { intMant++; - if (intMant == (uint)Math.Pow(2d, f)) biasedExp = 1u; + if (intMant == (uint)Math.Pow(2d, f)) + { + biasedExp = 1u; + } if (intMant == (uint)Math.Pow(2d, f + 1)) { @@ -372,7 +414,10 @@ namespace ChocolArm64.Instruction (int)(((sign ? 1u : 0u) << 31) | ((biasedExp & 0xFFu) << 23) | (intMant & 0x007FFFFFu))); } - if (error != 0d) FpProcessException(FPExc.Inexact, state); + if (error != 0d) + { + FpProcessException(FPExc.Inexact, state); + } return result; } @@ -388,9 +433,13 @@ namespace ChocolArm64.Instruction int enable = (int)exc + 8; if ((state.Fpcr & (1 << enable)) != 0) + { throw new NotImplementedException("floating-point trap handling"); + } else + { state.Fpsr |= 1 << (int)exc; + } } } @@ -409,13 +458,22 @@ namespace ChocolArm64.Instruction if (type == FPType.SnaN || type == FPType.QnaN) { if (altHp) + { resultBits = FpZero(sign); + } else if (state.GetFpcrFlag(FPCR.Dn)) + { resultBits = FpDefaultNaN(); + } else + { resultBits = FpConvertNaN(valueBits); + } - if (type == FPType.SnaN || altHp) FpProcessException(FPExc.InvalidOp, state); + if (type == FPType.SnaN || altHp) + { + FpProcessException(FPExc.InvalidOp, state); + } } else if (type == FPType.Infinity) { @@ -480,7 +538,10 @@ namespace ChocolArm64.Instruction type = FPType.Zero; real = 0d; - if (frac32 != 0u) FpProcessException(FPExc.InputDenorm, state); + if (frac32 != 0u) + { + FpProcessException(FPExc.InputDenorm, state); + } } else { @@ -547,12 +608,18 @@ namespace ChocolArm64.Instruction uint biasedExp = (uint)Math.Max(exponent - minimumExp + 1, 0); - if (biasedExp == 0u) mantissa /= Math.Pow(2d, minimumExp - exponent); + if (biasedExp == 0u) + { + mantissa /= Math.Pow(2d, minimumExp - exponent); + } uint intMant = (uint)Math.Floor(mantissa * Math.Pow(2d, f)); double error = mantissa * Math.Pow(2d, f) - (double)intMant; - if (biasedExp == 0u && (error != 0d || state.GetFpcrFlag(FPCR.Ufe))) FpProcessException(FPExc.Underflow, state); + if (biasedExp == 0u && (error != 0d || state.GetFpcrFlag(FPCR.Ufe))) + { + FpProcessException(FPExc.Underflow, state); + } bool overflowToInf; bool roundUp; @@ -585,7 +652,10 @@ namespace ChocolArm64.Instruction { intMant++; - if (intMant == (uint)Math.Pow(2d, f)) biasedExp = 1u; + if (intMant == (uint)Math.Pow(2d, f)) + { + biasedExp = 1u; + } if (intMant == (uint)Math.Pow(2d, f + 1)) { @@ -627,7 +697,10 @@ namespace ChocolArm64.Instruction } } - if (error != 0d) FpProcessException(FPExc.Inexact, state); + if (error != 0d) + { + FpProcessException(FPExc.Inexact, state); + } return resultBits; } @@ -642,9 +715,13 @@ namespace ChocolArm64.Instruction int enable = (int)exc + 8; if ((state.Fpcr & (1 << enable)) != 0) + { throw new NotImplementedException("floating-point trap handling"); + } else + { state.Fpsr |= 1 << (int)exc; + } } } @@ -715,7 +792,10 @@ namespace ChocolArm64.Instruction { result = FpInfinity(sign1 ^ sign2); - if (!inf1) FpProcessException(FPExc.DivideByZero, state); + if (!inf1) + { + FpProcessException(FPExc.DivideByZero, state); + } } else if (zero1 || inf2) { @@ -744,20 +824,32 @@ namespace ChocolArm64.Instruction if (value1 > value2) { if (type1 == FPType.Infinity) + { result = FpInfinity(sign1); + } else if (type1 == FPType.Zero) + { result = FpZero(sign1 && sign2); + } else + { result = value1; + } } else { if (type2 == FPType.Infinity) + { result = FpInfinity(sign2); + } else if (type2 == FPType.Zero) + { result = FpZero(sign1 && sign2); + } else + { result = value2; + } } } @@ -772,8 +864,13 @@ namespace ChocolArm64.Instruction value2.FpUnpack(out FPType type2, out _, out _); if (type1 == FPType.QnaN && type2 != FPType.QnaN) + { value1 = FpInfinity(true); - else if (type1 != FPType.QnaN && type2 == FPType.QnaN) value2 = FpInfinity(true); + } + else if (type1 != FPType.QnaN && type2 == FPType.QnaN) + { + value2 = FpInfinity(true); + } return FpMax(value1, value2, state); } @@ -792,20 +889,32 @@ namespace ChocolArm64.Instruction if (value1 < value2) { if (type1 == FPType.Infinity) + { result = FpInfinity(sign1); + } else if (type1 == FPType.Zero) + { result = FpZero(sign1 || sign2); + } else + { result = value1; + } } else { if (type2 == FPType.Infinity) + { result = FpInfinity(sign2); + } else if (type2 == FPType.Zero) + { result = FpZero(sign1 || sign2); + } else + { result = value2; + } } } @@ -820,8 +929,13 @@ namespace ChocolArm64.Instruction value2.FpUnpack(out FPType type2, out _, out _); if (type1 == FPType.QnaN && type2 != FPType.QnaN) + { value1 = FpInfinity(false); - else if (type1 != FPType.QnaN && type2 == FPType.QnaN) value2 = FpInfinity(false); + } + else if (type1 != FPType.QnaN && type2 == FPType.QnaN) + { + value2 = FpInfinity(false); + } return FpMin(value1, value2, state); } @@ -946,13 +1060,21 @@ namespace ChocolArm64.Instruction bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; if (inf1 && zero2 || zero1 && inf2) + { result = FpTwo(sign1 ^ sign2); + } else if (inf1 || inf2) + { result = FpInfinity(sign1 ^ sign2); + } else if (zero1 || zero2) + { result = FpZero(sign1 ^ sign2); + } else + { result = value1 * value2; + } } return result; @@ -975,11 +1097,17 @@ namespace ChocolArm64.Instruction bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; if (inf1 && zero2 || zero1 && inf2) + { result = FpTwo(false); + } else if (inf1 || inf2) + { result = FpInfinity(sign1 ^ sign2); + } else + { result = 2f + value1 * value2; + } } return result; @@ -1026,11 +1154,17 @@ namespace ChocolArm64.Instruction bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; if (inf1 && zero2 || zero1 && inf2) + { result = FpOnePointFive(false); + } else if (inf1 || inf2) + { result = FpInfinity(sign1 ^ sign2); + } else + { result = (3f + value1 * value2) / 2f; + } } return result; @@ -1150,9 +1284,13 @@ namespace ChocolArm64.Instruction if ((valueBits & 0x7F800000u) == 0u) { if ((valueBits & 0x007FFFFFu) == 0u) + { type = FPType.Zero; + } else + { type = FPType.Nonzero; + } } else if ((~valueBits & 0x7F800000u) == 0u) { @@ -1188,12 +1326,21 @@ namespace ChocolArm64.Instruction done = true; if (type1 == FPType.SnaN) + { return FpProcessNaN(type1, op1, state); + } else if (type2 == FPType.SnaN) + { return FpProcessNaN(type2, op2, state); + } else if (type1 == FPType.QnaN) + { return FpProcessNaN(type1, op1, state); - else if (type2 == FPType.QnaN) return FpProcessNaN(type2, op2, state); + } + else if (type2 == FPType.QnaN) + { + return FpProcessNaN(type2, op2, state); + } done = false; @@ -1213,16 +1360,29 @@ namespace ChocolArm64.Instruction done = true; if (type1 == FPType.SnaN) + { return FpProcessNaN(type1, op1, state); + } else if (type2 == FPType.SnaN) + { return FpProcessNaN(type2, op2, state); + } else if (type3 == FPType.SnaN) + { return FpProcessNaN(type3, op3, state); + } else if (type1 == FPType.QnaN) + { return FpProcessNaN(type1, op1, state); + } else if (type2 == FPType.QnaN) + { return FpProcessNaN(type2, op2, state); - else if (type3 == FPType.QnaN) return FpProcessNaN(type3, op3, state); + } + else if (type3 == FPType.QnaN) + { + return FpProcessNaN(type3, op3, state); + } done = false; @@ -1238,7 +1398,10 @@ namespace ChocolArm64.Instruction FpProcessException(FPExc.InvalidOp, state); } - if (state.GetFpcrFlag(FPCR.Dn)) return FpDefaultNaN(); + if (state.GetFpcrFlag(FPCR.Dn)) + { + return FpDefaultNaN(); + } return BitConverter.Int32BitsToSingle((int)op); } @@ -1248,9 +1411,13 @@ namespace ChocolArm64.Instruction int enable = (int)exc + 8; if ((state.Fpcr & (1 << enable)) != 0) + { throw new NotImplementedException("floating-point trap handling"); + } else + { state.Fpsr |= 1 << (int)exc; + } } } @@ -1321,7 +1488,10 @@ namespace ChocolArm64.Instruction { result = FpInfinity(sign1 ^ sign2); - if (!inf1) FpProcessException(FPExc.DivideByZero, state); + if (!inf1) + { + FpProcessException(FPExc.DivideByZero, state); + } } else if (zero1 || inf2) { @@ -1350,20 +1520,32 @@ namespace ChocolArm64.Instruction if (value1 > value2) { if (type1 == FPType.Infinity) + { result = FpInfinity(sign1); + } else if (type1 == FPType.Zero) + { result = FpZero(sign1 && sign2); + } else + { result = value1; + } } else { if (type2 == FPType.Infinity) + { result = FpInfinity(sign2); + } else if (type2 == FPType.Zero) + { result = FpZero(sign1 && sign2); + } else + { result = value2; + } } } @@ -1378,8 +1560,13 @@ namespace ChocolArm64.Instruction value2.FpUnpack(out FPType type2, out _, out _); if (type1 == FPType.QnaN && type2 != FPType.QnaN) + { value1 = FpInfinity(true); - else if (type1 != FPType.QnaN && type2 == FPType.QnaN) value2 = FpInfinity(true); + } + else if (type1 != FPType.QnaN && type2 == FPType.QnaN) + { + value2 = FpInfinity(true); + } return FpMax(value1, value2, state); } @@ -1398,20 +1585,32 @@ namespace ChocolArm64.Instruction if (value1 < value2) { if (type1 == FPType.Infinity) + { result = FpInfinity(sign1); + } else if (type1 == FPType.Zero) + { result = FpZero(sign1 || sign2); + } else + { result = value1; + } } else { if (type2 == FPType.Infinity) + { result = FpInfinity(sign2); + } else if (type2 == FPType.Zero) + { result = FpZero(sign1 || sign2); + } else + { result = value2; + } } } @@ -1426,8 +1625,13 @@ namespace ChocolArm64.Instruction value2.FpUnpack(out FPType type2, out _, out _); if (type1 == FPType.QnaN && type2 != FPType.QnaN) + { value1 = FpInfinity(false); - else if (type1 != FPType.QnaN && type2 == FPType.QnaN) value2 = FpInfinity(false); + } + else if (type1 != FPType.QnaN && type2 == FPType.QnaN) + { + value2 = FpInfinity(false); + } return FpMin(value1, value2, state); } @@ -1552,13 +1756,21 @@ namespace ChocolArm64.Instruction bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; if (inf1 && zero2 || zero1 && inf2) + { result = FpTwo(sign1 ^ sign2); + } else if (inf1 || inf2) + { result = FpInfinity(sign1 ^ sign2); + } else if (zero1 || zero2) + { result = FpZero(sign1 ^ sign2); + } else + { result = value1 * value2; + } } return result; @@ -1581,11 +1793,17 @@ namespace ChocolArm64.Instruction bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; if (inf1 && zero2 || zero1 && inf2) + { result = FpTwo(false); + } else if (inf1 || inf2) + { result = FpInfinity(sign1 ^ sign2); + } else + { result = 2d + value1 * value2; + } } return result; @@ -1632,11 +1850,17 @@ namespace ChocolArm64.Instruction bool inf2 = type2 == FPType.Infinity; bool zero2 = type2 == FPType.Zero; if (inf1 && zero2 || zero1 && inf2) + { result = FpOnePointFive(false); + } else if (inf1 || inf2) + { result = FpInfinity(sign1 ^ sign2); + } else + { result = (3d + value1 * value2) / 2d; + } } return result; @@ -1756,9 +1980,13 @@ namespace ChocolArm64.Instruction if ((valueBits & 0x7FF0000000000000ul) == 0ul) { if ((valueBits & 0x000FFFFFFFFFFFFFul) == 0ul) + { type = FPType.Zero; + } else + { type = FPType.Nonzero; + } } else if ((~valueBits & 0x7FF0000000000000ul) == 0ul) { @@ -1794,12 +2022,21 @@ namespace ChocolArm64.Instruction done = true; if (type1 == FPType.SnaN) + { return FpProcessNaN(type1, op1, state); + } else if (type2 == FPType.SnaN) + { return FpProcessNaN(type2, op2, state); + } else if (type1 == FPType.QnaN) + { return FpProcessNaN(type1, op1, state); - else if (type2 == FPType.QnaN) return FpProcessNaN(type2, op2, state); + } + else if (type2 == FPType.QnaN) + { + return FpProcessNaN(type2, op2, state); + } done = false; @@ -1819,16 +2056,29 @@ namespace ChocolArm64.Instruction done = true; if (type1 == FPType.SnaN) + { return FpProcessNaN(type1, op1, state); + } else if (type2 == FPType.SnaN) + { return FpProcessNaN(type2, op2, state); + } else if (type3 == FPType.SnaN) + { return FpProcessNaN(type3, op3, state); + } else if (type1 == FPType.QnaN) + { return FpProcessNaN(type1, op1, state); + } else if (type2 == FPType.QnaN) + { return FpProcessNaN(type2, op2, state); - else if (type3 == FPType.QnaN) return FpProcessNaN(type3, op3, state); + } + else if (type3 == FPType.QnaN) + { + return FpProcessNaN(type3, op3, state); + } done = false; @@ -1844,7 +2094,10 @@ namespace ChocolArm64.Instruction FpProcessException(FPExc.InvalidOp, state); } - if (state.GetFpcrFlag(FPCR.Dn)) return FpDefaultNaN(); + if (state.GetFpcrFlag(FPCR.Dn)) + { + return FpDefaultNaN(); + } return BitConverter.Int64BitsToDouble((long)op); } @@ -1854,9 +2107,13 @@ namespace ChocolArm64.Instruction int enable = (int)exc + 8; if ((state.Fpcr & (1 << enable)) != 0) + { throw new NotImplementedException("floating-point trap handling"); + } else + { state.Fpsr |= 1 << (int)exc; + } } } } diff --git a/ChocolArm64/Instruction/AVectorHelper.cs b/ChocolArm64/Instruction/AVectorHelper.cs index 4e33f93c43..baf1882185 100644 --- a/ChocolArm64/Instruction/AVectorHelper.cs +++ b/ChocolArm64/Instruction/AVectorHelper.cs @@ -13,7 +13,10 @@ namespace ChocolArm64.Instruction static AVectorHelper() { - if (!Sse2.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse2.IsSupported) + { + throw new PlatformNotSupportedException(); + } _zero32_128Mask = Sse.StaticCast(Sse2.SetVector128(0, 0, 0, 0xffffffff)); } @@ -33,7 +36,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SatF32ToS32(float value) { - if (float.IsNaN(value)) return 0; + if (float.IsNaN(value)) + { + return 0; + } return value > int.MaxValue ? int.MaxValue : value < int.MinValue ? int.MinValue : (int)value; @@ -42,7 +48,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long SatF32ToS64(float value) { - if (float.IsNaN(value)) return 0; + if (float.IsNaN(value)) + { + return 0; + } return value > long.MaxValue ? long.MaxValue : value < long.MinValue ? long.MinValue : (long)value; @@ -51,7 +60,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint SatF32ToU32(float value) { - if (float.IsNaN(value)) return 0; + if (float.IsNaN(value)) + { + return 0; + } return value > uint.MaxValue ? uint.MaxValue : value < uint.MinValue ? uint.MinValue : (uint)value; @@ -60,7 +72,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong SatF32ToU64(float value) { - if (float.IsNaN(value)) return 0; + if (float.IsNaN(value)) + { + return 0; + } return value > ulong.MaxValue ? ulong.MaxValue : value < ulong.MinValue ? ulong.MinValue : (ulong)value; @@ -69,7 +84,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SatF64ToS32(double value) { - if (double.IsNaN(value)) return 0; + if (double.IsNaN(value)) + { + return 0; + } return value > int.MaxValue ? int.MaxValue : value < int.MinValue ? int.MinValue : (int)value; @@ -78,7 +96,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long SatF64ToS64(double value) { - if (double.IsNaN(value)) return 0; + if (double.IsNaN(value)) + { + return 0; + } return value > long.MaxValue ? long.MaxValue : value < long.MinValue ? long.MinValue : (long)value; @@ -87,7 +108,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint SatF64ToU32(double value) { - if (double.IsNaN(value)) return 0; + if (double.IsNaN(value)) + { + return 0; + } return value > uint.MaxValue ? uint.MaxValue : value < uint.MinValue ? uint.MinValue : (uint)value; @@ -96,7 +120,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong SatF64ToU64(double value) { - if (double.IsNaN(value)) return 0; + if (double.IsNaN(value)) + { + return 0; + } return value > ulong.MaxValue ? ulong.MaxValue : value < ulong.MinValue ? ulong.MinValue : (ulong)value; @@ -203,14 +230,21 @@ namespace ChocolArm64.Instruction byte[] table = new byte[tb.Length * 16]; for (byte index = 0; index < tb.Length; index++) - for (byte index2 = 0; index2 < 16; index2++) - table[index * 16 + index2] = (byte)VectorExtractIntZx(tb[index], index2, 0); + { + for (byte index2 = 0; index2 < 16; index2++) + { + table[index * 16 + index2] = (byte)VectorExtractIntZx(tb[index], index2, 0); + } + } for (byte index = 0; index < bytes; index++) { byte tblIdx = (byte)VectorExtractIntZx(vector, index, 0); - if (tblIdx < table.Length) res = VectorInsertInt(table[tblIdx], res, index, 0); + if (tblIdx < table.Length) + { + res = VectorInsertInt(table[tblIdx], res, index, 0); + } } return res; @@ -220,8 +254,13 @@ namespace ChocolArm64.Instruction public static double VectorExtractDouble(Vector128 vector, byte index) { if (Sse41.IsSupported) + { return BitConverter.Int64BitsToDouble(Sse41.Extract(Sse.StaticCast(vector), index)); - else if (Sse2.IsSupported) return BitConverter.Int64BitsToDouble((long)VectorExtractIntZx(vector, index, 3)); + } + else if (Sse2.IsSupported) + { + return BitConverter.Int64BitsToDouble((long)VectorExtractIntZx(vector, index, 3)); + } throw new PlatformNotSupportedException(); } @@ -232,28 +271,48 @@ namespace ChocolArm64.Instruction if (Sse41.IsSupported) { if (size == 0) + { return (sbyte)Sse41.Extract(Sse.StaticCast(vector), index); + } else if (size == 1) + { return (short)Sse2.Extract(Sse.StaticCast(vector), index); + } else if (size == 2) + { return Sse41.Extract(Sse.StaticCast(vector), index); + } else if (size == 3) + { return Sse41.Extract(Sse.StaticCast(vector), index); + } else + { throw new ArgumentOutOfRangeException(nameof(size)); + } } else if (Sse2.IsSupported) { if (size == 0) + { return (sbyte)VectorExtractIntZx(vector, index, size); + } else if (size == 1) + { return (short)VectorExtractIntZx(vector, index, size); + } else if (size == 2) + { return (int)VectorExtractIntZx(vector, index, size); + } else if (size == 3) + { return (long)VectorExtractIntZx(vector, index, size); + } else + { throw new ArgumentOutOfRangeException(nameof(size)); + } } throw new PlatformNotSupportedException(); @@ -265,15 +324,25 @@ namespace ChocolArm64.Instruction if (Sse41.IsSupported) { if (size == 0) + { return Sse41.Extract(Sse.StaticCast(vector), index); + } else if (size == 1) + { return Sse2.Extract(Sse.StaticCast(vector), index); + } else if (size == 2) + { return Sse41.Extract(Sse.StaticCast(vector), index); + } else if (size == 3) + { return Sse41.Extract(Sse.StaticCast(vector), index); + } else + { throw new ArgumentOutOfRangeException(nameof(size)); + } } else if (Sse2.IsSupported) { @@ -295,7 +364,10 @@ namespace ChocolArm64.Instruction { ushort value1 = Sse2.Extract(Sse.StaticCast(vector), (byte)(shortIdx + 1)); - if (size == 2) return (uint)(value | (value1 << 16)); + if (size == 2) + { + return (uint)(value | (value1 << 16)); + } ushort value2 = Sse2.Extract(Sse.StaticCast(vector), (byte)(shortIdx + 2)); ushort value3 = Sse2.Extract(Sse.StaticCast(vector), (byte)(shortIdx + 3)); @@ -346,15 +418,25 @@ namespace ChocolArm64.Instruction if (Sse41.IsSupported) { if (size == 0) + { return Sse.StaticCast(Sse41.Insert(Sse.StaticCast(vector), (byte)value, index)); + } else if (size == 1) + { return Sse.StaticCast(Sse2.Insert(Sse.StaticCast(vector), (ushort)value, index)); + } else if (size == 2) + { return Sse.StaticCast(Sse41.Insert(Sse.StaticCast(vector), (uint)value, index)); + } else if (size == 3) + { return Sse.StaticCast(Sse41.Insert(Sse.StaticCast(vector), value, index)); + } else + { throw new ArgumentOutOfRangeException(nameof(size)); + } } else if (Sse2.IsSupported) { @@ -411,15 +493,25 @@ namespace ChocolArm64.Instruction //produce a single INSERTPS instruction instead of the //jump table fallback. if (index == 0) + { return Sse41.Insert(vector, value, 0x00); + } else if (index == 1) + { return Sse41.Insert(vector, value, 0x10); + } else if (index == 2) + { return Sse41.Insert(vector, value, 0x20); + } else if (index == 3) + { return Sse41.Insert(vector, value, 0x30); + } else + { throw new ArgumentOutOfRangeException(nameof(index)); + } } else if (Sse2.IsSupported) { @@ -449,7 +541,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorSByteZero() { - if (Sse2.IsSupported) return Sse2.SetZeroVector128(); + if (Sse2.IsSupported) + { + return Sse2.SetZeroVector128(); + } throw new PlatformNotSupportedException(); } @@ -457,7 +552,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorInt16Zero() { - if (Sse2.IsSupported) return Sse2.SetZeroVector128(); + if (Sse2.IsSupported) + { + return Sse2.SetZeroVector128(); + } throw new PlatformNotSupportedException(); } @@ -465,7 +563,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorInt32Zero() { - if (Sse2.IsSupported) return Sse2.SetZeroVector128(); + if (Sse2.IsSupported) + { + return Sse2.SetZeroVector128(); + } throw new PlatformNotSupportedException(); } @@ -473,7 +574,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorInt64Zero() { - if (Sse2.IsSupported) return Sse2.SetZeroVector128(); + if (Sse2.IsSupported) + { + return Sse2.SetZeroVector128(); + } throw new PlatformNotSupportedException(); } @@ -481,7 +585,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorSingleZero() { - if (Sse.IsSupported) return Sse.SetZeroVector128(); + if (Sse.IsSupported) + { + return Sse.SetZeroVector128(); + } throw new PlatformNotSupportedException(); } @@ -489,7 +596,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorDoubleZero() { - if (Sse2.IsSupported) return Sse2.SetZeroVector128(); + if (Sse2.IsSupported) + { + return Sse2.SetZeroVector128(); + } throw new PlatformNotSupportedException(); } @@ -497,7 +607,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorZero32_128(Vector128 vector) { - if (Sse.IsSupported) return Sse.And(vector, _zero32_128Mask); + if (Sse.IsSupported) + { + return Sse.And(vector, _zero32_128Mask); + } throw new PlatformNotSupportedException(); } @@ -505,7 +618,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorSingleToSByte(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -513,7 +629,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorSingleToInt16(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -521,7 +640,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorSingleToInt32(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -529,7 +651,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorSingleToInt64(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -537,7 +662,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorSingleToByte(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -545,7 +673,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorSingleToUInt16(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -553,7 +684,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorSingleToUInt32(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -561,7 +695,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorSingleToUInt64(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -569,7 +706,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorSingleToDouble(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -577,7 +717,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorSByteToSingle(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -585,7 +728,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorInt16ToSingle(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -593,7 +739,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorInt32ToSingle(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -601,7 +750,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorInt64ToSingle(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -609,7 +761,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorByteToSingle(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -617,7 +772,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorUInt16ToSingle(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -625,7 +783,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorUInt32ToSingle(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -633,7 +794,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorUInt64ToSingle(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } @@ -641,7 +805,10 @@ namespace ChocolArm64.Instruction [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 VectorDoubleToSingle(Vector128 vector) { - if (Sse.IsSupported) return Sse.StaticCast(vector); + if (Sse.IsSupported) + { + return Sse.StaticCast(vector); + } throw new PlatformNotSupportedException(); } diff --git a/ChocolArm64/Instruction32/A32InstInterpretFlow.cs b/ChocolArm64/Instruction32/A32InstInterpretFlow.cs index d73128dd11..cf46b38525 100644 --- a/ChocolArm64/Instruction32/A32InstInterpretFlow.cs +++ b/ChocolArm64/Instruction32/A32InstInterpretFlow.cs @@ -13,7 +13,10 @@ namespace ChocolArm64.Instruction32 { A32OpCodeBImmAl op = (A32OpCodeBImmAl)opCode; - if (IsConditionTrue(state, op.Cond)) BranchWritePc(state, GetPc(state) + (uint)op.Imm); + if (IsConditionTrue(state, op.Cond)) + { + BranchWritePc(state, GetPc(state) + (uint)op.Imm); + } } public static void Bl(AThreadState state, AMemory memory, AOpCode opCode) @@ -35,13 +38,23 @@ namespace ChocolArm64.Instruction32 uint pc = GetPc(state); if (state.Thumb) + { state.R14 = pc | 1; + } else + { state.R14 = pc - 4U; + } - if (x) state.Thumb = !state.Thumb; + if (x) + { + state.Thumb = !state.Thumb; + } - if (!state.Thumb) pc &= ~3U; + if (!state.Thumb) + { + pc &= ~3U; + } BranchWritePc(state, pc + (uint)op.Imm); } diff --git a/ChocolArm64/Instruction32/A32InstInterpretHelper.cs b/ChocolArm64/Instruction32/A32InstInterpretHelper.cs index 4be8a93366..16919b3e43 100644 --- a/ChocolArm64/Instruction32/A32InstInterpretHelper.cs +++ b/ChocolArm64/Instruction32/A32InstInterpretHelper.cs @@ -31,7 +31,10 @@ namespace ChocolArm64.Instruction32 public static unsafe uint GetReg(AThreadState state, int reg) { - if ((uint)reg > 15) throw new ArgumentOutOfRangeException(nameof(reg)); + if ((uint)reg > 15) + { + throw new ArgumentOutOfRangeException(nameof(reg)); + } fixed (uint* ptr = &state.R0) { @@ -41,7 +44,10 @@ namespace ChocolArm64.Instruction32 public static unsafe void SetReg(AThreadState state, int reg, uint value) { - if ((uint)reg > 15) throw new ArgumentOutOfRangeException(nameof(reg)); + if ((uint)reg > 15) + { + throw new ArgumentOutOfRangeException(nameof(reg)); + } fixed (uint* ptr = &state.R0) { diff --git a/ChocolArm64/Memory/AMemory.cs b/ChocolArm64/Memory/AMemory.cs index 48e1fcf6ca..663798b172 100644 --- a/ChocolArm64/Memory/AMemory.cs +++ b/ChocolArm64/Memory/AMemory.cs @@ -66,7 +66,10 @@ namespace ChocolArm64.Memory _pageTable = (byte***)Marshal.AllocHGlobal(PtLvl0Size * IntPtr.Size); - for (int l0 = 0; l0 < PtLvl0Size; l0++) _pageTable[l0] = null; + for (int l0 = 0; l0 < PtLvl0Size; l0++) + { + _pageTable[l0] = null; + } } public void RemoveMonitor(int core) @@ -86,7 +89,12 @@ namespace ChocolArm64.Memory lock (_monitors) { foreach (ArmMonitor mon in _monitors.Values) - if (mon.Position == position && mon.ExState) mon.ExState = false; + { + if (mon.Position == position && mon.ExState) + { + mon.ExState = false; + } + } if (!_monitors.TryGetValue(core, out ArmMonitor threadMon)) { @@ -108,18 +116,27 @@ namespace ChocolArm64.Memory Monitor.Enter(_monitors); - if (!_monitors.TryGetValue(core, out ArmMonitor threadMon)) return false; + if (!_monitors.TryGetValue(core, out ArmMonitor threadMon)) + { + return false; + } bool exState = threadMon.HasExclusiveAccess(position); - if (!exState) Monitor.Exit(_monitors); + if (!exState) + { + Monitor.Exit(_monitors); + } return exState; } public void ClearExclusiveForStore(int core) { - if (_monitors.TryGetValue(core, out ArmMonitor threadMon)) threadMon.ExState = false; + if (_monitors.TryGetValue(core, out ArmMonitor threadMon)) + { + threadMon.ExState = false; + } Monitor.Exit(_monitors); } @@ -128,7 +145,10 @@ namespace ChocolArm64.Memory { lock (_monitors) { - if (_monitors.TryGetValue(core, out ArmMonitor threadMon)) threadMon.ExState = false; + if (_monitors.TryGetValue(core, out ArmMonitor threadMon)) + { + threadMon.ExState = false; + } } } @@ -139,7 +159,12 @@ namespace ChocolArm64.Memory lock (_monitors) { foreach (ArmMonitor mon in _monitors.Values) - if (mon.Position == maskedPosition && mon.ExState) mon.ExState = false; + { + if (mon.Position == maskedPosition && mon.ExState) + { + mon.ExState = false; + } + } WriteInt32(position, value); } @@ -188,50 +213,73 @@ namespace ChocolArm64.Memory public Vector128 ReadVector8(long position) { if (Sse2.IsSupported) + { return Sse.StaticCast(Sse2.SetVector128(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ReadByte(position))); + } else + { throw new PlatformNotSupportedException(); + } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector128 ReadVector16(long position) { if (Sse2.IsSupported) + { return Sse.StaticCast(Sse2.Insert(Sse2.SetZeroVector128(), ReadUInt16(position), 0)); + } else + { throw new PlatformNotSupportedException(); + } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector128 ReadVector32(long position) { if (Sse.IsSupported) + { return Sse.LoadScalarVector128((float*)Translate(position)); + } else + { throw new PlatformNotSupportedException(); + } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector128 ReadVector64(long position) { if (Sse2.IsSupported) + { return Sse.StaticCast(Sse2.LoadScalarVector128((double*)Translate(position))); + } else + { throw new PlatformNotSupportedException(); + } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector128 ReadVector128(long position) { if (Sse.IsSupported) + { return Sse.LoadVector128((float*)Translate(position)); + } else + { throw new PlatformNotSupportedException(); + } } public byte[] ReadBytes(long position, long size) { - if ((uint)size > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(size)); + if ((uint)size > int.MaxValue) + { + throw new ArgumentOutOfRangeException(nameof(size)); + } EnsureRangeIsValid(position, size); @@ -294,47 +342,69 @@ namespace ChocolArm64.Memory public void WriteVector8(long position, Vector128 value) { if (Sse41.IsSupported) + { WriteByte(position, Sse41.Extract(Sse.StaticCast(value), 0)); + } else if (Sse2.IsSupported) + { WriteByte(position, (byte)Sse2.Extract(Sse.StaticCast(value), 0)); + } else + { throw new PlatformNotSupportedException(); + } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteVector16(long position, Vector128 value) { if (Sse2.IsSupported) + { WriteUInt16(position, Sse2.Extract(Sse.StaticCast(value), 0)); + } else + { throw new PlatformNotSupportedException(); + } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteVector32(long position, Vector128 value) { if (Sse.IsSupported) + { Sse.StoreScalar((float*)TranslateWrite(position), value); + } else + { throw new PlatformNotSupportedException(); + } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteVector64(long position, Vector128 value) { if (Sse2.IsSupported) + { Sse2.StoreScalar((double*)TranslateWrite(position), Sse.StaticCast(value)); + } else + { throw new PlatformNotSupportedException(); + } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteVector128(long position, Vector128 value) { if (Sse.IsSupported) + { Sse.Store((float*)TranslateWrite(position), value); + } else + { throw new PlatformNotSupportedException(); + } } public void WriteBytes(long position, byte[] data) @@ -379,12 +449,18 @@ namespace ChocolArm64.Memory public bool IsMapped(long position) { - if (!IsValidPosition(position)) return false; + if (!IsValidPosition(position)) + { + return false; + } long l0 = (position >> PtLvl0Bit) & PtLvl0Mask; long l1 = (position >> PtLvl1Bit) & PtLvl1Mask; - if (_pageTable[l0] == null) return false; + if (_pageTable[l0] == null) + { + return false; + } return _pageTable[l0][l1] != null || _observedPages.ContainsKey(position >> PtPageBits); } @@ -405,15 +481,24 @@ namespace ChocolArm64.Memory byte** lvl1 = _pageTable[l0]; - if (position >> (PtLvl0Bit + PtLvl0Bits) != 0) goto Unmapped; + if (position >> (PtLvl0Bit + PtLvl0Bits) != 0) + { + goto Unmapped; + } - if (lvl1 == null) goto Unmapped; + if (lvl1 == null) + { + goto Unmapped; + } position &= PageMask; byte* ptr = lvl1[l1]; - if (ptr == null) goto Unmapped; + if (ptr == null) + { + goto Unmapped; + } return ptr + position; @@ -425,7 +510,10 @@ Unmapped: { long key = position >> PtPageBits; - if (_observedPages.TryGetValue(key, out IntPtr ptr)) return (byte*)ptr + (position & PageMask); + if (_observedPages.TryGetValue(key, out IntPtr ptr)) + { + return (byte*)ptr + (position & PageMask); + } InvalidAccess?.Invoke(this, new AInvalidAccessEventArgs(position)); @@ -441,15 +529,24 @@ Unmapped: byte** lvl1 = _pageTable[l0]; - if (position >> (PtLvl0Bit + PtLvl0Bits) != 0) goto Unmapped; + if (position >> (PtLvl0Bit + PtLvl0Bits) != 0) + { + goto Unmapped; + } - if (lvl1 == null) goto Unmapped; + if (lvl1 == null) + { + goto Unmapped; + } position &= PageMask; byte* ptr = lvl1[l1]; - if (ptr == null) goto Unmapped; + if (ptr == null) + { + goto Unmapped; + } return ptr + position; @@ -483,13 +580,19 @@ Unmapped: va += PageSize; - if (ptr != null) ptr += PageSize; + if (ptr != null) + { + ptr += PageSize; + } } } private void SetPtEntry(long position, byte* ptr) { - if (!IsValidPosition(position)) throw new ArgumentOutOfRangeException(nameof(position)); + if (!IsValidPosition(position)) + { + throw new ArgumentOutOfRangeException(nameof(position)); + } long l0 = (position >> PtLvl0Bit) & PtLvl0Mask; long l1 = (position >> PtLvl1Bit) & PtLvl1Mask; @@ -498,7 +601,10 @@ Unmapped: { byte** lvl1 = (byte**)Marshal.AllocHGlobal(PtLvl1Size * IntPtr.Size); - for (int zl1 = 0; zl1 < PtLvl1Size; zl1++) lvl1[zl1] = null; + for (int zl1 = 0; zl1 < PtLvl1Size; zl1++) + { + lvl1[zl1] = null; + } Thread.MemoryBarrier(); @@ -540,7 +646,12 @@ Unmapped: byte** lvl1 = _pageTable[l0]; if (lvl1 != null) - if (modified[page] = lvl1[l1] != null) count++; + { + if (modified[page] = lvl1[l1] != null) + { + count++; + } + } } SetPtEntry(position, null); @@ -560,7 +671,10 @@ Unmapped: { lock (_observedPages) { - if (_observedPages.TryRemove(position >> PtPageBits, out IntPtr ptr)) SetPtEntry(position, (byte*)ptr); + if (_observedPages.TryRemove(position >> PtPageBits, out IntPtr ptr)) + { + SetPtEntry(position, (byte*)ptr); + } } position += PageSize; @@ -586,7 +700,10 @@ Unmapped: { long pa = GetPhysicalAddress(position); - if (pa != expectedPa) throw new VmmAccessException(position, size); + if (pa != expectedPa) + { + throw new VmmAccessException(position, size); + } position += PageSize; expectedPa += PageSize; @@ -605,11 +722,17 @@ Unmapped: protected virtual void Dispose(bool disposing) { - if (_pageTable == null) return; + if (_pageTable == null) + { + return; + } for (int l0 = 0; l0 < PtLvl0Size; l0++) { - if (_pageTable[l0] != null) Marshal.FreeHGlobal((IntPtr)_pageTable[l0]); + if (_pageTable[l0] != null) + { + Marshal.FreeHGlobal((IntPtr)_pageTable[l0]); + } _pageTable[l0] = null; } diff --git a/ChocolArm64/Memory/AMemoryHelper.cs b/ChocolArm64/Memory/AMemoryHelper.cs index 8054613ed5..2d42574878 100644 --- a/ChocolArm64/Memory/AMemoryHelper.cs +++ b/ChocolArm64/Memory/AMemoryHelper.cs @@ -11,9 +11,15 @@ namespace ChocolArm64.Memory { int size8 = size & ~(8 - 1); - for (int offs = 0; offs < size8; offs += 8) memory.WriteInt64(position + offs, 0); + for (int offs = 0; offs < size8; offs += 8) + { + memory.WriteInt64(position + offs, 0); + } - for (int offs = size8; offs < size - size8; offs++) memory.WriteByte(position + offs, 0); + for (int offs = size8; offs < size - size8; offs++) + { + memory.WriteByte(position + offs, 0); + } } public static unsafe T Read(AMemory memory, long position) where T : struct @@ -46,7 +52,10 @@ namespace ChocolArm64.Memory { byte value = (byte)memory.ReadByte(position + offs); - if (value == 0) break; + if (value == 0) + { + break; + } ms.WriteByte(value); } diff --git a/ChocolArm64/State/AThreadState.cs b/ChocolArm64/State/AThreadState.cs index 4650a24fd8..9b559f18bc 100644 --- a/ChocolArm64/State/AThreadState.cs +++ b/ChocolArm64/State/AThreadState.cs @@ -99,7 +99,10 @@ namespace ChocolArm64.State //do it after a given number of instructions has executed. _syncCount += bbWeight; - if (_syncCount >= MinInstForCheck) CheckInterrupt(); + if (_syncCount >= MinInstForCheck) + { + CheckInterrupt(); + } return Running; } diff --git a/ChocolArm64/Translation/AILBlock.cs b/ChocolArm64/Translation/AILBlock.cs index 990494f1b5..e54e481300 100644 --- a/ChocolArm64/Translation/AILBlock.cs +++ b/ChocolArm64/Translation/AILBlock.cs @@ -47,14 +47,19 @@ namespace ChocolArm64.Translation else if (ilEmitter is AILOpCodeStore st) { if (AILEmitter.IsRegIndex(st.Index)) + { switch (st.IoType) { case AIoType.Flag: IntOutputs |= 1L << st.Index << 32; break; case AIoType.Int: IntOutputs |= 1L << st.Index; break; case AIoType.Vector: VecOutputs |= 1L << st.Index; break; } + } - if (st.IoType == AIoType.Fields) HasStateStore = true; + if (st.IoType == AIoType.Fields) + { + HasStateStore = true; + } } IlEmitters.Add(ilEmitter); @@ -62,7 +67,10 @@ namespace ChocolArm64.Translation public void Emit(AILEmitter context) { - foreach (IAilEmit ilEmitter in IlEmitters) ilEmitter.Emit(context); + foreach (IAilEmit ilEmitter in IlEmitters) + { + ilEmitter.Emit(context); + } } } } \ No newline at end of file diff --git a/ChocolArm64/Translation/AILEmitter.cs b/ChocolArm64/Translation/AILEmitter.cs index b3c4d4c33b..f3d7b82782 100644 --- a/ChocolArm64/Translation/AILEmitter.cs +++ b/ChocolArm64/Translation/AILEmitter.cs @@ -35,9 +35,15 @@ namespace ChocolArm64.Translation AILBlock GetBlock(int index) { - if (index < 0 || index >= _ilBlocks.Length) return null; + if (index < 0 || index >= _ilBlocks.Length) + { + return null; + } - if (_ilBlocks[index] == null) _ilBlocks[index] = new AILBlock(); + if (_ilBlocks[index] == null) + { + _ilBlocks[index] = new AILBlock(); + } return _ilBlocks[index]; } @@ -65,7 +71,10 @@ namespace ChocolArm64.Translation InitSubroutine(); InitLocals(); - foreach (AILBlock ilBlock in _ilBlocks) ilBlock.Emit(this); + foreach (AILBlock ilBlock in _ilBlocks) + { + ilBlock.Emit(this); + } return _subroutine; } @@ -80,7 +89,10 @@ namespace ChocolArm64.Translation { long mask = 1L << bit; - if ((inputs & mask) != 0) Params.Add(GetRegFromBit(bit, baseType)); + if ((inputs & mask) != 0) + { + Params.Add(GetRegFromBit(bit, baseType)); + } } } @@ -119,7 +131,10 @@ namespace ChocolArm64.Translation int typeIdx = fixedArgs.Length; - for (int index = 0; index < Params.Count; index++) output[typeIdx++] = GetFieldType(Params[index].Type); + for (int index = 0; index < Params.Count; index++) + { + output[typeIdx++] = GetFieldType(Params[index].Type); + } return output; } @@ -158,11 +173,17 @@ namespace ChocolArm64.Translation public static ARegister GetRegFromBit(int bit, ARegisterType baseType) { if (bit < 32) + { return new ARegister(bit, baseType); + } else if (baseType == ARegisterType.Int) + { return new ARegister(bit & 0x1f, ARegisterType.Flag); + } else + { throw new ArgumentOutOfRangeException(nameof(bit)); + } } public static bool IsRegIndex(int index) diff --git a/ChocolArm64/Translation/AILEmitterCtx.cs b/ChocolArm64/Translation/AILEmitterCtx.cs index f105997cde..0b3f1b7d43 100644 --- a/ChocolArm64/Translation/AILEmitterCtx.cs +++ b/ChocolArm64/Translation/AILEmitterCtx.cs @@ -58,7 +58,10 @@ namespace ChocolArm64.Translation _opcIndex = -1; - if (graph.Length == 0 || !AdvanceOpCode()) throw new ArgumentException(nameof(graph)); + if (graph.Length == 0 || !AdvanceOpCode()) + { + throw new ArgumentException(nameof(graph)); + } } public ATranslatedSub GetSubroutine() @@ -70,7 +73,9 @@ namespace ChocolArm64.Translation { if (_opcIndex + 1 == CurrBlock.OpCodes.Count && _blkIndex + 1 == _graph.Length) + { return false; + } while (++_opcIndex >= (CurrBlock?.OpCodes.Count ?? 0)) { @@ -123,21 +128,35 @@ namespace ChocolArm64.Translation public bool TryOptEmitSubroutineCall() { - if (CurrBlock.Next == null) return false; + if (CurrBlock.Next == null) + { + return false; + } - if (CurrOp.Emitter != AInstEmit.Bl) return false; + if (CurrOp.Emitter != AInstEmit.Bl) + { + return false; + } - if (!_cache.TryGetSubroutine(((AOpCodeBImmAl)CurrOp).Imm, out ATranslatedSub subroutine)) return false; + if (!_cache.TryGetSubroutine(((AOpCodeBImmAl)CurrOp).Imm, out ATranslatedSub subroutine)) + { + return false; + } - for (int index = 0; index < ATranslatedSub.FixedArgTypes.Length; index++) EmitLdarg(index); + for (int index = 0; index < ATranslatedSub.FixedArgTypes.Length; index++) + { + EmitLdarg(index); + } foreach (ARegister reg in subroutine.Params) + { switch (reg.Type) { case ARegisterType.Flag: Ldloc(reg.Index, AIoType.Flag); break; case ARegisterType.Int: Ldloc(reg.Index, AIoType.Int); break; case ARegisterType.Vector: Ldloc(reg.Index, AIoType.Vector); break; } + } EmitCall(subroutine.Method); @@ -250,14 +269,20 @@ namespace ChocolArm64.Translation if (sz64 == (intType == AIntType.UInt64 || intType == AIntType.Int64)) + { return; + } if (sz64) + { Emit(intType >= AIntType.Int8 ? OpCodes.Conv_I8 : OpCodes.Conv_U8); + } else + { Emit(OpCodes.Conv_U4); + } } public void EmitLsl(int amount) @@ -345,17 +370,25 @@ namespace ChocolArm64.Translation public void EmitLdintzr(int index) { if (index != AThreadState.ZrIndex) + { EmitLdint(index); + } else + { EmitLdc_I(0); + } } public void EmitStintzr(int index) { if (index != AThreadState.ZrIndex) + { EmitStint(index); + } else + { Emit(OpCodes.Pop); + } } public void EmitLoadState(ABlock retBlk) @@ -447,43 +480,70 @@ namespace ChocolArm64.Translation public void EmitCallPropGet(Type objType, string propName) { - if (objType == null) throw new ArgumentNullException(nameof(objType)); + if (objType == null) + { + throw new ArgumentNullException(nameof(objType)); + } - if (propName == null) throw new ArgumentNullException(nameof(propName)); + if (propName == null) + { + throw new ArgumentNullException(nameof(propName)); + } EmitCall(objType.GetMethod($"get_{propName}")); } public void EmitCallPropSet(Type objType, string propName) { - if (objType == null) throw new ArgumentNullException(nameof(objType)); + if (objType == null) + { + throw new ArgumentNullException(nameof(objType)); + } - if (propName == null) throw new ArgumentNullException(nameof(propName)); + if (propName == null) + { + throw new ArgumentNullException(nameof(propName)); + } EmitCall(objType.GetMethod($"set_{propName}")); } public void EmitCall(Type objType, string mthdName) { - if (objType == null) throw new ArgumentNullException(nameof(objType)); + if (objType == null) + { + throw new ArgumentNullException(nameof(objType)); + } - if (mthdName == null) throw new ArgumentNullException(nameof(mthdName)); + if (mthdName == null) + { + throw new ArgumentNullException(nameof(mthdName)); + } EmitCall(objType.GetMethod(mthdName)); } public void EmitPrivateCall(Type objType, string mthdName) { - if (objType == null) throw new ArgumentNullException(nameof(objType)); + if (objType == null) + { + throw new ArgumentNullException(nameof(objType)); + } - if (mthdName == null) throw new ArgumentNullException(nameof(mthdName)); + if (mthdName == null) + { + throw new ArgumentNullException(nameof(mthdName)); + } EmitCall(objType.GetMethod(mthdName, BindingFlags.Instance | BindingFlags.NonPublic)); } public void EmitCall(MethodInfo mthdInfo) { - if (mthdInfo == null) throw new ArgumentNullException(nameof(mthdInfo)); + if (mthdInfo == null) + { + throw new ArgumentNullException(nameof(mthdInfo)); + } _ilBlock.Add(new AILOpCodeCall(mthdInfo)); } @@ -491,9 +551,13 @@ namespace ChocolArm64.Translation public void EmitLdc_I(long value) { if (CurrOp.RegisterSize == ARegisterSize.Int32) + { EmitLdc_I4((int)value); + } else + { EmitLdc_I8(value); + } } public void EmitLdc_I4(int value) @@ -527,7 +591,10 @@ namespace ChocolArm64.Translation Emit(OpCodes.Dup); Emit(OpCodes.Ldc_I4_0); - if (CurrOp.RegisterSize != ARegisterSize.Int32) Emit(OpCodes.Conv_I8); + if (CurrOp.RegisterSize != ARegisterSize.Int32) + { + Emit(OpCodes.Conv_I8); + } Emit(ilCmpOp); diff --git a/ChocolArm64/Translation/AILOpCodeLoad.cs b/ChocolArm64/Translation/AILOpCodeLoad.cs index e70acf8d9d..d5418cec9d 100644 --- a/ChocolArm64/Translation/AILOpCodeLoad.cs +++ b/ChocolArm64/Translation/AILOpCodeLoad.cs @@ -67,7 +67,9 @@ namespace ChocolArm64.Translation if (registerType == ARegisterType.Int && RegisterSize == ARegisterSize.Int32) + { context.Generator.Emit(OpCodes.Conv_U4); + } } } } \ No newline at end of file diff --git a/ChocolArm64/Translation/AILOpCodeStore.cs b/ChocolArm64/Translation/AILOpCodeStore.cs index 266c9054b5..11d4df5eae 100644 --- a/ChocolArm64/Translation/AILOpCodeStore.cs +++ b/ChocolArm64/Translation/AILOpCodeStore.cs @@ -65,7 +65,9 @@ namespace ChocolArm64.Translation if (registerType == ARegisterType.Int && RegisterSize == ARegisterSize.Int32) + { context.Generator.Emit(OpCodes.Conv_U8); + } context.Generator.EmitStloc(context.GetLocalIndex(reg)); } diff --git a/ChocolArm64/Translation/ALocalAlloc.cs b/ChocolArm64/Translation/ALocalAlloc.cs index f526defafc..f3657cb9aa 100644 --- a/ChocolArm64/Translation/ALocalAlloc.cs +++ b/ChocolArm64/Translation/ALocalAlloc.cs @@ -24,16 +24,25 @@ namespace ChocolArm64.Translation public void Set(AILBlock root, long inputs, long outputs) { - if (!_allInputs.TryAdd(root, inputs)) _allInputs[root] |= inputs; + if (!_allInputs.TryAdd(root, inputs)) + { + _allInputs[root] |= inputs; + } - if (!_cmnOutputs.TryAdd(root, outputs)) _cmnOutputs[root] &= outputs; + if (!_cmnOutputs.TryAdd(root, outputs)) + { + _cmnOutputs[root] &= outputs; + } _allOutputs |= outputs; } public long GetInputs(AILBlock root) { - if (_allInputs.TryGetValue(root, out long inputs)) return inputs | (_allOutputs & ~_cmnOutputs[root]); + if (_allInputs.TryGetValue(root, out long inputs)) + { + return inputs | (_allOutputs & ~_cmnOutputs[root]); + } return 0; } @@ -67,9 +76,13 @@ namespace ChocolArm64.Translation if (graph.Length > 1 && graph.Length < MaxOptGraphLength) + { InitializeOptimal(graph, root); + } else + { InitializeFast(graph); + } } private void InitializeOptimal(AILBlock[] graph, AILBlock root) @@ -117,9 +130,15 @@ namespace ChocolArm64.Translation if (current.Block.Next == null && current.Block.Branch == null || current.Block.HasStateStore) { - if (!_intPaths.TryGetValue(current.Block, out PathIo intPath)) _intPaths.Add(current.Block, intPath = new PathIo()); + if (!_intPaths.TryGetValue(current.Block, out PathIo intPath)) + { + _intPaths.Add(current.Block, intPath = new PathIo()); + } - if (!_vecPaths.TryGetValue(current.Block, out PathIo vecPath)) _vecPaths.Add(current.Block, vecPath = new PathIo()); + if (!_vecPaths.TryGetValue(current.Block, out PathIo vecPath)) + { + _vecPaths.Add(current.Block, vecPath = new PathIo()); + } intPath.Set(current.Entry, current.IntInputs, current.IntOutputs); vecPath.Set(current.Entry, current.VecInputs, current.VecOutputs); @@ -145,9 +164,15 @@ namespace ChocolArm64.Translation Enqueue(blkIo); } - if (current.Block.Next != null) EnqueueFromCurrent(current.Block.Next, current.Block.HasStateStore); + if (current.Block.Next != null) + { + EnqueueFromCurrent(current.Block.Next, current.Block.HasStateStore); + } - if (current.Block.Branch != null) EnqueueFromCurrent(current.Block.Branch, false); + if (current.Block.Branch != null) + { + EnqueueFromCurrent(current.Block.Branch, false); + } } } @@ -197,7 +222,10 @@ namespace ChocolArm64.Translation { long inputs = 0; - foreach (PathIo path in values) inputs |= path.GetInputs(root); + foreach (PathIo path in values) + { + inputs |= path.GetInputs(root); + } return inputs; } diff --git a/ChocolArm64/Translation/ILGeneratorEx.cs b/ChocolArm64/Translation/ILGeneratorEx.cs index 8139e29cd1..eebb3a7e61 100644 --- a/ChocolArm64/Translation/ILGeneratorEx.cs +++ b/ChocolArm64/Translation/ILGeneratorEx.cs @@ -35,11 +35,18 @@ namespace ChocolArm64 default: if ((uint)index <= byte.MaxValue) + { generator.Emit(OpCodes.Ldarg_S, (byte)index); + } else if ((uint)index < ushort.MaxValue) + { generator.Emit(OpCodes.Ldarg, (short)index); + } else + { throw new ArgumentOutOfRangeException(nameof(index)); + } + break; } } @@ -47,11 +54,17 @@ namespace ChocolArm64 public static void EmitStarg(this ILGenerator generator, int index) { if ((uint)index <= byte.MaxValue) + { generator.Emit(OpCodes.Starg_S, (byte)index); + } else if ((uint)index < ushort.MaxValue) + { generator.Emit(OpCodes.Starg, (short)index); + } else + { throw new ArgumentOutOfRangeException(nameof(index)); + } } public static void EmitLdloc(this ILGenerator generator, int index) @@ -65,11 +78,18 @@ namespace ChocolArm64 default: if ((uint)index <= byte.MaxValue) + { generator.Emit(OpCodes.Ldloc_S, (byte)index); + } else if ((uint)index < ushort.MaxValue) + { generator.Emit(OpCodes.Ldloc, (short)index); + } else + { throw new ArgumentOutOfRangeException(nameof(index)); + } + break; } } @@ -85,18 +105,28 @@ namespace ChocolArm64 default: if ((uint)index <= byte.MaxValue) + { generator.Emit(OpCodes.Stloc_S, (byte)index); + } else if ((uint)index < ushort.MaxValue) + { generator.Emit(OpCodes.Stloc, (short)index); + } else + { throw new ArgumentOutOfRangeException(nameof(index)); + } + break; } } public static void EmitLdargSeq(this ILGenerator generator, int count) { - for (int index = 0; index < count; index++) generator.EmitLdarg(index); + for (int index = 0; index < count; index++) + { + generator.EmitLdarg(index); + } } } } diff --git a/Ryujinx.Audio/Adpcm/AdpcmDecoder.cs b/Ryujinx.Audio/Adpcm/AdpcmDecoder.cs index a05193ce11..10a64c8e5b 100644 --- a/Ryujinx.Audio/Adpcm/AdpcmDecoder.cs +++ b/Ryujinx.Audio/Adpcm/AdpcmDecoder.cs @@ -30,7 +30,10 @@ namespace Ryujinx.Audio.Adpcm int frameSamples = SamplesPerFrame; - if (frameSamples > samples) frameSamples = samples; + if (frameSamples > samples) + { + frameSamples = samples; + } int value = 0; diff --git a/Ryujinx.Audio/DspUtils.cs b/Ryujinx.Audio/DspUtils.cs index 1ce154b231..931b9b16ee 100644 --- a/Ryujinx.Audio/DspUtils.cs +++ b/Ryujinx.Audio/DspUtils.cs @@ -5,10 +5,14 @@ namespace Ryujinx.Audio.Adpcm public static short Saturate(int value) { if (value > short.MaxValue) + { value = short.MaxValue; + } if (value < short.MinValue) + { value = short.MinValue; + } return (short)value; } diff --git a/Ryujinx.Audio/OpenAL/OpenALAudioOut.cs b/Ryujinx.Audio/OpenAL/OpenALAudioOut.cs index cef1c288cb..025b809d74 100644 --- a/Ryujinx.Audio/OpenAL/OpenALAudioOut.cs +++ b/Ryujinx.Audio/OpenAL/OpenALAudioOut.cs @@ -56,7 +56,12 @@ namespace Ryujinx.Audio.OpenAL public bool ContainsBuffer(long tag) { foreach (long queuedTag in _queuedTagsQueue) - if (queuedTag == tag) return true; + { + if (queuedTag == tag) + { + return true; + } + } return false; } @@ -67,11 +72,17 @@ namespace Ryujinx.Audio.OpenAL releasedCount += _releasedTagsQueue.Count; - if (count > releasedCount) count = releasedCount; + if (count > releasedCount) + { + count = releasedCount; + } List tags = new List(); - while (count-- > 0 && _releasedTagsQueue.TryDequeue(out long tag)) tags.Add(tag); + while (count-- > 0 && _releasedTagsQueue.TryDequeue(out long tag)) + { + tags.Add(tag); + } while (count-- > 0 && _queuedTagsQueue.TryDequeue(out long tag)) { @@ -85,7 +96,10 @@ namespace Ryujinx.Audio.OpenAL public int AppendBuffer(long tag) { - if (_disposed) throw new ObjectDisposedException(nameof(Track)); + if (_disposed) + { + throw new ObjectDisposedException(nameof(Track)); + } int id = AL.GenBuffer(); @@ -135,7 +149,10 @@ namespace Ryujinx.Audio.OpenAL AL.DeleteSource(SourceId); - foreach (int id in _buffers.Values) AL.DeleteBuffer(id); + foreach (int id in _buffers.Values) + { + AL.DeleteBuffer(id); + } } } } @@ -164,17 +181,22 @@ namespace Ryujinx.Audio.OpenAL do { foreach (Track td in _tracks.Values) + { lock (td) { td.CallReleaseCallbackIfNeeded(); } + } //If it's not slept it will waste cycles. Thread.Sleep(10); } while (_keepPolling); - foreach (Track td in _tracks.Values) td.Dispose(); + foreach (Track td in _tracks.Values) + { + td.Dispose(); + } _tracks.Clear(); } @@ -184,7 +206,12 @@ namespace Ryujinx.Audio.OpenAL Track td = new Track(sampleRate, GetAlFormat(channels), callback); for (int id = 0; id < MaxTracks; id++) - if (_tracks.TryAdd(id, td)) return id; + { + if (_tracks.TryAdd(id, td)) + { + return id; + } + } return -1; } @@ -204,19 +231,23 @@ namespace Ryujinx.Audio.OpenAL public void CloseTrack(int track) { if (_tracks.TryRemove(track, out Track td)) + { lock (td) { td.Dispose(); } + } } public bool ContainsBuffer(int track, long tag) { if (_tracks.TryGetValue(track, out Track td)) + { lock (td) { return td.ContainsBuffer(tag); } + } return false; } @@ -224,10 +255,12 @@ namespace Ryujinx.Audio.OpenAL public long[] GetReleasedBuffers(int track, int maxCount) { if (_tracks.TryGetValue(track, out Track td)) + { lock (td) { return td.GetReleasedBuffers(maxCount); } + } return null; } @@ -235,6 +268,7 @@ namespace Ryujinx.Audio.OpenAL public void AppendBuffer(int track, long tag, T[] buffer) where T : struct { if (_tracks.TryGetValue(track, out Track td)) + { lock (td) { int bufferId = td.AppendBuffer(tag); @@ -247,17 +281,20 @@ namespace Ryujinx.Audio.OpenAL StartPlaybackIfNeeded(td); } + } } public void Start(int track) { if (_tracks.TryGetValue(track, out Track td)) + { lock (td) { td.State = PlaybackState.Playing; StartPlaybackIfNeeded(td); } + } } private void StartPlaybackIfNeeded(Track td) @@ -266,23 +303,31 @@ namespace Ryujinx.Audio.OpenAL ALSourceState state = (ALSourceState)stateInt; - if (state != ALSourceState.Playing && td.State == PlaybackState.Playing) AL.SourcePlay(td.SourceId); + if (state != ALSourceState.Playing && td.State == PlaybackState.Playing) + { + AL.SourcePlay(td.SourceId); + } } public void Stop(int track) { if (_tracks.TryGetValue(track, out Track td)) + { lock (td) { td.State = PlaybackState.Stopped; AL.SourceStop(td.SourceId); } + } } public PlaybackState GetState(int track) { - if (_tracks.TryGetValue(track, out Track td)) return td.State; + if (_tracks.TryGetValue(track, out Track td)) + { + return td.State; + } return PlaybackState.Stopped; } @@ -294,7 +339,10 @@ namespace Ryujinx.Audio.OpenAL protected virtual void Dispose(bool disposing) { - if (disposing) _keepPolling = false; + if (disposing) + { + _keepPolling = false; + } } } } \ No newline at end of file diff --git a/Ryujinx.Common/Logging/Logger.cs b/Ryujinx.Common/Logging/Logger.cs index ddb9ce88c4..2be5dbc35a 100644 --- a/Ryujinx.Common/Logging/Logger.cs +++ b/Ryujinx.Common/Logging/Logger.cs @@ -23,7 +23,10 @@ namespace Ryujinx.Common.Logging _enabledLevels[(int)LogLevel.Warning] = true; _enabledLevels[(int)LogLevel.Error] = true; - for (int index = 0; index < _enabledClasses.Length; index++) _enabledClasses[index] = true; + for (int index = 0; index < _enabledClasses.Length; index++) + { + _enabledClasses[index] = true; + } _time = new Stopwatch(); @@ -67,7 +70,10 @@ namespace Ryujinx.Common.Logging private static void Print(LogLevel level, LogClass Class, string message) { - if (_enabledLevels[(int)level] && _enabledClasses[(int)Class]) Updated?.Invoke(null, new LogEventArgs(level, _time.Elapsed, message)); + if (_enabledLevels[(int)level] && _enabledClasses[(int)Class]) + { + Updated?.Invoke(null, new LogEventArgs(level, _time.Elapsed, message)); + } } private static string GetFormattedMessage(LogClass Class, string message, string caller) diff --git a/Ryujinx.Graphics/Gal/GalImage.cs b/Ryujinx.Graphics/Gal/GalImage.cs index 57d832c21a..9d39a21a8d 100644 --- a/Ryujinx.Graphics/Gal/GalImage.cs +++ b/Ryujinx.Graphics/Gal/GalImage.cs @@ -47,11 +47,15 @@ namespace Ryujinx.Graphics.Gal { if (ImageUtils.GetBytesPerPixel(Format) != ImageUtils.GetBytesPerPixel(image.Format)) + { return false; + } if (ImageUtils.GetAlignedWidth(this) != ImageUtils.GetAlignedWidth(image)) + { return false; + } return Height == image.Height; } diff --git a/Ryujinx.Graphics/Gal/GalPipelineState.cs b/Ryujinx.Graphics/Gal/GalPipelineState.cs index 390df95adb..188bec9ebe 100644 --- a/Ryujinx.Graphics/Gal/GalPipelineState.cs +++ b/Ryujinx.Graphics/Gal/GalPipelineState.cs @@ -84,7 +84,10 @@ { ConstBufferKeys = new long[Stages][]; - for (int stage = 0; stage < Stages; stage++) ConstBufferKeys[stage] = new long[ConstBuffersPerStage]; + for (int stage = 0; stage < Stages; stage++) + { + ConstBufferKeys[stage] = new long[ConstBuffersPerStage]; + } ColorMasks = new ColorMaskRgba[RenderTargetsCount]; } diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLCachedResource.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLCachedResource.cs index d1afb59180..5499579912 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLCachedResource.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/OGLCachedResource.cs @@ -42,7 +42,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL public OGLCachedResource(DeleteValue deleteValueCallback) { - if (deleteValueCallback == null) throw new ArgumentNullException(nameof(deleteValueCallback)); + if (deleteValueCallback == null) + { + throw new ArgumentNullException(nameof(deleteValueCallback)); + } _deleteValueCallback = deleteValueCallback; @@ -62,14 +65,20 @@ namespace Ryujinx.Graphics.Gal.OpenGL { _locked = false; - while (_deletePending.TryDequeue(out T value)) _deleteValueCallback(value); + while (_deletePending.TryDequeue(out T value)) + { + _deleteValueCallback(value); + } ClearCacheIfNeeded(); } public void AddOrUpdate(long key, T value, long size) { - if (!_locked) ClearCacheIfNeeded(); + if (!_locked) + { + ClearCacheIfNeeded(); + } LinkedListNode node = _sortedCache.AddLast(key); @@ -78,9 +87,13 @@ namespace Ryujinx.Graphics.Gal.OpenGL if (_cache.TryGetValue(key, out CacheBucket bucket)) { if (_locked) + { _deletePending.Enqueue(bucket.Value); + } else + { _deleteValueCallback(bucket.Value); + } _sortedCache.Remove(bucket.Node); @@ -136,13 +149,19 @@ namespace Ryujinx.Graphics.Gal.OpenGL { LinkedListNode node = _sortedCache.First; - if (node == null) break; + if (node == null) + { + break; + } CacheBucket bucket = _cache[node.Value]; int timeDelta = RingDelta(bucket.Timestamp, timestamp); - if ((uint)timeDelta <= (uint)MaxTimeDelta) break; + if ((uint)timeDelta <= (uint)MaxTimeDelta) + { + break; + } _sortedCache.Remove(node); @@ -155,9 +174,13 @@ namespace Ryujinx.Graphics.Gal.OpenGL private int RingDelta(int old, int New) { if ((uint)New < (uint)old) + { return New + ~old + 1; + } else + { return New - old; + } } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLConstBuffer.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLConstBuffer.cs index f43674027f..e7dd99dce0 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLConstBuffer.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/OGLConstBuffer.cs @@ -36,7 +36,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL public void SetData(long key, long size, IntPtr hostAddress) { - if (_cache.TryGetValue(key, out OGLStreamBuffer buffer)) buffer.SetData(size, hostAddress); + if (_cache.TryGetValue(key, out OGLStreamBuffer buffer)) + { + buffer.SetData(size, hostAddress); + } } public bool TryGetUbo(long key, out int uboHandle) diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLEnumConverter.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLEnumConverter.cs index 12d05c560b..8f051f1869 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLEnumConverter.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/OGLEnumConverter.cs @@ -50,7 +50,9 @@ namespace Ryujinx.Graphics.Gal.OpenGL //Looks like the GPU can take it's own values (described in GalComparisonOp) and OpenGL values alike if ((int)func >= (int)DepthFunction.Never && (int)func <= (int)DepthFunction.Always) + { return (DepthFunction)func; + } switch (func) { @@ -229,19 +231,23 @@ namespace Ryujinx.Graphics.Gal.OpenGL } if (OGLExtension.TextureMirrorClamp) + { switch (wrap) { case GalTextureWrap.MirrorClampToEdge: return (TextureWrapMode)ExtTextureMirrorClamp.MirrorClampToEdgeExt; case GalTextureWrap.MirrorClampToBorder: return (TextureWrapMode)ExtTextureMirrorClamp.MirrorClampToBorderExt; case GalTextureWrap.MirrorClamp: return (TextureWrapMode)ExtTextureMirrorClamp.MirrorClampExt; } + } else + { switch (wrap) { case GalTextureWrap.MirrorClampToEdge: return TextureWrapMode.ClampToEdge; case GalTextureWrap.MirrorClampToBorder: return TextureWrapMode.ClampToBorder; case GalTextureWrap.MirrorClamp: return TextureWrapMode.Clamp; } + } throw new ArgumentException(nameof(wrap) + " \"" + wrap + "\" is not valid!"); } diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLExtension.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLExtension.cs index eb3d500c48..7e6d9c3ec4 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLExtension.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/OGLExtension.cs @@ -18,7 +18,12 @@ namespace Ryujinx.Graphics.Gal.OpenGL int numExtensions = GL.GetInteger(GetPName.NumExtensions); for (int extension = 0; extension < numExtensions; extension++) - if (GL.GetString(StringNameIndexed.Extensions, extension) == name) return true; + { + if (GL.GetString(StringNameIndexed.Extensions, extension) == name) + { + return true; + } + } return false; } diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLPipeline.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLPipeline.cs index d5d3770284..0c06b06e8a 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLPipeline.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/OGLPipeline.cs @@ -135,7 +135,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL PrimitiveRestartIndex = 0 }; - for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) _old.ColorMasks[index] = ColorMaskRgba.Default; + for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) + { + _old.ColorMasks[index] = ColorMaskRgba.Default; + } } public void Bind(GalPipelineState New) @@ -144,9 +147,15 @@ namespace Ryujinx.Graphics.Gal.OpenGL BindVertexLayout(New); - if (New.FramebufferSrgb != _old.FramebufferSrgb) Enable(EnableCap.FramebufferSrgb, New.FramebufferSrgb); + if (New.FramebufferSrgb != _old.FramebufferSrgb) + { + Enable(EnableCap.FramebufferSrgb, New.FramebufferSrgb); + } - if (New.FlipX != _old.FlipX || New.FlipY != _old.FlipY || New.Instance != _old.Instance) _shader.SetExtraData(New.FlipX, New.FlipY, New.Instance); + if (New.FlipX != _old.FlipX || New.FlipY != _old.FlipY || New.Instance != _old.Instance) + { + _shader.SetExtraData(New.FlipX, New.FlipY, New.Instance); + } //Note: Uncomment SetFrontFace and SetCullFace when flipping issues are solved @@ -168,65 +177,101 @@ namespace Ryujinx.Graphics.Gal.OpenGL // } //} - if (New.DepthTestEnabled != _old.DepthTestEnabled) Enable(EnableCap.DepthTest, New.DepthTestEnabled); + if (New.DepthTestEnabled != _old.DepthTestEnabled) + { + Enable(EnableCap.DepthTest, New.DepthTestEnabled); + } - if (New.DepthWriteEnabled != _old.DepthWriteEnabled) GL.DepthMask(New.DepthWriteEnabled); + if (New.DepthWriteEnabled != _old.DepthWriteEnabled) + { + GL.DepthMask(New.DepthWriteEnabled); + } if (New.DepthTestEnabled) - if (New.DepthFunc != _old.DepthFunc) GL.DepthFunc(OGLEnumConverter.GetDepthFunc(New.DepthFunc)); + { + if (New.DepthFunc != _old.DepthFunc) + { + GL.DepthFunc(OGLEnumConverter.GetDepthFunc(New.DepthFunc)); + } + } if (New.DepthRangeNear != _old.DepthRangeNear || New.DepthRangeFar != _old.DepthRangeFar) + { GL.DepthRange(New.DepthRangeNear, New.DepthRangeFar); + } - if (New.StencilTestEnabled != _old.StencilTestEnabled) Enable(EnableCap.StencilTest, New.StencilTestEnabled); + if (New.StencilTestEnabled != _old.StencilTestEnabled) + { + Enable(EnableCap.StencilTest, New.StencilTestEnabled); + } - if (New.StencilTwoSideEnabled != _old.StencilTwoSideEnabled) Enable((EnableCap)All.StencilTestTwoSideExt, New.StencilTwoSideEnabled); + if (New.StencilTwoSideEnabled != _old.StencilTwoSideEnabled) + { + Enable((EnableCap)All.StencilTestTwoSideExt, New.StencilTwoSideEnabled); + } if (New.StencilTestEnabled) { if (New.StencilBackFuncFunc != _old.StencilBackFuncFunc || New.StencilBackFuncRef != _old.StencilBackFuncRef || New.StencilBackFuncMask != _old.StencilBackFuncMask) + { GL.StencilFuncSeparate( StencilFace.Back, OGLEnumConverter.GetStencilFunc(New.StencilBackFuncFunc), New.StencilBackFuncRef, New.StencilBackFuncMask); + } if (New.StencilBackOpFail != _old.StencilBackOpFail || New.StencilBackOpZFail != _old.StencilBackOpZFail || New.StencilBackOpZPass != _old.StencilBackOpZPass) + { GL.StencilOpSeparate( StencilFace.Back, OGLEnumConverter.GetStencilOp(New.StencilBackOpFail), OGLEnumConverter.GetStencilOp(New.StencilBackOpZFail), OGLEnumConverter.GetStencilOp(New.StencilBackOpZPass)); + } - if (New.StencilBackMask != _old.StencilBackMask) GL.StencilMaskSeparate(StencilFace.Back, New.StencilBackMask); + if (New.StencilBackMask != _old.StencilBackMask) + { + GL.StencilMaskSeparate(StencilFace.Back, New.StencilBackMask); + } if (New.StencilFrontFuncFunc != _old.StencilFrontFuncFunc || New.StencilFrontFuncRef != _old.StencilFrontFuncRef || New.StencilFrontFuncMask != _old.StencilFrontFuncMask) + { GL.StencilFuncSeparate( StencilFace.Front, OGLEnumConverter.GetStencilFunc(New.StencilFrontFuncFunc), New.StencilFrontFuncRef, New.StencilFrontFuncMask); + } if (New.StencilFrontOpFail != _old.StencilFrontOpFail || New.StencilFrontOpZFail != _old.StencilFrontOpZFail || New.StencilFrontOpZPass != _old.StencilFrontOpZPass) + { GL.StencilOpSeparate( StencilFace.Front, OGLEnumConverter.GetStencilOp(New.StencilFrontOpFail), OGLEnumConverter.GetStencilOp(New.StencilFrontOpZFail), OGLEnumConverter.GetStencilOp(New.StencilFrontOpZPass)); + } - if (New.StencilFrontMask != _old.StencilFrontMask) GL.StencilMaskSeparate(StencilFace.Front, New.StencilFrontMask); + if (New.StencilFrontMask != _old.StencilFrontMask) + { + GL.StencilMaskSeparate(StencilFace.Front, New.StencilFrontMask); + } } - if (New.BlendEnabled != _old.BlendEnabled) Enable(EnableCap.Blend, New.BlendEnabled); + if (New.BlendEnabled != _old.BlendEnabled) + { + Enable(EnableCap.Blend, New.BlendEnabled); + } if (New.BlendEnabled) { @@ -234,57 +279,80 @@ namespace Ryujinx.Graphics.Gal.OpenGL { if (New.BlendEquationRgb != _old.BlendEquationRgb || New.BlendEquationAlpha != _old.BlendEquationAlpha) + { GL.BlendEquationSeparate( OGLEnumConverter.GetBlendEquation(New.BlendEquationRgb), OGLEnumConverter.GetBlendEquation(New.BlendEquationAlpha)); + } if (New.BlendFuncSrcRgb != _old.BlendFuncSrcRgb || New.BlendFuncDstRgb != _old.BlendFuncDstRgb || New.BlendFuncSrcAlpha != _old.BlendFuncSrcAlpha || New.BlendFuncDstAlpha != _old.BlendFuncDstAlpha) + { GL.BlendFuncSeparate( (BlendingFactorSrc) OGLEnumConverter.GetBlendFactor(New.BlendFuncSrcRgb), (BlendingFactorDest)OGLEnumConverter.GetBlendFactor(New.BlendFuncDstRgb), (BlendingFactorSrc) OGLEnumConverter.GetBlendFactor(New.BlendFuncSrcAlpha), (BlendingFactorDest)OGLEnumConverter.GetBlendFactor(New.BlendFuncDstAlpha)); + } } else { - if (New.BlendEquationRgb != _old.BlendEquationRgb) GL.BlendEquation(OGLEnumConverter.GetBlendEquation(New.BlendEquationRgb)); + if (New.BlendEquationRgb != _old.BlendEquationRgb) + { + GL.BlendEquation(OGLEnumConverter.GetBlendEquation(New.BlendEquationRgb)); + } if (New.BlendFuncSrcRgb != _old.BlendFuncSrcRgb || New.BlendFuncDstRgb != _old.BlendFuncDstRgb) + { GL.BlendFunc( OGLEnumConverter.GetBlendFactor(New.BlendFuncSrcRgb), OGLEnumConverter.GetBlendFactor(New.BlendFuncDstRgb)); + } } } if (New.ColorMaskCommon) { if (New.ColorMaskCommon != _old.ColorMaskCommon || !New.ColorMasks[0].Equals(_old.ColorMasks[0])) + { GL.ColorMask( New.ColorMasks[0].Red, New.ColorMasks[0].Green, New.ColorMasks[0].Blue, New.ColorMasks[0].Alpha); + } } else { for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) + { if (!New.ColorMasks[index].Equals(_old.ColorMasks[index])) + { GL.ColorMask( index, New.ColorMasks[index].Red, New.ColorMasks[index].Green, New.ColorMasks[index].Blue, New.ColorMasks[index].Alpha); + } + } } - if (New.PrimitiveRestartEnabled != _old.PrimitiveRestartEnabled) Enable(EnableCap.PrimitiveRestart, New.PrimitiveRestartEnabled); + if (New.PrimitiveRestartEnabled != _old.PrimitiveRestartEnabled) + { + Enable(EnableCap.PrimitiveRestart, New.PrimitiveRestartEnabled); + } if (New.PrimitiveRestartEnabled) - if (New.PrimitiveRestartIndex != _old.PrimitiveRestartIndex) GL.PrimitiveRestartIndex(New.PrimitiveRestartIndex); + { + if (New.PrimitiveRestartIndex != _old.PrimitiveRestartIndex) + { + GL.PrimitiveRestartIndex(New.PrimitiveRestartIndex); + } + } _old = New; } @@ -296,14 +364,19 @@ namespace Ryujinx.Graphics.Gal.OpenGL void BindIfNotNull(OGLShaderStage stage) { if (stage != null) + { foreach (ShaderDeclInfo declInfo in stage.ConstBufferUsage) { long key = New.ConstBufferKeys[(int)stage.Type][declInfo.Cbuf]; - if (key != 0 && _buffer.TryGetUbo(key, out int uboHandle)) GL.BindBufferBase(BufferRangeTarget.UniformBuffer, freeBinding, uboHandle); + if (key != 0 && _buffer.TryGetUbo(key, out int uboHandle)) + { + GL.BindBufferBase(BufferRangeTarget.UniformBuffer, freeBinding, uboHandle); + } freeBinding++; } + } } BindIfNotNull(_shader.Current.Vertex); @@ -317,7 +390,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL { foreach (GalVertexBinding binding in New.VertexBindings) { - if (!binding.Enabled || !_rasterizer.TryGetVbo(binding.VboKey, out int vboHandle)) continue; + if (!binding.Enabled || !_rasterizer.TryGetVbo(binding.VboKey, out int vboHandle)) + { + continue; + } if (_vaoHandle == 0) { @@ -331,7 +407,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL foreach (GalVertexAttrib attrib in binding.Attribs) { //Skip uninitialized attributes. - if (attrib.Size == 0) continue; + if (attrib.Size == 0) + { + continue; + } GL.BindBuffer(BufferTarget.ArrayBuffer, vboHandle); @@ -353,12 +432,19 @@ namespace Ryujinx.Graphics.Gal.OpenGL else { if (unsigned) + { type = GetType(_unsignedAttribTypes, attrib); + } else + { type = GetType(_signedAttribTypes, attrib); + } } - if (!_attribElements.TryGetValue(attrib.Size, out int size)) throw new InvalidOperationException("Invalid attribute size \"" + attrib.Size + "\"!"); + if (!_attribElements.TryGetValue(attrib.Size, out int size)) + { + throw new InvalidOperationException("Invalid attribute size \"" + attrib.Size + "\"!"); + } int offset = attrib.Offset; @@ -388,16 +474,23 @@ namespace Ryujinx.Graphics.Gal.OpenGL } if (binding.Instanced && binding.Divisor != 0) + { GL.VertexAttribDivisor(attrib.Index, 1); + } else + { GL.VertexAttribDivisor(attrib.Index, 0); + } } } } private static VertexAttribPointerType GetType(Dictionary dict, GalVertexAttrib attrib) { - if (!dict.TryGetValue(attrib.Size, out VertexAttribPointerType type)) ThrowUnsupportedAttrib(attrib); + if (!dict.TryGetValue(attrib.Size, out VertexAttribPointerType type)) + { + ThrowUnsupportedAttrib(attrib); + } return type; } @@ -406,9 +499,12 @@ namespace Ryujinx.Graphics.Gal.OpenGL { if (attrib.Size == GalVertexAttribSize._10_10_10_2 || attrib.Size == GalVertexAttribSize._11_11_10) + { ThrowUnsupportedAttrib(attrib); + } if (attrib.Type == GalVertexAttribType.Unorm) + { switch (attrib.Size) { case GalVertexAttribSize._8: @@ -432,7 +528,9 @@ namespace Ryujinx.Graphics.Gal.OpenGL GL.VertexAttrib4N((uint)attrib.Index, (uint*)attrib.Pointer); break; } + } else if (attrib.Type == GalVertexAttribType.Snorm) + { switch (attrib.Size) { case GalVertexAttribSize._8: @@ -456,7 +554,9 @@ namespace Ryujinx.Graphics.Gal.OpenGL GL.VertexAttrib4N((uint)attrib.Index, (int*)attrib.Pointer); break; } + } else if (attrib.Type == GalVertexAttribType.Uint) + { switch (attrib.Size) { case GalVertexAttribSize._8: @@ -480,7 +580,9 @@ namespace Ryujinx.Graphics.Gal.OpenGL GL.VertexAttribI4((uint)attrib.Index, (uint*)attrib.Pointer); break; } + } else if (attrib.Type == GalVertexAttribType.Sint) + { switch (attrib.Size) { case GalVertexAttribSize._8: @@ -504,7 +606,9 @@ namespace Ryujinx.Graphics.Gal.OpenGL GL.VertexAttribI4((uint)attrib.Index, (int*)attrib.Pointer); break; } + } else if (attrib.Type == GalVertexAttribType.Float) + { switch (attrib.Size) { case GalVertexAttribSize._32: @@ -516,6 +620,7 @@ namespace Ryujinx.Graphics.Gal.OpenGL default: ThrowUnsupportedAttrib(attrib); break; } + } } private static void ThrowUnsupportedAttrib(GalVertexAttrib attrib) @@ -526,9 +631,13 @@ namespace Ryujinx.Graphics.Gal.OpenGL private void Enable(EnableCap cap, bool enabled) { if (enabled) + { GL.Enable(cap); + } else + { GL.Disable(cap); + } } public void ResetDepthMask() diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLRasterizer.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLRasterizer.cs index 9bc9f44801..7290e742ef 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLRasterizer.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/OGLRasterizer.cs @@ -64,9 +64,15 @@ namespace Ryujinx.Graphics.Gal.OpenGL GL.ColorMask(attachment, true, true, true, true); GL.DepthMask(true); - if (flags.HasFlag(GalClearBufferFlags.Depth)) GL.ClearBuffer(ClearBuffer.Depth, 0, ref depth); + if (flags.HasFlag(GalClearBufferFlags.Depth)) + { + GL.ClearBuffer(ClearBuffer.Depth, 0, ref depth); + } - if (flags.HasFlag(GalClearBufferFlags.Stencil)) GL.ClearBuffer(ClearBuffer.Stencil, 0, ref stencil); + if (flags.HasFlag(GalClearBufferFlags.Stencil)) + { + GL.ClearBuffer(ClearBuffer.Stencil, 0, ref stencil); + } } public bool IsVboCached(long key, long dataSize) @@ -126,17 +132,26 @@ namespace Ryujinx.Graphics.Gal.OpenGL public void DrawArrays(int first, int count, GalPrimitiveType primType) { - if (count == 0) return; + if (count == 0) + { + return; + } if (primType == GalPrimitiveType.Quads) { - for (int offset = 0; offset < count; offset += 4) GL.DrawArrays(PrimitiveType.TriangleFan, first + offset, 4); + for (int offset = 0; offset < count; offset += 4) + { + GL.DrawArrays(PrimitiveType.TriangleFan, first + offset, 4); + } } else if (primType == GalPrimitiveType.QuadStrip) { GL.DrawArrays(PrimitiveType.TriangleFan, first, 4); - for (int offset = 2; offset < count; offset += 2) GL.DrawArrays(PrimitiveType.TriangleFan, first + offset, 4); + for (int offset = 2; offset < count; offset += 2) + { + GL.DrawArrays(PrimitiveType.TriangleFan, first + offset, 4); + } } else { @@ -146,7 +161,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL public void DrawElements(long iboKey, int first, int vertexBase, GalPrimitiveType primType) { - if (!_iboCache.TryGetValue(iboKey, out int iboHandle)) return; + if (!_iboCache.TryGetValue(iboKey, out int iboHandle)) + { + return; + } PrimitiveType mode = OGLEnumConverter.GetPrimitiveType(primType); diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLRenderTarget.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLRenderTarget.cs index 33f64a7492..690d35730f 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLRenderTarget.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/OGLRenderTarget.cs @@ -110,14 +110,25 @@ namespace Ryujinx.Graphics.Gal.OpenGL //Texture was deleted, the handle is no longer valid, so //reset all uses of this handle on a render target. for (int attachment = 0; attachment < RenderTargetsCount; attachment++) - if (_colorHandles[attachment] == handle) _colorHandles[attachment] = 0; + { + if (_colorHandles[attachment] == handle) + { + _colorHandles[attachment] = 0; + } + } - if (_zetaHandle == handle) _zetaHandle = 0; + if (_zetaHandle == handle) + { + _zetaHandle = 0; + } } public void Bind() { - if (_dummyFrameBuffer == 0) _dummyFrameBuffer = GL.GenFramebuffer(); + if (_dummyFrameBuffer == 0) + { + _dummyFrameBuffer = GL.GenFramebuffer(); + } GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, _dummyFrameBuffer); @@ -129,9 +140,15 @@ namespace Ryujinx.Graphics.Gal.OpenGL int handle = 0; - if (key != 0 && _texture.TryGetImageHandler(key, out cachedImage)) handle = cachedImage.Handle; + if (key != 0 && _texture.TryGetImageHandler(key, out cachedImage)) + { + handle = cachedImage.Handle; + } - if (handle == _colorHandles[attachment]) continue; + if (handle == _colorHandles[attachment]) + { + continue; + } GL.FramebufferTexture( FramebufferTarget.DrawFramebuffer, @@ -188,20 +205,30 @@ namespace Ryujinx.Graphics.Gal.OpenGL } if (OGLExtension.ViewportArray) + { GL.ViewportArray(0, RenderTargetsCount, _viewports); + } else + { GL.Viewport( (int)_viewports[0], (int)_viewports[1], (int)_viewports[2], (int)_viewports[3]); + } if (_attachments.MapCount > 1) + { GL.DrawBuffers(_attachments.MapCount, _attachments.Map); + } else if (_attachments.MapCount == 1) + { GL.DrawBuffer((DrawBufferMode)_attachments.Map[0]); + } else + { GL.DrawBuffer(DrawBufferMode.None); + } _oldAttachments.Update(_attachments); } @@ -237,7 +264,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL { _attachments.MapCount = map.Length; - for (int attachment = 0; attachment < _attachments.MapCount; attachment++) _attachments.Map[attachment] = DrawBuffersEnum.ColorAttachment0 + map[attachment]; + for (int attachment = 0; attachment < _attachments.MapCount; attachment++) + { + _attachments.Map[attachment] = DrawBuffersEnum.ColorAttachment0 + map[attachment]; + } } else { @@ -273,7 +303,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL public void Render() { - if (_readTex == null) return; + if (_readTex == null) + { + return; + } int srcX0, srcX1, srcY0, srcY1; @@ -316,7 +349,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL GL.Viewport(0, 0, _window.Width, _window.Height); - if (_srcFb == 0) _srcFb = GL.GenFramebuffer(); + if (_srcFb == 0) + { + _srcFb = GL.GenFramebuffer(); + } GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, _srcFb); GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, 0); @@ -352,11 +388,19 @@ namespace Ryujinx.Graphics.Gal.OpenGL if (srcTex.HasColor != dstTex.HasColor || srcTex.HasDepth != dstTex.HasDepth || srcTex.HasStencil != dstTex.HasStencil) + { throw new NotImplementedException(); + } - if (_srcFb == 0) _srcFb = GL.GenFramebuffer(); + if (_srcFb == 0) + { + _srcFb = GL.GenFramebuffer(); + } - if (_dstFb == 0) _dstFb = GL.GenFramebuffer(); + if (_dstFb == 0) + { + _dstFb = GL.GenFramebuffer(); + } GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, _srcFb); GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, _dstFb); @@ -385,17 +429,29 @@ namespace Ryujinx.Graphics.Gal.OpenGL public void Reinterpret(long key, GalImage newImage) { - if (!_texture.TryGetImage(key, out GalImage oldImage)) return; + if (!_texture.TryGetImage(key, out GalImage oldImage)) + { + return; + } - if (newImage.Format == oldImage.Format) return; + if (newImage.Format == oldImage.Format) + { + return; + } - if (_copyPbo == 0) _copyPbo = GL.GenBuffer(); + if (_copyPbo == 0) + { + _copyPbo = GL.GenBuffer(); + } GL.BindBuffer(BufferTarget.PixelPackBuffer, _copyPbo); GL.BufferData(BufferTarget.PixelPackBuffer, Math.Max(ImageUtils.GetSize(oldImage), ImageUtils.GetSize(newImage)), IntPtr.Zero, BufferUsageHint.StreamCopy); - if (!_texture.TryGetImageHandler(key, out ImageHandler cachedImage)) throw new InvalidOperationException(); + if (!_texture.TryGetImageHandler(key, out ImageHandler cachedImage)) + { + throw new InvalidOperationException(); + } (_, PixelFormat format, PixelType type) = OGLEnumConverter.GetImageFormat(cachedImage.Format); @@ -414,15 +470,25 @@ namespace Ryujinx.Graphics.Gal.OpenGL private static FramebufferAttachment GetAttachment(ImageHandler cachedImage) { if (cachedImage.HasColor) + { return FramebufferAttachment.ColorAttachment0; + } else if (cachedImage.HasDepth && cachedImage.HasStencil) + { return FramebufferAttachment.DepthStencilAttachment; + } else if (cachedImage.HasDepth) + { return FramebufferAttachment.DepthAttachment; + } else if (cachedImage.HasStencil) + { return FramebufferAttachment.StencilAttachment; + } else + { throw new InvalidOperationException(); + } } private static ClearBufferMask GetClearMask(ImageHandler cachedImage) diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLRenderer.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLRenderer.cs index b4b9166324..ab872f652e 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLRenderer.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/OGLRenderer.cs @@ -45,7 +45,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL { int count = _actionsQueue.Count; - while (count-- > 0 && _actionsQueue.TryDequeue(out Action renderAction)) renderAction(); + while (count-- > 0 && _actionsQueue.TryDequeue(out Action renderAction)) + { + renderAction(); + } } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLShader.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLShader.cs index 5624837bde..72996c5421 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLShader.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/OGLShader.cs @@ -73,21 +73,30 @@ namespace Ryujinx.Graphics.Gal.OpenGL string code = program.Code; - if (ShaderDumper.IsDumpEnabled()) code = "//Shader " + shaderDumpIndex + Environment.NewLine + code; + if (ShaderDumper.IsDumpEnabled()) + { + code = "//Shader " + shaderDumpIndex + Environment.NewLine + code; + } return new OGLShaderStage(type, code, program.Uniforms, program.Textures); } public IEnumerable GetConstBufferUsage(long key) { - if (_stages.TryGetValue(key, out OGLShaderStage stage)) return stage.ConstBufferUsage; + if (_stages.TryGetValue(key, out OGLShaderStage stage)) + { + return stage.ConstBufferUsage; + } return Enumerable.Empty(); } public IEnumerable GetTextureUsage(long key) { - if (_stages.TryGetValue(key, out OGLShaderStage stage)) return stage.TextureUsage; + if (_stages.TryGetValue(key, out OGLShaderStage stage)) + { + return stage.TextureUsage; + } return Enumerable.Empty(); } @@ -113,13 +122,21 @@ namespace Ryujinx.Graphics.Gal.OpenGL public void Bind(long key) { - if (_stages.TryGetValue(key, out OGLShaderStage stage)) Bind(stage); + if (_stages.TryGetValue(key, out OGLShaderStage stage)) + { + Bind(stage); + } } private void Bind(OGLShaderStage stage) { if (stage.Type == GalShaderType.Geometry) - if (!OGLExtension.EnhancedLayouts) return; + { + if (!OGLExtension.EnhancedLayouts) + { + return; + } + } switch (stage.Type) { @@ -147,7 +164,9 @@ namespace Ryujinx.Graphics.Gal.OpenGL { if (Current.Vertex == null || Current.Fragment == null) + { return; + } if (!_programs.TryGetValue(Current, out int handle)) { @@ -209,16 +228,21 @@ namespace Ryujinx.Graphics.Gal.OpenGL void BindUniformBlocksIfNotNull(OGLShaderStage stage) { if (stage != null) + { foreach (ShaderDeclInfo declInfo in stage.ConstBufferUsage) { int blockIndex = GL.GetUniformBlockIndex(programHandle, declInfo.Name); - if (blockIndex < 0) throw new InvalidOperationException(); + if (blockIndex < 0) + { + throw new InvalidOperationException(); + } GL.UniformBlockBinding(programHandle, blockIndex, freeBinding); freeBinding++; } + } } BindUniformBlocksIfNotNull(Current.Vertex); @@ -235,6 +259,7 @@ namespace Ryujinx.Graphics.Gal.OpenGL void BindTexturesIfNotNull(OGLShaderStage stage) { if (stage != null) + { foreach (ShaderDeclInfo decl in stage.TextureUsage) { int location = GL.GetUniformLocation(programHandle, decl.Name); @@ -243,6 +268,7 @@ namespace Ryujinx.Graphics.Gal.OpenGL index++; } + } } GL.UseProgram(programHandle); @@ -260,7 +286,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL GL.GetProgram(handle, GetProgramParameterName.LinkStatus, out status); - if (status == 0) throw new ShaderException(GL.GetProgramInfoLog(handle)); + if (status == 0) + { + throw new ShaderException(GL.GetProgramInfoLog(handle)); + } } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLShaderProgram.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLShaderProgram.cs index 44cc5e0d1d..0d48855134 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLShaderProgram.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/OGLShaderProgram.cs @@ -77,7 +77,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL GL.GetShader(handle, ShaderParameter.CompileStatus, out status); - if (status == 0) throw new ShaderException(GL.GetShaderInfoLog(handle)); + if (status == 0) + { + throw new ShaderException(GL.GetShaderInfoLog(handle)); + } } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/OpenGL/OGLTexture.cs b/Ryujinx.Graphics/Gal/OpenGL/OGLTexture.cs index ebfbac03f5..8971116686 100644 --- a/Ryujinx.Graphics/Gal/OpenGL/OGLTexture.cs +++ b/Ryujinx.Graphics/Gal/OpenGL/OGLTexture.cs @@ -43,7 +43,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL _textureCache.AddOrUpdate(key, new ImageHandler(handle, image), (uint)size); - if (ImageUtils.IsCompressed(image.Format)) throw new InvalidOperationException("Surfaces with compressed formats are not supported!"); + if (ImageUtils.IsCompressed(image.Format)) + { + throw new InvalidOperationException("Surfaces with compressed formats are not supported!"); + } (PixelInternalFormat internalFmt, PixelFormat format, @@ -144,7 +147,10 @@ namespace Ryujinx.Graphics.Gal.OpenGL public bool TryGetImageHandler(long key, out ImageHandler cachedImage) { - if (_textureCache.TryGetValue(key, out cachedImage)) return true; + if (_textureCache.TryGetValue(key, out cachedImage)) + { + return true; + } cachedImage = null; diff --git a/Ryujinx.Graphics/Gal/Shader/GlslDecl.cs b/Ryujinx.Graphics/Gal/Shader/GlslDecl.cs index 8893af3eb9..06411fa36f 100644 --- a/Ryujinx.Graphics/Gal/Shader/GlslDecl.cs +++ b/Ryujinx.Graphics/Gal/Shader/GlslDecl.cs @@ -108,13 +108,17 @@ namespace Ryujinx.Graphics.Gal.Shader int index = 0; for (int attachment = 0; attachment < 8; attachment++) - for (int component = 0; component < 4; component++) - if (header.OmapTargets[attachment].ComponentEnabled(component)) + { + for (int component = 0; component < 4; component++) + { + if (header.OmapTargets[attachment].ComponentEnabled(component)) { _gprs.TryAdd(index, new ShaderDeclInfo(GetGprName(index), index)); index++; } + } + } if (header.OmapDepth) { @@ -128,7 +132,10 @@ namespace Ryujinx.Graphics.Gal.Shader { ShaderIrNode[] nodes = block.GetNodes(); - foreach (ShaderIrNode node in nodes) Traverse(nodes, null, node); + foreach (ShaderIrNode node in nodes) + { + Traverse(nodes, null, node); + } } } @@ -146,15 +153,23 @@ namespace Ryujinx.Graphics.Gal.Shader Merge(combined._preds, vpA._preds, vpB._preds); //Merge input attributes. - foreach (KeyValuePair kv in vpA._inAttributes) combined._inAttributes.TryAdd(kv.Key, kv.Value); + foreach (KeyValuePair kv in vpA._inAttributes) + { + combined._inAttributes.TryAdd(kv.Key, kv.Value); + } foreach (KeyValuePair kv in vpB._inAttributes) - //If Vertex Program A already writes to this attribute, + { + //If Vertex Program A already writes to this attribute, //then we don't need to add it as an input attribute since //Vertex Program A will already have written to it anyway, //and there's no guarantee that there is an input attribute //for this slot. - if (!vpA._outAttributes.ContainsKey(kv.Key)) combined._inAttributes.TryAdd(kv.Key, kv.Value); + if (!vpA._outAttributes.ContainsKey(kv.Key)) + { + combined._inAttributes.TryAdd(kv.Key, kv.Value); + } + } return combined; } @@ -169,9 +184,15 @@ namespace Ryujinx.Graphics.Gal.Shader Dictionary a, Dictionary b) { - foreach (KeyValuePair kv in a) c.TryAdd(kv.Key, kv.Value); + foreach (KeyValuePair kv in a) + { + c.TryAdd(kv.Key, kv.Value); + } - foreach (KeyValuePair kv in b) c.TryAdd(kv.Key, kv.Value); + foreach (KeyValuePair kv in b) + { + c.TryAdd(kv.Key, kv.Value); + } } private void Traverse(ShaderIrNode[] nodes, ShaderIrNode parent, ShaderIrNode node) @@ -223,13 +244,15 @@ namespace Ryujinx.Graphics.Gal.Shader ShaderIrNode curr = nodes[index]; if (curr is ShaderIrAsg asg && asg.Dst is ShaderIrOperGpr gpr) - if (gpr.Index == ((ShaderIrOperGpr)op.OperandC).Index) + { + if (gpr.Index == ((ShaderIrOperGpr)op.OperandC).Index) { handleSrc = asg.Src; break; } - } + } + } if (handleSrc != null && handleSrc is ShaderIrOperCbuf cbuf) { @@ -268,16 +291,21 @@ namespace Ryujinx.Graphics.Gal.Shader abuf.Offs == VertexIdAttr || abuf.Offs == InstanceIdAttr || abuf.Offs == FaceAttr) - break; + { + break; + } - int index = abuf.Offs >> 4; + int index = abuf.Offs >> 4; int elem = (abuf.Offs >> 2) & 3; int glslIndex = index - AttrStartIndex; - if (glslIndex < 0) return; + if (glslIndex < 0) + { + return; + } - ShaderDeclInfo declInfo; + ShaderDeclInfo declInfo; if (parent is ShaderIrAsg asg && asg.Dst == node) { @@ -344,7 +372,12 @@ namespace Ryujinx.Graphics.Gal.Shader int vecIndex = index & ~3; if (decls.TryGetValue(vecIndex, out ShaderDeclInfo declInfo)) - if (declInfo.Size > 1 && index < vecIndex + declInfo.Size) return true; + { + if (declInfo.Size > 1 && index < vecIndex + declInfo.Size) + { + return true; + } + } return decls.ContainsKey(index); } diff --git a/Ryujinx.Graphics/Gal/Shader/GlslDecompiler.cs b/Ryujinx.Graphics/Gal/Shader/GlslDecompiler.cs index f8f252fa00..1d6be89de2 100644 --- a/Ryujinx.Graphics/Gal/Shader/GlslDecompiler.cs +++ b/Ryujinx.Graphics/Gal/Shader/GlslDecompiler.cs @@ -217,7 +217,10 @@ namespace Ryujinx.Graphics.Gal.Shader private void PrintDeclTextures() { - foreach (ShaderDeclInfo declInfo in IterateCbTextures()) _sb.AppendLine("uniform sampler2D " + declInfo.Name + ";"); + foreach (ShaderDeclInfo declInfo in IterateCbTextures()) + { + _sb.AppendLine("uniform sampler2D " + declInfo.Name + ";"); + } PrintDecls(_decl.Textures, "uniform sampler2D"); } @@ -227,7 +230,12 @@ namespace Ryujinx.Graphics.Gal.Shader HashSet names = new HashSet(); foreach (ShaderDeclInfo declInfo in _decl.CbTextures.Values.OrderBy(DeclKeySelector)) - if (names.Add(declInfo.Name)) yield return declInfo; + { + if (names.Add(declInfo.Name)) + { + yield return declInfo; + } + } } private void PrintDeclUniforms() @@ -256,7 +264,10 @@ namespace Ryujinx.Graphics.Gal.Shader _sb.AppendLine("};"); } - if (_decl.Uniforms.Count > 0) _sb.AppendLine(); + if (_decl.Uniforms.Count > 0) + { + _sb.AppendLine(); + } } private void PrintDeclAttributes() @@ -268,7 +279,10 @@ namespace Ryujinx.Graphics.Gal.Shader private void PrintDeclInAttributes() { - if (_decl.ShaderType == GalShaderType.Fragment) _sb.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") in vec4 " + GlslDecl.PositionOutAttrName + ";"); + if (_decl.ShaderType == GalShaderType.Fragment) + { + _sb.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") in vec4 " + GlslDecl.PositionOutAttrName + ";"); + } if (_decl.ShaderType == GalShaderType.Geometry) { @@ -277,7 +291,12 @@ namespace Ryujinx.Graphics.Gal.Shader _sb.AppendLine("in Vertex {"); foreach (ShaderDeclInfo declInfo in _decl.InAttributes.Values.OrderBy(DeclKeySelector)) - if (declInfo.Index >= 0) _sb.AppendLine(IdentationStr + "layout (location = " + declInfo.Index + ") vec4 " + declInfo.Name + "; "); + { + if (declInfo.Index >= 0) + { + _sb.AppendLine(IdentationStr + "layout (location = " + declInfo.Index + ") vec4 " + declInfo.Name + "; "); + } + } _sb.AppendLine("} block_in[];" + Environment.NewLine); } @@ -295,14 +314,19 @@ namespace Ryujinx.Graphics.Gal.Shader int count = 0; for (int attachment = 0; attachment < 8; attachment++) + { if (_header.OmapTargets[attachment].Enabled) { _sb.AppendLine("layout (location = " + attachment + ") out vec4 " + GlslDecl.FragmentOutputName + attachment + ";"); count++; } + } - if (count > 0) _sb.AppendLine(); + if (count > 0) + { + _sb.AppendLine(); + } } else { @@ -318,14 +342,19 @@ namespace Ryujinx.Graphics.Gal.Shader int count = 0; foreach (ShaderDeclInfo declInfo in decls.OrderBy(DeclKeySelector)) + { if (declInfo.Index >= 0) { _sb.AppendLine("layout (location = " + declInfo.Index + ") " + inOut + " vec4 " + declInfo.Name + ";"); count++; } + } - if (count > 0) _sb.AppendLine(); + if (count > 0) + { + _sb.AppendLine(); + } } private void PrintDeclGprs() @@ -352,16 +381,25 @@ namespace Ryujinx.Graphics.Gal.Shader string name; if (customType != null) + { name = customType + " " + declInfo.Name + suffix + ";"; + } else if (declInfo.Name.Contains(GlslDecl.FragmentOutputName)) + { name = "layout (location = " + declInfo.Index / 4 + ") out vec4 " + declInfo.Name + suffix + ";"; + } else + { name = GetDecl(declInfo) + suffix + ";"; + } _sb.AppendLine(name); } - if (dict.Count > 0) _sb.AppendLine(); + if (dict.Count > 0) + { + _sb.AppendLine(); + } } private int DeclKeySelector(ShaderDeclInfo declInfo) @@ -372,9 +410,13 @@ namespace Ryujinx.Graphics.Gal.Shader private string GetDecl(ShaderDeclInfo declInfo) { if (declInfo.Size == 4) + { return "vec4 " + declInfo.Name; + } else + { return "float " + declInfo.Name; + } } private void PrintMain() @@ -383,11 +425,15 @@ namespace Ryujinx.Graphics.Gal.Shader foreach (KeyValuePair kv in _decl.InAttributes) { - if (!_decl.Attributes.TryGetValue(kv.Key, out ShaderDeclInfo attr)) continue; + if (!_decl.Attributes.TryGetValue(kv.Key, out ShaderDeclInfo attr)) + { + continue; + } ShaderDeclInfo declInfo = kv.Value; if (_decl.ShaderType == GalShaderType.Geometry) + { for (int vertex = 0; vertex < MaxVertexInput; vertex++) { string dst = attr.Name + "[" + vertex + "]"; @@ -396,8 +442,11 @@ namespace Ryujinx.Graphics.Gal.Shader _sb.AppendLine(IdentationStr + dst + " = " + src + ";"); } + } else + { _sb.AppendLine(IdentationStr + attr.Name + " = " + declInfo.Name + ";"); + } } _sb.AppendLine(IdentationStr + "uint pc;"); @@ -412,11 +461,17 @@ namespace Ryujinx.Graphics.Gal.Shader PrintProgram(_blocks, GlslDecl.BasicBlockName); } - if (_decl.ShaderType != GalShaderType.Geometry) PrintAttrToOutput(); + if (_decl.ShaderType != GalShaderType.Geometry) + { + PrintAttrToOutput(); + } if (_decl.ShaderType == GalShaderType.Fragment) { - if (_header.OmapDepth) _sb.AppendLine(IdentationStr + "gl_FragDepth = " + GlslDecl.GetGprName(_header.DepthRegister) + ";"); + if (_header.OmapDepth) + { + _sb.AppendLine(IdentationStr + "gl_FragDepth = " + GlslDecl.GetGprName(_header.DepthRegister) + ";"); + } int gprIndex = 0; @@ -427,12 +482,14 @@ namespace Ryujinx.Graphics.Gal.Shader OmapTarget target = _header.OmapTargets[attachment]; for (int component = 0; component < 4; component++) + { if (target.ComponentEnabled(component)) { _sb.AppendLine(IdentationStr + output + "[" + component + "] = " + GlslDecl.GetGprName(gprIndex) + ";"); gprIndex++; } + } } } @@ -469,18 +526,27 @@ namespace Ryujinx.Graphics.Gal.Shader { foreach (KeyValuePair kv in _decl.OutAttributes) { - if (!_decl.Attributes.TryGetValue(kv.Key, out ShaderDeclInfo attr)) continue; + if (!_decl.Attributes.TryGetValue(kv.Key, out ShaderDeclInfo attr)) + { + continue; + } ShaderDeclInfo declInfo = kv.Value; string name = attr.Name; - if (_decl.ShaderType == GalShaderType.Geometry) name += "[0]"; + if (_decl.ShaderType == GalShaderType.Geometry) + { + name += "[0]"; + } _sb.AppendLine(identation + declInfo.Name + " = " + name + ";"); } - if (_decl.ShaderType == GalShaderType.Vertex) _sb.AppendLine(identation + "gl_Position.xy *= " + GlslDecl.FlipUniformName + ";"); + if (_decl.ShaderType == GalShaderType.Vertex) + { + _sb.AppendLine(identation + "gl_Position.xy *= " + GlslDecl.FlipUniformName + ";"); + } if (_decl.ShaderType != GalShaderType.Fragment) { @@ -503,7 +569,10 @@ namespace Ryujinx.Graphics.Gal.Shader private void PrintNodes(ShaderIrBlock block, ShaderIrNode[] nodes) { - foreach (ShaderIrNode node in nodes) PrintNode(block, node, IdentationStr); + foreach (ShaderIrNode node in nodes) + { + PrintNode(block, node, IdentationStr); + } if (nodes.Length == 0) { @@ -517,6 +586,7 @@ namespace Ryujinx.Graphics.Gal.Shader bool unconditionalFlowChange = false; if (last is ShaderIrOp op) + { switch (op.Inst) { case ShaderIrInst.Bra: @@ -525,13 +595,18 @@ namespace Ryujinx.Graphics.Gal.Shader unconditionalFlowChange = true; break; } + } if (!unconditionalFlowChange) { if (block.Next != null) + { _sb.AppendLine(IdentationStr + "return " + GetBlockPosition(block.Next) + ";"); + } else + { _sb.AppendLine(IdentationStr + "return 0u;"); + } } } @@ -541,7 +616,10 @@ namespace Ryujinx.Graphics.Gal.Shader { string ifExpr = GetSrcExpr(cond.Pred, true); - if (cond.Not) ifExpr = "!(" + ifExpr + ")"; + if (cond.Not) + { + ifExpr = "!(" + ifExpr + ")"; + } _sb.AppendLine(identation + "if (" + ifExpr + ") {"); @@ -625,8 +703,13 @@ namespace Ryujinx.Graphics.Gal.Shader private bool IsValidOutOper(ShaderIrNode node) { if (node is ShaderIrOperGpr gpr && gpr.IsConst) + { return false; - else if (node is ShaderIrOperPred pred && pred.IsConst) return false; + } + else if (node is ShaderIrOperPred pred && pred.IsConst) + { + return false; + } return true; } @@ -634,10 +717,17 @@ namespace Ryujinx.Graphics.Gal.Shader private string GetDstOperName(ShaderIrNode node) { if (node is ShaderIrOperAbuf abuf) + { return GetOutAbufName(abuf); + } else if (node is ShaderIrOperGpr gpr) + { return GetName(gpr); - else if (node is ShaderIrOperPred pred) return GetName(pred); + } + else if (node is ShaderIrOperPred pred) + { + return GetName(pred); + } throw new ArgumentException(nameof(node)); } @@ -657,11 +747,18 @@ namespace Ryujinx.Graphics.Gal.Shader string expr; if (_instsExpr.TryGetValue(op.Inst, out GetInstExpr getExpr)) + { expr = getExpr(op); + } else + { throw new NotImplementedException(op.Inst.ToString()); + } - if (!entry && NeedsParentheses(op)) expr = "(" + expr + ")"; + if (!entry && NeedsParentheses(op)) + { + expr = "(" + expr + ")"; + } return expr; @@ -685,7 +782,10 @@ namespace Ryujinx.Graphics.Gal.Shader private string GetName(ShaderIrOperCbuf cbuf) { - if (!_decl.Uniforms.TryGetValue(cbuf.Index, out ShaderDeclInfo declInfo)) throw new InvalidOperationException(); + if (!_decl.Uniforms.TryGetValue(cbuf.Index, out ShaderDeclInfo declInfo)) + { + throw new InvalidOperationException(); + } if (cbuf.Offs != null) { @@ -704,10 +804,12 @@ namespace Ryujinx.Graphics.Gal.Shader private string GetOutAbufName(ShaderIrOperAbuf abuf) { if (_decl.ShaderType == GalShaderType.Geometry) + { switch (abuf.Offs) { case GlslDecl.LayerAttr: return "gl_Layer"; } + } return GetAttrTempName(abuf); } @@ -716,19 +818,24 @@ namespace Ryujinx.Graphics.Gal.Shader { //Handle special scalar read-only attributes here. if (_decl.ShaderType == GalShaderType.Vertex) + { switch (abuf.Offs) { case GlslDecl.VertexIdAttr: return "gl_VertexID"; case GlslDecl.InstanceIdAttr: return GlslDecl.InstanceUniformName; } + } else if (_decl.ShaderType == GalShaderType.TessEvaluation) + { switch (abuf.Offs) { case GlslDecl.TessCoordAttrX: return "gl_TessCoord.x"; case GlslDecl.TessCoordAttrY: return "gl_TessCoord.y"; case GlslDecl.TessCoordAttrZ: return "gl_TessCoord.z"; } + } else if (_decl.ShaderType == GalShaderType.Fragment) + { switch (abuf.Offs) { case GlslDecl.PointCoordAttrX: return "gl_PointCoord.x"; @@ -737,6 +844,7 @@ namespace Ryujinx.Graphics.Gal.Shader //Note: It's a guess that Maxwell's face is 1 when gl_FrontFacing == true case GlslDecl.FaceAttr: return "(gl_FrontFacing ? 1 : 0)"; } + } return GetAttrTempName(abuf); } @@ -766,7 +874,10 @@ namespace Ryujinx.Graphics.Gal.Shader } } - if (declInfo.Index >= 16) throw new InvalidOperationException($"Shader attribute offset {abuf.Offs} is invalid."); + if (declInfo.Index >= 16) + { + throw new InvalidOperationException($"Shader attribute offset {abuf.Offs} is invalid."); + } if (_decl.ShaderType == GalShaderType.Geometry) { @@ -790,9 +901,13 @@ namespace Ryujinx.Graphics.Gal.Shader //Only use hex is the value is too big and would likely be hard to read as int. if (imm.Value > 0xfff || imm.Value < -0xfff) + { return "0x" + imm.Value.ToString("x8", CultureInfo.InvariantCulture); + } else + { return GetIntConst(imm.Value); + } } private string GetValue(ShaderIrOperImmf immf) @@ -810,9 +925,17 @@ namespace Ryujinx.Graphics.Gal.Shader int vecIndex = index & ~3; if (dict.TryGetValue(vecIndex, out ShaderDeclInfo declInfo)) - if (declInfo.Size > 1 && index < vecIndex + declInfo.Size) return declInfo.Name + "." + GetAttrSwizzle(index & 3); + { + if (declInfo.Size > 1 && index < vecIndex + declInfo.Size) + { + return declInfo.Name + "." + GetAttrSwizzle(index & 3); + } + } - if (!dict.TryGetValue(index, out declInfo)) throw new InvalidOperationException(); + if (!dict.TryGetValue(index, out declInfo)) + { + throw new InvalidOperationException(); + } return declInfo.Name; } @@ -1033,6 +1156,7 @@ namespace Ryujinx.Graphics.Gal.Shader int elem = (abuf.Offs >> 2) & 3; if (_decl.ShaderType == GalShaderType.Fragment && index == GlslDecl.GlPositionVec4Index) + { switch (elem) { case 0: return "gl_FragCoord.x"; @@ -1040,6 +1164,7 @@ namespace Ryujinx.Graphics.Gal.Shader case 2: return "gl_FragCoord.z"; case 3: return "1"; } + } } return GetSrcExpr(op.OperandA); @@ -1105,7 +1230,10 @@ namespace Ryujinx.Graphics.Gal.Shader { ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData; - if (!_decl.CbTextures.TryGetValue(op, out ShaderDeclInfo declInfo)) throw new InvalidOperationException(); + if (!_decl.CbTextures.TryGetValue(op, out ShaderDeclInfo declInfo)) + { + throw new InvalidOperationException(); + } string coords = GetTexSamplerCoords(op); @@ -1229,7 +1357,10 @@ namespace Ryujinx.Graphics.Gal.Shader int handle = ((ShaderIrOperImm)op.OperandC).Value; - if (!_decl.Textures.TryGetValue(handle, out ShaderDeclInfo declInfo)) throw new InvalidOperationException(); + if (!_decl.Textures.TryGetValue(handle, out ShaderDeclInfo declInfo)) + { + throw new InvalidOperationException(); + } return declInfo.Name; } @@ -1266,7 +1397,9 @@ namespace Ryujinx.Graphics.Gal.Shader //(like bool to int/float and others). if (srcType != OperType.F32 && srcType != OperType.I32) + { throw new InvalidOperationException(); + } switch (src) { @@ -1274,8 +1407,12 @@ namespace Ryujinx.Graphics.Gal.Shader { //When the Gpr is ZR, just return the 0 value directly, //since the float encoding for 0 is 0. - if (gpr.IsConst) return "0"; - break; + if (gpr.IsConst) + { + return "0"; + } + + break; } case ShaderIrOperImm imm: @@ -1286,8 +1423,11 @@ namespace Ryujinx.Graphics.Gal.Shader { float value = BitConverter.Int32BitsToSingle(imm.Value); - if (!float.IsNaN(value) && !float.IsInfinity(value)) return GetFloatConst(value); - } + if (!float.IsNaN(value) && !float.IsInfinity(value)) + { + return GetFloatConst(value); + } + } break; } } @@ -1321,6 +1461,7 @@ namespace Ryujinx.Graphics.Gal.Shader //Special case instructions with the result type different //from the input types (like integer <-> float conversion) here. if (node is ShaderIrOp op) + { switch (op.Inst) { case ShaderIrInst.Stof: @@ -1332,6 +1473,7 @@ namespace Ryujinx.Graphics.Gal.Shader case ShaderIrInst.Ftou: return OperType.I32; } + } return GetSrcNodeType(node); } @@ -1357,13 +1499,20 @@ namespace Ryujinx.Graphics.Gal.Shader case ShaderIrOp op: if (op.Inst > ShaderIrInst.BStart && op.Inst < ShaderIrInst.BEnd) + { return OperType.Bool; + } else if (op.Inst > ShaderIrInst.FStart && op.Inst < ShaderIrInst.FEnd) + { return OperType.F32; + } else if (op.Inst > ShaderIrInst.Start && op.Inst < ShaderIrInst.End) + { return OperType.I32; + } + break; } @@ -1373,9 +1522,13 @@ namespace Ryujinx.Graphics.Gal.Shader private static string GetBlockPosition(ShaderIrBlock block) { if (block != null) + { return "0x" + block.Position.ToString("x8") + "u"; + } else + { return "0u"; + } } } } diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeAlu.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeAlu.cs index 1cc1ef171b..436a829fb7 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeAlu.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeAlu.cs @@ -351,9 +351,15 @@ namespace Ryujinx.Graphics.Gal.Shader ShaderIrNode operA = opCode.Pred12(); ShaderIrNode operB = opCode.Pred29(); - if (negA) operA = new ShaderIrOp(ShaderIrInst.Bnot, operA); + if (negA) + { + operA = new ShaderIrOp(ShaderIrInst.Bnot, operA); + } - if (negB) operB = new ShaderIrOp(ShaderIrInst.Bnot, operB); + if (negB) + { + operB = new ShaderIrOp(ShaderIrInst.Bnot, operB); + } ShaderIrOp op = new ShaderIrOp(lopInst, operA, operB); @@ -365,11 +371,17 @@ namespace Ryujinx.Graphics.Gal.Shader lopInst = opCode.BLop45(); - if (lopInst == ShaderIrInst.Band && p1Node.IsConst && p2Node.IsConst) return; + if (lopInst == ShaderIrInst.Band && p1Node.IsConst && p2Node.IsConst) + { + return; + } ShaderIrNode p2NNode = p2Node; - if (negP) p2NNode = new ShaderIrOp(ShaderIrInst.Bnot, p2NNode); + if (negP) + { + p2NNode = new ShaderIrOp(ShaderIrInst.Bnot, p2NNode); + } op = new ShaderIrOp(ShaderIrInst.Bnot, p0Node); @@ -441,9 +453,13 @@ namespace Ryujinx.Graphics.Gal.Shader ShaderIrNode operB; if (opCode.Read(50)) + { operB = opCode.Gpr20(); + } else + { operB = opCode.Imm19_20(); + } ShaderIrOperGpr operC = opCode.Gpr39(); @@ -635,9 +651,13 @@ namespace Ryujinx.Graphics.Gal.Shader operB = GetAluFneg(operB, negB); if (oper == ShaderOper.Rc) + { operC = GetAluFneg(opCode.Cbuf34(), negC); + } else + { operC = GetAluFneg(opCode.Gpr39(), negC); + } ShaderIrOp op = new ShaderIrOp(ShaderIrInst.Ffma, operA, operB, operC); @@ -694,7 +714,10 @@ namespace Ryujinx.Graphics.Gal.Shader ShaderIrNode ApplyHeight(ShaderIrNode src, int height) { - if (oper != ShaderOper.Rr) return src; + if (oper != ShaderOper.Rr) + { + return src; + } switch (height) { @@ -713,11 +736,13 @@ namespace Ryujinx.Graphics.Gal.Shader ShaderIrOp sum = new ShaderIrOp(ShaderIrInst.Add, src1, src2); if (oper == ShaderOper.Rr) + { switch (mode) { case 1: sum = new ShaderIrOp(ShaderIrInst.Lsr, sum, new ShaderIrOperImm(16)); break; case 2: sum = new ShaderIrOp(ShaderIrInst.Lsl, sum, new ShaderIrOperImm(16)); break; } + } //Note: Here there should be a "+ 1" when carry flag is set //but since carry is mostly ignored by other instructions, it's excluded for now @@ -772,9 +797,13 @@ namespace Ryujinx.Graphics.Gal.Shader ShaderIrNode operA = opCode.Gpr8(), operB; if (isFloat) + { operA = GetAluFabsFneg(operA, absA, negA); + } else + { operA = GetAluIabsIneg(operA, absA, negA); + } switch (oper) { @@ -787,9 +816,13 @@ namespace Ryujinx.Graphics.Gal.Shader } if (isFloat) + { operB = GetAluFabsFneg(operB, absB, negB); + } else + { operB = GetAluIabsIneg(operB, absB, negB); + } ShaderIrOperPred pred = opCode.Pred39(); @@ -985,11 +1018,17 @@ namespace Ryujinx.Graphics.Gal.Shader ShaderIrInst lopInst = opCode.BLop45(); - if (lopInst == ShaderIrInst.Band && p1Node.IsConst && p2Node.IsConst) return; + if (lopInst == ShaderIrInst.Band && p1Node.IsConst && p2Node.IsConst) + { + return; + } ShaderIrNode p2NNode = p2Node; - if (negP) p2NNode = new ShaderIrOp(ShaderIrInst.Bnot, p2NNode); + if (negP) + { + p2NNode = new ShaderIrOp(ShaderIrInst.Bnot, p2NNode); + } op = new ShaderIrOp(ShaderIrInst.Bnot, p0Node); @@ -1035,9 +1074,13 @@ namespace Ryujinx.Graphics.Gal.Shader ShaderIrNode op; if (subOp < 3) + { op = new ShaderIrOp(inst, operA, operB); + } else + { op = operB; + } ShaderIrNode compare = new ShaderIrOp(ShaderIrInst.Cne, op, new ShaderIrOperImm(0)); @@ -1065,7 +1108,10 @@ namespace Ryujinx.Graphics.Gal.Shader ShaderIrInst shiftAb = signAb ? ShaderIrInst.Asr : ShaderIrInst.Lsr; ShaderIrInst shiftC = signC ? ShaderIrInst.Asr : ShaderIrInst.Lsr; - if (highA) operA = new ShaderIrOp(shiftAb, operA, imm16); + if (highA) + { + operA = new ShaderIrOp(shiftAb, operA, imm16); + } switch (oper) { @@ -1102,11 +1148,17 @@ namespace Ryujinx.Graphics.Gal.Shader ShaderIrNode operBh = operB; - if (highB) operBh = new ShaderIrOp(shiftAb, operBh, imm16); + if (highB) + { + operBh = new ShaderIrOp(shiftAb, operBh, imm16); + } ShaderIrOp mulOp = new ShaderIrOp(ShaderIrInst.Mul, operA, operBh); - if (productShiftLeft) mulOp = new ShaderIrOp(ShaderIrInst.Lsl, mulOp, imm16); + if (productShiftLeft) + { + mulOp = new ShaderIrOp(ShaderIrInst.Lsl, mulOp, imm16); + } ShaderIrOp addOp = new ShaderIrOp(ShaderIrInst.Add, mulOp, operC); diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeFlow.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeFlow.cs index 39be8872e9..e06597da8d 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeFlow.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeFlow.cs @@ -6,7 +6,10 @@ namespace Ryujinx.Graphics.Gal.Shader { public static void Bra(ShaderIrBlock block, long opCode, int position) { - if ((opCode & 0x20) != 0) throw new NotImplementedException(); + if ((opCode & 0x20) != 0) + { + throw new NotImplementedException(); + } ShaderIrOperImm imm = new ShaderIrOperImm(position + opCode.Branch()); @@ -18,7 +21,10 @@ namespace Ryujinx.Graphics.Gal.Shader int cCode = (int)opCode & 0x1f; //TODO: Figure out what the other condition codes mean... - if (cCode == 0xf) block.AddNode(opCode.PredNode(new ShaderIrOp(ShaderIrInst.Exit))); + if (cCode == 0xf) + { + block.AddNode(opCode.PredNode(new ShaderIrOp(ShaderIrInst.Exit))); + } } public static void Kil(ShaderIrBlock block, long opCode, int position) @@ -28,7 +34,10 @@ namespace Ryujinx.Graphics.Gal.Shader public static void Ssy(ShaderIrBlock block, long opCode, int position) { - if ((opCode & 0x20) != 0) throw new NotImplementedException(); + if ((opCode & 0x20) != 0) + { + throw new NotImplementedException(); + } ShaderIrOperImm imm = new ShaderIrOperImm(position + opCode.Branch()); diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMem.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMem.cs index 516a957edc..9568b3b620 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMem.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMem.cs @@ -56,7 +56,10 @@ namespace Ryujinx.Graphics.Gal.Shader int cbufIndex = opCode.Read(36, 0x1f); int type = opCode.Read(48, 7); - if (type > 5) throw new InvalidOperationException(); + if (type > 5) + { + throw new InvalidOperationException(); + } ShaderIrOperGpr temp = ShaderIrOperGpr.MakeTemporary(); @@ -73,7 +76,10 @@ namespace Ryujinx.Graphics.Gal.Shader operA.Pos += index; operD.Index += index; - if (!operD.IsValidRegister) break; + if (!operD.IsValidRegister) + { + break; + } ShaderIrNode node = operA; @@ -147,7 +153,10 @@ namespace Ryujinx.Graphics.Gal.Shader coords[index].Index += index; - if (coords[index].Index > ShaderIrOperGpr.ZrIndex) coords[index].Index = ShaderIrOperGpr.ZrIndex; + if (coords[index].Index > ShaderIrOperGpr.ZrIndex) + { + coords[index].Index = ShaderIrOperGpr.ZrIndex; + } } int chMask = opCode.Read(31, 0xf); @@ -173,7 +182,10 @@ namespace Ryujinx.Graphics.Gal.Shader for (int ch = 0; ch < 4; ch++) { - if (!IsChannelUsed(chMask, ch)) continue; + if (!IsChannelUsed(chMask, ch)) + { + continue; + } ShaderIrOperGpr src = new ShaderIrOperGpr(TempRegStart + ch); @@ -181,7 +193,10 @@ namespace Ryujinx.Graphics.Gal.Shader dst.Index += regInc++; - if (dst.Index >= ShaderIrOperGpr.ZrIndex) continue; + if (dst.Index >= ShaderIrOperGpr.ZrIndex) + { + continue; + } block.AddNode(opCode.PredNode(new ShaderIrAsg(dst, src))); } @@ -209,7 +224,10 @@ namespace Ryujinx.Graphics.Gal.Shader lutIndex = opCode.Gpr0 ().Index != ShaderIrOperGpr.ZrIndex ? 1 : 0; lutIndex |= opCode.Gpr28().Index != ShaderIrOperGpr.ZrIndex ? 2 : 0; - if (lutIndex == 0) return; + if (lutIndex == 0) + { + return; + } int chMask = _maskLut[lutIndex, opCode.Read(50, 7)]; @@ -248,13 +266,19 @@ namespace Ryujinx.Graphics.Gal.Shader for (int ch = 0; ch < 4; ch++) { - if (!IsChannelUsed(chMask, ch)) continue; + if (!IsChannelUsed(chMask, ch)) + { + continue; + } ShaderIrOperGpr src = new ShaderIrOperGpr(TempRegStart + ch); ShaderIrOperGpr dst = GetDst(); - if (dst.Index != ShaderIrOperGpr.ZrIndex) block.AddNode(opCode.PredNode(new ShaderIrAsg(dst, src))); + if (dst.Index != ShaderIrOperGpr.ZrIndex) + { + block.AddNode(opCode.PredNode(new ShaderIrAsg(dst, src))); + } } } diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMove.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMove.cs index 0f5ad2c9dd..c14cc4555b 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMove.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeMove.cs @@ -168,7 +168,10 @@ namespace Ryujinx.Graphics.Gal.Shader ShaderIrInst roundInst = GetRoundInst(opCode); - if (roundInst != ShaderIrInst.Invalid) operA = new ShaderIrOp(roundInst, operA); + if (roundInst != ShaderIrInst.Invalid) + { + operA = new ShaderIrOp(roundInst, operA); + } block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), operA))); } @@ -179,7 +182,9 @@ namespace Ryujinx.Graphics.Gal.Shader if (type == IntType.U64 || type == IntType.S64) + { throw new NotImplementedException(); + } bool negA = opCode.Read(45); bool absA = opCode.Read(49); @@ -199,7 +204,10 @@ namespace Ryujinx.Graphics.Gal.Shader ShaderIrInst roundInst = GetRoundInst(opCode); - if (roundInst != ShaderIrInst.Invalid) operA = new ShaderIrOp(roundInst, operA); + if (roundInst != ShaderIrInst.Invalid) + { + operA = new ShaderIrOp(roundInst, operA); + } bool signed = type >= IntType.S8; @@ -241,7 +249,9 @@ namespace Ryujinx.Graphics.Gal.Shader if (type == IntType.U64 || type == IntType.S64) + { throw new NotImplementedException(); + } int sel = opCode.Read(41, 3); @@ -267,9 +277,15 @@ namespace Ryujinx.Graphics.Gal.Shader int size = 8 << ((int)type & 3); - if (shift != 0) operA = new ShaderIrOp(ShaderIrInst.Asr, operA, new ShaderIrOperImm(shift)); + if (shift != 0) + { + operA = new ShaderIrOp(ShaderIrInst.Asr, operA, new ShaderIrOperImm(shift)); + } - if (size < 32) operA = ExtendTo32(operA, signed, size); + if (size < 32) + { + operA = ExtendTo32(operA, signed, size); + } ShaderIrInst inst = signed ? ShaderIrInst.Stof @@ -286,7 +302,9 @@ namespace Ryujinx.Graphics.Gal.Shader if (type == IntType.U64 || type == IntType.S64) + { throw new NotImplementedException(); + } int sel = opCode.Read(41, 3); @@ -313,7 +331,10 @@ namespace Ryujinx.Graphics.Gal.Shader int size = 8 << ((int)type & 3); - if (shift != 0) operA = new ShaderIrOp(ShaderIrInst.Asr, operA, new ShaderIrOperImm(shift)); + if (shift != 0) + { + operA = new ShaderIrOp(ShaderIrInst.Asr, operA, new ShaderIrOperImm(shift)); + } if (size < 32) { @@ -376,7 +397,10 @@ namespace Ryujinx.Graphics.Gal.Shader IntType type = (IntType)opCode.Read(10, 3); - if (signed) type += (int)IntType.S8; + if (signed) + { + type += (int)IntType.S8; + } return type; } diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeOpCode.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeOpCode.cs index 3ffdd2cc4d..92d1e06342 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeOpCode.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeOpCode.cs @@ -28,7 +28,10 @@ namespace Ryujinx.Graphics.Gal.Shader ShaderIrOperAbuf[] opers = new ShaderIrOperAbuf[size + 1]; - for (int index = 0; index <= size; index++) opers[index] = new ShaderIrOperAbuf(abuf + index * 4, vertex); + for (int index = 0; index <= size; index++) + { + opers[index] = new ShaderIrOperAbuf(abuf + index * 4, vertex); + } return opers; } @@ -98,7 +101,10 @@ namespace Ryujinx.Graphics.Gal.Shader bool neg = opCode.Read(56); - if (neg) value = -value; + if (neg) + { + value = -value; + } return new ShaderIrOperImm(value); } @@ -111,7 +117,10 @@ namespace Ryujinx.Graphics.Gal.Shader imm <<= 12; - if (neg) imm |= 0x80000000; + if (neg) + { + imm |= 0x80000000; + } float value = BitConverter.Int32BitsToSingle((int)imm); @@ -142,7 +151,10 @@ namespace Ryujinx.Graphics.Gal.Shader { ShaderIrNode node = opCode.Pred39(); - if (opCode.Read(42)) node = new ShaderIrOp(ShaderIrInst.Bnot, node); + if (opCode.Read(42)) + { + node = new ShaderIrOp(ShaderIrInst.Bnot, node); + } return node; } @@ -237,7 +249,10 @@ namespace Ryujinx.Graphics.Gal.Shader { int pred = opCode.Read(16, 0xf); - if (pred != 0xf) pred &= 7; + if (pred != 0xf) + { + pred &= 7; + } return new ShaderIrOperPred(pred); } diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeSpecial.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeSpecial.cs index b0a3e76d9a..5ed6545bb6 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecodeSpecial.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecodeSpecial.cs @@ -11,9 +11,15 @@ int type = opCode.Read(39, 3); - if ((type & 1) != 0) block.AddNode(opCode.PredNode(new ShaderIrOp(ShaderIrInst.Emit))); + if ((type & 1) != 0) + { + block.AddNode(opCode.PredNode(new ShaderIrOp(ShaderIrInst.Emit))); + } - if ((type & 2) != 0) block.AddNode(opCode.PredNode(new ShaderIrOp(ShaderIrInst.Cut))); + if ((type & 2) != 0) + { + block.AddNode(opCode.PredNode(new ShaderIrOp(ShaderIrInst.Cut))); + } } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderDecoder.cs b/Ryujinx.Graphics/Gal/Shader/ShaderDecoder.cs index 4dee39ec92..97d925067c 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderDecoder.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderDecoder.cs @@ -28,7 +28,10 @@ namespace Ryujinx.Graphics.Gal.Shader visited.Add(position, output); } - if (source != null) output.Sources.Add(source); + if (source != null) + { + output.Sources.Add(source); + } return output; } @@ -70,7 +73,10 @@ namespace Ryujinx.Graphics.Gal.Shader } } - if (NodeHasNext(lastNode)) current.Next = Enqueue(current.EndPosition); + if (NodeHasNext(lastNode)) + { + current.Next = Enqueue(current.EndPosition); + } } //If we have on the graph two blocks with the same end position, @@ -109,8 +115,12 @@ namespace Ryujinx.Graphics.Gal.Shader uint firstPos = uint.MaxValue; foreach (ShaderIrBlock block in visited.Values) + { if (firstPos > (uint)block.Position) + { firstPos = (uint)block.Position; + } + } ShaderIrBlock current = visited[(int)firstPos]; @@ -169,7 +179,10 @@ namespace Ryujinx.Graphics.Gal.Shader block.AddNode(new ShaderIrCmnt(dbgOpCode)); } - if (decode == null) continue; + if (decode == null) + { + continue; + } decode(block, opCode, position); } @@ -185,14 +198,20 @@ namespace Ryujinx.Graphics.Gal.Shader private static ShaderIrOp GetInnermostOp(ShaderIrNode node) { - if (node is ShaderIrCond cond) node = cond.Child; + if (node is ShaderIrCond cond) + { + node = cond.Child; + } return node is ShaderIrOp op ? op : null; } private static bool NodeHasNext(ShaderIrNode node) { - if (!(node is ShaderIrOp op)) return true; + if (!(node is ShaderIrOp op)) + { + return true; + } return op.Inst != ShaderIrInst.Exit && op.Inst != ShaderIrInst.Bra; diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderHeader.cs b/Ryujinx.Graphics/Gal/Shader/ShaderHeader.cs index bca1809f22..62162b073d 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderHeader.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderHeader.cs @@ -121,8 +121,15 @@ namespace Ryujinx.Graphics.Gal.Shader int count = 0; for (int index = 0; index < OmapTargets.Length; index++) - for (int component = 0; component < 4; component++) - if (OmapTargets[index].ComponentEnabled(component)) count++; + { + for (int component = 0; component < 4; component++) + { + if (OmapTargets[index].ComponentEnabled(component)) + { + count++; + } + } + } // Depth register is always two registers after the last color output return count + 1; diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderIrBlock.cs b/Ryujinx.Graphics/Gal/Shader/ShaderIrBlock.cs index 29b61a296e..484c1bafe7 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderIrBlock.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderIrBlock.cs @@ -35,7 +35,10 @@ namespace Ryujinx.Graphics.Gal.Shader public ShaderIrNode GetLastNode() { - if (Nodes.Count > 0) return Nodes[Nodes.Count - 1]; + if (Nodes.Count > 0) + { + return Nodes[Nodes.Count - 1]; + } return null; } diff --git a/Ryujinx.Graphics/Gal/Shader/ShaderOpCodeTable.cs b/Ryujinx.Graphics/Gal/Shader/ShaderOpCodeTable.cs index a13603f255..a06efcf8ef 100644 --- a/Ryujinx.Graphics/Gal/Shader/ShaderOpCodeTable.cs +++ b/Ryujinx.Graphics/Gal/Shader/ShaderOpCodeTable.cs @@ -130,7 +130,10 @@ namespace Ryujinx.Graphics.Gal.Shader private static void Set(string encoding, ShaderDecodeFunc func) { - if (encoding.Length != EncodingBits) throw new ArgumentException(nameof(encoding)); + if (encoding.Length != EncodingBits) + { + throw new ArgumentException(nameof(encoding)); + } int bit = encoding.Length - 1; int value = 0; @@ -163,9 +166,15 @@ namespace Ryujinx.Graphics.Gal.Shader { value &= xMask; - for (int x = 0; x < xBits; x++) value |= ((index >> x) & 1) << xPos[x]; + for (int x = 0; x < xBits; x++) + { + value |= ((index >> x) & 1) << xPos[x]; + } - if (_opCodes[value] == null || _opCodes[value].XBits > xBits) _opCodes[value] = entry; + if (_opCodes[value] == null || _opCodes[value].XBits > xBits) + { + _opCodes[value] = entry; + } } } diff --git a/Ryujinx.Graphics/Gal/ShaderDeclInfo.cs b/Ryujinx.Graphics/Gal/ShaderDeclInfo.cs index 572b2e2c9c..2b277d7b6e 100644 --- a/Ryujinx.Graphics/Gal/ShaderDeclInfo.cs +++ b/Ryujinx.Graphics/Gal/ShaderDeclInfo.cs @@ -25,7 +25,10 @@ namespace Ryujinx.Graphics.Gal internal void Enlarge(int newSize) { - if (Size < newSize) Size = newSize; + if (Size < newSize) + { + Size = newSize; + } } } } \ No newline at end of file diff --git a/Ryujinx.Graphics/Gal/ShaderDumper.cs b/Ryujinx.Graphics/Gal/ShaderDumper.cs index 4ca37e63e8..101a492edb 100644 --- a/Ryujinx.Graphics/Gal/ShaderDumper.cs +++ b/Ryujinx.Graphics/Gal/ShaderDumper.cs @@ -11,7 +11,10 @@ namespace Ryujinx.Graphics.Gal public static void Dump(IGalMemory memory, long position, GalShaderType type, string extSuffix = "") { - if (!IsDumpEnabled()) return; + if (!IsDumpEnabled()) + { + return; + } string fileName = "Shader" + DumpIndex.ToString("d4") + "." + ShaderExtension(type) + extSuffix + ".bin"; @@ -26,7 +29,10 @@ namespace Ryujinx.Graphics.Gal BinaryWriter fullWriter = new BinaryWriter(fullFile); BinaryWriter codeWriter = new BinaryWriter(codeFile); - for (long i = 0; i < 0x50; i += 4) fullWriter.Write(memory.ReadInt32(position + i)); + for (long i = 0; i < 0x50; i += 4) + { + fullWriter.Write(memory.ReadInt32(position + i)); + } long offset = 0; @@ -42,7 +48,10 @@ namespace Ryujinx.Graphics.Gal //Zero instructions (other kind of NOP) stop immediatly, //this is to avoid two rows of zeroes - if (instruction == 0) break; + if (instruction == 0) + { + break; + } fullWriter.Write(instruction); codeWriter.Write(instruction); @@ -98,7 +107,10 @@ namespace Ryujinx.Graphics.Gal private static string CreateAndReturn(string dir) { - if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); + if (!Directory.Exists(dir)) + { + Directory.CreateDirectory(dir); + } return dir; } diff --git a/Ryujinx.Graphics/GpuResourceManager.cs b/Ryujinx.Graphics/GpuResourceManager.cs index e33bc423ce..bb2c500dfa 100644 --- a/Ryujinx.Graphics/GpuResourceManager.cs +++ b/Ryujinx.Graphics/GpuResourceManager.cs @@ -27,7 +27,10 @@ namespace Ryujinx.Graphics _uploadedKeys = new HashSet[(int)NvGpuBufferType.Count]; - for (int index = 0; index < _uploadedKeys.Length; index++) _uploadedKeys[index] = new HashSet(); + for (int index = 0; index < _uploadedKeys.Length; index++) + { + _uploadedKeys[index] = new HashSet(); + } _imageTypes = new Dictionary(); } @@ -38,7 +41,10 @@ namespace Ryujinx.Graphics _imageTypes[position] = ImageType.ColorBuffer; - if (!TryReuse(vmm, position, newImage)) _gpu.Renderer.Texture.Create(position, (int)size, newImage); + if (!TryReuse(vmm, position, newImage)) + { + _gpu.Renderer.Texture.Create(position, (int)size, newImage); + } _gpu.Renderer.RenderTarget.BindColor(position, attachment); } @@ -49,7 +55,10 @@ namespace Ryujinx.Graphics _imageTypes[position] = ImageType.ZetaBuffer; - if (!TryReuse(vmm, position, newImage)) _gpu.Renderer.Texture.Create(position, (int)size, newImage); + if (!TryReuse(vmm, position, newImage)) + { + _gpu.Renderer.Texture.Create(position, (int)size, newImage); + } _gpu.Renderer.RenderTarget.BindZeta(position); } @@ -58,7 +67,10 @@ namespace Ryujinx.Graphics { PrepareSendTexture(vmm, position, newImage); - if (texIndex >= 0) _gpu.Renderer.Texture.Bind(position, texIndex, newImage); + if (texIndex >= 0) + { + _gpu.Renderer.Texture.Bind(position, texIndex, newImage); + } _imageTypes[position] = ImageType.Texture; } @@ -70,6 +82,7 @@ namespace Ryujinx.Graphics bool skipCheck = false; if (_imageTypes.TryGetValue(position, out ImageType oldType)) + { if (oldType == ImageType.ColorBuffer || oldType == ImageType.ZetaBuffer) { //Avoid data destruction @@ -77,9 +90,15 @@ namespace Ryujinx.Graphics skipCheck = true; } + } if (skipCheck || !MemoryRegionModified(vmm, position, size, NvGpuBufferType.Texture)) - if (TryReuse(vmm, position, newImage)) return; + { + if (TryReuse(vmm, position, newImage)) + { + return; + } + } byte[] data = ImageUtils.ReadTexture(vmm, newImage, position); @@ -102,14 +121,20 @@ namespace Ryujinx.Graphics { HashSet uploaded = _uploadedKeys[(int)type]; - if (!uploaded.Add(position)) return false; + if (!uploaded.Add(position)) + { + return false; + } return vmm.IsRegionModified(position, size, type); } public void ClearPbCache() { - for (int index = 0; index < _uploadedKeys.Length; index++) _uploadedKeys[index].Clear(); + for (int index = 0; index < _uploadedKeys.Length; index++) + { + _uploadedKeys[index].Clear(); + } } } } diff --git a/Ryujinx.Graphics/MacroInterpreter.cs b/Ryujinx.Graphics/MacroInterpreter.cs index b2f03fd36b..6c66dd8db3 100644 --- a/Ryujinx.Graphics/MacroInterpreter.cs +++ b/Ryujinx.Graphics/MacroInterpreter.cs @@ -79,7 +79,10 @@ namespace Ryujinx.Graphics FetchOpCode(mme); - while (Step(vmm, mme)); + while (Step(vmm, mme)) + { + ; + } //Due to the delay slot, we still need to execute //one more instruction before we actually exit. @@ -88,7 +91,10 @@ namespace Ryujinx.Graphics private void Reset() { - for (int index = 0; index < _gprs.Length; index++) _gprs[index] = 0; + for (int index = 0; index < _gprs.Length; index++) + { + _gprs[index] = 0; + } _methAddr = 0; _methIncr = 0; @@ -207,7 +213,10 @@ namespace Ryujinx.Graphics bool noDelays = (_opCode & 0x20) != 0; - if (noDelays) FetchOpCode(mme); + if (noDelays) + { + FetchOpCode(mme); + } return true; } @@ -385,7 +394,12 @@ namespace Ryujinx.Graphics //If we don't have any parameters in the FIFO, //keep running the PFIFO engine until it writes the parameters. while (!Fifo.TryDequeue(out value)) - if (!_pFifo.Step()) return 0; + { + if (!_pFifo.Step()) + { + return 0; + } + } return value; } diff --git a/Ryujinx.Graphics/Memory/NvGpuPushBuffer.cs b/Ryujinx.Graphics/Memory/NvGpuPushBuffer.cs index c427fafb63..76219c18a0 100644 --- a/Ryujinx.Graphics/Memory/NvGpuPushBuffer.cs +++ b/Ryujinx.Graphics/Memory/NvGpuPushBuffer.cs @@ -39,9 +39,12 @@ namespace Ryujinx.Graphics.Memory { case SubmissionMode.Incrementing: { - for (int index = 0; index < args && CanRead(); index++, meth++) pushBuffer.Add(new NvGpuPBEntry(meth, subC, reader.ReadInt32())); + for (int index = 0; index < args && CanRead(); index++, meth++) + { + pushBuffer.Add(new NvGpuPBEntry(meth, subC, reader.ReadInt32())); + } - break; + break; } case SubmissionMode.NonIncrementing: @@ -50,9 +53,12 @@ namespace Ryujinx.Graphics.Memory for (int index = 0; index < arguments.Length; index++) { - if (!CanRead()) break; + if (!CanRead()) + { + break; + } - arguments[index] = reader.ReadInt32(); + arguments[index] = reader.ReadInt32(); } pushBuffer.Add(new NvGpuPBEntry(meth, subC, arguments)); @@ -69,15 +75,21 @@ namespace Ryujinx.Graphics.Memory case SubmissionMode.IncrementOnce: { - if (CanRead()) pushBuffer.Add(new NvGpuPBEntry(meth, subC, reader.ReadInt32())); + if (CanRead()) + { + pushBuffer.Add(new NvGpuPBEntry(meth, subC, reader.ReadInt32())); + } - if (CanRead() && args > 1) + if (CanRead() && args > 1) { int[] arguments = new int[args - 1]; - for (int index = 0; index < arguments.Length && CanRead(); index++) arguments[index] = reader.ReadInt32(); + for (int index = 0; index < arguments.Length && CanRead(); index++) + { + arguments[index] = reader.ReadInt32(); + } - pushBuffer.Add(new NvGpuPBEntry(meth + 1, subC, arguments)); + pushBuffer.Add(new NvGpuPBEntry(meth + 1, subC, arguments)); } break; diff --git a/Ryujinx.Graphics/Memory/NvGpuVmm.cs b/Ryujinx.Graphics/Memory/NvGpuVmm.cs index 1fa01fc518..606cc7a3e6 100644 --- a/Ryujinx.Graphics/Memory/NvGpuVmm.cs +++ b/Ryujinx.Graphics/Memory/NvGpuVmm.cs @@ -45,7 +45,10 @@ namespace Ryujinx.Graphics.Memory { lock (_pageTable) { - for (long offset = 0; offset < size; offset += PageSize) SetPte(va + offset, pa + offset); + for (long offset = 0; offset < size; offset += PageSize) + { + SetPte(va + offset, pa + offset); + } } return va; @@ -58,7 +61,12 @@ namespace Ryujinx.Graphics.Memory long va = GetFreePosition(size); if (va != -1) - for (long offset = 0; offset < size; offset += PageSize) SetPte(va + offset, pa + offset); + { + for (long offset = 0; offset < size; offset += PageSize) + { + SetPte(va + offset, pa + offset); + } + } return va; } @@ -69,9 +77,17 @@ namespace Ryujinx.Graphics.Memory lock (_pageTable) { for (long offset = 0; offset < size; offset += PageSize) - if (IsPageInUse(va + offset)) return -1; + { + if (IsPageInUse(va + offset)) + { + return -1; + } + } - for (long offset = 0; offset < size; offset += PageSize) SetPte(va + offset, PteReserved); + for (long offset = 0; offset < size; offset += PageSize) + { + SetPte(va + offset, PteReserved); + } } return va; @@ -84,7 +100,12 @@ namespace Ryujinx.Graphics.Memory long position = GetFreePosition(size, align); if (position != -1) - for (long offset = 0; offset < size; offset += PageSize) SetPte(position + offset, PteReserved); + { + for (long offset = 0; offset < size; offset += PageSize) + { + SetPte(position + offset, PteReserved); + } + } return position; } @@ -94,7 +115,10 @@ namespace Ryujinx.Graphics.Memory { lock (_pageTable) { - for (long offset = 0; offset < size; offset += PageSize) SetPte(va + offset, PteUnmapped); + for (long offset = 0; offset < size; offset += PageSize) + { + SetPte(va + offset, PteUnmapped); + } } } @@ -105,16 +129,23 @@ namespace Ryujinx.Graphics.Memory long position = PageSize; long freeSize = 0; - if (align < 1) align = 1; + if (align < 1) + { + align = 1; + } align = (align + PageMask) & ~PageMask; while (position + freeSize < AddrSize) + { if (!IsPageInUse(position + freeSize)) { freeSize += PageSize; - if (freeSize >= size) return position; + if (freeSize >= size) + { + return position; + } } else { @@ -123,8 +154,12 @@ namespace Ryujinx.Graphics.Memory long remainder = position % align; - if (remainder != 0) position = position - remainder + align; + if (remainder != 0) + { + position = position - remainder + align; + } } + } return -1; } @@ -133,7 +168,10 @@ namespace Ryujinx.Graphics.Memory { long basePos = GetPte(va); - if (basePos < 0) return -1; + if (basePos < 0) + { + return -1; + } return basePos + (va & PageMask); } @@ -141,19 +179,30 @@ namespace Ryujinx.Graphics.Memory public bool IsRegionFree(long va, long size) { for (long offset = 0; offset < size; offset += PageSize) - if (IsPageInUse(va + offset)) return false; + { + if (IsPageInUse(va + offset)) + { + return false; + } + } return true; } private bool IsPageInUse(long va) { - if (va >> (PtLvl0Bits + PtLvl1Bits + PtPageBits) != 0) return false; + if (va >> (PtLvl0Bits + PtLvl1Bits + PtPageBits) != 0) + { + return false; + } long l0 = (va >> PtLvl0Bit) & PtLvl0Mask; long l1 = (va >> PtLvl1Bit) & PtLvl1Mask; - if (_pageTable[l0] == null) return false; + if (_pageTable[l0] == null) + { + return false; + } return _pageTable[l0][l1] != PteUnmapped; } @@ -163,7 +212,10 @@ namespace Ryujinx.Graphics.Memory long l0 = (position >> PtLvl0Bit) & PtLvl0Mask; long l1 = (position >> PtLvl1Bit) & PtLvl1Mask; - if (_pageTable[l0] == null) return -1; + if (_pageTable[l0] == null) + { + return -1; + } return _pageTable[l0][l1]; } @@ -177,7 +229,10 @@ namespace Ryujinx.Graphics.Memory { _pageTable[l0] = new long[PtLvl1Size]; - for (int index = 0; index < PtLvl1Size; index++) _pageTable[l0][index] = PteUnmapped; + for (int index = 0; index < PtLvl1Size; index++) + { + _pageTable[l0][index] = PteUnmapped; + } } _pageTable[l0][l1] = tgtAddr; diff --git a/Ryujinx.Graphics/Memory/NvGpuVmmCache.cs b/Ryujinx.Graphics/Memory/NvGpuVmmCache.cs index c90ec636aa..65f8217686 100644 --- a/Ryujinx.Graphics/Memory/NvGpuVmmCache.cs +++ b/Ryujinx.Graphics/Memory/NvGpuVmmCache.cs @@ -55,16 +55,26 @@ namespace Ryujinx.Graphics.Memory long rgEnd = Math.Min(current.End, newCached.End); if ((current.Value & mask) == 0) + { _cachedRanges.Add(new ValueRange(rgStart, rgEnd, current.Value | mask)); + } else + { coverage += rgEnd - rgStart; + } - if (rgStart > lastEnd) _cachedRanges.Add(new ValueRange(lastEnd, rgStart, mask)); + if (rgStart > lastEnd) + { + _cachedRanges.Add(new ValueRange(lastEnd, rgStart, mask)); + } lastEnd = rgEnd; } - if (lastEnd < newCached.End) _cachedRanges.Add(new ValueRange(lastEnd, newCached.End, mask)); + if (lastEnd < newCached.End) + { + _cachedRanges.Add(new ValueRange(lastEnd, newCached.End, mask)); + } return coverage != size; } diff --git a/Ryujinx.Graphics/NvGpuEngine2d.cs b/Ryujinx.Graphics/NvGpuEngine2d.cs index 153d2c0559..fe52ac3930 100644 --- a/Ryujinx.Graphics/NvGpuEngine2d.cs +++ b/Ryujinx.Graphics/NvGpuEngine2d.cs @@ -48,9 +48,13 @@ namespace Ryujinx.Graphics public void CallMethod(NvGpuVmm vmm, NvGpuPBEntry pbEntry) { if (_methods.TryGetValue(pbEntry.Method, out NvGpuMethod method)) + { method(vmm, pbEntry); + } else + { WriteRegister(pbEntry); + } } private void TextureCopy(NvGpuVmm vmm, NvGpuPBEntry pbEntry) @@ -134,7 +138,10 @@ namespace Ryujinx.Graphics { int argsCount = pbEntry.Arguments.Count; - if (argsCount > 0) Registers[pbEntry.Method] = pbEntry.Arguments[argsCount - 1]; + if (argsCount > 0) + { + Registers[pbEntry.Method] = pbEntry.Arguments[argsCount - 1]; + } } private int ReadRegister(NvGpuEngine2dReg reg) diff --git a/Ryujinx.Graphics/NvGpuEngine3d.cs b/Ryujinx.Graphics/NvGpuEngine3d.cs index 49363659bb..8d544cd48f 100644 --- a/Ryujinx.Graphics/NvGpuEngine3d.cs +++ b/Ryujinx.Graphics/NvGpuEngine3d.cs @@ -53,11 +53,17 @@ namespace Ryujinx.Graphics _constBuffers = new ConstBuffer[6][]; - for (int index = 0; index < _constBuffers.Length; index++) _constBuffers[index] = new ConstBuffer[18]; + for (int index = 0; index < _constBuffers.Length; index++) + { + _constBuffers[index] = new ConstBuffer[18]; + } _uploadedKeys = new List[(int)NvGpuBufferType.Count]; - for (int i = 0; i < _uploadedKeys.Length; i++) _uploadedKeys[i] = new List(); + for (int i = 0; i < _uploadedKeys.Length; i++) + { + _uploadedKeys[i] = new List(); + } //Ensure that all components are enabled by default. //FIXME: Is this correct? @@ -67,14 +73,21 @@ namespace Ryujinx.Graphics public void CallMethod(NvGpuVmm vmm, NvGpuPBEntry pbEntry) { if (_methods.TryGetValue(pbEntry.Method, out NvGpuMethod method)) + { method(vmm, pbEntry); + } else + { WriteRegister(pbEntry); + } } public void ResetCache() { - foreach (List uploaded in _uploadedKeys) uploaded.Clear(); + foreach (List uploaded in _uploadedKeys) + { + uploaded.Clear(); + } } private void VertexEndGl(NvGpuVmm vmm, NvGpuPBEntry pbEntry) @@ -92,7 +105,10 @@ namespace Ryujinx.Graphics SetColorMask(state); SetPrimitiveRestart(state); - for (int fbIndex = 0; fbIndex < 8; fbIndex++) SetFrameBuffer(vmm, fbIndex); + for (int fbIndex = 0; fbIndex < 8; fbIndex++) + { + SetFrameBuffer(vmm, fbIndex); + } SetZeta(vmm); @@ -328,11 +344,13 @@ namespace Ryujinx.Graphics //Flipping breaks facing. Flipping front facing too fixes it if (signX != signY) + { switch (frontFace) { case GalFrontFace.Cw: frontFace = GalFrontFace.Ccw; break; case GalFrontFace.Ccw: frontFace = GalFrontFace.Cw; break; } + } state.FrontFace = frontFace; } @@ -341,7 +359,10 @@ namespace Ryujinx.Graphics { state.CullFaceEnabled = ReadRegisterBool(NvGpuEngine3dReg.CullFaceEnable); - if (state.CullFaceEnabled) state.CullFace = (GalCullFace)ReadRegister(NvGpuEngine3dReg.CullFace); + if (state.CullFaceEnabled) + { + state.CullFace = (GalCullFace)ReadRegister(NvGpuEngine3dReg.CullFace); + } } private void SetDepth(GalPipelineState state) @@ -350,7 +371,10 @@ namespace Ryujinx.Graphics state.DepthWriteEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthWriteEnable); - if (state.DepthTestEnabled) state.DepthFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.DepthTestFunction); + if (state.DepthTestEnabled) + { + state.DepthFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.DepthTestFunction); + } state.DepthRangeNear = ReadRegisterFloat(NvGpuEngine3dReg.DepthRangeNNear); state.DepthRangeFar = ReadRegisterFloat(NvGpuEngine3dReg.DepthRangeNFar); @@ -419,7 +443,10 @@ namespace Ryujinx.Graphics { state.PrimitiveRestartEnabled = ReadRegisterBool(NvGpuEngine3dReg.PrimRestartEnable); - if (state.PrimitiveRestartEnabled) state.PrimitiveRestartIndex = (uint)ReadRegister(NvGpuEngine3dReg.PrimRestartIndex); + if (state.PrimitiveRestartEnabled) + { + state.PrimitiveRestartIndex = (uint)ReadRegister(NvGpuEngine3dReg.PrimRestartIndex); + } } private void SetRenderTargets() @@ -459,14 +486,19 @@ namespace Ryujinx.Graphics int texIndex = 0; for (int index = 0; index < keys.Length; index++) + { foreach (ShaderDeclInfo declInfo in _gpu.Renderer.Shader.GetTextureUsage(keys[index])) { long position; if (declInfo.IsCb) + { position = _constBuffers[index][declInfo.Cbuf].Position; + } else + { position = _constBuffers[index][textureCbIndex].Position; + } int textureHandle = vmm.ReadInt32(position + declInfo.Index * 4); @@ -474,11 +506,15 @@ namespace Ryujinx.Graphics texIndex++; } + } } private void UploadTexture(NvGpuVmm vmm, int texIndex, int textureHandle) { - if (textureHandle == 0) return; + if (textureHandle == 0) + { + return; + } int ticIndex = (textureHandle >> 0) & 0xfffff; int tscIndex = (textureHandle >> 20) & 0xfff; @@ -496,12 +532,20 @@ namespace Ryujinx.Graphics long key = vmm.ReadInt64(ticPosition + 4) & 0xffffffffffff; if (image.Layout == GalMemoryLayout.BlockLinear) + { key &= ~0x1ffL; - else if (image.Layout == GalMemoryLayout.Pitch) key &= ~0x1fL; + } + else if (image.Layout == GalMemoryLayout.Pitch) + { + key &= ~0x1fL; + } key = vmm.GetPhysicalAddress(key); - if (key == -1) return; + if (key == -1) + { + return; + } _gpu.ResourceManager.SendTexture(vmm, key, image, texIndex); @@ -511,11 +555,15 @@ namespace Ryujinx.Graphics private void UploadConstBuffers(NvGpuVmm vmm, GalPipelineState state, long[] keys) { for (int stage = 0; stage < keys.Length; stage++) + { foreach (ShaderDeclInfo declInfo in _gpu.Renderer.Shader.GetConstBufferUsage(keys[stage])) { ConstBuffer cb = _constBuffers[stage][declInfo.Cbuf]; - if (!cb.Enabled) continue; + if (!cb.Enabled) + { + continue; + } long key = vmm.GetPhysicalAddress(cb.Position); @@ -528,6 +576,7 @@ namespace Ryujinx.Graphics state.ConstBufferKeys[stage][declInfo.Cbuf] = key; } + } } private void UploadVertexArrays(NvGpuVmm vmm, GalPipelineState state) @@ -546,7 +595,10 @@ namespace Ryujinx.Graphics int indexEntrySize = 1 << indexEntryFmt; - if (indexEntrySize > 4) throw new InvalidOperationException(); + if (indexEntrySize > 4) + { + throw new InvalidOperationException(); + } if (indexCount != 0) { @@ -571,9 +623,13 @@ namespace Ryujinx.Graphics byte[] buffer = vmm.ReadBytes(ibPosition, ibSize); if (primType == GalPrimitiveType.Quads) + { buffer = QuadHelper.ConvertIbQuadsToTris(buffer, indexEntrySize, indexCount); + } else /* if (PrimType == GalPrimitiveType.QuadStrip) */ + { buffer = QuadHelper.ConvertIbQuadStripToTris(buffer, indexEntrySize, indexCount); + } _gpu.Renderer.Rasterizer.CreateIbo(iboKey, ibSize, buffer); } @@ -586,9 +642,13 @@ namespace Ryujinx.Graphics else { if (primType == GalPrimitiveType.Quads) + { _gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertIbSizeQuadsToTris(ibSize), indexFormat); + } else /* if (PrimType == GalPrimitiveType.QuadStrip) */ + { _gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertIbSizeQuadStripToTris(ibSize), indexFormat); + } } } @@ -600,7 +660,10 @@ namespace Ryujinx.Graphics int arrayIndex = packed & 0x1f; - if (attribs[arrayIndex] == null) attribs[arrayIndex] = new List(); + if (attribs[arrayIndex] == null) + { + attribs[arrayIndex] = new List(); + } long vertexPosition = MakeInt64From2XInt32(NvGpuEngine3dReg.VertexArrayNAddress + arrayIndex * 4); @@ -624,13 +687,19 @@ namespace Ryujinx.Graphics for (int index = 0; index < 32; index++) { - if (attribs[index] == null) continue; + if (attribs[index] == null) + { + continue; + } int control = ReadRegister(NvGpuEngine3dReg.VertexArrayNControl + index * 4); bool enable = (control & 0x1000) != 0; - if (!enable) continue; + if (!enable) + { + continue; + } long vertexPosition = MakeInt64From2XInt32(NvGpuEngine3dReg.VertexArrayNAddress + index * 4); long vertexEndPos = MakeInt64From2XInt32(NvGpuEngine3dReg.VertexArrayNEndAddr + index * 2); @@ -641,9 +710,15 @@ namespace Ryujinx.Graphics int stride = control & 0xfff; - if (instanced && vertexDivisor != 0) vertexPosition += stride * (_currentInstance / vertexDivisor); + if (instanced && vertexDivisor != 0) + { + vertexPosition += stride * (_currentInstance / vertexDivisor); + } - if (vertexPosition > vertexEndPos) continue; + if (vertexPosition > vertexEndPos) + { + continue; + } long vboKey = vmm.GetPhysicalAddress(vertexPosition); @@ -677,11 +752,19 @@ namespace Ryujinx.Graphics bool instanceNext = ((primCtrl >> 26) & 1) != 0; bool instanceCont = ((primCtrl >> 27) & 1) != 0; - if (instanceNext && instanceCont) throw new InvalidOperationException("GPU tried to increase and reset instance count at the same time"); + if (instanceNext && instanceCont) + { + throw new InvalidOperationException("GPU tried to increase and reset instance count at the same time"); + } if (instanceNext) + { _currentInstance++; - else if (!instanceCont) _currentInstance = 0; + } + else if (!instanceCont) + { + _currentInstance = 0; + } state.Instance = _currentInstance; @@ -711,9 +794,13 @@ namespace Ryujinx.Graphics //vertex of a quad, if it points to the middle of a //quad (First % 4 != 0 for Quads) then it will not work properly. if (primType == GalPrimitiveType.Quads) + { indexFirst = QuadHelper.ConvertIbSizeQuadsToTris(indexFirst); + } else /* if (PrimType == GalPrimitiveType.QuadStrip) */ + { indexFirst = QuadHelper.ConvertIbSizeQuadStripToTris(indexFirst); + } } _gpu.Renderer.Rasterizer.DrawElements(iboKey, indexFirst, vertexBase, primType); @@ -804,7 +891,10 @@ namespace Ryujinx.Graphics int size = ReadRegister(NvGpuEngine3dReg.ConstBufferSize); - if (!_gpu.Renderer.Buffer.IsCached(cbKey, size)) _gpu.Renderer.Buffer.Create(cbKey, size); + if (!_gpu.Renderer.Buffer.IsCached(cbKey, size)) + { + _gpu.Renderer.Buffer.Create(cbKey, size); + } ConstBuffer cb = _constBuffers[stage][index]; @@ -832,7 +922,10 @@ namespace Ryujinx.Graphics { int argsCount = pbEntry.Arguments.Count; - if (argsCount > 0) Registers[pbEntry.Method] = pbEntry.Arguments[argsCount - 1]; + if (argsCount > 0) + { + Registers[pbEntry.Method] = pbEntry.Arguments[argsCount - 1]; + } } private int ReadRegister(NvGpuEngine3dReg reg) @@ -859,7 +952,10 @@ namespace Ryujinx.Graphics { List uploaded = _uploadedKeys[(int)type]; - if (uploaded.Contains(key)) return false; + if (uploaded.Contains(key)) + { + return false; + } uploaded.Add(key); diff --git a/Ryujinx.Graphics/NvGpuEngineM2mf.cs b/Ryujinx.Graphics/NvGpuEngineM2mf.cs index 8f8616215f..b68ce5f76d 100644 --- a/Ryujinx.Graphics/NvGpuEngineM2mf.cs +++ b/Ryujinx.Graphics/NvGpuEngineM2mf.cs @@ -36,9 +36,13 @@ namespace Ryujinx.Graphics public void CallMethod(NvGpuVmm vmm, NvGpuPBEntry pbEntry) { if (_methods.TryGetValue(pbEntry.Method, out NvGpuMethod method)) + { method(vmm, pbEntry); + } else + { WriteRegister(pbEntry); + } } private void Execute(NvGpuVmm vmm, NvGpuPBEntry pbEntry) @@ -92,9 +96,15 @@ namespace Ryujinx.Graphics if (copy2D) { - if (srcLinear) srcPosX = srcPosY = srcPosZ = 0; + if (srcLinear) + { + srcPosX = srcPosY = srcPosZ = 0; + } - if (dstLinear) dstPosX = dstPosY = dstPosZ = 0; + if (dstLinear) + { + dstPosX = dstPosY = dstPosZ = 0; + } if (srcLinear && dstLinear) { @@ -114,19 +124,28 @@ namespace Ryujinx.Graphics ISwizzle srcSwizzle; if (srcLinear) + { srcSwizzle = new LinearSwizzle(srcPitch, srcCpp); + } else + { srcSwizzle = new BlockLinearSwizzle(srcSizeX, srcCpp, srcBlockHeight); + } ISwizzle dstSwizzle; if (dstLinear) + { dstSwizzle = new LinearSwizzle(dstPitch, dstCpp); + } else + { dstSwizzle = new BlockLinearSwizzle(dstSizeX, dstCpp, dstBlockHeight); + } for (int y = 0; y < yCount; y++) - for (int x = 0; x < xCount; x++) + { + for (int x = 0; x < xCount; x++) { int srcOffset = srcSwizzle.GetSwizzleOffset(srcPosX + x, srcPosY + y); int dstOffset = dstSwizzle.GetSwizzleOffset(dstPosX + x, dstPosY + y); @@ -136,6 +155,7 @@ namespace Ryujinx.Graphics vmm.Memory.CopyBytes(src, dst, srcCpp); } + } } } else @@ -155,7 +175,10 @@ namespace Ryujinx.Graphics { int argsCount = pbEntry.Arguments.Count; - if (argsCount > 0) Registers[pbEntry.Method] = pbEntry.Arguments[argsCount - 1]; + if (argsCount > 0) + { + Registers[pbEntry.Method] = pbEntry.Arguments[argsCount - 1]; + } } private int ReadRegister(NvGpuEngineM2mfReg reg) diff --git a/Ryujinx.Graphics/NvGpuEngineP2mf.cs b/Ryujinx.Graphics/NvGpuEngineP2mf.cs index 8d52d1b553..c6e0e4a379 100644 --- a/Ryujinx.Graphics/NvGpuEngineP2mf.cs +++ b/Ryujinx.Graphics/NvGpuEngineP2mf.cs @@ -39,9 +39,13 @@ namespace Ryujinx.Graphics public void CallMethod(NvGpuVmm vmm, NvGpuPBEntry pbEntry) { if (_methods.TryGetValue(pbEntry.Method, out NvGpuMethod method)) + { method(vmm, pbEntry); + } else + { WriteRegister(pbEntry); + } } private void Execute(NvGpuVmm vmm, NvGpuPBEntry pbEntry) @@ -57,7 +61,10 @@ namespace Ryujinx.Graphics _gpu.Fifo.Step(); - for (int offset = 0; offset < lineLengthIn; offset += 4) vmm.WriteInt32(dstAddress + offset, _dataBuffer[offset >> 2]); + for (int offset = 0; offset < lineLengthIn; offset += 4) + { + vmm.WriteInt32(dstAddress + offset, _dataBuffer[offset >> 2]); + } } private void PushData(NvGpuVmm vmm, NvGpuPBEntry pbEntry) @@ -76,7 +83,10 @@ namespace Ryujinx.Graphics { int argsCount = pbEntry.Arguments.Count; - if (argsCount > 0) Registers[pbEntry.Method] = pbEntry.Arguments[argsCount - 1]; + if (argsCount > 0) + { + Registers[pbEntry.Method] = pbEntry.Arguments[argsCount - 1]; + } } private int ReadRegister(NvGpuEngineP2mfReg reg) diff --git a/Ryujinx.Graphics/NvGpuFifo.cs b/Ryujinx.Graphics/NvGpuFifo.cs index afc2f4d821..eb8077e3b0 100644 --- a/Ryujinx.Graphics/NvGpuFifo.cs +++ b/Ryujinx.Graphics/NvGpuFifo.cs @@ -76,7 +76,10 @@ namespace Ryujinx.Graphics public void DispatchCalls() { - while (Step()); + while (Step()) + { + ; + } } private (NvGpuVmm Vmm, NvGpuPBEntry[] Pb) _curr; @@ -87,7 +90,10 @@ namespace Ryujinx.Graphics { while (_curr.Pb == null || _curr.Pb.Length <= _currPbEntryIndex) { - if (!_bufferQueue.TryDequeue(out _curr)) return false; + if (!_bufferQueue.TryDequeue(out _curr)) + { + return false; + } _gpu.Engine3D.ResetCache(); @@ -141,8 +147,12 @@ namespace Ryujinx.Graphics case NvGpuFifoMeth.SendMacroCodeData: { - foreach (int arg in pbEntry.Arguments) _mme[_currMacroPosition++] = arg; - break; + foreach (int arg in pbEntry.Arguments) + { + _mme[_currMacroPosition++] = arg; + } + + break; } case NvGpuFifoMeth.SetMacroBindingIndex: @@ -171,9 +181,16 @@ namespace Ryujinx.Graphics int macroIndex = (pbEntry.Method >> 1) & MacroIndexMask; if ((pbEntry.Method & 1) != 0) - foreach (int arg in pbEntry.Arguments) _macros[macroIndex].PushParam(arg); + { + foreach (int arg in pbEntry.Arguments) + { + _macros[macroIndex].PushParam(arg); + } + } else + { _macros[macroIndex].Execute(vmm, _mme, pbEntry.Arguments[0]); + } } } diff --git a/Ryujinx.Graphics/Texture/ASTCDecoder.cs b/Ryujinx.Graphics/Texture/ASTCDecoder.cs index 1abad2e086..45584132e3 100644 --- a/Ryujinx.Graphics/Texture/ASTCDecoder.cs +++ b/Ryujinx.Graphics/Texture/ASTCDecoder.cs @@ -29,7 +29,10 @@ namespace Ryujinx.Graphics.Texture // How many indices do we have? int indices = Height * Width; - if (DualPlane) indices *= 2; + if (DualPlane) + { + indices *= 2; + } IntegerEncoded intEncoded = IntegerEncoded.CreateEncoding(MaxWeight); @@ -40,7 +43,10 @@ namespace Ryujinx.Graphics.Texture { int ret = Width * Height; - if (DualPlane) ret *= 2; + if (DualPlane) + { + ret *= 2; + } return ret; } @@ -59,16 +65,23 @@ namespace Ryujinx.Graphics.Texture { BinaryReader binReader = new BinaryReader(inputStream); - if (blockX > 12 || blockY > 12) throw new ASTCDecoderException("Block size unsupported!"); + if (blockX > 12 || blockY > 12) + { + throw new ASTCDecoderException("Block size unsupported!"); + } - if (blockZ != 1 || z != 1) throw new ASTCDecoderException("3D compressed textures unsupported!"); + if (blockZ != 1 || z != 1) + { + throw new ASTCDecoderException("3D compressed textures unsupported!"); + } using (MemoryStream outputStream = new MemoryStream()) { int blockIndex = 0; for (int j = 0; j < y; j += blockY) - for (int i = 0; i < x; i += blockX) + { + for (int i = 0; i < x; i += blockX) { int[] decompressedData = new int[144]; @@ -90,6 +103,7 @@ namespace Ryujinx.Graphics.Texture blockIndex++; } + } return outputStream.ToArray(); } @@ -105,7 +119,10 @@ namespace Ryujinx.Graphics.Texture BitArrayStream bitStream = new BitArrayStream(new BitArray(inputBuffer)); TexelWeightParams texelParams = DecodeBlockInfo(bitStream); - if (texelParams.Error) throw new ASTCDecoderException("Invalid block mode"); + if (texelParams.Error) + { + throw new ASTCDecoderException("Invalid block mode"); + } if (texelParams.VoidExtentLdr) { @@ -114,17 +131,29 @@ namespace Ryujinx.Graphics.Texture return true; } - if (texelParams.VoidExtentHdr) throw new ASTCDecoderException("HDR void extent blocks are unsupported!"); + if (texelParams.VoidExtentHdr) + { + throw new ASTCDecoderException("HDR void extent blocks are unsupported!"); + } - if (texelParams.Width > blockWidth) throw new ASTCDecoderException("Texel weight grid width should be smaller than block width"); + if (texelParams.Width > blockWidth) + { + throw new ASTCDecoderException("Texel weight grid width should be smaller than block width"); + } - if (texelParams.Height > blockHeight) throw new ASTCDecoderException("Texel weight grid height should be smaller than block height"); + if (texelParams.Height > blockHeight) + { + throw new ASTCDecoderException("Texel weight grid height should be smaller than block height"); + } // Read num partitions int numberPartitions = bitStream.ReadBits(2) + 1; Debug.Assert(numberPartitions <= 4); - if (numberPartitions == 4 && texelParams.DualPlane) throw new ASTCDecoderException("Dual plane mode is incompatible with four partition blocks"); + if (numberPartitions == 4 && texelParams.DualPlane) + { + throw new ASTCDecoderException("Dual plane mode is incompatible with four partition blocks"); + } // Based on the number of partitions, read the color endpoint mode for // each partition. @@ -160,6 +189,7 @@ namespace Ryujinx.Graphics.Texture uint extraColorEndpointModeBits = 0; if (baseMode != 0) + { switch (numberPartitions) { case 2: extraColorEndpointModeBits += 2; break; @@ -167,13 +197,17 @@ namespace Ryujinx.Graphics.Texture case 4: extraColorEndpointModeBits += 8; break; default: Debug.Assert(false); break; } + } remainingBits -= (int)extraColorEndpointModeBits; // Do we have a dual plane situation? int planeSelectorBits = 0; - if (texelParams.DualPlane) planeSelectorBits = 2; + if (texelParams.DualPlane) + { + planeSelectorBits = 2; + } remainingBits -= planeSelectorBits; @@ -218,7 +252,11 @@ namespace Ryujinx.Graphics.Texture for (int i = 0; i < numberPartitions; i++) { colorEndpointMode[i] = baseMode; - if (!c[i]) colorEndpointMode[i] -= 1; + if (!c[i]) + { + colorEndpointMode[i] -= 1; + } + colorEndpointMode[i] <<= 2; colorEndpointMode[i] |= m[i]; } @@ -227,11 +265,18 @@ namespace Ryujinx.Graphics.Texture { uint tempColorEndpointMode = baseColorEndpointMode >> 2; - for (uint i = 0; i < numberPartitions; i++) colorEndpointMode[i] = tempColorEndpointMode; + for (uint i = 0; i < numberPartitions; i++) + { + colorEndpointMode[i] = tempColorEndpointMode; + } } // Make sure everything up till here is sane. - for (int i = 0; i < numberPartitions; i++) Debug.Assert(colorEndpointMode[i] < 16); + for (int i = 0; i < numberPartitions; i++) + { + Debug.Assert(colorEndpointMode[i] < 16); + } + Debug.Assert(bitStream.Position + texelParams.GetPackedBitSize() == 128); // Decode both color data and texel weight data @@ -246,7 +291,10 @@ namespace Ryujinx.Graphics.Texture int colorValuesPosition = 0; - for (int i = 0; i < numberPartitions; i++) ComputeEndpoints(endPoints[i], colorValues, colorEndpointMode[i], ref colorValuesPosition); + for (int i = 0; i < numberPartitions; i++) + { + ComputeEndpoints(endPoints[i], colorValues, colorEndpointMode[i], ref colorValuesPosition); + } // Read the texel weight data. byte[] texelWeightData = (byte[])inputBuffer.Clone(); @@ -266,7 +314,10 @@ namespace Ryujinx.Graphics.Texture texelWeightData[clearByteStart - 1] &= (byte)((1 << (texelParams.GetPackedBitSize() % 8)) - 1); int cLen = 16 - clearByteStart; - for (int i = clearByteStart; i < clearByteStart + cLen; i++) texelWeightData[i] = 0; + for (int i = clearByteStart; i < clearByteStart + cLen; i++) + { + texelWeightData[i] = 0; + } List texelWeightValues = new List(); BitArrayStream weightBitStream = new BitArrayStream(new BitArray(texelWeightData)); @@ -283,7 +334,8 @@ namespace Ryujinx.Graphics.Texture // Now that we have endpoints and weights, we can interpolate and generate // the proper decoding... for (int j = 0; j < blockHeight; j++) - for (int i = 0; i < blockWidth; i++) + { + for (int i = 0; i < blockWidth; i++) { int partition = Select2DPartition(partitionIndex, i, j, numberPartitions, blockHeight * blockWidth < 32); Debug.Assert(partition < numberPartitions); @@ -298,9 +350,12 @@ namespace Ryujinx.Graphics.Texture int plane = 0; - if (texelParams.DualPlane && ((planeIndices + 1) & 3) == component) plane = 1; + if (texelParams.DualPlane && ((planeIndices + 1) & 3) == component) + { + plane = 1; + } - int weight = weights[plane][j * blockWidth + i]; + int weight = weights[plane][j * blockWidth + i]; int finalComponent = (component0 * (64 - weight) + component1 * weight + 32) / 64; if (finalComponent == 65535) @@ -316,6 +371,7 @@ namespace Ryujinx.Graphics.Texture outputBuffer[j * blockWidth + i] = pixel.Pack(); } + } return true; } @@ -327,7 +383,10 @@ namespace Ryujinx.Graphics.Texture private static int SelectPartition(int seed, int x, int y, int z, int partitionCount, bool isSmallBlock) { - if (partitionCount == 1) return 0; + if (partitionCount == 1) + { + return 0; + } if (isSmallBlock) { @@ -385,12 +444,29 @@ namespace Ryujinx.Graphics.Texture a &= 0x3F; b &= 0x3F; c &= 0x3F; d &= 0x3F; - if (partitionCount < 4) d = 0; - if (partitionCount < 3) c = 0; + if (partitionCount < 4) + { + d = 0; + } + + if (partitionCount < 3) + { + c = 0; + } + + if (a >= b && a >= c && a >= d) + { + return 0; + } + else if (b >= c && b >= d) + { + return 1; + } + else if (c >= d) + { + return 2; + } - if (a >= b && a >= c && a >= d) return 0; - else if (b >= c && b >= d) return 1; - else if (c >= d) return 2; return 3; } @@ -424,10 +500,16 @@ namespace Ryujinx.Graphics.Texture i++; unquantized[1][weightIndices] = UnquantizeTexelWeight(weights[i]); - if (i == weights.Count) break; + if (i == weights.Count) + { + break; + } } - if (++weightIndices >= texelParams.Width * texelParams.Height) break; + if (++weightIndices >= texelParams.Width * texelParams.Height) + { + break; + } } // Do infill if necessary (Section C.2.18) ... @@ -437,8 +519,10 @@ namespace Ryujinx.Graphics.Texture int planeScale = texelParams.DualPlane ? 2 : 1; for (int plane = 0; plane < planeScale; plane++) - for (int t = 0; t < blockHeight; t++) - for (int s = 0; s < blockWidth; s++) + { + for (int t = 0; t < blockHeight; t++) + { + for (int s = 0; s < blockWidth; s++) { int cs = ds * s; int ct = dt * t; @@ -464,15 +548,29 @@ namespace Ryujinx.Graphics.Texture int p10 = 0; int p11 = 0; - if (v0 < texelParams.Width * texelParams.Height) p00 = unquantized[plane][v0]; + if (v0 < texelParams.Width * texelParams.Height) + { + p00 = unquantized[plane][v0]; + } - if (v0 + 1 < texelParams.Width * texelParams.Height) p01 = unquantized[plane][v0 + 1]; + if (v0 + 1 < texelParams.Width * texelParams.Height) + { + p01 = unquantized[plane][v0 + 1]; + } - if (v0 + texelParams.Width < texelParams.Width * texelParams.Height) p10 = unquantized[plane][v0 + texelParams.Width]; + if (v0 + texelParams.Width < texelParams.Width * texelParams.Height) + { + p10 = unquantized[plane][v0 + texelParams.Width]; + } - if (v0 + texelParams.Width + 1 < texelParams.Width * texelParams.Height) p11 = unquantized[plane][v0 + texelParams.Width + 1]; + if (v0 + texelParams.Width + 1 < texelParams.Width * texelParams.Height) + { + p11 = unquantized[plane][v0 + texelParams.Width + 1]; + } - outputBuffer[plane][t * blockWidth + s] = (p00 * w00 + p01 * w01 + p10 * w10 + p11 * w11 + 8) >> 4; + outputBuffer[plane][t * blockWidth + s] = (p00 * w00 + p01 * w01 + p10 * w10 + p11 * w11 + 8) >> 4; + } + } } } @@ -588,7 +686,10 @@ namespace Ryujinx.Graphics.Texture Debug.Assert(result < 64); // Change from [0,63] to [0,64] - if (result > 32) result += 1; + if (result > 32) + { + result += 1; + } return result; } @@ -603,7 +704,10 @@ namespace Ryujinx.Graphics.Texture { uint[] ret = new uint[number]; - for (int i = 0; i < number; i++) ret[i] = (uint)colorValues[colorValuesPosition++]; + for (int i = 0; i < number; i++) + { + ret[i] = (uint)colorValues[colorValuesPosition++]; + } return ret; } @@ -612,7 +716,10 @@ namespace Ryujinx.Graphics.Texture { int[] ret = new int[number]; - for (int i = 0; i < number; i++) ret[i] = colorValues[colorValuesPosition++]; + for (int i = 0; i < number; i++) + { + ret[i] = colorValues[colorValuesPosition++]; + } return ret; } @@ -796,7 +903,10 @@ namespace Ryujinx.Graphics.Texture // First figure out how many color values we have int numberValues = 0; - for (int i = 0; i < numberPartitions; i++) numberValues += (int)((modes[i] >> 2) + 1) << 1; + for (int i = 0; i < numberPartitions; i++) + { + numberValues += (int)((modes[i] >> 2) + 1) << 1; + } // Then based on the number of values and the remaining number of bits, // figure out the max value for each of them... @@ -813,7 +923,10 @@ namespace Ryujinx.Graphics.Texture while (--range > 0) { IntegerEncoded newIntEncoded = IntegerEncoded.CreateEncoding(range); - if (!newIntEncoded.MatchesEncoding(intEncoded)) break; + if (!newIntEncoded.MatchesEncoding(intEncoded)) + { + break; + } } // Return to last matching range. @@ -994,13 +1107,19 @@ namespace Ryujinx.Graphics.Texture } // Make sure that each of our values is in the proper range... - for (int i = 0; i < numberValues; i++) Debug.Assert(outputValues[i] <= 255); + for (int i = 0; i < numberValues; i++) + { + Debug.Assert(outputValues[i] <= 255); + } } private static void FillVoidExtentLdr(BitArrayStream bitStream, int[] outputBuffer, int blockWidth, int blockHeight) { // Don't actually care about the void extent, just read the bits... - for (int i = 0; i < 4; ++i) bitStream.ReadBits(13); + for (int i = 0; i < 4; ++i) + { + bitStream.ReadBits(13); + } // Decode the RGBA components and renormalize them to the range [0, 255] ushort r = (ushort)bitStream.ReadBits(16); @@ -1011,7 +1130,12 @@ namespace Ryujinx.Graphics.Texture int rgba = (r >> 8) | (g & 0xFF00) | ((b & 0xFF00) << 8) | ((a & 0xFF00) << 16); for (int j = 0; j < blockHeight; j++) - for (int i = 0; i < blockWidth; i++) outputBuffer[j * blockWidth + i] = rgba; + { + for (int i = 0; i < blockWidth; i++) + { + outputBuffer[j * blockWidth + i] = rgba; + } + } } private static TexelWeightParams DecodeBlockInfo(BitArrayStream bitStream) @@ -1025,12 +1149,19 @@ namespace Ryujinx.Graphics.Texture if ((modeBits & 0x01FF) == 0x1FC) { if ((modeBits & 0x200) != 0) + { texelParams.VoidExtentHdr = true; + } else + { texelParams.VoidExtentLdr = true; + } // Next two bits must be one. - if ((modeBits & 0x400) == 0 || bitStream.ReadBits(1) == 0) texelParams.Error = true; + if ((modeBits & 0x400) == 0 || bitStream.ReadBits(1) == 0) + { + texelParams.Error = true; + } return texelParams; } @@ -1067,9 +1198,13 @@ namespace Ryujinx.Graphics.Texture { // layout is in [3-4] if ((modeBits & 0x100) != 0) + { layout = 4; + } else + { layout = 3; + } } else { @@ -1080,9 +1215,13 @@ namespace Ryujinx.Graphics.Texture { // layout is in [0-1] if ((modeBits & 0x4) != 0) + { layout = 1; + } else + { layout = 0; + } } } else @@ -1097,9 +1236,13 @@ namespace Ryujinx.Graphics.Texture Debug.Assert((modeBits & 0x40) == 0); if ((modeBits & 0x20) != 0) + { layout = 8; + } else + { layout = 7; + } } else { @@ -1110,9 +1253,13 @@ namespace Ryujinx.Graphics.Texture { // layout is in [5-6] if ((modeBits & 0x80) != 0) + { layout = 6; + } else + { layout = 5; + } } } @@ -1121,9 +1268,13 @@ namespace Ryujinx.Graphics.Texture // Determine R int r = (modeBits >> 4) & 1; if (layout < 5) + { r |= (modeBits & 0x3) << 1; + } else + { r |= (modeBits & 0xC) >> 1; + } Debug.Assert(2 <= r && r <= 7); diff --git a/Ryujinx.Graphics/Texture/ASTCPixel.cs b/Ryujinx.Graphics/Texture/ASTCPixel.cs index f6c1088584..2a4e0f99cc 100644 --- a/Ryujinx.Graphics/Texture/ASTCPixel.cs +++ b/Ryujinx.Graphics/Texture/ASTCPixel.cs @@ -20,7 +20,9 @@ namespace Ryujinx.Graphics.Texture B = b; for (int i = 0; i < 4; i++) + { _bitDepth[i] = 8; + } } public void ClampByte() diff --git a/Ryujinx.Graphics/Texture/BitArrayStream.cs b/Ryujinx.Graphics/Texture/BitArrayStream.cs index ebca18963c..15ef3cf04a 100644 --- a/Ryujinx.Graphics/Texture/BitArrayStream.cs +++ b/Ryujinx.Graphics/Texture/BitArrayStream.cs @@ -19,7 +19,12 @@ namespace Ryujinx.Graphics.Texture { int retValue = 0; for (int i = Position; i < Position + length; i++) - if (BitsArray[i]) retValue |= 1 << (i - Position); + { + if (BitsArray[i]) + { + retValue |= 1 << (i - Position); + } + } Position += length; return (short)retValue; @@ -29,7 +34,12 @@ namespace Ryujinx.Graphics.Texture { int retValue = 0; for (int i = start; i <= end; i++) - if (BitsArray[i]) retValue |= 1 << (i - start); + { + if (BitsArray[i]) + { + retValue |= 1 << (i - start); + } + } return retValue; } @@ -41,7 +51,10 @@ namespace Ryujinx.Graphics.Texture public void WriteBits(int value, int length) { - for (int i = Position; i < Position + length; i++) BitsArray[i] = ((value >> (i - Position)) & 1) != 0; + for (int i = Position; i < Position + length; i++) + { + BitsArray[i] = ((value >> (i - Position)) & 1) != 0; + } Position += length; } @@ -55,8 +68,15 @@ namespace Ryujinx.Graphics.Texture public static int Replicate(int value, int numberBits, int toBit) { - if (numberBits == 0) return 0; - if (toBit == 0) return 0; + if (numberBits == 0) + { + return 0; + } + + if (toBit == 0) + { + return 0; + } int tempValue = value & ((1 << numberBits) - 1); int retValue = tempValue; @@ -81,7 +101,11 @@ namespace Ryujinx.Graphics.Texture public static int PopCnt(int number) { int counter; - for (counter = 0; number != 0; counter++) number &= number - 1; + for (counter = 0; number != 0; counter++) + { + number &= number - 1; + } + return counter; } @@ -99,7 +123,10 @@ namespace Ryujinx.Graphics.Texture b |= a & 0x80; a >>= 1; a &= 0x3F; - if ((a & 0x20) != 0) a -= 0x40; + if ((a & 0x20) != 0) + { + a -= 0x40; + } } } } diff --git a/Ryujinx.Graphics/Texture/BlockLinearSwizzle.cs b/Ryujinx.Graphics/Texture/BlockLinearSwizzle.cs index d4079e753d..4e3d646033 100644 --- a/Ryujinx.Graphics/Texture/BlockLinearSwizzle.cs +++ b/Ryujinx.Graphics/Texture/BlockLinearSwizzle.cs @@ -29,7 +29,10 @@ namespace Ryujinx.Graphics.Texture { int count = 0; - while (((value >> count) & 1) == 0) count++; + while (((value >> count) & 1) == 0) + { + count++; + } return count; } diff --git a/Ryujinx.Graphics/Texture/ImageUtils.cs b/Ryujinx.Graphics/Texture/ImageUtils.cs index 584f363a3c..972e6c3b81 100644 --- a/Ryujinx.Graphics/Texture/ImageUtils.cs +++ b/Ryujinx.Graphics/Texture/ImageUtils.cs @@ -144,15 +144,24 @@ namespace Ryujinx.Graphics.Texture GalTextureType aType, bool convSrgb) { - if (rType != gType || rType != bType || rType != aType) throw new NotImplementedException("Per component types are not implemented!"); + if (rType != gType || rType != bType || rType != aType) + { + throw new NotImplementedException("Per component types are not implemented!"); + } - if (!_textureTable.TryGetValue(format, out GalImageFormat imageFormat)) throw new NotImplementedException($"Format 0x{(int)format:x} not implemented!"); + if (!_textureTable.TryGetValue(format, out GalImageFormat imageFormat)) + { + throw new NotImplementedException($"Format 0x{(int)format:x} not implemented!"); + } GalImageFormat formatType = convSrgb ? Srgb : GetFormatType(rType); GalImageFormat combinedFormat = (imageFormat & GalImageFormat.FormatMask) | formatType; - if (!imageFormat.HasFlag(formatType)) throw new NotImplementedException($"Format \"{combinedFormat}\" not implemented!"); + if (!imageFormat.HasFlag(formatType)) + { + throw new NotImplementedException($"Format \"{combinedFormat}\" not implemented!"); + } return combinedFormat; } @@ -212,9 +221,13 @@ namespace Ryujinx.Graphics.Texture AMemory cpuMemory; if (memory is NvGpuVmm vmm) + { cpuMemory = vmm.Memory; + } else + { cpuMemory = (AMemory)memory; + } ISwizzle swizzle = TextureHelper.GetSwizzle(image); @@ -259,7 +272,8 @@ namespace Ryujinx.Graphics.Texture int inOffs = 0; for (int y = 0; y < height; y++) - for (int x = 0; x < width; x++) + { + for (int x = 0; x < width; x++) { long offset = (uint)swizzle.GetSwizzleOffset(x, y); @@ -267,6 +281,7 @@ namespace Ryujinx.Graphics.Texture inOffs += bytesPerPixel; } + } } public static int GetSize(GalImage image) @@ -307,9 +322,13 @@ namespace Ryujinx.Graphics.Texture int alignMask; if (image.Layout == GalMemoryLayout.BlockLinear) + { alignMask = image.TileWidth * (64 / desc.BytesPerPixel) - 1; + } else + { alignMask = 32 / desc.BytesPerPixel - 1; + } return (image.Width + alignMask) & ~alignMask; } @@ -358,7 +377,10 @@ namespace Ryujinx.Graphics.Texture { GalImageFormat pixelFormat = format & GalImageFormat.FormatMask; - if (_imageTable.TryGetValue(pixelFormat, out ImageDescriptor descriptor)) return descriptor; + if (_imageTable.TryGetValue(pixelFormat, out ImageDescriptor descriptor)) + { + return descriptor; + } throw new NotImplementedException($"Format \"{pixelFormat}\" not implemented!"); } diff --git a/Ryujinx.Graphics/Texture/IntegerEncoded.cs b/Ryujinx.Graphics/Texture/IntegerEncoded.cs index e2ab599016..54a3334606 100644 --- a/Ryujinx.Graphics/Texture/IntegerEncoded.cs +++ b/Ryujinx.Graphics/Texture/IntegerEncoded.cs @@ -41,8 +41,14 @@ namespace Ryujinx.Graphics.Texture { int totalBits = NumberBits * numberVals; if (_encoding == EIntegerEncoding.Trit) + { totalBits += (numberVals * 8 + 4) / 5; - else if (_encoding == EIntegerEncoding.Quint) totalBits += (numberVals * 7 + 2) / 3; + } + else if (_encoding == EIntegerEncoding.Quint) + { + totalBits += (numberVals * 7 + 2) / 3; + } + return totalBits; } @@ -53,13 +59,22 @@ namespace Ryujinx.Graphics.Texture int check = maxVal + 1; // Is maxVal a power of two? - if ((check & (check - 1)) == 0) return new IntegerEncoded(EIntegerEncoding.JustBits, BitArrayStream.PopCnt(maxVal)); + if ((check & (check - 1)) == 0) + { + return new IntegerEncoded(EIntegerEncoding.JustBits, BitArrayStream.PopCnt(maxVal)); + } // Is maxVal of the type 3*2^n - 1? - if (check % 3 == 0 && ((check / 3) & (check / 3 - 1)) == 0) return new IntegerEncoded(EIntegerEncoding.Trit, BitArrayStream.PopCnt(check / 3 - 1)); + if (check % 3 == 0 && ((check / 3) & (check / 3 - 1)) == 0) + { + return new IntegerEncoded(EIntegerEncoding.Trit, BitArrayStream.PopCnt(check / 3 - 1)); + } // Is maxVal of the type 5*2^n - 1? - if (check % 5 == 0 && ((check / 5) & (check / 5 - 1)) == 0) return new IntegerEncoded(EIntegerEncoding.Quint, BitArrayStream.PopCnt(check / 5 - 1)); + if (check % 5 == 0 && ((check / 5) & (check / 5 - 1)) == 0) + { + return new IntegerEncoded(EIntegerEncoding.Quint, BitArrayStream.PopCnt(check / 5 - 1)); + } // Apparently it can't be represented with a bounded integer sequence... // just iterate. @@ -221,6 +236,7 @@ namespace Ryujinx.Graphics.Texture // Start decoding int numberValuesDecoded = 0; while (numberValuesDecoded < numberValues) + { switch (intEncoded.GetEncoding()) { case EIntegerEncoding.Quint: @@ -248,6 +264,7 @@ namespace Ryujinx.Graphics.Texture break; } } + } } } } diff --git a/Ryujinx.Graphics/Texture/TextureFactory.cs b/Ryujinx.Graphics/Texture/TextureFactory.cs index 438331d8db..df93dd55b5 100644 --- a/Ryujinx.Graphics/Texture/TextureFactory.cs +++ b/Ryujinx.Graphics/Texture/TextureFactory.cs @@ -23,9 +23,13 @@ namespace Ryujinx.Graphics.Texture if (swizzle == TextureSwizzle.BlockLinear || swizzle == TextureSwizzle.BlockLinearColorKey) + { layout = GalMemoryLayout.BlockLinear; + } else + { layout = GalMemoryLayout.Pitch; + } int blockHeightLog2 = (tic[3] >> 3) & 7; int tileWidthLog2 = (tic[3] >> 10) & 7; @@ -48,7 +52,10 @@ namespace Ryujinx.Graphics.Texture zSource, wSource); - if (layout == GalMemoryLayout.Pitch) image.Pitch = (tic[3] & 0xffff) << 5; + if (layout == GalMemoryLayout.Pitch) + { + image.Pitch = (tic[3] & 0xffff) << 5; + } return image; } @@ -99,7 +106,10 @@ namespace Ryujinx.Graphics.Texture { int[] words = new int[count]; - for (int index = 0; index < count; index++, position += 4) words[index] = vmm.ReadInt32(position); + for (int index = 0; index < count; index++, position += 4) + { + words[index] = vmm.ReadInt32(position); + } return words; } diff --git a/Ryujinx.Graphics/Texture/TextureHelper.cs b/Ryujinx.Graphics/Texture/TextureHelper.cs index d3f2bd5eb1..f014c36a9c 100644 --- a/Ryujinx.Graphics/Texture/TextureHelper.cs +++ b/Ryujinx.Graphics/Texture/TextureHelper.cs @@ -31,7 +31,10 @@ namespace Ryujinx.Graphics.Texture IAMemory memory, long position) { - if (memory is NvGpuVmm vmm) return (vmm.Memory, vmm.GetPhysicalAddress(position)); + if (memory is NvGpuVmm vmm) + { + return (vmm.Memory, vmm.GetPhysicalAddress(position)); + } return ((AMemory)memory, position); } diff --git a/Ryujinx.Graphics/ValueRangeSet.cs b/Ryujinx.Graphics/ValueRangeSet.cs index daaacddf16..dc6e7caa63 100644 --- a/Ryujinx.Graphics/ValueRangeSet.cs +++ b/Ryujinx.Graphics/ValueRangeSet.cs @@ -13,7 +13,10 @@ namespace Ryujinx.Graphics public void Add(ValueRange range) { - if (range.End <= range.Start) return; + if (range.End <= range.Start) + { + return; + } int first = BinarySearchFirstIntersection(range); @@ -25,9 +28,13 @@ namespace Ryujinx.Graphics int gtIndex = BinarySearchGt(range); if (gtIndex != -1) + { _ranges.Insert(gtIndex, range); + } else + { _ranges.Add(range); + } return; } @@ -82,7 +89,10 @@ namespace Ryujinx.Graphics { int first = BinarySearchFirstIntersection(range); - if (first == -1) return; + if (first == -1) + { + return; + } (int start, int end) = GetAllIntersectionRanges(range, first); @@ -98,13 +108,19 @@ namespace Ryujinx.Graphics private void InsertNextNeighbour(int index, ValueRange range, ValueRange next) { //Split last intersection (ordered by Start) if necessary. - if (range.End < next.End) InsertNewRange(index, range.End, next.End, next.Value); + if (range.End < next.End) + { + InsertNewRange(index, range.End, next.End, next.Value); + } } private void InsertPrevNeighbour(int index, ValueRange range, ValueRange prev) { //Split first intersection (ordered by Start) if necessary. - if (range.Start > prev.Start) InsertNewRange(index, prev.Start, range.Start, prev.Value); + if (range.Start > prev.Start) + { + InsertNewRange(index, prev.Start, range.Start, prev.Value); + } } private void InsertNewRange(int index, long start, long end, T value) @@ -116,7 +132,10 @@ namespace Ryujinx.Graphics { int first = BinarySearchFirstIntersection(range); - if (first == -1) return new ValueRange[0]; + if (first == -1) + { + return new ValueRange[0]; + } (int start, int end) = GetAllIntersectionRanges(range, first); @@ -128,9 +147,15 @@ namespace Ryujinx.Graphics int start = baseIndex; int end = baseIndex; - while (start > 0 && Intersects(range, _ranges[start - 1])) start--; + while (start > 0 && Intersects(range, _ranges[start - 1])) + { + start--; + } - while (end < _ranges.Count - 1 && Intersects(range, _ranges[end + 1])) end++; + while (end < _ranges.Count - 1 && Intersects(range, _ranges[end + 1])) + { + end++; + } return (start, end); } @@ -148,12 +173,19 @@ namespace Ryujinx.Graphics ValueRange current = _ranges[middle]; - if (Intersects(range, current)) return middle; + if (Intersects(range, current)) + { + return middle; + } if (range.Start < current.Start) + { right = middle - 1; + } else + { left = middle + 1; + } } return -1; @@ -178,7 +210,10 @@ namespace Ryujinx.Graphics { right = middle - 1; - if (gtIndex == -1 || current.Start < _ranges[gtIndex].Start) gtIndex = middle; + if (gtIndex == -1 || current.Start < _ranges[gtIndex].Start) + { + gtIndex = middle; + } } else { diff --git a/Ryujinx.HLE/FileSystem/SaveHelper.cs b/Ryujinx.HLE/FileSystem/SaveHelper.cs index bf2d19b3c6..dd56dbb8b8 100644 --- a/Ryujinx.HLE/FileSystem/SaveHelper.cs +++ b/Ryujinx.HLE/FileSystem/SaveHelper.cs @@ -28,7 +28,12 @@ namespace Ryujinx.HLE.FileSystem baseSavePath = Path.Combine(baseSavePath, "save"); if (saveMetaData.TitleId == 0 && saveMetaData.SaveDataType == SaveDataType.SaveData) - if (context.Process.MetaData != null) currentTitleId = context.Process.MetaData.Aci0.TitleId; + { + if (context.Process.MetaData != null) + { + currentTitleId = context.Process.MetaData.Aci0.TitleId; + } + } string saveAccount = saveMetaData.UserId.IsZero() ? "savecommon" : saveMetaData.UserId.ToString(); diff --git a/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs b/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs index 613420a198..3962b573be 100644 --- a/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs +++ b/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs @@ -30,15 +30,24 @@ namespace Ryujinx.HLE.FileSystem public string GetFullPath(string basePath, string fileName) { if (fileName.StartsWith("//")) + { fileName = fileName.Substring(2); + } else if (fileName.StartsWith('/')) + { fileName = fileName.Substring(1); + } else + { return null; + } string fullPath = Path.GetFullPath(Path.Combine(basePath, fileName)); - if (!fullPath.StartsWith(GetBasePath())) return null; + if (!fullPath.StartsWith(GetBasePath())) + { + return null; + } return fullPath; } @@ -66,7 +75,11 @@ namespace Ryujinx.HLE.FileSystem public string SwitchPathToSystemPath(string switchPath) { string[] parts = switchPath.Split(":"); - if (parts.Length != 2) return null; + if (parts.Length != 2) + { + return null; + } + return GetFullPath(MakeDirAndGetFullPath(parts[0]), parts[1]); } @@ -77,7 +90,10 @@ namespace Ryujinx.HLE.FileSystem { string rawPath = systemPath.Replace(baseSystemPath, ""); int firstSeparatorOffset = rawPath.IndexOf(Path.DirectorySeparatorChar); - if (firstSeparatorOffset == -1) return $"{rawPath}:/"; + if (firstSeparatorOffset == -1) + { + return $"{rawPath}:/"; + } string basePath = rawPath.Substring(0, firstSeparatorOffset); string fileName = rawPath.Substring(firstSeparatorOffset + 1); @@ -90,7 +106,10 @@ namespace Ryujinx.HLE.FileSystem { string fullPath = Path.Combine(GetBasePath(), dir); - if (!Directory.Exists(fullPath)) Directory.CreateDirectory(fullPath); + if (!Directory.Exists(fullPath)) + { + Directory.CreateDirectory(fullPath); + } return fullPath; } @@ -114,7 +133,10 @@ namespace Ryujinx.HLE.FileSystem protected virtual void Dispose(bool disposing) { - if (disposing) RomFs?.Dispose(); + if (disposing) + { + RomFs?.Dispose(); + } } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ArrayType.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ArrayType.cs index 5d4ffffaed..4b1041ab79 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ArrayType.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ArrayType.cs @@ -43,8 +43,13 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast writer.Write("["); if (_dimensionString != null) + { writer.Write(_dimensionString); - else if (_dimensionExpression != null) _dimensionExpression.Print(writer); + } + else if (_dimensionExpression != null) + { + _dimensionExpression.Print(writer); + } writer.Write("]"); diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BaseNode.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BaseNode.cs index 07aba05418..ca4b98f88f 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BaseNode.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BaseNode.cs @@ -71,7 +71,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { PrintLeft(writer); - if (HasRightPart()) PrintRight(writer); + if (HasRightPart()) + { + PrintRight(writer); + } } public abstract void PrintLeft(TextWriter writer); diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BinaryExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BinaryExpression.cs index cd98609c66..0c492df394 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BinaryExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BinaryExpression.cs @@ -17,7 +17,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast public override void PrintLeft(TextWriter writer) { - if (_name.Equals(">")) writer.Write("("); + if (_name.Equals(">")) + { + writer.Write("("); + } writer.Write("("); _leftPart.Print(writer); @@ -29,7 +32,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast _rightPart.Print(writer); writer.Write(")"); - if (_name.Equals(">")) writer.Write(")"); + if (_name.Equals(">")) + { + writer.Write(")"); + } } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedExpression.cs index 6c6bd85c5e..6b9782f5c2 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedExpression.cs @@ -29,7 +29,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast _element.Print(writer); } - if (!_expression.GetType().Equals(NodeType.BracedExpression) || !_expression.GetType().Equals(NodeType.BracedRangeExpression)) writer.Write(" = "); + if (!_expression.GetType().Equals(NodeType.BracedExpression) || !_expression.GetType().Equals(NodeType.BracedRangeExpression)) + { + writer.Write(" = "); + } _expression.Print(writer); } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedRangeExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedRangeExpression.cs index 78e43df96c..802422d9a1 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedRangeExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/BracedRangeExpression.cs @@ -23,7 +23,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast _lastNode.Print(writer); writer.Write("]"); - if (!_expression.GetType().Equals(NodeType.BracedExpression) || !_expression.GetType().Equals(NodeType.BracedRangeExpression)) writer.Write(" = "); + if (!_expression.GetType().Equals(NodeType.BracedExpression) || !_expression.GetType().Equals(NodeType.BracedRangeExpression)) + { + writer.Write(" = "); + } _expression.Print(writer); } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CtorDtorNameType.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CtorDtorNameType.cs index 16d40833ba..5f45812358 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CtorDtorNameType.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/CtorDtorNameType.cs @@ -13,7 +13,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast public override void PrintLeft(TextWriter writer) { - if (_isDestructor) writer.Write("~"); + if (_isDestructor) + { + writer.Write("~"); + } writer.Write(Child.GetName()); } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DeleteExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DeleteExpression.cs index b835e2d47b..14715d25e5 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DeleteExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/DeleteExpression.cs @@ -15,11 +15,17 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast public override void PrintLeft(TextWriter writer) { - if (_isGlobal) writer.Write("::"); + if (_isGlobal) + { + writer.Write("::"); + } writer.Write("delete"); - if (_isArrayExpression) writer.Write("[] "); + if (_isArrayExpression) + { + writer.Write("[] "); + } Child.Print(writer); } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/EncodedFunction.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/EncodedFunction.cs index 1b5f83bf2e..c7b6dab1a8 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/EncodedFunction.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/EncodedFunction.cs @@ -27,7 +27,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { _ret.PrintLeft(writer); - if (!_ret.HasRightPart()) writer.Write(" "); + if (!_ret.HasRightPart()) + { + writer.Write(" "); + } } _name.Print(writer); @@ -43,17 +46,32 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { writer.Write("("); - if (_params != null) _params.Print(writer); + if (_params != null) + { + _params.Print(writer); + } writer.Write(")"); - if (_ret != null) _ret.PrintRight(writer); + if (_ret != null) + { + _ret.PrintRight(writer); + } - if (_cv != null) _cv.Print(writer); + if (_cv != null) + { + _cv.Print(writer); + } - if (_ref != null) _ref.Print(writer); + if (_ref != null) + { + _ref.Print(writer); + } - if (_attrs != null) _attrs.Print(writer); + if (_attrs != null) + { + _attrs.Print(writer); + } } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FunctionParameter.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FunctionParameter.cs index dc23fc12b1..5654a048f4 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FunctionParameter.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/FunctionParameter.cs @@ -15,7 +15,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { writer.Write("fp "); - if (_number != null) writer.Write(_number); + if (_number != null) + { + writer.Write(_number); + } } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/InitListExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/InitListExpression.cs index e9b0660e85..7155dd601e 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/InitListExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/InitListExpression.cs @@ -16,7 +16,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast public override void PrintLeft(TextWriter writer) { - if (_typeNode != null) _typeNode.Print(writer); + if (_typeNode != null) + { + _typeNode.Print(writer); + } writer.Write("{"); writer.Write(string.Join(", ", _nodes.ToArray())); diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/IntegerLiteral.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/IntegerLiteral.cs index bf5bb0084a..7c37f485ba 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/IntegerLiteral.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/IntegerLiteral.cs @@ -32,7 +32,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast writer.Write(_litteralValue); } - if (_litteralName.Length <= 3) writer.Write(_litteralName); + if (_litteralName.Length <= 3) + { + writer.Write(_litteralName); + } } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NewExpression.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NewExpression.cs index 1348c46ed1..ba4690af4d 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NewExpression.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/NewExpression.cs @@ -23,11 +23,17 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast public override void PrintLeft(TextWriter writer) { - if (_isGlobal) writer.Write("::operator "); + if (_isGlobal) + { + writer.Write("::operator "); + } writer.Write("new "); - if (_isArrayExpression) writer.Write("[] "); + if (_isArrayExpression) + { + writer.Write("[] "); + } if (_expressions.Nodes.Count != 0) { diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameter.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameter.cs index 4cae0de65d..4c82009588 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameter.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameter.cs @@ -9,18 +9,29 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast public override void PrintLeft(TextWriter writer) { - foreach (BaseNode node in Nodes) node.PrintLeft(writer); + foreach (BaseNode node in Nodes) + { + node.PrintLeft(writer); + } } public override void PrintRight(TextWriter writer) { - foreach (BaseNode node in Nodes) node.PrintLeft(writer); + foreach (BaseNode node in Nodes) + { + node.PrintLeft(writer); + } } public override bool HasRightPart() { foreach (BaseNode node in Nodes) - if (node.HasRightPart()) return true; + { + if (node.HasRightPart()) + { + return true; + } + } return false; } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameterExpansion.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameterExpansion.cs index 80efff67be..c3645044ab 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameterExpansion.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PackedTemplateParameterExpansion.cs @@ -10,7 +10,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { if (Child is PackedTemplateParameter) { - if (((PackedTemplateParameter)Child).Nodes.Count != 0) Child.Print(writer); + if (((PackedTemplateParameter)Child).Nodes.Count != 0) + { + Child.Print(writer); + } } else { diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PointerType.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PointerType.cs index 6e991a89b7..b1a3ec422e 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PointerType.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/PointerType.cs @@ -19,16 +19,25 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast public override void PrintLeft(TextWriter writer) { _child.PrintLeft(writer); - if (_child.IsArray()) writer.Write(" "); + if (_child.IsArray()) + { + writer.Write(" "); + } - if (_child.IsArray() || _child.HasFunctions()) writer.Write("("); + if (_child.IsArray() || _child.HasFunctions()) + { + writer.Write("("); + } writer.Write("*"); } public override void PrintRight(TextWriter writer) { - if (_child.IsArray() || _child.HasFunctions()) writer.Write(")"); + if (_child.IsArray() || _child.HasFunctions()) + { + writer.Write(")"); + } _child.PrintRight(writer); } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/Qualifier.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/Qualifier.cs index 20fa9fbdc4..6a3f5c8b4b 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/Qualifier.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/Qualifier.cs @@ -28,16 +28,28 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast public void PrintQualifier(TextWriter writer) { - if ((Qualifier & CV.Const) != 0) writer.Write(" const"); + if ((Qualifier & CV.Const) != 0) + { + writer.Write(" const"); + } - if ((Qualifier & CV.Volatile) != 0) writer.Write(" volatile"); + if ((Qualifier & CV.Volatile) != 0) + { + writer.Write(" volatile"); + } - if ((Qualifier & CV.Restricted) != 0) writer.Write(" restrict"); + if ((Qualifier & CV.Restricted) != 0) + { + writer.Write(" restrict"); + } } public override void PrintLeft(TextWriter writer) { - if (Child != null) Child.PrintLeft(writer); + if (Child != null) + { + Child.PrintLeft(writer); + } PrintQualifier(writer); } @@ -49,7 +61,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast public override void PrintRight(TextWriter writer) { - if (Child != null) Child.PrintRight(writer); + if (Child != null) + { + Child.PrintRight(writer); + } } } @@ -64,16 +79,27 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast public void PrintQualifier(TextWriter writer) { - if ((Qualifier & Reference.LValue) != 0) writer.Write("&"); + if ((Qualifier & Reference.LValue) != 0) + { + writer.Write("&"); + } - if ((Qualifier & Reference.RValue) != 0) writer.Write("&&"); + if ((Qualifier & Reference.RValue) != 0) + { + writer.Write("&&"); + } } public override void PrintLeft(TextWriter writer) { if (Child != null) + { Child.PrintLeft(writer); - else if (Qualifier != Reference.None) writer.Write(" "); + } + else if (Qualifier != Reference.None) + { + writer.Write(" "); + } PrintQualifier(writer); } @@ -85,7 +111,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast public override void PrintRight(TextWriter writer) { - if (Child != null) Child.PrintRight(writer); + if (Child != null) + { + Child.PrintRight(writer); + } } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ReferenceType.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ReferenceType.cs index d88b41a435..a3214171f5 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ReferenceType.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/ReferenceType.cs @@ -22,15 +22,24 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast { _child.PrintLeft(writer); - if (_child.IsArray()) writer.Write(" "); + if (_child.IsArray()) + { + writer.Write(" "); + } - if (_child.IsArray() || _child.HasFunctions()) writer.Write("("); + if (_child.IsArray() || _child.HasFunctions()) + { + writer.Write("("); + } writer.Write(_reference); } public override void PrintRight(TextWriter writer) { - if (_child.IsArray() || _child.HasFunctions()) writer.Write(")"); + if (_child.IsArray() || _child.HasFunctions()) + { + writer.Write(")"); + } _child.PrintRight(writer); } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/SpecialSubstitution.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/SpecialSubstitution.cs index 667300fcf1..33b8c0be55 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/SpecialSubstitution.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/SpecialSubstitution.cs @@ -35,7 +35,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast case SpecialType.BasicString: return "basic_string"; case SpecialType.String: - if (Type == NodeType.ExpandedSpecialSubstitution) return "basic_string"; + if (Type == NodeType.ExpandedSpecialSubstitution) + { + return "basic_string"; + } return "string"; case SpecialType.Stream: diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/TemplateArguments.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/TemplateArguments.cs index 88c59ab100..aefd668de7 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/TemplateArguments.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Ast/TemplateArguments.cs @@ -15,7 +15,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast writer.Write(Params); - if (Params.EndsWith(">")) writer.Write(" "); + if (Params.EndsWith(">")) + { + writer.Write(" "); + } writer.Write(">"); } diff --git a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs index 4b9cc55d07..d65c36f2d1 100644 --- a/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs +++ b/Ryujinx.HLE/HOS/Diagnostics/Demangler/Demangler.cs @@ -46,21 +46,30 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler private string PeekString(int offset = 0, int length = 1) { - if (_position + offset >= length) return null; + if (_position + offset >= length) + { + return null; + } return Mangled.Substring(_position + offset, length); } private char Peek(int offset = 0) { - if (_position + offset >= _length) return '\0'; + if (_position + offset >= _length) + { + return '\0'; + } return Mangled[_position + offset]; } private char Consume() { - if (_position < _length) return Mangled[_position++]; + if (_position < _length) + { + return Mangled[_position++]; + } return '\0'; } @@ -79,7 +88,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler for (int i = 0; i < reversedEncoded.Length; i++) { int value = _base36.IndexOf(reversedEncoded[i]); - if (value == -1) return -1; + if (value == -1) + { + return -1; + } result += value * (int)Math.Pow(36, i); } @@ -93,7 +105,12 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler int seqIdLen = 0; for (; seqIdLen < part.Length; seqIdLen++) - if (!char.IsLetterOrDigit(part[seqIdLen])) break; + { + if (!char.IsLetterOrDigit(part[seqIdLen])) + { + break; + } + } _position += seqIdLen; @@ -111,10 +128,14 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= Sd # std::basic_iostream > private BaseNode ParseSubstitution() { - if (!ConsumeIf("S")) return null; + if (!ConsumeIf("S")) + { + return null; + } char substitutionSecondChar = Peek(); if (char.IsLower(substitutionSecondChar)) + { switch (substitutionSecondChar) { case 'a': @@ -138,22 +159,32 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler default: return null; } + } // ::= S_ if (ConsumeIf("_")) { - if (_substitutionList.Count != 0) return _substitutionList[0]; + if (_substitutionList.Count != 0) + { + return _substitutionList[0]; + } return null; } // ::= S _ int seqId = ParseSeqId(); - if (seqId < 0) return null; + if (seqId < 0) + { + return null; + } seqId++; - if (!ConsumeIf("_") || seqId >= _substitutionList.Count) return null; + if (!ConsumeIf("_") || seqId >= _substitutionList.Count) + { + return null; + } return _substitutionList[seqId]; } @@ -168,8 +199,13 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler private bool ParseCallOffset() { if (ConsumeIf("h")) + { return ParseNumber(true).Length == 0 || !ConsumeIf("_"); - else if (ConsumeIf("v")) return ParseNumber(true).Length == 0 || !ConsumeIf("_") || ParseNumber(true).Length == 0 || !ConsumeIf("_"); + } + else if (ConsumeIf("v")) + { + return ParseNumber(true).Length == 0 || !ConsumeIf("_") || ParseNumber(true).Length == 0 || !ConsumeIf("_"); + } return true; } @@ -184,15 +220,28 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler string elaboratedType = null; if (ConsumeIf("Ts")) + { elaboratedType = "struct"; + } else if (ConsumeIf("Tu")) + { elaboratedType = "union"; - else if (ConsumeIf("Te")) elaboratedType = "enum"; + } + else if (ConsumeIf("Te")) + { + elaboratedType = "enum"; + } BaseNode name = ParseName(); - if (name == null) return null; + if (name == null) + { + return null; + } - if (elaboratedType == null) return name; + if (elaboratedType == null) + { + return name; + } return new ElaboratedType(elaboratedType, name); } @@ -216,7 +265,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler else if (ConsumeIf("DO")) { BaseNode expression = ParseExpression(); - if (expression == null || !ConsumeIf("E")) return null; + if (expression == null || !ConsumeIf("E")) + { + return null; + } exceptionSpec = new NoexceptSpec(expression); } @@ -227,7 +279,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler while (!ConsumeIf("E")) { BaseNode type = ParseType(); - if (type == null) return null; + if (type == null) + { + return null; + } types.Add(type); } @@ -238,22 +293,34 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // We don't need the transaction ConsumeIf("Dx"); - if (!ConsumeIf("F")) return null; + if (!ConsumeIf("F")) + { + return null; + } // extern "C" ConsumeIf("Y"); BaseNode returnType = ParseType(); - if (returnType == null) return null; + if (returnType == null) + { + return null; + } Reference referenceQualifier = Reference.None; List Params = new List(); while (true) { - if (ConsumeIf("E")) break; + if (ConsumeIf("E")) + { + break; + } - if (ConsumeIf("v")) continue; + if (ConsumeIf("v")) + { + continue; + } if (ConsumeIf("RE")) { @@ -267,7 +334,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler } BaseNode type = ParseType(); - if (type == null) return null; + if (type == null) + { + return null; + } Params.Add(type); } @@ -279,16 +349,25 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= A [] _ private BaseNode ParseArrayType() { - if (!ConsumeIf("A")) return null; + if (!ConsumeIf("A")) + { + return null; + } BaseNode elementType; if (char.IsDigit(Peek())) { string dimension = ParseNumber(); - if (dimension.Length == 0 || !ConsumeIf("_")) return null; + if (dimension.Length == 0 || !ConsumeIf("_")) + { + return null; + } elementType = ParseType(); - if (elementType == null) return null; + if (elementType == null) + { + return null; + } return new ArrayType(elementType, dimension); } @@ -296,16 +375,25 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (!ConsumeIf("_")) { BaseNode dimensionExpression = ParseExpression(); - if (dimensionExpression == null || !ConsumeIf("_")) return null; + if (dimensionExpression == null || !ConsumeIf("_")) + { + return null; + } elementType = ParseType(); - if (elementType == null) return null; + if (elementType == null) + { + return null; + } return new ArrayType(elementType, dimensionExpression); } elementType = ParseType(); - if (elementType == null) return null; + if (elementType == null) + { + return null; + } return new ArrayType(elementType); } @@ -328,7 +416,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler private BaseNode ParseType(NameParserContext context = null) { // Temporary context - if (context == null) context = new NameParserContext(); + if (context == null) + { + context = new NameParserContext(); + } BaseNode result = null; switch (Peek()) @@ -338,11 +429,20 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'K': int typePos = 0; - if (Peek(typePos) == 'r') typePos++; + if (Peek(typePos) == 'r') + { + typePos++; + } - if (Peek(typePos) == 'V') typePos++; + if (Peek(typePos) == 'V') + { + typePos++; + } - if (Peek(typePos) == 'K') typePos++; + if (Peek(typePos) == 'K') + { + typePos++; + } if (Peek(typePos) == 'F' || Peek(typePos) == 'D' && (Peek(typePos + 1) == 'o' || Peek(typePos + 1) == 'O' || Peek(typePos + 1) == 'w' || Peek(typePos + 1) == 'x')) { @@ -354,7 +454,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler result = ParseType(context); - if (result == null) return null; + if (result == null) + { + return null; + } result = new CVType(cv, result); break; @@ -491,12 +594,18 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler } result = ParseTemplateParam(); - if (result == null) return null; + if (result == null) + { + return null; + } if (_canParseTemplateArgs && Peek() == 'I') { BaseNode templateArguments = ParseTemplateArguments(); - if (templateArguments == null) return null; + if (templateArguments == null) + { + return null; + } result = new NameTypeWithTemplateArguments(result, templateArguments); } @@ -505,7 +614,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler _position++; result = ParseType(context); - if (result == null) return null; + if (result == null) + { + return null; + } result = new PointerType(result); break; @@ -513,7 +625,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler _position++; result = ParseType(context); - if (result == null) return null; + if (result == null) + { + return null; + } result = new ReferenceType("&", result); break; @@ -521,7 +636,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler _position++; result = ParseType(context); - if (result == null) return null; + if (result == null) + { + return null; + } result = new ReferenceType("&&", result); break; @@ -529,7 +647,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler _position++; result = ParseType(context); - if (result == null) return null; + if (result == null) + { + return null; + } result = new PostfixQualifiedType(" complex", result); break; @@ -537,7 +658,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler _position++; result = ParseType(context); - if (result == null) return null; + if (result == null) + { + return null; + } result = new PostfixQualifiedType(" imaginary", result); break; @@ -545,12 +669,18 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (Peek(1) != 't') { BaseNode substitution = ParseSubstitution(); - if (substitution == null) return null; + if (substitution == null) + { + return null; + } if (_canParseTemplateArgs && Peek() == 'I') { BaseNode templateArgument = ParseTemplateArgument(); - if (templateArgument == null) return null; + if (templateArgument == null) + { + return null; + } result = new NameTypeWithTemplateArguments(substitution, templateArgument); break; @@ -566,7 +696,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler result = ParseClassEnumType(); break; } - if (result != null) _substitutionList.Add(result); + if (result != null) + { + _substitutionList.Add(result); + } return result; } @@ -588,7 +721,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (ConsumeIf("GV")) { BaseNode name = ParseName(); - if (name == null) return null; + if (name == null) + { + return null; + } return new SpecialName("guard variable for ", name); } @@ -602,44 +738,65 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'V': _position += 2; node = ParseType(context); - if (node == null) return null; + if (node == null) + { + return null; + } return new SpecialName("vtable for ", node); // ::= TT # VTT structure (construction vtable index) case 'T': _position += 2; node = ParseType(context); - if (node == null) return null; + if (node == null) + { + return null; + } return new SpecialName("VTT for ", node); // ::= TI # typeinfo structure case 'I': _position += 2; node = ParseType(context); - if (node == null) return null; + if (node == null) + { + return null; + } return new SpecialName("typeinfo for ", node); // ::= TS # typeinfo name (null-terminated byte string) case 'S': _position += 2; node = ParseType(context); - if (node == null) return null; + if (node == null) + { + return null; + } return new SpecialName("typeinfo name for ", node); // ::= Tc case 'c': _position += 2; - if (ParseCallOffset() || ParseCallOffset()) return null; + if (ParseCallOffset() || ParseCallOffset()) + { + return null; + } node = ParseEncoding(); - if (node == null) return null; + if (node == null) + { + return null; + } return new SpecialName("covariant return thunk to ", node); // extension ::= TC _ case 'C': _position += 2; BaseNode firstType = ParseType(); - if (firstType == null || ParseNumber(true).Length == 0 || !ConsumeIf("_")) return null; + if (firstType == null || ParseNumber(true).Length == 0 || !ConsumeIf("_")) + { + return null; + } BaseNode secondType = ParseType(); @@ -648,25 +805,40 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'H': _position += 2; node = ParseName(); - if (node == null) return null; + if (node == null) + { + return null; + } return new SpecialName("thread-local initialization routine for ", node); // ::= TW # Thread-local wrapper case 'W': _position += 2; node = ParseName(); - if (node == null) return null; + if (node == null) + { + return null; + } return new SpecialName("thread-local wrapper routine for ", node); default: _position++; bool isVirtual = Peek() == 'v'; - if (ParseCallOffset()) return null; + if (ParseCallOffset()) + { + return null; + } node = ParseEncoding(); - if (node == null) return null; + if (node == null) + { + return null; + } - if (isVirtual) return new SpecialName("virtual thunk to ", node); + if (isVirtual) + { + return new SpecialName("virtual thunk to ", node); + } return new SpecialName("non-virtual thunk to ", node); } @@ -677,9 +849,20 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { CV qualifiers = CV.None; - if (ConsumeIf("r")) qualifiers |= CV.Restricted; - if (ConsumeIf("V")) qualifiers |= CV.Volatile; - if (ConsumeIf("K")) qualifiers |= CV.Const; + if (ConsumeIf("r")) + { + qualifiers |= CV.Restricted; + } + + if (ConsumeIf("V")) + { + qualifiers |= CV.Volatile; + } + + if (ConsumeIf("K")) + { + qualifiers |= CV.Const; + } return qualifiers; } @@ -691,17 +874,29 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { Reference result = Reference.None; if (ConsumeIf("O")) + { result = Reference.RValue; - else if (ConsumeIf("R")) result = Reference.LValue; + } + else if (ConsumeIf("R")) + { + result = Reference.LValue; + } + return new SimpleReferenceType(result, null); } private BaseNode CreateNameNode(BaseNode prev, BaseNode name, NameParserContext context) { BaseNode result = name; - if (prev != null) result = new NestedName(name, prev); + if (prev != null) + { + result = new NestedName(name, prev); + } - if (context != null) context.FinishWithTemplateArguments = false; + if (context != null) + { + context.FinishWithTemplateArguments = false; + } return result; } @@ -712,26 +907,45 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler int numberLength = 0; for (; numberLength < part.Length; numberLength++) - if (!char.IsDigit(part[numberLength])) break; + { + if (!char.IsDigit(part[numberLength])) + { + break; + } + } _position += numberLength; - if (numberLength == 0) return -1; + if (numberLength == 0) + { + return -1; + } return int.Parse(part.Substring(0, numberLength)); } private string ParseNumber(bool isSigned = false) { - if (isSigned) ConsumeIf("n"); + if (isSigned) + { + ConsumeIf("n"); + } - if (Count() == 0 || !char.IsDigit(Mangled[_position])) return null; + if (Count() == 0 || !char.IsDigit(Mangled[_position])) + { + return null; + } string part = Mangled.Substring(_position); int numberLength = 0; for (; numberLength < part.Length; numberLength++) - if (!char.IsDigit(part[numberLength])) break; + { + if (!char.IsDigit(part[numberLength])) + { + break; + } + } _position += numberLength; @@ -742,11 +956,17 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler private BaseNode ParseSourceName() { int length = ParsePositiveNumber(); - if (Count() < length || length <= 0) return null; + if (Count() < length || length <= 0) + { + return null; + } string name = Mangled.Substring(_position, length); _position += length; - if (name.StartsWith("_GLOBAL__N")) return new NameType("(anonymous namespace)"); + if (name.StartsWith("_GLOBAL__N")) + { + return new NameType("(anonymous namespace)"); + } return new NameType(name); } @@ -851,9 +1071,15 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler _canParseTemplateArgs = canParseTemplateArgsBackup; _canForwardTemplateReference = canForwardTemplateReferenceBackup; - if (type == null) return null; + if (type == null) + { + return null; + } - if (context != null) context.CtorDtorConversion = true; + if (context != null) + { + context.CtorDtorConversion = true; + } return new ConversionOperatorType(type); default: @@ -923,7 +1149,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'i': _position += 2; BaseNode sourceName = ParseSourceName(); - if (sourceName == null) return null; + if (sourceName == null) + { + return null; + } return new LiteralOperator(sourceName); case 's': @@ -1101,20 +1330,32 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= D2 # base object destructor private BaseNode ParseCtorDtorName(NameParserContext context, BaseNode prev) { - if (prev.Type == NodeType.SpecialSubstitution && prev is SpecialSubstitution) ((SpecialSubstitution)prev).SetExtended(); + if (prev.Type == NodeType.SpecialSubstitution && prev is SpecialSubstitution) + { + ((SpecialSubstitution)prev).SetExtended(); + } if (ConsumeIf("C")) { bool isInherited = ConsumeIf("I"); char ctorDtorType = Peek(); - if (ctorDtorType != '1' && ctorDtorType != '2' && ctorDtorType != '3') return null; + if (ctorDtorType != '1' && ctorDtorType != '2' && ctorDtorType != '3') + { + return null; + } _position++; - if (context != null) context.CtorDtorConversion = true; + if (context != null) + { + context.CtorDtorConversion = true; + } - if (isInherited && ParseName(context) == null) return null; + if (isInherited && ParseName(context) == null) + { + return null; + } return new CtorDtorNameType(prev, false); } @@ -1122,11 +1363,17 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (ConsumeIf("D")) { char c = Peek(); - if (c != '0' && c != '1' && c != '2') return null; + if (c != '0' && c != '1' && c != '2') + { + return null; + } _position++; - if (context != null) context.CtorDtorConversion = true; + if (context != null) + { + context.CtorDtorConversion = true; + } return new CtorDtorNameType(prev, true); } @@ -1145,21 +1392,33 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ignored ParseCvQualifiers(); - if (!ConsumeIf("_")) return null; + if (!ConsumeIf("_")) + { + return null; + } return new FunctionParameter(ParseNumber()); } else if (ConsumeIf("fL")) { string l1Number = ParseNumber(); - if (l1Number == null || l1Number.Length == 0) return null; + if (l1Number == null || l1Number.Length == 0) + { + return null; + } - if (!ConsumeIf("p")) return null; + if (!ConsumeIf("p")) + { + return null; + } // ignored ParseCvQualifiers(); - if (!ConsumeIf("_")) return null; + if (!ConsumeIf("_")) + { + return null; + } return new FunctionParameter(ParseNumber()); } @@ -1173,13 +1432,19 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= fr private BaseNode ParseFoldExpression() { - if (!ConsumeIf("f")) return null; + if (!ConsumeIf("f")) + { + return null; + } char foldKind = Peek(); bool hasInitializer = foldKind == 'L' || foldKind == 'R'; bool isLeftFold = foldKind == 'l' || foldKind == 'L'; - if (!isLeftFold && !(foldKind == 'r' || foldKind == 'R')) return null; + if (!isLeftFold && !(foldKind == 'r' || foldKind == 'R')) + { + return null; + } _position++; @@ -1287,14 +1552,20 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler _position += 2; BaseNode expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } BaseNode initializer = null; if (hasInitializer) { initializer = ParseExpression(); - if (initializer == null) return null; + if (initializer == null) + { + return null; + } } if (isLeftFold && initializer != null) @@ -1312,14 +1583,20 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= cv _ * E # type (expr-list), conversion with other than one argument private BaseNode ParseConversionExpression() { - if (!ConsumeIf("cv")) return null; + if (!ConsumeIf("cv")) + { + return null; + } bool canParseTemplateArgsBackup = _canParseTemplateArgs; _canParseTemplateArgs = false; BaseNode type = ParseType(); _canParseTemplateArgs = canParseTemplateArgsBackup; - if (type == null) return null; + if (type == null) + { + return null; + } List expressions = new List(); if (ConsumeIf("_")) @@ -1327,7 +1604,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler while (!ConsumeIf("E")) { BaseNode expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } expressions.Add(expression); } @@ -1335,7 +1615,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler else { BaseNode expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } expressions.Add(expression); } @@ -1346,10 +1629,16 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler private BaseNode ParseBinaryExpression(string name) { BaseNode leftPart = ParseExpression(); - if (leftPart == null) return null; + if (leftPart == null) + { + return null; + } BaseNode rightPart = ParseExpression(); - if (rightPart == null) return null; + if (rightPart == null) + { + return null; + } return new BinaryExpression(leftPart, name, rightPart); } @@ -1357,7 +1646,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler private BaseNode ParsePrefixExpression(string name) { BaseNode expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } return new PrefixExpression(name, expression); } @@ -1378,31 +1670,52 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'i': _position += 2; BaseNode field = ParseSourceName(); - if (field == null) return null; + if (field == null) + { + return null; + } bracedExpressionNode = ParseBracedExpression(); - if (bracedExpressionNode == null) return null; + if (bracedExpressionNode == null) + { + return null; + } return new BracedExpression(field, bracedExpressionNode, false); case 'x': _position += 2; BaseNode index = ParseExpression(); - if (index == null) return null; + if (index == null) + { + return null; + } bracedExpressionNode = ParseBracedExpression(); - if (bracedExpressionNode == null) return null; + if (bracedExpressionNode == null) + { + return null; + } return new BracedExpression(index, bracedExpressionNode, true); case 'X': _position += 2; BaseNode rangeBeginExpression = ParseExpression(); - if (rangeBeginExpression == null) return null; + if (rangeBeginExpression == null) + { + return null; + } BaseNode rangeEndExpression = ParseExpression(); - if (rangeEndExpression == null) return null; + if (rangeEndExpression == null) + { + return null; + } bracedExpressionNode = ParseBracedExpression(); - if (bracedExpressionNode == null) return null; + if (bracedExpressionNode == null) + { + return null; + } return new BracedRangeExpression(rangeBeginExpression, rangeEndExpression, bracedExpressionNode); } @@ -1422,7 +1735,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler bool isGlobal = ConsumeIf("gs"); bool isArray = Peek(1) == 'a'; - if (!ConsumeIf("nw") || !ConsumeIf("na")) return null; + if (!ConsumeIf("nw") || !ConsumeIf("na")) + { + return null; + } List expressions = new List(); List initializers = new List(); @@ -1430,23 +1746,37 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler while (!ConsumeIf("_")) { BaseNode expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } expressions.Add(expression); } BaseNode typeNode = ParseType(); - if (typeNode == null) return null; + if (typeNode == null) + { + return null; + } if (ConsumeIf("pi")) + { while (!ConsumeIf("E")) { BaseNode initializer = ParseExpression(); - if (initializer == null) return null; + if (initializer == null) + { + return null; + } initializers.Add(initializer); } - else if (!ConsumeIf("E")) return null; + } + else if (!ConsumeIf("E")) + { + return null; + } return new NewExpression(new NodeArray(expressions), typeNode, new NodeArray(initializers), isGlobal, isArray); } @@ -1498,7 +1828,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { bool isGlobal = ConsumeIf("gs"); BaseNode expression = null; - if (Count() < 2) return null; + if (Count() < 2) + { + return null; + } switch (Peek()) { @@ -1508,7 +1841,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return ParseTemplateParam(); case 'f': char c = Peek(1); - if (c == 'p' || c == 'L' && char.IsDigit(Peek(2))) return ParseFunctionParameter(); + if (c == 'p' || c == 'L' && char.IsDigit(Peek(2))) + { + return ParseFunctionParameter(); + } return ParseFoldExpression(); case 'a': @@ -1530,13 +1866,19 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 't': _position += 2; BaseNode type = ParseType(); - if (type == null) return null; + if (type == null) + { + return null; + } return new EnclosedExpression("alignof (", type, ")"); case 'z': _position += 2; expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } return new EnclosedExpression("alignof (", expression, ")"); } @@ -1547,22 +1889,34 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'c': _position += 2; BaseNode to = ParseType(); - if (to == null) return null; + if (to == null) + { + return null; + } BaseNode @from = ParseExpression(); - if (@from == null) return null; + if (@from == null) + { + return null; + } return new CastExpression("const_cast", to, @from); case 'l': _position += 2; BaseNode callee = ParseExpression(); - if (callee == null) return null; + if (callee == null) + { + return null; + } List names = new List(); while (!ConsumeIf("E")) { expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } names.Add(expression); } @@ -1585,16 +1939,25 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'a': _position += 2; expression = ParseExpression(); - if (expression == null) return expression; + if (expression == null) + { + return expression; + } return new DeleteExpression(expression, isGlobal, true); case 'c': _position += 2; BaseNode type = ParseType(); - if (type == null) return null; + if (type == null) + { + return null; + } expression = ParseExpression(); - if (expression == null) return expression; + if (expression == null) + { + return expression; + } return new CastExpression("dynamic_cast", type, expression); case 'e': @@ -1603,7 +1966,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'l': _position += 2; expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } return new DeleteExpression(expression, isGlobal, false); case 'n': @@ -1611,19 +1977,31 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 's': _position += 2; leftNode = ParseExpression(); - if (leftNode == null) return null; + if (leftNode == null) + { + return null; + } rightNode = ParseExpression(); - if (rightNode == null) return null; + if (rightNode == null) + { + return null; + } return new MemberExpression(leftNode, ".*", rightNode); case 't': _position += 2; leftNode = ParseExpression(); - if (leftNode == null) return null; + if (leftNode == null) + { + return null; + } rightNode = ParseExpression(); - if (rightNode == null) return null; + if (rightNode == null) + { + return null; + } return new MemberExpression(leftNode, ".", rightNode); case 'v': @@ -1665,10 +2043,16 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'x': _position += 2; BaseNode Base = ParseExpression(); - if (Base == null) return null; + if (Base == null) + { + return null; + } BaseNode subscript = ParseExpression(); - if (Base == null) return null; + if (Base == null) + { + return null; + } return new ArraySubscriptingExpression(Base, subscript); case 'l': @@ -1678,7 +2062,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler while (!ConsumeIf("E")) { expression = ParseBracedExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } bracedExpressions.Add(expression); } @@ -1719,10 +2106,16 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return ParseBinaryExpression("*="); case 'm': _position += 2; - if (ConsumeIf("_")) return ParsePrefixExpression("--"); + if (ConsumeIf("_")) + { + return ParsePrefixExpression("--"); + } expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } return new PostfixExpression(expression, "--"); } @@ -1746,7 +2139,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'x': _position += 2; expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } return new EnclosedExpression("noexcept (", expression, ")"); } @@ -1782,19 +2178,31 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler return ParseBinaryExpression("+="); case 'p': _position += 2; - if (ConsumeIf("_")) return ParsePrefixExpression("++"); + if (ConsumeIf("_")) + { + return ParsePrefixExpression("++"); + } expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } return new PostfixExpression(expression, "++"); case 't': _position += 2; leftNode = ParseExpression(); - if (leftNode == null) return null; + if (leftNode == null) + { + return null; + } rightNode = ParseExpression(); - if (rightNode == null) return null; + if (rightNode == null) + { + return null; + } return new MemberExpression(leftNode, "->", rightNode); } @@ -1804,13 +2212,22 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { _position += 2; BaseNode condition = ParseExpression(); - if (condition == null) return null; + if (condition == null) + { + return null; + } leftNode = ParseExpression(); - if (leftNode == null) return null; + if (leftNode == null) + { + return null; + } rightNode = ParseExpression(); - if (rightNode == null) return null; + if (rightNode == null) + { + return null; + } return new ConditionalExpression(condition, leftNode, rightNode); } @@ -1821,10 +2238,16 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'c': _position += 2; BaseNode to = ParseType(); - if (to == null) return null; + if (to == null) + { + return null; + } BaseNode @from = ParseExpression(); - if (@from == null) return null; + if (@from == null) + { + return null; + } return new CastExpression("reinterpret_cast", to, @from); case 'm': @@ -1847,16 +2270,25 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'c': _position += 2; BaseNode to = ParseType(); - if (to == null) return null; + if (to == null) + { + return null; + } BaseNode @from = ParseExpression(); - if (@from == null) return null; + if (@from == null) + { + return null; + } return new CastExpression("static_cast", to, @from); case 'p': _position += 2; expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } return new PackedTemplateParameterExpansion(expression); case 'r': @@ -1864,13 +2296,19 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 't': _position += 2; BaseNode enclosedType = ParseType(); - if (enclosedType == null) return null; + if (enclosedType == null) + { + return null; + } return new EnclosedExpression("sizeof (", enclosedType, ")"); case 'z': _position += 2; expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } return new EnclosedExpression("sizeof (", expression, ")"); case 'Z': @@ -1881,12 +2319,18 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'T': // FIXME: ??? Not entire sure if it's right sizeofParamNode = ParseFunctionParameter(); - if (sizeofParamNode == null) return null; + if (sizeofParamNode == null) + { + return null; + } return new EnclosedExpression("sizeof...(", new PackedTemplateParameterExpansion(sizeofParamNode), ")"); case 'f': sizeofParamNode = ParseFunctionParameter(); - if (sizeofParamNode == null) return null; + if (sizeofParamNode == null) + { + return null; + } return new EnclosedExpression("sizeof...(", sizeofParamNode, ")"); } @@ -1897,7 +2341,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler while (!ConsumeIf("E")) { BaseNode argument = ParseTemplateArgument(); - if (argument == null) return null; + if (argument == null) + { + return null; + } arguments.Add(argument); } @@ -1909,24 +2356,36 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { case 'e': expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } return new EnclosedExpression("typeid (", expression, ")"); case 't': BaseNode enclosedType = ParseExpression(); - if (enclosedType == null) return null; + if (enclosedType == null) + { + return null; + } return new EnclosedExpression("typeid (", enclosedType, ")"); case 'l': _position += 2; BaseNode typeNode = ParseType(); - if (typeNode == null) return null; + if (typeNode == null) + { + return null; + } List bracedExpressions = new List(); while (!ConsumeIf("E")) { expression = ParseBracedExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } bracedExpressions.Add(expression); } @@ -1937,14 +2396,20 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'w': _position += 2; expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } return new ThrowExpression(expression); } return null; } - if (char.IsDigit(Peek())) return ParseUnresolvedName(); + if (char.IsDigit(Peek())) + { + return ParseUnresolvedName(); + } return null; } @@ -1952,7 +2417,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler private BaseNode ParseIntegerLiteral(string literalName) { string number = ParseNumber(true); - if (number == null || number.Length == 0 || !ConsumeIf("E")) return null; + if (number == null || number.Length == 0 || !ConsumeIf("E")) + { + return null; + } return new IntegerLiteral(literalName, number); } @@ -1966,7 +2434,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= L _Z E # external name private BaseNode ParseExpressionPrimary() { - if (!ConsumeIf("L")) return null; + if (!ConsumeIf("L")) + { + return null; + } switch (Peek()) { @@ -1974,9 +2445,15 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler _position++; return ParseIntegerLiteral("wchar_t"); case 'b': - if (ConsumeIf("b0E")) return new NameType("false", NodeType.BooleanExpression); + if (ConsumeIf("b0E")) + { + return new NameType("false", NodeType.BooleanExpression); + } - if (ConsumeIf("b1E")) return new NameType("true", NodeType.BooleanExpression); + if (ConsumeIf("b1E")) + { + return new NameType("true", NodeType.BooleanExpression); + } return null; case 'c': @@ -2027,17 +2504,26 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (ConsumeIf("_Z")) { BaseNode encoding = ParseEncoding(); - if (encoding != null && ConsumeIf("E")) return encoding; + if (encoding != null && ConsumeIf("E")) + { + return encoding; + } } return null; case 'T': return null; default: BaseNode type = ParseType(); - if (type == null) return null; + if (type == null) + { + return null; + } string number = ParseNumber(); - if (number == null || number.Length == 0 || !ConsumeIf("E")) return null; + if (number == null || number.Length == 0 || !ConsumeIf("E")) + { + return null; + } return new IntegerCastExpression(type, number); } @@ -2047,12 +2533,21 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= DT E # decltype of an expression (C++0x) private BaseNode ParseDecltype() { - if (!ConsumeIf("D") || !ConsumeIf("t") && !ConsumeIf("T")) return null; + if (!ConsumeIf("D") || !ConsumeIf("t") && !ConsumeIf("T")) + { + return null; + } BaseNode expression = ParseExpression(); - if (expression == null) return null; + if (expression == null) + { + return null; + } - if (!ConsumeIf("E")) return null; + if (!ConsumeIf("E")) + { + return null; + } return new EnclosedExpression("decltype(", expression, ")"); } @@ -2063,16 +2558,25 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= private BaseNode ParseTemplateParam() { - if (!ConsumeIf("T")) return null; + if (!ConsumeIf("T")) + { + return null; + } int index = 0; if (!ConsumeIf("_")) { index = ParsePositiveNumber(); - if (index < 0) return null; + if (index < 0) + { + return null; + } index++; - if (!ConsumeIf("_")) return null; + if (!ConsumeIf("_")) + { + return null; + } } // 5.1.8: TODO: lambda? @@ -2085,7 +2589,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler _forwardTemplateReferenceList.Add(forwardTemplateReference); return forwardTemplateReference; } - if (index >= _templateParamList.Count) return null; + if (index >= _templateParamList.Count) + { + return null; + } return _templateParamList[index]; } @@ -2093,30 +2600,48 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= I + E private BaseNode ParseTemplateArguments(bool hasContext = false) { - if (!ConsumeIf("I")) return null; + if (!ConsumeIf("I")) + { + return null; + } - if (hasContext) _templateParamList.Clear(); + if (hasContext) + { + _templateParamList.Clear(); + } List args = new List(); while (!ConsumeIf("E")) + { if (hasContext) { List templateParamListTemp = new List(_templateParamList); BaseNode templateArgument = ParseTemplateArgument(); _templateParamList = templateParamListTemp; - if (templateArgument == null) return null; + if (templateArgument == null) + { + return null; + } args.Add(templateArgument); - if (templateArgument.GetType().Equals(NodeType.PackedTemplateArgument)) templateArgument = new PackedTemplateParameter(((NodeArray)templateArgument).Nodes); + if (templateArgument.GetType().Equals(NodeType.PackedTemplateArgument)) + { + templateArgument = new PackedTemplateParameter(((NodeArray)templateArgument).Nodes); + } + _templateParamList.Add(templateArgument); } else { BaseNode templateArgument = ParseTemplateArgument(); - if (templateArgument == null) return null; + if (templateArgument == null) + { + return null; + } args.Add(templateArgument); } + } return new TemplateArguments(args); } @@ -2134,7 +2659,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler case 'X': _position++; BaseNode expression = ParseExpression(); - if (expression == null || !ConsumeIf("E")) return null; + if (expression == null || !ConsumeIf("E")) + { + return null; + } return expression; // @@ -2147,7 +2675,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler while (!ConsumeIf("E")) { BaseNode templateArgument = ParseTemplateArgument(); - if (templateArgument == null) return null; + if (templateArgument == null) + { + return null; + } templateArguments.Add(templateArgument); } @@ -2175,7 +2706,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (Peek() == 'T') { BaseNode templateParam = ParseTemplateParam(); - if (templateParam == null) return null; + if (templateParam == null) + { + return null; + } _substitutionList.Add(templateParam); return templateParam; @@ -2183,7 +2717,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler else if (Peek() == 'D') { BaseNode declType = ParseDecltype(); - if (declType == null) return null; + if (declType == null) + { + return null; + } _substitutionList.Add(declType); return declType; @@ -2195,12 +2732,18 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler private BaseNode ParseSimpleId() { BaseNode sourceName = ParseSourceName(); - if (sourceName == null) return null; + if (sourceName == null) + { + return null; + } if (Peek() == 'I') { BaseNode templateArguments = ParseTemplateArguments(); - if (templateArguments == null) return null; + if (templateArguments == null) + { + return null; + } return new NameTypeWithTemplateArguments(sourceName, templateArguments); } @@ -2213,10 +2756,18 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { BaseNode node; if (char.IsDigit(Peek())) + { node = ParseSimpleId(); + } else + { node = ParseUnresolvedType(); - if (node == null) return null; + } + + if (node == null) + { + return null; + } return new DtorName(node); } @@ -2231,17 +2782,28 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler private BaseNode ParseBaseUnresolvedName() { if (char.IsDigit(Peek())) + { return ParseSimpleId(); - else if (ConsumeIf("dn")) return ParseDestructorName(); + } + else if (ConsumeIf("dn")) + { + return ParseDestructorName(); + } ConsumeIf("on"); BaseNode operatorName = ParseOperatorName(null); - if (operatorName == null) return null; + if (operatorName == null) + { + return null; + } if (Peek() == 'I') { BaseNode templateArguments = ParseTemplateArguments(); - if (templateArguments == null) return null; + if (templateArguments == null) + { + return null; + } return new NameTypeWithTemplateArguments(operatorName, templateArguments); } @@ -2260,28 +2822,46 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (ConsumeIf("srN")) { result = ParseUnresolvedType(); - if (result == null) return null; + if (result == null) + { + return null; + } if (Peek() == 'I') { BaseNode templateArguments = ParseTemplateArguments(); - if (templateArguments == null) return null; + if (templateArguments == null) + { + return null; + } result = new NameTypeWithTemplateArguments(result, templateArguments); - if (result == null) return null; + if (result == null) + { + return null; + } } while (!ConsumeIf("E")) { BaseNode simpleId = ParseSimpleId(); - if (simpleId == null) return null; + if (simpleId == null) + { + return null; + } result = new QualifiedName(result, simpleId); - if (result == null) return null; + if (result == null) + { + return null; + } } BaseNode baseName = ParseBaseUnresolvedName(); - if (baseName == null) return null; + if (baseName == null) + { + return null; + } return new QualifiedName(result, baseName); } @@ -2292,9 +2872,15 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (!ConsumeIf("sr")) { result = ParseBaseUnresolvedName(); - if (result == null) return null; + if (result == null) + { + return null; + } - if (isGlobal) result = new GlobalQualifiedName(result); + if (isGlobal) + { + result = new GlobalQualifiedName(result); + } return result; } @@ -2305,38 +2891,65 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler do { BaseNode qualifier = ParseSimpleId(); - if (qualifier == null) return null; + if (qualifier == null) + { + return null; + } if (result != null) + { result = new QualifiedName(result, qualifier); + } else if (isGlobal) + { result = new GlobalQualifiedName(qualifier); + } else + { result = qualifier; + } - if (result == null) return null; + if (result == null) + { + return null; + } } while (!ConsumeIf("E")); } // ::= sr [tempate-args] # T::x / decltype(p)::x else { result = ParseUnresolvedType(); - if (result == null) return null; + if (result == null) + { + return null; + } if (Peek() == 'I') { BaseNode templateArguments = ParseTemplateArguments(); - if (templateArguments == null) return null; + if (templateArguments == null) + { + return null; + } result = new NameTypeWithTemplateArguments(result, templateArguments); - if (result == null) return null; + if (result == null) + { + return null; + } } } - if (result == null) return null; + if (result == null) + { + return null; + } BaseNode baseUnresolvedName = ParseBaseUnresolvedName(); - if (baseUnresolvedName == null) return null; + if (baseUnresolvedName == null) + { + return null; + } return new QualifiedName(result, baseUnresolvedName); } @@ -2348,7 +2961,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (ConsumeIf("St")) { BaseNode unresolvedName = ParseUnresolvedName(context); - if (unresolvedName == null) return null; + if (unresolvedName == null) + { + return null; + } return new StdQualifiedName(unresolvedName); } @@ -2360,23 +2976,38 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler private BaseNode ParseNestedName(NameParserContext context) { // Impossible in theory - if (Consume() != 'N') return null; + if (Consume() != 'N') + { + return null; + } BaseNode result = null; CVType cv = new CVType(ParseCvQualifiers(), null); - if (context != null) context.Cv = cv; + if (context != null) + { + context.Cv = cv; + } SimpleReferenceType Ref = ParseRefQualifiers(); - if (context != null) context.Ref = Ref; + if (context != null) + { + context.Ref = Ref; + } - if (ConsumeIf("St")) result = new NameType("std"); + if (ConsumeIf("St")) + { + result = new NameType("std"); + } while (!ConsumeIf("E")) { // end if (ConsumeIf("M")) { - if (result == null) return null; + if (result == null) + { + return null; + } continue; } @@ -2386,7 +3017,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (c == 'T') { BaseNode templateParam = ParseTemplateParam(); - if (templateParam == null) return null; + if (templateParam == null) + { + return null; + } result = CreateNameNode(result, templateParam, context); _substitutionList.Add(result); @@ -2397,10 +3031,16 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (c == 'I') { BaseNode templateArgument = ParseTemplateArguments(context != null); - if (templateArgument == null || result == null) return null; + if (templateArgument == null || result == null) + { + return null; + } result = new NameTypeWithTemplateArguments(result, templateArgument); - if (context != null) context.FinishWithTemplateArguments = true; + if (context != null) + { + context.FinishWithTemplateArguments = true; + } _substitutionList.Add(result); continue; @@ -2410,7 +3050,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (c == 'D' && (Peek(1) == 't' || Peek(1) == 'T')) { BaseNode decltype = ParseDecltype(); - if (decltype == null) return null; + if (decltype == null) + { + return null; + } result = CreateNameNode(result, decltype, context); _substitutionList.Add(result); @@ -2421,10 +3064,16 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (c == 'S' && Peek(1) != 't') { BaseNode substitution = ParseSubstitution(); - if (substitution == null) return null; + if (substitution == null) + { + return null; + } result = CreateNameNode(result, substitution, context); - if (result != substitution) _substitutionList.Add(substitution); + if (result != substitution) + { + _substitutionList.Add(substitution); + } continue; } @@ -2433,28 +3082,44 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (c == 'C' || c == 'D' && Peek(1) != 'C') { // We cannot have nothing before this - if (result == null) return null; + if (result == null) + { + return null; + } BaseNode ctOrDtorName = ParseCtorDtorName(context, result); - if (ctOrDtorName == null) return null; + if (ctOrDtorName == null) + { + return null; + } result = CreateNameNode(result, ctOrDtorName, context); // TODO: ABI Tags (before) - if (result == null) return null; + if (result == null) + { + return null; + } _substitutionList.Add(result); continue; } BaseNode unqualifiedName = ParseUnqualifiedName(context); - if (unqualifiedName == null) return null; + if (unqualifiedName == null) + { + return null; + } + result = CreateNameNode(result, unqualifiedName, context); _substitutionList.Add(result); } - if (result == null || _substitutionList.Count == 0) return null; + if (result == null || _substitutionList.Count == 0) + { + return null; + } _substitutionList.RemoveAt(_substitutionList.Count - 1); return result; @@ -2464,12 +3129,19 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= __ _ # when number >= 10 private void ParseDiscriminator() { - if (Count() == 0) return; + if (Count() == 0) + { + return; + } // We ignore the discriminator, we don't need it. if (ConsumeIf("_")) { ConsumeIf("_"); - while (char.IsDigit(Peek()) && Count() != 0) Consume(); + while (char.IsDigit(Peek()) && Count() != 0) + { + Consume(); + } + ConsumeIf("_"); } } @@ -2479,10 +3151,16 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler // ::= Z Ed [ ] _ private BaseNode ParseLocalName(NameParserContext context) { - if (!ConsumeIf("Z")) return null; + if (!ConsumeIf("Z")) + { + return null; + } BaseNode encoding = ParseEncoding(); - if (encoding == null || !ConsumeIf("E")) return null; + if (encoding == null || !ConsumeIf("E")) + { + return null; + } BaseNode entityName; if (ConsumeIf("s")) @@ -2493,16 +3171,25 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler else if (ConsumeIf("d")) { ParseNumber(true); - if (!ConsumeIf("_")) return null; + if (!ConsumeIf("_")) + { + return null; + } entityName = ParseName(context); - if (entityName == null) return null; + if (entityName == null) + { + return null; + } return new LocalName(encoding, entityName); } entityName = ParseName(context); - if (entityName == null) return null; + if (entityName == null) + { + return null; + } ParseDiscriminator(); return new LocalName(encoding, entityName); @@ -2516,35 +3203,62 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler { ConsumeIf("L"); - if (Peek() == 'N') return ParseNestedName(context); + if (Peek() == 'N') + { + return ParseNestedName(context); + } - if (Peek() == 'Z') return ParseLocalName(context); + if (Peek() == 'Z') + { + return ParseLocalName(context); + } if (Peek() == 'S' && Peek(1) != 't') { BaseNode substitution = ParseSubstitution(); - if (substitution == null) return null; + if (substitution == null) + { + return null; + } - if (Peek() != 'I') return null; + if (Peek() != 'I') + { + return null; + } BaseNode templateArguments = ParseTemplateArguments(context != null); - if (templateArguments == null) return null; + if (templateArguments == null) + { + return null; + } - if (context != null) context.FinishWithTemplateArguments = true; + if (context != null) + { + context.FinishWithTemplateArguments = true; + } return new NameTypeWithTemplateArguments(substitution, templateArguments); } BaseNode result = ParseUnscopedName(context); - if (result == null) return null; + if (result == null) + { + return null; + } if (Peek() == 'I') { _substitutionList.Add(result); BaseNode templateArguments = ParseTemplateArguments(context != null); - if (templateArguments == null) return null; + if (templateArguments == null) + { + return null; + } - if (context != null) context.FinishWithTemplateArguments = true; + if (context != null) + { + context.FinishWithTemplateArguments = true; + } return new NameTypeWithTemplateArguments(result, templateArguments); } @@ -2564,14 +3278,23 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler private BaseNode ParseEncoding() { NameParserContext context = new NameParserContext(); - if (Peek() == 'T' || Peek() == 'G' && Peek(1) == 'V') return ParseSpecialName(context); + if (Peek() == 'T' || Peek() == 'G' && Peek(1) == 'V') + { + return ParseSpecialName(context); + } BaseNode name = ParseName(context); - if (name == null) return null; + if (name == null) + { + return null; + } // TODO: compute template refs here - if (IsEncodingEnd()) return name; + if (IsEncodingEnd()) + { + return name; + } // TODO: Ua9enable_ifI @@ -2579,10 +3302,16 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (!context.CtorDtorConversion && context.FinishWithTemplateArguments) { returnType = ParseType(); - if (returnType == null) return null; + if (returnType == null) + { + return null; + } } - if (ConsumeIf("v")) return new EncodedFunction(name, null, context.Cv, context.Ref, null, returnType); + if (ConsumeIf("v")) + { + return new EncodedFunction(name, null, context.Cv, context.Ref, null, returnType); + } List Params = new List(); @@ -2593,7 +3322,10 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler while (!IsEncodingEnd()) { BaseNode param = ParseType(); - if (param == null) return null; + if (param == null) + { + return null; + } Params.Add(param); } @@ -2608,13 +3340,21 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler if (ConsumeIf("_Z")) { BaseNode encoding = ParseEncoding(); - if (encoding != null && Count() == 0) return encoding; + if (encoding != null && Count() == 0) + { + return encoding; + } + return null; } else { BaseNode type = ParseType(); - if (type != null && Count() == 0) return type; + if (type != null && Count() == 0) + { + return type; + } + return null; } } diff --git a/Ryujinx.HLE/HOS/Font/SharedFontManager.cs b/Ryujinx.HLE/HOS/Font/SharedFontManager.cs index 4cd48a328c..6d56f33cc0 100644 --- a/Ryujinx.HLE/HOS/Font/SharedFontManager.cs +++ b/Ryujinx.HLE/HOS/Font/SharedFontManager.cs @@ -61,7 +61,10 @@ namespace Ryujinx.HLE.HOS.Font uint start = fontOffset; - for (; fontOffset - start < data.Length; fontOffset++) _memory.WriteByte(_physicalAddress + fontOffset, data[fontOffset - start]); + for (; fontOffset - start < data.Length; fontOffset++) + { + _memory.WriteByte(_physicalAddress + fontOffset, data[fontOffset - start]); + } return info; } @@ -82,10 +85,12 @@ namespace Ryujinx.HLE.HOS.Font }; if (fontOffset > Horizon.FontSize) + { throw new InvalidSystemResourceException( $"The sum of all fonts size exceed the shared memory size. " + $"Please make sure that the fonts don't exceed {Horizon.FontSize} bytes in total. " + $"(actual size: {fontOffset} bytes)."); + } } } diff --git a/Ryujinx.HLE/HOS/GlobalStateTable.cs b/Ryujinx.HLE/HOS/GlobalStateTable.cs index 6ad99b2b06..ea14774ca0 100644 --- a/Ryujinx.HLE/HOS/GlobalStateTable.cs +++ b/Ryujinx.HLE/HOS/GlobalStateTable.cs @@ -28,28 +28,40 @@ namespace Ryujinx.HLE.HOS public object GetData(Process process, int id) { - if (_dictByProcess.TryGetValue(process, out IdDictionary dict)) return dict.GetData(id); + if (_dictByProcess.TryGetValue(process, out IdDictionary dict)) + { + return dict.GetData(id); + } return null; } public T GetData(Process process, int id) { - if (_dictByProcess.TryGetValue(process, out IdDictionary dict)) return dict.GetData(id); + if (_dictByProcess.TryGetValue(process, out IdDictionary dict)) + { + return dict.GetData(id); + } return default(T); } public object Delete(Process process, int id) { - if (_dictByProcess.TryGetValue(process, out IdDictionary dict)) return dict.Delete(id); + if (_dictByProcess.TryGetValue(process, out IdDictionary dict)) + { + return dict.Delete(id); + } return null; } public ICollection DeleteProcess(Process process) { - if (_dictByProcess.TryRemove(process, out IdDictionary dict)) return dict.Clear(); + if (_dictByProcess.TryRemove(process, out IdDictionary dict)) + { + return dict.Clear(); + } return null; } diff --git a/Ryujinx.HLE/HOS/Horizon.cs b/Ryujinx.HLE/HOS/Horizon.cs index 41c0c4a5ed..8f4584f767 100644 --- a/Ryujinx.HLE/HOS/Horizon.cs +++ b/Ryujinx.HLE/HOS/Horizon.cs @@ -77,7 +77,9 @@ namespace Ryujinx.HLE.HOS if (!device.Memory.Allocator.TryAllocate(HidSize, out long hidPa) || !device.Memory.Allocator.TryAllocate(FontSize, out long fontPa)) + { throw new InvalidOperationException(); + } HidSharedMem = new KSharedMemory(hidPa, HidSize); FontSharedMem = new KSharedMemory(fontPa, FontSize); @@ -91,7 +93,10 @@ namespace Ryujinx.HLE.HOS public void LoadCart(string exeFsDir, string romFsFile = null) { - if (romFsFile != null) _device.FileSystem.LoadRomFs(romFsFile); + if (romFsFile != null) + { + _device.FileSystem.LoadRomFs(romFsFile); + } string npdmFileName = Path.Combine(exeFsDir, "main.npdm"); @@ -117,7 +122,10 @@ namespace Ryujinx.HLE.HOS { foreach (string file in Directory.GetFiles(exeFsDir, fileName)) { - if (Path.GetExtension(file) != string.Empty) continue; + if (Path.GetExtension(file) != string.Empty) + { + continue; + } Logger.PrintInfo(LogClass.Loader, $"Loading {Path.GetFileNameWithoutExtension(file)}..."); @@ -132,7 +140,10 @@ namespace Ryujinx.HLE.HOS } } - if (!(mainProcess.MetaData?.Is64Bits ?? true)) throw new NotImplementedException("32-bit titles are unsupported!"); + if (!(mainProcess.MetaData?.Is64Bits ?? true)) + { + throw new NotImplementedException("32-bit titles are unsupported!"); + } CurrentTitle = mainProcess.MetaData.Aci0.TitleId.ToString("x16"); @@ -167,7 +178,10 @@ namespace Ryujinx.HLE.HOS private (Nca Main, Nca Control) GetXciGameData(Xci xci) { - if (xci.SecurePartition == null) throw new InvalidDataException("Could not find XCI secure partition"); + if (xci.SecurePartition == null) + { + throw new InvalidDataException("Could not find XCI secure partition"); + } Nca mainNca = null; Nca patchNca = null; @@ -182,8 +196,13 @@ namespace Ryujinx.HLE.HOS if (nca.Header.ContentType == ContentType.Program) { if (nca.Sections.Any(x => x?.Type == SectionType.Romfs)) + { mainNca = nca; - else if (nca.Sections.Any(x => x?.Type == SectionType.Bktr)) patchNca = nca; + } + else if (nca.Sections.Any(x => x?.Type == SectionType.Bktr)) + { + patchNca = nca; + } } else if (nca.Header.ContentType == ContentType.Control) { @@ -191,11 +210,17 @@ namespace Ryujinx.HLE.HOS } } - if (mainNca == null) Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided XCI file"); + if (mainNca == null) + { + Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided XCI file"); + } mainNca.SetBaseNca(patchNca); - if (controlNca != null) ReadControlData(controlNca); + if (controlNca != null) + { + ReadControlData(controlNca); + } if (patchNca != null) { @@ -251,8 +276,13 @@ namespace Ryujinx.HLE.HOS Nca nca = new Nca(KeySet, nsp.OpenFile(ncaFile), true); if (nca.Header.ContentType == ContentType.Program) + { mainNca = nca; - else if (nca.Header.ContentType == ContentType.Control) controlNca = nca; + } + else if (nca.Header.ContentType == ContentType.Control) + { + controlNca = nca; + } } if (mainNca != null) @@ -311,7 +341,10 @@ namespace Ryujinx.HLE.HOS { foreach (PfsFileEntry file in exefs.Files.Where(x => x.Name.StartsWith(filename))) { - if (Path.GetExtension(file.Name) != string.Empty) continue; + if (Path.GetExtension(file.Name) != string.Empty) + { + continue; + } Logger.PrintInfo(LogClass.Loader, $"Loading {filename}..."); @@ -335,17 +368,27 @@ namespace Ryujinx.HLE.HOS CurrentTitle = controlData.Languages[(int)State.DesiredTitleLanguage].Title; - if (string.IsNullOrWhiteSpace(CurrentTitle)) CurrentTitle = controlData.Languages.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title; + if (string.IsNullOrWhiteSpace(CurrentTitle)) + { + CurrentTitle = controlData.Languages.ToList().Find(x => !string.IsNullOrWhiteSpace(x.Title)).Title; + } return controlData; } if (controlNca != null) + { mainProcess.ControlData = ReadControlData(); + } else + { CurrentTitle = mainProcess.MetaData.Aci0.TitleId.ToString("x16"); + } - if (!mainProcess.MetaData.Is64Bits) throw new NotImplementedException("32-bit titles are unsupported!"); + if (!mainProcess.MetaData.Is64Bits) + { + throw new NotImplementedException("32-bit titles are unsupported!"); + } LoadNso("rtld"); @@ -372,7 +415,10 @@ namespace Ryujinx.HLE.HOS string switchDir = Path.GetDirectoryName(tempPath); - if (!Directory.Exists(switchDir)) Directory.CreateDirectory(switchDir); + if (!Directory.Exists(switchDir)) + { + Directory.CreateDirectory(switchDir); + } File.Copy(filePath, tempPath, true); @@ -411,11 +457,20 @@ namespace Ryujinx.HLE.HOS string localTitleKeyFile = Path.Combine(basePath, "title.keys"); string localConsoleKeyFile = Path.Combine(basePath, "console.keys"); - if (File.Exists(localKeyFile)) keyFile = localKeyFile; + if (File.Exists(localKeyFile)) + { + keyFile = localKeyFile; + } - if (File.Exists(localTitleKeyFile)) titleKeyFile = localTitleKeyFile; + if (File.Exists(localTitleKeyFile)) + { + titleKeyFile = localTitleKeyFile; + } - if (File.Exists(localConsoleKeyFile)) consoleKeyFile = localConsoleKeyFile; + if (File.Exists(localConsoleKeyFile)) + { + consoleKeyFile = localConsoleKeyFile; + } } } @@ -434,7 +489,10 @@ namespace Ryujinx.HLE.HOS { int processId = 0; - while (_processes.ContainsKey(processId)) processId++; + while (_processes.ContainsKey(processId)) + { + processId++; + } process = new Process(_device, processId, metaData); @@ -470,12 +528,18 @@ namespace Ryujinx.HLE.HOS public void EnableMultiCoreScheduling() { - if (!_hasStarted) Scheduler.MultiCoreScheduling = true; + if (!_hasStarted) + { + Scheduler.MultiCoreScheduling = true; + } } public void DisableMultiCoreScheduling() { - if (!_hasStarted) Scheduler.MultiCoreScheduling = false; + if (!_hasStarted) + { + Scheduler.MultiCoreScheduling = false; + } } public void Dispose() @@ -486,7 +550,12 @@ namespace Ryujinx.HLE.HOS protected virtual void Dispose(bool disposing) { if (disposing) - foreach (Process process in _processes.Values) process.Dispose(); + { + foreach (Process process in _processes.Values) + { + process.Dispose(); + } + } } } } diff --git a/Ryujinx.HLE/HOS/IdDictionary.cs b/Ryujinx.HLE/HOS/IdDictionary.cs index 25705ef079..173c291b46 100644 --- a/Ryujinx.HLE/HOS/IdDictionary.cs +++ b/Ryujinx.HLE/HOS/IdDictionary.cs @@ -21,28 +21,42 @@ namespace Ryujinx.HLE.HOS public int Add(object data) { for (int id = 1; id < int.MaxValue; id++) - if (_objs.TryAdd(id, data)) return id; + { + if (_objs.TryAdd(id, data)) + { + return id; + } + } throw new InvalidOperationException(); } public object GetData(int id) { - if (_objs.TryGetValue(id, out object data)) return data; + if (_objs.TryGetValue(id, out object data)) + { + return data; + } return null; } public T GetData(int id) { - if (_objs.TryGetValue(id, out object data) && data is T) return (T)data; + if (_objs.TryGetValue(id, out object data) && data is T) + { + return (T)data; + } return default(T); } public object Delete(int id) { - if (_objs.TryRemove(id, out object obj)) return obj; + if (_objs.TryRemove(id, out object obj)) + { + return obj; + } return null; } diff --git a/Ryujinx.HLE/HOS/Ipc/IpcHandleDesc.cs b/Ryujinx.HLE/HOS/Ipc/IpcHandleDesc.cs index cb3c16c26a..856329c09d 100644 --- a/Ryujinx.HLE/HOS/Ipc/IpcHandleDesc.cs +++ b/Ryujinx.HLE/HOS/Ipc/IpcHandleDesc.cs @@ -23,9 +23,15 @@ namespace Ryujinx.HLE.HOS.Ipc PId = HasPId ? reader.ReadInt64() : 0; - for (int index = 0; index < ToCopy.Length; index++) ToCopy[index] = reader.ReadInt32(); + for (int index = 0; index < ToCopy.Length; index++) + { + ToCopy[index] = reader.ReadInt32(); + } - for (int index = 0; index < ToMove.Length; index++) ToMove[index] = reader.ReadInt32(); + for (int index = 0; index < ToMove.Length; index++) + { + ToMove[index] = reader.ReadInt32(); + } } public IpcHandleDesc(int[] copy, int[] move) @@ -64,11 +70,20 @@ namespace Ryujinx.HLE.HOS.Ipc writer.Write(word); - if (HasPId) writer.Write((long)PId); + if (HasPId) + { + writer.Write((long)PId); + } - foreach (int handle in ToCopy) writer.Write(handle); + foreach (int handle in ToCopy) + { + writer.Write(handle); + } - foreach (int handle in ToMove) writer.Write(handle); + foreach (int handle in ToMove) + { + writer.Write(handle); + } return ms.ToArray(); } diff --git a/Ryujinx.HLE/HOS/Ipc/IpcHandler.cs b/Ryujinx.HLE/HOS/Ipc/IpcHandler.cs index 9a55038be5..71a68f5f25 100644 --- a/Ryujinx.HLE/HOS/Ipc/IpcHandler.cs +++ b/Ryujinx.HLE/HOS/Ipc/IpcHandler.cs @@ -73,9 +73,12 @@ namespace Ryujinx.HLE.HOS.Ipc { int unknown = reqReader.ReadInt32(); - if (process.HandleTable.GenerateHandle(session, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (process.HandleTable.GenerateHandle(session, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } - response.HandleDesc = IpcHandleDesc.MakeMove(handle); + response.HandleDesc = IpcHandleDesc.MakeMove(handle); request = FillResponse(response, 0); @@ -106,7 +109,10 @@ namespace Ryujinx.HLE.HOS.Ipc { BinaryWriter writer = new BinaryWriter(ms); - foreach (int value in values) writer.Write(value); + foreach (int value in values) + { + writer.Write(value); + } return FillResponse(response, result, ms.ToArray()); } @@ -123,7 +129,10 @@ namespace Ryujinx.HLE.HOS.Ipc writer.Write(IpcMagic.Sfco); writer.Write(result); - if (data != null) writer.Write(data); + if (data != null) + { + writer.Write(data); + } response.RawData = ms.ToArray(); } diff --git a/Ryujinx.HLE/HOS/Ipc/IpcMessage.cs b/Ryujinx.HLE/HOS/Ipc/IpcMessage.cs index 148cddac1d..59db9d2b2e 100644 --- a/Ryujinx.HLE/HOS/Ipc/IpcMessage.cs +++ b/Ryujinx.HLE/HOS/Ipc/IpcMessage.cs @@ -56,13 +56,22 @@ namespace Ryujinx.HLE.HOS.Ipc int recvListFlags = (word1 >> 10) & 0xf; bool hndDescEnable = ((word1 >> 31) & 0x1) != 0; - if (hndDescEnable) HandleDesc = new IpcHandleDesc(reader); + if (hndDescEnable) + { + HandleDesc = new IpcHandleDesc(reader); + } - for (int index = 0; index < ptrBuffCount; index++) PtrBuff.Add(new IpcPtrBuffDesc(reader)); + for (int index = 0; index < ptrBuffCount; index++) + { + PtrBuff.Add(new IpcPtrBuffDesc(reader)); + } void ReadBuff(List buff, int count) { - for (int index = 0; index < count; index++) buff.Add(new IpcBuffDesc(reader)); + for (int index = 0; index < count; index++) + { + buff.Add(new IpcBuffDesc(reader)); + } } ReadBuff(SendBuff, sendBuffCount); @@ -80,14 +89,22 @@ namespace Ryujinx.HLE.HOS.Ipc int recvListCount = recvListFlags - 2; if (recvListCount == 0) + { recvListCount = 1; - else if (recvListCount < 0) recvListCount = 0; + } + else if (recvListCount < 0) + { + recvListCount = 0; + } RawData = reader.ReadBytes(rawDataSize); reader.BaseStream.Seek(recvListPos, SeekOrigin.Begin); - for (int index = 0; index < recvListCount; index++) RecvListBuff.Add(new IpcRecvListBuffDesc(reader)); + for (int index = 0; index < recvListCount; index++) + { + RecvListBuff.Add(new IpcRecvListBuffDesc(reader)); + } } public byte[] GetBytes(long cmdPtr) @@ -107,7 +124,10 @@ namespace Ryujinx.HLE.HOS.Ipc byte[] handleData = new byte[0]; - if (HandleDesc != null) handleData = HandleDesc.GetBytes(); + if (HandleDesc != null) + { + handleData = HandleDesc.GetBytes(); + } int dataLength = RawData?.Length ?? 0; @@ -122,7 +142,10 @@ namespace Ryujinx.HLE.HOS.Ipc word1 = dataLength & 0x3ff; - if (HandleDesc != null) word1 |= 1 << 31; + if (HandleDesc != null) + { + word1 |= 1 << 31; + } writer.Write(word0); writer.Write(word1); @@ -130,7 +153,10 @@ namespace Ryujinx.HLE.HOS.Ipc ms.Seek(pad0, SeekOrigin.Current); - if (RawData != null) writer.Write(RawData); + if (RawData != null) + { + writer.Write(RawData); + } writer.Write(new byte[pad1]); @@ -140,7 +166,10 @@ namespace Ryujinx.HLE.HOS.Ipc private long GetPadSize16(long position) { - if ((position & 0xf) != 0) return 0x10 - (position & 0xf); + if ((position & 0xf) != 0) + { + return 0x10 - (position & 0xf); + } return 0; } @@ -150,12 +179,16 @@ namespace Ryujinx.HLE.HOS.Ipc if (PtrBuff.Count > index && PtrBuff[index].Position != 0 && PtrBuff[index].Size != 0) + { return (PtrBuff[index].Position, PtrBuff[index].Size); + } if (SendBuff.Count > index && SendBuff[index].Position != 0 && SendBuff[index].Size != 0) + { return (SendBuff[index].Position, SendBuff[index].Size); + } return (0, 0); } @@ -165,12 +198,16 @@ namespace Ryujinx.HLE.HOS.Ipc if (RecvListBuff.Count > index && RecvListBuff[index].Position != 0 && RecvListBuff[index].Size != 0) + { return (RecvListBuff[index].Position, RecvListBuff[index].Size); + } if (ReceiveBuff.Count > index && ReceiveBuff[index].Position != 0 && ReceiveBuff[index].Size != 0) + { return (ReceiveBuff[index].Position, ReceiveBuff[index].Size); + } return (0, 0); } diff --git a/Ryujinx.HLE/HOS/Kernel/HleScheduler.cs b/Ryujinx.HLE/HOS/Kernel/HleScheduler.cs index 038775d9aa..ef8184bc4d 100644 --- a/Ryujinx.HLE/HOS/Kernel/HleScheduler.cs +++ b/Ryujinx.HLE/HOS/Kernel/HleScheduler.cs @@ -36,17 +36,29 @@ namespace Ryujinx.HLE.HOS.Kernel { KCoreContext coreContext = CoreContexts[core]; - if (coreContext.ContextSwitchNeeded && (coreContext.CurrentThread?.Context.IsCurrentThread() ?? false)) coreContext.ContextSwitch(); + if (coreContext.ContextSwitchNeeded && (coreContext.CurrentThread?.Context.IsCurrentThread() ?? false)) + { + coreContext.ContextSwitch(); + } - if (coreContext.CurrentThread?.Context.IsCurrentThread() ?? false) selectedCount++; + if (coreContext.CurrentThread?.Context.IsCurrentThread() ?? false) + { + selectedCount++; + } } if (selectedCount == 0) + { _coreManager.GetThread(Thread.CurrentThread).Reset(); + } else if (selectedCount == 1) + { _coreManager.GetThread(Thread.CurrentThread).Set(); + } else + { throw new InvalidOperationException("Thread scheduled in more than one core!"); + } } else { @@ -92,7 +104,10 @@ namespace Ryujinx.HLE.HOS.Kernel //If nothing was running before, then we are on a "external" //HLE thread, we don't need to wait. - if (!hasThreadExecuting) return; + if (!hasThreadExecuting) + { + return; + } } } diff --git a/Ryujinx.HLE/HOS/Kernel/KAddressArbiter.cs b/Ryujinx.HLE/HOS/Kernel/KAddressArbiter.cs index 37fe077b22..5e99ed20f0 100644 --- a/Ryujinx.HLE/HOS/Kernel/KAddressArbiter.cs +++ b/Ryujinx.HLE/HOS/Kernel/KAddressArbiter.cs @@ -70,7 +70,10 @@ namespace Ryujinx.HLE.HOS.Kernel _system.CriticalSectionLock.Unlock(); _system.CriticalSectionLock.Lock(); - if (currentThread.MutexOwner != null) currentThread.MutexOwner.RemoveMutexWaiter(currentThread); + if (currentThread.MutexOwner != null) + { + currentThread.MutexOwner.RemoveMutexWaiter(currentThread); + } _system.CriticalSectionLock.Unlock(); @@ -137,16 +140,25 @@ namespace Ryujinx.HLE.HOS.Kernel { currentThread.Reschedule(ThreadSchedState.Paused); - if (timeout > 0) _system.TimeManager.ScheduleFutureInvocation(currentThread, timeout); + if (timeout > 0) + { + _system.TimeManager.ScheduleFutureInvocation(currentThread, timeout); + } } _system.CriticalSectionLock.Unlock(); - if (timeout > 0) _system.TimeManager.UnscheduleFutureInvocation(currentThread); + if (timeout > 0) + { + _system.TimeManager.UnscheduleFutureInvocation(currentThread); + } _system.CriticalSectionLock.Lock(); - if (currentThread.MutexOwner != null) currentThread.MutexOwner.RemoveMutexWaiter(currentThread); + if (currentThread.MutexOwner != null) + { + currentThread.MutexOwner.RemoveMutexWaiter(currentThread); + } CondVarThreads.Remove(currentThread); @@ -165,7 +177,10 @@ namespace Ryujinx.HLE.HOS.Kernel { mutexValue = newOwnerThread.ThreadHandleForUserMutex; - if (count >= 2) mutexValue |= HasListenersMask; + if (count >= 2) + { + mutexValue |= HasListenersMask; + } newOwnerThread.SignaledObj = null; newOwnerThread.ObjSyncResult = 0; @@ -175,7 +190,10 @@ namespace Ryujinx.HLE.HOS.Kernel long result = 0; - if (!KernelToUserInt32(memory, mutexAddress, mutexValue)) result = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + if (!KernelToUserInt32(memory, mutexAddress, mutexValue)) + { + result = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + } return (result, newOwnerThread); } @@ -195,10 +213,16 @@ namespace Ryujinx.HLE.HOS.Kernel signaledThreads.Enqueue(thread); //If the count is <= 0, we should signal all threads waiting. - if (count >= 1 && --count == 0) break; + if (count >= 1 && --count == 0) + { + break; + } } - while (signaledThreads.TryDequeue(out KThread thread)) CondVarThreads.Remove(thread); + while (signaledThreads.TryDequeue(out KThread thread)) + { + CondVarThreads.Remove(thread); + } _system.CriticalSectionLock.Unlock(); } @@ -225,9 +249,13 @@ namespace Ryujinx.HLE.HOS.Kernel if (memory.TestExclusive(0, address)) { if (mutexValue != 0) + { memory.WriteInt32(address, mutexValue | HasListenersMask); + } else + { memory.WriteInt32(address, requester.ThreadHandleForUserMutex); + } memory.ClearExclusiveForStore(0); @@ -311,11 +339,17 @@ namespace Ryujinx.HLE.HOS.Kernel currentThread.Reschedule(ThreadSchedState.Paused); - if (timeout > 0) _system.TimeManager.ScheduleFutureInvocation(currentThread, timeout); + if (timeout > 0) + { + _system.TimeManager.ScheduleFutureInvocation(currentThread, timeout); + } _system.CriticalSectionLock.Unlock(); - if (timeout > 0) _system.TimeManager.UnscheduleFutureInvocation(currentThread); + if (timeout > 0) + { + _system.TimeManager.UnscheduleFutureInvocation(currentThread); + } _system.CriticalSectionLock.Lock(); @@ -369,6 +403,7 @@ namespace Ryujinx.HLE.HOS.Kernel } if (shouldDecrement) + { while (currentValue < value) { if (memory.TestExclusive(0, address)) @@ -384,6 +419,7 @@ namespace Ryujinx.HLE.HOS.Kernel currentValue = memory.ReadInt32(address); } + } memory.ClearExclusive(0); @@ -403,11 +439,17 @@ namespace Ryujinx.HLE.HOS.Kernel currentThread.Reschedule(ThreadSchedState.Paused); - if (timeout > 0) _system.TimeManager.ScheduleFutureInvocation(currentThread, timeout); + if (timeout > 0) + { + _system.TimeManager.ScheduleFutureInvocation(currentThread, timeout); + } _system.CriticalSectionLock.Unlock(); - if (timeout > 0) _system.TimeManager.UnscheduleFutureInvocation(currentThread); + if (timeout > 0) + { + _system.TimeManager.UnscheduleFutureInvocation(currentThread); + } _system.CriticalSectionLock.Lock(); @@ -433,17 +475,23 @@ namespace Ryujinx.HLE.HOS.Kernel int nextIndex = -1; for (int index = 0; index < threads.Count; index++) + { if (threads[index].DynamicPriority > thread.DynamicPriority) { nextIndex = index; break; } + } if (nextIndex != -1) + { threads.Insert(nextIndex, thread); + } else + { threads.Add(thread); + } } public long Signal(long address, int count) @@ -514,12 +562,21 @@ namespace Ryujinx.HLE.HOS.Kernel int waitingCount = 0; foreach (KThread thread in ArbiterThreads.Where(x => x.MutexAddress == address)) - if (++waitingCount > count) break; + { + if (++waitingCount > count) + { + break; + } + } if (waitingCount > 0) + { offset = waitingCount <= count || count <= 0 ? -1 : 0; + } else + { offset = 1; + } memory.SetExclusive(0, address); @@ -571,7 +628,10 @@ namespace Ryujinx.HLE.HOS.Kernel signaledThreads.Enqueue(thread); //If the count is <= 0, we should signal all threads waiting. - if (count >= 1 && --count == 0) break; + if (count >= 1 && --count == 0) + { + break; + } } while (signaledThreads.TryDequeue(out KThread thread)) diff --git a/Ryujinx.HLE/HOS/Kernel/KCoreContext.cs b/Ryujinx.HLE/HOS/Kernel/KCoreContext.cs index 5c8cb808f5..61d312099e 100644 --- a/Ryujinx.HLE/HOS/Kernel/KCoreContext.cs +++ b/Ryujinx.HLE/HOS/Kernel/KCoreContext.cs @@ -23,9 +23,15 @@ namespace Ryujinx.HLE.HOS.Kernel { SelectedThread = thread; - if (thread != null) thread.LastScheduledTicks = (uint)Environment.TickCount; + if (thread != null) + { + thread.LastScheduledTicks = (uint)Environment.TickCount; + } - if (SelectedThread != CurrentThread) ContextSwitchNeeded = true; + if (SelectedThread != CurrentThread) + { + ContextSwitchNeeded = true; + } } public void UpdateCurrentThread() @@ -39,7 +45,10 @@ namespace Ryujinx.HLE.HOS.Kernel { ContextSwitchNeeded = false; - if (CurrentThread != null) _coreManager.GetThread(CurrentThread.Context.Work).Reset(); + if (CurrentThread != null) + { + _coreManager.GetThread(CurrentThread.Context.Work).Reset(); + } CurrentThread = SelectedThread; diff --git a/Ryujinx.HLE/HOS/Kernel/KMemoryManager.cs b/Ryujinx.HLE/HOS/Kernel/KMemoryManager.cs index f11c2c9b6d..36dda57e89 100644 --- a/Ryujinx.HLE/HOS/Kernel/KMemoryManager.cs +++ b/Ryujinx.HLE/HOS/Kernel/KMemoryManager.cs @@ -53,7 +53,10 @@ namespace Ryujinx.HLE.HOS.Kernel AddressSpaceType addrType = AddressSpaceType.Addr39Bits; - if (process.MetaData != null) addrType = (AddressSpaceType)process.MetaData.AddressSpaceWidth; + if (process.MetaData != null) + { + addrType = (AddressSpaceType)process.MetaData.AddressSpaceWidth; + } switch (addrType) { @@ -132,7 +135,10 @@ namespace Ryujinx.HLE.HOS.Kernel { long pagesCount = size / PageSize; - if (!_allocator.TryAllocate(size, out long pa)) throw new InvalidOperationException(); + if (!_allocator.TryAllocate(size, out long pa)) + { + throw new InvalidOperationException(); + } lock (_blocks) { @@ -232,7 +238,10 @@ namespace Ryujinx.HLE.HOS.Kernel { long pagesCount = size / PageSize; - if (!_allocator.TryAllocate(size, out long pa)) throw new InvalidOperationException(); + if (!_allocator.TryAllocate(size, out long pa)) + { + throw new InvalidOperationException(); + } lock (_blocks) { @@ -256,7 +265,10 @@ namespace Ryujinx.HLE.HOS.Kernel { InsertBlock(position, 1, MemoryState.ThreadLocal, MemoryPermission.ReadAndWrite); - if (!_allocator.TryAllocate(PageSize, out long pa)) throw new InvalidOperationException(); + if (!_allocator.TryAllocate(PageSize, out long pa)) + { + throw new InvalidOperationException(); + } _cpuMemory.Map(position, pa, PageSize); @@ -274,7 +286,10 @@ namespace Ryujinx.HLE.HOS.Kernel { position = 0; - if ((ulong)size > (ulong)(HeapRegionEnd - HeapRegionStart)) return MakeError(ErrorModule.Kernel, KernelErr.OutOfMemory); + if ((ulong)size > (ulong)(HeapRegionEnd - HeapRegionStart)) + { + return MakeError(ErrorModule.Kernel, KernelErr.OutOfMemory); + } bool success = false; @@ -289,7 +304,10 @@ namespace Ryujinx.HLE.HOS.Kernel { if (success = IsUnmapped(_currentHeapAddr, diffSize)) { - if (!_allocator.TryAllocate(diffSize, out long pa)) return MakeError(ErrorModule.Kernel, KernelErr.OutOfMemory); + if (!_allocator.TryAllocate(diffSize, out long pa)) + { + return MakeError(ErrorModule.Kernel, KernelErr.OutOfMemory); + } long pagesCount = diffSize / PageSize; @@ -391,11 +409,14 @@ namespace Ryujinx.HLE.HOS.Kernel { if ((ulong)position >= (ulong)AddrSpaceStart && (ulong)position < (ulong)AddrSpaceEnd) + { lock (_blocks) { return FindBlock(position).GetInfo(); } + } else + { return new KMemoryInfo( AddrSpaceEnd, -AddrSpaceEnd, @@ -404,6 +425,7 @@ namespace Ryujinx.HLE.HOS.Kernel MemoryAttribute.None, 0, 0); + } } public long Map(long src, long dst, long size) @@ -623,11 +645,17 @@ namespace Ryujinx.HLE.HOS.Kernel out _)) { if (state == MemoryState.CodeStatic) + { state = MemoryState.CodeMutable; + } else if (state == MemoryState.ModCodeStatic) + { state = MemoryState.ModCodeMutable; + } else + { throw new InvalidOperationException(); + } long pagesCount = size / PageSize; @@ -658,17 +686,26 @@ namespace Ryujinx.HLE.HOS.Kernel { info = node.Value.GetInfo(); - if (info.State != MemoryState.Unmapped) mappedSize += GetSizeInRange(info, position, end); + if (info.State != MemoryState.Unmapped) + { + mappedSize += GetSizeInRange(info, position, end); + } node = node.Next; } while ((ulong)(info.Position + info.Size) < (ulong)end && node != null); - if (mappedSize == size) return 0; + if (mappedSize == size) + { + return 0; + } long remainingSize = size - mappedSize; - if (!_allocator.TryAllocate(remainingSize, out long pa)) return MakeError(ErrorModule.Kernel, KernelErr.OutOfMemory); + if (!_allocator.TryAllocate(remainingSize, out long pa)) + { + return MakeError(ErrorModule.Kernel, KernelErr.OutOfMemory); + } node = baseNode; @@ -682,7 +719,10 @@ namespace Ryujinx.HLE.HOS.Kernel long mapPosition = info.Position; - if ((ulong)mapPosition < (ulong)position) mapPosition = position; + if ((ulong)mapPosition < (ulong)position) + { + mapPosition = position; + } _cpuMemory.Map(mapPosition, pa, currSize); @@ -731,7 +771,10 @@ namespace Ryujinx.HLE.HOS.Kernel if (info.State == MemoryState.Heap) { - if (info.Attribute != MemoryAttribute.None) return MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + if (info.Attribute != MemoryAttribute.None) + { + return MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm); + } heapMappedSize += GetSizeInRange(info, position, end); } @@ -744,7 +787,10 @@ namespace Ryujinx.HLE.HOS.Kernel } while ((ulong)(info.Position + info.Size) < (ulong)end && node != null); - if (heapMappedSize == 0) return 0; + if (heapMappedSize == 0) + { + return 0; + } PersonalMmHeapUsage -= heapMappedSize; @@ -765,9 +811,15 @@ namespace Ryujinx.HLE.HOS.Kernel long currEnd = info.Size + info.Position; long currSize = info.Size; - if ((ulong)info.Position < (ulong)start) currSize -= start - info.Position; + if ((ulong)info.Position < (ulong)start) + { + currSize -= start - info.Position; + } - if ((ulong)currEnd > (ulong)end) currSize -= currEnd - end; + if ((ulong)currEnd > (ulong)end) + { + currSize -= currEnd - end; + } return currSize; } @@ -778,7 +830,10 @@ namespace Ryujinx.HLE.HOS.Kernel { long va = position + page * PageSize; - if (!_cpuMemory.IsMapped(va)) continue; + if (!_cpuMemory.IsMapped(va)) + { + continue; + } long pa = _cpuMemory.GetPhysicalAddress(va); @@ -835,6 +890,7 @@ namespace Ryujinx.HLE.HOS.Kernel ulong end = (ulong)size + start; if (end <= (ulong)(blkInfo.Position + blkInfo.Size)) + { if ((blkInfo.Attribute & attributeMask) == attributeExpected && (blkInfo.State & stateMask) == stateExpected && (blkInfo.Permission & permissionMask) == permissionExpected) @@ -845,6 +901,7 @@ namespace Ryujinx.HLE.HOS.Kernel return true; } + } outState = MemoryState.Unmapped; outPermission = MemoryPermission.None; @@ -990,7 +1047,10 @@ namespace Ryujinx.HLE.HOS.Kernel if (start < currEnd && currStart < end) { - if (start >= currStart && end <= currEnd) block.Attribute |= currBlock.Attribute & MemoryAttribute.IpcAndDeviceMapped; + if (start >= currStart && end <= currEnd) + { + block.Attribute |= currBlock.Attribute & MemoryAttribute.IpcAndDeviceMapped; + } if (start > currStart && end < currEnd) { @@ -1015,17 +1075,26 @@ namespace Ryujinx.HLE.HOS.Kernel currBlock.PagesCount = (long)((currEnd - end) / PageSize); - if (newNode == null) newNode = _blocks.AddBefore(node, block); + if (newNode == null) + { + newNode = _blocks.AddBefore(node, block); + } } else if (start > currStart && end >= currEnd) { currBlock.PagesCount = (long)((start - currStart) / PageSize); - if (newNode == null) newNode = _blocks.AddAfter(node, block); + if (newNode == null) + { + newNode = _blocks.AddAfter(node, block); + } } else { - if (newNode == null) newNode = _blocks.AddBefore(node, block); + if (newNode == null) + { + newNode = _blocks.AddBefore(node, block); + } _blocks.Remove(node); } @@ -1034,7 +1103,10 @@ namespace Ryujinx.HLE.HOS.Kernel node = nextNode; } - if (newNode == null) newNode = _blocks.AddFirst(block); + if (newNode == null) + { + newNode = _blocks.AddFirst(block); + } MergeEqualStateNeighbours(newNode); } @@ -1104,7 +1176,10 @@ namespace Ryujinx.HLE.HOS.Kernel ulong start = (ulong)block.BasePosition; ulong end = (ulong)block.PagesCount * PageSize + start; - if (start <= addr && end - 1 >= addr) return node; + if (start <= addr && end - 1 >= addr) + { + return node; + } node = node.Next; } diff --git a/Ryujinx.HLE/HOS/Kernel/KProcessHandleTable.cs b/Ryujinx.HLE/HOS/Kernel/KProcessHandleTable.cs index bb34632412..966c39a035 100644 --- a/Ryujinx.HLE/HOS/Kernel/KProcessHandleTable.cs +++ b/Ryujinx.HLE/HOS/Kernel/KProcessHandleTable.cs @@ -57,7 +57,10 @@ namespace Ryujinx.HLE.HOS.Kernel lock (_lockObj) { - if (_activeSlotsCount >= _size) return KernelResult.HandleTableFull; + if (_activeSlotsCount >= _size) + { + return KernelResult.HandleTableFull; + } KHandleEntry entry = _nextFreeEntry; @@ -71,9 +74,13 @@ namespace Ryujinx.HLE.HOS.Kernel handle = (int)((_idCounter << 15) & (uint)0xffff8000) | entry.Index; if ((short)(_idCounter + 1) >= 0) + { _idCounter++; + } else + { _idCounter = 1; + } } return KernelResult.Success; @@ -84,7 +91,9 @@ namespace Ryujinx.HLE.HOS.Kernel if (handle >> 30 != 0 || handle == SelfThreadHandle || handle == SelfProcessHandle) + { return false; + } int index = (handle >> 0) & 0x7fff; int handleId = handle >> 15; @@ -125,7 +134,10 @@ namespace Ryujinx.HLE.HOS.Kernel { KHandleEntry entry = _table[index]; - if (entry.HandleId == handleId && entry.Obj is T obj) return obj; + if (entry.HandleId == handleId && entry.Obj is T obj) + { + return obj; + } } } @@ -135,9 +147,13 @@ namespace Ryujinx.HLE.HOS.Kernel public KThread GetKThread(int handle) { if (handle == SelfThreadHandle) + { return _system.Scheduler.GetCurrentThread(); + } else + { return GetObject(handle); + } } public void Destroy() @@ -150,7 +166,10 @@ namespace Ryujinx.HLE.HOS.Kernel if (entry.Obj != null) { - if (entry.Obj is IDisposable disposableObj) disposableObj.Dispose(); + if (entry.Obj is IDisposable disposableObj) + { + disposableObj.Dispose(); + } entry.Obj = null; entry.Next = _nextFreeEntry; diff --git a/Ryujinx.HLE/HOS/Kernel/KRecursiveLock.cs b/Ryujinx.HLE/HOS/Kernel/KRecursiveLock.cs index 5a8a7a6e1e..d8006afd4d 100644 --- a/Ryujinx.HLE/HOS/Kernel/KRecursiveLock.cs +++ b/Ryujinx.HLE/HOS/Kernel/KRecursiveLock.cs @@ -27,17 +27,24 @@ namespace Ryujinx.HLE.HOS.Kernel public void Unlock() { - if (_recursionCount == 0) return; + if (_recursionCount == 0) + { + return; + } bool doContextSwitch = false; if (--_recursionCount == 0) { - if (_system.Scheduler.ThreadReselectionRequested) _system.Scheduler.SelectThreads(); + if (_system.Scheduler.ThreadReselectionRequested) + { + _system.Scheduler.SelectThreads(); + } Monitor.Exit(LockObj); if (_system.Scheduler.MultiCoreScheduling) + { lock (_system.Scheduler.CoreContexts) { for (int core = 0; core < KScheduler.CpuCoresCount; core++) @@ -49,23 +56,35 @@ namespace Ryujinx.HLE.HOS.Kernel AThread currentHleThread = coreContext.CurrentThread?.Context; if (currentHleThread == null) + { coreContext.ContextSwitch(); + } else if (currentHleThread.IsCurrentThread()) + { doContextSwitch = true; + } else + { currentHleThread.RequestInterrupt(); + } } } } + } else + { doContextSwitch = true; + } } else { Monitor.Exit(LockObj); } - if (doContextSwitch) _system.Scheduler.ContextSwitch(); + if (doContextSwitch) + { + _system.Scheduler.ContextSwitch(); + } } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KScheduler.cs b/Ryujinx.HLE/HOS/Kernel/KScheduler.cs index 76c2b2d819..b190c3a6ce 100644 --- a/Ryujinx.HLE/HOS/Kernel/KScheduler.cs +++ b/Ryujinx.HLE/HOS/Kernel/KScheduler.cs @@ -30,7 +30,10 @@ namespace Ryujinx.HLE.HOS.Kernel CoreContexts = new KCoreContext[CpuCoresCount]; - for (int core = 0; core < CpuCoresCount; core++) CoreContexts[core] = new KCoreContext(this, _coreManager); + for (int core = 0; core < CpuCoresCount; core++) + { + CoreContexts[core] = new KCoreContext(this, _coreManager); + } } private void PreemptThreads() @@ -52,7 +55,10 @@ namespace Ryujinx.HLE.HOS.Kernel KThread selectedThread = scheduledThreads.FirstOrDefault(x => x.DynamicPriority == prio); //Yield priority queue. - if (selectedThread != null) SchedulingData.Reschedule(prio, core, selectedThread); + if (selectedThread != null) + { + SchedulingData.Reschedule(prio, core, selectedThread); + } IEnumerable SuitableCandidates() { @@ -64,13 +70,22 @@ namespace Ryujinx.HLE.HOS.Kernel { KThread highestPrioSrcCore = SchedulingData.ScheduledThreads(srcCore).FirstOrDefault(); - if (highestPrioSrcCore != null && highestPrioSrcCore.DynamicPriority < 2) break; + if (highestPrioSrcCore != null && highestPrioSrcCore.DynamicPriority < 2) + { + break; + } - if (highestPrioSrcCore == thread) continue; + if (highestPrioSrcCore == thread) + { + continue; + } } //If the candidate was scheduled after the current thread, then it's not worth it. - if (selectedThread == null || selectedThread.LastScheduledTicks >= thread.LastScheduledTicks) yield return thread; + if (selectedThread == null || selectedThread.LastScheduledTicks >= thread.LastScheduledTicks) + { + yield return thread; + } } } @@ -93,7 +108,10 @@ namespace Ryujinx.HLE.HOS.Kernel dst = SuitableCandidates().FirstOrDefault(predicate); - if (dst != null) SchedulingData.TransferToCore(dst.DynamicPriority, core, dst); + if (dst != null) + { + SchedulingData.TransferToCore(dst.DynamicPriority, core, dst); + } } ThreadReselectionRequested = true; @@ -114,7 +132,10 @@ namespace Ryujinx.HLE.HOS.Kernel { //If the core is not idle (there's already a thread running on it), //then we don't need to attempt load balancing. - if (SchedulingData.ScheduledThreads(core).Any()) continue; + if (SchedulingData.ScheduledThreads(core).Any()) + { + continue; + } int[] srcCoresHighestPrioThreads = new int[CpuCoresCount]; @@ -180,7 +201,12 @@ namespace Ryujinx.HLE.HOS.Kernel lock (CoreContexts) { for (int core = 0; core < CpuCoresCount; core++) - if (CoreContexts[core].CurrentThread?.Context.IsCurrentThread() ?? false) return CoreContexts[core].CurrentThread; + { + if (CoreContexts[core].CurrentThread?.Context.IsCurrentThread() ?? false) + { + return CoreContexts[core].CurrentThread; + } + } } throw new InvalidOperationException("Current thread is not scheduled!"); @@ -193,7 +219,10 @@ namespace Ryujinx.HLE.HOS.Kernel protected virtual void Dispose(bool disposing) { - if (disposing) _keepPreempting = false; + if (disposing) + { + _keepPreempting = false; + } } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KSchedulingData.cs b/Ryujinx.HLE/HOS/Kernel/KSchedulingData.cs index 1f35adfb7c..e6ce166cc6 100644 --- a/Ryujinx.HLE/HOS/Kernel/KSchedulingData.cs +++ b/Ryujinx.HLE/HOS/Kernel/KSchedulingData.cs @@ -72,9 +72,15 @@ namespace Ryujinx.HLE.HOS.Kernel { int count = 0; - while (((value >> count) & 0xf) == 0 && count < 64) count += 4; + while (((value >> count) & 0xf) == 0 && count < 64) + { + count += 4; + } - while (((value >> count) & 1) == 0 && count < 64) count++; + while (((value >> count) & 1) == 0 && count < 64) + { + count++; + } return count; } @@ -87,9 +93,15 @@ namespace Ryujinx.HLE.HOS.Kernel thread.CurrentCore = dstCore; - if (srcCore == dstCore || !schedulable) return; + if (srcCore == dstCore || !schedulable) + { + return; + } - if (srcCore >= 0) Unschedule(prio, srcCore, thread); + if (srcCore >= 0) + { + Unschedule(prio, srcCore, thread); + } if (dstCore >= 0) { @@ -97,12 +109,18 @@ namespace Ryujinx.HLE.HOS.Kernel Schedule(prio, dstCore, thread); } - if (srcCore >= 0) Suggest(prio, srcCore, thread); + if (srcCore >= 0) + { + Suggest(prio, srcCore, thread); + } } public void Suggest(int prio, int core, KThread thread) { - if (prio >= KScheduler.PrioritiesCount) return; + if (prio >= KScheduler.PrioritiesCount) + { + return; + } thread.SiblingsPerCore[core] = SuggestedQueue(prio, core).AddFirst(thread); @@ -111,18 +129,27 @@ namespace Ryujinx.HLE.HOS.Kernel public void Unsuggest(int prio, int core, KThread thread) { - if (prio >= KScheduler.PrioritiesCount) return; + if (prio >= KScheduler.PrioritiesCount) + { + return; + } LinkedList queue = SuggestedQueue(prio, core); queue.Remove(thread.SiblingsPerCore[core]); - if (queue.First == null) _suggestedPrioritiesPerCore[core] &= ~(1L << prio); + if (queue.First == null) + { + _suggestedPrioritiesPerCore[core] &= ~(1L << prio); + } } public void Schedule(int prio, int core, KThread thread) { - if (prio >= KScheduler.PrioritiesCount) return; + if (prio >= KScheduler.PrioritiesCount) + { + return; + } thread.SiblingsPerCore[core] = ScheduledQueue(prio, core).AddLast(thread); @@ -131,7 +158,10 @@ namespace Ryujinx.HLE.HOS.Kernel public void SchedulePrepend(int prio, int core, KThread thread) { - if (prio >= KScheduler.PrioritiesCount) return; + if (prio >= KScheduler.PrioritiesCount) + { + return; + } thread.SiblingsPerCore[core] = ScheduledQueue(prio, core).AddFirst(thread); @@ -149,13 +179,19 @@ namespace Ryujinx.HLE.HOS.Kernel public void Unschedule(int prio, int core, KThread thread) { - if (prio >= KScheduler.PrioritiesCount) return; + if (prio >= KScheduler.PrioritiesCount) + { + return; + } LinkedList queue = ScheduledQueue(prio, core); queue.Remove(thread.SiblingsPerCore[core]); - if (queue.First == null) _scheduledPrioritiesPerCore[core] &= ~(1L << prio); + if (queue.First == null) + { + _scheduledPrioritiesPerCore[core] &= ~(1L << prio); + } } private LinkedList SuggestedQueue(int prio, int core) diff --git a/Ryujinx.HLE/HOS/Kernel/KSession.cs b/Ryujinx.HLE/HOS/Kernel/KSession.cs index b63103ed3f..d4f36b0a0e 100644 --- a/Ryujinx.HLE/HOS/Kernel/KSession.cs +++ b/Ryujinx.HLE/HOS/Kernel/KSession.cs @@ -22,7 +22,10 @@ namespace Ryujinx.HLE.HOS.Kernel protected virtual void Dispose(bool disposing) { - if (disposing && Service is IDisposable disposableService) disposableService.Dispose(); + if (disposing && Service is IDisposable disposableService) + { + disposableService.Dispose(); + } } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Kernel/KSynchronization.cs b/Ryujinx.HLE/HOS/Kernel/KSynchronization.cs index cdc1c6b5b1..d1a6151efe 100644 --- a/Ryujinx.HLE/HOS/Kernel/KSynchronization.cs +++ b/Ryujinx.HLE/HOS/Kernel/KSynchronization.cs @@ -22,7 +22,10 @@ namespace Ryujinx.HLE.HOS.Kernel //Check if objects are already signaled before waiting. for (int index = 0; index < syncObjs.Length; index++) { - if (!syncObjs[index].IsSignaled()) continue; + if (!syncObjs[index].IsSignaled()) + { + continue; + } hndIndex = index; @@ -55,7 +58,10 @@ namespace Ryujinx.HLE.HOS.Kernel { LinkedListNode[] syncNodes = new LinkedListNode[syncObjs.Length]; - for (int index = 0; index < syncObjs.Length; index++) syncNodes[index] = syncObjs[index].AddWaitingThread(currentThread); + for (int index = 0; index < syncObjs.Length; index++) + { + syncNodes[index] = syncObjs[index].AddWaitingThread(currentThread); + } currentThread.WaitingSync = true; currentThread.SignaledObj = null; @@ -63,13 +69,19 @@ namespace Ryujinx.HLE.HOS.Kernel currentThread.Reschedule(ThreadSchedState.Paused); - if (timeout > 0) _system.TimeManager.ScheduleFutureInvocation(currentThread, timeout); + if (timeout > 0) + { + _system.TimeManager.ScheduleFutureInvocation(currentThread, timeout); + } _system.CriticalSectionLock.Unlock(); currentThread.WaitingSync = false; - if (timeout > 0) _system.TimeManager.UnscheduleFutureInvocation(currentThread); + if (timeout > 0) + { + _system.TimeManager.UnscheduleFutureInvocation(currentThread); + } _system.CriticalSectionLock.Lock(); @@ -81,7 +93,10 @@ namespace Ryujinx.HLE.HOS.Kernel { syncObjs[index].RemoveWaitingThread(syncNodes[index]); - if (syncObjs[index] == currentThread.SignaledObj) hndIndex = index; + if (syncObjs[index] == currentThread.SignaledObj) + { + hndIndex = index; + } } } diff --git a/Ryujinx.HLE/HOS/Kernel/KThread.cs b/Ryujinx.HLE/HOS/Kernel/KThread.cs index c07ed003ea..513ccd4631 100644 --- a/Ryujinx.HLE/HOS/Kernel/KThread.cs +++ b/Ryujinx.HLE/HOS/Kernel/KThread.cs @@ -115,7 +115,10 @@ namespace Ryujinx.HLE.HOS.Kernel if (currentThread._forcePauseFlags == ThreadSchedState.None) { - if (Owner != null && _forcePauseFlags != ThreadSchedState.None) CombineForcePauseFlags(); + if (Owner != null && _forcePauseFlags != ThreadSchedState.None) + { + CombineForcePauseFlags(); + } SetNewSchedFlags(ThreadSchedState.Running); @@ -130,7 +133,10 @@ namespace Ryujinx.HLE.HOS.Kernel System.CriticalSectionLock.Unlock(); System.CriticalSectionLock.Lock(); - if (currentThread.ShallBeTerminated) break; + if (currentThread.ShallBeTerminated) + { + break; + } } } } @@ -177,11 +183,17 @@ namespace Ryujinx.HLE.HOS.Kernel SetNewSchedFlags(ThreadSchedState.Paused); - if (timeout > 0) System.TimeManager.ScheduleFutureInvocation(this, timeout); + if (timeout > 0) + { + System.TimeManager.ScheduleFutureInvocation(this, timeout); + } System.CriticalSectionLock.Unlock(); - if (timeout > 0) System.TimeManager.UnscheduleFutureInvocation(this); + if (timeout > 0) + { + System.TimeManager.UnscheduleFutureInvocation(this); + } return 0; } @@ -199,7 +211,10 @@ namespace Ryujinx.HLE.HOS.Kernel return; } - if (DynamicPriority < KScheduler.PrioritiesCount) _schedulingData.Reschedule(DynamicPriority, CurrentCore, this); + if (DynamicPriority < KScheduler.PrioritiesCount) + { + _schedulingData.Reschedule(DynamicPriority, CurrentCore, this); + } _scheduler.ThreadReselectionRequested = true; @@ -246,14 +261,19 @@ namespace Ryujinx.HLE.HOS.Kernel { KThread selectedSrcCore = _scheduler.CoreContexts[srcCore].SelectedThread; - if (selectedSrcCore == thread || (selectedSrcCore?.DynamicPriority ?? 2) < 2) continue; + if (selectedSrcCore == thread || (selectedSrcCore?.DynamicPriority ?? 2) < 2) + { + continue; + } } //If the candidate was scheduled after the current thread, then it's not worth it, //unless the priority is higher than the current one. if (nextThreadOnCurrentQueue.LastScheduledTicks >= thread.LastScheduledTicks || nextThreadOnCurrentQueue.DynamicPriority < thread.DynamicPriority) + { yield return thread; + } } } @@ -266,7 +286,10 @@ namespace Ryujinx.HLE.HOS.Kernel _scheduler.ThreadReselectionRequested = true; } - if (this != nextThreadOnCurrentQueue) _scheduler.ThreadReselectionRequested = true; + if (this != nextThreadOnCurrentQueue) + { + _scheduler.ThreadReselectionRequested = true; + } System.CriticalSectionLock.Unlock(); @@ -293,13 +316,20 @@ namespace Ryujinx.HLE.HOS.Kernel KThread selectedThread = null; if (!_schedulingData.ScheduledThreads(core).Any()) + { foreach (KThread thread in _schedulingData.SuggestedThreads(core)) { - if (thread.CurrentCore < 0) continue; + if (thread.CurrentCore < 0) + { + continue; + } KThread firstCandidate = _schedulingData.ScheduledThreads(thread.CurrentCore).FirstOrDefault(); - if (firstCandidate == thread) continue; + if (firstCandidate == thread) + { + continue; + } if (firstCandidate == null || firstCandidate.DynamicPriority >= 2) { @@ -310,8 +340,12 @@ namespace Ryujinx.HLE.HOS.Kernel break; } + } - if (selectedThread != this) _scheduler.ThreadReselectionRequested = true; + if (selectedThread != this) + { + _scheduler.ThreadReselectionRequested = true; + } System.CriticalSectionLock.Unlock(); @@ -462,9 +496,13 @@ namespace Ryujinx.HLE.HOS.Kernel if (CurrentCore >= 0 && ((AffinityMask >> CurrentCore) & 1) == 0) { if (PreferredCore < 0) + { CurrentCore = HighestSetCore(AffinityMask); + } else + { CurrentCore = PreferredCore; + } } AdjustSchedulingForNewAffinity(oldAffinityMask, oldCore); @@ -479,7 +517,12 @@ namespace Ryujinx.HLE.HOS.Kernel private static int HighestSetCore(long mask) { for (int core = KScheduler.CpuCoresCount - 1; core >= 0; core--) - if (((mask >> core) & 1) != 0) return core; + { + if (((mask >> core) & 1) != 0) + { + return core; + } + } return -1; } @@ -502,7 +545,10 @@ namespace Ryujinx.HLE.HOS.Kernel SchedFlags = (oldFlags & ThreadSchedState.HighNibbleMask) | newFlags; - if ((oldFlags & ThreadSchedState.LowNibbleMask) != newFlags) AdjustScheduling(oldFlags); + if ((oldFlags & ThreadSchedState.LowNibbleMask) != newFlags) + { + AdjustScheduling(oldFlags); + } System.CriticalSectionLock.Unlock(); } @@ -555,7 +601,10 @@ namespace Ryujinx.HLE.HOS.Kernel public void RemoveMutexWaiter(KThread thread) { - if (thread._mutexWaiterNode?.List != null) _mutexWaiters.Remove(thread._mutexWaiterNode); + if (thread._mutexWaiterNode?.List != null) + { + _mutexWaiters.Remove(thread._mutexWaiterNode); + } thread.MutexOwner = null; @@ -566,7 +615,10 @@ namespace Ryujinx.HLE.HOS.Kernel { count = 0; - if (_mutexWaiters.First == null) return null; + if (_mutexWaiters.First == null) + { + return null; + } KThread newMutexOwner = null; @@ -575,9 +627,15 @@ namespace Ryujinx.HLE.HOS.Kernel do { //Skip all threads that are not waiting for this mutex. - while (currentNode != null && currentNode.Value.MutexAddress != mutexAddress) currentNode = currentNode.Next; + while (currentNode != null && currentNode.Value.MutexAddress != mutexAddress) + { + currentNode = currentNode.Next; + } - if (currentNode == null) break; + if (currentNode == null) + { + break; + } LinkedListNode nextNode = currentNode.Next; @@ -586,9 +644,13 @@ namespace Ryujinx.HLE.HOS.Kernel currentNode.Value.MutexOwner = newMutexOwner; if (newMutexOwner != null) + { newMutexOwner.AddToMutexWaitersList(currentNode.Value); + } else + { newMutexOwner = currentNode.Value; + } count++; @@ -617,7 +679,10 @@ namespace Ryujinx.HLE.HOS.Kernel { int waitingDynamicPriority = _mutexWaiters.First.Value.DynamicPriority; - if (waitingDynamicPriority < highestPriority) highestPriority = waitingDynamicPriority; + if (waitingDynamicPriority < highestPriority) + { + highestPriority = waitingDynamicPriority; + } } if (highestPriority != DynamicPriority) @@ -646,33 +711,59 @@ namespace Ryujinx.HLE.HOS.Kernel int currentPriority = thread.DynamicPriority; - while (nextPrio != null && nextPrio.Value.DynamicPriority <= currentPriority) nextPrio = nextPrio.Next; + while (nextPrio != null && nextPrio.Value.DynamicPriority <= currentPriority) + { + nextPrio = nextPrio.Next; + } if (nextPrio != null) + { thread._mutexWaiterNode = _mutexWaiters.AddBefore(nextPrio, thread); + } else + { thread._mutexWaiterNode = _mutexWaiters.AddLast(thread); + } } private void AdjustScheduling(ThreadSchedState oldFlags) { - if (oldFlags == SchedFlags) return; + if (oldFlags == SchedFlags) + { + return; + } if (oldFlags == ThreadSchedState.Running) { //Was running, now it's stopped. - if (CurrentCore >= 0) _schedulingData.Unschedule(DynamicPriority, CurrentCore, this); + if (CurrentCore >= 0) + { + _schedulingData.Unschedule(DynamicPriority, CurrentCore, this); + } for (int core = 0; core < KScheduler.CpuCoresCount; core++) - if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0) _schedulingData.Unsuggest(DynamicPriority, core, this); + { + if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0) + { + _schedulingData.Unsuggest(DynamicPriority, core, this); + } + } } else if (SchedFlags == ThreadSchedState.Running) { //Was stopped, now it's running. - if (CurrentCore >= 0) _schedulingData.Schedule(DynamicPriority, CurrentCore, this); + if (CurrentCore >= 0) + { + _schedulingData.Schedule(DynamicPriority, CurrentCore, this); + } for (int core = 0; core < KScheduler.CpuCoresCount; core++) - if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0) _schedulingData.Suggest(DynamicPriority, core, this); + { + if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0) + { + _schedulingData.Suggest(DynamicPriority, core, this); + } + } } _scheduler.ThreadReselectionRequested = true; @@ -680,13 +771,24 @@ namespace Ryujinx.HLE.HOS.Kernel private void AdjustSchedulingForNewPriority(int oldPriority) { - if (SchedFlags != ThreadSchedState.Running) return; + if (SchedFlags != ThreadSchedState.Running) + { + return; + } //Remove thread from the old priority queues. - if (CurrentCore >= 0) _schedulingData.Unschedule(oldPriority, CurrentCore, this); + if (CurrentCore >= 0) + { + _schedulingData.Unschedule(oldPriority, CurrentCore, this); + } for (int core = 0; core < KScheduler.CpuCoresCount; core++) - if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0) _schedulingData.Unsuggest(oldPriority, core, this); + { + if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0) + { + _schedulingData.Unsuggest(oldPriority, core, this); + } + } //Add thread to the new priority queues. KThread currentThread = _scheduler.GetCurrentThread(); @@ -694,40 +796,64 @@ namespace Ryujinx.HLE.HOS.Kernel if (CurrentCore >= 0) { if (currentThread == this) + { _schedulingData.SchedulePrepend(DynamicPriority, CurrentCore, this); + } else + { _schedulingData.Schedule(DynamicPriority, CurrentCore, this); + } } for (int core = 0; core < KScheduler.CpuCoresCount; core++) - if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0) _schedulingData.Suggest(DynamicPriority, core, this); + { + if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0) + { + _schedulingData.Suggest(DynamicPriority, core, this); + } + } _scheduler.ThreadReselectionRequested = true; } private void AdjustSchedulingForNewAffinity(long oldAffinityMask, int oldCore) { - if (SchedFlags != ThreadSchedState.Running || DynamicPriority >= KScheduler.PrioritiesCount) return; + if (SchedFlags != ThreadSchedState.Running || DynamicPriority >= KScheduler.PrioritiesCount) + { + return; + } //Remove from old queues. for (int core = 0; core < KScheduler.CpuCoresCount; core++) + { if (((oldAffinityMask >> core) & 1) != 0) { if (core == oldCore) + { _schedulingData.Unschedule(DynamicPriority, core, this); + } else + { _schedulingData.Unsuggest(DynamicPriority, core, this); + } } + } //Insert on new queues. for (int core = 0; core < KScheduler.CpuCoresCount; core++) + { if (((AffinityMask >> core) & 1) != 0) { if (core == CurrentCore) + { _schedulingData.Schedule(DynamicPriority, core, this); + } else + { _schedulingData.Suggest(DynamicPriority, core, this); + } } + } _scheduler.ThreadReselectionRequested = true; } diff --git a/Ryujinx.HLE/HOS/Kernel/KTimeManager.cs b/Ryujinx.HLE/HOS/Kernel/KTimeManager.cs index 2c44d272c7..6c69beb77a 100644 --- a/Ryujinx.HLE/HOS/Kernel/KTimeManager.cs +++ b/Ryujinx.HLE/HOS/Kernel/KTimeManager.cs @@ -60,7 +60,10 @@ namespace Ryujinx.HLE.HOS.Kernel { timeout /= 1000000; - if ((ulong)timeout > int.MaxValue) return int.MaxValue; + if ((ulong)timeout > int.MaxValue) + { + return int.MaxValue; + } return timeout; } @@ -89,7 +92,10 @@ namespace Ryujinx.HLE.HOS.Kernel { long timePoint = _counter.ElapsedMilliseconds; - if (next.TimePoint > timePoint) _waitEvent.WaitOne((int)(next.TimePoint - timePoint)); + if (next.TimePoint > timePoint) + { + _waitEvent.WaitOne((int)(next.TimePoint - timePoint)); + } Monitor.Enter(_waitingObjects); @@ -97,7 +103,10 @@ namespace Ryujinx.HLE.HOS.Kernel Monitor.Exit(_waitingObjects); - if (timeUp) next.Object.TimeUp(); + if (timeUp) + { + next.Object.TimeUp(); + } } else { diff --git a/Ryujinx.HLE/HOS/Kernel/KTlsPageManager.cs b/Ryujinx.HLE/HOS/Kernel/KTlsPageManager.cs index 4933fc8ca8..b73107f347 100644 --- a/Ryujinx.HLE/HOS/Kernel/KTlsPageManager.cs +++ b/Ryujinx.HLE/HOS/Kernel/KTlsPageManager.cs @@ -47,7 +47,10 @@ namespace Ryujinx.HLE.HOS.Kernel public void FreeTlsSlot(int slot) { - if ((uint)slot > _slots.Length) throw new ArgumentOutOfRangeException(nameof(slot)); + if ((uint)slot > _slots.Length) + { + throw new ArgumentOutOfRangeException(nameof(slot)); + } _slots[slot] = false; diff --git a/Ryujinx.HLE/HOS/Kernel/SvcMemory.cs b/Ryujinx.HLE/HOS/Kernel/SvcMemory.cs index 9e4a104130..04526996a4 100644 --- a/Ryujinx.HLE/HOS/Kernel/SvcMemory.cs +++ b/Ryujinx.HLE/HOS/Kernel/SvcMemory.cs @@ -25,9 +25,13 @@ namespace Ryujinx.HLE.HOS.Kernel threadState.X0 = (ulong)result; if (result == 0) + { threadState.X1 = (ulong)position; + } else + { Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } } private void SvcSetMemoryAttribute(AThreadState threadState) @@ -75,9 +79,13 @@ namespace Ryujinx.HLE.HOS.Kernel attributeValue); if (result != 0) + { Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } else + { _memory.StopObservingRegion(position, size); + } threadState.X0 = (ulong)result; } @@ -135,7 +143,10 @@ namespace Ryujinx.HLE.HOS.Kernel long result = _process.MemoryManager.Map(src, dst, size); - if (result != 0) Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + if (result != 0) + { + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } threadState.X0 = (ulong)result; } @@ -193,7 +204,10 @@ namespace Ryujinx.HLE.HOS.Kernel long result = _process.MemoryManager.Unmap(src, dst, size); - if (result != 0) Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + if (result != 0) + { + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } threadState.X0 = (ulong)result; } @@ -293,7 +307,10 @@ namespace Ryujinx.HLE.HOS.Kernel long result = _process.MemoryManager.MapSharedMemory(sharedMemory, permission, position); - if (result != 0) Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + if (result != 0) + { + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } threadState.X0 = (ulong)result; } @@ -353,7 +370,10 @@ namespace Ryujinx.HLE.HOS.Kernel long result = _process.MemoryManager.UnmapSharedMemory(position, size); - if (result != 0) Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + if (result != 0) + { + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } threadState.X0 = (ulong)result; } @@ -454,7 +474,10 @@ namespace Ryujinx.HLE.HOS.Kernel long result = _process.MemoryManager.MapPhysicalMemory(position, size); - if (result != 0) Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + if (result != 0) + { + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } threadState.X0 = (ulong)result; } @@ -502,7 +525,10 @@ namespace Ryujinx.HLE.HOS.Kernel long result = _process.MemoryManager.UnmapPhysicalMemory(position, size); - if (result != 0) Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + if (result != 0) + { + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } threadState.X0 = (ulong)result; } diff --git a/Ryujinx.HLE/HOS/Kernel/SvcSystem.cs b/Ryujinx.HLE/HOS/Kernel/SvcSystem.cs index 16b75059a6..8e1b1e6c14 100644 --- a/Ryujinx.HLE/HOS/Kernel/SvcSystem.cs +++ b/Ryujinx.HLE/HOS/Kernel/SvcSystem.cs @@ -44,7 +44,10 @@ namespace Ryujinx.HLE.HOS.Kernel result = KernelResult.InvalidHandle; } - if (result != KernelResult.Success) Logger.PrintWarning(LogClass.KernelSvc, "Operation failed with error: " + result + "!"); + if (result != KernelResult.Success) + { + Logger.PrintWarning(LogClass.KernelSvc, "Operation failed with error: " + result + "!"); + } return result; } @@ -71,7 +74,10 @@ namespace Ryujinx.HLE.HOS.Kernel result = writableEvent.Clear(); } - if (result != KernelResult.Success) Logger.PrintWarning(LogClass.KernelSvc, "Operation failed with error: " + result + "!"); + if (result != KernelResult.Success) + { + Logger.PrintWarning(LogClass.KernelSvc, "Operation failed with error: " + result + "!"); + } return result; } @@ -94,11 +100,15 @@ namespace Ryujinx.HLE.HOS.Kernel } if (obj is KSession session) + { session.Dispose(); + } else if (obj is KTransferMemory transferMemory) + { _process.MemoryManager.ResetTransferMemory( transferMemory.Position, transferMemory.Size); + } threadState.X0 = 0; } @@ -116,13 +126,22 @@ namespace Ryujinx.HLE.HOS.Kernel //TODO: KProcess support. if (readableEvent != null) + { result = readableEvent.ClearIfSignaled(); + } else + { result = KernelResult.InvalidHandle; + } if (result == KernelResult.InvalidState) + { Logger.PrintDebug(LogClass.KernelSvc, "Operation failed with error: " + result + "!"); - else if (result != KernelResult.Success) Logger.PrintWarning(LogClass.KernelSvc, "Operation failed with error: " + result + "!"); + } + else if (result != KernelResult.Success) + { + Logger.PrintWarning(LogClass.KernelSvc, "Operation failed with error: " + result + "!"); + } return result; } @@ -143,7 +162,10 @@ namespace Ryujinx.HLE.HOS.Kernel //actually exists, return error codes otherwise. KSession session = new KSession(ServiceFactory.MakeService(_system, name), name); - if (_process.HandleTable.GenerateHandle(session, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (_process.HandleTable.GenerateHandle(session, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } threadState.X0 = 0; threadState.X1 = (uint)handle; @@ -363,7 +385,10 @@ namespace Ryujinx.HLE.HOS.Kernel { result = _process.HandleTable.GenerateHandle(Event.ReadableEvent, out rEventHandle); - if (result != KernelResult.Success) _process.HandleTable.CloseHandle(wEventHandle); + if (result != KernelResult.Success) + { + _process.HandleTable.CloseHandle(wEventHandle); + } } else { diff --git a/Ryujinx.HLE/HOS/Kernel/SvcThread.cs b/Ryujinx.HLE/HOS/Kernel/SvcThread.cs index f1cb6b427f..0ee280f243 100644 --- a/Ryujinx.HLE/HOS/Kernel/SvcThread.cs +++ b/Ryujinx.HLE/HOS/Kernel/SvcThread.cs @@ -59,7 +59,10 @@ namespace Ryujinx.HLE.HOS.Kernel { long result = thread.Start(); - if (result != 0) Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + if (result != 0) + { + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } threadState.X0 = (ulong)result; } @@ -229,7 +232,10 @@ namespace Ryujinx.HLE.HOS.Kernel long result = thread.SetCoreAndAffinityMask(prefferedCore, affinityMask); - if (result != 0) Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + if (result != 0) + { + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } threadState.X0 = (ulong)result; } @@ -285,7 +291,10 @@ namespace Ryujinx.HLE.HOS.Kernel long result = thread.SetActivity(pause); - if (result != 0) Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + if (result != 0) + { + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } threadState.X0 = (ulong)result; } diff --git a/Ryujinx.HLE/HOS/Kernel/SvcThreadSync.cs b/Ryujinx.HLE/HOS/Kernel/SvcThreadSync.cs index 78f7581ac6..6a0c0b9e84 100644 --- a/Ryujinx.HLE/HOS/Kernel/SvcThreadSync.cs +++ b/Ryujinx.HLE/HOS/Kernel/SvcThreadSync.cs @@ -34,7 +34,10 @@ namespace Ryujinx.HLE.HOS.Kernel KSynchronizationObject syncObj = _process.HandleTable.GetObject(handle); - if (syncObj == null) break; + if (syncObj == null) + { + break; + } syncObjs.Add(syncObj); } @@ -49,9 +52,13 @@ namespace Ryujinx.HLE.HOS.Kernel { if (result == MakeError(ErrorModule.Kernel, KernelErr.Timeout) || result == MakeError(ErrorModule.Kernel, KernelErr.Cancelled)) + { Logger.PrintDebug(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } else + { Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } } threadState.X0 = (ulong)result; @@ -116,7 +123,10 @@ namespace Ryujinx.HLE.HOS.Kernel mutexAddress, requesterHandle); - if (result != 0) Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + if (result != 0) + { + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } threadState.X0 = (ulong)result; } @@ -147,7 +157,10 @@ namespace Ryujinx.HLE.HOS.Kernel long result = _system.AddressArbiter.ArbitrateUnlock(_memory, mutexAddress); - if (result != 0) Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + if (result != 0) + { + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } threadState.X0 = (ulong)result; } @@ -193,9 +206,13 @@ namespace Ryujinx.HLE.HOS.Kernel if (result != 0) { if (result == MakeError(ErrorModule.Kernel, KernelErr.Timeout)) + { Logger.PrintDebug(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } else + { Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } } threadState.X0 = (ulong)result; @@ -267,7 +284,10 @@ namespace Ryujinx.HLE.HOS.Kernel break; } - if (result != 0) Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + if (result != 0) + { + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } threadState.X0 = (ulong)result; } @@ -324,7 +344,10 @@ namespace Ryujinx.HLE.HOS.Kernel break; } - if (result != 0) Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + if (result != 0) + { + Logger.PrintWarning(LogClass.KernelSvc, $"Operation failed with error 0x{result:x}!"); + } threadState.X0 = (ulong)result; } diff --git a/Ryujinx.HLE/HOS/Process.cs b/Ryujinx.HLE/HOS/Process.cs index 61a89b49cd..04da2d752b 100644 --- a/Ryujinx.HLE/HOS/Process.cs +++ b/Ryujinx.HLE/HOS/Process.cs @@ -76,13 +76,17 @@ namespace Ryujinx.HLE.HOS int handleTableSize = 1024; if (metaData != null) + { foreach (KernelAccessControlItem item in metaData.Aci0.KernelAccessControl.Items) + { if (item.HasHandleTableSize) { handleTableSize = item.HandleTableSize; break; } + } + } HandleTable = new KProcessHandleTable(device.System, handleTableSize); @@ -99,7 +103,10 @@ namespace Ryujinx.HLE.HOS public void LoadProgram(IExecutable program) { - if (_disposed) throw new ObjectDisposedException(nameof(Process)); + if (_disposed) + { + throw new ObjectDisposedException(nameof(Process)); + } long imageEnd = LoadProgram(program, _imageBase); @@ -108,7 +115,10 @@ namespace Ryujinx.HLE.HOS public long LoadProgram(IExecutable program, long executableBase) { - if (_disposed) throw new ObjectDisposedException(nameof(Process)); + if (_disposed) + { + throw new ObjectDisposedException(nameof(Process)); + } Logger.PrintInfo(LogClass.Loader, $"Image base at 0x{executableBase:x16}."); @@ -122,11 +132,13 @@ namespace Ryujinx.HLE.HOS public void RemoveProgram(long executableBase) { foreach (Executable executable in _executables) + { if (executable.ImageBase == executableBase) { _executables.Remove(executable); break; } + } } public void SetEmptyArgs() @@ -137,11 +149,17 @@ namespace Ryujinx.HLE.HOS public bool Run(bool needsHbAbi = false) { - if (_disposed) throw new ObjectDisposedException(nameof(Process)); + if (_disposed) + { + throw new ObjectDisposedException(nameof(Process)); + } NeedsHbAbi = needsHbAbi; - if (_executables.Count == 0) return false; + if (_executables.Count == 0) + { + return false; + } long mainStackTop = MemoryManager.CodeRegionEnd - KMemoryManager.PageSize; @@ -157,7 +175,10 @@ namespace Ryujinx.HLE.HOS int handle = MakeThread(_executables[0].ImageBase, mainStackTop, 0, 44, 0); - if (handle == -1) return false; + if (handle == -1) + { + return false; + } KThread mainThread = HandleTable.GetKThread(handle); @@ -195,7 +216,10 @@ namespace Ryujinx.HLE.HOS int priority, int processorId) { - if (_disposed) throw new ObjectDisposedException(nameof(Process)); + if (_disposed) + { + throw new ObjectDisposedException(nameof(Process)); + } AThread cpuThread = new AThread(GetTranslator(), Memory, entryPoint); @@ -235,7 +259,12 @@ namespace Ryujinx.HLE.HOS lock (_tlsPages) { for (int index = 0; index < _tlsPages.Count; index++) - if (_tlsPages[index].TryGetFreeTlsAddr(out position)) return position; + { + if (_tlsPages[index].TryGetFreeTlsAddr(out position)) + { + return position; + } + } long pagePosition = MemoryManager.HleMapTlsPage(); @@ -282,9 +311,15 @@ namespace Ryujinx.HLE.HOS { Executable exe = GetExecutable(e.Position); - if (exe == null) return; + if (exe == null) + { + return; + } - if (!TryGetSubName(exe, e.Position, out string subName)) subName = string.Empty; + if (!TryGetSubName(exe, e.Position, out string subName)) + { + subName = string.Empty; + } long offset = e.Position - exe.ImageBase; @@ -313,12 +348,14 @@ namespace Ryujinx.HLE.HOS private void PrintStackTraceForCurrentThread() { foreach (KThread thread in _threads.Values) + { if (thread.Context.IsCurrentThread()) { PrintStackTrace(thread.Context.ThreadState); break; } + } } public void PrintStackTrace(AThreadState threadState) @@ -331,11 +368,19 @@ namespace Ryujinx.HLE.HOS { Executable exe = GetExecutable(position); - if (exe == null) return; + if (exe == null) + { + return; + } if (!TryGetSubName(exe, position, out string subName)) + { subName = $"Sub{position:x16}"; - else if (subName.StartsWith("_Z")) subName = Demangler.Parse(subName); + } + else if (subName.StartsWith("_Z")) + { + subName = Demangler.Parse(subName); + } long offset = position - exe.ImageBase; @@ -381,9 +426,13 @@ namespace Ryujinx.HLE.HOS } if ((ulong)position < (ulong)symbol.Value) + { right = middle - 1; + } else + { left = middle + 1; + } } name = null; @@ -396,7 +445,12 @@ namespace Ryujinx.HLE.HOS string name = string.Empty; for (int index = _executables.Count - 1; index >= 0; index--) - if ((ulong)position >= (ulong)_executables[index].ImageBase) return _executables[index]; + { + if ((ulong)position >= (ulong)_executables[index].ImageBase) + { + return _executables[index]; + } + } return null; } @@ -404,21 +458,35 @@ namespace Ryujinx.HLE.HOS private void ThreadFinished(object sender, EventArgs e) { if (sender is AThread thread) - if (_threads.TryRemove(thread.ThreadState.Tpidr, out KThread kernelThread)) Device.System.Scheduler.RemoveThread(kernelThread); + { + if (_threads.TryRemove(thread.ThreadState.Tpidr, out KThread kernelThread)) + { + Device.System.Scheduler.RemoveThread(kernelThread); + } + } - if (_threads.Count == 0) Device.System.ExitProcess(ProcessId); + if (_threads.Count == 0) + { + Device.System.ExitProcess(ProcessId); + } } public KThread GetThread(long tpidr) { - if (!_threads.TryGetValue(tpidr, out KThread thread)) throw new InvalidOperationException(); + if (!_threads.TryGetValue(tpidr, out KThread thread)) + { + throw new InvalidOperationException(); + } return thread; } private void Unload() { - if (_disposed || _threads.Count > 0) return; + if (_disposed || _threads.Count > 0) + { + return; + } _disposed = true; @@ -426,7 +494,10 @@ namespace Ryujinx.HLE.HOS INvDrvServices.UnloadProcess(this); - if (NeedsHbAbi && _executables.Count > 0 && _executables[0].FilePath.EndsWith(Homebrew.TemporaryNroSuffix)) File.Delete(_executables[0].FilePath); + if (NeedsHbAbi && _executables.Count > 0 && _executables[0].FilePath.EndsWith(Homebrew.TemporaryNroSuffix)) + { + File.Delete(_executables[0].FilePath); + } Logger.PrintInfo(LogClass.Loader, $"Process {ProcessId} exiting..."); } @@ -441,9 +512,16 @@ namespace Ryujinx.HLE.HOS if (disposing) { if (_threads.Count > 0) - foreach (KThread thread in _threads.Values) Device.System.Scheduler.StopThread(thread); + { + foreach (KThread thread in _threads.Values) + { + Device.System.Scheduler.StopThread(thread); + } + } else + { Unload(); + } } } } diff --git a/Ryujinx.HLE/HOS/Services/Acc/IAccountService.cs b/Ryujinx.HLE/HOS/Services/Acc/IAccountService.cs index b447f4a236..331c03490a 100644 --- a/Ryujinx.HLE/HOS/Services/Acc/IAccountService.cs +++ b/Ryujinx.HLE/HOS/Services/Acc/IAccountService.cs @@ -72,7 +72,10 @@ namespace Ryujinx.HLE.HOS.Services.Acc foreach (UserProfile profile in profiles) { - if ((ulong)offset + 16 > (ulong)outputSize) break; + if ((ulong)offset + 16 > (ulong)outputSize) + { + break; + } context.Memory.WriteInt64(outputPosition, profile.Uuid.Low); context.Memory.WriteInt64(outputPosition + 8, profile.Uuid.High); diff --git a/Ryujinx.HLE/HOS/Services/Am/ICommonStateGetter.cs b/Ryujinx.HLE/HOS/Services/Am/ICommonStateGetter.cs index 2273516a78..1ece1a43b0 100644 --- a/Ryujinx.HLE/HOS/Services/Am/ICommonStateGetter.cs +++ b/Ryujinx.HLE/HOS/Services/Am/ICommonStateGetter.cs @@ -37,7 +37,10 @@ namespace Ryujinx.HLE.HOS.Services.Am { KEvent Event = context.Process.AppletState.MessageEvent; - if (context.Process.HandleTable.GenerateHandle(Event.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(Event.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); @@ -46,7 +49,10 @@ namespace Ryujinx.HLE.HOS.Services.Am public long ReceiveMessage(ServiceCtx context) { - if (!context.Process.AppletState.TryDequeueMessage(out MessageInfo message)) return MakeError(ErrorModule.Am, AmErr.NoMessages); + if (!context.Process.AppletState.TryDequeueMessage(out MessageInfo message)) + { + return MakeError(ErrorModule.Am, AmErr.NoMessages); + } context.ResponseData.Write((int)message); @@ -101,7 +107,10 @@ namespace Ryujinx.HLE.HOS.Services.Am public long GetDefaultDisplayResolutionChangeEvent(ServiceCtx context) { - if (context.Process.HandleTable.GenerateHandle(_displayResolutionChangeEvent.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_displayResolutionChangeEvent.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); diff --git a/Ryujinx.HLE/HOS/Services/Am/IHomeMenuFunctions.cs b/Ryujinx.HLE/HOS/Services/Am/IHomeMenuFunctions.cs index 73ae036273..525df50891 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IHomeMenuFunctions.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IHomeMenuFunctions.cs @@ -35,7 +35,10 @@ namespace Ryujinx.HLE.HOS.Services.Am public long GetPopFromGeneralChannelEvent(ServiceCtx context) { - if (context.Process.HandleTable.GenerateHandle(_channelEvent.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_channelEvent.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); diff --git a/Ryujinx.HLE/HOS/Services/Am/ILibraryAppletAccessor.cs b/Ryujinx.HLE/HOS/Services/Am/ILibraryAppletAccessor.cs index 872306a360..7dd554b1b6 100644 --- a/Ryujinx.HLE/HOS/Services/Am/ILibraryAppletAccessor.cs +++ b/Ryujinx.HLE/HOS/Services/Am/ILibraryAppletAccessor.cs @@ -32,7 +32,10 @@ namespace Ryujinx.HLE.HOS.Services.Am { _stateChangedEvent.ReadableEvent.Signal(); - if (context.Process.HandleTable.GenerateHandle(_stateChangedEvent.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_stateChangedEvent.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); diff --git a/Ryujinx.HLE/HOS/Services/Am/ISelfController.cs b/Ryujinx.HLE/HOS/Services/Am/ISelfController.cs index 7475ad9356..7573af073c 100644 --- a/Ryujinx.HLE/HOS/Services/Am/ISelfController.cs +++ b/Ryujinx.HLE/HOS/Services/Am/ISelfController.cs @@ -64,7 +64,10 @@ namespace Ryujinx.HLE.HOS.Services.Am { _launchableEvent.ReadableEvent.Signal(); - if (context.Process.HandleTable.GenerateHandle(_launchableEvent.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_launchableEvent.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); diff --git a/Ryujinx.HLE/HOS/Services/Am/IStorageAccessor.cs b/Ryujinx.HLE/HOS/Services/Am/IStorageAccessor.cs index 755948c0a4..11e0fe5a75 100644 --- a/Ryujinx.HLE/HOS/Services/Am/IStorageAccessor.cs +++ b/Ryujinx.HLE/HOS/Services/Am/IStorageAccessor.cs @@ -42,7 +42,10 @@ namespace Ryujinx.HLE.HOS.Services.Am { long maxSize = _storage.Data.Length - writePosition; - if (size > maxSize) size = maxSize; + if (size > maxSize) + { + size = maxSize; + } byte[] data = context.Memory.ReadBytes(position, size); diff --git a/Ryujinx.HLE/HOS/Services/Aud/AudioOut/IAudioOut.cs b/Ryujinx.HLE/HOS/Services/Aud/AudioOut/IAudioOut.cs index 6441049911..a700c84b1e 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/AudioOut/IAudioOut.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/AudioOut/IAudioOut.cs @@ -67,7 +67,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioOut public long RegisterBufferEvent(ServiceCtx context) { - if (context.Process.HandleTable.GenerateHandle(_releaseEvent.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_releaseEvent.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); @@ -132,7 +135,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioOut { long tag = 0; - if (index < releasedBuffers.Length) tag = releasedBuffers[index]; + if (index < releasedBuffers.Length) + { + tag = releasedBuffers[index]; + } context.Memory.WriteInt64(position + index * 8, tag); } @@ -149,7 +155,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioOut protected virtual void Dispose(bool disposing) { - if (disposing) _audioOut.CloseTrack(_track); + if (disposing) + { + _audioOut.CloseTrack(_track); + } } } } diff --git a/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/IAudioRenderer.cs b/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/IAudioRenderer.cs index 01be4aecc1..2753870477 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/IAudioRenderer.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/IAudioRenderer.cs @@ -121,7 +121,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer { T[] output = new T[size]; - for (int index = 0; index < size; index++) output[index] = new T(); + for (int index = 0; index < size; index++) + { + output[index] = new T(); + } return output; } @@ -158,8 +161,13 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer MemoryPoolIn memoryPool = memoryPoolsIn[index]; if (memoryPool.State == MemoryPoolState.RequestAttach) + { _memoryPools[index].OutStatus.State = MemoryPoolState.Attached; - else if (memoryPool.State == MemoryPoolState.RequestDetach) _memoryPools[index].OutStatus.State = MemoryPoolState.Detached; + } + else if (memoryPool.State == MemoryPoolState.RequestDetach) + { + _memoryPools[index].OutStatus.State = MemoryPoolState.Detached; + } } reader.Read(inputHeader.VoiceResourceSize); @@ -174,7 +182,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer voiceCtx.SetAcquireState(voice.Acquired != 0); - if (voice.Acquired == 0) continue; + if (voice.Acquired == 0) + { + continue; + } if (voice.FirstUpdate != 0) { @@ -220,9 +231,15 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer writer.Write(outputHeader); - foreach (MemoryPoolContext memoryPool in _memoryPools) writer.Write(memoryPool.OutStatus); + foreach (MemoryPoolContext memoryPool in _memoryPools) + { + writer.Write(memoryPool.OutStatus); + } - foreach (VoiceContext voice in _voices) writer.Write(voice.OutStatus); + foreach (VoiceContext voice in _voices) + { + writer.Write(voice.OutStatus); + } return 0; } @@ -247,7 +264,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer public long QuerySystemEvent(ServiceCtx context) { - if (context.Process.HandleTable.GenerateHandle(_updateEvent.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_updateEvent.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); @@ -256,13 +276,19 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer private AdpcmDecoderContext GetAdpcmDecoderContext(long position, long size) { - if (size == 0) return null; + if (size == 0) + { + return null; + } AdpcmDecoderContext context = new AdpcmDecoderContext(); context.Coefficients = new short[size >> 1]; - for (int offset = 0; offset < size; offset += 2) context.Coefficients[offset >> 1] = _memory.ReadInt16(position + offset); + for (int offset = 0; offset < size; offset += 2) + { + context.Coefficients[offset >> 1] = _memory.ReadInt16(position + offset); + } return context; } @@ -271,7 +297,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer { long[] released = _audioOut.GetReleasedBuffers(_track, 2); - for (int index = 0; index < released.Length; index++) AppendMixedBuffer(released[index]); + for (int index = 0; index < released.Length; index++) + { + AppendMixedBuffer(released[index]); + } } private void AppendMixedBuffer(long tag) @@ -280,7 +309,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer foreach (VoiceContext voice in _voices) { - if (!voice.Playing) continue; + if (!voice.Playing) + { + continue; + } int outOffset = 0; @@ -290,7 +322,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer { int[] samples = voice.GetBufferData(_memory, pendingSamples, out int returnedSamples); - if (returnedSamples == 0) break; + if (returnedSamples == 0) + { + break; + } pendingSamples -= returnedSamples; @@ -310,7 +345,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer { short[] output = new short[buffer.Length]; - for (int offset = 0; offset < buffer.Length; offset++) output[offset] = DspUtils.Saturate(buffer[offset]); + for (int offset = 0; offset < buffer.Length; offset++) + { + output[offset] = DspUtils.Saturate(buffer[offset]); + } return output; } @@ -322,7 +360,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer protected virtual void Dispose(bool disposing) { - if (disposing) _audioOut.CloseTrack(_track); + if (disposing) + { + _audioOut.CloseTrack(_track); + } } } } diff --git a/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/Resampler.cs b/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/Resampler.cs index 7712db6af8..a307d4e825 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/Resampler.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/Resampler.cs @@ -121,11 +121,20 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer int samplesCount, ref int fracPart) { - if (buffer == null) throw new ArgumentNullException(nameof(buffer)); + if (buffer == null) + { + throw new ArgumentNullException(nameof(buffer)); + } - if (srcSampleRate <= 0) throw new ArgumentOutOfRangeException(nameof(srcSampleRate)); + if (srcSampleRate <= 0) + { + throw new ArgumentOutOfRangeException(nameof(srcSampleRate)); + } - if (dstSampleRate <= 0) throw new ArgumentOutOfRangeException(nameof(dstSampleRate)); + if (dstSampleRate <= 0) + { + throw new ArgumentOutOfRangeException(nameof(dstSampleRate)); + } double ratio = (double)srcSampleRate / dstSampleRate; @@ -138,11 +147,17 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer short[] lut; if (step > 0xaaaa) + { lut = _curveLut0; + } else if (step <= 0x8000) + { lut = _curveLut1; + } else + { lut = _curveLut2; + } int inOffs = 0; diff --git a/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/VoiceContext.cs b/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/VoiceContext.cs index ca9afe798f..ec9c7a6f19 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/VoiceContext.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/AudioRenderer/VoiceContext.cs @@ -40,7 +40,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer public void SetAcquireState(bool newState) { - if (_acquired && !newState) Reset(); + if (_acquired && !newState) + { + Reset(); + } _acquired = newState; } @@ -79,7 +82,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer int size = maxSamples * AudioConsts.HostChannelsCount; - if (size > maxSize) size = maxSize; + if (size > maxSize) + { + size = maxSize; + } int[] output = new int[size]; @@ -95,11 +101,17 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer { _offset = 0; - if (wb.Looping == 0) SetBufferIndex((_bufferIndex + 1) & 3); + if (wb.Looping == 0) + { + SetBufferIndex((_bufferIndex + 1) & 3); + } OutStatus.PlayedWaveBuffersCount++; - if (wb.LastBuffer != 0) PlayState = PlayState.Paused; + if (wb.LastBuffer != 0) + { + PlayState = PlayState.Paused; + } } return output; @@ -126,6 +138,7 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer _samples = new int[samplesCount * AudioConsts.HostChannelsCount]; if (ChannelsCount == 1) + { for (int index = 0; index < samplesCount; index++) { short sample = memory.ReadInt16(wb.Position + index * 2); @@ -133,8 +146,14 @@ namespace Ryujinx.HLE.HOS.Services.Aud.AudioRenderer _samples[index * 2 + 0] = sample; _samples[index * 2 + 1] = sample; } + } else - for (int index = 0; index < samplesCount * 2; index++) _samples[index] = memory.ReadInt16(wb.Position + index * 2); + { + for (int index = 0; index < samplesCount * 2; index++) + { + _samples[index] = memory.ReadInt16(wb.Position + index * 2); + } + } } else if (SampleFormat == SampleFormat.Adpcm) { diff --git a/Ryujinx.HLE/HOS/Services/Aud/IAudioDevice.cs b/Ryujinx.HLE/HOS/Services/Aud/IAudioDevice.cs index 615d5896b2..721fb5606f 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/IAudioDevice.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/IAudioDevice.cs @@ -95,16 +95,23 @@ namespace Ryujinx.HLE.HOS.Services.Aud byte[] deviceNameBuffer = Encoding.ASCII.GetBytes(name + "\0"); if ((ulong)deviceNameBuffer.Length <= (ulong)size) + { context.Memory.WriteBytes(position, deviceNameBuffer); + } else + { Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {size} too small!"); + } return 0; } public long QueryAudioDeviceSystemEvent(ServiceCtx context) { - if (context.Process.HandleTable.GenerateHandle(_systemEvent.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_systemEvent.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); @@ -184,16 +191,23 @@ namespace Ryujinx.HLE.HOS.Services.Aud byte[] deviceNameBuffer = Encoding.UTF8.GetBytes(name + '\0'); if ((ulong)deviceNameBuffer.Length <= (ulong)size) + { context.Memory.WriteBytes(position, deviceNameBuffer); + } else + { Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {size} too small!"); + } return 0; } public long QueryAudioDeviceInputEvent(ServiceCtx context) { - if (context.Process.HandleTable.GenerateHandle(_systemEvent.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_systemEvent.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); @@ -204,7 +218,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud public long QueryAudioDeviceOutputEvent(ServiceCtx context) { - if (context.Process.HandleTable.GenerateHandle(_systemEvent.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_systemEvent.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); diff --git a/Ryujinx.HLE/HOS/Services/Aud/IAudioOutManager.cs b/Ryujinx.HLE/HOS/Services/Aud/IAudioOutManager.cs index 18244197ac..b6ae012fa5 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/IAudioOutManager.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/IAudioOutManager.cs @@ -101,7 +101,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud sendPosition, sendSize); - if (deviceName == string.Empty) deviceName = DefaultAudioOutput; + if (deviceName == string.Empty) + { + deviceName = DefaultAudioOutput; + } if (deviceName != DefaultAudioOutput) { @@ -113,14 +116,21 @@ namespace Ryujinx.HLE.HOS.Services.Aud byte[] deviceNameBuffer = Encoding.ASCII.GetBytes(deviceName + "\0"); if ((ulong)deviceNameBuffer.Length <= (ulong)receiveSize) + { context.Memory.WriteBytes(receivePosition, deviceNameBuffer); + } else + { Logger.PrintError(LogClass.ServiceAudio, $"Output buffer size {receiveSize} too small!"); + } int sampleRate = context.RequestData.ReadInt32(); int channels = context.RequestData.ReadInt32(); - if (sampleRate == 0) sampleRate = DefaultSampleRate; + if (sampleRate == 0) + { + sampleRate = DefaultSampleRate; + } if (sampleRate != DefaultSampleRate) { @@ -131,7 +141,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud channels = (ushort)channels; - if (channels == 0) channels = DefaultChannelsCount; + if (channels == 0) + { + channels = DefaultChannelsCount; + } KEvent releaseEvent = new KEvent(context.Device.System); diff --git a/Ryujinx.HLE/HOS/Services/Aud/IAudioRendererManager.cs b/Ryujinx.HLE/HOS/Services/Aud/IAudioRendererManager.cs index 08fb91e0e5..b6c64d9391 100644 --- a/Ryujinx.HLE/HOS/Services/Aud/IAudioRendererManager.cs +++ b/Ryujinx.HLE/HOS/Services/Aud/IAudioRendererManager.cs @@ -90,11 +90,13 @@ namespace Ryujinx.HLE.HOS.Services.Aud IntUtils.AlignUp(size, 64) + 0x40; if (Params.PerformanceManagerCount >= 1) + { size += (((Params.EffectCount + Params.SinkCount + Params.VoiceCount + Params.MixCount + 1) * 16 + 0x658) * (Params.PerformanceManagerCount + 1) + 0x13F) & ~0x3FL; + } size = (size + 0x1907D) & ~0xFFFL; @@ -139,7 +141,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud { int result = IntUtils.AlignUp(value, 64); - if (result < 0) result |= 7; + if (result < 0) + { + result |= 7; + } return 4 * value * value + 0x12 * value + 2 * (result / 8); } @@ -148,7 +153,10 @@ namespace Ryujinx.HLE.HOS.Services.Aud { int result = IntUtils.AlignUp(value * value, 64); - if (result < 0) result |= 7; + if (result < 0) + { + result |= 7; + } return result / 8; } diff --git a/Ryujinx.HLE/HOS/Services/Bsd/IClient.cs b/Ryujinx.HLE/HOS/Services/Bsd/IClient.cs index f94716281c..0eb97e831c 100644 --- a/Ryujinx.HLE/HOS/Services/Bsd/IClient.cs +++ b/Ryujinx.HLE/HOS/Services/Bsd/IClient.cs @@ -144,7 +144,10 @@ namespace Ryujinx.HLE.HOS.Services.Bsd { LinuxError errno; - if (!_errorMap.TryGetValue(errorCode, out errno)) errno = (LinuxError)errorCode; + if (!_errorMap.TryGetValue(errorCode, out errno)) + { + errno = (LinuxError)errorCode; + } return errno; } @@ -156,7 +159,10 @@ namespace Ryujinx.HLE.HOS.Services.Bsd private long WriteBsdResult(ServiceCtx context, int result, LinuxError errorCode = 0) { - if (errorCode != LinuxError.Success) result = -1; + if (errorCode != LinuxError.Success) + { + result = -1; + } context.ResponseData.Write(result); context.ResponseData.Write((int)errorCode); @@ -166,7 +172,10 @@ namespace Ryujinx.HLE.HOS.Services.Bsd private BsdSocket RetrieveSocket(int socketFd) { - if (socketFd >= 0 && _sockets.Count > socketFd) return _sockets[socketFd]; + if (socketFd >= 0 && _sockets.Count > socketFd) + { + return _sockets[socketFd]; + } return null; } @@ -178,7 +187,10 @@ namespace Ryujinx.HLE.HOS.Services.Bsd private AddressFamily ConvertFromBsd(int domain) { - if (domain == 2) return AddressFamily.InterNetwork; + if (domain == 2) + { + return AddressFamily.InterNetwork; + } // FIXME: AF_ROUTE ignored, is that really needed? return AddressFamily.Unknown; @@ -191,9 +203,16 @@ namespace Ryujinx.HLE.HOS.Services.Bsd ProtocolType protocol = (ProtocolType)context.RequestData.ReadInt32(); if (domain == AddressFamily.Unknown) + { return WriteBsdResult(context, -1, LinuxError.Eprotonosupport); + } else if ((type == SocketType.Seqpacket || type == SocketType.Raw) && !_isPrivileged) - if (domain != AddressFamily.InterNetwork || type != SocketType.Raw || protocol != ProtocolType.Icmp) return WriteBsdResult(context, -1, LinuxError.Enoent); + { + if (domain != AddressFamily.InterNetwork || type != SocketType.Raw || protocol != ProtocolType.Icmp) + { + return WriteBsdResult(context, -1, LinuxError.Enoent); + } + } BsdSocket newBsdSocket = new BsdSocket { @@ -205,7 +224,10 @@ namespace Ryujinx.HLE.HOS.Services.Bsd _sockets.Add(newBsdSocket); - if (exempt) newBsdSocket.Handle.Disconnect(true); + if (exempt) + { + newBsdSocket.Handle.Disconnect(true); + } return WriteBsdResult(context, _sockets.Count - 1); } @@ -319,7 +341,10 @@ namespace Ryujinx.HLE.HOS.Services.Bsd (long bufferPosition, long bufferSize) = context.Request.GetBufferType0X21(); - if (timeout < -1 || fdsCount < 0 || fdsCount * 8 > bufferSize) return WriteBsdResult(context, -1, LinuxError.Einval); + if (timeout < -1 || fdsCount < 0 || fdsCount * 8 > bufferSize) + { + return WriteBsdResult(context, -1, LinuxError.Einval); + } PollEvent[] events = new PollEvent[fdsCount]; @@ -329,7 +354,10 @@ namespace Ryujinx.HLE.HOS.Services.Bsd BsdSocket socket = RetrieveSocket(socketFd); - if (socket == null) return WriteBsdResult(context, -1, LinuxError.Ebadf); + if (socket == null) + { + return WriteBsdResult(context, -1, LinuxError.Ebadf); + } PollEvent.EventTypeMask inputEvents = (PollEvent.EventTypeMask)context.Memory.ReadInt16(bufferPosition + i * 8 + 4); PollEvent.EventTypeMask outputEvents = (PollEvent.EventTypeMask)context.Memory.ReadInt16(bufferPosition + i * 8 + 6); @@ -405,13 +433,24 @@ namespace Ryujinx.HLE.HOS.Services.Bsd { outputEvents |= PollEvent.EventTypeMask.Error; - if (!socket.Connected || !socket.IsBound) outputEvents |= PollEvent.EventTypeMask.Disconnected; + if (!socket.Connected || !socket.IsBound) + { + outputEvents |= PollEvent.EventTypeMask.Disconnected; + } } if (readEvents.Contains(socket)) - if ((Event.InputEvents & PollEvent.EventTypeMask.Input) != 0) outputEvents |= PollEvent.EventTypeMask.Input; + { + if ((Event.InputEvents & PollEvent.EventTypeMask.Input) != 0) + { + outputEvents |= PollEvent.EventTypeMask.Input; + } + } - if (writeEvents.Contains(socket)) outputEvents |= PollEvent.EventTypeMask.Output; + if (writeEvents.Contains(socket)) + { + outputEvents |= PollEvent.EventTypeMask.Output; + } context.Memory.WriteInt16(bufferPosition + i * 8 + 6, (short)outputEvents); } @@ -764,9 +803,13 @@ namespace Ryujinx.HLE.HOS.Services.Bsd errno = LinuxError.Enoprotoopt; if (level == 0xFFFF) + { errno = HandleGetSocketOption(context, socket, (SocketOptionName)optionName, bufferPosition, bufferSize); + } else + { Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported GetSockOpt Level: {(SocketOptionLevel)level}"); + } } return WriteBsdResult(context, 0, errno); @@ -809,6 +852,7 @@ namespace Ryujinx.HLE.HOS.Services.Bsd BsdSocket socket = RetrieveSocket(socketFd); if (socket != null) + { switch (cmd) { case BsdIoctl.AtMark: @@ -826,6 +870,7 @@ namespace Ryujinx.HLE.HOS.Services.Bsd Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported Ioctl Cmd: {cmd}"); break; } + } return WriteBsdResult(context, 0, errno); } @@ -968,9 +1013,13 @@ namespace Ryujinx.HLE.HOS.Services.Bsd errno = LinuxError.Enoprotoopt; if (level == 0xFFFF) + { errno = HandleSetSocketOption(context, socket, (SocketOptionName)optionName, bufferPos, bufferSize); + } else + { Logger.PrintWarning(LogClass.ServiceBsd, $"Unsupported SetSockOpt Level: {(SocketOptionLevel)level}"); + } } return WriteBsdResult(context, 0, errno); @@ -1019,7 +1068,9 @@ namespace Ryujinx.HLE.HOS.Services.Bsd errno = LinuxError.Success; foreach (BsdSocket socket in _sockets) + { if (socket != null) + { try { socket.Handle.Shutdown((SocketShutdown)how); @@ -1029,6 +1080,8 @@ namespace Ryujinx.HLE.HOS.Services.Bsd errno = ConvertError((WSAError)exception.ErrorCode); break; } + } + } } return WriteBsdResult(context, 0, errno); diff --git a/Ryujinx.HLE/HOS/Services/Friend/IFriendService.cs b/Ryujinx.HLE/HOS/Services/Friend/IFriendService.cs index df73e50dc6..3e71b44751 100644 --- a/Ryujinx.HLE/HOS/Services/Friend/IFriendService.cs +++ b/Ryujinx.HLE/HOS/Services/Friend/IFriendService.cs @@ -66,7 +66,10 @@ namespace Ryujinx.HLE.HOS.Services.Friend context.RequestData.ReadInt64(), context.RequestData.ReadInt64()); - if (context.Device.System.State.TryGetUser(uuid, out UserProfile profile)) profile.OnlinePlayState = OpenCloseState.Closed; + if (context.Device.System.State.TryGetUser(uuid, out UserProfile profile)) + { + profile.OnlinePlayState = OpenCloseState.Closed; + } Logger.PrintStub(LogClass.ServiceFriend, $"Stubbed. Uuid: {uuid.ToString()} - " + $"OnlinePlayState: {profile.OnlinePlayState}"); diff --git a/Ryujinx.HLE/HOS/Services/FspSrv/IDirectory.cs b/Ryujinx.HLE/HOS/Services/FspSrv/IDirectory.cs index dbe466dce3..bfed6ab3ea 100644 --- a/Ryujinx.HLE/HOS/Services/FspSrv/IDirectory.cs +++ b/Ryujinx.HLE/HOS/Services/FspSrv/IDirectory.cs @@ -34,9 +34,15 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv _directoryEntries = new List(); - if ((flags & 1) != 0) _directoryEntries.AddRange(Directory.GetDirectories(hostPath)); + if ((flags & 1) != 0) + { + _directoryEntries.AddRange(Directory.GetDirectories(hostPath)); + } - if ((flags & 2) != 0) _directoryEntries.AddRange(Directory.GetFiles(hostPath)); + if ((flags & 2) != 0) + { + _directoryEntries.AddRange(Directory.GetFiles(hostPath)); + } _currentItemIndex = 0; } @@ -64,7 +70,10 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv private void WriteDirectoryEntry(ServiceCtx context, long position, string fullPath) { - for (int offset = 0; offset < 0x300; offset += 8) context.Memory.WriteInt64(position + offset, 0); + for (int offset = 0; offset < 0x300; offset += 8) + { + context.Memory.WriteInt64(position + offset, 0); + } byte[] nameBuffer = Encoding.UTF8.GetBytes(Path.GetFileName(fullPath)); @@ -98,7 +107,10 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv protected virtual void Dispose(bool disposing) { - if (disposing) Disposed?.Invoke(this, EventArgs.Empty); + if (disposing) + { + Disposed?.Invoke(this, EventArgs.Empty); + } } } } diff --git a/Ryujinx.HLE/HOS/Services/FspSrv/IFileSystem.cs b/Ryujinx.HLE/HOS/Services/FspSrv/IFileSystem.cs index 3fb8e3df1f..0d0d7aabda 100644 --- a/Ryujinx.HLE/HOS/Services/FspSrv/IFileSystem.cs +++ b/Ryujinx.HLE/HOS/Services/FspSrv/IFileSystem.cs @@ -53,11 +53,20 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv string fileName = context.Device.FileSystem.GetFullPath(_path, name); - if (fileName == null) return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + if (fileName == null) + { + return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + } - if (File.Exists(fileName)) return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); + if (File.Exists(fileName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); + } - if (IsPathAlreadyInUse(fileName)) return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + if (IsPathAlreadyInUse(fileName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + } using (FileStream newFile = File.Create(fileName)) { @@ -73,9 +82,15 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv string fileName = context.Device.FileSystem.GetFullPath(_path, name); - if (!File.Exists(fileName)) return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + if (!File.Exists(fileName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + } - if (IsPathAlreadyInUse(fileName)) return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + if (IsPathAlreadyInUse(fileName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + } File.Delete(fileName); @@ -88,11 +103,20 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv string dirName = context.Device.FileSystem.GetFullPath(_path, name); - if (dirName == null) return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + if (dirName == null) + { + return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + } - if (Directory.Exists(dirName)) return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); + if (Directory.Exists(dirName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); + } - if (IsPathAlreadyInUse(dirName)) return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + if (IsPathAlreadyInUse(dirName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + } Directory.CreateDirectory(dirName); @@ -115,9 +139,15 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv string dirName = context.Device.FileSystem.GetFullPath(_path, name); - if (!Directory.Exists(dirName)) return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + if (!Directory.Exists(dirName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + } - if (IsPathAlreadyInUse(dirName)) return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + if (IsPathAlreadyInUse(dirName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + } Directory.Delete(dirName, recursive); @@ -132,11 +162,20 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv string oldFileName = context.Device.FileSystem.GetFullPath(_path, oldName); string newFileName = context.Device.FileSystem.GetFullPath(_path, newName); - if (!File.Exists(oldFileName)) return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + if (!File.Exists(oldFileName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + } - if (File.Exists(newFileName)) return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); + if (File.Exists(newFileName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); + } - if (IsPathAlreadyInUse(oldFileName)) return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + if (IsPathAlreadyInUse(oldFileName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + } File.Move(oldFileName, newFileName); @@ -151,11 +190,20 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv string oldDirName = context.Device.FileSystem.GetFullPath(_path, oldName); string newDirName = context.Device.FileSystem.GetFullPath(_path, newName); - if (!Directory.Exists(oldDirName)) return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + if (!Directory.Exists(oldDirName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + } - if (Directory.Exists(newDirName)) return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); + if (Directory.Exists(newDirName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); + } - if (IsPathAlreadyInUse(oldDirName)) return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + if (IsPathAlreadyInUse(oldDirName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + } Directory.Move(oldDirName, newDirName); @@ -194,9 +242,15 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv string fileName = context.Device.FileSystem.GetFullPath(_path, name); - if (!File.Exists(fileName)) return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + if (!File.Exists(fileName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + } - if (IsPathAlreadyInUse(fileName)) return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + if (IsPathAlreadyInUse(fileName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + } FileStream stream = new FileStream(fileName, FileMode.Open); @@ -222,7 +276,10 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv string dirName = context.Device.FileSystem.GetFullPath(_path, name); - if (!Directory.Exists(dirName)) return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + if (!Directory.Exists(dirName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + } IDirectory dirInterface = new IDirectory(dirName, filterFlags); @@ -267,14 +324,27 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv string dirName = context.Device.FileSystem.GetFullPath(_path, name); - if (!Directory.Exists(dirName)) return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + if (!Directory.Exists(dirName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); + } - if (IsPathAlreadyInUse(dirName)) return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + if (IsPathAlreadyInUse(dirName)) + { + return MakeError(ErrorModule.Fs, FsErr.PathAlreadyInUse); + } foreach (string entry in Directory.EnumerateFileSystemEntries(dirName)) + { if (Directory.Exists(entry)) + { Directory.Delete(entry, true); - else if (File.Exists(entry)) File.Delete(entry); + } + else if (File.Exists(entry)) + { + File.Delete(entry); + } + } return 0; } @@ -322,7 +392,10 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv { byte value = context.Memory.ReadByte(position++); - if (value == 0) break; + if (value == 0) + { + break; + } ms.WriteByte(value); } diff --git a/Ryujinx.HLE/HOS/Services/FspSrv/IStorage.cs b/Ryujinx.HLE/HOS/Services/FspSrv/IStorage.cs index 314f99fcde..bffb87c391 100644 --- a/Ryujinx.HLE/HOS/Services/FspSrv/IStorage.cs +++ b/Ryujinx.HLE/HOS/Services/FspSrv/IStorage.cs @@ -32,7 +32,10 @@ namespace Ryujinx.HLE.HOS.Services.FspSrv IpcBuffDesc buffDesc = context.Request.ReceiveBuff[0]; //Use smaller length to avoid overflows. - if (size > buffDesc.Size) size = buffDesc.Size; + if (size > buffDesc.Size) + { + size = buffDesc.Size; + } byte[] data = new byte[size]; diff --git a/Ryujinx.HLE/HOS/Services/Hid/IAppletResource.cs b/Ryujinx.HLE/HOS/Services/Hid/IAppletResource.cs index c82815ce9c..e143d27bb6 100644 --- a/Ryujinx.HLE/HOS/Services/Hid/IAppletResource.cs +++ b/Ryujinx.HLE/HOS/Services/Hid/IAppletResource.cs @@ -25,7 +25,10 @@ namespace Ryujinx.HLE.HOS.Services.Hid public long GetSharedMemoryHandle(ServiceCtx context) { - if (context.Process.HandleTable.GenerateHandle(_hidSharedMem, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_hidSharedMem, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); diff --git a/Ryujinx.HLE/HOS/Services/Hid/IHidServer.cs b/Ryujinx.HLE/HOS/Services/Hid/IHidServer.cs index a01b659681..d83f9d152b 100644 --- a/Ryujinx.HLE/HOS/Services/Hid/IHidServer.cs +++ b/Ryujinx.HLE/HOS/Services/Hid/IHidServer.cs @@ -218,7 +218,10 @@ namespace Ryujinx.HLE.HOS.Services.Hid { long xpadId = context.RequestData.ReadInt64(); - if (context.Process.HandleTable.GenerateHandle(_xpadIdEvent, out _xpadIdEventHandle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_xpadIdEvent, out _xpadIdEventHandle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(_xpadIdEventHandle); @@ -711,7 +714,10 @@ namespace Ryujinx.HLE.HOS.Services.Hid int npadId = context.RequestData.ReadInt32(); long npadStyleSet = context.RequestData.ReadInt64(); - if (context.Process.HandleTable.GenerateHandle(_npadStyleSetUpdateEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_npadStyleSetUpdateEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); @@ -1350,7 +1356,10 @@ namespace Ryujinx.HLE.HOS.Services.Hid { int palmaConnectionHandle = context.RequestData.ReadInt32(); - if (context.Process.HandleTable.GenerateHandle(_palmaOperationCompleteEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_palmaOperationCompleteEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); diff --git a/Ryujinx.HLE/HOS/Services/IpcService.cs b/Ryujinx.HLE/HOS/Services/IpcService.cs index 187aecaeb8..4e2ad21426 100644 --- a/Ryujinx.HLE/HOS/Services/IpcService.cs +++ b/Ryujinx.HLE/HOS/Services/IpcService.cs @@ -26,7 +26,10 @@ namespace Ryujinx.HLE.HOS.Services public int ConvertToDomain() { - if (_selfId == -1) _selfId = _domainObjects.Add(this); + if (_selfId == -1) + { + _selfId = _domainObjects.Add(this); + } _isDomain = true; @@ -53,7 +56,10 @@ namespace Ryujinx.HLE.HOS.Services context.RequestData.BaseStream.Seek(0x10 + dataPayloadSize, SeekOrigin.Begin); - for (int index = 0; index < inputObjCount; index++) context.Request.ObjectIds.Add(context.RequestData.ReadInt32()); + for (int index = 0; index < inputObjCount; index++) + { + context.Request.ObjectIds.Add(context.RequestData.ReadInt32()); + } context.RequestData.BaseStream.Seek(0x10, SeekOrigin.Begin); @@ -91,7 +97,10 @@ namespace Ryujinx.HLE.HOS.Services if (_isDomain) { - foreach (int id in context.Response.ObjectIds) context.ResponseData.Write(id); + foreach (int id in context.Response.ObjectIds) + { + context.ResponseData.Write(id); + } context.ResponseData.BaseStream.Seek(0, SeekOrigin.Begin); @@ -123,7 +132,10 @@ namespace Ryujinx.HLE.HOS.Services { KSession session = new KSession(obj, context.Session.ServiceName); - if (context.Process.HandleTable.GenerateHandle(session, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(session, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeMove(handle); } @@ -158,7 +170,10 @@ namespace Ryujinx.HLE.HOS.Services { object obj = _domainObjects.Delete(id); - if (obj is IDisposable disposableObj) disposableObj.Dispose(); + if (obj is IDisposable disposableObj) + { + disposableObj.Dispose(); + } return obj != null; } diff --git a/Ryujinx.HLE/HOS/Services/Ldr/IRoInterface.cs b/Ryujinx.HLE/HOS/Services/Ldr/IRoInterface.cs index 7f565d68cd..9a6ab2415b 100644 --- a/Ryujinx.HLE/HOS/Services/Ldr/IRoInterface.cs +++ b/Ryujinx.HLE/HOS/Services/Ldr/IRoInterface.cs @@ -113,19 +113,32 @@ namespace Ryujinx.HLE.HOS.Services.Ldr nrrInfo = null; if (nrrSize == 0 || nrrAddress + nrrSize <= nrrAddress || (nrrSize & 0xFFF) != 0) + { return MakeError(ErrorModule.Loader, LoaderErr.BadSize); - else if ((nrrAddress & 0xFFF) != 0) return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress); + } + else if ((nrrAddress & 0xFFF) != 0) + { + return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress); + } StructReader reader = new StructReader(context.Memory, nrrAddress); NrrHeader header = reader.Read(); if (header.Magic != NrrMagic) + { return MakeError(ErrorModule.Loader, LoaderErr.InvalidNrr); - else if (header.NrrSize != nrrSize) return MakeError(ErrorModule.Loader, LoaderErr.BadSize); + } + else if (header.NrrSize != nrrSize) + { + return MakeError(ErrorModule.Loader, LoaderErr.BadSize); + } List hashes = new List(); - for (int i = 0; i < header.HashCount; i++) hashes.Add(context.Memory.ReadBytes(nrrAddress + header.HashOffset + i * 0x20, 0x20)); + for (int i = 0; i < header.HashCount; i++) + { + hashes.Add(context.Memory.ReadBytes(nrrAddress + header.HashOffset + i * 0x20, 0x20)); + } nrrInfo = new NrrInfo(nrrAddress, header, hashes); @@ -135,8 +148,15 @@ namespace Ryujinx.HLE.HOS.Services.Ldr public bool IsNroHashPresent(byte[] nroHash) { foreach (NrrInfo info in _nrrInfos) - foreach (byte[] hash in info.Hashes) - if (hash.SequenceEqual(nroHash)) return true; + { + foreach (byte[] hash in info.Hashes) + { + if (hash.SequenceEqual(nroHash)) + { + return true; + } + } + } return false; } @@ -144,7 +164,12 @@ namespace Ryujinx.HLE.HOS.Services.Ldr public bool IsNroLoaded(byte[] nroHash) { foreach (NroInfo info in _nroInfos) - if (info.Hash.SequenceEqual(nroHash)) return true; + { + if (info.Hash.SequenceEqual(nroHash)) + { + return true; + } + } return false; } @@ -154,17 +179,29 @@ namespace Ryujinx.HLE.HOS.Services.Ldr res = null; if (_nroInfos.Count >= MaxNro) + { return MakeError(ErrorModule.Loader, LoaderErr.MaxNro); + } else if (nroSize == 0 || nroHeapAddress + nroSize <= nroHeapAddress || (nroSize & 0xFFF) != 0) + { return MakeError(ErrorModule.Loader, LoaderErr.BadSize); + } else if (bssSize != 0 && bssHeapAddress + bssSize <= bssHeapAddress) + { return MakeError(ErrorModule.Loader, LoaderErr.BadSize); - else if ((nroHeapAddress & 0xFFF) != 0) return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress); + } + else if ((nroHeapAddress & 0xFFF) != 0) + { + return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress); + } uint magic = context.Memory.ReadUInt32(nroHeapAddress + 0x10); uint nroFileSize = context.Memory.ReadUInt32(nroHeapAddress + 0x18); - if (magic != NroMagic || nroSize != nroFileSize) return MakeError(ErrorModule.Loader, LoaderErr.InvalidNro); + if (magic != NroMagic || nroSize != nroFileSize) + { + return MakeError(ErrorModule.Loader, LoaderErr.InvalidNro); + } byte[] nroData = context.Memory.ReadBytes(nroHeapAddress, nroSize); byte[] nroHash = null; @@ -176,9 +213,15 @@ namespace Ryujinx.HLE.HOS.Services.Ldr nroHash = hasher.ComputeHash(stream); } - if (!IsNroHashPresent(nroHash)) return MakeError(ErrorModule.Loader, LoaderErr.NroHashNotPresent); + if (!IsNroHashPresent(nroHash)) + { + return MakeError(ErrorModule.Loader, LoaderErr.NroHashNotPresent); + } - if (IsNroLoaded(nroHash)) return MakeError(ErrorModule.Loader, LoaderErr.NroAlreadyLoaded); + if (IsNroLoaded(nroHash)) + { + return MakeError(ErrorModule.Loader, LoaderErr.NroAlreadyLoaded); + } stream.Position = 0; @@ -187,16 +230,23 @@ namespace Ryujinx.HLE.HOS.Services.Ldr // check if everything is page align. if ((executable.Text.Length & 0xFFF) != 0 || (executable.Ro.Length & 0xFFF) != 0 || (executable.Data.Length & 0xFFF) != 0 || (executable.BssSize & 0xFFF) != 0) + { return MakeError(ErrorModule.Loader, LoaderErr.InvalidNro); + } // check if everything is contiguous. if (executable.RoOffset != executable.TextOffset + executable.Text.Length || executable.DataOffset != executable.RoOffset + executable.Ro.Length || nroFileSize != executable.DataOffset + executable.Data.Length) + { return MakeError(ErrorModule.Loader, LoaderErr.InvalidNro); + } // finally check the bss size match. - if (executable.BssSize != bssSize) return MakeError(ErrorModule.Loader, LoaderErr.InvalidNro); + if (executable.BssSize != bssSize) + { + return MakeError(ErrorModule.Loader, LoaderErr.InvalidNro); + } res = new NroInfo(executable, nroHash, executable.Text.Length + executable.Ro.Length + executable.Data.Length + executable.BssSize); @@ -216,7 +266,10 @@ namespace Ryujinx.HLE.HOS.Services.Ldr while (true) { - if (targetAddress + info.TotalSize >= context.Process.MemoryManager.AddrSpaceEnd) return MakeError(ErrorModule.Loader, LoaderErr.InvalidMemoryState); + if (targetAddress + info.TotalSize >= context.Process.MemoryManager.AddrSpaceEnd) + { + return MakeError(ErrorModule.Loader, LoaderErr.InvalidMemoryState); + } bool isValidAddress = !(heapRegionStart > 0 && heapRegionStart <= targetAddress + info.TotalSize - 1 && targetAddress <= heapRegionEnd - 1) @@ -224,7 +277,10 @@ namespace Ryujinx.HLE.HOS.Services.Ldr && mapRegionStart <= targetAddress + info.TotalSize - 1 && targetAddress <= mapRegionEnd - 1); - if (isValidAddress && context.Process.MemoryManager.HleIsUnmapped(targetAddress, info.TotalSize)) break; + if (isValidAddress && context.Process.MemoryManager.HleIsUnmapped(targetAddress, info.TotalSize)) + { + break; + } targetAddress += 0x1000; } @@ -240,12 +296,14 @@ namespace Ryujinx.HLE.HOS.Services.Ldr private long RemoveNrrInfo(long nrrAddress) { foreach (NrrInfo info in _nrrInfos) + { if (info.NrrAddress == nrrAddress) { _nrrInfos.Remove(info); return 0; } + } return MakeError(ErrorModule.Loader, LoaderErr.BadNrrAddress); } @@ -253,6 +311,7 @@ namespace Ryujinx.HLE.HOS.Services.Ldr private long RemoveNroInfo(ServiceCtx context, long nroMappedAddress, long nroHeapAddress) { foreach (NroInfo info in _nroInfos) + { if (info.NroMappedAddress == nroMappedAddress && info.Executable.SourceAddress == nroHeapAddress) { _nroInfos.Remove(info); @@ -261,10 +320,14 @@ namespace Ryujinx.HLE.HOS.Services.Ldr long result = context.Process.MemoryManager.UnmapProcessCodeMemory(info.NroMappedAddress, info.Executable.SourceAddress, info.TotalSize - info.Executable.BssSize); - if (result == 0 && info.Executable.BssSize != 0) result = context.Process.MemoryManager.UnmapProcessCodeMemory(info.NroMappedAddress + info.TotalSize - info.Executable.BssSize, info.Executable.BssAddress, info.Executable.BssSize); + if (result == 0 && info.Executable.BssSize != 0) + { + result = context.Process.MemoryManager.UnmapProcessCodeMemory(info.NroMappedAddress + info.TotalSize - info.Executable.BssSize, info.Executable.BssAddress, info.Executable.BssSize); + } return result; } + } return MakeError(ErrorModule.Loader, LoaderErr.BadNroAddress); } @@ -294,7 +357,10 @@ namespace Ryujinx.HLE.HOS.Services.Ldr { result = MapNro(context, info, out nroMappedAddress); - if (result == 0) _nroInfos.Add(info); + if (result == 0) + { + _nroInfos.Add(info); + } } } @@ -313,7 +379,10 @@ namespace Ryujinx.HLE.HOS.Services.Ldr if (_isInitialized) { - if ((nroMappedAddress & 0xFFF) != 0 || (nroHeapAddress & 0xFFF) != 0) return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress); + if ((nroMappedAddress & 0xFFF) != 0 || (nroHeapAddress & 0xFFF) != 0) + { + return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress); + } result = RemoveNroInfo(context, nroMappedAddress, nroHeapAddress); } @@ -340,9 +409,13 @@ namespace Ryujinx.HLE.HOS.Services.Ldr if(result == 0) { if (_nrrInfos.Count >= MaxNrr) + { result = MakeError(ErrorModule.Loader, LoaderErr.MaxNrr); + } else + { _nrrInfos.Add(info); + } } } @@ -361,7 +434,10 @@ namespace Ryujinx.HLE.HOS.Services.Ldr if (_isInitialized) { - if ((nrrHeapAddress & 0xFFF) != 0) return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress); + if ((nrrHeapAddress & 0xFFF) != 0) + { + return MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress); + } result = RemoveNrrInfo(nrrHeapAddress); } diff --git a/Ryujinx.HLE/HOS/Services/Nfp/IUser.cs b/Ryujinx.HLE/HOS/Services/Nfp/IUser.cs index 375b7465ec..8a4ccf89c0 100644 --- a/Ryujinx.HLE/HOS/Services/Nfp/IUser.cs +++ b/Ryujinx.HLE/HOS/Services/Nfp/IUser.cs @@ -56,7 +56,10 @@ namespace Ryujinx.HLE.HOS.Services.Nfp { Logger.PrintStub(LogClass.ServiceNfp, "Stubbed."); - if (context.Process.HandleTable.GenerateHandle(_activateEvent.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_activateEvent.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle);; @@ -67,7 +70,10 @@ namespace Ryujinx.HLE.HOS.Services.Nfp { Logger.PrintStub(LogClass.ServiceNfp, "Stubbed."); - if (context.Process.HandleTable.GenerateHandle(_deactivateEvent.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_deactivateEvent.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); @@ -105,7 +111,10 @@ namespace Ryujinx.HLE.HOS.Services.Nfp { Logger.PrintStub(LogClass.ServiceNfp, "Stubbed."); - if (context.Process.HandleTable.GenerateHandle(_availabilityChangeEvent.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_availabilityChangeEvent.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); diff --git a/Ryujinx.HLE/HOS/Services/Nifm/IGeneralService.cs b/Ryujinx.HLE/HOS/Services/Nifm/IGeneralService.cs index e5dda8bb9e..6a9d8b8254 100644 --- a/Ryujinx.HLE/HOS/Services/Nifm/IGeneralService.cs +++ b/Ryujinx.HLE/HOS/Services/Nifm/IGeneralService.cs @@ -39,7 +39,10 @@ namespace Ryujinx.HLE.HOS.Services.Nifm public long GetCurrentIpAddress(ServiceCtx context) { - if (!NetworkInterface.GetIsNetworkAvailable()) return MakeError(ErrorModule.Nifm, NifmErr.NoInternetConnection); + if (!NetworkInterface.GetIsNetworkAvailable()) + { + return MakeError(ErrorModule.Nifm, NifmErr.NoInternetConnection); + } IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); diff --git a/Ryujinx.HLE/HOS/Services/Nifm/IRequest.cs b/Ryujinx.HLE/HOS/Services/Nifm/IRequest.cs index 66ae443384..fc47c32fff 100644 --- a/Ryujinx.HLE/HOS/Services/Nifm/IRequest.cs +++ b/Ryujinx.HLE/HOS/Services/Nifm/IRequest.cs @@ -49,9 +49,15 @@ namespace Ryujinx.HLE.HOS.Services.Nifm public long GetSystemEventReadableHandles(ServiceCtx context) { - if (context.Process.HandleTable.GenerateHandle(_event0.ReadableEvent, out int handle0) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_event0.ReadableEvent, out int handle0) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } - if (context.Process.HandleTable.GenerateHandle(_event1.ReadableEvent, out int handle1) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_event1.ReadableEvent, out int handle1) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle0, handle1); diff --git a/Ryujinx.HLE/HOS/Services/Nv/INvDrvServices.cs b/Ryujinx.HLE/HOS/Services/Nv/INvDrvServices.cs index d8d908d26d..36392ea471 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/INvDrvServices.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/INvDrvServices.cs @@ -80,9 +80,13 @@ namespace Ryujinx.HLE.HOS.Services.Nv int result; if (_ioctlProcessors.TryGetValue(fdData.Name, out IoctlProcessor process)) + { result = process(context, cmd); + } else + { throw new NotImplementedException($"{fdData.Name} {cmd:x4}"); + } //TODO: Verify if the error codes needs to be translated. context.ResponseData.Write(result); @@ -119,7 +123,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv int eventId = context.RequestData.ReadInt32(); //TODO: Use Fd/EventId, different channels have different events. - if (context.Process.HandleTable.GenerateHandle(_event.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_event.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASCtx.cs b/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASCtx.cs index b51440a76d..6f04de5d9d 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASCtx.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASCtx.cs @@ -51,18 +51,30 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS long mapEnd = position + size; //Check if size is valid (0 is also not allowed). - if ((ulong)mapEnd <= (ulong)position) return false; + if ((ulong)mapEnd <= (ulong)position) + { + return false; + } //Check if address is page aligned. - if ((position & NvGpuVmm.PageMask) != 0) return false; + if ((position & NvGpuVmm.PageMask) != 0) + { + return false; + } //Check if region is reserved. - if (BinarySearch(_reservations, position) == null) return false; + if (BinarySearch(_reservations, position) == null) + { + return false; + } //Check for overlap with already mapped buffers. Range map = BinarySearchLt(_maps, mapEnd); - if (map != null && map.End > (ulong)position) return false; + if (map != null && map.End > (ulong)position) + { + return false; + } return true; } @@ -84,7 +96,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS { MappedMemory map = (MappedMemory)value; - if (map.VaAllocated) size = (long)(map.End - map.Start); + if (map.VaAllocated) + { + size = (long)(map.End - map.Start); + } return true; } @@ -131,12 +146,19 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS Range rg = lst.Values[middle]; - if ((ulong)position >= rg.Start && (ulong)position < rg.End) return rg; + if ((ulong)position >= rg.Start && (ulong)position < rg.End) + { + return rg; + } if ((ulong)position < rg.Start) + { right = middle - 1; + } else + { left = middle + 1; + } } return null; @@ -165,7 +187,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS { left = middle + 1; - if ((ulong)position > rg.Start) ltRg = rg; + if ((ulong)position > rg.Start) + { + ltRg = rg; + } } } diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASIoctl.cs b/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASIoctl.cs index fc41c64fe2..7280da17a2 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASIoctl.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvGpuAS/NvGpuASIoctl.cs @@ -66,9 +66,13 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS //Note: When the fixed offset flag is not set, //the Offset field holds the alignment size instead. if ((args.Flags & FlagFixedOffset) != 0) + { args.Offset = asCtx.Vmm.ReserveFixed(args.Offset, (long)size); + } else + { args.Offset = asCtx.Vmm.Reserve((long)size, args.Offset); + } if (args.Offset < 0) { @@ -134,7 +138,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS { if (asCtx.RemoveMap(args.Offset, out long size)) { - if (size != 0) asCtx.Vmm.Free(args.Offset, size); + if (size != 0) + { + asCtx.Vmm.Free(args.Offset, size); + } } else { @@ -168,6 +175,7 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS long pa; if ((args.Flags & FlagRemapSubRange) != 0) + { lock (asCtx) { if (asCtx.TryGetMapPhysicalAddress(args.Offset, out pa)) @@ -194,12 +202,16 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuAS return NvResult.InvalidInput; } } + } pa = map.Address + args.BufferOffset; long size = args.MappingSize; - if (size == 0) size = (uint)map.Size; + if (size == 0) + { + size = (uint)map.Size; + } int result = NvResult.Success; diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvGpuGpu/NvGpuGpuIoctl.cs b/Ryujinx.HLE/HOS/Services/Nv/NvGpuGpu/NvGpuGpuIoctl.cs index bea2ae3c05..11f27ab73a 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvGpuGpu/NvGpuGpuIoctl.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvGpuGpu/NvGpuGpuIoctl.cs @@ -142,7 +142,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvGpuGpu NvGpuGpuGetTpcMasks args = AMemoryHelper.Read(context.Memory, inputPosition); - if (args.MaskBufferSize != 0) args.TpcMask = 3; + if (args.MaskBufferSize != 0) + { + args.TpcMask = 3; + } AMemoryHelper.Write(context.Memory, outputPosition, args); diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostCtrlIoctl.cs b/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostCtrlIoctl.cs index 4fa8354eb9..096c4bdbc8 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostCtrlIoctl.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostCtrlIoctl.cs @@ -17,7 +17,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl { _userCtxs = new ConcurrentDictionary(); - if (Set.NxSettings.Settings.TryGetValue("nv!rmos_set_production_mode", out object productionModeSetting)) _isProductionMode = (string)productionModeSetting != "0"; // Default value is "" + if (Set.NxSettings.Settings.TryGetValue("nv!rmos_set_production_mode", out object productionModeSetting)) + { + _isProductionMode = (string)productionModeSetting != "0"; // Default value is "" + } } public static int ProcessIoctl(ServiceCtx context, int cmd) @@ -49,7 +52,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl int id = context.Memory.ReadInt32(inputPosition); - if ((uint)id >= NvHostSyncpt.SyncptsCount) return NvResult.InvalidInput; + if ((uint)id >= NvHostSyncpt.SyncptsCount) + { + return NvResult.InvalidInput; + } GetUserCtx(context).Syncpt.Increment(id); @@ -88,17 +94,27 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl if (nvSetting is string stringValue) { if (stringValue.Length > 0x100) + { Logger.PrintError(LogClass.ServiceNv, $"{domain}!{name} String value size is too big!"); + } else + { settingBuffer = Encoding.ASCII.GetBytes(stringValue + "\0"); + } } if (nvSetting is int intValue) + { settingBuffer = BitConverter.GetBytes(intValue); + } else if (nvSetting is bool boolValue) + { settingBuffer[0] = boolValue ? (byte)1 : (byte)0; + } else + { throw new NotImplementedException(nvSetting.GetType().Name); + } context.Memory.WriteBytes(outputPosition + 0x82, settingBuffer); @@ -140,12 +156,19 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl NvHostCtrlSyncptRead args = AMemoryHelper.Read(context.Memory, inputPosition); - if ((uint)args.Id >= NvHostSyncpt.SyncptsCount) return NvResult.InvalidInput; + if ((uint)args.Id >= NvHostSyncpt.SyncptsCount) + { + return NvResult.InvalidInput; + } if (max) + { args.Value = GetUserCtx(context).Syncpt.GetMax(args.Id); + } else + { args.Value = GetUserCtx(context).Syncpt.GetMin(args.Id); + } AMemoryHelper.Write(context.Memory, outputPosition, args); @@ -161,7 +184,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl NvHostSyncpt syncpt = GetUserCtx(context).Syncpt; - if ((uint)args.Id >= NvHostSyncpt.SyncptsCount) return NvResult.InvalidInput; + if ((uint)args.Id >= NvHostSyncpt.SyncptsCount) + { + return NvResult.InvalidInput; + } int result; @@ -185,7 +211,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl //in this case we just use the maximum timeout possible. int timeout = args.Timeout; - if (timeout < -1) timeout = int.MaxValue; + if (timeout < -1) + { + timeout = int.MaxValue; + } if (timeout == -1) { @@ -206,7 +235,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl Logger.PrintDebug(LogClass.ServiceNv, "Resuming..."); } - if (extended) context.Memory.WriteInt32(outputPosition + 0xc, syncpt.GetMin(args.Id)); + if (extended) + { + context.Memory.WriteInt32(outputPosition + 0xc, syncpt.GetMin(args.Id)); + } return result; } @@ -218,7 +250,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl NvHostCtrlSyncptWaitEx args = AMemoryHelper.Read(context.Memory, inputPosition); - if ((uint)args.Id >= NvHostSyncpt.SyncptsCount) return NvResult.InvalidInput; + if ((uint)args.Id >= NvHostSyncpt.SyncptsCount) + { + return NvResult.InvalidInput; + } void WriteArgs() { @@ -236,7 +271,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl return NvResult.Success; } - if (!async) args.Value = 0; + if (!async) + { + args.Value = 0; + } if (args.Timeout == 0) { @@ -253,7 +291,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl { eventIndex = args.Value; - if ((uint)eventIndex >= NvHostCtrlUserCtx.EventsCount) return NvResult.InvalidInput; + if ((uint)eventIndex >= NvHostCtrlUserCtx.EventsCount) + { + return NvResult.InvalidInput; + } Event = GetUserCtx(context).Events[eventIndex]; } @@ -272,9 +313,13 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl Event.State = NvHostEventState.Waiting; if (!async) + { args.Value = ((args.Id & 0xfff) << 16) | 0x10000000; + } else + { args.Value = args.Id << 4; + } args.Value |= eventIndex; @@ -313,7 +358,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl { eventIndex = index; - if (Event.Id == id) return Event; + if (Event.Id == id) + { + return Event; + } } } else if (nullIndex == NvHostCtrlUserCtx.EventsCount) @@ -329,7 +377,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl return events[nullIndex] = new NvHostEvent(); } - if (eventIndex < NvHostCtrlUserCtx.EventsCount) return events[eventIndex]; + if (eventIndex < NvHostCtrlUserCtx.EventsCount) + { + return events[eventIndex]; + } return null; } diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostSyncPt.cs b/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostSyncPt.cs index 6b7cc44e0e..01a7643163 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostSyncPt.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvHostCtrl/NvHostSyncPt.cs @@ -36,7 +36,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl public int Increment(int id) { - if (((_eventMask >> id) & 1) != 0) Interlocked.Increment(ref _counterMax[id]); + if (((_eventMask >> id) & 1) != 0) + { + Interlocked.Increment(ref _counterMax[id]); + } return IncrementMin(id); } @@ -57,7 +60,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl public void AddWaiter(int threshold, EventWaitHandle waitEvent) { - if (!_waiters.TryAdd(waitEvent, threshold)) throw new InvalidOperationException(); + if (!_waiters.TryAdd(waitEvent, threshold)) + { + throw new InvalidOperationException(); + } } public bool RemoveWaiter(EventWaitHandle waitEvent) @@ -68,12 +74,14 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl private void WakeUpWaiters(int id, int newValue) { foreach (KeyValuePair kv in _waiters) + { if (MinCompare(id, newValue, _counterMax[id], kv.Value)) { kv.Key.Set(); _waiters.TryRemove(kv.Key, out _); } + } } public bool MinCompare(int id, int threshold) @@ -87,9 +95,13 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvHostCtrl int maxDiff = max - threshold; if (((_eventMask >> id) & 1) != 0) + { return minDiff >= 0; + } else + { return (uint)maxDiff >= (uint)minDiff; + } } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Nv/NvMap/NvMapIoctl.cs b/Ryujinx.HLE/HOS/Services/Nv/NvMap/NvMapIoctl.cs index 3c6538cd1f..9637cc434a 100644 --- a/Ryujinx.HLE/HOS/Services/Nv/NvMap/NvMapIoctl.cs +++ b/Ryujinx.HLE/HOS/Services/Nv/NvMap/NvMapIoctl.cs @@ -107,7 +107,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvMap return NvResult.InvalidInput; } - if ((uint)args.Align < NvGpuVmm.PageSize) args.Align = NvGpuVmm.PageSize; + if ((uint)args.Align < NvGpuVmm.PageSize) + { + args.Align = NvGpuVmm.PageSize; + } int result = NvResult.Success; @@ -123,7 +126,12 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvMap long address = args.Address; if (address == 0) - if (!context.Device.Memory.Allocator.TryAllocate((uint)size, out address)) result = NvResult.OutOfMemory; + { + if (!context.Device.Memory.Allocator.TryAllocate((uint)size, out address)) + { + result = NvResult.OutOfMemory; + } + } if (result == NvResult.Success) { @@ -248,7 +256,10 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvMap private static bool DeleteNvMap(ServiceCtx context, int handle) { - if (_maps.TryGetValue(context.Process, out IdDictionary dict)) return dict.Delete(handle) != null; + if (_maps.TryGetValue(context.Process, out IdDictionary dict)) + { + return dict.Delete(handle) != null; + } return false; } @@ -262,14 +273,20 @@ namespace Ryujinx.HLE.HOS.Services.Nv.NvMap public static NvMapHandle GetNvMapWithFb(ServiceCtx context, int handle) { - if (_maps.TryGetValue(context.Process, out IdDictionary dict)) return dict.GetData(handle); + if (_maps.TryGetValue(context.Process, out IdDictionary dict)) + { + return dict.GetData(handle); + } return null; } public static NvMapHandle GetNvMap(ServiceCtx context, int handle) { - if (handle != 0 && _maps.TryGetValue(context.Process, out IdDictionary dict)) return dict.GetData(handle); + if (handle != 0 && _maps.TryGetValue(context.Process, out IdDictionary dict)) + { + return dict.GetData(handle); + } return null; } diff --git a/Ryujinx.HLE/HOS/Services/Pctl/IParentalControlService.cs b/Ryujinx.HLE/HOS/Services/Pctl/IParentalControlService.cs index bc9e6012bc..123b9bfddc 100644 --- a/Ryujinx.HLE/HOS/Services/Pctl/IParentalControlService.cs +++ b/Ryujinx.HLE/HOS/Services/Pctl/IParentalControlService.cs @@ -27,9 +27,13 @@ namespace Ryujinx.HLE.HOS.Services.Pctl public long Initialize(ServiceCtx context) { if (_needInitialize && !_initialized) + { _initialized = true; + } else + { Logger.PrintWarning(LogClass.ServicePctl, "Service is already initialized!"); + } return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Pl/ISharedFontManager.cs b/Ryujinx.HLE/HOS/Services/Pl/ISharedFontManager.cs index 9c5ed9025e..427ca24ba4 100644 --- a/Ryujinx.HLE/HOS/Services/Pl/ISharedFontManager.cs +++ b/Ryujinx.HLE/HOS/Services/Pl/ISharedFontManager.cs @@ -67,7 +67,10 @@ namespace Ryujinx.HLE.HOS.Services.Pl { context.Device.System.Font.EnsureInitialized(); - if (context.Process.HandleTable.GenerateHandle(context.Device.System.FontSharedMem, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(context.Device.System.FontSharedMem, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); @@ -83,7 +86,10 @@ namespace Ryujinx.HLE.HOS.Services.Pl { int offset = (int)type * 4; - if (!AddFontToOrderOfPriorityList(context, (SharedFontType)type, offset)) break; + if (!AddFontToOrderOfPriorityList(context, (SharedFontType)type, offset)) + { + break; + } loadedCount++; } @@ -108,7 +114,9 @@ namespace Ryujinx.HLE.HOS.Services.Pl if ((uint)offset + 4 > (uint)typesSize || (uint)offset + 4 > (uint)offsetsSize || (uint)offset + 4 > (uint)fontSizeBufferSize) + { return false; + } context.Memory.WriteInt32(typesPosition + offset, (int)fontType); diff --git a/Ryujinx.HLE/HOS/Services/Psm/IPsmSession.cs b/Ryujinx.HLE/HOS/Services/Psm/IPsmSession.cs index 284548a67d..6dc40bdfbe 100644 --- a/Ryujinx.HLE/HOS/Services/Psm/IPsmSession.cs +++ b/Ryujinx.HLE/HOS/Services/Psm/IPsmSession.cs @@ -36,7 +36,10 @@ namespace Ryujinx.HLE.HOS.Services.Psm { KernelResult resultCode = context.Process.HandleTable.GenerateHandle(_stateChangeEvent, out int stateChangeEventHandle); - if (resultCode != KernelResult.Success) return (long)resultCode; + if (resultCode != KernelResult.Success) + { + return (long)resultCode; + } } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(_stateChangeEventHandle); diff --git a/Ryujinx.HLE/HOS/Services/Set/ISettingsServer.cs b/Ryujinx.HLE/HOS/Services/Set/ISettingsServer.cs index 8cad27472f..76d1773213 100644 --- a/Ryujinx.HLE/HOS/Services/Set/ISettingsServer.cs +++ b/Ryujinx.HLE/HOS/Services/Set/ISettingsServer.cs @@ -59,7 +59,10 @@ namespace Ryujinx.HLE.HOS.Services.Set { int count = (int)(size / 8); - if (count > SystemStateMgr.LanguageCodes.Length) count = SystemStateMgr.LanguageCodes.Length; + if (count > SystemStateMgr.LanguageCodes.Length) + { + count = SystemStateMgr.LanguageCodes.Length; + } for (int index = 0; index < count; index++) { diff --git a/Ryujinx.HLE/HOS/Services/Set/ISystemSettingsServer.cs b/Ryujinx.HLE/HOS/Services/Set/ISystemSettingsServer.cs index bcde831623..459303ad59 100644 --- a/Ryujinx.HLE/HOS/Services/Set/ISystemSettingsServer.cs +++ b/Ryujinx.HLE/HOS/Services/Set/ISystemSettingsServer.cs @@ -115,17 +115,27 @@ namespace Ryujinx.HLE.HOS.Services.Set if (nxSetting is string stringValue) { if (stringValue.Length + 1 > replySize) + { Logger.PrintError(LogClass.ServiceSet, $"{askedSetting} String value size is too big!"); + } else + { settingBuffer = Encoding.ASCII.GetBytes(stringValue + "\0"); + } } if (nxSetting is int intValue) + { settingBuffer = BitConverter.GetBytes(intValue); + } else if (nxSetting is bool boolValue) + { settingBuffer[0] = boolValue ? (byte)1 : (byte)0; + } else + { throw new NotImplementedException(nxSetting.GetType().Name); + } context.Memory.WriteBytes(replyPos, settingBuffer); diff --git a/Ryujinx.HLE/HOS/Services/Sfdnsres/IResolver.cs b/Ryujinx.HLE/HOS/Services/Sfdnsres/IResolver.cs index 86a89c3aea..90ad357065 100644 --- a/Ryujinx.HLE/HOS/Services/Sfdnsres/IResolver.cs +++ b/Ryujinx.HLE/HOS/Services/Sfdnsres/IResolver.cs @@ -68,18 +68,23 @@ namespace Ryujinx.HLE.HOS.Services.Sfdnsres bufferPosition += 4; if (addresses != null) + { foreach (IPAddress ip in addresses) { context.Memory.WriteInt32(bufferPosition, IPAddress.HostToNetworkOrder(BitConverter.ToInt32(ip.GetAddressBytes(), 0))); bufferPosition += 4; } + } return bufferPosition - originalBufferPosition; } private string GetGaiStringErrorFromErrorCode(GaiError errorCode) { - if (errorCode > GaiError.Max) errorCode = GaiError.Max; + if (errorCode > GaiError.Max) + { + errorCode = GaiError.Max; + } switch (errorCode) { @@ -120,7 +125,10 @@ namespace Ryujinx.HLE.HOS.Services.Sfdnsres private string GetHostStringErrorFromErrorCode(NetDBError errorCode) { - if (errorCode <= NetDBError.Internal) return "Resolver internal error"; + if (errorCode <= NetDBError.Internal) + { + return "Resolver internal error"; + } switch (errorCode) { @@ -143,8 +151,13 @@ namespace Ryujinx.HLE.HOS.Services.Sfdnsres { List result = new List(); foreach (IPAddress ip in hostEntry.AddressList) + { if (ip.AddressFamily == AddressFamily.InterNetwork) + { result.Add(ip); + } + } + return result; } @@ -190,6 +203,7 @@ namespace Ryujinx.HLE.HOS.Services.Sfdnsres long serializedSize = 0; if (name.Length <= 255) + { try { hostEntry = Dns.GetHostEntry(name); @@ -220,8 +234,11 @@ namespace Ryujinx.HLE.HOS.Services.Sfdnsres errno = GaiError.Again; } } + } else + { netDbErrorCode = NetDBError.HostNotFound; + } if (hostEntry != null) { @@ -265,6 +282,7 @@ namespace Ryujinx.HLE.HOS.Services.Sfdnsres long serializedSize = 0; if (rawIp.Length == 4) + { try { IPAddress address = new IPAddress(rawIp); @@ -296,8 +314,11 @@ namespace Ryujinx.HLE.HOS.Services.Sfdnsres errno = GaiError.Again; } } + } else + { netDbErrorCode = NetDBError.NoAddress; + } if (hostEntry != null) { diff --git a/Ryujinx.HLE/HOS/Services/Sm/IUserInterface.cs b/Ryujinx.HLE/HOS/Services/Sm/IUserInterface.cs index 03327189c2..2b612e830f 100644 --- a/Ryujinx.HLE/HOS/Services/Sm/IUserInterface.cs +++ b/Ryujinx.HLE/HOS/Services/Sm/IUserInterface.cs @@ -47,14 +47,23 @@ namespace Ryujinx.HLE.HOS.Services.Sm { byte chr = context.RequestData.ReadByte(); - if (chr >= 0x20 && chr < 0x7f) name += (char)chr; + if (chr >= 0x20 && chr < 0x7f) + { + name += (char)chr; + } } - if (name == string.Empty) return 0; + if (name == string.Empty) + { + return 0; + } KSession session = new KSession(ServiceFactory.MakeService(context.Device.System, name), name); - if (context.Process.HandleTable.GenerateHandle(session, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(session, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeMove(handle); diff --git a/Ryujinx.HLE/HOS/Services/Spl/IRandomInterface.cs b/Ryujinx.HLE/HOS/Services/Spl/IRandomInterface.cs index 38244889cb..843fff5ad2 100644 --- a/Ryujinx.HLE/HOS/Services/Spl/IRandomInterface.cs +++ b/Ryujinx.HLE/HOS/Services/Spl/IRandomInterface.cs @@ -41,7 +41,10 @@ namespace Ryujinx.HLE.HOS.Services.Spl protected virtual void Dispose(bool disposing) { - if (disposing) _rng.Dispose(); + if (disposing) + { + _rng.Dispose(); + } } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Time/ISteadyClock.cs b/Ryujinx.HLE/HOS/Services/Time/ISteadyClock.cs index 63b447acfb..b376c1b296 100644 --- a/Ryujinx.HLE/HOS/Services/Time/ISteadyClock.cs +++ b/Ryujinx.HLE/HOS/Services/Time/ISteadyClock.cs @@ -28,7 +28,10 @@ namespace Ryujinx.HLE.HOS.Services.Time { context.ResponseData.Write((long)(System.Diagnostics.Process.GetCurrentProcess().StartTime - DateTime.Now).TotalSeconds); - for (int i = 0; i < 0x10; i++) context.ResponseData.Write((byte)0); + for (int i = 0; i < 0x10; i++) + { + context.ResponseData.Write((byte)0); + } return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Time/ISystemClock.cs b/Ryujinx.HLE/HOS/Services/Time/ISystemClock.cs index a9462eadfd..bd1d03abdf 100644 --- a/Ryujinx.HLE/HOS/Services/Time/ISystemClock.cs +++ b/Ryujinx.HLE/HOS/Services/Time/ISystemClock.cs @@ -39,7 +39,9 @@ namespace Ryujinx.HLE.HOS.Services.Time if (clockType == SystemClockType.User || clockType == SystemClockType.Network) + { _systemClockContextEpoch = _systemClockContextEpoch.ToUniversalTime(); + } _systemClockTimePoint = (long)(_systemClockContextEpoch - _epoch).TotalSeconds; } @@ -50,7 +52,9 @@ namespace Ryujinx.HLE.HOS.Services.Time if (_clockType == SystemClockType.User || _clockType == SystemClockType.Network) + { currentTime = currentTime.ToUniversalTime(); + } context.ResponseData.Write((long)(currentTime - _epoch).TotalSeconds + _timeOffset); @@ -63,7 +67,9 @@ namespace Ryujinx.HLE.HOS.Services.Time if (_clockType == SystemClockType.User || _clockType == SystemClockType.Network) + { currentTime = currentTime.ToUniversalTime(); + } _timeOffset = context.RequestData.ReadInt64() - (long)(currentTime - _epoch).TotalSeconds; @@ -78,7 +84,10 @@ namespace Ryujinx.HLE.HOS.Services.Time context.ResponseData.Write(_systemClockTimePoint); // This seems to be some kind of identifier? - for (int i = 0; i < 0x10; i++) context.ResponseData.Write(_systemClockContextEnding[i]); + for (int i = 0; i < 0x10; i++) + { + context.ResponseData.Write(_systemClockContextEnding[i]); + } return 0; } diff --git a/Ryujinx.HLE/HOS/Services/Time/ITimeZoneService.cs b/Ryujinx.HLE/HOS/Services/Time/ITimeZoneService.cs index e61f7d2aaf..1f29f3d7ef 100644 --- a/Ryujinx.HLE/HOS/Services/Time/ITimeZoneService.cs +++ b/Ryujinx.HLE/HOS/Services/Time/ITimeZoneService.cs @@ -42,7 +42,10 @@ namespace Ryujinx.HLE.HOS.Services.Time int padding = 0x24 - tzName.Length; - for (int index = 0; index < padding; index++) context.ResponseData.Write((byte)0); + for (int index = 0; index < padding; index++) + { + context.ResponseData.Write((byte)0); + } return 0; } @@ -89,7 +92,10 @@ namespace Ryujinx.HLE.HOS.Services.Time int padding = 0x24 - tzData.Length; - for (int index = 0; index < padding; index++) context.ResponseData.Write((byte)0); + for (int index = 0; index < padding; index++) + { + context.ResponseData.Write((byte)0); + } offset += 0x24; } @@ -102,7 +108,10 @@ namespace Ryujinx.HLE.HOS.Services.Time long bufferPosition = context.Request.ReceiveBuff[0].Position; long bufferSize = context.Request.ReceiveBuff[0].Size; - if (bufferSize != 0x4000) Logger.PrintWarning(LogClass.ServiceTime, $"TimeZoneRule buffer size is 0x{bufferSize:x} (expected 0x4000)"); + if (bufferSize != 0x4000) + { + Logger.PrintWarning(LogClass.ServiceTime, $"TimeZoneRule buffer size is 0x{bufferSize:x} (expected 0x4000)"); + } long resultCode = 0; @@ -159,7 +168,10 @@ namespace Ryujinx.HLE.HOS.Services.Time long bufferPosition = context.Request.SendBuff[0].Position; long bufferSize = context.Request.SendBuff[0].Size; - if (bufferSize != 0x4000) Logger.PrintWarning(LogClass.ServiceTime, $"TimeZoneRule buffer size is 0x{bufferSize:x} (expected 0x4000)"); + if (bufferSize != 0x4000) + { + Logger.PrintWarning(LogClass.ServiceTime, $"TimeZoneRule buffer size is 0x{bufferSize:x} (expected 0x4000)"); + } // TODO: Reverse the TZif2 conversion in PCV to make this match with real hardware. byte[] tzData = context.Memory.ReadBytes(bufferPosition, 0x24); @@ -206,7 +218,10 @@ namespace Ryujinx.HLE.HOS.Services.Time DateTime calendarTime = new DateTime(year, month, day, hour, minute, second); - if (bufferSize != 0x4000) Logger.PrintWarning(LogClass.ServiceTime, $"TimeZoneRule buffer size is 0x{bufferSize:x} (expected 0x4000)"); + if (bufferSize != 0x4000) + { + Logger.PrintWarning(LogClass.ServiceTime, $"TimeZoneRule buffer size is 0x{bufferSize:x} (expected 0x4000)"); + } // TODO: Reverse the TZif2 conversion in PCV to make this match with real hardware. byte[] tzData = context.Memory.ReadBytes(bufferPosition, 0x24); diff --git a/Ryujinx.HLE/HOS/Services/Vi/IApplicationDisplayService.cs b/Ryujinx.HLE/HOS/Services/Vi/IApplicationDisplayService.cs index 90238e1e83..776d782ba2 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/IApplicationDisplayService.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/IApplicationDisplayService.cs @@ -180,7 +180,10 @@ namespace Ryujinx.HLE.HOS.Services.Vi { string name = GetDisplayName(context); - if (context.Process.HandleTable.GenerateHandle(context.Device.System.VsyncEvent.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(context.Device.System.VsyncEvent.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeCopy(handle); @@ -227,7 +230,10 @@ namespace Ryujinx.HLE.HOS.Services.Vi { byte chr = context.RequestData.ReadByte(); - if (chr >= 0x20 && chr < 0x7f) name += (char)chr; + if (chr >= 0x20 && chr < 0x7f) + { + name += (char)chr; + } } return name; diff --git a/Ryujinx.HLE/HOS/Services/Vi/IHOSBinderDriver.cs b/Ryujinx.HLE/HOS/Services/Vi/IHOSBinderDriver.cs index a0cbfab70a..67de201412 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/IHOSBinderDriver.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/IHOSBinderDriver.cs @@ -77,7 +77,10 @@ namespace Ryujinx.HLE.HOS.Services.Vi int id = context.RequestData.ReadInt32(); uint unk = context.RequestData.ReadUInt32(); - if (context.Process.HandleTable.GenerateHandle(_binderEvent.ReadableEvent, out int handle) != KernelResult.Success) throw new InvalidOperationException("Out of handles!"); + if (context.Process.HandleTable.GenerateHandle(_binderEvent.ReadableEvent, out int handle) != KernelResult.Success) + { + throw new InvalidOperationException("Out of handles!"); + } context.Response.HandleDesc = IpcHandleDesc.MakeMove(handle); @@ -91,7 +94,10 @@ namespace Ryujinx.HLE.HOS.Services.Vi protected virtual void Dispose(bool disposing) { - if (disposing) _flinger.Dispose(); + if (disposing) + { + _flinger.Dispose(); + } } } } \ No newline at end of file diff --git a/Ryujinx.HLE/HOS/Services/Vi/NvFlinger.cs b/Ryujinx.HLE/HOS/Services/Vi/NvFlinger.cs index e30c309bcb..12be15529e 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/NvFlinger.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/NvFlinger.cs @@ -105,7 +105,10 @@ namespace Ryujinx.HLE.HOS.Services.Android long remainder = ms.Position & 0xf; - if (remainder != 0) ms.Seek(0x10 - remainder, SeekOrigin.Current); + if (remainder != 0) + { + ms.Seek(0x10 - remainder, SeekOrigin.Current); + } ms.Seek(0x50, SeekOrigin.Begin); @@ -197,7 +200,10 @@ namespace Ryujinx.HLE.HOS.Services.Android SendFrameBuffer(context, slot); - if (context.Device.EnableDeviceVsync) context.Device.VsyncEvent.WaitOne(); + if (context.Device.EnableDeviceVsync) + { + context.Device.VsyncEvent.WaitOne(); + } return MakeReplyParcel(context, 1280, 720, 0, 0, 0); } @@ -258,7 +264,10 @@ namespace Ryujinx.HLE.HOS.Services.Android { BinaryWriter writer = new BinaryWriter(ms); - foreach (int Int in ints) writer.Write(Int); + foreach (int Int in ints) + { + writer.Write(Int); + } return MakeReplyParcel(context, ms.ToArray()); } @@ -307,11 +316,13 @@ namespace Ryujinx.HLE.HOS.Services.Android _renderer.QueueAction(() => { if (!_renderer.Texture.TryGetImage(fbAddr, out GalImage image)) + { image = new GalImage( fbWidth, fbHeight, 1, 16, GalMemoryLayout.BlockLinear, GalImageFormat.Rgba8 | GalImageFormat.Unorm); + } context.Device.Gpu.ResourceManager.ClearPbCache(); context.Device.Gpu.ResourceManager.SendTexture(vmm, fbAddr, image); @@ -338,9 +349,15 @@ namespace Ryujinx.HLE.HOS.Services.Android do { - if ((slot = GetFreeSlot(width, height)) != -1) break; + if ((slot = GetFreeSlot(width, height)) != -1) + { + break; + } - if (_disposed) break; + if (_disposed) + { + break; + } _waitBufferFree.WaitOne(); } @@ -355,7 +372,10 @@ namespace Ryujinx.HLE.HOS.Services.Android { for (int slot = 0; slot < _bufferQueue.Length; slot++) { - if (_bufferQueue[slot].State != BufferState.Free) continue; + if (_bufferQueue[slot].State != BufferState.Free) + { + continue; + } GbpBuffer data = _bufferQueue[slot].Data; diff --git a/Ryujinx.HLE/HOS/Services/Vi/Parcel.cs b/Ryujinx.HLE/HOS/Services/Vi/Parcel.cs index e2df18acae..b432683252 100644 --- a/Ryujinx.HLE/HOS/Services/Vi/Parcel.cs +++ b/Ryujinx.HLE/HOS/Services/Vi/Parcel.cs @@ -7,7 +7,10 @@ namespace Ryujinx.HLE.HOS.Services.Android { public static byte[] GetParcelData(byte[] parcel) { - if (parcel == null) throw new ArgumentNullException(nameof(parcel)); + if (parcel == null) + { + throw new ArgumentNullException(nameof(parcel)); + } using (MemoryStream ms = new MemoryStream(parcel)) { @@ -26,9 +29,15 @@ namespace Ryujinx.HLE.HOS.Services.Android public static byte[] MakeParcel(byte[] data, byte[] objs) { - if (data == null) throw new ArgumentNullException(nameof(data)); + if (data == null) + { + throw new ArgumentNullException(nameof(data)); + } - if (objs == null) throw new ArgumentNullException(nameof(objs)); + if (objs == null) + { + throw new ArgumentNullException(nameof(objs)); + } using (MemoryStream ms = new MemoryStream()) { diff --git a/Ryujinx.HLE/HOS/SystemState/AppletStateMgr.cs b/Ryujinx.HLE/HOS/SystemState/AppletStateMgr.cs index 44c0393bd0..85e594d2b2 100644 --- a/Ryujinx.HLE/HOS/SystemState/AppletStateMgr.cs +++ b/Ryujinx.HLE/HOS/SystemState/AppletStateMgr.cs @@ -37,7 +37,10 @@ namespace Ryujinx.HLE.HOS.SystemState public bool TryDequeueMessage(out MessageInfo message) { - if (_messages.Count < 2) MessageEvent.ReadableEvent.Clear(); + if (_messages.Count < 2) + { + MessageEvent.ReadableEvent.Clear(); + } return _messages.TryDequeue(out message); } diff --git a/Ryujinx.HLE/HOS/SystemState/SystemStateMgr.cs b/Ryujinx.HLE/HOS/SystemState/SystemStateMgr.cs index daa8299ce0..a3436d8a68 100644 --- a/Ryujinx.HLE/HOS/SystemState/SystemStateMgr.cs +++ b/Ryujinx.HLE/HOS/SystemState/SystemStateMgr.cs @@ -96,12 +96,18 @@ namespace Ryujinx.HLE.HOS.SystemState public void OpenUser(UInt128 uuid) { - if (_profiles.TryGetValue(uuid.ToString(), out UserProfile profile)) (LastOpenUser = profile).AccountState = OpenCloseState.Open; + if (_profiles.TryGetValue(uuid.ToString(), out UserProfile profile)) + { + (LastOpenUser = profile).AccountState = OpenCloseState.Open; + } } public void CloseUser(UInt128 uuid) { - if (_profiles.TryGetValue(uuid.ToString(), out UserProfile profile)) profile.AccountState = OpenCloseState.Closed; + if (_profiles.TryGetValue(uuid.ToString(), out UserProfile profile)) + { + profile.AccountState = OpenCloseState.Closed; + } } public int GetUserCount() @@ -126,12 +132,18 @@ namespace Ryujinx.HLE.HOS.SystemState internal static long GetLanguageCode(int index) { - if ((uint)index >= LanguageCodes.Length) throw new ArgumentOutOfRangeException(nameof(index)); + if ((uint)index >= LanguageCodes.Length) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } long code = 0; int shift = 0; - foreach (char chr in LanguageCodes[index]) code |= (long)(byte)chr << (shift++ * 8); + foreach (char chr in LanguageCodes[index]) + { + code |= (long)(byte)chr << (shift++ * 8); + } return code; } diff --git a/Ryujinx.HLE/Loaders/Compression/Lz4.cs b/Ryujinx.HLE/Loaders/Compression/Lz4.cs index 19c96b57d3..04c7085663 100644 --- a/Ryujinx.HLE/Loaders/Compression/Lz4.cs +++ b/Ryujinx.HLE/Loaders/Compression/Lz4.cs @@ -16,11 +16,13 @@ namespace Ryujinx.HLE.Loaders.Compression byte sum; if (length == 0xf) + { do { length += sum = cmp[cmpPos++]; } while (sum == 0xff); + } return length; } @@ -40,7 +42,10 @@ namespace Ryujinx.HLE.Loaders.Compression cmpPos += litCount; decPos += litCount; - if (cmpPos >= cmp.Length) break; + if (cmpPos >= cmp.Length) + { + break; + } //Copy compressed chunck int back = (cmp[cmpPos++] << 0) | @@ -58,7 +63,10 @@ namespace Ryujinx.HLE.Loaders.Compression } else { - while (encCount-- > 0) dec[decPos++] = dec[encPos++]; + while (encCount-- > 0) + { + dec[decPos++] = dec[encPos++]; + } } } while (cmpPos < cmp.Length && diff --git a/Ryujinx.HLE/Loaders/Executable.cs b/Ryujinx.HLE/Loaders/Executable.cs index 945a026476..76b7c66d01 100644 --- a/Ryujinx.HLE/Loaders/Executable.cs +++ b/Ryujinx.HLE/Loaders/Executable.cs @@ -34,7 +34,10 @@ namespace Ryujinx.HLE.Loaders FilePath = exe.FilePath; - if (FilePath != null) Name = Path.GetFileNameWithoutExtension(FilePath.Replace(Homebrew.TemporaryNroSuffix, "")); + if (FilePath != null) + { + Name = Path.GetFileNameWithoutExtension(FilePath.Replace(Homebrew.TemporaryNroSuffix, "")); + } _memory = memory; _memoryManager = memoryManager; @@ -69,7 +72,10 @@ namespace Ryujinx.HLE.Loaders { long result = memoryManager.MapProcessCodeMemory(textPosition, exe.SourceAddress, textSize + roSize + dataSize); - if (result != 0) throw new InvalidOperationException(); + if (result != 0) + { + throw new InvalidOperationException(); + } memoryManager.SetProcessMemoryPermission(roPosition, roSize, MemoryPermission.Read); memoryManager.SetProcessMemoryPermission(dataPosition, dataSize, MemoryPermission.ReadAndWrite); @@ -78,13 +84,19 @@ namespace Ryujinx.HLE.Loaders { result = memoryManager.MapProcessCodeMemory(dataPosition + dataSize, exe.BssAddress, bssSize); - if (result != 0) throw new InvalidOperationException(); + if (result != 0) + { + throw new InvalidOperationException(); + } memoryManager.SetProcessMemoryPermission(dataPosition + dataSize, bssSize, MemoryPermission.ReadAndWrite); } } - if (exe.Mod0Offset == 0) return; + if (exe.Mod0Offset == 0) + { + return; + } long mod0Offset = imageBase + exe.Mod0Offset; @@ -105,7 +117,10 @@ namespace Ryujinx.HLE.Loaders ElfDynTag tag = (ElfDynTag)tagVal; - if (tag == ElfDynTag.DtNull) break; + if (tag == ElfDynTag.DtNull) + { + break; + } _dynamic.Add(new ElfDyn(tag, value)); } @@ -166,7 +181,10 @@ namespace Ryujinx.HLE.Loaders string name = string.Empty; - for (int chr; (chr = _memory.ReadByte(strTblAddr + nameIndex++)) != 0;) name += (char)chr; + for (int chr; (chr = _memory.ReadByte(strTblAddr + nameIndex++)) != 0;) + { + name += (char)chr; + } return new ElfSym(name, info, other, shIdx, value, size); } @@ -174,7 +192,12 @@ namespace Ryujinx.HLE.Loaders private long GetFirstValue(ElfDynTag tag) { foreach (ElfDyn entry in _dynamic) - if (entry.Tag == tag) return entry.Value; + { + if (entry.Tag == tag) + { + return entry.Value; + } + } return 0; } diff --git a/Ryujinx.HLE/Loaders/Executables/Nso.cs b/Ryujinx.HLE/Loaders/Executables/Nso.cs index a8bbf6ffb1..d07779a993 100644 --- a/Ryujinx.HLE/Loaders/Executables/Nso.cs +++ b/Ryujinx.HLE/Loaders/Executables/Nso.cs @@ -89,21 +89,30 @@ namespace Ryujinx.HLE.Loaders.Executables Text = reader.ReadBytes(textSize); - if (flags.HasFlag(NsoFlags.IsTextCompressed) || true) Text = Lz4.Decompress(Text, textDecSize); + if (flags.HasFlag(NsoFlags.IsTextCompressed) || true) + { + Text = Lz4.Decompress(Text, textDecSize); + } //Read-only data segment input.Seek(roOffset, SeekOrigin.Begin); Ro = reader.ReadBytes(roSize); - if (flags.HasFlag(NsoFlags.IsRoCompressed) || true) Ro = Lz4.Decompress(Ro, roDecSize); + if (flags.HasFlag(NsoFlags.IsRoCompressed) || true) + { + Ro = Lz4.Decompress(Ro, roDecSize); + } //Data segment input.Seek(dataOffset, SeekOrigin.Begin); Data = reader.ReadBytes(dataSize); - if (flags.HasFlag(NsoFlags.IsDataCompressed) || true) Data = Lz4.Decompress(Data, dataDecSize); + if (flags.HasFlag(NsoFlags.IsDataCompressed) || true) + { + Data = Lz4.Decompress(Data, dataDecSize); + } using (MemoryStream textMs = new MemoryStream(Text)) { diff --git a/Ryujinx.HLE/Loaders/Npdm/ACI0.cs b/Ryujinx.HLE/Loaders/Npdm/ACI0.cs index eddf93e879..7bb8003d64 100644 --- a/Ryujinx.HLE/Loaders/Npdm/ACI0.cs +++ b/Ryujinx.HLE/Loaders/Npdm/ACI0.cs @@ -21,7 +21,10 @@ namespace Ryujinx.HLE.Loaders.Npdm BinaryReader reader = new BinaryReader(stream); - if (reader.ReadInt32() != Aci0Magic) throw new InvalidNpdmException("ACI0 Stream doesn't contain ACI0 section!"); + if (reader.ReadInt32() != Aci0Magic) + { + throw new InvalidNpdmException("ACI0 Stream doesn't contain ACI0 section!"); + } stream.Seek(0xc, SeekOrigin.Current); diff --git a/Ryujinx.HLE/Loaders/Npdm/ACID.cs b/Ryujinx.HLE/Loaders/Npdm/ACID.cs index 5b093c60b8..ffe9a225fe 100644 --- a/Ryujinx.HLE/Loaders/Npdm/ACID.cs +++ b/Ryujinx.HLE/Loaders/Npdm/ACID.cs @@ -28,7 +28,10 @@ namespace Ryujinx.HLE.Loaders.Npdm Rsa2048Signature = reader.ReadBytes(0x100); Rsa2048Modulus = reader.ReadBytes(0x100); - if (reader.ReadInt32() != AcidMagic) throw new InvalidNpdmException("ACID Stream doesn't contain ACID section!"); + if (reader.ReadInt32() != AcidMagic) + { + throw new InvalidNpdmException("ACID Stream doesn't contain ACID section!"); + } //Size field used with the above signature (?). Unknown1 = reader.ReadInt32(); diff --git a/Ryujinx.HLE/Loaders/Npdm/FsAccessHeader.cs b/Ryujinx.HLE/Loaders/Npdm/FsAccessHeader.cs index 4eaf7b1100..fd4bdec9f2 100644 --- a/Ryujinx.HLE/Loaders/Npdm/FsAccessHeader.cs +++ b/Ryujinx.HLE/Loaders/Npdm/FsAccessHeader.cs @@ -20,12 +20,18 @@ namespace Ryujinx.HLE.Loaders.Npdm int dataSize = reader.ReadInt32(); - if (dataSize != 0x1c) throw new InvalidNpdmException("FsAccessHeader is corrupted!"); + if (dataSize != 0x1c) + { + throw new InvalidNpdmException("FsAccessHeader is corrupted!"); + } int contentOwnerIdSize = reader.ReadInt32(); int dataAndContentOwnerIdSize = reader.ReadInt32(); - if (dataAndContentOwnerIdSize != 0x1c) throw new NotImplementedException("ContentOwnerId section is not implemented!"); + if (dataAndContentOwnerIdSize != 0x1c) + { + throw new NotImplementedException("ContentOwnerId section is not implemented!"); + } } } } diff --git a/Ryujinx.HLE/Loaders/Npdm/KernelAccessControl.cs b/Ryujinx.HLE/Loaders/Npdm/KernelAccessControl.cs index 70194c47a8..77e152ada5 100644 --- a/Ryujinx.HLE/Loaders/Npdm/KernelAccessControl.cs +++ b/Ryujinx.HLE/Loaders/Npdm/KernelAccessControl.cs @@ -22,7 +22,10 @@ namespace Ryujinx.HLE.Loaders.Npdm uint descriptor = reader.ReadUInt32(); //Ignore the descriptor. - if (descriptor == 0xffffffff) continue; + if (descriptor == 0xffffffff) + { + continue; + } items[index] = new KernelAccessControlItem(); @@ -77,13 +80,19 @@ namespace Ryujinx.HLE.Loaders.Npdm ulong address = (descriptor & 0xffffff) << 12; bool isRo = descriptor >> 24 != 0; - if (index == size / 4 - 1) throw new InvalidNpdmException("Invalid Kernel Access Control Descriptors!"); + if (index == size / 4 - 1) + { + throw new InvalidNpdmException("Invalid Kernel Access Control Descriptors!"); + } - descriptor = reader.ReadUInt32(); + descriptor = reader.ReadUInt32(); - if ((descriptor & 0x7f) != 0x3f) throw new InvalidNpdmException("Invalid Kernel Access Control Descriptors!"); + if ((descriptor & 0x7f) != 0x3f) + { + throw new InvalidNpdmException("Invalid Kernel Access Control Descriptors!"); + } - descriptor >>= 7; + descriptor >>= 7; ulong mmioSize = (descriptor & 0xffffff) << 12; bool isNormal = descriptor >> 24 != 0; diff --git a/Ryujinx.HLE/Loaders/Npdm/Npdm.cs b/Ryujinx.HLE/Loaders/Npdm/Npdm.cs index fe82724d9c..9f88a5c64f 100644 --- a/Ryujinx.HLE/Loaders/Npdm/Npdm.cs +++ b/Ryujinx.HLE/Loaders/Npdm/Npdm.cs @@ -29,7 +29,10 @@ namespace Ryujinx.HLE.Loaders.Npdm { BinaryReader reader = new BinaryReader(stream); - if (reader.ReadInt32() != MetaMagic) throw new InvalidNpdmException("NPDM Stream doesn't contain NPDM file!"); + if (reader.ReadInt32() != MetaMagic) + { + throw new InvalidNpdmException("NPDM Stream doesn't contain NPDM file!"); + } reader.ReadInt64(); diff --git a/Ryujinx.HLE/Loaders/Npdm/ServiceAccessControl.cs b/Ryujinx.HLE/Loaders/Npdm/ServiceAccessControl.cs index 47cb19828d..ef673d8c2a 100644 --- a/Ryujinx.HLE/Loaders/Npdm/ServiceAccessControl.cs +++ b/Ryujinx.HLE/Loaders/Npdm/ServiceAccessControl.cs @@ -23,7 +23,10 @@ namespace Ryujinx.HLE.Loaders.Npdm { byte controlByte = reader.ReadByte(); - if (controlByte == 0) break; + if (controlByte == 0) + { + break; + } int length = (controlByte & 0x07) + 1; bool registerAllowed = (controlByte & 0x80) != 0; diff --git a/Ryujinx.HLE/Memory/ArenaAllocator.cs b/Ryujinx.HLE/Memory/ArenaAllocator.cs index ed94f89837..0b43acc7b5 100644 --- a/Ryujinx.HLE/Memory/ArenaAllocator.cs +++ b/Ryujinx.HLE/Memory/ArenaAllocator.cs @@ -57,12 +57,19 @@ namespace Ryujinx.HLE.Memory _freeRegions.Remove(node.Next); - while (node != null && (ulong)node.Value.Size > (ulong)rg.Size) node = node.Previous; + while (node != null && (ulong)node.Value.Size > (ulong)rg.Size) + { + node = node.Previous; + } if (node != null) + { _freeRegions.AddAfter(node, rg); + } else + { _freeRegions.AddFirst(rg); + } } TotalUsedSize += size; @@ -115,19 +122,27 @@ namespace Ryujinx.HLE.Memory else { if (prevSz == null) + { prevSz = node; + } else if ((ulong)rg.Size < (ulong)newRg.Size && (ulong)rg.Size > (ulong)prevSz.Value.Size) + { prevSz = node; + } } node = nextNode; } if (prevSz != null && (ulong)prevSz.Value.Size < (ulong)size) + { _freeRegions.AddAfter(prevSz, newRg); + } else + { _freeRegions.AddFirst(newRg); + } TotalUsedSize -= size; } diff --git a/Ryujinx.HLE/Memory/DeviceMemory.cs b/Ryujinx.HLE/Memory/DeviceMemory.cs index d53ea68d7e..2b3ab5fd41 100644 --- a/Ryujinx.HLE/Memory/DeviceMemory.cs +++ b/Ryujinx.HLE/Memory/DeviceMemory.cs @@ -106,9 +106,15 @@ namespace Ryujinx.HLE.Memory { int size8 = size & ~(8 - 1); - for (int offs = 0; offs < size8; offs += 8) WriteInt64(position + offs, 0); + for (int offs = 0; offs < size8; offs += 8) + { + WriteInt64(position + offs, 0); + } - for (int offs = size8; offs < size - size8; offs++) WriteByte(position + offs, 0); + for (int offs = size8; offs < size - size8; offs++) + { + WriteByte(position + offs, 0); + } } public void Dispose() diff --git a/Ryujinx.HLE/PerformanceStatistics.cs b/Ryujinx.HLE/PerformanceStatistics.cs index 5736a7c5d2..408e5d72ad 100644 --- a/Ryujinx.HLE/PerformanceStatistics.cs +++ b/Ryujinx.HLE/PerformanceStatistics.cs @@ -59,7 +59,10 @@ namespace Ryujinx.HLE { double frameRate = 0; - if (_accumulatedFrameTime[frameType] > 0) frameRate = _framesRendered[frameType] / _accumulatedFrameTime[frameType]; + if (_accumulatedFrameTime[frameType] > 0) + { + frameRate = _framesRendered[frameType] / _accumulatedFrameTime[frameType]; + } lock (_frameLock[frameType]) { diff --git a/Ryujinx.HLE/Switch.cs b/Ryujinx.HLE/Switch.cs index 108be9116b..4283394d75 100644 --- a/Ryujinx.HLE/Switch.cs +++ b/Ryujinx.HLE/Switch.cs @@ -34,9 +34,15 @@ namespace Ryujinx.HLE public Switch(IGalRenderer renderer, IAalOutput audioOut) { - if (renderer == null) throw new ArgumentNullException(nameof(renderer)); + if (renderer == null) + { + throw new ArgumentNullException(nameof(renderer)); + } - if (audioOut == null) throw new ArgumentNullException(nameof(audioOut)); + if (audioOut == null) + { + throw new ArgumentNullException(nameof(audioOut)); + } AudioOut = audioOut; diff --git a/Ryujinx.HLE/Utilities/StringUtils.cs b/Ryujinx.HLE/Utilities/StringUtils.cs index a6f1d6659c..53fa517a36 100644 --- a/Ryujinx.HLE/Utilities/StringUtils.cs +++ b/Ryujinx.HLE/Utilities/StringUtils.cs @@ -40,7 +40,10 @@ namespace Ryujinx.HLE.Utilities byte[] output = new byte[bytesInHex]; - for (int index = 0; index < bytesInHex; index++) output[index] = byte.Parse(hexString.Substring(index * 2, 2), NumberStyles.HexNumber); + for (int index = 0; index < bytesInHex; index++) + { + output[index] = byte.Parse(hexString.Substring(index * 2, 2), NumberStyles.HexNumber); + } return output; } diff --git a/Ryujinx.HLE/Utilities/UInt128.cs b/Ryujinx.HLE/Utilities/UInt128.cs index aa8389ac7f..a637cfb60d 100644 --- a/Ryujinx.HLE/Utilities/UInt128.cs +++ b/Ryujinx.HLE/Utilities/UInt128.cs @@ -17,7 +17,10 @@ namespace Ryujinx.HLE.Utilities public UInt128(string uInt128Hex) { - if (uInt128Hex == null || uInt128Hex.Length != 32 || !uInt128Hex.All("0123456789abcdefABCDEF".Contains)) throw new ArgumentException("Invalid Hex value!", nameof(uInt128Hex)); + if (uInt128Hex == null || uInt128Hex.Length != 32 || !uInt128Hex.All("0123456789abcdefABCDEF".Contains)) + { + throw new ArgumentException("Invalid Hex value!", nameof(uInt128Hex)); + } Low = Convert.ToInt64(uInt128Hex.Substring(16), 16); High = Convert.ToInt64(uInt128Hex.Substring(0, 16), 16); diff --git a/Ryujinx.Tests.Unicorn/Native/Interface.cs b/Ryujinx.Tests.Unicorn/Native/Interface.cs index 7434ed1ac9..9c5b1c95c6 100644 --- a/Ryujinx.Tests.Unicorn/Native/Interface.cs +++ b/Ryujinx.Tests.Unicorn/Native/Interface.cs @@ -7,7 +7,10 @@ namespace Ryujinx.Tests.Unicorn.Native { public static void Checked(UnicornError error) { - if (error != UnicornError.UcErrOk) throw new UnicornException(error); + if (error != UnicornError.UcErrOk) + { + throw new UnicornException(error); + } } public static void MarshalArrayOf(IntPtr input, int length, out T[] output) diff --git a/Ryujinx.Tests.Unicorn/UnicornAArch64.cs b/Ryujinx.Tests.Unicorn/UnicornAArch64.cs index acc23b5a95..bf291b2d85 100644 --- a/Ryujinx.Tests.Unicorn/UnicornAArch64.cs +++ b/Ryujinx.Tests.Unicorn/UnicornAArch64.cs @@ -292,7 +292,10 @@ namespace Ryujinx.Tests.Unicorn { Native.Interface.Checked(Native.Interface.uc_mem_regions(Uc, out IntPtr regionsRaw, out uint length)); Native.Interface.MarshalArrayOf(regionsRaw, (int)length, out var regions); - foreach (var region in regions) Console.WriteLine("region: begin {0:X16} end {1:X16} perms {2:X8}", region.begin, region.end, region.perms); + foreach (var region in regions) + { + Console.WriteLine("region: begin {0:X16} end {1:X16} perms {2:X8}", region.begin, region.end, region.perms); + } } public static bool IsAvailable() diff --git a/Ryujinx.Tests/Cpu/CpuTest.cs b/Ryujinx.Tests/Cpu/CpuTest.cs index 2792973394..28ce540944 100644 --- a/Ryujinx.Tests/Cpu/CpuTest.cs +++ b/Ryujinx.Tests/Cpu/CpuTest.cs @@ -34,7 +34,10 @@ namespace Ryujinx.Tests.Cpu { _unicornAvailable = UnicornAArch64.IsAvailable(); - if (!_unicornAvailable) Console.WriteLine("WARNING: Could not find Unicorn."); + if (!_unicornAvailable) + { + Console.WriteLine("WARNING: Could not find Unicorn."); + } } [SetUp] @@ -78,7 +81,10 @@ namespace Ryujinx.Tests.Cpu { _thread.Memory.WriteUInt32(Position, opcode); - if (_unicornAvailable) _unicornEmu.MemoryWrite32((ulong)Position, opcode); + if (_unicornAvailable) + { + _unicornEmu.MemoryWrite32((ulong)Position, opcode); + } Position += 4; } @@ -146,7 +152,10 @@ namespace Ryujinx.Tests.Cpu wait.WaitOne(); } - if (_unicornAvailable) _unicornEmu.RunForCount((ulong)(Position - _entryPoint - 8) / 4); + if (_unicornAvailable) + { + _unicornEmu.RunForCount((ulong)(Position - _entryPoint - 8) / 4); + } } protected AThreadState GetThreadState() @@ -244,9 +253,15 @@ namespace Ryujinx.Tests.Cpu FpSkips fpSkips = FpSkips.None, FpTolerances fpTolerances = FpTolerances.None) { - if (!_unicornAvailable) return; + if (!_unicornAvailable) + { + return; + } - if (fpSkips != FpSkips.None) ManageFpSkips(fpSkips); + if (fpSkips != FpSkips.None) + { + ManageFpSkips(fpSkips); + } Assert.That(_thread.ThreadState.X0, Is.EqualTo(_unicornEmu.X[0])); Assert.That(_thread.ThreadState.X1, Is.EqualTo(_unicornEmu.X[1])); @@ -283,9 +298,14 @@ namespace Ryujinx.Tests.Cpu Assert.That(_thread.ThreadState.X31, Is.EqualTo(_unicornEmu.Sp)); if (fpTolerances == FpTolerances.None) + { Assert.That(_thread.ThreadState.V0, Is.EqualTo(_unicornEmu.Q[0])); + } else + { ManageFpTolerances(fpTolerances); + } + Assert.That(_thread.ThreadState.V1, Is.EqualTo(_unicornEmu.Q[1])); Assert.That(_thread.ThreadState.V2, Is.EqualTo(_unicornEmu.Q[2])); Assert.That(_thread.ThreadState.V3, Is.EqualTo(_unicornEmu.Q[3])); @@ -332,18 +352,34 @@ namespace Ryujinx.Tests.Cpu { if (fpSkips.HasFlag(FpSkips.IfNaNS)) { - if (float.IsNaN(VectorExtractSingle(_unicornEmu.Q[0], (byte)0))) Assert.Ignore("NaN test."); + if (float.IsNaN(VectorExtractSingle(_unicornEmu.Q[0], (byte)0))) + { + Assert.Ignore("NaN test."); + } } else if (fpSkips.HasFlag(FpSkips.IfNaND)) { - if (double.IsNaN(VectorExtractDouble(_unicornEmu.Q[0], (byte)0))) Assert.Ignore("NaN test."); + if (double.IsNaN(VectorExtractDouble(_unicornEmu.Q[0], (byte)0))) + { + Assert.Ignore("NaN test."); + } } if (fpSkips.HasFlag(FpSkips.IfUnderflow)) - if ((_unicornEmu.Fpsr & (int)FPSR.Ufc) != 0) Assert.Ignore("Underflow test."); + { + if ((_unicornEmu.Fpsr & (int)FPSR.Ufc) != 0) + { + Assert.Ignore("Underflow test."); + } + } if (fpSkips.HasFlag(FpSkips.IfOverflow)) - if ((_unicornEmu.Fpsr & (int)FPSR.Ofc) != 0) Assert.Ignore("Overflow test."); + { + if ((_unicornEmu.Fpsr & (int)FPSR.Ofc) != 0) + { + Assert.Ignore("Overflow test."); + } + } } private void ManageFpTolerances(FpTolerances fpTolerances) @@ -404,14 +440,20 @@ namespace Ryujinx.Tests.Cpu protected static Vector128 MakeVectorE0(double e0) { - if (!Sse2.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse2.IsSupported) + { + throw new PlatformNotSupportedException(); + } return Sse.StaticCast(Sse2.SetVector128(0, BitConverter.DoubleToInt64Bits(e0))); } protected static Vector128 MakeVectorE0E1(double e0, double e1) { - if (!Sse2.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse2.IsSupported) + { + throw new PlatformNotSupportedException(); + } return Sse.StaticCast( Sse2.SetVector128(BitConverter.DoubleToInt64Bits(e1), BitConverter.DoubleToInt64Bits(e0))); @@ -419,14 +461,20 @@ namespace Ryujinx.Tests.Cpu protected static Vector128 MakeVectorE1(double e1) { - if (!Sse2.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse2.IsSupported) + { + throw new PlatformNotSupportedException(); + } return Sse.StaticCast(Sse2.SetVector128(BitConverter.DoubleToInt64Bits(e1), 0)); } protected static float VectorExtractSingle(Vector128 vector, byte index) { - if (!Sse41.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse41.IsSupported) + { + throw new PlatformNotSupportedException(); + } int value = Sse41.Extract(Sse.StaticCast(vector), index); @@ -435,7 +483,10 @@ namespace Ryujinx.Tests.Cpu protected static double VectorExtractDouble(Vector128 vector, byte index) { - if (!Sse41.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse41.IsSupported) + { + throw new PlatformNotSupportedException(); + } long value = Sse41.Extract(Sse.StaticCast(vector), index); @@ -444,35 +495,50 @@ namespace Ryujinx.Tests.Cpu protected static Vector128 MakeVectorE0(ulong e0) { - if (!Sse2.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse2.IsSupported) + { + throw new PlatformNotSupportedException(); + } return Sse.StaticCast(Sse2.SetVector128(0, e0)); } protected static Vector128 MakeVectorE0E1(ulong e0, ulong e1) { - if (!Sse2.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse2.IsSupported) + { + throw new PlatformNotSupportedException(); + } return Sse.StaticCast(Sse2.SetVector128(e1, e0)); } protected static Vector128 MakeVectorE1(ulong e1) { - if (!Sse2.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse2.IsSupported) + { + throw new PlatformNotSupportedException(); + } return Sse.StaticCast(Sse2.SetVector128(e1, 0)); } protected static ulong GetVectorE0(Vector128 vector) { - if (!Sse41.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse41.IsSupported) + { + throw new PlatformNotSupportedException(); + } return Sse41.Extract(Sse.StaticCast(vector), (byte)0); } protected static ulong GetVectorE1(Vector128 vector) { - if (!Sse41.IsSupported) throw new PlatformNotSupportedException(); + if (!Sse41.IsSupported) + { + throw new PlatformNotSupportedException(); + } return Sse41.Extract(Sse.StaticCast(vector), (byte)1); } diff --git a/Ryujinx.Tests/Cpu/CpuTestAluImm.cs b/Ryujinx.Tests/Cpu/CpuTestAluImm.cs index 42dfddbf75..e7c5f8cbcb 100644 --- a/Ryujinx.Tests/Cpu/CpuTestAluImm.cs +++ b/Ryujinx.Tests/Cpu/CpuTestAluImm.cs @@ -30,9 +30,13 @@ namespace Ryujinx.Tests.Cpu AThreadState threadState; if (rn != 31) + { threadState = SingleOpcode(opcode, x1: xnSp); + } else + { threadState = SingleOpcode(opcode, x31: xnSp); + } CompareAgainstUnicorn(); } @@ -52,9 +56,13 @@ namespace Ryujinx.Tests.Cpu AThreadState threadState; if (rn != 31) + { threadState = SingleOpcode(opcode, x1: wnWsp); + } else + { threadState = SingleOpcode(opcode, x31: wnWsp); + } CompareAgainstUnicorn(); } @@ -74,9 +82,13 @@ namespace Ryujinx.Tests.Cpu AThreadState threadState; if (rn != 31) + { threadState = SingleOpcode(opcode, x1: xnSp); + } else + { threadState = SingleOpcode(opcode, x31: xnSp); + } CompareAgainstUnicorn(); } @@ -96,9 +108,13 @@ namespace Ryujinx.Tests.Cpu AThreadState threadState; if (rn != 31) + { threadState = SingleOpcode(opcode, x1: wnWsp); + } else + { threadState = SingleOpcode(opcode, x31: wnWsp); + } CompareAgainstUnicorn(); } @@ -346,9 +362,13 @@ namespace Ryujinx.Tests.Cpu AThreadState threadState; if (rn != 31) + { threadState = SingleOpcode(opcode, x1: xnSp); + } else + { threadState = SingleOpcode(opcode, x31: xnSp); + } CompareAgainstUnicorn(); } @@ -368,9 +388,13 @@ namespace Ryujinx.Tests.Cpu AThreadState threadState; if (rn != 31) + { threadState = SingleOpcode(opcode, x1: wnWsp); + } else + { threadState = SingleOpcode(opcode, x31: wnWsp); + } CompareAgainstUnicorn(); } @@ -390,9 +414,13 @@ namespace Ryujinx.Tests.Cpu AThreadState threadState; if (rn != 31) + { threadState = SingleOpcode(opcode, x1: xnSp); + } else + { threadState = SingleOpcode(opcode, x31: xnSp); + } CompareAgainstUnicorn(); } @@ -412,9 +440,13 @@ namespace Ryujinx.Tests.Cpu AThreadState threadState; if (rn != 31) + { threadState = SingleOpcode(opcode, x1: wnWsp); + } else + { threadState = SingleOpcode(opcode, x31: wnWsp); + } CompareAgainstUnicorn(); } diff --git a/Ryujinx.Tests/Cpu/CpuTestMisc.cs b/Ryujinx.Tests/Cpu/CpuTestMisc.cs index fb9e57ef51..51a28d9be0 100644 --- a/Ryujinx.Tests/Cpu/CpuTestMisc.cs +++ b/Ryujinx.Tests/Cpu/CpuTestMisc.cs @@ -147,7 +147,10 @@ namespace Ryujinx.Tests.Cpu { ulong a = 0, b = 1, c; - if (n == 0) return a; + if (n == 0) + { + return a; + } for (uint i = 2; i <= n; i++) { diff --git a/Ryujinx.Tests/Cpu/CpuTestSimdArithmetic.cs b/Ryujinx.Tests/Cpu/CpuTestSimdArithmetic.cs index e411a9dac9..311f552f53 100644 --- a/Ryujinx.Tests/Cpu/CpuTestSimdArithmetic.cs +++ b/Ryujinx.Tests/Cpu/CpuTestSimdArithmetic.cs @@ -73,7 +73,10 @@ namespace Ryujinx.Tests.Cpu Vector128 v1 = MakeVectorE0(a); int fpcrTemp = 0x0; - if (defaultNaN) fpcrTemp = 0x2000000; + if (defaultNaN) + { + fpcrTemp = 0x2000000; + } AThreadState threadState = SingleOpcode(opcode, v1: v1, fpcr: fpcrTemp); @@ -99,7 +102,10 @@ namespace Ryujinx.Tests.Cpu Vector128 v1 = MakeVectorE0E1(a, b); int fpcrTemp = 0x0; - if (defaultNaN) fpcrTemp = 0x2000000; + if (defaultNaN) + { + fpcrTemp = 0x2000000; + } AThreadState threadState = SingleOpcode(opcode, v1: v1, fpcr: fpcrTemp); @@ -166,7 +172,10 @@ namespace Ryujinx.Tests.Cpu case 'M': fpcrTemp = 0x800000; break; case 'Z': fpcrTemp = 0xC00000; break; } - if (defaultNaN) fpcrTemp |= 1 << 25; + if (defaultNaN) + { + fpcrTemp |= 1 << 25; + } AThreadState threadState = SingleOpcode(opcode, v1: v1, fpcr: fpcrTemp); @@ -219,7 +228,10 @@ namespace Ryujinx.Tests.Cpu case 'M': fpcrTemp = 0x800000; break; case 'Z': fpcrTemp = 0xC00000; break; } - if (defaultNaN) fpcrTemp |= 1 << 25; + if (defaultNaN) + { + fpcrTemp |= 1 << 25; + } AThreadState threadState = SingleOpcode(opcode, v1: v1, fpcr: fpcrTemp); @@ -277,7 +289,10 @@ namespace Ryujinx.Tests.Cpu Vector128 v1 = MakeVectorE0(a); int fpcrTemp = 0x0; - if (defaultNaN) fpcrTemp = 0x2000000; + if (defaultNaN) + { + fpcrTemp = 0x2000000; + } AThreadState threadState = SingleOpcode(opcode, v1: v1, fpcr: fpcrTemp); @@ -299,7 +314,10 @@ namespace Ryujinx.Tests.Cpu Vector128 v1 = MakeVectorE0E1(a, b); int fpcrTemp = 0x0; - if (defaultNaN) fpcrTemp = 0x2000000; + if (defaultNaN) + { + fpcrTemp = 0x2000000; + } AThreadState threadState = SingleOpcode(opcode, v1: v1, fpcr: fpcrTemp); @@ -358,7 +376,10 @@ namespace Ryujinx.Tests.Cpu Vector128 v1 = MakeVectorE0(a); int fpcrTemp = 0x0; - if (defaultNaN) fpcrTemp = 0x2000000; + if (defaultNaN) + { + fpcrTemp = 0x2000000; + } AThreadState threadState = SingleOpcode(opcode, v1: v1, fpcr: fpcrTemp); @@ -383,7 +404,10 @@ namespace Ryujinx.Tests.Cpu Vector128 v1 = MakeVectorE0E1(a, b); int fpcrTemp = 0x0; - if (defaultNaN) fpcrTemp = 0x2000000; + if (defaultNaN) + { + fpcrTemp = 0x2000000; + } AThreadState threadState = SingleOpcode(opcode, v1: v1, fpcr: fpcrTemp); @@ -441,7 +465,10 @@ namespace Ryujinx.Tests.Cpu Vector128 v1 = MakeVectorE0(a); int fpcrTemp = 0x0; - if (defaultNaN) fpcrTemp = 0x2000000; + if (defaultNaN) + { + fpcrTemp = 0x2000000; + } AThreadState threadState = SingleOpcode(opcode, v1: v1, fpcr: fpcrTemp); @@ -463,7 +490,10 @@ namespace Ryujinx.Tests.Cpu Vector128 v1 = MakeVectorE0E1(a, b); int fpcrTemp = 0x0; - if (defaultNaN) fpcrTemp = 0x2000000; + if (defaultNaN) + { + fpcrTemp = 0x2000000; + } AThreadState threadState = SingleOpcode(opcode, v1: v1, fpcr: fpcrTemp); @@ -530,9 +560,12 @@ namespace Ryujinx.Tests.Cpu case 'M': fpcrTemp = 0x800000; break; case 'Z': fpcrTemp = 0xC00000; break; } - if (defaultNaN) fpcrTemp |= 1 << 25; + if (defaultNaN) + { + fpcrTemp |= 1 << 25; + } - AThreadState threadState = SingleOpcode(opcode, v1: v1, fpcr: fpcrTemp); + AThreadState threadState = SingleOpcode(opcode, v1: v1, fpcr: fpcrTemp); Assert.That(GetVectorE0(threadState.V0), Is.EqualTo(result)); @@ -583,7 +616,10 @@ namespace Ryujinx.Tests.Cpu case 'M': fpcrTemp = 0x800000; break; case 'Z': fpcrTemp = 0xC00000; break; } - if (defaultNaN) fpcrTemp |= 1 << 25; + if (defaultNaN) + { + fpcrTemp |= 1 << 25; + } AThreadState threadState = SingleOpcode(opcode, v1: v1, fpcr: fpcrTemp); diff --git a/Ryujinx.Tests/Cpu/CpuTestSimdCrypto.cs b/Ryujinx.Tests/Cpu/CpuTestSimdCrypto.cs index 7e6c62d90d..88f34edd08 100644 --- a/Ryujinx.Tests/Cpu/CpuTestSimdCrypto.cs +++ b/Ryujinx.Tests/Cpu/CpuTestSimdCrypto.cs @@ -98,11 +98,13 @@ namespace Ryujinx.Tests.Cpu Assert.That(GetVectorE1(threadState.V0), Is.EqualTo(resultH)); }); if (rn == 1u) + { Assert.Multiple(() => { Assert.That(GetVectorE0(threadState.V1), Is.EqualTo(valueL)); Assert.That(GetVectorE1(threadState.V1), Is.EqualTo(valueH)); }); + } CompareAgainstUnicorn(); } @@ -131,11 +133,13 @@ namespace Ryujinx.Tests.Cpu Assert.That(GetVectorE1(threadState.V0), Is.EqualTo(resultH)); }); if (rn == 1u) + { Assert.Multiple(() => { Assert.That(GetVectorE0(threadState.V1), Is.EqualTo(valueL)); Assert.That(GetVectorE1(threadState.V1), Is.EqualTo(valueH)); }); + } CompareAgainstUnicorn(); } diff --git a/Ryujinx/Config.cs b/Ryujinx/Config.cs index d5c547d84f..0ee74c6512 100644 --- a/Ryujinx/Config.cs +++ b/Ryujinx/Config.cs @@ -38,18 +38,35 @@ namespace Ryujinx //So, first disable everything, then enable //the classes that the user added to the list. if (filteredLogClasses.Length > 0) - foreach (LogClass Class in Enum.GetValues(typeof(LogClass))) Logger.SetEnable(Class, false); + { + foreach (LogClass Class in Enum.GetValues(typeof(LogClass))) + { + Logger.SetEnable(Class, false); + } + } foreach (string logClass in filteredLogClasses) + { if (!string.IsNullOrEmpty(logClass.Trim())) + { foreach (LogClass Class in Enum.GetValues(typeof(LogClass))) - if (Class.ToString().ToLower().Contains(logClass.Trim().ToLower())) Logger.SetEnable(Class, true); + { + if (Class.ToString().ToLower().Contains(logClass.Trim().ToLower())) + { + Logger.SetEnable(Class, true); + } + } + } + } device.System.State.DockedMode = Convert.ToBoolean(parser.Value("Docked_Mode")); device.EnableDeviceVsync = Convert.ToBoolean(parser.Value("Enable_Vsync")); - if (Convert.ToBoolean(parser.Value("Enable_MultiCore_Scheduling"))) device.System.EnableMultiCoreScheduling(); + if (Convert.ToBoolean(parser.Value("Enable_MultiCore_Scheduling"))) + { + device.System.EnableMultiCoreScheduling(); + } device.System.EnableFsIntegrityChecks = Convert.ToBoolean(parser.Value("Enable_FS_Integrity_Checks")); diff --git a/Ryujinx/Ui/ConsoleLog.cs b/Ryujinx/Ui/ConsoleLog.cs index f128fac827..8a7d4568dd 100644 --- a/Ryujinx/Ui/ConsoleLog.cs +++ b/Ryujinx/Ui/ConsoleLog.cs @@ -33,6 +33,7 @@ namespace Ryujinx _messageThread = new Thread(() => { while (!_messageQueue.IsCompleted) + { try { PrintLog(_messageQueue.Take()); @@ -45,6 +46,7 @@ namespace Ryujinx // We can simply catch the exception since the loop will break // on the next iteration. } + } }); _messageThread.IsBackground = true; @@ -60,6 +62,7 @@ namespace Ryujinx string message = formattedTime + " | " + currentThread + " " + e.Message; if (_logColors.TryGetValue(e.Level, out ConsoleColor color)) + { lock (_consoleLock) { Console.ForegroundColor = color; @@ -67,13 +70,19 @@ namespace Ryujinx Console.WriteLine(message); Console.ResetColor(); } + } else + { Console.WriteLine(message); + } } public static void Log(object sender, LogEventArgs e) { - if (!_messageQueue.IsAddingCompleted) _messageQueue.Add(e); + if (!_messageQueue.IsAddingCompleted) + { + _messageQueue.Add(e); + } } } } \ No newline at end of file diff --git a/Ryujinx/Ui/GLScreen.cs b/Ryujinx/Ui/GLScreen.cs index 072758b04e..a970eb73ca 100644 --- a/Ryujinx/Ui/GLScreen.cs +++ b/Ryujinx/Ui/GLScreen.cs @@ -62,7 +62,10 @@ namespace Ryujinx while (Exists && !IsExiting) { - if (_device.WaitFifo()) _device.ProcessFrame(); + if (_device.WaitFifo()) + { + _device.ProcessFrame(); + } _renderer.RunActions(); @@ -150,9 +153,15 @@ namespace Ryujinx currentButton |= Config.JoyConController.GetButtons(); //Keyboard has priority stick-wise - if (leftJoystickDx == 0 && leftJoystickDy == 0) (leftJoystickDx, leftJoystickDy) = Config.JoyConController.GetLeftStick(); + if (leftJoystickDx == 0 && leftJoystickDy == 0) + { + (leftJoystickDx, leftJoystickDy) = Config.JoyConController.GetLeftStick(); + } - if (rightJoystickDx == 0 && rightJoystickDy == 0) (rightJoystickDx, rightJoystickDy) = Config.JoyConController.GetRightStick(); + if (rightJoystickDx == 0 && rightJoystickDy == 0) + { + (rightJoystickDx, rightJoystickDy) = Config.JoyConController.GetRightStick(); + } leftJoystick = new HidJoystickPosition { @@ -178,9 +187,13 @@ namespace Ryujinx int scrnHeight = Height; if (Width > Height * TouchScreenWidth / TouchScreenHeight) + { scrnWidth = Height * TouchScreenWidth / TouchScreenHeight; + } else + { scrnHeight = Width * TouchScreenHeight / TouchScreenWidth; + } int startX = (Width - scrnWidth) >> 1; int startY = (Height - scrnHeight) >> 1; @@ -216,7 +229,10 @@ namespace Ryujinx } } - if (!hasTouch) _device.Hid.SetTouchPoints(); + if (!hasTouch) + { + _device.Hid.SetTouchPoints(); + } _device.Hid.SetJoyconButton( HidControllerId.ControllerHandheld, @@ -276,13 +292,22 @@ namespace Ryujinx if (WindowState == WindowState.Fullscreen) { - if (e.Key == Key.Escape || toggleFullscreen) WindowState = WindowState.Normal; + if (e.Key == Key.Escape || toggleFullscreen) + { + WindowState = WindowState.Normal; + } } else { - if (e.Key == Key.Escape) Exit(); + if (e.Key == Key.Escape) + { + Exit(); + } - if (toggleFullscreen) WindowState = WindowState.Fullscreen; + if (toggleFullscreen) + { + WindowState = WindowState.Fullscreen; + } } _keyboard = e.Keyboard; diff --git a/Ryujinx/Ui/JoyConController.cs b/Ryujinx/Ui/JoyConController.cs index c226823cfe..83a9df82ce 100644 --- a/Ryujinx/Ui/JoyConController.cs +++ b/Ryujinx/Ui/JoyConController.cs @@ -84,48 +84,122 @@ namespace Ryujinx.UI.Input Right = right; //Unmapped controllers are problematic, skip them - if (GamePad.GetName(index) == "Unmapped Controller") Enabled = false; + if (GamePad.GetName(index) == "Unmapped Controller") + { + Enabled = false; + } } public HidControllerButtons GetButtons() { - if (!Enabled) return 0; + if (!Enabled) + { + return 0; + } GamePadState gpState = GamePad.GetState(Index); HidControllerButtons buttons = 0; - if (IsPressed(gpState, Left.DPadUp)) buttons |= HidControllerButtons.KeyDup; - if (IsPressed(gpState, Left.DPadDown)) buttons |= HidControllerButtons.KeyDdown; - if (IsPressed(gpState, Left.DPadLeft)) buttons |= HidControllerButtons.KeyDleft; - if (IsPressed(gpState, Left.DPadRight)) buttons |= HidControllerButtons.KeyDright; - if (IsPressed(gpState, Left.StickButton)) buttons |= HidControllerButtons.KeyLstick; - if (IsPressed(gpState, Left.ButtonMinus)) buttons |= HidControllerButtons.KeyMinus; - if (IsPressed(gpState, Left.ButtonL)) buttons |= HidControllerButtons.KeyL; - if (IsPressed(gpState, Left.ButtonZl)) buttons |= HidControllerButtons.KeyZl; + if (IsPressed(gpState, Left.DPadUp)) + { + buttons |= HidControllerButtons.KeyDup; + } - if (IsPressed(gpState, Right.ButtonA)) buttons |= HidControllerButtons.KeyA; - if (IsPressed(gpState, Right.ButtonB)) buttons |= HidControllerButtons.KeyB; - if (IsPressed(gpState, Right.ButtonX)) buttons |= HidControllerButtons.KeyX; - if (IsPressed(gpState, Right.ButtonY)) buttons |= HidControllerButtons.KeyY; - if (IsPressed(gpState, Right.StickButton)) buttons |= HidControllerButtons.KeyRstick; - if (IsPressed(gpState, Right.ButtonPlus)) buttons |= HidControllerButtons.KeyPlus; - if (IsPressed(gpState, Right.ButtonR)) buttons |= HidControllerButtons.KeyR; - if (IsPressed(gpState, Right.ButtonZr)) buttons |= HidControllerButtons.KeyZr; + if (IsPressed(gpState, Left.DPadDown)) + { + buttons |= HidControllerButtons.KeyDdown; + } + + if (IsPressed(gpState, Left.DPadLeft)) + { + buttons |= HidControllerButtons.KeyDleft; + } + + if (IsPressed(gpState, Left.DPadRight)) + { + buttons |= HidControllerButtons.KeyDright; + } + + if (IsPressed(gpState, Left.StickButton)) + { + buttons |= HidControllerButtons.KeyLstick; + } + + if (IsPressed(gpState, Left.ButtonMinus)) + { + buttons |= HidControllerButtons.KeyMinus; + } + + if (IsPressed(gpState, Left.ButtonL)) + { + buttons |= HidControllerButtons.KeyL; + } + + if (IsPressed(gpState, Left.ButtonZl)) + { + buttons |= HidControllerButtons.KeyZl; + } + + if (IsPressed(gpState, Right.ButtonA)) + { + buttons |= HidControllerButtons.KeyA; + } + + if (IsPressed(gpState, Right.ButtonB)) + { + buttons |= HidControllerButtons.KeyB; + } + + if (IsPressed(gpState, Right.ButtonX)) + { + buttons |= HidControllerButtons.KeyX; + } + + if (IsPressed(gpState, Right.ButtonY)) + { + buttons |= HidControllerButtons.KeyY; + } + + if (IsPressed(gpState, Right.StickButton)) + { + buttons |= HidControllerButtons.KeyRstick; + } + + if (IsPressed(gpState, Right.ButtonPlus)) + { + buttons |= HidControllerButtons.KeyPlus; + } + + if (IsPressed(gpState, Right.ButtonR)) + { + buttons |= HidControllerButtons.KeyR; + } + + if (IsPressed(gpState, Right.ButtonZr)) + { + buttons |= HidControllerButtons.KeyZr; + } return buttons; } public (short, short) GetLeftStick() { - if (!Enabled) return (0, 0); + if (!Enabled) + { + return (0, 0); + } return GetStick(Left.Stick); } public (short, short) GetRightStick() { - if (!Enabled) return (0, 0); + if (!Enabled) + { + return (0, 0); + } return GetStick(Right.Stick); } @@ -156,9 +230,13 @@ namespace Ryujinx.UI.Input private static short ClampAxis(float value) { if (value <= -short.MaxValue) + { return -short.MaxValue; + } else + { return (short)(value * short.MaxValue); + } } private bool IsPressed(GamePadState gpState, ControllerInputID button) diff --git a/Ryujinx/Ui/JoyConKeyboard.cs b/Ryujinx/Ui/JoyConKeyboard.cs index 9d2ed5af4c..52bfc0adc0 100644 --- a/Ryujinx/Ui/JoyConKeyboard.cs +++ b/Ryujinx/Ui/JoyConKeyboard.cs @@ -52,23 +52,85 @@ namespace Ryujinx.UI.Input { HidControllerButtons buttons = 0; - if (keyboard[(Key)Left.StickButton]) buttons |= HidControllerButtons.KeyLstick; - if (keyboard[(Key)Left.DPadUp]) buttons |= HidControllerButtons.KeyDup; - if (keyboard[(Key)Left.DPadDown]) buttons |= HidControllerButtons.KeyDdown; - if (keyboard[(Key)Left.DPadLeft]) buttons |= HidControllerButtons.KeyDleft; - if (keyboard[(Key)Left.DPadRight]) buttons |= HidControllerButtons.KeyDright; - if (keyboard[(Key)Left.ButtonMinus]) buttons |= HidControllerButtons.KeyMinus; - if (keyboard[(Key)Left.ButtonL]) buttons |= HidControllerButtons.KeyL; - if (keyboard[(Key)Left.ButtonZl]) buttons |= HidControllerButtons.KeyZl; - - if (keyboard[(Key)Right.StickButton]) buttons |= HidControllerButtons.KeyRstick; - if (keyboard[(Key)Right.ButtonA]) buttons |= HidControllerButtons.KeyA; - if (keyboard[(Key)Right.ButtonB]) buttons |= HidControllerButtons.KeyB; - if (keyboard[(Key)Right.ButtonX]) buttons |= HidControllerButtons.KeyX; - if (keyboard[(Key)Right.ButtonY]) buttons |= HidControllerButtons.KeyY; - if (keyboard[(Key)Right.ButtonPlus]) buttons |= HidControllerButtons.KeyPlus; - if (keyboard[(Key)Right.ButtonR]) buttons |= HidControllerButtons.KeyR; - if (keyboard[(Key)Right.ButtonZr]) buttons |= HidControllerButtons.KeyZr; + if (keyboard[(Key)Left.StickButton]) + { + buttons |= HidControllerButtons.KeyLstick; + } + + if (keyboard[(Key)Left.DPadUp]) + { + buttons |= HidControllerButtons.KeyDup; + } + + if (keyboard[(Key)Left.DPadDown]) + { + buttons |= HidControllerButtons.KeyDdown; + } + + if (keyboard[(Key)Left.DPadLeft]) + { + buttons |= HidControllerButtons.KeyDleft; + } + + if (keyboard[(Key)Left.DPadRight]) + { + buttons |= HidControllerButtons.KeyDright; + } + + if (keyboard[(Key)Left.ButtonMinus]) + { + buttons |= HidControllerButtons.KeyMinus; + } + + if (keyboard[(Key)Left.ButtonL]) + { + buttons |= HidControllerButtons.KeyL; + } + + if (keyboard[(Key)Left.ButtonZl]) + { + buttons |= HidControllerButtons.KeyZl; + } + + if (keyboard[(Key)Right.StickButton]) + { + buttons |= HidControllerButtons.KeyRstick; + } + + if (keyboard[(Key)Right.ButtonA]) + { + buttons |= HidControllerButtons.KeyA; + } + + if (keyboard[(Key)Right.ButtonB]) + { + buttons |= HidControllerButtons.KeyB; + } + + if (keyboard[(Key)Right.ButtonX]) + { + buttons |= HidControllerButtons.KeyX; + } + + if (keyboard[(Key)Right.ButtonY]) + { + buttons |= HidControllerButtons.KeyY; + } + + if (keyboard[(Key)Right.ButtonPlus]) + { + buttons |= HidControllerButtons.KeyPlus; + } + + if (keyboard[(Key)Right.ButtonR]) + { + buttons |= HidControllerButtons.KeyR; + } + + if (keyboard[(Key)Right.ButtonZr]) + { + buttons |= HidControllerButtons.KeyZr; + } return buttons; } @@ -78,10 +140,25 @@ namespace Ryujinx.UI.Input short dx = 0; short dy = 0; - if (keyboard[(Key)Left.StickUp]) dy = short.MaxValue; - if (keyboard[(Key)Left.StickDown]) dy = -short.MaxValue; - if (keyboard[(Key)Left.StickLeft]) dx = -short.MaxValue; - if (keyboard[(Key)Left.StickRight]) dx = short.MaxValue; + if (keyboard[(Key)Left.StickUp]) + { + dy = short.MaxValue; + } + + if (keyboard[(Key)Left.StickDown]) + { + dy = -short.MaxValue; + } + + if (keyboard[(Key)Left.StickLeft]) + { + dx = -short.MaxValue; + } + + if (keyboard[(Key)Left.StickRight]) + { + dx = short.MaxValue; + } return (dx, dy); } @@ -91,10 +168,25 @@ namespace Ryujinx.UI.Input short dx = 0; short dy = 0; - if (keyboard[(Key)Right.StickUp]) dy = short.MaxValue; - if (keyboard[(Key)Right.StickDown]) dy = -short.MaxValue; - if (keyboard[(Key)Right.StickLeft]) dx = -short.MaxValue; - if (keyboard[(Key)Right.StickRight]) dx = short.MaxValue; + if (keyboard[(Key)Right.StickUp]) + { + dy = short.MaxValue; + } + + if (keyboard[(Key)Right.StickDown]) + { + dy = -short.MaxValue; + } + + if (keyboard[(Key)Right.StickLeft]) + { + dx = -short.MaxValue; + } + + if (keyboard[(Key)Right.StickRight]) + { + dx = short.MaxValue; + } return (dx, dy); } diff --git a/Ryujinx/Ui/Program.cs b/Ryujinx/Ui/Program.cs index 36394eb3c7..28d7e9f012 100644 --- a/Ryujinx/Ui/Program.cs +++ b/Ryujinx/Ui/Program.cs @@ -31,7 +31,10 @@ namespace Ryujinx { string[] romFsFiles = Directory.GetFiles(args[0], "*.istorage"); - if (romFsFiles.Length == 0) romFsFiles = Directory.GetFiles(args[0], "*.romfs"); + if (romFsFiles.Length == 0) + { + romFsFiles = Directory.GetFiles(args[0], "*.romfs"); + } if (romFsFiles.Length > 0) {