From b3cdf06c5ad4bc84b5c99201023719765be476fa Mon Sep 17 00:00:00 2001 From: "Unknown W. Brackets" Date: Thu, 10 Aug 2023 23:13:26 -0700 Subject: [PATCH] riscv: Write fixup on block invalidation. --- Core/MIPS/IR/IRNativeCommon.cpp | 2 +- Core/MIPS/RiscV/RiscVJit.cpp | 31 ++++++++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/Core/MIPS/IR/IRNativeCommon.cpp b/Core/MIPS/IR/IRNativeCommon.cpp index db9c4a159d..52995eb5f4 100644 --- a/Core/MIPS/IR/IRNativeCommon.cpp +++ b/Core/MIPS/IR/IRNativeCommon.cpp @@ -426,8 +426,8 @@ void IRNativeJit::InvalidateCacheAt(u32 em_address, int length) { std::vector numbers = blocks_.FindInvalidatedBlockNumbers(em_address, length); for (int block_num : numbers) { auto block = blocks_.GetBlock(block_num); - block->Destroy(block->GetTargetOffset()); backend_->InvalidateBlock(block, block_num); + block->Destroy(block->GetTargetOffset()); } } diff --git a/Core/MIPS/RiscV/RiscVJit.cpp b/Core/MIPS/RiscV/RiscVJit.cpp index 71df439f65..22ecdb4311 100644 --- a/Core/MIPS/RiscV/RiscVJit.cpp +++ b/Core/MIPS/RiscV/RiscVJit.cpp @@ -85,6 +85,12 @@ bool RiscVJitBackend::CompileBlock(IRBlock *block, int block_num, bool preload) QuickJ(R_RA, hooks_.crashHandler); } + int len = (int)GetOffset(GetCodePointer()) - block->GetTargetOffset(); + if (len < 16) { + // We need at least 16 bytes to invalidate blocks with, but larger doesn't need to align. + AlignCode16(); + } + FlushIcache(); return true; @@ -163,7 +169,30 @@ void RiscVJitBackend::ClearAllBlocks() { } void RiscVJitBackend::InvalidateBlock(IRBlock *block, int block_num) { - // TODO + int offset = block->GetTargetOffset(); + u8 *writable = GetWritablePtrFromCodePtr(GetBasePtr()) + offset; + + u32 pc, len; + block->GetRange(pc, len); + + // Overwrite the block with a jump to compile it again. + if (pc != 0) { + // Hopefully we always have at least 16 bytes, which should be all we need. + if (PlatformIsWXExclusive()) { + ProtectMemoryPages(writable, 16, MEM_PROT_READ | MEM_PROT_WRITE); + } + + RiscVEmitter emitter(GetBasePtr() + offset, writable); + // We sign extend to ensure it will fit in 32-bit and 8 bytes LI. + // TODO: Would need to change if dispatcher doesn't reload PC. + emitter.LI(SCRATCH1, (int32_t)pc); + emitter.J(dispatcherPCInSCRATCH1_); + emitter.FlushIcache(); + + if (PlatformIsWXExclusive()) { + ProtectMemoryPages(writable, 16, MEM_PROT_READ | MEM_PROT_EXEC); + } + } } void RiscVJitBackend::RestoreRoundingMode(bool force) {