id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
23,103
|
coreinit_IM.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_IM.cpp
|
#include "Cafe/OS/common/OSCommon.h"
// APD = Automatic Power Down
namespace coreinit
{
#define IM_ERROR_NONE 0
void coreinitExport_IMIsAPDEnabledBySysSettings(PPCInterpreter_t* hCPU)
{
debug_printf("IMIsAPDEnabledBySysSettings(0x%08x)\n", hCPU->gpr[3]);
ppcDefineParamTypePtr(isAPDEnabled, uint32be, 0);
*isAPDEnabled = 0;
osLib_returnFromFunction(hCPU, IM_ERROR_NONE);
}
void coreinitExport_IMGetTimeBeforeAPD(PPCInterpreter_t* hCPU)
{
// parameters:
// r3 uint32* returns the remaining number of seconds until auto-shutdown
memory_writeU32(hCPU->gpr[3], 60 * 30); // 30 minutes
osLib_returnFromFunction(hCPU, IM_ERROR_NONE);
}
void coreinitExport_IMGetTimeBeforeDimming(PPCInterpreter_t* hCPU)
{
// parameters:
// r3 uint32* returns the remaining number of seconds until dimming
memory_writeU32(hCPU->gpr[3], 60 * 30); // 30 minutes
osLib_returnFromFunction(hCPU, IM_ERROR_NONE);
}
bool imDimIsEnabled = true;
void coreinitExport_IMEnableDim(PPCInterpreter_t* hCPU)
{
imDimIsEnabled = true;
osLib_returnFromFunction(hCPU, IM_ERROR_NONE);
}
void coreinitExport_IMIsDimEnabled(PPCInterpreter_t* hCPU)
{
// parameters:
// r3 uint32* returns the remaining number of seconds until auto-shutdown
memory_writeU32(hCPU->gpr[3], imDimIsEnabled ? 1 : 0); // enabled
osLib_returnFromFunction(hCPU, IM_ERROR_NONE);
}
void coreinitExport_IMGetAPDPeriod(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "IMGetAPDPeriod(0x{:08x})", hCPU->gpr[3]);
// parameters:
// r3 uint32* returns the number of seconds until auto-shutdown occurs
memory_writeU32(hCPU->gpr[3], 600);
osLib_returnFromFunction(hCPU, IM_ERROR_NONE);
}
void coreinitExport_IM_GetParameter(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "IM_GetParameter()");
ppcDefineParamS32(imHandle, 0); // handle from IM_Open()
ppcDefineParamS32(uknR4, 1);
ppcDefineParamS32(parameterId, 2);
ppcDefineParamStructPtr(output, void, 3);
ppcDefineParamS32(uknR7, 4);
ppcDefineParamS32(uknR8, 5);
if (parameterId == 0)
{
// inactive seconds
*(uint32be*)output = 600;
}
else
{
cemu_assert_unimplemented();
}
osLib_returnFromFunction(hCPU, IM_ERROR_NONE);
}
void coreinitExport_IM_GetRuntimeParameter(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "IM_GetRuntimeParameter()");
ppcDefineParamS32(parameterId, 0);
ppcDefineParamStructPtr(output, void, 1);
if (parameterId == 8)
{
// indicates if last session was ended due to auto-power-down
*(uint32be*)output = 0;
}
else
{
cemu_assert_unimplemented();
}
osLib_returnFromFunction(hCPU, IM_ERROR_NONE);
}
void coreinitExport_IM_GetHomeButtonParams(PPCInterpreter_t* hCPU)
{
debug_printf("IM_GetHomeButtonParams(...)\n");
ppcDefineParamS32(imObj, 0);
ppcDefineParamMPTR(ipcBuf, 1);
ppcDefineParamMPTR(paramOut, 2);
ppcDefineParamS32(uknR6, 3);
ppcDefineParamS32(uknR7, 4);
// todo
// note: No idea what these values mean. But they were chosen so that the Browser (surf.rpx) does not OSPanic()
memory_writeU32(paramOut + 0x0, 0);
memory_writeU32(paramOut + 0x4, 0);
// for scope.rpx (Download Manager)
//memory_writeU32(paramOut + 0x0, 1);
//memory_writeU32(paramOut + 0x4, 2); // some sort of index (starting at 1?)
osLib_returnFromFunction(hCPU, IM_ERROR_NONE);
}
void InitializeIM()
{
osLib_addFunction("coreinit", "IMIsAPDEnabledBySysSettings", coreinitExport_IMIsAPDEnabledBySysSettings);
osLib_addFunction("coreinit", "IMGetTimeBeforeAPD", coreinitExport_IMGetTimeBeforeAPD);
osLib_addFunction("coreinit", "IMGetTimeBeforeDimming", coreinitExport_IMGetTimeBeforeDimming);
osLib_addFunction("coreinit", "IMEnableDim", coreinitExport_IMEnableDim);
osLib_addFunction("coreinit", "IMIsDimEnabled", coreinitExport_IMIsDimEnabled);
osLib_addFunction("coreinit", "IMGetAPDPeriod", coreinitExport_IMGetAPDPeriod);
osLib_addFunction("coreinit", "IM_GetHomeButtonParams", coreinitExport_IM_GetHomeButtonParams);
osLib_addFunction("coreinit", "IM_GetParameter", coreinitExport_IM_GetParameter);
osLib_addFunction("coreinit", "IM_GetRuntimeParameter", coreinitExport_IM_GetRuntimeParameter);
}
};
| 4,222
|
C++
|
.cpp
| 113
| 34.469027
| 113
| 0.761812
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,104
|
coreinit_IPC.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_IPC.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/IOSU/kernel/iosu_kernel.h"
#include "Cafe/HW/Espresso/Const.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "coreinit_MessageQueue.h"
#include "coreinit_IPC.h"
namespace coreinit
{
static constexpr inline size_t IPC_NUM_RESOURCE_BUFFERS = 0x30;
struct IPCResourceBuffer
{
IPCCommandBody commandBody;
uint8 bufferData[0x80 - 0x48];
};
static_assert(sizeof(IPCCommandBody) == 0x48);
static_assert(sizeof(IPCResourceBuffer) == 0x80);
struct IPCResourceBufferDescriptor
{
/* +0x00 */ uint32be IsAllocated;
/* +0x04 */ MEMPTR<OSMessageQueue> asyncMsgQueue; // optional, if set a message will be sent to this queue...
/* +0x08 */ MEMPTR<void> asyncResultFunc; // ...otherwise this is checked and delegated to the IPC threads. If false, only eventSynchronousIPC will be signaled. If true, a message will be sent to the per-core ipc queue
/* +0x0C */ MEMPTR<void> asyncResultUserParam;
/* +0x10 */ uint32 ukn10;
/* +0x14 */ MEMPTR<IPCResourceBuffer> resourcePtr;
/* +0x18 */ OSEvent eventSynchronousIPC;
};
static_assert(sizeof(IPCResourceBufferDescriptor) == 0x3C);
struct IPCBufferFIFO
{
sint32be writeIndex;
sint32be readIndex;
sint32be numQueuedEntries;
sint32be mostQueuedEntries;
MEMPTR<IPCResourceBufferDescriptor> ringbufferArray[IPC_NUM_RESOURCE_BUFFERS];
void Init()
{
writeIndex = 0;
readIndex = -1;
numQueuedEntries = 0;
mostQueuedEntries = 0;
for (size_t i = 0; i < IPC_NUM_RESOURCE_BUFFERS; i++)
ringbufferArray[i] = nullptr;
}
void Push(IPCResourceBufferDescriptor* descriptor)
{
cemu_assert(readIndex != writeIndex); // if equal, fifo is full (should not happen as there not more buffers than ringbuffer entries)
ringbufferArray[writeIndex] = descriptor;
if (readIndex < 0)
readIndex = writeIndex;
writeIndex = (writeIndex + 1) % IPC_NUM_RESOURCE_BUFFERS;
++numQueuedEntries;
if (numQueuedEntries > mostQueuedEntries)
mostQueuedEntries = numQueuedEntries;
}
IPCResourceBufferDescriptor* Pop()
{
if (numQueuedEntries == 0)
return nullptr;
IPCResourceBufferDescriptor* r = ringbufferArray[readIndex].GetPtr();
--numQueuedEntries;
if (numQueuedEntries == 0)
readIndex = -1;
else
readIndex = (readIndex + 1) % IPC_NUM_RESOURCE_BUFFERS;
return r;
}
};
struct IPCDriverCOSKernelCommunicationArea
{
uint32be numAvailableResponses;
MEMPTR<IPCCommandBody> responseArray[11];
};
static_assert(sizeof(IPCDriverCOSKernelCommunicationArea) == 0x30);
struct alignas(64) IPCDriver
{
betype<IPCDriverState> state;
uint32 ukn04;
uint32 coreIndex;
uint32 writeIndexCmd020;
MEMPTR<IPCResourceBuffer> resourceBuffers;
/* 0x16C */ IPCBufferFIFO fifoFreeBuffers;
/* 0x23C */ IPCBufferFIFO fifoBuffersInFlight;
/* 0x334 */ uint32 resourceBuffersInitialized;
/* 0x338 */ IPCDriverCOSKernelCommunicationArea kernelSharedArea; // this is passed to system call 0x1E00 (IPCOpen)
/* 0x3FC */ IPCResourceBufferDescriptor resBufferDescriptor[IPC_NUM_RESOURCE_BUFFERS];
};
//static_assert(sizeof(IPCDriverInstance) == 0x1740);
SysAllocator<IPCResourceBuffer, IPC_NUM_RESOURCE_BUFFERS * Espresso::CORE_COUNT, 0x40> s_ipcResourceBuffers;
SysAllocator<IPCDriver, Espresso::CORE_COUNT, 0x40> s_ipcDriver;
IPCDriver& IPCDriver_GetByCore(uint32 coreIndex)
{
cemu_assert_debug(coreIndex >= 0 && coreIndex < (uint32)Espresso::CORE_COUNT);
return s_ipcDriver[coreIndex];
}
void IPCDriver_InitForCore(uint32 coreIndex)
{
IPCDriver& ipcDriver = IPCDriver_GetByCore(coreIndex);
ipcDriver.coreIndex = coreIndex;
ipcDriver.state = IPCDriverState::INITIALIZED;
ipcDriver.resourceBuffers = s_ipcResourceBuffers.GetPtr() + IPC_NUM_RESOURCE_BUFFERS * coreIndex;
ipcDriver.resourceBuffersInitialized = 0;
// setup resource descriptors
for (size_t i = 0; i < IPC_NUM_RESOURCE_BUFFERS; i++)
{
ipcDriver.resBufferDescriptor[i].resourcePtr = ipcDriver.resourceBuffers.GetPtr() + i;
ipcDriver.resBufferDescriptor[i].asyncResultFunc = nullptr;
ipcDriver.resBufferDescriptor[i].asyncResultUserParam = nullptr;
}
ipcDriver.resourceBuffersInitialized = 1;
// setup resource buffer FIFOs
ipcDriver.fifoFreeBuffers.Init();
ipcDriver.fifoBuffersInFlight.Init();
for (size_t i = 0; i < IPC_NUM_RESOURCE_BUFFERS; i++)
ipcDriver.fifoFreeBuffers.Push(ipcDriver.resBufferDescriptor + i);
}
IPCResourceBufferDescriptor* IPCDriver_AllocateResource(IPCDriver* ipcDriver, IOSDevHandle devHandle, IPCCommandId cmdId, OSMessageQueue* asyncMessageQueue, MEMPTR<void> asyncResultFunc, MEMPTR<void> asyncResultUserParam)
{
cemu_assert_debug(ipcDriver->coreIndex == OSGetCoreId());
IPCResourceBufferDescriptor* descriptor = nullptr;
while (true)
{
descriptor = ipcDriver->fifoFreeBuffers.Pop();
if (!descriptor)
{
cemuLog_log(LogType::Force, "IPCDriver: Exceeded free resources");
OSYieldThread();
cemu_assert_unimplemented(); // we should wait for an event instead of busylooping
}
else
break;
}
cemu_assert_debug(descriptor >= ipcDriver->resBufferDescriptor && descriptor < ipcDriver->resBufferDescriptor + IPC_NUM_RESOURCE_BUFFERS);
cemu_assert_debug(descriptor->resourcePtr.GetPtr() >= ipcDriver->resourceBuffers.GetPtr() && descriptor->resourcePtr.GetPtr() < (ipcDriver->resourceBuffers.GetPtr() + IPC_NUM_RESOURCE_BUFFERS));
IPCResourceBuffer* res = descriptor->resourcePtr;
IPCCommandBody& cmdBody = res->commandBody;
descriptor->IsAllocated = 1;
descriptor->asyncMsgQueue = asyncMessageQueue;
descriptor->asyncResultFunc = asyncResultFunc;
descriptor->asyncResultUserParam = asyncResultUserParam;
cmdBody.cmdId = cmdId;
cmdBody.ukn0C = 0;
cmdBody.ukn14 = 0;
cmdBody.result = 0;
cmdBody.devHandle = devHandle;
return descriptor;
}
void IPCDriver_ReleaseResource(IPCDriver* ipcDriver, IPCResourceBufferDescriptor* requestDescriptor)
{
requestDescriptor->IsAllocated = 0;
ipcDriver->fifoFreeBuffers.Push(requestDescriptor);
}
/* IPC threads */
SysAllocator<OSThread_t, Espresso::CORE_COUNT> gIPCThread;
SysAllocator<uint8, 0x4000 * Espresso::CORE_COUNT> _gIPCThreadStack;
SysAllocator<uint8, 0x18 * Espresso::CORE_COUNT> _gIPCThreadNameStorage;
SysAllocator<OSMessageQueue, Espresso::CORE_COUNT> gIPCThreadMsgQueue;
SysAllocator<OSMessage, Espresso::CORE_COUNT * IPC_NUM_RESOURCE_BUFFERS> _gIPCThreadSemaphoreStorage;
// handler thread for asynchronous callbacks for IPC responses
void __IPCDriverThreadFunc(PPCInterpreter_t* hCPU)
{
uint32 coreIndex = OSGetCoreId();
while (true)
{
OSMessage msg;
OSReceiveMessage(gIPCThreadMsgQueue.GetPtr() + coreIndex, &msg, OS_MESSAGE_BLOCK);
cemu_assert(msg.data2 == 1); // type must be callback
MEMPTR<void> cbFunc{ msg.message };
cemu_assert(cbFunc != nullptr);
PPCCoreCallback(cbFunc.GetPtr(), (uint32)msg.data0, (uint32)msg.data1);
}
osLib_returnFromFunction(hCPU, 0);
}
void IPCDriver_InitIPCThread(uint32 coreIndex)
{
// create a thread with 0x4000 stack space
// and a message queue large enough to hold the maximum number of commands (IPC_NUM_RESOURCE_BUFFERS)
OSInitMessageQueue(gIPCThreadMsgQueue.GetPtr() + coreIndex, _gIPCThreadSemaphoreStorage.GetPtr() + coreIndex * IPC_NUM_RESOURCE_BUFFERS, IPC_NUM_RESOURCE_BUFFERS);
OSThread_t* ipcThread = gIPCThread.GetPtr() + coreIndex;
__OSCreateThreadType(ipcThread, PPCInterpreter_makeCallableExportDepr(__IPCDriverThreadFunc), 0, nullptr, _gIPCThreadStack.GetPtr() + 0x4000 * coreIndex + 0x4000, 0x4000, 15, (1 << coreIndex), OSThread_t::THREAD_TYPE::TYPE_DRIVER);
sprintf((char*)_gIPCThreadNameStorage.GetPtr()+coreIndex*0x18, "{SYS IPC Core %d}", coreIndex);
OSSetThreadName(ipcThread, (char*)_gIPCThreadNameStorage.GetPtr() + coreIndex * 0x18);
OSResumeThread(ipcThread);
}
/* coreinit IOS_* API */
void _IPCDriver_SubmitCmdAllQueued(IPCDriver& ipcDriver)
{
// on COS, submitted commands first go to the COS kernel via syscall 0x2000, where they are processed, copied and queued again
// we skip all of this and just pass our IPC commands directly to the IOSU kernel handler HLE function
// important: IOSU needs to know which PPC core sent the command, so that it can also notify the same core about the result
ipcDriver.state = IPCDriverState::SUBMITTING;
while (true)
{
IPCResourceBufferDescriptor* res = ipcDriver.fifoBuffersInFlight.Pop();
if (!res)
break;
// resolve pointers
switch (res->resourcePtr->commandBody.cmdId)
{
case IPCCommandId::IOS_OPEN:
res->resourcePtr->commandBody.args[0] = res->resourcePtr->commandBody.ppcVirt0.GetMPTR();
break;
case IPCCommandId::IOS_CLOSE:
break;
case IPCCommandId::IOS_IOCTL:
res->resourcePtr->commandBody.args[1] = res->resourcePtr->commandBody.ppcVirt0.GetMPTR();
res->resourcePtr->commandBody.args[3] = res->resourcePtr->commandBody.ppcVirt1.GetMPTR();
break;
case IPCCommandId::IOS_IOCTLV:
res->resourcePtr->commandBody.args[3] = res->resourcePtr->commandBody.ppcVirt0.GetMPTR();
break;
default:
cemu_assert_unimplemented();
break;
}
iosu::kernel::IPCSubmitFromCOS(ipcDriver.coreIndex, &res->resourcePtr->commandBody);
}
ipcDriver.state = IPCDriverState::READY;
}
void _IPCDriver_SubmitCmd(IPCDriver& ipcDriver, IPCResourceBufferDescriptor* requestDescriptor)
{
if (requestDescriptor->asyncResultFunc == nullptr)
OSInitEvent(&requestDescriptor->eventSynchronousIPC, OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, OSEvent::EVENT_MODE::MODE_AUTO);
ipcDriver.fifoBuffersInFlight.Push(requestDescriptor);
cemu_assert_debug(ipcDriver.state == IPCDriverState::READY || ipcDriver.state == IPCDriverState::INITIALIZED);
_IPCDriver_SubmitCmdAllQueued(ipcDriver);
}
uint32 _IPCDriver_WaitForResultAndRelease(IPCDriver& ipcDriver, IPCResourceBufferDescriptor* requestDescriptor)
{
OSWaitEvent(&requestDescriptor->eventSynchronousIPC);
uint32 r = requestDescriptor->resourcePtr->commandBody.result;
IPCDriver_ReleaseResource(&ipcDriver, requestDescriptor);
return r;
}
void IPCDriver_HandleResponse(IPCDriver& ipcDriver, IPCCommandBody* res, uint32 ppcCoreIndex)
{
size_t index = (IPCResourceBuffer*)res - ipcDriver.resourceBuffers.GetPtr();
cemu_assert(index < IPC_NUM_RESOURCE_BUFFERS);
IPCResourceBufferDescriptor* descriptor = ipcDriver.resBufferDescriptor + index;
cemu_assert(descriptor->IsAllocated != 0);
if (descriptor->asyncMsgQueue != nullptr)
{
OSMessage msg;
msg.message = 0;
msg.data0 = res->result;
msg.data1 = descriptor->asyncResultUserParam.GetMPTR();
msg.data2 = 0;
sint32 r = OSSendMessage(descriptor->asyncMsgQueue.GetPtr(), &msg, 0);
cemu_assert(r != 0);
IPCDriver_ReleaseResource(&ipcDriver, descriptor);
return;
}
if (descriptor->asyncResultFunc != nullptr)
{
OSMessage msg;
msg.message = descriptor->asyncResultFunc.GetMPTR();
msg.data0 = res->result;
msg.data1 = descriptor->asyncResultUserParam.GetMPTR();
msg.data2 = 1;
sint32 r = OSSendMessage(gIPCThreadMsgQueue.GetPtr() + ppcCoreIndex, &msg, 0);
cemu_assert(r != 0);
IPCDriver_ReleaseResource(&ipcDriver, descriptor);
return;
}
// signal event for synchronous IPC
OSSignalEvent(&descriptor->eventSynchronousIPC);
}
// handles responses queued in shared region
void IPCDriver_KernelCallback(IPCDriver& ipcDriver)
{
cemu_assert_debug(ipcDriver.kernelSharedArea.numAvailableResponses != 0);
for (uint32 i = 0; i < ipcDriver.kernelSharedArea.numAvailableResponses; i++)
IPCDriver_HandleResponse(ipcDriver, ipcDriver.kernelSharedArea.responseArray[i], ipcDriver.coreIndex);
ipcDriver.kernelSharedArea.numAvailableResponses = 0;
}
// called by our HLE'd IOSU directly
void IPCDriver_NotifyResponses(uint32 ppcCoreIndex, IPCCommandBody** responseArray, uint32 numResponses)
{
cemu_assert(numResponses < 11);
IPCDriver& ipcDriver = IPCDriver_GetByCore(ppcCoreIndex);
ipcDriver.kernelSharedArea.numAvailableResponses = numResponses;
for (uint32 i = 0; i < numResponses; i++)
ipcDriver.kernelSharedArea.responseArray[i] = responseArray[i];
IPCDriver_KernelCallback(ipcDriver);
}
void _IPCDriver_SetupCmd_IOSOpen(IPCDriver& ipcDriver, IPCResourceBufferDescriptor* requestDescriptor, const char* devicePath, uint32 flags)
{
// store the path in the buffer after the command body
IPCResourceBuffer* resBuffer = requestDescriptor->resourcePtr;
IPCCommandBody& cmdBody = resBuffer->commandBody;
uint8* buffer = resBuffer->bufferData;
size_t pathLen = strlen(devicePath);
if (pathLen > 31)
{
cemuLog_log(LogType::Force, "IOS_Open(): Device path must not exceed 31 characters");
cemu_assert_error();
}
memcpy(buffer, devicePath, pathLen + 1);
cmdBody.ppcVirt0 = MEMPTR<void>(buffer).GetMPTR();
cmdBody.args[0] = 0;
cmdBody.args[1] = (uint32)(pathLen + 1);
cmdBody.args[2] = flags;
}
IOS_ERROR _IPCDriver_SetupCmd_IOSIoctl(IPCDriver& ipcDriver, IPCResourceBufferDescriptor* requestDescriptor, uint32 requestId, void* ptrIn, uint32 sizeIn, void* ptrOut, uint32 sizeOut)
{
IPCCommandBody& cmdBody = requestDescriptor->resourcePtr->commandBody;
cmdBody.args[0] = requestId;
cmdBody.args[1] = MPTR_NULL; // set to ppcVirt0 later
cmdBody.args[2] = sizeIn;
cmdBody.args[3] = MPTR_NULL; // set to ppcVirt1 later
cmdBody.args[4] = sizeOut;
cmdBody.ppcVirt0 = MEMPTR<void>(ptrIn).GetMPTR();
cmdBody.ppcVirt1 = MEMPTR<void>(ptrOut).GetMPTR();
return IOS_ERROR_OK;
}
IOS_ERROR _IPCDriver_SetupCmd_IOSIoctlv(IPCDriver& ipcDriver, IPCResourceBufferDescriptor* requestDescriptor, uint32 requestId, uint32 numIn, uint32 numOut, IPCIoctlVector* vec)
{
IPCCommandBody& cmdBody = requestDescriptor->resourcePtr->commandBody;
// set args
cmdBody.ppcVirt0 = MEMPTR<void>(vec).GetMPTR();
cmdBody.args[0] = requestId;
cmdBody.args[1] = numIn;
cmdBody.args[2] = numOut;
cmdBody.args[3] = 0; // set to ppcVirt0 later
return IOS_ERROR_OK;
}
IOSDevHandle IOS_Open(const char* devicePath, uint32 flags)
{
IPCDriver& ipcDriver = IPCDriver_GetByCore(OSGetCoreId());
IPCResourceBufferDescriptor* ipcDescriptor = IPCDriver_AllocateResource(&ipcDriver, 0, IPCCommandId::IOS_OPEN, nullptr, nullptr, nullptr);
_IPCDriver_SetupCmd_IOSOpen(ipcDriver, ipcDescriptor, devicePath, flags);
_IPCDriver_SubmitCmd(ipcDriver, ipcDescriptor);
uint32 r = _IPCDriver_WaitForResultAndRelease(ipcDriver, ipcDescriptor);
return r;
}
IOS_ERROR IOS_Close(IOSDevHandle devHandle)
{
IPCDriver& ipcDriver = IPCDriver_GetByCore(OSGetCoreId());
IPCResourceBufferDescriptor* ipcDescriptor = IPCDriver_AllocateResource(&ipcDriver, devHandle, IPCCommandId::IOS_CLOSE, nullptr, nullptr, nullptr);
_IPCDriver_SubmitCmd(ipcDriver, ipcDescriptor);
IOS_ERROR r = (IOS_ERROR)_IPCDriver_WaitForResultAndRelease(ipcDriver, ipcDescriptor);
return r;
}
IOS_ERROR IOS_Ioctl(IOSDevHandle devHandle, uint32 requestId, void* ptrIn, uint32 sizeIn, void* ptrOut, uint32 sizeOut)
{
IPCDriver& ipcDriver = IPCDriver_GetByCore(OSGetCoreId());
IPCResourceBufferDescriptor* ipcDescriptor = IPCDriver_AllocateResource(&ipcDriver, devHandle, IPCCommandId::IOS_IOCTL, nullptr, nullptr, nullptr);
IOS_ERROR r = _IPCDriver_SetupCmd_IOSIoctl(ipcDriver, ipcDescriptor, requestId, ptrIn, sizeIn, ptrOut, sizeOut);
if (r != IOS_ERROR_OK)
{
cemuLog_log(LogType::Force, "IOS_Ioctl failed due to bad parameters");
IPCDriver_ReleaseResource(&ipcDriver, ipcDescriptor);
return r;
}
_IPCDriver_SubmitCmd(ipcDriver, ipcDescriptor);
r = (IOS_ERROR)_IPCDriver_WaitForResultAndRelease(ipcDriver, ipcDescriptor);
return r;
}
IOS_ERROR IOS_IoctlAsync(IOSDevHandle devHandle, uint32 requestId, void* ptrIn, uint32 sizeIn, void* ptrOut, uint32 sizeOut, MEMPTR<void> asyncResultFunc, MEMPTR<void> asyncResultUserParam)
{
IPCDriver& ipcDriver = IPCDriver_GetByCore(OSGetCoreId());
IPCResourceBufferDescriptor* ipcDescriptor = IPCDriver_AllocateResource(&ipcDriver, devHandle, IPCCommandId::IOS_IOCTL, nullptr, asyncResultFunc, asyncResultUserParam);
IOS_ERROR r = _IPCDriver_SetupCmd_IOSIoctl(ipcDriver, ipcDescriptor, requestId, ptrIn, sizeIn, ptrOut, sizeOut);
if (r != IOS_ERROR_OK)
{
cemuLog_log(LogType::Force, "IOS_Ioctl failed due to bad parameters");
IPCDriver_ReleaseResource(&ipcDriver, ipcDescriptor);
return r;
}
_IPCDriver_SubmitCmd(ipcDriver, ipcDescriptor);
return r;
}
IOS_ERROR IOS_Ioctlv(IOSDevHandle devHandle, uint32 requestId, uint32 numIn, uint32 numOut, IPCIoctlVector* vec)
{
IPCDriver& ipcDriver = IPCDriver_GetByCore(OSGetCoreId());
IPCResourceBufferDescriptor* ipcDescriptor = IPCDriver_AllocateResource(&ipcDriver, devHandle, IPCCommandId::IOS_IOCTLV, nullptr, nullptr, nullptr);
IOS_ERROR r = _IPCDriver_SetupCmd_IOSIoctlv(ipcDriver, ipcDescriptor, requestId, numIn, numOut, vec);
if (r != IOS_ERROR_OK)
{
cemuLog_log(LogType::Force, "IOS_Ioctlv failed due to bad parameters");
IPCDriver_ReleaseResource(&ipcDriver, ipcDescriptor);
return r;
}
_IPCDriver_SubmitCmd(ipcDriver, ipcDescriptor);
r = (IOS_ERROR)_IPCDriver_WaitForResultAndRelease(ipcDriver, ipcDescriptor);
return r;
}
IOS_ERROR IOS_IoctlvAsync(IOSDevHandle devHandle, uint32 requestId, uint32 numIn, uint32 numOut, IPCIoctlVector* vec, MEMPTR<void> asyncResultFunc, MEMPTR<void> asyncResultUserParam)
{
IPCDriver& ipcDriver = IPCDriver_GetByCore(OSGetCoreId());
IPCResourceBufferDescriptor* ipcDescriptor = IPCDriver_AllocateResource(&ipcDriver, devHandle, IPCCommandId::IOS_IOCTLV, nullptr, asyncResultFunc, asyncResultUserParam);
IOS_ERROR r = _IPCDriver_SetupCmd_IOSIoctlv(ipcDriver, ipcDescriptor, requestId, numIn, numOut, vec);
if (r != IOS_ERROR_OK)
{
cemuLog_log(LogType::Force, "IOS_Ioctlv failed due to bad parameters");
IPCDriver_ReleaseResource(&ipcDriver, ipcDescriptor);
return r;
}
_IPCDriver_SubmitCmd(ipcDriver, ipcDescriptor);
return r;
}
void InitializeIPC()
{
for (uint32 i = 0; i < Espresso::CORE_COUNT; i++)
{
IPCDriver_InitForCore(i);
IPCDriver_InitIPCThread(i);
}
// register API
cafeExportRegister("coreinit", IOS_Open, LogType::PPC_IPC);
cafeExportRegister("coreinit", IOS_Close, LogType::PPC_IPC);
cafeExportRegister("coreinit", IOS_Ioctl, LogType::PPC_IPC);
cafeExportRegister("coreinit", IOS_IoctlAsync, LogType::PPC_IPC);
cafeExportRegister("coreinit", IOS_Ioctlv, LogType::PPC_IPC);
cafeExportRegister("coreinit", IOS_IoctlvAsync, LogType::PPC_IPC);
}
};
| 18,550
|
C++
|
.cpp
| 416
| 41.451923
| 233
| 0.770171
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,105
|
coreinit_OSScreen.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_OSScreen.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/gx2/GX2.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/OS/libs/coreinit/coreinit_OSScreen_font.h"
#include "Cafe/OS/libs/coreinit/coreinit_OSScreen.h"
#define OSSCREEN_TV (0)
#define OSSCREEN_DRC (1)
namespace coreinit
{
struct
{
sint32 x;
sint32 y;
sint32 pitch;
}screenSizes[2] =
{
{ 1280, 720, 1280}, // TV
{ 896, 480, 896 } // DRC (values might be incorrect)
};
void* currentScreenBasePtr[2] = { 0 };
void _OSScreen_Clear(uint32 screenIndex, uint32 color)
{
if (!currentScreenBasePtr[screenIndex])
return;
uint32* output = (uint32*)currentScreenBasePtr[screenIndex];
sint32 sizeInPixels = screenSizes[screenIndex].pitch * screenSizes[screenIndex].y;
color = _swapEndianU32(color);
for (sint32 i = 0; i < sizeInPixels; i++)
{
*output = color;
output++;
}
}
void coreinitExport_OSScreenInit(PPCInterpreter_t* hCPU)
{
// todo - init VI registers?
osLib_returnFromFunction(hCPU, 0);
}
void coreinitExport_OSScreenGetBufferSizeEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(screenIndex, 0);
cemu_assert(screenIndex < 2);
uint32 bufferSize = screenSizes[screenIndex].pitch * screenSizes[screenIndex].y * 4 * 2;
osLib_returnFromFunction(hCPU, bufferSize);
}
void _updateCurrentDrawScreen(sint32 screenIndex)
{
uint32 screenDataSize = screenSizes[screenIndex].pitch * screenSizes[screenIndex].y * 4;
if ((LatteGPUState.osScreen.screen[screenIndex].flipRequestCount & 1) != 0)
currentScreenBasePtr[screenIndex] = memory_getPointerFromPhysicalOffset(LatteGPUState.osScreen.screen[screenIndex].physPtr + screenDataSize);
else
currentScreenBasePtr[screenIndex] = memory_getPointerFromPhysicalOffset(LatteGPUState.osScreen.screen[screenIndex].physPtr);
}
void coreinitExport_OSScreenSetBufferEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(screenIndex, 0);
ppcDefineParamU32(buffer, 1);
cemu_assert(screenIndex < 2);
LatteGPUState.osScreen.screen[screenIndex].physPtr = buffer;
_updateCurrentDrawScreen(screenIndex);
osLib_returnFromFunction(hCPU, 0);
}
void coreinitExport_OSScreenEnableEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(screenIndex, 0);
ppcDefineParamU32(isEnabled, 1);
cemu_assert(screenIndex < 2);
LatteGPUState.osScreen.screen[screenIndex].isEnabled = isEnabled != 0;
osLib_returnFromFunction(hCPU, 0);
}
void coreinitExport_OSScreenClearBufferEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(screenIndex, 0);
ppcDefineParamU32(color, 1);
cemu_assert(screenIndex < 2);
_OSScreen_Clear(screenIndex, color);
osLib_returnFromFunction(hCPU, 0);
}
void coreinitExport_OSScreenFlipBuffersEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(screenIndex, 0);
cemu_assert(screenIndex < 2);
cemuLog_logDebug(LogType::Force, "OSScreenFlipBuffersEx {}", screenIndex);
LatteGPUState.osScreen.screen[screenIndex].flipRequestCount++;
_updateCurrentDrawScreen(screenIndex);
osLib_returnFromFunction(hCPU, 0);
}
void coreinitExport_OSScreenPutPixelEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(screenIndex, 0);
ppcDefineParamS32(x, 1);
ppcDefineParamS32(y, 2);
ppcDefineParamU32(color, 3);
if (screenIndex >= 2)
{
osLib_returnFromFunction(hCPU, 0);
return;
}
if (x >= 0 && x < screenSizes[screenIndex].x && y >= 0 && y < screenSizes[screenIndex].y)
{
*(uint32*)((uint8*)currentScreenBasePtr[screenIndex] + (x + y * screenSizes[screenIndex].pitch) * 4) = _swapEndianS32(color);
}
osLib_returnFromFunction(hCPU, 0);
}
const char* osScreenCharset = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
sint32 _getOSScreenFontCharIndex(char c)
{
const char* charset = osScreenCharset;
while (*charset)
{
if (*charset == c)
{
return (sint32)(charset - osScreenCharset);
}
charset++;
}
return -1;
}
void coreinitExport_OSScreenPutFontEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(screenIndex, 0);
ppcDefineParamS32(x, 1);
ppcDefineParamS32(y, 2);
ppcDefineParamStr(str, 3);
// characters are:
// 16 x 32 (including the margin)
// with a margin of 4 x 8
if (y < 0)
{
debug_printf("OSScreenPutFontEx: y has invalid value\n");
osLib_returnFromFunction(hCPU, 0);
return;
}
sint32 px = x * 16;
sint32 py = y * 24;
while (*str)
{
sint32 charIndex = _getOSScreenFontCharIndex(*str);
if (charIndex >= 0)
{
const uint8* charBitmap = osscreenBitmapFont + charIndex * 50;
for (sint32 fy = 0; fy < 25; fy++)
{
for (sint32 fx = 0; fx < 14; fx++)
{
if (((charBitmap[(fx / 8) + (fy) * 2] >> (7 - (fx & 7))) & 1) == 0)
continue;
*(uint32*)((uint8*)currentScreenBasePtr[screenIndex] + ((px + fx) + (py + fy) * screenSizes[screenIndex].pitch) * 4) = 0xFFFFFFFF;
}
}
}
px += 16;
str++;
}
osLib_returnFromFunction(hCPU, 0);
}
void InitializeOSScreen()
{
osLib_addFunction("coreinit", "OSScreenInit", coreinitExport_OSScreenInit);
osLib_addFunction("coreinit", "OSScreenGetBufferSizeEx", coreinitExport_OSScreenGetBufferSizeEx);
osLib_addFunction("coreinit", "OSScreenSetBufferEx", coreinitExport_OSScreenSetBufferEx);
osLib_addFunction("coreinit", "OSScreenEnableEx", coreinitExport_OSScreenEnableEx);
osLib_addFunction("coreinit", "OSScreenClearBufferEx", coreinitExport_OSScreenClearBufferEx);
osLib_addFunction("coreinit", "OSScreenFlipBuffersEx", coreinitExport_OSScreenFlipBuffersEx);
osLib_addFunction("coreinit", "OSScreenPutPixelEx", coreinitExport_OSScreenPutPixelEx);
osLib_addFunction("coreinit", "OSScreenPutFontEx", coreinitExport_OSScreenPutFontEx);
}
}
| 5,696
|
C++
|
.cpp
| 168
| 30.815476
| 144
| 0.73887
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,106
|
coreinit_Memory.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_Memory.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "coreinit_Memory.h"
#include "Cafe/HW/Latte/Core/LatteBufferCache.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/GraphicPack/GraphicPack2.h"
#include "Cafe/CafeSystem.h"
namespace coreinit
{
void DCInvalidateRange(MPTR addr, uint32 size)
{
MPTR addrEnd = (addr + size + 0x1F) & ~0x1F;
addr &= ~0x1F;
//LatteBufferCache_notifyDCFlush(addr, addrEnd - addr);
}
void DCFlushRange(MPTR addr, uint32 size)
{
MPTR addrEnd = (addr + size + 0x1F) & ~0x1F;
addr &= ~0x1F;
LatteBufferCache_notifyDCFlush(addr, addrEnd - addr);
}
void DCFlushRangeNoSync(MPTR addr, uint32 size)
{
MPTR addrEnd = (addr + size + 0x1F) & ~0x1F;
addr &= ~0x1F;
LatteBufferCache_notifyDCFlush(addr, addrEnd - addr);
}
void DCStoreRange(MPTR addr, uint32 size)
{
MPTR addrEnd = (addr + size + 0x1F) & ~0x1F;
addr &= ~0x1F;
//LatteBufferCache_notifyDCFlush(addr, addrEnd - addr);
}
void DCStoreRangeNoSync(MPTR addr, uint32 size)
{
MPTR addrEnd = (addr + size + 0x1F) & ~0x1F;
addr &= ~0x1F;
LatteBufferCache_notifyDCFlush(addr, addrEnd - addr);
}
void DCZeroRange(MPTR addr, uint32 size)
{
MPTR alignedAddr = addr & ~31;
uint32 cachlineOffset = addr & 31;
uint32 blocks = (cachlineOffset + size + 31) / 32;
if (blocks > 0)
{
memset(memory_getPointerFromVirtualOffset(alignedAddr), 0x00, blocks * 32);
LatteBufferCache_notifyDCFlush(alignedAddr, blocks * 32);
}
}
bool OSIsAddressRangeDCValid(uint32 startOffset, uint32 range)
{
uint32 endOffset = startOffset + range - 1;
uint32 boundaryLow = 0xE8000000;
uint32 boundaryHigh = 0xEC000000;
if (startOffset < boundaryLow || startOffset >= boundaryHigh)
return false;
if (endOffset < boundaryLow || endOffset >= boundaryHigh)
return false;
return true;
}
void* coreinit_memset(void* dst, uint32 value, uint32 size)
{
memset(dst, value, size);
return dst;
}
void* coreinit_memcpy(MEMPTR<void> dst, MEMPTR<void> src, uint32 size)
{
if (dst.GetMPTR() == 0xFFFFFFFF)
{
// games this was seen in: The Swapper
// this may be a bug in the game. The last few bytes of the address space are writable, but wrap-around behavior of COS memcpy is unknown
cemu_assert_debug(false);
}
if (size > 0)
{
memcpy(dst.GetPtr(), src.GetPtr(), size);
// always flushes the cache!
LatteBufferCache_notifyDCFlush(dst.GetMPTR(), size);
}
return dst.GetPtr();
}
void* coreinit_memmove(MEMPTR<void> dst, void* src, uint32 size)
{
if (size > 0)
{
memmove(dst.GetPtr(), src, size);
// always flushes the cache!
LatteBufferCache_notifyDCFlush(dst.GetMPTR(), size);
}
return dst.GetPtr();
}
void* OSBlockMove(MEMPTR<void> dst, MEMPTR<void> src, uint32 size, bool flushDC)
{
if (size > 0)
{
memmove(dst.GetPtr(), src.GetPtr(), size);
if (flushDC)
LatteBufferCache_notifyDCFlush(dst.GetMPTR(), size);
}
return dst.GetPtr();
}
void* OSBlockSet(MEMPTR<void> dst, uint32 value, uint32 size)
{
memset(dst.GetPtr(), value&0xFF, size);
return dst.GetPtr();
}
MPTR OSEffectiveToPhysical(MPTR effectiveAddr)
{
MPTR physicalAddr = memory_virtualToPhysical(effectiveAddr);
return physicalAddr;
}
void OSMemoryBarrier()
{
// no-op
}
void OSGetMemBound(sint32 memType, MEMPTR<void>* offsetOutput, uint32be* sizeOutput)
{
MPTR memAddr = MPTR_NULL;
uint32 memSize = 0;
/*
Data taken from browser dump:
type start size
MEM1 0xF4000000 0x02000000
MEM2 0x106DE000 0x170C2000
*/
if (memType == 1)
{
// MEM1
memAddr = mmuRange_MEM1.getBase();
memSize = mmuRange_MEM1.getSize();
}
else if (memType == 2)
{
// MEM2
uint32 currentRPLAllocatorOffset = RPLLoader_GetDataAllocatorAddr();
// due to differences in our library implementations we currently allocate less memory for the OS/RPLs than on the actual hardware,
// as a result more memory is available to games
// however, some games crash due to internal overflows if there is too much memory available
// here we artificially reduce the available memory for the affected games
uint64 titleId = CafeSystem::GetForegroundTitleId();
if (
titleId == 0x0005000010132400ULL || // Lego Marvel Super Heroes (EU)
titleId == 0x0005000010132B00ULL || // Lego Marvel Super Heroes (US)
titleId == 0x0005000010194200ull || // Lego Dimensions (US)
titleId == 0x0005000010195D00ull || // Lego Dimensions (EU)
titleId == 0x00050000101A6200ull || // Lego Jurassic World (US)
titleId == 0x00050000101A5C00 || // Lego Jurassic World (EU)
titleId == 0x000500001014DE00 || // The Lego Movie Videogame (US)
titleId == 0x000500001014E000 || // The Lego Movie Videogame (EU)
titleId == 0x0005000010168D00 || // Lego The Hobbit (EU)
titleId == 0x000500001016A700 || // Lego The Hobbit (JP)
// The Hobbit US title id?
titleId == 0x00050000101DAB00 || // Lego Star Wars: The Force Awakens (US)
titleId == 0x00050000101DAA00 || // Lego Star Wars: The Force Awakens (EU)
// LEGO Batman 3: BEYOND GOTHAM
titleId == 0x000500001016A400 || // EU
titleId == 0x000500001016AD00 || // US
// Lego Marvel Avengers
titleId == 0x00050000101BE900 || // EU
titleId == 0x00050000101BEF00 || // US
// LEGO BATMAN 2: DC Super Heroes
titleId == 0x0005000010135500 || // EU
titleId == 0x0005000010135E00 // US
)
{
cemuLog_logDebug(LogType::Force, "Hack: Reduce available memory to simulate loaded RPLs");
currentRPLAllocatorOffset += (48 * 1024 * 1024); // 48MB
}
memAddr = currentRPLAllocatorOffset;
memSize = mmuRange_MEM2.getEnd() - currentRPLAllocatorOffset;
}
else
{
cemu_assert_debug(false);
}
if (offsetOutput)
*offsetOutput = memAddr;
if (sizeOutput)
*sizeOutput = memSize;
}
void InitializeMemory()
{
cafeExportRegister("coreinit", DCInvalidateRange, LogType::Placeholder);
cafeExportRegister("coreinit", DCFlushRange, LogType::Placeholder);
cafeExportRegister("coreinit", DCFlushRangeNoSync, LogType::Placeholder);
cafeExportRegister("coreinit", DCStoreRange, LogType::Placeholder);
cafeExportRegister("coreinit", DCStoreRangeNoSync, LogType::Placeholder);
cafeExportRegister("coreinit", DCZeroRange, LogType::Placeholder);
cafeExportRegister("coreinit", OSIsAddressRangeDCValid, LogType::Placeholder);
cafeExportRegisterFunc(coreinit_memcpy, "coreinit", "memcpy", LogType::Placeholder);
cafeExportRegisterFunc(coreinit_memset, "coreinit", "memset", LogType::Placeholder);
cafeExportRegisterFunc(coreinit_memmove, "coreinit", "memmove", LogType::Placeholder);
cafeExportRegister("coreinit", OSBlockMove, LogType::Placeholder);
cafeExportRegister("coreinit", OSBlockSet, LogType::Placeholder);
cafeExportRegister("coreinit", OSEffectiveToPhysical, LogType::Placeholder);
cafeExportRegister("coreinit", OSMemoryBarrier, LogType::Placeholder);
cafeExportRegister("coreinit", OSGetMemBound, LogType::Placeholder);
}
}
| 6,985
|
C++
|
.cpp
| 199
| 31.859296
| 140
| 0.726036
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,107
|
coreinit_MEM_ExpHeap.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_MEM_ExpHeap.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM_ExpHeap.h"
#define EXP_HEAP_GET_FROM_FREE_BLOCKCHAIN(__blockchain__) (MEMExpHeapHead2*)((uintptr_t)__blockchain__ - offsetof(MEMExpHeapHead2, expHeapHead) - offsetof(MEMExpHeapHead40_t, chainFreeBlocks))
namespace coreinit
{
#define MBLOCK_TYPE_FREE ('FR')
#define MBLOCK_TYPE_USED ('UD')
struct MBlock2_t
{
uint32be fields; // 0x00
uint32be dataSize; // 0x04 | size of raw data (excluding size of this struct)
MEMPTR<MBlock2_t> prevBlock; // 0x08
MEMPTR<MBlock2_t> nextBlock; // 0x0C
uint16be typeCode; // 0x10
uint16be padding; // 0x12
};
static_assert(sizeof(MBlock2_t) == 0x14);
struct ExpMemBlockRegion
{
uintptr_t start;
uintptr_t end;
};
#define MBLOCK_GET_HEADER(__mblock__) (MBlock2_t*)((uintptr_t)__mblock__ - sizeof(MBlock2_t))
#define MBLOCK_GET_MEMORY(__mblock__) ((uintptr_t)__mblock__ + sizeof(MBlock2_t))
#define MBLOCK_GET_END(__mblock__) ((uintptr_t)__mblock__ + sizeof(MBlock2_t) + (uint32)__mblock__->dataSize)
#pragma region internal
MBlock2_t* _MEMExpHeap_InitMBlock(ExpMemBlockRegion* region, uint16 typeCode)
{
MBlock2_t* mBlock = (MBlock2_t*)region->start;
memset(mBlock, 0x00, sizeof(MBlock2_t));
mBlock->typeCode = typeCode;
mBlock->dataSize = (uint32)(region->end - (region->start + sizeof(MBlock2_t)));
return mBlock;
}
bool _MEMExpHeap_CheckMBlock(MBlock2_t* mBlock, MEMHeapHandle heap, uint16 typeCode, const char* debugText, int options)
{
#ifndef MBLOCK_DEBUG_ASSERT
return true;
#endif
const uintptr_t mBlockAddr = (uintptr_t)mBlock;
const uintptr_t mBlockRawAddr = MBLOCK_GET_MEMORY(mBlock);
uintptr_t heapStart = 0, heapEnd = 0;
if (heap)
{
heapStart = (uintptr_t)heap->heapStart.GetPtr();
heapEnd = (uintptr_t)heap->heapEnd.GetPtr();
if (heap == MEM_HEAP_INVALID_HANDLE)
{
if (mBlockAddr < heapStart || mBlockRawAddr > heapEnd)
{
return false;
}
}
}
if (typeCode == (uint16)mBlock->typeCode)
{
if (heap == MEM_HEAP_INVALID_HANDLE)
return true;
const uint32 dataSize = mBlock->dataSize;
if (mBlockRawAddr + dataSize <= heapEnd)
return true;
return false;
}
return false;
}
bool _MEMExpHeap_IsValidUsedMBlock(const void* memBlock, MEMHeapHandle heap)
{
#ifndef MBLOCK_DEBUG_ASSERT
return true;
#endif
if (!memBlock)
return false;
heap->AcquireLock();
bool valid = false;
MBlock2_t* mBlock = MBLOCK_GET_HEADER(memBlock);
if (heap)
{
MEMExpHeapHead2* expHeap = (MEMExpHeapHead2*)heap;
MEMPTR<MBlock2_t> usedBlock = expHeap->expHeapHead.chainUsedBlocks.headMBlock;
while (usedBlock)
{
if (mBlock == usedBlock.GetPtr())
{
valid = _MEMExpHeap_CheckMBlock(mBlock, heap, MBLOCK_TYPE_USED, "used", 0);
break;
}
usedBlock = usedBlock->nextBlock;
}
}
else
{
valid = _MEMExpHeap_CheckMBlock(mBlock, heap, MBLOCK_TYPE_USED, "used", 0);
}
heap->ReleaseLock();
return valid;
}
void _MEMExpHeap_GetRegionOfMBlock(ExpMemBlockRegion* region, MBlock2_t* memBlock)
{
uint32 alignment = ((memBlock->fields) >> 8) & 0x7FFFFF;
uintptr_t memBlockAddr = (uintptr_t)memBlock;
region->start = memBlockAddr - alignment;
region->end = memBlockAddr + sizeof(MBlock2_t) + (uint32)memBlock->dataSize;
}
void* _MEMExpHeap_RemoveMBlock(MBlockChain2_t* blockChain, MBlock2_t* block)
{
MEMPTR<MBlock2_t> prevBlock = block->prevBlock;
MEMPTR<MBlock2_t> nextBlock = block->nextBlock;
if (prevBlock)
prevBlock->nextBlock = nextBlock;
else
blockChain->headMBlock = nextBlock;
if (nextBlock)
nextBlock->prevBlock = prevBlock;
else
blockChain->tailMBlock = prevBlock;
return prevBlock.GetPtr();
}
MBlock2_t* _MEMExpHeap_InsertMBlock(MBlockChain2_t* blockChain, MBlock2_t* newBlock, MBlock2_t* prevBlock)
{
newBlock->prevBlock = prevBlock;
MEMPTR<MBlock2_t> nextBlock;
if (prevBlock)
{
nextBlock = prevBlock->nextBlock;
prevBlock->nextBlock = newBlock;
}
else
{
nextBlock = blockChain->headMBlock;
blockChain->headMBlock = newBlock;
}
newBlock->nextBlock = nextBlock;
if (nextBlock)
nextBlock->prevBlock = newBlock;
else
blockChain->tailMBlock = newBlock;
return newBlock;
}
bool _MEMExpHeap_RecycleRegion(MBlockChain2_t* blockChain, ExpMemBlockRegion* region)
{
ExpMemBlockRegion newRegion;
newRegion.start = region->start;
newRegion.end = region->end;
MEMPTR<MBlock2_t> prev;
MEMPTR<MBlock2_t> find = blockChain->headMBlock;
while (find)
{
MBlock2_t* findMBlock = find.GetPtr();
const uintptr_t blockAddr = (uintptr_t)findMBlock;
if (blockAddr >= region->start)
{
if (blockAddr == region->end)
{
newRegion.end = MBLOCK_GET_END(findMBlock);
_MEMExpHeap_RemoveMBlock(blockChain, findMBlock);
MEMExpHeapHead2* heap = EXP_HEAP_GET_FROM_FREE_BLOCKCHAIN(blockChain);
uint8 options = heap->flags;
if (HAS_FLAG(options, MEM_HEAP_OPTION_FILL))
{
const uint32 fillVal = MEMGetFillValForHeap(HEAP_FILL_TYPE::ON_FREE);
memset(findMBlock, fillVal, sizeof(MBlock2_t));
}
}
break;
}
prev = find;
find = findMBlock->nextBlock;
}
if (prev)
{
MBlock2_t* prevMBlock = prev.GetPtr();
if (MBLOCK_GET_END(prevMBlock) == region->start)
{
newRegion.start = (uintptr_t)prevMBlock;
prev = (MBlock2_t*)_MEMExpHeap_RemoveMBlock(blockChain, prevMBlock);
}
}
if ((newRegion.end - newRegion.start) < sizeof(MBlock2_t))
return false;
MEMExpHeapHead2* heap = EXP_HEAP_GET_FROM_FREE_BLOCKCHAIN(blockChain);
uint8 options = heap->flags;
if (HAS_FLAG(options, MEM_HEAP_OPTION_FILL))
{
const uint32 fillVal = MEMGetFillValForHeap(HEAP_FILL_TYPE::ON_FREE);
memset((void*)region->start, fillVal, region->end - region->start);
}
MBlock2_t* newBlock = _MEMExpHeap_InitMBlock(&newRegion, MBLOCK_TYPE_FREE);
_MEMExpHeap_InsertMBlock(blockChain, newBlock, prev.GetPtr());
return true;
}
void* _MEMExpHeap_AllocUsedBlockFromFreeBlock(MBlockChain2_t* blockChain, MBlock2_t* freeBlock, uintptr_t blockMemStart, uint32 size, MEMExpHeapAllocDirection direction)
{
MEMExpHeapHead2* heap = EXP_HEAP_GET_FROM_FREE_BLOCKCHAIN(blockChain);
ExpMemBlockRegion freeRegion;
_MEMExpHeap_GetRegionOfMBlock(&freeRegion, freeBlock);
ExpMemBlockRegion newRegion = {blockMemStart + size, freeRegion.end};
freeRegion.end = blockMemStart - sizeof(MBlock2_t);
MBlock2_t* prevBlock = (MBlock2_t*)_MEMExpHeap_RemoveMBlock(blockChain, freeBlock);
if ((freeRegion.end - freeRegion.start) >= 0x18 && (direction != MEMExpHeapAllocDirection::HEAD || HAS_FLAG(heap->expHeapHead.fields, MEM_EXPHEAP_USE_ALIGN_MARGIN)))
{
MBlock2_t* newBlock = _MEMExpHeap_InitMBlock(&freeRegion, MBLOCK_TYPE_FREE);
prevBlock = _MEMExpHeap_InsertMBlock(blockChain, newBlock, prevBlock);
}
else
freeRegion.end = freeRegion.start;
if ((newRegion.end - newRegion.start) >= 0x18 && (direction != MEMExpHeapAllocDirection::TAIL || HAS_FLAG(heap->expHeapHead.fields, MEM_EXPHEAP_USE_ALIGN_MARGIN)))
{
MBlock2_t* newBlock = _MEMExpHeap_InitMBlock(&newRegion, MBLOCK_TYPE_FREE);
prevBlock = _MEMExpHeap_InsertMBlock(blockChain, newBlock, prevBlock);
}
else
newRegion.start = newRegion.end;
uint8 options = heap->flags;
if (HAS_FLAG(options, MEM_HEAP_OPTION_CLEAR))
{
memset((void*)freeRegion.end, 0x00, newRegion.start - freeRegion.end);
}
else if (HAS_FLAG(options, MEM_HEAP_OPTION_FILL))
{
const uint32 fillValue = MEMGetFillValForHeap(HEAP_FILL_TYPE::ON_ALLOC);
memset((void*)freeRegion.end, fillValue, newRegion.start - freeRegion.end);
}
ExpMemBlockRegion allocRegion = {blockMemStart - sizeof(MBlock2_t), newRegion.start};
MBlock2_t* newBlock = _MEMExpHeap_InitMBlock(&allocRegion, MBLOCK_TYPE_USED);
uint32 fields = (uint32)newBlock->fields;
if(direction == MEMExpHeapAllocDirection::TAIL)
fields |= 1 << 31;
else
fields &= ~(1 << 31);
uint32 alignmentPadding = (uint32)((uintptr_t)newBlock - (uintptr_t)freeRegion.end);
fields |= (alignmentPadding & 0x7FFFFF) << 8;
fields |= ((uint32)heap->expHeapHead.groupID & 0xFF);
newBlock->fields = fields;
MBlock2_t* tailBlock = heap->expHeapHead.chainUsedBlocks.tailMBlock.GetPtr();
_MEMExpHeap_InsertMBlock(&heap->expHeapHead.chainUsedBlocks, newBlock, tailBlock);
return (void*)blockMemStart;
}
void* _MEMExpHeap_AllocFromTail(MEMHeapHandle heap, uint32 size, int alignment)
{
MEMExpHeapHead2* expHeap = (MEMExpHeapHead2*)heap;
const bool searchForFirstEntry = (expHeap->expHeapHead.fields&1) == MEM_EXPHEAP_ALLOC_MODE_FIRST;
const int alignmentMinusOne = alignment - 1;
MBlock2_t* freeBlock = nullptr;
uintptr_t blockMemStart = 0;
uint32 foundSize = -1;
for (MBlock2_t* findBlock = expHeap->expHeapHead.chainFreeBlocks.tailMBlock.GetPtr(); findBlock != nullptr; findBlock = findBlock->prevBlock.GetPtr())
{
const uintptr_t blockMemory = MBLOCK_GET_MEMORY(findBlock);
const uint32 dataSize = (uint32)findBlock->dataSize;
const uintptr_t alignedEndBlockMemory = (blockMemory + dataSize - size) & ~alignmentMinusOne;
if (alignedEndBlockMemory < blockMemory)
continue;
if (foundSize <= dataSize)
continue;
freeBlock = findBlock;
blockMemStart = alignedEndBlockMemory;
foundSize = dataSize;
if (searchForFirstEntry)
break;
if (foundSize == size)
break;
}
void* mem = nullptr;
if (freeBlock)
mem = _MEMExpHeap_AllocUsedBlockFromFreeBlock(&expHeap->expHeapHead.chainFreeBlocks, freeBlock, blockMemStart, size, coreinit::MEMExpHeapAllocDirection::TAIL);
return mem;
}
void* _MEMExpHeap_AllocFromHead(MEMHeapHandle heap, uint32 size, int alignment)
{
MEMExpHeapHead2* expHeap = (MEMExpHeapHead2*)heap;
const bool searchForFirstEntry = (expHeap->expHeapHead.fields&1) == MEM_EXPHEAP_ALLOC_MODE_FIRST;
const int alignmentMinusOne = alignment - 1;
MBlock2_t* freeBlock = nullptr;
uintptr_t blockMemStart = 0;
uint32 foundSize = -1;
for (MBlock2_t* findBlock = expHeap->expHeapHead.chainFreeBlocks.headMBlock.GetPtr(); findBlock != nullptr; findBlock = findBlock->nextBlock.GetPtr())
{
const uintptr_t blockMemory = MBLOCK_GET_MEMORY(findBlock);
const uintptr_t alignedBlockMemory = (blockMemory + alignmentMinusOne) & ~alignmentMinusOne;
const uint32 dataSize = (uint32)findBlock->dataSize;
if (dataSize < alignedBlockMemory - blockMemory + size)
continue;
if (foundSize <= dataSize)
continue;
freeBlock = findBlock;
blockMemStart = alignedBlockMemory;
foundSize = dataSize;
if (searchForFirstEntry)
break;
if (foundSize == size)
break;
}
void* mem = nullptr;
if (freeBlock)
mem = _MEMExpHeap_AllocUsedBlockFromFreeBlock(&expHeap->expHeapHead.chainFreeBlocks, freeBlock, blockMemStart, size, coreinit::MEMExpHeapAllocDirection::HEAD);
return mem;
}
MEMHeapHandle _MEMExpHeap_InitHeap(void* startAddress, void* endAddress, uint32 createFlags)
{
MEMExpHeapHead2* header = (MEMExpHeapHead2*)startAddress;
uintptr_t heapStart = (uintptr_t)startAddress + sizeof(MEMExpHeapHead2);
MEMInitHeapBase(header, coreinit::MEMHeapMagic::EXP_HEAP, (void*)heapStart, endAddress, createFlags);
ExpMemBlockRegion region;
region.start = (uintptr_t)header->heapStart.GetPtr();
region.end = (uintptr_t)header->heapEnd.GetPtr();
MBlock2_t* mBlock = _MEMExpHeap_InitMBlock(®ion, MBLOCK_TYPE_FREE);
header->expHeapHead.chainFreeBlocks.headMBlock = mBlock;
header->expHeapHead.chainFreeBlocks.tailMBlock = mBlock;
header->expHeapHead.chainUsedBlocks.headMBlock = nullptr;
header->expHeapHead.chainUsedBlocks.tailMBlock = nullptr;
header->expHeapHead.groupID = 0;
header->expHeapHead.fields = 0;
return (MEMHeapHandle)header;
}
MEMHeapHandle MEMCreateExpHeap(void* startAddress, uint32 size)
{
return MEMCreateExpHeapEx(startAddress, size, MEM_HEAP_OPTION_NONE);
}
void* MEMAllocFromExpHeap(MEMHeapHandle heap, uint32 size)
{
return MEMAllocFromExpHeapEx(heap, size, MEM_HEAP_DEFAULT_ALIGNMENT);
}
uint32 MEMGetAllocatableSizeForExpHeap(MEMHeapHandle heap)
{
return MEMGetAllocatableSizeForExpHeapEx(heap, MEM_HEAP_DEFAULT_ALIGNMENT);
}
void IsValidExpHeapHandle_(MEMHeapHandle heap)
{
cemu_assert_debug(heap != MEM_HEAP_INVALID_HANDLE);
cemu_assert_debug(heap->magic == coreinit::MEMHeapMagic::EXP_HEAP);
}
#pragma endregion
#pragma region exported
MEMHeapHandle MEMCreateExpHeapEx(void* startAddress, uint32 size, uint32 createFlags)
{
if (startAddress == nullptr)
return MEM_HEAP_INVALID_HANDLE;
const uintptr_t alignedStart = ((uintptr_t)startAddress + MIN_ALIGNMENT_MINUS_ONE) & (~MIN_ALIGNMENT_MINUS_ONE);
const uintptr_t alignedEnd = ((uintptr_t)startAddress + size) & (~MIN_ALIGNMENT_MINUS_ONE);
if (alignedStart > alignedEnd)
return MEM_HEAP_INVALID_HANDLE;
if (alignedEnd - alignedStart < 0x6C)
return MEM_HEAP_INVALID_HANDLE;
MEMHeapHandle result = _MEMExpHeap_InitHeap((void*)alignedStart, (void*)alignedEnd, createFlags);
if (result)
MEMHeapTable_Add(result);
return result;
}
void* MEMDestroyExpHeap(MEMHeapHandle heap)
{
IsValidExpHeapHandle_(heap);
MEMBaseDestroyHeap(heap);
MEMHeapTable_Remove(heap);
return heap;
}
void* MEMAllocFromExpHeapEx(MEMHeapHandle heap, uint32 size, sint32 alignment)
{
IsValidExpHeapHandle_(heap);
if (alignment == 0)
{
// this is a guaranteed crash on the actual console
cemuLog_log(LogType::Force, "MEMAllocFromExpHeapEx(): Alignment 0 not allowed");
alignment = 4;
return nullptr;
}
if (size == 0)
size = 1;
size = (size + MIN_ALIGNMENT_MINUS_ONE) & ~MIN_ALIGNMENT_MINUS_ONE;
heap->AcquireLock();
void* mem;
if (alignment < 0)
{
alignment = -alignment;
mem = _MEMExpHeap_AllocFromTail(heap, size, alignment);
}
else
{
mem = _MEMExpHeap_AllocFromHead(heap, size, alignment);
}
heap->ReleaseLock();
return mem;
}
void MEMFreeToExpHeap(MEMHeapHandle heap, void* mem)
{
IsValidExpHeapHandle_(heap);
if (mem)
{
heap->AcquireLock();
cemu_assert_debug(_MEMExpHeap_IsValidUsedMBlock(mem, heap) == true);
cemu_assert_debug((uintptr_t)heap->heapStart.GetPtr() <= (uintptr_t)mem && (uintptr_t)mem < (uintptr_t)heap->heapEnd.GetPtr());
MEMExpHeapHead2* expHeap = (MEMExpHeapHead2*)heap;
ExpMemBlockRegion region;
MBlock2_t* mBlock = MBLOCK_GET_HEADER(mem);
_MEMExpHeap_GetRegionOfMBlock(®ion, mBlock);
_MEMExpHeap_RemoveMBlock(&expHeap->expHeapHead.chainUsedBlocks, mBlock);
_MEMExpHeap_RecycleRegion(&expHeap->expHeapHead.chainFreeBlocks, ®ion);
heap->ReleaseLock();
}
}
uint16 MEMSetAllocModeForExpHeap(MEMHeapHandle heap, uint16 mode)
{
IsValidExpHeapHandle_(heap);
heap->AcquireLock();
MEMExpHeapHead2* expHeap = (MEMExpHeapHead2*)heap;
const uint16 oldMode = expHeap->expHeapHead.fields & 0x1;
expHeap->expHeapHead.fields |= (mode & 0x1);
heap->ReleaseLock();
return oldMode;
}
uint16 MEMGetAllocModeForExpHeap(MEMHeapHandle heap)
{
IsValidExpHeapHandle_(heap);
heap->AcquireLock();
MEMExpHeapHead2* expHeap = (MEMExpHeapHead2*)heap;
const uint16 mode = expHeap->expHeapHead.fields & 0x1;
heap->ReleaseLock();
return mode;
}
uint32 MEMAdjustExpHeap(MEMHeapHandle heap)
{
uint32 newSize = 0;
IsValidExpHeapHandle_(heap);
heap->AcquireLock();
MEMExpHeapHead2* expHeap = (MEMExpHeapHead2*)heap;
MEMPTR<MBlock2_t> tailBlock = expHeap->expHeapHead.chainFreeBlocks.tailMBlock;
if (tailBlock)
{
MBlock2_t* tail = tailBlock.GetPtr();
uintptr_t blockMemEnd = MBLOCK_GET_END(tail);
uintptr_t heapEnd = (uintptr_t)heap->heapEnd.GetPtr();
if (blockMemEnd == heapEnd)
{
_MEMExpHeap_RemoveMBlock(&expHeap->expHeapHead.chainFreeBlocks, tail);
uint32 removedBlockSize = sizeof(MBlock2_t) + (uint32)tail->dataSize;
uintptr_t newHeapEnd = heapEnd - removedBlockSize;
heap->heapEnd = (void*)newHeapEnd;
newSize = (uint32)(newHeapEnd - (uintptr_t)heap);
}
}
heap->ReleaseLock();
return newSize;
}
uint32 MEMResizeForMBlockExpHeap(MEMHeapHandle heap, void* memBlock, uint32 size)
{
uint32 newSize = 0;
IsValidExpHeapHandle_(heap);
cemu_assert_debug(memBlock != nullptr);
heap->AcquireLock();
MBlock2_t* mBlock = MBLOCK_GET_HEADER(memBlock);
const uint32 dataSize = mBlock->dataSize;
if (dataSize != size)
{
cemu_assert_debug(_MEMExpHeap_IsValidUsedMBlock(memBlock, heap));
MEMExpHeapHead2* expHeap = (MEMExpHeapHead2*)heap;
if (size <= dataSize)
{
ExpMemBlockRegion region;
region.start = (uintptr_t)memBlock + size;
region.end = MBLOCK_GET_END(mBlock);
mBlock->dataSize = size;
if (!_MEMExpHeap_RecycleRegion(&expHeap->expHeapHead.chainFreeBlocks, ®ion))
mBlock->dataSize = dataSize;
newSize = (uint32)mBlock->dataSize;
}
else
{
MEMPTR<MBlock2_t> free = expHeap->expHeapHead.chainFreeBlocks.headMBlock;
const uintptr_t blockEndAddr = MBLOCK_GET_END(mBlock);
while (free)
{
MBlock2_t* freeBlock = free.GetPtr();
if ((uintptr_t)freeBlock == blockEndAddr)
{
const uint32 freeDataSize = freeBlock->dataSize;
if (size > (dataSize + freeDataSize + sizeof(MBlock2_t)))
{
newSize = 0;
break;
}
ExpMemBlockRegion region;
_MEMExpHeap_GetRegionOfMBlock(®ion, freeBlock);
MBlock2_t* prevBlock = (MBlock2_t*)_MEMExpHeap_RemoveMBlock(&expHeap->expHeapHead.chainFreeBlocks, freeBlock);
uintptr_t oldStart = region.start;
region.start = (uintptr_t)memBlock + size;
if (region.end - region.start < sizeof(MBlock2_t))
region.start = region.end;
mBlock->dataSize = (uint32)(region.start - (uintptr_t)memBlock);
if (region.end - region.start >= sizeof(MBlock2_t))
{
MBlock2_t* newBlock = _MEMExpHeap_InitMBlock(®ion, MBLOCK_TYPE_FREE);
_MEMExpHeap_InsertMBlock(&expHeap->expHeapHead.chainFreeBlocks, newBlock, prevBlock);
}
if (HAS_FLAG(heap->flags, MEM_HEAP_OPTION_CLEAR))
memset((void*)oldStart, 0x00, region.start - oldStart);
else if (HAS_FLAG(heap->flags, MEM_HEAP_OPTION_FILL))
{
const uint32 fillValue = MEMGetFillValForHeap(HEAP_FILL_TYPE::ON_ALLOC);
memset((void*)oldStart, fillValue, region.start - oldStart);
}
newSize = (uint32)mBlock->dataSize;
break;
}
free = freeBlock->nextBlock;
}
if (!free)
newSize = 0;
}
}
heap->ReleaseLock();
return newSize;
}
uint32 MEMGetTotalFreeSizeForExpHeap(MEMHeapHandle heap)
{
uint32 freeSize = 0;
IsValidExpHeapHandle_(heap);
heap->AcquireLock();
MEMExpHeapHead2* expHeap = (MEMExpHeapHead2*)heap;
MEMPTR<MBlock2_t> block = expHeap->expHeapHead.chainFreeBlocks.headMBlock;
while (block)
{
freeSize += (uint32)block->dataSize;
block = block->nextBlock;
}
heap->ReleaseLock();
return freeSize;
}
uint32 MEMGetAllocatableSizeForExpHeapEx(MEMHeapHandle heap, sint32 alignment)
{
uint32 result = 0;
IsValidExpHeapHandle_(heap);
cemu_assert_debug((alignment & 3) == 0);
alignment = abs(alignment);
heap->AcquireLock();
MEMExpHeapHead2* exp_heap = (MEMExpHeapHead2*)heap;
const sint32 alignment_minus_one = alignment - 1;
uint32 smallest_alignment_space = -1;
for(auto free_block = exp_heap->expHeapHead.chainFreeBlocks.headMBlock; free_block; free_block = free_block->nextBlock)
{
MBlock2_t* block = free_block.GetPtr();
const uintptr_t block_memory = MBLOCK_GET_MEMORY(block);
const uintptr_t block_end = MBLOCK_GET_END(block);
const uintptr_t aligned_memory = (block_memory + alignment_minus_one) & ~alignment_minus_one;
if (aligned_memory >= block_end)
continue;
const uint32 size = (uint32)(block_end - aligned_memory);
const uint32 alignment_space = (uint32)(aligned_memory - block_memory);
if (size < result)
continue;
if (size == result)
{
if (smallest_alignment_space <= alignment_space)
continue;
}
smallest_alignment_space = alignment_space;
result = size;
}
heap->ReleaseLock();
return result;
}
uint16 MEMSetGroupIDForExpHeap(MEMHeapHandle heap, uint16 groupId)
{
IsValidExpHeapHandle_(heap);
heap->AcquireLock();
MEMExpHeapHead2* expHeap = (MEMExpHeapHead2*)heap;
const uint16 oldGroupId = expHeap->expHeapHead.groupID;
expHeap->expHeapHead.groupID = groupId;
heap->ReleaseLock();
return oldGroupId;
}
uint16 MEMGetGroupIDForExpHeap(MEMHeapHandle heap)
{
IsValidExpHeapHandle_(heap);
heap->AcquireLock();
MEMExpHeapHead2* expHeap = (MEMExpHeapHead2*)heap;
const uint16 oldGroupId = expHeap->expHeapHead.groupID;
heap->ReleaseLock();
return oldGroupId;
}
void MEMVisitAllocatedForExpHeap(MEMHeapHandle heap, const MEMPTR<void>& visitor, uint32 userParam)
{
IsValidExpHeapHandle_(heap);
cemu_assert_debug(visitor != nullptr);
heap->AcquireLock();
MEMPTR<MEMHeapBase> heapMPTR = heap;
MEMExpHeapHead2* expHeap = (MEMExpHeapHead2*)heap;
MEMPTR<MBlock2_t> find = expHeap->expHeapHead.chainUsedBlocks.headMBlock;
while (find)
{
MBlock2_t* mBlock = find.GetPtr();
MEMPTR<void> memMPTR = (void*)MBLOCK_GET_MEMORY(mBlock);
PPCCoreCallback(visitor.GetMPTR(), memMPTR.GetMPTR(), heapMPTR.GetMPTR(), userParam);
find = mBlock->nextBlock;
}
heap->ReleaseLock();
}
uint32 MEMGetSizeForMBlockExpHeap(const void* memBlock)
{
cemu_assert_debug(_MEMExpHeap_IsValidUsedMBlock(memBlock, nullptr));
MBlock2_t* mBlock = MBLOCK_GET_HEADER(memBlock);
return mBlock->dataSize;
}
uint16 MEMGetGroupIDForMBlockExpHeap(const void* memBlock)
{
cemu_assert_debug(_MEMExpHeap_IsValidUsedMBlock(memBlock, nullptr));
MBlock2_t* mBlock = MBLOCK_GET_HEADER(memBlock);
return (uint32)mBlock->fields & 0xFF;
}
uint16 MEMGetAllocDirForMBlockExpHeap(const void* memBlock)
{
cemu_assert_debug(_MEMExpHeap_IsValidUsedMBlock(memBlock, nullptr));
MBlock2_t* mBlock = MBLOCK_GET_HEADER(memBlock);
const uint32 fields = mBlock->fields;
return (fields >> 31) & 1;
}
bool MEMCheckExpHeap(MEMHeapHandle heap, uint32 options)
{
if (heap == MEM_HEAP_INVALID_HANDLE || heap->magic != coreinit::MEMHeapMagic::EXP_HEAP)
return false;
heap->AcquireLock();
// todo
heap->ReleaseLock();
return true;
}
bool MEMCheckForMBlockExpHeap(const void* memBlock, MEMHeapHandle heap, uint32 options)
{
return true;
}
void _DefaultAllocatorForExpHeap_Alloc(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(allocator, MEMAllocator, 0);
ppcDefineParamU32(size, 1);
MEMPTR<void> result = MEMAllocFromExpHeapEx((MEMHeapHandle)allocator->heap.GetPtr(), size, (uint32)allocator->param1);
osLib_returnFromFunction(hCPU, result.GetMPTR());
}
void _DefaultAllocatorForExpHeap_Free(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(allocator, MEMAllocator, 0);
ppcDefineParamMEMPTR(mem, void, 1);
MEMFreeToExpHeap((MEMHeapHandle)allocator->heap.GetPtr(), mem);
osLib_returnFromFunction(hCPU, 0);
}
SysAllocator<MEMAllocatorFunc> gExpHeapDefaultAllocator;
void MEMInitAllocatorForExpHeap(MEMAllocator* allocator, MEMHeapHandle heap, sint32 alignment)
{
allocator->func = gExpHeapDefaultAllocator.GetPtr();
gExpHeapDefaultAllocator->funcAlloc = PPCInterpreter_makeCallableExportDepr(_DefaultAllocatorForExpHeap_Alloc);
gExpHeapDefaultAllocator->funcFree = PPCInterpreter_makeCallableExportDepr(_DefaultAllocatorForExpHeap_Free);
allocator->heap = heap;
allocator->param1 = alignment;
allocator->param2 = 0;
}
#pragma endregion
#pragma region wrapper
void expheap_test();
void export_MEMCreateExpHeapEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(startAddress, void, 0);
ppcDefineParamU32(size, 1);
ppcDefineParamU16(options, 2);
MEMPTR<MEMHeapBase> heap = MEMCreateExpHeapEx(startAddress.GetPtr(), size, options);
cemuLog_logDebug(LogType::CoreinitMem, "MEMCreateExpHeapEx(0x{:08x}, 0x{:x}, 0x{:x}) Result: 0x{:08x}", startAddress.GetMPTR(), size, options, heap.GetMPTR());
osLib_returnFromFunction(hCPU, heap.GetMPTR());
}
void export_MEMDestroyExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(heap, MEMHeapBase, 0);
cemuLog_logDebug(LogType::CoreinitMem, "MEMDestroyExpHeap(0x{:08x})", heap.GetMPTR());
MEMPTR<MEMHeapBase> oldHeap = (MEMHeapBase*)MEMDestroyExpHeap(heap.GetPtr());
osLib_returnFromFunction(hCPU, oldHeap.GetMPTR());
}
void export_MEMAllocFromExpHeapEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(heap, MEMHeapBase, 0);
ppcDefineParamU32(size, 1);
ppcDefineParamS32(alignment, 2);
MEMPTR<void> mem = MEMAllocFromExpHeapEx(heap.GetPtr(), size, alignment);
cemuLog_logDebug(LogType::CoreinitMem, "MEMAllocFromExpHeapEx(0x{:08x}, 0x{:x}, {}) Result: 0x{:08x}", heap.GetMPTR(), size, alignment, mem.GetMPTR());
osLib_returnFromFunction(hCPU, mem.GetMPTR());
}
void export_MEMFreeToExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(heap, MEMHeapBase, 0);
ppcDefineParamMEMPTR(mem, void, 1);
cemuLog_logDebug(LogType::CoreinitMem, "MEMFreeToExpHeap(0x{:08x}, 0x{:08x})", heap.GetMPTR(), mem.GetMPTR());
MEMFreeToExpHeap(heap.GetPtr(), mem.GetPtr());
osLib_returnFromFunction(hCPU, 0);
}
void export_MEMSetAllocModeForExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(heap, MEMHeapBase, 0);
ppcDefineParamU16(mode, 1);
cemuLog_logDebug(LogType::CoreinitMem, "MEMSetAllocModeForExpHeap(0x{:08x}, {})", heap.GetMPTR(), mode);
uint16 oldMode = MEMSetAllocModeForExpHeap(heap.GetPtr(), mode);
osLib_returnFromFunction(hCPU, oldMode);
}
void export_MEMGetAllocModeForExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(heap, MEMHeapBase, 0);
cemuLog_logDebug(LogType::CoreinitMem, "MEMGetAllocModeForExpHeap(0x{:08x})", heap.GetMPTR());
uint16 oldMode = MEMGetAllocModeForExpHeap(heap.GetPtr());
osLib_returnFromFunction(hCPU, oldMode);
}
void export_MEMAdjustExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(heap, MEMHeapBase, 0);
cemuLog_logDebug(LogType::CoreinitMem, "MEMAdjustExpHeap(0x{:08x})", heap.GetMPTR());
uint32 newSize = MEMAdjustExpHeap(heap.GetPtr());
osLib_returnFromFunction(hCPU, newSize);
}
void export_MEMResizeForMBlockExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(heap, MEMHeapBase, 0);
ppcDefineParamMEMPTR(mem, void, 1);
ppcDefineParamU32(size, 2);
uint32 newSize = MEMResizeForMBlockExpHeap(heap.GetPtr(), mem.GetPtr(), size);
cemuLog_logDebug(LogType::CoreinitMem, "MEMResizeForMBlockExpHeap(0x{:08x}, 0x{:08x}, 0x{:x}) Result: 0x{:x}", heap.GetMPTR(), mem.GetMPTR(), size, newSize);
osLib_returnFromFunction(hCPU, newSize);
}
void export_MEMGetTotalFreeSizeForExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(heap, MEMHeapBase, 0);
uint32 size = MEMGetTotalFreeSizeForExpHeap(heap.GetPtr());
cemuLog_logDebug(LogType::CoreinitMem, "MEMGetTotalFreeSizeForExpHeap(0x{:08x}) Result: 0x{:x}", heap.GetMPTR(), size);
osLib_returnFromFunction(hCPU, size);
}
void export_MEMGetAllocatableSizeForExpHeapEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(heap, MEMHeapBase, 0);
ppcDefineParamS32(alignment, 1);
uint32 size = MEMGetAllocatableSizeForExpHeapEx(heap.GetPtr(), alignment);
cemuLog_logDebug(LogType::CoreinitMem, "MEMGetAllocatableSizeForExpHeapEx(0x{:08x}, 0x{:x}) Result: 0x{:x}", heap.GetMPTR(), alignment, size);
osLib_returnFromFunction(hCPU, size);
}
void export_MEMSetGroupIDForExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(heap, MEMHeapBase, 0);
ppcDefineParamU16(groupId, 1);
cemuLog_logDebug(LogType::CoreinitMem, "MEMSetGroupIDForExpHeap(0x{:08x}, {})", heap.GetMPTR(), groupId);
#ifdef CEMU_DEBUG_ASSERT
assert_dbg(); // someone test this and the entire groupId feature
#endif
uint16 oldGroupId = MEMSetGroupIDForExpHeap(heap.GetPtr(), groupId);
osLib_returnFromFunction(hCPU, oldGroupId);
}
void export_MEMGetGroupIDForExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(heap, MEMHeapBase, 0);
cemuLog_logDebug(LogType::Force, "MEMGetGroupIDForExpHeap(0x{:08x})", heap.GetMPTR());
uint16 oldGroupId = MEMGetGroupIDForExpHeap(heap.GetPtr());
osLib_returnFromFunction(hCPU, oldGroupId);
}
void export_MEMVisitAllocatedForExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(heap, MEMHeapBase, 0);
ppcDefineParamMEMPTR(visitor, void, 1);
ppcDefineParamU32(userParam, 2);
cemuLog_logDebug(LogType::CoreinitMem, "MEMVisitAllocatedForExpHeap(0x{:08x}, 0x{:08x}, 0x{:x})", heap.GetMPTR(), visitor.GetMPTR(), userParam);
MEMVisitAllocatedForExpHeap(heap.GetPtr(), visitor, userParam);
osLib_returnFromFunction(hCPU, 0);
}
void export_MEMGetSizeForMBlockExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(memBlock, void, 0);
uint32 size = MEMGetSizeForMBlockExpHeap(memBlock.GetPtr());
cemuLog_logDebug(LogType::CoreinitMem, "MEMGetSizeForMBlockExpHeap(0x{:08x}) Result: 0x{:x}", memBlock.GetMPTR(), size);
osLib_returnFromFunction(hCPU, size);
}
void export_MEMGetGroupIDForMBlockExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(memBlock, void, 0);
cemuLog_logDebug(LogType::CoreinitMem, "MEMGetGroupIDForMBlockExpHeap(0x{:08x})", memBlock.GetMPTR());
uint16 groupId = MEMGetGroupIDForMBlockExpHeap(memBlock.GetPtr());
osLib_returnFromFunction(hCPU, groupId);
}
void export_MEMGetAllocDirForMBlockExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(memBlock, void, 0);
cemuLog_logDebug(LogType::CoreinitMem, "MEMGetAllocDirForMBlockExpHeap(0x{:08x})", memBlock.GetMPTR());
uint16 allocDir = MEMGetAllocDirForMBlockExpHeap(memBlock.GetPtr());
osLib_returnFromFunction(hCPU, allocDir);
}
void export_MEMCheckExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(heap, MEMHeapBase, 0);
ppcDefineParamU32(options, 1);
cemuLog_logDebug(LogType::CoreinitMem, "MEMCheckExpHeap(0x{:08x}, 0x{:x})", heap.GetMPTR(), options);
bool result = MEMCheckExpHeap(heap.GetPtr(), options);
osLib_returnFromFunction(hCPU, result ? 1 : 0);
}
void export_MEMCheckForMBlockExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(memBlock, void, 0);
ppcDefineParamMEMPTR(heap, MEMHeapBase, 1);
ppcDefineParamU32(options, 2);
bool result = MEMCheckForMBlockExpHeap(memBlock.GetPtr(), heap.GetPtr(), options);
cemuLog_logDebug(LogType::CoreinitMem, "MEMCheckForMBlockExpHeap(0x{:08x}, 0x{:08x}, 0x{:x}) Result: {}", memBlock.GetMPTR(), heap.GetMPTR(), options, result);
osLib_returnFromFunction(hCPU, result ? 1 : 0);
}
void export_MEMInitAllocatorForExpHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(allocator, MEMAllocator, 0);
ppcDefineParamMEMPTR(heap, MEMHeapBase, 1);
ppcDefineParamS32(alignment, 2);
cemuLog_logDebug(LogType::CoreinitMem, "MEMInitAllocatorForExpHeap(0x{:08x}, 0x{:08x}, {})", allocator.GetMPTR(), heap.GetMPTR(), alignment);
MEMInitAllocatorForExpHeap(allocator.GetPtr(), heap.GetPtr(), alignment);
osLib_returnFromFunction(hCPU, 0);
}
void expheap_test()
{
srand(1000);
MEMHeapHandle heapHandle = MEMCreateExpHeapEx(memory_getPointerFromVirtualOffset(0x11000000), 0x10000000, 0);
MEMExpHeapHead2* expHeap = (MEMExpHeapHead2*)heapHandle;
sint32 idx = 0;
for (MBlock2_t* findBlock = expHeap->expHeapHead.chainFreeBlocks.headMBlock.GetPtr(); findBlock != nullptr; findBlock = findBlock->nextBlock.GetPtr())
{
const uintptr_t blockMemory = MBLOCK_GET_MEMORY(findBlock);
const uint32 dataSize = (uint32)findBlock->dataSize;
debug_printf(">> freeBlock %04d addr %08x - %08x\n", idx, memory_getVirtualOffsetFromPointer((void*)blockMemory), memory_getVirtualOffsetFromPointer((void*)blockMemory) + dataSize);
idx++;
}
void* allocTable[1024];
sint32 allocCount = 0;
printf("Run ExpHeap test...\n");
for (sint32 t = 0; t < 2; t++)
{
// allocate a bunch of entries
sint32 r = rand() % 100;
//for (sint32 i = 0; i < r; i++)
{
if( allocCount >= 1024 )
continue;
uint32 size = (rand() % 1000) * 12;
void* mem = MEMAllocFromExpHeapEx(heapHandle, size * 12, -0x2000);
if (mem)
{
allocTable[allocCount] = mem;
allocCount++;
}
}
}
// free everything that remains
for (sint32 i = 0; i < allocCount; i++)
{
MEMFreeToExpHeap(heapHandle, allocTable[i]);
}
allocCount = 0;
// debug print free blocks (only one should remain)
expHeap = (MEMExpHeapHead2*)heapHandle;
idx = 0;
for (MBlock2_t* findBlock = expHeap->expHeapHead.chainFreeBlocks.headMBlock.GetPtr(); findBlock != nullptr; findBlock = findBlock->nextBlock.GetPtr())
{
const uintptr_t blockMemory = MBLOCK_GET_MEMORY(findBlock);
const uint32 dataSize = (uint32)findBlock->dataSize;
debug_printf("freeBlock %04d addr %08x - %08x\n", idx, memory_getVirtualOffsetFromPointer((void*)blockMemory), memory_getVirtualOffsetFromPointer((void*)blockMemory) + dataSize);
idx++;
}
assert_dbg();
}
void expheap_load()
{
osLib_addFunction("coreinit", "MEMCreateExpHeapEx", export_MEMCreateExpHeapEx);
osLib_addFunction("coreinit", "MEMDestroyExpHeap", export_MEMDestroyExpHeap);
osLib_addFunction("coreinit", "MEMAllocFromExpHeapEx", export_MEMAllocFromExpHeapEx);
osLib_addFunction("coreinit", "MEMFreeToExpHeap", export_MEMFreeToExpHeap);
osLib_addFunction("coreinit", "MEMSetAllocModeForExpHeap", export_MEMSetAllocModeForExpHeap);
osLib_addFunction("coreinit", "MEMGetAllocModeForExpHeap", export_MEMGetAllocModeForExpHeap);
osLib_addFunction("coreinit", "MEMAdjustExpHeap", export_MEMAdjustExpHeap);
osLib_addFunction("coreinit", "MEMResizeForMBlockExpHeap", export_MEMResizeForMBlockExpHeap);
osLib_addFunction("coreinit", "MEMGetTotalFreeSizeForExpHeap", export_MEMGetTotalFreeSizeForExpHeap);
osLib_addFunction("coreinit", "MEMGetAllocatableSizeForExpHeapEx", export_MEMGetAllocatableSizeForExpHeapEx);
osLib_addFunction("coreinit", "MEMSetGroupIDForExpHeap", export_MEMSetGroupIDForExpHeap);
osLib_addFunction("coreinit", "MEMGetGroupIDForExpHeap", export_MEMGetGroupIDForExpHeap);
osLib_addFunction("coreinit", "MEMVisitAllocatedForExpHeap", export_MEMVisitAllocatedForExpHeap);
osLib_addFunction("coreinit", "MEMGetSizeForMBlockExpHeap", export_MEMGetSizeForMBlockExpHeap);
osLib_addFunction("coreinit", "MEMGetGroupIDForMBlockExpHeap", export_MEMGetGroupIDForMBlockExpHeap);
osLib_addFunction("coreinit", "MEMGetAllocDirForMBlockExpHeap", export_MEMGetAllocDirForMBlockExpHeap);
osLib_addFunction("coreinit", "MEMCheckExpHeap", export_MEMCheckExpHeap);
osLib_addFunction("coreinit", "MEMCheckForMBlockExpHeap", export_MEMCheckForMBlockExpHeap);
osLib_addFunction("coreinit", "MEMInitAllocatorForExpHeap", export_MEMInitAllocatorForExpHeap);
}
#pragma endregion
}
| 34,153
|
C++
|
.cpp
| 883
| 35.960362
| 192
| 0.765518
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,108
|
coreinit_FG.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_FG.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include <memory>
#define FG_BUCKET_AREA_FREE 0 // free area available game
#define FG_BUCKET_AREA_AUDIO_TRANSITION 1 // transition audio buffer
#define FG_BUCKET_AREA2 2 // frame storage? TV?
#define FG_BUCKET_AREA3 3 // frame storage? DRC?
#define FG_BUCKET_AREA4 4 // frame storage? TV?
#define FG_BUCKET_AREA5 5 // frame storage? DRC?
#define FG_BUCKET_AREA_SAVE 6
#define FG_BUCKET_AREA_COPY 7 // for OS copy data (clipboard and title switch parameters)
#define FG_BUCKET_AREA_FREE_SIZE 0x2800000
#define FG_BUCKET_AREA_SAVE_SIZE 0x1000
#define FG_BUCKET_AREA_COPY_SIZE 0x400000
#define FG_BUCKET_AREA_COUNT 8
namespace coreinit
{
MEMPTR<void> fgAddr = nullptr; // NULL if not in foreground
MEMPTR<uint8> fgSaveAreaAddr = nullptr;
struct
{
uint32 id;
uint32 startOffset;
uint32 size;
}fgAreaEntries[FG_BUCKET_AREA_COUNT] =
{
{ 0, 0, 0x2800000 },
{ 7, 0x2800000, 0x400000 },
{ 1, 0x2C00000, 0x900000 },
{ 2, 0x3500000, 0x3C0000 },
{ 3, 0x38C0000, 0x1C0000 },
{ 4, 0x3A80000, 0x3C0000 },
{ 5, 0x3E40000, 0x1BF000 },
{ 6, 0x3FFF000, 0x1000 }
};
MEMPTR<uint8> GetFGMemByArea(uint32 areaId)
{
if (fgAddr == nullptr)
return nullptr;
for (sint32 i = 0; i < FG_BUCKET_AREA_COUNT; i++)
{
if (fgAreaEntries[i].id == areaId)
return MEMPTR<uint8>(fgAddr.GetPtr<uint8>() + fgAreaEntries[i].startOffset);
}
return nullptr;
}
bool OSGetForegroundBucket(MEMPTR<void>* offset, uint32be* size)
{
// return full size of foreground bucket area
if (offset)
*offset = { (MPTR)MEMORY_FGBUCKET_AREA_ADDR };
if (size)
*size = MEMORY_FGBUCKET_AREA_SIZE;
// return true if in foreground
return true;
}
bool OSGetForegroundBucketFreeArea(MEMPTR<void>* offset, uint32be* size)
{
uint8* freeAreaAddr = GetFGMemByArea(FG_BUCKET_AREA_FREE).GetPtr();
*offset = freeAreaAddr;
*size = FG_BUCKET_AREA_FREE_SIZE;
// return true if in foreground
return (fgAddr != nullptr);
}
void coreinitExport_OSGetForegroundBucket(PPCInterpreter_t* hCPU)
{
//debug_printf("OSGetForegroundBucket(0x%x,0x%x)\n", hCPU->gpr[3], hCPU->gpr[4]);
// returns the whole FG bucket area (if the current process is in the foreground)
ppcDefineParamMPTR(areaOutput, 0);
ppcDefineParamMPTR(areaSize, 1);
bool r = OSGetForegroundBucket((MEMPTR<void>*)memory_getPointerFromVirtualOffsetAllowNull(areaOutput), (uint32be*)memory_getPointerFromVirtualOffsetAllowNull(areaSize));
osLib_returnFromFunction(hCPU, r ? 1 : 0);
}
void InitForegroundBucket()
{
uint32be fgSize;
OSGetForegroundBucket(&fgAddr, &fgSize);
uint8* freeAreaPtr = GetFGMemByArea(FG_BUCKET_AREA_FREE).GetPtr();
memset(freeAreaPtr, 0, FG_BUCKET_AREA_FREE_SIZE);
uint8* saveAreaPtr = GetFGMemByArea(FG_BUCKET_AREA_SAVE).GetPtr();
fgSaveAreaAddr = saveAreaPtr;
if (*(uint32be*)saveAreaPtr != (uint32be)'Save')
{
// clear save area
memset(saveAreaPtr, 0, FG_BUCKET_AREA_SAVE_SIZE);
// clear copy area
memset(GetFGMemByArea(FG_BUCKET_AREA_COPY).GetPtr(), 0, FG_BUCKET_AREA_COPY_SIZE);
// init save area
*(uint32be*)(saveAreaPtr + 0x00) = 'Save';
*(uint32be*)(saveAreaPtr + 0x08) |= 0x300;
}
}
void __OSClearCopyData()
{
uint8* fgCopyArea = GetFGMemByArea(FG_BUCKET_AREA_COPY).GetPtr();
if (fgCopyArea)
{
*(uint32be*)(fgCopyArea + 0x00) = 0;
}
}
uint32 __OSGetCopyDataSize()
{
uint8* fgCopyArea = GetFGMemByArea(FG_BUCKET_AREA_COPY).GetPtr();
if (fgCopyArea)
{
return *(uint32be*)(fgCopyArea + 0x00);
}
return 0;
}
uint8* __OSGetCopyDataPtr()
{
uint8* fgCopyArea = GetFGMemByArea(FG_BUCKET_AREA_COPY).GetPtr();
if (fgCopyArea)
return fgCopyArea + 4;
return nullptr;
}
bool __OSAppendCopyData(uint8* data, sint32 length)
{
uint8* fgCopyArea = GetFGMemByArea(FG_BUCKET_AREA_COPY).GetPtr();
if (fgCopyArea == nullptr)
return false;
uint32 currentOffset = *(uint32be*)(fgCopyArea + 0x00);
if ((currentOffset + length) > FG_BUCKET_AREA_COPY_SIZE - 4)
{
return false;
}
memcpy(fgCopyArea + currentOffset + 4, data, length);
*(uint32be*)(fgCopyArea + 0x00) += length;
return true;
}
bool __OSResizeCopyData(sint32 length)
{
uint8* fgCopyArea = GetFGMemByArea(FG_BUCKET_AREA_COPY).GetPtr();
if (fgCopyArea == nullptr)
return false;
sint32 currentOffset = (sint32) * (uint32be*)(fgCopyArea + 0x00);
if (length < currentOffset)
{
// can only make copy data smaller
*(uint32be*)(fgCopyArea + 0x00) = length;
return true;
}
return false;
}
bool OSCopyFromClipboard(void* data, uint32be* size)
{
uint32 cSize = *size;
if (cSize == 0 && data == nullptr)
return false;
if (OSGetForegroundBucket(nullptr, nullptr) == false)
return false;
// todo
*size = 0;
return true;
}
void coreinitExport_OSCopyFromClipboard(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "OSCopyFromClipboard(0x{:x},0x{:x})", hCPU->gpr[3], hCPU->gpr[4]);
ppcDefineParamMEMPTR(buffer, void, 0);
ppcDefineParamMEMPTR(size, uint32be, 1);
bool r = OSCopyFromClipboard(buffer.GetPtr(), size.GetPtr());
osLib_returnFromFunction(hCPU, r ? 1 : 0);
}
void InitializeFG()
{
osLib_addFunction("coreinit", "OSGetForegroundBucket", coreinitExport_OSGetForegroundBucket);
cafeExportRegister("coreinit", OSGetForegroundBucket, LogType::CoreinitMem);
cafeExportRegister("coreinit", OSGetForegroundBucketFreeArea, LogType::CoreinitMem);
osLib_addFunction("coreinit", "OSCopyFromClipboard", coreinitExport_OSCopyFromClipboard);
}
}
| 5,558
|
C++
|
.cpp
| 170
| 29.9
| 171
| 0.722191
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,109
|
coreinit_SystemInfo.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_SystemInfo.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_SystemInfo.h"
namespace coreinit
{
SysAllocator<OSSystemInfo> g_system_info;
const OSSystemInfo& OSGetSystemInfo()
{
return *g_system_info.GetPtr();
}
void InitializeSystemInfo()
{
cemu_assert(ppcCyclesSince2000 != 0);
g_system_info->busClock = ESPRESSO_BUS_CLOCK;
g_system_info->coreClock = ESPRESSO_CORE_CLOCK;
g_system_info->ticksSince2000 = ESPRESSO_CORE_CLOCK_TO_TIMER_CLOCK(ppcCyclesSince2000);
g_system_info->l2cacheSize[0] = 512*1024; // 512KB // 512KB
g_system_info->l2cacheSize[1] = 2*1024*1924; // 2MB
g_system_info->l2cacheSize[2] = 512*1024; // 512KB
g_system_info->coreClockToBusClockRatio = 5;
cafeExportRegister("coreinit", OSGetSystemInfo, LogType::Placeholder);
}
}
| 792
|
C++
|
.cpp
| 22
| 33.636364
| 89
| 0.757497
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,110
|
coreinit_GHS.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_GHS.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_GHS.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/OS/RPL/rpl.h"
namespace coreinit
{
struct iobbuf
{
uint32be ukn00; // lock index?
uint32be ukn04; // ?
uint32be ukn08; // ?
uint32be flags; // permissions and channel
};
#define GHS_FOPEN_MAX 100
struct GHSAccessibleData
{
iobbuf _iob[GHS_FOPEN_MAX];
MPTR _iob_lock[GHS_FOPEN_MAX];
uint16be __gh_FOPEN_MAX;
MEMPTR<void> ghs_environ;
uint32 ghs_Errno; // exposed as 'errno' data export
};
SysAllocator<GHSAccessibleData> g_ghs_data;
struct ghs_flock
{
uint32be mutexIndex;
};
void __ghs_flock_create(ghs_flock* flock);
ghs_flock* __ghs_flock_ptr(iobbuf* iob);
std::recursive_mutex g_ghsLock;
std::recursive_mutex g_ghsLockFlock;
SysAllocator<coreinit::OSMutex, GHS_FOPEN_MAX> _flockMutexArray;
bool _flockMutexMask[GHS_FOPEN_MAX]; // if set, mutex in _flockMutexArray is reserved
#define IOB_FLAG_IN (0x1)
#define IOB_FLAG_OUT (0x2)
#define IOB_FLAG_CHANNEL(__x) ((__x)<<18)
void PrepareGHSRuntime()
{
g_ghs_data->ghs_environ = nullptr;
g_ghs_data->__gh_FOPEN_MAX = GHS_FOPEN_MAX;
g_ghs_data->ghs_Errno = 0;
for (sint32 i = 0; i < GHS_FOPEN_MAX; i++)
_flockMutexMask[i] = false;
// init stdin/stdout/stderr
g_ghs_data->_iob[0].flags = IOB_FLAG_IN;
g_ghs_data->_iob[1].flags = IOB_FLAG_OUT;
g_ghs_data->_iob[1].flags = IOB_FLAG_OUT;
g_ghs_data->_iob[0].flags |= IOB_FLAG_CHANNEL(0);
g_ghs_data->_iob[1].flags |= IOB_FLAG_CHANNEL(1);
g_ghs_data->_iob[2].flags |= IOB_FLAG_CHANNEL(2);
__ghs_flock_create(__ghs_flock_ptr(g_ghs_data->_iob + 0));
__ghs_flock_create(__ghs_flock_ptr(g_ghs_data->_iob + 1));
__ghs_flock_create(__ghs_flock_ptr(g_ghs_data->_iob + 2));
osLib_addVirtualPointer("coreinit", "__gh_FOPEN_MAX", memory_getVirtualOffsetFromPointer(&g_ghs_data->__gh_FOPEN_MAX));
osLib_addVirtualPointer("coreinit", "_iob", memory_getVirtualOffsetFromPointer(g_ghs_data->_iob));
osLib_addVirtualPointer("coreinit", "environ", memory_getVirtualOffsetFromPointer(&g_ghs_data->ghs_environ));
osLib_addVirtualPointer("coreinit", "errno", memory_getVirtualOffsetFromPointer(&g_ghs_data->ghs_Errno));
}
void __ghs_flock_create(ghs_flock* flock)
{
g_ghsLockFlock.lock();
// find available mutex
sint32 mutexIndex = -1;
for (sint32 i = 0; i < GHS_FOPEN_MAX; i++)
{
if (!_flockMutexMask[i])
{
mutexIndex = i;
break;
}
}
if (mutexIndex == -1)
{
cemuLog_log(LogType::Force, "__ghs_flock_create(): No flock available");
cemu_assert(false); // no available mutex
}
// mark mutex as reserved
_flockMutexMask[mutexIndex] = true;
// init mutex
coreinit::OSInitMutexEx(_flockMutexArray.GetPtr() + mutexIndex, NULL);
// update flock to point to the reserved mutex
flock->mutexIndex = mutexIndex;
g_ghsLockFlock.unlock();
}
void __ghs_flock_destroy(uint32 index)
{
g_ghsLockFlock.lock();
cemu_assert_debug(index > 2); // stdin/stdout/stderr should never be released?
cemu_assert(index < GHS_FOPEN_MAX);
cemu_assert_debug(_flockMutexMask[index]);
_flockMutexMask[index] = false;
g_ghsLockFlock.unlock();
}
ghs_flock* __ghs_flock_ptr(iobbuf* iob)
{
size_t streamIndex = iob - g_ghs_data->_iob;
return (ghs_flock*)&(g_ghs_data->_iob_lock[streamIndex]);
}
void __ghs_flock_file(uint32 index)
{
cemu_assert(index < GHS_FOPEN_MAX);
OSLockMutex(_flockMutexArray.GetPtr() + index);
}
void __ghs_funlock_file(uint32 index)
{
cemu_assert(index < GHS_FOPEN_MAX);
OSUnlockMutex(_flockMutexArray.GetPtr() + index);
}
void __ghsLock()
{
while (!g_ghsLock.try_lock())
{
PPCCore_switchToScheduler();
}
}
void __ghsUnlock()
{
g_ghsLock.unlock();
}
void* __get_eh_init_block()
{
return nullptr;
}
void* __get_eh_globals()
{
OSThread_t* currentThread = coreinit::OSGetCurrentThread();
return currentThread->crt.eh_globals.GetPtr();
}
void* __get_eh_mem_manage()
{
OSThread_t* currentThread = coreinit::OSGetCurrentThread();
return ¤tThread->crt.eh_mem_manage;
}
void* __gh_errno_ptr()
{
OSThread_t* currentThread = coreinit::OSGetCurrentThread();
return ¤tThread->context.ghs_errno;
}
void* __get_eh_store_globals()
{
OSThread_t* currentThread = coreinit::OSGetCurrentThread();
return ¤tThread->crt.eh_store_globals;
}
void* __get_eh_store_globals_tdeh()
{
OSThread_t* currentThread = coreinit::OSGetCurrentThread();
return ¤tThread->crt.eh_store_globals_tdeh;
}
struct ghs_mtx_t
{
MEMPTR<coreinit::OSMutex> mutexPtr;
};
void __ghs_mtx_init(ghs_mtx_t* mtx)
{
mtx->mutexPtr = (coreinit::OSMutex*)coreinit::_weak_MEMAllocFromDefaultHeapEx(ppcsizeof<coreinit::OSMutex>(), 8);
coreinit::OSInitMutex(mtx->mutexPtr.GetPtr());
}
void __ghs_mtx_dst(ghs_mtx_t* mtx)
{
coreinit::_weak_MEMFreeToDefaultHeap(mtx->mutexPtr.GetPtr());
mtx->mutexPtr = nullptr;
}
void __ghs_mtx_lock(ghs_mtx_t* mtx)
{
coreinit::OSLockMutex(mtx->mutexPtr.GetPtr());
}
void __ghs_mtx_unlock(ghs_mtx_t* mtx)
{
coreinit::OSUnlockMutex(mtx->mutexPtr.GetPtr());
}
struct OSTLSBlock
{
MPTR addr;
uint32 ukn04;
};
static_assert(sizeof(OSTLSBlock) == 8);
struct TLS_Index
{
uint16 ukn00;
uint16 tlsModuleIndex;
MPTR ukn04;
};
void* __tls_get_addr(TLS_Index* tlsIndex)
{
OSThread_t* currentThread = coreinit::OSGetCurrentThread();
if (_swapEndianU16(tlsIndex->tlsModuleIndex) == 0)
assert_dbg();
// check if we need to allocate additional TLS blocks for this thread
if (_swapEndianU16(tlsIndex->tlsModuleIndex) >= _swapEndianU32(currentThread->numAllocatedTLSBlocks))
{
uint32 allocSize = (RPLLoader_GetMaxTLSModuleIndex() + 1) * sizeof(OSTLSBlock); // __OSDynLoad_gTLSHeader.ukn00 * 8;
MPTR allocMem = coreinit_allocFromSysArea(allocSize, 4);
memset(memory_getPointerFromVirtualOffset(allocMem), 0, allocSize);
if (_swapEndianU32(currentThread->numAllocatedTLSBlocks) != 0)
{
// keep previously allocated blocks
memcpy(memory_getPointerFromVirtualOffset(allocMem), memory_getPointerFromVirtualOffset(_swapEndianU32(currentThread->tlsBlocksMPTR)), _swapEndianU32(currentThread->numAllocatedTLSBlocks) * 8);
}
currentThread->tlsBlocksMPTR = _swapEndianU32(allocMem);
currentThread->numAllocatedTLSBlocks = _swapEndianU16(RPLLoader_GetMaxTLSModuleIndex() + 1);
}
// look up TLS address based on moduleIndex
OSTLSBlock* tlsBlock = (OSTLSBlock*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(currentThread->tlsBlocksMPTR) + sizeof(OSTLSBlock) * (uint32)_swapEndianU16(tlsIndex->tlsModuleIndex));
if (tlsBlock->addr != _swapEndianU32(MPTR_NULL))
{
//osLib_returnFromFunction(hCPU, _swapEndianU32(tlsBlock->addr)+_swapEndianU32(tlsIndex->ukn04));
return memory_getPointerFromVirtualOffset(_swapEndianU32(tlsBlock->addr) + _swapEndianU32(tlsIndex->ukn04));
}
// alloc data for TLS block
uint8* tlsSectionData = nullptr;
sint32 tlsSize = 0;
bool r = RPLLoader_GetTLSDataByTLSIndex((sint16)_swapEndianU16(tlsIndex->tlsModuleIndex), &tlsSectionData, &tlsSize);
cemu_assert(r);
cemu_assert(tlsSize != 0);
MPTR tlsData = coreinit_allocFromSysArea(tlsSize, 32);
memcpy(memory_getPointerFromVirtualOffset(tlsData), tlsSectionData, tlsSize);
tlsBlock->addr = _swapEndianU32(tlsData);
return memory_getPointerFromVirtualOffset(_swapEndianU32(tlsBlock->addr) + _swapEndianU32(tlsIndex->ukn04));
}
void InitializeGHS()
{
cafeExportRegister("coreinit", __ghs_flock_create, LogType::Placeholder);
cafeExportRegister("coreinit", __ghs_flock_destroy, LogType::Placeholder);
cafeExportRegister("coreinit", __ghs_flock_ptr, LogType::Placeholder);
cafeExportRegister("coreinit", __ghs_flock_file, LogType::Placeholder);
cafeExportRegister("coreinit", __ghs_funlock_file, LogType::Placeholder);
cafeExportRegister("coreinit", __ghsLock, LogType::Placeholder);
cafeExportRegister("coreinit", __ghsUnlock, LogType::Placeholder);
cafeExportRegister("coreinit", __get_eh_init_block, LogType::Placeholder);
cafeExportRegister("coreinit", __get_eh_globals, LogType::Placeholder);
cafeExportRegister("coreinit", __get_eh_mem_manage, LogType::Placeholder);
cafeExportRegister("coreinit", __gh_errno_ptr, LogType::Placeholder);
cafeExportRegister("coreinit", __get_eh_store_globals, LogType::Placeholder);
cafeExportRegister("coreinit", __get_eh_store_globals_tdeh, LogType::Placeholder);
cafeExportRegister("coreinit", __ghs_mtx_init, LogType::Placeholder);
cafeExportRegister("coreinit", __ghs_mtx_dst, LogType::Placeholder);
cafeExportRegister("coreinit", __ghs_mtx_lock, LogType::Placeholder);
cafeExportRegister("coreinit", __ghs_mtx_unlock, LogType::Placeholder);
cafeExportRegister("coreinit", __tls_get_addr, LogType::Placeholder);
}
};
| 8,917
|
C++
|
.cpp
| 242
| 34
| 200
| 0.732507
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,111
|
coreinit_MPQueue.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_MPQueue.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_MPQueue.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "util/helpers/fspinlock.h"
// titles that utilize MP task queue: Yoshi's Woolly World, Fast Racing Neo, Tokyo Mirage Sessions, Mii Maker
#define AcquireMPQLock() s_workaroundSpinlock.lock()
#define ReleaseMPQLock() s_workaroundSpinlock.unlock()
namespace coreinit
{
FSpinlock s_workaroundSpinlock; // workaround for a race condition
/*
Race condition pseudo-code:
WorkerThreads:
while( task = MPDequeTask() ) MPRunTask(task);
MainThread:
QueueTasks();
// wait and reset
MPWaitForTaskQWithTimeout(DONE)
MPTermTaskQ()
MPInitTaskQ()
The race condition then happens when a worker thread calls MPDequeTask()/MPRunTask while MPInitTaskQ() is being executed on the main thread.
Since MPInitTaskQ() (re)initializes the internal spinlock it's not thread-safe, leading to a corruption of the spinlock state for other threads
We work around this by using a global spinlock instead of the taskQ specific one
*/
void MPInitTask(MPTask* task, void* func, void* data, uint32 size)
{
s_workaroundSpinlock.lock();
task->thisptr = task;
task->coreIndex = PPC_CORE_COUNT;
task->taskFunc.func = func;
task->taskFunc.data = data;
task->taskFunc.size = size;
task->taskState = MP_TASK_STATE_INIT;
task->userdata = nullptr;
task->runtime = 0;
s_workaroundSpinlock.unlock();
}
bool MPTermTask(MPTask* task)
{
return true;
}
bool MPRunTask(MPTask* task)
{
if (task->taskState != MP_TASK_STATE_READY)
return false;
auto* taskQ = task->taskQ.GetPtr();
if(taskQ->state != MP_TASKQ_STATE_STOPPING && taskQ->state != MP_TASKQ_STATE_STOP)
{
AcquireMPQLock(); // OSUninterruptibleSpinLock_Acquire(&taskQ->spinlock);
if (taskQ->state == MP_TASKQ_STATE_STOPPING || taskQ->state == MP_TASKQ_STATE_STOP)
{
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskQ->spinlock);
return false;
}
taskQ->taskReadyCount = taskQ->taskReadyCount - 1;
taskQ->taskRunCount = taskQ->taskRunCount + 1;
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskQ->spinlock);
const auto startTime = OSGetSystemTime();
task->coreIndex = OSGetCoreId();
task->taskState = MP_TASK_STATE_RUN;
task->taskFunc.result = PPCCoreCallback(task->taskFunc.func, task->taskFunc.data, task->taskFunc.size);
task->taskState = MP_TASK_STATE_DONE;
const auto endTime = OSGetSystemTime();
task->runtime = endTime - startTime;
cemu_assert_debug(taskQ->state != MP_TASKQ_STATE_DONE);
AcquireMPQLock(); // OSUninterruptibleSpinLock_Acquire(&taskQ->spinlock);
taskQ->taskRunCount = taskQ->taskRunCount - 1;
taskQ->taskDoneCount[1] = taskQ->taskDoneCount[1] + 1;
if (taskQ->state == MP_TASKQ_STATE_STOPPING && taskQ->taskRunCount == 0)
taskQ->state = MP_TASKQ_STATE_STOP;
if (taskQ->taskCount == taskQ->taskDoneCount[1])
taskQ->state = MP_TASKQ_STATE_DONE;
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskQ->spinlock);
return true;
}
return false;
}
bool MPGetTaskInfo(MPTask* task, MPTaskInfo* info)
{
info->state = task->taskState;
info->coreIndex = task->coreIndex;
info->runtime = task->runtime;
// not setting function result?
return true;
}
void* MPGetTaskUserData(MPTask* task)
{
return task->userdata.GetPtr();
}
void MPSetTaskUserData(MPTask* task, void* userdata)
{
task->userdata = userdata;
}
void MPInitTaskQ(MPTaskQ* taskQ, MPTask** tasks, uint32 taskCount)
{
AcquireMPQLock();
taskQ->thisptr = taskQ;
OSInitSpinLock(&taskQ->spinlock);
taskQ->state = MP_TASKQ_STATE_INIT;
taskQ->taskReadyCount = 0;
taskQ->taskCount = 0;
taskQ->taskRunCount = 0;
for(uint32 i = 0; i < OSGetCoreCount(); ++i)
{
taskQ->taskDoneCount[i] = 0;
taskQ->nextIndex[i] = 0;
taskQ->endIndex[i] = 0;
}
taskQ->taskQueue = (MEMPTR<MPTask>*)tasks;
taskQ->taskQueueSize = taskCount;
ReleaseMPQLock();
}
bool MPEnqueTask(MPTaskQ* taskq, MPTask* task)
{
bool result = false;
if(task->taskState == MP_TASK_STATE_INIT)
{
AcquireMPQLock(); // OSUninterruptibleSpinLock_Acquire(&taskq->spinlock);
const uint32 taskQState = taskq->state;
if((uint32)taskq->endIndex[1] < taskq->taskQueueSize
&& (taskQState == MP_TASKQ_STATE_INIT || taskQState == MP_TASKQ_STATE_RUN || taskQState == MP_TASKQ_STATE_STOPPING || taskQState == MP_TASKQ_STATE_STOP || taskQState == MP_TASKQ_STATE_DONE))
{
task->taskQ = taskq;
task->taskState = MP_TASK_STATE_READY;
taskq->thisptr = taskq;
const uint32 endIndex = taskq->endIndex[1];
taskq->endIndex[1] = endIndex + 1;
taskq->taskCount = taskq->taskCount + 1;
taskq->taskReadyCount = taskq->taskReadyCount + 1;
taskq->taskQueue[endIndex] = task;
if (taskQState == MP_TASKQ_STATE_DONE)
taskq->state = MP_TASKQ_STATE_RUN;
result = true;
}
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskq->spinlock);
}
return result;
}
bool MPTermTaskQ(MPTaskQ* taskq)
{
// workaround code for TMS
AcquireMPQLock(); // OSUninterruptibleSpinLock_Acquire(&taskq->spinlock);
//if ((uint32)taskq->taskReadyCount > 0 && taskq->state == MP_TASKQ_STATE_RUN)
if (taskq->state == MP_TASKQ_STATE_RUN)
{
taskq->state = MP_TASKQ_STATE_STOP;
}
while (taskq->taskRunCount != 0)
{
// wait for tasks to finish
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskq->spinlock);
OSYieldThread();
AcquireMPQLock(); // OSUninterruptibleSpinLock_Acquire(&taskq->spinlock);
}
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskq->spinlock);
return true;
}
bool MPGetTaskQInfo(MPTaskQ* taskq, MPTaskQInfo* info)
{
AcquireMPQLock(); // OSUninterruptibleSpinLock_Acquire(&taskq->spinlock);
info->state = taskq->state;
info->taskCount = taskq->taskCount;
info->taskReadyCount = taskq->taskReadyCount;
info->taskRunCount = taskq->taskRunCount;
info->taskDoneCount = taskq->taskDoneCount[1];
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskq->spinlock);
return true;
}
bool MPStartTaskQ(MPTaskQ* taskq)
{
bool result = false;
AcquireMPQLock(); // OSUninterruptibleSpinLock_Acquire(&taskq->spinlock);
if (taskq->state == MP_TASKQ_STATE_INIT || taskq->state == MP_TASKQ_STATE_STOP)
{
taskq->state = MP_TASKQ_STATE_RUN;
result = true;
}
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskq->spinlock);
return result;
}
bool MPRunTasksFromTaskQ(MPTaskQ* taskq, int granularity)
{
uint32 result = 0;
while (true)
{
if (taskq->state != MP_TASKQ_STATE_RUN)
return (taskq->state & MP_TASKQ_STATE_DONE) != 0;
AcquireMPQLock(); // OSUninterruptibleSpinLock_Acquire(&taskq->spinlock);
const auto nextIndex = taskq->nextIndex[1];
const auto endIndex = taskq->endIndex[1];
if (nextIndex == endIndex)
break;
auto newNextIndex = nextIndex + granularity;
if (endIndex < nextIndex + granularity)
newNextIndex = endIndex;
const auto workCount = (newNextIndex - nextIndex);
taskq->nextIndex[1] = newNextIndex;
taskq->taskReadyCount = taskq->taskReadyCount - workCount;
taskq->taskRunCount = taskq->taskRunCount + workCount;
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskq->spinlock);
// since we are having a granularity parameter, we might want to give the scheduler the chance for other stuff when having multiple tasks
if(result != 0)
PPCCore_switchToScheduler();
for (int i = nextIndex; i < newNextIndex; ++i)
{
const auto startTime = OSGetSystemTime();
const auto& task = taskq->taskQueue[i];
result = task->thisptr.GetMPTR();
task->taskState = MP_TASK_STATE_RUN;
task->coreIndex = OSGetCoreId();
task->taskFunc.result = PPCCoreCallback(task->taskFunc.func, task->taskFunc.data, task->taskFunc.size);
task->taskState = MP_TASK_STATE_DONE;
const auto endTime = OSGetSystemTime();
task->runtime = endTime - startTime;
}
AcquireMPQLock(); // OSUninterruptibleSpinLock_Acquire(&taskq->spinlock);
const auto runRemaining = taskq->taskRunCount - workCount;
taskq->taskRunCount = runRemaining;
const auto doneCount = taskq->taskDoneCount[1] + workCount;
taskq->taskDoneCount[1] = doneCount;
if (taskq->state == 4 && runRemaining == 0)
taskq->state = MP_TASKQ_STATE_STOP;
if (taskq->taskCount == doneCount)
taskq->state = MP_TASKQ_STATE_DONE;
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskq->spinlock);
}
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskq->spinlock);
return result != 0;
}
bool MPStopTaskQ(MPTaskQ* taskq)
{
bool result = false;
AcquireMPQLock(); // OSUninterruptibleSpinLock_Acquire(&taskq->spinlock);
if (taskq->state == MP_TASKQ_STATE_RUN)
{
taskq->state = MP_TASKQ_STATE_STOPPING;
if (taskq->taskRunCount == 0)
taskq->state = MP_TASKQ_STATE_STOP;
result = true;
}
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskq->spinlock);
return result;
}
bool MPWaitTaskQ(MPTaskQ* taskQ, uint32 waitState)
{
bool waitRun = (waitState & MP_TASKQ_STATE_RUN) != 0;
bool waitStop = (waitState & MP_TASKQ_STATE_STOP) != 0;
bool waitDone = (waitState & MP_TASKQ_STATE_DONE) != 0;
size_t loopCounter = 0;
while (waitStop || waitDone || waitRun)
{
const uint32 state = taskQ->state;
if (waitRun && HAS_FLAG(state, MP_TASKQ_STATE_RUN))
{
waitRun = false;
waitDone = false;
continue;
}
if (waitStop && HAS_FLAG(state, MP_TASKQ_STATE_STOP))
{
waitStop = false;
waitDone = false;
continue;
}
if (waitDone && HAS_FLAG(state, MP_TASKQ_STATE_DONE))
{
waitDone = false;
waitRun = false;
waitStop = false;
continue;
}
if (loopCounter > 0)
coreinit::OSSleepTicks(EspressoTime::ConvertNsToTimerTicks(50000)); // sleep thread for 0.05ms to give other threads a chance to run (avoids softlocks in YWW)
else
PPCCore_switchToScheduler();
loopCounter++;
}
return true;
}
bool MPWaitTaskQWithTimeout(MPTaskQ* taskQ, uint32 waitState, sint64 timeout)
{
bool waitRun = (waitState & MP_TASKQ_STATE_RUN) != 0;
bool waitStop = (waitState & MP_TASKQ_STATE_STOP) != 0;
bool waitDone = (waitState & MP_TASKQ_STATE_DONE) != 0;
const auto startTime = OSGetSystemTime();
const auto timerTicks = EspressoTime::ConvertNsToTimerTicks(timeout);
const auto endTime = startTime + timerTicks;
while (waitStop || waitDone || waitRun)
{
const uint32 state = taskQ->state;
if (waitRun && HAS_FLAG(state, MP_TASKQ_STATE_RUN))
{
waitRun = false;
waitDone = false;
continue;
}
if (waitStop && HAS_FLAG(state, MP_TASKQ_STATE_STOP))
{
waitStop = false;
waitDone = false;
continue;
}
if (waitDone && HAS_FLAG(state, MP_TASKQ_STATE_DONE))
{
waitDone = false;
waitRun = false;
waitStop = false;
continue;
}
if (OSGetSystemTime() >= endTime)
{
if (waitState == MP_TASKQ_STATE_DONE)
cemuLog_log(LogType::Force, "MPWaitTaskQWithTimeout(): Timeout occurred while waiting for done-only state");
return false;
}
PPCCore_switchToScheduler();
}
return true;
}
MPTask* MPDequeTask(MPTaskQ* taskq)
{
MPTask* result = nullptr;
if (taskq->state == MP_TASKQ_STATE_RUN)
{
AcquireMPQLock(); // OSUninterruptibleSpinLock_Acquire(&taskq->spinlock);
if (taskq->state == MP_TASKQ_STATE_RUN && taskq->nextIndex[1] != taskq->endIndex[1])
{
result = taskq->taskQueue[taskq->nextIndex[1]].GetPtr();
taskq->nextIndex[1] = taskq->nextIndex[1] + 1;
}
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskq->spinlock);
}
return result;
}
uint32 MPDequeTasks(MPTaskQ* taskq, MPTask** tasks, sint32 maxTasks)
{
uint32 dequeCount = 0;
if (taskq->state == MP_TASKQ_STATE_RUN)
{
AcquireMPQLock(); // OSUninterruptibleSpinLock_Acquire(&taskq->spinlock);
if (taskq->state == MP_TASKQ_STATE_RUN)
{
auto nextIndex = (sint32)taskq->nextIndex[1];
auto newEndIndex = nextIndex + maxTasks;
if (taskq->endIndex[1] < nextIndex + maxTasks)
newEndIndex = taskq->endIndex[1];
dequeCount = newEndIndex - nextIndex;
taskq->nextIndex[1] = newEndIndex;
for(int i = 0; nextIndex < newEndIndex; ++nextIndex, ++i)
{
tasks[i] = taskq->taskQueue[nextIndex].GetPtr();
}
auto idx = 0;
while (nextIndex < newEndIndex)
{
tasks[idx] = taskq->taskQueue[nextIndex].GetPtr();
nextIndex = nextIndex + 1;
idx = idx + 1;
}
}
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskq->spinlock);
}
return dequeCount;
}
bool MPResetTaskQ(MPTaskQ* taskq)
{
debug_printf("MPResetTaskQ called\n");
bool result = false;
AcquireMPQLock(); // OSUninterruptibleSpinLock_Acquire(&taskq->spinlock);
if (taskq->state == MP_TASKQ_STATE_DONE || taskq->state == MP_TASKQ_STATE_STOP)
{
taskq->state = MP_TASKQ_STATE_INIT;
taskq->taskRunCount = 0;
taskq->taskCount = taskq->endIndex[1];
taskq->taskReadyCount = taskq->endIndex[1];
for(uint32 i = 0; i < OSGetCoreCount(); ++i)
{
taskq->taskDoneCount[i] = 0;
taskq->nextIndex[i] = 0;
}
for(uint32 i = 0; i < taskq->taskCount; ++i)
{
const auto& task = taskq->taskQueue[i];
task->taskFunc.result = 0;
task->coreIndex = PPC_CORE_COUNT;
task->runtime = 0;
task->taskState = MP_TASK_STATE_READY;
}
result = true;
}
ReleaseMPQLock(); // OSUninterruptibleSpinLock_Release(&taskq->spinlock);
return result;
}
void InitializeMP()
{
// task
cafeExportRegister("coreinit", MPInitTask, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPTermTask, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPRunTask, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPGetTaskInfo, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPGetTaskUserData, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPSetTaskUserData, LogType::CoreinitMP);
// taskq
cafeExportRegister("coreinit", MPInitTaskQ, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPResetTaskQ, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPEnqueTask, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPDequeTask, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPDequeTasks, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPRunTasksFromTaskQ, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPStartTaskQ, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPWaitTaskQ, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPWaitTaskQWithTimeout, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPStopTaskQ, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPTermTaskQ, LogType::CoreinitMP);
cafeExportRegister("coreinit", MPGetTaskQInfo, LogType::CoreinitMP);
}
}
| 15,133
|
C++
|
.cpp
| 418
| 32.174641
| 194
| 0.712307
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,112
|
coreinit_MEM.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_MEM.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_FG.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM_ExpHeap.h"
#include "Cafe/OS/libs/coreinit/coreinit_Memory.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM_FrmHeap.h"
#include "coreinit_DynLoad.h"
// the system area is a block of memory that exists only in the emulator. It is used to simplify dynamic memory allocation for system data
// this partially overlaps with the system heap from coreinit_SysHeap.cpp -> Use SysHeap for everything
MPTR sysAreaAllocatorOffset = 0;
MPTR coreinit_allocFromSysArea(uint32 size, uint32 alignment)
{
cemu_assert_debug(mmuRange_CEMU_AREA.isMapped());
// deprecated, use OSAllocFromSystem instead (for everything but SysAllocator which probably should use its own allocator?)
static std::mutex s_allocator_mutex;
s_allocator_mutex.lock();
sysAreaAllocatorOffset = (sysAreaAllocatorOffset+alignment-1);
sysAreaAllocatorOffset -= (sysAreaAllocatorOffset%alignment);
uint32 newMemOffset = mmuRange_CEMU_AREA.getBase() + sysAreaAllocatorOffset;
sysAreaAllocatorOffset += (size+3)&~3;
if( sysAreaAllocatorOffset >= mmuRange_CEMU_AREA.getSize() )
{
cemuLog_log(LogType::Force, "Ran out of system memory");
cemu_assert(false); // out of bounds
}
s_allocator_mutex.unlock();
return newMemOffset;
}
void coreinit_freeToSysArea(MPTR mem)
{
// todo
}
namespace coreinit
{
#define MEM_MAX_HEAP_TABLE (0x20)
sint32 g_heapTableCount = 0;
MEMHeapBase* g_heapTable[MEM_MAX_HEAP_TABLE] = {};
bool g_slockInitialized = false;
bool g_listsInitialized = false;
MEMList g_list1;
MEMList g_list2;
MEMList g_list3;
std::array<uint32, 3> gHeapFillValues{ 0xC3C3C3C3, 0xF3F3F3F3, 0xD3D3D3D3 };
SysAllocator<OSSpinLock> gHeapGlobalLock;
MEMHeapBase* gDefaultHeap;
bool MEMHeapTable_Add(MEMHeapBase* heap)
{
if (g_heapTableCount >= MEM_MAX_HEAP_TABLE)
return false;
g_heapTable[g_heapTableCount] = heap;
g_heapTableCount++;
return true;
}
bool MEMHeapTable_Remove(MEMHeapBase* heap)
{
if (g_heapTableCount == 0)
return false;
if (g_heapTableCount > MEM_MAX_HEAP_TABLE)
return false;
for (sint32 i = 0; i < g_heapTableCount; ++i)
{
if (g_heapTable[i] == heap)
{
g_heapTable[i] = nullptr;
g_heapTableCount--;
if (g_heapTableCount == 0)
return true;
if (i >= g_heapTableCount)
return true;
cemu_assert_debug(i < MEM_MAX_HEAP_TABLE);
for (; i < g_heapTableCount; ++i)
{
g_heapTable[i] = g_heapTable[i + 1];
}
cemu_assert_debug(i < MEM_MAX_HEAP_TABLE);
g_heapTable[i] = nullptr;
return true;
}
}
return false;
}
MEMHeapBase* _MEMList_FindContainingHeap(MEMList* list, MEMHeapBase* heap)
{
for (MEMHeapBase* obj = (MEMHeapBase*)MEMGetFirstListObject(list); obj; obj = (MEMHeapBase*)MEMGetNextListObject(list, obj))
{
if (obj->heapStart.GetPtr() <= heap && heap < obj->heapEnd.GetPtr())
{
const MEMHeapHandle containHeap = _MEMList_FindContainingHeap(&obj->childList, heap);
return containHeap ? containHeap : obj;
}
}
return nullptr;
}
bool MEMList_ContainsHeap(MEMList* list, MEMHeapBase* heap)
{
for (MEMHeapBase* obj = (MEMHeapBase*)MEMGetFirstListObject(list); obj; obj = (MEMHeapBase*)MEMGetNextListObject(list, obj))
{
if (obj == heap)
return true;
}
return false;
}
MEMList* MEMList_FindContainingHeap(MEMHeapBase* head)
{
MEMPTR<void> memBound;
uint32be memBoundSize;
OSGetMemBound(1, &memBound, &memBoundSize);
MEMPTR<void> bucket;
uint32be bucketSize;
coreinit::OSGetForegroundBucket(&bucket, &bucketSize);
if ((uintptr_t)memBound.GetPtr() > (uintptr_t)head || (uintptr_t)head >= (uintptr_t)memBound.GetPtr() + (uint32)memBoundSize)
{
if ((uintptr_t)bucket.GetPtr() > (uintptr_t)head || (uintptr_t)head >= (uintptr_t)bucket.GetPtr() + (uint32)bucketSize)
{
MEMHeapBase* containHeap = _MEMList_FindContainingHeap(&g_list1, head);
if (containHeap)
return &containHeap->childList;
return &g_list1;
}
MEMHeapBase* containHeap = _MEMList_FindContainingHeap(&g_list3, head);
if (containHeap)
return &containHeap->childList;
return &g_list3;
}
MEMHeapBase* containHeap = _MEMList_FindContainingHeap(&g_list2, head);
if (containHeap)
return &containHeap->childList;
return &g_list2;
}
void MEMInitHeapBase(MEMHeapBase* heap, MEMHeapMagic magic, void* heapStart, void* heapEnd, uint32 createFlags)
{
memset(heap, 0, sizeof(MEMHeapBase));
heap->magic = magic;
heap->heapStart = heapStart;
heap->heapEnd = heapEnd;
heap->flags = (uint8)createFlags;
MEMInitList(&heap->childList, 4);
if (!g_slockInitialized)
{
OSInitSpinLock(&gHeapGlobalLock);
g_slockInitialized = true;
}
if (!g_listsInitialized)
{
MEMInitList(&g_list1, offsetof(MEMHeapBase, link));
MEMInitList(&g_list2, offsetof(MEMHeapBase, link));
MEMInitList(&g_list3, offsetof(MEMHeapBase, link));
g_listsInitialized = true;
}
OSInitSpinLock(&heap->spinlock);
OSUninterruptibleSpinLock_Acquire(&gHeapGlobalLock);
MEMList* list = MEMList_FindContainingHeap(heap);
MEMAppendListObject(list, heap);
OSUninterruptibleSpinLock_Release(&gHeapGlobalLock);
}
void MEMBaseDestroyHeap(MEMHeapBase* heap)
{
OSUninterruptibleSpinLock_Acquire(&gHeapGlobalLock);
if (HAS_FLAG(heap->flags, MEM_HEAP_OPTION_THREADSAFE))
OSUninterruptibleSpinLock_Acquire(&heap->spinlock);
MEMList* containHeap = MEMList_FindContainingHeap(heap);
cemu_assert_debug(MEMList_ContainsHeap(containHeap, heap));
MEMRemoveListObject(containHeap, heap);
if (HAS_FLAG(heap->flags, MEM_HEAP_OPTION_THREADSAFE))
OSUninterruptibleSpinLock_Release(&heap->spinlock);
OSUninterruptibleSpinLock_Release(&gHeapGlobalLock);
}
std::array<MEMHeapBase*, 9> sHeapBaseHandle{};
MEMHeapBase* MEMGetBaseHeapHandle(uint32 index)
{
if (index >= sHeapBaseHandle.size())
return nullptr;
return sHeapBaseHandle[index];
}
MEMHeapBase* MEMSetBaseHeapHandle(uint32 index, MEMHeapBase* heapBase)
{
if (index >= sHeapBaseHandle.size())
return nullptr;
if (sHeapBaseHandle[index] != nullptr)
{
cemuLog_log(LogType::Force, "MEMSetBaseHeapHandle(): Trying to assign heap to non-empty slot");
return sHeapBaseHandle[index];
}
sHeapBaseHandle[index] = heapBase;
return nullptr;
}
uint32 MEMSetFillValForHeap(HEAP_FILL_TYPE type, uint32 value)
{
uint32 idx = (uint32)type;
cemu_assert(idx < gHeapFillValues.size());
OSUninterruptibleSpinLock_Acquire(&gHeapGlobalLock);
const uint32 oldValue = gHeapFillValues[idx];
gHeapFillValues[idx] = value;
OSUninterruptibleSpinLock_Release(&gHeapGlobalLock);
return oldValue;
}
uint32 MEMGetFillValForHeap(HEAP_FILL_TYPE type)
{
uint32 idx = (uint32)type;
cemu_assert(idx < gHeapFillValues.size());
OSUninterruptibleSpinLock_Acquire(&gHeapGlobalLock);
const uint32 value = gHeapFillValues[idx];
OSUninterruptibleSpinLock_Release(&gHeapGlobalLock);
return value;
}
MEMHeapBase* MEMFindContainHeap(const void* memBlock)
{
MEMPTR<void> memBound;
uint32be memBoundSize;
OSGetMemBound(1, &memBound, &memBoundSize);
MEMPTR<void> bucket;
uint32be bucketSize;
coreinit::OSGetForegroundBucket(&bucket, &bucketSize);
OSUninterruptibleSpinLock_Acquire(&gHeapGlobalLock);
MEMHeapBase* result;
if ((uintptr_t)memBound.GetPtr() > (uintptr_t)memBlock || (uintptr_t)memBlock >= (uintptr_t)memBound.GetPtr() + (uint32)memBoundSize)
{
if ((uintptr_t)bucket.GetPtr() > (uintptr_t)memBlock || (uintptr_t)memBlock >= (uintptr_t)bucket.GetPtr() + (uint32)bucketSize)
{
result = _MEMList_FindContainingHeap(&g_list1, (MEMHeapBase*)memBlock);
}
else
{
if (coreinit::OSGetForegroundBucket(nullptr, nullptr) == 0)
{
cemu_assert_unimplemented(); // foreground required
result = nullptr;
}
else
{
result = _MEMList_FindContainingHeap(&g_list3, (MEMHeapBase*)memBlock);
}
}
}
else
{
if (coreinit::OSGetForegroundBucket(nullptr, nullptr) == 0)
{
cemu_assert_unimplemented(); // foreground required
result = nullptr;
}
else
{
result = _MEMList_FindContainingHeap(&g_list2, (MEMHeapBase*)memBlock);
}
}
OSUninterruptibleSpinLock_Release(&gHeapGlobalLock);
return result;
}
void* MEMCreateUserHeapHandle(void* heapAddress, uint32 heapSize)
{
MEMInitHeapBase((MEMHeapBase*)heapAddress, MEMHeapMagic::USER_HEAP, (uint8*)heapAddress + 0x40, (uint8*)heapAddress + heapSize, 0);
return heapAddress;
}
/* MEM Heap list */
#define GET_MEM_LINK(__obj__,__offset__) ((MEMLink*)((uintptr_t)__obj__ + (uint16)__offset__))
void* MEMGetFirstListObject(MEMList* list)
{
return MEMGetNextListObject(list, nullptr);
}
void MEMList_SetSingleObject(MEMList* list, void* object)
{
cemu_assert_debug(list != nullptr);
cemu_assert_debug(object != nullptr);
MEMLink* link = GET_MEM_LINK(object, list->offset);
link->prev = nullptr;
link->next = nullptr;
list->numObjects = list->numObjects + 1;
list->head = object;
list->tail = object;
}
void MEMInitList(MEMList* list, uint32 offset)
{
cemu_assert_debug(list != nullptr);
cemu_assert(offset <= 0xFFFF);
memset(list, 0x00, sizeof(MEMLink));
list->offset = (uint16)offset;
}
void MEMAppendListObject(MEMList* list, void* object)
{
cemu_assert_debug(list != nullptr);
cemu_assert_debug(object != nullptr);
if (list->head)
{
list->numObjects = list->numObjects + 1;
MEMLink* link = GET_MEM_LINK(object, list->offset);
link->prev = list->tail;
link->next = nullptr;
MEMLink* tailLink = GET_MEM_LINK(list->tail.GetPtr(), list->offset);
tailLink->next = object;
list->tail = object;
}
else
MEMList_SetSingleObject(list, object);
}
void MEMPrependListObject(MEMList* list, void* object)
{
cemu_assert_debug(list != nullptr);
cemu_assert_debug(object != nullptr);
MEMPTR<void> headObject = list->head;
if (headObject)
{
list->numObjects = list->numObjects + 1;
MEMLink* link = GET_MEM_LINK(object, list->offset);
link->prev = nullptr;
link->next = headObject;
MEMLink* headLink = GET_MEM_LINK(headObject.GetPtr(), list->offset);
headLink->prev = object;
list->head = object;
}
else
MEMList_SetSingleObject(list, object);
}
void MEMRemoveListObject(MEMList* list, void* object)
{
cemu_assert_debug(list != nullptr);
cemu_assert_debug(object != nullptr);
MEMLink* link = GET_MEM_LINK(object, list->offset);
MEMPTR<void> prevObject = link->prev;
if (prevObject)
{
MEMLink* prevLink = GET_MEM_LINK(prevObject.GetPtr(), list->offset);
prevLink->next = link->next;
}
else
list->head = link->next;
MEMPTR<void> nextObject = link->next;
if (nextObject)
{
MEMLink* nextLink = GET_MEM_LINK(nextObject.GetPtr(), list->offset);
nextLink->prev = prevObject;
}
else
list->tail = prevObject;
link->prev = nullptr;
link->next = nullptr;
list->numObjects = list->numObjects - 1;
}
void* MEMGetNextListObject(MEMList* list, void* object)
{
cemu_assert_debug(list != nullptr);
if (!object)
return list->head.GetPtr();
MEMLink* result = GET_MEM_LINK(object, list->offset);
return result->next.GetPtr();
}
void* MEMGetPrevListObject(MEMList* list, void* object)
{
cemu_assert_debug(list != nullptr);
if (!object)
return list->tail.GetPtr();
MEMLink* result = GET_MEM_LINK(object, list->offset);
return result->prev.GetPtr();
}
void* MEMGetNthListObject(MEMList* list, uint32 index)
{
cemu_assert_debug(list != nullptr);
void* result = MEMGetNextListObject(list, nullptr);
for (uint32 i = 0; i != index; ++i)
{
result = MEMGetNextListObject(list, result);
}
return result;
}
/* Default allocators */
MEMHeapBase* MEMDefaultHeap_Init(void* mem, uint32 size)
{
MEMHeapBase* heap = MEMCreateExpHeapEx(mem, size, 4);
gDefaultHeap = heap;
cemu_assert_debug(heap);
return heap;
}
void* default_MEMAllocFromDefaultHeap(uint32 size)
{
void* mem = MEMAllocFromExpHeapEx(gDefaultHeap, size, 0x40);
cemuLog_logDebug(LogType::CoreinitMem, "MEMAllocFromDefaultHeap(0x{:08x}) Result: 0x{:08x}", size, memory_getVirtualOffsetFromPointer(mem));
return mem;
}
void export_default_MEMAllocFromDefaultHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(size, 0);
MEMPTR<void> mem = default_MEMAllocFromDefaultHeap(size);
osLib_returnFromFunction(hCPU, mem.GetMPTR());
}
void* default_MEMAllocFromDefaultHeapEx(uint32 size, sint32 alignment)
{
void* mem = MEMAllocFromExpHeapEx(gDefaultHeap, size, alignment);
cemuLog_logDebug(LogType::CoreinitMem, "MEMAllocFromDefaultHeap(0x{:08x},{}) Result: 0x{:08x}", size, alignment, memory_getVirtualOffsetFromPointer(mem));
return mem;
}
void export_default_MEMAllocFromDefaultHeapEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(size, 0);
ppcDefineParamS32(alignment, 1);
MEMPTR<void> mem = default_MEMAllocFromDefaultHeapEx(size, alignment);
osLib_returnFromFunction(hCPU, mem.GetMPTR());
}
void default_MEMFreeToDefaultHeap(void* mem)
{
MEMFreeToExpHeap(gDefaultHeap, mem);
}
void export_default_MEMFreeToDefaultHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(mem, void, 0);
default_MEMFreeToDefaultHeap(mem.GetPtr());
osLib_returnFromFunction(hCPU, 0);
}
void default_DynLoadAlloc(PPCInterpreter_t* hCPU)
{
ppcDefineParamS32(size, 0);
ppcDefineParamS32(alignment, 1);
ppcDefineParamMEMPTR(memResultPtr, uint32be, 2);
MPTR mem = PPCCoreCallback(gCoreinitData->MEMAllocFromDefaultHeapEx.GetMPTR(), size, alignment);
*memResultPtr = mem;
osLib_returnFromFunction(hCPU, 0);
}
void default_DynLoadFree(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(mem, void, 0);
PPCCoreCallback(gCoreinitData->MEMFreeToDefaultHeap.GetMPTR(), mem);
osLib_returnFromFunction(hCPU, 0);
}
void* _weak_MEMAllocFromDefaultHeapEx(uint32 size, sint32 alignment)
{
MEMPTR<void> r{ PPCCoreCallback(gCoreinitData->MEMAllocFromDefaultHeapEx.GetMPTR(), size, alignment) };
return r.GetPtr();
}
void* _weak_MEMAllocFromDefaultHeap(uint32 size)
{
MEMPTR<void> r{ PPCCoreCallback(gCoreinitData->MEMAllocFromDefaultHeap.GetMPTR(), size) };
return r.GetPtr();
}
void _weak_MEMFreeToDefaultHeap(void* ptr)
{
PPCCoreCallback(gCoreinitData->MEMFreeToDefaultHeap.GetMPTR(), ptr);
}
void coreinitExport_MEMAllocFromAllocator(PPCInterpreter_t* hCPU)
{
MEMAllocator* memAllocator = (MEMAllocator*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
// redirect execution to allocator alloc callback
hCPU->instructionPointer = memAllocator->func->funcAlloc.GetMPTR();
}
void coreinitExport_MEMFreeToAllocator(PPCInterpreter_t* hCPU)
{
MEMAllocator* memAllocator = (MEMAllocator*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
// redirect execution to allocator free callback
hCPU->instructionPointer = memAllocator->func->funcFree.GetMPTR();
}
void _DefaultHeapAllocator_Alloc(PPCInterpreter_t* hCPU)
{
hCPU->gpr[3] = hCPU->gpr[4];
hCPU->instructionPointer = gCoreinitData->MEMAllocFromDefaultHeap.GetMPTR();
}
void _DefaultHeapAllocator_Free(PPCInterpreter_t* hCPU)
{
hCPU->gpr[3] = hCPU->gpr[4];
hCPU->instructionPointer = gCoreinitData->MEMFreeToDefaultHeap.GetMPTR();
}
SysAllocator<MEMAllocatorFunc> gDefaultHeapAllocator;
void coreinitExport_MEMInitAllocatorForDefaultHeap(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(memAllocator, MEMAllocator, 0);
gDefaultHeapAllocator->funcAlloc = PPCInterpreter_makeCallableExportDepr(_DefaultHeapAllocator_Alloc);
gDefaultHeapAllocator->funcFree = PPCInterpreter_makeCallableExportDepr(_DefaultHeapAllocator_Free);
memAllocator->func = gDefaultHeapAllocator.GetPtr();
memAllocator->heap = MEMPTR<void>(MEMGetBaseHeapHandle(1));
memAllocator->param1 = 0;
memAllocator->param2 = 0;
osLib_returnFromFunction(hCPU, 0);
}
void InitDefaultHeaps(MEMPTR<MEMHeapBase>& mem1Heap, MEMPTR<MEMHeapBase>& memFGHeap, MEMPTR<MEMHeapBase>& mem2Heap)
{
mem1Heap = nullptr;
memFGHeap = nullptr;
mem2Heap = nullptr;
gCoreinitData->MEMAllocFromDefaultHeap = RPLLoader_MakePPCCallable(export_default_MEMAllocFromDefaultHeap);
gCoreinitData->MEMAllocFromDefaultHeapEx = RPLLoader_MakePPCCallable(export_default_MEMAllocFromDefaultHeapEx);
gCoreinitData->MEMFreeToDefaultHeap = RPLLoader_MakePPCCallable(export_default_MEMFreeToDefaultHeap);
if (OSGetForegroundBucket(nullptr, nullptr))
{
MEMPTR<void> memBound;
uint32be memBoundSize;
OSGetMemBound(1, &memBound, &memBoundSize);
mem1Heap = MEMCreateFrmHeapEx(memBound.GetPtr(), (uint32)memBoundSize, 0);
OSGetForegroundBucketFreeArea(&memBound, &memBoundSize);
memFGHeap = MEMCreateFrmHeapEx(memBound.GetPtr(), (uint32)memBoundSize, 0);
}
MEMPTR<void> memBound;
uint32be memBoundSize;
OSGetMemBound(2, &memBound, &memBoundSize);
mem2Heap = MEMDefaultHeap_Init(memBound.GetPtr(), (uint32)memBoundSize);
// set DynLoad allocators
OSDynLoad_SetAllocator(RPLLoader_MakePPCCallable(default_DynLoadAlloc), RPLLoader_MakePPCCallable(default_DynLoadFree));
OSDynLoad_SetTLSAllocator(RPLLoader_MakePPCCallable(default_DynLoadAlloc), RPLLoader_MakePPCCallable(default_DynLoadFree));
}
void CoreInitDefaultHeap(/* ukn */)
{
cemu_assert_unimplemented();
}
void MEMResetToDefaultState()
{
for (auto& it : sHeapBaseHandle)
it = nullptr;
g_heapTableCount = 0;
g_slockInitialized = false;
g_listsInitialized = false;
gDefaultHeap = nullptr;
memset(&g_list1, 0, sizeof(g_list1));
memset(&g_list2, 0, sizeof(g_list2));
memset(&g_list3, 0, sizeof(g_list3));
}
void InitializeMEM()
{
MEMResetToDefaultState();
cafeExportRegister("coreinit", CoreInitDefaultHeap, LogType::CoreinitMem);
osLib_addFunction("coreinit", "MEMInitAllocatorForDefaultHeap", coreinitExport_MEMInitAllocatorForDefaultHeap);
osLib_addFunction("coreinit", "MEMAllocFromAllocator", coreinitExport_MEMAllocFromAllocator);
osLib_addFunction("coreinit", "MEMFreeToAllocator", coreinitExport_MEMFreeToAllocator);
cafeExportRegister("coreinit", MEMGetBaseHeapHandle, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMSetBaseHeapHandle, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMFindContainHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMGetFillValForHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMSetFillValForHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMCreateUserHeapHandle, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMInitList, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMPrependListObject, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMAppendListObject, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMRemoveListObject, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMGetNextListObject, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMGetNthListObject, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMGetPrevListObject, LogType::CoreinitMem);
}
}
| 19,261
|
C++
|
.cpp
| 534
| 32.790262
| 156
| 0.753696
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,113
|
coreinit_BSP.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_BSP.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "coreinit_BSP.h"
namespace coreinit
{
bool bspGetHardwareVersion(uint32be* version)
{
uint8 highVersion = 0x11; // anything below 0x11 will be considered as Hollywood
// todo: Check version returned on console
uint32 tempVers = highVersion << 24;
*version = tempVers;
return true;
}
void InitializeBSP()
{
cafeExportRegister("coreinit", bspGetHardwareVersion, LogType::Placeholder);
}
}
| 452
|
C++
|
.cpp
| 17
| 24.470588
| 82
| 0.771889
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,114
|
coreinit_Callbacks.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_Callbacks.cpp
|
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "util/helpers/fspinlock.h"
struct CoreinitAsyncCallback
{
CoreinitAsyncCallback(MPTR functionMPTR, uint32 numParameters, uint32 r3, uint32 r4, uint32 r5, uint32 r6, uint32 r7, uint32 r8, uint32 r9, uint32 r10) :
m_functionMPTR(functionMPTR), m_numParameters(numParameters), m_gprParam{ r3, r4, r5, r6, r7, r8, r9, r10 } {};
static void queue(MPTR functionMPTR, uint32 numParameters, uint32 r3, uint32 r4, uint32 r5, uint32 r6, uint32 r7, uint32 r8, uint32 r9, uint32 r10)
{
s_asyncCallbackSpinlock.lock();
s_asyncCallbackQueue.emplace_back(allocateAndInitFromPool(functionMPTR, numParameters, r3, r4, r5, r6, r7, r8, r9, r10));
s_asyncCallbackSpinlock.unlock();
}
static void callNextFromQueue()
{
s_asyncCallbackSpinlock.lock();
if (s_asyncCallbackQueue.empty())
{
cemuLog_log(LogType::Force, "AsyncCallbackQueue is empty. Unexpected behavior");
s_asyncCallbackSpinlock.unlock();
return;
}
CoreinitAsyncCallback* cb = s_asyncCallbackQueue[0];
s_asyncCallbackQueue.erase(s_asyncCallbackQueue.begin());
s_asyncCallbackSpinlock.unlock();
cb->doCall();
s_asyncCallbackSpinlock.lock();
releaseToPool(cb);
s_asyncCallbackSpinlock.unlock();
}
private:
void doCall()
{
PPCCoreCallback(m_functionMPTR, m_gprParam[0], m_gprParam[1], m_gprParam[2], m_gprParam[3], m_gprParam[4], m_gprParam[5], m_gprParam[6], m_gprParam[7]);
}
static CoreinitAsyncCallback* allocateAndInitFromPool(MPTR functionMPTR, uint32 numParameters, uint32 r3, uint32 r4, uint32 r5, uint32 r6, uint32 r7, uint32 r8, uint32 r9, uint32 r10)
{
cemu_assert_debug(s_asyncCallbackSpinlock.is_locked());
if (s_asyncCallbackPool.empty())
{
CoreinitAsyncCallback* cb = new CoreinitAsyncCallback(functionMPTR, numParameters, r3, r4, r5, r6, r7, r8, r9, r10);
return cb;
}
CoreinitAsyncCallback* cb = s_asyncCallbackPool[0];
s_asyncCallbackPool.erase(s_asyncCallbackPool.begin());
*cb = CoreinitAsyncCallback(functionMPTR, numParameters, r3, r4, r5, r6, r7, r8, r9, r10);
return cb;
}
static void releaseToPool(CoreinitAsyncCallback* cb)
{
cemu_assert_debug(s_asyncCallbackSpinlock.is_locked());
s_asyncCallbackPool.emplace_back(cb);
}
static std::vector<struct CoreinitAsyncCallback*> s_asyncCallbackPool;
static std::vector<struct CoreinitAsyncCallback*> s_asyncCallbackQueue;
static FSpinlock s_asyncCallbackSpinlock;
sint32 m_numParameters;
uint32 m_gprParam[9];
MPTR m_functionMPTR;
};
std::vector<struct CoreinitAsyncCallback*> CoreinitAsyncCallback::s_asyncCallbackPool;
std::vector<struct CoreinitAsyncCallback*> CoreinitAsyncCallback::s_asyncCallbackQueue;
FSpinlock CoreinitAsyncCallback::s_asyncCallbackSpinlock;
SysAllocator<OSThread_t> g_coreinitCallbackThread;
SysAllocator<uint8, 1024*64> _g_coreinitCallbackThreadStack;
SysAllocator<coreinit::OSSemaphore> g_asyncCallbackAsync;
SysAllocator<char, 32> _g_coreinitCBThreadName;
void _coreinitCallbackThread(PPCInterpreter_t* hCPU)
{
while (coreinit::OSWaitSemaphore(g_asyncCallbackAsync.GetPtr()))
{
CoreinitAsyncCallback::callNextFromQueue();
}
}
void coreinitAsyncCallback_addWithLock(MPTR functionMPTR, uint32 numParameters, uint32 r3, uint32 r4, uint32 r5, uint32 r6, uint32 r7, uint32 r8, uint32 r9, uint32 r10)
{
cemu_assert_debug(numParameters <= 8);
if (functionMPTR >= 0x10000000)
{
cemuLog_log(LogType::Force, fmt::format("Suspicious callback address {0:08x} params: {1:08x} {2:08x} {3:08x} {4:08x}", functionMPTR, r3, r4, r5, r6));
cemuLog_waitForFlush();
}
CoreinitAsyncCallback::queue(functionMPTR, numParameters, r3, r4, r5, r6, r7, r8, r9, r10);
__OSLockScheduler();
coreinit::OSSignalSemaphoreInternal(g_asyncCallbackAsync.GetPtr(), false);
__OSUnlockScheduler();
}
void coreinitAsyncCallback_add(MPTR functionMPTR, uint32 numParameters, uint32 r3, uint32 r4, uint32 r5, uint32 r6, uint32 r7, uint32 r8, uint32 r9, uint32 r10)
{
cemu_assert_debug(__OSHasSchedulerLock() == false); // do not call when holding scheduler lock
coreinitAsyncCallback_addWithLock(functionMPTR, numParameters, r3, r4, r5, r6, r7, r8, r9, r10);
}
void InitializeAsyncCallback()
{
coreinit::OSInitSemaphore(g_asyncCallbackAsync.GetPtr(), 0);
coreinit::OSCreateThreadType(g_coreinitCallbackThread.GetPtr(), PPCInterpreter_makeCallableExportDepr(_coreinitCallbackThread), 0, nullptr, _g_coreinitCallbackThreadStack.GetPtr() + _g_coreinitCallbackThreadStack.GetByteSize(), (sint32)_g_coreinitCallbackThreadStack.GetByteSize(), 0, 7, OSThread_t::THREAD_TYPE::TYPE_IO);
coreinit::OSResumeThread(g_coreinitCallbackThread.GetPtr());
strcpy(_g_coreinitCBThreadName.GetPtr(), "Callback Thread");
coreinit::OSSetThreadName(g_coreinitCallbackThread.GetPtr(), _g_coreinitCBThreadName.GetPtr());
}
| 4,781
|
C++
|
.cpp
| 99
| 45.979798
| 323
| 0.783708
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,115
|
coreinit_LockedCache.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_LockedCache.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit.h"
#include "Cafe/HW/Latte/Core/LatteBufferCache.h"
/*
Locked cache is mapped to the following memory regions:
offset size
core0: 0xFFC00000 0x4000
core1: 0xFFC40000 0x4000
core2: 0xFFC80000 0x4000
*/
#define LC_LOCKED_CACHE_GRANULARITY (0x200) // 512B
#define LC_LOCKED_CACHE_SIZE (0x4000) // 16KB
#define LC_MASK_FREE (0)
#define LC_MASK_RESERVED (1)
#define LC_MASK_RESERVED_END (2) // indicates end of reserved block
namespace coreinit
{
uint8 lcCacheMask[PPC_CORE_COUNT][(LC_LOCKED_CACHE_SIZE + LC_LOCKED_CACHE_GRANULARITY - 1) / LC_LOCKED_CACHE_GRANULARITY] = { 0 };
uint32 lcAllocatedBlocks[PPC_CORE_COUNT] = { 0 };
MPTR lcAddr[] =
{
0xFFC00000, // core 0
0xFFC40000, // core 1
0xFFC80000 // core 2
};
void coreinitExport_LCGetMaxSize(PPCInterpreter_t* hCPU)
{
osLib_returnFromFunction(hCPU, LC_LOCKED_CACHE_SIZE);
}
void coreinitExport_LCAlloc(PPCInterpreter_t* hCPU)
{
//debug_printf("LCAlloc(0x%04x) Thread %08x Core %d", hCPU->gpr[3], coreinitThread_getCurrentThread(hCPU), PPCInterpreter_getCoreIndex(hCPU));
uint32 size = hCPU->gpr[3];
if (size == 0 || size > LC_LOCKED_CACHE_SIZE)
{
debug_printf("LCAlloc: Invalid alloc size %d\n", size);
osLib_returnFromFunction(hCPU, MPTR_NULL);
return;
}
if ((size % LC_LOCKED_CACHE_GRANULARITY) != 0)
{
debug_printf("LCAlloc: Unaligned alloc size 0x%04x\n", size);
size += (LC_LOCKED_CACHE_GRANULARITY - 1);
size &= ~(LC_LOCKED_CACHE_GRANULARITY - 1);
}
uint32 coreIndex = PPCInterpreter_getCoreIndex(hCPU);
uint8* cacheMask = lcCacheMask[coreIndex];
uint32 entryMaskLength = size / LC_LOCKED_CACHE_GRANULARITY;
for (uint32 i = 0; i <= (LC_LOCKED_CACHE_SIZE / LC_LOCKED_CACHE_GRANULARITY) - entryMaskLength; i++)
{
// check if range starting at i is free
bool rangeIsFree = true;
for (uint32 f = 0; f < entryMaskLength; f++)
{
if (cacheMask[i + f] != LC_MASK_FREE)
{
rangeIsFree = false;
break;
}
}
if (rangeIsFree)
{
// found space for allocation
MPTR allocAddr = lcAddr[coreIndex] + i * LC_LOCKED_CACHE_GRANULARITY;
// mark range as allocated
for (uint32 f = 0; f < entryMaskLength - 1; f++)
{
cacheMask[i + f] = LC_MASK_RESERVED;
}
cacheMask[i + entryMaskLength - 1] = LC_MASK_RESERVED_END;
// update allocation counter
lcAllocatedBlocks[coreIndex] += entryMaskLength;
// return allocAddr
//debug_printf("LCAlloc result %08x Thread %08x Core %d", (uint32)allocAddr, coreinitThread_getCurrentThread(hCPU), PPCInterpreter_getCoreIndex(hCPU));
osLib_returnFromFunction(hCPU, allocAddr);
return;
}
}
// not enough space left
//debug_printf("LCAlloc failed Thread %08x Core %d", coreinitThread_getCurrentThread(hCPU), PPCInterpreter_getCoreIndex(hCPU));
osLib_returnFromFunction(hCPU, MPTR_NULL);
}
void coreinitExport_LCDealloc(PPCInterpreter_t* hCPU)
{
uint32 coreIndex = PPCInterpreter_getCoreIndex(hCPU);
uint8* cacheMask = lcCacheMask[coreIndex];
//printf("LCDealloc(0x%08x)\n", hCPU->gpr[3]);
MPTR deallocAddr = hCPU->gpr[3];
if (deallocAddr < lcAddr[coreIndex] || deallocAddr >= (lcAddr[coreIndex] + LC_LOCKED_CACHE_SIZE))
{
// out of bounds
#ifdef CEMU_DEBUG_ASSERT
cemuLog_log(LogType::Force, "LCDealloc(): Out of bounds");
#endif
osLib_returnFromFunction(hCPU, 0);
return;
}
uint32 relativeOffset = (uint32)deallocAddr - lcAddr[coreIndex];
if ((relativeOffset % LC_LOCKED_CACHE_GRANULARITY) != 0)
{
debug_printf("LCDealloc: Offset alignment is invalid (0x%08x / 0x%08x)\n", deallocAddr, relativeOffset);
osLib_returnFromFunction(hCPU, 0);
return;
}
uint32 startIndex = relativeOffset / LC_LOCKED_CACHE_GRANULARITY;
// check this is really the beginning of an allocated block
if (startIndex > 0 && (cacheMask[startIndex - 1] != LC_MASK_RESERVED_END && cacheMask[startIndex - 1] != LC_MASK_FREE))
{
debug_printf("LCDealloc: Offset is invalid (0x%08x / 0x%08x)\n", deallocAddr, relativeOffset);
osLib_returnFromFunction(hCPU, 0);
return;
}
// free range by reseting mask in allocated region
for (uint32 i = startIndex; i < (LC_LOCKED_CACHE_SIZE / LC_LOCKED_CACHE_GRANULARITY); i++)
{
if (cacheMask[i] == LC_MASK_RESERVED_END)
{
// end of allocated block reached
cacheMask[i] = LC_MASK_FREE;
// update allocation counter
lcAllocatedBlocks[coreIndex]--;
break;
}
else if (cacheMask[i] == LC_MASK_FREE)
{
debug_printf("LCDealloc: Allocation mask error detected\n");
break;
}
cacheMask[i] = LC_MASK_FREE;
// update allocation counter
lcAllocatedBlocks[coreIndex]--;
}
osLib_returnFromFunction(hCPU, 0);
}
void coreinitExport_LCGetUnallocated(PPCInterpreter_t* hCPU)
{
uint32 unallocatedBytes = 0;
uint32 coreIndex = PPCInterpreter_getCoreIndex(hCPU);
unallocatedBytes = LC_LOCKED_CACHE_SIZE - (lcAllocatedBlocks[coreIndex] * LC_LOCKED_CACHE_GRANULARITY);
//debug_printf("LCGetUnallocated() Result: 0x%x\n", unallocatedBytes);
osLib_returnFromFunction(hCPU, unallocatedBytes);
}
void coreinitExport_LCGetAllocatableSize(PPCInterpreter_t* hCPU)
{
debug_printf("LCGetAllocatableSize()\n");
// no parameters, returns largest allocatable block size
// get core LC parameters
uint32 coreIndex = PPCInterpreter_getCoreIndex(hCPU);
uint8* cacheMask = lcCacheMask[coreIndex];
// scan for largest range of available blocks
uint32 largestFreeRange = 0;
uint32 currentRangeSize = 0;
for (uint32 i = 0; i < LC_LOCKED_CACHE_SIZE / LC_LOCKED_CACHE_GRANULARITY; i++)
{
if (cacheMask[i] == LC_MASK_FREE)
{
currentRangeSize++;
}
else
{
largestFreeRange = std::max(largestFreeRange, currentRangeSize);
currentRangeSize = 0;
}
}
largestFreeRange = std::max(largestFreeRange, currentRangeSize);
osLib_returnFromFunction(hCPU, largestFreeRange * LC_LOCKED_CACHE_GRANULARITY);
}
uint32 LCIsEnabled[PPC_CORE_COUNT] = { 0 };
void coreinitExport_LCEnableDMA(PPCInterpreter_t* hCPU)
{
//debug_printf("LCEnableDMA()\n");
LCIsEnabled[PPCInterpreter_getCoreIndex(hCPU)]++;
osLib_returnFromFunction(hCPU, 1);
}
sint32 _lcDisableErrorCounter = 0;
void coreinitExport_LCDisableDMA(PPCInterpreter_t* hCPU)
{
//debug_printf("LCDisableDMA()\n");
#ifndef PUBLIC_RELASE
if (LCIsEnabled[PPCInterpreter_getCoreIndex(hCPU)] == 0)
assert_dbg();
#endif
LCIsEnabled[PPCInterpreter_getCoreIndex(hCPU)]--;
#ifdef CEMU_DEBUG_ASSERT
if (LCIsEnabled[PPCInterpreter_getCoreIndex(hCPU)] == 0)
{
uint32 coreIndex = PPCInterpreter_getCoreIndex(hCPU);
uint8* cacheMask = lcCacheMask[coreIndex];
for (uint32 i = 0; i <= (LC_LOCKED_CACHE_SIZE / LC_LOCKED_CACHE_GRANULARITY); i++)
{
if (cacheMask[i] != LC_MASK_FREE)
{
if (_lcDisableErrorCounter < 15)
{
cemuLog_log(LogType::Force, "LC disabled but there is still memory allocated");
_lcDisableErrorCounter++;
}
}
}
}
#endif
osLib_returnFromFunction(hCPU, 1);
}
void coreinitExport_LCIsDMAEnabled(PPCInterpreter_t* hCPU)
{
osLib_returnFromFunction(hCPU, LCIsEnabled[PPCInterpreter_getCoreIndex(hCPU)] ? 1 : 0);
}
void coreinitExport_LCHardwareIsAvailable(PPCInterpreter_t* hCPU)
{
// on the real HW, LC is shared between processes and not all processes can access it. In the emulator we don't care and always return true.
osLib_returnFromFunction(hCPU, 1);
}
void coreinitExport_LCLoadDMABlocks(PPCInterpreter_t* hCPU)
{
//printf("LCLoadDMABlocks(0x%08x, 0x%08x, 0x%08x)\n", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
uint32 numBlocks = hCPU->gpr[5];
if (numBlocks == 0)
numBlocks = 128;
uint32 transferSize = numBlocks * 32;
uint8* destPtr = memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
uint8* srcPtr = memory_getPointerFromVirtualOffset(hCPU->gpr[4]);
// copy right away, we don't emulate the DMAQueue currently
memcpy(destPtr, srcPtr, transferSize);
osLib_returnFromFunction(hCPU, 0);
}
void coreinitExport_LCStoreDMABlocks(PPCInterpreter_t* hCPU)
{
//printf("LCStoreDMABlocks(0x%08x, 0x%08x, 0x%08x)\n", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
uint32 numBlocks = hCPU->gpr[5];
if (numBlocks == 0)
numBlocks = 128;
//uint32 transferSize = numBlocks*32;
uint8* destPtr = memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
uint8* srcPtr = memory_getPointerFromVirtualOffset(hCPU->gpr[4]);
// copy right away, we don't emulate the DMAQueue currently
memcpy_qwords(destPtr, srcPtr, numBlocks * (32 / sizeof(uint64)));
LatteBufferCache_notifyDCFlush(hCPU->gpr[3], numBlocks * 32);
osLib_returnFromFunction(hCPU, 0);
}
void coreinitExport_LCWaitDMAQueue(PPCInterpreter_t* hCPU)
{
//printf("LCWaitDMAQueue(%d)\n", hCPU->gpr[3]);
uint32 len = hCPU->gpr[3];
// todo: Implement (be aware DMA queue is per core)
osLib_returnFromFunction(hCPU, 0);
}
void InitializeLC()
{
for (sint32 f = 0; f < PPC_CORE_COUNT; f++)
{
memset(lcCacheMask[f], LC_MASK_FREE, (LC_LOCKED_CACHE_SIZE + LC_LOCKED_CACHE_GRANULARITY - 1) / LC_LOCKED_CACHE_GRANULARITY);
}
osLib_addFunction("coreinit", "LCGetMaxSize", coreinitExport_LCGetMaxSize);
osLib_addFunction("coreinit", "LCAlloc", coreinitExport_LCAlloc);
osLib_addFunction("coreinit", "LCDealloc", coreinitExport_LCDealloc);
osLib_addFunction("coreinit", "LCGetUnallocated", coreinitExport_LCGetUnallocated);
osLib_addFunction("coreinit", "LCGetAllocatableSize", coreinitExport_LCGetAllocatableSize);
osLib_addFunction("coreinit", "LCEnableDMA", coreinitExport_LCEnableDMA);
osLib_addFunction("coreinit", "LCDisableDMA", coreinitExport_LCDisableDMA);
osLib_addFunction("coreinit", "LCIsDMAEnabled", coreinitExport_LCIsDMAEnabled);
osLib_addFunction("coreinit", "LCHardwareIsAvailable", coreinitExport_LCHardwareIsAvailable);
osLib_addFunction("coreinit", "LCLoadDMABlocks", coreinitExport_LCLoadDMABlocks);
osLib_addFunction("coreinit", "LCStoreDMABlocks", coreinitExport_LCStoreDMABlocks);
osLib_addFunction("coreinit", "LCWaitDMAQueue", coreinitExport_LCWaitDMAQueue);
}
}
| 10,153
|
C++
|
.cpp
| 266
| 34.87218
| 155
| 0.729754
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,116
|
coreinit_Misc.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_Misc.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_Misc.h"
#include "Cafe/OS/libs/coreinit/coreinit_MessageQueue.h"
#include "Cafe/CafeSystem.h"
#include "Cafe/Filesystem/fsc.h"
#include <pugixml.hpp>
namespace coreinit
{
sint32 ppc_vprintf(const char* formatStr, char* strOut, sint32 maxLength, ppc_va_list* vargs)
{
char tempStr[4096];
sint32 writeIndex = 0;
while (*formatStr)
{
char c = *formatStr;
if (c == '%')
{
const char* formatStart = formatStr;
formatStr++;
if (*formatStr == '%')
{
// percent sign
if (writeIndex >= maxLength)
break;
strOut[writeIndex] = '%';
writeIndex++;
formatStr++;
continue;
}
// flags
bool flag_leftJustify = false;
bool flag_zeroPadding = false;
if (*formatStr == '-')
{
flag_leftJustify = true;
formatStr++;
}
if (*formatStr == '+')
{
// todo
formatStr++;
}
if (*formatStr == ' ')
{
// todo
formatStr++;
}
if (*formatStr == '#')
{
// todo
formatStr++;
}
if (*formatStr == '0')
{
flag_zeroPadding = true;
formatStr++;
}
// width
if (*formatStr == '*')
{
cemu_assert_debug(false);
formatStr++;
}
bool widthIsSpecified = false;
sint32 width = 0;
while (*formatStr >= '0' && *formatStr <= '9')
{
width *= 10;
width += (*formatStr - '0');
formatStr++;
widthIsSpecified = true;
}
// precision
if (*formatStr == '.')
{
formatStr++;
if (*formatStr == '*')
{
cemu_assert_debug(false);
}
while (*formatStr >= '0' && *formatStr <= '9')
{
formatStr++;
}
}
// length + specifier
char tempFormat[64];
if (*formatStr == 'X' || *formatStr == 'x' || *formatStr == 'u' || *formatStr == 'd' || *formatStr == 'p' || *formatStr == 'i' ||
(formatStr[0] == 'l' && formatStr[1] == 'd'))
{
// number
formatStr++;
strncpy(tempFormat, formatStart, std::min((std::ptrdiff_t)sizeof(tempFormat) - 1, formatStr - formatStart));
if ((formatStr - formatStart) < sizeof(tempFormat))
tempFormat[(formatStr - formatStart)] = '\0';
else
tempFormat[sizeof(tempFormat) - 1] = '\0';
sint32 tempLen = sprintf(tempStr, tempFormat, (uint32)*(uint32be*)_ppc_va_arg(vargs, ppc_va_type::INT32));
for (sint32 i = 0; i < tempLen; i++)
{
if (writeIndex >= maxLength)
break;
strOut[writeIndex] = tempStr[i];
writeIndex++;
}
}
else if (*formatStr == 's')
{
// string
formatStr++;
strncpy(tempFormat, formatStart, std::min((std::ptrdiff_t)sizeof(tempFormat) - 1, formatStr - formatStart));
if ((formatStr - formatStart) < sizeof(tempFormat))
tempFormat[(formatStr - formatStart)] = '\0';
else
tempFormat[sizeof(tempFormat) - 1] = '\0';
MPTR strOffset = *(uint32be*)_ppc_va_arg(vargs, ppc_va_type::INT32);
sint32 tempLen = 0;
if (strOffset == MPTR_NULL)
tempLen = sprintf(tempStr, "NULL");
else
tempLen = sprintf(tempStr, tempFormat, memory_getPointerFromVirtualOffset(strOffset));
for (sint32 i = 0; i < tempLen; i++)
{
if (writeIndex >= maxLength)
break;
strOut[writeIndex] = tempStr[i];
writeIndex++;
}
strOut[std::min(maxLength - 1, writeIndex)] = '\0';
}
else if (*formatStr == 'c')
{
// character
formatStr++;
strncpy(tempFormat, formatStart, std::min((std::ptrdiff_t)sizeof(tempFormat) - 1, formatStr - formatStart));
if ((formatStr - formatStart) < sizeof(tempFormat))
tempFormat[(formatStr - formatStart)] = '\0';
else
tempFormat[sizeof(tempFormat) - 1] = '\0';
sint32 tempLen = sprintf(tempStr, tempFormat, (uint32)*(uint32be*)_ppc_va_arg(vargs, ppc_va_type::INT32));
for (sint32 i = 0; i < tempLen; i++)
{
if (writeIndex >= maxLength)
break;
strOut[writeIndex] = tempStr[i];
writeIndex++;
}
}
else if (*formatStr == 'f' || *formatStr == 'g' || *formatStr == 'G')
{
formatStr++;
strncpy(tempFormat, formatStart, std::min((std::ptrdiff_t)sizeof(tempFormat) - 1, formatStr - formatStart));
if ((formatStr - formatStart) < sizeof(tempFormat))
tempFormat[(formatStr - formatStart)] = '\0';
else
tempFormat[sizeof(tempFormat) - 1] = '\0';
sint32 tempLen = sprintf(tempStr, tempFormat, (double)*(betype<double>*)_ppc_va_arg(vargs, ppc_va_type::FLOAT_OR_DOUBLE));
for (sint32 i = 0; i < tempLen; i++)
{
if (writeIndex >= maxLength)
break;
strOut[writeIndex] = tempStr[i];
writeIndex++;
}
}
else if (formatStr[0] == 'l' && formatStr[1] == 'f')
{
// double
formatStr += 2;
strncpy(tempFormat, formatStart, std::min((std::ptrdiff_t)sizeof(tempFormat) - 1, formatStr - formatStart));
if ((formatStr - formatStart) < sizeof(tempFormat))
tempFormat[(formatStr - formatStart)] = '\0';
else
tempFormat[sizeof(tempFormat) - 1] = '\0';
sint32 tempLen = sprintf(tempStr, tempFormat, (double)*(betype<double>*)_ppc_va_arg(vargs, ppc_va_type::FLOAT_OR_DOUBLE));
for (sint32 i = 0; i < tempLen; i++)
{
if (writeIndex >= maxLength)
break;
strOut[writeIndex] = tempStr[i];
writeIndex++;
}
}
else if ((formatStr[0] == 'l' && formatStr[1] == 'l' && (formatStr[2] == 'x' || formatStr[2] == 'X')))
{
formatStr += 3;
// 64bit int
strncpy(tempFormat, formatStart, std::min((std::ptrdiff_t)sizeof(tempFormat) - 1, formatStr - formatStart));
if ((formatStr - formatStart) < sizeof(tempFormat))
tempFormat[(formatStr - formatStart)] = '\0';
else
tempFormat[sizeof(tempFormat) - 1] = '\0';
sint32 tempLen = sprintf(tempStr, tempFormat, (uint64)*(uint64be*)_ppc_va_arg(vargs, ppc_va_type::INT64));
for (sint32 i = 0; i < tempLen; i++)
{
if (writeIndex >= maxLength)
break;
strOut[writeIndex] = tempStr[i];
writeIndex++;
}
}
else if ((formatStr[0] == 'l' && formatStr[1] == 'l' && formatStr[2] == 'd'))
{
formatStr += 3;
// signed integer (64bit)
strncpy(tempFormat, formatStart, std::min((std::ptrdiff_t)sizeof(tempFormat) - 1, formatStr - formatStart));
if ((formatStr - formatStart) < sizeof(tempFormat))
tempFormat[(formatStr - formatStart)] = '\0';
else
tempFormat[sizeof(tempFormat) - 1] = '\0';
sint32 tempLen = sprintf(tempStr, tempFormat, (sint64)*(sint64be*)_ppc_va_arg(vargs, ppc_va_type::INT64));
for (sint32 i = 0; i < tempLen; i++)
{
if (writeIndex >= maxLength)
break;
strOut[writeIndex] = tempStr[i];
writeIndex++;
}
}
else
{
// unsupported / unknown specifier
cemu_assert_debug(false);
break;
}
}
else
{
if (writeIndex >= maxLength)
break;
strOut[writeIndex] = c;
writeIndex++;
formatStr++;
}
}
strOut[std::min(writeIndex, maxLength - 1)] = '\0';
return std::min(writeIndex, maxLength - 1);
}
/* coreinit logging and string format */
sint32 __os_snprintf(char* outputStr, sint32 maxLength, const char* formatStr)
{
ppc_define_va_list(3, 0);
sint32 r = ppc_vprintf(formatStr, outputStr, maxLength, &vargs);
return r;
}
enum class CafeLogType
{
OSCONSOLE = 0,
};
struct CafeLogBuffer
{
std::array<char, 270> lineBuffer;
size_t lineLength{};
};
CafeLogBuffer g_logBuffer_OSReport;
CafeLogBuffer& getLogBuffer(CafeLogType cafeLogType)
{
if (cafeLogType == CafeLogType::OSCONSOLE)
return g_logBuffer_OSReport;
// default to OSReport
return g_logBuffer_OSReport;
}
std::string_view getLogBufferName(CafeLogType cafeLogType)
{
if (cafeLogType == CafeLogType::OSCONSOLE)
return "OSConsole";
return "Unknown";
}
std::mutex sCafeConsoleMutex;
void WriteCafeConsole(CafeLogType cafeLogType, const char* msg, sint32 len)
{
std::unique_lock _l(sCafeConsoleMutex);
CafeLogBuffer& logBuffer = getLogBuffer(cafeLogType);
// once a line is full or \n is written it will be posted to log
auto flushLine = [](CafeLogBuffer& cafeLogBuffer, std::string_view cafeLogName) -> void
{
cemuLog_log(LogType::CoreinitLogging, "[{0}] {1}", cafeLogName, std::basic_string_view(cafeLogBuffer.lineBuffer.data(), cafeLogBuffer.lineLength));
cafeLogBuffer.lineLength = 0;
};
while (len)
{
char c = *msg;
msg++;
len--;
if (c == '\r')
continue;
if (c == '\n')
{
// flush line immediately
flushLine(logBuffer, getLogBufferName(cafeLogType));
continue;
}
logBuffer.lineBuffer[logBuffer.lineLength] = c;
logBuffer.lineLength++;
if (logBuffer.lineLength >= logBuffer.lineBuffer.size())
flushLine(logBuffer, getLogBufferName(cafeLogType));
}
}
void COSVReport(COSReportModule module, COSReportLevel level, const char* format, ppc_va_list* vargs)
{
char tmpBuffer[1024];
sint32 len = ppc_vprintf(format, tmpBuffer, sizeof(tmpBuffer), vargs);
WriteCafeConsole(CafeLogType::OSCONSOLE, tmpBuffer, len);
}
void OSReport(const char* format)
{
ppc_define_va_list(1, 0);
COSVReport(COSReportModule::coreinit, COSReportLevel::Info, format, &vargs);
}
void OSVReport(const char* format, ppc_va_list* vargs)
{
COSVReport(COSReportModule::coreinit, COSReportLevel::Info, format, vargs);
}
void COSWarn(int moduleId, const char* format)
{
ppc_define_va_list(2, 0);
char tmpBuffer[1024];
int prefixLen = sprintf(tmpBuffer, "[COSWarn-%d] ", moduleId);
sint32 len = ppc_vprintf(format, tmpBuffer + prefixLen, sizeof(tmpBuffer) - prefixLen, &vargs);
WriteCafeConsole(CafeLogType::OSCONSOLE, tmpBuffer, len + prefixLen);
}
void OSLogPrintf(int ukn1, int ukn2, int ukn3, const char* format)
{
ppc_define_va_list(4, 0);
char tmpBuffer[1024];
int prefixLen = sprintf(tmpBuffer, "[OSLogPrintf-%d-%d-%d] ", ukn1, ukn2, ukn3);
sint32 len = ppc_vprintf(format, tmpBuffer + prefixLen, sizeof(tmpBuffer) - prefixLen, &vargs);
WriteCafeConsole(CafeLogType::OSCONSOLE, tmpBuffer, len + prefixLen);
}
void OSConsoleWrite(const char* strPtr, sint32 length)
{
if (length < 0)
return;
WriteCafeConsole(CafeLogType::OSCONSOLE, strPtr, length);
}
/* home button menu */
bool g_homeButtonMenuEnabled = false;
bool OSIsHomeButtonMenuEnabled()
{
return g_homeButtonMenuEnabled;
}
bool OSEnableHomeButtonMenu(bool enable)
{
g_homeButtonMenuEnabled = enable;
return true;
}
uint32 OSGetPFID()
{
return 15; // hardcoded as game
}
uint32 OSGetUPID()
{
return OSGetPFID();
}
uint64 s_currentTitleId;
uint64 OSGetTitleID()
{
return s_currentTitleId;
}
uint32 s_sdkVersion;
uint32 __OSGetProcessSDKVersion()
{
return s_sdkVersion;
}
// move this to CafeSystem.cpp?
void OSLauncherThread(uint64 titleId)
{
CafeSystem::ShutdownTitle();
CafeSystem::PrepareForegroundTitle(titleId);
CafeSystem::RequestRecreateCanvas();
CafeSystem::LaunchForegroundTitle();
}
uint32 __LaunchByTitleId(uint64 titleId, uint32 argc, MEMPTR<char>* argv)
{
// prepare argument buffer
#if 0
char argumentBuffer[4096];
uint32 argumentBufferLength = 0;
char* argWriter = argumentBuffer;
for(uint32 i=0; i<argc; i++)
{
const char* arg = argv[i];
uint32 argLength = strlen(arg);
if((argumentBufferLength + argLength + 1) >= sizeof(argumentBuffer))
{
// argument buffer full
cemuLog_logDebug(LogType::Force, "LaunchByTitleId: argument buffer full");
return 0x80000000;
}
memcpy(argWriter, arg, argLength);
argWriter[argLength] = '\0';
argWriter += argLength + 1;
argumentBufferLength += argLength + 1;
}
#endif
// normally the above buffer is passed to the PPC kernel via syscall 0x2B and then
// the kernel forwards it to IOSU MCP when requesting a title launch
// but for now we HLE most of the launching code and can just set the argument array directly
std::vector<std::string> argArray;
for(uint32 i=0; i<argc; i++)
argArray.emplace_back(argv[i]);
CafeSystem::SetOverrideArgs(argArray);
// spawn launcher thread (this current thread will be destroyed during relaunch)
std::thread launcherThread(OSLauncherThread, titleId);
launcherThread.detach();
// suspend this thread
coreinit::OSSuspendThread(coreinit::OSGetCurrentThread());
return 0;
}
uint32 OSLaunchTitleByPathl(const char* path, uint32 pathLength, uint32 argc)
{
char appXmlPath[1024];
cemu_assert_debug(argc == 0); // custom args not supported yet
if(pathLength >= (sizeof(appXmlPath) - 32))
{
// path too long
cemuLog_logDebug(LogType::Force, "OSLaunchTitleByPathl: path too long");
return 0x80000000;
}
// read app.xml to get the titleId
memcpy(appXmlPath, path, pathLength);
appXmlPath[pathLength] = '\0';
strcat(appXmlPath, "/code/app.xml");
sint32 status;
auto fscfile = fsc_open(appXmlPath, FSC_ACCESS_FLAG::OPEN_FILE | FSC_ACCESS_FLAG::READ_PERMISSION, &status);
if (!fscfile)
{
cemuLog_logDebug(LogType::Force, "OSLaunchTitleByPathl: failed to open target app.xml");
return 0x80000000;
}
uint32 size = fsc_getFileSize(fscfile);
std::vector<uint8> tmpData(size);
fsc_readFile(fscfile, tmpData.data(), size);
fsc_close(fscfile);
// parse app.xml to get the titleId
pugi::xml_document app_doc;
if (!app_doc.load_buffer_inplace(tmpData.data(), tmpData.size()))
return false;
uint64 titleId = std::stoull(app_doc.child("app").child("title_id").child_value(), nullptr, 16);
if(titleId == 0)
{
cemuLog_logDebug(LogType::Force, "OSLaunchTitleByPathl: failed to parse titleId from app.xml");
return 0x80000000;
}
__LaunchByTitleId(titleId, 0, nullptr);
return 0;
}
uint32 OSRestartGame(uint32 argc, MEMPTR<char>* argv)
{
__LaunchByTitleId(CafeSystem::GetForegroundTitleId(), argc, argv);
return 0;
}
void OSReleaseForeground()
{
cemuLog_logDebug(LogType::Force, "OSReleaseForeground not implemented");
}
bool s_transitionToBackground = false;
bool s_transitionToForeground = false;
void StartBackgroundForegroundTransition()
{
s_transitionToBackground = true;
s_transitionToForeground = true;
}
// called at the beginning of OSReceiveMessage if the queue is the system message queue
void UpdateSystemMessageQueue()
{
if(!OSIsInterruptEnabled())
return;
cemu_assert_debug(!__OSHasSchedulerLock());
// normally syscall 0x2E is used to get the next message
// for now we just have some preliminary logic here to allow a fake transition to background & foreground
if(s_transitionToBackground)
{
// add transition to background message
OSMessage msg{};
msg.data0 = stdx::to_underlying(SysMessageId::MsgReleaseForeground);
msg.data1 = 0; // 1 -> System is shutting down 0 -> Begin transitioning to background
OSMessageQueue* systemMessageQueue = coreinit::OSGetSystemMessageQueue();
if(OSSendMessage(systemMessageQueue, &msg, 0))
s_transitionToBackground = false;
return;
}
if(s_transitionToForeground)
{
// add transition to foreground message
OSMessage msg{};
msg.data0 = stdx::to_underlying(SysMessageId::MsgAcquireForeground);
msg.data1 = 1; // ?
msg.data2 = 1; // ?
OSMessageQueue* systemMessageQueue = coreinit::OSGetSystemMessageQueue();
if(OSSendMessage(systemMessageQueue, &msg, 0))
s_transitionToForeground = false;
return;
}
}
// called when OSReceiveMessage returns a message from the system message queue
void HandleReceivedSystemMessage(OSMessage* msg)
{
cemu_assert_debug(!__OSHasSchedulerLock());
cemuLog_log(LogType::Force, "Receiving message: {:08x}", (uint32)msg->data0);
}
uint32 OSDriver_Register(uint32 moduleHandle, sint32 priority, OSDriverInterface* driverCallbacks, sint32 driverId, uint32be* outUkn1, uint32be* outUkn2, uint32be* outUkn3)
{
cemuLog_logDebug(LogType::Force, "OSDriver_Register stubbed");
return 0;
}
uint32 OSDriver_Deregister(uint32 moduleHandle, sint32 driverId)
{
cemuLog_logDebug(LogType::Force, "OSDriver_Deregister stubbed");
return 0;
}
void miscInit()
{
s_currentTitleId = CafeSystem::GetForegroundTitleId();
s_sdkVersion = CafeSystem::GetForegroundTitleSDKVersion();
s_transitionToBackground = false;
s_transitionToForeground = false;
cafeExportRegister("coreinit", __os_snprintf, LogType::Placeholder);
cafeExportRegister("coreinit", COSVReport, LogType::Placeholder);
cafeExportRegister("coreinit", COSWarn, LogType::Placeholder);
cafeExportRegister("coreinit", OSReport, LogType::Placeholder);
cafeExportRegister("coreinit", OSVReport, LogType::Placeholder);
cafeExportRegister("coreinit", OSLogPrintf, LogType::Placeholder);
cafeExportRegister("coreinit", OSConsoleWrite, LogType::Placeholder);
cafeExportRegister("coreinit", OSGetPFID, LogType::Placeholder);
cafeExportRegister("coreinit", OSGetUPID, LogType::Placeholder);
cafeExportRegister("coreinit", OSGetTitleID, LogType::Placeholder);
cafeExportRegister("coreinit", __OSGetProcessSDKVersion, LogType::Placeholder);
g_homeButtonMenuEnabled = true; // enabled by default
// Disney Infinity 2.0 actually relies on home button menu being enabled by default. If it's false it will crash due to calling erreula->IsAppearHomeNixSign() before initializing erreula
cafeExportRegister("coreinit", OSIsHomeButtonMenuEnabled, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSEnableHomeButtonMenu, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSLaunchTitleByPathl, LogType::Placeholder);
cafeExportRegister("coreinit", OSRestartGame, LogType::Placeholder);
cafeExportRegister("coreinit", OSReleaseForeground, LogType::Placeholder);
cafeExportRegister("coreinit", OSDriver_Register, LogType::Placeholder);
cafeExportRegister("coreinit", OSDriver_Deregister, LogType::Placeholder);
}
};
| 17,960
|
C++
|
.cpp
| 539
| 29.150278
| 188
| 0.686065
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,117
|
coreinit_CodeGen.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_CodeGen.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/libs/coreinit/coreinit_CodeGen.h"
#include "Cafe/HW/Espresso/Recompiler/PPCRecompiler.h"
#include "Common/ExceptionHandler/ExceptionHandler.h"
namespace coreinit
{
struct
{
bool rangeIsAllocated;
MPTR rangeStart;
uint32 rangeSize;
uint8* cacheStateCopy; // holds a copy of the entire range, simulates icache state (updated via ICBI)
}coreinitCodeGen = {0};
void codeGenArea_memoryWriteCallback(void* pageStart, size_t size)
{
uint32 ea = memory_getVirtualOffsetFromPointer(pageStart);
uint32 eaEnd = ea + (uint32)size;
while (ea <= eaEnd)
{
codeGenHandleICBI(ea);
ea += 0x20;
}
}
void OSGetCodegenVirtAddrRange(betype<uint32>* rangeStart, betype<uint32>* rangeSize)
{
uint32 codegenSize = 0x01000000; // todo: Read from cos.xml
//debug_printf("OSGetCodegenVirtAddrRange(0x%08x,0x%08x)\n", hCPU->gpr[3], hCPU->gpr[4]);
// on first call, allocate range
if( coreinitCodeGen.rangeIsAllocated == false )
{
coreinitCodeGen.rangeStart = RPLLoader_AllocateCodeSpace(codegenSize, 0x1000);
coreinitCodeGen.rangeSize = codegenSize;
coreinitCodeGen.cacheStateCopy = new uint8[codegenSize];
memset(coreinitCodeGen.cacheStateCopy, 0, codegenSize);
coreinitCodeGen.rangeIsAllocated = true;
}
*rangeStart = coreinitCodeGen.rangeStart;
*rangeSize = coreinitCodeGen.rangeSize;
}
void OSGetCodegenVirtAddrRangeInternal(uint32& rangeStart, uint32& rangeSize)
{
if (coreinitCodeGen.rangeIsAllocated == 0)
{
rangeStart = 0;
rangeSize = 0;
return;
}
rangeStart = coreinitCodeGen.rangeStart;
rangeSize = coreinitCodeGen.rangeSize;
}
void ICInvalidateRange(uint32 startAddress, uint32 size)
{
uint32 ea = startAddress & ~0x1F;
uint32 eaEnd = (startAddress + size + 0x1F)&~0x1F;
while (ea <= eaEnd)
{
codeGenHandleICBI(ea);
ea += 0x20;
}
}
void coreinitExport_OSCodegenCopy(PPCInterpreter_t* hCPU)
{
if( coreinitCodeGen.rangeIsAllocated == false )
assert_dbg();
uint32 codeAddrDest = hCPU->gpr[3];
uint32 memAddrSrc = hCPU->gpr[4];
uint32 size = hCPU->gpr[5];
if( codeAddrDest < coreinitCodeGen.rangeStart || codeAddrDest >= (coreinitCodeGen.rangeStart+coreinitCodeGen.rangeSize) )
assert_dbg();
if( (codeAddrDest+size) < coreinitCodeGen.rangeStart || (codeAddrDest+size) > (coreinitCodeGen.rangeStart+coreinitCodeGen.rangeSize) )
assert_dbg();
memcpy(memory_getPointerFromVirtualOffset(codeAddrDest), memory_getPointerFromVirtualOffset(memAddrSrc), size);
// invalidate recompiler range
uint32 ea = codeAddrDest & ~0x1F;
uint32 eaEnd = (codeAddrDest + size + 0x1F)&~0x1F;
while (ea <= eaEnd)
{
codeGenHandleICBI(ea);
ea += 0x20;
}
osLib_returnFromFunction(hCPU, 0);
}
void codeGenHandleICBI(uint32 ea)
{
cemu_assert_debug((ea & 0x1F) == 0);
if (coreinitCodeGen.rangeIsAllocated == false)
return;
cemu_assert_debug((coreinitCodeGen.rangeStart & 0x1F) == 0);
cemu_assert_debug((coreinitCodeGen.rangeSize & 0x1F) == 0);
if (ea >= coreinitCodeGen.rangeStart && ea < (coreinitCodeGen.rangeStart + coreinitCodeGen.rangeSize))
{
uint8* cacheCopy = coreinitCodeGen.cacheStateCopy + (ea - coreinitCodeGen.rangeStart);
uint8* currentState = memory_getPointerFromVirtualOffset(ea);
if (memcmp(currentState, cacheCopy, 32) != 0)
{
// instructions changed
// flush cache
PPCRecompiler_invalidateRange(ea, ea+0x20);
// update icache copy
memcpy(cacheCopy, currentState, 32);
}
}
}
bool _avoidCodeGenJIT = false;
// currently we dont handle code invalidation well for direct write access
// therefore if we detect attempts to write we will disable JITing the area
bool codeGenShouldAvoid()
{
return _avoidCodeGenJIT;
}
bool OSSwitchSecCodeGenMode(bool isRXOnly)
{
if (!_avoidCodeGenJIT)
{
cemuLog_log(LogType::Force, "Disable JIT on dynamic code area");
}
_avoidCodeGenJIT = true; // this function getting called is usually a sign that
// does this have a return value?
return true;
}
void InitializeCodeGen()
{
cafeExportRegister("coreinit", OSGetCodegenVirtAddrRange, LogType::Placeholder);
cafeExportRegister("coreinit", ICInvalidateRange, LogType::Placeholder);
osLib_addFunction("coreinit", "OSCodegenCopy", coreinitExport_OSCodegenCopy);
cafeExportRegister("coreinit", OSSwitchSecCodeGenMode, LogType::Placeholder);
}
}
| 4,433
|
C++
|
.cpp
| 129
| 31.325581
| 136
| 0.754492
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,118
|
coreinit_MessageQueue.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_MessageQueue.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_MessageQueue.h"
namespace coreinit
{
void UpdateSystemMessageQueue();
void HandleReceivedSystemMessage(OSMessage* msg);
SysAllocator<OSMessageQueue> g_systemMessageQueue;
SysAllocator<OSMessage, 16> _systemMessageQueueArray;
void OSInitMessageQueueEx(OSMessageQueue* msgQueue, OSMessage* msgArray, uint32 msgCount, void* userData)
{
msgQueue->magic = 'mSgQ';
msgQueue->userData = userData;
msgQueue->msgArray = msgArray;
msgQueue->msgCount = msgCount;
msgQueue->firstIndex = 0;
msgQueue->usedCount = 0;
msgQueue->ukn08 = 0;
OSInitThreadQueueEx(&msgQueue->threadQueueReceive, msgQueue);
OSInitThreadQueueEx(&msgQueue->threadQueueSend, msgQueue);
}
void OSInitMessageQueue(OSMessageQueue* msgQueue, OSMessage* msgArray, uint32 msgCount)
{
OSInitMessageQueueEx(msgQueue, msgArray, msgCount, nullptr);
}
bool OSReceiveMessage(OSMessageQueue* msgQueue, OSMessage* msg, uint32 flags)
{
bool isSystemMessageQueue = (msgQueue == g_systemMessageQueue);
if(isSystemMessageQueue)
UpdateSystemMessageQueue();
__OSLockScheduler(msgQueue);
while (msgQueue->usedCount == (uint32be)0)
{
if ((flags & OS_MESSAGE_BLOCK))
{
msgQueue->threadQueueReceive.queueAndWait(OSGetCurrentThread());
}
else
{
__OSUnlockScheduler(msgQueue);
return false;
}
}
// copy message
sint32 messageIndex = msgQueue->firstIndex;
OSMessage* readMsg = &(msgQueue->msgArray[messageIndex]);
memcpy(msg, readMsg, sizeof(OSMessage));
msgQueue->firstIndex = ((uint32)msgQueue->firstIndex + 1) % (uint32)(msgQueue->msgCount);
msgQueue->usedCount = (uint32)msgQueue->usedCount - 1;
// wake up any thread waiting to add a message
if (!msgQueue->threadQueueSend.isEmpty())
msgQueue->threadQueueSend.wakeupSingleThreadWaitQueue(true);
__OSUnlockScheduler(msgQueue);
if(isSystemMessageQueue)
HandleReceivedSystemMessage(msg);
return true;
}
bool OSPeekMessage(OSMessageQueue* msgQueue, OSMessage* msg)
{
__OSLockScheduler(msgQueue);
if ((msgQueue->usedCount == (uint32be)0))
{
__OSUnlockScheduler(msgQueue);
return false;
}
// copy message
sint32 messageIndex = msgQueue->firstIndex;
if (msg)
{
OSMessage* readMsg = &(msgQueue->msgArray[messageIndex]);
memcpy(msg, readMsg, sizeof(OSMessage));
}
__OSUnlockScheduler(msgQueue);
return true;
}
sint32 OSSendMessage(OSMessageQueue* msgQueue, OSMessage* msg, uint32 flags)
{
__OSLockScheduler();
while (msgQueue->usedCount >= msgQueue->msgCount)
{
if ((flags & OS_MESSAGE_BLOCK))
{
msgQueue->threadQueueSend.queueAndWait(OSGetCurrentThread());
}
else
{
__OSUnlockScheduler();
return 0;
}
}
// add message
if ((flags & OS_MESSAGE_HIGH_PRIORITY))
{
// decrease firstIndex
sint32 newFirstIndex = (sint32)((sint32)msgQueue->firstIndex + (sint32)msgQueue->msgCount - 1) % (sint32)msgQueue->msgCount;
msgQueue->firstIndex = newFirstIndex;
// insert message at new first index
msgQueue->usedCount = (uint32)msgQueue->usedCount + 1;
OSMessage* newMsg = &(msgQueue->msgArray[newFirstIndex]);
memcpy(newMsg, msg, sizeof(OSMessage));
}
else
{
sint32 messageIndex = (uint32)(msgQueue->firstIndex + msgQueue->usedCount) % (uint32)msgQueue->msgCount;
msgQueue->usedCount = (uint32)msgQueue->usedCount + 1;
OSMessage* newMsg = &(msgQueue->msgArray[messageIndex]);
memcpy(newMsg, msg, sizeof(OSMessage));
}
// wake up any thread waiting to read a message
if (!msgQueue->threadQueueReceive.isEmpty())
msgQueue->threadQueueReceive.wakeupSingleThreadWaitQueue(true);
__OSUnlockScheduler();
return 1;
}
OSMessageQueue* OSGetSystemMessageQueue()
{
return g_systemMessageQueue.GetPtr();
}
void InitializeMessageQueue()
{
OSInitMessageQueue(g_systemMessageQueue.GetPtr(), _systemMessageQueueArray.GetPtr(), _systemMessageQueueArray.GetCount());
cafeExportRegister("coreinit", OSInitMessageQueueEx, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSInitMessageQueue, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSReceiveMessage, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSPeekMessage, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSSendMessage, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSGetSystemMessageQueue, LogType::CoreinitThread);
}
};
| 4,447
|
C++
|
.cpp
| 128
| 31.453125
| 127
| 0.755803
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,119
|
coreinit_IOS.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_IOS.cpp
|
#include "Cafe/OS/libs/coreinit/coreinit_IOS.h"
#include "Cafe/IOSU/legacy/iosu_ioctl.h"
// superseded by coreinit_IPC.cpp/h
sint32 __depr__IOS_Open(char* path, uint32 mode)
{
sint32 iosDevice = 0;
if (path == nullptr)
{
iosDevice = 0;
}
else
{
if (strcmp(path, IOS_PATH_ODM) == 0)
iosDevice = IOS_DEVICE_ODM;
else if (strcmp(path, IOS_PATH_SOCKET) == 0)
iosDevice = IOS_DEVICE_SOCKET;
else if (strcmp(path, IOS_PATH_ACT) == 0)
iosDevice = IOS_DEVICE_ACT;
else if (strcmp(path, IOS_PATH_FPD) == 0)
iosDevice = IOS_DEVICE_FPD;
else if (strcmp(path, IOS_PATH_ACP_MAIN) == 0)
iosDevice = IOS_DEVICE_ACP_MAIN;
else if (strcmp(path, IOS_PATH_MCP) == 0)
iosDevice = IOS_DEVICE_MCP;
else if (strcmp(path, IOS_PATH_BOSS) == 0)
iosDevice = IOS_DEVICE_BOSS;
else if (strcmp(path, IOS_PATH_NIM) == 0)
iosDevice = IOS_DEVICE_NIM;
else if (strcmp(path, IOS_PATH_IOSUHAX) == 0)
return -1;
else
iosDevice = IOS_DEVICE_UKN;
}
return iosDevice;
}
sint32 __depr__IOS_Ioctl(uint32 fd, uint32 request, void* inBuffer, uint32 inSize, void* outBuffer, uint32 outSize)
{
switch (fd)
{
case IOS_DEVICE_ODM:
{
// Home Menu uses ioctl cmd 5 on startup and then repeats cmd 4 every frame
if (request == 4)
{
// check drive state
debug_printf("checkDriveState()\n");
*(uint32be*)outBuffer = 0xA;
}
else
{
debug_printf("odm unsupported ioctl %d\n", request);
}
break;
}
default:
{
// todo
cemuLog_logDebug(LogType::Force, "Unsupported Ioctl command");
}
}
return 0;
}
sint32 __depr__IOS_Ioctlv(uint32 fd, uint32 request, uint32 countIn, uint32 countOut, ioBufferVector_t* ioBufferVectors)
{
StackAllocator<ioQueueEntry_t> _queueEntryBuf;
ioQueueEntry_t* queueEntry = _queueEntryBuf.GetPointer();
queueEntry->isIoctlv = true;
queueEntry->isAsync = false;
queueEntry->request = request;
queueEntry->countIn = countIn;
queueEntry->countOut = countOut;
queueEntry->bufferVectors = ioBufferVectors;
queueEntry->ppcThread = nullptr;
queueEntry->returnValue = 0;
queueEntry->isCompleted = false;
sint32 r = iosuIoctl_pushAndWait(fd, queueEntry);
return r;
}
sint32 __depr__IOS_Close(uint32 fd)
{
return 0;
}
| 2,217
|
C++
|
.cpp
| 82
| 24.268293
| 120
| 0.70461
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,120
|
coreinit_SysHeap.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_SysHeap.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_SysHeap.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM_ExpHeap.h"
namespace coreinit
{
coreinit::MEMHeapHandle _sysHeapHandle = MPTR_NULL;
sint32 _sysHeapAllocCounter = 0;
sint32 _sysHeapFreeCounter = 0;
void* OSAllocFromSystem(uint32 size, uint32 alignment)
{
_sysHeapAllocCounter++;
return coreinit::MEMAllocFromExpHeapEx(_sysHeapHandle, size, alignment);
}
void OSFreeToSystem(void* ptr)
{
_sysHeapFreeCounter++;
coreinit::MEMFreeToExpHeap(_sysHeapHandle, ptr);
}
void InitSysHeap()
{
uint32 sysHeapSize = 8 * 1024 * 1024; // actual size is unknown
MEMPTR<void> heapBaseAddress = memory_getPointerFromVirtualOffset(coreinit_allocFromSysArea(sysHeapSize, 0x1000));
_sysHeapHandle = coreinit::MEMCreateExpHeapEx(heapBaseAddress.GetPtr(), sysHeapSize, MEM_HEAP_OPTION_THREADSAFE);
_sysHeapAllocCounter = 0;
_sysHeapFreeCounter = 0;
}
void InitializeSysHeap()
{
cafeExportRegister("h264", OSAllocFromSystem, LogType::CoreinitMem);
cafeExportRegister("h264", OSFreeToSystem, LogType::CoreinitMem);
}
}
| 1,122
|
C++
|
.cpp
| 32
| 32.71875
| 116
| 0.789668
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,121
|
coreinit_Scheduler.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_Scheduler.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "coreinit_Scheduler.h"
thread_local sint32 s_schedulerLockCount = 0;
#if BOOST_OS_WINDOWS
#include <synchapi.h>
CRITICAL_SECTION s_csSchedulerLock;
#else
#include <pthread.h>
pthread_mutex_t s_ptmSchedulerLock;
#endif
void __OSLockScheduler(void* obj)
{
#if BOOST_OS_WINDOWS
EnterCriticalSection(&s_csSchedulerLock);
#else
pthread_mutex_lock(&s_ptmSchedulerLock);
#endif
s_schedulerLockCount++;
cemu_assert_debug(s_schedulerLockCount <= 1); // >= 2 should not happen. Scheduler lock does not allow recursion
}
bool __OSHasSchedulerLock()
{
return s_schedulerLockCount > 0;
}
bool __OSTryLockScheduler(void* obj)
{
bool r;
#if BOOST_OS_WINDOWS
r = TryEnterCriticalSection(&s_csSchedulerLock);
#else
r = pthread_mutex_trylock(&s_ptmSchedulerLock) == 0;
#endif
if (r)
{
s_schedulerLockCount++;
return true;
}
return false;
}
void __OSUnlockScheduler(void* obj)
{
s_schedulerLockCount--;
cemu_assert_debug(s_schedulerLockCount >= 0);
#if BOOST_OS_WINDOWS
LeaveCriticalSection(&s_csSchedulerLock);
#else
pthread_mutex_unlock(&s_ptmSchedulerLock);
#endif
}
namespace coreinit
{
uint32 OSIsInterruptEnabled()
{
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
if (hCPU == nullptr)
return 0;
return hCPU->coreInterruptMask;
}
// disables interrupts and scheduling
uint32 OSDisableInterrupts()
{
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
if (hCPU == nullptr)
return 0;
uint32 prevInterruptMask = hCPU->coreInterruptMask;
if (hCPU->coreInterruptMask != 0)
{
// we have no efficient method to turn off scheduling completely, so instead we just increase the remaining cycles
if (hCPU->remainingCycles >= 0x40000000)
cemuLog_log(LogType::Force, "OSDisableInterrupts(): Warning - Interrupts already disabled but the mask was still set? remCycles {:08x} LR {:08x}", hCPU->remainingCycles, hCPU->spr.LR);
hCPU->remainingCycles += 0x40000000;
}
hCPU->coreInterruptMask = 0;
return prevInterruptMask;
}
uint32 OSRestoreInterrupts(uint32 interruptMask)
{
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
if (hCPU == nullptr)
return 0;
uint32 prevInterruptMask = hCPU->coreInterruptMask;
if (hCPU->coreInterruptMask == 0 && interruptMask != 0)
{
hCPU->remainingCycles -= 0x40000000;
}
hCPU->coreInterruptMask = interruptMask;
return prevInterruptMask;
}
uint32 OSEnableInterrupts()
{
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
uint32 prevInterruptMask = hCPU->coreInterruptMask;
OSRestoreInterrupts(1);
return prevInterruptMask;
}
void InitializeSchedulerLock()
{
#if BOOST_OS_WINDOWS
InitializeCriticalSection(&s_csSchedulerLock);
#else
pthread_mutexattr_t ma;
pthread_mutexattr_init(&ma);
pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&s_ptmSchedulerLock, &ma);
#endif
cafeExportRegister("coreinit", __OSLockScheduler, LogType::Placeholder);
cafeExportRegister("coreinit", __OSUnlockScheduler, LogType::Placeholder);
cafeExportRegister("coreinit", OSDisableInterrupts, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSEnableInterrupts, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSRestoreInterrupts, LogType::CoreinitThread);
}
};
| 3,318
|
C++
|
.cpp
| 112
| 27.375
| 188
| 0.778891
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,122
|
coreinit_IPCBuf.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_IPCBuf.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "coreinit_IPCBuf.h"
namespace coreinit
{
void FIFOInit(IPCFifo_t* fifo, uint32 entryCount, void* entryArray)
{
fifo->entryCount = entryCount;
fifo->entryArray = (FIFOEntry_t*)entryArray;
fifo->writeIndex = 0;
fifo->readIndex = -1;
fifo->availableEntries = 0;
}
sint32 FIFOPush(IPCFifo_t* fifo, void* entry)
{
if (fifo->readIndex == fifo->writeIndex)
{
assert_dbg();
return -8;
}
fifo->entryArray[(uint32)fifo->writeIndex].p = (uint8*)entry;
if ((sint32)fifo->readIndex < 0)
{
// set readIndex to valid value when fifo was empty
fifo->readIndex = fifo->writeIndex;
}
fifo->availableEntries = (uint32)fifo->availableEntries + 1;
fifo->writeIndex = ((uint32)fifo->writeIndex + 1) % (uint32)fifo->entryCount;
return 0;
}
sint32 FIFOPop(IPCFifo_t* fifo, uint8** entry)
{
*entry = nullptr;
if ((sint32)fifo->readIndex < 0)
return -7;
fifo->availableEntries = (uint32)fifo->availableEntries - 1;
*entry = fifo->entryArray[(uint32)fifo->readIndex].p.GetPtr();
fifo->readIndex = ((uint32)fifo->readIndex + 1) % (uint32)fifo->entryCount;
if (fifo->availableEntries == (uint32be)0)
{
fifo->readIndex = -1;
}
return 0;
}
void* getUpwardsAlignedAddr(void* addr, uint32 alignment)
{
uint64 v = ((uint64)addr + alignment - 1) & ~(uint64)(alignment - 1);
return (uint8*)v;
}
void* getDownwardsAlignedAddr(void* addr, uint32 alignment)
{
uint64 v = ((uint64)addr) & ~(uint64)(alignment - 1);
return (uint8*)v;
}
IPCBufPool_t* IPCBufPoolCreate(uint8* bufferArea, uint32 bufferSize, uint32 entrySize, uint32be* entryCountOutput, uint32 uknR7)
{
memset(bufferArea, 0, bufferSize);
IPCBufPool_t* ipcBufPool = (IPCBufPool_t*)getUpwardsAlignedAddr(bufferArea, 4);
uint8* alignedEnd = (uint8*)getDownwardsAlignedAddr(bufferArea + bufferSize, 4);
uint8* dataStart = (uint8*)getUpwardsAlignedAddr(ipcBufPool + 1, 0x4);
*entryCountOutput = 0;
// todo: Validate parameters
OSInitMutexEx(&ipcBufPool->mutex, NULL);
ipcBufPool->fullBufferPtr = bufferArea;
ipcBufPool->fullBufferSize = bufferSize;
ipcBufPool->uknFromParamR7 = uknR7;
uint32 paddedEntrySize = (entrySize + 0x3F) & ~0x3F;
ipcBufPool->ukn10 = 0;
ipcBufPool->magic = 0xBADF00D;
ipcBufPool->entrySize1 = paddedEntrySize;
ipcBufPool->entrySize2 = paddedEntrySize;
uint32 remainingSize = (uint32)((bufferArea + bufferSize) - dataStart);
uint32 entryCount = remainingSize / paddedEntrySize;
if (entryCount <= 1)
assert_dbg();
ipcBufPool->entryCountMul4 = entryCount * 4;
if ((uint32)ipcBufPool->entryCountMul4 >= paddedEntrySize)
{
// special handling required (need to adjust entry count?)
assert_dbg();
}
else
{
entryCount--; // remove one entry to make room for entry pointer array
ipcBufPool->entryCount = entryCount;
*entryCountOutput = entryCount;
ipcBufPool->entryStartPtr = (dataStart + (uint32)ipcBufPool->entryCountMul4);
FIFOInit(&ipcBufPool->fifo, (uint32)ipcBufPool->entryCount, dataStart);
}
// add all entries to the fifo
for (sint32 i = 0; i < (sint32)ipcBufPool->entryCount; i++)
{
uint8* entry = ipcBufPool->entryStartPtr.GetPtr() + i * (uint32)ipcBufPool->entrySize2;
if (FIFOPush(&ipcBufPool->fifo, entry) != 0)
return nullptr;
}
return ipcBufPool;
}
uint8* IPCBufPoolAllocate(IPCBufPool_t* ipcBufPool, uint32 size)
{
uint8* entry = nullptr;
OSLockMutex(&ipcBufPool->mutex);
if (ipcBufPool->magic == (uint32be)0xBADF00D && size <= (uint32)ipcBufPool->entrySize1)
{
FIFOPop(&ipcBufPool->fifo, &entry);
}
else
{
assert_dbg();
}
OSUnlockMutex(&ipcBufPool->mutex);
return entry;
}
sint32 IPCBufPoolFree(IPCBufPool_t* ipcBufPool, uint8* entry)
{
OSLockMutex(&ipcBufPool->mutex);
sint32 res = 0;
if (ipcBufPool->magic == (uint32be)0xBADF00D)
{
// check if entry is actually part of the pool
uint32 offset = (uint32)(entry - (uint8*)ipcBufPool->entryStartPtr.GetPtr());
if ((offset % (uint32)ipcBufPool->entrySize2) != 0)
assert_dbg();
uint32 index = offset / (uint32)ipcBufPool->entrySize2;
if ((index >= (uint32)ipcBufPool->entryCount))
assert_dbg();
FIFOPush(&ipcBufPool->fifo, entry);
}
else
{
assert_dbg();
res = -4;
}
OSUnlockMutex(&ipcBufPool->mutex);
return res;
}
void coreinitExport_IPCBufPoolCreate(PPCInterpreter_t* hCPU)
{
ppcDefineParamTypePtr(bufferArea, uint8, 0);
ppcDefineParamU32(bufferSize, 1);
ppcDefineParamU32(entrySize, 2);
ppcDefineParamU32BEPtr(entryCountOutput, 3);
ppcDefineParamU32(uknR7, 4);
IPCBufPool_t* ipcBufPool = IPCBufPoolCreate(bufferArea, bufferSize, entrySize, entryCountOutput, uknR7);
osLib_returnFromFunction(hCPU, memory_getVirtualOffsetFromPointer(ipcBufPool));
return;
// example dump of IPC buffer (at 0x1011FF40):
// 0000 0B AD F0 0D 10 11 FF 40 00 00 53 01 00 00 00 01 00 00 00 00 00 00 02 C0 00 00 02 C0 00 00 00 1D
// 0020 10 12 00 40 00 00 00 78 00 00 00 00 00 00 00 00 00 00 00 1D 00 00 00 1D 10 11 FF A8 6D 55 74 58
// 0040 10 00 87 2C 00 00 00 00 00 00 00 00 00 00 00 00 10 11 FF 7C 00 00 00 00 00 00 00 00 00 00 00 00
// 0060 00 00 00 00 00 00 00 00 10 12 00 40 10 12 03 00 10 12 05 C0 10 12 08 80 10 12 0B 40 10 12 0E 00
// 0080 10 12 10 C0 10 12 13 80 10 12 16 40 10 12 19 00 10 12 1B C0 10 12 1E 80 10 12 21 40 10 12 24 00
// 00A0 10 12 26 C0 10 12 29 80 10 12 2C 40 10 12 2F 00 10 12 31 C0 10 12 34 80 10 12 37 40 10 12 3A 00
// 00C0 10 12 3C C0 10 12 3F 80 10 12 42 40 10 12 45 00 10 12 47 C0 10 12 4A 80 10 12 4D 40 00 00 00 00
// 00E0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
}
void coreinitExport_IPCBufPoolAllocate(PPCInterpreter_t* hCPU)
{
debug_printf("IPCBufPoolAllocate(0x%08x,0x%x)\n", hCPU->gpr[3], hCPU->gpr[4]);
ppcDefineParamStructPtr(ipcBufPool, IPCBufPool_t, 0);
ppcDefineParamU32(size, 1);
uint8* entry = IPCBufPoolAllocate(ipcBufPool, size);
osLib_returnFromFunction(hCPU, memory_getVirtualOffsetFromPointer(entry));
}
void coreinitExport_IPCBufPoolFree(PPCInterpreter_t* hCPU)
{
debug_printf("IPCBufPoolFree(0x%08x,0x%08x)\n", hCPU->gpr[3], hCPU->gpr[4]);
ppcDefineParamStructPtr(ipcBufPool, IPCBufPool_t, 0);
ppcDefineParamTypePtr(entry, uint8, 1);
sint32 res = IPCBufPoolFree(ipcBufPool, entry);
osLib_returnFromFunction(hCPU, res);
}
void InitializeIPCBuf()
{
osLib_addFunction("coreinit", "IPCBufPoolCreate", coreinitExport_IPCBufPoolCreate);
osLib_addFunction("coreinit", "IPCBufPoolAllocate", coreinitExport_IPCBufPoolAllocate);
osLib_addFunction("coreinit", "IPCBufPoolFree", coreinitExport_IPCBufPoolFree);
}
}
| 6,793
|
C++
|
.cpp
| 179
| 34.927374
| 129
| 0.718987
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,123
|
coreinit_Time.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_Time.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
namespace coreinit
{
uint64 coreinit_getTimerTick()
{
// bus clock is 1/5th of core clock
// timer clock is 1/4th of bus clock
return PPCInterpreter_getMainCoreCycleCounter() / 20ULL;
}
uint64 coreinit_getOSTime()
{
return coreinit_getTimerTick() + ppcCyclesSince2000TimerClock;
}
void export_OSGetTick(PPCInterpreter_t* hCPU)
{
uint64 osTime = coreinit_getOSTime();
osLib_returnFromFunction(hCPU, (uint32)osTime);
}
uint64 OSGetTime()
{
return coreinit_getOSTime();
}
void export_OSGetSystemTime(PPCInterpreter_t* hCPU)
{
osLib_returnFromFunction64(hCPU, coreinit_getTimerTick());
}
void export_OSGetSystemTick(PPCInterpreter_t* hCPU)
{
osLib_returnFromFunction(hCPU, (uint32)coreinit_getTimerTick());
}
uint32 getLeapDaysUntilYear(uint32 year)
{
if (year == 0)
return 0;
return (year + 3) / 4 - (year - 1) / 100 + (year - 1) / 400;
}
bool IsLeapYear(uint32 year)
{
if (((year & 3) == 0) && (year % 100) != 0)
return true;
if ((year % 400) == 0)
return true;
return false;
}
uint32 dayToMonth[12] =
{
0,31,59,90,120,151,181,212,243,273,304,334
};
uint32 dayToMonthLeapYear[12] =
{
0,31,60,91,121,152,182,213,244,274,305,335
};
uint32 getDayInYearByYearAndMonth(uint32 year, uint32 month)
{
// Project Zero Maiden of Black Water (JPN) gives us an invalid calendar object
month %= 12; // or return 0 if too big?
if (IsLeapYear(year))
return dayToMonthLeapYear[month];
return dayToMonth[month];
}
inline const uint64 DAY_BIAS_2000 = 0xB2575;
uint64 OSCalendarTimeToTicks(OSCalendarTime_t *calendar)
{
uint32 year = calendar->year;
uint32 leapDays = getLeapDaysUntilYear(year);
uint32 startDayOfCurrentMonth = getDayInYearByYearAndMonth(year, calendar->month);
uint64 dayInYear = (startDayOfCurrentMonth + calendar->dayOfMonth) - 1;
uint64 dayCount = dayInYear + year * 365 + leapDays - DAY_BIAS_2000;
// convert date to seconds
uint64 tSeconds = 0;
tSeconds += (uint64)dayCount * 24 * 60 * 60;
tSeconds += (uint64)calendar->hour * 60 * 60;
tSeconds += (uint64)calendar->minute * 60;
tSeconds += (uint64)calendar->second;
uint64 tSubSecondTicks = 0;
tSubSecondTicks += (uint64)calendar->millisecond * ESPRESSO_TIMER_CLOCK / 1000;
tSubSecondTicks += (uint64)calendar->microsecond * ESPRESSO_TIMER_CLOCK / 1000000;
return tSeconds * ESPRESSO_TIMER_CLOCK + tSubSecondTicks;
}
void OSTicksToCalendarTime(uint64 ticks, OSCalendarTime_t* calenderStruct)
{
uint64 tSubSecondTicks = ticks % ESPRESSO_TIMER_CLOCK;
uint64 tSeconds = ticks / ESPRESSO_TIMER_CLOCK;
uint64 microsecond = tSubSecondTicks * 1000000ull / ESPRESSO_TIMER_CLOCK;
microsecond %= 1000ull;
calenderStruct->microsecond = (uint32)microsecond;
uint64 millisecond = tSubSecondTicks * 1000ull / ESPRESSO_TIMER_CLOCK;
millisecond %= 1000ull;
calenderStruct->millisecond = (uint32)millisecond;
uint64 dayOfWeek = (tSeconds/(24ull * 60 * 60) + 6ull) % 7ull;
uint64 secondOfDay = (tSeconds % (24ull * 60 * 60));
calenderStruct->dayOfWeek = (sint32)dayOfWeek;
uint64 daysSince0AD = tSeconds / (24ull * 60 * 60) + DAY_BIAS_2000;
uint32 year = (uint32)(daysSince0AD / 365ull);
uint64 yearStartDay = year * 365 + getLeapDaysUntilYear(year);
while (yearStartDay > daysSince0AD)
{
year--;
if (IsLeapYear(year))
yearStartDay -= 366;
else
yearStartDay -= 365;
}
calenderStruct->year = year;
// calculate time of day
uint32 tempSecond = (uint32)secondOfDay;
calenderStruct->second = tempSecond % 60;
tempSecond /= 60;
calenderStruct->minute = tempSecond % 60;
tempSecond /= 60;
calenderStruct->hour = tempSecond % 24;
tempSecond /= 24;
// calculate month and day
uint32 dayInYear = (uint32)(daysSince0AD - yearStartDay);
bool isLeapYear = IsLeapYear(year);
uint32 month = 0; // 0-11
uint32 dayInMonth = 0;
if (isLeapYear && dayInYear < (31+29))
{
if (dayInYear < 31)
{
// January
month = 0;
dayInMonth = dayInYear;
}
else
{
// February
month = 1;
dayInMonth = dayInYear-31;
}
}
else
{
if (isLeapYear)
dayInYear--;
dayInMonth = dayInYear;
if (dayInYear >= 334)
{
// December
month = 11;
dayInMonth -= 334;
}
else if (dayInYear >= 304)
{
// November
month = 10;
dayInMonth -= 304;
}
else if (dayInYear >= 273)
{
// October
month = 9;
dayInMonth -= 273;
}
else if (dayInYear >= 243)
{
// September
month = 8;
dayInMonth -= 243;
}
else if (dayInYear >= 212)
{
// August
month = 7;
dayInMonth -= 212;
}
else if (dayInYear >= 181)
{
// July
month = 6;
dayInMonth -= 181;
}
else if (dayInYear >= 151)
{
// June
month = 5;
dayInMonth -= 151;
}
else if (dayInYear >= 120)
{
// May
month = 4;
dayInMonth -= 120;
}
else if (dayInYear >= 90)
{
// April
month = 3;
dayInMonth -= 90;
}
else if (dayInYear >= 59)
{
// March
month = 2;
dayInMonth -= 59;
}
else if (dayInYear >= 31)
{
// February
month = 1;
dayInMonth -= 31;
}
else
{
// January
month = 0;
dayInMonth -= 0;
}
}
calenderStruct->dayOfYear = dayInYear;
calenderStruct->month = month;
calenderStruct->dayOfMonth = dayInMonth + 1;
}
uint32 getDaysInMonth(uint32 year, uint32 month)
{
switch (month)
{
case 0: // January
return 31;
case 1: // February
return IsLeapYear(year) ? 29 : 28;
case 2: // March
return 31;
case 3: // April
return 30;
case 4: // May
return 31;
case 5: // June
return 30;
case 6: // July
return 31;
case 7: // August
return 31;
case 8: // September
return 30;
case 9: // October
return 31;
case 10: // November
return 30;
case 11: // December
return 31;
default:
cemu_assert(false);
}
return 31;
}
void verifyDateMatch(OSCalendarTime_t* ct1, OSCalendarTime_t* ct2)
{
sint64 m1 = ct1->millisecond * 1000 + ct1->microsecond;
sint64 m2 = ct2->millisecond * 1000 + ct2->microsecond;
sint64 microDif = std::abs(m1 - m2);
if (ct1->year != ct2->year ||
ct1->month != ct2->month ||
ct1->dayOfMonth != ct2->dayOfMonth ||
ct1->hour != ct2->hour ||
ct1->minute != ct2->minute ||
ct1->second != ct2->second ||
microDif > 1ull)
{
debug_printf("Mismatch\n");
assert_dbg();
}
}
void timeTest()
{
sint32 iterCount = 0;
OSCalendarTime_t ct{};
ct.year = 2000;
ct.month = 1;
ct.dayOfMonth = 1;
ct.hour = 1;
ct.minute = 1;
ct.second = 1;
ct.millisecond = 123;
ct.microsecond = 321;
while (true)
{
iterCount++;
uint64 ticks = OSCalendarTimeToTicks(&ct);
// make sure converting it back results in the same date
OSCalendarTime_t ctTemp;
OSTicksToCalendarTime(ticks, &ctTemp);
verifyDateMatch(&ct, &ctTemp);
// add a day
ticks += 24ull * 60 * 60 * ESPRESSO_TIMER_CLOCK;
OSCalendarTime_t ctOutput;
OSTicksToCalendarTime(ticks, &ctOutput);
OSCalendarTime_t ctExpected;
ctExpected = ct;
// add a day manually
sint32 daysInMonth = getDaysInMonth(ctExpected.year, ctExpected.month);
ctExpected.dayOfMonth = ctExpected.dayOfMonth + 1;
if (ctExpected.dayOfMonth >= daysInMonth+1)
{
ctExpected.dayOfMonth = 1;
ctExpected.month = ctExpected.month + 1;
if (ctExpected.month > 11)
{
ctExpected.month = 0;
ctExpected.year = ctExpected.year + 1;
}
}
verifyDateMatch(&ctExpected, &ctOutput);
ct = ctOutput;
}
}
void InitializeTimeAndCalendar()
{
cafeExportRegister("coreinit", OSGetTime, LogType::Placeholder);
osLib_addFunction("coreinit", "OSGetSystemTime", export_OSGetSystemTime);
osLib_addFunction("coreinit", "OSGetTick", export_OSGetTick);
osLib_addFunction("coreinit", "OSGetSystemTick", export_OSGetSystemTick);
cafeExportRegister("coreinit", OSTicksToCalendarTime, LogType::Placeholder);
cafeExportRegister("coreinit", OSCalendarTimeToTicks, LogType::Placeholder);
//timeTest();
}
};
| 8,184
|
C++
|
.cpp
| 319
| 22.043887
| 84
| 0.679349
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,124
|
coreinit_Spinlock.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_Spinlock.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/OS/libs/coreinit/coreinit_Spinlock.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "Cafe/OS/libs/coreinit/coreinit.h"
namespace coreinit
{
void __OSBoostThread(OSThread_t* thread)
{
__OSLockScheduler();
thread->stateFlags |= 0x20000;
thread->context.boostCount += 1;
__OSUpdateThreadEffectivePriority(thread); // sets thread->effectivePriority to zero since boostCount != 0
__OSUnlockScheduler();
}
void __OSDeboostThread(OSThread_t* thread)
{
__OSLockScheduler();
cemu_assert_debug(thread->context.boostCount != 0);
thread->context.boostCount -= 1;
if (thread->context.boostCount == 0)
{
thread->stateFlags &= ~0x20000;
__OSUpdateThreadEffectivePriority(thread);
// todo - reschedule if lower priority than other threads on current core?
}
__OSUnlockScheduler();
}
void OSInitSpinLock(OSSpinLock* spinlock)
{
spinlock->userData = spinlock;
spinlock->ownerThread = nullptr;
spinlock->count = 0;
spinlock->interruptMask = 1;
}
bool OSAcquireSpinLock(OSSpinLock* spinlock)
{
OSThread_t* currentThread = OSGetCurrentThread();
if (spinlock->ownerThread == currentThread)
{
spinlock->count += 1;
return true;
}
else
{
// loop until lock acquired
while (!spinlock->ownerThread.atomic_compare_exchange(nullptr, currentThread))
{
OSYieldThread();
}
}
__OSBoostThread(currentThread);
return true;
}
bool OSTryAcquireSpinLock(OSSpinLock* spinlock)
{
OSThread_t* currentThread = OSGetCurrentThread();
if (spinlock->ownerThread == currentThread)
{
spinlock->count += 1;
return true;
}
// try acquire once
if (!spinlock->ownerThread.atomic_compare_exchange(nullptr, currentThread))
return false;
__OSBoostThread(currentThread);
return true;
}
bool OSTryAcquireSpinLockWithTimeout(OSSpinLock* spinlock, uint64 timeout)
{
// used by CoD: Ghosts
cemu_assert_debug((timeout >> 63) == 0); // negative?
OSThread_t* currentThread = OSGetCurrentThread();
if (spinlock->ownerThread == currentThread)
{
spinlock->count += 1;
return true;
}
else
{
// loop until lock acquired or timeout occurred
uint64 timeoutValue = coreinit_getTimerTick() + coreinit::EspressoTime::ConvertNsToTimerTicks(timeout);
while (!spinlock->ownerThread.atomic_compare_exchange(nullptr, currentThread))
{
OSYieldThread();
if (coreinit_getTimerTick() >= timeoutValue)
{
return false;
}
}
}
__OSBoostThread(currentThread);
return true;
}
bool OSReleaseSpinLock(OSSpinLock* spinlock)
{
OSThread_t* currentThread = OSGetCurrentThread();
cemu_assert_debug(spinlock->ownerThread == currentThread);
if (spinlock->count != 0)
{
spinlock->count -= 1;
return true;
}
// release spinlock
while (!spinlock->ownerThread.atomic_compare_exchange(currentThread, nullptr));
__OSDeboostThread(currentThread);
return true;
}
bool OSUninterruptibleSpinLock_Acquire(OSSpinLock* spinlock)
{
// frequently used by VC DS
OSThread_t* currentThread = OSGetCurrentThread();
cemu_assert_debug(currentThread != nullptr);
if (spinlock->ownerThread == currentThread)
{
spinlock->count += 1;
return true;
}
else
{
// loop until lock acquired
if (coreinit::__CemuIsMulticoreMode())
{
while (!spinlock->ownerThread.atomic_compare_exchange(nullptr, currentThread))
{
_mm_pause();
}
}
else
{
// we are in single-core mode and the lock will never be released unless we let other threads resume work
// to avoid an infinite loop we have no choice but to yield the thread even it is in an uninterruptible state
if( !OSIsInterruptEnabled() )
cemuLog_logOnce(LogType::APIErrors, "OSUninterruptibleSpinLock_Acquire(): Lock is occupied which requires a wait but current thread is already in an uninterruptible state (Avoid cascaded OSDisableInterrupts and/or OSUninterruptibleSpinLock)");
while (!spinlock->ownerThread.atomic_compare_exchange(nullptr, currentThread))
{
OSYieldThread();
}
}
}
__OSBoostThread(currentThread);
spinlock->interruptMask = OSDisableInterrupts();
cemu_assert_debug(spinlock->ownerThread == currentThread);
return true;
}
bool OSUninterruptibleSpinLock_TryAcquire(OSSpinLock* spinlock)
{
OSThread_t* currentThread = OSGetCurrentThread();
if (spinlock->ownerThread == currentThread)
{
spinlock->count += 1;
return true;
}
// try acquire once
if (!spinlock->ownerThread.atomic_compare_exchange(nullptr, currentThread))
return false;
__OSBoostThread(currentThread);
spinlock->interruptMask = OSDisableInterrupts();
return true;
}
bool OSUninterruptibleSpinLock_TryAcquireWithTimeout(OSSpinLock* spinlock, uint64 timeout)
{
cemu_assert_debug((timeout >> 63) == 0); // negative?
OSThread_t* currentThread = OSGetCurrentThread();
if (spinlock->ownerThread == currentThread)
{
spinlock->count += 1;
return true;
}
else
{
// loop until lock acquired or timeout occurred
uint64 timeoutValue = coreinit_getTimerTick() + coreinit::EspressoTime::ConvertNsToTimerTicks(timeout);
while (!spinlock->ownerThread.atomic_compare_exchange(nullptr, currentThread))
{
OSYieldThread();
if (coreinit_getTimerTick() >= timeoutValue)
{
return false;
}
}
}
__OSBoostThread(currentThread);
spinlock->interruptMask = OSDisableInterrupts();
return true;
}
bool OSUninterruptibleSpinLock_Release(OSSpinLock* spinlock)
{
OSThread_t* currentThread = OSGetCurrentThread();
cemu_assert_debug(spinlock->ownerThread == currentThread);
if (spinlock->count != 0)
{
spinlock->count -= 1;
return true;
}
// release spinlock
OSRestoreInterrupts(spinlock->interruptMask);
spinlock->interruptMask = 1;
while (!spinlock->ownerThread.atomic_compare_exchange(currentThread, nullptr));
__OSDeboostThread(currentThread);
return true;
}
void InitializeSpinlock()
{
cafeExportRegister("coreinit", OSInitSpinLock, LogType::Placeholder);
cafeExportRegister("coreinit", OSAcquireSpinLock, LogType::Placeholder);
cafeExportRegister("coreinit", OSTryAcquireSpinLock, LogType::Placeholder);
cafeExportRegister("coreinit", OSTryAcquireSpinLockWithTimeout, LogType::Placeholder);
cafeExportRegister("coreinit", OSReleaseSpinLock, LogType::Placeholder);
cafeExportRegister("coreinit", OSUninterruptibleSpinLock_Acquire, LogType::Placeholder);
cafeExportRegister("coreinit", OSUninterruptibleSpinLock_TryAcquire, LogType::Placeholder);
cafeExportRegister("coreinit", OSUninterruptibleSpinLock_TryAcquireWithTimeout, LogType::Placeholder);
cafeExportRegister("coreinit", OSUninterruptibleSpinLock_Release, LogType::Placeholder);
}
#pragma endregion
}
| 6,827
|
C++
|
.cpp
| 216
| 28.356481
| 248
| 0.749242
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,125
|
coreinit_MCP.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_MCP.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/IOSU/legacy/iosu_ioctl.h"
#include "Cafe/IOSU/legacy/iosu_mcp.h"
#include "Cafe/OS/libs/coreinit/coreinit_IOS.h"
#include "Cafe/OS/libs/coreinit/coreinit_MCP.h"
#include "Cafe/OS/libs/nn_common.h"
#include "Cafe/OS/libs/nn_act/nn_act.h"
#include "config/CemuConfig.h"
#include "Cafe/CafeSystem.h"
#define mcpPrepareRequest() \
StackAllocator<iosuMcpCemuRequest_t> _buf_mcpRequest; \
StackAllocator<ioBufferVector_t> _buf_bufferVector; \
iosuMcpCemuRequest_t* mcpRequest = _buf_mcpRequest.GetPointer(); \
ioBufferVector_t* mcpBufferVector = _buf_bufferVector.GetPointer(); \
memset(mcpRequest, 0, sizeof(iosuMcpCemuRequest_t)); \
memset(mcpBufferVector, 0, sizeof(ioBufferVector_t)); \
mcpBufferVector->buffer = (uint8*)mcpRequest;
#define MCP_FAKE_HANDLE (0x00000010)
typedef struct
{
uint32be n0;
uint32be n1;
uint32be n2;
}mcpSystemVersion_t;
static_assert(sizeof(MCPTitleInfo) == 0x61, "title entry size is invalid");
static_assert(offsetof(MCPTitleInfo, appPath) == 0xC, "title entry appPath has invalid offset");
static_assert(offsetof(MCPTitleInfo, titleVersion) == 0x48, "title entry titleVersion has invalid offset");
static_assert(offsetof(MCPTitleInfo, osVersion) == 0x4A, "title entry osVersion has invalid offset");
MCPHANDLE MCP_Open()
{
// placeholder
return MCP_FAKE_HANDLE;
}
void MCP_Close(MCPHANDLE mcpHandle)
{
// placeholder
}
void coreinitExport_MCP_Open(PPCInterpreter_t* hCPU)
{
// placeholder
osLib_returnFromFunction(hCPU, MCP_Open());
}
void coreinitExport_MCP_Close(PPCInterpreter_t* hCPU)
{
// placeholder
osLib_returnFromFunction(hCPU, 0);
}
sint32 MCP_GetSysProdSettings(MCPHANDLE mcpHandle, SysProdSettings* sysProdSettings)
{
memset(sysProdSettings, 0x00, sizeof(SysProdSettings));
// todo: Other fields are currently unknown
sysProdSettings->gameRegion = (uint8)CafeSystem::GetForegroundTitleRegion();
sysProdSettings->platformRegion = (uint8)CafeSystem::GetPlatformRegion();
// contains Wii U serial parts at +0x1A and +0x22?
return 0;
}
void coreinitExport_MCP_GetSysProdSettings(PPCInterpreter_t* hCPU)
{
sint32 result = MCP_GetSysProdSettings(hCPU->gpr[3], (SysProdSettings*)memory_getPointerFromVirtualOffset(hCPU->gpr[4]));
osLib_returnFromFunction(hCPU, result);
}
void coreinitExport_MCP_TitleListByAppType(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "MCP_TitleListByAppType(0x{:08x},0x{:08x},0x{:08x},0x{:08x},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6], hCPU->gpr[7]);
ppcDefineParamU32(mcpHandle, 0);
ppcDefineParamU32(appType, 1);
ppcDefineParamU32BEPtr(countOutput, 2);
ppcDefineParamStructPtr(titleList, MCPTitleInfo, 3);
ppcDefineParamU32(titleListSize, 4);
sint32 maxCount = titleListSize / sizeof(MCPTitleInfo);
mcpPrepareRequest();
mcpRequest->requestCode = IOSU_MCP_GET_TITLE_LIST_BY_APP_TYPE;
mcpRequest->titleListRequest.titleCount = maxCount;
mcpRequest->titleListRequest.titleList = titleList;
mcpRequest->titleListRequest.titleListBufferSize = sizeof(MCPTitleInfo) * 1;
mcpRequest->titleListRequest.appType = appType;
__depr__IOS_Ioctlv(IOS_DEVICE_MCP, IOSU_MCP_REQUEST_CEMU, 1, 1, mcpBufferVector);
*countOutput = mcpRequest->titleListRequest.titleCount;
osLib_returnFromFunction(hCPU, 0);
}
void coreinitExport_MCP_TitleList(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(mcpHandle, 0);
ppcDefineParamU32BEPtr(countOutput, 1);
ppcDefineParamStructPtr(titleList, MCPTitleInfo, 2);
ppcDefineParamU32(titleListBufferSize, 3);
// todo -> Other parameters?
mcpPrepareRequest();
mcpRequest->requestCode = IOSU_MCP_GET_TITLE_LIST;
mcpRequest->titleListRequest.titleCount = *countOutput;
mcpRequest->titleListRequest.titleList = titleList;
mcpRequest->titleListRequest.titleListBufferSize = titleListBufferSize;
__depr__IOS_Ioctlv(IOS_DEVICE_MCP, IOSU_MCP_REQUEST_CEMU, 1, 1, mcpBufferVector);
*countOutput = mcpRequest->titleListRequest.titleCount;
cemuLog_logDebug(LogType::Force, "MCP_TitleList(...) returned {} titles", (uint32)mcpRequest->titleListRequest.titleCount);
osLib_returnFromFunction(hCPU, mcpRequest->returnCode);
}
void coreinitExport_MCP_TitleCount(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "MCP_TitleCount(): Untested");
ppcDefineParamU32(mcpHandle, 0);
mcpPrepareRequest();
mcpRequest->requestCode = IOSU_MCP_GET_TITLE_COUNT;
mcpRequest->titleListRequest.titleCount = 0;
__depr__IOS_Ioctlv(IOS_DEVICE_MCP, IOSU_MCP_REQUEST_CEMU, 1, 1, mcpBufferVector);
osLib_returnFromFunction(hCPU, mcpRequest->titleListRequest.titleCount);
}
void coreinitExport_MCP_GetTitleInfo(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(mcpHandle, 0);
ppcDefineParamU64(titleId, 2);
ppcDefineParamStructPtr(titleList, MCPTitleInfo, 4);
cemuLog_logDebug(LogType::Force, "MCP_GetTitleInfo() called");
mcpPrepareRequest();
mcpRequest->requestCode = IOSU_MCP_GET_TITLE_INFO;
mcpRequest->titleListRequest.titleCount = 1;
mcpRequest->titleListRequest.titleList = titleList;
mcpRequest->titleListRequest.titleListBufferSize = sizeof(MCPTitleInfo);
mcpRequest->titleListRequest.titleId = titleId;
__depr__IOS_Ioctlv(IOS_DEVICE_MCP, IOSU_MCP_REQUEST_CEMU, 1, 1, mcpBufferVector);
if (mcpRequest->titleListRequest.titleCount == 0)
{
cemuLog_log(LogType::Force, "MCP_GetTitleInfo() failed to get title info");
}
osLib_returnFromFunction(hCPU, mcpRequest->returnCode);
}
void coreinitExport_MCP_GetTitleInfoByTitleAndDevice(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(mcpHandle, 0);
ppcDefineParamU64(titleId, 2);
ppcDefineParamStr(device, 4); // e.g. "odd"
ppcDefineParamStructPtr(titleList, MCPTitleInfo, 5);
cemuLog_logDebug(LogType::Force, "MCP_GetTitleInfoByTitleAndDevice() called (todo - device type support)");
mcpPrepareRequest();
mcpRequest->requestCode = IOSU_MCP_GET_TITLE_INFO;
mcpRequest->titleListRequest.titleCount = 1;
mcpRequest->titleListRequest.titleList = titleList;
mcpRequest->titleListRequest.titleListBufferSize = sizeof(MCPTitleInfo);
mcpRequest->titleListRequest.titleId = titleId;
__depr__IOS_Ioctlv(IOS_DEVICE_MCP, IOSU_MCP_REQUEST_CEMU, 1, 1, mcpBufferVector);
if (mcpRequest->titleListRequest.titleCount == 0)
{
cemuLog_logDebug(LogType::Force, "MCP_GetTitleInfoByTitleAndDevice() no title found");
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_MCP, 0)); // E-Shop/nn_vctl.rpl expects error to be returned when no title is found
return;
}
osLib_returnFromFunction(hCPU, mcpRequest->returnCode);
}
namespace coreinit
{
void export_MCP_GetSystemVersion(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "MCP_GetSystemVersion({},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4]);
ppcDefineParamU32(mcpHandle, 0);
ppcDefineParamStructPtr(systemVersion, mcpSystemVersion_t, 1);
systemVersion->n0 = 0x5;
systemVersion->n1 = 0x5;
systemVersion->n2 = 0x5;
// todo: Load this from \sys\title\00050010\10041200\content\version.bin
osLib_returnFromFunction(hCPU, 0);
}
void export_MCP_Get4SecondOffStatus(PPCInterpreter_t* hCPU)
{
// r3 = mcpHandle
cemuLog_logDebug(LogType::Force, "MCP_Get4SecondOffStatus(...) placeholder");
// if this returns 1 then Barista will display the warning about cold-shutdown ('Holding the POWER button for at least four seconds...')
osLib_returnFromFunction(hCPU, 0);
}
void export_MCP_TitleListByDevice(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(mcpHandle, 0);
ppcDefineParamStr(deviceName, 1);
ppcDefineParamU32BEPtr(titleCount, 2);
ppcDefineParamStructPtr(titleList, MCPTitleInfo, 3); // type guessed
// purpose of r7 parameter is unknown
cemu_assert_unimplemented();
titleList[0].titleIdHigh = 0x00050000;
titleList[0].titleIdLow = 0x11223344;
strcpy(titleList[0].appPath, "titlePathTest");
*titleCount = 1;
cemuLog_logDebug(LogType::Force, "MCP_TitleListByDevice() - placeholder");
osLib_returnFromFunction(hCPU, 0);
}
#pragma pack(1)
struct MCPDevice_t
{
/* +0x000 */ char storageName[0x8]; // the name in the storage path (mlc, slc, usb?) // volumeId at +8
/* +0x008 */ char volumeId[16]; //
/* +0x018 */ char ukn[0x90 - 0x18];
/* +0x090 */ char storagePath[0x280 - 1]; // /vol/storage_%s%02x
/* +0x30F */ uint32be flags; // men.rpx checks for 0x2 and 0x8
uint8 ukn313[4];
uint8 ukn317[4];
};
#pragma pack()
static_assert(sizeof(MCPDevice_t) == 0x31B);
static_assert(sizeof(MCPDevice_t) == 0x31B);
static_assert(offsetof(MCPDevice_t, storagePath) == 0x90);
static_assert(offsetof(MCPDevice_t, flags) == 0x30F);
static_assert(offsetof(MCPDevice_t, ukn313) == 0x313);
static_assert(offsetof(MCPDevice_t, ukn317) == 0x317);
void MCP_DeviceListEx(uint32 mcpHandle, uint32be* deviceCount, MCPDevice_t* deviceList, uint32 deviceListSize, bool returnFullList)
{
sint32 maxDeviceCount = deviceListSize / sizeof(MCPDevice_t);
cemu_assert(maxDeviceCount >= 2);
memset(deviceList, 0, deviceListSize);
sint32 index = 0;
uint32 flags = 2 | 8;
// flag 2 is necessary for Wii U menu and Friend List to load
// if we dont set flag 0x8 then Wii U menu will show a disk loading icon and screen
// slc
strcpy(deviceList[index].storageName, "slc");
strcpy(deviceList[index].volumeId, "VOLID_SLC");
deviceList[index].flags = flags;
strcpy(deviceList[index].storagePath, "/vol/system_slc"); // unsure
index++;
// mlc
strcpy(deviceList[index].storageName, "mlc");
strcpy(deviceList[index].volumeId, "VOLID_MLC");
deviceList[index].flags = flags;
sprintf(deviceList[index].storagePath, "/vol/storage_mlc01");
index++;
// we currently dont emulate USB storage
*deviceCount = index;
}
void export_MCP_DeviceList(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(mcpHandle, 0);
ppcDefineParamU32BEPtr(deviceCount, 1);
ppcDefineParamStructPtr(deviceList, MCPDevice_t, 2);
ppcDefineParamU32(deviceListSize, 3);
cemuLog_logDebug(LogType::Force, "MCP_DeviceList()");
sint32 maxDeviceCount = deviceListSize / sizeof(MCPDevice_t);
if (maxDeviceCount < 2)
assert_dbg();
// if this doesnt return both MLC and SLC friendlist (frd.rpx) will softlock during boot
memset(deviceList, 0, sizeof(MCPDevice_t) * 1);
// 0
strcpy(deviceList[0].storageName, "mlc");
deviceList[0].flags = (0x01); // bitmask?
sprintf(deviceList[0].storagePath, "/vol/storage_%s%02x", deviceList[0].storageName, (sint32)deviceList[0].flags);
// 1
strcpy(deviceList[1].storageName, "slc");
deviceList[1].flags = (0x01); // bitmask?
sprintf(deviceList[1].storagePath, "/vol/storage_%s%02x", deviceList[1].storageName, (sint32)deviceList[1].flags);
// 2
//strcpy(deviceList[2].storageName, "usb");
//deviceList[2].storageSubindex = 1;
//sprintf(deviceList[2].storagePath, "/vol/storage_%s%02x", deviceList[2].storageName, (sint32)deviceList[2].storageSubindex);
*deviceCount = 2;
osLib_returnFromFunction(hCPU, 0);
}
void export_MCP_FullDeviceList(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(mcpHandle, 0);
ppcDefineParamU32BEPtr(deviceCount, 1);
ppcDefineParamStructPtr(deviceList, MCPDevice_t, 2);
ppcDefineParamU32(deviceListSize, 3);
cemuLog_logDebug(LogType::Force, "MCP_FullDeviceList()");
MCP_DeviceListEx(mcpHandle, deviceCount, deviceList, deviceListSize, true);
osLib_returnFromFunction(hCPU, 0);
}
void export_MCP_UpdateCheckContext(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(mcpHandle, 0);
ppcDefineParamU32BEPtr(unknownParam, 1);
cemuLog_logDebug(LogType::Force, "MCP_UpdateCheckContext() - placeholder (might be wrong)");
*unknownParam = 1;
osLib_returnFromFunction(hCPU, 0);
}
void export_MCP_TitleListUpdateGetNext(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(mcpHandle, 0);
ppcDefineParamMPTR(callbackMPTR, 1);
cemuLog_logDebug(LogType::Force, "MCP_TitleListUpdateGetNext() - placeholder/unimplemented");
// this callback is to let the app know when the title list changed?
//PPCCoreCallback(callbackMPTR); // -> If we trigger the callback then the menu will repeat with a call to MCP_GetTitleList(), MCP_DeviceList() and MCP_TitleListUpdateGetNext
osLib_returnFromFunction(hCPU, 0);
}
void export_MCP_GetOverlayAppInfo(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "MCP_GetOverlayAppInfo(...) placeholder");
ppcDefineParamU32(mcpHandle, 0);
ppcDefineParamU32(appType, 1);
ppcDefineParamU32(uknR5, 2);
ppcDefineParamStructPtr(titleList, MCPTitleInfo, 3);
// hacky
mcpPrepareRequest();
mcpRequest->requestCode = IOSU_MCP_GET_TITLE_LIST_BY_APP_TYPE;
mcpRequest->titleListRequest.titleCount = 1;
mcpRequest->titleListRequest.titleList = titleList;
mcpRequest->titleListRequest.titleListBufferSize = sizeof(MCPTitleInfo)*1;
mcpRequest->titleListRequest.appType = appType;
__depr__IOS_Ioctlv(IOS_DEVICE_MCP, IOSU_MCP_REQUEST_CEMU, 1, 1, mcpBufferVector);
if (mcpRequest->titleListRequest.titleCount != 1)
assert_dbg();
osLib_returnFromFunction(hCPU, 0);
}
uint32 MCP_UpdateClearContextAsync(uint32 mcpHandle, betype<MPTR>* callbackPtr)
{
cemuLog_logDebug(LogType::Force, "MCP_UpdateClearContextAsync() - stubbed");
uint32 clearContextResult = 0;
PPCCoreCallback(*callbackPtr, clearContextResult);
return 0;
}
uint32 MCP_InstallUtilGetTitleEnability(uint32 mcpHandle, uint32be* enabilityOutput, MCPTitleInfo* title)
{
*enabilityOutput = 1;
return 0;
}
uint32 MCP_GetEcoSettings(uint32 mcpHandle, uint32be* flagCaffeineEnable, uint32be* uknFlag2, uint32be* uknFlag3)
{
*flagCaffeineEnable = 1; // returning 1 here will stop the Wii U Menu from showing the Quick Start setup dialogue
*uknFlag2 = 0;
*uknFlag3 = 0;
return 0;
}
uint32 MCP_RightCheckLaunchable(uint32 mcpHandle, uint64 titleId, uint32be* launchableOut)
{
*launchableOut = 1;
return 0;
}
uint32 MCP_GetTitleId(uint32 mcpHandle, uint64be* outTitleId)
{
*outTitleId = CafeSystem::GetForegroundTitleId();
return 0;
}
void InitializeMCP()
{
osLib_addFunction("coreinit", "MCP_Open", coreinitExport_MCP_Open);
osLib_addFunction("coreinit", "MCP_Close", coreinitExport_MCP_Close);
osLib_addFunction("coreinit", "MCP_GetSysProdSettings", coreinitExport_MCP_GetSysProdSettings);
osLib_addFunction("coreinit", "MCP_TitleListByAppType", coreinitExport_MCP_TitleListByAppType);
osLib_addFunction("coreinit", "MCP_TitleList", coreinitExport_MCP_TitleList);
osLib_addFunction("coreinit", "MCP_TitleCount", coreinitExport_MCP_TitleCount);
osLib_addFunction("coreinit", "MCP_GetTitleInfo", coreinitExport_MCP_GetTitleInfo);
osLib_addFunction("coreinit", "MCP_GetTitleInfoByTitleAndDevice", coreinitExport_MCP_GetTitleInfoByTitleAndDevice);
osLib_addFunction("coreinit", "MCP_TitleListByDevice", export_MCP_TitleListByDevice);
osLib_addFunction("coreinit", "MCP_GetSystemVersion", export_MCP_GetSystemVersion);
osLib_addFunction("coreinit", "MCP_Get4SecondOffStatus", export_MCP_Get4SecondOffStatus);
osLib_addFunction("coreinit", "MCP_DeviceList", export_MCP_DeviceList);
osLib_addFunction("coreinit", "MCP_FullDeviceList", export_MCP_FullDeviceList);
osLib_addFunction("coreinit", "MCP_UpdateCheckContext", export_MCP_UpdateCheckContext);
osLib_addFunction("coreinit", "MCP_TitleListUpdateGetNext", export_MCP_TitleListUpdateGetNext);
osLib_addFunction("coreinit", "MCP_GetOverlayAppInfo", export_MCP_GetOverlayAppInfo);
cafeExportRegister("coreinit", MCP_UpdateClearContextAsync, LogType::Placeholder);
cafeExportRegister("coreinit", MCP_InstallUtilGetTitleEnability, LogType::Placeholder);
cafeExportRegister("coreinit", MCP_RightCheckLaunchable, LogType::Placeholder);
cafeExportRegister("coreinit", MCP_GetEcoSettings, LogType::Placeholder);
cafeExportRegister("coreinit", MCP_GetTitleId, LogType::Placeholder);
}
}
typedef struct
{
char settingName[0x40];
uint32 ukn1;
uint32 ukn2;
uint32 ukn3;
uint32 ukn4_size; // size guessed
MPTR resultPtr; // pointer to output value
}UCParamStruct_t;
static_assert(sizeof(UCParamStruct_t) == 0x54); // unsure
#if BOOST_OS_LINUX || BOOST_OS_MACOS
#define _strcmpi strcasecmp
#endif
void coreinitExport_UCReadSysConfig(PPCInterpreter_t* hCPU)
{
// parameters:
// r3 = UC handle?
// r4 = Number of values to read (count of UCParamStruct_t entries)
// r5 = UCParamStruct_t*
UCParamStruct_t* ucParamBase = (UCParamStruct_t*)memory_getPointerFromVirtualOffset(hCPU->gpr[5]);
uint32 ucParamCount = hCPU->gpr[4];
for(uint32 i=0; i<ucParamCount; i++)
{
UCParamStruct_t* ucParam = ucParamBase+i;
if(_strcmpi(ucParam->settingName, "cafe.cntry_reg") == 0)
{
// country code
// get country from simple address
uint32be simpleAddress = 0;
nn::act::GetSimpleAddressIdEx(&simpleAddress, nn::act::ACT_SLOT_CURRENT);
uint32 countryCode = nn::act::getCountryCodeFromSimpleAddress(simpleAddress);
if( ucParam->resultPtr != _swapEndianU32(MPTR_NULL) )
memory_writeU32(_swapEndianU32(ucParam->resultPtr), countryCode);
}
else if (_strcmpi(ucParam->settingName, "cafe.language") == 0)
{
// language
// 0 -> Japanese
// 1 -> English
// ...
uint32 languageId = (uint32)GetConfig().console_language.GetValue();
if (ucParam->resultPtr != _swapEndianU32(MPTR_NULL))
memory_writeU32(_swapEndianU32(ucParam->resultPtr), languageId);
}
else if (_strcmpi(ucParam->settingName, "cafe.initial_launch") == 0)
{
// initial launch
// possible ids:
// 0xFF Set by SCIFormatSystem (default?)
// 0x01 Inited but no user created yet (setting this will make the home menu go into user creation dialog)
// 0x02 Inited, with user
// other values are unknown
memory_writeU8(_swapEndianU32(ucParam->resultPtr), 2);
}
else if (_strcmpi(ucParam->settingName, "cafe.eula_version") == 0)
{
// todo - investigate values
memory_writeU32(_swapEndianU32(ucParam->resultPtr), 0);
}
else if (_strcmpi(ucParam->settingName, "cafe.eula_agree") == 0)
{
// todo - investigate values
memory_writeU8(_swapEndianU32(ucParam->resultPtr), 0);
}
else if (_strcmpi(ucParam->settingName, "cafe.version") == 0)
{
// todo - investigate values
memory_writeU16(_swapEndianU32(ucParam->resultPtr), 0);
}
else if (_strcmpi(ucParam->settingName, "cafe.eco") == 0)
{
// todo - investigate values
memory_writeU8(_swapEndianU32(ucParam->resultPtr), 0);
}
else if (_strcmpi(ucParam->settingName, "cafe.fast_boot") == 0)
{
// todo - investigate values
memory_writeU8(_swapEndianU32(ucParam->resultPtr), 0);
}
else if (_strcmpi(ucParam->settingName, "parent.enable") == 0)
{
// parental feature enabled
if (ucParam->resultPtr != _swapEndianU32(MPTR_NULL))
memory_writeU32(_swapEndianU32(ucParam->resultPtr), 0);
}
else if (_strcmpi(ucParam->settingName, "nn.act.account_repaired") == 0)
{
if (ucParam->resultPtr != _swapEndianU32(MPTR_NULL))
memory_writeU8(_swapEndianU32(ucParam->resultPtr), 0);
}
else if (_strcmpi(ucParam->settingName, "p_acct1.net_communication_on_game") == 0)
{
// get parental online control for online features
// note: This option is account-bound, the p_acct1 prefix indicates that the account in slot 1 is used
// a non-zero value means network access is restricted through parental access. 0 means allowed
// account in slot 1
if (ucParam->resultPtr != _swapEndianU32(MPTR_NULL))
memory_writeU8(_swapEndianU32(ucParam->resultPtr), 0); // data type is guessed
}
else if (_strcmpi(ucParam->settingName, "p_acct1.int_movie") == 0)
{
// get parental online control for movies?
// used by Pikmin HD movies
if (ucParam->resultPtr != _swapEndianU32(MPTR_NULL))
memory_writeU8(_swapEndianU32(ucParam->resultPtr), 0); // 0 -> allowed
}
else if (_strcmpi(ucParam->settingName, "p_acct1.network_launcher") == 0)
{
// miiverse restrictions
if (ucParam->resultPtr != _swapEndianU32(MPTR_NULL))
memory_writeU8(_swapEndianU32(ucParam->resultPtr), 0); // data type is guessed (0 -> no restrictions, 1 -> read only, 2 -> no access)
}
else if (_strcmpi(ucParam->settingName, "s_acct01.uuid") == 0)
{
if (ucParam->resultPtr != _swapEndianU32(MPTR_NULL) && ucParam->ukn4_size >= 37)
{
StackAllocator<uint8, 16> _uuid;
uint8* uuid = _uuid.GetPointer();
nn::act::GetUuidEx(uuid, 1, 0);
char tempStr[64];
sprintf(tempStr, "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7],
uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
strcpy((char*)memory_getPointerFromVirtualOffset(_swapEndianU32(ucParam->resultPtr)), tempStr);
}
}
else if (_strcmpi(ucParam->settingName, "s_acct01.nn.ec.eshop_initialized") == 0)
{
// E-Shop welcome screen
if (ucParam->resultPtr != _swapEndianU32(MPTR_NULL))
memory_writeU8(_swapEndianU32(ucParam->resultPtr), 1); // data type is guessed
}
else if (_strcmpi(ucParam->settingName, "p_acct1.int_browser") == 0)
{
if (ucParam->resultPtr != _swapEndianU32(MPTR_NULL))
memory_writeU8(_swapEndianU32(ucParam->resultPtr), 0);
}
/* caffeine settings (Quick Start) */
else if (_strcmpi(ucParam->settingName, "caffeine.enable") == 0)
{
if (ucParam->resultPtr != _swapEndianU32(MPTR_NULL))
memory_writeU8(_swapEndianU32(ucParam->resultPtr), 1);
}
else if (_strcmpi(ucParam->settingName, "caffeine.ad_enable") == 0)
{
if (ucParam->resultPtr != _swapEndianU32(MPTR_NULL))
memory_writeU8(_swapEndianU32(ucParam->resultPtr), 0);
}
else if (_strcmpi(ucParam->settingName, "caffeine.push_enable") == 0)
{
if (ucParam->resultPtr != _swapEndianU32(MPTR_NULL))
memory_writeU8(_swapEndianU32(ucParam->resultPtr), 0);
}
else if (_strcmpi(ucParam->settingName, "caffeine.drcled_enable") == 0)
{
if (ucParam->resultPtr != _swapEndianU32(MPTR_NULL))
memory_writeU8(_swapEndianU32(ucParam->resultPtr), 0);
}
else
{
cemuLog_logDebug(LogType::Force, "Unsupported SCI value: {} Size {:08x}", ucParam->settingName, ucParam->ukn4_size);
}
}
osLib_returnFromFunction(hCPU, 0); // 0 -> success
}
| 22,155
|
C++
|
.cpp
| 516
| 40.114341
| 176
| 0.754634
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,126
|
nlibcurl.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nlibcurl/nlibcurl.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/common/OSUtil.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "nlibcurl.h"
#include "openssl/bn.h"
#include "openssl/x509.h"
#include "openssl/ssl.h"
#define CURL_STRICTER
#include "curl/curl.h"
#include <unordered_map>
#include <atomic>
#include "Cafe/IOSU/legacy/iosu_crypto.h"
#include "Cafe/OS/libs/nsysnet/nsysnet.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM.h"
#include "util/helpers/ConcurrentQueue.h"
#include "Cafe/OS/common/PPCConcurrentQueue.h"
#include "Common/FileStream.h"
#include "config/ActiveSettings.h"
namespace nlibcurl
{
#define CURL_MULTI_HANDLE (0x000bab1e)
#define NSSL_VERIFY_NONE (0x0)
#define NSSL_VERIFY_PEER (1<<0)
#define NSSL_VERIFY_HOSTNAME (1<<1)
#define NSSL_VERIFY_DATE (1<<2)
enum QueueOrder
{
QueueOrder_None,
QueueOrder_Result,
QueueOrder_CBDone,
QueueOrder_HeaderCB,
QueueOrder_ReadCB,
QueueOrder_WriteCB,
QueueOrder_ProgressCB,
QueueOrder_Perform,
QueueOrder_Pause,
};
struct QueueMsg_t
{
QueueOrder order;
union
{
uint32 result;
struct
{
char* buffer;
uint32 size;
uint32 nitems;
} header_cb;
struct
{
char* buffer;
uint32 size;
uint32 nitems;
} read_cb;
struct
{
char* buffer;
uint32 size;
uint32 nmemb;
} write_cb;
struct
{
uint32 clientp;
double dltotal;
double dlnow;
double ultotal;
double ulnow;
} progress_cb;
struct
{
sint32 bitmask;
} pause;
};
};
struct MEMPTRHash_t
{
size_t operator()(const MEMPTR<void>& p) const
{
return p.GetMPTR();
}
};
struct WU_curl_slist
{
MEMPTR<char> data;
MEMPTR<WU_curl_slist> next;
};
enum class WU_CURLcode
{
placeholder = 0,
};
struct
{
sint32 initialized;
MEMPTR<void> proxyConfig;
MEMPTR<curl_malloc_callback> malloc;
MEMPTR<curl_free_callback> free;
MEMPTR<curl_realloc_callback> realloc;
MEMPTR<curl_strdup_callback> strdup;
MEMPTR<curl_calloc_callback> calloc;
} g_nlibcurl = {};
using WU_CURL_off_t = uint64be;
enum class WU_HTTPREQ : uint32
{
HTTPREQ_GET = 0x1,
HTTPREQ_POST = 0x2,
UKN_3 = 0x3,
};
struct WU_UserDefined
{
// starting at 0xD8 (probably) in CURL_t
/* 0x0D8 / +0x00 */ uint32be ukn0D8;
/* 0x0DC / +0x04 */ uint32be ukn0DC;
/* 0x0E0 / +0x08 */ MEMPTR<WU_curl_slist> headers;
/* 0x0E4 / +0x0C */ uint32be ukn0E4;
/* 0x0E8 / +0x10 */ uint32be ukn0E8;
/* 0x0EC / +0x14 */ uint32be ukn0EC;
/* 0x0F0 / +0x18 */ uint32be ukn0F0[4];
/* 0x100 / +0x28 */ uint32be ukn100[4];
/* 0x110 / +0x38 */ uint32be ukn110[4]; // +0x40 -> WU_CURL_off_t postfieldsize ?
/* 0x120 / +0x48 */ uint32be ukn120[4];
/* 0x130 / +0x58 */ uint32be ukn130[4];
/* 0x140 / +0x68 */ uint32be ukn140[4];
/* 0x150 / +0x78 */ uint32be ukn150[4];
/* 0x160 / +0x88 */ uint32be ukn160[4];
/* 0x170 / +0x98 */ uint32be ukn170[4];
/* 0x180 / +0xA8 */ uint32be ukn180[4];
/* 0x190 / +0xB0 */ sint64be infilesize_190{0};
/* 0x198 / +0xB8 */ uint32be ukn198;
/* 0x19C / +0xBC */ uint32be ukn19C;
/* 0x1A0 / +0xC8 */ uint32be ukn1A0[4];
/* 0x1B0 / +0xD8 */ uint32be ukn1B0[4];
/* 0x1C0 / +0xE8 */ uint32be ukn1C0[4];
/* 0x1D0 / +0xF8 */ uint32be ukn1D0[4];
/* 0x1E0 / +0x108 */ uint32be ukn1E0;
/* 0x1E4 / +0x108 */ uint32be ukn1E4;
/* 0x1E8 / +0x108 */ uint32be ukn1E8;
/* 0x1EC / +0x108 */ betype<WU_HTTPREQ> httpreq_1EC;
/* 0x1F0 / +0x118 */ uint32be ukn1F0[4];
void SetToDefault()
{
memset(this, 0, sizeof(WU_UserDefined));
httpreq_1EC = WU_HTTPREQ::HTTPREQ_GET;
}
};
struct CURL_t
{
CURL* curl;
uint32be hNSSL;
uint32be nsslVerifyOptions;
MEMPTR<void> out; // CURLOPT_WRITEDATA
MEMPTR<void> in_set; // CURLOPT_READDATA
MEMPTR<void> writeheader; // CURLOPT_HEADERDATA
MEMPTR<void> fwrite_func; // CURLOPT_WRITEFUNCTION
MEMPTR<void> fwrite_header; // CURLOPT_HEADERFUNCTION
MEMPTR<void> fread_func_set; // CURLOPT_READFUNCTION
MEMPTR<void> progress_client; // CURLOPT_PROGRESSDATA
MEMPTR<void> fprogress; // CURLOPT_PROGRESSFUNCTION
MEMPTR<void> fsockopt; // CURLOPT_SOCKOPTFUNCTION
MEMPTR<void> sockopt_client; // CURLOPT_SOCKOPTDATA
// Cemu specific
OSThread_t* curlThread;
MEMPTR<char> info_redirectUrl; // stores CURLINFO_REDIRECT_URL ptr
MEMPTR<char> info_contentType; // stores CURLINFO_CONTENT_TYPE ptr
bool isDirty{true};
// debug
struct
{
uint32 activeRequestIndex{};
uint32 responseRequestIndex{}; // set to activeRequestIndex once perform is called
bool hasDumpedResultInfo{}; // set once the response info has been dumped (reset when next request is performed)
FileStream* file_requestParam{};
FileStream* file_responseHeaders{};
FileStream* file_responseRaw{};
}debug;
// fields below match the actual memory layout, above still needs refactoring
/* 0x78 */ uint32be ukn078;
/* 0x7C */ uint32be ukn07C;
/* 0x80 */ uint32be ukn080;
/* 0x84 */ uint32be ukn084;
/* 0x88 */ uint32be ukn088;
/* 0x8C */ uint32be ukn08C;
/* 0x90 */ uint32be ukn090[4];
/* 0xA0 */ uint32be ukn0A0[4];
/* 0xB0 */ uint32be ukn0B0[4];
/* 0xC0 */ uint32be ukn0C0[4];
/* 0xD0 */ uint32be ukn0D0;
/* 0xD4 */ uint32be ukn0D4;
/* 0xD8 */ WU_UserDefined set;
/* 0x200 */ uint32be ukn200[4];
/* 0x210 */ uint32be ukn210[4];
/* 0x220 */ uint32be ukn220[4];
/* 0x230 */ uint32be ukn230[4];
/* 0x240 */ uint32be ukn240[4];
/* 0x250 */ uint32be ukn250[4];
/* 0x260 */ uint32be ukn260[4];
/* 0x270 */ uint32be ukn270[4];
/* 0x280 */ uint8be ukn280;
/* 0x281 */ uint8be opt_no_body_281;
/* 0x282 */ uint8be ukn282;
/* 0x283 */ uint8be upload_283;
};
static_assert(sizeof(CURL_t) <= 0x8698);
static_assert(offsetof(CURL_t, ukn078) == 0x78);
static_assert(offsetof(CURL_t, set) == 0xD8);
static_assert(offsetof(CURL_t, set) + offsetof(WU_UserDefined, headers) == 0xE0);
static_assert(offsetof(CURL_t, set) + offsetof(WU_UserDefined, infilesize_190) == 0x190);
static_assert(offsetof(CURL_t, set) + offsetof(WU_UserDefined, httpreq_1EC) == 0x1EC);
static_assert(offsetof(CURL_t, opt_no_body_281) == 0x281);
typedef MEMPTR<CURL_t> CURLPtr;
#pragma pack(1) // may affect structs below, we can probably remove this but lets keep it for now as the code below is fragile
typedef struct
{
//uint32be specifier; // 0x00
//uint32be dirty; // 0x04
MEMPTR<void> lockfunc; // 0x08
MEMPTR<void> unlockfunc; // 0x0C
MEMPTR<void> data; // 0x10
//MEMPTR<void> uk14; // 0x14
//MEMPTR<void> uk18; // 0x18
CURLSH* curlsh;
MEMPTR <CURL_t> curl;
uint32 uk1;
}CURLSH_t; // SCURL
static_assert(sizeof(CURLSH_t) <= 0x1C);
typedef MEMPTR<CURLSH_t> CURLSHPtr;
typedef struct
{
CURLM* curlm;
std::vector<MEMPTR<CURL_t>> curl;
}CURLM_t;
static_assert(sizeof(CURLM_t) <= 0x80, "sizeof(CURLM_t)");
typedef MEMPTR<CURLM_t> CURLMPtr;
static_assert(sizeof(WU_curl_slist) <= 0x8, "sizeof(curl_slist_t)");
struct CURLMsg_t
{
uint32be msg;
MEMPTR<CURL_t> curl;
uint32be result; // CURLcode
};
static_assert(sizeof(CURLMsg_t) <= 0xC, "sizeof(CURLMsg_t)");
#pragma pack()
#include "nlibcurlDebug.hpp"
size_t header_callback(char* buffer, size_t size, size_t nitems, void* userdata);
thread_local PPCConcurrentQueue<QueueMsg_t>* g_callerQueue;
thread_local ConcurrentQueue<QueueMsg_t>* g_threadQueue;
void CurlWorkerThread(CURL_t* curl, PPCConcurrentQueue<QueueMsg_t>* callerQueue, ConcurrentQueue<QueueMsg_t>* threadQueue)
{
g_callerQueue = callerQueue;
g_threadQueue = threadQueue;
const QueueMsg_t msg = threadQueue->pop();
QueueMsg_t resultMsg = {};
resultMsg.order = QueueOrder_Result;
if (msg.order == QueueOrder_Perform)
resultMsg.result = ::curl_easy_perform(curl->curl);
else if(msg.order == QueueOrder_Pause)
resultMsg.result = ::curl_easy_pause(curl->curl, msg.pause.bitmask);
else
assert_dbg();
callerQueue->push(resultMsg, curl->curlThread);
}
uint32 SendOrderToWorker(CURL_t* curl, QueueOrder order, uint32 arg1 = 0)
{
OSThread_t* currentThread = coreinit::OSGetCurrentThread();
curl->curlThread = currentThread;
// cemuLog_logDebug(LogType::Force, "CURRENTTHREAD: 0x{} -> {}",currentThread, order)
PPCConcurrentQueue<QueueMsg_t> callerQueue;
ConcurrentQueue<QueueMsg_t> threadQueue;
std::thread worker(CurlWorkerThread, curl, &callerQueue, &threadQueue);
worker.detach();
QueueMsg_t orderMsg = {};
orderMsg.order = order;
if (order == QueueOrder_Pause)
orderMsg.pause.bitmask = arg1;
threadQueue.push(orderMsg);
uint32 result;
while (true)
{
const QueueMsg_t msg = callerQueue.pop(currentThread);
if (msg.order == QueueOrder_ProgressCB)
{
QueueMsg_t sendMsg = {};
sendMsg.order = QueueOrder_CBDone;
sendMsg.result = PPCCoreCallback(curl->fprogress.GetMPTR(), curl->progress_client.GetMPTR(), msg.progress_cb.dltotal, msg.progress_cb.dlnow, msg.progress_cb.ultotal, msg.progress_cb.ulnow);
threadQueue.push(sendMsg);
}
else if (msg.order == QueueOrder_HeaderCB)
{
StackAllocator<char> tmp(msg.header_cb.size * msg.header_cb.nitems);
memcpy(tmp.GetPointer(), msg.header_cb.buffer, msg.header_cb.size * msg.header_cb.nitems);
QueueMsg_t sendMsg = {};
sendMsg.order = QueueOrder_CBDone;
sendMsg.result = PPCCoreCallback(curl->fwrite_header.GetMPTR(), tmp.GetMPTR(), msg.header_cb.size, msg.header_cb.nitems, curl->writeheader.GetMPTR());
threadQueue.push(sendMsg);
}
else if (msg.order == QueueOrder_ReadCB)
{
StackAllocator<char> tmp(msg.read_cb.size * msg.read_cb.nitems);
QueueMsg_t sendMsg = {};
sendMsg.order = QueueOrder_CBDone;
cemuLog_logDebug(LogType::Force, "QueueOrder_ReadCB size: {} nitems: {}", msg.read_cb.size, msg.read_cb.nitems);
sendMsg.result = PPCCoreCallback(curl->fread_func_set.GetMPTR(), tmp.GetMPTR(), msg.read_cb.size, msg.read_cb.nitems, curl->in_set.GetMPTR());
cemuLog_logDebug(LogType::Force, "readcb size: {}", (sint32)sendMsg.result);
if (sendMsg.result > 0)
memcpy(msg.read_cb.buffer, tmp.GetPointer(), sendMsg.result);
threadQueue.push(sendMsg);
}
else if (msg.order == QueueOrder_WriteCB)
{
StackAllocator<char> tmp(msg.write_cb.size * msg.write_cb.nmemb);
memcpy(tmp.GetPointer(), msg.write_cb.buffer, msg.write_cb.size * msg.write_cb.nmemb);
QueueMsg_t sendMsg = {};
sendMsg.order = QueueOrder_CBDone;
sendMsg.result = PPCCoreCallback(curl->fwrite_func.GetMPTR(), tmp.GetMPTR(), msg.write_cb.size, msg.write_cb.nmemb, curl->out.GetMPTR());
threadQueue.push(sendMsg);
}
else if (msg.order == QueueOrder_Result)
{
result = msg.result;
break;
}
}
return result;
}
static int curl_closesocket(void *clientp, curl_socket_t item)
{
nsysnet_notifyCloseSharedSocket((SOCKET)item);
closesocket(item);
return 0;
}
void _curl_set_default_parameters(CURL_t* curl)
{
curl->set.SetToDefault();
// default parameters
curl_easy_setopt(curl->curl, CURLOPT_HEADERFUNCTION, header_callback);
curl_easy_setopt(curl->curl, CURLOPT_HEADERDATA, curl);
curl_easy_setopt(curl->curl, CURLOPT_CLOSESOCKETFUNCTION, curl_closesocket);
curl_easy_setopt(curl->curl, CURLOPT_CLOSESOCKETDATA, nullptr);
}
void _curl_sync_parameters(CURL_t* curl)
{
// sync ppc curl to actual curl state
// not all parameters are covered yet, many are still set directly in easy_setopt
bool isPost = curl->set.httpreq_1EC == WU_HTTPREQ::HTTPREQ_POST;
// http request type
if(curl->set.httpreq_1EC == WU_HTTPREQ::HTTPREQ_GET)
{
::curl_easy_setopt(curl->curl, CURLOPT_HTTPGET, 1);
cemu_assert_debug(curl->opt_no_body_281 == 0);
cemu_assert_debug(curl->upload_283 == 0);
}
else if(curl->set.httpreq_1EC == WU_HTTPREQ::HTTPREQ_POST)
{
::curl_easy_setopt(curl->curl, CURLOPT_POST, 1);
cemu_assert_debug(curl->upload_283 == 0);
::curl_easy_setopt(curl->curl, CURLOPT_NOBODY, curl->opt_no_body_281 ? 1 : 0);
}
else
{
cemu_assert_unimplemented();
}
// CURLOPT_HTTPHEADER
std::optional<uint64> manualHeaderContentLength;
if (curl->set.headers)
{
struct curl_slist* list = nullptr;
WU_curl_slist* ppcList = curl->set.headers;
while(ppcList)
{
if(isPost)
{
// for recent libcurl manually adding Content-Length header is undefined behavior. Instead CURLOPT_INFILESIZE(_LARGE) should be set
// here we remove Content-Length and instead substitute it with CURLOPT_INFILESIZE (NEX DataStore in Super Mario Maker requires this)
if(strncmp(ppcList->data.GetPtr(), "Content-Length:", 15) == 0)
{
manualHeaderContentLength = std::stoull(ppcList->data.GetPtr() + 15);
ppcList = ppcList->next;
continue;
}
}
cemuLog_logDebug(LogType::Force, "curl_slist_append: {}", ppcList->data.GetPtr());
curlDebug_logEasySetOptStr(curl, "CURLOPT_HTTPHEADER", (const char*)ppcList->data.GetPtr());
list = ::curl_slist_append(list, ppcList->data.GetPtr());
ppcList = ppcList->next;
}
::curl_easy_setopt(curl->curl, CURLOPT_HTTPHEADER, list);
// todo - prevent leaking of list (maybe store in host curl object, similar to how our zlib implementation does stuff)
}
else
::curl_easy_setopt(curl->curl, CURLOPT_HTTPHEADER, nullptr);
// infile size (post data size)
if (curl->set.infilesize_190)
{
cemu_assert_debug(manualHeaderContentLength == 0); // should not have both?
::curl_easy_setopt(curl->curl, CURLOPT_INFILESIZE_LARGE, curl->set.infilesize_190);
}
else
{
if(isPost && manualHeaderContentLength > 0)
::curl_easy_setopt(curl->curl, CURLOPT_INFILESIZE_LARGE, manualHeaderContentLength);
else
::curl_easy_setopt(curl->curl, CURLOPT_INFILESIZE_LARGE, 0);
}
}
void export_malloc(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(size, 0);
MPTR memAddr = PPCCoreCallback(gCoreinitData->MEMAllocFromDefaultHeap, size);
osLib_returnFromFunction(hCPU, memAddr);
}
void export_calloc(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(count, 0);
ppcDefineParamU32(size, 1);
MPTR memAddr = PPCCoreCallback(gCoreinitData->MEMAllocFromDefaultHeap, count*size);
osLib_returnFromFunction(hCPU, memAddr);
}
void export_free(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(mem, void, 0);
PPCCoreCallback(gCoreinitData->MEMFreeToDefaultHeap, mem.GetMPTR());
osLib_returnFromFunction(hCPU, 0);
}
void export_strdup(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(str, const char, 0);
int len = (int)strlen(str.GetPtr()) + 1;
MEMPTR<char> result = (char*)coreinit::default_MEMAllocFromDefaultHeap(len);
strcpy(result.GetPtr(), str.GetPtr());
osLib_returnFromFunction(hCPU, result.GetMPTR());
}
void export_realloc(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(mem, void, 0);
ppcDefineParamU32(size, 1);
MEMPTR<void> result = coreinit::default_MEMAllocFromDefaultHeap(size);
memcpy(result.GetPtr(), mem.GetPtr(), size);
coreinit::default_MEMFreeToDefaultHeap(mem.GetPtr());
osLib_returnFromFunction(hCPU, result.GetMPTR());
}
CURLcode curl_global_init(uint32 flags)
{
if (g_nlibcurl.initialized++)
{
return CURLE_OK;
}
g_nlibcurl.malloc = PPCInterpreter_makeCallableExportDepr(export_malloc);
g_nlibcurl.calloc = PPCInterpreter_makeCallableExportDepr(export_calloc);
g_nlibcurl.free = PPCInterpreter_makeCallableExportDepr(export_free);
g_nlibcurl.strdup = PPCInterpreter_makeCallableExportDepr(export_strdup);
g_nlibcurl.realloc = PPCInterpreter_makeCallableExportDepr(export_realloc);
// curl_read_default_proxy_config()
return ::curl_global_init(flags);
}
void export_curl_multi_init(PPCInterpreter_t* hCPU)
{
CURLMPtr result{ PPCCoreCallback(g_nlibcurl.calloc, 1, ppcsizeof<CURLM_t>()) };
cemuLog_logDebug(LogType::Force, "curl_multi_init() -> 0x{:08x}", result.GetMPTR());
if (result)
{
memset(result.GetPtr(), 0, sizeof(CURLM_t));
*result = {};
result->curlm = curl_multi_init();
}
osLib_returnFromFunction(hCPU, result.GetMPTR());
}
void export_curl_multi_add_handle(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(curlm, CURLM_t, 0);
ppcDefineParamMEMPTR(curl, CURL_t, 1);
curlDebug_markActiveRequest(curl.GetPtr());
curlDebug_notifySubmitRequest(curl.GetPtr());
CURLMcode result = ::curl_multi_add_handle(curlm->curlm, curl->curl);
if (result == CURLM_OK)
curlm->curl.push_back(curl.GetPtr());
cemuLog_logDebug(LogType::Force, "curl_multi_add_handle(0x{:08x}, 0x{:08x}) -> 0x{:x}", curlm.GetMPTR(), curl.GetMPTR(), result);
osLib_returnFromFunction(hCPU, result);
}
void export_curl_multi_remove_handle(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(curlm, CURLM_t, 0);
ppcDefineParamMEMPTR(curl, CURL_t, 1);
CURLMcode result = curl_multi_remove_handle(curlm->curlm, curl->curl);
if (result == CURLM_OK)
{
curlm->curl.erase(std::remove(curlm->curl.begin(), curlm->curl.end(), (void*)curl.GetPtr()), curlm->curl.end());
}
cemuLog_logDebug(LogType::Force, "curl_multi_remove_handle(0x{:08x}, 0x{:08x}) -> 0x{:x}", curlm.GetMPTR(), curl.GetMPTR(), result);
osLib_returnFromFunction(hCPU, result);
}
void export_curl_multi_timeout(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(curlm, CURLM_t, 0);
ppcDefineParamMEMPTR(timeoParam, uint32be, 1);
long timeoutLE = (long)(uint32)*timeoParam;
CURLMcode result = ::curl_multi_timeout(curlm->curlm, &timeoutLE);
*timeoParam = (uint32)timeoutLE;
cemuLog_logDebug(LogType::Force, "curl_multi_timeout(0x{:08x}, 0x{:08x} [{}]) -> 0x{:x}", curlm.GetMPTR(), timeoParam.GetMPTR(), timeoutLE, result);
osLib_returnFromFunction(hCPU, result);
}
void export_curl_multi_cleanup(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(curlm, CURLM_t, 0);
CURLMcode result = ::curl_multi_cleanup(curlm->curlm);
cemuLog_logDebug(LogType::Force, "curl_multi_cleanup(0x{:08x}) -> 0x{:x}", curlm.GetMPTR(), result);
curlm->curl.clear();
PPCCoreCallback(g_nlibcurl.free.GetMPTR(), curlm.GetMPTR());
osLib_returnFromFunction(hCPU, result);
}
void export_curl_multi_perform(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(curlm, CURLM_t, 0);
ppcDefineParamMEMPTR(runningHandles, uint32be, 1);
//cemuLog_logDebug(LogType::Force, "curl_multi_perform(0x{:08x}, 0x{:08x})", curlm.GetMPTR(), runningHandles.GetMPTR());
//curl_multi_get_handles(curlm->curlm);
for(auto _curl : curlm->curl)
{
CURL_t* curl = (CURL_t*)_curl.GetPtr();
if(curl->isDirty)
{
curl->isDirty = false;
_curl_sync_parameters(curl);
}
}
//g_callerQueue = curlm->callerQueue;
//g_threadQueue = curlm->threadQueue;
int tempRunningHandles = 0;
CURLMcode result = curl_multi_perform(curlm->curlm, &tempRunningHandles);
*(runningHandles.GetPtr()) = tempRunningHandles;
cemuLog_logDebug(LogType::Force, "curl_multi_perform(0x{:08x}, 0x{:08x}) -> 0x{:x} (running handles: {})", curlm.GetMPTR(), runningHandles.GetMPTR(), result, tempRunningHandles);
//const uint32 result = SendOrderToWorker(curlm.GetPtr(), QueueOrder_MultiPerform);
osLib_returnFromFunction(hCPU, result);
}
void export_curl_multi_fdset(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(curlm, CURLM_t, 0);
ppcDefineParamMEMPTR(readFd, wu_fd_set, 1);
ppcDefineParamMEMPTR(writeFd, wu_fd_set, 2);
ppcDefineParamMEMPTR(exceptionFd, wu_fd_set, 3);
ppcDefineParamU32BEPtr(maxFd, 4);
fd_set h_readFd;
fd_set h_writeFd;
fd_set h_exceptionFd;
FD_ZERO(&h_readFd);
FD_ZERO(&h_writeFd);
FD_ZERO(&h_exceptionFd);
sint32 h_maxFd = 0;
CURLMcode result = curl_multi_fdset(curlm->curlm, &h_readFd, &h_writeFd, &h_exceptionFd, &h_maxFd);
nsysnet::wuResetFD(readFd.GetPtr());
nsysnet::wuResetFD(writeFd.GetPtr());
nsysnet::wuResetFD(exceptionFd.GetPtr());
sint32 c_maxFD = -1;
auto hostFdSet = [&](SOCKET s, wu_fd_set* fds)
{
sint32 wuSocket = nsysnet_getVirtualSocketHandleFromHostHandle(s);
if (wuSocket < 0)
wuSocket = nsysnet_createVirtualSocketFromExistingSocket(s);
if (wuSocket >= 0)
{
c_maxFD = std::max(wuSocket, c_maxFD);
nsysnet::wuSetFD(fds, wuSocket);
}
};
#if BOOST_OS_UNIX
for (int s = 0; s < h_maxFd + 1; s++)
{
if(FD_ISSET(s, &h_readFd))
hostFdSet(s, readFd.GetPtr());
if(FD_ISSET(s, &h_writeFd))
hostFdSet(s, writeFd.GetPtr());
if(FD_ISSET(s, &h_exceptionFd))
hostFdSet(s, exceptionFd.GetPtr());
}
#else
// fd read set
for (uint32 i = 0; i < h_readFd.fd_count; i++)
{
hostFdSet(h_readFd.fd_array[i], readFd.GetPtr());
}
// fd write set
for (uint32 i = 0; i < h_writeFd.fd_count; i++)
{
hostFdSet(h_writeFd.fd_array[i], writeFd.GetPtr());
}
// fd exception set
for (uint32 i = 0; i < h_exceptionFd.fd_count; i++)
{
cemu_assert_debug(false);
}
#endif
*maxFd = c_maxFD;
osLib_returnFromFunction(hCPU, result);
}
void export_curl_multi_setopt(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(curlm, CURLM_t, 0);
ppcDefineParamU32(option, 1);
ppcDefineParamMEMPTR(parameter, void, 2);
ppcDefineParamU64(parameterU64, 2);
CURLMcode result = CURLM_OK;
switch (option)
{
case CURLMOPT_MAXCONNECTS:
result = ::curl_multi_setopt(curlm->curlm, (CURLMoption)option, parameter.GetMPTR());
break;
default:
cemuLog_logDebug(LogType::Force, "curl_multi_setopt(0x{:08x}, {}, 0x{:08x}) unsupported option", curlm.GetMPTR(), option, parameter.GetMPTR());
}
cemuLog_logDebug(LogType::Force, "curl_multi_setopt(0x{:08x}, {}, 0x{:08x}) -> 0x{:x}", curlm.GetMPTR(), option, parameter.GetMPTR(), result);
osLib_returnFromFunction(hCPU, result);
}
void export_curl_multi_info_read(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(curlm, CURLM_t, 0);
ppcDefineParamMEMPTR(msgsInQueue, int, 1);
CURLMsg* msg = ::curl_multi_info_read(curlm->curlm, msgsInQueue.GetPtr());
cemuLog_logDebug(LogType::Force, "curl_multi_info_read - todo");
if (msg)
{
MEMPTR<CURLMsg_t> result{ PPCCoreCallback(g_nlibcurl.malloc.GetMPTR(), ppcsizeof<CURLMsg_t>()) };
result->msg = msg->msg;
result->result = msg->data.result;
if (msg->easy_handle)
{
const auto it = find_if(curlm->curl.cbegin(), curlm->curl.cend(),
[msg](const MEMPTR<CURL_t>& curl)
{
const MEMPTR<CURL_t> _curl{ curl };
return _curl->curl = msg->easy_handle;
});
if (it != curlm->curl.cend())
result->curl = (CURL_t*)(*it).GetPtr();
}
else
result->curl = nullptr;
cemuLog_logDebug(LogType::Force, "curl_multi_info_read(0x{:08x}, 0x{:08x} [{}]) -> 0x{:08x} (0x{:x}, 0x{:08x}, 0x{:x})", curlm.GetMPTR(), msgsInQueue.GetMPTR(), *msgsInQueue.GetPtr(),
result.GetMPTR(), msg->msg, result->curl.GetMPTR(), msg->data.result);
osLib_returnFromFunction(hCPU, result.GetMPTR());
}
else
{
osLib_returnFromFunction(hCPU, 0);
}
}
void lock_function(CURL* handle, curl_lock_data data, curl_lock_access access, void* userptr)
{
CURLSH_t* share = (CURLSH_t*)userptr;
PPCCoreCallback(share->lockfunc.GetMPTR(), share->curl.GetMPTR(), (uint32)data, (uint32)access, share->data.GetMPTR());
}
void unlock_function(CURL* handle, curl_lock_data data, void* userptr)
{
CURLSH_t* share = (CURLSH_t*)userptr;
PPCCoreCallback(share->unlockfunc.GetMPTR(), share->curl.GetMPTR(), (uint32)data, share->data.GetMPTR());
}
void export_curl_share_setopt(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(share, CURLSH_t, 0);
ppcDefineParamU32(option, 1);
ppcDefineParamMEMPTR(parameter, void, 2);
/*if(share->dirty)
{
osLib_returnFromFunction(hCPU, CURLSHE_IN_USE);
return;
}*/
CURLSH* curlSh = share->curlsh;
CURLSHcode result = CURLSHE_OK;
switch (option)
{
case CURLSHOPT_USERDATA:
share->data = parameter;
result = curl_share_setopt(curlSh, CURLSHOPT_USERDATA, share.GetPtr());
break;
case CURLSHOPT_LOCKFUNC:
share->lockfunc = parameter;
result = curl_share_setopt(curlSh, CURLSHOPT_LOCKFUNC, lock_function);
break;
case CURLSHOPT_UNLOCKFUNC:
share->unlockfunc = parameter;
result = curl_share_setopt(curlSh, CURLSHOPT_UNLOCKFUNC, unlock_function);
break;
case CURLSHOPT_SHARE:
{
const sint32 type = parameter.GetMPTR();
result = curl_share_setopt(curlSh, CURLSHOPT_SHARE, type);
break;
}
case CURLSHOPT_UNSHARE:
{
const sint32 type = parameter.GetMPTR();
result = curl_share_setopt(curlSh, CURLSHOPT_UNSHARE, type);
break;
}
default:
cemu_assert_unimplemented();
}
cemuLog_logDebug(LogType::Force, "curl_share_setopt(0x{:08x}, 0x{:x}, 0x{:08x}) -> 0x{:x}", share.GetMPTR(), option, parameter.GetMPTR(), result);
osLib_returnFromFunction(hCPU, result);
}
void export_curl_share_init(PPCInterpreter_t* hCPU)
{
CURLSHPtr result{ PPCCoreCallback(g_nlibcurl.calloc.GetMPTR(), (uint32)1, ppcsizeof<CURLSH_t>()) };
cemuLog_logDebug(LogType::Force, "curl_share_init() -> 0x{:08x}", result.GetMPTR());
if (result)
{
memset(result.GetPtr(), 0, sizeof(CURLSH_t));
*result = {};
result->curlsh = curl_share_init();
}
osLib_returnFromFunction(hCPU, result.GetMPTR());
}
void export_curl_share_cleanup(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(curlsh, CURLSH_t, 0);
uint32 result = ::curl_share_cleanup(curlsh->curlsh);
cemuLog_logDebug(LogType::Force, "curl_share_cleanup(0x{:08x}) -> 0x{:x}", curlsh.GetMPTR(), result);
PPCCoreCallback(g_nlibcurl.free.GetMPTR(), curlsh.GetMPTR());
osLib_returnFromFunction(hCPU, 0);
}
CURL_t* curl_easy_init()
{
if (g_nlibcurl.initialized == 0)
{
if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK)
{
return nullptr;
}
}
// Curl_open
MEMPTR<CURL_t> result{ PPCCoreCallback(g_nlibcurl.calloc.GetMPTR(), (uint32)1, ppcsizeof<CURL_t>()) };
cemuLog_logDebug(LogType::Force, "curl_easy_init() -> 0x{:08x}", result.GetMPTR());
if (result)
{
memset(result.GetPtr(), 0, sizeof(CURL_t));
*result = {};
result->curl = ::curl_easy_init();
result->curlThread = coreinit::OSGetCurrentThread();
result->info_contentType = nullptr;
result->info_redirectUrl = nullptr;
_curl_set_default_parameters(result.GetPtr());
if (g_nlibcurl.proxyConfig)
{
// todo
}
}
return result;
}
CURL_t* mw_curl_easy_init()
{
return curl_easy_init();
}
void export_curl_easy_pause(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(curl, CURL_t, 0);
ppcDefineParamS32(bitmask, 1);
cemuLog_logDebug(LogType::Force, "curl_easy_pause(0x{:08x}, 0x{:x})", curl.GetMPTR(), bitmask);
//const CURLcode result = ::curl_easy_pause(curl->curl, bitmask);
const uint32 result = SendOrderToWorker(curl.GetPtr(), QueueOrder_Pause, bitmask);
cemuLog_logDebug(LogType::Force, "curl_easy_pause(0x{:08x}, 0x{:x}) DONE", curl.GetMPTR(), bitmask);
osLib_returnFromFunction(hCPU, result);
}
void export_curl_easy_cleanup(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(curl, CURL_t, 0);
cemuLog_logDebug(LogType::Force, "curl_easy_cleanup(0x{:08x})", curl.GetMPTR());
curlDebug_cleanup(curl.GetPtr());
::curl_easy_cleanup(curl->curl);
PPCCoreCallback(g_nlibcurl.free.GetMPTR(), curl.GetMPTR());
if (curl->info_contentType.IsNull() == false)
PPCCoreCallback(g_nlibcurl.free.GetMPTR(), curl->info_contentType.GetMPTR());
if (curl->info_redirectUrl.IsNull() == false)
PPCCoreCallback(g_nlibcurl.free.GetMPTR(), curl->info_redirectUrl.GetMPTR());
osLib_returnFromFunction(hCPU, 0);
}
void export_curl_easy_reset(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(curl, CURL_t, 0);
cemuLog_logDebug(LogType::Force, "curl_easy_reset(0x{:08x})", curl.GetMPTR());
// curl_apply_default_proxy_config();
::curl_easy_reset(curl->curl);
osLib_returnFromFunction(hCPU, 0);
}
int ssl_verify_callback(int preverify_ok, X509_STORE_CTX* ctx)
{
if (preverify_ok) return preverify_ok;
int err = X509_STORE_CTX_get_error(ctx);
if(err != 0)
cemuLog_logDebug(LogType::Force, "ssl_verify_callback: Error {} but allow certificate anyway", err);
X509_STORE_CTX_set_error(ctx, 0);
return 1;
}
CURLcode ssl_ctx_callback(CURL* curl, void* sslctx, void* param)
{
//peterBreak();
CURL_t* ppcCurl = (CURL_t*)param;
nsysnet::NSSLInternalState_t* nssl = nsysnet::GetNSSLContext((uint32)ppcCurl->hNSSL);
for (uint32 i : nssl->serverPKIs)
{
if (iosuCrypto_addCACertificate(sslctx, i) == false)
{
cemu_assert_suspicious();
return CURLE_SSL_CACERT;
}
}
for (auto& customPKI : nssl->serverCustomPKIs)
{
if (iosuCrypto_addCustomCACertificate(sslctx, &customPKI[0], (sint32)customPKI.size()) == false)
{
cemu_assert_suspicious();
return CURLE_SSL_CACERT;
}
}
if (nssl->clientPKI != 0 && iosuCrypto_addClientCertificate(sslctx, nssl->clientPKI) == false)
{
cemu_assert_suspicious();
return CURLE_SSL_CERTPROBLEM;
}
uint32 flags = ppcCurl->nsslVerifyOptions;
if (HAS_FLAG(flags, NSSL_VERIFY_PEER))
{
::SSL_CTX_set_cipher_list((SSL_CTX*)sslctx, "AES256-SHA"); // TLS_RSA_WITH_AES_256_CBC_SHA (in CURL it's called rsa_aes_256_sha)
::SSL_CTX_set_mode((SSL_CTX*)sslctx, SSL_MODE_AUTO_RETRY);
::SSL_CTX_set_verify_depth((SSL_CTX*)sslctx, 2);
::SSL_CTX_set_verify((SSL_CTX*)sslctx, SSL_VERIFY_PEER, ssl_verify_callback);
}
else
{
::SSL_CTX_set_verify((SSL_CTX*)sslctx, SSL_VERIFY_NONE, nullptr);
}
return CURLE_OK;
}
size_t header_callback(char* buffer, size_t size, size_t nitems, void* userdata)
{
//peterBreak();
CURL_t* curl = (CURL_t*)userdata;
curlDebug_headerWrite(curl, buffer, size, nitems);
if (curl->fwrite_header.IsNull())
{
return size * nitems;
}
if (g_callerQueue == nullptr || g_threadQueue == nullptr)
{
StackAllocator<char> tmp((uint32)(size * nitems));
memcpy(tmp.GetPointer(), buffer, size * nitems);
return PPCCoreCallback(curl->fwrite_header.GetMPTR(), tmp.GetMPTR(), (uint32)size, (uint32)nitems, curl->writeheader.GetMPTR());
}
QueueMsg_t msg = {};
msg.order = QueueOrder_HeaderCB;
msg.header_cb.buffer = buffer;
msg.header_cb.size = (uint32)size;
msg.header_cb.nitems = (uint32)nitems;
g_callerQueue->push(msg, curl->curlThread);
msg = g_threadQueue->pop();
if (msg.order != QueueOrder_CBDone)
cemu_assert_suspicious();
#ifdef CEMU_DEBUG_ASSERT
char debug[500];
cemu_assert_debug((size*nitems) < 500);
memcpy(debug, buffer, size*nitems);
debug[size*nitems] = 0;
cemuLog_logDebug(LogType::Force, "header_callback(0x{}, 0x{:x}, 0x{:x}, 0x{:08x}) [{}]", (void*)buffer, size, nitems, curl->writeheader.GetMPTR(), debug);
#endif
return msg.result;
}
size_t write_callback(char* ptr, size_t size, size_t nmemb, void* userdata)
{
CURL_t* curl = (CURL_t*)userdata;
curlDebug_resultWrite(curl, ptr, size, nmemb);
//StackAllocator<char> tmp(size * nmemb);
//memcpy(tmp.GetPointer(), ptr, size * nmemb);
cemuLog_logDebug(LogType::Force, "write_callback(0x{} 0x{:x}, 0x{:x}, 0x{:08x})", (void*)ptr, size, nmemb, curl->out.GetMPTR());
if (g_callerQueue == nullptr || g_threadQueue == nullptr)
{
StackAllocator<char> tmp((uint32)(size * nmemb));
memcpy(tmp.GetPointer(), ptr, size * nmemb);
int r = PPCCoreCallback(curl->fwrite_func.GetMPTR(), tmp.GetMPTR(), (uint32)size, (uint32)nmemb, curl->out.GetMPTR());
return r;
}
QueueMsg_t msg = {};
msg.order = QueueOrder_WriteCB;
msg.write_cb.buffer = ptr;
msg.write_cb.size = (uint32)size;
msg.write_cb.nmemb = (uint32)nmemb;
g_callerQueue->push(msg, curl->curlThread);
msg = g_threadQueue->pop();
if (msg.order != QueueOrder_CBDone)
cemu_assert_suspicious();
return msg.result;
}
int sockopt_callback(void* clientp, curl_socket_t curlfd, curlsocktype purpose)
{
CURL_t* curl = (CURL_t*)clientp;
cemuLog_logDebug(LogType::Force, "sockopt_callback called!");
sint32 r = 0;
return r;
}
size_t read_callback(char* buffer, size_t size, size_t nitems, void* instream)
{
nitems = std::min<uint32>(nitems, 0x4000);
CURL_t* curl = (CURL_t*)instream;
cemuLog_logDebug(LogType::Force, "read_callback(0x{}, 0x{:x}, 0x{:x}, 0x{:08x}) [func: 0x{:x}]", (void*)buffer, size, nitems, curl->in_set.GetMPTR(), curl->fread_func_set.GetMPTR());
if (g_callerQueue == nullptr || g_threadQueue == nullptr)
{
StackAllocator<char> tmp((uint32)(size * nitems));
const sint32 result = PPCCoreCallback(curl->fread_func_set.GetMPTR(), tmp.GetMPTR(), (uint32)size, (uint32)nitems, curl->in_set.GetMPTR());
memcpy(buffer, tmp.GetPointer(), result);
return result;
}
QueueMsg_t msg = {};
msg.order = QueueOrder_ReadCB;
msg.read_cb.buffer = buffer;
msg.read_cb.size = (uint32)size;
msg.read_cb.nitems = (uint32)std::min<uint32>(nitems, 0x4000); // limit this to 16KB which is the limit in nlibcurl.rpl (Super Mario Maker crashes on level upload if the size is too big)
cemuLog_logDebug(LogType::Force, "read_callback(0x{}, 0x{:x}, 0x{:x}, 0x{:08x}) [func: 0x{:x}] PUSH", (void*)buffer, size, nitems, curl->in_set.GetMPTR(), curl->fread_func_set.GetMPTR());
g_callerQueue->push(msg, curl->curlThread);
msg = g_threadQueue->pop();
if (msg.order != QueueOrder_CBDone)
cemu_assert_suspicious();
cemuLog_logDebug(LogType::Force, "read_callback(0x{}, 0x{:x}, 0x{:x}, 0x{:08x}) DONE Result: {}", (void*)buffer, size, nitems, curl->in_set.GetMPTR(), msg.result);
return msg.result;
}
int progress_callback(void* clientp, double dltotal, double dlnow, double ultotal, double ulnow)
{
//peterBreak();
CURL_t* curl = (CURL_t*)clientp;
//int result = PPCCoreCallback(curl->fprogress.GetMPTR(), curl->progress_client.GetMPTR(), dltotal, dlnow, ultotal, ulnow);
if(g_callerQueue == nullptr || g_threadQueue == nullptr)
return PPCCoreCallback(curl->fprogress.GetMPTR(), curl->progress_client.GetMPTR(), dltotal, dlnow, ultotal, ulnow);
QueueMsg_t msg = {};
msg.order = QueueOrder_ProgressCB;
msg.progress_cb.dltotal = dltotal;
msg.progress_cb.dlnow = dlnow;
msg.progress_cb.ultotal = ultotal;
msg.progress_cb.ulnow = ulnow;
g_callerQueue->push(msg, curl->curlThread);
msg = g_threadQueue->pop();
if (msg.order != QueueOrder_CBDone)
cemu_assert_suspicious();
cemuLog_logDebug(LogType::Force, "progress_callback({:.02}, {:.02}, {:.02}, {:.02}) -> {}", dltotal, dlnow, ultotal, ulnow, msg.result);
return msg.result;
}
void export_curl_easy_setopt(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(curl, CURL_t, 0);
ppcDefineParamU32(option, 1);
ppcDefineParamMEMPTR(parameter, void, 2);
ppcDefineParamU64(parameterU64, 2);
CURL* curlObj = curl->curl;
curl->isDirty = true;
CURLcode result = CURLE_OK;
switch (option)
{
case CURLOPT_POST:
{
if(parameter)
{
curl->set.httpreq_1EC = WU_HTTPREQ::HTTPREQ_POST;
curl->opt_no_body_281 = 0;
}
else
curl->set.httpreq_1EC = WU_HTTPREQ::HTTPREQ_GET;
break;
}
case CURLOPT_HTTPGET:
{
if (parameter)
{
curl->set.httpreq_1EC = WU_HTTPREQ::HTTPREQ_GET;
curl->opt_no_body_281 = 0;
curl->upload_283 = 0;
}
break;
}
case CURLOPT_INFILESIZE:
{
curl->set.infilesize_190 = (sint64)(sint32)(uint32)parameter.GetBEValue();
break;
}
case CURLOPT_INFILESIZE_LARGE:
{
curl->set.infilesize_190 = (sint64)(uint64)parameterU64;
break;
}
case CURLOPT_NOSIGNAL:
case CURLOPT_FOLLOWLOCATION:
case CURLOPT_BUFFERSIZE:
case CURLOPT_TIMEOUT:
case CURLOPT_CONNECTTIMEOUT_MS:
case CURLOPT_NOPROGRESS:
case CURLOPT_LOW_SPEED_LIMIT:
case CURLOPT_LOW_SPEED_TIME:
case CURLOPT_CONNECTTIMEOUT:
{
result = ::curl_easy_setopt(curlObj, (CURLoption)option, parameter.GetMPTR());
break;
}
case CURLOPT_URL:
{
curlDebug_logEasySetOptStr(curl.GetPtr(), "CURLOPT_URL", (const char*)parameter.GetPtr());
cemuLog_logDebug(LogType::Force, "curl_easy_setopt({}) [{}]", option, parameter.GetPtr());
result = ::curl_easy_setopt(curlObj, (CURLoption)option, parameter.GetPtr());
break;
}
case CURLOPT_PROXY:
case CURLOPT_USERAGENT:
{
cemuLog_logDebug(LogType::Force, "curl_easy_setopt({}) [{}]", option, parameter.GetPtr());
result = ::curl_easy_setopt(curlObj, (CURLoption)option, parameter.GetPtr());
break;
}
case CURLOPT_POSTFIELDS:
{
curlDebug_logEasySetOptStr(curl.GetPtr(), "CURLOPT_POSTFIELDS", (const char*)parameter.GetPtr());
cemuLog_logDebug(LogType::Force, "curl_easy_setopt({}) [{}]", option, parameter.GetPtr());
result = ::curl_easy_setopt(curlObj, (CURLoption)option, parameter.GetPtr());
break;
}
case CURLOPT_MAX_SEND_SPEED_LARGE:
case CURLOPT_MAX_RECV_SPEED_LARGE:
case CURLOPT_POSTFIELDSIZE_LARGE:
{
result = ::curl_easy_setopt(curlObj, (CURLoption)option, parameterU64);
break;
}
case 211: // verifyOpt
{
uint32 flags = parameter.GetMPTR();
curl->nsslVerifyOptions = flags;
if (HAS_FLAG(flags, NSSL_VERIFY_PEER))
::curl_easy_setopt(curlObj, CURLOPT_SSL_VERIFYPEER, 1);
else
::curl_easy_setopt(curlObj, CURLOPT_SSL_VERIFYPEER, 0);
if (HAS_FLAG(flags, NSSL_VERIFY_HOSTNAME))
::curl_easy_setopt(curlObj, CURLOPT_SSL_VERIFYHOST, 2);
else
::curl_easy_setopt(curlObj, CURLOPT_SSL_VERIFYHOST, 0);
break;
}
case 210: // SSL_CONTEXT -> set context created with NSSLCreateContext before
{
const uint32 nsslIndex = parameter.GetMPTR();
nsysnet::NSSLInternalState_t* nssl = nsysnet::GetNSSLContext(nsslIndex);
if (nssl)
{
curl->hNSSL = nsslIndex;
result = ::curl_easy_setopt(curlObj, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
::curl_easy_setopt(curlObj, CURLOPT_SSL_CTX_DATA, curl.GetPtr());
if (nssl->sslVersion == 2)
::curl_easy_setopt(curlObj, CURLOPT_SSLVERSION, CURL_SSLVERSION_SSLv3);
else // auto = highest = 0 || 2 for v3
::curl_easy_setopt(curlObj, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
}
else
cemu_assert_suspicious();
break;
}
case CURLOPT_SHARE:
{
CURLSH* shObj = nullptr;
if (parameter)
{
auto curlSh = (MEMPTR<CURLSH_t>)parameter;
curlSh->curl = curl;
shObj = curlSh->curlsh;
}
result = ::curl_easy_setopt(curlObj, CURLOPT_SHARE, shObj);
break;
}
case CURLOPT_HEADERFUNCTION:
{
curlDebug_logEasySetOptPtr(curl.GetPtr(), "CURLOPT_HEADERFUNCTION", parameter.GetMPTR());
curl->fwrite_header = parameter;
break;
}
case CURLOPT_HEADERDATA:
{
curlDebug_logEasySetOptPtr(curl.GetPtr(), "CURLOPT_HEADERDATA", parameter.GetMPTR());
curl->writeheader = parameter;
break;
}
case CURLOPT_WRITEFUNCTION:
{
curlDebug_logEasySetOptPtr(curl.GetPtr(), "CURLOPT_WRITEFUNCTION", parameter.GetMPTR());
curl->fwrite_func = parameter;
result = ::curl_easy_setopt(curlObj, CURLOPT_WRITEFUNCTION, write_callback);
::curl_easy_setopt(curlObj, CURLOPT_WRITEDATA, curl.GetPtr());
break;
}
case CURLOPT_WRITEDATA: // aka CURLOPT_FILE
{
curlDebug_logEasySetOptPtr(curl.GetPtr(), "CURLOPT_WRITEDATA", parameter.GetMPTR());
curl->out = parameter;
break;
}
case CURLOPT_HTTPHEADER:
{
curl->set.headers = (WU_curl_slist*)parameter.GetPtr();
result = CURLE_OK;
break;
}
case CURLOPT_SOCKOPTFUNCTION:
{
curl->fsockopt = parameter;
result = ::curl_easy_setopt(curlObj, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
::curl_easy_setopt(curlObj, CURLOPT_SOCKOPTDATA, curl.GetPtr());
break;
}
case CURLOPT_SOCKOPTDATA:
{
curl->sockopt_client = parameter;
break;
}
case CURLOPT_READFUNCTION:
{
curlDebug_logEasySetOptPtr(curl.GetPtr(), "CURLOPT_READFUNCTION", parameter.GetMPTR());
curl->fread_func_set = parameter;
result = ::curl_easy_setopt(curlObj, CURLOPT_READFUNCTION, read_callback);
::curl_easy_setopt(curlObj, CURLOPT_READDATA, curl.GetPtr());
break;
}
case CURLOPT_READDATA:
{
curlDebug_logEasySetOptPtr(curl.GetPtr(), "CURLOPT_READDATA", parameter.GetMPTR());
curl->in_set = parameter;
break;
}
case CURLOPT_PROGRESSFUNCTION:
{
curlDebug_logEasySetOptPtr(curl.GetPtr(), "CURLOPT_PROGRESSFUNCTION", parameter.GetMPTR());
curl->fprogress = parameter;
result = ::curl_easy_setopt(curlObj, CURLOPT_PROGRESSFUNCTION, progress_callback);
::curl_easy_setopt(curlObj, CURLOPT_PROGRESSDATA, curl.GetPtr());
break;
}
case CURLOPT_PROGRESSDATA:
{
curlDebug_logEasySetOptPtr(curl.GetPtr(), "CURLOPT_PROGRESSDATA", parameter.GetMPTR());
curl->progress_client = parameter;
break;
}
default:
cemuLog_logDebug(LogType::Force, "curl_easy_setopt(0x{:08x}, {}, 0x{:08x}) unsupported option", curl.GetMPTR(), option, parameter.GetMPTR());
}
cemuLog_logDebug(LogType::Force, "curl_easy_setopt(0x{:08x}, {}, 0x{:08x}) -> 0x{:x}", curl.GetMPTR(), option, parameter.GetMPTR(), result);
osLib_returnFromFunction(hCPU, result);
}
WU_CURLcode curl_easy_perform(CURL_t* curl)
{
curlDebug_markActiveRequest(curl);
curlDebug_notifySubmitRequest(curl);
if(curl->isDirty)
{
curl->isDirty = false;
_curl_sync_parameters(curl);
}
const uint32 result = SendOrderToWorker(curl, QueueOrder_Perform);
return static_cast<WU_CURLcode>(result);
}
void _updateGuestString(CURL_t* curl, MEMPTR<char>& ppcStr, char* hostStr)
{
// free current string
if (ppcStr.IsNull() == false)
{
PPCCoreCallback(g_nlibcurl.free.GetMPTR(), ppcStr);
ppcStr = nullptr;
}
if (hostStr == nullptr)
return;
sint32 length = (sint32)strlen(hostStr);
ppcStr = PPCCoreCallback(g_nlibcurl.malloc.GetMPTR(), length+1);
memcpy(ppcStr.GetPtr(), hostStr, length + 1);
}
void export_curl_easy_getinfo(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(curl, CURL_t, 0);
ppcDefineParamU32(info, 1);
ppcDefineParamMEMPTR(parameter, void, 2);
CURL* curlObj = curl->curl;
CURLcode result = CURLE_OK;
switch (info)
{
case CURLINFO_SIZE_DOWNLOAD:
case CURLINFO_SPEED_DOWNLOAD:
case CURLINFO_SIZE_UPLOAD:
case CURLINFO_SPEED_UPLOAD:
case CURLINFO_CONTENT_LENGTH_DOWNLOAD:
{
double tempDouble = 0.0;
result = curl_easy_getinfo(curlObj, (CURLINFO)info, &tempDouble);
*(uint64*)parameter.GetPtr() = _swapEndianU64(*(uint64*)&tempDouble);
break;
}
case CURLINFO_RESPONSE_CODE:
case CURLINFO_SSL_VERIFYRESULT:
{
long tempLong = 0;
result = curl_easy_getinfo(curlObj, (CURLINFO)info, &tempLong);
*(uint32*)parameter.GetPtr() = _swapEndianU32((uint32)tempLong);
break;
}
case CURLINFO_CONTENT_TYPE:
{
char* contentType = nullptr;
result = curl_easy_getinfo(curlObj, CURLINFO_REDIRECT_URL, &contentType);
_updateGuestString(curl.GetPtr(), curl->info_contentType, contentType);
*(MEMPTR<char>*)parameter.GetPtr() = curl->info_contentType;
break;
}
case CURLINFO_REDIRECT_URL:
{
char* redirectUrl = nullptr;
result = curl_easy_getinfo(curlObj, CURLINFO_REDIRECT_URL, &redirectUrl);
_updateGuestString(curl.GetPtr(), curl->info_redirectUrl, redirectUrl);
*(MEMPTR<char>*)parameter.GetPtr() = curl->info_redirectUrl;
break;
}
default:
cemu_assert_unimplemented();
result = curl_easy_getinfo(curlObj, (CURLINFO)info, (double*)parameter.GetPtr());
}
cemuLog_logDebug(LogType::Force, "curl_easy_getinfo(0x{:08x}, 0x{:x}, 0x{:08x}) -> 0x{:x}", curl.GetMPTR(), info, parameter.GetMPTR(), result);
osLib_returnFromFunction(hCPU, result);
}
void export_curl_easy_strerror(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(code, 0);
MEMPTR<char> result;
const char* error = curl_easy_strerror((CURLcode)code);
if (error)
{
cemuLog_logDebug(LogType::Force, "curl_easy_strerror: {}", error);
int len = (int)strlen(error) + 1;
result = coreinit_allocFromSysArea(len, 4);
memcpy(result.GetPtr(), error, len);
}
osLib_returnFromFunction(hCPU, result.GetMPTR());
}
WU_curl_slist* curl_slist_append(WU_curl_slist* list, const char* data)
{
MEMPTR<char> dupdata{ PPCCoreCallback(g_nlibcurl.strdup.GetMPTR(), data) };
if (!dupdata)
{
cemuLog_logDebug(LogType::Force, "curl_slist_append(): Failed to duplicate string");
return nullptr;
}
MEMPTR<WU_curl_slist> result{ PPCCoreCallback(g_nlibcurl.malloc.GetMPTR(), ppcsizeof<WU_curl_slist>()) };
if (result)
{
result->data = dupdata;
result->next = nullptr;
// update last obj of list
if (list)
{
MEMPTR<WU_curl_slist> tmp = list;
while (tmp->next)
{
tmp = tmp->next;
}
tmp->next = result;
}
}
else
{
cemuLog_logDebug(LogType::Force, "curl_slist_append(): Failed to allocate memory");
PPCCoreCallback(g_nlibcurl.free.GetMPTR(), dupdata.GetMPTR());
}
if(list)
return list;
return result;
}
void curl_slist_free_all(WU_curl_slist* list)
{
cemuLog_logDebug(LogType::Force, "export_curl_slist_free_all: TODO");
}
CURLcode curl_global_init_mem(uint32 flags, MEMPTR<curl_malloc_callback> malloc_callback, MEMPTR<curl_free_callback> free_callback, MEMPTR<curl_realloc_callback> realloc_callback, MEMPTR<curl_strdup_callback> strdup_callback, MEMPTR<curl_calloc_callback> calloc_callback)
{
if(!malloc_callback || !free_callback || !realloc_callback || !strdup_callback || !calloc_callback)
return CURLE_FAILED_INIT;
CURLcode result = CURLE_OK;
if (g_nlibcurl.initialized == 0)
{
result = curl_global_init(flags);
if (result == CURLE_OK)
{
g_nlibcurl.malloc = malloc_callback;
g_nlibcurl.free = free_callback;
g_nlibcurl.realloc = realloc_callback;
g_nlibcurl.strdup = strdup_callback;
g_nlibcurl.calloc = calloc_callback;
}
}
return result;
}
void load()
{
cafeExportRegister("nlibcurl", curl_global_init_mem, LogType::nlibcurl);
cafeExportRegister("nlibcurl", curl_global_init, LogType::nlibcurl);
cafeExportRegister("nlibcurl", curl_slist_append, LogType::nlibcurl);
cafeExportRegister("nlibcurl", curl_slist_free_all, LogType::nlibcurl);
osLib_addFunction("nlibcurl", "curl_easy_strerror", export_curl_easy_strerror);
osLib_addFunction("nlibcurl", "curl_share_init", export_curl_share_init);
osLib_addFunction("nlibcurl", "curl_share_setopt", export_curl_share_setopt);
osLib_addFunction("nlibcurl", "curl_share_cleanup", export_curl_share_cleanup);
cafeExportRegister("nlibcurl", mw_curl_easy_init, LogType::nlibcurl);
osLib_addFunction("nlibcurl", "curl_multi_init", export_curl_multi_init);
osLib_addFunction("nlibcurl", "curl_multi_add_handle", export_curl_multi_add_handle);
osLib_addFunction("nlibcurl", "curl_multi_perform", export_curl_multi_perform);
osLib_addFunction("nlibcurl", "curl_multi_info_read", export_curl_multi_info_read);
osLib_addFunction("nlibcurl", "curl_multi_remove_handle", export_curl_multi_remove_handle);
osLib_addFunction("nlibcurl", "curl_multi_setopt", export_curl_multi_setopt);
osLib_addFunction("nlibcurl", "curl_multi_fdset", export_curl_multi_fdset);
osLib_addFunction("nlibcurl", "curl_multi_cleanup", export_curl_multi_cleanup);
osLib_addFunction("nlibcurl", "curl_multi_timeout", export_curl_multi_timeout);
cafeExportRegister("nlibcurl", curl_easy_init, LogType::nlibcurl);
osLib_addFunction("nlibcurl", "curl_easy_reset", export_curl_easy_reset);
osLib_addFunction("nlibcurl", "curl_easy_setopt", export_curl_easy_setopt);
osLib_addFunction("nlibcurl", "curl_easy_getinfo", export_curl_easy_getinfo);
cafeExportRegister("nlibcurl", curl_easy_perform, LogType::nlibcurl);
osLib_addFunction("nlibcurl", "curl_easy_cleanup", export_curl_easy_cleanup);
osLib_addFunction("nlibcurl", "curl_easy_pause", export_curl_easy_pause);
}
}
| 46,403
|
C++
|
.cpp
| 1,321
| 32.480696
| 271
| 0.723295
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,127
|
nn_cmpt.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_cmpt/nn_cmpt.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "nn_cmpt.h"
namespace nn::cmpt
{
uint32 CMPTAcctGetPcConf(uint32be* pcConf)
{
cemuLog_logDebug(LogType::Force, "CMPTAcctGetPcConf() - todo");
pcConf[0] = 0;
pcConf[1] = 0;
pcConf[2] = 0;
return 0;
}
uint32 CMPTGetDataSize(uint32be* sizeOut)
{
*sizeOut = 0xC0000;
return 0;
}
void Initialize()
{
cafeExportRegister("nn_cmpt", CMPTAcctGetPcConf, LogType::Placeholder);
cafeExportRegister("nn_cmpt", CMPTGetDataSize, LogType::Placeholder);
}
}
| 517
|
C++
|
.cpp
| 23
| 20.173913
| 73
| 0.733198
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,128
|
mic.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/mic/mic.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "input/InputManager.h"
#include "audio/IAudioInputAPI.h"
#include "config/CemuConfig.h"
enum class MIC_RESULT
{
SUCCESS = 0,
BAD_PARAM = -2,
ALREADY_OPEN = -5,
NOT_OPEN = -6,
NOT_INITIALIZED = -7,
NOT_CONNECTED = -8
};
#define MIC_SAMPLERATE 32000
const int MIC_SAMPLES_PER_3MS_32KHZ = (96); // 32000*3/1000
enum class MIC_STATUS_FLAGS : uint32
{
FORMAT_PCM16 = (1 << 0),
IS_OPEN = (1 << 1),
IS_CONNECTED = (1 << 2)
};
DEFINE_ENUM_FLAG_OPERATORS(MIC_STATUS_FLAGS);
#define MIC_HANDLE_DRC0 0
#define MIC_HANDLE_DRC1 1
enum class MIC_STATEID
{
SAMPLERATE = 0,
GAIN_DB = 1,
GAIN_MIN = 2,
GAIN_MAX = 3,
GAIN_STEP = 4,
MUTE = 5,
ECHO_CANCELLATION = 7,
AUTO_SELECTION = 8
};
struct
{
struct
{
bool isInited;
bool isOpen;
// ringbuffer information
void* ringbufferSampleData;
uint32 ringbufferSize;
uint32 readIndex;
uint32 writeIndex;
// state
uint32 echoCancellation;
uint32 autoSelection;
uint32 gainDB;
}drc[2];
}MICStatus = {0};
typedef struct
{
uint32 size;
MPTR samples;
}micRingbuffer_t;
struct micStatus_t
{
betype<MIC_STATUS_FLAGS> flags;
uint32be numSamplesAvailable;
uint32be readIndex;
};
static_assert(sizeof(micStatus_t) == 0xC);
bool mic_isConnected(uint32 drcIndex)
{
if( drcIndex != 0 )
return false;
return InputManager::instance().get_vpad_controller(drcIndex) != nullptr;
}
sint32 mic_availableSamples(uint32 drcIndex)
{
return (MICStatus.drc[drcIndex].ringbufferSize+MICStatus.drc[drcIndex].writeIndex-MICStatus.drc[drcIndex].readIndex) % MICStatus.drc[drcIndex].ringbufferSize;
}
bool mic_isActive(uint32 drcIndex)
{
return MICStatus.drc[drcIndex].isOpen;
}
void mic_feedSamples(uint32 drcIndex, sint16* sampleData, sint32 numSamples)
{
uint16* sampleDataU16 = (uint16*)sampleData;
sint32 ringBufferSize = MICStatus.drc[0].ringbufferSize;
sint32 writeIndex = MICStatus.drc[0].writeIndex;
uint16* ringBufferBase = (uint16*)MICStatus.drc[0].ringbufferSampleData;
do
{
ringBufferBase[writeIndex] = _swapEndianU16(*sampleDataU16);
sampleDataU16++;
writeIndex++;
writeIndex %= ringBufferSize;
}while( (--numSamples) > 0 );
MICStatus.drc[0].writeIndex = writeIndex;
}
void micExport_MICInit(PPCInterpreter_t* hCPU)
{
debug_printf("MICInit(%d,%d,0x%08x,0x%08x)\n", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6]);
uint32 drcIndex = hCPU->gpr[3];
if( drcIndex > 1 || (drcIndex == 0 && mic_isConnected(drcIndex) == false) )
{
memory_writeU32(hCPU->gpr[6], (uint32)MIC_RESULT::NOT_CONNECTED);
osLib_returnFromFunction(hCPU, -1);
return;
}
if( drcIndex != 0 )
{
// DRC1 microphone is not supported (only DRC0)
memory_writeU32(hCPU->gpr[6], (uint32)MIC_RESULT::NOT_CONNECTED);
osLib_returnFromFunction(hCPU, -1);
return;
}
if( MICStatus.drc[drcIndex].isInited )
{
memory_writeU32(hCPU->gpr[6], (uint32)MIC_RESULT::ALREADY_OPEN);
osLib_returnFromFunction(hCPU, -1);
return;
}
micRingbuffer_t* micRingbuffer = (micRingbuffer_t*)memory_getPointerFromVirtualOffset(hCPU->gpr[5]);
MICStatus.drc[drcIndex].ringbufferSampleData = memory_getPointerFromVirtualOffset(_swapEndianU32(micRingbuffer->samples));
MICStatus.drc[drcIndex].ringbufferSize = _swapEndianU32(micRingbuffer->size);
MICStatus.drc[drcIndex].readIndex = 0;
MICStatus.drc[drcIndex].writeIndex = 0;
MICStatus.drc[drcIndex].isInited = true;
// init default states
MICStatus.drc[drcIndex].echoCancellation = 1; // guessed
MICStatus.drc[drcIndex].autoSelection = 1; // guessed
// return status
memory_writeU32(hCPU->gpr[6], 0); // no error
osLib_returnFromFunction(hCPU, (drcIndex==0)?MIC_HANDLE_DRC0:MIC_HANDLE_DRC1); // success
auto& config = GetConfig();
const auto audio_api = IAudioInputAPI::Cubeb; // change this if more input apis get implemented
std::unique_lock lock(g_audioInputMutex);
if (!g_inputAudio)
{
IAudioInputAPI::DeviceDescriptionPtr device_description;
if (IAudioInputAPI::IsAudioInputAPIAvailable(audio_api))
{
auto devices = IAudioInputAPI::GetDevices(audio_api);
const auto it = std::find_if(devices.begin(), devices.end(), [&config](const auto& d) {return d->GetIdentifier() == config.input_device; });
if (it != devices.end())
device_description = *it;
}
if (device_description)
{
try
{
g_inputAudio = IAudioInputAPI::CreateDevice(audio_api, device_description, MIC_SAMPLERATE, 1, MIC_SAMPLES_PER_3MS_32KHZ, 16);
g_inputAudio->SetVolume(config.input_volume);
}
catch (std::runtime_error& ex)
{
cemuLog_log(LogType::Force, "can't initialize audio input: {}", ex.what());
exit(0);
}
}
}
}
void micExport_MICOpen(PPCInterpreter_t* hCPU)
{
debug_printf("MICOpen(%d)\n", hCPU->gpr[3]);
uint32 micHandle = hCPU->gpr[3];
if( micHandle != MIC_HANDLE_DRC0 && micHandle != MIC_HANDLE_DRC1 )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::BAD_PARAM);
return;
}
uint32 drcIndex = (micHandle==MIC_HANDLE_DRC0)?0:1;
if( MICStatus.drc[drcIndex].isInited == false )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::NOT_INITIALIZED);
return;
}
// check if already open
if( MICStatus.drc[drcIndex].isOpen )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::ALREADY_OPEN);
return;
}
// check if DRC is connected
bool hasDRCConnected = InputManager::instance().get_vpad_controller(drcIndex) != nullptr;
if( hasDRCConnected == false )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::NOT_CONNECTED);
return;
}
// success
MICStatus.drc[drcIndex].isOpen = true;
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::SUCCESS);
std::shared_lock lock(g_audioInputMutex);
if(g_inputAudio)
g_inputAudio->Play();
}
void micExport_MICClose(PPCInterpreter_t* hCPU)
{
// debug_printf("MICClose(%d)\n", hCPU->gpr[3]);
uint32 micHandle = hCPU->gpr[3];
if( micHandle != MIC_HANDLE_DRC0 && micHandle != MIC_HANDLE_DRC1 )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::BAD_PARAM);
return;
}
uint32 drcIndex = (micHandle==MIC_HANDLE_DRC0)?0:1;
if( MICStatus.drc[drcIndex].isInited == false )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::NOT_INITIALIZED);
return;
}
// check if already closed
if( MICStatus.drc[drcIndex].isOpen == false )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::ALREADY_OPEN);
return;
}
// success
MICStatus.drc[drcIndex].isOpen = false;
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::SUCCESS);
std::shared_lock lock(g_audioInputMutex);
if (g_inputAudio)
g_inputAudio->Stop();
}
void micExport_MICGetStatus(PPCInterpreter_t* hCPU)
{
debug_printf("MICGetStatus(%d,0x%08x)\n", hCPU->gpr[3], hCPU->gpr[4]);
uint32 micHandle = hCPU->gpr[3];
if( micHandle != MIC_HANDLE_DRC0 && micHandle != MIC_HANDLE_DRC1 )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::BAD_PARAM);
return;
}
uint32 drcIndex = (micHandle==MIC_HANDLE_DRC0)?0:1;
if( MICStatus.drc[drcIndex].isInited == false )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::NOT_INITIALIZED);
return;
}
micStatus_t* micStatus = (micStatus_t*)memory_getPointerFromVirtualOffset(hCPU->gpr[4]);
MIC_STATUS_FLAGS micFlags = MIC_STATUS_FLAGS::FORMAT_PCM16;
if( mic_isConnected(drcIndex) )
micFlags |= MIC_STATUS_FLAGS::IS_CONNECTED;
if( MICStatus.drc[drcIndex].isOpen )
micFlags |= MIC_STATUS_FLAGS::IS_OPEN;
micStatus->flags = micFlags;
micStatus->numSamplesAvailable = mic_availableSamples(drcIndex);
micStatus->readIndex = MICStatus.drc[drcIndex].readIndex;
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::SUCCESS);
}
void micExport_MICGetState(PPCInterpreter_t* hCPU)
{
// debug_printf("MICGetState(%d,%d,0x%08x)\n", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
// parameters:
// r3 uint32 micHandle
// r4 uint32 stateId
// r5 uint32* value
uint32 micHandle = hCPU->gpr[3];
if( micHandle != MIC_HANDLE_DRC0 && micHandle != MIC_HANDLE_DRC1 )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::BAD_PARAM);
return;
}
uint32 drcIndex = (micHandle==MIC_HANDLE_DRC0)?0:1;
if( MICStatus.drc[drcIndex].isInited == false )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::NOT_INITIALIZED);
return;
}
// get state
MIC_STATEID stateId = (MIC_STATEID)hCPU->gpr[4];
if (stateId == MIC_STATEID::SAMPLERATE)
{
memory_writeU32(hCPU->gpr[5], MIC_SAMPLERATE);
}
else if (stateId == MIC_STATEID::AUTO_SELECTION)
{
memory_writeU32(hCPU->gpr[5], MICStatus.drc[drcIndex].autoSelection);
}
else if (stateId == MIC_STATEID::GAIN_MIN)
{
// value guessed
memory_writeU32(hCPU->gpr[5], 0x0000); // S7.8
}
else if (stateId == MIC_STATEID::GAIN_MAX)
{
// value guessed
memory_writeU32(hCPU->gpr[5], 0x0200); // S7.8
}
else if (stateId == MIC_STATEID::GAIN_STEP)
{
// value guessed
memory_writeU32(hCPU->gpr[5], 0x0001); // S7.8
}
else if (stateId == MIC_STATEID::ECHO_CANCELLATION)
{
memory_writeU32(hCPU->gpr[5], MICStatus.drc[drcIndex].echoCancellation);
}
else if (stateId == MIC_STATEID::GAIN_DB)
{
// value guessed
memory_writeU32(hCPU->gpr[5], MICStatus.drc[drcIndex].gainDB); // S7.8
}
else
cemu_assert_unimplemented();
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::SUCCESS);
return;
}
void micExport_MICSetState(PPCInterpreter_t* hCPU)
{
uint32 micHandle = hCPU->gpr[3];
if( micHandle != MIC_HANDLE_DRC0 && micHandle != MIC_HANDLE_DRC1 )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::BAD_PARAM);
return;
}
uint32 drcIndex = (micHandle==MIC_HANDLE_DRC0)?0:1;
if( MICStatus.drc[drcIndex].isInited == false )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::NOT_INITIALIZED);
return;
}
// set state
MIC_STATEID stateId = (MIC_STATEID)hCPU->gpr[4];
uint32 newValue = hCPU->gpr[5];
if( stateId == MIC_STATEID::ECHO_CANCELLATION )
{
MICStatus.drc[drcIndex].echoCancellation = (newValue!=0)?1:0;
}
else if( stateId == MIC_STATEID::AUTO_SELECTION )
{
MICStatus.drc[drcIndex].autoSelection = (newValue!=0)?1:0;
}
else if( stateId == MIC_STATEID::GAIN_DB )
{
MICStatus.drc[drcIndex].gainDB = newValue;
}
else
assert_dbg();
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::SUCCESS);
return;
}
void micExport_MICSetDataConsumed(PPCInterpreter_t* hCPU)
{
// debug_printf("MICSetDataConsumed(%d,%d)\n", hCPU->gpr[3], hCPU->gpr[4]);
// parameters:
// r3 uint32 micHandle
// r4 uint32 numConsumedSamples
uint32 micHandle = hCPU->gpr[3];
if( micHandle != MIC_HANDLE_DRC0 && micHandle != MIC_HANDLE_DRC1 )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::BAD_PARAM);
return;
}
uint32 drcIndex = (micHandle==MIC_HANDLE_DRC0)?0:1;
if( MICStatus.drc[drcIndex].isInited == false )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::NOT_INITIALIZED);
return;
}
if( MICStatus.drc[drcIndex].isOpen == false )
{
osLib_returnFromFunction(hCPU, (uint32)MIC_RESULT::NOT_OPEN);
return;
}
sint32 numConsumedSamples = (sint32)hCPU->gpr[4];
//debug_printf("MIC consume samples 0x%04x\n", numConsumedSamples);
if( mic_availableSamples(drcIndex) < numConsumedSamples )
{
MICStatus.drc[drcIndex].readIndex = MICStatus.drc[drcIndex].writeIndex;
osLib_returnFromFunction(hCPU, -81);
}
else
{
MICStatus.drc[drcIndex].readIndex += numConsumedSamples;
MICStatus.drc[drcIndex].readIndex %= MICStatus.drc[drcIndex].ringbufferSize;
osLib_returnFromFunction(hCPU, 0);
}
return;
}
void mic_updateDevicePlayState(bool isPlaying)
{
if (g_inputAudio)
{
if (isPlaying)
g_inputAudio->Play();
else
g_inputAudio->Stop();
}
}
void mic_updateOnAXFrame()
{
sint32 drcIndex = 0;
if( mic_isActive(0) == false )
{
drcIndex = 1;
if (mic_isActive(1) == false)
{
std::shared_lock lock(g_audioInputMutex);
mic_updateDevicePlayState(false);
return;
}
}
std::shared_lock lock(g_audioInputMutex);
mic_updateDevicePlayState(true);
if (g_inputAudio)
{
sint16 micSampleData[MIC_SAMPLES_PER_3MS_32KHZ];
g_inputAudio->ConsumeBlock(micSampleData);
mic_feedSamples(0, micSampleData, MIC_SAMPLES_PER_3MS_32KHZ);
}
else
{
const sint32 micSampleCount = 32000 / 32;
sint16 micSampleData[micSampleCount];
auto controller = InputManager::instance().get_vpad_controller(drcIndex);
if( controller && controller->is_mic_active() )
{
for(sint32 i=0; i<micSampleCount; i++)
{
micSampleData[i] = (sint16)(sin((float)GetTickCount()*0.1f+sin((float)GetTickCount()*0.0001f)*100.0f)*30000.0f);
}
}
else
{
memset(micSampleData, 0x00, sizeof(micSampleData));
}
mic_feedSamples(0, micSampleData, micSampleCount);
}
}
namespace mic
{
void Initialize()
{
osLib_addFunction("mic", "MICInit", micExport_MICInit);
osLib_addFunction("mic", "MICOpen", micExport_MICOpen);
osLib_addFunction("mic", "MICClose", micExport_MICClose);
osLib_addFunction("mic", "MICGetStatus", micExport_MICGetStatus);
osLib_addFunction("mic", "MICGetState", micExport_MICGetState);
osLib_addFunction("mic", "MICSetState", micExport_MICSetState);
osLib_addFunction("mic", "MICSetDataConsumed", micExport_MICSetDataConsumed);
}
};
| 13,050
|
C++
|
.cpp
| 438
| 27.474886
| 159
| 0.73132
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,129
|
nn_fp.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_fp/nn_fp.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/IOSU/legacy/iosu_act.h"
#include "Cafe/IOSU/legacy/iosu_fpd.h"
#include "Cafe/IOSU/legacy/iosu_ioctl.h" // deprecated
#include "Cafe/IOSU/iosu_ipc_common.h"
#include "Cafe/OS/libs/coreinit/coreinit_IOS.h"
#include "Cafe/OS/libs/coreinit/coreinit_IPC.h"
#include "Cafe/OS/libs/nn_common.h"
#include "util/ChunkedHeap/ChunkedHeap.h"
#include "Common/CafeString.h"
namespace nn
{
namespace fp
{
static const auto FPResult_OkZero = 0;
static const auto FPResult_Ok = BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_FP, 0);
static const auto FPResult_InvalidIPCParam = BUILD_NN_RESULT(NN_RESULT_LEVEL_LVL6, NN_RESULT_MODULE_NN_FP, 0x680);
static const auto FPResult_RequestFailed = BUILD_NN_RESULT(NN_RESULT_LEVEL_FATAL, NN_RESULT_MODULE_NN_FP, 0); // figure out proper error code
struct
{
uint32 initCounter;
bool isAdminMode;
bool isLoggedIn;
IOSDevHandle fpdHandle;
SysAllocator<coreinit::OSMutex> fpMutex;
SysAllocator<uint8, 0x12000> g_fpdAllocatorSpace;
VHeap* fpBufferHeap{nullptr};
// PPC buffers for async notification query
SysAllocator<uint32be> notificationCount;
SysAllocator<iosu::fpd::FPDNotification, 256> notificationBuffer;
bool getNotificationCalled{false};
// notification handler
MEMPTR<void> notificationHandler{nullptr};
MEMPTR<void> notificationHandlerParam{nullptr};
}g_fp = { };
class
{
public:
void Init()
{
std::unique_lock _l(m_mtx);
g_fp.fpBufferHeap = new VHeap(g_fp.g_fpdAllocatorSpace.GetPtr(), g_fp.g_fpdAllocatorSpace.GetByteSize());
}
void Destroy()
{
std::unique_lock _l(m_mtx);
delete g_fp.fpBufferHeap;
}
void* Allocate(uint32 size, uint32 alignment)
{
std::unique_lock _l(m_mtx);
void* p = g_fp.fpBufferHeap->alloc(size, 32);
if (!p)
cemuLog_log(LogType::Force, "nn_fp: Internal heap is full");
return p;
}
void Free(void* ptr)
{
std::unique_lock _l(m_mtx);
g_fp.fpBufferHeap->free(ptr);
}
private:
std::mutex m_mtx;
}FPIpcBufferAllocator;
class FPIpcContext {
static inline constexpr uint32 MAX_VEC_COUNT = 8;
public:
// use FP heap for this class
static void* operator new(size_t size)
{
return FPIpcBufferAllocator.Allocate(size, (uint32)alignof(FPIpcContext));
}
static void operator delete(void* ptr)
{
FPIpcBufferAllocator.Free(ptr);
}
FPIpcContext(iosu::fpd::FPD_REQUEST_ID requestId) : m_requestId(requestId)
{
}
~FPIpcContext()
{
if(m_dataBuffer)
FPIpcBufferAllocator.Free(m_dataBuffer);
}
void AddInput(void* ptr, uint32 size)
{
size_t vecIndex = GetVecInIndex(m_numVecIn);
m_vec[vecIndex].baseVirt = ptr;
m_vec[vecIndex].size = size;
m_numVecIn = m_numVecIn + 1;
}
void AddOutput(void* ptr, uint32 size)
{
cemu_assert_debug(m_numVecIn == 0); // all outputs need to be added before any inputs
size_t vecIndex = GetVecOutIndex(m_numVecOut);
m_vec[vecIndex].baseVirt = ptr;
m_vec[vecIndex].size = size;
m_numVecOut = m_numVecOut + 1;
}
uint32 Submit(std::unique_ptr<FPIpcContext> owner)
{
InitSubmissionBuffer();
// note: While generally, Ioctlv() usage has the order as input (app->IOSU) followed by output (IOSU->app), FP uses it the other way around
nnResult r = coreinit::IOS_Ioctlv(g_fp.fpdHandle, (uint32)m_requestId.value(), m_numVecOut, m_numVecIn, m_vec);
CopyBackOutputs();
owner.reset();
return r;
}
nnResult SubmitAsync(std::unique_ptr<FPIpcContext> owner, MEMPTR<void> callbackFunc, MEMPTR<void> callbackParam)
{
InitSubmissionBuffer();
this->m_callbackFunc = callbackFunc;
this->m_callbackParam = callbackParam;
nnResult r = coreinit::IOS_IoctlvAsync(g_fp.fpdHandle, (uint32)m_requestId.value(), m_numVecOut, m_numVecIn, m_vec, MEMPTR<void>(PPCInterpreter_makeCallableExportDepr(AsyncHandler)), MEMPTR<void>(this));
owner.release();
return r;
}
private:
size_t GetVecInIndex(uint8 inIndex)
{
return m_numVecOut + inIndex;
}
size_t GetVecOutIndex(uint8 outIndex)
{
return outIndex;
}
void InitSubmissionBuffer()
{
// allocate a chunk of memory to hold the input/output vectors and their data
uint32 vecOffset[MAX_VEC_COUNT];
uint32 totalBufferSize = 0;
for(uint8 i=0; i<m_numVecIn + m_numVecOut; i++)
{
vecOffset[i] = totalBufferSize;
totalBufferSize += m_vec[i].size;
totalBufferSize = (totalBufferSize+31)&~31;
}
if(totalBufferSize > 0)
{
m_dataBuffer = FPIpcBufferAllocator.Allocate(totalBufferSize, 32);
cemu_assert_debug(m_dataBuffer);
}
// update Ioctl vector addresses
for(uint8 i=0; i<m_numVecIn + m_numVecOut; i++)
{
void* bufferAddr = (uint8be*)m_dataBuffer.GetPtr() + vecOffset[i];
m_vecOriginalAddress[i] = m_vec[i].baseVirt;
m_vec[i].baseVirt = bufferAddr;
}
// copy input data to buffer
for(uint8 i=0; i<m_numVecIn; i++)
{
uint8 vecIndex = GetVecInIndex(i);
memcpy(MEMPTR<void>(m_vec[vecIndex].baseVirt).GetPtr(), MEMPTR<void>(m_vecOriginalAddress[vecIndex]).GetPtr(), m_vec[vecIndex].size);
}
}
static void AsyncHandler(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(result, 0);
ppcDefineParamPtr(ipcCtx, FPIpcContext, 1);
ipcCtx->m_asyncResult = result; // store result in variable since FP callbacks pass a pointer to nnResult and not the value directly
ipcCtx->CopyBackOutputs();
PPCCoreCallback(ipcCtx->m_callbackFunc, &ipcCtx->m_asyncResult, ipcCtx->m_callbackParam);
delete ipcCtx;
osLib_returnFromFunction(hCPU, 0);
}
void CopyBackOutputs()
{
if(m_numVecOut > 0)
{
// copy output from temporary output buffers to the original addresses
for(uint8 i=0; i<m_numVecOut; i++)
{
uint32 vecOffset = (uint32)m_vec[GetVecOutIndex(i)].baseVirt.GetMPTR() - (uint32)m_vec[0].baseVirt.GetMPTR();
memcpy(m_vecOriginalAddress[GetVecOutIndex(i)].GetPtr(), (uint8be*)m_dataBuffer.GetPtr() + vecOffset, m_vec[GetVecOutIndex(i)].size);
}
}
}
betype<iosu::fpd::FPD_REQUEST_ID> m_requestId;
uint8be m_numVecIn{0};
uint8be m_numVecOut{0};
IPCIoctlVector m_vec[MAX_VEC_COUNT];
MEMPTR<void> m_vecOriginalAddress[MAX_VEC_COUNT]{};
MEMPTR<void> m_dataBuffer{nullptr};
MEMPTR<void> m_callbackFunc{nullptr};
MEMPTR<void> m_callbackParam{nullptr};
betype<nnResult> m_asyncResult;
};
struct FPGlobalLock
{
FPGlobalLock()
{
coreinit::OSLockMutex(&g_fp.fpMutex);
}
~FPGlobalLock()
{
coreinit::OSUnlockMutex(&g_fp.fpMutex);
}
};
#define FP_API_BASE() if (g_fp.initCounter == 0) return 0xC0C00580; FPGlobalLock _fpLock;
#define FP_API_BASE_ZeroOnError() if (g_fp.initCounter == 0) return 0; FPGlobalLock _fpLock;
nnResult Initialize()
{
FPGlobalLock _fpLock;
if (g_fp.initCounter == 0)
{
g_fp.fpdHandle = coreinit::IOS_Open("/dev/fpd", 0);
}
g_fp.initCounter++;
return FPResult_OkZero;
}
uint32 IsInitialized()
{
FPGlobalLock _fpLock;
return g_fp.initCounter > 0 ? 1 : 0;
}
nnResult InitializeAdmin(PPCInterpreter_t* hCPU)
{
FPGlobalLock _fpLock;
g_fp.isAdminMode = true;
return Initialize();
}
uint32 IsInitializedAdmin()
{
FPGlobalLock _fpLock;
return g_fp.initCounter > 0 ? 1 : 0;
}
nnResult Finalize()
{
FPGlobalLock _fpLock;
if (g_fp.initCounter == 1)
{
g_fp.initCounter = 0;
g_fp.isAdminMode = false;
g_fp.isLoggedIn = false;
coreinit::IOS_Close(g_fp.fpdHandle);
g_fp.getNotificationCalled = false;
}
else if (g_fp.initCounter > 0)
g_fp.initCounter--;
return FPResult_OkZero;
}
nnResult FinalizeAdmin()
{
return Finalize();
}
void GetNextNotificationAsync();
nnResult SetNotificationHandler(uint32 notificationMask, void* funcPtr, void* userParam)
{
FP_API_BASE();
g_fp.notificationHandler = funcPtr;
g_fp.notificationHandlerParam = userParam;
StackAllocator<uint32be> notificationMaskBuf; notificationMaskBuf = notificationMask;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::SetNotificationMask);
ipcCtx->AddInput(¬ificationMaskBuf, sizeof(uint32be));
nnResult r = ipcCtx->Submit(std::move(ipcCtx));
if (NN_RESULT_IS_SUCCESS(r))
{
// async query for notifications
GetNextNotificationAsync();
}
return r;
}
void GetNextNotificationAsyncHandler(PPCInterpreter_t* hCPU)
{
coreinit::OSLockMutex(&g_fp.fpMutex);
cemu_assert_debug(g_fp.getNotificationCalled);
g_fp.getNotificationCalled = false;
auto bufPtr = g_fp.notificationBuffer.GetPtr();
uint32 count = g_fp.notificationCount->value();
if (count == 0)
{
GetNextNotificationAsync();
coreinit::OSUnlockMutex(&g_fp.fpMutex);
osLib_returnFromFunction(hCPU, 0);
return;
}
// copy notifications to temporary buffer using std::copy
iosu::fpd::FPDNotification tempBuffer[256];
std::copy(g_fp.notificationBuffer.GetPtr(), g_fp.notificationBuffer.GetPtr() + count, tempBuffer);
// call handler for each notification, but do it outside of the lock
void* notificationHandler = g_fp.notificationHandler;
void* notificationHandlerParam = g_fp.notificationHandlerParam;
coreinit::OSUnlockMutex(&g_fp.fpMutex);
iosu::fpd::FPDNotification* notificationBuffer = g_fp.notificationBuffer.GetPtr();
for (uint32 i = 0; i < count; i++)
PPCCoreCallback(notificationHandler, (uint32)notificationBuffer[i].type, notificationBuffer[i].pid, notificationHandlerParam);
coreinit::OSLockMutex(&g_fp.fpMutex);
// query more notifications
GetNextNotificationAsync();
coreinit::OSUnlockMutex(&g_fp.fpMutex);
osLib_returnFromFunction(hCPU, 0);
}
void GetNextNotificationAsync()
{
if (g_fp.getNotificationCalled)
return;
g_fp.getNotificationCalled = true;
g_fp.notificationCount = 0;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetNotificationAsync);
ipcCtx->AddOutput(g_fp.notificationBuffer.GetPtr(), g_fp.notificationBuffer.GetByteSize());
ipcCtx->AddOutput(g_fp.notificationCount.GetPtr(), sizeof(uint32be));
cemu_assert_debug(g_fp.notificationBuffer.GetByteSize() == 0x800);
nnResult r = ipcCtx->SubmitAsync(std::move(ipcCtx), MEMPTR<void>(PPCInterpreter_makeCallableExportDepr(GetNextNotificationAsyncHandler)), nullptr);
}
nnResult LoginAsync(void* funcPtr, void* userParam)
{
FP_API_BASE();
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::LoginAsync);
return ipcCtx->SubmitAsync(std::move(ipcCtx), funcPtr, userParam);
}
uint32 HasLoggedIn()
{
FP_API_BASE_ZeroOnError();
// Sonic All Star Racing uses this
// and Monster Hunter 3 Ultimate needs this to return false at least once to initiate login and not get stuck
// this returns false until LoginAsync was called and has completed (?) even if the user is already logged in
StackAllocator<uint32be> resultBuf;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::HasLoggedIn);
ipcCtx->AddOutput(&resultBuf, sizeof(uint32be));
ipcCtx->Submit(std::move(ipcCtx));
return resultBuf != 0 ? 1 : 0;
}
uint32 IsOnline()
{
FP_API_BASE_ZeroOnError();
StackAllocator<uint32be> resultBuf;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::IsOnline);
ipcCtx->AddOutput(&resultBuf, sizeof(uint32be));
ipcCtx->Submit(std::move(ipcCtx));
return resultBuf != 0 ? 1 : 0;
}
nnResult GetFriendList(uint32be* pidList, uint32be* returnedCount, uint32 startIndex, uint32 maxCount)
{
FP_API_BASE();
StackAllocator<uint32be> startIndexBuf; startIndexBuf = startIndex;
StackAllocator<uint32be> maxCountBuf; maxCountBuf = maxCount;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetFriendList);
ipcCtx->AddOutput(pidList, sizeof(uint32be) * maxCount);
ipcCtx->AddOutput(returnedCount, sizeof(uint32be));
ipcCtx->AddInput(&startIndexBuf, sizeof(uint32be));
ipcCtx->AddInput(&maxCountBuf, sizeof(uint32be));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetFriendRequestList(uint32be* pidList, uint32be* returnedCount, uint32 startIndex, uint32 maxCount)
{
FP_API_BASE();
StackAllocator<uint32be> startIndexBuf; startIndexBuf = startIndex;
StackAllocator<uint32be> maxCountBuf; maxCountBuf = maxCount;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetFriendRequestList);
ipcCtx->AddOutput(pidList, sizeof(uint32be) * maxCount);
ipcCtx->AddOutput(returnedCount, sizeof(uint32be));
ipcCtx->AddInput(&startIndexBuf, sizeof(uint32be));
ipcCtx->AddInput(&maxCountBuf, sizeof(uint32be));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetFriendListAll(uint32be* pidList, uint32be* returnedCount, uint32 startIndex, uint32 maxCount)
{
FP_API_BASE();
StackAllocator<uint32be> startIndexBuf; startIndexBuf = startIndex;
StackAllocator<uint32be> maxCountBuf; maxCountBuf = maxCount;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetFriendListAll);
ipcCtx->AddOutput(pidList, sizeof(uint32be) * maxCount);
ipcCtx->AddOutput(returnedCount, sizeof(uint32be));
ipcCtx->AddInput(&startIndexBuf, sizeof(uint32be));
ipcCtx->AddInput(&maxCountBuf, sizeof(uint32be));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetFriendListEx(iosu::fpd::FriendData* friendData, uint32be* pidList, uint32 count)
{
FP_API_BASE();
StackAllocator<uint32be> countBuf; countBuf = count;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetFriendListEx);
ipcCtx->AddOutput(friendData, sizeof(iosu::fpd::FriendData) * count);
ipcCtx->AddInput(pidList, sizeof(uint32be) * count);
ipcCtx->AddInput(&countBuf, sizeof(uint32be));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetFriendRequestListEx(iosu::fpd::FriendRequest* friendRequest, uint32be* pidList, uint32 count)
{
FP_API_BASE();
StackAllocator<uint32be> countBuf; countBuf = count;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetFriendRequestListEx);
ipcCtx->AddOutput(friendRequest, sizeof(iosu::fpd::FriendRequest) * count);
ipcCtx->AddInput(pidList, sizeof(uint32be) * count);
ipcCtx->AddInput(&countBuf, sizeof(uint32be));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetBasicInfoAsync(iosu::fpd::FriendBasicInfo* basicInfo, uint32be* pidList, uint32 count, void* funcPtr, void* customParam)
{
FP_API_BASE();
StackAllocator<uint32be> countBuf; countBuf = count;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetBasicInfoAsync);
ipcCtx->AddOutput(basicInfo, sizeof(iosu::fpd::FriendBasicInfo) * count);
ipcCtx->AddInput(pidList, sizeof(uint32be) * count);
ipcCtx->AddInput(&countBuf, sizeof(uint32be));
return ipcCtx->SubmitAsync(std::move(ipcCtx), funcPtr, customParam);
}
uint32 GetMyPrincipalId()
{
FP_API_BASE_ZeroOnError();
StackAllocator<uint32be> resultBuf;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetMyPrincipalId);
ipcCtx->AddOutput(&resultBuf, sizeof(uint32be));
ipcCtx->Submit(std::move(ipcCtx));
return resultBuf->value();
}
nnResult GetMyAccountId(uint8be* accountId)
{
FP_API_BASE();
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetMyAccountId);
ipcCtx->AddOutput(accountId, ACT_ACCOUNTID_LENGTH);
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetMyScreenName(uint16be* screenname)
{
FP_API_BASE();
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetMyScreenName);
ipcCtx->AddOutput(screenname, ACT_NICKNAME_SIZE*sizeof(uint16));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetMyPlayingGame(iosu::fpd::GameKey* myPlayingGame)
{
FP_API_BASE();
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetMyPlayingGame);
ipcCtx->AddOutput(myPlayingGame, sizeof(iosu::fpd::GameKey));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetMyPreference(iosu::fpd::FPDPreference* myPreference)
{
FP_API_BASE();
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetMyPreference);
ipcCtx->AddOutput(myPreference, sizeof(iosu::fpd::FPDPreference));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetMyComment(uint16be* myComment)
{
FP_API_BASE();
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetMyComment);
ipcCtx->AddOutput(myComment, iosu::fpd::MY_COMMENT_LENGTH * sizeof(uint16be));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetMyMii(FFLData_t* fflData)
{
FP_API_BASE();
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetMyMii);
ipcCtx->AddOutput(fflData, sizeof(FFLData_t));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetFriendAccountId(uint8be* accountIdArray, uint32be* pidList, uint32 count)
{
FP_API_BASE();
if (count == 0)
return 0;
StackAllocator<uint32be> countBuf; countBuf = count;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetFriendAccountId);
ipcCtx->AddOutput(accountIdArray, ACT_ACCOUNTID_LENGTH * count);
ipcCtx->AddInput(pidList, sizeof(uint32be) * count);
ipcCtx->AddInput(&countBuf, sizeof(uint32be));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetFriendScreenName(uint16be* nameList, uint32be* pidList, uint32 count, uint8 replaceNonAscii, uint8be* languageList)
{
FP_API_BASE();
if (count == 0)
return 0;
StackAllocator<uint32be> countBuf; countBuf = count;
StackAllocator<uint32be> replaceNonAsciiBuf; replaceNonAsciiBuf = replaceNonAscii;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetFriendScreenName);
ipcCtx->AddOutput(nameList, ACT_NICKNAME_SIZE * sizeof(uint16be) * count);
ipcCtx->AddOutput(languageList, languageList ? sizeof(uint8be) * count : 0);
ipcCtx->AddInput(pidList, sizeof(uint32be) * count);
ipcCtx->AddInput(&countBuf, sizeof(uint32be));
ipcCtx->AddInput(&replaceNonAsciiBuf, sizeof(uint8be));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetFriendMii(FFLData_t* miiList, uint32be* pidList, uint32 count)
{
FP_API_BASE();
if(count == 0)
return 0;
StackAllocator<uint32be> countBuf; countBuf = count;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetFriendMii);
ipcCtx->AddOutput(miiList, sizeof(FFLData_t) * count);
ipcCtx->AddInput(pidList, sizeof(uint32be) * count);
ipcCtx->AddInput(&countBuf, sizeof(uint32be));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetFriendPresence(iosu::fpd::FriendPresence* presenceList, uint32be* pidList, uint32 count)
{
FP_API_BASE();
if(count == 0)
return 0;
StackAllocator<uint32be> countBuf; countBuf = count;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetFriendPresence);
ipcCtx->AddOutput(presenceList, sizeof(iosu::fpd::FriendPresence) * count);
ipcCtx->AddInput(pidList, sizeof(uint32be) * count);
ipcCtx->AddInput(&countBuf, sizeof(uint32be));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult GetFriendRelationship(uint8* relationshipList, uint32be* pidList, uint32 count)
{
FP_API_BASE();
if(count == 0)
return 0;
StackAllocator<uint32be> countBuf; countBuf = count;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetFriendRelationship);
ipcCtx->AddOutput(relationshipList, sizeof(uint8) * count);
ipcCtx->AddInput(pidList, sizeof(uint32be) * count);
ipcCtx->AddInput(&countBuf, sizeof(uint32be));
return ipcCtx->Submit(std::move(ipcCtx));
}
uint32 IsJoinable(iosu::fpd::FriendPresence* presence, uint64 joinMask)
{
if (presence->isValid == 0 ||
presence->isOnline == 0 ||
presence->gameMode.joinGameId == 0 ||
presence->gameMode.matchmakeType == 0 ||
presence->gameMode.groupId == 0 ||
presence->gameMode.joinGameMode >= 64 )
{
return 0;
}
uint32 joinGameMode = presence->gameMode.joinGameMode;
uint64 joinModeMask = (1ULL<<joinGameMode);
if ((joinModeMask&joinMask) == 0)
return 0;
// check relation ship
uint32 joinFlagMask = presence->gameMode.joinFlagMask;
if (joinFlagMask == 0)
return 0;
if (joinFlagMask == 1)
return 1;
if (joinFlagMask == 2)
{
// check relationship
uint8 relationship[1] = { 0 };
StackAllocator<uint32be, 1> pidList;
pidList = presence->gameMode.hostPid;
GetFriendRelationship(relationship, &pidList, 1);
if(relationship[0] == iosu::fpd::RELATIONSHIP_FRIEND)
return 1;
return 0;
}
if (joinFlagMask == 0x65 || joinFlagMask == 0x66)
{
cemuLog_log(LogType::Force, "Unsupported friend invite");
}
return 0;
}
nnResult CheckSettingStatusAsync(uint8* status, void* funcPtr, void* customParam)
{
FP_API_BASE();
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::CheckSettingStatusAsync);
ipcCtx->AddOutput(status, sizeof(uint8be));
return ipcCtx->SubmitAsync(std::move(ipcCtx), funcPtr, customParam);
}
uint32 IsPreferenceValid()
{
FP_API_BASE_ZeroOnError();
StackAllocator<uint32be> resultBuf;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::IsPreferenceValid);
ipcCtx->AddOutput(&resultBuf, sizeof(uint32be));
ipcCtx->Submit(std::move(ipcCtx));
return resultBuf != 0 ? 1 : 0;
}
nnResult UpdateCommentAsync(uint16be* newComment, void* funcPtr, void* customParam)
{
FP_API_BASE();
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::UpdateCommentAsync);
uint32 commentLen = CafeStringHelpers::Length(newComment, iosu::fpd::MY_COMMENT_LENGTH-1);
if (commentLen >= iosu::fpd::MY_COMMENT_LENGTH-1)
{
cemuLog_log(LogType::Force, "UpdateCommentAsync: message too long");
return FPResult_InvalidIPCParam;
}
ipcCtx->AddInput(newComment, sizeof(uint16be) * commentLen + 2);
return ipcCtx->SubmitAsync(std::move(ipcCtx), funcPtr, customParam);
}
nnResult UpdatePreferenceAsync(iosu::fpd::FPDPreference* newPreference, void* funcPtr, void* customParam)
{
FP_API_BASE();
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::UpdatePreferenceAsync);
ipcCtx->AddInput(newPreference, sizeof(iosu::fpd::FPDPreference));
return ipcCtx->SubmitAsync(std::move(ipcCtx), funcPtr, customParam);
}
nnResult UpdateGameModeWithUnusedParam(iosu::fpd::GameMode* gameMode, uint16be* gameModeMessage, uint32 unusedParam)
{
FP_API_BASE();
uint32 messageLen = CafeStringHelpers::Length(gameModeMessage, iosu::fpd::GAMEMODE_MAX_MESSAGE_LENGTH);
if(messageLen >= iosu::fpd::GAMEMODE_MAX_MESSAGE_LENGTH)
{
cemuLog_log(LogType::Force, "UpdateGameMode: message too long");
return FPResult_InvalidIPCParam;
}
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::UpdateGameModeVariation2);
ipcCtx->AddInput(gameMode, sizeof(iosu::fpd::GameMode));
ipcCtx->AddInput(gameModeMessage, sizeof(uint16be) * (messageLen + 1));
return ipcCtx->Submit(std::move(ipcCtx));
}
nnResult UpdateGameMode(iosu::fpd::GameMode* gameMode, uint16be* gameModeMessage)
{
return UpdateGameModeWithUnusedParam(gameMode, gameModeMessage, 0);
}
nnResult GetRequestBlockSettingAsync(uint8* blockSettingList, uint32be* pidList, uint32 count, void* funcPtr, void* customParam)
{
FP_API_BASE();
StackAllocator<uint32be> countBuf; countBuf = count;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::GetRequestBlockSettingAsync);
ipcCtx->AddOutput(blockSettingList, sizeof(uint8be) * count);
ipcCtx->AddInput(pidList, sizeof(uint32be) * count);
ipcCtx->AddInput(&countBuf, sizeof(uint32be));
return ipcCtx->SubmitAsync(std::move(ipcCtx), funcPtr, customParam);
}
// overload of AddFriendAsync
nnResult AddFriendAsyncByPid(uint32 pid, void* funcPtr, void* customParam)
{
FP_API_BASE();
StackAllocator<uint32be> pidBuf; pidBuf = pid;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::AddFriendAsyncByPid);
ipcCtx->AddInput(&pidBuf, sizeof(uint32be));
return ipcCtx->SubmitAsync(std::move(ipcCtx), funcPtr, customParam);
}
nnResult DeleteFriendFlagsAsync(uint32be* pidList, uint32 pidCount, uint32 ukn, void* funcPtr, void* customParam)
{
// admin function?
FP_API_BASE();
StackAllocator<uint32be> pidCountBuf; pidCountBuf = pidCount;
StackAllocator<uint32be> uknBuf; uknBuf = ukn;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::DeleteFriendFlagsAsync);
ipcCtx->AddInput(pidList, sizeof(uint32be) * pidCount);
ipcCtx->AddInput(&pidCountBuf, sizeof(uint32be));
ipcCtx->AddInput(&uknBuf, sizeof(uint32be));
return ipcCtx->SubmitAsync(std::move(ipcCtx), funcPtr, customParam);
}
// overload of AddFriendRequestAsync
nnResult AddFriendRequestByPlayRecordAsync(iosu::fpd::RecentPlayRecordEx* playRecord, uint16be* message, void* funcPtr, void* customParam)
{
FP_API_BASE();
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::AddFriendRequestByPlayRecordAsync);
uint32 messageLen = 0;
while(message[messageLen] != 0)
messageLen++;
ipcCtx->AddInput(playRecord, sizeof(iosu::fpd::RecentPlayRecordEx));
ipcCtx->AddInput(message, sizeof(uint16be) * (messageLen+1));
return ipcCtx->SubmitAsync(std::move(ipcCtx), funcPtr, customParam);
}
nnResult RemoveFriendAsync(uint32 pid, void* funcPtr, void* customParam)
{
FP_API_BASE();
StackAllocator<uint32be> pidBuf; pidBuf = pid;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::RemoveFriendAsync);
ipcCtx->AddInput(&pidBuf, sizeof(uint32be));
return ipcCtx->SubmitAsync(std::move(ipcCtx), funcPtr, customParam);
}
nnResult MarkFriendRequestsAsReceivedAsync(uint64be* messageIdList, uint32 count, void* funcPtr, void* customParam)
{
FP_API_BASE();
StackAllocator<uint32be> countBuf; countBuf = count;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::MarkFriendRequestsAsReceivedAsync);
ipcCtx->AddInput(messageIdList, sizeof(uint64be) * count);
ipcCtx->AddInput(&countBuf, sizeof(uint32be));
return ipcCtx->SubmitAsync(std::move(ipcCtx), funcPtr, customParam);
}
nnResult CancelFriendRequestAsync(uint64 requestId, void* funcPtr, void* customParam)
{
FP_API_BASE();
StackAllocator<uint64be> requestIdBuf; requestIdBuf = requestId;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::CancelFriendRequestAsync);
ipcCtx->AddInput(&requestIdBuf, sizeof(uint64be));
return ipcCtx->SubmitAsync(std::move(ipcCtx), funcPtr, customParam);
}
nnResult DeleteFriendRequestAsync(uint64 requestId, void* funcPtr, void* customParam)
{
FP_API_BASE();
StackAllocator<uint64be> requestIdBuf; requestIdBuf = requestId;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::DeleteFriendRequestAsync);
ipcCtx->AddInput(&requestIdBuf, sizeof(uint64be));
return ipcCtx->SubmitAsync(std::move(ipcCtx), funcPtr, customParam);
}
nnResult AcceptFriendRequestAsync(uint64 requestId, void* funcPtr, void* customParam)
{
FP_API_BASE();
StackAllocator<uint64be> requestIdBuf; requestIdBuf = requestId;
auto ipcCtx = std::make_unique<FPIpcContext>(iosu::fpd::FPD_REQUEST_ID::AcceptFriendRequestAsync);
ipcCtx->AddInput(&requestIdBuf, sizeof(uint64be));
return ipcCtx->SubmitAsync(std::move(ipcCtx), funcPtr, customParam);
}
void load()
{
g_fp.initCounter = 0;
g_fp.isAdminMode = false;
g_fp.isLoggedIn = false;
g_fp.getNotificationCalled = false;
g_fp.notificationHandler = nullptr;
g_fp.notificationHandlerParam = nullptr;
coreinit::OSInitMutex(&g_fp.fpMutex);
FPIpcBufferAllocator.Init();
cafeExportRegisterFunc(Initialize, "nn_fp", "Initialize__Q2_2nn2fpFv", LogType::NN_FP);
cafeExportRegisterFunc(InitializeAdmin, "nn_fp", "InitializeAdmin__Q2_2nn2fpFv", LogType::NN_FP);
cafeExportRegisterFunc(IsInitialized, "nn_fp", "IsInitialized__Q2_2nn2fpFv", LogType::NN_FP);
cafeExportRegisterFunc(IsInitializedAdmin, "nn_fp", "IsInitializedAdmin__Q2_2nn2fpFv", LogType::NN_FP);
cafeExportRegisterFunc(Finalize, "nn_fp", "Finalize__Q2_2nn2fpFv", LogType::NN_FP);
cafeExportRegisterFunc(FinalizeAdmin, "nn_fp", "FinalizeAdmin__Q2_2nn2fpFv", LogType::NN_FP);
cafeExportRegisterFunc(SetNotificationHandler, "nn_fp", "SetNotificationHandler__Q2_2nn2fpFUiPFQ3_2nn2fp16NotificationTypeUiPv_vPv", LogType::NN_FP);
cafeExportRegisterFunc(LoginAsync, "nn_fp", "LoginAsync__Q2_2nn2fpFPFQ2_2nn6ResultPv_vPv", LogType::NN_FP);
cafeExportRegisterFunc(HasLoggedIn, "nn_fp", "HasLoggedIn__Q2_2nn2fpFv", LogType::NN_FP);
cafeExportRegisterFunc(IsOnline, "nn_fp", "IsOnline__Q2_2nn2fpFv", LogType::NN_FP);
cafeExportRegisterFunc(GetFriendList, "nn_fp", "GetFriendList__Q2_2nn2fpFPUiT1UiT3", LogType::NN_FP);
cafeExportRegisterFunc(GetFriendRequestList, "nn_fp", "GetFriendRequestList__Q2_2nn2fpFPUiT1UiT3", LogType::NN_FP);
cafeExportRegisterFunc(GetFriendListAll, "nn_fp", "GetFriendListAll__Q2_2nn2fpFPUiT1UiT3", LogType::NN_FP);
cafeExportRegisterFunc(GetFriendListEx, "nn_fp", "GetFriendListEx__Q2_2nn2fpFPQ3_2nn2fp10FriendDataPCUiUi", LogType::NN_FP);
cafeExportRegisterFunc(GetFriendRequestListEx, "nn_fp", "GetFriendRequestListEx__Q2_2nn2fpFPQ3_2nn2fp13FriendRequestPCUiUi", LogType::NN_FP);
cafeExportRegisterFunc(GetBasicInfoAsync, "nn_fp", "GetBasicInfoAsync__Q2_2nn2fpFPQ3_2nn2fp9BasicInfoPCUiUiPFQ2_2nn6ResultPv_vPv", LogType::NN_FP);
cafeExportRegisterFunc(GetMyPrincipalId, "nn_fp", "GetMyPrincipalId__Q2_2nn2fpFv", LogType::NN_FP);
cafeExportRegisterFunc(GetMyAccountId, "nn_fp", "GetMyAccountId__Q2_2nn2fpFPc", LogType::NN_FP);
cafeExportRegisterFunc(GetMyScreenName, "nn_fp", "GetMyScreenName__Q2_2nn2fpFPw", LogType::NN_FP);
cafeExportRegisterFunc(GetMyMii, "nn_fp", "GetMyMii__Q2_2nn2fpFP12FFLStoreData", LogType::NN_FP);
cafeExportRegisterFunc(GetMyPlayingGame, "nn_fp", "GetMyPlayingGame__Q2_2nn2fpFPQ3_2nn2fp7GameKey", LogType::NN_FP);
cafeExportRegisterFunc(GetMyPreference, "nn_fp", "GetMyPreference__Q2_2nn2fpFPQ3_2nn2fp10Preference", LogType::NN_FP);
cafeExportRegisterFunc(GetMyComment, "nn_fp", "GetMyComment__Q2_2nn2fpFPQ3_2nn2fp7Comment", LogType::NN_FP);
cafeExportRegisterFunc(GetFriendAccountId, "nn_fp", "GetFriendAccountId__Q2_2nn2fpFPA17_cPCUiUi", LogType::NN_FP);
cafeExportRegisterFunc(GetFriendScreenName, "nn_fp", "GetFriendScreenName__Q2_2nn2fpFPA11_wPCUiUibPUc", LogType::NN_FP);
cafeExportRegisterFunc(GetFriendMii, "nn_fp", "GetFriendMii__Q2_2nn2fpFP12FFLStoreDataPCUiUi", LogType::NN_FP);
cafeExportRegisterFunc(GetFriendPresence, "nn_fp", "GetFriendPresence__Q2_2nn2fpFPQ3_2nn2fp14FriendPresencePCUiUi", LogType::NN_FP);
cafeExportRegisterFunc(GetFriendRelationship, "nn_fp", "GetFriendRelationship__Q2_2nn2fpFPUcPCUiUi", LogType::NN_FP);
cafeExportRegisterFunc(IsJoinable, "nn_fp", "IsJoinable__Q2_2nn2fpFPCQ3_2nn2fp14FriendPresenceUL", LogType::NN_FP);
cafeExportRegisterFunc(CheckSettingStatusAsync, "nn_fp", "CheckSettingStatusAsync__Q2_2nn2fpFPUcPFQ2_2nn6ResultPv_vPv", LogType::NN_FP);
cafeExportRegisterFunc(IsPreferenceValid, "nn_fp", "IsPreferenceValid__Q2_2nn2fpFv", LogType::NN_FP);
cafeExportRegisterFunc(UpdateCommentAsync, "nn_fp", "UpdateCommentAsync__Q2_2nn2fpFPCwPFQ2_2nn6ResultPv_vPv", LogType::NN_FP);
cafeExportRegisterFunc(UpdatePreferenceAsync, "nn_fp", "UpdatePreferenceAsync__Q2_2nn2fpFPCQ3_2nn2fp10PreferencePFQ2_2nn6ResultPv_vPv", LogType::NN_FP);
cafeExportRegisterFunc(GetRequestBlockSettingAsync, "nn_fp", "GetRequestBlockSettingAsync__Q2_2nn2fpFPUcPCUiUiPFQ2_2nn6ResultPv_vPv", LogType::NN_FP);
cafeExportRegisterFunc(UpdateGameModeWithUnusedParam, "nn_fp", "UpdateGameMode__Q2_2nn2fpFPCQ3_2nn2fp8GameModePCwUi", LogType::NN_FP);
cafeExportRegisterFunc(UpdateGameMode, "nn_fp", "UpdateGameMode__Q2_2nn2fpFPCQ3_2nn2fp8GameModePCw", LogType::NN_FP);
cafeExportRegisterFunc(AddFriendAsyncByPid, "nn_fp", "AddFriendAsync__Q2_2nn2fpFUiPFQ2_2nn6ResultPv_vPv", LogType::NN_FP);
cafeExportRegisterFunc(AddFriendRequestByPlayRecordAsync, "nn_fp", "AddFriendRequestAsync__Q2_2nn2fpFPCQ3_2nn2fp18RecentPlayRecordExPCwPFQ2_2nn6ResultPv_vPv", LogType::NN_FP);
cafeExportRegisterFunc(DeleteFriendFlagsAsync, "nn_fp", "DeleteFriendFlagsAsync__Q2_2nn2fpFPCUiUiT2PFQ2_2nn6ResultPv_vPv", LogType::NN_FP);
cafeExportRegisterFunc(RemoveFriendAsync, "nn_fp", "RemoveFriendAsync__Q2_2nn2fpFUiPFQ2_2nn6ResultPv_vPv", LogType::NN_FP);
cafeExportRegisterFunc(MarkFriendRequestsAsReceivedAsync, "nn_fp", "MarkFriendRequestsAsReceivedAsync__Q2_2nn2fpFPCULUiPFQ2_2nn6ResultPv_vPv", LogType::NN_FP);
cafeExportRegisterFunc(CancelFriendRequestAsync, "nn_fp", "CancelFriendRequestAsync__Q2_2nn2fpFULPFQ2_2nn6ResultPv_vPv", LogType::NN_FP);
cafeExportRegisterFunc(DeleteFriendRequestAsync, "nn_fp", "DeleteFriendRequestAsync__Q2_2nn2fpFULPFQ2_2nn6ResultPv_vPv", LogType::NN_FP);
cafeExportRegisterFunc(AcceptFriendRequestAsync, "nn_fp", "AcceptFriendRequestAsync__Q2_2nn2fpFULPFQ2_2nn6ResultPv_vPv", LogType::NN_FP);
}
}
}
| 33,602
|
C++
|
.cpp
| 745
| 41.061745
| 207
| 0.741815
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,130
|
dmae.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/dmae/dmae.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "Cafe/HW/Latte/Core/LatteBufferCache.h"
#define DMAE_ENDIAN_NONE 0
#define DMAE_ENDIAN_16 1
#define DMAE_ENDIAN_32 2
#define DMAE_ENDIAN_64 3
uint64 dmaeRetiredTimestamp = 0;
uint64 dmae_getTimestamp()
{
return coreinit::coreinit_getTimerTick();
}
void dmae_setRetiredTimestamp(uint64 timestamp)
{
dmaeRetiredTimestamp = timestamp;
}
void dmaeExport_DMAECopyMem(PPCInterpreter_t* hCPU)
{
if( hCPU->gpr[6] == DMAE_ENDIAN_NONE )
{
// don't change endianness
memcpy(memory_getPointerFromVirtualOffset(hCPU->gpr[3]), memory_getPointerFromVirtualOffset(hCPU->gpr[4]), hCPU->gpr[5]*4);
}
else if( hCPU->gpr[6] == DMAE_ENDIAN_32 )
{
// swap per uint32
uint32* srcBuffer = (uint32*)memory_getPointerFromVirtualOffset(hCPU->gpr[4]);
uint32* dstBuffer = (uint32*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
for(uint32 i=0; i<hCPU->gpr[5]; i++)
{
dstBuffer[i] = _swapEndianU32(srcBuffer[i]);
}
}
else
{
cemuLog_logDebug(LogType::Force, "DMAECopyMem(): Unsupported endian swap\n");
}
uint64 dmaeTimestamp = dmae_getTimestamp();
dmae_setRetiredTimestamp(dmaeTimestamp);
if(hCPU->gpr[5] > 0)
LatteBufferCache_notifyDCFlush(hCPU->gpr[3], hCPU->gpr[5]*4);
osLib_returnFromFunction64(hCPU, dmaeTimestamp);
}
void dmaeExport_DMAEFillMem(PPCInterpreter_t* hCPU)
{
uint32* dstBuffer = (uint32*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
uint32 value = hCPU->gpr[4];
uint32 numU32s = hCPU->gpr[5];
value = _swapEndianU32(value);
for(uint32 i=0; i<numU32s; i++)
{
*dstBuffer = value;
dstBuffer++;
}
uint64 dmaeTimestamp = dmae_getTimestamp();
dmae_setRetiredTimestamp(dmaeTimestamp);
osLib_returnFromFunction64(hCPU, dmaeTimestamp);
}
void dmaeExport_DMAEWaitDone(PPCInterpreter_t* hCPU)
{
//debug_printf("DMAEWaitDone(...)\n");
// parameter:
// r3/r4 uint64 dmaeTimestamp
osLib_returnFromFunction(hCPU, 1);
}
void dmaeExport_DMAESemaphore(PPCInterpreter_t* hCPU)
{
// parameter:
// r3 MPTR addr
// r4 uint32 actionType
uint32 actionType = hCPU->gpr[4];
std::atomic<uint64le>* semaphore = _rawPtrToAtomic((uint64le*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]));
if( actionType == 1 )
{
// Signal Semaphore
semaphore->fetch_add(1);
}
else if (actionType == 0) // wait
{
cemuLog_logDebug(LogType::Force, "DMAESemaphore: Unsupported wait operation");
semaphore->fetch_sub(1);
}
else
{
cemuLog_logDebug(LogType::Force, "DMAESemaphore unknown action type {}", actionType);
cemu_assert_debug(false);
}
uint64 dmaeTimestamp = dmae_getTimestamp();
dmae_setRetiredTimestamp(dmaeTimestamp);
osLib_returnFromFunction64(hCPU, dmaeTimestamp);
}
void dmaeExport_DMAEGetRetiredTimeStamp(PPCInterpreter_t* hCPU)
{
debug_printf("DMAEGetRetiredTimeStamp()\n");
osLib_returnFromFunction64(hCPU, dmaeRetiredTimestamp);
}
void dmae_load()
{
osLib_addFunction("dmae", "DMAECopyMem", dmaeExport_DMAECopyMem);
osLib_addFunction("dmae", "DMAEFillMem", dmaeExport_DMAEFillMem);
osLib_addFunction("dmae", "DMAEWaitDone", dmaeExport_DMAEWaitDone);
osLib_addFunction("dmae", "DMAESemaphore", dmaeExport_DMAESemaphore);
osLib_addFunction("dmae", "DMAEGetRetiredTimeStamp", dmaeExport_DMAEGetRetiredTimeStamp);
}
| 3,287
|
C++
|
.cpp
| 104
| 29.567308
| 125
| 0.763258
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,131
|
snd_user.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/snd_user/snd_user.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/snd_user/snd_user.h"
#include "Cafe/OS/libs/snd_core/ax.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "Cafe/OS/RPL/rpl.h"
using namespace snd_core;
namespace snd
{
namespace user
{
#define AX_MAX_NUM_DRC (2)
#define AX_MAX_NUM_RMT (4)
#define AX_UPDATE_MODE_10000000 (0x10000000)
#define AX_UPDATE_MODE_20000000 (0x20000000)
#define AX_UPDATE_MODE_40000000_VOLUME (0x40000000)
#define AX_UPDATE_MODE_50000000 (0x50000000)
#define AX_UPDATE_MODE_40000007 (0x40000007)
#define AX_UPDATE_MODE_80000000 (0x80000000)
struct VolumeData
{
sint16 volume; // 0x00
sint16 volume_target; // 0x02
};
static_assert(sizeof(VolumeData) == 0x4, "sizeof(VolumeData)");
struct MixControl
{
sint16 aux[AX_AUX_BUS_COUNT];
sint16 pan;
sint16 span;
sint16 fader;
sint16 lfe;
};
static_assert(sizeof(MixControl) == 0xE, "sizeof(MixControl)");
using MixMode = uint32_t;
struct MixChannel
{
MEMPTR<AXVPB> voice;
uint32 update_mode;
sint16 input_level;
VolumeData volume;
MixControl tv_control;
sint16 tv_channels[AX_TV_CHANNEL_COUNT];
VolumeData tv_volume[AX_MAX_NUM_BUS][AX_TV_CHANNEL_COUNT];
MixMode tv_mode;
MixControl drc_control[AX_MAX_NUM_DRC];
sint16 drc_channels[AX_MAX_NUM_DRC][AX_DRC_CHANNEL_COUNT];
VolumeData drc_volume[AX_MAX_NUM_DRC][AX_MAX_NUM_BUS][AX_DRC_CHANNEL_COUNT];
MixMode drc_mode[AX_MAX_NUM_DRC];
MixControl rmt_control[AX_MAX_NUM_RMT];
sint16 rmt_channels[AX_MAX_NUM_RMT][AX_RMT_CHANNEL_COUNT];
VolumeData rmt_volume[AX_MAX_NUM_RMT][AX_MAX_NUM_BUS][AX_RMT_CHANNEL_COUNT];
MixMode rmt_mode[AX_MAX_NUM_RMT];
MixControl& GetMixControl(uint32 device, uint32 deviceIndex)
{
if (device == AX_DEV_TV)
{
cemu_assert(deviceIndex == 0);
return tv_control;
}
else if (device == AX_DEV_DRC)
{
cemu_assert(deviceIndex < AX_MAX_NUM_DRC);
return drc_control[deviceIndex];
}
else if (device == AX_DEV_RMT)
{
cemu_assert(deviceIndex < AX_MAX_NUM_RMT);
return rmt_control[deviceIndex];
}
cemuLog_log(LogType::Force, "GetMixControl({}, {}): Invalid device/deviceIndex", device, deviceIndex);
cemu_assert(false);
return tv_control;
}
MixMode& GetMode(uint32 device, uint32 deviceIndex)
{
if (device == AX_DEV_TV)
{
cemu_assert(deviceIndex == 0);
return tv_mode;
}
else if (device == AX_DEV_DRC)
{
cemu_assert(deviceIndex < AX_MAX_NUM_DRC);
return drc_mode[deviceIndex];
}
else if (device == AX_DEV_RMT)
{
cemu_assert(deviceIndex < AX_MAX_NUM_RMT);
return rmt_mode[deviceIndex];
}
cemuLog_log(LogType::Force, "GetMode({}, {}): Invalid device/deviceIndex", device, deviceIndex);
cemu_assert(false);
return tv_mode;
}
sint16* GetChannels(uint32 device, uint32 deviceIndex)
{
if (device == AX_DEV_TV)
{
cemu_assert(deviceIndex == 0);
return tv_channels;
}
else if (device == AX_DEV_DRC)
{
cemu_assert(deviceIndex < AX_MAX_NUM_DRC);
return drc_channels[deviceIndex];
}
else if (device == AX_DEV_RMT)
{
cemu_assert(deviceIndex < AX_MAX_NUM_RMT);
return rmt_channels[deviceIndex];
}
cemuLog_log(LogType::Force, "GetChannels({}, {}): Invalid device/deviceIndex", device, deviceIndex);
cemu_assert(false);
return tv_channels;
}
};
static_assert(sizeof(MixChannel) == 0x1D0, "sizeof(MixChannel)");
struct DeviceInfo
{
uint32 tv_sound_mode; // 0x00
uint32 drc_sound_mode; // 0x04
uint32 rmt_sound_mode; // 0x08
};
struct snd_user_data_t
{
bool initialized;
DeviceInfo device_info;
sint32 max_voices;
MixChannel mix_channel[AX_MAX_VOICES];
const uint16 volume[0x388 + 0x3C + 1] =
{
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0xA, 0xA, 0xA, 0xA, 0xA, 0xA, 0xA, 0xA, 0xA, 0xB, 0xB, 0xB, 0xB, 0xB, 0xB, 0xB, 0xC,
0xC, 0xC, 0xC, 0xC, 0xC, 0xC, 0xD, 0xD, 0xD, 0xD, 0xD, 0xD, 0xD, 0xE, 0xE, 0xE, 0xE, 0xE, 0xE, 0xF, 0xF, 0xF, 0xF, 0xF, 0x10, 0x10, 0x10, 0x10, 0x10, 0x11, 0x11, 0x11, 0x11, 0x11, 0x12, 0x12, 0x12, 0x12, 0x12, 0x13, 0x13, 0x13,
0x13, 0x13, 0x14, 0x14, 0x14, 0x14, 0x15, 0x15, 0x15, 0x15, 0x16, 0x16, 0x16, 0x16, 0x17, 0x17, 0x17, 0x18, 0x18, 0x18, 0x18, 0x19, 0x19, 0x19, 0x1A, 0x1A, 0x1A, 0x1A, 0x1B, 0x1B, 0x1B, 0x1C, 0x1C, 0x1C, 0x1D, 0x1D, 0x1D, 0x1E,
0x1E, 0x1E, 0x1F, 0x1F, 0x20, 0x20, 0x20, 0x21, 0x21, 0x21, 0x22, 0x22, 0x23, 0x23, 0x23, 0x24, 0x24, 0x25, 0x25, 0x26, 0x26, 0x26, 0x27, 0x27, 0x28, 0x28, 0x29, 0x29, 0x2A, 0x2A, 0x2B, 0x2B, 0x2C, 0x2C, 0x2D, 0x2D, 0x2E, 0x2E,
0x2F, 0x2F, 0x30, 0x31, 0x31, 0x32, 0x32, 0x33, 0x33, 0x34, 0x35, 0x35, 0x36, 0x37, 0x37, 0x38, 0x38, 0x39, 0x3A, 0x3A, 0x3B, 0x3C, 0x3D, 0x3D, 0x3E, 0x3F, 0x3F, 0x40, 0x41, 0x42, 0x42, 0x43, 0x44, 0x45, 0x46, 0x46, 0x47, 0x48,
0x49, 0x4A, 0x4B, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x64, 0x65, 0x66, 0x67, 0x68, 0x6A, 0x6B, 0x6C, 0x6D, 0x6F, 0x70,
0x71, 0x72, 0x74, 0x75, 0x76, 0x78, 0x79, 0x7B, 0x7C, 0x7E, 0x7F, 0x80, 0x82, 0x83, 0x85, 0x87, 0x88, 0x8A, 0x8B, 0x8D, 0x8F, 0x90, 0x92, 0x94, 0x95, 0x97, 0x99, 0x9B, 0x9C, 0x9E, 0xA0, 0xA2, 0xA4, 0xA6, 0xA8, 0xAA, 0xAB, 0xAD,
0xAF, 0xB2, 0xB4, 0xB6, 0xB8, 0xBA, 0xBC, 0xBE, 0xC0, 0xC3, 0xC5, 0xC7, 0xCA, 0xCC, 0xCE, 0xD1, 0xD3, 0xD6, 0xD8, 0xDB, 0xDD, 0xE0, 0xE2, 0xE5, 0xE7, 0xEA, 0xED, 0xF0, 0xF2, 0xF5, 0xF8, 0xFB, 0xFE, 0x101, 0x104, 0x107, 0x10A, 0x10D,
0x110, 0x113, 0x116, 0x11A, 0x11D, 0x120, 0x124, 0x127, 0x12A, 0x12E, 0x131, 0x135, 0x138, 0x13C, 0x140, 0x143, 0x147, 0x14B, 0x14F, 0x153, 0x157, 0x15B, 0x15F, 0x163, 0x167, 0x16B, 0x16F, 0x173, 0x178, 0x17C, 0x180, 0x185, 0x189,
0x18E, 0x193, 0x197, 0x19C, 0x1A1, 0x1A6, 0x1AB, 0x1AF, 0x1B4, 0x1BA, 0x1BF, 0x1C4, 0x1C9, 0x1CE, 0x1D4, 0x1D9, 0x1DF, 0x1E4, 0x1EA, 0x1EF, 0x1F5, 0x1FB, 0x201, 0x207, 0x20D, 0x213, 0x219, 0x21F, 0x226, 0x22C, 0x232, 0x239, 0x240,
0x246, 0x24D, 0x254, 0x25B, 0x262, 0x269, 0x270, 0x277, 0x27E, 0x286, 0x28D, 0x295, 0x29D, 0x2A4, 0x2AC, 0x2B4, 0x2BC, 0x2C4, 0x2CC, 0x2D5, 0x2DD, 0x2E6, 0x2EE, 0x2F7, 0x300, 0x309, 0x312, 0x31B, 0x324, 0x32D, 0x337, 0x340, 0x34A,
0x354, 0x35D, 0x367, 0x371, 0x37C, 0x386, 0x390, 0x39B, 0x3A6, 0x3B1, 0x3BB, 0x3C7, 0x3D2, 0x3DD, 0x3E9, 0x3F4, 0x400, 0x40C, 0x418, 0x424, 0x430, 0x43D, 0x449, 0x456, 0x463, 0x470, 0x47D, 0x48A, 0x498, 0x4A5, 0x4B3, 0x4C1, 0x4CF,
0x4DD, 0x4EC, 0x4FA, 0x509, 0x518, 0x527, 0x536, 0x546, 0x555, 0x565, 0x575, 0x586, 0x596, 0x5A6, 0x5B7, 0x5C8, 0x5D9, 0x5EB, 0x5FC, 0x60E, 0x620, 0x632, 0x644, 0x657, 0x66A, 0x67D, 0x690, 0x6A4, 0x6B7, 0x6CB, 0x6DF, 0x6F4, 0x708,
0x71D, 0x732, 0x748, 0x75D, 0x773, 0x789, 0x79F, 0x7B6, 0x7CD, 0x7E4, 0x7FB, 0x813, 0x82B, 0x843, 0x85C, 0x874, 0x88E, 0x8A7, 0x8C1, 0x8DA, 0x8F5, 0x90F, 0x92A, 0x945, 0x961, 0x97D, 0x999, 0x9B5, 0x9D2, 0x9EF, 0xA0D, 0xA2A, 0xA48,
0xA67, 0xA86, 0xAA5, 0xAC5, 0xAE5, 0xB05, 0xB25, 0xB47, 0xB68, 0xB8A, 0xBAC, 0xBCF, 0xBF2, 0xC15, 0xC39, 0xC5D, 0xC82, 0xCA7, 0xCCC, 0xCF2, 0xD19, 0xD3F, 0xD67, 0xD8E, 0xDB7, 0xDDF, 0xE08, 0xE32, 0xE5C, 0xE87, 0xEB2, 0xEDD, 0xF09,
0xF36, 0xF63, 0xF91, 0xFBF, 0xFEE, 0x101D, 0x104D, 0x107D, 0x10AE, 0x10DF, 0x1111, 0x1144, 0x1177, 0x11AB, 0x11DF, 0x1214, 0x124A, 0x1280, 0x12B7, 0x12EE, 0x1326, 0x135F, 0x1399, 0x13D3, 0x140D, 0x1449, 0x1485, 0x14C2, 0x14FF, 0x153E,
0x157D, 0x15BC, 0x15FD, 0x163E, 0x1680, 0x16C3, 0x1706, 0x174A, 0x178F, 0x17D5, 0x181C, 0x1863, 0x18AC, 0x18F5, 0x193F, 0x198A, 0x19D5, 0x1A22, 0x1A6F, 0x1ABE, 0x1B0D, 0x1B5D, 0x1BAE, 0x1C00, 0x1C53, 0x1CA7, 0x1CFC, 0x1D52, 0x1DA9,
0x1E01, 0x1E5A, 0x1EB4, 0x1F0F, 0x1F6B, 0x1FC8, 0x2026, 0x2086, 0x20E6, 0x2148, 0x21AA, 0x220E, 0x2273, 0x22D9, 0x2341, 0x23A9, 0x2413, 0x247E, 0x24EA, 0x2557, 0x25C6, 0x2636, 0x26A7, 0x271A, 0x278E, 0x2803, 0x287A, 0x28F2, 0x296B,
0x29E6, 0x2A62, 0x2AE0, 0x2B5F, 0x2BDF, 0x2C61, 0x2CE5, 0x2D6A, 0x2DF1, 0x2E79, 0x2F03, 0x2F8E, 0x301B, 0x30AA, 0x313A, 0x31CC, 0x325F, 0x32F5, 0x338C, 0x3425, 0x34BF, 0x355B, 0x35FA, 0x369A, 0x373C, 0x37DF, 0x3885, 0x392C, 0x39D6,
0x3A81, 0x3B2F, 0x3BDE, 0x3C90, 0x3D43, 0x3DF9, 0x3EB1, 0x3F6A, 0x4026, 0x40E5, 0x41A5, 0x4268, 0x432C, 0x43F4, 0x44BD, 0x4589, 0x4657, 0x4727, 0x47FA, 0x48D0, 0x49A8, 0x4A82, 0x4B5F, 0x4C3E, 0x4D20, 0x4E05, 0x4EEC, 0x4FD6, 0x50C3,
0x51B2, 0x52A4, 0x5399, 0x5491, 0x558C, 0x5689, 0x578A, 0x588D, 0x5994, 0x5A9D, 0x5BAA, 0x5CBA, 0x5DCD, 0x5EE3, 0x5FFC, 0x6119, 0x6238, 0x635C, 0x6482, 0x65AC, 0x66D9, 0x680A, 0x693F, 0x6A77, 0x6BB2, 0x6CF2, 0x6E35, 0x6F7B, 0x70C6,
0x7214, 0x7366, 0x74BC, 0x7616, 0x7774, 0x78D6, 0x7A3D, 0x7BA7, 0x7D16, 0x7E88, 0x7FFF, 0x817B, 0x82FB, 0x847F, 0x8608, 0x8795, 0x8927, 0x8ABE, 0x8C59, 0x8DF9, 0x8F9E, 0x9148, 0x92F6, 0x94AA, 0x9663, 0x9820, 0x99E3, 0x9BAB, 0x9D79,
0x9F4C, 0xA124, 0xA302, 0xA4E5, 0xA6CE, 0xA8BC, 0xAAB0, 0xACAA, 0xAEAA, 0xB0B0, 0xB2BC, 0xB4CE, 0xB6E5, 0xB904, 0xBB28, 0xBD53, 0xBF84, 0xC1BC, 0xC3FA, 0xC63F, 0xC88B, 0xCADD, 0xCD37, 0xCF97, 0xD1FE, 0xD46D, 0xD6E3, 0xD960, 0xDBE4,
0xDE70, 0xE103, 0xE39E, 0xE641, 0xE8EB, 0xEB9E, 0xEE58, 0xF11B, 0xF3E6, 0xF6B9, 0xF994, 0xFC78, 0xFF64
};
const uint32 pan_values[128] =
{
00, 00,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFE, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFD, 0xFFFFFFFC, 0xFFFFFFFC, 0xFFFFFFFC, 0xFFFFFFFB, 0xFFFFFFFB, 0xFFFFFFFB,
0xFFFFFFFA, 0xFFFFFFFA, 0xFFFFFFF9, 0xFFFFFFF9, 0xFFFFFFF9, 0xFFFFFFF8, 0xFFFFFFF8, 0xFFFFFFF7, 0xFFFFFFF7, 0xFFFFFFF6, 0xFFFFFFF6, 0xFFFFFFF6, 0xFFFFFFF5, 0xFFFFFFF5,
0xFFFFFFF4, 0xFFFFFFF4, 0xFFFFFFF3, 0xFFFFFFF3, 0xFFFFFFF2, 0xFFFFFFF2, 0xFFFFFFF2, 0xFFFFFFF1, 0xFFFFFFF1, 0xFFFFFFF0, 0xFFFFFFF0, 0xFFFFFFEF, 0xFFFFFFEF, 0xFFFFFFEE,
0xFFFFFFEE, 0xFFFFFFED, 0xFFFFFFEC, 0xFFFFFFEC, 0xFFFFFFEB, 0xFFFFFFEB, 0xFFFFFFEA, 0xFFFFFFEA, 0xFFFFFFE9, 0xFFFFFFE9, 0xFFFFFFE8, 0xFFFFFFE7, 0xFFFFFFE7, 0xFFFFFFE6,
0xFFFFFFE6, 0xFFFFFFE5, 0xFFFFFFE4, 0xFFFFFFE4, 0xFFFFFFE3, 0xFFFFFFE2, 0xFFFFFFE2, 0xFFFFFFE1, 0xFFFFFFE0, 0xFFFFFFDF, 0xFFFFFFDF, 0xFFFFFFDE, 0xFFFFFFDD, 0xFFFFFFDC,
0xFFFFFFDC, 0xFFFFFFDB, 0xFFFFFFDA, 0xFFFFFFD9, 0xFFFFFFD8, 0xFFFFFFD8, 0xFFFFFFD7, 0xFFFFFFD6, 0xFFFFFFD5, 0xFFFFFFD4, 0xFFFFFFD3, 0xFFFFFFD2, 0xFFFFFFD1, 0xFFFFFFD0,
0xFFFFFFCF, 0xFFFFFFCE, 0xFFFFFFCD, 0xFFFFFFCC, 0xFFFFFFCA, 0xFFFFFFC9, 0xFFFFFFC8, 0xFFFFFFC7, 0xFFFFFFC5, 0xFFFFFFC4, 0xFFFFFFC3, 0xFFFFFFC1, 0xFFFFFFC0, 0xFFFFFFBE,
0xFFFFFFBD, 0xFFFFFFBB, 0xFFFFFFB9, 0xFFFFFFB8, 0xFFFFFFB6, 0xFFFFFFB4, 0xFFFFFFB2, 0xFFFFFFB0, 0xFFFFFFAD, 0xFFFFFFAB, 0xFFFFFFA9, 0xFFFFFFA6, 0xFFFFFFA3, 0xFFFFFFA0,
0xFFFFFF9D, 0xFFFFFF9A, 0xFFFFFF96, 0xFFFFFF92, 0xFFFFFF8D, 0xFFFFFF88, 0xFFFFFF82, 0xFFFFFF7B, 0xFFFFFF74, 0xFFFFFF6A, 0xFFFFFF5D, 0xFFFFFF4C, 0xFFFFFF2E, 0xFFFFFC78
};
const uint16 pan_values_low[128] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFE, 0xFFFE, 0xFFFE, 0xFFFE, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFC, 0xFFFC, 0xFFFC, 0xFFFB, 0xFFFB, 0xFFFA, 0xFFFA, 0xFFFA, 0xFFF9, 0xFFF9, 0xFFF8, 0xFFF8,
0xFFF7, 0xFFF7, 0xFFF6, 0xFFF5, 0xFFF5, 0xFFF4, 0xFFF4, 0xFFF3, 0xFFF2, 0xFFF2, 0xFFF1, 0xFFF0, 0xFFEF, 0xFFEF, 0xFFEE, 0xFFED, 0xFFEC, 0xFFEB, 0xFFEB, 0xFFEA, 0xFFE9, 0xFFE8, 0xFFE7, 0xFFE6, 0xFFE5, 0xFFE4, 0xFFE3, 0xFFE2, 0xFFE1,
0xFFE0, 0xFFDE, 0xFFDD, 0xFFDC, 0xFFDB, 0xFFDA, 0xFFD8, 0xFFD7, 0xFFD6, 0xFFD4, 0xFFD3, 0xFFD1, 0xFFD0, 0xFFCE, 0xFFCC, 0xFFCB, 0xFFC9, 0xFFC7, 0xFFC6, 0xFFC4, 0xFFC2, 0xFFC0, 0xFFBE, 0xFFBC, 0xFFBA, 0xFFB7, 0xFFB5, 0xFFB3, 0xFFB0,
0xFFAE, 0xFFAB, 0xFFA8, 0xFFA6, 0xFFA3, 0xFFA0, 0xFF9C, 0xFF99, 0xFF96, 0xFF92, 0xFF8E, 0xFF8A, 0xFF86, 0xFF82, 0xFF7D, 0xFF78, 0xFF73, 0xFF6E, 0xFF68, 0xFF61, 0xFF5A, 0xFF53, 0xFF4B, 0xFF42, 0xFF37, 0xFF2C, 0xFF1F, 0xFF0F, 0xFEFB,
0xFEE2, 0xFEBF, 0xFE83, 0xFC40
};
const uint16 pan_values_high[128] =
{
0xFFC3, 0xFFC3, 0xFFC4, 0xFFC5, 0xFFC5, 0xFFC6, 0xFFC6, 0xFFC7, 0xFFC8, 0xFFC8, 0xFFC9, 0xFFC9, 0xFFCA, 0xFFCB, 0xFFCB, 0xFFCC, 0xFFCC, 0xFFCD, 0xFFCE, 0xFFCE, 0xFFCF, 0xFFCF, 0xFFD0, 0xFFD0, 0xFFD1, 0xFFD1, 0xFFD2, 0xFFD2, 0xFFD3,
0xFFD3, 0xFFD4, 0xFFD4, 0xFFD5, 0xFFD5, 0xFFD6, 0xFFD6, 0xFFD7, 0xFFD7, 0xFFD8, 0xFFD8, 0xFFD9, 0xFFD9, 0xFFDA, 0xFFDA, 0xFFDA, 0xFFDB, 0xFFDB, 0xFFDC, 0xFFDC, 0xFFDD, 0xFFDD, 0xFFDD, 0xFFDE, 0xFFDE, 0xFFDF, 0xFFDF, 0xFFE0, 0xFFE0,
0xFFE0, 0xFFE1, 0xFFE1, 0xFFE1, 0xFFE2, 0xFFE2, 0xFFE3, 0xFFE3, 0xFFE3, 0xFFE4, 0xFFE4, 0xFFE4, 0xFFE5, 0xFFE5, 0xFFE5, 0xFFE6, 0xFFE6, 0xFFE6, 0xFFE7, 0xFFE7, 0xFFE7, 0xFFE8, 0xFFE8, 0xFFE8, 0xFFE9, 0xFFE9, 0xFFE9, 0xFFEA, 0xFFEA,
0xFFEA, 0xFFEB, 0xFFEB, 0xFFEB, 0xFFEC, 0xFFEC, 0xFFEC, 0xFFEC, 0xFFED, 0xFFED, 0xFFED, 0xFFEE, 0xFFEE, 0xFFEE, 0xFFEE, 0xFFEF, 0xFFEF, 0xFFEF, 0xFFEF, 0xFFF0, 0xFFF0, 0xFFF0, 0xFFF0, 0xFFF1, 0xFFF1, 0xFFF1, 0xFFF1, 0xFFF2, 0xFFF2,
0xFFF2, 0xFFF2, 0xFFF3, 0xFFF3, 0xFFF3, 0xFFF3, 0xFFF3, 0xFFF4, 0xFFF4, 0xFFF4, 0xFFF4, 0xFFF5
};
} g_snd_user_data{};
void _MIXChannelResetTV(MixChannel* channel, sint32 index)
{
assert(index == 0);
channel->tv_mode = 0;
channel->tv_control.pan = 0x40;
channel->tv_control.span = 0x7F;
channel->tv_control.fader = 0;
channel->tv_control.lfe = -960;
for (size_t i = 0; i < AX_AUX_BUS_COUNT; ++i)
{
channel->tv_control.aux[i] = -960;
}
for (size_t i = 0; i < AX_MAX_NUM_BUS; ++i)
{
for (size_t j = 0; j < AX_TV_CHANNEL_COUNT; ++j)
{
channel->tv_volume[i][j].volume = 0;
channel->tv_volume[i][j].volume_target = 0;
}
}
}
void _MIXChannelResetDRC(MixChannel* channel, sint32 index)
{
assert(index < AX_MAX_NUM_DRC);
channel->drc_mode[index] = 0;
channel->drc_control[index].pan = 0x40;
channel->drc_control[index].span = 0x7F;
channel->drc_control[index].fader = 0;
channel->drc_control[index].lfe = -960;
for (size_t i = 0; i < AX_AUX_BUS_COUNT; ++i)
{
channel->drc_control[index].aux[i] = -960;
}
for (size_t i = 0; i < AX_MAX_NUM_BUS; ++i)
{
for (size_t j = 0; j < AX_DRC_CHANNEL_COUNT; ++j)
{
channel->drc_volume[index][i][j].volume = 0;
channel->drc_volume[index][i][j].volume_target = 0;
}
}
}
void _MIXChannelResetRmt(MixChannel* channel, sint32 index)
{
assert(index < AX_MAX_NUM_RMT);
channel->rmt_mode[index] = 0;
channel->rmt_control[index].pan = 0x40;
channel->rmt_control[index].span = 0x7F;
channel->rmt_control[index].fader = 0;
channel->rmt_control[index].lfe = -960;
for (size_t i = 0; i < AX_AUX_BUS_COUNT; ++i)
{
channel->rmt_control[index].aux[i] = -960;
}
for (size_t i = 0; i < AX_MAX_NUM_BUS; ++i)
{
for (size_t j = 0; j < AX_RMT_CHANNEL_COUNT; ++j)
{
channel->rmt_volume[index][i][j].volume = 0;
channel->rmt_volume[index][i][j].volume_target = 0;
}
}
}
void MIXResetChannelData(MixChannel* channel)
{
channel->update_mode = AX_UPDATE_MODE_50000000;
channel->input_level = 0;
channel->volume.volume = 0;
channel->volume.volume_target = 0;
_MIXChannelResetTV(channel, 0);
for (int i = 0; i < AX_MAX_NUM_DRC; ++i)
_MIXChannelResetDRC(channel, i);
for (int i = 0; i < AX_MAX_NUM_RMT; ++i)
_MIXChannelResetRmt(channel, i);
}
void _MIXControl_SetDevicePan(MixControl* control, int device_type, sint16 channels[])
{
const auto pandiff = 0x7F - control->pan;
const auto spandiff = 0x7F - control->span;
if (device_type == AX_DEV_TV)
{
const uint32 sound_mode = g_snd_user_data.device_info.tv_sound_mode;
if (sound_mode == 3)
{
channels[0] = g_snd_user_data.pan_values_low[control->pan];
channels[1] = g_snd_user_data.pan_values_low[pandiff];
channels[2] = g_snd_user_data.pan_values_high[pandiff];
channels[3] = g_snd_user_data.pan_values_high[control->pan];
channels[4] = g_snd_user_data.pan_values_high[spandiff];
channels[5] = g_snd_user_data.pan_values_high[control->span];
}
else if (sound_mode != 4)
{
channels[0] = g_snd_user_data.pan_values[control->pan];
channels[1] = g_snd_user_data.pan_values[pandiff];
channels[2] = 0;
channels[3] = 0;
channels[4] = g_snd_user_data.pan_values[spandiff];
channels[5] = g_snd_user_data.pan_values[control->span];
}
else
{
uint32 pan = 0x7F;
if (((uint32)control->pan >> 1) < 0x7F)
pan = (uint32)control->pan >> 1;
channels[0] = g_snd_user_data.pan_values[pan] + g_snd_user_data.pan_values[spandiff];
uint32 span = 0x7F;
if (((uint32)pandiff >> 1) < 0x7E)
span = (uint32)pandiff >> 1;
channels[1] = g_snd_user_data.pan_values[span] + g_snd_user_data.pan_values[spandiff];
// TODO
}
}
else if (device_type == AX_DEV_DRC)
{
// TODO
}
}
sint16 __MIXTranslateVolume(sint16 input)
{
if (input <= -904)
return 0;
if (input > 0x3C)
return -156;
return (sint16)g_snd_user_data.volume[input + 903];
}
void AXFXInitDefaultHooks();
void MIXInit()
{
cemuLog_log(LogType::SoundAPI, "MIXInit()");
if (g_snd_user_data.initialized)
return;
g_snd_user_data.max_voices = AX_MAX_VOICES; // AXGetMaxVoices();
for (sint32 i = 0; i < g_snd_user_data.max_voices; ++i)
{
MIXResetChannelData(&g_snd_user_data.mix_channel[i]);
}
g_snd_user_data.initialized = true;
g_snd_user_data.device_info.tv_sound_mode = 1;
g_snd_user_data.device_info.drc_sound_mode = 1;
g_snd_user_data.device_info.rmt_sound_mode = 0;
AXFXInitDefaultHooks();
}
void MIXSetSoundMode(uint32 sound_mode)
{
cemuLog_log(LogType::SoundAPI, "MIXSetSoundMode(0x{:x})", sound_mode);
if (sound_mode >= 2)
sound_mode = 1;
g_snd_user_data.device_info.tv_sound_mode = sound_mode;
}
uint32 MIXGetSoundMode()
{
cemuLog_log(LogType::SoundAPI, "MIXGetSoundMode()");
return g_snd_user_data.device_info.tv_sound_mode;
}
void _MIXUpdateTV(MixChannel* channel, sint32 index)
{
assert(index == 0);
bool updated_volume = false;
if ((channel->tv_mode & AX_UPDATE_MODE_80000000) != 0)
{
for (size_t i = 0; i < AX_MAX_NUM_BUS; ++i)
{
for (size_t j = 0; j < AX_TV_CHANNEL_COUNT; ++j)
{
channel->tv_volume[i][j].volume = channel->tv_volume[i][j].volume_target;
}
}
channel->tv_mode &= ~AX_UPDATE_MODE_80000000;
updated_volume = true;
}
if ((channel->tv_mode & AX_UPDATE_MODE_40000000_VOLUME) == 0)
{
if (!updated_volume)
return;
}
else
{
if (g_snd_user_data.device_info.tv_sound_mode == 0)
{
sint32 chan4 = channel->tv_channels[4];
if (chan4 < -0x78)
chan4 = -0x78;
const sint32 fader = channel->tv_control.fader;
channel->tv_volume[0][0].volume_target = __MIXTranslateVolume(chan4 + fader);
channel->tv_volume[0][1].volume_target = __MIXTranslateVolume(chan4 + fader);
channel->tv_volume[0][2].volume_target = 0;
channel->tv_volume[0][3].volume_target = 0;
channel->tv_volume[0][4].volume_target = 0;
channel->tv_volume[0][5].volume_target = 0;
for (int i = 0; i < 3; ++i)
{
const sint32 aux = channel->tv_control.aux[i];
if ((channel->tv_mode & (1 << i)) == 0)
{
channel->tv_volume[1 + i][0].volume_target = __MIXTranslateVolume(chan4 + fader + aux);
channel->tv_volume[1 + i][1].volume_target = __MIXTranslateVolume(chan4 + fader + aux);
}
else
{
channel->tv_volume[1 + i][0].volume_target = __MIXTranslateVolume(chan4 + aux);
channel->tv_volume[1 + i][1].volume_target = __MIXTranslateVolume(chan4 + aux);
}
channel->tv_volume[1 + i][2].volume_target = 0;
channel->tv_volume[1 + i][3].volume_target = 0;
channel->tv_volume[1 + i][4].volume_target = 0;
channel->tv_volume[1 + i][5].volume_target = 0;
}
channel->tv_mode &= ~AX_UPDATE_MODE_40000000_VOLUME;
channel->tv_mode |= AX_UPDATE_MODE_80000000;
}
else if (g_snd_user_data.device_info.tv_sound_mode < 3)
{
sint32 chan4 = channel->tv_channels[4];
if (chan4 < -0x78)
chan4 = -0x78;
const sint32 fader = channel->tv_control.fader;
const sint32 chan0 = channel->tv_channels[0];
const sint32 chan1 = channel->tv_channels[1];
channel->tv_volume[0][0].volume_target = __MIXTranslateVolume(chan4 + chan0 + fader);
channel->tv_volume[0][1].volume_target = __MIXTranslateVolume(chan4 + chan1 + fader);
channel->tv_volume[0][2].volume_target = 0;
channel->tv_volume[0][3].volume_target = 0;
channel->tv_volume[0][4].volume_target = 0;
channel->tv_volume[0][5].volume_target = 0;
for (int i = 0; i < 3; ++i)
{
const sint32 aux = channel->tv_control.aux[i];
if ((channel->tv_mode & (1 << i)) == 0)
{
channel->tv_volume[1 + i][0].volume_target = __MIXTranslateVolume(chan4 + chan0 + fader + aux);
channel->tv_volume[1 + i][1].volume_target = __MIXTranslateVolume(chan4 + chan1 + fader + aux);
}
else
{
channel->tv_volume[1 + i][0].volume_target = __MIXTranslateVolume(chan4 + chan0 + aux);
channel->tv_volume[1 + i][1].volume_target = __MIXTranslateVolume(chan4 + chan1 + aux);
}
channel->tv_volume[1 + i][2].volume_target = 0;
channel->tv_volume[1 + i][3].volume_target = 0;
channel->tv_volume[1 + i][4].volume_target = 0;
channel->tv_volume[1 + i][5].volume_target = 0;
}
channel->tv_mode &= ~AX_UPDATE_MODE_40000000_VOLUME;
channel->tv_mode |= AX_UPDATE_MODE_80000000;
}
else if (g_snd_user_data.device_info.tv_sound_mode == 3)
{
// TODO
}
else if (g_snd_user_data.device_info.tv_sound_mode == 4)
{
// TODO
}
else
{
channel->tv_mode &= ~AX_UPDATE_MODE_40000000_VOLUME;
channel->tv_mode |= AX_UPDATE_MODE_80000000;
}
}
AXCHMIX2 mix[AX_TV_CHANNEL_COUNT][AX_MAX_NUM_BUS];
for (size_t i = 0; i < AX_MAX_NUM_BUS; ++i)
{
for (size_t j = 0; j < AX_TV_CHANNEL_COUNT; ++j)
{
const sint16 target = channel->tv_volume[i][j].volume_target;
const sint16 volume = channel->tv_volume[i][j].volume;
mix[j][i].vol = volume;
mix[j][i].delta = (target - volume) / 96; // 32000HZ SAMPLES_3MS
}
}
AXSetVoiceDeviceMix(channel->voice.GetPtr(), AX_DEV_TV, index, (snd_core::AXCHMIX_DEPR*)&mix[0][0]);
}
void _MIXUpdateDRC(MixChannel* channel, sint32 index)
{
// todo
}
void _MIXUpdateRmt(MixChannel* channel, sint32 index)
{
// todo
}
void MIXInitChannel(AXVPB* voice, uint16 mode, uint16 input, uint16 aux1, uint16 aux2, uint16 aux3, uint16 pan, uint16 span, uint16 fader)
{
cemuLog_log(LogType::SoundAPI, "MIXInitChannel(0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x})", MEMPTR(voice).GetMPTR(), mode, input, aux1, aux2, aux3, pan, span, fader);
cemu_assert_debug(voice);
AXVoiceBegin(voice);
MIXAssignChannel(voice);
MIXInitInputControl(voice, input, mode);
const uint32 index = voice->index;
auto& channel = g_snd_user_data.mix_channel[index];
channel.tv_control.aux[0] = aux1;
channel.tv_control.aux[1] = aux2;
channel.tv_control.aux[2] = aux3;
channel.tv_control.pan = pan;
channel.tv_control.span = span;
channel.tv_control.fader = fader;
// channel.tv_control.lfe = lfe; // 0x1A -> not set?
channel.tv_mode = AX_UPDATE_MODE_40000007 & mode;
_MIXControl_SetDevicePan(&channel.tv_control, AX_DEV_TV, channel.tv_channels);
channel.tv_mode |= AX_UPDATE_MODE_40000000_VOLUME;
_MIXUpdateTV(&channel, 0);
AXVoiceEnd(voice);
}
void MIXAssignChannel(AXVPB* voice)
{
cemuLog_log(LogType::SoundAPI, "MIXAssignChannel(0x{:x})", MEMPTR(voice).GetMPTR());
cemu_assert_debug(voice);
AXVoiceBegin(voice);
const uint32 voice_index = voice->index;
auto channel = &g_snd_user_data.mix_channel[voice_index];
MIXResetChannelData(channel);
channel->voice = voice;
AXVoiceEnd(voice);
}
void MIXDRCInitChannel(AXVPB* voice, uint16 mode, uint16 vol1, uint16 vol2, uint16 vol3)
{
cemuLog_log(LogType::SoundAPI, "MIXDRCInitChannel(0x{:x}, 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x})", MEMPTR(voice).GetMPTR(), mode, vol1, vol2, vol3);
cemu_assert_debug(voice);
AXVoiceBegin(voice);
const uint32 index = voice->index;
auto& channel = g_snd_user_data.mix_channel[index];
_MIXChannelResetDRC(&channel, 0);
channel.drc_volume[1][1][1].volume = vol1;
channel.drc_volume[1][1][2].volume_target = vol2;
channel.drc_volume[1][1][3].volume_target = vol3;
channel.drc_mode[0] = AX_UPDATE_MODE_40000007 & mode;
_MIXControl_SetDevicePan(&channel.drc_control[0], AX_DEV_DRC, &channel.drc_channels[0][0]);
channel.drc_mode[0] |= AX_UPDATE_MODE_40000000_VOLUME;
_MIXUpdateDRC(&channel, 0);
AXVoiceEnd(voice);
}
void MIXSetInput(AXVPB* voice, uint16 input)
{
cemuLog_log(LogType::SoundAPI, "MIXSetInput(0x{:x}, 0x{:x})", MEMPTR(voice).GetMPTR(), input);
const uint32 voice_index = voice->index;
const auto channel = &g_snd_user_data.mix_channel[voice_index];
channel->input_level = input;
channel->update_mode |= AX_UPDATE_MODE_10000000;
}
void MIXUpdateSettings()
{
cemuLog_log(LogType::SoundAPI, "MIXUpdateSettings()");
if (!g_snd_user_data.initialized)
return;
if (g_snd_user_data.max_voices <= 0)
return;
for (sint32 i = 0; i < g_snd_user_data.max_voices; ++i)
{
auto& channel = g_snd_user_data.mix_channel[i];
if (!channel.voice)
continue;
const auto voice = channel.voice.GetPtr();
AXVoiceBegin(voice);
bool volume_updated = false;
if ((channel.update_mode & AX_UPDATE_MODE_20000000) != 0)
{
channel.volume.volume = channel.volume.volume_target;
channel.update_mode &= ~AX_UPDATE_MODE_20000000;
volume_updated = true;
}
if ((channel.update_mode & AX_UPDATE_MODE_10000000) == 0)
{
if (volume_updated)
{
AXPBVE ve;
ve.currentVolume = channel.volume.volume;
ve.currentDelta = (channel.volume.volume_target - channel.volume.volume) / 96;
AXSetVoiceVe(voice, &ve);
}
}
else
{
sint32 volume = 0;
if ((channel.update_mode & 8) == 0)
volume = __MIXTranslateVolume(channel.input_level);
channel.volume.volume_target = volume;
channel.update_mode &= ~AX_UPDATE_MODE_10000000;
channel.update_mode |= AX_UPDATE_MODE_20000000;
AXPBVE ve;
ve.currentVolume = channel.volume.volume;
ve.currentDelta = (channel.volume.volume_target - channel.volume.volume) / 96;
AXSetVoiceVe(voice, &ve);
}
_MIXUpdateTV(&channel, 0);
for (int i = 0; i < 2; ++i)
_MIXUpdateDRC(&channel, i);
// TODO remote mix
AXCHMIX2 mix[4];
for (int j = 0; j < 4; ++j)
{
AXSetVoiceDeviceMix(voice, AX_DEV_RMT, i, (snd_core::AXCHMIX_DEPR*)mix);
}
AXVoiceEnd(voice);
}
// TODO
}
void MIXSetDeviceSoundMode(uint32 device, uint32 mode)
{
cemuLog_log(LogType::SoundAPI, "MIXSetDeviceSoundMode(0x{:x}, 0x{:x})", device, mode);
cemu_assert_debug(device < AX_DEV_COUNT);
cemu_assert_debug(mode <= 4);
bool is_tv_device = false;
bool is_drc_device = false;
if (device == AX_DEV_TV)
{
g_snd_user_data.device_info.tv_sound_mode = mode;
is_tv_device = true;
}
else if (device == AX_DEV_DRC)
{
cemu_assert_debug(mode <= 2);
g_snd_user_data.device_info.drc_sound_mode = mode;
is_drc_device = true;
}
else if (device == AX_DEV_RMT)
{
cemu_assert_debug(mode == 0);
g_snd_user_data.device_info.rmt_sound_mode = mode;
}
else
{
cemuLog_log(LogType::SoundAPI, "ERROR: MIXSetDeviceSoundMode(0x{:x}, 0x{:x}) -> wrong device", device, mode);
}
for (sint32 i = 0; i < g_snd_user_data.max_voices; ++i)
{
auto& channel = g_snd_user_data.mix_channel[i];
if (!channel.voice)
continue;
const auto voice = channel.voice.GetPtr();
AXVoiceBegin(voice);
if (is_tv_device)
{
channel.tv_mode |= AX_UPDATE_MODE_40000000_VOLUME;
_MIXControl_SetDevicePan(&channel.tv_control, AX_DEV_TV, channel.tv_channels);
}
if (is_drc_device)
{
for (sint32 j = 0; j < AX_MAX_NUM_DRC; ++j)
{
channel.drc_mode[j] |= AX_UPDATE_MODE_40000000_VOLUME;
_MIXControl_SetDevicePan(&channel.drc_control[j], AX_DEV_DRC, channel.drc_channels[j]);
}
}
AXVoiceEnd(voice);
}
}
void MIXInitDeviceControl(AXVPB* voice, uint32 device_type, uint32 index, MixControl* control, uint32 mode)
{
cemuLog_log(LogType::SoundAPI, "MIXInitDeviceControl(0x{:0x}, 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x} )", MEMPTR(voice).GetMPTR(), device_type, index, MEMPTR(control).GetMPTR(), mode);
cemu_assert_debug(device_type < AX_DEV_COUNT);
cemu_assert_debug(voice);
cemu_assert_debug(control);
AXVoiceBegin(voice);
const uint32 voice_index = voice->index;
auto& channel = g_snd_user_data.mix_channel[voice_index];
channel.voice = voice;
if (device_type == AX_DEV_TV)
{
cemu_assert_debug(index == 0);
_MIXChannelResetTV(&channel, index);
memcpy(&channel.tv_control, control, sizeof(MixControl));
_MIXControl_SetDevicePan(&channel.tv_control, device_type, channel.tv_channels);
channel.tv_mode |= AX_UPDATE_MODE_40000000_VOLUME;
_MIXUpdateTV(&channel, index);
}
else if (device_type == AX_DEV_DRC)
{
cemu_assert_debug(index < 2);
_MIXChannelResetDRC(&channel, index);
memcpy(&channel.drc_control[index], control, sizeof(MixControl));
_MIXControl_SetDevicePan(&channel.drc_control[index], device_type, channel.drc_channels[index]);
channel.drc_mode[index] |= AX_UPDATE_MODE_40000000_VOLUME;
_MIXUpdateDRC(&channel, index);
}
else if (device_type == AX_DEV_RMT)
{
cemu_assert_debug(index < 4);
_MIXChannelResetRmt(&channel, index);
memcpy(&channel.rmt_control[index], control, sizeof(MixControl));
_MIXControl_SetDevicePan(&channel.rmt_control[index], device_type, channel.rmt_channels[index]);
channel.rmt_mode[index] = mode & 0xf;
_MIXUpdateRmt(&channel, index);
}
AXVoiceEnd(voice);
}
void MIXInitInputControl(AXVPB* voice, uint16 input, uint32 mode)
{
cemuLog_log(LogType::SoundAPI, "MIXInitInputControl(0x{:x}, 0x{:x}, 0x{:x} )", MEMPTR(voice).GetMPTR(), input, mode);
cemu_assert_debug(voice);
AXVoiceBegin(voice);
const uint32 voice_index = voice->index;
auto& channel = g_snd_user_data.mix_channel[voice_index];
mode &= 8;
mode |= AX_UPDATE_MODE_10000000;
channel.update_mode = mode;
channel.input_level = input;
AXVoiceEnd(voice);
}
void MIXSetDeviceFader(AXVPB* vpb, uint32 device, uint32 deviceIndex, sint16 newFader)
{
// not well tested
cemu_assert(device < AX_DEV_COUNT);
MixChannel& mixChannel = g_snd_user_data.mix_channel[vpb->index];
AXVoiceBegin(vpb);
MixControl& mixControl = mixChannel.GetMixControl(device, deviceIndex);
MixMode& mixMode = mixChannel.GetMode(device, deviceIndex);
if (mixControl.fader == newFader)
{
AXVoiceEnd(vpb);
return;
}
mixControl.fader = newFader;
mixMode |= AX_UPDATE_MODE_40000000_VOLUME;
AXVoiceEnd(vpb);
}
void MIXSetDevicePan(AXVPB* vpb, uint32 device, uint32 deviceIndex, sint16 newPan)
{
// not well tested
cemu_assert(device < AX_DEV_COUNT);
MixChannel& mixChannel = g_snd_user_data.mix_channel[vpb->index];
AXVoiceBegin(vpb);
MixControl& mixControl = mixChannel.GetMixControl(device, deviceIndex);
MixMode& mixMode = mixChannel.GetMode(device, deviceIndex);
sint16* deviceChannels = mixChannel.GetChannels(device, deviceIndex);
if (mixControl.fader == newPan)
{
AXVoiceEnd(vpb);
return;
}
mixControl.pan = newPan;
_MIXControl_SetDevicePan(&mixControl, device, deviceChannels);
mixMode |= AX_UPDATE_MODE_40000000_VOLUME;
AXVoiceEnd(vpb);
}
struct AXPBADPCM
{
uint16be table[8][2]; // 0x00
uint16be gain;
uint16be predicator;
uint16be yn1;
uint16be yn2;
};
struct AXPBADPCMLOOP
{
uint16be predicator; // 0x00
uint16be yn1; // 0x02
uint16be yn2; // 0x04
};
struct SPAdpcmEntry
{
AXPBADPCM adpcm;
AXPBADPCMLOOP adpcmLoop;
};
struct SPSoundEntry
{
uint32be type; // 0x00
uint32be sampleRate; // 0x04
uint32be loopAddress; // 0x08
uint32be loopEndAddress; // 0x0C
uint32be endOffset; // 0x10
uint32be currentOffset; // 0x14
MEMPTR<SPAdpcmEntry> adpcmEntry; // 0x18
};
static_assert(sizeof(SPSoundEntry) == 0x1C);
struct SPSoundTable
{
uint32be count;
SPSoundEntry entries[1];
};
void SPInitSoundTable(SPSoundTable* soundTable, uint8* samples, uint32be* endOffsetPtr)
{
cemuLog_log(LogType::SoundAPI, "SPInitSoundTable(0x{:x}, 0x{:x}, 0x{:x} )", MEMPTR(soundTable).GetMPTR(), MEMPTR(samples).GetMPTR(), MEMPTR(endOffsetPtr).GetMPTR());
if (!soundTable)
return;
if (!samples)
return;
uint32be endOffset = 0;
for(uint32 i = 0; i < soundTable->count; ++i)
{
auto& entryPtr = soundTable->entries[i];
if(entryPtr.type == 0)
{
entryPtr.loopAddress = entryPtr.currentOffset;
entryPtr.loopEndAddress = 0;
uint32be tmp = entryPtr.endOffset >> 1;
if (tmp > endOffset)
endOffset = tmp;
/// ???
}
else if (entryPtr.type == 1)
{
uint32be tmp = entryPtr.endOffset >> 1;
if (tmp > endOffset)
endOffset = tmp;
/// ???
}
else if (entryPtr.type == 2)
{
entryPtr.loopAddress = entryPtr.currentOffset;
entryPtr.loopEndAddress = 0;
uint32be tmp = entryPtr.endOffset << 1;
if (tmp > endOffset)
endOffset = tmp;
}
else if (entryPtr.type == 3)
{
uint32be tmp = entryPtr.endOffset << 1;
if (tmp > endOffset)
endOffset = tmp;
}
else if (entryPtr.type == 4)
{
entryPtr.loopAddress = entryPtr.currentOffset;
entryPtr.loopEndAddress = 0;
if (entryPtr.endOffset > endOffset)
endOffset = entryPtr.endOffset;
}
else if (entryPtr.type == 5)
{
if (entryPtr.endOffset > endOffset)
endOffset = entryPtr.endOffset;
}
}
if (endOffsetPtr)
*endOffsetPtr = endOffset;
}
SPSoundEntry* SPGetSoundEntry(SPSoundTable* soundTable, uint32 index)
{
cemuLog_log(LogType::SoundAPI, "SPGetSoundEntry(0x{:x}, {})", MEMPTR(soundTable).GetMPTR(), index);
if (!soundTable)
return nullptr;
if (soundTable->count <= index)
return nullptr;
return &soundTable->entries[index];
}
MEMPTR<void> s_fxAlloc = nullptr;
MEMPTR<void> s_fxFree = nullptr;
void _AXDefaultHook_alloc(PPCInterpreter_t* hCPU)
{
uint32 size = hCPU->gpr[3];
MEMPTR<void> mem = coreinit::_weak_MEMAllocFromDefaultHeap(size);
osLib_returnFromFunction(hCPU, mem.GetMPTR());
}
void _AXDefaultHook_free(PPCInterpreter_t* hCPU)
{
MEMPTR<void> mem{ hCPU->gpr[3] };
return coreinit::_weak_MEMFreeToDefaultHeap(mem.GetPtr());
}
void AXFXInitDefaultHooks()
{
// todo - this should only be applied when the library is loaded? MIXInit() does not affect this?
if (!s_fxAlloc)
{
s_fxAlloc = RPLLoader_MakePPCCallable(_AXDefaultHook_alloc);
s_fxFree = RPLLoader_MakePPCCallable(_AXDefaultHook_free);
}
}
void AXFXSetHooks(void* allocFunc, void* freeFunc)
{
s_fxAlloc = allocFunc;
s_fxFree = freeFunc;
}
void AXFXGetHooks(MEMPTR<void>* allocFuncOut, MEMPTR<void>* freeFuncOut)
{
*allocFuncOut = s_fxAlloc;
*freeFuncOut = s_fxFree;
}
void* AXFXInternalAlloc(uint32 size, bool clearToZero)
{
if (s_fxAlloc)
{
MEMPTR<void> mem{ PPCCoreCallback(s_fxAlloc, size) };
if (clearToZero)
memset(mem.GetPtr(), 0, size);
return mem.GetPtr();
}
void* mem = coreinit::_weak_MEMAllocFromDefaultHeapEx(size, 4);
if (clearToZero)
memset(mem, 0, size);
return mem;
}
void AXFXInternalFree(void* mem)
{
if (s_fxFree)
{
PPCCoreCallback(s_fxFree, mem);
return;
}
coreinit::_weak_MEMFreeToDefaultHeap(mem);
}
/* AUX callback */
struct AUXCBSAMPLEDATA
{
MEMPTR<sint32be> channelSamples[6];
};
bool gUnsupportedSoundEffectWarning = false;
void PrintUnsupportedSoundEffectWarning()
{
if (gUnsupportedSoundEffectWarning)
return;
cemuLog_log(LogType::Force, "The currently running title is trying to utilize an unsupported audio effect");
cemuLog_log(LogType::Force, "To emulate these correctly, place snd_user.rpl and snduser2.rpl from the original Wii U firmware in /cafeLibs/ folder");
gUnsupportedSoundEffectWarning = true;
}
void __UnimplementedFXCallback(AUXCBSAMPLEDATA* auxSamples, size_t sampleCount, bool clearCh0, bool clearCh1, bool clearCh2, bool clearCh3, bool clearCh4, bool clearCh5)
{
PrintUnsupportedSoundEffectWarning();
bool clearChannel[6] = { clearCh0, clearCh1, clearCh2, clearCh3, clearCh4, clearCh5 };
for (sint32 channel = 0; channel < 6; channel++)
{
if(!clearChannel[channel])
continue;
sint32be* channelPtr = auxSamples->channelSamples[channel].GetPtr();
while (sampleCount)
{
*channelPtr = 0;
channelPtr++;
sampleCount--;
}
}
}
/* AXFXReverbHi */
struct AXFXReverbHiData
{
// todo - implement
uint32be placeholder;
};
void AXFXReverbHiInit(AXFXReverbHiData* param)
{
cemuLog_log(LogType::Force, "AXFXReverbHiInit - stub");
}
void AXFXReverbHiSettings(AXFXReverbHiData* param)
{
cemuLog_log(LogType::Force, "AXFXReverbHiSettings - stub");
}
void AXFXReverbHiShutdown(AXFXReverbHiData* param)
{
cemuLog_log(LogType::Force, "AXFXReverbHiShutdown - stub");
}
void AXFXReverbHiCallback(AUXCBSAMPLEDATA* auxSamples, AXFXReverbHiData* reverbHi)
{
// todo - implement me
__UnimplementedFXCallback(auxSamples, 96, true, true, true, false, false, false);
}
/* AXFXMultiChReverb */
struct AXFXMultiChReverbData
{
// todo - implement
uint32 placeholder;
};
void AXFXMultiChReverbInit(AXFXMultiChReverbData* param, int ukn2, int ukn3)
{
cemuLog_log(LogType::Force, "AXFXMultiChReverbInit (Stubbed)");
}
void AXFXMultiChReverbSettingsUpdate(AXFXMultiChReverbData* param)
{
// todo
}
void AXFXMultiChReverbShutdown(AXFXMultiChReverbData* param)
{
// todo
}
void AXFXMultiChReverbCallback(AUXCBSAMPLEDATA* auxSamples, AXFXMultiChReverbData* reverbHi, AXAUXCBCHANNELINFO* auxInfo)
{
// todo - implement me
__UnimplementedFXCallback(auxSamples, auxInfo->numSamples, true, true, true, true, true, true);
}
/* AXFXReverbStd */
struct AXFXReverbStdData
{
uint32be placeholder;
};
uint32 AXFXReverbStdExpGetMemSize(AXFXReverbStdData* reverbParam)
{
return 0xC; // placeholder size
}
bool AXFXReverbStdExpInit(AXFXReverbStdData* reverbParam)
{
return true;
}
void AXFXReverbStdExpShutdown(AXFXReverbStdData* reverbParam)
{
}
void AXFXReverbStdExpCallback(AUXCBSAMPLEDATA* auxSamples, AXFXReverbStdData* reverbData)
{
// todo - implement me
__UnimplementedFXCallback(auxSamples, 96, true, true, true, false, false, false);
}
void Initialize()
{
/* snd_user */
cafeExportRegister("snd_user", MIXInit, LogType::SoundAPI);
cafeExportRegister("snd_user", MIXSetSoundMode, LogType::SoundAPI);
cafeExportRegister("snd_user", MIXGetSoundMode, LogType::SoundAPI);
cafeExportRegister("snd_user", MIXInitChannel, LogType::SoundAPI);
cafeExportRegister("snd_user", MIXAssignChannel, LogType::SoundAPI);
cafeExportRegister("snd_user", MIXDRCInitChannel, LogType::SoundAPI);
cafeExportRegister("snd_user", MIXSetInput, LogType::SoundAPI);
cafeExportRegister("snd_user", MIXUpdateSettings, LogType::SoundAPI);
cafeExportRegister("snd_user", MIXSetDeviceSoundMode, LogType::SoundAPI);
cafeExportRegister("snd_user", MIXSetDeviceFader, LogType::SoundAPI);
cafeExportRegister("snd_user", MIXSetDevicePan, LogType::SoundAPI);
cafeExportRegister("snd_user", MIXInitDeviceControl, LogType::SoundAPI);
cafeExportRegister("snd_user", MIXInitInputControl, LogType::SoundAPI);
cafeExportRegister("snd_user", SPInitSoundTable, LogType::SoundAPI);
cafeExportRegister("snd_user", SPGetSoundEntry, LogType::SoundAPI);
//cafeExportRegister("snd_user", SPPrepareSound);
cafeExportRegister("snd_user", AXFXSetHooks, LogType::SoundAPI);
cafeExportRegister("snd_user", AXFXGetHooks, LogType::SoundAPI);
cafeExportRegister("snd_user", AXFXReverbHiInit, LogType::SoundAPI);
cafeExportRegister("snd_user", AXFXReverbHiSettings, LogType::SoundAPI);
cafeExportRegister("snd_user", AXFXReverbHiShutdown, LogType::SoundAPI);
cafeExportRegister("snd_user", AXFXReverbHiCallback, LogType::SoundAPI);
cafeExportRegister("snd_user", AXFXMultiChReverbInit, LogType::SoundAPI);
cafeExportRegister("snd_user", AXFXMultiChReverbSettingsUpdate, LogType::SoundAPI);
cafeExportRegister("snd_user", AXFXMultiChReverbShutdown, LogType::SoundAPI);
cafeExportRegister("snd_user", AXFXMultiChReverbCallback, LogType::SoundAPI);
/* snduser2 */
cafeExportRegister("snduser2", MIXInit, LogType::SoundAPI);
cafeExportRegister("snduser2", MIXSetSoundMode, LogType::SoundAPI);
cafeExportRegister("snduser2", MIXGetSoundMode, LogType::SoundAPI);
cafeExportRegister("snduser2", MIXInitChannel, LogType::SoundAPI);
cafeExportRegister("snduser2", MIXAssignChannel, LogType::SoundAPI);
cafeExportRegister("snduser2", MIXDRCInitChannel, LogType::SoundAPI);
cafeExportRegister("snduser2", MIXSetInput, LogType::SoundAPI);
cafeExportRegister("snduser2", MIXUpdateSettings, LogType::SoundAPI);
cafeExportRegister("snduser2", MIXSetDeviceSoundMode, LogType::SoundAPI);
cafeExportRegister("snduser2", MIXSetDeviceFader, LogType::SoundAPI);
cafeExportRegister("snduser2", MIXSetDevicePan, LogType::SoundAPI);
cafeExportRegister("snduser2", MIXInitDeviceControl, LogType::SoundAPI);
cafeExportRegister("snduser2", MIXInitInputControl, LogType::SoundAPI);
cafeExportRegister("snduser2", AXFXSetHooks, LogType::Placeholder);
cafeExportRegister("snduser2", AXFXGetHooks, LogType::Placeholder);
cafeExportRegister("snduser2", AXFXReverbStdExpGetMemSize, LogType::Placeholder);
cafeExportRegister("snduser2", AXFXReverbStdExpInit, LogType::Placeholder);
cafeExportRegister("snduser2", AXFXReverbStdExpShutdown, LogType::Placeholder);
cafeExportRegister("snduser2", AXFXReverbStdExpCallback, LogType::Placeholder);
cafeExportRegister("snduser2", AXFXReverbHiInit, LogType::SoundAPI);
cafeExportRegister("snduser2", AXFXReverbHiSettings, LogType::SoundAPI);
cafeExportRegister("snduser2", AXFXReverbHiShutdown, LogType::SoundAPI);
cafeExportRegister("snduser2", AXFXReverbHiCallback, LogType::SoundAPI);
cafeExportRegister("snduser2", AXFXMultiChReverbInit, LogType::SoundAPI);
cafeExportRegister("snduser2", AXFXMultiChReverbSettingsUpdate, LogType::SoundAPI);
cafeExportRegister("snduser2", AXFXMultiChReverbShutdown, LogType::SoundAPI);
cafeExportRegister("snduser2", AXFXMultiChReverbCallback, LogType::SoundAPI);
}
}
}
| 43,888
|
C++
|
.cpp
| 1,037
| 37.720347
| 238
| 0.68599
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,132
|
nn_ec.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_ec/nn_ec.cpp
|
#include "Cafe/OS/common/OSCommon.h"
typedef struct
{
/* +0x00 */ uint8 ukn00[0x10];
/* +0x10 */ uint8 ukn10[0x0C];
/* +0x2C */ uint8 ukn2C[0x10]; // currency string?
/* +0x3C */ uint32 ukn3C; // money amount?
// size of struct is 0x40
}nnEcUknMoneyStruct_t;
void nnEcExport___ct__Q3_2nn2ec5MoneyFPCcN21(PPCInterpreter_t* hCPU)
{
debug_printf("nn_ec.__ct__Q3_2nn2ec5MoneyFPCcN21(0x%08x, ...)\n", hCPU->gpr[3]);
nnEcUknMoneyStruct_t* moneyStruct = (nnEcUknMoneyStruct_t*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
// todo -> Setup struct
osLib_returnFromFunction(hCPU, memory_getVirtualOffsetFromPointer(moneyStruct));
}
/*
* Load E commerce functions (E-Shop stuff)
*/
void nnEc_load()
{
osLib_addFunction("nn_ec", "__ct__Q3_2nn2ec5MoneyFPCcN21", nnEcExport___ct__Q3_2nn2ec5MoneyFPCcN21);
}
| 814
|
C++
|
.cpp
| 23
| 33.695652
| 109
| 0.730038
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,133
|
ntag.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/ntag/ntag.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/libs/ntag/ntag.h"
#include "Cafe/OS/libs/nfc/nfc.h"
#include "Cafe/OS/libs/coreinit/coreinit_IPC.h"
#include "Cafe/IOSU/ccr_nfc/iosu_ccr_nfc.h"
namespace ntag
{
struct NTAGWriteData
{
uint16 size;
uint8 data[0x1C8];
nfc::NFCUid uid;
nfc::NFCUid uidMask;
};
NTAGWriteData gWriteData[2];
bool ccrNfcOpened = false;
IOSDevHandle gCcrNfcHandle;
NTAGFormatSettings gFormatSettings;
MPTR gDetectCallbacks[2];
MPTR gAbortCallbacks[2];
MPTR gReadCallbacks[2];
MPTR gWriteCallbacks[2];
sint32 __NTAGConvertNFCResult(sint32 result)
{
if (result == NFC_RESULT_SUCCESS)
{
return NTAG_RESULT_SUCCESS;
}
switch (result & NFC_RESULT_MASK)
{
case NFC_RESULT_UNINITIALIZED:
return NTAG_RESULT_UNINITIALIZED;
case NFC_RESULT_INVALID_STATE:
return NTAG_RESULT_INVALID_STATE;
case NFC_RESULT_NO_TAG:
return NTAG_RESULT_NO_TAG;
case NFC_RESULT_UID_MISMATCH:
return NTAG_RESULT_UID_MISMATCH;
}
// TODO convert more errors
return NTAG_RESULT_INVALID;
}
sint32 NTAGInit(uint32 chan)
{
return NTAGInitEx(chan);
}
sint32 NTAGInitEx(uint32 chan)
{
sint32 result = nfc::NFCInitEx(chan, 1);
return __NTAGConvertNFCResult(result);
}
sint32 NTAGShutdown(uint32 chan)
{
sint32 result = nfc::NFCShutdown(chan);
if (ccrNfcOpened)
{
coreinit::IOS_Close(gCcrNfcHandle);
ccrNfcOpened = false;
}
gDetectCallbacks[chan] = MPTR_NULL;
gAbortCallbacks[chan] = MPTR_NULL;
gReadCallbacks[chan] = MPTR_NULL;
gWriteCallbacks[chan] = MPTR_NULL;
return __NTAGConvertNFCResult(result);
}
bool NTAGIsInit(uint32 chan)
{
return nfc::NFCIsInit(chan);
}
void NTAGProc(uint32 chan)
{
nfc::NFCProc(chan);
}
void NTAGSetFormatSettings(NTAGFormatSettings* formatSettings)
{
gFormatSettings.version = formatSettings->version;
gFormatSettings.makerCode = _swapEndianU32(formatSettings->makerCode);
gFormatSettings.identifyCode = _swapEndianU32(formatSettings->identifyCode);
}
void __NTAGDetectCallback(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(chan, 0);
ppcDefineParamU32(hasTag, 1);
ppcDefineParamPtr(context, void, 2);
cemuLog_log(LogType::NTAG, "__NTAGDetectCallback: {} {} {}", chan, hasTag, context);
PPCCoreCallback(gDetectCallbacks[chan], chan, hasTag, context);
osLib_returnFromFunction(hCPU, 0);
}
void NTAGSetTagDetectCallback(uint32 chan, MPTR callback, void* context)
{
cemu_assert(chan < 2);
gDetectCallbacks[chan] = callback;
nfc::NFCSetTagDetectCallback(chan, RPLLoader_MakePPCCallable(__NTAGDetectCallback), context);
}
void __NTAGAbortCallback(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(chan, 0);
ppcDefineParamS32(error, 1);
ppcDefineParamPtr(context, void, 2);
PPCCoreCallback(gAbortCallbacks[chan], chan, __NTAGConvertNFCResult(error), context);
osLib_returnFromFunction(hCPU, 0);
}
sint32 NTAGAbort(uint32 chan, MPTR callback, void* context)
{
cemu_assert(chan < 2);
// TODO is it normal that Rumble U calls this?
gAbortCallbacks[chan] = callback;
sint32 result = nfc::NFCAbort(chan, RPLLoader_MakePPCCallable(__NTAGAbortCallback), context);
return __NTAGConvertNFCResult(result);
}
bool __NTAGRawDataToNfcData(iosu::ccr_nfc::CCRNFCCryptData* raw, iosu::ccr_nfc::CCRNFCCryptData* nfc)
{
memcpy(nfc, raw, sizeof(iosu::ccr_nfc::CCRNFCCryptData));
if (raw->version == 0)
{
nfc->version = 0;
nfc->dataSize = 0x1C8;
nfc->seedOffset = 0x25;
nfc->keyGenSaltOffset = 0x1A8;
nfc->uuidOffset = 0x198;
nfc->unfixedInfosOffset = 0x28;
nfc->unfixedInfosSize = 0x120;
nfc->lockedSecretOffset = 0x168;
nfc->lockedSecretSize = 0x30;
nfc->unfixedInfosHmacOffset = 0;
nfc->lockedSecretHmacOffset = 0x148;
}
else if (raw->version == 2)
{
nfc->version = 2;
nfc->dataSize = 0x208;
nfc->seedOffset = 0x29;
nfc->keyGenSaltOffset = 0x1E8;
nfc->uuidOffset = 0x1D4;
nfc->unfixedInfosOffset = 0x2C;
nfc->unfixedInfosSize = 0x188;
nfc->lockedSecretOffset = 0x1DC;
nfc->lockedSecretSize = 0;
nfc->unfixedInfosHmacOffset = 0x8;
nfc->lockedSecretHmacOffset = 0x1B4;
memcpy(nfc->data + 0x1d4, raw->data, 0x8);
memcpy(nfc->data, raw->data + 0x8, 0x8);
memcpy(nfc->data + 0x28, raw->data + 0x10, 0x4);
memcpy(nfc->data + nfc->unfixedInfosOffset, raw->data + 0x14, 0x20);
memcpy(nfc->data + nfc->lockedSecretHmacOffset, raw->data + 0x34, 0x20);
memcpy(nfc->data + nfc->lockedSecretOffset, raw->data + 0x54, 0xC);
memcpy(nfc->data + nfc->keyGenSaltOffset, raw->data + 0x60, 0x20);
memcpy(nfc->data + nfc->unfixedInfosHmacOffset, raw->data + 0x80, 0x20);
memcpy(nfc->data + nfc->unfixedInfosOffset + 0x20, raw->data + 0xa0, 0x168);
memcpy(nfc->data + 0x208, raw->data + 0x208, 0x14);
}
else
{
return false;
}
return true;
}
bool __NTAGNfcDataToRawData(iosu::ccr_nfc::CCRNFCCryptData* nfc, iosu::ccr_nfc::CCRNFCCryptData* raw)
{
memcpy(raw, nfc, sizeof(iosu::ccr_nfc::CCRNFCCryptData));
if (nfc->version == 0)
{
raw->version = 0;
raw->dataSize = 0x1C8;
raw->seedOffset = 0x25;
raw->keyGenSaltOffset = 0x1A8;
raw->uuidOffset = 0x198;
raw->unfixedInfosOffset = 0x28;
raw->unfixedInfosSize = 0x120;
raw->lockedSecretOffset = 0x168;
raw->lockedSecretSize = 0x30;
raw->unfixedInfosHmacOffset = 0;
raw->lockedSecretHmacOffset = 0x148;
}
else if (nfc->version == 2)
{
raw->version = 2;
raw->dataSize = 0x208;
raw->seedOffset = 0x11;
raw->keyGenSaltOffset = 0x60;
raw->uuidOffset = 0;
raw->unfixedInfosOffset = 0x14;
raw->unfixedInfosSize = 0x188;
raw->lockedSecretOffset = 0x54;
raw->lockedSecretSize = 0xC;
raw->unfixedInfosHmacOffset = 0x80;
raw->lockedSecretHmacOffset = 0x34;
memcpy(raw->data + 0x8, nfc->data, 0x8);
memcpy(raw->data + raw->unfixedInfosHmacOffset, nfc->data + 0x8, 0x20);
memcpy(raw->data + 0x10, nfc->data + 0x28, 0x4);
memcpy(raw->data + raw->unfixedInfosOffset, nfc->data + 0x2C, 0x20);
memcpy(raw->data + 0xa0, nfc->data + 0x4C, 0x168);
memcpy(raw->data + raw->lockedSecretHmacOffset, nfc->data + 0x1B4, 0x20);
memcpy(raw->data + raw->uuidOffset, nfc->data + 0x1D4, 0x8);
memcpy(raw->data + raw->lockedSecretOffset, nfc->data + 0x1DC, 0xC);
memcpy(raw->data + raw->keyGenSaltOffset, nfc->data + 0x1E8, 0x20);
memcpy(raw->data + 0x208, nfc->data + 0x208, 0x14);
}
else
{
return false;
}
return true;
}
sint32 __NTAGDecryptData(void* decryptedData, const void* rawData)
{
StackAllocator<iosu::ccr_nfc::CCRNFCCryptData> nfcRawData, nfcInData, nfcOutData;
if (!ccrNfcOpened)
{
gCcrNfcHandle = coreinit::IOS_Open("/dev/ccr_nfc", 0);
}
// Prepare nfc buffer
nfcRawData->version = 0;
memcpy(nfcRawData->data, rawData, 0x1C8);
__NTAGRawDataToNfcData(nfcRawData.GetPointer(), nfcInData.GetPointer());
// Decrypt
sint32 result = coreinit::IOS_Ioctl(gCcrNfcHandle, 2, nfcInData.GetPointer(), sizeof(iosu::ccr_nfc::CCRNFCCryptData), nfcOutData.GetPointer(), sizeof(iosu::ccr_nfc::CCRNFCCryptData));
// Unpack nfc buffer
__NTAGNfcDataToRawData(nfcOutData.GetPointer(), nfcRawData.GetPointer());
memcpy(decryptedData, nfcRawData->data, 0x1C8);
// Convert result
if (result == CCR_NFC_INVALID_UNFIXED_INFOS)
{
return -0x2708;
}
else if (result == CCR_NFC_INVALID_LOCKED_SECRET)
{
return -0x2707;
}
return result;
}
sint32 __NTAGValidateHeaders(NTAGNoftHeader* noftHeader, NTAGInfoHeader* infoHeader, NTAGAreaHeader* rwHeader, NTAGAreaHeader* roHeader)
{
if (infoHeader->formatVersion != gFormatSettings.version || noftHeader->version != 0x1)
{
cemuLog_log(LogType::Force, "Invalid format version");
return -0x2710;
}
if (_swapEndianU32(noftHeader->magic) != 0x4E4F4654 /* 'NOFT' */ ||
_swapEndianU16(rwHeader->magic) != 0x5257 /* 'RW' */ ||
_swapEndianU16(roHeader->magic) != 0x524F /* 'RO' */)
{
cemuLog_log(LogType::Force, "Invalid header magic");
return -0x270F;
}
if (_swapEndianU32(rwHeader->makerCode) != gFormatSettings.makerCode ||
_swapEndianU32(roHeader->makerCode) != gFormatSettings.makerCode)
{
cemuLog_log(LogType::Force, "Invalid maker code");
return -0x270E;
}
if (infoHeader->formatVersion != 0 &&
(_swapEndianU32(rwHeader->identifyCode) != gFormatSettings.identifyCode ||
_swapEndianU32(roHeader->identifyCode) != gFormatSettings.identifyCode))
{
cemuLog_log(LogType::Force, "Invalid identify code");
return -0x2709;
}
if (_swapEndianU16(rwHeader->size) + _swapEndianU16(roHeader->size) != 0x130)
{
cemuLog_log(LogType::Force, "Invalid data size");
return -0x270D;
}
return 0;
}
sint32 __NTAGParseHeaders(const uint8* data, NTAGNoftHeader* noftHeader, NTAGInfoHeader* infoHeader, NTAGAreaHeader* rwHeader, NTAGAreaHeader* roHeader)
{
memcpy(noftHeader, data + 0x20, sizeof(NTAGNoftHeader));
memcpy(infoHeader, data + 0x198, sizeof(NTAGInfoHeader));
cemu_assert(_swapEndianU16(infoHeader->rwHeaderOffset) + sizeof(NTAGAreaHeader) < 0x200);
cemu_assert(_swapEndianU16(infoHeader->roHeaderOffset) + sizeof(NTAGAreaHeader) < 0x200);
memcpy(rwHeader, data + _swapEndianU16(infoHeader->rwHeaderOffset), sizeof(NTAGAreaHeader));
memcpy(roHeader, data + _swapEndianU16(infoHeader->roHeaderOffset), sizeof(NTAGAreaHeader));
return __NTAGValidateHeaders(noftHeader, infoHeader, rwHeader, roHeader);
}
sint32 __NTAGParseData(void* rawData, void* rwData, void* roData, nfc::NFCUid* uid, uint32 lockedDataSize, NTAGNoftHeader* noftHeader, NTAGInfoHeader* infoHeader, NTAGAreaHeader* rwHeader, NTAGAreaHeader* roHeader)
{
uint8 decryptedData[0x1C8];
sint32 result = __NTAGDecryptData(decryptedData, rawData);
if (result < 0)
{
return result;
}
result = __NTAGParseHeaders(decryptedData, noftHeader, infoHeader, rwHeader, roHeader);
if (result < 0)
{
return result;
}
if (_swapEndianU16(roHeader->size) + 0x70 != lockedDataSize)
{
cemuLog_log(LogType::Force, "Invalid locked area size");
return -0x270C;
}
if (memcmp(infoHeader->uid.uid, uid->uid, sizeof(nfc::NFCUid)) != 0)
{
cemuLog_log(LogType::Force, "UID mismatch");
return -0x270B;
}
cemu_assert(_swapEndianU16(rwHeader->offset) + _swapEndianU16(rwHeader->size) < 0x200);
cemu_assert(_swapEndianU16(roHeader->offset) + _swapEndianU16(roHeader->size) < 0x200);
memcpy(rwData, decryptedData + _swapEndianU16(rwHeader->offset), _swapEndianU16(rwHeader->size));
memcpy(roData, decryptedData + _swapEndianU16(roHeader->offset), _swapEndianU16(roHeader->size));
return 0;
}
void __NTAGReadCallback(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(chan, 0);
ppcDefineParamS32(error, 1);
ppcDefineParamPtr(uid, nfc::NFCUid, 2);
ppcDefineParamU32(readOnly, 3);
ppcDefineParamU32(dataSize, 4);
ppcDefineParamPtr(data, void, 5);
ppcDefineParamU32(lockedDataSize, 6);
ppcDefineParamPtr(lockedData, void, 7);
ppcDefineParamPtr(context, void, 8);
uint8 rawData[0x1C8]{};
StackAllocator<NTAGData> readResult;
StackAllocator<uint8, 0x1C8> rwData;
StackAllocator<uint8, 0x1C8> roData;
NTAGNoftHeader noftHeader;
NTAGInfoHeader infoHeader;
NTAGAreaHeader rwHeader;
NTAGAreaHeader roHeader;
readResult->readOnly = readOnly;
error = __NTAGConvertNFCResult(error);
if (error == 0)
{
memset(rwData.GetPointer(), 0, 0x1C8);
memset(roData.GetPointer(), 0, 0x1C8);
// Copy raw and locked data into a contigous buffer
memcpy(rawData, data, dataSize);
memcpy(rawData + dataSize, lockedData, lockedDataSize);
error = __NTAGParseData(rawData, rwData.GetPointer(), roData.GetPointer(), uid, lockedDataSize, &noftHeader, &infoHeader, &rwHeader, &roHeader);
if (error == 0)
{
memcpy(readResult->uid.uid, uid->uid, sizeof(uid->uid));
readResult->rwInfo.data = _swapEndianU32(rwData.GetMPTR());
readResult->roInfo.data = _swapEndianU32(roData.GetMPTR());
readResult->rwInfo.makerCode = rwHeader.makerCode;
readResult->rwInfo.size = rwHeader.size;
readResult->roInfo.makerCode = roHeader.makerCode;
readResult->rwInfo.identifyCode = rwHeader.identifyCode;
readResult->roInfo.identifyCode = roHeader.identifyCode;
readResult->formatVersion = infoHeader.formatVersion;
readResult->roInfo.size = roHeader.size;
cemuLog_log(LogType::NTAG, "__NTAGReadCallback: {} {} {}", chan, error, context);
PPCCoreCallback(gReadCallbacks[chan], chan, 0, readResult.GetPointer(), context);
osLib_returnFromFunction(hCPU, 0);
return;
}
}
if (uid)
{
memcpy(readResult->uid.uid, uid->uid, sizeof(uid->uid));
}
readResult->roInfo.size = 0;
readResult->rwInfo.size = 0;
readResult->roInfo.data = MPTR_NULL;
readResult->formatVersion = 0;
readResult->rwInfo.data = MPTR_NULL;
cemuLog_log(LogType::NTAG, "__NTAGReadCallback: {} {} {}", chan, error, context);
PPCCoreCallback(gReadCallbacks[chan], chan, error, readResult.GetPointer(), context);
osLib_returnFromFunction(hCPU, 0);
}
sint32 NTAGRead(uint32 chan, uint32 timeout, nfc::NFCUid* uid, nfc::NFCUid* uidMask, MPTR callback, void* context)
{
cemu_assert(chan < 2);
gReadCallbacks[chan] = callback;
nfc::NFCUid _uid{}, _uidMask{};
if (uid && uidMask)
{
memcpy(&_uid, uid, sizeof(*uid));
memcpy(&_uidMask, uidMask, sizeof(*uidMask));
}
sint32 result = nfc::NFCRead(chan, timeout, &_uid, &_uidMask, RPLLoader_MakePPCCallable(__NTAGReadCallback), context);
return __NTAGConvertNFCResult(result);
}
sint32 __NTAGEncryptData(void* encryptedData, const void* rawData)
{
StackAllocator<iosu::ccr_nfc::CCRNFCCryptData> nfcRawData, nfcInData, nfcOutData;
if (!ccrNfcOpened)
{
gCcrNfcHandle = coreinit::IOS_Open("/dev/ccr_nfc", 0);
}
// Prepare nfc buffer
nfcRawData->version = 0;
memcpy(nfcRawData->data, rawData, 0x1C8);
__NTAGRawDataToNfcData(nfcRawData.GetPointer(), nfcInData.GetPointer());
// Encrypt
sint32 result = coreinit::IOS_Ioctl(gCcrNfcHandle, 1, nfcInData.GetPointer(), sizeof(iosu::ccr_nfc::CCRNFCCryptData), nfcOutData.GetPointer(), sizeof(iosu::ccr_nfc::CCRNFCCryptData));
// Unpack nfc buffer
__NTAGNfcDataToRawData(nfcOutData.GetPointer(), nfcRawData.GetPointer());
memcpy(encryptedData, nfcRawData->data, 0x1C8);
return result;
}
sint32 __NTAGPrepareWriteData(void* outBuffer, uint32 dataSize, const void* data, const void* tagData, NTAGNoftHeader* noftHeader, NTAGAreaHeader* rwHeader)
{
uint8 decryptedBuffer[0x1C8];
uint8 encryptedBuffer[0x1C8];
memcpy(decryptedBuffer, tagData, 0x1C8);
// Fill the rest of the rw area with random data
if (dataSize < _swapEndianU16(rwHeader->size))
{
uint8 randomBuffer[0x1C8];
for (int i = 0; i < sizeof(randomBuffer); i++)
{
randomBuffer[i] = rand() & 0xFF;
}
memcpy(decryptedBuffer + _swapEndianU16(rwHeader->offset) + dataSize, randomBuffer, _swapEndianU16(rwHeader->size) - dataSize);
}
// Make sure the data fits into the rw area
if (_swapEndianU16(rwHeader->size) < dataSize)
{
return -0x270D;
}
// Update write count (check for overflow)
if ((_swapEndianU16(noftHeader->writeCount) & 0x7fff) == 0x7fff)
{
noftHeader->writeCount = _swapEndianU16(_swapEndianU16(noftHeader->writeCount) & 0x8000);
}
else
{
noftHeader->writeCount = _swapEndianU16(_swapEndianU16(noftHeader->writeCount) + 1);
}
memcpy(decryptedBuffer + 0x20, noftHeader, sizeof(NTAGNoftHeader));
memcpy(decryptedBuffer + _swapEndianU16(rwHeader->offset), data, dataSize);
// Encrypt
sint32 result = __NTAGEncryptData(encryptedBuffer, decryptedBuffer);
if (result < 0)
{
return result;
}
memcpy(outBuffer, encryptedBuffer, _swapEndianU16(rwHeader->size) + 0x28);
return 0;
}
void __NTAGWriteCallback(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(chan, 0);
ppcDefineParamS32(error, 1);
ppcDefineParamPtr(context, void, 2);
PPCCoreCallback(gWriteCallbacks[chan], chan, __NTAGConvertNFCResult(error), context);
osLib_returnFromFunction(hCPU, 0);
}
void __NTAGReadBeforeWriteCallback(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(chan, 0);
ppcDefineParamS32(error, 1);
ppcDefineParamPtr(uid, nfc::NFCUid, 2);
ppcDefineParamU32(readOnly, 3);
ppcDefineParamU32(dataSize, 4);
ppcDefineParamPtr(data, void, 5);
ppcDefineParamU32(lockedDataSize, 6);
ppcDefineParamPtr(lockedData, void, 7);
ppcDefineParamPtr(context, void, 8);
uint8 rawData[0x1C8]{};
uint8 rwData[0x1C8]{};
uint8 roData[0x1C8]{};
NTAGNoftHeader noftHeader;
NTAGInfoHeader infoHeader;
NTAGAreaHeader rwHeader;
NTAGAreaHeader roHeader;
uint8 writeBuffer[0x1C8]{};
error = __NTAGConvertNFCResult(error);
if (error == 0)
{
// Copy raw and locked data into a contigous buffer
memcpy(rawData, data, dataSize);
memcpy(rawData + dataSize, lockedData, lockedDataSize);
error = __NTAGParseData(rawData, rwData, roData, uid, lockedDataSize, &noftHeader, &infoHeader, &rwHeader, &roHeader);
if (error < 0)
{
cemuLog_log(LogType::Force, "Failed to parse data before write");
PPCCoreCallback(gWriteCallbacks[chan], chan, -0x3E3, context);
osLib_returnFromFunction(hCPU, 0);
return;
}
// Prepare data
memcpy(rawData + _swapEndianU16(infoHeader.rwHeaderOffset), &rwHeader, sizeof(rwHeader));
memcpy(rawData + _swapEndianU16(infoHeader.roHeaderOffset), &roHeader, sizeof(roHeader));
memcpy(rawData + _swapEndianU16(roHeader.offset), roData, _swapEndianU16(roHeader.size));
error = __NTAGPrepareWriteData(writeBuffer, gWriteData[chan].size, gWriteData[chan].data, rawData, &noftHeader, &rwHeader);
if (error < 0)
{
cemuLog_log(LogType::Force, "Failed to prepare write data");
PPCCoreCallback(gWriteCallbacks[chan], chan, -0x3E3, context);
osLib_returnFromFunction(hCPU, 0);
return;
}
// Write data to tag
error = nfc::NFCWrite(chan, 200, &gWriteData[chan].uid, &gWriteData[chan].uidMask,
_swapEndianU16(rwHeader.size) + 0x28, writeBuffer, RPLLoader_MakePPCCallable(__NTAGWriteCallback), context);
if (error >= 0)
{
osLib_returnFromFunction(hCPU, 0);
return;
}
error = __NTAGConvertNFCResult(error);
}
PPCCoreCallback(gWriteCallbacks[chan], chan, error, context);
osLib_returnFromFunction(hCPU, 0);
}
sint32 NTAGWrite(uint32 chan, uint32 timeout, nfc::NFCUid* uid, uint32 rwSize, void* rwData, MPTR callback, void* context)
{
cemu_assert(chan < 2);
cemu_assert(rwSize < 0x1C8);
gWriteCallbacks[chan] = callback;
if (uid)
{
memcpy(&gWriteData[chan].uid, uid, sizeof(nfc::NFCUid));
}
memset(&gWriteData[chan].uidMask, 0xff, sizeof(nfc::NFCUid));
gWriteData[chan].size = rwSize;
memcpy(gWriteData[chan].data, rwData, rwSize);
sint32 result = nfc::NFCRead(chan, timeout, &gWriteData[chan].uid, &gWriteData[chan].uidMask, RPLLoader_MakePPCCallable(__NTAGReadBeforeWriteCallback), context);
return __NTAGConvertNFCResult(result);
}
sint32 NTAGFormat(uint32 chan, uint32 timeout, nfc::NFCUid* uid, uint32 rwSize, void* rwData, MPTR callback, void* context)
{
cemu_assert(chan < 2);
// TODO
cemu_assert_debug(false);
return NTAG_RESULT_INVALID;
}
void Initialize()
{
cafeExportRegister("ntag", NTAGInit, LogType::NTAG);
cafeExportRegister("ntag", NTAGInitEx, LogType::NTAG);
cafeExportRegister("ntag", NTAGShutdown, LogType::NTAG);
cafeExportRegister("ntag", NTAGIsInit, LogType::Placeholder); // disabled logging, since this gets spammed
cafeExportRegister("ntag", NTAGProc, LogType::Placeholder); // disabled logging, since this gets spammed
cafeExportRegister("ntag", NTAGSetFormatSettings, LogType::NTAG);
cafeExportRegister("ntag", NTAGSetTagDetectCallback, LogType::NTAG);
cafeExportRegister("ntag", NTAGAbort, LogType::NTAG);
cafeExportRegister("ntag", NTAGRead, LogType::NTAG);
cafeExportRegister("ntag", NTAGWrite, LogType::NTAG);
cafeExportRegister("ntag", NTAGFormat, LogType::NTAG);
}
}
| 19,988
|
C++
|
.cpp
| 539
| 33.710575
| 215
| 0.733309
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,134
|
BackendWindowsHID.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nsyshid/BackendWindowsHID.cpp
|
#include "BackendWindowsHID.h"
#if NSYSHID_ENABLE_BACKEND_WINDOWS_HID
#include <setupapi.h>
#include <initguid.h>
#include <hidsdi.h>
#pragma comment(lib, "Setupapi.lib")
#pragma comment(lib, "hid.lib")
DEFINE_GUID(GUID_DEVINTERFACE_HID,
0x4D1E55B2L, 0xF16F, 0x11CF, 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30);
namespace nsyshid::backend::windows
{
BackendWindowsHID::BackendWindowsHID()
{
}
void BackendWindowsHID::AttachVisibleDevices()
{
// add all currently connected devices
HDEVINFO hDevInfo;
SP_DEVICE_INTERFACE_DATA DevIntfData;
PSP_DEVICE_INTERFACE_DETAIL_DATA DevIntfDetailData;
SP_DEVINFO_DATA DevData;
DWORD dwSize, dwMemberIdx;
hDevInfo = SetupDiGetClassDevs(&GUID_DEVINTERFACE_HID, NULL, 0, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
if (hDevInfo != INVALID_HANDLE_VALUE)
{
DevIntfData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
dwMemberIdx = 0;
SetupDiEnumDeviceInterfaces(hDevInfo, NULL, &GUID_DEVINTERFACE_HID,
dwMemberIdx, &DevIntfData);
while (GetLastError() != ERROR_NO_MORE_ITEMS)
{
DevData.cbSize = sizeof(DevData);
SetupDiGetDeviceInterfaceDetail(
hDevInfo, &DevIntfData, NULL, 0, &dwSize, NULL);
DevIntfDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
dwSize);
DevIntfDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &DevIntfData,
DevIntfDetailData, dwSize, &dwSize, &DevData))
{
HANDLE hHIDDevice = OpenDevice(DevIntfDetailData->DevicePath);
if (hHIDDevice != INVALID_HANDLE_VALUE)
{
auto device = CheckAndCreateDevice(DevIntfDetailData->DevicePath, hHIDDevice);
if (device != nullptr)
{
if (IsDeviceWhitelisted(device->m_vendorId, device->m_productId))
{
if (!AttachDevice(device))
{
cemuLog_log(LogType::Force,
"nsyshid::BackendWindowsHID: failed to attach device: {:04x}:{:04x}",
device->m_vendorId,
device->m_productId);
}
}
}
CloseHandle(hHIDDevice);
}
}
HeapFree(GetProcessHeap(), 0, DevIntfDetailData);
// next
SetupDiEnumDeviceInterfaces(hDevInfo, NULL, &GUID_DEVINTERFACE_HID, ++dwMemberIdx, &DevIntfData);
}
SetupDiDestroyDeviceInfoList(hDevInfo);
}
}
BackendWindowsHID::~BackendWindowsHID()
{
}
bool BackendWindowsHID::IsInitialisedOk()
{
return true;
}
std::shared_ptr<Device> BackendWindowsHID::CheckAndCreateDevice(wchar_t* devicePath, HANDLE hDevice)
{
HIDD_ATTRIBUTES hidAttr;
hidAttr.Size = sizeof(HIDD_ATTRIBUTES);
if (HidD_GetAttributes(hDevice, &hidAttr) == FALSE)
return nullptr;
auto device = std::make_shared<DeviceWindowsHID>(hidAttr.VendorID,
hidAttr.ProductID,
1,
2,
0,
_wcsdup(devicePath));
// get additional device info
sint32 maxPacketInputLength = -1;
sint32 maxPacketOutputLength = -1;
PHIDP_PREPARSED_DATA ppData = nullptr;
if (HidD_GetPreparsedData(hDevice, &ppData))
{
HIDP_CAPS caps;
if (HidP_GetCaps(ppData, &caps) == HIDP_STATUS_SUCCESS)
{
// length includes the report id byte
maxPacketInputLength = caps.InputReportByteLength - 1;
maxPacketOutputLength = caps.OutputReportByteLength - 1;
}
HidD_FreePreparsedData(ppData);
}
if (maxPacketInputLength <= 0 || maxPacketInputLength >= 0xF000)
{
cemuLog_logDebug(LogType::Force, "HID: Input packet length not available or out of range (length = {})", maxPacketInputLength);
maxPacketInputLength = 0x20;
}
if (maxPacketOutputLength <= 0 || maxPacketOutputLength >= 0xF000)
{
cemuLog_logDebug(LogType::Force, "HID: Output packet length not available or out of range (length = {})", maxPacketOutputLength);
maxPacketOutputLength = 0x20;
}
device->m_maxPacketSizeRX = maxPacketInputLength;
device->m_maxPacketSizeTX = maxPacketOutputLength;
return device;
}
DeviceWindowsHID::DeviceWindowsHID(uint16 vendorId,
uint16 productId,
uint8 interfaceIndex,
uint8 interfaceSubClass,
uint8 protocol,
wchar_t* devicePath)
: Device(vendorId,
productId,
interfaceIndex,
interfaceSubClass,
protocol),
m_devicePath(devicePath),
m_hFile(INVALID_HANDLE_VALUE)
{
}
DeviceWindowsHID::~DeviceWindowsHID()
{
if (m_hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(m_hFile);
m_hFile = INVALID_HANDLE_VALUE;
}
}
bool DeviceWindowsHID::Open()
{
if (IsOpened())
{
return true;
}
m_hFile = OpenDevice(m_devicePath);
if (m_hFile == INVALID_HANDLE_VALUE)
{
return false;
}
HidD_SetNumInputBuffers(m_hFile, 2); // don't cache too many reports
return true;
}
void DeviceWindowsHID::Close()
{
if (m_hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(m_hFile);
m_hFile = INVALID_HANDLE_VALUE;
}
}
bool DeviceWindowsHID::IsOpened()
{
return m_hFile != INVALID_HANDLE_VALUE;
}
Device::ReadResult DeviceWindowsHID::Read(ReadMessage* message)
{
message->bytesRead = 0;
DWORD bt;
OVERLAPPED ovlp = {0};
ovlp.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
uint8* tempBuffer = (uint8*)malloc(message->length + 1);
sint32 transferLength = 0; // minus report byte
_debugPrintHex("HID_READ_BEFORE", message->data, message->length);
cemuLog_logDebug(LogType::Force, "HidRead Begin (Length 0x{:08x})", message->length);
BOOL readResult = ReadFile(this->m_hFile, tempBuffer, message->length + 1, &bt, &ovlp);
if (readResult != FALSE)
{
// sometimes we get the result immediately
if (bt == 0)
transferLength = 0;
else
transferLength = bt - 1;
cemuLog_logDebug(LogType::Force, "HidRead Result received immediately (error 0x{:08x}) Length 0x{:08x}",
GetLastError(), transferLength);
}
else
{
// wait for result
cemuLog_logDebug(LogType::Force, "HidRead WaitForResult (error 0x{:08x})", GetLastError());
// async hid read is never supposed to return unless there is a response? Lego Dimensions stops HIDRead calls as soon as one of them fails with a non-zero error (which includes time out)
DWORD r = WaitForSingleObject(ovlp.hEvent, 2000 * 100);
if (r == WAIT_TIMEOUT)
{
cemuLog_logDebug(LogType::Force, "HidRead internal timeout (error 0x{:08x})", GetLastError());
// return -108 in case of timeout
free(tempBuffer);
CloseHandle(ovlp.hEvent);
return ReadResult::ErrorTimeout;
}
cemuLog_logDebug(LogType::Force, "HidRead WaitHalfComplete");
GetOverlappedResult(this->m_hFile, &ovlp, &bt, false);
if (bt == 0)
transferLength = 0;
else
transferLength = bt - 1;
cemuLog_logDebug(LogType::Force, "HidRead WaitComplete Length: 0x{:08x}", transferLength);
}
sint32 returnCode = 0;
ReadResult result = ReadResult::Success;
if (bt != 0)
{
memcpy(message->data, tempBuffer + 1, transferLength);
sint32 hidReadLength = transferLength;
char debugOutput[1024] = {0};
for (sint32 i = 0; i < transferLength; i++)
{
sprintf(debugOutput + i * 3, "%02x ", tempBuffer[1 + i]);
}
cemuLog_logDebug(LogType::Force, "HIDRead data: {}", debugOutput);
message->bytesRead = transferLength;
result = ReadResult::Success;
}
else
{
cemuLog_log(LogType::Force, "Failed HID read");
result = ReadResult::Error;
}
free(tempBuffer);
CloseHandle(ovlp.hEvent);
return result;
}
Device::WriteResult DeviceWindowsHID::Write(WriteMessage* message)
{
message->bytesWritten = 0;
DWORD bt;
OVERLAPPED ovlp = {0};
ovlp.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
uint8* tempBuffer = (uint8*)malloc(message->length + 1);
memcpy(tempBuffer + 1, message->data, message->length);
tempBuffer[0] = 0; // report byte?
cemuLog_logDebug(LogType::Force, "HidWrite Begin (Length 0x{:08x})", message->length);
BOOL writeResult = WriteFile(this->m_hFile, tempBuffer, message->length + 1, &bt, &ovlp);
if (writeResult != FALSE)
{
// sometimes we get the result immediately
cemuLog_logDebug(LogType::Force, "HidWrite Result received immediately (error 0x{:08x}) Length 0x{:08x}",
GetLastError());
}
else
{
// wait for result
cemuLog_logDebug(LogType::Force, "HidWrite WaitForResult (error 0x{:08x})", GetLastError());
// todo - check for error type
DWORD r = WaitForSingleObject(ovlp.hEvent, 2000);
if (r == WAIT_TIMEOUT)
{
cemuLog_logDebug(LogType::Force, "HidWrite internal timeout");
// return -108 in case of timeout
free(tempBuffer);
CloseHandle(ovlp.hEvent);
return WriteResult::ErrorTimeout;
}
cemuLog_logDebug(LogType::Force, "HidWrite WaitHalfComplete");
GetOverlappedResult(this->m_hFile, &ovlp, &bt, false);
cemuLog_logDebug(LogType::Force, "HidWrite WaitComplete");
}
free(tempBuffer);
CloseHandle(ovlp.hEvent);
if (bt != 0)
{
message->bytesWritten = message->length;
return WriteResult::Success;
}
return WriteResult::Error;
}
bool DeviceWindowsHID::GetDescriptor(uint8 descType,
uint8 descIndex,
uint8 lang,
uint8* output,
uint32 outputMaxLength)
{
if (!IsOpened())
{
cemuLog_logDebug(LogType::Force, "nsyshid::DeviceWindowsHID::getDescriptor(): device is not opened");
return false;
}
if (descType == 0x02)
{
uint8 configurationDescriptor[0x29];
uint8* currentWritePtr;
// configuration descriptor
currentWritePtr = configurationDescriptor + 0;
*(uint8*)(currentWritePtr + 0) = 9; // bLength
*(uint8*)(currentWritePtr + 1) = 2; // bDescriptorType
*(uint16be*)(currentWritePtr + 2) = 0x0029; // wTotalLength
*(uint8*)(currentWritePtr + 4) = 1; // bNumInterfaces
*(uint8*)(currentWritePtr + 5) = 1; // bConfigurationValue
*(uint8*)(currentWritePtr + 6) = 0; // iConfiguration
*(uint8*)(currentWritePtr + 7) = 0x80; // bmAttributes
*(uint8*)(currentWritePtr + 8) = 0xFA; // MaxPower
currentWritePtr = currentWritePtr + 9;
// configuration descriptor
*(uint8*)(currentWritePtr + 0) = 9; // bLength
*(uint8*)(currentWritePtr + 1) = 0x04; // bDescriptorType
*(uint8*)(currentWritePtr + 2) = 0; // bInterfaceNumber
*(uint8*)(currentWritePtr + 3) = 0; // bAlternateSetting
*(uint8*)(currentWritePtr + 4) = 2; // bNumEndpoints
*(uint8*)(currentWritePtr + 5) = 3; // bInterfaceClass
*(uint8*)(currentWritePtr + 6) = 0; // bInterfaceSubClass
*(uint8*)(currentWritePtr + 7) = 0; // bInterfaceProtocol
*(uint8*)(currentWritePtr + 8) = 0; // iInterface
currentWritePtr = currentWritePtr + 9;
// configuration descriptor
*(uint8*)(currentWritePtr + 0) = 9; // bLength
*(uint8*)(currentWritePtr + 1) = 0x21; // bDescriptorType
*(uint16be*)(currentWritePtr + 2) = 0x0111; // bcdHID
*(uint8*)(currentWritePtr + 4) = 0x00; // bCountryCode
*(uint8*)(currentWritePtr + 5) = 0x01; // bNumDescriptors
*(uint8*)(currentWritePtr + 6) = 0x22; // bDescriptorType
*(uint16be*)(currentWritePtr + 7) = 0x001D; // wDescriptorLength
currentWritePtr = currentWritePtr + 9;
// endpoint descriptor 1
*(uint8*)(currentWritePtr + 0) = 7; // bLength
*(uint8*)(currentWritePtr + 1) = 0x05; // bDescriptorType
*(uint8*)(currentWritePtr + 2) = 0x81; // bEndpointAddress
*(uint8*)(currentWritePtr + 3) = 0x03; // bmAttributes
*(uint16be*)(currentWritePtr + 4) =
this->m_maxPacketSizeRX; // wMaxPacketSize
*(uint8*)(currentWritePtr + 6) = 0x01; // bInterval
currentWritePtr = currentWritePtr + 7;
// endpoint descriptor 2
*(uint8*)(currentWritePtr + 0) = 7; // bLength
*(uint8*)(currentWritePtr + 1) = 0x05; // bDescriptorType
*(uint8*)(currentWritePtr + 2) = 0x02; // bEndpointAddress
*(uint8*)(currentWritePtr + 3) = 0x03; // bmAttributes
*(uint16be*)(currentWritePtr + 4) =
this->m_maxPacketSizeTX; // wMaxPacketSize
*(uint8*)(currentWritePtr + 6) = 0x01; // bInterval
currentWritePtr = currentWritePtr + 7;
cemu_assert_debug((currentWritePtr - configurationDescriptor) == 0x29);
memcpy(output, configurationDescriptor,
std::min<uint32>(outputMaxLength, sizeof(configurationDescriptor)));
return true;
}
else
{
cemu_assert_unimplemented();
}
return false;
}
bool DeviceWindowsHID::SetProtocol(uint8 ifIndex, uint8 protocol)
{
// ToDo: implement this
// pretend that everything is fine
return true;
}
bool DeviceWindowsHID::SetReport(ReportMessage* message)
{
sint32 retryCount = 0;
while (true)
{
BOOL r = HidD_SetOutputReport(this->m_hFile, message->reportData, message->length);
if (r != FALSE)
break;
Sleep(20); // retry
retryCount++;
if (retryCount >= 50)
{
cemuLog_log(LogType::Force, "nsyshid::DeviceWindowsHID::SetReport(): HID SetReport failed");
return false;
}
}
return true;
}
HANDLE OpenDevice(wchar_t* devicePath)
{
return CreateFile(devicePath,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ |
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL);
}
void _debugPrintHex(std::string prefix, uint8* data, size_t len)
{
char debugOutput[1024] = {0};
len = std::min(len, (size_t)100);
for (sint32 i = 0; i < len; i++)
{
sprintf(debugOutput + i * 3, "%02x ", data[i]);
}
cemuLog_logDebug(LogType::Force, "[{}] Data: {}", prefix, debugOutput);
}
} // namespace nsyshid::backend::windows
#endif // NSYSHID_ENABLE_BACKEND_WINDOWS_HID
| 13,611
|
C++
|
.cpp
| 397
| 29.937028
| 189
| 0.68854
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,135
|
Infinity.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nsyshid/Infinity.cpp
|
#include "Infinity.h"
#include <random>
#include "nsyshid.h"
#include "Backend.h"
#include "util/crypto/aes128.h"
#include <openssl/crypto.h>
#include "openssl/sha.h"
namespace nsyshid
{
static constexpr std::array<uint8, 32> SHA1_CONSTANT = {
0xAF, 0x62, 0xD2, 0xEC, 0x04, 0x91, 0x96, 0x8C, 0xC5, 0x2A, 0x1A, 0x71, 0x65, 0xF8, 0x65, 0xFE,
0x28, 0x63, 0x29, 0x20, 0x44, 0x69, 0x73, 0x6e, 0x65, 0x79, 0x20, 0x32, 0x30, 0x31, 0x33};
InfinityUSB g_infinitybase;
const std::map<const uint32, const std::pair<const uint8, const char*>> s_listFigures = {
{0x0F4241, {1, "Mr. Incredible"}},
{0x0F4242, {1, "Sulley"}},
{0x0F4243, {1, "Jack Sparrow"}},
{0x0F4244, {1, "Lone Ranger"}},
{0x0F4245, {1, "Tonto"}},
{0x0F4246, {1, "Lightning McQueen"}},
{0x0F4247, {1, "Holley Shiftwell"}},
{0x0F4248, {1, "Buzz Lightyear"}},
{0x0F4249, {1, "Jessie"}},
{0x0F424A, {1, "Mike"}},
{0x0F424B, {1, "Mrs. Incredible"}},
{0x0F424C, {1, "Hector Barbossa"}},
{0x0F424D, {1, "Davy Jones"}},
{0x0F424E, {1, "Randy"}},
{0x0F424F, {1, "Syndrome"}},
{0x0F4250, {1, "Woody"}},
{0x0F4251, {1, "Mater"}},
{0x0F4252, {1, "Dash"}},
{0x0F4253, {1, "Violet"}},
{0x0F4254, {1, "Francesco Bernoulli"}},
{0x0F4255, {1, "Sorcerer's Apprentice Mickey"}},
{0x0F4256, {1, "Jack Skellington"}},
{0x0F4257, {1, "Rapunzel"}},
{0x0F4258, {1, "Anna"}},
{0x0F4259, {1, "Elsa"}},
{0x0F425A, {1, "Phineas"}},
{0x0F425B, {1, "Agent P"}},
{0x0F425C, {1, "Wreck-It Ralph"}},
{0x0F425D, {1, "Vanellope"}},
{0x0F425E, {1, "Mr. Incredible (Crystal)"}},
{0x0F425F, {1, "Jack Sparrow (Crystal)"}},
{0x0F4260, {1, "Sulley (Crystal)"}},
{0x0F4261, {1, "Lightning McQueen (Crystal)"}},
{0x0F4262, {1, "Lone Ranger (Crystal)"}},
{0x0F4263, {1, "Buzz Lightyear (Crystal)"}},
{0x0F4264, {1, "Agent P (Crystal)"}},
{0x0F4265, {1, "Sorcerer's Apprentice Mickey (Crystal)"}},
{0x0F4266, {1, "Buzz Lightyear (Glowing)"}},
{0x0F42A4, {2, "Captain America"}},
{0x0F42A5, {2, "Hulk"}},
{0x0F42A6, {2, "Iron Man"}},
{0x0F42A7, {2, "Thor"}},
{0x0F42A8, {2, "Groot"}},
{0x0F42A9, {2, "Rocket Raccoon"}},
{0x0F42AA, {2, "Star-Lord"}},
{0x0F42AB, {2, "Spider-Man"}},
{0x0F42AC, {2, "Nick Fury"}},
{0x0F42AD, {2, "Black Widow"}},
{0x0F42AE, {2, "Hawkeye"}},
{0x0F42AF, {2, "Drax"}},
{0x0F42B0, {2, "Gamora"}},
{0x0F42B1, {2, "Iron Fist"}},
{0x0F42B2, {2, "Nova"}},
{0x0F42B3, {2, "Venom"}},
{0x0F42B4, {2, "Donald Duck"}},
{0x0F42B5, {2, "Aladdin"}},
{0x0F42B6, {2, "Stitch"}},
{0x0F42B7, {2, "Merida"}},
{0x0F42B8, {2, "Tinker Bell"}},
{0x0F42B9, {2, "Maleficent"}},
{0x0F42BA, {2, "Hiro"}},
{0x0F42BB, {2, "Baymax"}},
{0x0F42BC, {2, "Loki"}},
{0x0F42BD, {2, "Ronan"}},
{0x0F42BE, {2, "Green Goblin"}},
{0x0F42BF, {2, "Falcon"}},
{0x0F42C0, {2, "Yondu"}},
{0x0F42C1, {2, "Jasmine"}},
{0x0F42C6, {2, "Black Suit Spider-Man"}},
{0x0F42D6, {3, "Sam Flynn"}},
{0x0F42D7, {3, "Quorra"}},
{0x0F4308, {3, "Anakin Skywalker"}},
{0x0F4309, {3, "Obi-Wan Kenobi"}},
{0x0F430A, {3, "Yoda"}},
{0x0F430B, {3, "Ahsoka Tano"}},
{0x0F430C, {3, "Darth Maul"}},
{0x0F430E, {3, "Luke Skywalker"}},
{0x0F430F, {3, "Han Solo"}},
{0x0F4310, {3, "Princess Leia"}},
{0x0F4311, {3, "Chewbacca"}},
{0x0F4312, {3, "Darth Vader"}},
{0x0F4313, {3, "Boba Fett"}},
{0x0F4314, {3, "Ezra Bridger"}},
{0x0F4315, {3, "Kanan Jarrus"}},
{0x0F4316, {3, "Sabine Wren"}},
{0x0F4317, {3, "Zeb Orrelios"}},
{0x0F4318, {3, "Joy"}},
{0x0F4319, {3, "Anger"}},
{0x0F431A, {3, "Fear"}},
{0x0F431B, {3, "Sadness"}},
{0x0F431C, {3, "Disgust"}},
{0x0F431D, {3, "Mickey Mouse"}},
{0x0F431E, {3, "Minnie Mouse"}},
{0x0F431F, {3, "Mulan"}},
{0x0F4320, {3, "Olaf"}},
{0x0F4321, {3, "Vision"}},
{0x0F4322, {3, "Ultron"}},
{0x0F4323, {3, "Ant-Man"}},
{0x0F4325, {3, "Captain America - The First Avenger"}},
{0x0F4326, {3, "Finn"}},
{0x0F4327, {3, "Kylo Ren"}},
{0x0F4328, {3, "Poe Dameron"}},
{0x0F4329, {3, "Rey"}},
{0x0F432B, {3, "Spot"}},
{0x0F432C, {3, "Nick Wilde"}},
{0x0F432D, {3, "Judy Hopps"}},
{0x0F432E, {3, "Hulkbuster"}},
{0x0F432F, {3, "Anakin Skywalker (Light FX)"}},
{0x0F4330, {3, "Obi-Wan Kenobi (Light FX)"}},
{0x0F4331, {3, "Yoda (Light FX)"}},
{0x0F4332, {3, "Luke Skywalker (Light FX)"}},
{0x0F4333, {3, "Darth Vader (Light FX)"}},
{0x0F4334, {3, "Kanan Jarrus (Light FX)"}},
{0x0F4335, {3, "Kylo Ren (Light FX)"}},
{0x0F4336, {3, "Black Panther"}},
{0x0F436C, {3, "Nemo"}},
{0x0F436D, {3, "Dory"}},
{0x0F436E, {3, "Baloo"}},
{0x0F436F, {3, "Alice"}},
{0x0F4370, {3, "Mad Hatter"}},
{0x0F4371, {3, "Time"}},
{0x0F4372, {3, "Peter Pan"}},
{0x1E8481, {1, "Starter Play Set"}},
{0x1E8482, {1, "Lone Ranger Play Set"}},
{0x1E8483, {1, "Cars Play Set"}},
{0x1E8484, {1, "Toy Story in Space Play Set"}},
{0x1E84E4, {2, "Marvel's The Avengers Play Set"}},
{0x1E84E5, {2, "Marvel's Spider-Man Play Set"}},
{0x1E84E6, {2, "Marvel's Guardians of the Galaxy Play Set"}},
{0x1E84E7, {2, "Assault on Asgard"}},
{0x1E84E8, {2, "Escape from the Kyln"}},
{0x1E84E9, {2, "Stitch's Tropical Rescue"}},
{0x1E84EA, {2, "Brave Forest Siege"}},
{0x1E8548, {3, "Inside Out Play Set"}},
{0x1E8549, {3, "Star Wars: Twilight of the Republic Play Set"}},
{0x1E854A, {3, "Star Wars: Rise Against the Empire Play Set"}},
{0x1E854B, {3, "Star Wars: The Force Awakens Play Set"}},
{0x1E854C, {3, "Marvel Battlegrounds Play Set"}},
{0x1E854D, {3, "Toy Box Speedway"}},
{0x1E854E, {3, "Toy Box Takeover"}},
{0x1E85AC, {3, "Finding Dory Play Set"}},
{0x2DC6C3, {1, "Bolt's Super Strength"}},
{0x2DC6C4, {1, "Ralph's Power of Destruction"}},
{0x2DC6C5, {1, "Chernabog's Power"}},
{0x2DC6C6, {1, "C.H.R.O.M.E. Damage Increaser"}},
{0x2DC6C7, {1, "Dr. Doofenshmirtz's Damage-Inator!"}},
{0x2DC6C8, {1, "Electro-Charge"}},
{0x2DC6C9, {1, "Fix-It Felix's Repair Power"}},
{0x2DC6CA, {1, "Rapunzel's Healing"}},
{0x2DC6CB, {1, "C.H.R.O.M.E. Armor Shield"}},
{0x2DC6CC, {1, "Star Command Shield"}},
{0x2DC6CD, {1, "Violet's Force Field"}},
{0x2DC6CE, {1, "Pieces of Eight"}},
{0x2DC6CF, {1, "Scrooge McDuck's Lucky Dime"}},
{0x2DC6D0, {1, "User Control"}},
{0x2DC6D1, {1, "Sorcerer Mickey's Hat"}},
{0x2DC6FE, {1, "Emperor Zurg's Wrath"}},
{0x2DC6FF, {1, "Merlin's Summon"}},
{0x2DC765, {2, "Enchanted Rose"}},
{0x2DC766, {2, "Mulan's Training Uniform"}},
{0x2DC767, {2, "Flubber"}},
{0x2DC768, {2, "S.H.I.E.L.D. Helicarrier Strike"}},
{0x2DC769, {2, "Zeus' Thunderbolts"}},
{0x2DC76A, {2, "King Louie's Monkeys"}},
{0x2DC76B, {2, "Infinity Gauntlet"}},
{0x2DC76D, {2, "Sorcerer Supreme"}},
{0x2DC76E, {2, "Maleficent's Spell Cast"}},
{0x2DC76F, {2, "Chernabog's Spirit Cyclone"}},
{0x2DC770, {2, "Marvel Team-Up: Capt. Marvel"}},
{0x2DC771, {2, "Marvel Team-Up: Iron Patriot"}},
{0x2DC772, {2, "Marvel Team-Up: Ant-Man"}},
{0x2DC773, {2, "Marvel Team-Up: White Tiger"}},
{0x2DC774, {2, "Marvel Team-Up: Yondu"}},
{0x2DC775, {2, "Marvel Team-Up: Winter Soldier"}},
{0x2DC776, {2, "Stark Arc Reactor"}},
{0x2DC777, {2, "Gamma Rays"}},
{0x2DC778, {2, "Alien Symbiote"}},
{0x2DC779, {2, "All for One"}},
{0x2DC77A, {2, "Sandy Claws Surprise"}},
{0x2DC77B, {2, "Glory Days"}},
{0x2DC77C, {2, "Cursed Pirate Gold"}},
{0x2DC77D, {2, "Sentinel of Liberty"}},
{0x2DC77E, {2, "The Immortal Iron Fist"}},
{0x2DC77F, {2, "Space Armor"}},
{0x2DC780, {2, "Rags to Riches"}},
{0x2DC781, {2, "Ultimate Falcon"}},
{0x2DC788, {3, "Tomorrowland Time Bomb"}},
{0x2DC78E, {3, "Galactic Team-Up: Mace Windu"}},
{0x2DC791, {3, "Luke's Rebel Alliance Flight Suit Costume"}},
{0x2DC798, {3, "Finn's Stormtrooper Costume"}},
{0x2DC799, {3, "Poe's Resistance Jacket"}},
{0x2DC79A, {3, "Resistance Tactical Strike"}},
{0x2DC79E, {3, "Officer Nick Wilde"}},
{0x2DC79F, {3, "Meter Maid Judy"}},
{0x2DC7A2, {3, "Darkhawk's Blast"}},
{0x2DC7A3, {3, "Cosmic Cube Blast"}},
{0x2DC7A4, {3, "Princess Leia's Boushh Disguise"}},
{0x2DC7A6, {3, "Nova Corps Strike"}},
{0x2DC7A7, {3, "King Mickey"}},
{0x3D0912, {1, "Mickey's Car"}},
{0x3D0913, {1, "Cinderella's Coach"}},
{0x3D0914, {1, "Electric Mayhem Bus"}},
{0x3D0915, {1, "Cruella De Vil's Car"}},
{0x3D0916, {1, "Pizza Planet Delivery Truck"}},
{0x3D0917, {1, "Mike's New Car"}},
{0x3D0919, {1, "Parking Lot Tram"}},
{0x3D091A, {1, "Captain Hook's Ship"}},
{0x3D091B, {1, "Dumbo"}},
{0x3D091C, {1, "Calico Helicopter"}},
{0x3D091D, {1, "Maximus"}},
{0x3D091E, {1, "Angus"}},
{0x3D091F, {1, "Abu the Elephant"}},
{0x3D0920, {1, "Headless Horseman's Horse"}},
{0x3D0921, {1, "Phillipe"}},
{0x3D0922, {1, "Khan"}},
{0x3D0923, {1, "Tantor"}},
{0x3D0924, {1, "Dragon Firework Cannon"}},
{0x3D0925, {1, "Stitch's Blaster"}},
{0x3D0926, {1, "Toy Story Mania Blaster"}},
{0x3D0927, {1, "Flamingo Croquet Mallet"}},
{0x3D0928, {1, "Carl Fredricksen's Cane"}},
{0x3D0929, {1, "Hangin' Ten Stitch With Surfboard"}},
{0x3D092A, {1, "Condorman Glider"}},
{0x3D092B, {1, "WALL-E's Fire Extinguisher"}},
{0x3D092C, {1, "On the Grid"}},
{0x3D092D, {1, "WALL-E's Collection"}},
{0x3D092E, {1, "King Candy's Dessert Toppings"}},
{0x3D0930, {1, "Victor's Experiments"}},
{0x3D0931, {1, "Jack's Scary Decorations"}},
{0x3D0933, {1, "Frozen Flourish"}},
{0x3D0934, {1, "Rapunzel's Kingdom"}},
{0x3D0935, {1, "TRON Interface"}},
{0x3D0936, {1, "Buy N Large Atmosphere"}},
{0x3D0937, {1, "Sugar Rush Sky"}},
{0x3D0939, {1, "New Holland Skyline"}},
{0x3D093A, {1, "Halloween Town Sky"}},
{0x3D093C, {1, "Chill in the Air"}},
{0x3D093D, {1, "Rapunzel's Birthday Sky"}},
{0x3D0940, {1, "Astro Blasters Space Cruiser"}},
{0x3D0941, {1, "Marlin's Reef"}},
{0x3D0942, {1, "Nemo's Seascape"}},
{0x3D0943, {1, "Alice's Wonderland"}},
{0x3D0944, {1, "Tulgey Wood"}},
{0x3D0945, {1, "Tri-State Area Terrain"}},
{0x3D0946, {1, "Danville Sky"}},
{0x3D0965, {2, "Stark Tech"}},
{0x3D0966, {2, "Spider-Streets"}},
{0x3D0967, {2, "World War Hulk"}},
{0x3D0968, {2, "Gravity Falls Forest"}},
{0x3D0969, {2, "Neverland"}},
{0x3D096A, {2, "Simba's Pridelands"}},
{0x3D096C, {2, "Calhoun's Command"}},
{0x3D096D, {2, "Star-Lord's Galaxy"}},
{0x3D096E, {2, "Dinosaur World"}},
{0x3D096F, {2, "Groot's Roots"}},
{0x3D0970, {2, "Mulan's Countryside"}},
{0x3D0971, {2, "The Sands of Agrabah"}},
{0x3D0974, {2, "A Small World"}},
{0x3D0975, {2, "View from the Suit"}},
{0x3D0976, {2, "Spider-Sky"}},
{0x3D0977, {2, "World War Hulk Sky"}},
{0x3D0978, {2, "Gravity Falls Sky"}},
{0x3D0979, {2, "Second Star to the Right"}},
{0x3D097A, {2, "The King's Domain"}},
{0x3D097C, {2, "CyBug Swarm"}},
{0x3D097D, {2, "The Rip"}},
{0x3D097E, {2, "Forgotten Skies"}},
{0x3D097F, {2, "Groot's View"}},
{0x3D0980, {2, "The Middle Kingdom"}},
{0x3D0984, {2, "Skies of the World"}},
{0x3D0985, {2, "S.H.I.E.L.D. Containment Truck"}},
{0x3D0986, {2, "Main Street Electrical Parade Float"}},
{0x3D0987, {2, "Mr. Toad's Motorcar"}},
{0x3D0988, {2, "Le Maximum"}},
{0x3D0989, {2, "Alice in Wonderland's Caterpillar"}},
{0x3D098A, {2, "Eglantine's Motorcycle"}},
{0x3D098B, {2, "Medusa's Swamp Mobile"}},
{0x3D098C, {2, "Hydra Motorcycle"}},
{0x3D098D, {2, "Darkwing Duck's Ratcatcher"}},
{0x3D098F, {2, "The USS Swinetrek"}},
{0x3D0991, {2, "Spider-Copter"}},
{0x3D0992, {2, "Aerial Area Rug"}},
{0x3D0993, {2, "Jack-O-Lantern's Glider"}},
{0x3D0994, {2, "Spider-Buggy"}},
{0x3D0995, {2, "Jack Skellington's Reindeer"}},
{0x3D0996, {2, "Fantasyland Carousel Horse"}},
{0x3D0997, {2, "Odin's Horse"}},
{0x3D0998, {2, "Gus the Mule"}},
{0x3D099A, {2, "Darkwing Duck's Grappling Gun"}},
{0x3D099C, {2, "Ghost Rider's Chain Whip"}},
{0x3D099D, {2, "Lew Zealand's Boomerang Fish"}},
{0x3D099E, {2, "Sergeant Calhoun's Blaster"}},
{0x3D09A0, {2, "Falcon's Wings"}},
{0x3D09A1, {2, "Mabel's Kittens for Fists"}},
{0x3D09A2, {2, "Jim Hawkins' Solar Board"}},
{0x3D09A3, {2, "Black Panther's Vibranium Knives"}},
{0x3D09A4, {2, "Cloak of Levitation"}},
{0x3D09A5, {2, "Aladdin's Magic Carpet"}},
{0x3D09A6, {2, "Honey Lemon's Ice Capsules"}},
{0x3D09A7, {2, "Jasmine's Palace View"}},
{0x3D09C1, {2, "Lola"}},
{0x3D09C2, {2, "Spider-Cycle"}},
{0x3D09C3, {2, "The Avenjet"}},
{0x3D09C4, {2, "Spider-Glider"}},
{0x3D09C5, {2, "Light Cycle"}},
{0x3D09C6, {2, "Light Jet"}},
{0x3D09C9, {3, "Retro Ray Gun"}},
{0x3D09CA, {3, "Tomorrowland Futurescape"}},
{0x3D09CB, {3, "Tomorrowland Stratosphere"}},
{0x3D09CC, {3, "Skies Over Felucia"}},
{0x3D09CD, {3, "Forests of Felucia"}},
{0x3D09CF, {3, "General Grievous' Wheel Bike"}},
{0x3D09D2, {3, "Slave I Flyer"}},
{0x3D09D3, {3, "Y-Wing Fighter"}},
{0x3D09D4, {3, "Arlo"}},
{0x3D09D5, {3, "Nash"}},
{0x3D09D6, {3, "Butch"}},
{0x3D09D7, {3, "Ramsey"}},
{0x3D09DC, {3, "Stars Over Sahara Square"}},
{0x3D09DD, {3, "Sahara Square Sands"}},
{0x3D09E0, {3, "Ghost Rider's Motorcycle"}},
{0x3D09E5, {3, "Quad Jumper"}}};
InfinityBaseDevice::InfinityBaseDevice()
: Device(0x0E6F, 0x0129, 1, 2, 0)
{
m_IsOpened = false;
}
bool InfinityBaseDevice::Open()
{
if (!IsOpened())
{
m_IsOpened = true;
}
return true;
}
void InfinityBaseDevice::Close()
{
if (IsOpened())
{
m_IsOpened = false;
}
}
bool InfinityBaseDevice::IsOpened()
{
return m_IsOpened;
}
Device::ReadResult InfinityBaseDevice::Read(ReadMessage* message)
{
memcpy(message->data, g_infinitybase.GetStatus().data(), message->length);
message->bytesRead = message->length;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
return Device::ReadResult::Success;
}
Device::WriteResult InfinityBaseDevice::Write(WriteMessage* message)
{
g_infinitybase.SendCommand(message->data, message->length);
message->bytesWritten = message->length;
return Device::WriteResult::Success;
}
bool InfinityBaseDevice::GetDescriptor(uint8 descType,
uint8 descIndex,
uint8 lang,
uint8* output,
uint32 outputMaxLength)
{
uint8 configurationDescriptor[0x29];
uint8* currentWritePtr;
// configuration descriptor
currentWritePtr = configurationDescriptor + 0;
*(uint8*)(currentWritePtr + 0) = 9; // bLength
*(uint8*)(currentWritePtr + 1) = 2; // bDescriptorType
*(uint16be*)(currentWritePtr + 2) = 0x0029; // wTotalLength
*(uint8*)(currentWritePtr + 4) = 1; // bNumInterfaces
*(uint8*)(currentWritePtr + 5) = 1; // bConfigurationValue
*(uint8*)(currentWritePtr + 6) = 0; // iConfiguration
*(uint8*)(currentWritePtr + 7) = 0x80; // bmAttributes
*(uint8*)(currentWritePtr + 8) = 0xFA; // MaxPower
currentWritePtr = currentWritePtr + 9;
// configuration descriptor
*(uint8*)(currentWritePtr + 0) = 9; // bLength
*(uint8*)(currentWritePtr + 1) = 0x04; // bDescriptorType
*(uint8*)(currentWritePtr + 2) = 0; // bInterfaceNumber
*(uint8*)(currentWritePtr + 3) = 0; // bAlternateSetting
*(uint8*)(currentWritePtr + 4) = 2; // bNumEndpoints
*(uint8*)(currentWritePtr + 5) = 3; // bInterfaceClass
*(uint8*)(currentWritePtr + 6) = 0; // bInterfaceSubClass
*(uint8*)(currentWritePtr + 7) = 0; // bInterfaceProtocol
*(uint8*)(currentWritePtr + 8) = 0; // iInterface
currentWritePtr = currentWritePtr + 9;
// configuration descriptor
*(uint8*)(currentWritePtr + 0) = 9; // bLength
*(uint8*)(currentWritePtr + 1) = 0x21; // bDescriptorType
*(uint16be*)(currentWritePtr + 2) = 0x0111; // bcdHID
*(uint8*)(currentWritePtr + 4) = 0x00; // bCountryCode
*(uint8*)(currentWritePtr + 5) = 0x01; // bNumDescriptors
*(uint8*)(currentWritePtr + 6) = 0x22; // bDescriptorType
*(uint16be*)(currentWritePtr + 7) = 0x001D; // wDescriptorLength
currentWritePtr = currentWritePtr + 9;
// endpoint descriptor 1
*(uint8*)(currentWritePtr + 0) = 7; // bLength
*(uint8*)(currentWritePtr + 1) = 0x05; // bDescriptorType
*(uint8*)(currentWritePtr + 2) = 0x81; // bEndpointAddress
*(uint8*)(currentWritePtr + 3) = 0x03; // bmAttributes
*(uint16be*)(currentWritePtr + 4) = 0x40; // wMaxPacketSize
*(uint8*)(currentWritePtr + 6) = 0x01; // bInterval
currentWritePtr = currentWritePtr + 7;
// endpoint descriptor 2
*(uint8*)(currentWritePtr + 0) = 7; // bLength
*(uint8*)(currentWritePtr + 1) = 0x05; // bDescriptorType
*(uint8*)(currentWritePtr + 1) = 0x02; // bEndpointAddress
*(uint8*)(currentWritePtr + 2) = 0x03; // bmAttributes
*(uint16be*)(currentWritePtr + 3) = 0x40; // wMaxPacketSize
*(uint8*)(currentWritePtr + 5) = 0x01; // bInterval
currentWritePtr = currentWritePtr + 7;
cemu_assert_debug((currentWritePtr - configurationDescriptor) == 0x29);
memcpy(output, configurationDescriptor,
std::min<uint32>(outputMaxLength, sizeof(configurationDescriptor)));
return true;
}
bool InfinityBaseDevice::SetProtocol(uint8 ifIndex, uint8 protocol)
{
return true;
}
bool InfinityBaseDevice::SetReport(ReportMessage* message)
{
return true;
}
std::array<uint8, 32> InfinityUSB::GetStatus()
{
std::array<uint8, 32> response = {};
bool responded = false;
do
{
if (!m_figureAddedRemovedResponses.empty())
{
memcpy(response.data(), m_figureAddedRemovedResponses.front().data(),
0x20);
m_figureAddedRemovedResponses.pop();
responded = true;
}
else if (!m_queries.empty())
{
memcpy(response.data(), m_queries.front().data(), 0x20);
m_queries.pop();
responded = true;
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
/* code */
}
while (!responded);
return response;
}
void InfinityUSB::SendCommand(uint8* buf, sint32 originalLength)
{
const uint8 command = buf[2];
const uint8 sequence = buf[3];
std::array<uint8, 32> q_result{};
switch (command)
{
case 0x80:
{
q_result = {0xaa, 0x15, 0x00, 0x00, 0x0f, 0x01, 0x00, 0x03,
0x02, 0x09, 0x09, 0x43, 0x20, 0x32, 0x62, 0x36,
0x36, 0x4b, 0x34, 0x99, 0x67, 0x31, 0x93, 0x8c};
break;
}
case 0x81:
{
// Initiate Challenge
g_infinitybase.DescrambleAndSeed(buf, sequence, q_result);
break;
}
case 0x83:
{
// Challenge Response
g_infinitybase.GetNextAndScramble(sequence, q_result);
break;
}
case 0x90:
case 0x92:
case 0x93:
case 0x95:
case 0x96:
{
// Color commands
g_infinitybase.GetBlankResponse(sequence, q_result);
break;
}
case 0xA1:
{
// Get Present Figures
g_infinitybase.GetPresentFigures(sequence, q_result);
break;
}
case 0xA2:
{
// Read Block from Figure
g_infinitybase.QueryBlock(buf[4], buf[5], q_result, sequence);
break;
}
case 0xA3:
{
// Write block to figure
g_infinitybase.WriteBlock(buf[4], buf[5], &buf[7], q_result, sequence);
break;
}
case 0xB4:
{
// Get figure ID
g_infinitybase.GetFigureIdentifier(buf[4], sequence, q_result);
break;
}
case 0xB5:
{
// Get status?
g_infinitybase.GetBlankResponse(sequence, q_result);
break;
}
default:
cemu_assert_error();
break;
}
m_queries.push(q_result);
}
uint8 InfinityUSB::GenerateChecksum(const std::array<uint8, 32>& data,
int numOfBytes) const
{
int checksum = 0;
for (int i = 0; i < numOfBytes; i++)
{
checksum += data[i];
}
return (checksum & 0xFF);
}
void InfinityUSB::GetBlankResponse(uint8 sequence,
std::array<uint8, 32>& replyBuf)
{
replyBuf[0] = 0xaa;
replyBuf[1] = 0x01;
replyBuf[2] = sequence;
replyBuf[3] = GenerateChecksum(replyBuf, 3);
}
void InfinityUSB::DescrambleAndSeed(uint8* buf, uint8 sequence,
std::array<uint8, 32>& replyBuf)
{
uint64 value = uint64(buf[4]) << 56 | uint64(buf[5]) << 48 |
uint64(buf[6]) << 40 | uint64(buf[7]) << 32 |
uint64(buf[8]) << 24 | uint64(buf[9]) << 16 |
uint64(buf[10]) << 8 | uint64(buf[11]);
uint32 seed = Descramble(value);
GenerateSeed(seed);
GetBlankResponse(sequence, replyBuf);
}
void InfinityUSB::GetNextAndScramble(uint8 sequence,
std::array<uint8, 32>& replyBuf)
{
const uint32 nextRandom = GetNext();
const uint64 scrambledNextRandom = Scramble(nextRandom, 0);
replyBuf = {0xAA, 0x09, sequence};
replyBuf[3] = uint8((scrambledNextRandom >> 56) & 0xFF);
replyBuf[4] = uint8((scrambledNextRandom >> 48) & 0xFF);
replyBuf[5] = uint8((scrambledNextRandom >> 40) & 0xFF);
replyBuf[6] = uint8((scrambledNextRandom >> 32) & 0xFF);
replyBuf[7] = uint8((scrambledNextRandom >> 24) & 0xFF);
replyBuf[8] = uint8((scrambledNextRandom >> 16) & 0xFF);
replyBuf[9] = uint8((scrambledNextRandom >> 8) & 0xFF);
replyBuf[10] = uint8(scrambledNextRandom & 0xFF);
replyBuf[11] = GenerateChecksum(replyBuf, 11);
}
uint32 InfinityUSB::Descramble(uint64 numToDescramble)
{
uint64 mask = 0x8E55AA1B3999E8AA;
uint32 ret = 0;
for (int i = 0; i < 64; i++)
{
if (mask & 0x8000000000000000)
{
ret = (ret << 1) | (numToDescramble & 0x01);
}
numToDescramble >>= 1;
mask <<= 1;
}
return ret;
}
uint64 InfinityUSB::Scramble(uint32 numToScramble, uint32 garbage)
{
uint64 mask = 0x8E55AA1B3999E8AA;
uint64 ret = 0;
for (int i = 0; i < 64; i++)
{
ret <<= 1;
if ((mask & 1) != 0)
{
ret |= (numToScramble & 1);
numToScramble >>= 1;
}
else
{
ret |= (garbage & 1);
garbage >>= 1;
}
mask >>= 1;
}
return ret;
}
void InfinityUSB::GenerateSeed(uint32 seed)
{
m_randomA = 0xF1EA5EED;
m_randomB = seed;
m_randomC = seed;
m_randomD = seed;
for (int i = 0; i < 23; i++)
{
GetNext();
}
}
uint32 InfinityUSB::GetNext()
{
uint32 a = m_randomA;
uint32 b = m_randomB;
uint32 c = m_randomC;
uint32 ret = std::rotl(m_randomB, 27);
const uint32 temp = (a + ((ret ^ 0xFFFFFFFF) + 1));
b ^= std::rotl(c, 17);
a = m_randomD;
c += a;
ret = b + temp;
a += temp;
m_randomC = a;
m_randomA = b;
m_randomB = c;
m_randomD = ret;
return ret;
}
void InfinityUSB::GetPresentFigures(uint8 sequence,
std::array<uint8, 32>& replyBuf)
{
int x = 3;
for (uint8 i = 0; i < m_figures.size(); i++)
{
uint8 slot = i == 0 ? 0x10 : (i < 4) ? 0x20
: 0x30;
if (m_figures[i].present)
{
replyBuf[x] = slot + m_figures[i].orderAdded;
replyBuf[x + 1] = 0x09;
x += 2;
}
}
replyBuf[0] = 0xaa;
replyBuf[1] = x - 2;
replyBuf[2] = sequence;
replyBuf[x] = GenerateChecksum(replyBuf, x);
}
InfinityUSB::InfinityFigure&
InfinityUSB::GetFigureByOrder(uint8 orderAdded)
{
for (uint8 i = 0; i < m_figures.size(); i++)
{
if (m_figures[i].orderAdded == orderAdded)
{
return m_figures[i];
}
}
return m_figures[0];
}
void InfinityUSB::QueryBlock(uint8 fig_num, uint8 block,
std::array<uint8, 32>& replyBuf,
uint8 sequence)
{
std::lock_guard lock(m_infinityMutex);
InfinityFigure& figure = GetFigureByOrder(fig_num);
replyBuf[0] = 0xaa;
replyBuf[1] = 0x12;
replyBuf[2] = sequence;
replyBuf[3] = 0x00;
const uint8 file_block = (block == 0) ? 1 : (block * 4);
if (figure.present && file_block < 20)
{
memcpy(&replyBuf[4], figure.data.data() + (16 * file_block), 16);
}
replyBuf[20] = GenerateChecksum(replyBuf, 20);
}
void InfinityUSB::WriteBlock(uint8 fig_num, uint8 block,
const uint8* to_write_buf,
std::array<uint8, 32>& replyBuf,
uint8 sequence)
{
std::lock_guard lock(m_infinityMutex);
InfinityFigure& figure = GetFigureByOrder(fig_num);
replyBuf[0] = 0xaa;
replyBuf[1] = 0x02;
replyBuf[2] = sequence;
replyBuf[3] = 0x00;
const uint8 file_block = (block == 0) ? 1 : (block * 4);
if (figure.present && file_block < 20)
{
memcpy(figure.data.data() + (file_block * 16), to_write_buf, 16);
figure.Save();
}
replyBuf[4] = GenerateChecksum(replyBuf, 4);
}
void InfinityUSB::GetFigureIdentifier(uint8 fig_num, uint8 sequence,
std::array<uint8, 32>& replyBuf)
{
std::lock_guard lock(m_infinityMutex);
InfinityFigure& figure = GetFigureByOrder(fig_num);
replyBuf[0] = 0xaa;
replyBuf[1] = 0x09;
replyBuf[2] = sequence;
replyBuf[3] = 0x00;
if (figure.present)
{
memcpy(&replyBuf[4], figure.data.data(), 7);
}
replyBuf[11] = GenerateChecksum(replyBuf, 11);
}
std::pair<uint8, std::string> InfinityUSB::FindFigure(uint32 figNum)
{
for (const auto& it : GetFigureList())
{
if (it.first == figNum)
{
return it.second;
}
}
return {0, fmt::format("Unknown Figure ({})", figNum)};
}
std::map<const uint32, const std::pair<const uint8, const char*>> InfinityUSB::GetFigureList()
{
return s_listFigures;
}
void InfinityUSB::InfinityFigure::Save()
{
if (!infFile)
return;
infFile->SetPosition(0);
infFile->writeData(data.data(), data.size());
}
bool InfinityUSB::RemoveFigure(uint8 position)
{
std::lock_guard lock(m_infinityMutex);
InfinityFigure& figure = m_figures[position];
figure.Save();
figure.infFile.reset();
if (figure.present)
{
figure.present = false;
position = DeriveFigurePosition(position);
if (position == 0)
{
return false;
}
std::array<uint8, 32> figureChangeResponse = {0xab, 0x04, position, 0x09, figure.orderAdded,
0x01};
figureChangeResponse[6] = GenerateChecksum(figureChangeResponse, 6);
m_figureAddedRemovedResponses.push(figureChangeResponse);
return true;
}
return false;
}
uint32
InfinityUSB::LoadFigure(const std::array<uint8, INF_FIGURE_SIZE>& buf,
std::unique_ptr<FileStream> inFile, uint8 position)
{
std::lock_guard lock(m_infinityMutex);
uint8 orderAdded;
std::vector<uint8> sha1Calc = {SHA1_CONSTANT.begin(), SHA1_CONSTANT.end() - 1};
for (int i = 0; i < 7; i++)
{
sha1Calc.push_back(buf[i]);
}
std::array<uint8, 16> key = GenerateInfinityFigureKey(sha1Calc);
std::array<uint8, 16> infinity_decrypted_block = {};
std::array<uint8, 16> encryptedBlock = {};
memcpy(encryptedBlock.data(), &buf[16], 16);
AES128_ECB_decrypt(encryptedBlock.data(), key.data(), infinity_decrypted_block.data());
uint32 number = uint32(infinity_decrypted_block[1]) << 16 | uint32(infinity_decrypted_block[2]) << 8 |
uint32(infinity_decrypted_block[3]);
InfinityFigure& figure = m_figures[position];
figure.infFile = std::move(inFile);
memcpy(figure.data.data(), buf.data(), figure.data.size());
figure.present = true;
if (figure.orderAdded == 255)
{
figure.orderAdded = m_figureOrder;
m_figureOrder++;
}
orderAdded = figure.orderAdded;
position = DeriveFigurePosition(position);
if (position == 0)
{
return 0;
}
std::array<uint8, 32> figureChangeResponse = {0xab, 0x04, position, 0x09, orderAdded, 0x00};
figureChangeResponse[6] = GenerateChecksum(figureChangeResponse, 6);
m_figureAddedRemovedResponses.push(figureChangeResponse);
return number;
}
static uint32 InfinityCRC32(const std::array<uint8, 16>& buffer)
{
static constexpr std::array<uint32, 256> CRC32_TABLE{
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535,
0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd,
0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d,
0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac,
0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab,
0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb,
0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea,
0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce,
0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409,
0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739,
0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268,
0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0,
0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8,
0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703,
0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7,
0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae,
0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6,
0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d,
0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5,
0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d};
// Infinity m_figures calculate their CRC32 based on 12 bytes in the block of 16
uint32 ret = 0;
for (uint32 i = 0; i < 12; ++i)
{
uint8 index = uint8(ret & 0xFF) ^ buffer[i];
ret = ((ret >> 8) ^ CRC32_TABLE[index]);
}
return ret;
}
bool InfinityUSB::CreateFigure(fs::path pathName, uint32 figureNum, uint8 series)
{
FileStream* infFile(FileStream::createFile2(pathName));
if (!infFile)
{
return false;
}
std::array<uint8, INF_FIGURE_SIZE> fileData{};
uint32 firstBlock = 0x17878E;
uint32 otherBlocks = 0x778788;
for (sint8 i = 2; i >= 0; i--)
{
fileData[0x38 - i] = uint8((firstBlock >> i * 8) & 0xFF);
}
for (uint32 index = 1; index < 0x05; index++)
{
for (sint8 i = 2; i >= 0; i--)
{
fileData[((index * 0x40) + 0x38) - i] = uint8((otherBlocks >> i * 8) & 0xFF);
}
}
// Create the vector to calculate the SHA1 hash with
std::vector<uint8> sha1Calc = {SHA1_CONSTANT.begin(), SHA1_CONSTANT.end() - 1};
// Generate random UID, used for AES encrypt/decrypt
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(0, 255);
std::array<uint8, 16> uid_data = {0, 0, 0, 0, 0, 0, 0, 0x89, 0x44, 0x00, 0xC2};
uid_data[0] = dist(mt);
uid_data[1] = dist(mt);
uid_data[2] = dist(mt);
uid_data[3] = dist(mt);
uid_data[4] = dist(mt);
uid_data[5] = dist(mt);
uid_data[6] = dist(mt);
for (sint8 i = 0; i < 7; i++)
{
sha1Calc.push_back(uid_data[i]);
}
std::array<uint8, 16> figureData = GenerateBlankFigureData(figureNum, series);
if (figureData[1] == 0x00)
return false;
std::array<uint8, 16> key = GenerateInfinityFigureKey(sha1Calc);
std::array<uint8, 16> encryptedBlock = {};
std::array<uint8, 16> blankBlock = {};
std::array<uint8, 16> encryptedBlank = {};
AES128_ECB_encrypt(figureData.data(), key.data(), encryptedBlock.data());
AES128_ECB_encrypt(blankBlock.data(), key.data(), encryptedBlank.data());
memcpy(&fileData[0], uid_data.data(), uid_data.size());
memcpy(&fileData[16], encryptedBlock.data(), encryptedBlock.size());
memcpy(&fileData[16 * 0x04], encryptedBlank.data(), encryptedBlank.size());
memcpy(&fileData[16 * 0x08], encryptedBlank.data(), encryptedBlank.size());
memcpy(&fileData[16 * 0x0C], encryptedBlank.data(), encryptedBlank.size());
memcpy(&fileData[16 * 0x0D], encryptedBlank.data(), encryptedBlank.size());
infFile->writeData(fileData.data(), fileData.size());
delete infFile;
return true;
}
std::array<uint8, 16> InfinityUSB::GenerateInfinityFigureKey(const std::vector<uint8>& sha1Data)
{
std::array<uint8, 20> digest = {};
SHA1(sha1Data.data(), sha1Data.size(), digest.data());
// Infinity AES keys are the first 16 bytes of the SHA1 Digest, every set of 4 bytes need to be
// reversed due to endianness
std::array<uint8, 16> key = {};
for (int i = 0; i < 4; i++)
{
for (int x = 3; x >= 0; x--)
{
key[(3 - x) + (i * 4)] = digest[x + (i * 4)];
}
}
return key;
}
std::array<uint8, 16> InfinityUSB::GenerateBlankFigureData(uint32 figureNum, uint8 series)
{
std::array<uint8, 16> figureData = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0xD1, 0x1F};
// Figure Number, input by end user
figureData[1] = uint8((figureNum >> 16) & 0xFF);
figureData[2] = uint8((figureNum >> 8) & 0xFF);
figureData[3] = uint8(figureNum & 0xFF);
// Manufacture date, formatted as YY/MM/DD. Set to release date of figure's series
if (series == 1)
{
figureData[4] = 0x0D;
figureData[5] = 0x08;
figureData[6] = 0x12;
}
else if (series == 2)
{
figureData[4] = 0x0E;
figureData[5] = 0x09;
figureData[6] = 0x12;
}
else if (series == 3)
{
figureData[4] = 0x0F;
figureData[5] = 0x08;
figureData[6] = 0x1C;
}
uint32 checksum = InfinityCRC32(figureData);
for (sint8 i = 3; i >= 0; i--)
{
figureData[15 - i] = uint8((checksum >> i * 8) & 0xFF);
}
return figureData;
}
uint8 InfinityUSB::DeriveFigurePosition(uint8 position)
{
// In the added/removed response, position needs to be 1 for the hexagon, 2 for Player 1 and
// Player 1's abilities, and 3 for Player 2 and Player 2's abilities. In the UI, positions 0, 1
// and 2 represent the hexagon slot, 3, 4 and 5 represent Player 1's slot and 6, 7 and 8 represent
// Player 2's slot.
switch (position)
{
case 0:
case 1:
case 2:
return 1;
case 3:
case 4:
case 5:
return 2;
case 6:
case 7:
case 8:
return 3;
default:
return 0;
}
}
} // namespace nsyshid
| 34,900
|
C++
|
.cpp
| 998
| 31.6002
| 104
| 0.657279
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,136
|
Whitelist.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nsyshid/Whitelist.cpp
|
#include "Whitelist.h"
namespace nsyshid
{
Whitelist& Whitelist::GetInstance()
{
static Whitelist whitelist;
return whitelist;
}
Whitelist::Whitelist()
{
// add known devices
{
// lego dimensions portal
m_devices.emplace_back(0x0e6f, 0x0241);
// skylanders portal
m_devices.emplace_back(0x1430, 0x0150);
// disney infinity base
m_devices.emplace_back(0x0e6f, 0x0129);
}
}
bool Whitelist::IsDeviceWhitelisted(uint16 vendorId, uint16 productId)
{
auto it = std::find(m_devices.begin(), m_devices.end(),
std::tuple<uint16, uint16>(vendorId, productId));
return it != m_devices.end();
}
void Whitelist::AddDevice(uint16 vendorId, uint16 productId)
{
if (!IsDeviceWhitelisted(vendorId, productId))
{
m_devices.emplace_back(vendorId, productId);
}
}
void Whitelist::RemoveDevice(uint16 vendorId, uint16 productId)
{
m_devices.remove(std::tuple<uint16, uint16>(vendorId, productId));
}
std::list<std::tuple<uint16, uint16>> Whitelist::GetDevices()
{
return m_devices;
}
void Whitelist::RemoveAllDevices()
{
m_devices.clear();
}
} // namespace nsyshid
| 1,126
|
C++
|
.cpp
| 46
| 21.695652
| 71
| 0.72973
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,137
|
AttachDefaultBackends.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nsyshid/AttachDefaultBackends.cpp
|
#include "nsyshid.h"
#include "Backend.h"
#include "BackendEmulated.h"
#if NSYSHID_ENABLE_BACKEND_LIBUSB
#include "BackendLibusb.h"
#endif
#if NSYSHID_ENABLE_BACKEND_WINDOWS_HID
#include "BackendWindowsHID.h"
#endif
namespace nsyshid::backend
{
void AttachDefaultBackends()
{
#if NSYSHID_ENABLE_BACKEND_LIBUSB
// add libusb backend
{
auto backendLibusb = std::make_shared<backend::libusb::BackendLibusb>();
if (backendLibusb->IsInitialisedOk())
{
AttachBackend(backendLibusb);
}
}
#endif // NSYSHID_ENABLE_BACKEND_LIBUSB
#if NSYSHID_ENABLE_BACKEND_WINDOWS_HID
// add windows hid backend
{
auto backendWindowsHID = std::make_shared<backend::windows::BackendWindowsHID>();
if (backendWindowsHID->IsInitialisedOk())
{
AttachBackend(backendWindowsHID);
}
}
#endif // NSYSHID_ENABLE_BACKEND_WINDOWS_HID
// add emulated backend
{
auto backendEmulated = std::make_shared<backend::emulated::BackendEmulated>();
if (backendEmulated->IsInitialisedOk())
{
AttachBackend(backendEmulated);
}
}
}
} // namespace nsyshid::backend
| 1,093
|
C++
|
.cpp
| 43
| 22.604651
| 84
| 0.750719
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,138
|
Skylander.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nsyshid/Skylander.cpp
|
#include "Skylander.h"
#include <random>
#include "nsyshid.h"
#include "Backend.h"
#include "Common/FileStream.h"
namespace nsyshid
{
SkylanderUSB g_skyportal;
const std::map<const std::pair<const uint16, const uint16>, const char*>
s_listSkylanders = {
{{0, 0x0000}, "Whirlwind"},
{{0, 0x1801}, "Series 2 Whirlwind"},
{{0, 0x1C02}, "Polar Whirlwind"},
{{0, 0x2805}, "Horn Blast Whirlwind"},
{{0, 0x3810}, "Eon's Elite Whirlwind"},
{{1, 0x0000}, "Sonic Boom"},
{{1, 0x1801}, "Series 2 Sonic Boom"},
{{2, 0x0000}, "Warnado"},
{{2, 0x2206}, "LightCore Warnado"},
{{3, 0x0000}, "Lightning Rod"},
{{3, 0x1801}, "Series 2 Lightning Rod"},
{{4, 0x0000}, "Bash"},
{{4, 0x1801}, "Series 2 Bash"},
{{5, 0x0000}, "Terrafin"},
{{5, 0x1801}, "Series 2 Terrafin"},
{{5, 0x2805}, "Knockout Terrafin"},
{{5, 0x3810}, "Eon's Elite Terrafin"},
{{6, 0x0000}, "Dino Rang"},
{{6, 0x4810}, "Eon's Elite Dino Rang"},
{{7, 0x0000}, "Prism Break"},
{{7, 0x1801}, "Series 2 Prism Break"},
{{7, 0x2805}, "Hyper Beam Prism Break"},
{{7, 0x1206}, "LightCore Prism Break"},
{{8, 0x0000}, "Sunburn"},
{{9, 0x0000}, "Eruptor"},
{{9, 0x1801}, "Series 2 Eruptor"},
{{9, 0x2C02}, "Volcanic Eruptor"},
{{9, 0x2805}, "Lava Barf Eruptor"},
{{9, 0x1206}, "LightCore Eruptor"},
{{9, 0x3810}, "Eon's Elite Eruptor"},
{{10, 0x0000}, "Ignitor"},
{{10, 0x1801}, "Series 2 Ignitor"},
{{10, 0x1C03}, "Legendary Ignitor"},
{{11, 0x0000}, "Flameslinger"},
{{11, 0x1801}, "Series 2 Flameslinger"},
{{12, 0x0000}, "Zap"},
{{12, 0x1801}, "Series 2 Zap"},
{{13, 0x0000}, "Wham Shell"},
{{13, 0x2206}, "LightCore Wham Shell"},
{{14, 0x0000}, "Gill Grunt"},
{{14, 0x1801}, "Series 2 Gill Grunt"},
{{14, 0x2805}, "Anchors Away Gill Grunt"},
{{14, 0x3805}, "Tidal Wave Gill Grunt"},
{{14, 0x3810}, "Eon's Elite Gill Grunt"},
{{15, 0x0000}, "Slam Bam"},
{{15, 0x1801}, "Series 2 Slam Bam"},
{{15, 0x1C03}, "Legendary Slam Bam"},
{{15, 0x4810}, "Eon's Elite Slam Bam"},
{{16, 0x0000}, "Spyro"},
{{16, 0x1801}, "Series 2 Spyro"},
{{16, 0x2C02}, "Dark Mega Ram Spyro"},
{{16, 0x2805}, "Mega Ram Spyro"},
{{16, 0x3810}, "Eon's Elite Spyro"},
{{17, 0x0000}, "Voodood"},
{{17, 0x4810}, "Eon's Elite Voodood"},
{{18, 0x0000}, "Double Trouble"},
{{18, 0x1801}, "Series 2 Double Trouble"},
{{18, 0x1C02}, "Royal Double Trouble"},
{{19, 0x0000}, "Trigger Happy"},
{{19, 0x1801}, "Series 2 Trigger Happy"},
{{19, 0x2C02}, "Springtime Trigger Happy"},
{{19, 0x2805}, "Big Bang Trigger Happy"},
{{19, 0x3810}, "Eon's Elite Trigger Happy"},
{{20, 0x0000}, "Drobot"},
{{20, 0x1801}, "Series 2 Drobot"},
{{20, 0x1206}, "LightCore Drobot"},
{{21, 0x0000}, "Drill Seargeant"},
{{21, 0x1801}, "Series 2 Drill Seargeant"},
{{22, 0x0000}, "Boomer"},
{{22, 0x4810}, "Eon's Elite Boomer"},
{{23, 0x0000}, "Wrecking Ball"},
{{23, 0x1801}, "Series 2 Wrecking Ball"},
{{24, 0x0000}, "Camo"},
{{24, 0x2805}, "Thorn Horn Camo"},
{{25, 0x0000}, "Zook"},
{{25, 0x1801}, "Series 2 Zook"},
{{25, 0x4810}, "Eon's Elite Zook"},
{{26, 0x0000}, "Stealth Elf"},
{{26, 0x1801}, "Series 2 Stealth Elf"},
{{26, 0x2C02}, "Dark Stealth Elf"},
{{26, 0x1C03}, "Legendary Stealth Elf"},
{{26, 0x2805}, "Ninja Stealth Elf"},
{{26, 0x3810}, "Eon's Elite Stealth Elf"},
{{27, 0x0000}, "Stump Smash"},
{{27, 0x1801}, "Series 2 Stump Smash"},
{{28, 0x0000}, "Dark Spyro"},
{{29, 0x0000}, "Hex"},
{{29, 0x1801}, "Series 2 Hex"},
{{29, 0x1206}, "LightCore Hex"},
{{30, 0x0000}, "Chop Chop"},
{{30, 0x1801}, "Series 2 Chop Chop"},
{{30, 0x2805}, "Twin Blade Chop Chop"},
{{30, 0x3810}, "Eon's Elite Chop Chop"},
{{31, 0x0000}, "Ghost Roaster"},
{{31, 0x4810}, "Eon's Elite Ghost Roaster"},
{{32, 0x0000}, "Cynder"},
{{32, 0x1801}, "Series 2 Cynder"},
{{32, 0x2805}, "Phantom Cynder"},
{{100, 0x0000}, "Jet Vac"},
{{100, 0x1403}, "Legendary Jet Vac"},
{{100, 0x2805}, "Turbo Jet Vac"},
{{100, 0x3805}, "Full Blast Jet Vac"},
{{100, 0x1206}, "LightCore Jet Vac"},
{{101, 0x0000}, "Swarm"},
{{102, 0x0000}, "Crusher"},
{{102, 0x1602}, "Granite Crusher"},
{{103, 0x0000}, "Flashwing"},
{{103, 0x1402}, "Jade Flash Wing"},
{{103, 0x2206}, "LightCore Flashwing"},
{{104, 0x0000}, "Hot Head"},
{{105, 0x0000}, "Hot Dog"},
{{105, 0x1402}, "Molten Hot Dog"},
{{105, 0x2805}, "Fire Bone Hot Dog"},
{{106, 0x0000}, "Chill"},
{{106, 0x1603}, "Legendary Chill"},
{{106, 0x2805}, "Blizzard Chill"},
{{106, 0x1206}, "LightCore Chill"},
{{107, 0x0000}, "Thumpback"},
{{108, 0x0000}, "Pop Fizz"},
{{108, 0x1402}, "Punch Pop Fizz"},
{{108, 0x3C02}, "Love Potion Pop Fizz"},
{{108, 0x2805}, "Super Gulp Pop Fizz"},
{{108, 0x3805}, "Fizzy Frenzy Pop Fizz"},
{{108, 0x1206}, "LightCore Pop Fizz"},
{{109, 0x0000}, "Ninjini"},
{{109, 0x1602}, "Scarlet Ninjini"},
{{110, 0x0000}, "Bouncer"},
{{110, 0x1603}, "Legendary Bouncer"},
{{111, 0x0000}, "Sprocket"},
{{111, 0x2805}, "Heavy Duty Sprocket"},
{{112, 0x0000}, "Tree Rex"},
{{112, 0x1602}, "Gnarly Tree Rex"},
{{113, 0x0000}, "Shroomboom"},
{{113, 0x3805}, "Sure Shot Shroomboom"},
{{113, 0x1206}, "LightCore Shroomboom"},
{{114, 0x0000}, "Eye Brawl"},
{{115, 0x0000}, "Fright Rider"},
{{200, 0x0000}, "Anvil Rain"},
{{201, 0x0000}, "Hidden Treasure"},
{{201, 0x2000}, "Platinum Hidden Treasure"},
{{202, 0x0000}, "Healing Elixir"},
{{203, 0x0000}, "Ghost Pirate Swords"},
{{204, 0x0000}, "Time Twist Hourglass"},
{{205, 0x0000}, "Sky Iron Shield"},
{{206, 0x0000}, "Winged Boots"},
{{207, 0x0000}, "Sparx the Dragonfly"},
{{208, 0x0000}, "Dragonfire Cannon"},
{{208, 0x1602}, "Golden Dragonfire Cannon"},
{{209, 0x0000}, "Scorpion Striker"},
{{210, 0x3002}, "Biter's Bane"},
{{210, 0x3008}, "Sorcerous Skull"},
{{210, 0x300B}, "Axe of Illusion"},
{{210, 0x300E}, "Arcane Hourglass"},
{{210, 0x3012}, "Spell Slapper"},
{{210, 0x3014}, "Rune Rocket"},
{{211, 0x3001}, "Tidal Tiki"},
{{211, 0x3002}, "Wet Walter"},
{{211, 0x3006}, "Flood Flask"},
{{211, 0x3406}, "Legendary Flood Flask"},
{{211, 0x3007}, "Soaking Staff"},
{{211, 0x300B}, "Aqua Axe"},
{{211, 0x3016}, "Frost Helm"},
{{212, 0x3003}, "Breezy Bird"},
{{212, 0x3006}, "Drafty Decanter"},
{{212, 0x300D}, "Tempest Timer"},
{{212, 0x3010}, "Cloudy Cobra"},
{{212, 0x3011}, "Storm Warning"},
{{212, 0x3018}, "Cyclone Saber"},
{{213, 0x3004}, "Spirit Sphere"},
{{213, 0x3404}, "Legendary Spirit Sphere"},
{{213, 0x3008}, "Spectral Skull"},
{{213, 0x3408}, "Legendary Spectral Skull"},
{{213, 0x300B}, "Haunted Hatchet"},
{{213, 0x300C}, "Grim Gripper"},
{{213, 0x3010}, "Spooky Snake"},
{{213, 0x3017}, "Dream Piercer"},
{{214, 0x3000}, "Tech Totem"},
{{214, 0x3007}, "Automatic Angel"},
{{214, 0x3009}, "Factory Flower"},
{{214, 0x300C}, "Grabbing Gadget"},
{{214, 0x3016}, "Makers Mana"},
{{214, 0x301A}, "Topsy Techy"},
{{215, 0x3005}, "Eternal Flame"},
{{215, 0x3009}, "Fire Flower"},
{{215, 0x3011}, "Scorching Stopper"},
{{215, 0x3012}, "Searing Spinner"},
{{215, 0x3017}, "Spark Spear"},
{{215, 0x301B}, "Blazing Belch"},
{{216, 0x3000}, "Banded Boulder"},
{{216, 0x3003}, "Rock Hawk"},
{{216, 0x300A}, "Slag Hammer"},
{{216, 0x300E}, "Dust Of Time"},
{{216, 0x3013}, "Spinning Sandstorm"},
{{216, 0x301A}, "Rubble Trouble"},
{{217, 0x3003}, "Oak Eagle"},
{{217, 0x3005}, "Emerald Energy"},
{{217, 0x300A}, "Weed Whacker"},
{{217, 0x3010}, "Seed Serpent"},
{{217, 0x3018}, "Jade Blade"},
{{217, 0x301B}, "Shrub Shrieker"},
{{218, 0x3000}, "Dark Dagger"},
{{218, 0x3014}, "Shadow Spider"},
{{218, 0x301A}, "Ghastly Grimace"},
{{219, 0x3000}, "Shining Ship"},
{{219, 0x300F}, "Heavenly Hawk"},
{{219, 0x301B}, "Beam Scream"},
{{220, 0x301E}, "Kaos Trap"},
{{220, 0x351F}, "Ultimate Kaos Trap"},
{{230, 0x0000}, "Hand of Fate"},
{{230, 0x3403}, "Legendary Hand of Fate"},
{{231, 0x0000}, "Piggy Bank"},
{{232, 0x0000}, "Rocket Ram"},
{{233, 0x0000}, "Tiki Speaky"},
{{300, 0x0000}, "Dragon’s Peak"},
{{301, 0x0000}, "Empire of Ice"},
{{302, 0x0000}, "Pirate Seas"},
{{303, 0x0000}, "Darklight Crypt"},
{{304, 0x0000}, "Volcanic Vault"},
{{305, 0x0000}, "Mirror of Mystery"},
{{306, 0x0000}, "Nightmare Express"},
{{307, 0x0000}, "Sunscraper Spire"},
{{308, 0x0000}, "Midnight Museum"},
{{404, 0x0000}, "Legendary Bash"},
{{416, 0x0000}, "Legendary Spyro"},
{{419, 0x0000}, "Legendary Trigger Happy"},
{{430, 0x0000}, "Legendary Chop Chop"},
{{450, 0x0000}, "Gusto"},
{{451, 0x0000}, "Thunderbolt"},
{{452, 0x0000}, "Fling Kong"},
{{453, 0x0000}, "Blades"},
{{453, 0x3403}, "Legendary Blades"},
{{454, 0x0000}, "Wallop"},
{{455, 0x0000}, "Head Rush"},
{{455, 0x3402}, "Nitro Head Rush"},
{{456, 0x0000}, "Fist Bump"},
{{457, 0x0000}, "Rocky Roll"},
{{458, 0x0000}, "Wildfire"},
{{458, 0x3402}, "Dark Wildfire"},
{{459, 0x0000}, "Ka Boom"},
{{460, 0x0000}, "Trail Blazer"},
{{461, 0x0000}, "Torch"},
{{462, 0x3000}, "Snap Shot"},
{{462, 0x3402}, "Dark Snap Shot"},
{{463, 0x0000}, "Lob Star"},
{{463, 0x3402}, "Winterfest Lob-Star"},
{{464, 0x0000}, "Flip Wreck"},
{{465, 0x0000}, "Echo"},
{{466, 0x0000}, "Blastermind"},
{{467, 0x0000}, "Enigma"},
{{468, 0x0000}, "Deja Vu"},
{{468, 0x3403}, "Legendary Deja Vu"},
{{469, 0x0000}, "Cobra Candabra"},
{{469, 0x3402}, "King Cobra Cadabra"},
{{470, 0x0000}, "Jawbreaker"},
{{470, 0x3403}, "Legendary Jawbreaker"},
{{471, 0x0000}, "Gearshift"},
{{472, 0x0000}, "Chopper"},
{{473, 0x0000}, "Tread Head"},
{{474, 0x0000}, "Bushwack"},
{{474, 0x3403}, "Legendary Bushwack"},
{{475, 0x0000}, "Tuff Luck"},
{{476, 0x0000}, "Food Fight"},
{{476, 0x3402}, "Dark Food Fight"},
{{477, 0x0000}, "High Five"},
{{478, 0x0000}, "Krypt King"},
{{478, 0x3402}, "Nitro Krypt King"},
{{479, 0x0000}, "Short Cut"},
{{480, 0x0000}, "Bat Spin"},
{{481, 0x0000}, "Funny Bone"},
{{482, 0x0000}, "Knight Light"},
{{483, 0x0000}, "Spotlight"},
{{484, 0x0000}, "Knight Mare"},
{{485, 0x0000}, "Blackout"},
{{502, 0x0000}, "Bop"},
{{505, 0x0000}, "Terrabite"},
{{506, 0x0000}, "Breeze"},
{{508, 0x0000}, "Pet Vac"},
{{508, 0x3402}, "Power Punch Pet Vac"},
{{507, 0x0000}, "Weeruptor"},
{{507, 0x3402}, "Eggcellent Weeruptor"},
{{509, 0x0000}, "Small Fry"},
{{510, 0x0000}, "Drobit"},
{{519, 0x0000}, "Trigger Snappy"},
{{526, 0x0000}, "Whisper Elf"},
{{540, 0x0000}, "Barkley"},
{{540, 0x3402}, "Gnarly Barkley"},
{{541, 0x0000}, "Thumpling"},
{{514, 0x0000}, "Gill Runt"},
{{542, 0x0000}, "Mini-Jini"},
{{503, 0x0000}, "Spry"},
{{504, 0x0000}, "Hijinx"},
{{543, 0x0000}, "Eye Small"},
{{601, 0x0000}, "King Pen"},
{{602, 0x0000}, "Tri-Tip"},
{{603, 0x0000}, "Chopscotch"},
{{604, 0x0000}, "Boom Bloom"},
{{605, 0x0000}, "Pit Boss"},
{{606, 0x0000}, "Barbella"},
{{607, 0x0000}, "Air Strike"},
{{608, 0x0000}, "Ember"},
{{609, 0x0000}, "Ambush"},
{{610, 0x0000}, "Dr. Krankcase"},
{{611, 0x0000}, "Hood Sickle"},
{{612, 0x0000}, "Tae Kwon Crow"},
{{613, 0x0000}, "Golden Queen"},
{{614, 0x0000}, "Wolfgang"},
{{615, 0x0000}, "Pain-Yatta"},
{{616, 0x0000}, "Mysticat"},
{{617, 0x0000}, "Starcast"},
{{618, 0x0000}, "Buckshot"},
{{619, 0x0000}, "Aurora"},
{{620, 0x0000}, "Flare Wolf"},
{{621, 0x0000}, "Chompy Mage"},
{{622, 0x0000}, "Bad Juju"},
{{623, 0x0000}, "Grave Clobber"},
{{624, 0x0000}, "Blaster-Tron"},
{{625, 0x0000}, "Ro-Bow"},
{{626, 0x0000}, "Chain Reaction"},
{{627, 0x0000}, "Kaos"},
{{628, 0x0000}, "Wild Storm"},
{{629, 0x0000}, "Tidepool"},
{{630, 0x0000}, "Crash Bandicoot"},
{{631, 0x0000}, "Dr. Neo Cortex"},
{{1000, 0x0000}, "Boom Jet (Bottom)"},
{{1001, 0x0000}, "Free Ranger (Bottom)"},
{{1001, 0x2403}, "Legendary Free Ranger (Bottom)"},
{{1002, 0x0000}, "Rubble Rouser (Bottom)"},
{{1003, 0x0000}, "Doom Stone (Bottom)"},
{{1004, 0x0000}, "Blast Zone (Bottom)"},
{{1004, 0x2402}, "Dark Blast Zone (Bottom)"},
{{1005, 0x0000}, "Fire Kraken (Bottom)"},
{{1005, 0x2402}, "Jade Fire Kraken (Bottom)"},
{{1006, 0x0000}, "Stink Bomb (Bottom)"},
{{1007, 0x0000}, "Grilla Drilla (Bottom)"},
{{1008, 0x0000}, "Hoot Loop (Bottom)"},
{{1008, 0x2402}, "Enchanted Hoot Loop (Bottom)"},
{{1009, 0x0000}, "Trap Shadow (Bottom)"},
{{1010, 0x0000}, "Magna Charge (Bottom)"},
{{1010, 0x2402}, "Nitro Magna Charge (Bottom)"},
{{1011, 0x0000}, "Spy Rise (Bottom)"},
{{1012, 0x0000}, "Night Shift (Bottom)"},
{{1012, 0x2403}, "Legendary Night Shift (Bottom)"},
{{1013, 0x0000}, "Rattle Shake (Bottom)"},
{{1013, 0x2402}, "Quick Draw Rattle Shake (Bottom)"},
{{1014, 0x0000}, "Freeze Blade (Bottom)"},
{{1014, 0x2402}, "Nitro Freeze Blade (Bottom)"},
{{1015, 0x0000}, "Wash Buckler (Bottom)"},
{{1015, 0x2402}, "Dark Wash Buckler (Bottom)"},
{{2000, 0x0000}, "Boom Jet (Top)"},
{{2001, 0x0000}, "Free Ranger (Top)"},
{{2001, 0x2403}, "Legendary Free Ranger (Top)"},
{{2002, 0x0000}, "Rubble Rouser (Top)"},
{{2003, 0x0000}, "Doom Stone (Top)"},
{{2004, 0x0000}, "Blast Zone (Top)"},
{{2004, 0x2402}, "Dark Blast Zone (Top)"},
{{2005, 0x0000}, "Fire Kraken (Top)"},
{{2005, 0x2402}, "Jade Fire Kraken (Top)"},
{{2006, 0x0000}, "Stink Bomb (Top)"},
{{2007, 0x0000}, "Grilla Drilla (Top)"},
{{2008, 0x0000}, "Hoot Loop (Top)"},
{{2008, 0x2402}, "Enchanted Hoot Loop (Top)"},
{{2009, 0x0000}, "Trap Shadow (Top)"},
{{2010, 0x0000}, "Magna Charge (Top)"},
{{2010, 0x2402}, "Nitro Magna Charge (Top)"},
{{2011, 0x0000}, "Spy Rise (Top)"},
{{2012, 0x0000}, "Night Shift (Top)"},
{{2012, 0x2403}, "Legendary Night Shift (Top)"},
{{2013, 0x0000}, "Rattle Shake (Top)"},
{{2013, 0x2402}, "Quick Draw Rattle Shake (Top)"},
{{2014, 0x0000}, "Freeze Blade (Top)"},
{{2014, 0x2402}, "Nitro Freeze Blade (Top)"},
{{2015, 0x0000}, "Wash Buckler (Top)"},
{{2015, 0x2402}, "Dark Wash Buckler (Top)"},
{{3000, 0x0000}, "Scratch"},
{{3001, 0x0000}, "Pop Thorn"},
{{3002, 0x0000}, "Slobber Tooth"},
{{3002, 0x2402}, "Dark Slobber Tooth"},
{{3003, 0x0000}, "Scorp"},
{{3004, 0x0000}, "Fryno"},
{{3004, 0x3805}, "Hog Wild Fryno"},
{{3005, 0x0000}, "Smolderdash"},
{{3005, 0x2206}, "LightCore Smolderdash"},
{{3006, 0x0000}, "Bumble Blast"},
{{3006, 0x2402}, "Jolly Bumble Blast"},
{{3006, 0x2206}, "LightCore Bumble Blast"},
{{3007, 0x0000}, "Zoo Lou"},
{{3007, 0x2403}, "Legendary Zoo Lou"},
{{3008, 0x0000}, "Dune Bug"},
{{3009, 0x0000}, "Star Strike"},
{{3009, 0x2602}, "Enchanted Star Strike"},
{{3009, 0x2206}, "LightCore Star Strike"},
{{3010, 0x0000}, "Countdown"},
{{3010, 0x2402}, "Kickoff Countdown"},
{{3010, 0x2206}, "LightCore Countdown"},
{{3011, 0x0000}, "Wind Up"},
{{3011, 0x2404}, "Gear Head VVind Up"},
{{3012, 0x0000}, "Roller Brawl"},
{{3013, 0x0000}, "Grim Creeper"},
{{3013, 0x2603}, "Legendary Grim Creeper"},
{{3013, 0x2206}, "LightCore Grim Creeper"},
{{3014, 0x0000}, "Rip Tide"},
{{3015, 0x0000}, "Punk Shock"},
{{3200, 0x0000}, "Battle Hammer"},
{{3201, 0x0000}, "Sky Diamond"},
{{3202, 0x0000}, "Platinum Sheep"},
{{3203, 0x0000}, "Groove Machine"},
{{3204, 0x0000}, "UFO Hat"},
{{3300, 0x0000}, "Sheep Wreck Island"},
{{3301, 0x0000}, "Tower of Time"},
{{3302, 0x0000}, "Fiery Forge"},
{{3303, 0x0000}, "Arkeyan Crossbow"},
{{3220, 0x0000}, "Jet Stream"},
{{3221, 0x0000}, "Tomb Buggy"},
{{3222, 0x0000}, "Reef Ripper"},
{{3223, 0x0000}, "Burn Cycle"},
{{3224, 0x0000}, "Hot Streak"},
{{3224, 0x4402}, "Dark Hot Streak"},
{{3224, 0x4004}, "E3 Hot Streak"},
{{3224, 0x441E}, "Golden Hot Streak"},
{{3225, 0x0000}, "Shark Tank"},
{{3226, 0x0000}, "Thump Truck"},
{{3227, 0x0000}, "Crypt Crusher"},
{{3228, 0x0000}, "Stealth Stinger"},
{{3228, 0x4402}, "Nitro Stealth Stinger"},
{{3231, 0x0000}, "Dive Bomber"},
{{3231, 0x4402}, "Spring Ahead Dive Bomber"},
{{3232, 0x0000}, "Sky Slicer"},
{{3233, 0x0000}, "Clown Cruiser (Nintendo Only)"},
{{3233, 0x4402}, "Dark Clown Cruiser (Nintendo Only)"},
{{3234, 0x0000}, "Gold Rusher"},
{{3234, 0x4402}, "Power Blue Gold Rusher"},
{{3235, 0x0000}, "Shield Striker"},
{{3236, 0x0000}, "Sun Runner"},
{{3236, 0x4403}, "Legendary Sun Runner"},
{{3237, 0x0000}, "Sea Shadow"},
{{3237, 0x4402}, "Dark Sea Shadow"},
{{3238, 0x0000}, "Splatter Splasher"},
{{3238, 0x4402}, "Power Blue Splatter Splasher"},
{{3239, 0x0000}, "Soda Skimmer"},
{{3239, 0x4402}, "Nitro Soda Skimmer"},
{{3240, 0x0000}, "Barrel Blaster (Nintendo Only)"},
{{3240, 0x4402}, "Dark Barrel Blaster (Nintendo Only)"},
{{3241, 0x0000}, "Buzz Wing"},
{{3400, 0x0000}, "Fiesta"},
{{3400, 0x4515}, "Frightful Fiesta"},
{{3401, 0x0000}, "High Volt"},
{{3402, 0x0000}, "Splat"},
{{3402, 0x4502}, "Power Blue Splat"},
{{3406, 0x0000}, "Stormblade"},
{{3411, 0x0000}, "Smash Hit"},
{{3411, 0x4502}, "Steel Plated Smash Hit"},
{{3412, 0x0000}, "Spitfire"},
{{3412, 0x4502}, "Dark Spitfire"},
{{3413, 0x0000}, "Hurricane Jet Vac"},
{{3413, 0x4503}, "Legendary Hurricane Jet Vac"},
{{3414, 0x0000}, "Double Dare Trigger Happy"},
{{3414, 0x4502}, "Power Blue Double Dare Trigger Happy"},
{{3415, 0x0000}, "Super Shot Stealth Elf"},
{{3415, 0x4502}, "Dark Super Shot Stealth Elf"},
{{3416, 0x0000}, "Shark Shooter Terrafin"},
{{3417, 0x0000}, "Bone Bash Roller Brawl"},
{{3417, 0x4503}, "Legendary Bone Bash Roller Brawl"},
{{3420, 0x0000}, "Big Bubble Pop Fizz"},
{{3420, 0x450E}, "Birthday Bash Big Bubble Pop Fizz"},
{{3421, 0x0000}, "Lava Lance Eruptor"},
{{3422, 0x0000}, "Deep Dive Gill Grunt"},
{{3423, 0x0000}, "Turbo Charge Donkey Kong (Nintendo Only)"},
{{3423, 0x4502}, "Dark Turbo Charge Donkey Kong (Nintendo Only)"},
{{3424, 0x0000}, "Hammer Slam Bowser (Nintendo Only)"},
{{3424, 0x4502}, "Dark Hammer Slam Bowser (Nintendo Only)"},
{{3425, 0x0000}, "Dive-Clops"},
{{3425, 0x450E}, "Missile-Tow Dive-Clops"},
{{3426, 0x0000}, "Astroblast"},
{{3426, 0x4503}, "Legendary Astroblast"},
{{3427, 0x0000}, "Nightfall"},
{{3428, 0x0000}, "Thrillipede"},
{{3428, 0x450D}, "Eggcited Thrillipede"},
{{3500, 0x0000}, "Sky Trophy"},
{{3501, 0x0000}, "Land Trophy"},
{{3502, 0x0000}, "Sea Trophy"},
{{3503, 0x0000}, "Kaos Trophy"},
};
uint16 SkylanderUSB::SkylanderCRC16(uint16 initValue, const uint8* buffer, uint32 size)
{
const unsigned short CRC_CCITT_TABLE[256] = {0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273,
0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528,
0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886,
0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF,
0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5,
0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2,
0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8,
0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691,
0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F,
0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64,
0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0};
uint16 crc = initValue;
for (uint32 i = 0; i < size; i++)
{
const uint16 tmp = (crc >> 8) ^ buffer[i];
crc = (crc << 8) ^ CRC_CCITT_TABLE[tmp];
}
return crc;
}
SkylanderPortalDevice::SkylanderPortalDevice()
: Device(0x1430, 0x0150, 1, 2, 0)
{
m_IsOpened = false;
}
bool SkylanderPortalDevice::Open()
{
if (!IsOpened())
{
m_IsOpened = true;
}
return true;
}
void SkylanderPortalDevice::Close()
{
if (IsOpened())
{
m_IsOpened = false;
}
}
bool SkylanderPortalDevice::IsOpened()
{
return m_IsOpened;
}
Device::ReadResult SkylanderPortalDevice::Read(ReadMessage* message)
{
memcpy(message->data, g_skyportal.GetStatus().data(), message->length);
message->bytesRead = message->length;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
return Device::ReadResult::Success;
}
Device::WriteResult SkylanderPortalDevice::Write(WriteMessage* message)
{
message->bytesWritten = message->length;
return Device::WriteResult::Success;
}
bool SkylanderPortalDevice::GetDescriptor(uint8 descType,
uint8 descIndex,
uint8 lang,
uint8* output,
uint32 outputMaxLength)
{
uint8 configurationDescriptor[0x29];
uint8* currentWritePtr;
// configuration descriptor
currentWritePtr = configurationDescriptor + 0;
*(uint8*)(currentWritePtr + 0) = 9; // bLength
*(uint8*)(currentWritePtr + 1) = 2; // bDescriptorType
*(uint16be*)(currentWritePtr + 2) = 0x0029; // wTotalLength
*(uint8*)(currentWritePtr + 4) = 1; // bNumInterfaces
*(uint8*)(currentWritePtr + 5) = 1; // bConfigurationValue
*(uint8*)(currentWritePtr + 6) = 0; // iConfiguration
*(uint8*)(currentWritePtr + 7) = 0x80; // bmAttributes
*(uint8*)(currentWritePtr + 8) = 0xFA; // MaxPower
currentWritePtr = currentWritePtr + 9;
// configuration descriptor
*(uint8*)(currentWritePtr + 0) = 9; // bLength
*(uint8*)(currentWritePtr + 1) = 0x04; // bDescriptorType
*(uint8*)(currentWritePtr + 2) = 0; // bInterfaceNumber
*(uint8*)(currentWritePtr + 3) = 0; // bAlternateSetting
*(uint8*)(currentWritePtr + 4) = 2; // bNumEndpoints
*(uint8*)(currentWritePtr + 5) = 3; // bInterfaceClass
*(uint8*)(currentWritePtr + 6) = 0; // bInterfaceSubClass
*(uint8*)(currentWritePtr + 7) = 0; // bInterfaceProtocol
*(uint8*)(currentWritePtr + 8) = 0; // iInterface
currentWritePtr = currentWritePtr + 9;
// configuration descriptor
*(uint8*)(currentWritePtr + 0) = 9; // bLength
*(uint8*)(currentWritePtr + 1) = 0x21; // bDescriptorType
*(uint16be*)(currentWritePtr + 2) = 0x0111; // bcdHID
*(uint8*)(currentWritePtr + 4) = 0x00; // bCountryCode
*(uint8*)(currentWritePtr + 5) = 0x01; // bNumDescriptors
*(uint8*)(currentWritePtr + 6) = 0x22; // bDescriptorType
*(uint16be*)(currentWritePtr + 7) = 0x001D; // wDescriptorLength
currentWritePtr = currentWritePtr + 9;
// endpoint descriptor 1
*(uint8*)(currentWritePtr + 0) = 7; // bLength
*(uint8*)(currentWritePtr + 1) = 0x05; // bDescriptorType
*(uint8*)(currentWritePtr + 2) = 0x81; // bEndpointAddress
*(uint8*)(currentWritePtr + 3) = 0x03; // bmAttributes
*(uint16be*)(currentWritePtr + 4) = 0x40; // wMaxPacketSize
*(uint8*)(currentWritePtr + 6) = 0x01; // bInterval
currentWritePtr = currentWritePtr + 7;
// endpoint descriptor 2
*(uint8*)(currentWritePtr + 0) = 7; // bLength
*(uint8*)(currentWritePtr + 1) = 0x05; // bDescriptorType
*(uint8*)(currentWritePtr + 2) = 0x02; // bEndpointAddress
*(uint8*)(currentWritePtr + 3) = 0x03; // bmAttributes
*(uint16be*)(currentWritePtr + 4) = 0x40; // wMaxPacketSize
*(uint8*)(currentWritePtr + 6) = 0x01; // bInterval
currentWritePtr = currentWritePtr + 7;
cemu_assert_debug((currentWritePtr - configurationDescriptor) == 0x29);
memcpy(output, configurationDescriptor,
std::min<uint32>(outputMaxLength, sizeof(configurationDescriptor)));
return true;
}
bool SkylanderPortalDevice::SetProtocol(uint8 ifIndex, uint8 protocol)
{
return true;
}
bool SkylanderPortalDevice::SetReport(ReportMessage* message)
{
g_skyportal.ControlTransfer(message->originalData, message->originalLength);
std::this_thread::sleep_for(std::chrono::milliseconds(1));
return true;
}
void SkylanderUSB::ControlTransfer(uint8* buf, sint32 originalLength)
{
std::array<uint8, 64> interruptResponse = {};
switch (buf[0])
{
case 'A':
{
interruptResponse = {buf[0], buf[1], 0xFF, 0x77};
g_skyportal.Activate();
break;
}
case 'C':
{
g_skyportal.SetLeds(0x01, buf[1], buf[2], buf[3]);
break;
}
case 'J':
{
g_skyportal.SetLeds(buf[1], buf[2], buf[3], buf[4]);
interruptResponse = {buf[0]};
break;
}
case 'L':
{
uint8 side = buf[1];
if (side == 0x02)
{
side = 0x04;
}
g_skyportal.SetLeds(side, buf[2], buf[3], buf[4]);
break;
}
case 'M':
{
interruptResponse = {buf[0], buf[1], 0x00, 0x19};
break;
}
case 'Q':
{
const uint8 skyNum = buf[1] & 0xF;
const uint8 block = buf[2];
g_skyportal.QueryBlock(skyNum, block, interruptResponse.data());
break;
}
case 'R':
{
interruptResponse = {buf[0], 0x02, 0x1b};
break;
}
case 'S':
case 'V':
{
// No response needed
break;
}
case 'W':
{
const uint8 skyNum = buf[1] & 0xF;
const uint8 block = buf[2];
g_skyportal.WriteBlock(skyNum, block, &buf[3], interruptResponse.data());
break;
}
default:
cemu_assert_error();
break;
}
if (interruptResponse[0] != 0)
{
std::lock_guard lock(m_queryMutex);
m_queries.push(interruptResponse);
}
}
void SkylanderUSB::Activate()
{
std::lock_guard lock(m_skyMutex);
if (m_activated)
{
// If the portal was already active no change is needed
return;
}
// If not we need to advertise change to all the figures present on the portal
for (auto& s : m_skylanders)
{
if (s.status & 1)
{
s.queuedStatus.push(3);
s.queuedStatus.push(1);
}
}
m_activated = true;
}
void SkylanderUSB::Deactivate()
{
std::lock_guard lock(m_skyMutex);
for (auto& s : m_skylanders)
{
// check if at the end of the updates there would be a figure on the portal
if (!s.queuedStatus.empty())
{
s.status = s.queuedStatus.back();
s.queuedStatus = std::queue<uint8>();
}
s.status &= 1;
}
m_activated = false;
}
void SkylanderUSB::SetLeds(uint8 side, uint8 r, uint8 g, uint8 b)
{
std::lock_guard lock(m_skyMutex);
if (side == 0x00)
{
m_colorRight.red = r;
m_colorRight.green = g;
m_colorRight.blue = b;
}
else if (side == 0x01)
{
m_colorRight.red = r;
m_colorRight.green = g;
m_colorRight.blue = b;
m_colorLeft.red = r;
m_colorLeft.green = g;
m_colorLeft.blue = b;
}
else if (side == 0x02)
{
m_colorLeft.red = r;
m_colorLeft.green = g;
m_colorLeft.blue = b;
}
else if (side == 0x03)
{
m_colorTrap.red = r;
m_colorTrap.green = g;
m_colorTrap.blue = b;
}
}
uint8 SkylanderUSB::LoadSkylander(uint8* buf, std::unique_ptr<FileStream> file)
{
std::lock_guard lock(m_skyMutex);
uint32 skySerial = 0;
for (int i = 3; i > -1; i--)
{
skySerial <<= 8;
skySerial |= buf[i];
}
uint8 foundSlot = 0xFF;
// mimics spot retaining on the portal
for (auto i = 0; i < 16; i++)
{
if ((m_skylanders[i].status & 1) == 0)
{
if (m_skylanders[i].lastId == skySerial)
{
foundSlot = i;
break;
}
if (i < foundSlot)
{
foundSlot = i;
}
}
}
if (foundSlot != 0xFF)
{
auto& skylander = m_skylanders[foundSlot];
memcpy(skylander.data.data(), buf, skylander.data.size());
skylander.skyFile = std::move(file);
skylander.status = Skylander::ADDED;
skylander.queuedStatus.push(Skylander::ADDED);
skylander.queuedStatus.push(Skylander::READY);
skylander.lastId = skySerial;
}
return foundSlot;
}
bool SkylanderUSB::RemoveSkylander(uint8 skyNum)
{
std::lock_guard lock(m_skyMutex);
auto& thesky = m_skylanders[skyNum];
if (thesky.status & 1)
{
thesky.status = 2;
thesky.queuedStatus.push(2);
thesky.queuedStatus.push(0);
thesky.Save();
thesky.skyFile.reset();
return true;
}
return false;
}
bool SkylanderUSB::CreateSkylander(fs::path pathName, uint16 skyId, uint16 skyVar)
{
FileStream* skyFile(FileStream::createFile2(pathName));
if (!skyFile)
{
return false;
}
std::array<uint8, SKY_FIGURE_SIZE> data{};
uint32 first_block = 0x690F0F0F;
uint32 other_blocks = 0x69080F7F;
memcpy(&data[0x36], &first_block, sizeof(first_block));
for (size_t index = 1; index < 0x10; index++)
{
memcpy(&data[(index * 0x40) + 0x36], &other_blocks, sizeof(other_blocks));
}
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(0, 255);
data[0] = dist(mt);
data[1] = dist(mt);
data[2] = dist(mt);
data[3] = dist(mt);
data[4] = data[0] ^ data[1] ^ data[2] ^ data[3];
data[5] = 0x81;
data[6] = 0x01;
data[7] = 0x0F;
memcpy(&data[0x10], &skyId, sizeof(skyId));
memcpy(&data[0x1C], &skyVar, sizeof(skyVar));
uint16 crc = nsyshid::g_skyportal.SkylanderCRC16(0xFFFF, data.data(), 0x1E);
memcpy(&data[0x1E], &crc, sizeof(crc));
skyFile->writeData(data.data(), data.size());
delete skyFile;
return true;
}
void SkylanderUSB::QueryBlock(uint8 skyNum, uint8 block, uint8* replyBuf)
{
std::lock_guard lock(m_skyMutex);
const auto& skylander = m_skylanders[skyNum];
replyBuf[0] = 'Q';
replyBuf[2] = block;
if (skylander.status & 1)
{
replyBuf[1] = (0x10 | skyNum);
memcpy(replyBuf + 3, skylander.data.data() + (16 * block), 16);
}
else
{
replyBuf[1] = skyNum;
}
}
void SkylanderUSB::WriteBlock(uint8 skyNum, uint8 block,
const uint8* toWriteBuf, uint8* replyBuf)
{
std::lock_guard lock(m_skyMutex);
auto& skylander = m_skylanders[skyNum];
replyBuf[0] = 'W';
replyBuf[2] = block;
if (skylander.status & 1)
{
replyBuf[1] = (0x10 | skyNum);
memcpy(skylander.data.data() + (block * 16), toWriteBuf, 16);
skylander.Save();
}
else
{
replyBuf[1] = skyNum;
}
}
std::array<uint8, 64> SkylanderUSB::GetStatus()
{
std::lock_guard lock(m_queryMutex);
std::array<uint8, 64> interruptResponse = {};
if (!m_queries.empty())
{
interruptResponse = m_queries.front();
m_queries.pop();
// This needs to happen after ~22 milliseconds
}
else
{
uint32 status = 0;
uint8 active = 0x00;
if (m_activated)
{
active = 0x01;
}
for (int i = 16 - 1; i >= 0; i--)
{
auto& s = m_skylanders[i];
if (!s.queuedStatus.empty())
{
s.status = s.queuedStatus.front();
s.queuedStatus.pop();
}
status <<= 2;
status |= s.status;
}
interruptResponse = {0x53, 0x00, 0x00, 0x00, 0x00, m_interruptCounter++,
active, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00};
memcpy(&interruptResponse[1], &status, sizeof(status));
}
return interruptResponse;
}
std::string SkylanderUSB::FindSkylander(uint16 skyId, uint16 skyVar)
{
for (const auto& it : GetListSkylanders())
{
if (it.first.first == skyId && it.first.second == skyVar)
{
return it.second;
}
}
return fmt::format("Unknown ({} {})", skyId, skyVar);
}
std::map<const std::pair<const uint16, const uint16>, const char*> SkylanderUSB::GetListSkylanders()
{
return s_listSkylanders;
}
void SkylanderUSB::Skylander::Save()
{
if (!skyFile)
return;
skyFile->SetPosition(0);
skyFile->writeData(data.data(), data.size());
}
} // namespace nsyshid
| 33,020
|
C++
|
.cpp
| 939
| 31.28754
| 205
| 0.619195
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,139
|
BackendEmulated.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nsyshid/BackendEmulated.cpp
|
#include "BackendEmulated.h"
#include "Dimensions.h"
#include "Infinity.h"
#include "Skylander.h"
#include "config/CemuConfig.h"
namespace nsyshid::backend::emulated
{
BackendEmulated::BackendEmulated()
{
cemuLog_logDebug(LogType::Force, "nsyshid::BackendEmulated: emulated backend initialised");
}
BackendEmulated::~BackendEmulated() = default;
bool BackendEmulated::IsInitialisedOk()
{
return true;
}
void BackendEmulated::AttachVisibleDevices()
{
if (GetConfig().emulated_usb_devices.emulate_skylander_portal && !FindDeviceById(0x1430, 0x0150))
{
cemuLog_logDebug(LogType::Force, "Attaching Emulated Portal");
// Add Skylander Portal
auto device = std::make_shared<SkylanderPortalDevice>();
AttachDevice(device);
}
if (GetConfig().emulated_usb_devices.emulate_infinity_base && !FindDeviceById(0x0E6F, 0x0129))
{
cemuLog_logDebug(LogType::Force, "Attaching Emulated Base");
// Add Infinity Base
auto device = std::make_shared<InfinityBaseDevice>();
AttachDevice(device);
}
if (GetConfig().emulated_usb_devices.emulate_dimensions_toypad && !FindDeviceById(0x0E6F, 0x0241))
{
cemuLog_logDebug(LogType::Force, "Attaching Emulated Toypad");
// Add Dimensions Toypad
auto device = std::make_shared<DimensionsToypadDevice>();
AttachDevice(device);
}
}
} // namespace nsyshid::backend::emulated
| 1,362
|
C++
|
.cpp
| 41
| 30.463415
| 100
| 0.757783
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,140
|
Dimensions.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nsyshid/Dimensions.cpp
|
#include "Dimensions.h"
#include "nsyshid.h"
#include "Backend.h"
#include "Common/FileStream.h"
#include <array>
#include <random>
namespace nsyshid
{
static constexpr std::array<uint8, 16> COMMAND_KEY = {0x55, 0xFE, 0xF6, 0xB0, 0x62, 0xBF, 0x0B, 0x41,
0xC9, 0xB3, 0x7C, 0xB4, 0x97, 0x3E, 0x29, 0x7B};
static constexpr std::array<uint8, 17> CHAR_CONSTANT = {0xB7, 0xD5, 0xD7, 0xE6, 0xE7, 0xBA, 0x3C, 0xA8,
0xD8, 0x75, 0x47, 0x68, 0xCF, 0x23, 0xE9, 0xFE, 0xAA};
static constexpr std::array<uint8, 25> PWD_CONSTANT = {0x28, 0x63, 0x29, 0x20, 0x43, 0x6F, 0x70, 0x79,
0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x4C, 0x45,
0x47, 0x4F, 0x20, 0x32, 0x30, 0x31, 0x34, 0xAA, 0xAA};
DimensionsUSB g_dimensionstoypad;
const std::map<const uint32, const char*> s_listMinis = {
{0, "Blank Tag"},
{1, "Batman"},
{2, "Gandalf"},
{3, "Wyldstyle"},
{4, "Aquaman"},
{5, "Bad Cop"},
{6, "Bane"},
{7, "Bart Simpson"},
{8, "Benny"},
{9, "Chell"},
{10, "Cole"},
{11, "Cragger"},
{12, "Cyborg"},
{13, "Cyberman"},
{14, "Doc Brown"},
{15, "The Doctor"},
{16, "Emmet"},
{17, "Eris"},
{18, "Gimli"},
{19, "Gollum"},
{20, "Harley Quinn"},
{21, "Homer Simpson"},
{22, "Jay"},
{23, "Joker"},
{24, "Kai"},
{25, "ACU Trooper"},
{26, "Gamer Kid"},
{27, "Krusty the Clown"},
{28, "Laval"},
{29, "Legolas"},
{30, "Lloyd"},
{31, "Marty McFly"},
{32, "Nya"},
{33, "Owen Grady"},
{34, "Peter Venkman"},
{35, "Slimer"},
{36, "Scooby-Doo"},
{37, "Sensei Wu"},
{38, "Shaggy"},
{39, "Stay Puft"},
{40, "Superman"},
{41, "Unikitty"},
{42, "Wicked Witch of the West"},
{43, "Wonder Woman"},
{44, "Zane"},
{45, "Green Arrow"},
{46, "Supergirl"},
{47, "Abby Yates"},
{48, "Finn the Human"},
{49, "Ethan Hunt"},
{50, "Lumpy Space Princess"},
{51, "Jake the Dog"},
{52, "Harry Potter"},
{53, "Lord Voldemort"},
{54, "Michael Knight"},
{55, "B.A. Baracus"},
{56, "Newt Scamander"},
{57, "Sonic the Hedgehog"},
{58, "Future Update (unreleased)"},
{59, "Gizmo"},
{60, "Stripe"},
{61, "E.T."},
{62, "Tina Goldstein"},
{63, "Marceline the Vampire Queen"},
{64, "Batgirl"},
{65, "Robin"},
{66, "Sloth"},
{67, "Hermione Granger"},
{68, "Chase McCain"},
{69, "Excalibur Batman"},
{70, "Raven"},
{71, "Beast Boy"},
{72, "Betelgeuse"},
{73, "Lord Vortech (unreleased)"},
{74, "Blossom"},
{75, "Bubbles"},
{76, "Buttercup"},
{77, "Starfire"},
{78, "World 15 (unreleased)"},
{79, "World 16 (unreleased)"},
{80, "World 17 (unreleased)"},
{81, "World 18 (unreleased)"},
{82, "World 19 (unreleased)"},
{83, "World 20 (unreleased)"},
{768, "Unknown 768"},
{769, "Supergirl Red Lantern"},
{770, "Unknown 770"}};
const std::map<const uint32, const char*> s_listTokens = {
{1000, "Police Car"},
{1001, "Aerial Squad Car"},
{1002, "Missile Striker"},
{1003, "Gravity Sprinter"},
{1004, "Street Shredder"},
{1005, "Sky Clobberer"},
{1006, "Batmobile"},
{1007, "Batblaster"},
{1008, "Sonic Batray"},
{1009, "Benny's Spaceship"},
{1010, "Lasercraft"},
{1011, "The Annihilator"},
{1012, "DeLorean Time Machine"},
{1013, "Electric Time Machine"},
{1014, "Ultra Time Machine"},
{1015, "Hoverboard"},
{1016, "Cyclone Board"},
{1017, "Ultimate Hoverjet"},
{1018, "Eagle Interceptor"},
{1019, "Eagle Sky Blazer"},
{1020, "Eagle Swoop Diver"},
{1021, "Swamp Skimmer"},
{1022, "Cragger's Fireship"},
{1023, "Croc Command Sub"},
{1024, "Cyber-Guard"},
{1025, "Cyber-Wrecker"},
{1026, "Laser Robot Walker"},
{1027, "K-9"},
{1028, "K-9 Ruff Rover"},
{1029, "K-9 Laser Cutter"},
{1030, "TARDIS"},
{1031, "Laser-Pulse TARDIS"},
{1032, "Energy-Burst TARDIS"},
{1033, "Emmet's Excavator"},
{1034, "Destroy Dozer"},
{1035, "Destruct-o-Mech"},
{1036, "Winged Monkey"},
{1037, "Battle Monkey"},
{1038, "Commander Monkey"},
{1039, "Axe Chariot"},
{1040, "Axe Hurler"},
{1041, "Soaring Chariot"},
{1042, "Shelob the Great"},
{1043, "8-Legged Stalker"},
{1044, "Poison Slinger"},
{1045, "Homer's Car"},
{1047, "The SubmaHomer"},
{1046, "The Homercraft"},
{1048, "Taunt-o-Vision"},
{1050, "The MechaHomer"},
{1049, "Blast Cam"},
{1051, "Velociraptor"},
{1053, "Venom Raptor"},
{1052, "Spike Attack Raptor"},
{1054, "Gyrosphere"},
{1055, "Sonic Beam Gyrosphere"},
{1056, " Gyrosphere"},
{1057, "Clown Bike"},
{1058, "Cannon Bike"},
{1059, "Anti-Gravity Rocket Bike"},
{1060, "Mighty Lion Rider"},
{1061, "Lion Blazer"},
{1062, "Fire Lion"},
{1063, "Arrow Launcher"},
{1064, "Seeking Shooter"},
{1065, "Triple Ballista"},
{1066, "Mystery Machine"},
{1067, "Mystery Tow & Go"},
{1068, "Mystery Monster"},
{1069, "Boulder Bomber"},
{1070, "Boulder Blaster"},
{1071, "Cyclone Jet"},
{1072, "Storm Fighter"},
{1073, "Lightning Jet"},
{1074, "Electro-Shooter"},
{1075, "Blade Bike"},
{1076, "Flight Fire Bike"},
{1077, "Blades of Fire"},
{1078, "Samurai Mech"},
{1079, "Samurai Shooter"},
{1080, "Soaring Samurai Mech"},
{1081, "Companion Cube"},
{1082, "Laser Deflector"},
{1083, "Gold Heart Emitter"},
{1084, "Sentry Turret"},
{1085, "Turret Striker"},
{1086, "Flight Turret Carrier"},
{1087, "Scooby Snack"},
{1088, "Scooby Fire Snack"},
{1089, "Scooby Ghost Snack"},
{1090, "Cloud Cuckoo Car"},
{1091, "X-Stream Soaker"},
{1092, "Rainbow Cannon"},
{1093, "Invisible Jet"},
{1094, "Laser Shooter"},
{1095, "Torpedo Bomber"},
{1096, "NinjaCopter"},
{1097, "Glaciator"},
{1098, "Freeze Fighter"},
{1099, "Travelling Time Train"},
{1100, "Flight Time Train"},
{1101, "Missile Blast Time Train"},
{1102, "Aqua Watercraft"},
{1103, "Seven Seas Speeder"},
{1104, "Trident of Fire"},
{1105, "Drill Driver"},
{1106, "Bane Dig 'n' Drill"},
{1107, "Bane Drill 'n' Blast"},
{1108, "Quinn Mobile"},
{1109, "Quinn Ultra Racer"},
{1110, "Missile Launcher"},
{1111, "The Joker's Chopper"},
{1112, "Mischievous Missile Blaster"},
{1113, "Lock 'n' Laser Jet"},
{1114, "Hover Pod"},
{1115, "Krypton Striker"},
{1116, "Super Stealth Pod"},
{1117, "Dalek"},
{1118, "Fire 'n' Ride Dalek"},
{1119, "Silver Shooter Dalek"},
{1120, "Ecto-1"},
{1121, "Ecto-1 Blaster"},
{1122, "Ecto-1 Water Diver"},
{1123, "Ghost Trap"},
{1124, "Ghost Stun 'n' Trap"},
{1125, "Proton Zapper"},
{1126, "Unknown"},
{1127, "Unknown"},
{1128, "Unknown"},
{1129, "Unknown"},
{1130, "Unknown"},
{1131, "Unknown"},
{1132, "Lloyd's Golden Dragon"},
{1133, "Sword Projector Dragon"},
{1134, "Unknown"},
{1135, "Unknown"},
{1136, "Unknown"},
{1137, "Unknown"},
{1138, "Unknown"},
{1139, "Unknown"},
{1140, "Unknown"},
{1141, "Unknown"},
{1142, "Unknown"},
{1143, "Unknown"},
{1144, "Mega Flight Dragon"},
{1145, "Unknown"},
{1146, "Unknown"},
{1147, "Unknown"},
{1148, "Unknown"},
{1149, "Unknown"},
{1150, "Unknown"},
{1151, "Unknown"},
{1152, "Unknown"},
{1153, "Unknown"},
{1154, "Unknown"},
{1155, "Flying White Dragon"},
{1156, "Golden Fire Dragon"},
{1157, "Ultra Destruction Dragon"},
{1158, "Arcade Machine"},
{1159, "8-Bit Shooter"},
{1160, "The Pixelator"},
{1161, "G-6155 Spy Hunter"},
{1162, "Interdiver"},
{1163, "Aerial Spyhunter"},
{1164, "Slime Shooter"},
{1165, "Slime Exploder"},
{1166, "Slime Streamer"},
{1167, "Terror Dog"},
{1168, "Terror Dog Destroyer"},
{1169, "Soaring Terror Dog"},
{1170, "Ancient Psychic Tandem War Elephant"},
{1171, "Cosmic Squid"},
{1172, "Psychic Submarine"},
{1173, "BMO"},
{1174, "DOGMO"},
{1175, "SNAKEMO"},
{1176, "Jakemobile"},
{1177, "Snail Dude Jake"},
{1178, "Hover Jake"},
{1179, "Lumpy Car"},
{1181, "Lumpy Land Whale"},
{1180, "Lumpy Truck"},
{1182, "Lunatic Amp"},
{1183, "Shadow Scorpion"},
{1184, "Heavy Metal Monster"},
{1185, "B.A.'s Van"},
{1186, "Fool Smasher"},
{1187, "Pain Plane"},
{1188, "Phone Home"},
{1189, "Mobile Uplink"},
{1190, "Super-Charged Satellite"},
{1191, "Niffler"},
{1192, "Sinister Scorpion"},
{1193, "Vicious Vulture"},
{1194, "Swooping Evil"},
{1195, "Brutal Bloom"},
{1196, "Crawling Creeper"},
{1197, "Ecto-1 (2016)"},
{1198, "Ectozer"},
{1199, "PerfEcto"},
{1200, "Flash 'n' Finish"},
{1201, "Rampage Record Player"},
{1202, "Stripe's Throne"},
{1203, "R.C. Racer"},
{1204, "Gadget-O-Matic"},
{1205, "Scarlet Scorpion"},
{1206, "Hogwarts Express"},
{1208, "Steam Warrior"},
{1207, "Soaring Steam Plane"},
{1209, "Enchanted Car"},
{1210, "Shark Sub"},
{1211, "Monstrous Mouth"},
{1212, "IMF Scrambler"},
{1213, "Shock Cycle"},
{1214, "IMF Covert Jet"},
{1215, "IMF Sports Car"},
{1216, "IMF Tank"},
{1217, "IMF Splorer"},
{1218, "Sonic Speedster"},
{1219, "Blue Typhoon"},
{1220, "Moto Bug"},
{1221, "The Tornado"},
{1222, "Crabmeat"},
{1223, "Eggcatcher"},
{1224, "K.I.T.T."},
{1225, "Goliath Armored Semi"},
{1226, "K.I.T.T. Jet"},
{1227, "Police Helicopter"},
{1228, "Police Hovercraft"},
{1229, "Police Plane"},
{1230, "Bionic Steed"},
{1231, "Bat-Raptor"},
{1232, "Ultrabat"},
{1233, "Batwing"},
{1234, "The Black Thunder"},
{1235, "Bat-Tank"},
{1236, "Skeleton Organ"},
{1237, "Skeleton Jukebox"},
{1238, "Skele-Turkey"},
{1239, "One-Eyed Willy's Pirate Ship"},
{1240, "Fanged Fortune"},
{1241, "Inferno Cannon"},
{1242, "Buckbeak"},
{1243, "Giant Owl"},
{1244, "Fierce Falcon"},
{1245, "Saturn's Sandworm"},
{1247, "Haunted Vacuum"},
{1246, "Spooky Spider"},
{1248, "PPG Smartphone"},
{1249, "PPG Hotline"},
{1250, "Powerpuff Mag-Net"},
{1253, "Mega Blast Bot"},
{1251, "Ka-Pow Cannon"},
{1252, "Slammin' Guitar"},
{1254, "Octi"},
{1255, "Super Skunk"},
{1256, "Sonic Squid"},
{1257, "T-Car"},
{1258, "T-Forklift"},
{1259, "T-Plane"},
{1260, "Spellbook of Azarath"},
{1261, "Raven Wings"},
{1262, "Giant Hand"},
{1263, "Titan Robot"},
{1264, "T-Rocket"},
{1265, "Robot Retriever"}};
DimensionsToypadDevice::DimensionsToypadDevice()
: Device(0x0E6F, 0x0241, 1, 2, 0)
{
m_IsOpened = false;
}
bool DimensionsToypadDevice::Open()
{
if (!IsOpened())
{
m_IsOpened = true;
}
return true;
}
void DimensionsToypadDevice::Close()
{
if (IsOpened())
{
m_IsOpened = false;
}
}
bool DimensionsToypadDevice::IsOpened()
{
return m_IsOpened;
}
Device::ReadResult DimensionsToypadDevice::Read(ReadMessage* message)
{
memcpy(message->data, g_dimensionstoypad.GetStatus().data(), message->length);
message->bytesRead = message->length;
return Device::ReadResult::Success;
}
Device::WriteResult DimensionsToypadDevice::Write(WriteMessage* message)
{
if (message->length != 32)
return Device::WriteResult::Error;
g_dimensionstoypad.SendCommand(std::span<const uint8, 32>{message->data, 32});
message->bytesWritten = message->length;
return Device::WriteResult::Success;
}
bool DimensionsToypadDevice::GetDescriptor(uint8 descType,
uint8 descIndex,
uint8 lang,
uint8* output,
uint32 outputMaxLength)
{
uint8 configurationDescriptor[0x29];
uint8* currentWritePtr;
// configuration descriptor
currentWritePtr = configurationDescriptor + 0;
*(uint8*)(currentWritePtr + 0) = 9; // bLength
*(uint8*)(currentWritePtr + 1) = 2; // bDescriptorType
*(uint16be*)(currentWritePtr + 2) = 0x0029; // wTotalLength
*(uint8*)(currentWritePtr + 4) = 1; // bNumInterfaces
*(uint8*)(currentWritePtr + 5) = 1; // bConfigurationValue
*(uint8*)(currentWritePtr + 6) = 0; // iConfiguration
*(uint8*)(currentWritePtr + 7) = 0x80; // bmAttributes
*(uint8*)(currentWritePtr + 8) = 0xFA; // MaxPower
currentWritePtr = currentWritePtr + 9;
// configuration descriptor
*(uint8*)(currentWritePtr + 0) = 9; // bLength
*(uint8*)(currentWritePtr + 1) = 0x04; // bDescriptorType
*(uint8*)(currentWritePtr + 2) = 0; // bInterfaceNumber
*(uint8*)(currentWritePtr + 3) = 0; // bAlternateSetting
*(uint8*)(currentWritePtr + 4) = 2; // bNumEndpoints
*(uint8*)(currentWritePtr + 5) = 3; // bInterfaceClass
*(uint8*)(currentWritePtr + 6) = 0; // bInterfaceSubClass
*(uint8*)(currentWritePtr + 7) = 0; // bInterfaceProtocol
*(uint8*)(currentWritePtr + 8) = 0; // iInterface
currentWritePtr = currentWritePtr + 9;
// configuration descriptor
*(uint8*)(currentWritePtr + 0) = 9; // bLength
*(uint8*)(currentWritePtr + 1) = 0x21; // bDescriptorType
*(uint16be*)(currentWritePtr + 2) = 0x0111; // bcdHID
*(uint8*)(currentWritePtr + 4) = 0x00; // bCountryCode
*(uint8*)(currentWritePtr + 5) = 0x01; // bNumDescriptors
*(uint8*)(currentWritePtr + 6) = 0x22; // bDescriptorType
*(uint16be*)(currentWritePtr + 7) = 0x001D; // wDescriptorLength
currentWritePtr = currentWritePtr + 9;
// endpoint descriptor 1
*(uint8*)(currentWritePtr + 0) = 7; // bLength
*(uint8*)(currentWritePtr + 1) = 0x05; // bDescriptorType
*(uint8*)(currentWritePtr + 2) = 0x81; // bEndpointAddress
*(uint8*)(currentWritePtr + 3) = 0x03; // bmAttributes
*(uint16be*)(currentWritePtr + 4) = 0x40; // wMaxPacketSize
*(uint8*)(currentWritePtr + 6) = 0x01; // bInterval
currentWritePtr = currentWritePtr + 7;
// endpoint descriptor 2
*(uint8*)(currentWritePtr + 0) = 7; // bLength
*(uint8*)(currentWritePtr + 1) = 0x05; // bDescriptorType
*(uint8*)(currentWritePtr + 1) = 0x02; // bEndpointAddress
*(uint8*)(currentWritePtr + 2) = 0x03; // bmAttributes
*(uint16be*)(currentWritePtr + 3) = 0x40; // wMaxPacketSize
*(uint8*)(currentWritePtr + 5) = 0x01; // bInterval
currentWritePtr = currentWritePtr + 7;
cemu_assert_debug((currentWritePtr - configurationDescriptor) == 0x29);
memcpy(output, configurationDescriptor,
std::min<uint32>(outputMaxLength, sizeof(configurationDescriptor)));
return true;
}
bool DimensionsToypadDevice::SetProtocol(uint8 ifIndex, uint8 protocol)
{
cemuLog_log(LogType::Force, "Toypad Protocol");
return true;
}
bool DimensionsToypadDevice::SetReport(ReportMessage* message)
{
cemuLog_log(LogType::Force, "Toypad Report");
return true;
}
std::array<uint8, 32> DimensionsUSB::GetStatus()
{
std::array<uint8, 32> response = {};
bool responded = false;
do
{
if (!m_queries.empty())
{
response = m_queries.front();
m_queries.pop();
responded = true;
}
else if (!m_figureAddedRemovedResponses.empty() && m_isAwake)
{
std::lock_guard lock(m_dimensionsMutex);
response = m_figureAddedRemovedResponses.front();
m_figureAddedRemovedResponses.pop();
responded = true;
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
while (responded == false);
return response;
}
void DimensionsUSB::SendCommand(std::span<const uint8, 32> buf)
{
const uint8 command = buf[2];
const uint8 sequence = buf[3];
std::array<uint8, 32> q_result{};
switch (command)
{
case 0xB0: // Wake
{
// Consistent device response to the wake command
q_result = {0x55, 0x0e, 0x01, 0x28, 0x63, 0x29,
0x20, 0x4c, 0x45, 0x47, 0x4f, 0x20,
0x32, 0x30, 0x31, 0x34, 0x46};
break;
}
case 0xB1: // Seed
{
// Initialise a random number generator using the seed provided
g_dimensionstoypad.GenerateRandomNumber(std::span<const uint8, 8>{buf.begin() + 4, 8}, sequence, q_result);
break;
}
case 0xB3: // Challenge
{
// Get the next number in the sequence based on the RNG from 0xB1 command
g_dimensionstoypad.GetChallengeResponse(std::span<const uint8, 8>{buf.begin() + 4, 8}, sequence, q_result);
break;
}
case 0xC0: // Color
case 0xC1: // Get Pad Color
case 0xC2: // Fade
case 0xC3: // Flash
case 0xC4: // Fade Random
case 0xC6: // Fade All
case 0xC7: // Flash All
case 0xC8: // Color All
{
// Send a blank response to acknowledge color has been sent to toypad
q_result = {0x55, 0x01, sequence};
q_result[3] = GenerateChecksum(q_result, 3);
break;
}
case 0xD2: // Read
{
// Read 4 pages from the figure at index (buf[4]), starting with page buf[5]
g_dimensionstoypad.QueryBlock(buf[4], buf[5], q_result, sequence);
break;
}
case 0xD3: // Write
{
// Write 4 bytes to page buf[5] to the figure at index buf[4]
g_dimensionstoypad.WriteBlock(buf[4], buf[5], std::span<const uint8, 4>{buf.begin() + 6, 4}, q_result, sequence);
break;
}
case 0xD4: // Model
{
// Get the model id of the figure at index buf[4]
g_dimensionstoypad.GetModel(std::span<const uint8, 8>{buf.begin() + 4, 8}, sequence, q_result);
break;
}
case 0xD0: // Tag List
case 0xE1: // PWD
case 0xE5: // Active
case 0xFF: // LEDS Query
{
// Further investigation required
cemuLog_log(LogType::Force, "Unimplemented LD Function: {:x}", command);
break;
}
default:
{
cemuLog_log(LogType::Force, "Unknown LD Function: {:x}", command);
break;
}
}
m_queries.push(q_result);
}
uint32 DimensionsUSB::LoadFigure(const std::array<uint8, 0x2D * 0x04>& buf, std::unique_ptr<FileStream> file, uint8 pad, uint8 index)
{
std::lock_guard lock(m_dimensionsMutex);
const uint32 id = GetFigureId(buf);
DimensionsMini& figure = GetFigureByIndex(index);
figure.dimFile = std::move(file);
figure.id = id;
figure.pad = pad;
figure.index = index + 1;
figure.data = buf;
// When a figure is added to the toypad, respond to the game with the pad they were added to, their index,
// the direction (0x00 in byte 6 for added) and their UID
std::array<uint8, 32> figureChangeResponse = {0x56, 0x0b, figure.pad, 0x00, figure.index, 0x00, buf[0], buf[1], buf[2], buf[4], buf[5], buf[6], buf[7]};
figureChangeResponse[13] = GenerateChecksum(figureChangeResponse, 13);
m_figureAddedRemovedResponses.push(figureChangeResponse);
return id;
}
bool DimensionsUSB::RemoveFigure(uint8 pad, uint8 index, bool fullRemove)
{
std::lock_guard lock(m_dimensionsMutex);
DimensionsMini& figure = GetFigureByIndex(index);
if (figure.index == 255)
return false;
// When a figure is removed from the toypad, respond to the game with the pad they were removed from, their index,
// the direction (0x01 in byte 6 for removed) and their UID
if (fullRemove)
{
std::array<uint8, 32> figureChangeResponse = {0x56, 0x0b, figure.pad, 0x00, figure.index, 0x01,
figure.data[0], figure.data[1], figure.data[2],
figure.data[4], figure.data[5], figure.data[6], figure.data[7]};
figureChangeResponse[13] = GenerateChecksum(figureChangeResponse, 13);
m_figureAddedRemovedResponses.push(figureChangeResponse);
figure.Save();
figure.dimFile.reset();
}
figure.index = 255;
figure.pad = 255;
figure.id = 0;
return true;
}
bool DimensionsUSB::TempRemove(uint8 index)
{
std::lock_guard lock(m_dimensionsMutex);
DimensionsMini& figure = GetFigureByIndex(index);
if (figure.index == 255)
return false;
// Send a response to the game that the figure has been "Picked up" from existing slot,
// until either the movement is cancelled, or user chooses a space to move to
std::array<uint8, 32> figureChangeResponse = {0x56, 0x0b, figure.pad, 0x00, figure.index, 0x01,
figure.data[0], figure.data[1], figure.data[2],
figure.data[4], figure.data[5], figure.data[6], figure.data[7]};
figureChangeResponse[13] = GenerateChecksum(figureChangeResponse, 13);
m_figureAddedRemovedResponses.push(figureChangeResponse);
}
bool DimensionsUSB::CancelRemove(uint8 index)
{
std::lock_guard lock(m_dimensionsMutex);
DimensionsMini& figure = GetFigureByIndex(index);
if (figure.index == 255)
return false;
// Cancel the previous movement of the figure
std::array<uint8, 32> figureChangeResponse = {0x56, 0x0b, figure.pad, 0x00, figure.index, 0x00,
figure.data[0], figure.data[1], figure.data[2],
figure.data[4], figure.data[5], figure.data[6], figure.data[7]};
figureChangeResponse[13] = GenerateChecksum(figureChangeResponse, 13);
m_figureAddedRemovedResponses.push(figureChangeResponse);
return true;
}
bool DimensionsUSB::CreateFigure(fs::path pathName, uint32 id)
{
FileStream* dimFile(FileStream::createFile2(pathName));
if (!dimFile)
return false;
std::array<uint8, 0x2D * 0x04> fileData{};
RandomUID(fileData);
fileData[3] = id & 0xFF;
std::array<uint8, 7> uid = {fileData[0], fileData[1], fileData[2], fileData[4], fileData[5], fileData[6], fileData[7]};
// Only characters are created with their ID encrypted and stored in pages 36 and 37,
// as well as a password stored in page 43. Blank tags have their information populated
// by the game when it calls the write_block command.
if (id != 0)
{
const std::array<uint8, 16> figureKey = GenerateFigureKey(fileData);
std::array<uint8, 8> valueToEncrypt = {uint8(id & 0xFF), uint8((id >> 8) & 0xFF), uint8((id >> 16) & 0xFF), uint8((id >> 24) & 0xFF),
uint8(id & 0xFF), uint8((id >> 8) & 0xFF), uint8((id >> 16) & 0xFF), uint8((id >> 24) & 0xFF)};
std::array<uint8, 8> encrypted = Encrypt(valueToEncrypt, figureKey);
std::memcpy(&fileData[36 * 4], &encrypted[0], 4);
std::memcpy(&fileData[37 * 4], &encrypted[4], 4);
std::memcpy(&fileData[43 * 4], PWDGenerate(fileData).data(), 4);
}
else
{
// Page 38 is used as verification for blank tags
fileData[(38 * 4) + 1] = 1;
}
if (fileData.size() != dimFile->writeData(fileData.data(), fileData.size()))
{
delete dimFile;
return false;
}
delete dimFile;
return true;
}
bool DimensionsUSB::MoveFigure(uint8 pad, uint8 index, uint8 oldPad, uint8 oldIndex)
{
if (oldIndex == index)
{
// Don't bother removing and loading again, just send response to the game
CancelRemove(index);
return true;
}
// When moving figures between spaces on the toypad, remove any figure from the space they are moving to,
// then remove them from their current space, then load them to the space they are moving to
RemoveFigure(pad, index, true);
DimensionsMini& figure = GetFigureByIndex(oldIndex);
const std::array<uint8, 0x2D * 0x04> data = figure.data;
std::unique_ptr<FileStream> inFile = std::move(figure.dimFile);
RemoveFigure(oldPad, oldIndex, false);
LoadFigure(data, std::move(inFile), pad, index);
return true;
}
void DimensionsUSB::GenerateRandomNumber(std::span<const uint8, 8> buf, uint8 sequence,
std::array<uint8, 32>& replyBuf)
{
// Decrypt payload into an 8 byte array
std::array<uint8, 8> value = Decrypt(buf, std::nullopt);
// Seed is the first 4 bytes (little endian) of the decrypted payload
uint32 seed = (uint32&)value[0];
// Confirmation is the second 4 bytes (big endian) of the decrypted payload
uint32 conf = (uint32be&)value[4];
// Initialize rng using the seed from decrypted payload
InitializeRNG(seed);
// Encrypt 8 bytes, first 4 bytes is the decrypted confirmation from payload, 2nd 4 bytes are blank
std::array<uint8, 8> valueToEncrypt = {value[4], value[5], value[6], value[7], 0, 0, 0, 0};
std::array<uint8, 8> encrypted = Encrypt(valueToEncrypt, std::nullopt);
replyBuf[0] = 0x55;
replyBuf[1] = 0x09;
replyBuf[2] = sequence;
// Copy encrypted value to response data
memcpy(&replyBuf[3], encrypted.data(), encrypted.size());
replyBuf[11] = GenerateChecksum(replyBuf, 11);
}
void DimensionsUSB::GetChallengeResponse(std::span<const uint8, 8> buf, uint8 sequence,
std::array<uint8, 32>& replyBuf)
{
// Decrypt payload into an 8 byte array
std::array<uint8, 8> value = Decrypt(buf, std::nullopt);
// Confirmation is the first 4 bytes of the decrypted payload
uint32 conf = (uint32be&)value[0];
// Generate next random number based on RNG
uint32 nextRandom = GetNext();
// Encrypt an 8 byte array, first 4 bytes are the next random number (little endian)
// followed by the confirmation from the decrypted payload
std::array<uint8, 8> valueToEncrypt = {uint8(nextRandom & 0xFF), uint8((nextRandom >> 8) & 0xFF),
uint8((nextRandom >> 16) & 0xFF), uint8((nextRandom >> 24) & 0xFF),
value[0], value[1], value[2], value[3]};
std::array<uint8, 8> encrypted = Encrypt(valueToEncrypt, std::nullopt);
replyBuf[0] = 0x55;
replyBuf[1] = 0x09;
replyBuf[2] = sequence;
// Copy encrypted value to response data
memcpy(&replyBuf[3], encrypted.data(), encrypted.size());
replyBuf[11] = GenerateChecksum(replyBuf, 11);
if (!m_isAwake)
m_isAwake = true;
}
void DimensionsUSB::InitializeRNG(uint32 seed)
{
m_randomA = 0xF1EA5EED;
m_randomB = seed;
m_randomC = seed;
m_randomD = seed;
for (int i = 0; i < 42; i++)
{
GetNext();
}
}
uint32 DimensionsUSB::GetNext()
{
uint32 e = m_randomA - std::rotl(m_randomB, 21);
m_randomA = m_randomB ^ std::rotl(m_randomC, 19);
m_randomB = m_randomC + std::rotl(m_randomD, 6);
m_randomC = m_randomD + e;
m_randomD = e + m_randomA;
return m_randomD;
}
std::array<uint8, 8> DimensionsUSB::Decrypt(std::span<const uint8, 8> buf, std::optional<std::array<uint8, 16>> key)
{
// Value to decrypt is separated in to two little endian 32 bit unsigned integers
uint32 dataOne = (uint32&)buf[0];
uint32 dataTwo = (uint32&)buf[4];
// Use the key as 4 32 bit little endian unsigned integers
uint32 keyOne;
uint32 keyTwo;
uint32 keyThree;
uint32 keyFour;
if (key)
{
keyOne = (uint32&)key.value()[0];
keyTwo = (uint32&)key.value()[4];
keyThree = (uint32&)key.value()[8];
keyFour = (uint32&)key.value()[12];
}
else
{
keyOne = (uint32&)COMMAND_KEY[0];
keyTwo = (uint32&)COMMAND_KEY[4];
keyThree = (uint32&)COMMAND_KEY[8];
keyFour = (uint32&)COMMAND_KEY[12];
}
uint32 sum = 0xC6EF3720;
uint32 delta = 0x9E3779B9;
for (int i = 0; i < 32; i++)
{
dataTwo -= (((dataOne << 4) + keyThree) ^ (dataOne + sum) ^ ((dataOne >> 5) + keyFour));
dataOne -= (((dataTwo << 4) + keyOne) ^ (dataTwo + sum) ^ ((dataTwo >> 5) + keyTwo));
sum -= delta;
}
cemu_assert(sum == 0);
std::array<uint8, 8> decrypted = {uint8(dataOne & 0xFF), uint8((dataOne >> 8) & 0xFF),
uint8((dataOne >> 16) & 0xFF), uint8((dataOne >> 24) & 0xFF),
uint8(dataTwo & 0xFF), uint8((dataTwo >> 8) & 0xFF),
uint8((dataTwo >> 16) & 0xFF), uint8((dataTwo >> 24) & 0xFF)};
return decrypted;
}
std::array<uint8, 8> DimensionsUSB::Encrypt(std::span<const uint8, 8> buf, std::optional<std::array<uint8, 16>> key)
{
// Value to encrypt is separated in to two little endian 32 bit unsigned integers
uint32 dataOne = (uint32&)buf[0];
uint32 dataTwo = (uint32&)buf[4];
// Use the key as 4 32 bit little endian unsigned integers
uint32 keyOne;
uint32 keyTwo;
uint32 keyThree;
uint32 keyFour;
if (key)
{
keyOne = (uint32&)key.value()[0];
keyTwo = (uint32&)key.value()[4];
keyThree = (uint32&)key.value()[8];
keyFour = (uint32&)key.value()[12];
}
else
{
keyOne = (uint32&)COMMAND_KEY[0];
keyTwo = (uint32&)COMMAND_KEY[4];
keyThree = (uint32&)COMMAND_KEY[8];
keyFour = (uint32&)COMMAND_KEY[12];
}
uint32 sum = 0;
uint32 delta = 0x9E3779B9;
for (int i = 0; i < 32; i++)
{
sum += delta;
dataOne += (((dataTwo << 4) + keyOne) ^ (dataTwo + sum) ^ ((dataTwo >> 5) + keyTwo));
dataTwo += (((dataOne << 4) + keyThree) ^ (dataOne + sum) ^ ((dataOne >> 5) + keyFour));
}
cemu_assert(sum == 0xC6EF3720);
std::array<uint8, 8> encrypted = {uint8(dataOne & 0xFF), uint8((dataOne >> 8) & 0xFF),
uint8((dataOne >> 16) & 0xFF), uint8((dataOne >> 24) & 0xFF),
uint8(dataTwo & 0xFF), uint8((dataTwo >> 8) & 0xFF),
uint8((dataTwo >> 16) & 0xFF), uint8((dataTwo >> 24) & 0xFF)};
return encrypted;
}
std::array<uint8, 16> DimensionsUSB::GenerateFigureKey(const std::array<uint8, 0x2D * 0x04>& buf)
{
std::array<uint8, 7> uid = {buf[0], buf[1], buf[2], buf[4], buf[5], buf[6], buf[7]};
uint32 scrambleA = Scramble(uid, 3);
uint32 scrambleB = Scramble(uid, 4);
uint32 scrambleC = Scramble(uid, 5);
uint32 scrambleD = Scramble(uid, 6);
return {uint8((scrambleA >> 24) & 0xFF), uint8((scrambleA >> 16) & 0xFF),
uint8((scrambleA >> 8) & 0xFF), uint8(scrambleA & 0xFF),
uint8((scrambleB >> 24) & 0xFF), uint8((scrambleB >> 16) & 0xFF),
uint8((scrambleB >> 8) & 0xFF), uint8(scrambleB & 0xFF),
uint8((scrambleC >> 24) & 0xFF), uint8((scrambleC >> 16) & 0xFF),
uint8((scrambleC >> 8) & 0xFF), uint8(scrambleC & 0xFF),
uint8((scrambleD >> 24) & 0xFF), uint8((scrambleD >> 16) & 0xFF),
uint8((scrambleD >> 8) & 0xFF), uint8(scrambleD & 0xFF)};
}
uint32 DimensionsUSB::Scramble(const std::array<uint8, 7>& uid, uint8 count)
{
std::vector<uint8> toScramble;
toScramble.reserve(uid.size() + CHAR_CONSTANT.size());
for (uint8 x : uid)
{
toScramble.push_back(x);
}
for (uint8 c : CHAR_CONSTANT)
{
toScramble.push_back(c);
}
toScramble[(count * 4) - 1] = 0xaa;
std::array<uint8, 4> randomized = DimensionsRandomize(toScramble, count);
return (uint32be&)randomized[0];
}
std::array<uint8, 4> DimensionsUSB::PWDGenerate(const std::array<uint8, 0x2D * 0x04>& buf)
{
std::array<uint8, 7> uid = {buf[0], buf[1], buf[2], buf[4], buf[5], buf[6], buf[7]};
std::vector<uint8> pwdCalc = {PWD_CONSTANT.begin(), PWD_CONSTANT.end() - 1};
for (uint8 i = 0; i < uid.size(); i++)
{
pwdCalc.insert(pwdCalc.begin() + i, uid[i]);
}
return DimensionsRandomize(pwdCalc, 8);
}
std::array<uint8, 4> DimensionsUSB::DimensionsRandomize(const std::vector<uint8> key, uint8 count)
{
uint32 scrambled = 0;
for (uint8 i = 0; i < count; i++)
{
const uint32 v4 = std::rotr(scrambled, 25);
const uint32 v5 = std::rotr(scrambled, 10);
const uint32 b = (uint32&)key[i * 4];
scrambled = b + v4 + v5 - scrambled;
}
return {uint8(scrambled & 0xFF), uint8(scrambled >> 8 & 0xFF), uint8(scrambled >> 16 & 0xFF), uint8(scrambled >> 24 & 0xFF)};
}
uint32 DimensionsUSB::GetFigureId(const std::array<uint8, 0x2D * 0x04>& buf)
{
const std::array<uint8, 16> figureKey = GenerateFigureKey(buf);
const std::span<const uint8, 8> modelNumber = std::span<const uint8, 8>{buf.begin() + (36 * 4), 8};
const std::array<uint8, 8> decrypted = Decrypt(modelNumber, figureKey);
const uint32 figNum = (uint32&)decrypted[0];
// Characters have their model number encrypted in page 36
if (figNum < 1000)
{
return figNum;
}
// Vehicles/Gadgets have their model number written as little endian in page 36
return (uint32&)modelNumber[0];
}
DimensionsUSB::DimensionsMini&
DimensionsUSB::GetFigureByIndex(uint8 index)
{
return m_figures[index];
}
void DimensionsUSB::QueryBlock(uint8 index, uint8 page,
std::array<uint8, 32>& replyBuf,
uint8 sequence)
{
std::lock_guard lock(m_dimensionsMutex);
replyBuf[0] = 0x55;
replyBuf[1] = 0x12;
replyBuf[2] = sequence;
replyBuf[3] = 0x00;
// Index from game begins at 1 rather than 0, so minus 1 here
if (const uint8 figureIndex = index - 1; figureIndex < 7)
{
const DimensionsMini& figure = GetFigureByIndex(figureIndex);
// Query 4 pages of 4 bytes from the figure, copy this to the response
if (figure.index != 255 && (4 * page) < ((0x2D * 4) - 16))
{
std::memcpy(&replyBuf[4], figure.data.data() + (4 * page), 16);
}
}
replyBuf[20] = GenerateChecksum(replyBuf, 20);
}
void DimensionsUSB::WriteBlock(uint8 index, uint8 page, std::span<const uint8, 4> toWriteBuf,
std::array<uint8, 32>& replyBuf, uint8 sequence)
{
std::lock_guard lock(m_dimensionsMutex);
replyBuf[0] = 0x55;
replyBuf[1] = 0x02;
replyBuf[2] = sequence;
replyBuf[3] = 0x00;
// Index from game begins at 1 rather than 0, so minus 1 here
if (const uint8 figureIndex = index - 1; figureIndex < 7)
{
DimensionsMini& figure = GetFigureByIndex(figureIndex);
// Copy 4 bytes to the page on the figure requested by the game
if (figure.index != 255 && page < 0x2D)
{
// Id is written to page 36
if (page == 36)
{
figure.id = (uint32&)toWriteBuf[0];
}
std::memcpy(figure.data.data() + (page * 4), toWriteBuf.data(), 4);
figure.Save();
}
}
replyBuf[4] = GenerateChecksum(replyBuf, 4);
}
void DimensionsUSB::GetModel(std::span<const uint8, 8> buf, uint8 sequence,
std::array<uint8, 32>& replyBuf)
{
// Decrypt payload to 8 byte array, byte 1 is the index, 4-7 are the confirmation
std::array<uint8, 8> value = Decrypt(buf, std::nullopt);
uint8 index = value[0];
uint32 conf = (uint32be&)value[4];
// Response is the figure's id (little endian) followed by the confirmation from payload
// Index from game begins at 1 rather than 0, so minus 1 here
std::array<uint8, 8> valueToEncrypt = {};
if (const uint8 figureIndex = index - 1; figureIndex < 7)
{
const DimensionsMini& figure = GetFigureByIndex(figureIndex);
valueToEncrypt = {uint8(figure.id & 0xFF), uint8((figure.id >> 8) & 0xFF),
uint8((figure.id >> 16) & 0xFF), uint8((figure.id >> 24) & 0xFF),
value[4], value[5], value[6], value[7]};
}
std::array<uint8, 8> encrypted = Encrypt(valueToEncrypt, std::nullopt);
replyBuf[0] = 0x55;
replyBuf[1] = 0x0a;
replyBuf[2] = sequence;
replyBuf[3] = 0x00;
memcpy(&replyBuf[4], encrypted.data(), encrypted.size());
replyBuf[12] = GenerateChecksum(replyBuf, 12);
}
void DimensionsUSB::RandomUID(std::array<uint8, 0x2D * 0x04>& uid_buffer)
{
uid_buffer[0] = 0x04;
uid_buffer[7] = 0x80;
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(0, 255);
uid_buffer[1] = dist(mt);
uid_buffer[2] = dist(mt);
uid_buffer[4] = dist(mt);
uid_buffer[5] = dist(mt);
uid_buffer[6] = dist(mt);
}
uint8 DimensionsUSB::GenerateChecksum(const std::array<uint8, 32>& data,
int num_of_bytes) const
{
int checksum = 0;
for (int i = 0; i < num_of_bytes; i++)
{
checksum += data[i];
}
return (checksum & 0xFF);
}
void DimensionsUSB::DimensionsMini::Save()
{
if (!dimFile)
return;
dimFile->SetPosition(0);
dimFile->writeData(data.data(), data.size());
}
std::map<const uint32, const char*> DimensionsUSB::GetListMinifigs()
{
return s_listMinis;
}
std::map<const uint32, const char*> DimensionsUSB::GetListTokens()
{
return s_listTokens;
}
std::string DimensionsUSB::FindFigure(uint32 figNum)
{
for (const auto& it : GetListMinifigs())
{
if (it.first == figNum)
{
return it.second;
}
}
for (const auto& it : GetListTokens())
{
if (it.first == figNum)
{
return it.second;
}
}
return fmt::format("Unknown ({})", figNum);
}
} // namespace nsyshid
| 34,959
|
C++
|
.cpp
| 1,048
| 29.871183
| 154
| 0.652376
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,141
|
nsyshid.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nsyshid/nsyshid.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include <bitset>
#include <mutex>
#include "nsyshid.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Backend.h"
#include "Whitelist.h"
namespace nsyshid
{
std::list<std::shared_ptr<Backend>> backendList;
std::list<std::shared_ptr<Device>> deviceList;
typedef struct _HIDClient_t
{
uint32be callbackFunc; // attach/detach callback
} HIDClient_t;
std::list<HIDClient_t*> HIDClientList;
std::recursive_mutex hidMutex;
void AttachClientToList(HIDClient_t* hidClient)
{
std::lock_guard<std::recursive_mutex> lock(hidMutex);
// todo - append at the beginning or end of the list? List order matters because it also controls the order in which attach callbacks are called
HIDClientList.push_front(hidClient);
}
void DetachClientFromList(HIDClient_t* hidClient)
{
std::lock_guard<std::recursive_mutex> lock(hidMutex);
HIDClientList.remove(hidClient);
}
std::shared_ptr<Device> GetDeviceByHandle(uint32 handle, bool openIfClosed = false)
{
std::shared_ptr<Device> device;
{
std::lock_guard<std::recursive_mutex> lock(hidMutex);
for (const auto& d : deviceList)
{
if (d->m_hid->handle == handle)
{
device = d;
break;
}
}
}
if (device != nullptr)
{
if (openIfClosed && !device->IsOpened())
{
if (!device->Open())
{
return nullptr;
}
}
return device;
}
return nullptr;
}
uint32 _lastGeneratedHidHandle = 1;
uint32 GenerateHIDHandle()
{
std::lock_guard<std::recursive_mutex> lock(hidMutex);
_lastGeneratedHidHandle++;
return _lastGeneratedHidHandle;
}
const int HID_MAX_NUM_DEVICES = 128;
SysAllocator<HID_t, HID_MAX_NUM_DEVICES> HIDPool;
std::queue<size_t> HIDPoolIndexQueue;
void InitHIDPoolIndexQueue()
{
static bool HIDPoolIndexQueueInitialized = false;
std::lock_guard<std::recursive_mutex> lock(hidMutex);
if (HIDPoolIndexQueueInitialized)
{
return;
}
HIDPoolIndexQueueInitialized = true;
for (size_t i = 0; i < HID_MAX_NUM_DEVICES; i++)
{
HIDPoolIndexQueue.push(i);
}
}
HID_t* GetFreeHID()
{
std::lock_guard<std::recursive_mutex> lock(hidMutex);
InitHIDPoolIndexQueue();
if (HIDPoolIndexQueue.empty())
{
return nullptr;
}
size_t index = HIDPoolIndexQueue.front();
HIDPoolIndexQueue.pop();
return HIDPool.GetPtr() + index;
}
void ReleaseHID(HID_t* device)
{
// this should never happen, but having a safeguard can't hurt
if (device == nullptr)
{
cemu_assert_error();
}
std::lock_guard<std::recursive_mutex> lock(hidMutex);
InitHIDPoolIndexQueue();
size_t index = device - HIDPool.GetPtr();
HIDPoolIndexQueue.push(index);
}
const int HID_CALLBACK_DETACH = 0;
const int HID_CALLBACK_ATTACH = 1;
uint32 DoAttachCallback(HIDClient_t* hidClient, const std::shared_ptr<Device>& device)
{
return PPCCoreCallback(hidClient->callbackFunc, memory_getVirtualOffsetFromPointer(hidClient),
memory_getVirtualOffsetFromPointer(device->m_hid), HID_CALLBACK_ATTACH);
}
void DoAttachCallbackAsync(HIDClient_t* hidClient, const std::shared_ptr<Device>& device)
{
coreinitAsyncCallback_add(hidClient->callbackFunc, 3, memory_getVirtualOffsetFromPointer(hidClient),
memory_getVirtualOffsetFromPointer(device->m_hid), HID_CALLBACK_ATTACH);
}
void DoDetachCallback(HIDClient_t* hidClient, const std::shared_ptr<Device>& device)
{
PPCCoreCallback(hidClient->callbackFunc, memory_getVirtualOffsetFromPointer(hidClient),
memory_getVirtualOffsetFromPointer(device->m_hid), HID_CALLBACK_DETACH);
}
void DoDetachCallbackAsync(HIDClient_t* hidClient, const std::shared_ptr<Device>& device)
{
coreinitAsyncCallback_add(hidClient->callbackFunc, 3, memory_getVirtualOffsetFromPointer(hidClient),
memory_getVirtualOffsetFromPointer(device->m_hid), HID_CALLBACK_DETACH);
}
void AttachBackend(const std::shared_ptr<Backend>& backend)
{
{
std::lock_guard<std::recursive_mutex> lock(hidMutex);
backendList.push_back(backend);
}
backend->OnAttach();
}
void DetachBackend(const std::shared_ptr<Backend>& backend)
{
{
std::lock_guard<std::recursive_mutex> lock(hidMutex);
backendList.remove(backend);
}
backend->OnDetach();
}
void DetachAllBackends()
{
std::list<std::shared_ptr<Backend>> backendListCopy;
{
std::lock_guard<std::recursive_mutex> lock(hidMutex);
backendListCopy = backendList;
backendList.clear();
}
for (const auto& backend : backendListCopy)
{
backend->OnDetach();
}
}
void AttachDefaultBackends()
{
backend::AttachDefaultBackends();
}
bool AttachDevice(const std::shared_ptr<Device>& device)
{
std::lock_guard<std::recursive_mutex> lock(hidMutex);
// is the device already attached?
{
auto it = std::find(deviceList.begin(), deviceList.end(), device);
if (it != deviceList.end())
{
cemuLog_logDebug(LogType::Force,
"nsyshid.AttachDevice(): failed to attach device: {:04x}:{:04x}: already attached",
device->m_vendorId,
device->m_productId);
return false;
}
}
HID_t* hidDevice = GetFreeHID();
if (hidDevice == nullptr)
{
cemuLog_logDebug(LogType::Force,
"nsyshid.AttachDevice(): failed to attach device: {:04x}:{:04x}: no free device slots left",
device->m_vendorId,
device->m_productId);
return false;
}
hidDevice->handle = GenerateHIDHandle();
device->AssignHID(hidDevice);
deviceList.push_back(device);
// do attach callbacks
for (auto client : HIDClientList)
{
DoAttachCallbackAsync(client, device);
}
cemuLog_logDebug(LogType::Force, "nsyshid.AttachDevice(): device attached: {:04x}:{:04x}",
device->m_vendorId,
device->m_productId);
return true;
}
void DetachDevice(const std::shared_ptr<Device>& device)
{
{
std::lock_guard<std::recursive_mutex> lock(hidMutex);
// remove from list
auto it = std::find(deviceList.begin(), deviceList.end(), device);
if (it == deviceList.end())
{
cemuLog_logDebug(LogType::Force, "nsyshid.DetachDevice(): device not found: {:04x}:{:04x}",
device->m_vendorId,
device->m_productId);
return;
}
deviceList.erase(it);
// do detach callbacks
for (auto client : HIDClientList)
{
DoDetachCallbackAsync(client, device);
}
ReleaseHID(device->m_hid);
}
device->Close();
cemuLog_logDebug(LogType::Force, "nsyshid.DetachDevice(): device removed: {:04x}:{:04x}",
device->m_vendorId,
device->m_productId);
}
bool FindDeviceById(uint16 vendorId, uint16 productId)
{
std::lock_guard<std::recursive_mutex> lock(hidMutex);
for (const auto& device : deviceList)
{
if (device->m_vendorId == vendorId && device->m_productId == productId)
{
return true;
}
}
return false;
}
void export_HIDAddClient(PPCInterpreter_t* hCPU)
{
ppcDefineParamTypePtr(hidClient, HIDClient_t, 0);
ppcDefineParamMPTR(callbackFuncMPTR, 1);
cemuLog_logDebug(LogType::Force, "nsyshid.HIDAddClient(0x{:08x},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4]);
hidClient->callbackFunc = callbackFuncMPTR;
std::lock_guard<std::recursive_mutex> lock(hidMutex);
AttachClientToList(hidClient);
// do attach callbacks
for (const auto& device : deviceList)
{
DoAttachCallback(hidClient, device);
}
osLib_returnFromFunction(hCPU, 0);
}
void export_HIDDelClient(PPCInterpreter_t* hCPU)
{
ppcDefineParamTypePtr(hidClient, HIDClient_t, 0);
cemuLog_logDebug(LogType::Force, "nsyshid.HIDDelClient(0x{:08x})", hCPU->gpr[3]);
std::lock_guard<std::recursive_mutex> lock(hidMutex);
DetachClientFromList(hidClient);
// do detach callbacks
for (const auto& device : deviceList)
{
DoDetachCallback(hidClient, device);
}
osLib_returnFromFunction(hCPU, 0);
}
void export_HIDGetDescriptor(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(hidHandle, 0); // r3
ppcDefineParamU8(descType, 1); // r4
ppcDefineParamU8(descIndex, 2); // r5
ppcDefineParamU8(lang, 3); // r6
ppcDefineParamUStr(output, 4); // r7
ppcDefineParamU32(outputMaxLength, 5); // r8
ppcDefineParamMPTR(cbFuncMPTR, 6); // r9
ppcDefineParamMPTR(cbParamMPTR, 7); // r10
int returnValue = -1;
std::shared_ptr<Device> device = GetDeviceByHandle(hidHandle, true);
if (device)
{
memset(output, 0, outputMaxLength);
if (device->GetDescriptor(descType, descIndex, lang, output, outputMaxLength))
{
returnValue = 0;
}
else
{
returnValue = -1;
}
}
else
{
cemu_assert_suspicious();
}
osLib_returnFromFunction(hCPU, returnValue);
}
void _debugPrintHex(std::string prefix, uint8* data, size_t len)
{
char debugOutput[1024] = {0};
len = std::min(len, (size_t)100);
for (sint32 i = 0; i < len; i++)
{
sprintf(debugOutput + i * 3, "%02x ", data[i]);
}
cemuLog_logDebug(LogType::Force, "[{}] Data: {}", prefix, debugOutput);
}
void DoHIDTransferCallback(MPTR callbackFuncMPTR, MPTR callbackParamMPTR, uint32 hidHandle, uint32 errorCode,
MPTR buffer, sint32 length)
{
coreinitAsyncCallback_add(callbackFuncMPTR, 5, hidHandle, errorCode, buffer, length, callbackParamMPTR);
}
void export_HIDSetIdle(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(hidHandle, 0); // r3
ppcDefineParamU32(ifIndex, 1); // r4
ppcDefineParamU32(ukn, 2); // r5
ppcDefineParamU32(duration, 3); // r6
ppcDefineParamMPTR(callbackFuncMPTR, 4); // r7
ppcDefineParamMPTR(callbackParamMPTR, 5); // r8
cemuLog_logDebug(LogType::Force, "nsyshid.HIDSetIdle(...)");
// todo
if (callbackFuncMPTR)
{
DoHIDTransferCallback(callbackFuncMPTR, callbackParamMPTR, hidHandle, 0, MPTR_NULL, 0);
}
else
{
cemu_assert_unimplemented();
}
osLib_returnFromFunction(hCPU, 0); // for non-async version, return number of bytes transferred
}
void export_HIDSetProtocol(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(hidHandle, 0); // r3
ppcDefineParamU8(ifIndex, 1); // r4
ppcDefineParamU8(protocol, 2); // r5
ppcDefineParamMPTR(callbackFuncMPTR, 3); // r6
ppcDefineParamMPTR(callbackParamMPTR, 4); // r7
cemuLog_logDebug(LogType::Force, "nsyshid.HIDSetProtocol(...)");
std::shared_ptr<Device> device = GetDeviceByHandle(hidHandle, true);
sint32 returnCode = -1;
if (device)
{
if (!device->IsOpened())
{
cemuLog_logDebug(LogType::Force, "nsyshid.HIDSetProtocol(): error: device is not opened");
}
else
{
if (device->SetProtocol(ifIndex, protocol))
{
returnCode = 0;
}
}
}
else
{
cemu_assert_suspicious();
}
if (callbackFuncMPTR)
{
DoHIDTransferCallback(callbackFuncMPTR, callbackParamMPTR, hidHandle, 0, MPTR_NULL, 0);
}
osLib_returnFromFunction(hCPU, returnCode);
}
// handler for async HIDSetReport transfers
void _hidSetReportAsync(std::shared_ptr<Device> device, uint8* reportData, sint32 length,
uint8* originalData,
sint32 originalLength, MPTR callbackFuncMPTR, MPTR callbackParamMPTR)
{
cemuLog_logDebug(LogType::Force, "_hidSetReportAsync begin");
ReportMessage message(reportData, length, originalData, originalLength);
if (device->SetReport(&message))
{
DoHIDTransferCallback(callbackFuncMPTR,
callbackParamMPTR,
device->m_hid->handle,
0,
memory_getVirtualOffsetFromPointer(originalData),
originalLength);
}
else
{
DoHIDTransferCallback(callbackFuncMPTR,
callbackParamMPTR,
device->m_hid->handle,
-1,
memory_getVirtualOffsetFromPointer(originalData),
0);
}
free(reportData);
}
// handler for synchronous HIDSetReport transfers
sint32 _hidSetReportSync(std::shared_ptr<Device> device, uint8* reportData, sint32 length,
uint8* originalData, sint32 originalLength, coreinit::OSEvent* event)
{
_debugPrintHex("_hidSetReportSync Begin", reportData, length);
sint32 returnCode = 0;
ReportMessage message(reportData, length, originalData, originalLength);
if (device->SetReport(&message))
{
returnCode = originalLength;
}
free(reportData);
cemuLog_logDebug(LogType::Force, "_hidSetReportSync end. returnCode: {}", returnCode);
coreinit::OSSignalEvent(event);
return returnCode;
}
void export_HIDSetReport(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(hidHandle, 0); // r3
ppcDefineParamU32(reportRelatedUkn, 1); // r4
ppcDefineParamU32(reportId, 2); // r5
ppcDefineParamUStr(data, 3); // r6
ppcDefineParamU32(dataLength, 4); // r7
ppcDefineParamMPTR(callbackFuncMPTR, 5); // r8
ppcDefineParamMPTR(callbackParamMPTR, 6); // r9
cemuLog_logDebug(LogType::Force, "nsyshid.HIDSetReport({},0x{:02x},0x{:02x},...)", hidHandle, reportRelatedUkn,
reportId);
_debugPrintHex("HIDSetReport", data, dataLength);
#ifdef CEMU_DEBUG_ASSERT
if (reportRelatedUkn != 2 || reportId != 0)
assert_dbg();
#endif
std::shared_ptr<Device> device = GetDeviceByHandle(hidHandle, true);
if (device == nullptr)
{
cemuLog_log(LogType::Force, "nsyshid.HIDSetReport(): Unable to find device with hid handle {}", hidHandle);
osLib_returnFromFunction(hCPU, -1);
return;
}
// prepare report data
// note: Currently we need to pad the data to 0x20 bytes for it to work (plus one extra byte for HidD_SetOutputReport)
// Does IOSU pad data to 0x20 byte? Also check if this is specific to Skylanders portal
sint32 paddedLength = (dataLength + 0x1F) & ~0x1F;
uint8* reportData = (uint8*)malloc(paddedLength + 1);
memset(reportData, 0, paddedLength + 1);
reportData[0] = 0;
memcpy(reportData + 1, data, dataLength);
// issue request (synchronous or asynchronous)
sint32 returnCode = 0;
if (callbackFuncMPTR == MPTR_NULL)
{
// synchronous
StackAllocator<coreinit::OSEvent> event;
coreinit::OSInitEvent(&event, coreinit::OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, coreinit::OSEvent::EVENT_MODE::MODE_AUTO);
std::future<sint32> res = std::async(std::launch::async, &_hidSetReportSync, device, reportData,
paddedLength + 1, data, dataLength, &event);
coreinit::OSWaitEvent(&event);
returnCode = res.get();
}
else
{
// asynchronous
std::thread(&_hidSetReportAsync, device, reportData, paddedLength + 1, data, dataLength,
callbackFuncMPTR, callbackParamMPTR)
.detach();
returnCode = 0;
}
osLib_returnFromFunction(hCPU, returnCode);
}
sint32 _hidReadInternalSync(std::shared_ptr<Device> device, uint8* data, sint32 maxLength)
{
cemuLog_logDebug(LogType::Force, "HidRead Begin (Length 0x{:08x})", maxLength);
if (!device->IsOpened())
{
cemuLog_logDebug(LogType::Force, "nsyshid.hidReadInternalSync(): cannot read from a non-opened device");
return -1;
}
memset(data, 0, maxLength);
ReadMessage message(data, maxLength, 0);
Device::ReadResult readResult = device->Read(&message);
switch (readResult)
{
case Device::ReadResult::Success:
{
cemuLog_logDebug(LogType::Force, "nsyshid.hidReadInternalSync(): read {} of {} bytes",
message.bytesRead,
maxLength);
return message.bytesRead;
}
break;
case Device::ReadResult::Error:
{
cemuLog_logDebug(LogType::Force, "nsyshid.hidReadInternalSync(): read error");
return -1;
}
break;
case Device::ReadResult::ErrorTimeout:
{
cemuLog_logDebug(LogType::Force, "nsyshid.hidReadInternalSync(): read error: timeout");
return -108;
}
break;
}
cemuLog_logDebug(LogType::Force, "nsyshid.hidReadInternalSync(): read error: unknown");
return -1;
}
void _hidReadAsync(std::shared_ptr<Device> device,
uint8* data, sint32 maxLength,
MPTR callbackFuncMPTR,
MPTR callbackParamMPTR)
{
sint32 returnCode = _hidReadInternalSync(device, data, maxLength);
sint32 errorCode = 0;
if (returnCode < 0)
errorCode = returnCode; // don't return number of bytes in error code
DoHIDTransferCallback(callbackFuncMPTR, callbackParamMPTR, device->m_hid->handle, errorCode,
memory_getVirtualOffsetFromPointer(data), (returnCode > 0) ? returnCode : 0);
}
sint32 _hidReadSync(std::shared_ptr<Device> device,
uint8* data,
sint32 maxLength,
coreinit::OSEvent* event)
{
sint32 returnCode = _hidReadInternalSync(device, data, maxLength);
coreinit::OSSignalEvent(event);
return returnCode;
}
void export_HIDRead(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(hidHandle, 0); // r3
ppcDefineParamUStr(data, 1); // r4
ppcDefineParamU32(maxLength, 2); // r5
ppcDefineParamMPTR(callbackFuncMPTR, 3); // r6
ppcDefineParamMPTR(callbackParamMPTR, 4); // r7
cemuLog_logDebug(LogType::Force, "nsyshid.HIDRead(0x{:x},0x{:08x},0x{:08x},0x{:08x},0x{:08x})", hCPU->gpr[3],
hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6], hCPU->gpr[7]);
std::shared_ptr<Device> device = GetDeviceByHandle(hidHandle, true);
if (device == nullptr)
{
cemuLog_log(LogType::Force, "nsyshid.HIDRead(): Unable to find device with hid handle {}", hidHandle);
osLib_returnFromFunction(hCPU, -1);
return;
}
sint32 returnCode = 0;
if (callbackFuncMPTR != MPTR_NULL)
{
// asynchronous transfer
std::thread(&_hidReadAsync, device, data, maxLength, callbackFuncMPTR, callbackParamMPTR).detach();
returnCode = 0;
}
else
{
// synchronous transfer
StackAllocator<coreinit::OSEvent> event;
coreinit::OSInitEvent(&event, coreinit::OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, coreinit::OSEvent::EVENT_MODE::MODE_AUTO);
std::future<sint32> res = std::async(std::launch::async, &_hidReadSync, device, data, maxLength, &event);
coreinit::OSWaitEvent(&event);
returnCode = res.get();
}
osLib_returnFromFunction(hCPU, returnCode);
}
sint32 _hidWriteInternalSync(std::shared_ptr<Device> device, uint8* data, sint32 maxLength)
{
cemuLog_logDebug(LogType::Force, "HidWrite Begin (Length 0x{:08x})", maxLength);
if (!device->IsOpened())
{
cemuLog_logDebug(LogType::Force, "nsyshid.hidWriteInternalSync(): cannot write to a non-opened device");
return -1;
}
WriteMessage message(data, maxLength, 0);
Device::WriteResult writeResult = device->Write(&message);
switch (writeResult)
{
case Device::WriteResult::Success:
{
cemuLog_logDebug(LogType::Force, "nsyshid.hidWriteInternalSync(): wrote {} of {} bytes", message.bytesWritten,
maxLength);
return message.bytesWritten;
}
break;
case Device::WriteResult::Error:
{
cemuLog_logDebug(LogType::Force, "nsyshid.hidWriteInternalSync(): write error");
return -1;
}
break;
case Device::WriteResult::ErrorTimeout:
{
cemuLog_logDebug(LogType::Force, "nsyshid.hidWriteInternalSync(): write error: timeout");
return -108;
}
break;
}
cemuLog_logDebug(LogType::Force, "nsyshid.hidWriteInternalSync(): write error: unknown");
return -1;
}
void _hidWriteAsync(std::shared_ptr<Device> device,
uint8* data,
sint32 maxLength,
MPTR callbackFuncMPTR,
MPTR callbackParamMPTR)
{
sint32 returnCode = _hidWriteInternalSync(device, data, maxLength);
sint32 errorCode = 0;
if (returnCode < 0)
errorCode = returnCode; // don't return number of bytes in error code
DoHIDTransferCallback(callbackFuncMPTR, callbackParamMPTR, device->m_hid->handle, errorCode,
memory_getVirtualOffsetFromPointer(data), (returnCode > 0) ? returnCode : 0);
}
sint32 _hidWriteSync(std::shared_ptr<Device> device,
uint8* data,
sint32 maxLength,
coreinit::OSEvent* event)
{
sint32 returnCode = _hidWriteInternalSync(device, data, maxLength);
coreinit::OSSignalEvent(event);
return returnCode;
}
void export_HIDWrite(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(hidHandle, 0); // r3
ppcDefineParamUStr(data, 1); // r4
ppcDefineParamU32(maxLength, 2); // r5
ppcDefineParamMPTR(callbackFuncMPTR, 3); // r6
ppcDefineParamMPTR(callbackParamMPTR, 4); // r7
cemuLog_logDebug(LogType::Force, "nsyshid.HIDWrite(0x{:x},0x{:08x},0x{:08x},0x{:08x},0x{:08x})", hCPU->gpr[3],
hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6], hCPU->gpr[7]);
std::shared_ptr<Device> device = GetDeviceByHandle(hidHandle, true);
if (device == nullptr)
{
cemuLog_log(LogType::Force, "nsyshid.HIDWrite(): Unable to find device with hid handle {}", hidHandle);
osLib_returnFromFunction(hCPU, -1);
return;
}
sint32 returnCode = 0;
if (callbackFuncMPTR != MPTR_NULL)
{
// asynchronous transfer
std::thread(&_hidWriteAsync, device, data, maxLength, callbackFuncMPTR, callbackParamMPTR).detach();
returnCode = 0;
}
else
{
// synchronous transfer
StackAllocator<coreinit::OSEvent> event;
coreinit::OSInitEvent(&event, coreinit::OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, coreinit::OSEvent::EVENT_MODE::MODE_AUTO);
std::future<sint32> res = std::async(std::launch::async, &_hidWriteSync, device, data, maxLength, &event);
coreinit::OSWaitEvent(&event);
returnCode = res.get();
}
osLib_returnFromFunction(hCPU, returnCode);
}
void export_HIDDecodeError(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(errorCode, 0);
ppcDefineParamTypePtr(ukn0, uint32be, 1);
ppcDefineParamTypePtr(ukn1, uint32be, 2);
cemuLog_logDebug(LogType::Force, "nsyshid.HIDDecodeError(0x{:08x},0x{:08x},0x{:08x})", hCPU->gpr[3],
hCPU->gpr[4], hCPU->gpr[5]);
// todo
*ukn0 = 0x3FF;
*ukn1 = (uint32)-0x7FFF;
osLib_returnFromFunction(hCPU, 0);
}
void Backend::DetachAllDevices()
{
std::lock_guard<std::recursive_mutex> lock(this->m_devicesMutex);
if (m_isAttached)
{
for (const auto& device : this->m_devices)
{
nsyshid::DetachDevice(device);
}
this->m_devices.clear();
}
}
bool Backend::AttachDevice(const std::shared_ptr<Device>& device)
{
std::lock_guard<std::recursive_mutex> lock(this->m_devicesMutex);
if (m_isAttached && nsyshid::AttachDevice(device))
{
this->m_devices.push_back(device);
return true;
}
return false;
}
void Backend::DetachDevice(const std::shared_ptr<Device>& device)
{
std::lock_guard<std::recursive_mutex> lock(this->m_devicesMutex);
if (m_isAttached)
{
nsyshid::DetachDevice(device);
this->m_devices.remove(device);
}
}
std::shared_ptr<Device> Backend::FindDevice(std::function<bool(const std::shared_ptr<Device>&)> isWantedDevice)
{
std::lock_guard<std::recursive_mutex> lock(this->m_devicesMutex);
auto it = std::find_if(this->m_devices.begin(), this->m_devices.end(), std::move(isWantedDevice));
if (it != this->m_devices.end())
{
return *it;
}
return nullptr;
}
bool Backend::FindDeviceById(uint16 vendorId, uint16 productId)
{
return nsyshid::FindDeviceById(vendorId, productId);
}
bool Backend::IsDeviceWhitelisted(uint16 vendorId, uint16 productId)
{
return Whitelist::GetInstance().IsDeviceWhitelisted(vendorId, productId);
}
Backend::Backend()
: m_isAttached(false)
{
}
void Backend::OnAttach()
{
std::lock_guard<std::recursive_mutex> lock(this->m_devicesMutex);
m_isAttached = true;
AttachVisibleDevices();
}
void Backend::OnDetach()
{
std::lock_guard<std::recursive_mutex> lock(this->m_devicesMutex);
DetachAllDevices();
m_isAttached = false;
}
bool Backend::IsBackendAttached()
{
std::lock_guard<std::recursive_mutex> lock(this->m_devicesMutex);
return m_isAttached;
}
Device::Device(uint16 vendorId,
uint16 productId,
uint8 interfaceIndex,
uint8 interfaceSubClass,
uint8 protocol)
: m_hid(nullptr),
m_vendorId(vendorId),
m_productId(productId),
m_interfaceIndex(interfaceIndex),
m_interfaceSubClass(interfaceSubClass),
m_protocol(protocol),
m_maxPacketSizeRX(0x20),
m_maxPacketSizeTX(0x20)
{
}
void Device::AssignHID(HID_t* hid)
{
if (hid != nullptr)
{
hid->vendorId = this->m_vendorId;
hid->productId = this->m_productId;
hid->ifIndex = this->m_interfaceIndex;
hid->subClass = this->m_interfaceSubClass;
hid->protocol = this->m_protocol;
hid->ukn04 = 0x11223344;
hid->paddingGuessed0F = 0;
hid->maxPacketSizeRX = this->m_maxPacketSizeRX;
hid->maxPacketSizeTX = this->m_maxPacketSizeTX;
}
this->m_hid = hid;
}
void load()
{
osLib_addFunction("nsyshid", "HIDAddClient", export_HIDAddClient);
osLib_addFunction("nsyshid", "HIDDelClient", export_HIDDelClient);
osLib_addFunction("nsyshid", "HIDGetDescriptor", export_HIDGetDescriptor);
osLib_addFunction("nsyshid", "HIDSetIdle", export_HIDSetIdle);
osLib_addFunction("nsyshid", "HIDSetProtocol", export_HIDSetProtocol);
osLib_addFunction("nsyshid", "HIDSetReport", export_HIDSetReport);
osLib_addFunction("nsyshid", "HIDRead", export_HIDRead);
osLib_addFunction("nsyshid", "HIDWrite", export_HIDWrite);
osLib_addFunction("nsyshid", "HIDDecodeError", export_HIDDecodeError);
// initialise whitelist
Whitelist::GetInstance();
AttachDefaultBackends();
}
} // namespace nsyshid
| 24,940
|
C++
|
.cpp
| 769
| 28.83355
| 146
| 0.717003
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,142
|
BackendLibusb.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nsyshid/BackendLibusb.cpp
|
#include "BackendLibusb.h"
#if NSYSHID_ENABLE_BACKEND_LIBUSB
namespace nsyshid::backend::libusb
{
BackendLibusb::BackendLibusb()
: m_ctx(nullptr),
m_initReturnCode(0),
m_callbackRegistered(false),
m_hotplugCallbackHandle(0),
m_hotplugThreadStop(false)
{
m_initReturnCode = libusb_init(&m_ctx);
if (m_initReturnCode < 0)
{
m_ctx = nullptr;
cemuLog_logDebug(LogType::Force, "nsyshid::BackendLibusb: failed to initialize libusb, return code: {}",
m_initReturnCode);
return;
}
if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG))
{
int ret = libusb_hotplug_register_callback(m_ctx,
(libusb_hotplug_event)(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |
LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT),
(libusb_hotplug_flag)0,
LIBUSB_HOTPLUG_MATCH_ANY,
LIBUSB_HOTPLUG_MATCH_ANY,
LIBUSB_HOTPLUG_MATCH_ANY,
HotplugCallback,
this,
&m_hotplugCallbackHandle);
if (ret != LIBUSB_SUCCESS)
{
cemuLog_logDebug(LogType::Force,
"nsyshid::BackendLibusb: failed to register hotplug callback with return code {}",
ret);
}
else
{
cemuLog_logDebug(LogType::Force, "nsyshid::BackendLibusb: registered hotplug callback");
m_callbackRegistered = true;
m_hotplugThread = std::thread([this] {
while (!m_hotplugThreadStop)
{
timeval timeout{
.tv_sec = 1,
.tv_usec = 0,
};
int ret = libusb_handle_events_timeout_completed(m_ctx, &timeout, nullptr);
if (ret != 0)
{
cemuLog_logDebug(LogType::Force,
"nsyshid::BackendLibusb: hotplug thread: error handling events: {}",
ret);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
});
}
}
else
{
cemuLog_logDebug(LogType::Force, "nsyshid::BackendLibusb: hotplug not supported by this version of libusb");
}
}
bool BackendLibusb::IsInitialisedOk()
{
return m_initReturnCode == 0;
}
void BackendLibusb::AttachVisibleDevices()
{
// add all currently connected devices
libusb_device** devices;
ssize_t deviceCount = libusb_get_device_list(m_ctx, &devices);
if (deviceCount < 0)
{
cemuLog_log(LogType::Force, "nsyshid::BackendLibusb: failed to get usb devices");
return;
}
libusb_device* dev;
for (int i = 0; (dev = devices[i]) != nullptr; i++)
{
auto device = CheckAndCreateDevice(dev);
if (device != nullptr)
{
if (IsDeviceWhitelisted(device->m_vendorId, device->m_productId))
{
if (!AttachDevice(device))
{
cemuLog_log(LogType::Force,
"nsyshid::BackendLibusb: failed to attach device: {:04x}:{:04x}",
device->m_vendorId,
device->m_productId);
}
}
else
{
cemuLog_log(LogType::Force,
"nsyshid::BackendLibusb: device not on whitelist: {:04x}:{:04x}",
device->m_vendorId,
device->m_productId);
}
}
}
libusb_free_device_list(devices, 1);
}
int BackendLibusb::HotplugCallback(libusb_context* ctx,
libusb_device* dev,
libusb_hotplug_event event,
void* user_data)
{
if (user_data)
{
BackendLibusb* backend = static_cast<BackendLibusb*>(user_data);
return backend->OnHotplug(dev, event);
}
return 0;
}
int BackendLibusb::OnHotplug(libusb_device* dev, libusb_hotplug_event event)
{
struct libusb_device_descriptor desc;
int ret = libusb_get_device_descriptor(dev, &desc);
if (ret < 0)
{
cemuLog_logDebug(LogType::Force, "nsyshid::BackendLibusb::OnHotplug(): failed to get device descriptor");
return 0;
}
switch (event)
{
case LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED:
{
cemuLog_logDebug(LogType::Force, "nsyshid::BackendLibusb::OnHotplug(): device arrived: {:04x}:{:04x}",
desc.idVendor,
desc.idProduct);
auto device = CheckAndCreateDevice(dev);
if (device != nullptr)
{
if (IsDeviceWhitelisted(device->m_vendorId, device->m_productId))
{
if (!AttachDevice(device))
{
cemuLog_log(LogType::Force,
"nsyshid::BackendLibusb::OnHotplug(): failed to attach device: {:04x}:{:04x}",
device->m_vendorId,
device->m_productId);
}
}
else
{
cemuLog_log(LogType::Force,
"nsyshid::BackendLibusb::OnHotplug(): device not on whitelist: {:04x}:{:04x}",
device->m_vendorId,
device->m_productId);
}
}
}
break;
case LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT:
{
cemuLog_logDebug(LogType::Force, "nsyshid::BackendLibusb::OnHotplug(): device left: {:04x}:{:04x}",
desc.idVendor,
desc.idProduct);
auto device = FindLibusbDevice(dev);
if (device != nullptr)
{
DetachDevice(device);
}
}
break;
}
return 0;
}
BackendLibusb::~BackendLibusb()
{
if (m_callbackRegistered)
{
m_hotplugThreadStop = true;
libusb_hotplug_deregister_callback(m_ctx, m_hotplugCallbackHandle);
m_hotplugThread.join();
}
DetachAllDevices();
if (m_ctx)
{
libusb_exit(m_ctx);
m_ctx = nullptr;
}
}
std::shared_ptr<Device> BackendLibusb::FindLibusbDevice(libusb_device* dev)
{
libusb_device_descriptor desc;
int ret = libusb_get_device_descriptor(dev, &desc);
if (ret < 0)
{
cemuLog_logDebug(LogType::Force,
"nsyshid::BackendLibusb::FindLibusbDevice(): failed to get device descriptor");
return nullptr;
}
uint8 busNumber = libusb_get_bus_number(dev);
uint8 deviceAddress = libusb_get_device_address(dev);
auto device = FindDevice([desc, busNumber, deviceAddress](const std::shared_ptr<Device>& d) -> bool {
auto device = std::dynamic_pointer_cast<DeviceLibusb>(d);
if (device != nullptr &&
desc.idVendor == device->m_vendorId &&
desc.idProduct == device->m_productId &&
busNumber == device->m_libusbBusNumber &&
deviceAddress == device->m_libusbDeviceAddress)
{
// we found our device!
return true;
}
return false;
});
if (device != nullptr)
{
return device;
}
return nullptr;
}
std::pair<int, ConfigDescriptor> MakeConfigDescriptor(libusb_device* device, uint8 config_num)
{
libusb_config_descriptor* descriptor = nullptr;
const int ret = libusb_get_config_descriptor(device, config_num, &descriptor);
if (ret == LIBUSB_SUCCESS)
return {ret, ConfigDescriptor{descriptor, libusb_free_config_descriptor}};
return {ret, ConfigDescriptor{nullptr, [](auto) {
}}};
}
std::shared_ptr<Device> BackendLibusb::CheckAndCreateDevice(libusb_device* dev)
{
struct libusb_device_descriptor desc;
int ret = libusb_get_device_descriptor(dev, &desc);
if (ret < 0)
{
cemuLog_log(LogType::Force,
"nsyshid::BackendLibusb::CheckAndCreateDevice(): failed to get device descriptor; return code: %i",
ret);
return nullptr;
}
std::vector<ConfigDescriptor> config_descriptors{};
for (uint8 i = 0; i < desc.bNumConfigurations; ++i)
{
auto [ret, config_descriptor] = MakeConfigDescriptor(dev, i);
if (ret != LIBUSB_SUCCESS || !config_descriptor)
{
cemuLog_log(LogType::Force, "Failed to make config descriptor {} for {:04x}:{:04x}: {}",
i, desc.idVendor, desc.idProduct, libusb_error_name(ret));
}
else
{
config_descriptors.emplace_back(std::move(config_descriptor));
}
}
if (desc.idVendor == 0x0e6f && desc.idProduct == 0x0241)
{
cemuLog_logDebug(LogType::Force,
"nsyshid::BackendLibusb::CheckAndCreateDevice(): lego dimensions portal detected");
}
auto device = std::make_shared<DeviceLibusb>(m_ctx,
desc.idVendor,
desc.idProduct,
1,
2,
0,
libusb_get_bus_number(dev),
libusb_get_device_address(dev),
std::move(config_descriptors));
// figure out device endpoints
if (!FindDefaultDeviceEndpoints(dev,
device->m_libusbHasEndpointIn,
device->m_libusbEndpointIn,
device->m_maxPacketSizeRX,
device->m_libusbHasEndpointOut,
device->m_libusbEndpointOut,
device->m_maxPacketSizeTX))
{
// most likely couldn't read config descriptor
cemuLog_log(LogType::Force,
"nsyshid::BackendLibusb::CheckAndCreateDevice(): failed to find default endpoints for device: {:04x}:{:04x}",
device->m_vendorId,
device->m_productId);
return nullptr;
}
return device;
}
bool BackendLibusb::FindDefaultDeviceEndpoints(libusb_device* dev, bool& endpointInFound, uint8& endpointIn,
uint16& endpointInMaxPacketSize, bool& endpointOutFound,
uint8& endpointOut, uint16& endpointOutMaxPacketSize)
{
endpointInFound = false;
endpointIn = 0;
endpointInMaxPacketSize = 0;
endpointOutFound = false;
endpointOut = 0;
endpointOutMaxPacketSize = 0;
struct libusb_config_descriptor* conf = nullptr;
int ret = libusb_get_active_config_descriptor(dev, &conf);
if (ret == 0)
{
for (uint8 interfaceIndex = 0; interfaceIndex < conf->bNumInterfaces; interfaceIndex++)
{
const struct libusb_interface& interface = conf->interface[interfaceIndex];
for (int altsettingIndex = 0; altsettingIndex < interface.num_altsetting; altsettingIndex++)
{
const struct libusb_interface_descriptor& altsetting = interface.altsetting[altsettingIndex];
for (uint8 endpointIndex = 0; endpointIndex < altsetting.bNumEndpoints; endpointIndex++)
{
const struct libusb_endpoint_descriptor& endpoint = altsetting.endpoint[endpointIndex];
// figure out direction
if ((endpoint.bEndpointAddress & (1 << 7)) != 0)
{
// in
if (!endpointInFound)
{
endpointInFound = true;
endpointIn = endpoint.bEndpointAddress;
endpointInMaxPacketSize = endpoint.wMaxPacketSize;
}
}
else
{
// out
if (!endpointOutFound)
{
endpointOutFound = true;
endpointOut = endpoint.bEndpointAddress;
endpointOutMaxPacketSize = endpoint.wMaxPacketSize;
}
}
}
}
}
libusb_free_config_descriptor(conf);
return true;
}
return false;
}
DeviceLibusb::DeviceLibusb(libusb_context* ctx,
uint16 vendorId,
uint16 productId,
uint8 interfaceIndex,
uint8 interfaceSubClass,
uint8 protocol,
uint8 libusbBusNumber,
uint8 libusbDeviceAddress,
std::vector<ConfigDescriptor> configs)
: Device(vendorId,
productId,
interfaceIndex,
interfaceSubClass,
protocol),
m_ctx(ctx),
m_libusbHandle(nullptr),
m_handleInUseCounter(-1),
m_libusbBusNumber(libusbBusNumber),
m_libusbDeviceAddress(libusbDeviceAddress),
m_libusbHasEndpointIn(false),
m_libusbEndpointIn(0),
m_libusbHasEndpointOut(false),
m_libusbEndpointOut(0)
{
m_config_descriptors = std::move(configs);
}
DeviceLibusb::~DeviceLibusb()
{
CloseDevice();
}
bool DeviceLibusb::Open()
{
std::unique_lock<std::mutex> lock(m_handleMutex);
if (IsOpened())
{
return true;
}
// we may still be in the process of closing the device; wait for that to finish
while (m_handleInUseCounter != -1)
{
m_handleInUseCounterDecremented.wait(lock);
}
libusb_device** devices;
ssize_t deviceCount = libusb_get_device_list(m_ctx, &devices);
if (deviceCount < 0)
{
cemuLog_log(LogType::Force, "nsyshid::DeviceLibusb::open(): failed to get usb devices");
return false;
}
libusb_device* dev;
libusb_device* found = nullptr;
for (int i = 0; (dev = devices[i]) != nullptr; i++)
{
struct libusb_device_descriptor desc;
int ret = libusb_get_device_descriptor(dev, &desc);
if (ret < 0)
{
cemuLog_log(LogType::Force,
"nsyshid::DeviceLibusb::open(): failed to get device descriptor, return code: {}",
ret);
libusb_free_device_list(devices, 1);
return false;
}
if (desc.idVendor == this->m_vendorId &&
desc.idProduct == this->m_productId &&
libusb_get_bus_number(dev) == this->m_libusbBusNumber &&
libusb_get_device_address(dev) == this->m_libusbDeviceAddress)
{
// we found our device!
found = dev;
break;
}
}
if (found != nullptr)
{
{
int ret = libusb_open(dev, &(this->m_libusbHandle));
if (ret < 0)
{
this->m_libusbHandle = nullptr;
cemuLog_log(LogType::Force,
"nsyshid::DeviceLibusb::open(): failed to open device: {}",
libusb_strerror(ret));
libusb_free_device_list(devices, 1);
return false;
}
this->m_handleInUseCounter = 0;
}
{
int ret = ClaimAllInterfaces(0);
if (ret != 0)
{
cemuLog_logDebug(LogType::Force, "nsyshid::DeviceLibusb::open(): cannot claim interface");
}
}
}
libusb_free_device_list(devices, 1);
return found != nullptr;
}
void DeviceLibusb::Close()
{
CloseDevice();
}
void DeviceLibusb::CloseDevice()
{
std::unique_lock<std::mutex> lock(m_handleMutex);
if (IsOpened())
{
auto handle = m_libusbHandle;
m_libusbHandle = nullptr;
while (m_handleInUseCounter > 0)
{
m_handleInUseCounterDecremented.wait(lock);
}
libusb_release_interface(handle, 0);
libusb_close(handle);
m_handleInUseCounter = -1;
m_handleInUseCounterDecremented.notify_all();
}
}
bool DeviceLibusb::IsOpened()
{
return m_libusbHandle != nullptr && m_handleInUseCounter >= 0;
}
Device::ReadResult DeviceLibusb::Read(ReadMessage* message)
{
auto handleLock = AquireHandleLock();
if (!handleLock->IsValid())
{
cemuLog_logDebug(LogType::Force,
"nsyshid::DeviceLibusb::read(): cannot read from a non-opened device\n");
return ReadResult::Error;
}
const unsigned int timeout = 50;
int actualLength = 0;
int ret = 0;
do
{
ret = libusb_bulk_transfer(handleLock->GetHandle(),
this->m_libusbEndpointIn,
message->data,
message->length,
&actualLength,
timeout);
}
while (ret == LIBUSB_ERROR_TIMEOUT && actualLength == 0 && IsOpened());
if (ret == 0 || ret == LIBUSB_ERROR_TIMEOUT)
{
// success
cemuLog_logDebug(LogType::Force, "nsyshid::DeviceLibusb::read(): read {} of {} bytes",
actualLength,
message->length);
message->bytesRead = actualLength;
return ReadResult::Success;
}
cemuLog_logDebug(LogType::Force,
"nsyshid::DeviceLibusb::read(): failed with error code: {}",
ret);
return ReadResult::Error;
}
Device::WriteResult DeviceLibusb::Write(WriteMessage* message)
{
auto handleLock = AquireHandleLock();
if (!handleLock->IsValid())
{
cemuLog_logDebug(LogType::Force,
"nsyshid::DeviceLibusb::write(): cannot write to a non-opened device\n");
return WriteResult::Error;
}
message->bytesWritten = 0;
int actualLength = 0;
int ret = libusb_bulk_transfer(handleLock->GetHandle(),
this->m_libusbEndpointOut,
message->data,
message->length,
&actualLength,
0);
if (ret == 0)
{
// success
message->bytesWritten = actualLength;
cemuLog_logDebug(LogType::Force,
"nsyshid::DeviceLibusb::write(): wrote {} of {} bytes",
message->bytesWritten,
message->length);
return WriteResult::Success;
}
cemuLog_logDebug(LogType::Force,
"nsyshid::DeviceLibusb::write(): failed with error code: {}",
ret);
return WriteResult::Error;
}
bool DeviceLibusb::GetDescriptor(uint8 descType,
uint8 descIndex,
uint8 lang,
uint8* output,
uint32 outputMaxLength)
{
auto handleLock = AquireHandleLock();
if (!handleLock->IsValid())
{
cemuLog_logDebug(LogType::Force, "nsyshid::DeviceLibusb::getDescriptor(): device is not opened");
return false;
}
if (descType == 0x02)
{
struct libusb_config_descriptor* conf = nullptr;
libusb_device* dev = libusb_get_device(handleLock->GetHandle());
int ret = libusb_get_active_config_descriptor(dev, &conf);
if (ret == 0)
{
std::vector<uint8> configurationDescriptor(conf->wTotalLength);
uint8* currentWritePtr = &configurationDescriptor[0];
// configuration descriptor
cemu_assert_debug(conf->bLength == LIBUSB_DT_CONFIG_SIZE);
*(uint8*)(currentWritePtr + 0) = conf->bLength; // bLength
*(uint8*)(currentWritePtr + 1) = conf->bDescriptorType; // bDescriptorType
*(uint16be*)(currentWritePtr + 2) = conf->wTotalLength; // wTotalLength
*(uint8*)(currentWritePtr + 4) = conf->bNumInterfaces; // bNumInterfaces
*(uint8*)(currentWritePtr + 5) = conf->bConfigurationValue; // bConfigurationValue
*(uint8*)(currentWritePtr + 6) = conf->iConfiguration; // iConfiguration
*(uint8*)(currentWritePtr + 7) = conf->bmAttributes; // bmAttributes
*(uint8*)(currentWritePtr + 8) = conf->MaxPower; // MaxPower
currentWritePtr = currentWritePtr + conf->bLength;
for (uint8_t interfaceIndex = 0; interfaceIndex < conf->bNumInterfaces; interfaceIndex++)
{
const struct libusb_interface& interface = conf->interface[interfaceIndex];
for (int altsettingIndex = 0; altsettingIndex < interface.num_altsetting; altsettingIndex++)
{
// interface descriptor
const struct libusb_interface_descriptor& altsetting = interface.altsetting[altsettingIndex];
cemu_assert_debug(altsetting.bLength == LIBUSB_DT_INTERFACE_SIZE);
*(uint8*)(currentWritePtr + 0) = altsetting.bLength; // bLength
*(uint8*)(currentWritePtr + 1) = altsetting.bDescriptorType; // bDescriptorType
*(uint8*)(currentWritePtr + 2) = altsetting.bInterfaceNumber; // bInterfaceNumber
*(uint8*)(currentWritePtr + 3) = altsetting.bAlternateSetting; // bAlternateSetting
*(uint8*)(currentWritePtr + 4) = altsetting.bNumEndpoints; // bNumEndpoints
*(uint8*)(currentWritePtr + 5) = altsetting.bInterfaceClass; // bInterfaceClass
*(uint8*)(currentWritePtr + 6) = altsetting.bInterfaceSubClass; // bInterfaceSubClass
*(uint8*)(currentWritePtr + 7) = altsetting.bInterfaceProtocol; // bInterfaceProtocol
*(uint8*)(currentWritePtr + 8) = altsetting.iInterface; // iInterface
currentWritePtr = currentWritePtr + altsetting.bLength;
if (altsetting.extra_length > 0)
{
// unknown descriptors - copy the ones that we can identify ourselves
const unsigned char* extraReadPointer = altsetting.extra;
while (extraReadPointer - altsetting.extra < altsetting.extra_length)
{
uint8 bLength = *(uint8*)(extraReadPointer + 0);
if (bLength == 0)
{
// prevent endless loop
break;
}
if (extraReadPointer + bLength - altsetting.extra > altsetting.extra_length)
{
// prevent out of bounds read
break;
}
uint8 bDescriptorType = *(uint8*)(extraReadPointer + 1);
// HID descriptor
if (bDescriptorType == LIBUSB_DT_HID && bLength == 9)
{
*(uint8*)(currentWritePtr + 0) =
*(uint8*)(extraReadPointer + 0); // bLength
*(uint8*)(currentWritePtr + 1) =
*(uint8*)(extraReadPointer + 1); // bDescriptorType
*(uint16be*)(currentWritePtr + 2) =
*(uint16*)(extraReadPointer + 2); // bcdHID
*(uint8*)(currentWritePtr + 4) =
*(uint8*)(extraReadPointer + 4); // bCountryCode
*(uint8*)(currentWritePtr + 5) =
*(uint8*)(extraReadPointer + 5); // bNumDescriptors
*(uint8*)(currentWritePtr + 6) =
*(uint8*)(extraReadPointer + 6); // bDescriptorType
*(uint16be*)(currentWritePtr + 7) =
*(uint16*)(extraReadPointer + 7); // wDescriptorLength
currentWritePtr += bLength;
}
extraReadPointer += bLength;
}
}
for (int endpointIndex = 0; endpointIndex < altsetting.bNumEndpoints; endpointIndex++)
{
// endpoint descriptor
const struct libusb_endpoint_descriptor& endpoint = altsetting.endpoint[endpointIndex];
cemu_assert_debug(endpoint.bLength == LIBUSB_DT_ENDPOINT_SIZE ||
endpoint.bLength == LIBUSB_DT_ENDPOINT_AUDIO_SIZE);
*(uint8*)(currentWritePtr + 0) = endpoint.bLength;
*(uint8*)(currentWritePtr + 1) = endpoint.bDescriptorType;
*(uint8*)(currentWritePtr + 2) = endpoint.bEndpointAddress;
*(uint8*)(currentWritePtr + 3) = endpoint.bmAttributes;
*(uint16be*)(currentWritePtr + 4) = endpoint.wMaxPacketSize;
*(uint8*)(currentWritePtr + 6) = endpoint.bInterval;
if (endpoint.bLength == LIBUSB_DT_ENDPOINT_AUDIO_SIZE)
{
*(uint8*)(currentWritePtr + 7) = endpoint.bRefresh;
*(uint8*)(currentWritePtr + 8) = endpoint.bSynchAddress;
}
currentWritePtr += endpoint.bLength;
}
}
}
uint32 bytesWritten = currentWritePtr - &configurationDescriptor[0];
libusb_free_config_descriptor(conf);
cemu_assert_debug(bytesWritten <= conf->wTotalLength);
memcpy(output, &configurationDescriptor[0],
std::min<uint32>(outputMaxLength, bytesWritten));
return true;
}
else
{
cemuLog_logDebug(LogType::Force,
"nsyshid::DeviceLibusb::getDescriptor(): failed to get config descriptor with error code: {}",
ret);
return false;
}
}
else
{
cemu_assert_unimplemented();
}
return false;
}
template<typename Configs, typename Function>
static int DoForEachInterface(const Configs& configs, uint8 config_num, Function action)
{
int ret = LIBUSB_ERROR_NOT_FOUND;
if (configs.size() <= config_num || !configs[config_num])
return ret;
for (uint8 i = 0; i < configs[config_num]->bNumInterfaces; ++i)
{
ret = action(i);
if (ret < LIBUSB_SUCCESS)
break;
}
return ret;
}
int DeviceLibusb::ClaimAllInterfaces(uint8 config_num)
{
const int ret = DoForEachInterface(m_config_descriptors, config_num, [this](uint8 i) {
if (libusb_kernel_driver_active(this->m_libusbHandle, i))
{
const int ret2 = libusb_detach_kernel_driver(this->m_libusbHandle, i);
if (ret2 < LIBUSB_SUCCESS && ret2 != LIBUSB_ERROR_NOT_FOUND &&
ret2 != LIBUSB_ERROR_NOT_SUPPORTED)
{
cemuLog_log(LogType::Force, "Failed to detach kernel driver {}", libusb_error_name(ret2));
return ret2;
}
}
return libusb_claim_interface(this->m_libusbHandle, i);
});
if (ret < LIBUSB_SUCCESS)
{
cemuLog_log(LogType::Force, "Failed to release all interfaces for config {}", config_num);
}
return ret;
}
int DeviceLibusb::ReleaseAllInterfaces(uint8 config_num)
{
const int ret = DoForEachInterface(m_config_descriptors, config_num, [this](uint8 i) {
return libusb_release_interface(AquireHandleLock()->GetHandle(), i);
});
if (ret < LIBUSB_SUCCESS && ret != LIBUSB_ERROR_NO_DEVICE && ret != LIBUSB_ERROR_NOT_FOUND)
{
cemuLog_log(LogType::Force, "Failed to release all interfaces for config {}", config_num);
}
return ret;
}
int DeviceLibusb::ReleaseAllInterfacesForCurrentConfig()
{
int config_num;
const int get_config_ret = libusb_get_configuration(AquireHandleLock()->GetHandle(), &config_num);
if (get_config_ret < LIBUSB_SUCCESS)
return get_config_ret;
return ReleaseAllInterfaces(config_num);
}
bool DeviceLibusb::SetProtocol(uint8 ifIndex, uint8 protocol)
{
auto handleLock = AquireHandleLock();
if (!handleLock->IsValid())
{
cemuLog_logDebug(LogType::Force, "nsyshid::DeviceLibusb::SetProtocol(): device is not opened");
return false;
}
if (m_interfaceIndex != ifIndex)
m_interfaceIndex = ifIndex;
ReleaseAllInterfacesForCurrentConfig();
int ret = libusb_set_configuration(AquireHandleLock()->GetHandle(), protocol);
if (ret == LIBUSB_SUCCESS)
ret = ClaimAllInterfaces(protocol);
if (ret == LIBUSB_SUCCESS)
return true;
return false;
}
bool DeviceLibusb::SetReport(ReportMessage* message)
{
auto handleLock = AquireHandleLock();
if (!handleLock->IsValid())
{
cemuLog_logDebug(LogType::Force, "nsyshid::DeviceLibusb::SetReport(): device is not opened");
return false;
}
int ret = libusb_control_transfer(handleLock->GetHandle(),
LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE | LIBUSB_ENDPOINT_OUT,
LIBUSB_REQUEST_SET_CONFIGURATION,
512,
0,
message->originalData,
message->originalLength,
0);
if (ret != message->originalLength)
{
cemuLog_logDebug(LogType::Force, "nsyshid::DeviceLibusb::SetReport(): Control Transfer Failed: {}", libusb_error_name(ret));
return false;
}
return true;
}
std::unique_ptr<DeviceLibusb::HandleLock> DeviceLibusb::AquireHandleLock()
{
return std::make_unique<HandleLock>(&m_libusbHandle,
m_handleMutex,
m_handleInUseCounter,
m_handleInUseCounterDecremented,
*this);
}
DeviceLibusb::HandleLock::HandleLock(libusb_device_handle** handle,
std::mutex& handleMutex,
std::atomic<sint32>& handleInUseCounter,
std::condition_variable& handleInUseCounterDecremented,
DeviceLibusb& device)
: m_handle(nullptr),
m_handleMutex(handleMutex),
m_handleInUseCounter(handleInUseCounter),
m_handleInUseCounterDecremented(handleInUseCounterDecremented)
{
std::lock_guard<std::mutex> lock(handleMutex);
if (device.IsOpened() && handle != nullptr && handleInUseCounter >= 0)
{
this->m_handle = *handle;
this->m_handleInUseCounter++;
}
}
DeviceLibusb::HandleLock::~HandleLock()
{
if (IsValid())
{
std::lock_guard<std::mutex> lock(m_handleMutex);
m_handleInUseCounter--;
m_handleInUseCounterDecremented.notify_all();
}
}
bool DeviceLibusb::HandleLock::IsValid()
{
return m_handle != nullptr;
}
libusb_device_handle* DeviceLibusb::HandleLock::GetHandle()
{
return m_handle;
}
} // namespace nsyshid::backend::libusb
#endif // NSYSHID_ENABLE_BACKEND_LIBUSB
| 26,044
|
C++
|
.cpp
| 799
| 27.216521
| 127
| 0.668149
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,143
|
nn_nfp.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_nfp/nn_nfp.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "Cafe/OS/libs/nn_common.h"
#include "nn_nfp.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Common/FileStream.h"
#include "Cafe/CafeSystem.h"
std::recursive_mutex g_nfpMutex;
void nnNfpLock()
{
g_nfpMutex.lock();
}
bool nnNfpTryLock()
{
return g_nfpMutex.try_lock();
}
void nnNfpUnlock()
{
g_nfpMutex.unlock();
}
struct AmiiboInternal
{
/* +0x000 */ uint16 lockBytes;
/* +0x002 */ uint16 staticLock;
/* +0x004 */ uint32 cc;
/* +0x008 */ uint8 dataHMAC[32];
/* +0x028 */ uint8 ukn_A5; // always 0xA5
/* +0x029 */ uint8 writeCounterHigh;
/* +0x029 */ uint8 writeCounterLow;
/* +0x02B */ uint8 unk02B;
/* encrypted region starts here */
struct
{
/* +0x02C */ uint8 flags;
/* +0x02D */ uint8 countryCode;
/* +0x02E */ uint16be crcWriteCounter;
/* +0x030 */ uint16be date1;
/* +0x032 */ uint16be date2;
/* +0x034 */ uint32be crc;
/* +0x038 */ uint16be nickname[10];
/* +0x04C */ uint8 mii[0x60];
/* +0x0AC */ uint32be appDataTitleIdHigh;
/* +0x0B0 */ uint32be appDataTitleIdLow;
/* +0x0B4 */ uint16be appWriteCounter;
/* +0x0B6 */ uint16be appDataIdHigh;
/* +0x0B8 */ uint16be appDataIdLow;
/* +0x0BA */ uint16be ukn0BA;
/* +0x0BC */ uint32be ukn0BC;
/* +0x0C0 */ uint32be ukn0C0;
/* +0x0C4 */ uint32be ukn0C4;
/* +0x0C8 */ uint32be ukn0C8;
/* +0x0CC */ uint32be ukn0CC;
/* +0x0D0 */ uint32be ukn0D0;
/* +0x0D4 */ uint32be ukn0D4;
/* +0x0D8 */ uint32be ukn0D8;
uint32 getAppDataAppId()
{
uint32 appId = (uint32)appDataIdHigh << 16;
appId |= (uint32)appDataIdLow;
return appId;
}
void setAppDataAppId(uint32 appId)
{
appDataIdHigh = (uint16)(appId >> 16);
appDataIdLow = (uint16)(appId & 0xFFFF);
}
}amiiboSettings;
/* +0x0DC */ uint8 applicationData[0xD8];
/* encrypted region ends here */
/* +0x1B4 */ uint8 tagHMAC[32];
/* +0x1D4 */ uint8 ntagSerial[7];
/* +0x1DB */ uint8 nintendoId;
struct
{
/* +0x1DC */ uint8 gameAndCharacterId[2];
/* +0x1DE */ uint8 characterVariation;
/* +0x1DF */ uint8 amiiboFigureType;
/* +0x1E0 */ uint8 amiiboModelNumber[2];
/* +0x1E2 */ uint8 amiiboSeries;
/* +0x1E3 */ uint8 ukn_02; // always 0x02 ?
/* +0x1E4 */ uint8 ukn5C[4];
}amiiboIdentificationBlock;
/* +0x1E8 */ uint8 keygenSalt[32];
};
static_assert(sizeof(AmiiboInternal) == 0x208);
static_assert(offsetof(AmiiboInternal, dataHMAC) == 0x8);
static_assert(offsetof(AmiiboInternal, amiiboSettings.appDataIdHigh) == 0xB6);
static_assert(offsetof(AmiiboInternal, amiiboSettings.ukn0D8) == 0xD8);
static_assert(offsetof(AmiiboInternal, tagHMAC) == 0x1B4);
union AmiiboRawNFCData
{
// each page is 4 bytes
struct
{
uint8 page0[4];
uint8 page1[4];
uint8 page2[4];
uint8 page3[4];
uint8 page4[4];
uint8 page5[4];
uint8 page6[4];
uint8 page7[4];
uint8 page8[4];
uint8 page9[4];
uint8 page10[4];
uint8 page11[4];
uint8 page12[4];
uint8 page13[4];
uint8 page14[4];
uint8 page15[4];
uint8 page16[4];
};
struct
{
uint8 rawByte[16 * 4];
};
struct
{
/* +0x000 */ uint8 ntagSerial[7];
/* +0x007 */ uint8 nintendoId;
/* +0x008 */ uint8 lockBytes[2];
/* +0x00A */ uint8 staticLock[2];
/* +0x00C */ uint8 cc[4]; // compatibility container
/* +0x010 */ uint8 ukn_A5; // always 0xA5
/* +0x011 */ uint8 writeCounter[2];
/* +0x013 */ uint8 unk013;
/* +0x014 */ uint8 encryptedSettings[32];
/* +0x034 */ uint8 tagHMAC[32]; // data hmac
/* +0x054 */
struct
{
/* +0x54 */ uint8 gameAndCharacterId[2];
/* +0x56 */ uint8 characterVariation;
/* +0x57 */ uint8 amiiboFigureType;
/* +0x58 */ uint8 amiiboModelNumber[2];
/* +0x5A */ uint8 amiiboSeries;
/* +0x5B */ uint8 ukn_02; // always 0x02 ?
/* +0x5C */ uint8 ukn5C[4];
}amiiboIdentificationBlock;
/* +0x060 */ uint8 keygenSalt[32];
/* +0x080 */ uint8 dataHMAC[32];
/* +0x0A0 */ uint8 encryptedMii[0x60];
/* +0x100 */ uint8 encryptedTitleId[8];
/* +0x108 */ uint8 encryptedApplicationWriteCounter[2];
/* +0x10A */ uint8 encryptedApplicationAreaId[4];
/* +0x10E */ uint8 ukn10E[2];
/* +0x110 */ uint8 unk110[32];
/* +0x130 */ uint8 encryptedApplicationArea[0xD8];
/* +0x208 */ uint8 dynamicLock[4];
/* +0x20C */ uint8 cfg0[4];
/* +0x210 */ uint8 cfg1[4];
};
};
static_assert(sizeof(AmiiboRawNFCData) == 532);
struct AmiiboProcessedData
{
uint8 uidLength;
uint8 uid[7];
};
struct
{
bool nfpIsInitialized;
MPTR activateEvent;
MPTR deactivateEvent;
bool isDetecting;
bool isMounted;
bool isReadOnly;
bool hasOpenApplicationArea; // set to true if application area was opened or created
// currently active Amiibo
bool hasActiveAmiibo;
fs::path amiiboPath;
bool hasInvalidHMAC;
uint32 amiiboTouchTime;
AmiiboRawNFCData amiiboNFCData; // raw data
AmiiboInternal amiiboInternal; // decrypted internal format
AmiiboProcessedData amiiboProcessedData;
}nfp_data = { 0 };
bool nnNfp_writeCurrentAmiibo();
#include "AmiiboCrypto.h"
void nnNfpExport_SetActivateEvent(PPCInterpreter_t* hCPU)
{
// parameters:
// r3 OSEvent_t*
ppcDefineParamStructPtr(osEvent, coreinit::OSEvent, 0);
ppcDefineParamMPTR(osEventMPTR, 0);
debug_printf("nn_nfp.SetActivateEvent(0x%08x)\n", osEventMPTR);
coreinit::OSInitEvent(osEvent, coreinit::OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, coreinit::OSEvent::EVENT_MODE::MODE_AUTO);
nnNfpLock();
nfp_data.activateEvent = osEventMPTR;
nnNfpUnlock();
osLib_returnFromFunction(hCPU, 0); // return value ukn
}
void nnNfpExport_SetDeactivateEvent(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(osEvent, coreinit::OSEvent, 0);
ppcDefineParamMPTR(osEventMPTR, 0);
cemuLog_log(LogType::NN_NFP, "SetDeactivateEvent(0x{:08x})", osEventMPTR);
coreinit::OSInitEvent(osEvent, coreinit::OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, coreinit::OSEvent::EVENT_MODE::MODE_AUTO);
nnNfpLock();
nfp_data.deactivateEvent = osEventMPTR;
nnNfpUnlock();
osLib_returnFromFunction(hCPU, 0); // return value ukn
}
void nnNfpExport_Initialize(PPCInterpreter_t* hCPU)
{
debug_printf("Nfp Initialize()\n");
nfp_data.nfpIsInitialized = true;
nfp_data.isDetecting = false;
nfp_data.hasActiveAmiibo = false;
nfp_data.hasOpenApplicationArea = false;
nfp_data.activateEvent = MPTR_NULL;
nfp_data.deactivateEvent = MPTR_NULL;
osLib_returnFromFunction(hCPU, 0);
}
void nnNfpExport_StartDetection(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "StartDetection()");
nnNfpLock();
nfp_data.isDetecting = true;
nnNfpUnlock();
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
void nnNfpExport_StopDetection(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "StopDetection()");
nnNfpLock();
nfp_data.isDetecting = false;
nnNfpUnlock();
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
#define NFP_TAG_MAX_LENGTH (10)
typedef struct
{
/* +0x00 */ uint8 uidLength;
/* +0x01 */ uint8 uid[0xA];
/* +0x0B */ uint8 unused0B[0x15];
/* +0x20 */ uint32 ukn20[4];
uint32 ukn30[4];
uint32 ukn40[4];
uint32 ukn50;
}nfpTagInfo_t;
static_assert(sizeof(nfpTagInfo_t) == 0x54, "nfpTagInfo_t has invalid size");
void nnNfpExport_GetTagInfo(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "GetTagInfo(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamStructPtr(tagInfo, nfpTagInfo_t, 0);
nnNfpLock();
if (nfp_data.hasActiveAmiibo == false)
{
nnNfpUnlock();
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0)); // todo: Return correct error code
return;
}
memset(tagInfo, 0x00, sizeof(nfpTagInfo_t));
memcpy(tagInfo->uid, nfp_data.amiiboProcessedData.uid, nfp_data.amiiboProcessedData.uidLength);
tagInfo->uidLength = (uint8)nfp_data.amiiboProcessedData.uidLength;
// todo - remaining values
nnNfpUnlock();
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
void nnNfpExport_Mount(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "Mount()");
nnNfpLock();
if (nfp_data.hasActiveAmiibo == false)
{
nnNfpUnlock();
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0)); // todo: Return correct error code
return;
}
nfp_data.isMounted = true;
nfp_data.isReadOnly = false;
nfp_data.isDetecting = false;
nnNfpUnlock();
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
void nnNfpExport_Unmount(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "Unmount()");
nfp_data.hasOpenApplicationArea = false;
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
void nnNfpExport_MountRom(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "MountRom()");
nnNfpLock();
if (nfp_data.hasActiveAmiibo == false)
{
nnNfpUnlock();
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0)); // todo: Return correct error code
return;
}
nfp_data.isMounted = true;
nfp_data.isReadOnly = true;
nfp_data.isDetecting = false;
nnNfpUnlock();
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
namespace nn::nfp
{
struct RomInfo
{
/* +0x00 */ uint8 characterId[3];
/* +0x03 */ uint8 amiiboSeries;
/* +0x04 */ uint16be number;
/* +0x06 */ uint8 nfpType;
/* +0x07 */ uint8 unused[0x2F];
};
static_assert(offsetof(RomInfo, amiiboSeries) == 0x3);
static_assert(offsetof(RomInfo, number) == 0x4);
static_assert(offsetof(RomInfo, nfpType) == 0x6);
static_assert(sizeof(RomInfo) == 0x36);
using ReadOnlyInfo = RomInfo; // same layout
void GetRomInfo(RomInfo* romInfo)
{
cemu_assert_debug(nfp_data.hasActiveAmiibo);
memset(romInfo, 0x00, sizeof(RomInfo));
romInfo->characterId[0] = nfp_data.amiiboNFCData.amiiboIdentificationBlock.gameAndCharacterId[0];
romInfo->characterId[1] = nfp_data.amiiboNFCData.amiiboIdentificationBlock.gameAndCharacterId[1];
romInfo->characterId[2] = nfp_data.amiiboNFCData.amiiboIdentificationBlock.characterVariation; // guessed
romInfo->amiiboSeries = nfp_data.amiiboNFCData.amiiboIdentificationBlock.amiiboSeries; // guessed
romInfo->number = *(uint16be*)nfp_data.amiiboNFCData.amiiboIdentificationBlock.amiiboModelNumber; // guessed
romInfo->nfpType = nfp_data.amiiboNFCData.amiiboIdentificationBlock.amiiboFigureType; // guessed
memset(romInfo->unused, 0x00, sizeof(romInfo->unused));
}
nnResult GetNfpRomInfo(RomInfo* romInfo)
{
nnNfpLock();
if (nfp_data.hasActiveAmiibo == false)
{
nnNfpUnlock();
return BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0); // todo: Return correct error code
}
GetRomInfo(romInfo);
nnNfpUnlock();
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0);
}
nnResult GetNfpReadOnlyInfo(ReadOnlyInfo* readOnlyInfo)
{
nnNfpLock();
if (nfp_data.hasActiveAmiibo == false)
{
nnNfpUnlock();
return BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0); // todo: Return correct error code
}
GetRomInfo(readOnlyInfo);
nnNfpUnlock();
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0);
}
};
typedef struct
{
uint16be year;
uint8 month;
uint8 day;
}nfpDate_t;
typedef struct
{
/* +0x00 */ nfpDate_t date;
/* +0x04 */ uint8 writeCount[2];
/* +0x06 */ uint8 characterId[3];
/* +0x09 */ uint8 amiiboSeries;
/* +0x0A */ uint16be number;
/* +0x0C */ uint8 nfpType;
/* +0x0D */ uint8 nfpVersion;
/* +0x0E */ uint16be applicationAreaSize;
/* +0x10 */ uint8 unused[0x30];
}nfpCommonData_t;
static_assert(sizeof(nfpCommonData_t) == 0x40, "nfpCommonData_t has invalid size");
static_assert(offsetof(nfpCommonData_t, writeCount) == 0x4, "nfpCommonData.writeCount has invalid offset");
static_assert(offsetof(nfpCommonData_t, amiiboSeries) == 0x9, "nfpCommonData.seriesId has invalid offset");
static_assert(offsetof(nfpCommonData_t, nfpType) == 0xC, "nfpCommonData.nfpType has invalid offset");
static_assert(offsetof(nfpCommonData_t, applicationAreaSize) == 0xE, "nfpCommonData.applicationAreaSize has invalid offset");
void nnNfpExport_GetNfpCommonInfo(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "GetNfpCommonInfo(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamStructPtr(commonInfo, nfpCommonData_t, 0);
nnNfpLock();
if (nfp_data.hasActiveAmiibo == false)
{
nnNfpUnlock();
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0)); // todo: Return correct error code
return;
}
// tag info format is currently unknown, so we just set it to all zeros for now
if (sizeof(nfpCommonData_t) != 0x40 )
assert_dbg();
memset(commonInfo, 0x00, sizeof(nfpCommonData_t));
cemuLog_logDebug(LogType::Force, "GetNfpCommonInfo(0x{:08x})");
commonInfo->writeCount[0] = nfp_data.amiiboNFCData.writeCounter[0];
commonInfo->writeCount[1] = nfp_data.amiiboNFCData.writeCounter[1];
commonInfo->characterId[0] = nfp_data.amiiboNFCData.amiiboIdentificationBlock.gameAndCharacterId[0];
commonInfo->characterId[1] = nfp_data.amiiboNFCData.amiiboIdentificationBlock.gameAndCharacterId[1];
commonInfo->characterId[2] = nfp_data.amiiboNFCData.amiiboIdentificationBlock.characterVariation;
commonInfo->number = *(uint16be*)nfp_data.amiiboNFCData.amiiboIdentificationBlock.amiiboModelNumber;
commonInfo->amiiboSeries = nfp_data.amiiboNFCData.amiiboIdentificationBlock.amiiboSeries;
commonInfo->nfpType = nfp_data.amiiboNFCData.amiiboIdentificationBlock.amiiboFigureType; // guessed
commonInfo->applicationAreaSize = sizeof(nfp_data.amiiboInternal.applicationData); // not 100% sure if this is always set to the maximum
nnNfpUnlock();
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
typedef struct
{
/* +0x00 */ uint8 ownerMii[0x60];
/* +0x60 */ uint8 nickname[0x14];
/* +0x74 */ uint16be ukn74;
/* +0x76 */ uint8 ukn76;
/* +0x77 */ uint8 _padding77;
/* +0x78 */ nfpDate_t registerDate;
/* +0x7C */ uint8 ukn7C[0x2C];
}nfpRegisterInfo_t;
typedef struct
{
/* +0x00 */ uint8 ownerMii[0x60];
/* +0x60 */ uint8 nickname[0x14];
// maybe has more fields?
}nfpRegisterInfoSet_t;
void nnNfpExport_GetNfpRegisterInfo(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "GetNfpRegisterInfo(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamStructPtr(registerInfo, nfpRegisterInfo_t, 0);
if(!registerInfo)
{
osLib_returnFromFunction(hCPU, 0xC1B03780);
return;
}
memset(registerInfo, 0, sizeof(nfpRegisterInfo_t));
if ((nfp_data.amiiboInternal.amiiboSettings.flags & 0x10) != 0)
{
memcpy(registerInfo->ownerMii, nfp_data.amiiboInternal.amiiboSettings.mii, sizeof(nfp_data.amiiboInternal.amiiboSettings.mii));
memcpy(registerInfo->nickname, nfp_data.amiiboInternal.amiiboSettings.nickname, sizeof(nfp_data.amiiboInternal.amiiboSettings.nickname));
}
// todo - missing fields
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
void nnNfpExport_InitializeRegisterInfoSet(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "InitializeRegisterInfoSet(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamStructPtr(registerInfoSet, nfpRegisterInfoSet_t, 0);
memset(registerInfoSet, 0, sizeof(nfpRegisterInfoSet_t));
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
void nnNfpExport_SetNfpRegisterInfo(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "SetNfpRegisterInfo(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamStructPtr(registerInfoSet, nfpRegisterInfoSet_t, 0);
memcpy(nfp_data.amiiboInternal.amiiboSettings.mii, registerInfoSet->ownerMii, sizeof(nfp_data.amiiboInternal.amiiboSettings.mii));
memcpy(nfp_data.amiiboInternal.amiiboSettings.nickname, registerInfoSet->nickname, sizeof(nfp_data.amiiboInternal.amiiboSettings.nickname));
// todo - set register date and other values
nfp_data.amiiboInternal.amiiboSettings.flags |= 0x10; // set registered bit
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
void nnNfpExport_IsExistApplicationArea(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "IsExistApplicationArea()");
if (!nfp_data.hasActiveAmiibo || !nfp_data.isMounted)
{
osLib_returnFromFunction(hCPU, 0);
return;
}
bool appAreaExists = (nfp_data.amiiboInternal.amiiboSettings.flags & 0x20) != 0;
osLib_returnFromFunction(hCPU, appAreaExists ? 1 : 0);
}
void nnNfpExport_OpenApplicationArea(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "OpenApplicationArea(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamU32(appAreaId, 0);
// note - this API doesn't fail if the application area has already been opened?
if (!(nfp_data.amiiboInternal.amiiboSettings.flags & 0x20))
{
// no application data set
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, NN_RESULT_NFP_CODE_NOAPPAREA));
return;
}
uint32 nfpAppAreaId = nfp_data.amiiboInternal.amiiboSettings.getAppDataAppId();
if (nfpAppAreaId != appAreaId)
{
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, NN_RESULT_NFP_CODE_APPAREAIDMISMATCH));
return;
}
nfp_data.hasOpenApplicationArea = true;
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
void nnNfpExport_ReadApplicationArea(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "ReadApplicationArea(0x{:08x}, 0x{:x})", hCPU->gpr[3], hCPU->gpr[4]);
ppcDefineParamPtr(bufferPtr, uint8*, 0);
ppcDefineParamU32(len, 1);
if (!nfp_data.hasOpenApplicationArea)
{
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0));
return;
}
len = std::min(len, (uint32)sizeof(nfp_data.amiiboInternal.applicationData));
memcpy(bufferPtr, nfp_data.amiiboInternal.applicationData, len);
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
void nnNfpExport_WriteApplicationArea(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "WriteApplicationArea(0x{:08x}, 0x{:x}, 0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
ppcDefineParamPtr(bufferPtr, uint8*, 0);
ppcDefineParamU32(len, 1);
if (!nfp_data.hasOpenApplicationArea)
{
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0));
return;
}
if (nfp_data.isReadOnly)
{
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0));
return;
}
len = std::min(len, (uint32)sizeof(nfp_data.amiiboInternal.applicationData));
memcpy(nfp_data.amiiboInternal.applicationData, bufferPtr, len);
// remaining data is filled with random bytes
for (uint32 i = len; i < sizeof(nfp_data.amiiboInternal.applicationData); i++)
nfp_data.amiiboInternal.applicationData[i] = rand() & 0xFF;
nfp_data.amiiboInternal.amiiboSettings.appWriteCounter = nfp_data.amiiboInternal.amiiboSettings.appWriteCounter + 1;
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
typedef struct
{
uint32be appAreaId;
MEMPTR<uint8> initialData;
uint32be initialLen;
// more?
}NfpCreateInfo_t;
void nnNfpExport_CreateApplicationArea(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "CreateApplicationArea(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamPtr(createInfo, NfpCreateInfo_t, 0);
if (nfp_data.hasOpenApplicationArea || (nfp_data.amiiboInternal.amiiboSettings.flags&0x20))
{
// cant create app area if it already exists
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0));
return;
}
if (nfp_data.isReadOnly)
{
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0));
return;
}
void* writePtr = createInfo->initialData.GetPtr();
uint32 writeSize = createInfo->initialLen;
if (writeSize > sizeof(nfp_data.amiiboInternal.applicationData))
{
// requested write size larger than available space
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0));
return;
}
nfp_data.amiiboInternal.amiiboSettings.setAppDataAppId(createInfo->appAreaId);
nfp_data.amiiboInternal.amiiboSettings.flags |= 0x20; // set application data exists bit
nfp_data.amiiboInternal.amiiboSettings.appWriteCounter = nfp_data.amiiboInternal.amiiboSettings.appWriteCounter + 1;
nfp_data.hasOpenApplicationArea = false;
// write initial data to application area
memcpy(nfp_data.amiiboInternal.applicationData, writePtr, writeSize);
// remaining data is filled with random bytes
for (uint32 i = writeSize; i < sizeof(nfp_data.amiiboInternal.applicationData); i++)
nfp_data.amiiboInternal.applicationData[i] = rand() & 0xFF;
// this API forces a flush (unsure, but without this data written by Smash doesn't stick)
if (!nnNfp_writeCurrentAmiibo())
{
cemuLog_log(LogType::Force, "Failed to write Amiibo file data when trying to remove appArea");
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0));
return;
}
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
void nnNfpExport_DeleteApplicationArea(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "DeleteApplicationArea()");
if (nfp_data.isReadOnly)
{
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0));
return;
}
if ((nfp_data.amiiboInternal.amiiboSettings.flags & 0x20) == 0)
{
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0));
return;
}
nfp_data.amiiboInternal.amiiboSettings.setAppDataAppId(0);
nfp_data.amiiboInternal.amiiboSettings.flags &= ~0x20;
nfp_data.amiiboInternal.amiiboSettings.appWriteCounter = nfp_data.amiiboInternal.amiiboSettings.appWriteCounter + 1;
// this API forces a flush
if (!nnNfp_writeCurrentAmiibo())
{
cemuLog_log(LogType::Force, "Failed to write Amiibo file data when trying to remove appArea");
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0));
return;
}
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
void nnNfpExport_Flush(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "Flush()");
// write Amiibo data
if (nfp_data.isReadOnly)
{
cemuLog_log(LogType::Force, "Cannot write to Amiibo when it is mounted in read-only mode");
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0));
return;
}
if (!nnNfp_writeCurrentAmiibo())
{
cemuLog_log(LogType::Force, "Failed to write Amiibo data");
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NFP, 0));
return;
}
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
typedef struct
{
/* +0x000 */ uint8 ukn00[0x10];
/* +0x010 */ uint32be mode;
/* +0x014 */ uint8 tagInfo[0x54];
/* +0x068 */ uint8 isRegistered; // could be uint32be?
/* +0x069 */ uint8 _padding69[3];
/* +0x06C */ uint8 registerInfo[0xA8];
/* +0x114 */ uint8 commonInfo[0x40];
/* +0x154 */ uint8 ukn154[0x20];
}AmiiboSettingsArgs_t;
static_assert(sizeof(AmiiboSettingsArgs_t) == 0x174);
static_assert(offsetof(AmiiboSettingsArgs_t, mode) == 0x10);
static_assert(offsetof(AmiiboSettingsArgs_t, tagInfo) == 0x14);
static_assert(offsetof(AmiiboSettingsArgs_t, isRegistered) == 0x68);
static_assert(offsetof(AmiiboSettingsArgs_t, registerInfo) == 0x6C);
static_assert(offsetof(AmiiboSettingsArgs_t, commonInfo) == 0x114);
void nnNfpExport_GetAmiiboSettingsArgs(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "GetAmiiboSettingsArgs(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamStructPtr(settingsArg, AmiiboSettingsArgs_t, 0);
memset(settingsArg, 0, sizeof(AmiiboSettingsArgs_t));
// modes:
// 0 -> Register owner and nickname
// 0x64 -> Launch normally
settingsArg->mode = 0x64;
osLib_returnFromFunction(hCPU, BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NFP, 0));
}
void nnNfp_unloadAmiibo()
{
nnNfpLock();
nfp_data.isMounted = false;
nfp_data.hasActiveAmiibo = false;
nnNfpUnlock();
}
bool nnNfp_isInitialized()
{
return nfp_data.nfpIsInitialized;
}
// CEMU NFC error codes
#define NFC_ERROR_NONE (0)
#define NFC_ERROR_NO_ACCESS (1)
#define NFC_ERROR_INVALID_FILE_FORMAT (2)
bool nnNfp_touchNfcTagFromFile(const fs::path& filePath, uint32* nfcError)
{
AmiiboRawNFCData rawData = { 0 };
auto nfcData = FileStream::LoadIntoMemory(filePath);
if (!nfcData)
{
*nfcError = NFC_ERROR_NO_ACCESS;
return false;
}
if (nfcData->size() < sizeof(AmiiboRawNFCData))
{
*nfcError = NFC_ERROR_INVALID_FILE_FORMAT;
return false;
}
memcpy(&rawData, nfcData->data(), sizeof(AmiiboRawNFCData));
// verify if the file is a valid ntag215/amiibo file
if (rawData.dynamicLock[0] != 0x01 || rawData.dynamicLock[1] != 0x00 || rawData.dynamicLock[2] != 0x0F || rawData.dynamicLock[3] != 0xBD)
{
// Temporary workaround to fix corrupted files by old cemu versions
rawData.dynamicLock[0] = 0x01;
rawData.dynamicLock[1] = 0x00;
rawData.dynamicLock[2] = 0x0F;
rawData.dynamicLock[3] = 0xBD;
// *nfcError = NFC_ERROR_INVALID_FILE_FORMAT;
// return false;
}
if (rawData.cfg0[0] != 0x00 || rawData.cfg0[1] != 0x00 || rawData.cfg0[2] != 0x00 || rawData.cfg0[3] != 0x04)
{
*nfcError = NFC_ERROR_INVALID_FILE_FORMAT;
return false;
}
if (rawData.cfg1[0] != 0x5F || rawData.cfg1[1] != 0x00 || rawData.cfg1[2] != 0x00 || rawData.cfg1[3] != 0x00)
{
*nfcError = NFC_ERROR_INVALID_FILE_FORMAT;
return false;
}
if (rawData.staticLock[0] != 0x0F || rawData.staticLock[1] != 0xE0)
{
*nfcError = NFC_ERROR_INVALID_FILE_FORMAT;
return false;
}
if (rawData.cc[0] != 0xF1 || rawData.cc[1] != 0x10 || rawData.cc[2] != 0xFF || rawData.cc[3] != 0xEE)
{
*nfcError = NFC_ERROR_INVALID_FILE_FORMAT;
return false;
}
// process uid
uint8 serialNumber[7];
serialNumber[0] = rawData.ntagSerial[0];
serialNumber[1] = rawData.ntagSerial[1];
serialNumber[2] = rawData.ntagSerial[2];
serialNumber[3] = rawData.ntagSerial[4];
serialNumber[4] = rawData.ntagSerial[5];
serialNumber[5] = rawData.ntagSerial[6];
serialNumber[6] = rawData.nintendoId;
uint8 serialCheckByte0 = rawData.ntagSerial[3];
uint8 serialCheckByte1 = rawData.lockBytes[0];
uint8 bcc0 = serialNumber[0] ^ serialNumber[1] ^ serialNumber[2] ^ 0x88;
uint8 bcc1 = serialNumber[3] ^ serialNumber[4] ^ serialNumber[5] ^ serialNumber[6];
if (serialCheckByte0 != bcc0 || serialCheckByte1 != bcc1)
{
cemuLog_log(LogType::Force, "nn_nfp: Mismatch in serial checksum of scanned NFC tag");
}
nfp_data.amiiboProcessedData.uidLength = 7;
memcpy(nfp_data.amiiboProcessedData.uid, serialNumber, 7);
// signal activation event
nnNfp_unloadAmiibo();
nnNfpLock();
memcpy(&nfp_data.amiiboNFCData, &rawData, sizeof(AmiiboRawNFCData));
// decrypt amiibo
amiiboDecrypt();
nfp_data.amiiboPath = filePath;
nfp_data.hasActiveAmiibo = true;
if (nfp_data.activateEvent)
{
MEMPTR<coreinit::OSEvent> osEvent(nfp_data.activateEvent);
coreinit::OSSignalEvent(osEvent);
}
nfp_data.amiiboTouchTime = GetTickCount();
nnNfpUnlock();
*nfcError = NFC_ERROR_NO_ACCESS;
return true;
}
bool nnNfp_writeCurrentAmiibo()
{
nnNfpLock();
if (!nfp_data.hasActiveAmiibo)
{
nnNfpUnlock();
return false;
}
uint16 writeCounter = nfp_data.amiiboInternal.writeCounterLow + (nfp_data.amiiboInternal.writeCounterHigh << 8);
writeCounter++;
nfp_data.amiiboInternal.writeCounterLow = writeCounter & 0xFF;
nfp_data.amiiboInternal.writeCounterHigh = (writeCounter >> 8) & 0xFF;
// open file for writing
FileStream* fs = FileStream::openFile2(nfp_data.amiiboPath, true);
if (!fs)
{
nnNfpUnlock();
return false;
}
// encrypt Amiibo and convert to NFC format
AmiiboRawNFCData nfcData;
amiiboEncrypt(&nfcData);
// write to file
fs->writeData(&nfcData, sizeof(AmiiboRawNFCData));
delete fs;
nnNfpUnlock();
return true;
}
void nnNfp_update()
{
// lock-free check if amiibo is touching
if (nfp_data.hasActiveAmiibo == false)
return;
if (!nnNfpTryLock())
return;
// make sure amiibo is still touching after acquiring lock
if (nfp_data.hasActiveAmiibo == false)
return;
uint32 amiiboElapsedTouchTime = GetTickCount() - nfp_data.amiiboTouchTime;
if (amiiboElapsedTouchTime >= 1500)
{
nnNfp_unloadAmiibo();
if (nfp_data.deactivateEvent)
{
coreinit::OSEvent* osEvent = (coreinit::OSEvent*)memory_getPointerFromVirtualOffset(nfp_data.deactivateEvent);
coreinit::OSSignalEvent(osEvent);
}
}
nnNfpUnlock();
}
void nnNfpExport_GetNfpState(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::NN_NFP, "GetNfpState()");
// workaround for Mario Party 10 eating CPU cycles in an infinite loop (maybe due to incorrect NFP detection handling?)
uint64 titleId = CafeSystem::GetForegroundTitleId();
if (titleId == 0x0005000010162d00 || titleId == 0x0005000010162e00)
{
coreinit::OSSleepTicks(ESPRESSO_CORE_CLOCK / 100); // pause for 10ms
}
uint32 nfpState;
if (nfp_data.nfpIsInitialized == false)
{
nfpState = NFP_STATE_NONE;
}
else
{
if (nfp_data.isMounted && nfp_data.hasActiveAmiibo)
{
if (nfp_data.isReadOnly)
nfpState = NFP_STATE_RW_MOUNT_ROM;
else
nfpState = NFP_STATE_RW_MOUNT;
}
else if (nfp_data.isDetecting)
{
// todo: is this handled correctly?
if (nfp_data.hasActiveAmiibo)
{
nfpState = NFP_STATE_RW_ACTIVE;
}
else
nfpState = NFP_STATE_RW_SEARCH;
}
else
{
nfpState = NFP_STATE_INIT;
}
}
// returns state of nfp library
osLib_returnFromFunction(hCPU, nfpState);
}
namespace nn::nfp
{
typedef struct
{
/* +0x00 */ uint8 uidLength;
/* +0x01 */ uint8 uid[0xA];
/* +0x0B */ uint8 ukn0B;
/* +0x0C */ uint8 ukn0C;
/* +0x0D */ uint8 ukn0D;
// more?
}NFCTagInfoCallbackParam_t;
uint32 NFCGetTagInfo(uint32 index, uint32 timeout, MPTR functionPtr, void* userParam)
{
cemuLog_log(LogType::NN_NFP, "NFCGetTagInfo({},{},0x{:08x},0x{:08x})", index, timeout, functionPtr, userParam ? memory_getVirtualOffsetFromPointer(userParam) : 0);
cemu_assert(index == 0);
nnNfpLock();
StackAllocator<NFCTagInfoCallbackParam_t> _callbackParam;
NFCTagInfoCallbackParam_t* callbackParam = _callbackParam.GetPointer();
memset(callbackParam, 0x00, sizeof(NFCTagInfoCallbackParam_t));
memcpy(callbackParam->uid, nfp_data.amiiboProcessedData.uid, nfp_data.amiiboProcessedData.uidLength);
callbackParam->uidLength = (uint8)nfp_data.amiiboProcessedData.uidLength;
PPCCoreCallback(functionPtr, index, 0, _callbackParam.GetPointer(), userParam);
nnNfpUnlock();
return 0; // 0 -> success
}
uint32 GetErrorCode(uint32 result)
{
uint32 level = (result >> 0x1b) & 3;
uint32 mask = 0x7f00000;
if (level != 3)
{
mask = 0x1ff00000;
}
if (((result & mask) == 0x1b00000) && ((result & 0x80000000) != 0))
{
mask = 0x3ff;
if (level != 3)
{
mask = 0xfffff;
}
return ((result & mask) >> 7) + 1680000;
}
return 1680000;
}
void nnNfp_load()
{
osLib_addFunction("nn_nfp", "SetActivateEvent__Q2_2nn3nfpFP7OSEvent", nnNfpExport_SetActivateEvent);
osLib_addFunction("nn_nfp", "SetDeactivateEvent__Q2_2nn3nfpFP7OSEvent", nnNfpExport_SetDeactivateEvent);
osLib_addFunction("nn_nfp", "StartDetection__Q2_2nn3nfpFv", nnNfpExport_StartDetection);
osLib_addFunction("nn_nfp", "StopDetection__Q2_2nn3nfpFv", nnNfpExport_StopDetection);
osLib_addFunction("nn_nfp", "GetTagInfo__Q2_2nn3nfpFPQ3_2nn3nfp7TagInfo", nnNfpExport_GetTagInfo);
osLib_addFunction("nn_nfp", "Mount__Q2_2nn3nfpFv", nnNfpExport_Mount);
osLib_addFunction("nn_nfp", "MountRom__Q2_2nn3nfpFv", nnNfpExport_MountRom);
osLib_addFunction("nn_nfp", "Unmount__Q2_2nn3nfpFv", nnNfpExport_Unmount);
osLib_addFunction("nn_nfp", "GetNfpCommonInfo__Q2_2nn3nfpFPQ3_2nn3nfp10CommonInfo", nnNfpExport_GetNfpCommonInfo);
osLib_addFunction("nn_nfp", "GetNfpRegisterInfo__Q2_2nn3nfpFPQ3_2nn3nfp12RegisterInfo", nnNfpExport_GetNfpRegisterInfo);
osLib_addFunction("nn_nfp", "InitializeRegisterInfoSet__Q2_2nn3nfpFPQ3_2nn3nfp15RegisterInfoSet", nnNfpExport_InitializeRegisterInfoSet);
osLib_addFunction("nn_nfp", "SetNfpRegisterInfo__Q2_2nn3nfpFRCQ3_2nn3nfp15RegisterInfoSet", nnNfpExport_SetNfpRegisterInfo);
osLib_addFunction("nn_nfp", "IsExistApplicationArea__Q2_2nn3nfpFv", nnNfpExport_IsExistApplicationArea);
osLib_addFunction("nn_nfp", "OpenApplicationArea__Q2_2nn3nfpFUi", nnNfpExport_OpenApplicationArea);
osLib_addFunction("nn_nfp", "CreateApplicationArea__Q2_2nn3nfpFRCQ3_2nn3nfp25ApplicationAreaCreateInfo", nnNfpExport_CreateApplicationArea);
osLib_addFunction("nn_nfp", "DeleteApplicationArea__Q2_2nn3nfpFv", nnNfpExport_DeleteApplicationArea);
osLib_addFunction("nn_nfp", "ReadApplicationArea__Q2_2nn3nfpFPvUi", nnNfpExport_ReadApplicationArea);
osLib_addFunction("nn_nfp", "WriteApplicationArea__Q2_2nn3nfpFPCvUiRCQ3_2nn3nfp5TagId", nnNfpExport_WriteApplicationArea);
osLib_addFunction("nn_nfp", "Flush__Q2_2nn3nfpFv", nnNfpExport_Flush);
osLib_addFunction("nn_nfp", "Initialize__Q2_2nn3nfpFv", nnNfpExport_Initialize);
osLib_addFunction("nn_nfp", "GetNfpState__Q2_2nn3nfpFv", nnNfpExport_GetNfpState);
osLib_addFunction("nn_nfp", "GetAmiiboSettingsArgs__Q2_2nn3nfpFPQ3_2nn3nfp18AmiiboSettingsArgs", nnNfpExport_GetAmiiboSettingsArgs);
}
void load()
{
nnNfp_load(); // legacy interface, update these to use cafeExportRegister / cafeExportRegisterFunc
cafeExportRegisterFunc(nn::nfp::GetErrorCode, "nn_nfp", "GetErrorCode__Q2_2nn3nfpFRCQ2_2nn6Result", LogType::NN_NFP);
cafeExportRegisterFunc(nn::nfp::GetNfpRomInfo, "nn_nfp", "GetNfpRomInfo__Q2_2nn3nfpFPQ3_2nn3nfp7RomInfo", LogType::NN_NFP);
cafeExportRegisterFunc(nn::nfp::GetNfpReadOnlyInfo, "nn_nfp", "GetNfpReadOnlyInfo__Q2_2nn3nfpFPQ3_2nn3nfp12ReadOnlyInfo", LogType::NN_NFP);
}
}
| 34,219
|
C++
|
.cpp
| 905
| 35.426519
| 165
| 0.751726
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,144
|
nn_temp.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_temp/nn_temp.cpp
|
#include "Cafe/OS/common/OSCommon.h"
namespace nn::temp
{
uint64 tempIdGenerator = 0xdc1b04bd961f2c04ULL;
void nnTempExport_TEMPCreateAndInitTempDir(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "TEMPCreateAndInitTempDir(...) - placeholder");
// create random temp id
memory_writeU64(hCPU->gpr[5], tempIdGenerator);
tempIdGenerator = (tempIdGenerator << 3) | (tempIdGenerator >> 61);
tempIdGenerator += 0x56e28bd5f4ULL;
osLib_returnFromFunction(hCPU, 0);
}
void Initialize()
{
osLib_addFunction("nn_temp", "TEMPCreateAndInitTempDir", nnTempExport_TEMPCreateAndInitTempDir);
}
};
| 619
|
C++
|
.cpp
| 18
| 31.888889
| 98
| 0.778151
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,145
|
nn_sl.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_sl/nn_sl.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_IOS.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM.h"
#include "config/ActiveSettings.h"
#include "Cafe/CafeSystem.h"
namespace nn
{
typedef uint32 Result;
namespace sl
{
struct VTableEntry
{
uint16be offsetA{0};
uint16be offsetB{0};
MEMPTR<void> ptr;
};
static_assert(sizeof(VTableEntry) == 8);
constexpr uint32 SL_MEM_MAGIC = 0xCAFE4321;
#define DTOR_WRAPPER(__TYPE) RPLLoader_MakePPCCallable([](PPCInterpreter_t* hCPU) { dtor(MEMPTR<__TYPE>(hCPU->gpr[3]), hCPU->gpr[4]); osLib_returnFromFunction(hCPU, 0); })
template<typename T>
MEMPTR<T> sl_new()
{
uint32 objSize = sizeof(T);
uint32be* basePtr = (uint32be*)coreinit::_weak_MEMAllocFromDefaultHeapEx(objSize + 8, 0x8);
basePtr[0] = SL_MEM_MAGIC;
basePtr[1] = objSize;
return (T*)(basePtr + 2);
}
void sl_delete(MEMPTR<void> mem)
{
if (!mem)
return;
uint32be* basePtr = (uint32be*)mem.GetPtr() - 2;
if (basePtr[0] != SL_MEM_MAGIC)
{
cemuLog_log(LogType::Force, "nn_sl: Detected memory corruption");
cemu_assert_suspicious();
}
coreinit::_weak_MEMFreeToDefaultHeap(basePtr);
}
#pragma pack(1)
struct WhiteList
{
uint32be titleTypes[50];
uint32be titleTypesCount;
uint32be padding;
uint64be titleIds[50];
uint32be titleIdCount;
};
static_assert(sizeof(WhiteList) == 0x264);
#pragma pack()
struct WhiteListAccessor
{
MEMPTR<void> vTablePtr{}; // 0x00
struct VTable
{
VTableEntry rtti;
VTableEntry dtor;
VTableEntry get;
};
static inline SysAllocator<VTable> s_titleVTable;
static WhiteListAccessor* ctor(WhiteListAccessor* _this)
{
if (!_this)
_this = sl_new<WhiteListAccessor>();
*_this = {};
_this->vTablePtr = s_titleVTable;
return _this;
}
static void dtor(WhiteListAccessor* _this, uint32 options)
{
if (_this && (options & 1))
sl_delete(_this);
}
static void Get(WhiteListAccessor* _this, nn::sl::WhiteList* outWhiteList)
{
*outWhiteList = {};
}
static void InitVTable()
{
s_titleVTable->rtti.ptr = nullptr; // todo
s_titleVTable->dtor.ptr = DTOR_WRAPPER(WhiteListAccessor);
s_titleVTable->get.ptr = RPLLoader_MakePPCCallable([](PPCInterpreter_t* hCPU) { Get(MEMPTR<WhiteListAccessor>(hCPU->gpr[3]), MEMPTR<WhiteList>(hCPU->gpr[4])); osLib_returnFromFunction(hCPU, 0); });
}
};
static_assert(sizeof(WhiteListAccessor) == 0x04);
SysAllocator<WhiteListAccessor> s_defaultWhiteListAccessor;
WhiteListAccessor* GetDefaultWhiteListAccessor()
{
return s_defaultWhiteListAccessor;
}
} // namespace sl
} // namespace nn
void nnSL_load()
{
nn::sl::WhiteListAccessor::InitVTable();
nn::sl::WhiteListAccessor::ctor(nn::sl::s_defaultWhiteListAccessor);
cafeExportRegisterFunc(nn::sl::GetDefaultWhiteListAccessor, "nn_sl", "GetDefaultWhiteListAccessor__Q2_2nn2slFv", LogType::NN_SL);
}
| 2,963
|
C++
|
.cpp
| 99
| 26.363636
| 201
| 0.708011
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,146
|
nsyskbd.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nsyskbd/nsyskbd.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/nn_common.h"
namespace nsyskbd
{
bool IsValidChannel(uint32 channel)
{
return channel >= 0 && channel < 4;
}
uint32 KBDGetChannelStatus(uint32 channel, uint32be* status)
{
static bool loggedError = false;
if (loggedError == false)
{
cemuLog_logDebug(LogType::Force, "KBDGetChannelStatus() placeholder");
loggedError = true;
}
*status = 1; // disconnected
return 0;
}
#pragma pack(push, 1)
struct KeyState
{
uint8be channel;
uint8be ukn1;
uint8be _padding[2];
uint32be ukn4;
uint32be ukn8;
uint16be uknC;
};
#pragma pack(pop)
static_assert(sizeof(KeyState) == 0xE); // actual size might be padded to 0x10?
uint32 KBDGetKey(uint32 channel, KeyState* keyState)
{
// used by MSX VC
if(!IsValidChannel(channel) || !keyState)
{
cemuLog_log(LogType::APIErrors, "KBDGetKey(): Invalid parameter");
return 0;
}
keyState->channel = channel;
keyState->ukn1 = 0;
keyState->ukn4 = 0;
keyState->ukn8 = 0;
keyState->uknC = 0;
return 0;
}
void nsyskbd_load()
{
cafeExportRegister("nsyskbd", KBDGetChannelStatus, LogType::Placeholder);
cafeExportRegister("nsyskbd", KBDGetKey, LogType::Placeholder);
}
}
| 1,230
|
C++
|
.cpp
| 52
| 21.038462
| 80
| 0.722696
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,147
|
padscore.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/padscore/padscore.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "gui/wxgui.h"
#include "Cafe/OS/libs/padscore/padscore.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "Cafe/OS/libs/coreinit/coreinit_Alarm.h"
#include "Cafe/OS/libs/coreinit/coreinit_SystemInfo.h"
#include "input/InputManager.h"
// KPAD
enum class KPAD_ERROR : sint32
{
NONE = 0,
NO_SAMPLE_DATA = -1,
NO_CONTROLLER = -2,
NOT_INITIALIZED = -5,
};
// WPAD (Wii Controller stuff)
enum WPADRumble
{
kStopRumble = 0,
kStartRumble = 1,
};
enum class WPADBatteryLevel : uint8
{
FULL = 4,
};
enum class WPADLed : uint8
{
CHAN0 = (1 << 0),
CHAN1 = (1 << 1),
CHAN2 = (1 << 2),
CHAN3 = (1 << 3),
};
namespace padscore
{
enum WPADState_t
{
kWPADStateMaster = 0,
kWPADStateShutdown,
kWPADStateInitializing,
kWPADStateAcquired,
kWPADStateReleased,
};
KPADUnifiedWpadStatus_t* g_kpad_ringbuffer = nullptr;
uint32 g_kpad_ringbuffer_length = 0;
bool g_wpad_callback_by_kpad = false;
WPADState_t g_wpad_state = kWPADStateMaster;
struct {
SysAllocator<coreinit::OSAlarm_t> alarm;
bool kpad_initialized = false;
struct WPADData
{
MEMPTR<void> extension_callback;
MEMPTR<void> connectCallback;
MEMPTR<void> sampling_callback;
MEMPTR<void> dpd_callback;
bool dpd_enabled = true;
bool disconnectCalled = false;
BtnRepeat btn_repeat{};
} controller_data[InputManager::kMaxWPADControllers] = {};
int max_controllers = kWPADMaxControllers; // max bt controllers?
} g_padscore;
}
#pragma region WPAD
void padscoreExport_WPADGetStatus(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::InputAPI, "WPADGetStatus()");
uint32 status = 1;
osLib_returnFromFunction(hCPU, status);
}
void padscoreExport_WPADGetBatteryLevel(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::InputAPI, "WPADGetBatteryLevel()");
osLib_returnFromFunction(hCPU, (uint32)WPADBatteryLevel::FULL);
}
void padscoreExport_WPADProbe(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamPtr(type, uint32be, 1);
cemuLog_log(LogType::InputAPI, "WPADProbe({})", channel);
if(const auto controller = InputManager::instance().get_wpad_controller(channel))
{
if(type)
*type = controller->get_device_type();
osLib_returnFromFunction(hCPU, WPAD_ERR_NONE);
}
else
{
if(type)
*type = 253;
osLib_returnFromFunction(hCPU, WPAD_ERR_NO_CONTROLLER);
}
}
typedef struct
{
uint32be dpd;
uint32be speaker;
uint32be attach;
uint32be lowBat;
uint32be nearempty;
betype<WPADBatteryLevel> batteryLevel;
betype<WPADLed> led;
uint8 protocol;
uint8 firmware;
}WPADInfo_t;
static_assert(sizeof(WPADInfo_t) == 0x18); // unsure
void padscoreExport_WPADGetInfoAsync(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamStructPtr(wpadInfo, WPADInfo_t, 1);
ppcDefineParamMPTR(callbackFunc, 2);
cemuLog_log(LogType::InputAPI, "WPADGetInfoAsync({}, 0x{:08x}, 0x{:08x})", channel, fmt::ptr(wpadInfo), callbackFunc);
if (channel < InputManager::kMaxWPADControllers)
{
if (const auto controller = InputManager::instance().get_wpad_controller(channel))
{
wpadInfo->dpd = FALSE;
wpadInfo->speaker = FALSE;
wpadInfo->attach = FALSE;
wpadInfo->lowBat = FALSE;
wpadInfo->nearempty = FALSE;
wpadInfo->batteryLevel = WPADBatteryLevel::FULL;
wpadInfo->led = WPADLed::CHAN0;
if(callbackFunc != MPTR_NULL)
coreinitAsyncCallback_add(callbackFunc, 2, channel, (uint32)KPAD_ERROR::NONE);
osLib_returnFromFunction(hCPU, WPAD_ERR_NONE);
return;
}
}
else
{
debugBreakpoint();
}
if (callbackFunc != MPTR_NULL)
coreinitAsyncCallback_add(callbackFunc, 2, channel, (uint32)KPAD_ERROR::NO_CONTROLLER);
osLib_returnFromFunction(hCPU, WPAD_ERR_NO_CONTROLLER);
}
void padscoreExport_WPADRead(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamPtr(wpadStatus, WPADStatus_t, 1);
cemuLog_log(LogType::InputAPI, "WPADRead({}, {:x})", channel, fmt::ptr(wpadStatus));
if (channel < InputManager::kMaxWPADControllers)
{
if(const auto controller = InputManager::instance().get_wpad_controller(channel) )
{
controller->WPADRead(wpadStatus);
}
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, WPAD_ERR_NO_CONTROLLER);
}
void padscoreExport_WPADSetDataFormat(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamU32(fmt, 1);
cemuLog_log(LogType::InputAPI, "WPADSetDataFormat({}, {})", channel, fmt);
if (channel < InputManager::kMaxWPADControllers)
{
if (const auto controller = InputManager::instance().get_wpad_controller(channel))
controller->set_data_format((WPADDataFormat)fmt);
}
osLib_returnFromFunction(hCPU, 0);
}
void padscoreExport_WPADGetDataFormat(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
cemuLog_log(LogType::InputAPI, "WPADGetDataFormat({})", channel);
sint32 dataFormat = kDataFormat_CORE;
if (channel < InputManager::kMaxWPADControllers)
{
if (const auto controller = InputManager::instance().get_wpad_controller(channel))
dataFormat = controller->get_data_format();
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, dataFormat);
}
void padscoreExport_WPADGetInfo(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamStructPtr(wpadInfo, WPADInfo_t, 1);
cemuLog_log(LogType::InputAPI, "WPADGetInfo({}, 0x{:08x})", channel, fmt::ptr(wpadInfo));
if (channel < InputManager::kMaxWPADControllers)
{
if (const auto controller = InputManager::instance().get_wpad_controller(channel))
{
wpadInfo->dpd = FALSE;
wpadInfo->speaker = FALSE;
wpadInfo->attach = FALSE;
wpadInfo->lowBat = FALSE;
wpadInfo->nearempty = FALSE;
wpadInfo->batteryLevel = WPADBatteryLevel::FULL;
wpadInfo->led = WPADLed::CHAN0;
osLib_returnFromFunction(hCPU, WPAD_ERR_NONE);
return;
}
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, WPAD_ERR_NO_CONTROLLER);
}
void padscoreExport_WPADIsMotorEnabled(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::InputAPI, "WPADIsMotorEnabled()");
osLib_returnFromFunction(hCPU, TRUE);
}
void padscoreExport_WPADControlMotor(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamU32(command, 1);
cemuLog_log(LogType::InputAPI, "WPADControlMotor({}, {})", channel, command);
if (channel < InputManager::kMaxWPADControllers)
{
if (const auto controller = InputManager::instance().get_wpad_controller(channel))
{
if( command == kStartRumble )
controller->start_rumble();
else
controller->stop_rumble();
}
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
#pragma endregion
#pragma region KPAD
void padscoreExport_KPADGetUnifiedWpadStatus(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamPtr(status, KPADUnifiedWpadStatus_t, 1);
ppcDefineParamU32(count, 2);
cemuLog_log(LogType::InputAPI, "KPADGetUnifiedWpadStatus({}, 0x{:08x}, 0x{:x})", channel, MEMPTR<void>(status).GetMPTR(), count);
if (channel < InputManager::kMaxWPADControllers)
{
memset(status, 0x00, sizeof(KPADUnifiedWpadStatus_t) * count);
if (const auto controller = InputManager::instance().get_wpad_controller(channel))
{
switch (controller->get_data_format())
{
case WPAD_FMT_CORE:
case WPAD_FMT_CORE_ACC:
case WPAD_FMT_CORE_ACC_DPD:
{
status->fmt = controller->get_data_format();
controller->WPADRead(&status->u.core);
break;
}
default:
debugBreakpoint();
}
}
else
{
status->u.core.err = WPAD_ERR_NO_CONTROLLER;
}
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void padscoreExport_KPADSetBtnRepeat(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
float delaySec = hCPU->fpr[1].fpr;
float pulseSec = hCPU->fpr[2].fpr;
cemuLog_log(LogType::InputAPI, "KPADSetBtnRepeat({}, {}, {})", channel, delaySec, pulseSec);
if (channel < InputManager::kMaxWPADControllers)
{
padscore::g_padscore.controller_data[channel].btn_repeat = { (int)delaySec, (int)pulseSec };
}
osLib_returnFromFunction(hCPU, 0);
}
void padscoreExport_KPADSetSamplingCallback(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamMPTR(callback, 1);
cemuLog_log(LogType::InputAPI, "KPADSetSamplingCallback({}, 0x{:x})", channel, callback);
if (channel >= InputManager::kMaxWPADControllers)
{
debugBreakpoint();
osLib_returnFromFunction(hCPU, MPTR_NULL);
return;
}
const auto old_callback = padscore::g_padscore.controller_data[channel].sampling_callback;
padscore::g_padscore.controller_data[channel].sampling_callback = callback;
osLib_returnFromFunction(hCPU, old_callback.GetMPTR());
}
void padscoreExport_WPADControlDpd(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamU32(command, 1);
ppcDefineParamMPTR(callback, 2);
cemuLog_log(LogType::InputAPI, "WPADControlDpd({}, {}, 0x{:x})", channel, command, callback);
if (channel < InputManager::kMaxWPADControllers)
{
if (const auto controller = InputManager::instance().get_wpad_controller(channel))
{
padscore::g_padscore.controller_data[channel].dpd_callback = callback;
if (callback)
{
coreinitAsyncCallback_add(callback, 2, channel, WPAD_ERR_NONE);
}
osLib_returnFromFunction(hCPU, WPAD_ERR_NONE);
return;
}
}
osLib_returnFromFunction(hCPU, WPAD_ERR_NO_CONTROLLER);
}
void padscoreExport_WPADSetExtensionCallback(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamMPTR(callback, 1);
cemuLog_log(LogType::InputAPI, "WPADSetExtensionCallback({}, 0x{:x})", channel, callback);
if (channel >= InputManager::kMaxWPADControllers)
{
debugBreakpoint();
osLib_returnFromFunction(hCPU, MPTR_NULL);
return;
}
const auto old_callback = padscore::g_padscore.controller_data[channel].extension_callback;
padscore::g_padscore.controller_data[channel].extension_callback = callback;
osLib_returnFromFunction(hCPU, old_callback.GetMPTR());
}
void padscoreExport_KPADSetConnectCallback(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamMPTR(callback, 1);
cemuLog_log(LogType::InputAPI, "KPADSetConnectCallback({}, 0x{:x})",channel, callback);
if (channel >= InputManager::kMaxWPADControllers)
{
debugBreakpoint();
osLib_returnFromFunction(hCPU, MPTR_NULL);
return;
}
const auto old_callback = padscore::g_padscore.controller_data[channel].connectCallback;
padscore::g_padscore.controller_data[channel].connectCallback = callback;
osLib_returnFromFunction(hCPU, old_callback.GetMPTR());
}
uint64 g_kpadLastRead[InputManager::kMaxWPADControllers] = {0};
bool g_kpadIsInited = true;
sint32 _KPADRead(uint32 channel, KPADStatus_t* samplingBufs, uint32 length, betype<KPAD_ERROR>* errResult)
{
if (channel >= InputManager::kMaxWPADControllers)
{
debugBreakpoint();
return 0;
}
if (g_kpadIsInited == false)
{
if (errResult)
*errResult = KPAD_ERROR::NOT_INITIALIZED;
return 0;
}
const auto controller = InputManager::instance().get_wpad_controller(channel);
if (!controller)
{
if (errResult)
*errResult = KPAD_ERROR::NO_CONTROLLER;
return 0;
}
// On console new input samples are only received every few ms and calling KPADRead(Ex) clears the internal queue regardless of length value
// thus calling KPADRead(Ex) again too soon on the same channel will result in no data being returned
// Games that depend on this: Affordable Space Adventures
uint64 currentTime = coreinit::OSGetTime();
uint64 timeDif = currentTime - g_kpadLastRead[channel];
if(length == 0 || timeDif < coreinit::EspressoTime::ConvertNsToTimerTicks(1000000))
{
if (errResult)
*errResult = KPAD_ERROR::NO_SAMPLE_DATA;
return 0;
}
g_kpadLastRead[channel] = currentTime;
memset(samplingBufs, 0x00, sizeof(KPADStatus_t));
samplingBufs->wpadErr = WPAD_ERR_NONE;
samplingBufs->data_format = controller->get_data_format();
samplingBufs->devType = controller->get_device_type();
if(!g_inputConfigWindowHasFocus)
{
const auto btn_repeat = padscore::g_padscore.controller_data[channel].btn_repeat;
controller->KPADRead(*samplingBufs, btn_repeat);
}
if (errResult)
*errResult = KPAD_ERROR::NONE;
return 1;
}
void padscoreExport_KPADReadEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamPtr(kpadStatus, KPADStatus_t, 1);
ppcDefineParamU32(length, 2);
ppcDefineParamPtr(errResult, betype<KPAD_ERROR>, 3);
cemuLog_log(LogType::InputAPI, "KPADReadEx({}, 0x{:x})", channel, length);
sint32 samplesRead = _KPADRead(channel, kpadStatus, length, errResult);
osLib_returnFromFunction(hCPU, samplesRead);
}
void padscoreExport_KPADRead(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamPtr(kpadStatus, KPADStatus_t, 1);
ppcDefineParamU32(length, 2);
cemuLog_log(LogType::InputAPI, "KPADRead({}, 0x{:x})", channel, length);
sint32 samplesRead = _KPADRead(channel, kpadStatus, length, nullptr);
osLib_returnFromFunction(hCPU, samplesRead);
}
#pragma endregion
namespace padscore
{
void export_KPADEnableDPD(PPCInterpreter_t* hCPU)
{
ppcDefineParamS32(channel, 0);
cemuLog_log(LogType::InputAPI, "KPADEnableDPD({})", channel);
cemu_assert_debug(0 <= channel && channel < InputManager::kMaxWPADControllers);
if(const auto controller = InputManager::instance().get_wpad_controller(channel))
{
if (controller->get_data_format() != kDataFormat_FREESTYLE && controller->get_data_format() != 0x1F)
g_padscore.controller_data[channel].dpd_enabled = true;
}
osLib_returnFromFunction(hCPU, 0);
}
void export_KPADGetMplsWorkSize(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::InputAPI, "KPADGetMplsWorkSize()");
osLib_returnFromFunction(hCPU, 0x5FE0);
}
void KPADInitEx(KPADUnifiedWpadStatus_t ring_buffer[], uint32 length)
{
if (g_padscore.kpad_initialized)
return;
for (uint32 i = 0; i < InputManager::kMaxWPADControllers; i++)
{
g_padscore.controller_data[i].dpd_enabled = true;
}
g_kpad_ringbuffer = ring_buffer;
g_kpad_ringbuffer_length = length;
g_padscore.kpad_initialized = true;
}
void export_KPADInit(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::InputAPI, "KPADInit()");
KPADInitEx(nullptr, 0);
osLib_returnFromFunction(hCPU, 0);
}
void export_KPADInitEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(ring_buffer, KPADUnifiedWpadStatus_t, 0);
ppcDefineParamU32(length, 1);
cemuLog_log(LogType::InputAPI, "KPADInitEx(0x{:08x}, 0x{:x})", ring_buffer.GetMPTR(), length);
KPADInitEx(ring_buffer.GetPtr(), length);
osLib_returnFromFunction(hCPU, 0);
}
void WPADSetCallbackByKPAD(bool state)
{
g_wpad_callback_by_kpad = state;
}
void export_WPADSetCallbackByKPAD(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(state, 0);
cemuLog_log(LogType::InputAPI, "WPADSetCallbackByKPAD({})", state);
WPADSetCallbackByKPAD(state);
osLib_returnFromFunction(hCPU, 0);
}
void export_KPADGetMaxControllers(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::InputAPI, "KPADGetMaxControllers()");
sint32 max_controllers = g_padscore.max_controllers;
osLib_returnFromFunction(hCPU, max_controllers);
}
bool WPADIsUsedCallbackByKPAD()
{
return g_wpad_callback_by_kpad == TRUE;
}
void* WPADSetSamplingCallback(sint32 channel, void* callback)
{
cemu_assert_debug(0 <= channel && channel < kKPADMaxControllers);
const auto result = g_padscore.controller_data[channel].sampling_callback;
g_padscore.controller_data[channel].sampling_callback = callback;
return result.GetPtr();
}
void export_KPADSetMaxControllers(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(new_max_count, 0);
cemuLog_log(LogType::InputAPI, "KPADSetMaxControllers({})", new_max_count);
if (new_max_count != kKPADMaxControllers && new_max_count != kWPADMaxControllers)
{
debugBreakpoint();
osLib_returnFromFunction(hCPU, -4);
return;
}
const uint32 max_controllers = g_padscore.max_controllers;
if (max_controllers == new_max_count)
{
osLib_returnFromFunction(hCPU, 0);
return;
}
WPADSetCallbackByKPAD(FALSE);
for (sint32 i = 0; i < kKPADMaxControllers; i++)
{
//WPADSetSamplingCallback(i, 0); TODO
}
g_padscore.max_controllers = new_max_count;
WPADSetCallbackByKPAD(true);
osLib_returnFromFunction(hCPU, new_max_count);
}
void export_WPADInit()
{
if (g_wpad_state != kWPADStateShutdown)
{
if (g_wpad_state == kWPADStateInitializing || g_wpad_state == kWPADStateAcquired)
return;
}
g_wpad_state = kWPADStateInitializing;
}
enum class WPADStatus : sint32
{
Success = 0,
NoController = -1,
Busy = -2,
};
WPADStatus WPADIsMplsAttached(sint32 index, uint32be* attached, void* callback)
{
if (index >= kKPADMaxControllers)
return WPADStatus::NoController;
const auto controller = InputManager::instance().get_wpad_controller(index);
*attached = controller && controller->is_mpls_attached();
if (callback)
PPCCoreCallback(MEMPTR(callback), index, controller ? WPADStatus::Success : WPADStatus::NoController);
return WPADStatus::Success;
}
struct WPADAcc
{
sint32be x;
sint32be y;
sint32be z;
};
void WPADGetAccGravityUnit(sint32 index, uint32 type, WPADAcc* acc)
{
if (index >= kKPADMaxControllers)
return;
// default values for wiimote usually are around 99
acc->x = 99;
acc->y = 99;
acc->z = 99;
}
#pragma endregion
void TickFunction(PPCInterpreter_t* hCPU)
{
auto& instance = InputManager::instance();
// test for connected/disconnected controllers
for (auto i = 0; i < InputManager::kMaxWPADControllers; ++i)
{
if (g_padscore.controller_data[i].connectCallback)
{
if(!g_padscore.controller_data[i].disconnectCalled)
{
g_padscore.controller_data[i].disconnectCalled = true;
cemuLog_log(LogType::InputAPI, "Calling WPADConnectCallback({}, {})", i, WPAD_ERR_NO_CONTROLLER);
PPCCoreCallback(g_padscore.controller_data[i].connectCallback, i, WPAD_ERR_NO_CONTROLLER);
continue;
}
if (const auto controller = instance.get_wpad_controller(i))
{
if (controller->m_status == WPADController::ConnectCallbackStatus::ReportDisconnect || controller->was_home_button_down()) // fixed!
{
controller->m_status = WPADController::ConnectCallbackStatus::ReportConnect;
cemuLog_log(LogType::InputAPI, "Calling WPADConnectCallback({}, {})", i, WPAD_ERR_NO_CONTROLLER);
PPCCoreCallback(g_padscore.controller_data[i].connectCallback, i, WPAD_ERR_NO_CONTROLLER);
}
else if (controller->m_status == WPADController::ConnectCallbackStatus::ReportConnect)
{
controller->m_status = WPADController::ConnectCallbackStatus::None;
cemuLog_log(LogType::InputAPI, "Calling WPADConnectCallback({}, {})", i, WPAD_ERR_NONE);
PPCCoreCallback(g_padscore.controller_data[i].connectCallback, i, WPAD_ERR_NONE);
}
}
}
}
// test for connected/disconnected extensions
for (auto i = 0; i < InputManager::kMaxWPADControllers; ++i)
{
if (g_padscore.controller_data[i].extension_callback)
{
if (const auto controller = instance.get_wpad_controller(i))
{
if (controller->m_extension_status == WPADController::ConnectCallbackStatus::ReportConnect)
{
controller->m_extension_status = WPADController::ConnectCallbackStatus::None;
cemuLog_log(LogType::InputAPI, "Calling WPADextensionCallback({})", i);
PPCCoreCallback(g_padscore.controller_data[i].extension_callback, i, controller->get_device_type());
}
}
}
}
// call sampling callback
for (auto i = 0; i < InputManager::kMaxWPADControllers; ++i)
{
if (g_padscore.controller_data[i].sampling_callback)
{
if (const auto controller = instance.get_wpad_controller(i))
{
cemuLog_log(LogType::InputAPI, "Calling WPADsamplingCallback({})", i);
PPCCoreCallback(g_padscore.controller_data[i].sampling_callback, i);
}
}
}
osLib_returnFromFunction(hCPU, 0);
}
void start()
{
OSCreateAlarm(&g_padscore.alarm);
const uint64 start_tick = coreinit::coreinit_getOSTime();
const uint64 period_tick = coreinit::EspressoTime::GetTimerClock() / 200; // every 5ms
MPTR handler = PPCInterpreter_makeCallableExportDepr(TickFunction);
OSSetPeriodicAlarm(&g_padscore.alarm, start_tick, period_tick, handler);
}
void load()
{
cafeExportRegister("padscore", WPADIsMplsAttached, LogType::InputAPI);
cafeExportRegister("padscore", WPADGetAccGravityUnit, LogType::InputAPI);
// wpad
//osLib_addFunction("padscore", "WPADInit", padscore::export_WPADInit);
// kpad
osLib_addFunction("padscore", "KPADSetMaxControllers", padscore::export_KPADSetMaxControllers);
osLib_addFunction("padscore", "KPADGetMaxControllers", padscore::export_KPADGetMaxControllers);
osLib_addFunction("padscore", "KPADEnableDPD", padscore::export_KPADEnableDPD);
osLib_addFunction("padscore", "KPADGetMplsWorkSize", padscore::export_KPADGetMplsWorkSize);
osLib_addFunction("padscore", "KPADInit", padscore::export_KPADInit);
osLib_addFunction("padscore", "KPADInitEx", padscore::export_KPADInitEx);
osLib_addFunction("padscore", "KPADSetConnectCallback", padscoreExport_KPADSetConnectCallback);
osLib_addFunction("padscore", "KPADReadEx", padscoreExport_KPADReadEx);
osLib_addFunction("padscore", "KPADRead", padscoreExport_KPADRead);
osLib_addFunction("padscore", "KPADGetUnifiedWpadStatus", padscoreExport_KPADGetUnifiedWpadStatus);
osLib_addFunction("padscore", "KPADSetSamplingCallback", padscoreExport_KPADSetSamplingCallback);
osLib_addFunction("padscore", "KPADSetBtnRepeat", padscoreExport_KPADSetBtnRepeat);
osLib_addFunction("padscore", "WPADGetBatteryLevel", padscoreExport_WPADGetBatteryLevel);
osLib_addFunction("padscore", "WPADControlMotor", padscoreExport_WPADControlMotor);
osLib_addFunction("padscore", "WPADIsMotorEnabled", padscoreExport_WPADIsMotorEnabled);
osLib_addFunction("padscore", "WPADGetStatus", padscoreExport_WPADGetStatus);
osLib_addFunction("padscore", "WPADProbe", padscoreExport_WPADProbe);
osLib_addFunction("padscore", "WPADGetInfoAsync", padscoreExport_WPADGetInfoAsync);
osLib_addFunction("padscore", "WPADGetInfo", padscoreExport_WPADGetInfo);
osLib_addFunction("padscore", "WPADSetConnectCallback", padscoreExport_KPADSetConnectCallback);
osLib_addFunction("padscore", "WPADSetDataFormat", padscoreExport_WPADSetDataFormat);
osLib_addFunction("padscore", "WPADGetDataFormat", padscoreExport_WPADGetDataFormat);
osLib_addFunction("padscore", "WPADRead", padscoreExport_WPADRead);
osLib_addFunction("padscore", "WPADSetExtensionCallback", padscoreExport_WPADSetExtensionCallback);
osLib_addFunction("padscore", "WPADSetSamplingCallback", padscoreExport_KPADSetSamplingCallback);
osLib_addFunction("padscore", "WPADControlDpd", padscoreExport_WPADControlDpd);
osLib_addFunction("padscore", "WPADSetCallbackByKPAD", padscore::export_WPADSetCallbackByKPAD);
}
}
| 22,936
|
C++
|
.cpp
| 663
| 31.723982
| 141
| 0.758479
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,148
|
nn_idbe.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_idbe/nn_idbe.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/nn_acp/nn_acp.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/OS/libs/nn_common.h"
#include "util/crypto/aes128.h"
#include "openssl/sha.h"
#include "Cemu/napi/napi.h"
namespace nn
{
namespace idbe
{
struct nnIdbeIconDataV0_t
{
// raw icon data as byte array
// check NAPI::IDBEIconDataV0 for exact data layout
uint8 rawData[0x12060];
uint8* GetTGAData()
{
return rawData + 0x2030;
}
};
static_assert(sizeof(nnIdbeIconDataV0_t) == 0x12060, "");
struct nnIdbeHeader_t
{
uint8 formatVersion;
uint8 keyIndex;
};
struct nnIdbeEncryptedIcon_t
{
nnIdbeHeader_t header;
uint8 hashSHA256[32];
nnIdbeIconDataV0_t iconData;
};
static_assert(offsetof(nnIdbeEncryptedIcon_t, hashSHA256) == 2, "");
static_assert(offsetof(nnIdbeEncryptedIcon_t, iconData) == 0x22, "");
static_assert(sizeof(nnIdbeEncryptedIcon_t) == 0x12082);
void asyncDownloadIconFile(uint64 titleId, nnIdbeEncryptedIcon_t* iconOut, coreinit::OSEvent* event)
{
std::vector<uint8> idbeData = NAPI::IDBE_RequestRawEncrypted(ActiveSettings::GetNetworkService(), titleId);
if (idbeData.size() != sizeof(nnIdbeEncryptedIcon_t))
{
// icon does not exist or has the wrong size
cemuLog_log(LogType::Force, "IDBE: Failed to retrieve icon for title {:016x}", titleId);
memset(iconOut, 0, sizeof(nnIdbeEncryptedIcon_t));
coreinit::OSSignalEvent(event);
return;
}
memcpy(iconOut, idbeData.data(), sizeof(nnIdbeEncryptedIcon_t));
coreinit::OSSignalEvent(event);
}
void export_DownloadIconFile(PPCInterpreter_t* hCPU)
{
ppcDefineParamTypePtr(encryptedIconData, nnIdbeEncryptedIcon_t, 0);
ppcDefineParamU64(titleId, 2);
ppcDefineParamU32(uknR7, 4);
ppcDefineParamU32(uknR8, 5);
StackAllocator<coreinit::OSEvent> event;
coreinit::OSInitEvent(&event, coreinit::OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, coreinit::OSEvent::EVENT_MODE::MODE_AUTO);
auto asyncTask = std::async(std::launch::async, asyncDownloadIconFile, titleId, encryptedIconData, &event);
coreinit::OSWaitEvent(&event);
osLib_returnFromFunction(hCPU, 1);
}
static_assert(sizeof(nnIdbeHeader_t) == 0x2, "");
static uint8 idbeAesKeys[4 * 16] =
{
0x4A,0xB9,0xA4,0x0E,0x14,0x69,0x75,0xA8,0x4B,0xB1,0xB4,0xF3,0xEC,0xEF,0xC4,0x7B,
0x90,0xA0,0xBB,0x1E,0x0E,0x86,0x4A,0xE8,0x7D,0x13,0xA6,0xA0,0x3D,0x28,0xC9,0xB8,
0xFF,0xBB,0x57,0xC1,0x4E,0x98,0xEC,0x69,0x75,0xB3,0x84,0xFC,0xF4,0x07,0x86,0xB5,
0x80,0x92,0x37,0x99,0xB4,0x1F,0x36,0xA6,0xA7,0x5F,0xB8,0xB4,0x8C,0x95,0xF6,0x6F
};
static uint8 idbeAesIv[16] =
{
0xA4,0x69,0x87,0xAE,0x47,0xD8,0x2B,0xB4,0xFA,0x8A,0xBC,0x04,0x50,0x28,0x5F,0xA4
};
bool decryptIcon(nnIdbeEncryptedIcon_t* iconInput, nnIdbeIconDataV0_t* iconOutput)
{
// check header
nnIdbeHeader_t* idbeHeader = (nnIdbeHeader_t*)iconInput;
if (idbeHeader->formatVersion != 0)
{
cemuLog_log(LogType::Force, "idbe header version unknown ({})", (sint32)idbeHeader->formatVersion);
return false;
}
if (idbeHeader->keyIndex >= 4)
{
cemuLog_log(LogType::Force, "idbe header key count invalid ({})", (sint32)idbeHeader->keyIndex);
return false;
}
// decrypt data
uint8 iv[16];
memcpy(iv, idbeAesIv, sizeof(iv));
uint8 decryptedSHA256[SHA256_DIGEST_LENGTH];
AES128_CBC_decrypt_updateIV(decryptedSHA256, iconInput->hashSHA256, sizeof(decryptedSHA256), idbeAesKeys + 16 * idbeHeader->keyIndex, iv);
AES128_CBC_decrypt((uint8*)iconOutput, (uint8*)&iconInput->iconData, sizeof(iconInput->iconData), idbeAesKeys + 16 * idbeHeader->keyIndex, iv);
// calculate and compare sha256
uint8 calculatedSHA256[SHA256_DIGEST_LENGTH];
SHA256((const unsigned char*)iconOutput, sizeof(nnIdbeIconDataV0_t), calculatedSHA256);
if (memcmp(calculatedSHA256, decryptedSHA256, SHA256_DIGEST_LENGTH) != 0)
{
cemuLog_logDebug(LogType::Force, "Idbe icon has incorrect sha256 hash");
return false;
}
return true;
}
struct TGAHeader
{
/* +0x00 */ uint8 idLength;
/* +0x01 */ uint8 colorMap;
/* +0x02 */ uint8 imageType;
/* +0x03 */ uint8 colorMap_firstIndex_low;
/* +0x04 */ uint8 colorMap_firstIndex_high;
/* +0x05 */ uint8 colorMap_len_low;
/* +0x06 */ uint8 colorMap_len_high;
/* +0x07 */ uint8 colorMap_bpp;
/* +0x08 */ uint16 image_xOrigin;
/* +0x0A */ uint16 image_yOrigin;
/* +0x0C */ uint16 image_width;
/* +0x0E */ uint16 image_height;
/* +0x10 */ uint8 image_bpp;
/* +0x11 */ uint8 image_desc;
};
static_assert(offsetof(TGAHeader, colorMap_firstIndex_low) == 0x03);
static_assert(sizeof(TGAHeader) == 0x12);
void export_DecryptIconFile(PPCInterpreter_t* hCPU)
{
ppcDefineParamTypePtr(output, nnIdbeIconDataV0_t, 0);
ppcDefineParamTypePtr(input, nnIdbeEncryptedIcon_t, 1);
ppcDefineParamU32(platformMode, 2);
cemuLog_logDebug(LogType::Force, "nn_idbe.DecryptIconFile(...)");
if (decryptIcon(input, output))
{
osLib_returnFromFunction(hCPU, 1);
return;
}
cemuLog_logDebug(LogType::Force, "Unable to decrypt idbe icon file, using default icon");
// return default icon
TGAHeader* tgaHeader = (TGAHeader*)(output->GetTGAData());
memset(tgaHeader, 0, sizeof(TGAHeader));
tgaHeader->imageType = 2;
tgaHeader->image_width = 256;
tgaHeader->image_height = 256;
tgaHeader->image_bpp = 32;
tgaHeader->image_desc = (1 << 3);
osLib_returnFromFunction(hCPU, 1);
}
void load()
{
// this module is used by:
// Daily Log app
// Download Manager app
// and possibly other system titles?
osLib_addFunction("nn_idbe", "DownloadIconFile__Q2_2nn4idbeFPvULUsb", export_DownloadIconFile);
osLib_addFunction("nn_idbe", "DecryptIconFile__Q2_2nn4idbeFPvPCv", export_DecryptIconFile);
}
}
}
| 5,852
|
C++
|
.cpp
| 156
| 33.762821
| 146
| 0.721664
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,149
|
nn_boss.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_boss/nn_boss.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/nn_common.h"
#include "Cafe/OS/libs/nn_act/nn_act.h"
#include "Cafe/OS/libs/coreinit/coreinit_IOS.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM.h"
#include "Cafe/IOSU/legacy/iosu_boss.h"
#include "Cafe/IOSU/legacy/iosu_act.h"
#include "config/ActiveSettings.h"
#include "Cafe/CafeSystem.h"
#include "Cafe/Filesystem/fsc.h"
namespace nn
{
typedef uint32 Result;
namespace boss
{
#define bossPrepareRequest() \
StackAllocator<iosuBossCemuRequest_t> _buf_bossRequest; \
StackAllocator<ioBufferVector_t> _buf_bufferVector; \
iosuBossCemuRequest_t* bossRequest = _buf_bossRequest.GetPointer(); \
ioBufferVector_t* bossBufferVector = _buf_bufferVector.GetPointer(); \
memset(bossRequest, 0, sizeof(iosuBossCemuRequest_t)); \
memset(bossBufferVector, 0, sizeof(ioBufferVector_t)); \
bossBufferVector->buffer = (uint8*)bossRequest;
SysAllocator<coreinit::OSMutex> g_mutex;
sint32 g_initCounter = 0;
bool g_isInitialized = false;
struct VTableEntry
{
uint16be offsetA{0};
uint16be offsetB{0};
MEMPTR<void> ptr;
};
static_assert(sizeof(VTableEntry) == 8);
#define DTOR_WRAPPER(__TYPE) RPLLoader_MakePPCCallable([](PPCInterpreter_t* hCPU) { dtor(MEMPTR<__TYPE>(hCPU->gpr[3]), hCPU->gpr[4]); osLib_returnFromFunction(hCPU, 0); })
constexpr uint32 BOSS_MEM_MAGIC = 0xCAFE4321;
template<typename T>
MEMPTR<T> boss_new()
{
uint32 objSize = sizeof(T);
uint32be* basePtr = (uint32be*)coreinit::_weak_MEMAllocFromDefaultHeapEx(objSize + 8, 0x8);
basePtr[0] = BOSS_MEM_MAGIC;
basePtr[1] = objSize;
return (T*)(basePtr+2);
}
void boss_delete(MEMPTR<void> mem)
{
if(!mem)
return;
uint32be* basePtr = (uint32be*)mem.GetPtr() - 2;
if(basePtr[0] != BOSS_MEM_MAGIC)
{
cemuLog_log(LogType::Force, "nn_boss: Detected memory corruption");
cemu_assert_suspicious();
}
coreinit::_weak_MEMFreeToDefaultHeap(basePtr);
}
Result Initialize() // Initialize__Q2_2nn4bossFv
{
coreinit::OSLockMutex(&g_mutex);
Result result = 0;
if(g_initCounter == 0)
{
g_isInitialized = true;
// IPC init here etc.
result = 0x200080; // init result
}
g_initCounter++;
coreinit::OSUnlockMutex(&g_mutex);
return NN_RESULT_IS_SUCCESS(result) ? 0 : result;
}
uint32 IsInitialized() // IsInitialized__Q2_2nn4bossFv
{
return g_isInitialized;
}
void Finalize() // Finalize__Q2_2nn4bossFv
{
coreinit::OSLockMutex(&g_mutex);
if(g_initCounter == 0)
cemuLog_log(LogType::Force, "nn_boss: Finalize() called without corresponding Initialize()");
if(g_initCounter == 1)
{
g_isInitialized = false;
// IPC deinit here etc.
}
g_initCounter--;
coreinit::OSUnlockMutex(&g_mutex);
}
uint32 GetBossState(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_boss.GetBossState() - stub");
return 7;
}
struct TitleId
{
uint64be u64{};
static TitleId* ctor(TitleId* _thisptr, uint64 titleId)
{
if (!_thisptr)
_thisptr = boss_new<TitleId>();
_thisptr->u64 = titleId;
return _thisptr;
}
static TitleId* ctor(TitleId* _thisptr)
{
return ctor(_thisptr, 0);
}
static bool IsValid(TitleId* _thisptr)
{
return _thisptr->u64 != 0;
}
static TitleId* ctor1(TitleId* _thisptr, uint32 filler, uint64 titleId)
{
return ctor(_thisptr);
}
static TitleId* ctor2(TitleId* _thisptr, uint32 filler, uint64 titleId)
{
cemuLog_logDebug(LogType::Force, "nn_boss_TitleId_ctor2(0x{:x})", MEMPTR(_thisptr).GetMPTR());
if (!_thisptr)
{
// _thisptr = new Task_t
assert_dbg();
}
_thisptr->u64 = titleId;
return _thisptr;
}
static TitleId* ctor3(TitleId* _thisptr, TitleId* titleId)
{
cemuLog_logDebug(LogType::Force, "nn_boss_TitleId_cctor(0x{:x})", MEMPTR(_thisptr).GetMPTR());
if (!_thisptr)
_thisptr = boss_new<TitleId>();
_thisptr->u64 = titleId->u64;
return _thisptr;
}
static bool operator_ne(TitleId* _thisptr, TitleId* titleId)
{
cemuLog_logDebug(LogType::Force, "nn_boss_TitleId_operator_ne(0x{:x})", MEMPTR(_thisptr).GetMPTR());
return _thisptr->u64 != titleId->u64;
}
};
static_assert(sizeof(TitleId) == 8);
struct TaskId
{
char id[0x8]{};
static TaskId* ctor(TaskId* _thisptr)
{
if(!_thisptr)
_thisptr = boss_new<TaskId>();
_thisptr->id[0] = '\0';
return _thisptr;
}
};
static_assert(sizeof(TaskId) == 8);
struct Title
{
uint32be accountId{}; // 0x00
TitleId titleId{}; // 0x8
MEMPTR<void> vTablePtr{}; // 0x10
struct VTable
{
VTableEntry rtti;
VTableEntry dtor;
};
static inline SysAllocator<VTable> s_titleVTable;
static Title* ctor(Title* _this)
{
if (!_this)
_this = boss_new<Title>();
*_this = {};
_this->vTablePtr = s_titleVTable;
return _this;
}
static void dtor(Title* _this, uint32 options)
{
if (_this && (options & 1))
boss_delete(_this);
}
static void InitVTable()
{
s_titleVTable->rtti.ptr = nullptr; // todo
s_titleVTable->dtor.ptr = DTOR_WRAPPER(Title);
}
};
static_assert(sizeof(Title) == 0x18);
struct DirectoryName
{
char name[0x8]{};
static DirectoryName* ctor(DirectoryName* _thisptr)
{
if (!_thisptr)
_thisptr = boss_new<DirectoryName>();
memset(_thisptr->name, 0x00, 0x8);
return _thisptr;
}
static const char* operator_const_char(DirectoryName* _thisptr)
{
return _thisptr->name;
}
};
static_assert(sizeof(DirectoryName) == 8);
struct BossAccount // the actual class name is "Account" and while the boss namespace helps us separate this from Account(.h) we use an alternative name to avoid confusion
{
struct VTable
{
VTableEntry rtti;
VTableEntry dtor;
};
static inline SysAllocator<VTable> s_VTable;
uint32be accountId;
MEMPTR<void> vTablePtr;
static BossAccount* ctor(BossAccount* _this, uint32 accountId)
{
if (!_this)
_this = boss_new<BossAccount>();
_this->accountId = accountId;
_this->vTablePtr = s_VTable;
return _this;
}
static void dtor(BossAccount* _this, uint32 options)
{
if(_this && options & 1)
boss_delete(_this);
}
static void InitVTable()
{
s_VTable->rtti.ptr = nullptr; // todo
s_VTable->dtor.ptr = DTOR_WRAPPER(BossAccount);
}
};
static_assert(sizeof(BossAccount) == 8);
struct TaskSetting
{
static const uint32 kBossCode = 0x7C0;
static const uint32 kBossCodeLen = 0x20;
static const uint32 kDirectorySizeLimit = 0x7F0;
static const uint32 kDirectoryName = 0x7E0;
static const uint32 kDirectoryNameLen = 0x8;
//static const uint32 kFileName = 0x7F8;
static const uint32 kNbdlFileName = 0x7F8;
static const uint32 kFileNameLen = 0x20;
static const uint32 kURL = 0x48;
static const uint32 kURLLen = 0x100;
static const uint32 kClientCert = 0x41;
static const uint32 kCACert = 0x188;
static const uint32 kServiceToken = 0x590;
static const uint32 kServiceTokenLen = 0x200;
uint8 settings[0x1000];
MEMPTR<void> vTablePtr; // +0x1000
struct VTableTaskSetting
{
VTableEntry rtti;
VTableEntry dtor;
VTableEntry RegisterPreprocess;
VTableEntry unk1;
};
static inline SysAllocator<VTableTaskSetting> s_VTable;
static TaskSetting* ctor(TaskSetting* _thisptr)
{
if(!_thisptr)
_thisptr = boss_new<TaskSetting>();
_thisptr->vTablePtr = s_VTable;
InitializeSetting(_thisptr);
return _thisptr;
}
static void dtor(TaskSetting* _this, uint32 options)
{
cemuLog_logDebug(LogType::Force, "nn::boss::TaskSetting::dtor(0x{:08x}, 0x{:08x})", MEMPTR(_this).GetMPTR(), options);
if(options & 1)
boss_delete(_this);
}
static bool IsPrivileged(TaskSetting* _thisptr)
{
const uint16 value = *(uint16be*)&_thisptr->settings[0x28];
return value == 1 || value == 9 || value == 5;
}
static void InitializeSetting(TaskSetting* _thisptr)
{
memset(_thisptr, 0x00, sizeof(TaskSetting::settings));
*(uint32*)&_thisptr->settings[0x0C] = 0;
*(uint8*)&_thisptr->settings[0x2A] = 0x7D; // timeout?
*(uint32*)&_thisptr->settings[0x30] = 0x7080;
*(uint32*)&_thisptr->settings[0x8] = 0;
*(uint32*)&_thisptr->settings[0x38] = 0;
*(uint32*)&_thisptr->settings[0x3C] = 0x76A700;
*(uint32*)&_thisptr->settings[0] = 0x76A700;
}
static void InitVTable()
{
s_VTable->rtti.ptr = nullptr; // todo
s_VTable->dtor.ptr = DTOR_WRAPPER(TaskSetting);
s_VTable->RegisterPreprocess.ptr = nullptr; // todo
s_VTable->unk1.ptr = nullptr; // todo
}
};
static_assert(sizeof(TaskSetting) == 0x1004);
static_assert(offsetof(TaskSetting, vTablePtr) == 0x1000);
struct NetTaskSetting : TaskSetting
{
// 0x188 cert1 + 0x188 cert2 + 0x188 cert3
// 0x190 AddCaCert (3times) char cert[0x80];
// SetConnectionSetting
// SetFirstLastModifiedTime
struct VTableNetTaskSetting : public VTableTaskSetting
{ };
static inline SysAllocator<VTableNetTaskSetting> s_VTable;
static Result AddCaCert(NetTaskSetting* _thisptr, const char* name)
{
if(name == nullptr || strnlen(name, 0x80) == 0x80)
{
cemuLog_logDebug(LogType::Force, "nn_boss_NetTaskSetting_AddCaCert: name size is invalid");
return 0xC0203780;
}
cemu_assert_unimplemented();
return 0xA0220D00;
}
static NetTaskSetting* ctor(NetTaskSetting* _thisptr)
{
if (!_thisptr)
_thisptr = boss_new<NetTaskSetting>();
TaskSetting::ctor(_thisptr);
*(uint32*)&_thisptr->settings[0x18C] = 0x78;
_thisptr->vTablePtr = s_VTable;
return _thisptr;
}
static Result SetServiceToken(NetTaskSetting* _thisptr, const uint8* serviceToken)
{
cemuLog_logDebug(LogType::Force, "nn_boss_NetTaskSetting_SetServiceToken(0x{:x}, 0x{:x})", MEMPTR(_thisptr).GetMPTR(), MEMPTR(serviceToken).GetMPTR());
cemuLog_logDebug(LogType::Force, "\t->{}", fmt::ptr(serviceToken));
memcpy(&_thisptr->settings[TaskSetting::kServiceToken], serviceToken, TaskSetting::kServiceTokenLen);
return 0x200080;
}
static Result AddInternalCaCert(NetTaskSetting* _thisptr, char certId)
{
cemuLog_logDebug(LogType::Force, "nn_boss_NetTaskSetting_AddInternalCaCert(0x{:x}, 0x{:x})", MEMPTR(_thisptr).GetMPTR(), (int)certId);
uint32 location = TaskSetting::kCACert;
for(int i = 0; i < 3; ++i)
{
if(_thisptr->settings[location] == 0)
{
_thisptr->settings[location] = (uint8)certId;
return 0x200080;
}
location += TaskSetting::kCACert;
}
cemuLog_logDebug(LogType::Force, "nn_boss_NetTaskSetting_AddInternalCaCert: can't store certificate");
return 0xA0220D00;
}
static void SetInternalClientCert(NetTaskSetting* _thisptr, char certId)
{
cemuLog_logDebug(LogType::Force, "nn_boss_NetTaskSetting_SetInternalClientCert(0x{:x}, 0x{:x})", MEMPTR(_thisptr).GetMPTR(), (int)certId);
_thisptr->settings[TaskSetting::kClientCert] = (uint8)certId;
}
static void InitVTable()
{
s_VTable->rtti.ptr = nullptr; // todo
s_VTable->dtor.ptr = DTOR_WRAPPER(NetTaskSetting);
s_VTable->RegisterPreprocess.ptr = nullptr; // todo
s_VTable->unk1.ptr = nullptr; // todo
}
};
static_assert(sizeof(NetTaskSetting) == 0x1004);
struct NbdlTaskSetting : NetTaskSetting
{
struct VTableNbdlTaskSetting : public VTableNetTaskSetting
{
VTableEntry rttiNetTaskSetting; // unknown
};
static_assert(sizeof(VTableNbdlTaskSetting) == 8*5);
static inline SysAllocator<VTableNbdlTaskSetting> s_VTable;
static NbdlTaskSetting* ctor(NbdlTaskSetting* _thisptr)
{
if (!_thisptr)
_thisptr = boss_new<NbdlTaskSetting>();
NetTaskSetting::ctor(_thisptr);
_thisptr->vTablePtr = s_VTable;
return _thisptr;
}
static Result Initialize(NbdlTaskSetting* _thisptr, const char* bossCode, uint64 directorySizeLimit, const char* directoryName) // Initialize__Q3_2nn4boss15NbdlTaskSettingFPCcLT1
{
if(!bossCode || strnlen(bossCode, TaskSetting::kBossCodeLen) == TaskSetting::kBossCodeLen)
return BUILD_NN_RESULT(NN_RESULT_LEVEL_LVL6, NN_RESULT_MODULE_NN_BOSS, 0x3780);
if (directoryName && strnlen(directoryName, TaskSetting::kDirectoryNameLen) == TaskSetting::kDirectoryNameLen)
return BUILD_NN_RESULT(NN_RESULT_LEVEL_LVL6, NN_RESULT_MODULE_NN_BOSS, 0x3780);
strncpy((char*)&_thisptr->settings[TaskSetting::kBossCode], bossCode, TaskSetting::kBossCodeLen);
*(uint64be*)&_thisptr->settings[TaskSetting::kDirectorySizeLimit] = directorySizeLimit; // uint64be
if(directoryName)
strncpy((char*)&_thisptr->settings[TaskSetting::kDirectoryName], directoryName, TaskSetting::kDirectoryNameLen);
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_BOSS, 0x80);
}
static Result SetFileName(NbdlTaskSetting* _thisptr, const char* fileName)
{
cemuLog_logDebug(LogType::Force, "nn_boss_NbdlTaskSetting_t_SetFileName(0x{:08x}, {})", MEMPTR(_thisptr).GetMPTR(), fileName ? fileName : "\"\"");
if (!fileName || strnlen(fileName, TaskSetting::kFileNameLen) == TaskSetting::kFileNameLen)
return BUILD_NN_RESULT(NN_RESULT_LEVEL_LVL6, NN_RESULT_MODULE_NN_BOSS, 0x3780);
strncpy((char*)&_thisptr->settings[TaskSetting::kNbdlFileName], fileName, TaskSetting::kFileNameLen);
// also sets byte at +0x817 to zero?
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_BOSS, 0x80);
}
static void InitVTable()
{
s_VTable->rtti.ptr = nullptr; // todo
s_VTable->dtor.ptr = DTOR_WRAPPER(NbdlTaskSetting);
s_VTable->RegisterPreprocess.ptr = nullptr; // todo
s_VTable->unk1.ptr = nullptr; // todo
s_VTable->rttiNetTaskSetting.ptr = nullptr; // todo
}
};
static_assert(sizeof(NbdlTaskSetting) == 0x1004);
struct RawUlTaskSetting : NetTaskSetting
{
uint32be ukRaw1; // 0x1004
uint32be ukRaw2; // 0x1008
uint32be ukRaw3; // 0x100C
uint8 rawSpace[0x200]; // 0x1010
struct VTableRawUlTaskSetting : public VTableNetTaskSetting
{
VTableEntry rttiNetTaskSetting; // unknown
};
static_assert(sizeof(VTableRawUlTaskSetting) == 8*5);
static inline SysAllocator<VTableRawUlTaskSetting> s_VTable;
static RawUlTaskSetting* ctor(RawUlTaskSetting* _thisptr)
{
if (!_thisptr)
_thisptr = boss_new<RawUlTaskSetting>();
NetTaskSetting::ctor(_thisptr);
_thisptr->vTablePtr = s_VTable;
_thisptr->ukRaw1 = 0;
_thisptr->ukRaw2 = 0;
_thisptr->ukRaw3 = 0;
memset(_thisptr->rawSpace, 0x00, 0x200);
return _thisptr;
}
static void dtor(RawUlTaskSetting* _this, uint32 options)
{
cemuLog_logDebug(LogType::Force, "nn::boss::RawUlTaskSetting::dtor() is todo");
}
static void InitVTable()
{
s_VTable->rtti.ptr = nullptr; // todo
s_VTable->dtor.ptr = DTOR_WRAPPER(RawUlTaskSetting);
s_VTable->RegisterPreprocess.ptr = nullptr; // todo
s_VTable->unk1.ptr = nullptr; // todo
s_VTable->rttiNetTaskSetting.ptr = nullptr; // todo
}
};
static_assert(sizeof(RawUlTaskSetting) == 0x1210);
struct RawDlTaskSetting : NetTaskSetting
{
struct VTableRawDlTaskSetting : public VTableNetTaskSetting
{
VTableEntry rttiNetTaskSetting; // unknown
};
static_assert(sizeof(VTableRawDlTaskSetting) == 8*5);
static inline SysAllocator<VTableRawDlTaskSetting> s_VTable;
static RawDlTaskSetting* ctor(RawDlTaskSetting* _thisptr)
{
cemuLog_logDebug(LogType::Force, "nn_boss_RawDlTaskSetting_ctor(0x{:x}) TODO", MEMPTR(_thisptr).GetMPTR());
if (!_thisptr)
_thisptr = boss_new<RawDlTaskSetting>();
NetTaskSetting::ctor(_thisptr);
_thisptr->vTablePtr = s_VTable;
return _thisptr;
}
static Result Initialize(RawDlTaskSetting* _thisptr, const char* url, bool newArrival, bool led, const char* fileName, const char* directoryName)
{
cemuLog_logDebug(LogType::Force, "nn_boss_RawDlTaskSetting_Initialize(0x{:x}, 0x{:x}, {}, {}, 0x{:x}, 0x{:x})", MEMPTR(_thisptr).GetMPTR(), MEMPTR(url).GetMPTR(), newArrival, led, MEMPTR(fileName).GetMPTR(), MEMPTR(directoryName).GetMPTR());
if (!url)
{
return 0xC0203780;
}
if (strnlen(url, TaskSetting::kURLLen) == TaskSetting::kURLLen)
{
return 0xC0203780;
}
cemuLog_logDebug(LogType::Force, "\t-> url: {}", url);
if (fileName && strnlen(fileName, TaskSetting::kFileNameLen) == TaskSetting::kFileNameLen)
{
return 0xC0203780;
}
if (directoryName && strnlen(directoryName, TaskSetting::kDirectoryNameLen) == TaskSetting::kDirectoryNameLen)
{
return 0xC0203780;
}
strncpy((char*)_thisptr + TaskSetting::kURL, url, TaskSetting::kURLLen);
_thisptr->settings[0x147] = '\0';
if (fileName)
strncpy((char*)_thisptr + 0x7D0, fileName, TaskSetting::kFileNameLen);
else
strncpy((char*)_thisptr + 0x7D0, "rawcontent.dat", TaskSetting::kFileNameLen);
_thisptr->settings[0x7EF] = '\0';
cemuLog_logDebug(LogType::Force, "\t-> filename: {}", (char*)_thisptr + 0x7D0);
if (directoryName)
{
strncpy((char*)_thisptr + 0x7C8, directoryName, TaskSetting::kDirectoryNameLen);
_thisptr->settings[0x7CF] = '\0';
cemuLog_logDebug(LogType::Force, "\t-> directoryName: {}", (char*)_thisptr + 0x7C8);
}
_thisptr->settings[0x7C0] = newArrival;
_thisptr->settings[0x7C1] = led;
*(uint16be*)&_thisptr->settings[0x28] = 0x3;
return 0x200080;
}
static void InitVTable()
{
s_VTable->rtti.ptr = nullptr; // todo
s_VTable->dtor.ptr = DTOR_WRAPPER(RawDlTaskSetting);
s_VTable->RegisterPreprocess.ptr = nullptr; // todo
s_VTable->unk1.ptr = nullptr; // todo
s_VTable->rttiNetTaskSetting.ptr = nullptr; // todo
}
};
static_assert(sizeof(RawDlTaskSetting) == 0x1004);
struct PlayReportSetting : RawUlTaskSetting
{
MEMPTR<uint8> ukn1210_ptr; // 0x1210
uint32be ukn1214_size; // 0x1214
uint32be ukPlay3; // 0x1218
uint32be ukPlay4; // 0x121C
struct VTablePlayReportSetting : public VTableRawUlTaskSetting
{};
static_assert(sizeof(VTablePlayReportSetting) == 8*5);
static inline SysAllocator<VTablePlayReportSetting> s_VTable;
static PlayReportSetting* ctor(PlayReportSetting* _this)
{
if(!_this)
_this = boss_new<PlayReportSetting>();
RawUlTaskSetting::ctor(_this);
_this->vTablePtr = s_VTable;
_this->ukn1210_ptr = nullptr;
_this->ukn1214_size = 0;
_this->ukPlay3 = 0;
_this->ukPlay4 = 0;
return _this;
}
static void dtor(PlayReportSetting* _this, uint32 options)
{
RawUlTaskSetting::dtor(_this, 0);
if(options&1)
boss_delete(_this->ukn1210_ptr.GetPtr());
}
static void Initialize(PlayReportSetting* _this, uint8* ptr, uint32 size)
{
if(!ptr || size == 0 || size > 0x19000)
{
cemuLog_logDebug(LogType::Force, "nn::boss::PlayReportSetting::Initialize: invalid parameter");
return;
}
*ptr = 0;
*(uint16be*)&_this->settings[0x28] = 6;
*(uint16be*)&_this->settings[0x2B] |= 0x3;
*(uint16be*)&_this->settings[0x2C] |= 0xA;
*(uint32be*)&_this->settings[0x7C0] |= 2;
_this->ukn1210_ptr = ptr;
_this->ukn1214_size = size;
_this->ukPlay3 = 0;
_this->ukPlay4 = 0;
// TODO
}
static bool Set(PlayReportSetting* _this, const char* keyname, uint32 value)
{
// TODO
return true;
}
static void InitVTable()
{
s_VTable->rtti.ptr = nullptr; // todo
s_VTable->dtor.ptr = DTOR_WRAPPER(PlayReportSetting);
s_VTable->RegisterPreprocess.ptr = nullptr; // todo
s_VTable->unk1.ptr = nullptr; // todo
s_VTable->rttiNetTaskSetting.ptr = nullptr; // todo
}
};
static_assert(sizeof(PlayReportSetting) == 0x1220);
struct Task
{
struct VTableTask
{
VTableEntry rtti;
VTableEntry dtor;
};
static inline SysAllocator<VTableTask> s_vTable;
uint32be accountId; // 0x00
uint32be uk2; // 0x04
TaskId taskId; // 0x08
TitleId titleId; // 0x10
MEMPTR<VTableTask> vTablePtr; // 0x18
uint32be padding; // 0x1C
static Result Initialize1(Task* _thisptr, const char* taskId, uint32 accountId) // Initialize__Q3_2nn4boss4TaskFPCcUi
{
if(!taskId || strnlen(taskId, 0x8) == 8)
{
return BUILD_NN_RESULT(NN_RESULT_LEVEL_LVL6, NN_RESULT_MODULE_NN_BOSS, 0x3780);
}
_thisptr->accountId = accountId;
strncpy(_thisptr->taskId.id, taskId, 0x08);
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_BOSS, 0x80);
}
static Result Initialize2(Task* _thisptr, uint8 slot, const char* taskId) // Initialize__Q3_2nn4boss4TaskFUcPCc
{
const uint32 accountId = slot == 0 ? 0 : act::GetPersistentIdEx(slot);
return Initialize1(_thisptr, taskId, accountId);
}
static Result Initialize3(Task* _thisptr, const char* taskId) // Initialize__Q3_2nn4boss4TaskFPCc
{
return Initialize1(_thisptr, taskId, 0);
}
static Task* ctor2(Task* _thisptr, const char* taskId, uint32 accountId) // __ct__Q3_2nn4boss4TaskFPCcUi
{
if (!_thisptr)
_thisptr = boss_new<Task>();
_thisptr->accountId = 0;
_thisptr->vTablePtr = s_vTable;
TaskId::ctor(&_thisptr->taskId);
TitleId::ctor(&_thisptr->titleId, 0);
auto r = Initialize1(_thisptr, taskId, accountId);
cemu_assert_debug(NN_RESULT_IS_SUCCESS(r));
return _thisptr;
}
static Task* ctor1(Task* _thisptr, uint8 slot, const char* taskId) // __ct__Q3_2nn4boss4TaskFUcPCc
{
if (!_thisptr)
_thisptr = boss_new<Task>();
_thisptr->accountId = 0;
_thisptr->vTablePtr = s_vTable;
TaskId::ctor(&_thisptr->taskId);
TitleId::ctor(&_thisptr->titleId, 0);
auto r = Initialize2(_thisptr, slot, taskId);
cemu_assert_debug(NN_RESULT_IS_SUCCESS(r));
return _thisptr;
}
static Task* ctor3(Task* _thisptr, const char* taskId) // __ct__Q3_2nn4boss4TaskFPCc
{
if (!_thisptr)
_thisptr = boss_new<Task>();
_thisptr->accountId = 0;
_thisptr->vTablePtr = s_vTable;
TaskId::ctor(&_thisptr->taskId);
TitleId::ctor(&_thisptr->titleId, 0);
auto r = Initialize3(_thisptr, taskId);
cemu_assert_debug(NN_RESULT_IS_SUCCESS(r));
return _thisptr;
}
static Task* ctor4(Task* _thisptr) // __ct__Q3_2nn4boss4TaskFv
{
if (!_thisptr)
_thisptr = boss_new<Task>();
_thisptr->accountId = 0;
_thisptr->vTablePtr = s_vTable;
TaskId::ctor(&_thisptr->taskId);
TitleId::ctor(&_thisptr->titleId, 0);
memset(&_thisptr->taskId, 0x00, sizeof(TaskId));
return _thisptr;
}
static void dtor(Task* _this, uint32 options) // __dt__Q3_2nn4boss4TaskFv
{
cemuLog_logDebug(LogType::Force, "nn::boss::Task::dtor(0x{:08x}, 0x{:08x})", MEMPTR(_this).GetMPTR(), options);
// todo - Task::Finalize
if(options & 1)
boss_delete(_this);
}
static Result Run(Task* _thisptr, bool isForegroundRun)
{
if (isForegroundRun != 0)
{
cemuLog_logDebug(LogType::Force, "export_Run foreground run");
}
bossPrepareRequest();
bossRequest->requestCode = IOSU_NN_BOSS_TASK_RUN;
bossRequest->accountId = _thisptr->accountId;
bossRequest->taskId = _thisptr->taskId.id;
bossRequest->titleId = _thisptr->titleId.u64;
bossRequest->bool_parameter = isForegroundRun != 0;
__depr__IOS_Ioctlv(IOS_DEVICE_BOSS, IOSU_BOSS_REQUEST_CEMU, 1, 1, bossBufferVector);
return 0;
}
static Result StartScheduling(Task* _thisptr, uint8 executeImmediately)
{
bossPrepareRequest();
bossRequest->requestCode = IOSU_NN_BOSS_TASK_START_SCHEDULING;
bossRequest->accountId = _thisptr->accountId;
bossRequest->taskId = _thisptr->taskId.id;
bossRequest->titleId = _thisptr->titleId.u64;
bossRequest->bool_parameter = executeImmediately != 0;
__depr__IOS_Ioctlv(IOS_DEVICE_BOSS, IOSU_BOSS_REQUEST_CEMU, 1, 1, bossBufferVector);
return 0;
}
static Result StopScheduling(Task* _thisptr)
{
bossPrepareRequest();
bossRequest->requestCode = IOSU_NN_BOSS_TASK_STOP_SCHEDULING;
bossRequest->accountId = _thisptr->accountId;
bossRequest->taskId = _thisptr->taskId.id;
bossRequest->titleId = _thisptr->titleId.u64;
__depr__IOS_Ioctlv(IOS_DEVICE_BOSS, IOSU_BOSS_REQUEST_CEMU, 1, 1, bossBufferVector);
return 0;
}
static Result IsRegistered(Task* _thisptr)
{
bossPrepareRequest();
bossRequest->requestCode = IOSU_NN_BOSS_TASK_IS_REGISTERED;
bossRequest->accountId = _thisptr->accountId;
bossRequest->titleId = _thisptr->titleId.u64;
bossRequest->taskId = _thisptr->taskId.id;
__depr__IOS_Ioctlv(IOS_DEVICE_BOSS, IOSU_BOSS_REQUEST_CEMU, 1, 1, bossBufferVector);
return bossRequest->returnCode;
}
static Result Wait(Task* _thisptr, uint32 timeout, uint32 waitState) // Wait__Q3_2nn4boss4TaskFUiQ3_2nn4boss13TaskWaitState
{
bossPrepareRequest();
bossRequest->requestCode = IOSU_NN_BOSS_TASK_WAIT;
bossRequest->titleId = _thisptr->titleId.u64;
bossRequest->taskId = _thisptr->taskId.id;
bossRequest->timeout = timeout;
bossRequest->waitState = waitState;
__depr__IOS_Ioctlv(IOS_DEVICE_BOSS, IOSU_BOSS_REQUEST_CEMU, 1, 1, bossBufferVector);
return bossRequest->returnCode;
}
static Result RegisterForImmediateRun(Task* _thisptr, TaskSetting* settings) // RegisterForImmediateRun__Q3_2nn4boss4TaskFRCQ3_2nn4boss11TaskSetting
{
bossPrepareRequest();
bossRequest->requestCode = IOSU_NN_BOSS_TASK_REGISTER;
bossRequest->accountId = _thisptr->accountId;
bossRequest->taskId = _thisptr->taskId.id;
bossRequest->settings = settings;
bossRequest->uk1 = 0xC00;
if (TaskSetting::IsPrivileged(settings))
bossRequest->titleId = _thisptr->titleId.u64;
Result result = __depr__IOS_Ioctlv(IOS_DEVICE_BOSS, IOSU_BOSS_REQUEST_CEMU, 1, 1, bossBufferVector);
return result;
}
static Result Unregister(Task* _thisptr)
{
bossPrepareRequest();
bossRequest->requestCode = IOSU_NN_BOSS_TASK_UNREGISTER;
bossRequest->accountId = _thisptr->accountId;
bossRequest->taskId = _thisptr->taskId.id;
bossRequest->titleId = _thisptr->titleId.u64;
const sint32 result = __depr__IOS_Ioctlv(IOS_DEVICE_BOSS, IOSU_BOSS_REQUEST_CEMU, 1, 1, bossBufferVector);
return result;
}
static Result Register(Task* _thisptr, TaskSetting* settings)
{
if (!settings)
{
cemuLog_logDebug(LogType::Force, "nn_boss_Task_Register - crash workaround (fix me)"); // settings should never be zero
return 0;
}
bossPrepareRequest();
bossRequest->requestCode = IOSU_NN_BOSS_TASK_REGISTER_FOR_IMMEDIATE_RUN;
bossRequest->accountId = _thisptr->accountId;
bossRequest->taskId = _thisptr->taskId.id;
bossRequest->settings = settings;
bossRequest->uk1 = 0xC00;
if(TaskSetting::IsPrivileged(settings))
bossRequest->titleId = _thisptr->titleId.u64;
__depr__IOS_Ioctlv(IOS_DEVICE_BOSS, IOSU_BOSS_REQUEST_CEMU, 1, 1, bossBufferVector);
return bossRequest->returnCode;
}
static uint32 GetTurnState(Task* _this, uint32be* executionCountOut)
{
bossPrepareRequest();
bossRequest->requestCode = IOSU_NN_BOSS_TASK_GET_TURN_STATE;
bossRequest->accountId = _this->accountId;
bossRequest->taskId = _this->taskId.id;
bossRequest->titleId = _this->titleId.u64;
__depr__IOS_Ioctlv(IOS_DEVICE_BOSS, IOSU_BOSS_REQUEST_CEMU, 1, 1, bossBufferVector);
if (executionCountOut)
*executionCountOut = bossRequest->u32.exec_count;
return bossRequest->u32.result;
// 7 -> finished? 0x11 -> Error (Splatoon doesn't like it when we return 0x11 for Nbdl tasks)
}
static uint64 GetContentLength(Task* _this, uint32be* executionCountOut)
{
bossPrepareRequest();
bossRequest->requestCode = IOSU_NN_BOSS_TASK_GET_CONTENT_LENGTH;
bossRequest->accountId = _this->accountId;
bossRequest->taskId = _this->taskId.id;
bossRequest->titleId = _this->titleId.u64;
__depr__IOS_Ioctlv(IOS_DEVICE_BOSS, IOSU_BOSS_REQUEST_CEMU, 1, 1, bossBufferVector);
if (executionCountOut)
*executionCountOut = bossRequest->u64.exec_count;
return bossRequest->u64.result;
}
static uint64 GetProcessedLength(Task* _this, uint32be* executionCountOut)
{
bossPrepareRequest();
bossRequest->requestCode = IOSU_NN_BOSS_TASK_GET_PROCESSED_LENGTH;
bossRequest->accountId = _this->accountId;
bossRequest->taskId = _this->taskId.id;
bossRequest->titleId = _this->titleId.u64;
__depr__IOS_Ioctlv(IOS_DEVICE_BOSS, IOSU_BOSS_REQUEST_CEMU, 1, 1, bossBufferVector);
if (executionCountOut)
*executionCountOut = bossRequest->u64.exec_count;
return bossRequest->u64.result;
}
static uint32 GetHttpStatusCode(Task* _this, uint32be* executionCountOut)
{
bossPrepareRequest();
bossRequest->requestCode = IOSU_NN_BOSS_TASK_GET_HTTP_STATUS_CODE;
bossRequest->accountId = _this->accountId;
bossRequest->taskId = _this->taskId.id;
bossRequest->titleId = _this->titleId.u64;
__depr__IOS_Ioctlv(IOS_DEVICE_BOSS, IOSU_BOSS_REQUEST_CEMU, 1, 1, bossBufferVector);
if (executionCountOut)
*executionCountOut = bossRequest->u32.exec_count;
return bossRequest->u32.result;
}
static void InitVTable()
{
s_vTable->rtti.ptr = nullptr; // todo
s_vTable->dtor.ptr = RPLLoader_MakePPCCallable([](PPCInterpreter_t* hCPU) { Task::dtor(MEMPTR<Task>(hCPU->gpr[3]), hCPU->gpr[4]); osLib_returnFromFunction(hCPU, 0); });
}
};
static_assert(sizeof(Task) == 0x20);
struct PrivilegedTask : Task
{
struct VTablePrivilegedTask : public VTableTask
{
VTableEntry rttiTask;
};
static_assert(sizeof(VTablePrivilegedTask) == 8*3);
static inline SysAllocator<VTablePrivilegedTask> s_VTable;
static PrivilegedTask* ctor(PrivilegedTask* _thisptr)
{
if (!_thisptr)
_thisptr = boss_new<PrivilegedTask>();
Task::ctor4(_thisptr);
_thisptr->vTablePtr = s_VTable;
return _thisptr;
}
static void dtor(PrivilegedTask* _this, uint32 options)
{
if(!_this)
return;
Task::dtor(_this, 0);
if(options & 1)
boss_delete(_this);
}
static void InitVTable()
{
s_VTable->rtti.ptr = nullptr; // todo
s_VTable->dtor.ptr = DTOR_WRAPPER(PrivilegedTask);
s_VTable->rttiTask.ptr = nullptr; // todo
}
};
static_assert(sizeof(PrivilegedTask) == 0x20);
struct AlmightyTask : PrivilegedTask
{
struct VTableAlmightyTask : public VTablePrivilegedTask
{};
static_assert(sizeof(VTableAlmightyTask) == 8*3);
static inline SysAllocator<VTableAlmightyTask> s_VTable;
static AlmightyTask* ctor(AlmightyTask* _thisptr)
{
if (!_thisptr)
_thisptr = boss_new<AlmightyTask>();
PrivilegedTask::ctor(_thisptr);
_thisptr->vTablePtr = s_VTable;
return _thisptr;
}
static void dtor(AlmightyTask* _thisptr, uint32 options)
{
if (!_thisptr)
return;
PrivilegedTask::dtor(_thisptr, 0);
if(options&1)
boss_delete(_thisptr);
}
static uint32 Initialize(AlmightyTask* _thisptr, TitleId* titleId, const char* taskId, uint32 accountId)
{
if (!_thisptr)
return 0xc0203780;
_thisptr->accountId = accountId;
_thisptr->titleId.u64 = titleId->u64;
strncpy(_thisptr->taskId.id, taskId, 8);
_thisptr->taskId.id[7] = 0x00;
return 0x200080;
}
static void InitVTable()
{
s_VTable->rtti.ptr = nullptr; // todo
s_VTable->dtor.ptr = DTOR_WRAPPER(AlmightyTask);
s_VTable->rttiTask.ptr = nullptr; // todo
}
};
static_assert(sizeof(AlmightyTask) == 0x20);
struct DataName
{
char name[32];
static DataName* ctor(DataName* _this) // __ct__Q3_2nn4boss8DataNameFv
{
if(!_this)
_this = boss_new<DataName>();
memset(_this->name, 0, sizeof(name));
return _this;
}
static const char* operator_const_char(DataName* _this) // __opPCc__Q3_2nn4boss8DataNameCFv
{
return _this->name;
}
};
static_assert(sizeof(DataName) == 0x20);
struct BossStorageFadEntry
{
char name[32];
uint32be fileNameId;
uint32 ukn24;
uint32 ukn28;
uint32 ukn2C;
uint32 ukn30;
uint32be timestampRelated; // guessed
};
#define FAD_ENTRY_MAX_COUNT 512
struct Storage
{
struct VTableStorage
{
VTableEntry rtti;
VTableEntry dtor;
};
static inline SysAllocator<VTableStorage> s_vTable;
enum StorageKind
{
kStorageKind_NBDL,
kStorageKind_RawDl,
};
/* +0x00 */ uint32be accountId;
/* +0x04 */ uint32be storageKind;
/* +0x08 */ uint8 ukn08Array[3];
/* +0x0B */ char storageName[8];
uint8 ukn13;
uint8 ukn14;
uint8 ukn15;
uint8 ukn16;
uint8 ukn17;
/* +0x18 */ nn::boss::TitleId titleId;
/* +0x20 */ MEMPTR<VTableStorage> vTablePtr;
/* +0x24 */ uint32be ukn24;
static nn::boss::Storage* ctor1(nn::boss::Storage* _this) // __ct__Q3_2nn4boss7StorageFv
{
if(!_this)
_this = boss_new<nn::boss::Storage>();
_this->vTablePtr = s_vTable;
_this->titleId.u64 = 0;
return _this;
}
static void dtor(nn::boss::Storage* _this, uint32 options) // __dt__Q3_2nn4boss7StorageFv
{
cemuLog_logDebug(LogType::Force, "nn::boss::Storage::dtor(0x{:08x}, 0x{:08x})", MEMPTR(_this).GetMPTR(), options);
Finalize(_this);
if(options & 1)
boss_delete(_this);
}
static void nnBossStorage_prepareTitleId(Storage* storage)
{
if (storage->titleId.u64 != 0)
return;
storage->titleId.u64 = CafeSystem::GetForegroundTitleId();
}
static Result Initialize(Storage* _thisptr, const char* dirName, uint32 accountId, StorageKind type)
{
if (!dirName)
return 0xC0203780;
cemuLog_logDebug(LogType::Force, "boss::Storage::Initialize({}, 0x{:08x}, {})", dirName, accountId, type);
_thisptr->storageKind = type;
_thisptr->titleId.u64 = 0;
memset(_thisptr->storageName, 0, 0x8);
strncpy(_thisptr->storageName, dirName, 0x8);
_thisptr->storageName[7] = '\0';
_thisptr->accountId = accountId;
nnBossStorage_prepareTitleId(_thisptr); // usually not done like this
return 0x200080;
}
static Result Initialize2(Storage* _thisptr, const char* dirName, StorageKind type)
{
return Initialize(_thisptr, dirName, 0, type);
}
static void Finalize(Storage* _this)
{
memset(_this, 0, sizeof(Storage)); // todo - not all fields might be cleared
}
static Result GetDataList(nn::boss::Storage* storage, DataName* dataList, sint32 maxEntries, uint32be* outputEntryCount, uint32 startIndex) // GetDataList__Q3_2nn4boss7StorageCFPQ3_2nn4boss8DataNameUiPUiT2
{
// initialize titleId of storage if not already done
nnBossStorage_prepareTitleId(storage);
if(startIndex >= FAD_ENTRY_MAX_COUNT) {
*outputEntryCount = 0;
return 0;
}
// load fad.db
BossStorageFadEntry* fadTable = nnBossStorageFad_getTable(storage);
if (fadTable)
{
sint32 validEntryCount = 0;
for (sint32 i = startIndex; i < FAD_ENTRY_MAX_COUNT; i++)
{
if( fadTable[i].name[0] == '\0' )
continue;
memcpy(dataList[validEntryCount].name, fadTable[i].name, 0x20);
validEntryCount++;
if (validEntryCount >= maxEntries)
break;
}
*outputEntryCount = validEntryCount;
free(fadTable);
}
else
{
// could not load fad table
*outputEntryCount = 0;
}
return 0; // todo
}
static bool Exist(nn::boss::Storage* storage)
{
cemuLog_logDebug(LogType::Force, "nn_boss::Storage::Exist() TODO");
return true;
}
/* FAD access */
static FSCVirtualFile* nnBossStorageFile_open(nn::boss::Storage* storage, uint32 fileNameId)
{
char storageFilePath[1024];
sprintf(storageFilePath, "/cemuBossStorage/%08x/%08x/user/common/data/%s/%08x", (uint32)(storage->titleId.u64 >> 32), (uint32)(storage->titleId.u64), storage->storageName, fileNameId);
sint32 fscStatus;
FSCVirtualFile* fscStorageFile = fsc_open(storageFilePath, FSC_ACCESS_FLAG::OPEN_FILE | FSC_ACCESS_FLAG::READ_PERMISSION | FSC_ACCESS_FLAG::WRITE_PERMISSION, &fscStatus);
return fscStorageFile;
}
static BossStorageFadEntry* nnBossStorageFad_getTable(nn::boss::Storage* storage)
{
const auto accountId = ActiveSettings::GetPersistentId();
char fadPath[1024];
sprintf(fadPath, "/cemuBossStorage/%08x/%08x/user/common/%08x/%s/fad.db", (uint32)(storage->titleId.u64 >> 32), (uint32)(storage->titleId.u64), accountId, storage->storageName);
sint32 fscStatus;
FSCVirtualFile* fscFadFile = fsc_open(fadPath, FSC_ACCESS_FLAG::OPEN_FILE | FSC_ACCESS_FLAG::READ_PERMISSION, &fscStatus);
if (!fscFadFile)
{
return nullptr;
}
// skip first 8 bytes
fsc_setFileSeek(fscFadFile, 8);
// read entries
BossStorageFadEntry* fadTable = (BossStorageFadEntry*)malloc(sizeof(BossStorageFadEntry)*FAD_ENTRY_MAX_COUNT);
memset(fadTable, 0, sizeof(BossStorageFadEntry)*FAD_ENTRY_MAX_COUNT);
fsc_readFile(fscFadFile, fadTable, sizeof(BossStorageFadEntry)*FAD_ENTRY_MAX_COUNT);
fsc_close(fscFadFile);
return fadTable;
}
// Find index of entry by name. Returns -1 if not found
static sint32 nnBossStorageFad_getIndexByName(BossStorageFadEntry* fadTable, char* name)
{
for (sint32 i = 0; i < FAD_ENTRY_MAX_COUNT; i++)
{
if (fadTable[i].name[0] == '\0')
continue;
if (strncmp(name, fadTable[i].name, 0x20) == 0)
{
return i;
}
}
return -1;
}
static bool nnBossStorageFad_getEntryByName(nn::boss::Storage* storage, char* name, BossStorageFadEntry* fadEntry)
{
BossStorageFadEntry* fadTable = nnBossStorageFad_getTable(storage);
if (fadTable)
{
sint32 entryIndex = nnBossStorageFad_getIndexByName(fadTable, name);
if (entryIndex >= 0)
{
memcpy(fadEntry, fadTable + entryIndex, sizeof(BossStorageFadEntry));
free(fadTable);
return true;
}
free(fadTable);
}
return false;
}
static void InitVTable()
{
s_vTable->rtti.ptr = nullptr; // todo
s_vTable->dtor.ptr = DTOR_WRAPPER(Storage);
}
};
static_assert(sizeof(Storage) == 0x28);
static_assert(offsetof(Storage, storageKind) == 0x04);
static_assert(offsetof(Storage, ukn08Array) == 0x08);
static_assert(offsetof(Storage, storageName) == 0x0B);
static_assert(offsetof(Storage, titleId) == 0x18);
struct AlmightyStorage : Storage
{
struct VTableAlmightyStorage : public VTableStorage
{
VTableEntry rttiStorage;
};
static_assert(sizeof(VTableAlmightyStorage) == 8*3);
static inline SysAllocator<VTableAlmightyStorage> s_VTable;
static AlmightyStorage* ctor(AlmightyStorage* _thisptr)
{
cemuLog_logDebug(LogType::Force, "nn_boss_AlmightyStorage_ctor(0x{:x})", MEMPTR(_thisptr).GetMPTR());
if (!_thisptr)
_thisptr = boss_new<AlmightyStorage>();
Storage::ctor1(_thisptr);
_thisptr->vTablePtr = s_VTable;
return _thisptr;
}
static uint32 Initialize(AlmightyStorage* _thisptr, TitleId* titleId, const char* storageName, uint32 accountId, StorageKind storageKind)
{
cemuLog_logDebug(LogType::Force, "nn_boss_AlmightyStorage_Initialize(0x{:x})", MEMPTR(_thisptr).GetMPTR());
if (!_thisptr)
return 0xc0203780;
_thisptr->accountId = accountId;
_thisptr->storageKind = storageKind;
_thisptr->titleId.u64 = titleId->u64;
strncpy(_thisptr->storageName, storageName, 8);
_thisptr->storageName[0x7] = 0x00;
return 0x200080;
}
static void InitVTable()
{
s_VTable->rtti.ptr = nullptr; // todo
s_VTable->dtor.ptr = DTOR_WRAPPER(AlmightyStorage);
s_VTable->rttiStorage.ptr = nullptr; // todo
}
};
static_assert(sizeof(AlmightyStorage) == 0x28);
// NsData
struct NsData
{
struct VTableNsData
{
VTableEntry rtti;
VTableEntry dtor;
};
static inline SysAllocator<VTableNsData> s_vTable;
/* +0x00 */ char name[0x20]; // DataName ?
/* +0x20 */ nn::boss::Storage storage;
/* +0x48 */ uint64 readIndex;
/* +0x50 */ MEMPTR<void> vTablePtr;
/* +0x54 */ uint32 ukn54;
static NsData* ctor(NsData* _this)
{
if (!_this)
_this = boss_new<NsData>();
_this->vTablePtr = s_vTable;
memset(_this->name, 0, sizeof(_this->name));
_this->storage.ctor1(&_this->storage);
_this->readIndex = 0;
return _this;
}
static void dtor(NsData* _this, uint32 options) // __dt__Q3_2nn4boss6NsDataFv
{
_this->storage.dtor(&_this->storage, 0);
// todo
if(options & 1)
boss_delete(_this);
}
static Result Initialize(NsData* _this, nn::boss::Storage* storage, const char* dataName)
{
if(dataName == nullptr)
{
if (storage->storageKind != 1)
{
return 0xC0203780;
}
}
_this->storage.accountId = storage->accountId;
_this->storage.storageKind = storage->storageKind;
memcpy(_this->storage.ukn08Array, storage->ukn08Array, 3);
memcpy(_this->storage.storageName, storage->storageName, 8);
_this->storage.titleId.u64 = storage->titleId.u64;
_this->storage = *storage;
if (dataName != nullptr || storage->storageKind != 1)
strncpy(_this->name, dataName, 0x20);
else
strncpy(_this->name, "rawcontent.dat", 0x20);
_this->name[0x1F] = '\0';
_this->readIndex = 0;
cemuLog_logDebug(LogType::Force, "initialize: {}", _this->name);
return 0x200080;
}
static std::string _GetPath(NsData* nsData)
{
uint32 accountId = nsData->storage.accountId;
if (accountId == 0)
accountId = iosuAct_getAccountIdOfCurrentAccount();
uint64 title_id = nsData->storage.titleId.u64;
if (title_id == 0)
title_id = CafeSystem::GetForegroundTitleId();
fs::path path = fmt::format("cemuBossStorage/{:08x}/{:08x}/user/{:08x}", (uint32)(title_id >> 32), (uint32)(title_id & 0xFFFFFFFF), accountId);
path /= nsData->storage.storageName;
path /= nsData->name;
return path.string();
}
static Result DeleteRealFileWithHistory(NsData* nsData)
{
if (nsData->storage.storageKind == nn::boss::Storage::kStorageKind_NBDL)
{
// todo
cemuLog_log(LogType::Force, "BOSS NBDL: Unsupported delete");
}
else
{
sint32 fscStatus = FSC_STATUS_OK;
std::string filePath = _GetPath(nsData).c_str();
fsc_remove((char*)filePath.c_str(), &fscStatus);
if (fscStatus != 0)
cemuLog_log(LogType::Force, "Unhandeled FSC status in BOSS DeleteRealFileWithHistory()");
}
return 0;
}
static uint32 Exist(NsData* nsData)
{
bool fileExists = false;
if(nsData->storage.storageKind == nn::boss::Storage::kStorageKind_NBDL)
{
// check if name is present in fad table
BossStorageFadEntry* fadTable = nn::boss::Storage::nnBossStorageFad_getTable(&nsData->storage);
if (fadTable)
{
fileExists = nn::boss::Storage::nnBossStorageFad_getIndexByName(fadTable, nsData->name) >= 0;
cemuLog_logDebug(LogType::Force, "\t({}) -> {}", nsData->name, fileExists);
free(fadTable);
}
}
else
{
sint32 fscStatus;
auto fscStorageFile = fsc_open(_GetPath(nsData).c_str(), FSC_ACCESS_FLAG::OPEN_FILE, &fscStatus);
if (fscStorageFile != nullptr)
{
fileExists = true;
fsc_close(fscStorageFile);
}
}
return fileExists?1:0;
}
static uint64 GetSize(NsData* nsData)
{
FSCVirtualFile* fscStorageFile = nullptr;
if (nsData->storage.storageKind == nn::boss::Storage::kStorageKind_NBDL)
{
BossStorageFadEntry fadEntry;
if (nn::boss::Storage::nnBossStorageFad_getEntryByName(&nsData->storage, nsData->name, &fadEntry) == false)
{
cemuLog_log(LogType::Force, "BOSS storage cant find file {}", nsData->name);
return 0;
}
// open file
fscStorageFile = nn::boss::Storage::nnBossStorageFile_open(&nsData->storage, fadEntry.fileNameId);
}
else
{
sint32 fscStatus;
fscStorageFile = fsc_open(_GetPath(nsData).c_str(), FSC_ACCESS_FLAG::OPEN_FILE | FSC_ACCESS_FLAG::READ_PERMISSION, &fscStatus);
}
if (fscStorageFile == nullptr)
{
cemuLog_log(LogType::Force, "BOSS storage cant open file alias {}", nsData->name);
return 0;
}
// get size
const sint32 fileSize = fsc_getFileSize(fscStorageFile);
// close file
fsc_close(fscStorageFile);
return fileSize;
}
static uint64 GetCreatedTime(NsData* nsData)
{
cemuLog_logDebug(LogType::Force, "nn_boss.NsData_GetCreatedTime() not implemented. Returning 0");
uint64 createdTime = 0;
return createdTime;
}
static uint32 nnBossNsData_read(NsData* nsData, uint64be* sizeOutBE, void* buffer, sint32 length)
{
FSCVirtualFile* fscStorageFile = nullptr;
if (nsData->storage.storageKind == nn::boss::Storage::kStorageKind_NBDL)
{
BossStorageFadEntry fadEntry;
if (nn::boss::Storage::nnBossStorageFad_getEntryByName(&nsData->storage, nsData->name, &fadEntry) == false)
{
cemuLog_log(LogType::Force, "BOSS storage cant find file {} for reading", nsData->name);
return 0x80000000; // todo - proper error code
}
// open file
fscStorageFile = nn::boss::Storage::nnBossStorageFile_open(&nsData->storage, fadEntry.fileNameId);
}
else
{
sint32 fscStatus;
fscStorageFile = fsc_open(_GetPath(nsData).c_str(), FSC_ACCESS_FLAG::OPEN_FILE | FSC_ACCESS_FLAG::READ_PERMISSION, &fscStatus);
}
if (!fscStorageFile)
{
cemuLog_log(LogType::Force, "BOSS storage cant open file alias {} for reading", nsData->name);
return 0x80000000; // todo - proper error code
}
// get size
sint32 fileSize = fsc_getFileSize(fscStorageFile);
// verify read is within bounds
sint32 readEndOffset = (sint32)_swapEndianU64(nsData->readIndex) + length;
sint32 readBytes = length;
if (readEndOffset > fileSize)
{
readBytes = fileSize - (sint32)_swapEndianU64(nsData->readIndex);
cemu_assert_debug(readBytes != 0);
}
// read
fsc_setFileSeek(fscStorageFile, (uint32)_swapEndianU64(nsData->readIndex));
fsc_readFile(fscStorageFile, buffer, readBytes);
nsData->readIndex = _swapEndianU64((sint32)_swapEndianU64(nsData->readIndex) + readBytes);
// close file
fsc_close(fscStorageFile);
if (sizeOutBE)
*sizeOutBE = readBytes;
return 0;
}
#define NSDATA_SEEK_MODE_BEGINNING (0)
static uint32 nnBossNsData_seek(NsData* nsData, uint64 seek, uint32 mode)
{
FSCVirtualFile* fscStorageFile = nullptr;
if (nsData->storage.storageKind == nn::boss::Storage::kStorageKind_NBDL)
{
BossStorageFadEntry fadEntry;
if (nn::boss::Storage::nnBossStorageFad_getEntryByName(&nsData->storage, nsData->name, &fadEntry) == false)
{
cemuLog_log(LogType::Force, "BOSS storage cant find file {} for reading", nsData->name);
return 0x80000000; // todo - proper error code
}
// open file
fscStorageFile = nn::boss::Storage::nnBossStorageFile_open(&nsData->storage, fadEntry.fileNameId);
}
else
{
sint32 fscStatus;
fscStorageFile = fsc_open(_GetPath(nsData).c_str(), FSC_ACCESS_FLAG::OPEN_FILE | FSC_ACCESS_FLAG::READ_PERMISSION, &fscStatus);
}
if (fscStorageFile == nullptr)
{
cemuLog_log(LogType::Force, "BOSS storage cant open file alias {} for reading", nsData->name);
return 0x80000000; // todo - proper error code
}
// get size
sint32 fileSize = fsc_getFileSize(fscStorageFile);
// handle seek
if (mode == NSDATA_SEEK_MODE_BEGINNING)
{
seek = std::min(seek, (uint64)fileSize);
nsData->readIndex = _swapEndianU64((uint64)seek);
}
else
{
cemu_assert_unimplemented();
}
fsc_close(fscStorageFile);
return 0;
}
static sint32 Read(NsData* nsData, uint8* buffer, sint32 length)
{
cemuLog_logDebug(LogType::Force, "nsData read (filename {})", nsData->name);
return nnBossNsData_read(nsData, nullptr, buffer, length);
}
static sint32 ReadWithSizeOut(NsData* nsData, uint64be* sizeOut, uint8* buffer, sint32 length)
{
uint32 r = nnBossNsData_read(nsData, sizeOut, buffer, length);
cemuLog_logDebug(LogType::Force, "nsData readWithSizeOut (filename {} length 0x{:x}) Result: {} Sizeout: {:x}", nsData->name, length, r, _swapEndianU64(*sizeOut));
return r;
}
static Result Seek(NsData* nsData, uint64 seekPos, uint32 mode)
{
uint32 r = nnBossNsData_seek(nsData, seekPos, mode);
cemuLog_logDebug(LogType::Force, "nsData seek (filename {} seek 0x{:x}) Result: {}", nsData->name, (uint32)seekPos, r);
return r;
}
static void InitVTable()
{
s_vTable->rtti.ptr = nullptr; // todo
s_vTable->dtor.ptr = DTOR_WRAPPER(NsData);
}
};
static_assert(sizeof(NsData) == 0x58);
}
}
void nnBoss_load()
{
OSInitMutexEx(&nn::boss::g_mutex, nullptr);
nn::boss::g_initCounter = 0;
nn::boss::g_isInitialized = false;
cafeExportRegisterFunc(nn::boss::GetBossState, "nn_boss", "GetBossState__Q2_2nn4bossFv", LogType::NN_BOSS);
// boss lib
cafeExportRegisterFunc(nn::boss::Initialize, "nn_boss", "Initialize__Q2_2nn4bossFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::IsInitialized, "nn_boss", "IsInitialized__Q2_2nn4bossFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Finalize, "nn_boss", "Finalize__Q2_2nn4bossFv", LogType::NN_BOSS);
// task
nn::boss::Task::InitVTable();
cafeExportRegisterFunc(nn::boss::Task::ctor1, "nn_boss", "__ct__Q3_2nn4boss4TaskFUcPCc", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::ctor2, "nn_boss", "__ct__Q3_2nn4boss4TaskFPCcUi", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::ctor3, "nn_boss", "__ct__Q3_2nn4boss4TaskFPCc", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::ctor4, "nn_boss", "__ct__Q3_2nn4boss4TaskFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::dtor, "nn_boss", "__dt__Q3_2nn4boss4TaskFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::Initialize1, "nn_boss", "Initialize__Q3_2nn4boss4TaskFPCcUi", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::Initialize2, "nn_boss", "Initialize__Q3_2nn4boss4TaskFUcPCc", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::Initialize3, "nn_boss", "Initialize__Q3_2nn4boss4TaskFPCc", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::Run, "nn_boss", "Run__Q3_2nn4boss4TaskFb", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::Wait, "nn_boss", "Wait__Q3_2nn4boss4TaskFUiQ3_2nn4boss13TaskWaitState", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::GetTurnState, "nn_boss", "GetTurnState__Q3_2nn4boss4TaskCFPUi", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::GetHttpStatusCode, "nn_boss", "GetHttpStatusCode__Q3_2nn4boss4TaskCFPUi", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::GetContentLength, "nn_boss", "GetContentLength__Q3_2nn4boss4TaskCFPUi", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::GetProcessedLength, "nn_boss", "GetProcessedLength__Q3_2nn4boss4TaskCFPUi", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::Register, "nn_boss", "Register__Q3_2nn4boss4TaskFRQ3_2nn4boss11TaskSetting", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::Unregister, "nn_boss", "Unregister__Q3_2nn4boss4TaskFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::IsRegistered, "nn_boss", "IsRegistered__Q3_2nn4boss4TaskCFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::RegisterForImmediateRun, "nn_boss", "RegisterForImmediateRun__Q3_2nn4boss4TaskFRCQ3_2nn4boss11TaskSetting", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::StartScheduling, "nn_boss", "StartScheduling__Q3_2nn4boss4TaskFb", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Task::StopScheduling, "nn_boss", "StopScheduling__Q3_2nn4boss4TaskFv", LogType::NN_BOSS);
// TaskSetting
nn::boss::TaskSetting::InitVTable();
cafeExportRegisterFunc(nn::boss::TaskSetting::ctor, "nn_boss", "__ct__Q3_2nn4boss11TaskSettingFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::TaskSetting::dtor, "nn_boss", "__dt__Q3_2nn4boss11TaskSettingFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::TaskSetting::IsPrivileged, "nn_boss", "Initialize__Q3_2nn4boss11TaskSettingFPCcUi", LogType::NN_BOSS);
// NbdlTaskSetting
nn::boss::NbdlTaskSetting::InitVTable();
cafeExportRegisterFunc(nn::boss::NbdlTaskSetting::ctor, "nn_boss", "__ct__Q3_2nn4boss15NbdlTaskSettingFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NbdlTaskSetting::dtor, "nn_boss", "__dt__Q3_2nn4boss15NbdlTaskSettingFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NbdlTaskSetting::Initialize, "nn_boss", "Initialize__Q3_2nn4boss15NbdlTaskSettingFPCcLT1", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NbdlTaskSetting::SetFileName, "nn_boss", "SetFileName__Q3_2nn4boss15NbdlTaskSettingFPCc", LogType::NN_BOSS);
// PlayReportSetting
nn::boss::PlayReportSetting::InitVTable();
cafeExportRegisterFunc(nn::boss::PlayReportSetting::ctor, "nn_boss", "__ct__Q3_2nn4boss17PlayReportSettingFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::PlayReportSetting::dtor, "nn_boss", "__dt__Q3_2nn4boss17PlayReportSettingFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::PlayReportSetting::Initialize, "nn_boss", "Initialize__Q3_2nn4boss17PlayReportSettingFPvUi", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::PlayReportSetting::Set, "nn_boss", "Set__Q3_2nn4boss17PlayReportSettingFPCcUi", LogType::NN_BOSS);
// RawDlTaskSetting
nn::boss::RawDlTaskSetting::InitVTable();
cafeExportRegisterFunc(nn::boss::RawDlTaskSetting::ctor, "nn_boss", "__ct__Q3_2nn4boss16RawDlTaskSettingFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::RawDlTaskSetting::dtor, "nn_boss", "__dt__Q3_2nn4boss16RawDlTaskSettingFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::RawDlTaskSetting::Initialize, "nn_boss", "Initialize__Q3_2nn4boss16RawDlTaskSettingFPCcbT2N21", LogType::NN_BOSS);
// NetTaskSetting
nn::boss::NetTaskSetting::InitVTable();
cafeExportRegisterFunc(nn::boss::NetTaskSetting::ctor, "nn_boss", "__ct__Q3_2nn4boss14NetTaskSettingFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NetTaskSetting::dtor, "nn_boss", "__dt__Q3_2nn4boss14NetTaskSettingFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NetTaskSetting::SetServiceToken, "nn_boss", "SetServiceToken__Q3_2nn4boss14NetTaskSettingFPCUc", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NetTaskSetting::AddInternalCaCert, "nn_boss", "AddInternalCaCert__Q3_2nn4boss14NetTaskSettingFSc", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NetTaskSetting::SetInternalClientCert, "nn_boss", "SetInternalClientCert__Q3_2nn4boss14NetTaskSettingFSc", LogType::NN_BOSS);
// Title
nn::boss::Title::InitVTable();
cafeExportRegisterFunc(nn::boss::Title::ctor, "nn_boss", "__ct__Q3_2nn4boss5TitleFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Title::dtor, "nn_boss", "__dt__Q3_2nn4boss5TitleFv", LogType::NN_BOSS);
// cafeExportMakeWrapper<nn::boss::Title::SetNewArrivalFlagOff>("nn_boss", "SetNewArrivalFlagOff__Q3_2nn4boss5TitleFv"); SMM bookmarks
// TitleId
cafeExportRegisterFunc(nn::boss::TitleId::ctor1, "nn_boss", "__ct__Q3_2nn4boss7TitleIDFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::TitleId::ctor2, "nn_boss", "__ct__Q3_2nn4boss7TitleIDFUL", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::TitleId::ctor3, "nn_boss", "__ct__Q3_2nn4boss7TitleIDFRCQ3_2nn4boss7TitleID", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::TitleId::operator_ne, "nn_boss", "__ne__Q3_2nn4boss7TitleIDCFRCQ3_2nn4boss7TitleID", LogType::NN_BOSS);
// DataName
cafeExportRegisterFunc(nn::boss::DataName::ctor, "nn_boss", "__ct__Q3_2nn4boss8DataNameFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::DataName::operator_const_char, "nn_boss", "__opPCc__Q3_2nn4boss8DataNameCFv", LogType::NN_BOSS);
// DirectoryName
cafeExportRegisterFunc(nn::boss::DirectoryName::ctor, "nn_boss", "__ct__Q3_2nn4boss13DirectoryNameFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::DirectoryName::operator_const_char, "nn_boss", "__opPCc__Q3_2nn4boss13DirectoryNameCFv", LogType::NN_BOSS);
// Account
nn::boss::BossAccount::InitVTable();
cafeExportRegisterFunc(nn::boss::BossAccount::ctor, "nn_boss", "__ct__Q3_2nn4boss7AccountFUi", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::BossAccount::dtor, "nn_boss", "__dt__Q3_2nn4boss7AccountFv", LogType::NN_BOSS);
// AlmightyTask
nn::boss::AlmightyTask::InitVTable();
cafeExportRegisterFunc(nn::boss::AlmightyTask::ctor, "nn_boss", "__ct__Q3_2nn4boss12AlmightyTaskFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::AlmightyTask::Initialize, "nn_boss", "Initialize__Q3_2nn4boss12AlmightyTaskFQ3_2nn4boss7TitleIDPCcUi", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::AlmightyTask::dtor, "nn_boss", "__dt__Q3_2nn4boss12AlmightyTaskFv", LogType::NN_BOSS);
// Storage
nn::boss::Storage::InitVTable();
cafeExportRegisterFunc(nn::boss::Storage::ctor1, "nn_boss", "__ct__Q3_2nn4boss7StorageFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Storage::dtor, "nn_boss", "__dt__Q3_2nn4boss7StorageFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Storage::Finalize, "nn_boss", "Finalize__Q3_2nn4boss7StorageFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Storage::Exist, "nn_boss", "Exist__Q3_2nn4boss7StorageCFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Storage::GetDataList, "nn_boss", "GetDataList__Q3_2nn4boss7StorageCFPQ3_2nn4boss8DataNameUiPUiT2", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Storage::Initialize, "nn_boss", "Initialize__Q3_2nn4boss7StorageFPCcUiQ3_2nn4boss11StorageKind", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::Storage::Initialize2, "nn_boss", "Initialize__Q3_2nn4boss7StorageFPCcQ3_2nn4boss11StorageKind", LogType::NN_BOSS);
// AlmightyStorage
nn::boss::AlmightyStorage::InitVTable();
cafeExportRegisterFunc(nn::boss::AlmightyStorage::ctor, "nn_boss", "__ct__Q3_2nn4boss15AlmightyStorageFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::AlmightyStorage::Initialize, "nn_boss", "Initialize__Q3_2nn4boss15AlmightyStorageFQ3_2nn4boss7TitleIDPCcUiQ3_2nn4boss11StorageKind", LogType::NN_BOSS);
// NsData
nn::boss::NsData::InitVTable();
cafeExportRegisterFunc(nn::boss::NsData::ctor, "nn_boss", "__ct__Q3_2nn4boss6NsDataFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NsData::dtor, "nn_boss", "__dt__Q3_2nn4boss6NsDataFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NsData::Initialize, "nn_boss", "Initialize__Q3_2nn4boss6NsDataFRCQ3_2nn4boss7StoragePCc", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NsData::DeleteRealFileWithHistory, "nn_boss", "DeleteRealFileWithHistory__Q3_2nn4boss6NsDataFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NsData::Exist, "nn_boss", "Exist__Q3_2nn4boss6NsDataCFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NsData::GetSize, "nn_boss", "GetSize__Q3_2nn4boss6NsDataCFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NsData::GetCreatedTime, "nn_boss", "GetCreatedTime__Q3_2nn4boss6NsDataCFv", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NsData::Read, "nn_boss", "Read__Q3_2nn4boss6NsDataFPvUi", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NsData::ReadWithSizeOut, "nn_boss", "Read__Q3_2nn4boss6NsDataFPLPvUi", LogType::NN_BOSS);
cafeExportRegisterFunc(nn::boss::NsData::Seek, "nn_boss", "Seek__Q3_2nn4boss6NsDataFLQ3_2nn4boss12PositionBase", LogType::NN_BOSS);
}
| 58,357
|
C++
|
.cpp
| 1,493
| 35.446082
| 244
| 0.719121
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,150
|
TagV0.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nfc/TagV0.cpp
|
#include "TagV0.h"
#include "TLV.h"
#include <algorithm>
namespace
{
constexpr std::size_t kTagSize = 512u;
constexpr std::size_t kMaxBlockCount = kTagSize / sizeof(TagV0::Block);
constexpr uint8 kLockbyteBlock0 = 0xe;
constexpr uint8 kLockbytesStart0 = 0x0;
constexpr uint8 kLockbytesEnd0 = 0x2;
constexpr uint8 kLockbyteBlock1 = 0xf;
constexpr uint8 kLockbytesStart1 = 0x2;
constexpr uint8 kLockbytesEnd1 = 0x8;
constexpr uint8 kNDEFMagicNumber = 0xe1;
// These blocks are not part of the locked area
constexpr bool IsBlockLockedOrReserved(uint8 blockIdx)
{
// Block 0 is the UID
if (blockIdx == 0x0)
{
return true;
}
// Block 0xd is reserved
if (blockIdx == 0xd)
{
return true;
}
// Block 0xe and 0xf contains lock / reserved bytes
if (blockIdx == 0xe || blockIdx == 0xf)
{
return true;
}
return false;
}
} // namespace
TagV0::TagV0()
{
}
TagV0::~TagV0()
{
}
std::shared_ptr<TagV0> TagV0::FromBytes(const std::span<const std::byte>& data)
{
// Version 0 tags need at least 512 bytes
if (data.size() != kTagSize)
{
cemuLog_log(LogType::Force, "Error: Version 0 tags should be {} bytes in size", kTagSize);
return {};
}
std::shared_ptr<TagV0> tag = std::make_shared<TagV0>();
// Parse the locked area before continuing
if (!tag->ParseLockedArea(data))
{
cemuLog_log(LogType::Force, "Error: Failed to parse locked area");
return {};
}
// Now that the locked area is known, parse the data area
std::vector<std::byte> dataArea;
if (!tag->ParseDataArea(data, dataArea))
{
cemuLog_log(LogType::Force, "Error: Failed to parse data area");
return {};
}
// The first few bytes in the dataArea make up the capability container
std::copy_n(dataArea.begin(), tag->mCapabilityContainer.size(), std::as_writable_bytes(std::span(tag->mCapabilityContainer)).begin());
if (!tag->ValidateCapabilityContainer())
{
cemuLog_log(LogType::Force, "Error: Failed to validate capability container");
return {};
}
// The rest of the dataArea contains the TLVs
tag->mTLVs = TLV::FromBytes(std::span(dataArea).subspan(tag->mCapabilityContainer.size()));
if (tag->mTLVs.empty())
{
cemuLog_log(LogType::Force, "Error: Tag contains no TLVs");
return {};
}
// Look for the NDEF tlv
tag->mNdefTlvIdx = static_cast<size_t>(-1);
for (std::size_t i = 0; i < tag->mTLVs.size(); i++)
{
if (tag->mTLVs[i].GetTag() == TLV::TAG_NDEF)
{
tag->mNdefTlvIdx = i;
break;
}
}
if (tag->mNdefTlvIdx == static_cast<size_t>(-1))
{
cemuLog_log(LogType::Force, "Error: Tag contains no NDEF TLV");
return {};
}
// Append locked data
for (const auto& [key, value] : tag->mLockedBlocks)
{
tag->mLockedArea.insert(tag->mLockedArea.end(), value.begin(), value.end());
}
return tag;
}
std::vector<std::byte> TagV0::ToBytes() const
{
std::vector<std::byte> bytes(kTagSize);
// Insert locked or reserved blocks
for (const auto& [key, value] : mLockedOrReservedBlocks)
{
std::copy(value.begin(), value.end(), bytes.begin() + key * sizeof(Block));
}
// Insert locked area
auto lockedDataIterator = mLockedArea.begin();
for (const auto& [key, value] : mLockedBlocks)
{
std::copy_n(lockedDataIterator, sizeof(Block), bytes.begin() + key * sizeof(Block));
lockedDataIterator += sizeof(Block);
}
// Pack the dataArea into a linear buffer
std::vector<std::byte> dataArea;
const auto ccBytes = std::as_bytes(std::span(mCapabilityContainer));
dataArea.insert(dataArea.end(), ccBytes.begin(), ccBytes.end());
for (const TLV& tlv : mTLVs)
{
const auto tlvBytes = tlv.ToBytes();
dataArea.insert(dataArea.end(), tlvBytes.begin(), tlvBytes.end());
}
// Make sure the dataArea is block size aligned
dataArea.resize((dataArea.size() + (sizeof(Block)-1)) & ~(sizeof(Block)-1));
// The rest will be the data area
auto dataIterator = dataArea.begin();
for (uint8 currentBlock = 0; currentBlock < kMaxBlockCount; currentBlock++)
{
// All blocks which aren't locked make up the dataArea
if (!IsBlockLocked(currentBlock))
{
std::copy_n(dataIterator, sizeof(Block), bytes.begin() + currentBlock * sizeof(Block));
dataIterator += sizeof(Block);
}
}
return bytes;
}
const TagV0::Block& TagV0::GetUIDBlock() const
{
return mLockedOrReservedBlocks.at(0);
}
const std::vector<std::byte>& TagV0::GetNDEFData() const
{
return mTLVs[mNdefTlvIdx].GetValue();
}
const std::vector<std::byte>& TagV0::GetLockedArea() const
{
return mLockedArea;
}
void TagV0::SetNDEFData(const std::span<const std::byte>& data)
{
// Update the ndef value
mTLVs[mNdefTlvIdx].SetValue(data);
}
bool TagV0::ParseLockedArea(const std::span<const std::byte>& data)
{
uint8 currentBlock = 0;
// Start by parsing the first set of lock bytes
for (uint8 i = kLockbytesStart0; i < kLockbytesEnd0; i++)
{
uint8 lockByte = uint8(data[kLockbyteBlock0 * sizeof(Block) + i]);
// Iterate over the individual bits in the lock byte
for (uint8 j = 0; j < 8; j++)
{
// Is block locked?
if (lockByte & (1u << j))
{
Block blk;
std::copy_n(data.begin() + currentBlock * sizeof(Block), sizeof(Block), blk.begin());
// The lock bytes themselves are not part of the locked area
if (!IsBlockLockedOrReserved(currentBlock))
{
mLockedBlocks.emplace(currentBlock, blk);
}
else
{
mLockedOrReservedBlocks.emplace(currentBlock, blk);
}
}
currentBlock++;
}
}
// Parse the second set of lock bytes
for (uint8 i = kLockbytesStart1; i < kLockbytesEnd1; i++) {
uint8 lockByte = uint8(data[kLockbyteBlock1 * sizeof(Block) + i]);
// Iterate over the individual bits in the lock byte
for (uint8 j = 0; j < 8; j++)
{
// Is block locked?
if (lockByte & (1u << j))
{
Block blk;
std::copy_n(data.begin() + currentBlock * sizeof(Block), sizeof(Block), blk.begin());
// The lock bytes themselves are not part of the locked area
if (!IsBlockLockedOrReserved(currentBlock))
{
mLockedBlocks.emplace(currentBlock, blk);
}
else
{
mLockedOrReservedBlocks.emplace(currentBlock, blk);
}
}
currentBlock++;
}
}
return true;
}
bool TagV0::IsBlockLocked(uint8 blockIdx) const
{
return mLockedBlocks.contains(blockIdx) || IsBlockLockedOrReserved(blockIdx);
}
bool TagV0::ParseDataArea(const std::span<const std::byte>& data, std::vector<std::byte>& dataArea)
{
for (uint8 currentBlock = 0; currentBlock < kMaxBlockCount; currentBlock++)
{
// All blocks which aren't locked make up the dataArea
if (!IsBlockLocked(currentBlock))
{
auto blockOffset = data.begin() + sizeof(Block) * currentBlock;
dataArea.insert(dataArea.end(), blockOffset, blockOffset + sizeof(Block));
}
}
return true;
}
bool TagV0::ValidateCapabilityContainer()
{
// NDEF Magic Number
uint8 nmn = mCapabilityContainer[0];
if (nmn != kNDEFMagicNumber)
{
cemuLog_log(LogType::Force, "Error: CC: Invalid NDEF Magic Number");
return false;
}
// Version Number
uint8 vno = mCapabilityContainer[1];
if (vno >> 4 != 1)
{
cemuLog_log(LogType::Force, "Error: CC: Invalid Version Number");
return false;
}
// Tag memory size
uint8 tms = mCapabilityContainer[2];
if (8u * (tms + 1) < kTagSize)
{
cemuLog_log(LogType::Force, "Error: CC: Incomplete tag memory size");
return false;
}
return true;
}
| 7,277
|
C++
|
.cpp
| 251
| 26.414343
| 135
| 0.708429
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,151
|
stream.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nfc/stream.cpp
|
#include "stream.h"
#include <algorithm>
Stream::Stream(std::endian endianness)
: mError(ERROR_OK), mEndianness(endianness)
{
}
Stream::~Stream()
{
}
Stream::Error Stream::GetError() const
{
return mError;
}
void Stream::SetEndianness(std::endian endianness)
{
mEndianness = endianness;
}
std::endian Stream::GetEndianness() const
{
return mEndianness;
}
Stream& Stream::operator>>(bool& val)
{
uint8 i;
*this >> i;
val = !!i;
return *this;
}
Stream& Stream::operator>>(float& val)
{
uint32 i;
*this >> i;
val = std::bit_cast<float>(i);
return *this;
}
Stream& Stream::operator>>(double& val)
{
uint64 i;
*this >> i;
val = std::bit_cast<double>(i);
return *this;
}
Stream& Stream::operator<<(bool val)
{
uint8 i = val;
*this >> i;
return *this;
}
Stream& Stream::operator<<(float val)
{
uint32 i = std::bit_cast<uint32>(val);
*this >> i;
return *this;
}
Stream& Stream::operator<<(double val)
{
uint64 i = std::bit_cast<uint64>(val);
*this >> i;
return *this;
}
void Stream::SetError(Error error)
{
mError = error;
}
bool Stream::NeedsSwap()
{
return mEndianness != std::endian::native;
}
VectorStream::VectorStream(std::vector<std::byte>& vector, std::endian endianness)
: Stream(endianness), mVector(vector), mPosition(0)
{
}
VectorStream::~VectorStream()
{
}
std::size_t VectorStream::Read(const std::span<std::byte>& data)
{
if (data.size() > GetRemaining())
{
SetError(ERROR_READ_FAILED);
std::fill(data.begin(), data.end(), std::byte(0));
return 0;
}
std::copy_n(mVector.get().begin() + mPosition, data.size(), data.begin());
mPosition += data.size();
return data.size();
}
std::size_t VectorStream::Write(const std::span<const std::byte>& data)
{
// Resize vector if not enough bytes remain
if (mPosition + data.size() > mVector.get().size())
{
mVector.get().resize(mPosition + data.size());
}
std::copy(data.begin(), data.end(), mVector.get().begin() + mPosition);
mPosition += data.size();
return data.size();
}
bool VectorStream::SetPosition(std::size_t position)
{
if (position >= mVector.get().size())
{
return false;
}
mPosition = position;
return true;
}
std::size_t VectorStream::GetPosition() const
{
return mPosition;
}
std::size_t VectorStream::GetRemaining() const
{
return mVector.get().size() - mPosition;
}
SpanStream::SpanStream(std::span<const std::byte> span, std::endian endianness)
: Stream(endianness), mSpan(std::move(span)), mPosition(0)
{
}
SpanStream::~SpanStream()
{
}
std::size_t SpanStream::Read(const std::span<std::byte>& data)
{
if (data.size() > GetRemaining())
{
SetError(ERROR_READ_FAILED);
std::fill(data.begin(), data.end(), std::byte(0));
return 0;
}
std::copy_n(mSpan.begin() + mPosition, data.size(), data.begin());
mPosition += data.size();
return data.size();
}
std::size_t SpanStream::Write(const std::span<const std::byte>& data)
{
// Cannot write to const span
SetError(ERROR_WRITE_FAILED);
return 0;
}
bool SpanStream::SetPosition(std::size_t position)
{
if (position >= mSpan.size())
{
return false;
}
mPosition = position;
return true;
}
std::size_t SpanStream::GetPosition() const
{
return mPosition;
}
std::size_t SpanStream::GetRemaining() const
{
if (mPosition > mSpan.size())
{
return 0;
}
return mSpan.size() - mPosition;
}
| 3,312
|
C++
|
.cpp
| 161
| 18.776398
| 82
| 0.703632
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,152
|
nfc.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nfc/nfc.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/libs/nfc/nfc.h"
#include "Cafe/OS/libs/nn_nfp/nn_nfp.h"
#include "Common/FileStream.h"
#include "TagV0.h"
#include "ndef.h"
#define NFC_MODE_INVALID -1
#define NFC_MODE_IDLE 0
#define NFC_MODE_ACTIVE 1
#define NFC_STATE_UNINITIALIZED 0x0
#define NFC_STATE_INITIALIZED 0x1
#define NFC_STATE_IDLE 0x2
#define NFC_STATE_READ 0x3
#define NFC_STATE_WRITE 0x4
#define NFC_STATE_ABORT 0x5
#define NFC_STATE_FORMAT 0x6
#define NFC_STATE_SET_READ_ONLY 0x7
#define NFC_STATE_TAG_PRESENT 0x8
#define NFC_STATE_DETECT 0x9
#define NFC_STATE_SEND_RAW_DATA 0xA
#define NFC_STATUS_COMMAND_COMPLETE 0x1
#define NFC_STATUS_READY 0x2
#define NFC_STATUS_HAS_TAG 0x4
namespace nfc
{
struct NFCContext
{
bool isInitialized;
uint32 state;
sint32 mode;
bool hasTag;
uint32 nfcStatus;
std::chrono::time_point<std::chrono::system_clock> touchTime;
std::chrono::time_point<std::chrono::system_clock> discoveryTimeout;
struct {
NFCUid uid;
NFCUid mask;
} filter;
MPTR tagDetectCallback;
void* tagDetectContext;
MPTR abortCallback;
void* abortContext;
MPTR rawCallback;
void* rawContext;
MPTR readCallback;
void* readContext;
MPTR writeCallback;
void* writeContext;
MPTR getTagInfoCallback;
SysAllocator<NFCTagInfo> tagInfo;
fs::path tagPath;
std::shared_ptr<TagV0> tag;
ndef::Message writeMessage;
};
NFCContext gNFCContexts[2];
sint32 NFCInit(uint32 chan)
{
return NFCInitEx(chan, 0);
}
void __NFCClearContext(NFCContext* context)
{
context->isInitialized = false;
context->state = NFC_STATE_UNINITIALIZED;
context->mode = NFC_MODE_IDLE;
context->hasTag = false;
context->nfcStatus = NFC_STATUS_READY;
context->discoveryTimeout = {};
context->tagDetectCallback = MPTR_NULL;
context->tagDetectContext = nullptr;
context->abortCallback = MPTR_NULL;
context->abortContext = nullptr;
context->rawCallback = MPTR_NULL;
context->rawContext = nullptr;
context->readCallback = MPTR_NULL;
context->readContext = nullptr;
context->writeCallback = MPTR_NULL;
context->writeContext = nullptr;
context->tagPath = "";
context->tag = {};
}
sint32 NFCInitEx(uint32 chan, uint32 powerMode)
{
cemu_assert(chan < 2);
NFCContext* ctx = &gNFCContexts[chan];
__NFCClearContext(ctx);
ctx->isInitialized = true;
ctx->state = NFC_STATE_INITIALIZED;
return NFC_RESULT_SUCCESS;
}
sint32 NFCShutdown(uint32 chan)
{
cemu_assert(chan < 2);
NFCContext* ctx = &gNFCContexts[chan];
__NFCClearContext(ctx);
return NFC_RESULT_SUCCESS;
}
bool NFCIsInit(uint32 chan)
{
cemu_assert(chan < 2);
return gNFCContexts[chan].isInitialized;
}
bool __NFCCompareUid(NFCUid* uid, NFCUid* filterUid, NFCUid* filterMask)
{
for (int i = 0; i < sizeof(uid->uid); i++)
{
if ((uid->uid[i] & filterMask->uid[i]) != filterUid->uid[i])
{
return false;
}
}
return true;
}
void __NFCHandleRead(uint32 chan)
{
NFCContext* ctx = &gNFCContexts[chan];
ctx->state = NFC_STATE_IDLE;
sint32 result;
StackAllocator<NFCUid> uid;
bool readOnly = false;
uint32 dataSize = 0;
StackAllocator<uint8, 0x200> data;
uint32 lockedDataSize = 0;
StackAllocator<uint8, 0x200> lockedData;
if (ctx->tag)
{
// Compare UID
memcpy(uid.GetPointer(), ctx->tag->GetUIDBlock().data(), sizeof(NFCUid));
if (__NFCCompareUid(uid.GetPointer(), &ctx->filter.uid, &ctx->filter.mask))
{
// Try to parse ndef message
auto ndefMsg = ndef::Message::FromBytes(ctx->tag->GetNDEFData());
if (ndefMsg)
{
// Look for the unknown TNF which contains the data we care about
for (const auto& rec : *ndefMsg)
{
if (rec.GetTNF() == ndef::Record::NDEF_TNF_UNKNOWN)
{
dataSize = rec.GetPayload().size();
cemu_assert(dataSize < 0x200);
memcpy(data.GetPointer(), rec.GetPayload().data(), dataSize);
break;
}
}
if (dataSize)
{
// Get locked data
lockedDataSize = ctx->tag->GetLockedArea().size();
memcpy(lockedData.GetPointer(), ctx->tag->GetLockedArea().data(), lockedDataSize);
result = NFC_RESULT_SUCCESS;
}
else
{
result = NFC_MAKE_RESULT(NFC_RESULT_BASE_TAG_PARSE, NFC_RESULT_INVALID_TAG);
}
}
else
{
result = NFC_MAKE_RESULT(NFC_RESULT_BASE_TAG_PARSE, NFC_RESULT_INVALID_TAG);
}
}
else
{
result = NFC_MAKE_RESULT(NFC_RESULT_BASE_READ, NFC_RESULT_UID_MISMATCH);
}
}
else
{
result = NFC_MAKE_RESULT(NFC_RESULT_BASE_READ, NFC_RESULT_NO_TAG);
}
PPCCoreCallback(ctx->readCallback, chan, result, uid.GetPointer(), readOnly, dataSize, data.GetPointer(), lockedDataSize, lockedData.GetPointer(), ctx->readContext);
}
void __NFCHandleWrite(uint32 chan)
{
NFCContext* ctx = &gNFCContexts[chan];
ctx->state = NFC_STATE_IDLE;
sint32 result;
if (ctx->tag)
{
NFCUid uid;
memcpy(&uid, ctx->tag->GetUIDBlock().data(), sizeof(NFCUid));
if (__NFCCompareUid(&uid, &ctx->filter.uid, &ctx->filter.mask))
{
// Update tag NDEF data
ctx->tag->SetNDEFData(ctx->writeMessage.ToBytes());
// open file for writing
FileStream* fs = FileStream::openFile2(ctx->tagPath, true);
if (!fs)
{
result = NFC_MAKE_RESULT(NFC_RESULT_BASE_WRITE, 0x22);
}
else
{
auto tagBytes = ctx->tag->ToBytes();
fs->writeData(tagBytes.data(), tagBytes.size());
delete fs;
result = NFC_RESULT_SUCCESS;
}
}
else
{
result = NFC_MAKE_RESULT(NFC_RESULT_BASE_WRITE, NFC_RESULT_UID_MISMATCH);
}
}
else
{
result = NFC_MAKE_RESULT(NFC_RESULT_BASE_WRITE, NFC_RESULT_NO_TAG);
}
PPCCoreCallback(ctx->writeCallback, chan, result, ctx->writeContext);
}
void __NFCHandleAbort(uint32 chan)
{
NFCContext* ctx = &gNFCContexts[chan];
ctx->state = NFC_STATE_IDLE;
PPCCoreCallback(ctx->abortCallback, chan, 0, ctx->abortContext);
}
void __NFCHandleRaw(uint32 chan)
{
NFCContext* ctx = &gNFCContexts[chan];
ctx->state = NFC_STATE_IDLE;
sint32 result;
if (ctx->nfcStatus & NFC_STATUS_HAS_TAG)
{
result = NFC_RESULT_SUCCESS;
}
else
{
result = NFC_MAKE_RESULT(NFC_RESULT_BASE_SEND_RAW_DATA, NFC_RESULT_NO_TAG);
}
// We don't actually send any commands/responses
uint32 responseSize = 0;
void* responseData = nullptr;
PPCCoreCallback(ctx->rawCallback, chan, result, responseSize, responseData, ctx->rawContext);
}
bool __NFCShouldHandleState(NFCContext* ctx)
{
// Always handle abort
if (ctx->state == NFC_STATE_ABORT)
{
return true;
}
// Do we have a tag?
if (ctx->nfcStatus & NFC_STATUS_HAS_TAG)
{
return true;
}
// Did the timeout expire?
if (ctx->discoveryTimeout < std::chrono::system_clock::now())
{
return true;
}
return false;
}
void NFCProc(uint32 chan)
{
cemu_assert(chan < 2);
NFCContext* ctx = &gNFCContexts[chan];
if (!ctx->isInitialized)
{
return;
}
if (ctx->state == NFC_STATE_INITIALIZED)
{
ctx->state = NFC_STATE_IDLE;
}
// Check if the detect callback should be called
if (ctx->nfcStatus & NFC_STATUS_HAS_TAG)
{
if (!ctx->hasTag && ctx->state > NFC_STATE_IDLE && ctx->state != NFC_STATE_ABORT)
{
if (ctx->tagDetectCallback)
{
PPCCoreCallback(ctx->tagDetectCallback, chan, true, ctx->tagDetectContext);
}
ctx->hasTag = true;
}
// Check if the tag should be removed again
if (ctx->touchTime + std::chrono::seconds(2) < std::chrono::system_clock::now())
{
ctx->nfcStatus &= ~NFC_STATUS_HAS_TAG;
ctx->tag = {};
ctx->tagPath = "";
}
}
else
{
if (ctx->hasTag && ctx->state == NFC_STATE_IDLE)
{
if (ctx->tagDetectCallback)
{
PPCCoreCallback(ctx->tagDetectCallback, chan, false, ctx->tagDetectContext);
}
ctx->hasTag = false;
}
}
if (__NFCShouldHandleState(ctx))
{
switch (ctx->state)
{
case NFC_STATE_READ:
__NFCHandleRead(chan);
break;
case NFC_STATE_WRITE:
__NFCHandleWrite(chan);
break;
case NFC_STATE_ABORT:
__NFCHandleAbort(chan);
break;
case NFC_STATE_SEND_RAW_DATA:
__NFCHandleRaw(chan);
break;
default:
break;
}
// Return back to idle mode
ctx->mode = NFC_MODE_IDLE;
}
}
sint32 NFCGetMode(uint32 chan)
{
cemu_assert(chan < 2);
NFCContext* ctx = &gNFCContexts[chan];
if (!NFCIsInit(chan) || ctx->state == NFC_STATE_UNINITIALIZED)
{
return NFC_MODE_INVALID;
}
return ctx->mode;
}
sint32 NFCSetMode(uint32 chan, sint32 mode)
{
cemu_assert(chan < 2);
NFCContext* ctx = &gNFCContexts[chan];
if (!NFCIsInit(chan))
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_SET_MODE, NFC_RESULT_UNINITIALIZED);
}
if (ctx->state == NFC_STATE_UNINITIALIZED)
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_SET_MODE, NFC_RESULT_INVALID_STATE);
}
ctx->mode = mode;
return NFC_RESULT_SUCCESS;
}
void NFCSetTagDetectCallback(uint32 chan, MPTR callback, void* context)
{
cemu_assert(chan < 2);
NFCContext* ctx = &gNFCContexts[chan];
ctx->tagDetectCallback = callback;
ctx->tagDetectContext = context;
}
sint32 NFCAbort(uint32 chan, MPTR callback, void* context)
{
cemu_assert(chan < 2);
NFCContext* ctx = &gNFCContexts[chan];
if (!NFCIsInit(chan))
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_ABORT, NFC_RESULT_UNINITIALIZED);
}
if (ctx->state <= NFC_STATE_IDLE)
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_ABORT, NFC_RESULT_INVALID_STATE);
}
ctx->state = NFC_STATE_ABORT;
ctx->abortCallback = callback;
ctx->abortContext = context;
return NFC_RESULT_SUCCESS;
}
sint32 __NFCConvertGetTagInfoResult(sint32 result)
{
if (result == NFC_MAKE_RESULT(NFC_RESULT_BASE_SEND_RAW_DATA, NFC_RESULT_NO_TAG))
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_GET_TAG_INFO, NFC_RESULT_TAG_INFO_TIMEOUT);
}
// TODO convert the rest of the results
return result;
}
void __NFCGetTagInfoCallback(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(chan, 0);
ppcDefineParamS32(error, 1);
ppcDefineParamU32(responseSize, 2);
ppcDefineParamPtr(responseData, void, 3);
ppcDefineParamPtr(context, void, 4);
NFCContext* ctx = &gNFCContexts[chan];
error = __NFCConvertGetTagInfoResult(error);
if (error == 0 && ctx->tag)
{
// this is usually parsed from response data
ctx->tagInfo->uidSize = sizeof(NFCUid);
memcpy(ctx->tagInfo->uid, ctx->tag->GetUIDBlock().data(), ctx->tagInfo->uidSize);
ctx->tagInfo->technology = NFC_TECHNOLOGY_A;
ctx->tagInfo->protocol = NFC_PROTOCOL_T1T;
}
PPCCoreCallback(ctx->getTagInfoCallback, chan, error, ctx->tagInfo.GetPtr(), context);
osLib_returnFromFunction(hCPU, 0);
}
sint32 NFCGetTagInfo(uint32 chan, uint32 discoveryTimeout, MPTR callback, void* context)
{
cemu_assert(chan < 2);
// Forward this request to nn_nfp, if the title initialized it
// TODO integrate nn_nfp/ntag/nfc
if (nnNfp_isInitialized())
{
return nn::nfp::NFCGetTagInfo(chan, discoveryTimeout, callback, context);
}
NFCContext* ctx = &gNFCContexts[chan];
ctx->getTagInfoCallback = callback;
sint32 result = NFCSendRawData(chan, true, discoveryTimeout, 1000U, 0, 0, nullptr, RPLLoader_MakePPCCallable(__NFCGetTagInfoCallback), context);
return __NFCConvertGetTagInfoResult(result);
}
sint32 NFCSendRawData(uint32 chan, bool startDiscovery, uint32 discoveryTimeout, uint32 commandTimeout, uint32 commandSize, uint32 responseSize, void* commandData, MPTR callback, void* context)
{
cemu_assert(chan < 2);
NFCContext* ctx = &gNFCContexts[chan];
if (!NFCIsInit(chan))
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_SEND_RAW_DATA, NFC_RESULT_UNINITIALIZED);
}
// Only allow discovery
if (!startDiscovery)
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_SEND_RAW_DATA, NFC_RESULT_INVALID_MODE);
}
if (NFCGetMode(chan) == NFC_MODE_ACTIVE && NFCSetMode(chan, NFC_MODE_IDLE) < 0)
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_SEND_RAW_DATA, NFC_RESULT_INVALID_MODE);
}
if (ctx->state != NFC_STATE_IDLE)
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_SEND_RAW_DATA, NFC_RESULT_INVALID_STATE);
}
ctx->state = NFC_STATE_SEND_RAW_DATA;
ctx->rawCallback = callback;
ctx->rawContext = context;
// If the discoveryTimeout is 0, no timeout
if (discoveryTimeout == 0)
{
ctx->discoveryTimeout = std::chrono::time_point<std::chrono::system_clock>::max();
}
else
{
ctx->discoveryTimeout = std::chrono::system_clock::now() + std::chrono::milliseconds(discoveryTimeout);
}
return NFC_RESULT_SUCCESS;
}
sint32 NFCRead(uint32 chan, uint32 discoveryTimeout, NFCUid* uid, NFCUid* uidMask, MPTR callback, void* context)
{
cemu_assert(chan < 2);
NFCContext* ctx = &gNFCContexts[chan];
if (!NFCIsInit(chan))
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_READ, NFC_RESULT_UNINITIALIZED);
}
if (NFCGetMode(chan) == NFC_MODE_ACTIVE && NFCSetMode(chan, NFC_MODE_IDLE) < 0)
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_READ, NFC_RESULT_INVALID_MODE);
}
if (ctx->state != NFC_STATE_IDLE)
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_READ, NFC_RESULT_INVALID_STATE);
}
ctx->state = NFC_STATE_READ;
ctx->readCallback = callback;
ctx->readContext = context;
// If the discoveryTimeout is 0, no timeout
if (discoveryTimeout == 0)
{
ctx->discoveryTimeout = std::chrono::time_point<std::chrono::system_clock>::max();
}
else
{
ctx->discoveryTimeout = std::chrono::system_clock::now() + std::chrono::milliseconds(discoveryTimeout);
}
memcpy(&ctx->filter.uid, uid, sizeof(*uid));
memcpy(&ctx->filter.mask, uidMask, sizeof(*uidMask));
return NFC_RESULT_SUCCESS;
}
sint32 NFCWrite(uint32 chan, uint32 discoveryTimeout, NFCUid* uid, NFCUid* uidMask, uint32 size, void* data, MPTR callback, void* context)
{
cemu_assert(chan < 2);
NFCContext* ctx = &gNFCContexts[chan];
if (!NFCIsInit(chan))
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_WRITE, NFC_RESULT_UNINITIALIZED);
}
if (NFCGetMode(chan) == NFC_MODE_ACTIVE && NFCSetMode(chan, NFC_MODE_IDLE) < 0)
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_WRITE, NFC_RESULT_INVALID_MODE);
}
if (ctx->state != NFC_STATE_IDLE)
{
return NFC_MAKE_RESULT(NFC_RESULT_BASE_WRITE, NFC_RESULT_INVALID_STATE);
}
// Create unknown record which contains the rw area
ndef::Record rec;
rec.SetTNF(ndef::Record::NDEF_TNF_UNKNOWN);
rec.SetPayload(std::span(reinterpret_cast<std::byte*>(data), size));
// Create ndef message which contains the record
ndef::Message msg;
msg.append(rec);
ctx->writeMessage = msg;
ctx->state = NFC_STATE_WRITE;
ctx->writeCallback = callback;
ctx->writeContext = context;
// If the discoveryTimeout is 0, no timeout
if (discoveryTimeout == 0)
{
ctx->discoveryTimeout = std::chrono::time_point<std::chrono::system_clock>::max();
}
else
{
ctx->discoveryTimeout = std::chrono::system_clock::now() + std::chrono::milliseconds(discoveryTimeout);
}
memcpy(&ctx->filter.uid, uid, sizeof(*uid));
memcpy(&ctx->filter.mask, uidMask, sizeof(*uidMask));
return NFC_RESULT_SUCCESS;
}
void Initialize()
{
cafeExportRegister("nfc", NFCInit, LogType::NFC);
cafeExportRegister("nfc", NFCInitEx, LogType::NFC);
cafeExportRegister("nfc", NFCShutdown, LogType::NFC);
cafeExportRegister("nfc", NFCIsInit, LogType::NFC);
cafeExportRegister("nfc", NFCProc, LogType::NFC);
cafeExportRegister("nfc", NFCGetMode, LogType::NFC);
cafeExportRegister("nfc", NFCSetMode, LogType::NFC);
cafeExportRegister("nfc", NFCSetTagDetectCallback, LogType::NFC);
cafeExportRegister("nfc", NFCGetTagInfo, LogType::NFC);
cafeExportRegister("nfc", NFCSendRawData, LogType::NFC);
cafeExportRegister("nfc", NFCAbort, LogType::NFC);
cafeExportRegister("nfc", NFCRead, LogType::NFC);
cafeExportRegister("nfc", NFCWrite, LogType::NFC);
}
bool TouchTagFromFile(const fs::path& filePath, uint32* nfcError)
{
// Forward this request to nn_nfp, if the title initialized it
// TODO integrate nn_nfp/ntag/nfc
if (nnNfp_isInitialized())
{
return nnNfp_touchNfcTagFromFile(filePath, nfcError);
}
NFCContext* ctx = &gNFCContexts[0];
auto nfcData = FileStream::LoadIntoMemory(filePath);
if (!nfcData)
{
*nfcError = NFC_TOUCH_TAG_ERROR_NO_ACCESS;
return false;
}
ctx->tag = TagV0::FromBytes(std::as_bytes(std::span(nfcData->data(), nfcData->size())));
if (!ctx->tag)
{
*nfcError = NFC_TOUCH_TAG_ERROR_INVALID_FILE_FORMAT;
return false;
}
ctx->nfcStatus |= NFC_STATUS_HAS_TAG;
ctx->tagPath = filePath;
ctx->touchTime = std::chrono::system_clock::now();
*nfcError = NFC_TOUCH_TAG_ERROR_NONE;
return true;
}
}
| 16,734
|
C++
|
.cpp
| 562
| 26.274021
| 194
| 0.703316
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,153
|
ndef.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nfc/ndef.cpp
|
#include "ndef.h"
#include <cassert>
namespace ndef
{
Record::Record()
: mFlags(0), mTNF(NDEF_TNF_EMPTY)
{
}
Record::~Record()
{
}
std::optional<Record> Record::FromStream(Stream& stream)
{
Record rec;
// Read record header
uint8 recHdr;
stream >> recHdr;
rec.mFlags = recHdr & ~NDEF_TNF_MASK;
rec.mTNF = static_cast<TypeNameFormat>(recHdr & NDEF_TNF_MASK);
// Type length
uint8 typeLen;
stream >> typeLen;
// Payload length;
uint32 payloadLen;
if (recHdr & NDEF_SR)
{
uint8 len;
stream >> len;
payloadLen = len;
}
else
{
stream >> payloadLen;
}
// Some sane limits for the payload size
if (payloadLen > 2 * 1024 * 1024)
{
return {};
}
// ID length
uint8 idLen = 0;
if (recHdr & NDEF_IL)
{
stream >> idLen;
}
// Make sure we didn't read past the end of the stream yet
if (stream.GetError() != Stream::ERROR_OK)
{
return {};
}
// Type
rec.mType.resize(typeLen);
stream.Read(rec.mType);
// ID
rec.mID.resize(idLen);
stream.Read(rec.mID);
// Payload
rec.mPayload.resize(payloadLen);
stream.Read(rec.mPayload);
// Make sure we didn't read past the end of the stream again
if (stream.GetError() != Stream::ERROR_OK)
{
return {};
}
return rec;
}
std::vector<std::byte> Record::ToBytes(uint8 flags) const
{
std::vector<std::byte> bytes;
VectorStream stream(bytes, std::endian::big);
// Combine flags (clear message begin and end flags)
uint8 finalFlags = mFlags & ~(NDEF_MB | NDEF_ME);
finalFlags |= flags;
// Write flags + tnf
stream << uint8(finalFlags | uint8(mTNF));
// Type length
stream << uint8(mType.size());
// Payload length
if (IsShort())
{
stream << uint8(mPayload.size());
}
else
{
stream << uint32(mPayload.size());
}
// ID length
if (mFlags & NDEF_IL)
{
stream << uint8(mID.size());
}
// Type
stream.Write(mType);
// ID
stream.Write(mID);
// Payload
stream.Write(mPayload);
return bytes;
}
Record::TypeNameFormat Record::GetTNF() const
{
return mTNF;
}
const std::vector<std::byte>& Record::GetID() const
{
return mID;
}
const std::vector<std::byte>& Record::GetType() const
{
return mType;
}
const std::vector<std::byte>& Record::GetPayload() const
{
return mPayload;
}
void Record::SetTNF(TypeNameFormat tnf)
{
mTNF = tnf;
}
void Record::SetID(const std::span<const std::byte>& id)
{
cemu_assert(id.size() < 0x100);
if (id.size() > 0)
{
mFlags |= NDEF_IL;
}
else
{
mFlags &= ~NDEF_IL;
}
mID.assign(id.begin(), id.end());
}
void Record::SetType(const std::span<const std::byte>& type)
{
cemu_assert(type.size() < 0x100);
mType.assign(type.begin(), type.end());
}
void Record::SetPayload(const std::span<const std::byte>& payload)
{
// Update short record flag
if (payload.size() < 0xff)
{
mFlags |= NDEF_SR;
}
else
{
mFlags &= ~NDEF_SR;
}
mPayload.assign(payload.begin(), payload.end());
}
bool Record::IsLast() const
{
return mFlags & NDEF_ME;
}
bool Record::IsShort() const
{
return mFlags & NDEF_SR;
}
Message::Message()
{
}
Message::~Message()
{
}
std::optional<Message> Message::FromBytes(const std::span<const std::byte>& data)
{
Message msg;
SpanStream stream(data, std::endian::big);
while (stream.GetRemaining() > 0)
{
std::optional<Record> rec = Record::FromStream(stream);
if (!rec)
{
cemuLog_log(LogType::Force, "Warning: Failed to parse NDEF Record #{}."
"Ignoring the remaining {} bytes in NDEF message", msg.mRecords.size(), stream.GetRemaining());
break;
}
msg.mRecords.emplace_back(*rec);
if ((*rec).IsLast() && stream.GetRemaining() > 0)
{
cemuLog_log(LogType::Force, "Warning: Ignoring {} bytes in NDEF message", stream.GetRemaining());
break;
}
}
if (msg.mRecords.empty())
{
return {};
}
if (!msg.mRecords.back().IsLast())
{
cemuLog_log(LogType::Force, "Error: NDEF message missing end record");
return {};
}
return msg;
}
std::vector<std::byte> Message::ToBytes() const
{
std::vector<std::byte> bytes;
for (std::size_t i = 0; i < mRecords.size(); i++)
{
uint8 flags = 0;
// Add message begin flag to first record
if (i == 0)
{
flags |= Record::NDEF_MB;
}
// Add message end flag to last record
if (i == mRecords.size() - 1)
{
flags |= Record::NDEF_ME;
}
std::vector<std::byte> recordBytes = mRecords[i].ToBytes(flags);
bytes.insert(bytes.end(), recordBytes.begin(), recordBytes.end());
}
return bytes;
}
void Message::append(const Record& r)
{
mRecords.push_back(r);
}
} // namespace ndef
| 4,706
|
C++
|
.cpp
| 221
| 18.090498
| 102
| 0.6486
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,154
|
TLV.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nfc/TLV.cpp
|
#include "TLV.h"
#include "stream.h"
#include <cassert>
TLV::TLV()
{
}
TLV::TLV(Tag tag, std::vector<std::byte> value)
: mTag(tag), mValue(std::move(value))
{
}
TLV::~TLV()
{
}
std::vector<TLV> TLV::FromBytes(const std::span<std::byte>& data)
{
bool hasTerminator = false;
std::vector<TLV> tlvs;
SpanStream stream(data, std::endian::big);
while (stream.GetRemaining() > 0 && !hasTerminator)
{
// Read the tag
uint8 byte;
stream >> byte;
Tag tag = static_cast<Tag>(byte);
switch (tag)
{
case TLV::TAG_NULL:
// Don't need to do anything for NULL tags
break;
case TLV::TAG_TERMINATOR:
tlvs.emplace_back(tag, std::vector<std::byte>{});
hasTerminator = true;
break;
default:
{
// Read the length
uint16 length;
stream >> byte;
length = byte;
// If the length is 0xff, 2 bytes with length follow
if (length == 0xff) {
stream >> length;
}
std::vector<std::byte> value;
value.resize(length);
stream.Read(value);
tlvs.emplace_back(tag, value);
break;
}
}
if (stream.GetError() != Stream::ERROR_OK)
{
cemuLog_log(LogType::Force, "Error: TLV parsing read past end of stream");
// Clear tlvs to prevent further havoc while parsing ndef data
tlvs.clear();
break;
}
}
// This seems to be okay, at least NTAGs don't add a terminator tag
// if (!hasTerminator)
// {
// cemuLog_log(LogType::Force, "Warning: TLV parsing reached end of stream without terminator tag");
// }
return tlvs;
}
std::vector<std::byte> TLV::ToBytes() const
{
std::vector<std::byte> bytes;
VectorStream stream(bytes, std::endian::big);
// Write tag
stream << uint8(mTag);
switch (mTag)
{
case TLV::TAG_NULL:
case TLV::TAG_TERMINATOR:
// Nothing to do here
break;
default:
{
// Write length (decide if as a 8-bit or 16-bit value)
if (mValue.size() >= 0xff)
{
stream << uint8(0xff);
stream << uint16(mValue.size());
}
else
{
stream << uint8(mValue.size());
}
// Write value
stream.Write(mValue);
}
}
return bytes;
}
TLV::Tag TLV::GetTag() const
{
return mTag;
}
const std::vector<std::byte>& TLV::GetValue() const
{
return mValue;
}
void TLV::SetTag(Tag tag)
{
mTag = tag;
}
void TLV::SetValue(const std::span<const std::byte>& value)
{
// Can only write max 16-bit lengths into TLV
cemu_assert(value.size() < 0x10000);
mValue.assign(value.begin(), value.end());
}
| 2,455
|
C++
|
.cpp
| 113
| 18.681416
| 105
| 0.657588
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,155
|
nn_aoc.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_aoc/nn_aoc.cpp
|
#include "config/ActiveSettings.h"
#include "Cafe/OS/libs/nn_aoc/nn_aoc.h"
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/Filesystem/fsc.h"
#include "Cafe/TitleList/TitleId.h"
#include "Cemu/ncrypto/ncrypto.h"
#include "Common/FileStream.h"
namespace nn
{
namespace aoc
{
struct AOCTitle
{
uint64be titleId;
uint32be groupId;
uint16be titleVersion;
char path[88];
uint8 padding[2];
};
static_assert(sizeof(AOCTitle) == 0x68);
enum class AOC_RESULT : uint32
{
ERROR_OK = 0,
};
uint32 AOC_CalculateWorkBufferSize(uint32 count)
{
count = std::min(count, (uint32)256);
uint32 workBufferSize = 0x80 + count * 0x61;
return workBufferSize;
}
struct AOCCacheEntry
{
AOCCacheEntry(uint64 titleId) : aocTitleId(titleId) {};
uint64 aocTitleId;
std::string GetPath()
{
return fmt::format("/vol/aoc{:016x}", aocTitleId);
}
};
std::vector<AOCCacheEntry> sAocCache;
bool sAocCacheGenerated = false;
void generateAOCList()
{
if (sAocCacheGenerated)
return;
sAocCacheGenerated = true;
sint32 fscStatus;
FSCVirtualFile* volDirIterator = fsc_openDirIterator("/vol", &fscStatus);
cemu_assert_debug(volDirIterator); // for valid titles /vol should always exist
if (volDirIterator)
{
FSCDirEntry dirEntry;
while (fsc_nextDir(volDirIterator, &dirEntry))
{
std::string_view dirName = dirEntry.GetPath();
if(!dirEntry.isDirectory)
continue;
// check for pattern: aoc<titleId>
if(dirName.size() != (3+16))
continue;
if(dirName[0] != 'a' ||
dirName[1] != 'o' ||
dirName[2] != 'c')
continue;
TitleId aocTitleId;
if( !TitleIdParser::ParseFromStr(dirName.substr(3), aocTitleId) )
continue;
// add to list of known AOC
sAocCache.emplace_back(aocTitleId);
}
fsc_close(volDirIterator);
}
}
AOC_RESULT AOC_ListTitle(uint32be* titleCountOut, AOCTitle* titleList, uint32 maxCount, void* workBuffer, uint32 workBufferSize)
{
generateAOCList();
for (uint32 i = 0; i < std::min(maxCount, (uint32)sAocCache.size()); i++)
{
titleList[i].titleId = sAocCache[i].aocTitleId;
titleList[i].groupId = 0; // todo
titleList[i].titleVersion = 0; // todo
strcpy(titleList[i].path, sAocCache[i].GetPath().c_str());
}
*titleCountOut = std::min(maxCount, (uint32)sAocCache.size());
return AOC_RESULT::ERROR_OK;
}
AOC_RESULT AOC_OpenTitle(char* pathOut, AOCTitle* aocTitleInfo, void* workBuffer, uint32 workBufferSize)
{
strcpy(pathOut, aocTitleInfo->path);
return AOC_RESULT::ERROR_OK;
}
AOC_RESULT AOC_CloseTitle(void* ukn)
{
return AOC_RESULT::ERROR_OK;
}
AOC_RESULT AOC_GetPurchaseInfo(uint32be* purchaseBoolArrayOut, uint64 titleId, uint16be* entryIds, uint32 entryCount, void* workBuffer, uint32 workBufferSize)
{
// open ticket file
// on an actual Wii U they get stored to SLC but the download manager places these in the code folder currently
const auto ticketPath = ActiveSettings::GetMlcPath(L"usr/title/{:08x}/{:08x}/code/title.tik", (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF));
uint32 tikFileSize = 0;
std::unique_ptr<FileStream> fileStream(FileStream::openFile2(ticketPath));
std::vector<uint8> tikData;
if (fileStream)
fileStream->extract(tikData);
if (tikData.size() > 0)
{
NCrypto::ETicketParser eTicket;
if (eTicket.parse(tikData.data(), tikData.size()))
{
for (uint32 i = 0; i < entryCount; i++)
{
uint16 id = entryIds[i];
if (eTicket.CheckRight(id))
purchaseBoolArrayOut[i] = 1;
else
purchaseBoolArrayOut[i] = 0;
}
cemuLog_log(LogType::Force, "Using content rights from AOC title.tik");
return AOC_RESULT::ERROR_OK;
}
else
{
cemuLog_log(LogType::Force, "Unable to parse AOC title.tik");
}
}
// fallback: return true for all contentIds
for (uint32 i = 0; i < entryCount; i++)
{
uint16 id = entryIds[i];
purchaseBoolArrayOut[i] = 1;
}
return AOC_RESULT::ERROR_OK;
}
void Initialize()
{
cafeExportRegister("nn_aoc", AOC_CalculateWorkBufferSize, LogType::NN_AOC);
cafeExportRegister("nn_aoc", AOC_ListTitle, LogType::NN_AOC);
cafeExportRegister("nn_aoc", AOC_OpenTitle, LogType::NN_AOC);
cafeExportRegister("nn_aoc", AOC_CloseTitle, LogType::NN_AOC);
cafeExportRegister("nn_aoc", AOC_GetPurchaseInfo, LogType::NN_AOC);
}
}
}
| 4,471
|
C++
|
.cpp
| 144
| 26.805556
| 160
| 0.689487
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,156
|
ax_mix.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/snd_core/ax_mix.cpp
|
#include "Cafe/OS/libs/snd_core/ax.h"
#include "Cafe/OS/libs/snd_core/ax_internal.h"
#include "Cafe/HW/MMU/MMU.h"
#include "config/ActiveSettings.h"
void mic_updateOnAXFrame();
namespace snd_core
{
uint32 __AXDefaultMixerSelect = AX_MIXER_SELECT_BOTH;
uint16 __AXTVAuxReturnVolume[AX_AUX_BUS_COUNT];
void AXSetDefaultMixerSelect(uint32 mixerSelect)
{
__AXDefaultMixerSelect = mixerSelect;
}
uint32 AXGetDefaultMixerSelect()
{
return __AXDefaultMixerSelect;
}
void AXMix_Init()
{
AXSetDefaultMixerSelect(AX_MIXER_SELECT_PPC);
}
void AXMix_DepopVoice(AXVPBInternal_t* internalShadowCopy)
{
// todo
}
#define handleAdpcmDecodeLoop() \
if (internalShadowCopy->internalOffsets.loopFlag != 0) \
{ \
scale = _swapEndianU16(internalShadowCopy->adpcmLoop.loopScale); \
delta = 1 << (scale & 0xF); \
coefIndex = (scale >> 4) & 7; \
coefA = (sint32)(sint16)_swapEndianU16(internalShadowCopy->adpcmData.coef[coefIndex * 2 + 0]); \
coefB = (sint32)(sint16)_swapEndianU16(internalShadowCopy->adpcmData.coef[coefIndex * 2 + 1]); \
playbackNibbleOffset = vpbLoopOffset; \
} \
else \
{ \
/* no loop */ \
internalShadowCopy->playbackState = 0; \
memset(outputWriter, 0, sampleCount * sizeof(sint16)); \
break; \
}
uint32 _AX_fixAdpcmEndOffset(uint32 adpcmOffset)
{
// How to Survive uses an end offset of 0x40000 which is not a valid adpcm sample offset and thus can never be reached (the ppc side decoder jumps from 0x3FFFF to 0x40002)
// todo - investigate if the DSP decoder routines can handle invalid ADPCM end offsets
// for now we use this workaround to force a valid address
if ((adpcmOffset & 0xF) <= 1)
return adpcmOffset + 2;
return adpcmOffset;
}
void AX_readADPCMSamples(AXVPBInternal_t* internalShadowCopy, sint16* output, sint32 sampleCount)
{
if (internalShadowCopy->playbackState == 0)
{
memset(output, 0, sampleCount * sizeof(sint16));
return;
}
AXVPB* vpb = __AXVPBArrayPtr + (sint32)internalShadowCopy->index;
uint8* sampleBase = (uint8*)memory_getPointerFromVirtualOffset(_swapEndianU32(vpb->offsets.samples));
uint32 vpbLoopOffset = _swapEndianU32(*(uint32*)&vpb->offsets.loopOffset);
uint32 vpbEndOffset = _swapEndianU32(*(uint32*)&vpb->offsets.endOffset);
vpbEndOffset = _AX_fixAdpcmEndOffset(vpbEndOffset);
uint32 internalCurrentOffset = _swapEndianU32(*(uint32*)&internalShadowCopy->internalOffsets.currentOffsetPtrHigh);
uint32 internalLoopOffset = _swapEndianU32(*(uint32*)&internalShadowCopy->internalOffsets.loopOffsetPtrHigh);
sint32 scale = (sint32)_swapEndianU16(internalShadowCopy->adpcmData.scale);
sint32 delta = 1 << (scale & 0xF);
sint32 coefIndex = (scale >> 4) & 7;
sint32 coefA = (sint32)(sint16)_swapEndianU16(internalShadowCopy->adpcmData.coef[coefIndex * 2 + 0]);
sint32 coefB = (sint32)(sint16)_swapEndianU16(internalShadowCopy->adpcmData.coef[coefIndex * 2 + 1]);
sint32 hist0 = (sint32)_swapEndianS16(internalShadowCopy->adpcmData.yn1);
sint32 hist1 = (sint32)_swapEndianS16(internalShadowCopy->adpcmData.yn2);
uint32 playbackNibbleOffset = vpbLoopOffset + (internalCurrentOffset - internalLoopOffset);
uint32 playbackNibbleOffsetStart = playbackNibbleOffset;
sint16* outputWriter = output;
// decode samples from current partial ADPCM block
while (sampleCount && (playbackNibbleOffset & 0xF))
{
sint8 nibble = (sint8)sampleBase[(sint32)playbackNibbleOffset >> 1];
nibble <<= (4 * ((playbackNibbleOffset & 1)));
nibble &= 0xF0;
sint32 v = (sint32)nibble;
v <<= (11 - 4);
v *= delta;
v += (hist0 * coefA + hist1 * coefB);
v = (v + 0x400) >> 11;
v = std::clamp(v, -32768, 32767);
hist1 = hist0;
hist0 = v;
*outputWriter = v;
outputWriter++;
// check for loop / end offset
if (playbackNibbleOffset == vpbEndOffset)
{
handleAdpcmDecodeLoop();
}
else
{
playbackNibbleOffset++;
}
sampleCount--;
}
// optimized code to decode whole blocks
if (!(playbackNibbleOffset <= vpbEndOffset && ((uint64)playbackNibbleOffset + (uint64)(sampleCount * 16 / 14)) >= (uint64)vpbEndOffset))
{
while (sampleCount >= 14) // 14 samples per 16 byte block
{
// decode header
sint8* sampleInputData = (sint8*)sampleBase + ((sint32)playbackNibbleOffset >> 1);
scale = (uint8)sampleInputData[0];
delta = 1 << (scale & 0xF);
coefIndex = (scale >> 4) & 7;
coefA = (sint32)(sint16)_swapEndianU16(internalShadowCopy->adpcmData.coef[coefIndex * 2 + 0]);
coefB = (sint32)(sint16)_swapEndianU16(internalShadowCopy->adpcmData.coef[coefIndex * 2 + 1]);
playbackNibbleOffset += 2;
// decode samples
sampleInputData++;
for (sint32 i = 0; i < 7; i++)
{
// n0
sint8 nibble = *sampleInputData;
sampleInputData++;
sint32 v;
// upper nibble
v = (sint32)(sint8)(nibble & 0xF0);
v <<= (11 - 4);
v *= delta;
v += (hist0 * coefA + hist1 * coefB);
v = (v + 0x400) >> 11;
v = std::min(v, 32767);
v = std::max(v, -32768);
hist1 = hist0;
hist0 = v;
*outputWriter = v;
outputWriter++;
// lower nibble
v = (sint32)(sint8)(nibble << 4);
v <<= (11 - 4);
v *= delta;
v += (hist0 * coefA + hist1 * coefB);
v = (v + 0x400) >> 11;
v = std::min(v, 32767);
v = std::max(v, -32768);
hist1 = hist0;
hist0 = v;
*outputWriter = v;
outputWriter++;
}
playbackNibbleOffset += 7 * 2;
sampleCount -= 7 * 2;
}
}
// decode remaining samples
while (sampleCount)
{
if ((playbackNibbleOffset & 0xF) == 0)
{
scale = sampleBase[(sint32)playbackNibbleOffset >> 1];
delta = 1 << (scale & 0xF);
coefIndex = (scale >> 4) & 7;
coefA = (sint32)(sint16)_swapEndianU16(internalShadowCopy->adpcmData.coef[coefIndex * 2 + 0]);
coefB = (sint32)(sint16)_swapEndianU16(internalShadowCopy->adpcmData.coef[coefIndex * 2 + 1]);
playbackNibbleOffset += 2;
}
sint8 nibble = (sint8)sampleBase[(sint32)playbackNibbleOffset >> 1];
nibble <<= (4 * ((playbackNibbleOffset & 1)));
nibble &= 0xF0;
sint32 v = (sint32)nibble;
v <<= (11 - 4);
v *= delta;
v += (hist0 * coefA + hist1 * coefB);
v = (v + 0x400) >> 11;
v = std::min(v, 32767);
v = std::max(v, -32768);
hist1 = hist0;
hist0 = v;
*outputWriter = v;
outputWriter++;
// check for loop / end offset
if (playbackNibbleOffset == vpbEndOffset)
{
handleAdpcmDecodeLoop();
}
else
{
playbackNibbleOffset++;
}
sampleCount--;
}
// write updated values
internalShadowCopy->adpcmData.scale = _swapEndianU16(scale);
internalShadowCopy->adpcmData.yn1 = (uint16)_swapEndianS16(hist0);
internalShadowCopy->adpcmData.yn2 = (uint16)_swapEndianS16(hist1);
uint32 newInternalCurrentOffset = internalCurrentOffset + (playbackNibbleOffset - playbackNibbleOffsetStart);
*(uint32*)&internalShadowCopy->internalOffsets.currentOffsetPtrHigh = _swapEndianU32(newInternalCurrentOffset);
}
void AX_DecodeSamplesADPCM_NoSrc(AXVPBInternal_t* internalShadowCopy, float* output, sint32 sampleCount)
{
sint16 sampleBuffer[1024];
cemu_assert(sampleCount <= (sizeof(sampleBuffer) / sizeof(sampleBuffer[0])));
AX_readADPCMSamples(internalShadowCopy, sampleBuffer, sampleCount);
for (sint32 i = 0; i < sampleCount; i++)
{
// decode next sample
sint32 s = sampleBuffer[i];
s <<= 8;
*output = (float)s;
output++;
}
}
void AX_DecodeSamplesADPCM_Linear(AXVPBInternal_t* internalShadowCopy, float* output, sint32 sampleCount)
{
uint32 currentFracPos = (uint32)_swapEndianU16(internalShadowCopy->src.currentFrac);
uint32 ratio = _swapEndianU32(*(uint32*)&internalShadowCopy->src.ratioHigh);
sint16 historySamples[4];
historySamples[0] = _swapEndianS16(internalShadowCopy->src.historySamples[0]);
historySamples[1] = _swapEndianS16(internalShadowCopy->src.historySamples[1]);
historySamples[2] = _swapEndianS16(internalShadowCopy->src.historySamples[2]);
historySamples[3] = _swapEndianS16(internalShadowCopy->src.historySamples[3]);
sint32 historyIndex = 0;
sint32 numberOfDecodedAdpcmSamples = (sint32)((currentFracPos + ratio * sampleCount) >> 16);
sint16 adpcmSampleBuffer[4096];
if (numberOfDecodedAdpcmSamples >= 4096)
{
memset(output, 0, sizeof(float)*sampleCount);
cemuLog_log(LogType::Force, "Too many ADPCM samples to decode. ratio = {:08x}", ratio);
return;
}
AX_readADPCMSamples(internalShadowCopy, adpcmSampleBuffer, numberOfDecodedAdpcmSamples);
sint32 readSampleCount = 0;
if (ratio == 0x10000 && currentFracPos == 0)
{
// optimized path when accessing only fully aligned samples
for (sint32 i = 0; i < sampleCount; i++)
{
cemu_assert_debug(readSampleCount < numberOfDecodedAdpcmSamples);
// get next sample
sint16 s = adpcmSampleBuffer[readSampleCount];
readSampleCount++;
historyIndex = (historyIndex + 1) & 3;
historySamples[historyIndex] = s;
// use previous sample
sint32 previousSample = historySamples[(historyIndex + 3) & 3];
sint32 p0 = previousSample << 8;
*output = (float)p0;
output++;
}
}
else
{
for (sint32 i = 0; i < sampleCount; i++)
{
// move playback pos
currentFracPos += ratio;
// get more samples if needed
while (currentFracPos >= 0x10000)
{
cemu_assert_debug(readSampleCount < numberOfDecodedAdpcmSamples);
sint16 s = adpcmSampleBuffer[readSampleCount];
readSampleCount++;
currentFracPos -= 0x10000;
historyIndex = (historyIndex + 1) & 3;
historySamples[historyIndex] = s;
}
// linear interpolation of current sample
sint32 previousSample = historySamples[(historyIndex + 3) & 3];
sint32 nextSample = historySamples[historyIndex];
sint32 p0 = (sint32)previousSample * (sint32)(0x10000 - currentFracPos);
sint32 p1 = (sint32)nextSample * (sint32)(currentFracPos);
p0 >>= 7;
p1 >>= 7;
sint32 interpolatedSample = p0 + p1;
interpolatedSample >>= 1;
*output = (float)interpolatedSample;
output++;
}
}
cemu_assert_debug(readSampleCount == numberOfDecodedAdpcmSamples);
// set variables
internalShadowCopy->src.currentFrac = _swapEndianU16((uint16)(currentFracPos));
internalShadowCopy->src.historySamples[0] = _swapEndianS16(historySamples[(historyIndex + 0) & 3]);
internalShadowCopy->src.historySamples[1] = _swapEndianS16(historySamples[(historyIndex + 1) & 3]);
internalShadowCopy->src.historySamples[2] = _swapEndianS16(historySamples[(historyIndex + 2) & 3]);
internalShadowCopy->src.historySamples[3] = _swapEndianS16(historySamples[(historyIndex + 3) & 3]);
}
void AX_DecodeSamplesADPCM_Tap(AXVPBInternal_t* internalShadowCopy, float* output, sint32 sampleCount)
{
// todo - implement this
AX_DecodeSamplesADPCM_Linear(internalShadowCopy, output, sampleCount);
}
void AX_DecodeSamplesPCM8_Linear(AXVPBInternal_t* internalShadowCopy, float* output, sint32 sampleCount)
{
// get variables
uint32 currentFracPos = (uint32)_swapEndianU16(internalShadowCopy->src.currentFrac);
uint32 ratio = _swapEndianU32(*(uint32*)&internalShadowCopy->src.ratioHigh);
uint32 endOffsetPtr = _swapEndianU32(*(uint32*)&internalShadowCopy->internalOffsets.endOffsetPtrHigh);
uint32 currentOffsetPtr = _swapEndianU32(*(uint32*)&internalShadowCopy->internalOffsets.currentOffsetPtrHigh);
uint32 loopOffsetPtr = _swapEndianU32(*(uint32*)&internalShadowCopy->internalOffsets.loopOffsetPtrHigh);
uint32 ptrHighExtension = _swapEndianU16(internalShadowCopy->internalOffsets.ptrHighExtension);
uint8* endOffsetAddr = memory_base + (endOffsetPtr | (ptrHighExtension << 29));
uint8* currentOffsetAddr = memory_base + (currentOffsetPtr | (ptrHighExtension << 29));
sint16 historySamples[4];
historySamples[0] = _swapEndianS16(internalShadowCopy->src.historySamples[0]);
historySamples[1] = _swapEndianS16(internalShadowCopy->src.historySamples[1]);
historySamples[2] = _swapEndianS16(internalShadowCopy->src.historySamples[2]);
historySamples[3] = _swapEndianS16(internalShadowCopy->src.historySamples[3]);
sint32 historyIndex = 0;
for (sint32 i = 0; i<sampleCount; i++)
{
currentFracPos += ratio;
while (currentFracPos >= 0x10000)
{
// read next sample
historyIndex = (historyIndex + 1) & 3;
if (internalShadowCopy->playbackState)
{
sint32 s = (sint32)(sint8)*currentOffsetAddr;
s <<= 8;
historySamples[historyIndex] = s;
if (currentOffsetAddr == endOffsetAddr)
{
if (internalShadowCopy->internalOffsets.loopFlag)
{
// loop
currentOffsetAddr = memory_base + (loopOffsetPtr | (ptrHighExtension << 29));
}
else
{
// stop playing
internalShadowCopy->playbackState = 0;
}
}
else
{
currentOffsetAddr++;
}
}
else
{
// voice not playing, read sample as 0
historySamples[historyIndex] = 0;
}
currentFracPos -= 0x10000;
}
// interpolate sample
sint32 previousSample = historySamples[(historyIndex + 3) & 3];
sint32 nextSample = historySamples[historyIndex];
sint32 p0 = (sint32)previousSample * (sint32)(0x10000 - currentFracPos);
sint32 p1 = (sint32)nextSample * (sint32)(currentFracPos);
p0 >>= 7;
p1 >>= 7;
sint32 interpolatedSample = p0 + p1;
interpolatedSample >>= 1;
*output = (float)interpolatedSample;
output++;
}
// set variables
internalShadowCopy->src.currentFrac = _swapEndianU16((uint16)(currentFracPos));
internalShadowCopy->src.historySamples[0] = _swapEndianS16(historySamples[(historyIndex + 0) & 3]);
internalShadowCopy->src.historySamples[1] = _swapEndianS16(historySamples[(historyIndex + 1) & 3]);
internalShadowCopy->src.historySamples[2] = _swapEndianS16(historySamples[(historyIndex + 2) & 3]);
internalShadowCopy->src.historySamples[3] = _swapEndianS16(historySamples[(historyIndex + 3) & 3]);
// store current offset
currentOffsetPtr = (uint32)((uint8*)currentOffsetAddr - memory_base);
currentOffsetPtr &= 0x1FFFFFFF; // is this correct?
*(uint32*)&internalShadowCopy->internalOffsets.currentOffsetPtrHigh = _swapEndianU32(currentOffsetPtr);
}
void AX_DecodeSamplesPCM8_Tap(AXVPBInternal_t* internalShadowCopy, float* output, sint32 sampleCount)
{
// todo - implement this
AX_DecodeSamplesPCM8_Linear(internalShadowCopy, output, sampleCount);
}
void AX_DecodeSamplesPCM8_NoSrc(AXVPBInternal_t* internalShadowCopy, float* output, sint32 sampleCount)
{
// get variables
uint32 currentFracPos = (uint32)_swapEndianU16(internalShadowCopy->src.currentFrac);
uint32 ratio = _swapEndianU32(*(uint32*)&internalShadowCopy->src.ratioHigh);
uint32 endOffsetPtr = _swapEndianU32(*(uint32*)&internalShadowCopy->internalOffsets.endOffsetPtrHigh);
uint32 currentOffsetPtr = _swapEndianU32(*(uint32*)&internalShadowCopy->internalOffsets.currentOffsetPtrHigh);
uint32 ptrHighExtension = _swapEndianU16(internalShadowCopy->internalOffsets.ptrHighExtension);
uint8* endOffsetAddr = memory_base + (endOffsetPtr | (ptrHighExtension << 29));
uint8* currentOffsetAddr = memory_base + (currentOffsetPtr | (ptrHighExtension << 29));
sint16 historySamples[4];
historySamples[0] = _swapEndianS16(internalShadowCopy->src.historySamples[0]);
historySamples[1] = _swapEndianS16(internalShadowCopy->src.historySamples[1]);
historySamples[2] = _swapEndianS16(internalShadowCopy->src.historySamples[2]);
historySamples[3] = _swapEndianS16(internalShadowCopy->src.historySamples[3]);
cemu_assert_debug(false); // todo
}
void AX_DecodeSamplesPCM16_Linear(AXVPBInternal_t* internalShadowCopy, float* output, sint32 sampleCount)
{
uint32 currentFracPos = (uint32)_swapEndianU16(internalShadowCopy->src.currentFrac);
uint32 ratio = _swapEndianU32(*(uint32*)&internalShadowCopy->src.ratioHigh);
uint32 endOffsetPtr = _swapEndianU32(*(uint32*)&internalShadowCopy->internalOffsets.endOffsetPtrHigh);
uint32 currentOffsetPtr = _swapEndianU32(*(uint32*)&internalShadowCopy->internalOffsets.currentOffsetPtrHigh);
uint32 loopOffsetPtr = _swapEndianU32(*(uint32*)&internalShadowCopy->internalOffsets.loopOffsetPtrHigh);
uint32 ptrHighExtension = _swapEndianU16(internalShadowCopy->internalOffsets.ptrHighExtension);
uint16* endOffsetAddr = (uint16*)(memory_base + ((endOffsetPtr * 2) | (ptrHighExtension << 29)));
uint16* currentOffsetAddr = (uint16*)(memory_base + ((currentOffsetPtr * 2) | (ptrHighExtension << 29)));
uint16* loopOffsetAddrDebug = (uint16*)(memory_base + ((loopOffsetPtr * 2) | (ptrHighExtension << 29)));
sint16 historySamples[4];
historySamples[0] = _swapEndianS16(internalShadowCopy->src.historySamples[0]);
historySamples[1] = _swapEndianS16(internalShadowCopy->src.historySamples[1]);
historySamples[2] = _swapEndianS16(internalShadowCopy->src.historySamples[2]);
historySamples[3] = _swapEndianS16(internalShadowCopy->src.historySamples[3]);
sint32 historyIndex = 0;
for (sint32 i = 0; i < sampleCount; i++)
{
currentFracPos += ratio;
while (currentFracPos >= 0x10000)
{
// read next sample
historyIndex = (historyIndex + 1) & 3;
if (internalShadowCopy->playbackState)
{
sint32 s = _swapEndianS16(*currentOffsetAddr);
historySamples[historyIndex] = s;
if (currentOffsetAddr == endOffsetAddr)
{
if (internalShadowCopy->internalOffsets.loopFlag)
{
// loop
currentOffsetAddr = (uint16*)(memory_base + ((loopOffsetPtr * 2) | (ptrHighExtension << 29)));
}
else
{
// stop playing
internalShadowCopy->playbackState = 0;
}
}
else
{
currentOffsetAddr++; // increment pointer only if not at end offset
}
}
else
{
// voice not playing -> sample is silent
historySamples[historyIndex] = 0;
}
currentFracPos -= 0x10000;
}
// interpolate sample
sint32 previousSample = historySamples[(historyIndex + 3) & 3];
sint32 nextSample = historySamples[historyIndex];
sint32 p0 = (sint32)previousSample * (sint32)(0x10000 - currentFracPos);
sint32 p1 = (sint32)nextSample * (sint32)(currentFracPos);
p0 >>= 7;
p1 >>= 7;
sint32 interpolatedSample = p0 + p1;
interpolatedSample >>= 1;
*output = (float)interpolatedSample;
output++;
}
// set variables
internalShadowCopy->src.currentFrac = _swapEndianU16((uint16)(currentFracPos));
internalShadowCopy->src.historySamples[0] = _swapEndianS16(historySamples[(historyIndex + 0) & 3]);
internalShadowCopy->src.historySamples[1] = _swapEndianS16(historySamples[(historyIndex + 1) & 3]);
internalShadowCopy->src.historySamples[2] = _swapEndianS16(historySamples[(historyIndex + 2) & 3]);
internalShadowCopy->src.historySamples[3] = _swapEndianS16(historySamples[(historyIndex + 3) & 3]);
// store current offset
currentOffsetPtr = (uint32)((uint8*)currentOffsetAddr - memory_base);
currentOffsetPtr &= 0x1FFFFFFF;
currentOffsetPtr >>= 1;
*(uint32*)&internalShadowCopy->internalOffsets.currentOffsetPtrHigh = _swapEndianU32(currentOffsetPtr);
}
void AX_DecodeSamplesPCM16_Tap(AXVPBInternal_t* internalShadowCopy, float* output, sint32 sampleCount)
{
// todo - implement this
AX_DecodeSamplesPCM16_Linear(internalShadowCopy, output, sampleCount);
}
void AX_DecodeSamplesPCM16_NoSrc(AXVPBInternal_t* internalShadowCopy, float* output, sint32 sampleCount)
{
// get variables
uint32 currentFracPos = (uint32)_swapEndianU16(internalShadowCopy->src.currentFrac);
uint32 ratio = _swapEndianU32(*(uint32*)&internalShadowCopy->src.ratioHigh);
uint32 endOffsetPtr = _swapEndianU32(*(uint32*)&internalShadowCopy->internalOffsets.endOffsetPtrHigh);
uint32 currentOffsetPtr = _swapEndianU32(*(uint32*)&internalShadowCopy->internalOffsets.currentOffsetPtrHigh);
uint32 loopOffsetPtr = _swapEndianU32(*(uint32*)&internalShadowCopy->internalOffsets.loopOffsetPtrHigh);
uint32 ptrHighExtension = _swapEndianU16(internalShadowCopy->internalOffsets.ptrHighExtension);
uint16* endOffsetAddr = (uint16*)(memory_base + (endOffsetPtr * 2 | (ptrHighExtension << 29)));
uint16* currentOffsetAddr = (uint16*)(memory_base + (currentOffsetPtr * 2 | (ptrHighExtension << 29)));
if (internalShadowCopy->playbackState == 0)
{
memset(output, 0, sizeof(float)*sampleCount);
return;
}
for (sint32 i = 0; i < sampleCount; i++)
{
sint32 s = _swapEndianS16(*currentOffsetAddr);
s <<= 8;
output[i] = (float)s;
if (currentOffsetAddr == endOffsetAddr)
{
if (internalShadowCopy->internalOffsets.loopFlag)
{
currentOffsetAddr = (uint16*)(memory_base + (loopOffsetPtr * 2 | (ptrHighExtension << 29)));
}
else
{
internalShadowCopy->playbackState = 0;
for (; i < sampleCount; i++)
{
output[i] = 0.0f;
}
break;
}
}
else
currentOffsetAddr++;
}
// store current offset
currentOffsetPtr = (uint32)((uint8*)currentOffsetAddr - memory_base);
currentOffsetPtr &= 0x1FFFFFFF;
currentOffsetPtr >>= 1;
*(uint32*)&internalShadowCopy->internalOffsets.currentOffsetPtrHigh = _swapEndianU32(currentOffsetPtr);
}
void AXVoiceMix_DecodeSamples(AXVPBInternal_t* internalShadowCopy, float* output, sint32 sampleCount)
{
uint32 srcFilterMode = _swapEndianU16(internalShadowCopy->srcFilterMode);
uint16 format = _swapEndianU16(internalShadowCopy->internalOffsets.format);
if (srcFilterMode == AX_FILTER_MODE_LINEAR || srcFilterMode == AX_FILTER_MODE_TAP)
{
if (format == AX_FORMAT_ADPCM)
AX_DecodeSamplesADPCM_Tap(internalShadowCopy, output, sampleCount);
else if (format == AX_FORMAT_PCM16)
AX_DecodeSamplesPCM16_Tap(internalShadowCopy, output, sampleCount);
else if (format == AX_FORMAT_PCM8)
AX_DecodeSamplesPCM8_Tap(internalShadowCopy, output, sampleCount);
else
cemu_assert_debug(false);
}
else if (srcFilterMode == AX_FILTER_MODE_LINEAR)
{
if (format == AX_FORMAT_ADPCM)
AX_DecodeSamplesADPCM_Linear(internalShadowCopy, output, sampleCount);
else if (format == AX_FORMAT_PCM16)
AX_DecodeSamplesPCM16_Linear(internalShadowCopy, output, sampleCount);
else if (format == AX_FORMAT_PCM8)
AX_DecodeSamplesPCM8_Linear(internalShadowCopy, output, sampleCount);
else
cemu_assert_debug(false);
}
else if (srcFilterMode == AX_FILTER_MODE_NONE)
{
if (format == AX_FORMAT_ADPCM)
AX_DecodeSamplesADPCM_NoSrc(internalShadowCopy, output, sampleCount);
else if (format == AX_FORMAT_PCM16)
AX_DecodeSamplesPCM16_NoSrc(internalShadowCopy, output, sampleCount);
else if (format == AX_FORMAT_PCM8)
AX_DecodeSamplesPCM8_NoSrc(internalShadowCopy, output, sampleCount);
else
cemu_assert_debug(false);
}
}
sint32 AXVoiceMix_MergeInto(float* inputSamples, float* outputSamples, sint32 sampleCount, AXCHMIX_DEPR* mix, sint16 deltaI)
{
float vol = (float)_swapEndianU16(mix->vol) / (float)0x8000;
if (deltaI != 0)
{
float delta = (float)deltaI / (float)0x8000;
for (sint32 i = 0; i < sampleCount; i++)
{
vol += delta;
outputSamples[i] += inputSamples[i] * vol;
}
}
else
{
// optimized version for delta == 0.0
for (sint32 i = 0; i < sampleCount; i++)
{
outputSamples[i] += inputSamples[i] * vol;
}
}
uint16 volI = (uint16)(vol * 32768.0f);
mix->vol = _swapEndianU16(volI);
return volI;
}
float __AXMixBufferTV[AX_SAMPLES_MAX * AX_TV_CHANNEL_COUNT * AX_BUS_COUNT];
float __AXMixBufferDRC[2 * AX_SAMPLES_MAX * AX_DRC_CHANNEL_COUNT * AX_BUS_COUNT];
void AXVoiceMix_ApplyADSR(AXVPBInternal_t* internalShadowCopy, float* sampleData, sint32 sampleCount)
{
uint16 volume = internalShadowCopy->veVolume;
sint16 volumeDelta = (sint16)internalShadowCopy->veDelta;
if (volume == 0x8000 && volumeDelta == 0)
return;
float volumeScaler = (float)volume / 32768.0f;
if (volumeDelta == 0)
{
// without delta
for (sint32 i = 0; i < sampleCount; i++)
sampleData[i] *= volumeScaler;
return;
}
// with delta
double volumeScalerDelta = (double)volumeDelta / 32768.0;
volumeScalerDelta = volumeScalerDelta + volumeScalerDelta;
for (sint32 i = 0; i < sampleCount; i++)
{
volumeScaler += (float)volumeScalerDelta;
sampleData[i] *= volumeScaler;
}
if (volumeDelta != 0)
{
volume = (uint16)(volumeScaler * 32768.0);
internalShadowCopy->veVolume = volume;
}
}
void AXVoiceMix_ApplyBiquad(AXVPBInternal_t* internalShadowCopy, float* sampleData, sint32 sampleCount)
{
if (internalShadowCopy->biquad.on == AX_BIQUAD_OFF)
return;
#ifdef CEMU_DEBUG_ASSERT
if (internalShadowCopy->biquad.on != 0x0200)
{
cemuLog_logDebug(LogType::Force, "AX_ApplyBiquad() with incorrect biquad.on value 0x{:04x}", _swapEndianU16(internalShadowCopy->biquad.on));
}
#endif
float a1 = (float)(sint16)_swapEndianS16(internalShadowCopy->biquad.a1) / 16384.0f;
float a2 = (float)(sint16)_swapEndianS16(internalShadowCopy->biquad.a2) / 16384.0f;
float b0 = (float)(sint16)_swapEndianS16(internalShadowCopy->biquad.b0) / 16384.0f;
float b1 = (float)(sint16)_swapEndianS16(internalShadowCopy->biquad.b1) / 16384.0f;
float b2 = (float)(sint16)_swapEndianS16(internalShadowCopy->biquad.b2) / 16384.0f;
float yn1 = (float)_swapEndianS16(internalShadowCopy->biquad.yn1);
float yn2 = (float)_swapEndianS16(internalShadowCopy->biquad.yn2);
float xn1 = (float)_swapEndianS16(internalShadowCopy->biquad.xn1);
float xn2 = (float)_swapEndianS16(internalShadowCopy->biquad.xn2);
if (internalShadowCopy->biquad.b1 != 0)
{
for (sint32 i = 0; i < sampleCount; i++)
{
float inputSample = sampleData[i] / 256.0f;
float temp = b0 * inputSample + b1 * xn1 + b2 * xn2 + a1 * yn1 + a2 * yn2;
sampleData[i] = temp * 256.0f;
temp = std::min(32767.0f, temp);
temp = std::max(-32768.0f, temp);
yn2 = yn1;
xn2 = xn1;
yn1 = temp;
xn1 = inputSample;
}
}
else
{
// optimized variant where voiceInternal->biquad.b1 is hardcoded as zero (used heavily in BotW and Splatoon)
for (sint32 i = 0; i < sampleCount; i++)
{
float inputSample = sampleData[i] / 256.0f;
float temp = b0 * inputSample + b2 * xn2 + a1 * yn1 + a2 * yn2;
sampleData[i] = temp * 256.0f;
temp = std::min(32767.0f, temp);
temp = std::max(-32768.0f, temp);
yn2 = yn1;
xn2 = xn1;
yn1 = temp;
xn1 = inputSample;
}
}
internalShadowCopy->biquad.yn1 = _swapEndianU16((sint16)(yn1));
internalShadowCopy->biquad.yn2 = _swapEndianU16((sint16)(yn2));
internalShadowCopy->biquad.xn1 = _swapEndianU16((sint16)(xn1));
internalShadowCopy->biquad.xn2 = _swapEndianU16((sint16)(xn2));
}
void AXVoiceMix_ApplyLowPass(AXVPBInternal_t* internalShadowCopy, float* sampleData, sint32 sampleCount)
{
if (internalShadowCopy->lpf.on == _swapEndianU16(AX_LPF_OFF))
return;
float a0 = (float)_swapEndianS16(internalShadowCopy->lpf.a0) / 32767.0f;
float b0 = (float)_swapEndianS16(internalShadowCopy->lpf.b0) / 32767.0f;
float prevSample = (float)_swapEndianS16((sint16)internalShadowCopy->lpf.yn1) * 256.0f / 32767.0f;
for (sint32 i = 0; i < sampleCount; i++)
{
sampleData[i] = a0 * sampleData[i] - b0 * prevSample;
prevSample = sampleData[i];
}
internalShadowCopy->lpf.yn1 = (uint16)_swapEndianS16((sint16)(prevSample / 256.0f * 32767.0f));
}
// mix audio generated from voice into main bus and aux buses
void AXVoiceMix_MixIntoBuses(AXVPBInternal_t* internalShadowCopy, float* sampleData, sint32 sampleCount, sint32 samplesPerFrame)
{
// TV mixing
for (sint32 busIndex = 0; busIndex < AX_BUS_COUNT; busIndex++)
{
for (sint32 channel = 0; channel < 6; channel++)
{
uint32 channelMixMask = (_swapEndianU16(internalShadowCopy->deviceMixMaskTV[busIndex]) >> (channel * 2)) & 3;
if (channelMixMask == 0)
{
internalShadowCopy->reserved1E8[busIndex*AX_TV_CHANNEL_COUNT + channel] = 0;
continue;
}
AXCHMIX_DEPR* mix = internalShadowCopy->deviceMixTV + channel * 4 + busIndex;
float* output = __AXMixBufferTV + (busIndex * 6 + channel) * samplesPerFrame;
AXVoiceMix_MergeInto(sampleData, output, sampleCount, mix, _swapEndianS16(mix->delta));
internalShadowCopy->reserved1E8[busIndex*AX_TV_CHANNEL_COUNT + channel] = mix->vol;
}
}
// DRC0 mixing
for (sint32 busIndex = 0; busIndex < AX_BUS_COUNT; busIndex++)
{
for (sint32 channel = 0; channel < AX_DRC_CHANNEL_COUNT; channel++)
{
uint32 channelMixMask = (_swapEndianU16(internalShadowCopy->deviceMixMaskDRC[busIndex]) >> (channel * 2)) & 3;
if (channelMixMask == 0)
{
//internalShadowCopy->reserved1E8[busIndex*AX_DRC_CHANNEL_COUNT + channel] = 0;
continue;
}
AXCHMIX_DEPR* mix = internalShadowCopy->deviceMixDRC + channel * 4 + busIndex;
float* output = __AXMixBufferDRC + (busIndex * AX_DRC_CHANNEL_COUNT + channel) * samplesPerFrame;
AXVoiceMix_MergeInto(sampleData, output, sampleCount, mix, _swapEndianS16(mix->delta));
}
}
// DRC1 mixing + RMT mixing
// todo
}
void AXMix_ProcessVoices(AXVPBInternal_t* firstVoice)
{
if (firstVoice == nullptr)
return;
size_t sampleCount = AXGetInputSamplesPerFrame();
AXVPBInternal_t* internalVoice = firstVoice;
cemu_assert_debug(sndGeneric.initParam.frameLength == 0);
float tmpSampleBuffer[AX_SAMPLES_MAX];
while (internalVoice)
{
AXVoiceMix_DecodeSamples(internalVoice, tmpSampleBuffer, sampleCount);
AXVoiceMix_ApplyADSR(internalVoice, tmpSampleBuffer, sampleCount);
AXVoiceMix_ApplyBiquad(internalVoice, tmpSampleBuffer, sampleCount);
AXVoiceMix_ApplyLowPass(internalVoice, tmpSampleBuffer, sampleCount);
AXVoiceMix_MixIntoBuses(internalVoice, tmpSampleBuffer, sampleCount, sampleCount);
// next
internalVoice = internalVoice->nextToProcess.GetPtr();
}
}
void AXMix_MergeBusSamples(float* input, sint32* output, sint32 sampleCount, uint16& volume, sint16 delta)
{
float volumeF = (float)volume / 32768.0f;
float deltaF = (float)delta / 32768.0f;
if (delta)
{
for (sint32 i = 0; i < sampleCount; i++)
{
float s = *input;
input++;
s *= volumeF;
volumeF += deltaF;
*output = _swapEndianS32(_swapEndianS32(*output) + (sint32)s);
output++;
}
volume = (uint16)(volumeF * 32768.0f);
}
else
{
// no delta
for (sint32 i = 0; i < sampleCount; i++)
{
float s = *input;
input++;
s *= volumeF;
*output = _swapEndianS32(_swapEndianS32(*output) + (sint32)s);
output++;
}
}
}
void AXAuxMix_StoreAuxSamples(float* input, sint32be* output, sint32 sampleCount)
{
// Not 100% sure why but we need to temporarily right shift the aux samples by 8 to get the sample range the games expect for the AUX callback
// without this, Color Splash will apply it's effects incorrectly
// Its probably because AUX mixing always goes through the DSP which uses 16bit arithmetic?
// no delta
for (sint32 i = 0; i < sampleCount; i++)
{
float s = *input;
input++;
*output = ((sint32)s) >> 8;
output++;
}
}
void AXAuxMix_MixProcessedAuxSamplesIntoOutput(sint32be* input, float* output, sint32 sampleCount, uint16* volumePtr, sint16 delta)
{
uint16 volume = *volumePtr;
float volumeF = (float)volume / 32768.0f;
float deltaF = (float)delta / 32768.0f;
cemu_assert_debug(delta == 0); // todo
for (sint32 i = 0; i < sampleCount; i++)
{
float s = (float)(((sint32)*input)<<8);
input++;
s *= volumeF;
*output += s;
output++;
}
*volumePtr = volume;
}
uint16 __AXMasterVolume = 0x8000;
uint16 __AXDRCMasterVolume = 0x8000;
// mix into __AXTVOutputBuffer
void AXMix_mergeTVBuses()
{
size_t sampleCount = AXGetInputSamplesPerFrame();
// debug - Erase main bus and only output AUX
if (ActiveSettings::AudioOutputOnlyAux())
{
memset(__AXMixBufferTV, 0, sizeof(float) * sampleCount * 6);
}
// Mix aux into TV main bus
for (sint32 auxBus = 0; auxBus < AX_AUX_BUS_COUNT; auxBus++)
{
sint32be* auxOutput = AXAux_GetOutputBuffer(AX_DEV_TV, 0, auxBus);
if (auxOutput == nullptr)
continue;
// AUX return from output buffer
uint16 auxReturnVolume = __AXTVAuxReturnVolume[auxBus];
sint16 auxReturnDelta = 0;
AXAuxMix_MixProcessedAuxSamplesIntoOutput(auxOutput, __AXMixBufferTV, sampleCount * AX_TV_CHANNEL_COUNT, &auxReturnVolume, auxReturnDelta);
}
// mix TV main bus into output
float* input = __AXMixBufferTV;
uint16 masterVolume = __AXMasterVolume;
sint32* output = __AXTVOutputBuffer.GetPtr();
cemu_assert_debug(masterVolume == 0x8000); // todo -> Calculate delta between old master volume and new volume
sint16 delta = 0;
uint16 volVar;
for (uint16 c = 0; c < AX_TV_CHANNEL_COUNT; c++)
{
volVar = _swapEndianU16(masterVolume);
AXMix_MergeBusSamples(input, output, sampleCount, masterVolume, delta);
output += sampleCount;
input += sampleCount;
}
}
// mix into __AXDRCOutputBuffer
void AXMix_mergeDRC0Buses()
{
sint32* output = __AXDRCOutputBuffer.GetPtr();
uint16 masterVolume = __AXDRCMasterVolume;
size_t sampleCount = AXGetInputSamplesPerFrame();
// todo - drc0 AUX
// mix DRC0 main bus into output
float* input = __AXMixBufferDRC;
cemu_assert_debug(masterVolume == 0x8000); // todo -> Calculate delta between old master volume and new volume
sint16 delta = 0;
for (uint16 c = 0; c < AX_DRC_CHANNEL_COUNT; c++)
{
AXMix_MergeBusSamples(input, output, sampleCount, masterVolume, delta);
output += sampleCount;
input += sampleCount;
}
}
void AXMix_process(AXVPBInternal_t* internalShadowCopyHead)
{
memset(__AXMixBufferTV, 0, sizeof(__AXMixBufferTV));
memset(__AXMixBufferDRC, 0, sizeof(__AXMixBufferDRC));
AXMix_ProcessVoices(internalShadowCopyHead);
AXAux_Process(); // apply AUX effects to previous frame
AXIst_HandleFrameCallbacks();
size_t sampleCount = AXGetInputSamplesPerFrame();
// TV aux store
for (sint32 auxBus = 0; auxBus < AX_AUX_BUS_COUNT; auxBus++)
{
sint32be* auxInput = AXAux_GetInputBuffer(AX_DEV_TV, 0, auxBus);
if (auxInput == nullptr)
continue;
float* tvInput = __AXMixBufferTV + (1 + auxBus) * (sampleCount * AX_TV_CHANNEL_COUNT);
AXAuxMix_StoreAuxSamples(tvInput, auxInput, sampleCount * AX_TV_CHANNEL_COUNT);
}
// DRC aux store
// todo
// merge main and aux buses
AXMix_mergeTVBuses();
AXMix_mergeDRC0Buses();
AXAux_incrementBufferIndex();
// update microphone
mic_updateOnAXFrame();
}
}
| 34,495
|
C++
|
.cpp
| 878
| 35.420273
| 173
| 0.717125
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,157
|
ax_out.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/snd_core/ax_out.cpp
|
#include "Cafe/OS/libs/snd_core/ax.h"
#include "Cafe/OS/libs/snd_core/ax_internal.h"
#include "Cafe/HW/MMU/MMU.h"
#include "audio/IAudioAPI.h"
//#include "ax.h"
#include "config/CemuConfig.h"
namespace snd_core
{
uint32 numProcessedFrames = 0;
void resetNumProcessedFrames()
{
numProcessedFrames = 0;
}
uint32 getNumProcessedFrames()
{
return numProcessedFrames;
}
sint32 __AXMode[AX_DEV_COUNT]; // audio mode (AX_MODE_*) per device
bool AVMGetTVAudioMode(uint32be* tvAudioMode)
{
// 0 -> mono
// 1,2 -> stereo
// 3 -> surround
// 4 -> unknown mode
switch (GetConfig().tv_channels)
{
case kMono:
*tvAudioMode = 0;
break;
case kSurround:
*tvAudioMode = 3;
break;
default:
*tvAudioMode = 2;
break;
}
return true;
}
bool AVMGetDRCSystemAudioMode(uint32be* drcAudioMode)
{
*drcAudioMode = 1; // apparently the default is Stereo(?), MH3U exits if AXGetDeviceMode doesn't return 0 (DRCSystemAudioMode must return 1 to set DRC mode to 0)
return true;
}
sint32 __AXOutTVOutputChannelCount;
sint32 __AXOutDRCOutputChannelCount;
void __AXSetTVMode(sint32 mode)
{
cemu_assert(mode == AX_MODE_STEREO || mode == AX_MODE_6CH || mode == AX_MODE_MONO);
__AXMode[AX_DEV_TV] = mode;
}
void __AXSetDeviceMode(sint32 device, sint32 mode)
{
if (device == AX_DEV_TV)
__AXMode[AX_DEV_TV] = mode;
else if (device == AX_DEV_DRC)
__AXMode[AX_DEV_DRC] = mode;
else if (device == AX_DEV_RMT)
__AXMode[AX_DEV_RMT] = mode;
else
{
cemu_assert_debug(false);
}
}
sint32 AXGetDeviceMode(sint32 device)
{
if (device == AX_DEV_TV || device == AX_DEV_DRC || device == AX_DEV_RMT)
return __AXMode[device];
cemu_assert_debug(false);
return 0;
}
void _AXOutInitDeviceModes()
{
// TV mode
uint32be tvAudioMode;
AVMGetTVAudioMode(&tvAudioMode);
if (tvAudioMode == 0)
{
// mono
__AXSetTVMode(AX_MODE_MONO);
__AXOutTVOutputChannelCount = 1;
}
else if (tvAudioMode == 1 || tvAudioMode == 2)
{
// stereo
__AXSetTVMode(AX_MODE_STEREO);
__AXOutTVOutputChannelCount = 2;
}
else if (tvAudioMode == 3)
{
// surround (6ch)
__AXSetTVMode(AX_MODE_6CH);
__AXOutTVOutputChannelCount = 6;
}
else
{
assert_dbg();
}
// DRC mode
uint32be drcAudioMode;
AVMGetDRCSystemAudioMode(&drcAudioMode);
if (drcAudioMode == 0)
{
// mono
__AXSetDeviceMode(1, AX_MODE_MONO);
__AXOutDRCOutputChannelCount = 1;
}
else if (drcAudioMode == 2)
{
// surround
__AXSetDeviceMode(1, AX_MODE_SURROUND);
__AXOutDRCOutputChannelCount = 2; // output channel count still 2 for DRC 'surround'
}
else if (drcAudioMode == 1)
{
// stereo
__AXSetDeviceMode(1, AX_MODE_STEREO);
__AXOutDRCOutputChannelCount = 2;
}
else
{
assert_dbg();
}
}
void AXOut_Init()
{
_AXOutInitDeviceModes();
}
extern SysAllocator<sint32, AX_SAMPLES_MAX * AX_TV_CHANNEL_COUNT> __AXTVBuffer48;
extern SysAllocator<sint32, AX_SAMPLES_MAX* AX_DRC_CHANNEL_COUNT * 2> __AXDRCBuffer48;
sint16 __buf_AXTVDMABuffers_0[AX_SAMPLES_MAX * AX_TV_CHANNEL_COUNT];
sint16 __buf_AXTVDMABuffers_1[AX_SAMPLES_MAX * AX_TV_CHANNEL_COUNT];
sint16 __buf_AXTVDMABuffers_2[AX_SAMPLES_MAX * AX_TV_CHANNEL_COUNT];
sint16* __AXTVDMABuffers[3] = {__buf_AXTVDMABuffers_0, __buf_AXTVDMABuffers_1, __buf_AXTVDMABuffers_2};
#define AX_FRAMES_PER_GROUP (4)
sint16 tempTVChannelData[AX_SAMPLES_MAX * AX_TV_CHANNEL_COUNT * AX_FRAMES_PER_GROUP] = {};
sint32 tempAudioBlockCounter = 0;
sint16 __buf_AXDRCDMABuffers_0[AX_SAMPLES_MAX * 6];
sint16 __buf_AXDRCDMABuffers_1[AX_SAMPLES_MAX * 6];
sint16 __buf_AXDRCDMABuffers_2[AX_SAMPLES_MAX * 6];
sint16* __AXDRCDMABuffers[3] = { __buf_AXDRCDMABuffers_0, __buf_AXDRCDMABuffers_1, __buf_AXDRCDMABuffers_2 };
sint16 tempDRCChannelData[AX_SAMPLES_MAX * 6 * AX_FRAMES_PER_GROUP] = {};
sint32 tempDRCAudioBlockCounter = 0;
void AIInitDMA(sint16* sampleData, sint32 size)
{
sint32 sampleCount = size / sizeof(sint16); // sample count in total (summed up for all channels)
if (sndGeneric.initParam.frameLength != 0)
{
cemu_assert(false);
}
std::shared_lock lock(g_audioMutex);
const uint32 channels = g_tvAudio ? g_tvAudio->GetChannels() : AX_TV_CHANNEL_COUNT;
sint16* outputChannel = tempTVChannelData + AX_SAMPLES_PER_3MS_48KHZ * tempAudioBlockCounter * channels;
for (sint32 i = 0; i < sampleCount; ++i)
{
outputChannel[i] = _swapEndianS16(sampleData[i]);
}
tempAudioBlockCounter++;
if (tempAudioBlockCounter == AX_FRAMES_PER_GROUP)
{
if(g_tvAudio)
g_tvAudio->FeedBlock(tempTVChannelData);
tempAudioBlockCounter = 0;
}
}
sint32 AIGetSamplesPerChannel(uint32 device)
{
// TV and DRC output the same number of samples
return AX_SAMPLES_PER_3MS_48KHZ;
}
sint32 AIGetChannelCount(uint32 device)
{
if (__AXMode[device] == AX_MODE_6CH)
return 6;
if (__AXMode[device] == AX_MODE_STEREO)
return 2;
// default to mono
return 1;
}
sint16* AIGetCurrentDMABuffer(uint32 device)
{
if (device == AX_DEV_TV)
return __AXTVDMABuffers[0];
else if (device == AX_DEV_DRC)
return __AXDRCDMABuffers[0];
cemu_assert_debug(false);
return nullptr;
}
void AXOut_SubmitTVFrame(sint32 frameIndex)
{
sint32 numSamples = AIGetSamplesPerChannel(AX_DEV_TV);
if (__AXMode[AX_DEV_TV] == AX_MODE_6CH)
{
sint32* inputChannel0 = __AXTVBuffer48.GetPtr() + numSamples * 0;
sint32* inputChannel1 = __AXTVBuffer48.GetPtr() + numSamples * 1;
sint32* inputChannel2 = __AXTVBuffer48.GetPtr() + numSamples * 2;
sint32* inputChannel3 = __AXTVBuffer48.GetPtr() + numSamples * 3;
sint32* inputChannel4 = __AXTVBuffer48.GetPtr() + numSamples * 4;
sint32* inputChannel5 = __AXTVBuffer48.GetPtr() + numSamples * 5;
sint16* dmaOutputBuffer = AIGetCurrentDMABuffer(AX_DEV_TV);
for (sint32 i = 0; i < numSamples; i++)
{
/*
* DirectSound surround order
LEFT 0
RIGHT 1
SUR_LEFT 2
SUR_RIGHT 3
CH_FC 4
CH_LFE 5
=>
Front Left - FL 0
Front Right - FR 1
Front Center - FC 2
Low Frequency - LF 3
Back Left - BL 4
Back Right - BR 5
*/
dmaOutputBuffer[0] = _swapEndianS16((sint16)std::min(std::max(_swapEndianS32(*inputChannel0), -32768), 32767));
dmaOutputBuffer[1] = _swapEndianS16((sint16)std::min(std::max(_swapEndianS32(*inputChannel1), -32768), 32767));
dmaOutputBuffer[4] = _swapEndianS16((sint16)std::min(std::max(_swapEndianS32(*inputChannel2), -32768), 32767));
dmaOutputBuffer[5] = _swapEndianS16((sint16)std::min(std::max(_swapEndianS32(*inputChannel3), -32768), 32767));
dmaOutputBuffer[2] = _swapEndianS16((sint16)std::min(std::max(_swapEndianS32(*inputChannel4), -32768), 32767));
dmaOutputBuffer[3] = _swapEndianS16((sint16)std::min(std::max(_swapEndianS32(*inputChannel5), -32768), 32767));
dmaOutputBuffer += 6;
// next sample
inputChannel0++;
inputChannel1++;
inputChannel2++;
inputChannel3++;
inputChannel4++;
inputChannel5++;
}
AIInitDMA(__AXTVDMABuffers[frameIndex], numSamples * 6 * sizeof(sint16)); // 6ch output
}
else if (__AXMode[AX_DEV_TV] == AX_MODE_STEREO)
{
sint32* inputChannel0 = __AXTVBuffer48.GetPtr() + numSamples * 0;
sint32* inputChannel1 = __AXTVBuffer48.GetPtr() + numSamples * 1;
sint16* dmaOutputBuffer = __AXTVDMABuffers[frameIndex];
for (sint32 i = 0; i < numSamples; i++)
{
dmaOutputBuffer[0] = _swapEndianS16((sint16)std::min(std::max(_swapEndianS32(*inputChannel0), -32768), 32767));
dmaOutputBuffer[1] = _swapEndianS16((sint16)std::min(std::max(_swapEndianS32(*inputChannel1), -32768), 32767));
dmaOutputBuffer += 2;
// next sample
inputChannel0++;
inputChannel1++;
}
AIInitDMA(__AXTVDMABuffers[frameIndex], numSamples * 2 * sizeof(sint16)); // 2ch output
}
else if (__AXMode[AX_DEV_TV] == AX_MODE_MONO)
{
sint32* inputChannel0 = __AXTVBuffer48.GetPtr() + numSamples * 0;
sint16* dmaOutputBuffer = __AXTVDMABuffers[frameIndex];
for (sint32 i = 0; i < numSamples; i++)
{
dmaOutputBuffer[0] = _swapEndianS16((sint16)std::min(std::max(_swapEndianS32(*inputChannel0), -32768), 32767));
dmaOutputBuffer++;
// next sample
inputChannel0++;
}
AIInitDMA(__AXTVDMABuffers[frameIndex], numSamples * 1 * sizeof(sint16)); // 1ch (output as stereo)
}
else
assert_dbg();
}
void AIInitDRCDMA(sint16* sampleData, sint32 size)
{
sint32 sampleCount = size / sizeof(sint16); // sample count in total (summed up for all channels)
if (sndGeneric.initParam.frameLength != 0)
{
cemu_assert(false);
}
std::shared_lock lock(g_audioMutex);
const uint32 channels = g_padAudio ? g_padAudio->GetChannels() : AX_DRC_CHANNEL_COUNT;
sint16* outputChannel = tempDRCChannelData + AX_SAMPLES_PER_3MS_48KHZ * tempDRCAudioBlockCounter * channels;
for (sint32 i = 0; i < sampleCount; ++i)
{
outputChannel[i] = _swapEndianS16(sampleData[i]);
}
tempDRCAudioBlockCounter++;
if (tempDRCAudioBlockCounter == AX_FRAMES_PER_GROUP)
{
if (g_padAudio)
g_padAudio->FeedBlock(tempDRCChannelData);
tempDRCAudioBlockCounter = 0;
}
}
void AXOut_SubmitDRCFrame(sint32 frameIndex)
{
sint32 numSamples = AIGetSamplesPerChannel(AX_DEV_DRC);
if (__AXMode[AX_DEV_DRC] == AX_MODE_6CH)
{
sint32* inputChannel0 = __AXDRCBuffer48.GetPtr() + numSamples * 0;
sint32* inputChannel1 = __AXDRCBuffer48.GetPtr() + numSamples * 1;
sint32* inputChannel2 = __AXDRCBuffer48.GetPtr() + numSamples * 2;
sint32* inputChannel3 = __AXDRCBuffer48.GetPtr() + numSamples * 3;
sint16* dmaOutputBuffer = AIGetCurrentDMABuffer(AX_DEV_DRC);
for (sint32 i = 0; i < numSamples; i++)
{
dmaOutputBuffer[0] = _swapEndianS16((sint16)std::min(std::max(_swapEndianS32(*inputChannel0), -32768), 32767));
dmaOutputBuffer[1] = _swapEndianS16((sint16)std::min(std::max(_swapEndianS32(*inputChannel1), -32768), 32767));
dmaOutputBuffer[4] = 0;
dmaOutputBuffer[5] = 0;
dmaOutputBuffer[2] = 0;
dmaOutputBuffer[3] = 0;
dmaOutputBuffer += 6;
// next sample
inputChannel0++;
inputChannel1++;
inputChannel2++;
inputChannel3++;
}
AIInitDRCDMA(__AXDRCDMABuffers[frameIndex], numSamples * 6 * sizeof(sint16)); // 6ch output
}
else if (__AXMode[AX_DEV_DRC] == AX_MODE_STEREO)
{
sint32* inputChannel0 = __AXDRCBuffer48.GetPtr() + numSamples * 0;
sint32* inputChannel1 = __AXDRCBuffer48.GetPtr() + numSamples * 1;
sint16* dmaOutputBuffer = __AXDRCDMABuffers[frameIndex];
for (sint32 i = 0; i < numSamples; i++)
{
dmaOutputBuffer[0] = _swapEndianS16((sint16)std::min(std::max(_swapEndianS32(*inputChannel0), -32768), 32767));
dmaOutputBuffer[1] = _swapEndianS16((sint16)std::min(std::max(_swapEndianS32(*inputChannel1), -32768), 32767));
dmaOutputBuffer += 2;
// next sample
inputChannel0++;
inputChannel1++;
}
AIInitDRCDMA(__AXDRCDMABuffers[frameIndex], numSamples * 2 * sizeof(sint16)); // 2ch output
}
else if (__AXMode[AX_DEV_DRC] == AX_MODE_MONO)
{
sint32* inputChannel0 = __AXDRCBuffer48.GetPtr() + numSamples * 0;
sint16* dmaOutputBuffer = __AXDRCDMABuffers[frameIndex];
for (sint32 i = 0; i < numSamples; i++)
{
// write mono input as stereo output
dmaOutputBuffer[1] = dmaOutputBuffer[0] = _swapEndianS16((sint16)std::min(std::max(_swapEndianS32(*inputChannel0), -32768), 32767));
dmaOutputBuffer += 2;
// next sample
inputChannel0++;
}
AIInitDRCDMA(__AXDRCDMABuffers[frameIndex], numSamples * 2 * sizeof(sint16)); // 1ch (output as stereo)
}
else
assert_dbg();
}
/* AX output */
uint32 numQueuedFramesSndGeneric = 0;
void AXOut_init()
{
auto& config = GetConfig();
const auto audio_api = (IAudioAPI::AudioAPI)config.audio_api;
numQueuedFramesSndGeneric = 0;
std::unique_lock lock(g_audioMutex);
if (!g_tvAudio)
{
sint32 channels;
switch (config.tv_channels)
{
case 0:
channels = 1; // will mix mono sound on both output channels
break;
case 2:
channels = 6;
break;
default: // stereo
channels = 2;
break;
}
IAudioAPI::DeviceDescriptionPtr device_description;
if (IAudioAPI::IsAudioAPIAvailable(audio_api))
{
auto devices = IAudioAPI::GetDevices(audio_api);
const auto it = std::find_if(devices.begin(), devices.end(), [&config](const auto& d) {return d->GetIdentifier() == config.tv_device; });
if (it != devices.end())
device_description = *it;
}
if (device_description)
{
try
{
g_tvAudio = IAudioAPI::CreateDevice((IAudioAPI::AudioAPI)config.audio_api, device_description, 48000, channels, snd_core::AX_SAMPLES_PER_3MS_48KHZ * AX_FRAMES_PER_GROUP, 16);
g_tvAudio->SetVolume(config.tv_volume);
}
catch (std::runtime_error& ex)
{
cemuLog_log(LogType::Force, "can't initialize tv audio: {}", ex.what());
exit(0);
}
}
}
if (!g_padAudio)
{
sint32 channels;
switch (config.pad_channels)
{
case 0:
channels = 1; // will mix mono sound on both output channels
break;
case 2:
channels = 6;
break;
default: // stereo
channels = 2;
break;
}
IAudioAPI::DeviceDescriptionPtr device_description;
if (IAudioAPI::IsAudioAPIAvailable(audio_api))
{
auto devices = IAudioAPI::GetDevices(audio_api);
const auto it = std::find_if(devices.begin(), devices.end(), [&config](const auto& d) {return d->GetIdentifier() == config.pad_device; });
if (it != devices.end())
device_description = *it;
}
if (device_description)
{
try
{
g_padAudio = IAudioAPI::CreateDevice((IAudioAPI::AudioAPI)config.audio_api, device_description, 48000, channels, snd_core::AX_SAMPLES_PER_3MS_48KHZ * AX_FRAMES_PER_GROUP, 16);
g_padAudio->SetVolume(config.pad_volume);
g_padVolume = config.pad_volume;
}
catch (std::runtime_error& ex)
{
cemuLog_log(LogType::Force, "can't initialize pad audio: {}", ex.what());
exit(0);
}
}
}
}
void AXOut_reset()
{
std::unique_lock lock(g_audioMutex);
if (g_tvAudio)
{
g_tvAudio->Stop();
g_tvAudio.reset();
}
if (g_padAudio)
{
g_padAudio->Stop();
g_padAudio.reset();
}
}
void AXOut_updateDevicePlayState(bool isPlaying)
{
std::shared_lock lock(g_audioMutex);
if (g_tvAudio)
{
if (isPlaying)
g_tvAudio->Play();
else
g_tvAudio->Stop();
}
if (g_padAudio)
{
if (isPlaying)
g_padAudio->Play();
else
g_padAudio->Stop();
}
}
// called periodically to check for AX updates
void AXOut_update()
{
constexpr static auto kTimeout = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::milliseconds(((IAudioAPI::kBlockCount * 3) / 4) * (AX_FRAMES_PER_GROUP * 3)));
constexpr static auto kWaitDuration = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::milliseconds(3));
constexpr static auto kWaitDurationFast = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::microseconds(2900));
constexpr static auto kWaitDurationMinimum = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::microseconds(1700));
// if we haven't buffered any blocks, we will wait less time than usual
bool additional_blocks_required = false;
{
const std::shared_lock lock(g_audioMutex, std::try_to_lock);
if (lock)
additional_blocks_required = (g_tvAudio && g_tvAudio->NeedAdditionalBlocks()) || (g_padAudio && g_padAudio->NeedAdditionalBlocks());
}
const auto wait_duration = additional_blocks_required ? kWaitDurationFast : kWaitDuration;
// s_ax_interval_timer increases by the wait period
// it can lag behind by multiple periods (up to kTimeout) if there is minor stutter in the CPU thread
// s_last_check is always set to the timestamp at the time of firing
// it's used to enforce the minimum wait delay (we want to avoid calling AX update in quick succession because other threads may need to do work first)
static auto s_ax_interval_timer = now_cached() - kWaitDuration;
static auto s_last_check = now_cached();
const auto now = now_cached();
const auto diff = (now - s_ax_interval_timer);
if (diff < wait_duration)
return;
// handle minimum wait time (1.7MS)
if ((now - s_last_check) < kWaitDurationMinimum)
return;
s_last_check = now;
// if we're too far behind, skip forward
if (diff >= kTimeout)
s_ax_interval_timer = (now - wait_duration);
else
s_ax_interval_timer += wait_duration;
if (snd_core::isInitialized())
{
if (numQueuedFramesSndGeneric == snd_core::getNumProcessedFrames())
{
AXOut_updateDevicePlayState(true);
snd_core::AXIst_QueueFrame();
numQueuedFramesSndGeneric++;
}
}
}
}
| 16,765
|
C++
|
.cpp
| 509
| 29.261297
| 180
| 0.690388
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,158
|
ax_aux.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/snd_core/ax_aux.cpp
|
#include "Cafe/OS/libs/snd_core/ax.h"
#include "Cafe/OS/libs/snd_core/ax_internal.h"
#include "Cafe/HW/Espresso/PPCState.h"
namespace snd_core
{
const int AX_AUX_FRAME_COUNT = 2;
// old (deprecated) style AUX callbacks
MPTR __AXOldAuxDRCCallbackFunc[AX_AUX_BUS_COUNT * 2];
MPTR __AXOldAuxDRCCallbackUserParam[AX_AUX_BUS_COUNT * 2];
MPTR __AXOldAuxTVCallbackFunc[AX_AUX_BUS_COUNT];
MPTR __AXOldAuxTVCallbackUserParam[AX_AUX_BUS_COUNT];
// new style AUX callbacks
MPTR __AXAuxDRCCallbackFunc[AX_AUX_BUS_COUNT * 2]; // 2 DRCs
MPTR __AXAuxDRCCallbackUserParam[AX_AUX_BUS_COUNT * 2];
MPTR __AXAuxTVCallbackFunc[AX_AUX_BUS_COUNT];
MPTR __AXAuxTVCallbackUserParam[AX_AUX_BUS_COUNT];
struct AUXTVBuffer
{
sint32be _buf[AX_AUX_FRAME_COUNT * AX_TV_CHANNEL_COUNT * AX_AUX_BUS_COUNT * AX_SAMPLES_MAX];
sint32be* GetBuffer(uint32 auxBus, uint32 auxFrame, uint32 channel = 0)
{
const size_t samplesPerChannel = AXGetInputSamplesPerFrame();
const size_t samplesPerBus = AX_SAMPLES_PER_3MS_48KHZ * AX_TV_CHANNEL_COUNT;
const size_t samplesPerFrame = samplesPerBus * AX_AUX_BUS_COUNT;
return _buf + auxFrame * samplesPerFrame + auxBus * samplesPerBus + channel * samplesPerChannel;
}
void ClearBuffer()
{
memset(_buf, 0, sizeof(_buf));
}
};
struct AUXDRCBuffer
{
sint32be _buf[AX_AUX_FRAME_COUNT * AX_DRC_CHANNEL_COUNT * AX_AUX_BUS_COUNT * AX_SAMPLES_MAX];
sint32be* GetBuffer(uint32 auxBus, uint32 auxFrame, uint32 channel = 0)
{
const size_t samplesPerChannel = AXGetInputSamplesPerFrame();
const size_t samplesPerBus = AX_SAMPLES_PER_3MS_48KHZ * AX_DRC_CHANNEL_COUNT;
const size_t samplesPerFrame = samplesPerBus * AX_AUX_BUS_COUNT;
return _buf + auxFrame * samplesPerFrame + auxBus * samplesPerBus + channel * samplesPerChannel;
}
void ClearBuffer()
{
memset(_buf, 0, sizeof(_buf));
}
};
SysAllocator<AUXTVBuffer> __AXAuxTVBuffer;
SysAllocator<AUXDRCBuffer, 2> __AXAuxDRCBuffer;
uint32 __AXCurrentAuxInputFrameIndex = 0;
uint32 AXAux_GetOutputFrameIndex()
{
return 1 - __AXCurrentAuxInputFrameIndex;
}
sint32be* AXAux_GetInputBuffer(sint32 device, sint32 deviceIndex, sint32 auxBus)
{
if (auxBus < 0 || auxBus >= AX_AUX_BUS_COUNT)
return nullptr;
if (device == AX_DEV_TV)
{
cemu_assert_debug(deviceIndex == 0);
if (__AXOldAuxTVCallbackFunc[auxBus] == MPTR_NULL && __AXAuxTVCallbackFunc[auxBus] == MPTR_NULL)
return nullptr;
return __AXAuxTVBuffer->GetBuffer(auxBus, __AXCurrentAuxInputFrameIndex);
}
else if (device == AX_DEV_DRC)
{
cemu_assert_debug(deviceIndex >= 0 && deviceIndex <= 1);
if (__AXOldAuxDRCCallbackFunc[deviceIndex * AX_AUX_BUS_COUNT + auxBus] == MPTR_NULL && __AXAuxDRCCallbackFunc[deviceIndex * AX_AUX_BUS_COUNT + auxBus] == MPTR_NULL)
return nullptr;
return __AXAuxDRCBuffer[deviceIndex].GetBuffer(auxBus, __AXCurrentAuxInputFrameIndex);
}
else
{
cemu_assert_debug(false);
}
return nullptr;
}
sint32be* AXAux_GetOutputBuffer(sint32 device, sint32 deviceIndex, sint32 auxBus)
{
uint32 outputFrameIndex = AXAux_GetOutputFrameIndex();
if (device == AX_DEV_TV)
{
cemu_assert_debug(deviceIndex == 0);
if (__AXOldAuxTVCallbackFunc[auxBus] == MPTR_NULL && __AXAuxTVCallbackFunc[auxBus] == MPTR_NULL)
return nullptr;
return __AXAuxTVBuffer->GetBuffer(auxBus, outputFrameIndex);
}
else if (device == AX_DEV_DRC)
{
cemu_assert_debug(deviceIndex >= 0 && deviceIndex <= 1);
if (__AXOldAuxDRCCallbackFunc[deviceIndex * AX_AUX_BUS_COUNT + auxBus] == MPTR_NULL && __AXAuxDRCCallbackFunc[deviceIndex * AX_AUX_BUS_COUNT + auxBus] == MPTR_NULL)
return nullptr;
return __AXAuxDRCBuffer[deviceIndex].GetBuffer(auxBus, outputFrameIndex);
}
else
{
cemu_assert_debug(false);
}
return nullptr;
}
void AXAux_Init()
{
__AXCurrentAuxInputFrameIndex = 0;
__AXAuxTVBuffer->ClearBuffer();
__AXAuxDRCBuffer[0].ClearBuffer();
__AXAuxDRCBuffer[1].ClearBuffer();
memset(__AXAuxTVCallbackFunc, 0, sizeof(__AXAuxTVCallbackFunc));
memset(__AXAuxTVCallbackUserParam, 0, sizeof(__AXAuxTVCallbackUserParam));
memset(__AXOldAuxTVCallbackFunc, 0, sizeof(__AXOldAuxTVCallbackFunc));
memset(__AXOldAuxTVCallbackUserParam, 0, sizeof(__AXOldAuxTVCallbackUserParam));
memset(__AXAuxDRCCallbackFunc, 0, sizeof(__AXAuxDRCCallbackFunc));
memset(__AXAuxDRCCallbackUserParam, 0, sizeof(__AXAuxDRCCallbackUserParam));
memset(__AXOldAuxDRCCallbackFunc, 0, sizeof(__AXOldAuxDRCCallbackFunc));
memset(__AXOldAuxDRCCallbackUserParam, 0, sizeof(__AXOldAuxDRCCallbackUserParam));
// init aux return volume
__AXTVAuxReturnVolume[0] = 0x8000;
__AXTVAuxReturnVolume[1] = 0x8000;
__AXTVAuxReturnVolume[2] = 0x8000;
}
sint32 AXRegisterAuxCallback(sint32 device, sint32 deviceIndex, uint32 auxBusIndex, MPTR funcMPTR, MPTR userParam)
{
sint32 r = AXIsValidDevice(device, deviceIndex);
if (r != 0)
return r;
if (auxBusIndex >= AX_AUX_BUS_COUNT)
return -5;
if (device == AX_DEV_TV)
{
__AXAuxTVCallbackFunc[auxBusIndex] = funcMPTR;
__AXAuxTVCallbackUserParam[auxBusIndex] = userParam;
}
else if (device == AX_DEV_DRC)
{
__AXAuxDRCCallbackFunc[auxBusIndex + deviceIndex * 3] = funcMPTR;
__AXAuxDRCCallbackUserParam[auxBusIndex + deviceIndex * 3] = userParam;
}
else if (device == AX_DEV_RMT)
{
cemu_assert_debug(false);
}
return 0;
}
sint32 AXGetAuxCallback(sint32 device, sint32 deviceIndex, uint32 auxBusIndex, MEMPTR<uint32be> funcPtrOut, MEMPTR<uint32be> contextPtrOut)
{
sint32 r = AXIsValidDevice(device, deviceIndex);
if (r != 0)
return r;
if (auxBusIndex >= AX_AUX_BUS_COUNT)
return -5;
if (device == AX_DEV_TV)
{
*funcPtrOut = __AXAuxTVCallbackFunc[auxBusIndex];
*contextPtrOut = __AXAuxTVCallbackUserParam[auxBusIndex];
}
else if (device == AX_DEV_DRC)
{
*funcPtrOut = __AXAuxDRCCallbackFunc[auxBusIndex + deviceIndex * 3];
*contextPtrOut = __AXAuxDRCCallbackUserParam[auxBusIndex + deviceIndex * 3];
}
else if (device == AX_DEV_RMT)
{
cemu_assert_debug(false);
*funcPtrOut = MPTR_NULL;
*contextPtrOut = MPTR_NULL;
}
return 0;
}
SysAllocator<MEMPTR<sint32be>, 6> __AXAuxCB_dataPtrs;
SysAllocator<AXAUXCBCHANNELINFO> __AXAuxCB_auxCBStruct;
void AXAux_Process()
{
uint32 processedAuxFrameIndex = AXAux_GetOutputFrameIndex();
uint32 sampleCount = AXGetInputSamplesPerFrame();
// TV aux callbacks
uint32 tvChannelCount = AX_TV_CHANNEL_COUNT;
for (sint32 auxBusIndex = 0; auxBusIndex < AX_AUX_BUS_COUNT; auxBusIndex++)
{
MPTR auxCBFuncMPTR = MPTR_NULL;
auxCBFuncMPTR = __AXAuxTVCallbackFunc[auxBusIndex];
if (auxCBFuncMPTR == MPTR_NULL)
auxCBFuncMPTR = __AXOldAuxTVCallbackFunc[auxBusIndex];
if (auxCBFuncMPTR == MPTR_NULL)
{
void* auxOutput = __AXAuxTVBuffer->GetBuffer(auxBusIndex, processedAuxFrameIndex);
memset(auxOutput, 0, sampleCount * AX_TV_CHANNEL_COUNT * sizeof(sint32));
continue;
}
for (sint32 channelIndex = 0; channelIndex < AX_TV_CHANNEL_COUNT; channelIndex++)
__AXAuxCB_dataPtrs[channelIndex] = __AXAuxTVBuffer->GetBuffer(auxBusIndex, processedAuxFrameIndex, channelIndex);
// do callback
if (__AXAuxTVCallbackFunc[auxBusIndex] != MPTR_NULL)
{
// new style callback
AXAUXCBCHANNELINFO* cbStruct = __AXAuxCB_auxCBStruct.GetPtr();
cbStruct->numChannels = tvChannelCount;
cbStruct->numSamples = sampleCount;
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
hCPU->gpr[3] = __AXAuxCB_dataPtrs.GetMPTR();
hCPU->gpr[4] = __AXAuxTVCallbackUserParam[auxBusIndex];
hCPU->gpr[5] = __AXAuxCB_auxCBStruct.GetMPTR();
PPCCore_executeCallbackInternal(auxCBFuncMPTR);
}
else
{
// old style callback
cemu_assert_debug(false); // todo
}
}
// DRC aux callbacks
for (sint32 drcIndex = 0; drcIndex < 2; drcIndex++)
{
uint32 drcChannelCount = AX_DRC_CHANNEL_COUNT;
for (sint32 auxBusIndex = 0; auxBusIndex < AX_AUX_BUS_COUNT; auxBusIndex++)
{
MPTR auxCBFuncMPTR = MPTR_NULL;
auxCBFuncMPTR = __AXAuxDRCCallbackFunc[auxBusIndex + drcIndex * 3];
if (auxCBFuncMPTR == MPTR_NULL)
{
auxCBFuncMPTR = __AXOldAuxDRCCallbackFunc[auxBusIndex + drcIndex * 3];
}
if (auxCBFuncMPTR == MPTR_NULL)
{
void* auxOutput = __AXAuxDRCBuffer[drcIndex].GetBuffer(auxBusIndex, processedAuxFrameIndex);
memset(auxOutput, 0, 96 * 4 * sizeof(sint32));
continue;
}
if (__AXAuxDRCCallbackFunc[auxBusIndex + drcIndex * 3] != MPTR_NULL)
{
// new style callback
for (sint32 channelIndex = 0; channelIndex < AX_DRC_CHANNEL_COUNT; channelIndex++)
__AXAuxCB_dataPtrs[channelIndex] = __AXAuxDRCBuffer[drcIndex].GetBuffer(auxBusIndex, processedAuxFrameIndex, channelIndex);
AXAUXCBCHANNELINFO* cbStruct = __AXAuxCB_auxCBStruct.GetPtr();
cbStruct->numChannels = drcChannelCount;
cbStruct->numSamples = sampleCount;
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
hCPU->gpr[3] = __AXAuxCB_dataPtrs.GetMPTR();
hCPU->gpr[4] = __AXAuxDRCCallbackUserParam[auxBusIndex + drcIndex * 3];
hCPU->gpr[5] = __AXAuxCB_auxCBStruct.GetMPTR();
PPCCore_executeCallbackInternal(auxCBFuncMPTR);
}
else
{
// old style callback
cemu_assert_debug(false);
}
}
}
}
void AXAux_incrementBufferIndex()
{
__AXCurrentAuxInputFrameIndex = 1 - __AXCurrentAuxInputFrameIndex;
}
sint32 AXSetAuxReturnVolume(uint32 device, uint32 deviceIndex, uint32 auxBus, uint16 volume)
{
sint32 r = AXIsValidDevice(device, deviceIndex);
if (r)
return r;
if (auxBus >= AX_AUX_BUS_COUNT)
return -5;
if( device == AX_DEV_TV )
{
__AXTVAuxReturnVolume[auxBus] = volume;
}
else
{
cemuLog_logDebug(LogType::Force, "sndcore2.AXSetAuxReturnVolume() - unsupported device {}", device);
}
return 0;
}
}
| 9,862
|
C++
|
.cpp
| 270
| 32.97037
| 167
| 0.727026
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,159
|
ax_exports.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/snd_core/ax_exports.cpp
|
#include "Cafe/OS/libs/snd_core/ax.h"
#include "Cafe/OS/libs/snd_core/ax_internal.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_MessageQueue.h"
namespace snd_core
{
sndGeneric_t sndGeneric;
void AXResetToDefaultState()
{
memset(&sndGeneric, 0x00, sizeof(sndGeneric));
resetNumProcessedFrames();
AXVBP_Reset();
}
bool AXIsInit()
{
return sndGeneric.isInitialized;
}
void __AXInit(bool isSoundCore2, uint32 frameLength, uint32 rendererFreq, uint32 pipelineMode)
{
cemu_assert(frameLength == AX_FRAMELENGTH_3MS);
cemu_assert(rendererFreq == AX_RENDERER_FREQ_32KHZ || rendererFreq == AX_RENDERER_FREQ_48KHZ);
sndGeneric.isSoundCore2 = isSoundCore2;
sndGeneric.initParam.frameLength = frameLength;
sndGeneric.initParam.rendererFreq = rendererFreq;
sndGeneric.initParam.pipelineMode = pipelineMode;
// init submodules
AXIst_Init();
AXOut_Init();
AXVPB_Init();
AXAux_Init();
AXMix_Init();
AXMultiVoice_Init();
AXIst_InitThread();
sndGeneric.isInitialized = true;
}
void sndcore2_AXInitWithParams(AXINITPARAM* initParam)
{
if (sndGeneric.isInitialized)
return;
__AXInit(true, initParam->frameLength, initParam->freq, initParam->pipelineMode);
}
void sndcore2_AXInit()
{
if (sndGeneric.isInitialized)
return;
__AXInit(true, AX_FRAMELENGTH_3MS, AX_RENDERER_FREQ_32KHZ, AX_PIPELINE_SINGLE);
}
void sndcore1_AXInit()
{
if (sndGeneric.isInitialized)
return;
__AXInit(false, AX_FRAMELENGTH_3MS, AX_RENDERER_FREQ_32KHZ, AX_PIPELINE_SINGLE);
}
void sndcore2_AXInitEx(uint32 uknParam)
{
cemu_assert_debug(uknParam == 0);
if (sndGeneric.isInitialized)
return;
__AXInit(true, AX_FRAMELENGTH_3MS, AX_RENDERER_FREQ_32KHZ, AX_PIPELINE_SINGLE);
}
void sndcore1_AXInitEx(uint32 uknParam)
{
cemu_assert_debug(uknParam == 0);
if (sndGeneric.isInitialized)
return;
__AXInit(false, AX_FRAMELENGTH_3MS, AX_RENDERER_FREQ_32KHZ, AX_PIPELINE_SINGLE);
}
void AXQuit()
{
AXResetCallbacks();
// todo - should we wait to make sure any active callbacks are finished with execution before we exit AXQuit?
// request worker thread stop and wait until complete
AXIst_StopThread();
// clean up subsystems
AXVBP_Reset();
sndGeneric.isInitialized = false;
}
sint32 AXGetMaxVoices()
{
return sndGeneric.isInitialized ? AX_MAX_VOICES : 0;
}
void export_AXGetDeviceFinalMixCallback(PPCInterpreter_t* hCPU)
{
ppcDefineParamS32(device, 0);
ppcDefineParamU32BEPtr(funcAddrPtr, 1);
sint32 r = AXGetDeviceFinalMixCallback(device, funcAddrPtr);
cemuLog_log(LogType::SoundAPI, "AXGetDeviceFinalMixCallback({},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4]);
osLib_returnFromFunction(hCPU, r);
}
void export_AXRegisterDeviceFinalMixCallback(PPCInterpreter_t* hCPU)
{
ppcDefineParamS32(device, 0);
ppcDefineParamMPTR(funcAddr, 1);
cemuLog_log(LogType::SoundAPI, "AXRegisterDeviceFinalMixCallback({},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4]);
sint32 r = AXRegisterDeviceFinalMixCallback(device, funcAddr);
osLib_returnFromFunction(hCPU, r);
}
void export_AXRegisterAppFrameCallback(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::SoundAPI, "AXRegisterAppFrameCallback(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamMPTR(funcAddr, 0);
sint32 r = AXRegisterAppFrameCallback(funcAddr);
osLib_returnFromFunction(hCPU, r);
}
void export_AXDeregisterAppFrameCallback(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::SoundAPI, "AXDeregisterAppFrameCallback(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamMPTR(funcAddr, 0);
sint32 r = AXDeregisterAppFrameCallback(funcAddr);
osLib_returnFromFunction(hCPU, r);
}
void export_AXRegisterFrameCallback(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::SoundAPI, "AXRegisterFrameCallback(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamMPTR(funcAddr, 0);
sint32 r = AXRegisterFrameCallback(funcAddr);
osLib_returnFromFunction(hCPU, r);
}
void export_AXRegisterCallback(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::SoundAPI, "AXRegisterCallback(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamMPTR(funcAddr, 0);
sint32 r = AXRegisterFrameCallback(funcAddr);
osLib_returnFromFunction(hCPU, r);
}
void export_AXRegisterAuxCallback(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::SoundAPI, "AXRegisterAuxCallback(0x{:08x},0x{:08x},0x{:08x},0x{:08x},0x{:08x}) LR {:08x}", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6], hCPU->gpr[7], hCPU->spr.LR);
ppcDefineParamU32(device, 0);
ppcDefineParamU32(deviceIndex, 1);
ppcDefineParamU32(auxBusIndex, 2);
ppcDefineParamMPTR(funcAddr, 3);
ppcDefineParamMPTR(userParam, 4);
sint32 r = AXRegisterAuxCallback(device, deviceIndex, auxBusIndex, funcAddr, userParam);
osLib_returnFromFunction(hCPU, r);
}
void export_AXGetAuxCallback(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::SoundAPI, "AXGetAuxCallback(0x{:08x},0x{:08x},0x{:08x},0x{:08x},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6], hCPU->gpr[7]);
ppcDefineParamU32(device, 0);
ppcDefineParamU32(deviceIndex, 1);
ppcDefineParamU32(auxBusIndex, 2);
ppcDefineParamMEMPTR(funcAddrOut, uint32be, 3);
ppcDefineParamMEMPTR(userParamOut, uint32be, 4);
sint32 r = AXGetAuxCallback(device, deviceIndex, auxBusIndex, funcAddrOut, userParamOut);
osLib_returnFromFunction(hCPU, r);
}
void export_AXSetAuxReturnVolume(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::SoundAPI, "AXSetAuxReturnVolume(0x{:08x},0x{:08x},0x{:08x},0x{:04x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6]);
ppcDefineParamU32(device, 0);
ppcDefineParamU32(deviceIndex, 1);
ppcDefineParamU32(auxBusIndex, 2);
ppcDefineParamU16(volume, 3);
sint32 r = AXSetAuxReturnVolume(device, deviceIndex, auxBusIndex, volume);
osLib_returnFromFunction(hCPU, r);
}
void export_AXGetDeviceMode(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::SoundAPI, "AXGetDeviceMode({})", hCPU->gpr[3]);
ppcDefineParamS32(device, 0);
ppcDefineParamU32BEPtr(mode, 1);
*mode = AXGetDeviceMode(device);
osLib_returnFromFunction(hCPU, 0);
}
void export_AXSetDeviceUpsampleStage(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::SoundAPI, "AXSetDeviceUpsampleStage({},{})", hCPU->gpr[3], hCPU->gpr[4]);
ppcDefineParamS32(device, 0);
ppcDefineParamS32(upsampleStage, 1);
sint32 r = AXSetDeviceUpsampleStage(device, upsampleStage);
osLib_returnFromFunction(hCPU, r);
}
void export_AXGetDeviceUpsampleStage(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::SoundAPI, "AXGetDeviceUpsampleStage({},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4]);
ppcDefineParamS32(device, 0);
ppcDefineParamU32BEPtr(upsampleStagePtr, 1);
sint32 r = AXGetDeviceUpsampleStage(device, upsampleStagePtr);
osLib_returnFromFunction(hCPU, r);
}
void export_AXAcquireVoiceEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamS32(priority, 0);
ppcDefineParamMPTR(callbackEx, 1);
ppcDefineParamMPTR(userParam, 2);
cemuLog_log(LogType::SoundAPI, "AXAcquireVoiceEx({},0x{:08x},0x{:08x})", priority, callbackEx, userParam);
MEMPTR<AXVPB> r = AXAcquireVoiceEx(priority, callbackEx, userParam);
osLib_returnFromFunction(hCPU, r.GetMPTR());
}
void export_AXAcquireVoice(PPCInterpreter_t* hCPU)
{
ppcDefineParamS32(priority, 0);
ppcDefineParamMPTR(callback, 1);
ppcDefineParamMPTR(userParam, 2);
cemuLog_log(LogType::SoundAPI, "AXAcquireVoice({},0x{:08x},0x{:08x})", priority, callback, userParam);
MEMPTR<AXVPB> r = AXAcquireVoiceEx(priority, MPTR_NULL, MPTR_NULL);
if (r.IsNull() == false)
{
r->callback = (uint32be)callback;
r->userParam = (uint32be)userParam;
}
osLib_returnFromFunction(hCPU, r.GetMPTR());
}
void export_AXFreeVoice(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(vpb, AXVPB, 0);
cemuLog_log(LogType::SoundAPI, "AXFreeVoice(0x{:08x})", hCPU->gpr[3]);
AXFreeVoice(vpb);
osLib_returnFromFunction(hCPU, 0);
}
void export_AXUserIsProtected(PPCInterpreter_t* hCPU)
{
sint32 r = AXUserIsProtected();
cemuLog_log(LogType::SoundAPI, "AXUserIsProtected() -> {}", r!=0?"true":"false");
osLib_returnFromFunction(hCPU, r);
}
void export_AXUserBegin(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::SoundAPI, "AXUserBegin()");
sint32 r = AXUserBegin();
osLib_returnFromFunction(hCPU, r);
}
void export_AXUserEnd(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::SoundAPI, "AXUserEnd()");
sint32 r = AXUserEnd();
osLib_returnFromFunction(hCPU, r);
}
void export_AXVoiceBegin(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(vpb, AXVPB, 0);
cemuLog_log(LogType::SoundAPI, "AXVoiceBegin(0x{:08x})", hCPU->gpr[3]);
sint32 r = AXVoiceBegin(vpb);
osLib_returnFromFunction(hCPU, r);
}
void export_AXVoiceEnd(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(vpb, AXVPB, 0);
cemuLog_log(LogType::SoundAPI, "AXVoiceEnd(0x{:08x})", hCPU->gpr[3]);
sint32 r = AXVoiceEnd(vpb);
osLib_returnFromFunction(hCPU, r);
}
void export_AXVoiceIsProtected(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(vpb, AXVPB, 0);
cemuLog_log(LogType::SoundAPI, "AXVoiceIsProtected(0x{:08x})", hCPU->gpr[3]);
sint32 r = AXVoiceProtection_IsProtectedByCurrentThread(vpb)?1:0;
osLib_returnFromFunction(hCPU, r);
}
uint32 __AXCalculatePointerHighExtension(uint16 format, MPTR sampleBase, uint32 offset)
{
sampleBase = memory_virtualToPhysical(sampleBase);
uint32 ptrHighExtension;
if (format == AX_FORMAT_PCM8)
{
ptrHighExtension = ((sampleBase + offset) >> 29);
}
else if (format == AX_FORMAT_PCM16)
{
ptrHighExtension = ((sampleBase + offset * 2) >> 29);
}
else if (format == AX_FORMAT_ADPCM)
{
ptrHighExtension = ((sampleBase + offset / 2) >> 29);
}
return ptrHighExtension;
}
void export_AXCheckVoiceOffsets(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::SoundAPI, "AXCheckVoiceOffsets(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamStructPtr(pbOffset, AXPBOFFSET_t, 0);
uint16 format = _swapEndianU16(pbOffset->format);
MPTR sampleBase = _swapEndianU32(pbOffset->samples);
uint32 highExtLoop = __AXCalculatePointerHighExtension(format, sampleBase, _swapEndianU32(pbOffset->loopOffset));
uint32 highExtEnd = __AXCalculatePointerHighExtension(format, sampleBase, _swapEndianU32(pbOffset->endOffset));
uint32 highExtCurrent = __AXCalculatePointerHighExtension(format, sampleBase, _swapEndianU32(pbOffset->currentOffset));
bool isSameRange;
if (highExtLoop == highExtEnd && highExtEnd == highExtCurrent)
isSameRange = true;
else
isSameRange = false;
osLib_returnFromFunction(hCPU, isSameRange ? 1 : 0);
}
void export_AXSetDeviceRemixMatrix(PPCInterpreter_t* hCPU)
{
ppcDefineParamS32(device, 0);
ppcDefineParamU32(chanIn, 1);
ppcDefineParamU32(chanOut, 2);
ppcDefineParamMEMPTR(matrix, float32be, 3);
cemuLog_log(LogType::SoundAPI, "AXSetDeviceRemixMatrix({},{},{},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6]);
const auto result = AXSetDeviceRemixMatrix(device, chanIn, chanOut, matrix);
osLib_returnFromFunction(hCPU, result);
}
void export_AXGetDeviceRemixMatrix(PPCInterpreter_t* hCPU)
{
ppcDefineParamS32(device, 0);
ppcDefineParamU32(chanIn, 1);
ppcDefineParamU32(chanOut, 2);
ppcDefineParamMEMPTR(matrix, MEMPTR<float32be>, 3);
cemuLog_log(LogType::SoundAPI, "AXGetDeviceRemixMatrix({},{},{},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6]);
const auto result = AXGetDeviceRemixMatrix(device, chanIn, chanOut, matrix);
osLib_returnFromFunction(hCPU, result);
}
struct AXGetDeviceFinalOutput_t
{
/* +0x00 */ uint32be channelCount;
/* +0x04 */ uint32be uknValue;
/* +0x08 */ uint32be ukn08;
/* +0x0C */ uint32be ukn0C;
/* +0x10 */ uint32be size;
// struct might be bigger?
};
sint32 AXGetDeviceFinalOutput(uint32 device, sint16be* sampleBufferOutput, uint32 bufferSize, AXGetDeviceFinalOutput_t* output)
{
if (device != AX_DEV_TV && device != AX_DEV_DRC)
return -1;
sint32 channelCount = AIGetChannelCount(device);
sint32 samplesPerChannel = AIGetSamplesPerChannel(device);
sint32 samplesToCopy = samplesPerChannel * channelCount;
if (bufferSize < (samplesToCopy * sizeof(sint16be)))
return -11; // buffer not large enough
// copy samples to buffer
sint16* samplesBuffer = AIGetCurrentDMABuffer(device);
for (sint32 i = 0; i < samplesToCopy; i++)
sampleBufferOutput[i] = samplesBuffer[i];
// set output struct
output->size = samplesToCopy * sizeof(sint16be);
output->channelCount = channelCount;
output->uknValue = 1; // always set to 1/true?
return 0;
}
void loadExportsSndCore1()
{
cafeExportRegisterFunc(sndcore1_AXInit, "snd_core", "AXInit", LogType::SoundAPI);
cafeExportRegisterFunc(sndcore1_AXInitEx, "snd_core", "AXInitEx", LogType::SoundAPI);
cafeExportRegister("snd_core", AXIsInit, LogType::SoundAPI);
cafeExportRegister("snd_core", AXQuit, LogType::SoundAPI);
cafeExportRegister("snd_core", AXGetMaxVoices, LogType::SoundAPI);
cafeExportRegister("snd_core", AXGetInputSamplesPerFrame, LogType::SoundAPI);
cafeExportRegister("snd_core", AXGetInputSamplesPerSec, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetDefaultMixerSelect, LogType::SoundAPI);
cafeExportRegister("snd_core", AXGetDefaultMixerSelect, LogType::SoundAPI);
osLib_addFunction("snd_core", "AXGetDeviceFinalMixCallback", export_AXGetDeviceFinalMixCallback);
osLib_addFunction("snd_core", "AXRegisterDeviceFinalMixCallback", export_AXRegisterDeviceFinalMixCallback);
osLib_addFunction("snd_core", "AXRegisterAppFrameCallback", export_AXRegisterAppFrameCallback);
osLib_addFunction("snd_core", "AXDeregisterAppFrameCallback", export_AXDeregisterAppFrameCallback);
osLib_addFunction("snd_core", "AXRegisterFrameCallback", export_AXRegisterFrameCallback);
osLib_addFunction("snd_core", "AXRegisterCallback", export_AXRegisterCallback);
osLib_addFunction("snd_core", "AXRegisterAuxCallback", export_AXRegisterAuxCallback);
osLib_addFunction("snd_core", "AXGetAuxCallback", export_AXGetAuxCallback);
osLib_addFunction("snd_core", "AXSetAuxReturnVolume", export_AXSetAuxReturnVolume);
osLib_addFunction("snd_core", "AXGetDeviceMode", export_AXGetDeviceMode);
osLib_addFunction("snd_core", "AXSetDeviceUpsampleStage", export_AXSetDeviceUpsampleStage);
osLib_addFunction("snd_core", "AXGetDeviceUpsampleStage", export_AXGetDeviceUpsampleStage);
osLib_addFunction("snd_core", "AXAcquireVoiceEx", export_AXAcquireVoiceEx);
osLib_addFunction("snd_core", "AXAcquireVoice", export_AXAcquireVoice);
osLib_addFunction("snd_core", "AXFreeVoice", export_AXFreeVoice);
osLib_addFunction("snd_core", "AXUserIsProtected", export_AXUserIsProtected);
osLib_addFunction("snd_core", "AXUserBegin", export_AXUserBegin);
osLib_addFunction("snd_core", "AXUserEnd", export_AXUserEnd);
osLib_addFunction("snd_core", "AXVoiceBegin", export_AXVoiceBegin);
osLib_addFunction("snd_core", "AXVoiceEnd", export_AXVoiceEnd);
osLib_addFunction("snd_core", "AXVoiceIsProtected", export_AXVoiceIsProtected);
osLib_addFunction("snd_core", "AXCheckVoiceOffsets", export_AXCheckVoiceOffsets);
osLib_addFunction("snd_core", "AXSetDeviceRemixMatrix", export_AXSetDeviceRemixMatrix);
osLib_addFunction("snd_core", "AXGetDeviceRemixMatrix", export_AXGetDeviceRemixMatrix);
cafeExportRegister("snd_core", AXGetDeviceFinalOutput, LogType::SoundAPI);
}
void loadExportsSndCore2()
{
cafeExportRegisterFunc(sndcore2_AXInitWithParams, "sndcore2", "AXInitWithParams", LogType::SoundAPI);
cafeExportRegisterFunc(sndcore2_AXInit, "sndcore2", "AXInit", LogType::SoundAPI);
cafeExportRegisterFunc(sndcore2_AXInitEx, "sndcore2", "AXInitEx", LogType::SoundAPI);
cafeExportRegister("sndcore2", AXIsInit, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXQuit, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXGetMaxVoices, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXGetInputSamplesPerFrame, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXGetInputSamplesPerSec, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetDefaultMixerSelect, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXGetDefaultMixerSelect, LogType::SoundAPI);
osLib_addFunction("sndcore2", "AXGetDeviceFinalMixCallback", export_AXGetDeviceFinalMixCallback);
osLib_addFunction("sndcore2", "AXRegisterDeviceFinalMixCallback", export_AXRegisterDeviceFinalMixCallback);
osLib_addFunction("sndcore2", "AXRegisterAppFrameCallback", export_AXRegisterAppFrameCallback);
osLib_addFunction("sndcore2", "AXDeregisterAppFrameCallback", export_AXDeregisterAppFrameCallback);
osLib_addFunction("sndcore2", "AXRegisterFrameCallback", export_AXRegisterFrameCallback);
osLib_addFunction("sndcore2", "AXRegisterCallback", export_AXRegisterCallback);
osLib_addFunction("sndcore2", "AXRegisterAuxCallback", export_AXRegisterAuxCallback);
osLib_addFunction("sndcore2", "AXGetAuxCallback", export_AXGetAuxCallback);
osLib_addFunction("sndcore2", "AXSetAuxReturnVolume", export_AXSetAuxReturnVolume);
osLib_addFunction("sndcore2", "AXGetDeviceMode", export_AXGetDeviceMode);
osLib_addFunction("sndcore2", "AXSetDeviceUpsampleStage", export_AXSetDeviceUpsampleStage);
osLib_addFunction("sndcore2", "AXGetDeviceUpsampleStage", export_AXGetDeviceUpsampleStage);
osLib_addFunction("sndcore2", "AXAcquireVoiceEx", export_AXAcquireVoiceEx);
osLib_addFunction("sndcore2", "AXAcquireVoice", export_AXAcquireVoice);
osLib_addFunction("sndcore2", "AXFreeVoice", export_AXFreeVoice);
osLib_addFunction("sndcore2", "AXUserIsProtected", export_AXUserIsProtected);
osLib_addFunction("sndcore2", "AXUserBegin", export_AXUserBegin);
osLib_addFunction("sndcore2", "AXUserEnd", export_AXUserEnd);
osLib_addFunction("sndcore2", "AXVoiceBegin", export_AXVoiceBegin);
osLib_addFunction("sndcore2", "AXVoiceEnd", export_AXVoiceEnd);
osLib_addFunction("sndcore2", "AXVoiceIsProtected", export_AXVoiceIsProtected);
osLib_addFunction("sndcore2", "AXCheckVoiceOffsets", export_AXCheckVoiceOffsets);
osLib_addFunction("sndcore2", "AXSetDeviceRemixMatrix", export_AXSetDeviceRemixMatrix);
osLib_addFunction("sndcore2", "AXGetDeviceRemixMatrix", export_AXGetDeviceRemixMatrix);
cafeExportRegister("sndcore2", AXGetDeviceFinalOutput, LogType::SoundAPI);
// multi voice
cafeExportRegister("sndcore2", AXAcquireMultiVoice, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXFreeMultiVoice, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXGetMultiVoiceReformatBufferSize, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetMultiVoiceType, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetMultiVoiceAdpcm, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetMultiVoiceSrcType, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetMultiVoiceOffsets, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetMultiVoiceVe, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetMultiVoiceSrcRatio, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetMultiVoiceSrc, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetMultiVoiceLoop, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetMultiVoiceState, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetMultiVoiceAdpcmLoop, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXIsMultiVoiceRunning, LogType::SoundAPI);
}
void loadExports()
{
AXResetToDefaultState();
loadExportsSndCore1();
loadExportsSndCore2();
}
bool isInitialized()
{
return sndGeneric.isInitialized;
}
void reset()
{
AXOut_reset();
AXResetToDefaultState();
sndGeneric.isInitialized = false;
}
}
| 19,760
|
C++
|
.cpp
| 440
| 41.840909
| 198
| 0.771111
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,160
|
ax_voice.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/snd_core/ax_voice.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Espresso/PPCState.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "Cafe/OS/libs/snd_core/ax.h"
#include "Cafe/OS/libs/snd_core/ax_internal.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "util/helpers/fspinlock.h"
namespace snd_core
{
inline void AXSetSyncFlag(AXVPB* vpb, uint32 flags)
{
vpb->sync = (uint32be)((uint32)vpb->sync | flags);
}
inline void AXResetSyncFlag(AXVPB* vpb, uint32 flags)
{
vpb->sync = (uint32be)((uint32)vpb->sync & ~flags);
}
/* voice lists */
FSpinlock __AXVoiceListSpinlock;
std::vector<AXVPB*> __AXVoicesPerPriority[AX_PRIORITY_MAX];
std::vector<AXVPB*> __AXFreeVoices;
void AXVoiceList_AddFreeVoice(AXVPB* vpb)
{
cemu_assert(vpb->priority != AX_PRIORITY_FREE);
__AXFreeVoices.push_back(vpb);
vpb->prev = nullptr;
vpb->next = nullptr;
}
AXVPB* AXVoiceList_GetFreeVoice()
{
if (__AXFreeVoices.empty())
return nullptr;
AXVPB* vpb = __AXFreeVoices.back();
__AXFreeVoices.pop_back();
return vpb;
}
std::vector<AXVPB*>& AXVoiceList_GetFreeVoices()
{
return __AXFreeVoices;
}
void AXVoiceList_AddVoice(AXVPB* vpb, sint32 priority)
{
cemu_assert(priority != AX_PRIORITY_FREE && priority < AX_PRIORITY_MAX);
__AXVoicesPerPriority[priority].push_back(vpb);
vpb->next = nullptr;
vpb->prev = nullptr;
vpb->priority = priority;
}
void AXVoiceList_RemoveVoice(AXVPB* vpb)
{
uint32 priority = (uint32)vpb->priority;
cemu_assert(priority != AX_PRIORITY_FREE && priority < AX_PRIORITY_MAX);
vectorRemoveByValue(__AXVoicesPerPriority[priority], vpb);
}
AXVPB* AXVoiceList_GetLeastRecentVoiceByPriority(uint32 priority)
{
cemu_assert(priority != AX_PRIORITY_FREE && priority < AX_PRIORITY_MAX);
if (__AXVoicesPerPriority[priority].empty())
return nullptr;
return __AXVoicesPerPriority[priority].front();
}
std::vector<AXVPB*>& AXVoiceList_GetListByPriority(uint32 priority)
{
cemu_assert(priority != AX_PRIORITY_FREE && priority < AX_PRIORITY_MAX);
return __AXVoicesPerPriority[priority];
}
void AXVoiceList_Reset()
{
__AXFreeVoices.clear();
for (uint32 i = 0; i < AX_PRIORITY_MAX; i++)
__AXVoicesPerPriority[i].clear();
}
SysAllocator<AXVPBInternal_t, AX_MAX_VOICES> _buffer__AXVPBInternalVoiceArray;
AXVPBInternal_t* __AXVPBInternalVoiceArray;
SysAllocator<AXVPBInternal_t, AX_MAX_VOICES> _buffer__AXVPBInternalVoiceShadowCopyArray;
AXVPBInternal_t* __AXVPBInternalVoiceShadowCopyArrayPtr; // this is the array used by audio mixing (it's synced at the beginning of every audio frame with __AXVPBInternalVoiceArray)
SysAllocator<AXVPBItd, AX_MAX_VOICES> _buffer__AXVPBItdArray;
AXVPBItd* __AXVPBItdArrayPtr;
SysAllocator<AXVPB, AX_MAX_VOICES> _buffer__AXVPBArray;
AXVPB* __AXVPBArrayPtr;
struct AXUSERPROTECTION
{
MPTR threadMPTR;
uint32 count;
};
uint32 __AXUserProtectionArraySize = 0;
AXUSERPROTECTION __AXUserProtectionArray[AX_MAX_VOICES] = { 0 };
AXUSERPROTECTION __AXVoiceProtection[AX_MAX_VOICES] = { 0 };
bool AXUserIsProtected()
{
return __AXUserProtectionArraySize != 0;
}
sint32 AXUserBegin()
{
// some games (e.g. Color Splash) can block themselves from calling AXSetVoice* API in time if a thread gets
// rescheduled while inside a AXUserBegin() + AXUserEnd() block
// to prevent this from happening we extend the current thread's quantum while the protection is raised
PPCCore_boostQuantum(10000);
if (AXIst_IsFrameBeingProcessed())
{
return -2;
}
MPTR currentThreadMPTR = memory_getVirtualOffsetFromPointer(coreinit::OSGetCurrentThread());
for (sint32 i = __AXUserProtectionArraySize - 1; i >= 0; i--)
{
if (__AXUserProtectionArray[i].threadMPTR == currentThreadMPTR)
{
sint32 newCount = __AXUserProtectionArray[i].count + 1;
__AXUserProtectionArray[i].count = newCount;
return newCount;
}
}
// no matching entry found
if (__AXUserProtectionArraySize >= AX_MAX_VOICES)
{
// no entry available
return -4;
}
// create new entry
if (__AXUserProtectionArraySize < 0)
assert_dbg();
sint32 entryIndex = __AXUserProtectionArraySize;
__AXUserProtectionArray[entryIndex].threadMPTR = currentThreadMPTR;
__AXUserProtectionArray[entryIndex].count = 1;
__AXUserProtectionArraySize++;
return 1;
}
sint32 AXUserEnd()
{
PPCCore_deboostQuantum(10000);
if (AXIst_IsFrameBeingProcessed())
return -2;
MPTR currentThreadMPTR = memory_getVirtualOffsetFromPointer(coreinit::OSGetCurrentThread());
for (sint32 i = __AXUserProtectionArraySize - 1; i >= 0; i--)
{
if (__AXUserProtectionArray[i].threadMPTR == currentThreadMPTR)
{
sint32 newCount = __AXUserProtectionArray[i].count - 1;
__AXUserProtectionArray[i].count = newCount;
if (__AXUserProtectionArray[i].count == 0)
{
// count == 0 -> remove entry
if (i >= (sint32)(__AXUserProtectionArraySize - 1))
{
// entry is last in array, can just decrease array size
__AXUserProtectionArraySize--;
__AXUserProtectionArray[i].threadMPTR = MPTR_NULL;
}
else
{
// remove entry by shifting all remaining entries
//for (sint32 f = i; f >= 0; f--)
//{
// __AXUserProtectionArray[f].threadMPTR = __AXUserProtectionArray[f + 1].threadMPTR;
// __AXUserProtectionArray[f].count = __AXUserProtectionArray[f + 1].count;
//}
cemu_assert_debug(false);
}
// remove entries associated with the current thread from __AXVoiceProtection[] if the count is zero
for (sint32 f = 0; f < AX_MAX_VOICES; f++)
{
if (__AXVoiceProtection[f].threadMPTR == currentThreadMPTR && __AXVoiceProtection[f].count == 0)
{
__AXVoiceProtection[f].threadMPTR = MPTR_NULL;
}
}
}
return newCount;
}
}
cemu_assert_debug(false); // voice not found in list, did the game not call AXUserBegin()?
return -3;
}
bool AXVoiceProtection_IsProtectedByAnyThread(AXVPB* vpb)
{
sint32 index = vpb->index;
return __AXVoiceProtection[index].threadMPTR != MPTR_NULL;
}
bool AXVoiceProtection_IsProtectedByCurrentThread(AXVPB* vpb)
{
sint32 index = vpb->index;
bool isProtected = false;
if (AXIst_IsFrameBeingProcessed())
isProtected = __AXVoiceProtection[index].threadMPTR != MPTR_NULL;
else
isProtected = __AXVoiceProtection[index].threadMPTR != memory_getVirtualOffsetFromPointer(coreinit::OSGetCurrentThread());
return isProtected;
}
void AXVoiceProtection_Acquire(AXVPB* vpb)
{
sint32 index = vpb->index;
if (AXUserIsProtected() == false)
return;
if (AXIst_IsFrameBeingProcessed())
return;
if (__AXVoiceProtection[index].threadMPTR == MPTR_NULL)
{
__AXVoiceProtection[index].threadMPTR = memory_getVirtualOffsetFromPointer(coreinit::OSGetCurrentThread());
// does not set count?
}
}
void AXVoiceProtection_Release(AXVPB* vpb)
{
sint32 index = vpb->index;
__AXVoiceProtection[index].threadMPTR = MPTR_NULL;
__AXVoiceProtection[index].count = 0;
}
sint32 AXVoiceBegin(AXVPB* voice)
{
if (voice == nullptr)
{
cemuLog_log(LogType::Force, "AXVoiceBegin(): Invalid voice");
return -1;
}
uint32 index = (uint32)voice->index;
if (index >= AX_MAX_VOICES)
{
cemuLog_log(LogType::Force, "AXVoiceBegin(): Invalid voice index");
return -1;
}
if (AXIst_IsFrameBeingProcessed())
return -2;
MPTR currentThreadMPTR = memory_getVirtualOffsetFromPointer(coreinit::OSGetCurrentThread());
if (__AXVoiceProtection[index].threadMPTR == MPTR_NULL)
{
__AXVoiceProtection[index].threadMPTR = currentThreadMPTR;
__AXVoiceProtection[index].count = 1;
return 1;
}
else if (__AXVoiceProtection[index].threadMPTR == currentThreadMPTR)
{
__AXVoiceProtection[index].count++;
return __AXVoiceProtection[index].count;
}
return -1;
}
sint32 __GetThreadProtection(MPTR threadMPTR)
{
for (sint32 i = __AXUserProtectionArraySize - 1; i >= 0; i--)
{
if (__AXUserProtectionArray[i].threadMPTR == threadMPTR)
return i;
}
return -1;
}
sint32 AXVoiceEnd(AXVPB* voice)
{
if (voice == nullptr)
{
cemuLog_log(LogType::Force, "AXVoiceBegin(): Invalid voice");
return -1;
}
uint32 index = (uint32)voice->index;
if (index >= AX_MAX_VOICES)
{
cemuLog_log(LogType::Force, "AXVoiceBegin(): Invalid voice index");
return -1;
}
if (AXIst_IsFrameBeingProcessed())
return -2;
MPTR currentThreadMPTR = memory_getVirtualOffsetFromPointer(coreinit::OSGetCurrentThread());
if (__AXVoiceProtection[index].threadMPTR == currentThreadMPTR)
{
if (__AXVoiceProtection[index].count > 0)
__AXVoiceProtection[index].count--;
if (__AXVoiceProtection[index].count == 0)
{
if (__GetThreadProtection(currentThreadMPTR) == -1)
{
__AXVoiceProtection[index].threadMPTR = 0;
}
}
sint32 count = __AXVoiceProtection[index].count;
return count;
}
else
{
if (__AXVoiceProtection[index].threadMPTR == MPTR_NULL)
{
return -3;
}
else
{
return -1;
}
}
}
void AXVPB_SetVoiceDefault(AXVPB* vpb)
{
AXVPBInternal_t* internal = GetInternalVoice(vpb);
uint32 index = GetVoiceIndex(vpb);
vpb->playbackState = 0;
vpb->sync = 0;
AXSetSyncFlag(vpb, AX_SYNCFLAG_PLAYBACKSTATE);
AXSetSyncFlag(vpb, AX_SYNCFLAG_SRCDATA);
AXSetSyncFlag(vpb, AX_SYNCFLAG_LPFDATA);
AXSetSyncFlag(vpb, AX_SYNCFLAG_BIQUADDATA);
AXSetSyncFlag(vpb, AX_SYNCFLAG_VOICEREMOTEON);
AXSetSyncFlag(vpb, AX_SYNCFLAG_ITD20);
AXSetSyncFlag(vpb, AX_SYNCFLAG_8000000);
AXSetSyncFlag(vpb, 0x10000000);
internal->reserved282_rmtIIRGuessed = 0;
internal->reserved16C = 0;
internal->reserved148_voiceRmtOn = 0;
internal->biquad.on = 0;
internal->lpf.on = 0;
internal->playbackState = 0;
uint32 defaultMixer = AXGetDefaultMixerSelect();
internal->mixerSelect = defaultMixer;
vpb->mixerSelect = defaultMixer;
AXResetVoiceLoopCount(vpb);
internal->reserved280 = 0;
internal->src.currentFrac = 0;
internal->src.historySamples[0] = 0;
internal->src.historySamples[1] = 0;
internal->src.historySamples[2] = 0;
internal->src.historySamples[3] = 0;
internal->reserved278 = 0;
internal->reserved27A = 0;
internal->reserved27C = 0;
internal->reserved27E = 0;
internal->srcFilterMode = 0;
memset(&internal->deviceMixMaskTV, 0, 8);
memset(&internal->deviceMixMaskDRC, 0, 16);
memset(&internal->deviceMixMaskRMT, 0, 0x20);
memset(&internal->reserved1E8, 0, 0x30);
memset(&internal->reserved218, 0, 0x40);
memset(&internal->reserved258, 0, 0x20);
}
AXVPB* AXVPB_DropVoice(sint32 priority)
{
for (sint32 i = 1; i < priority; i++)
{
AXVPB* voiceItr = AXVoiceList_GetLeastRecentVoiceByPriority(i);
if (voiceItr)
{
// get last voice in chain
while (voiceItr->next)
voiceItr = voiceItr->next.GetPtr();
cemuLog_logDebug(LogType::Force, "Dropped voice {}", (uint32)voiceItr->index);
// drop voice
if (voiceItr->playbackState != 0)
{
voiceItr->depop = 1;
}
// do drop callback
if (voiceItr->callback)
{
PPCCoreCallback(voiceItr->callback, voiceItr);
}
voiceItr->ukn4C_dropReason = 0; // probably drop reason?
if (voiceItr->callbackEx)
{
PPCCoreCallback(voiceItr->callbackEx, voiceItr, voiceItr->userParam, voiceItr->ukn4C_dropReason);
}
// move voice to new stack
AXVoiceList_RemoveVoice(voiceItr);
AXVoiceList_AddVoice(voiceItr, priority);
return voiceItr;
}
}
return nullptr;
}
AXVPB* AXAcquireVoiceEx(uint32 priority, MPTR callbackEx, MPTR userParam)
{
cemu_assert(priority != AX_PRIORITY_FREE && priority < AX_PRIORITY_MAX);
__AXVoiceListSpinlock.lock();
AXVPB* vpb = AXVoiceList_GetFreeVoice();
if (vpb != nullptr)
{
AXVoiceList_AddVoice(vpb, priority);
vpb->userParam = userParam;
vpb->callback = MPTR_NULL;
vpb->callbackEx = callbackEx;
AXVPB_SetVoiceDefault(vpb);
}
else
{
// no free voice available, drop voice with lower priority
AXVPB* droppedVoice = AXVPB_DropVoice(priority);
if (droppedVoice == nullptr)
{
// no voice available
__AXVoiceListSpinlock.unlock();
return nullptr;
}
vpb->userParam = userParam;
vpb->callback = MPTR_NULL;
vpb->callbackEx = callbackEx;
AXVPB_SetVoiceDefault(vpb);
}
__AXVoiceListSpinlock.unlock();
return vpb;
}
void AXFreeVoice(AXVPB* vpb)
{
cemu_assert(vpb != nullptr);
__AXVoiceListSpinlock.lock();
if (vpb->priority == (uint32be)AX_PRIORITY_FREE)
{
cemuLog_log(LogType::Force, "AXFreeVoice() called on free voice");
__AXVoiceListSpinlock.unlock();
return;
}
AXVoiceProtection_Release(vpb);
AXVoiceList_RemoveVoice(vpb);
if (vpb->playbackState != (uint32be)0)
{
vpb->depop = (uint32be)1;
}
AXVPB_SetVoiceDefault(vpb);
vpb->callback = MPTR_NULL;
vpb->callbackEx = MPTR_NULL;
AXVoiceList_AddFreeVoice(vpb);
__AXVoiceListSpinlock.unlock();
}
void __AXVPBResetVoices()
{
__AXVPBInternalVoiceArray = _buffer__AXVPBInternalVoiceArray.GetPtr();
__AXVPBInternalVoiceShadowCopyArrayPtr = _buffer__AXVPBInternalVoiceShadowCopyArray.GetPtr();
__AXVPBArrayPtr = _buffer__AXVPBArray.GetPtr();
__AXVPBItdArrayPtr = _buffer__AXVPBItdArray.GetPtr();
memset(__AXVPBInternalVoiceShadowCopyArrayPtr, 0, sizeof(AXVPBInternal_t)*AX_MAX_VOICES);
memset(__AXVPBInternalVoiceArray, 0, sizeof(AXVPBInternal_t)*AX_MAX_VOICES);
memset(__AXVPBItdArrayPtr, 0, sizeof(AXVPBItd)*AX_MAX_VOICES);
memset(__AXVPBArrayPtr, 0, sizeof(AXVPB)*AX_MAX_VOICES);
}
void AXVPBInit()
{
__AXVPBResetVoices();
for (sint32 i = 0; i < AX_MAX_VOICES; i++)
{
AXVPBItd* itd = __AXVPBItdArrayPtr + i;
AXVPBInternal_t* internalShadowCopy = __AXVPBInternalVoiceShadowCopyArrayPtr + i;
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + i;
AXVPB* vpb = __AXVPBArrayPtr + i;
MPTR internalShadowCopyPhys = memory_virtualToPhysical(memory_getVirtualOffsetFromPointer(internalShadowCopy));
MPTR itdPhys = memory_virtualToPhysical(memory_getVirtualOffsetFromPointer(itd));
vpb->callbackEx = MPTR_NULL;
vpb->itd = itd;
vpb->callback = MPTR_NULL;
vpb->index = i;
AXVPB_SetVoiceDefault(vpb);
if (i == (AX_MAX_VOICES - 1))
{
internal->nextAddrHigh = 0;
internal->nextAddrLow = 0;
internalShadowCopy->nextAddrHigh = 0;
internalShadowCopy->nextAddrLow = 0;
}
else
{
MPTR nextShadowCopyPhys = internalShadowCopyPhys + sizeof(AXVPBInternal_t);
internalShadowCopy->nextAddrHigh = internal->nextAddrHigh = (nextShadowCopyPhys >> 16);
internalShadowCopy->nextAddrLow = internal->nextAddrLow = (nextShadowCopyPhys & 0xFFFF);
}
internalShadowCopy->index = internal->index = i;
internalShadowCopy->selfAddrHigh = internal->selfAddrHigh = (internalShadowCopyPhys >> 16);
internalShadowCopy->selfAddrLow = internal->selfAddrLow = (internalShadowCopyPhys & 0xFFFF);
internalShadowCopy->itdAddrHigh = internal->itdAddrHigh = (itdPhys >> 16);
internalShadowCopy->itdAddrLow = internal->itdAddrLow = (itdPhys & 0xFFFF);
vpb->priority = 1;
AXVoiceList_AddFreeVoice(vpb);
}
}
void AXVPB_Init()
{
__AXVPBResetVoices();
AXVPBInit();
}
void AXVBP_Reset()
{
AXVoiceList_Reset();
__AXVPBResetVoices();
}
sint32 AXIsValidDevice(sint32 device, sint32 deviceIndex)
{
if (device == AX_DEV_TV)
{
if (deviceIndex != 0)
return -2;
}
else if (device == AX_DEV_DRC)
{
if (deviceIndex != 0 && deviceIndex != 1)
return -2;
}
else if (device == AX_DEV_TV)
{
if (deviceIndex < 0 || deviceIndex >= 4)
return -2;
}
else
return -1;
return 0;
}
void __AXSetVoiceChannelMix(AXCHMIX_DEPR* mixOut, AXCHMIX_DEPR* mixIn, sint16* mixMask)
{
for (sint32 i = 0; i < AX_BUS_COUNT; i++)
{
mixOut[i].vol = mixIn[i].vol;
mixOut[i].delta = mixIn[i].delta;
if (mixIn[i].delta)
mixMask[i] = 3;
else if (mixIn[i].vol)
mixMask[i] = 1;
else
mixMask[i] = 0;
}
}
sint32 AXSetVoiceDeviceMix(AXVPB* vpb, sint32 device, sint32 deviceIndex, AXCHMIX_DEPR* mix)
{
if (vpb == nullptr)
return -4;
if (mix == nullptr)
return -3;
sint32 r = AXIsValidDevice(device, deviceIndex);
if (r)
return r;
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)vpb->index;
sint32 channelCount;
uint16* deviceMixMask;
AXCHMIX_DEPR* voiceMix;
if (device == AX_DEV_TV)
{
channelCount = AX_TV_CHANNEL_COUNT;
voiceMix = internal->deviceMixTV + deviceIndex * 0x60 / 4;
deviceMixMask = internal->deviceMixMaskTV;
}
else if (device == AX_DEV_DRC)
{
channelCount = AX_DRC_CHANNEL_COUNT;
voiceMix = internal->deviceMixDRC + deviceIndex * 16;
deviceMixMask = internal->deviceMixMaskDRC;
}
else if (device == AX_DEV_RMT)
{
assert_dbg();
channelCount = AX_RMT_CHANNEL_COUNT;
}
sint16 updatedMixMask[AX_BUS_COUNT];
for (sint32 i = 0; i < AX_BUS_COUNT; i++)
{
updatedMixMask[i] = 0;
}
sint16 channelMixMask[AX_BUS_COUNT];
for (sint32 c = 0; c < channelCount; c++)
{
__AXSetVoiceChannelMix(voiceMix, mix, channelMixMask);
for (sint32 i = 0; i < AX_BUS_COUNT; i++)
{
updatedMixMask[i] |= (channelMixMask[i] << (c * 2));
}
// next channel
voiceMix += AX_BUS_COUNT;
mix += AX_BUS_COUNT;
}
for (sint32 i = 0; i < AX_BUS_COUNT; i++)
{
deviceMixMask[i] = _swapEndianU16(updatedMixMask[i]);
}
vpb->sync = (uint32)vpb->sync | (AX_SYNCFLAG_DEVICEMIXMASK | AX_SYNCFLAG_DEVICEMIX);
AXVoiceProtection_Acquire(vpb);
return 0;
}
void AXSetVoiceState(AXVPB* vpb, sint32 voiceState)
{
if (vpb->playbackState != (uint32be)voiceState)
{
vpb->playbackState = voiceState;
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)vpb->index;
internal->playbackState = _swapEndianU16(voiceState);
AXSetSyncFlag(vpb, AX_SYNCFLAG_PLAYBACKSTATE);
AXVoiceProtection_Acquire(vpb);
if (voiceState == 0)
{
vpb->depop = (uint32be)1;
}
}
}
sint32 AXIsVoiceRunning(AXVPB* vpb)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)vpb->index;
return (_swapEndianU16(internal->playbackState) == 1) ? 1 : 0;
}
void AXSetVoiceType(AXVPB* vpb, uint16 voiceType)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)vpb->index;
internal->voiceType = _swapEndianU16(voiceType);
AXSetSyncFlag(vpb, AX_SYNCFLAG_VOICETYPE);
AXVoiceProtection_Acquire(vpb);
}
void AXSetVoiceAdpcm(AXVPB* vpb, AXPBADPCM_t* adpcm)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)(vpb->index);
for (sint32 i = 0; i < 16; i++)
internal->adpcmData.coef[i] = adpcm->a[i];
internal->adpcmData.gain = adpcm->gain;
internal->adpcmData.scale = adpcm->scale;
AXSetSyncFlag(vpb, AX_SYNCFLAG_ADPCMDATA);
AXVoiceProtection_Acquire(vpb);
}
void AXSetVoiceAdpcmLoop(AXVPB* vpb, AXPBADPCMLOOP_t* adpcmLoop)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)vpb->index;
internal->adpcmLoop.loopScale = adpcmLoop->loopScale;
if (internal->voiceType == 0)
{
internal->adpcmLoop.loopYn1 = adpcmLoop->loopYn1;
internal->adpcmLoop.loopYn2 = adpcmLoop->loopYn2;
}
AXSetSyncFlag(vpb, AX_SYNCFLAG_ADPCMLOOP);
AXVoiceProtection_Acquire(vpb);
}
void AXSetVoiceSrc(AXVPB* vpb, AXPBSRC_t* src)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)vpb->index;
internal->src.ratioHigh = src->ratioHigh;
internal->src.ratioLow = src->ratioLow;
internal->src.currentFrac = src->currentFrac;
internal->src.historySamples[0] = src->historySamples[0];
internal->src.historySamples[1] = src->historySamples[1];
internal->src.historySamples[2] = src->historySamples[2];
internal->src.historySamples[3] = src->historySamples[3];
AXResetSyncFlag(vpb, AX_SYNCFLAG_SRCRATIO);
AXSetSyncFlag(vpb, AX_SYNCFLAG_SRCDATA);
AXVoiceProtection_Acquire(vpb);
}
void AXSetVoiceSrcType(AXVPB* vpb, uint32 srcType)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)vpb->index;
if (srcType == AX_SRC_TYPE_NONE)
{
internal->srcFilterMode = _swapEndianU16(AX_FILTER_MODE_NONE);
}
else if (srcType == AX_SRC_TYPE_LINEAR)
{
internal->srcFilterMode = _swapEndianU16(AX_FILTER_MODE_LINEAR);
}
else if (srcType == AX_SRC_TYPE_LOWPASS1)
{
internal->srcFilterMode = _swapEndianU16(AX_FILTER_MODE_TAP);
internal->srcTapFilter = _swapEndianU16(AX_FILTER_LOWPASS_8K);
}
else if (srcType == AX_SRC_TYPE_LOWPASS2)
{
internal->srcFilterMode = _swapEndianU16(AX_FILTER_MODE_TAP);
internal->srcTapFilter = _swapEndianU16(AX_FILTER_LOWPASS_12K);
}
else if (srcType == AX_SRC_TYPE_LOWPASS3)
{
internal->srcFilterMode = _swapEndianU16(AX_FILTER_MODE_TAP);
internal->srcTapFilter = _swapEndianU16(AX_FILTER_LOWPASS_16K);
}
else
{
cemuLog_log(LogType::Force, "AXSetVoiceSrcType(): Unsupported src type {}", srcType);
}
AXSetSyncFlag(vpb, AX_SYNCFLAG_SRCFILTER);
AXVoiceProtection_Acquire(vpb);
}
sint32 AXSetVoiceSrcRatio(AXVPB* vpb, float ratio)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)vpb->index;
ratio *= 65536.0f;
#ifdef CEMU_DEBUG_ASSERT
if (ratio >= 4294967296.0f)
assert_dbg();
#endif
sint32 ratioI = (sint32)ratio;
if (ratioI < 0)
ratioI = 0;
else if (ratioI > 0x80000)
ratioI = 0x80000;
uint16 ratioHigh = (uint16)(ratioI >> 16);
uint16 ratioLow = (uint16)(ratioI & 0xFFFF);
ratioHigh = _swapEndianU16(ratioHigh);
ratioLow = _swapEndianU16(ratioLow);
if (internal->src.ratioHigh != ratioHigh || internal->src.ratioLow != ratioLow)
{
internal->src.ratioHigh = ratioHigh;
internal->src.ratioLow = ratioLow;
AXSetSyncFlag(vpb, AX_SYNCFLAG_SRCRATIO);
AXVoiceProtection_Acquire(vpb);
}
return 0;
}
void AXSetVoiceVe(AXVPB* vpb, AXPBVE* ve)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)vpb->index;
internal->veVolume = ve->currentVolume;
internal->veDelta = ve->currentDelta;
AXSetSyncFlag(vpb, AX_SYNCFLAG_VE);
AXVoiceProtection_Acquire(vpb);
}
void AXComputeLpfCoefs(uint32 freq, uint16be* a0, uint16be* b0)
{
// todo - verify algorithm
float t1 = cos((float)freq / 32000.0f * 6.2831855f);
float t2 = 2.0f - t1;
t1 = (float)sqrt(t2 * t2 - 1.0f);
t1 = t1 - t2;
t1 = t1 * 32768.0f;
t1 = -t1;
uint32 r = (uint16)t1;
*a0 = 0x7FFF - r;
*b0 = r;
}
void AXSetVoiceLpf(AXVPB* vpb, AXPBLPF_t* lpf)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)vpb->index;
internal->lpf.on = lpf->on;
internal->lpf.yn1 = lpf->yn1;
internal->lpf.a0 = lpf->a0;
internal->lpf.b0 = lpf->b0;
AXSetSyncFlag(vpb, AX_SYNCFLAG_LPFDATA);
AXVoiceProtection_Acquire(vpb);
}
void AXSetVoiceLpfCoefs(AXVPB* vpb, uint16 a0, uint16 b0)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)vpb->index;
internal->lpf.a0 = _swapEndianU16(a0);
internal->lpf.b0 = _swapEndianU16(b0);
AXSetSyncFlag(vpb, AX_SYNCFLAG_LPFCOEF);
AXVoiceProtection_Acquire(vpb);
}
void AXSetVoiceBiquad(AXVPB* vpb, AXPBBIQUAD_t* biquad)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)vpb->index;
internal->biquad.on = biquad->on;
internal->biquad.xn1 = biquad->xn1;
internal->biquad.xn2 = biquad->xn2;
internal->biquad.yn1 = biquad->yn1;
internal->biquad.yn2 = biquad->yn2;
internal->biquad.b0 = biquad->b0;
internal->biquad.b1 = biquad->b1;
internal->biquad.b2 = biquad->b2;
internal->biquad.a1 = biquad->a1;
internal->biquad.a2 = biquad->a2;
AXSetSyncFlag(vpb, AX_SYNCFLAG_BIQUADDATA);
AXVoiceProtection_Acquire(vpb);
}
void AXSetVoiceBiquadCoefs(AXVPB* vpb, uint16 b0, uint16 b1, uint16 b2, uint16 a1, uint16 a2)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)vpb->index;
internal->biquad.b0 = _swapEndianU16(b0);
internal->biquad.b1 = _swapEndianU16(b1);
internal->biquad.b2 = _swapEndianU16(b2);
internal->biquad.a1 = _swapEndianU16(a1);
internal->biquad.a2 = _swapEndianU16(a2);
AXSetSyncFlag(vpb, AX_SYNCFLAG_BIQUADCOEF);
AXVoiceProtection_Acquire(vpb);
}
void __AXSetVoiceAddr(AXVPB* vpb, axOffsetsInternal_t* voiceAddr)
{
sint32 voiceIndex = (sint32)(vpb->index);
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + voiceIndex;
memcpy(&internal->internalOffsets, voiceAddr, sizeof(axOffsetsInternal_t));
uint16 format = _swapEndianU16(voiceAddr->format);
if (format == AX_FORMAT_PCM8)
{
memset(&internal->adpcmData, 0x00, sizeof(axADPCMInternal_t));
internal->adpcmData.gain = 0x100;
AXSetSyncFlag(vpb, AX_SYNCFLAG_ADPCMDATA);
AXResetSyncFlag(vpb, AX_SYNCFLAG_LOOPFLAG | AX_SYNCFLAG_LOOPOFFSET | AX_SYNCFLAG_ENDOFFSET | AX_SYNCFLAG_CURRENTOFFSET);
AXSetSyncFlag(vpb, AX_SYNCFLAG_OFFSETS);
AXVoiceProtection_Acquire(vpb);
}
else if (format == AX_FORMAT_PCM16)
{
memset(&internal->adpcmData, 0x00, sizeof(axADPCMInternal_t));
internal->adpcmData.gain = 0x800;
AXSetSyncFlag(vpb, AX_SYNCFLAG_ADPCMDATA);
AXResetSyncFlag(vpb, AX_SYNCFLAG_LOOPFLAG | AX_SYNCFLAG_LOOPOFFSET | AX_SYNCFLAG_ENDOFFSET | AX_SYNCFLAG_CURRENTOFFSET);
AXSetSyncFlag(vpb, AX_SYNCFLAG_OFFSETS);
AXVoiceProtection_Acquire(vpb);
}
else if (format == AX_FORMAT_ADPCM)
{
// .adpcmData is left intact
AXResetSyncFlag(vpb, AX_SYNCFLAG_LOOPFLAG | AX_SYNCFLAG_LOOPOFFSET | AX_SYNCFLAG_ENDOFFSET | AX_SYNCFLAG_CURRENTOFFSET);
AXSetSyncFlag(vpb, AX_SYNCFLAG_OFFSETS);
AXVoiceProtection_Acquire(vpb);
}
else
{
cemu_assert_debug(false);
}
}
void AXSetVoiceOffsets(AXVPB* vpb, AXPBOFFSET_t* pbOffset)
{
cemuLog_log(LogType::SoundAPI, fmt::format("AXSetVoiceOffsets() -> Format: {0:04x} Current: {1:08x} End: {2:08x} Loop: {3:08x}", _swapEndianU16(pbOffset->format), _swapEndianU32(pbOffset->currentOffset), _swapEndianU32(pbOffset->endOffset), _swapEndianU32(pbOffset->loopOffset)));
MPTR sampleBase = _swapEndianU32(pbOffset->samples);
if (sampleBase == MPTR_NULL)
{
cemuLog_log(LogType::Force, "AXSetVoiceOffsets(): Invalid sample address");
cemu_assert_debug(false);
return;
}
memcpy(&vpb->offsets, pbOffset, sizeof(AXPBOFFSET_t));
sampleBase = memory_virtualToPhysical(sampleBase);
uint16 format = _swapEndianU16(pbOffset->format);
axOffsetsInternal_t voiceAddr;
if (format == AX_FORMAT_PCM8)
{
uint32 loopOffsetPtr = sampleBase + _swapEndianU32(pbOffset->loopOffset);
uint32 endOffsetPtr = sampleBase + _swapEndianU32(pbOffset->endOffset);
uint32 currentOffsetPtr = sampleBase + _swapEndianU32(pbOffset->currentOffset);
voiceAddr.format = _swapEndianU16(pbOffset->format);
voiceAddr.loopFlag = _swapEndianU16(pbOffset->loopFlag);
voiceAddr.loopOffsetPtrHigh = (loopOffsetPtr >> 16) & 0x1FFF;
voiceAddr.loopOffsetPtrLow = loopOffsetPtr & 0xFFFF;
voiceAddr.endOffsetPtrHigh = (endOffsetPtr >> 16) & 0x1FFF;
voiceAddr.endOffsetPtrLow = endOffsetPtr & 0xFFFF;
voiceAddr.currentOffsetPtrHigh = (currentOffsetPtr >> 16) & 0x1FFF;
voiceAddr.currentOffsetPtrLow = currentOffsetPtr & 0xFFFF;
voiceAddr.ptrHighExtension = (currentOffsetPtr >> 29);
// convert to big endian
voiceAddr.format = _swapEndianU16(voiceAddr.format);
voiceAddr.loopFlag = _swapEndianU16(voiceAddr.loopFlag);
voiceAddr.loopOffsetPtrHigh = _swapEndianU16(voiceAddr.loopOffsetPtrHigh);
voiceAddr.loopOffsetPtrLow = _swapEndianU16(voiceAddr.loopOffsetPtrLow);
voiceAddr.endOffsetPtrHigh = _swapEndianU16(voiceAddr.endOffsetPtrHigh);
voiceAddr.endOffsetPtrLow = _swapEndianU16(voiceAddr.endOffsetPtrLow);
voiceAddr.currentOffsetPtrHigh = _swapEndianU16(voiceAddr.currentOffsetPtrHigh);
voiceAddr.currentOffsetPtrLow = _swapEndianU16(voiceAddr.currentOffsetPtrLow);
voiceAddr.ptrHighExtension = _swapEndianU16(voiceAddr.ptrHighExtension);
__AXSetVoiceAddr(vpb, &voiceAddr);
}
else if (format == AX_FORMAT_PCM16)
{
uint32 loopOffsetPtr = sampleBase / 2 + _swapEndianU32(pbOffset->loopOffset);
uint32 endOffsetPtr = sampleBase / 2 + _swapEndianU32(pbOffset->endOffset);
uint32 currentOffset = _swapEndianU32(pbOffset->currentOffset);
uint32 currentOffsetPtr = sampleBase / 2 + currentOffset;
voiceAddr.format = _swapEndianU16(pbOffset->format);
voiceAddr.loopFlag = _swapEndianU16(pbOffset->loopFlag);
voiceAddr.loopOffsetPtrHigh = (loopOffsetPtr >> 16) & 0x0FFF;
voiceAddr.loopOffsetPtrLow = loopOffsetPtr & 0xFFFF;
voiceAddr.endOffsetPtrHigh = (endOffsetPtr >> 16) & 0x0FFF;
voiceAddr.endOffsetPtrLow = endOffsetPtr & 0xFFFF;
voiceAddr.currentOffsetPtrHigh = (currentOffsetPtr >> 16) & 0x0FFF;
voiceAddr.currentOffsetPtrLow = currentOffsetPtr & 0xFFFF;
voiceAddr.ptrHighExtension = ((sampleBase + currentOffset * 2) >> 29);
// convert to big endian
voiceAddr.format = _swapEndianU16(voiceAddr.format);
voiceAddr.loopFlag = _swapEndianU16(voiceAddr.loopFlag);
voiceAddr.loopOffsetPtrHigh = _swapEndianU16(voiceAddr.loopOffsetPtrHigh);
voiceAddr.loopOffsetPtrLow = _swapEndianU16(voiceAddr.loopOffsetPtrLow);
voiceAddr.endOffsetPtrHigh = _swapEndianU16(voiceAddr.endOffsetPtrHigh);
voiceAddr.endOffsetPtrLow = _swapEndianU16(voiceAddr.endOffsetPtrLow);
voiceAddr.currentOffsetPtrHigh = _swapEndianU16(voiceAddr.currentOffsetPtrHigh);
voiceAddr.currentOffsetPtrLow = _swapEndianU16(voiceAddr.currentOffsetPtrLow);
voiceAddr.ptrHighExtension = _swapEndianU16(voiceAddr.ptrHighExtension);
__AXSetVoiceAddr(vpb, &voiceAddr);
}
else if (format == AX_FORMAT_ADPCM)
{
uint32 loopOffsetPtr = sampleBase * 2 + _swapEndianU32(pbOffset->loopOffset);
uint32 endOffsetPtr = sampleBase * 2 + _swapEndianU32(pbOffset->endOffset);
uint32 currentOffset = _swapEndianU32(pbOffset->currentOffset);
uint32 currentOffsetPtr = sampleBase * 2 + currentOffset;
voiceAddr.format = _swapEndianU16(pbOffset->format);
voiceAddr.loopFlag = _swapEndianU16(pbOffset->loopFlag);
voiceAddr.loopOffsetPtrHigh = (loopOffsetPtr >> 16) & 0x3FFF;
voiceAddr.loopOffsetPtrLow = loopOffsetPtr & 0xFFFF;
voiceAddr.endOffsetPtrHigh = (endOffsetPtr >> 16) & 0x3FFF;
voiceAddr.endOffsetPtrLow = endOffsetPtr & 0xFFFF;
voiceAddr.currentOffsetPtrHigh = (currentOffsetPtr >> 16) & 0x3FFF;
voiceAddr.currentOffsetPtrLow = currentOffsetPtr & 0xFFFF;
voiceAddr.ptrHighExtension = ((sampleBase + currentOffset / 2) >> 29);
// convert to big endian
voiceAddr.format = _swapEndianU16(voiceAddr.format);
voiceAddr.loopFlag = _swapEndianU16(voiceAddr.loopFlag);
voiceAddr.loopOffsetPtrHigh = _swapEndianU16(voiceAddr.loopOffsetPtrHigh);
voiceAddr.loopOffsetPtrLow = _swapEndianU16(voiceAddr.loopOffsetPtrLow);
voiceAddr.endOffsetPtrHigh = _swapEndianU16(voiceAddr.endOffsetPtrHigh);
voiceAddr.endOffsetPtrLow = _swapEndianU16(voiceAddr.endOffsetPtrLow);
voiceAddr.currentOffsetPtrHigh = _swapEndianU16(voiceAddr.currentOffsetPtrHigh);
voiceAddr.currentOffsetPtrLow = _swapEndianU16(voiceAddr.currentOffsetPtrLow);
voiceAddr.ptrHighExtension = _swapEndianU16(voiceAddr.ptrHighExtension);
__AXSetVoiceAddr(vpb, &voiceAddr);
}
else
{
cemu_assert_debug(false);
}
}
void AXSetVoiceOffsetsEx(AXVPB* vpb, AXPBOFFSET_t* pbOffset, void* sampleBase)
{
// used by F1 Racing
cemu_assert(vpb != NULL && sampleBase != MPTR_NULL);
AXPBOFFSET_t tmpOffsets = *pbOffset;
tmpOffsets.samples = _swapEndianU32(memory_getVirtualOffsetFromPointer(sampleBase));
AXSetVoiceOffsets(vpb, &tmpOffsets);
}
void AXSetVoiceSamplesAddr(AXVPB* vpb, void* sampleBase)
{
vpb->offsets.samples = _swapEndianU32(memory_getVirtualOffsetFromPointer(sampleBase));
AXGetVoiceOffsets(vpb, &vpb->offsets);
}
void AXGetVoiceOffsets(AXVPB* vpb, AXPBOFFSET_t* pbOffset)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)vpb->index;
memcpy(pbOffset, &vpb->offsets, sizeof(AXPBOFFSET_t));
MPTR sampleBase = _swapEndianU32(vpb->offsets.samples);
sampleBase = memory_virtualToPhysical(sampleBase);
uint16 format = _swapEndianU16(pbOffset->format);
uint32 loopOffsetPtrLow = _swapEndianU16(internal->internalOffsets.loopOffsetPtrLow);
uint32 loopOffsetPtrHigh = _swapEndianU16(internal->internalOffsets.loopOffsetPtrHigh);
uint32 endOffsetPtrLow = _swapEndianU16(internal->internalOffsets.endOffsetPtrLow);
uint32 endOffsetPtrHigh = _swapEndianU16(internal->internalOffsets.endOffsetPtrHigh);
uint32 currentOffsetPtrLow = _swapEndianU16(internal->internalOffsets.currentOffsetPtrLow);
uint32 currentOffsetPtrHigh = _swapEndianU16(internal->internalOffsets.currentOffsetPtrHigh);
uint32 ptrHighExtension = _swapEndianU16(internal->internalOffsets.ptrHighExtension);
if (format == AX_FORMAT_PCM8)
{
uint32 loopOffset = (loopOffsetPtrLow | (loopOffsetPtrHigh << 16) | (ptrHighExtension << 29)) - sampleBase;
uint32 endOffset = (endOffsetPtrLow | (endOffsetPtrHigh << 16) | (ptrHighExtension << 29)) - sampleBase;
uint32 currentOffset = (currentOffsetPtrLow | (currentOffsetPtrHigh << 16) | (ptrHighExtension << 29)) - sampleBase;
pbOffset->loopOffset = _swapEndianU32(loopOffset);
pbOffset->endOffset = _swapEndianU32(endOffset);
pbOffset->currentOffset = _swapEndianU32(currentOffset);
}
else if (format == AX_FORMAT_PCM16)
{
uint32 loopOffset = (loopOffsetPtrLow | (loopOffsetPtrHigh << 16) | ((ptrHighExtension << 29) / 2)) - sampleBase / 2;
uint32 endOffset = (endOffsetPtrLow | (endOffsetPtrHigh << 16) | ((ptrHighExtension << 29) / 2)) - sampleBase / 2;
uint32 currentOffset = (currentOffsetPtrLow | (currentOffsetPtrHigh << 16) | ((ptrHighExtension << 29) / 2)) - sampleBase / 2;
pbOffset->loopOffset = _swapEndianU32(loopOffset);
pbOffset->endOffset = _swapEndianU32(endOffset);
pbOffset->currentOffset = _swapEndianU32(currentOffset);
}
else if (format == AX_FORMAT_ADPCM)
{
uint32 loopOffset = (loopOffsetPtrLow | (loopOffsetPtrHigh << 16) | ((ptrHighExtension << 29) * 2)) - sampleBase * 2;
uint32 endOffset = (endOffsetPtrLow | (endOffsetPtrHigh << 16) | ((ptrHighExtension << 29) * 2)) - sampleBase * 2;
uint32 currentOffset = (currentOffsetPtrLow | (currentOffsetPtrHigh << 16) | ((ptrHighExtension << 29) * 2)) - sampleBase * 2;
pbOffset->loopOffset = _swapEndianU32(loopOffset);
pbOffset->endOffset = _swapEndianU32(endOffset);
pbOffset->currentOffset = _swapEndianU32(currentOffset);
}
else
{
cemu_assert_debug(false);
}
cemuLog_log(LogType::SoundAPI, "Retrieved voice offsets for voice {:08x} - base {:08x} current {:08x} loopFlag {:04x} loop {:08x} end {:08x}", memory_getVirtualOffsetFromPointer(vpb), _swapEndianU32(pbOffset->samples), _swapEndianU32(pbOffset->currentOffset), _swapEndianU16(pbOffset->loopFlag), _swapEndianU32(pbOffset->loopOffset), _swapEndianU32(pbOffset->endOffset));
}
void AXGetVoiceOffsetsEx(AXVPB* vpb, AXPBOFFSET_t* pbOffset, MPTR sampleBase)
{
cemu_assert(vpb != NULL && sampleBase != MPTR_NULL);
vpb->offsets.samples = _swapEndianU32(sampleBase);
AXGetVoiceOffsets(vpb, pbOffset);
memcpy(&vpb->offsets, pbOffset, sizeof(AXPBOFFSET_t));
}
void AXSetVoiceCurrentOffset(AXVPB* vpb, uint32 currentOffset)
{
// untested
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)(vpb->index);
MPTR sampleBase = memory_virtualToPhysical(_swapEndianU32(vpb->offsets.samples));
vpb->offsets.currentOffset = _swapEndianU32(currentOffset);
uint16 voiceFormat = _swapEndianU16(internal->internalOffsets.format);
uint32 currentOffsetPtr;
sampleBase &= 0x1FFFFFFF;
if (voiceFormat == AX_FORMAT_PCM8)
{
// calculate offset (in bytes)
currentOffsetPtr = sampleBase + currentOffset;
}
else if (voiceFormat == AX_FORMAT_PCM16)
{
// calculate offset (in shorts)
currentOffsetPtr = sampleBase / 2 + currentOffset;
}
else if (voiceFormat == AX_FORMAT_ADPCM)
{
// calculate offset (in nibbles)
currentOffsetPtr = sampleBase * 2 + currentOffset;
}
else
{
cemu_assert_debug(false);
}
internal->internalOffsets.currentOffsetPtrHigh = _swapEndianU16(currentOffsetPtr >> 16);
internal->internalOffsets.currentOffsetPtrLow = _swapEndianU16(currentOffsetPtr & 0xFFFF);
AXSetSyncFlag(vpb, AX_SYNCFLAG_CURRENTOFFSET);
AXVoiceProtection_Acquire(vpb);
}
void AXSetVoiceLoopOffset(AXVPB* vpb, uint32 loopOffset)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)(vpb->index);
MPTR sampleBase = memory_virtualToPhysical(_swapEndianU32(vpb->offsets.samples));
vpb->offsets.loopOffset = _swapEndianU32(loopOffset);
uint16 voiceFormat = _swapEndianU16(internal->internalOffsets.format);
uint32 loopOffsetPtr;
sampleBase &= 0x1FFFFFFF;
if (voiceFormat == AX_FORMAT_PCM8)
{
// calculate offset (in bytes)
loopOffsetPtr = sampleBase + loopOffset;
}
else if (voiceFormat == AX_FORMAT_PCM16)
{
// calculate offset (in shorts)
loopOffsetPtr = sampleBase / 2 + loopOffset;
}
else if (voiceFormat == AX_FORMAT_ADPCM)
{
// calculate offset (in nibbles)
loopOffsetPtr = sampleBase * 2 + loopOffset;
}
else
{
cemu_assert_debug(false);
}
internal->internalOffsets.loopOffsetPtrHigh = _swapEndianU16(loopOffsetPtr >> 16);
internal->internalOffsets.loopOffsetPtrLow = _swapEndianU16(loopOffsetPtr & 0xFFFF);
AXSetSyncFlag(vpb, AX_SYNCFLAG_LOOPOFFSET);
AXVoiceProtection_Acquire(vpb);
}
void AXSetVoiceEndOffset(AXVPB* vpb, uint32 endOffset)
{
// untested
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)(vpb->index);
MPTR sampleBase = memory_virtualToPhysical(_swapEndianU32(vpb->offsets.samples));
vpb->offsets.endOffset = _swapEndianU32(endOffset);
uint16 voiceFormat = _swapEndianU16(internal->internalOffsets.format);
uint32 endOffsetPtr;
sampleBase &= 0x1FFFFFFF;
if (voiceFormat == AX_FORMAT_PCM8)
{
// calculate offset (in bytes)
endOffsetPtr = sampleBase + endOffset;
}
else if (voiceFormat == AX_FORMAT_PCM16)
{
// calculate offset (in shorts)
endOffsetPtr = sampleBase / 2 + endOffset;
}
else if (voiceFormat == AX_FORMAT_ADPCM)
{
// calculate offset (in nibbles)
endOffsetPtr = sampleBase * 2 + endOffset;
}
else
{
cemu_assert_debug(false);
}
internal->internalOffsets.endOffsetPtrHigh = _swapEndianU16(endOffsetPtr >> 16);
internal->internalOffsets.endOffsetPtrLow = _swapEndianU16(endOffsetPtr & 0xFFFF);
AXSetSyncFlag(vpb, AX_SYNCFLAG_ENDOFFSET);
AXVoiceProtection_Acquire(vpb);
}
void AXSetVoiceCurrentOffsetEx(AXVPB* vpb, uint32 currentOffset, MPTR sampleBase)
{
cemu_assert(vpb != NULL && sampleBase != MPTR_NULL);
AXPBOFFSET_t pbOffset;
vpb->offsets.samples = _swapEndianU32(sampleBase);
AXGetVoiceOffsets(vpb, &pbOffset);
AXSetVoiceCurrentOffset(vpb, currentOffset);
}
void AXSetVoiceLoopOffsetEx(AXVPB* vpb, uint32 loopOffset, MPTR sampleBase)
{
cemu_assert(vpb != NULL && sampleBase != MPTR_NULL);
AXPBOFFSET_t pbOffset;
vpb->offsets.samples = _swapEndianU32(sampleBase);
AXGetVoiceOffsets(vpb, &pbOffset);
AXSetVoiceLoopOffset(vpb, loopOffset);
}
void AXSetVoiceEndOffsetEx(AXVPB* vpb, uint32 endOffset, MPTR sampleBase)
{
cemu_assert(vpb != NULL && sampleBase != MPTR_NULL);
AXPBOFFSET_t pbOffset;
vpb->offsets.samples = _swapEndianU32(sampleBase);
AXGetVoiceOffsets(vpb, &pbOffset);
AXSetVoiceEndOffset(vpb, endOffset);
}
uint32 AXGetVoiceCurrentOffsetEx(AXVPB* vpb, MPTR sampleBase)
{
cemu_assert(vpb != NULL && sampleBase != MPTR_NULL);
AXPBOFFSET_t pbOffset;
AXGetVoiceOffsetsEx(vpb, &pbOffset, sampleBase);
return _swapEndianU32(pbOffset.currentOffset);
}
void AXSetVoiceLoop(AXVPB* vpb, uint16 loopState)
{
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + (sint32)(vpb->index);
vpb->offsets.loopFlag = _swapEndianU16(loopState);
internal->internalOffsets.loopFlag = _swapEndianU16(loopState);
AXSetSyncFlag(vpb, AX_SYNCFLAG_LOOPFLAG);
AXVoiceProtection_Acquire(vpb);
}
uint32 vpbLoopTracker_loopCount[AX_MAX_VOICES];
uint32 vpbLoopTracker_prevCurrentOffset[AX_MAX_VOICES];
void AXResetVoiceLoopCount(AXVPB* vpb)
{
if (!vpb)
return;
uint32 voiceIndex = vpb->index;
vpbLoopTracker_loopCount[voiceIndex] = 0;
vpbLoopTracker_prevCurrentOffset[voiceIndex] = 0;
}
sint32 AXGetVoiceLoopCount(AXVPB* vpb)
{
if (!vpb)
return 0;
uint32 voiceIndex = vpb->index;
AXVPBInternal_t* internal = __AXVPBInternalVoiceArray + voiceIndex;
uint32 loopOffset = internal->internalOffsets.GetLoopOffset32();
uint32 endOffset = internal->internalOffsets.GetEndOffset32();
uint32 currentOffset = internal->internalOffsets.GetCurrentOffset32();
uint32 srcRatio;
if (internal->srcFilterMode == AX_FILTER_MODE_NONE)
srcRatio = 0x10000;
else
srcRatio = internal->src.GetSrcRatio32();
uint32 loopLength = 0;
if (srcRatio != 0)
loopLength = ((endOffset - loopOffset) * 0x10000) / srcRatio;
uint32 prevCurrentOffset = vpbLoopTracker_prevCurrentOffset[voiceIndex];
uint32 voiceSamplesPerFrame = AXGetInputSamplesPerFrame();
if (loopOffset < endOffset && srcRatio != 0 && loopLength <= voiceSamplesPerFrame)
{
// handle loops shorter than one frame
uint32 loopsInFrame = ((prevCurrentOffset - loopOffset) + voiceSamplesPerFrame) / loopLength;
vpbLoopTracker_loopCount[voiceIndex] += loopsInFrame;
}
else // loopOffset >= endOffset
{
if (prevCurrentOffset <= endOffset) // loop could only happen if playback cursor was before end
{
if (loopOffset > endOffset && currentOffset >= loopOffset)
vpbLoopTracker_loopCount[voiceIndex]++;
else if (currentOffset < prevCurrentOffset && currentOffset >= loopOffset)
vpbLoopTracker_loopCount[voiceIndex]++;
}
}
vpbLoopTracker_prevCurrentOffset[voiceIndex] = currentOffset;
return vpbLoopTracker_loopCount[voiceIndex];
}
void Initialize()
{
// snd_core
cafeExportRegister("snd_core", AXSetVoiceDeviceMix, LogType::SoundAPI);
cafeExportRegister("snd_core", AXComputeLpfCoefs, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceState, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceType, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceAdpcmLoop, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceSrc, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceSrcType, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceSrcRatio, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceVe, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceAdpcm, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceLoop, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceLpf, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceLpfCoefs, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceBiquad, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceBiquadCoefs, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceOffsets, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceOffsetsEx, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceCurrentOffset, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceCurrentOffsetEx, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceLoopOffset, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceLoopOffsetEx, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceEndOffset, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceEndOffsetEx, LogType::SoundAPI);
cafeExportRegister("snd_core", AXSetVoiceSamplesAddr, LogType::SoundAPI);
cafeExportRegister("snd_core", AXIsVoiceRunning, LogType::SoundAPI);
cafeExportRegister("snd_core", AXGetVoiceLoopCount, LogType::SoundAPI);
cafeExportRegister("snd_core", AXGetVoiceOffsets, LogType::SoundAPI);
cafeExportRegister("snd_core", AXGetVoiceCurrentOffsetEx, LogType::SoundAPI);
// sndcore2
cafeExportRegister("sndcore2", AXSetVoiceDeviceMix, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXComputeLpfCoefs, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceState, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceType, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceAdpcmLoop, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceSrc, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceSrcType, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceSrcRatio, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceVe, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceAdpcm, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceLoop, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceLpf, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceLpfCoefs, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceBiquad, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceBiquadCoefs, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceOffsets, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceOffsetsEx, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceCurrentOffset, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceCurrentOffsetEx, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceLoopOffset, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceLoopOffsetEx, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceEndOffset, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceEndOffsetEx, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXSetVoiceSamplesAddr, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXIsVoiceRunning, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXGetVoiceLoopCount, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXGetVoiceOffsets, LogType::SoundAPI);
cafeExportRegister("sndcore2", AXGetVoiceCurrentOffsetEx, LogType::SoundAPI);
}
}
| 45,981
|
C++
|
.cpp
| 1,202
| 34.838602
| 373
| 0.741025
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,161
|
ax_multivoice.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/snd_core/ax_multivoice.cpp
|
#include "Cafe/OS/libs/snd_core/ax.h"
#include "Cafe/OS/libs/snd_core/ax_internal.h"
#include "Cafe/HW/MMU/MMU.h"
namespace snd_core
{
static_assert(sizeof(AXVPBMULTI) == 0x20, "");
SysAllocator<AXVPBMULTI, AX_MAX_VOICES> _buffer__AXVPBMultiVoiceArray;
AXVPBMULTI* __AXVPBMultiVoiceArray;
void AXMultiVoice_Init()
{
__AXVPBMultiVoiceArray = _buffer__AXVPBMultiVoiceArray.GetPtr();
for (sint32 i = 0; i < AX_MAX_VOICES; i++)
{
__AXVPBMultiVoiceArray[i].isUsed = 0;
}
}
sint32 AXAcquireMultiVoice(sint32 voicePriority, void* cbFunc, void* cbData, AXMULTIVOICEUKNSTRUCT* uknR6, MEMPTR<AXVPBMULTI>* multiVoiceOut)
{
for (sint32 i = 0; i < AX_MAX_VOICES; i++)
{
if (__AXVPBMultiVoiceArray[i].isUsed == (uint32)0)
{
sint16 channelCount = uknR6->channelCount;
if (channelCount <= 0 || channelCount > 6)
{
return -0x15;
}
for (sint32 f = 0; f < channelCount; f++)
{
__AXVPBMultiVoiceArray[i].voice[f] = nullptr;
}
__AXVPBMultiVoiceArray[i].isUsed = 1;
for (sint32 f = 0; f < channelCount; f++)
{
AXVPB* vpb = AXAcquireVoiceEx(voicePriority, memory_getVirtualOffsetFromPointer(cbFunc), memory_getVirtualOffsetFromPointer(cbData));
if (vpb == nullptr)
{
AXFreeMultiVoice(__AXVPBMultiVoiceArray + i);
return -0x16;
}
__AXVPBMultiVoiceArray[i].voice[f] = vpb;
}
__AXVPBMultiVoiceArray[i].channelCount = channelCount;
*multiVoiceOut = (__AXVPBMultiVoiceArray+i);
return 0;
}
}
return -0x14;
}
void AXFreeMultiVoice(AXVPBMULTI* multiVoice)
{
cemu_assert_debug(multiVoice->isUsed != (uint32)0);
uint16 numChannels = multiVoice->channelCount;
for (uint16 i = 0; i < numChannels; i++)
{
if(multiVoice->voice[i] != nullptr)
AXFreeVoice(multiVoice->voice[i].GetPtr());
multiVoice->voice[i] = nullptr;
}
multiVoice->isUsed = 0;
}
sint32 AXGetMultiVoiceReformatBufferSize(sint32 voiceFormat, uint32 channelCount, uint32 sizeInBytes, uint32be* sizeOutput)
{
// used by Axiom Verge
if (voiceFormat == AX_FORMAT_ADPCM)
{
sint32 alignedSize = (sizeInBytes + 7) & ~7;
*sizeOutput = alignedSize * channelCount;
}
else if (voiceFormat == AX_FORMAT_PCM16)
{
*sizeOutput = sizeInBytes;
}
else if (voiceFormat == AX_FORMAT_PCM8)
{
*sizeOutput = sizeInBytes<<1;
}
else
return -23;
return 0;
}
void AXSetMultiVoiceType(AXVPBMULTI* mv, uint16 type)
{
for(uint32 i = 0; i < mv->channelCount; ++i)
AXSetVoiceType(mv->voice[i].GetPtr(), type);
}
void AXSetMultiVoiceAdpcm(AXVPBMULTI* mv, AXDSPADPCM* adpcm)
{
static_assert(sizeof(AXDSPADPCM) == 0x60);
for (uint32 i = 0; i < mv->channelCount; ++i)
{
AXPBADPCM_t tmp;
tmp.gain = adpcm[i].gain.bevalue();
tmp.yn1 = adpcm[i].yn1.bevalue();
tmp.yn2 = adpcm[i].yn2.bevalue();
tmp.scale = adpcm[i].scale.bevalue();
static_assert(sizeof(tmp.a) == sizeof(adpcm->coef));
memcpy(tmp.a, adpcm[i].coef, sizeof(tmp.a));
AXSetVoiceAdpcm(mv->voice[i].GetPtr(), &tmp);
}
}
void AXSetMultiVoiceSrcType(AXVPBMULTI* mv, uint32 type)
{
for (uint32 i = 0; i < mv->channelCount; ++i)
AXSetVoiceSrcType(mv->voice[i].GetPtr(), type);
}
void AXSetMultiVoiceOffsets(AXVPBMULTI* mv, AXPBOFFSET_t* offsets)
{
for (uint32 i = 0; i < mv->channelCount; ++i)
AXSetVoiceOffsets(mv->voice[i].GetPtr(), offsets + i);
}
void AXSetMultiVoiceVe(AXVPBMULTI* mv, AXPBVE* ve)
{
for (uint32 i = 0; i < mv->channelCount; ++i)
AXSetVoiceVe(mv->voice[i].GetPtr(), ve);
}
void AXSetMultiVoiceSrcRatio(AXVPBMULTI* mv, float ratio)
{
for (uint32 i = 0; i < mv->channelCount; ++i)
AXSetVoiceSrcRatio(mv->voice[i].GetPtr(), ratio);
}
void AXSetMultiVoiceSrc(AXVPBMULTI* mv, AXPBSRC_t* src)
{
for (uint32 i = 0; i < mv->channelCount; ++i)
AXSetVoiceSrc(mv->voice[i].GetPtr(), src);
}
void AXSetMultiVoiceLoop(AXVPBMULTI* mv, uint16 loop)
{
for (uint32 i = 0; i < mv->channelCount; ++i)
AXSetVoiceLoop(mv->voice[i].GetPtr(), loop);
}
void AXSetMultiVoiceState(AXVPBMULTI* mv, uint16 state)
{
for (uint32 i = 0; i < mv->channelCount; ++i)
AXSetVoiceState(mv->voice[i].GetPtr(), state);
}
void AXSetMultiVoiceAdpcmLoop(AXVPBMULTI* mv, AXPBADPCMLOOP_t* loops)
{
for (uint32 i = 0; i < mv->channelCount; ++i)
AXSetVoiceAdpcmLoop(mv->voice[i].GetPtr(), loops + i);
}
sint32 AXIsMultiVoiceRunning(AXVPBMULTI* mv)
{
const sint32 result = AXIsVoiceRunning(mv->voice[0].GetPtr());
return result;
}
}
| 4,498
|
C++
|
.cpp
| 147
| 27.244898
| 142
| 0.688627
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,162
|
ax_ist.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/snd_core/ax_ist.cpp
|
#include "Cafe/OS/libs/snd_core/ax.h"
#include "Cafe/OS/libs/snd_core/ax_internal.h"
#include "Cafe/HW/Espresso/PPCState.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
namespace snd_core
{
sint32 __AXDeviceUpsampleStage[AX_DEV_COUNT]; // AX_UPSAMPLE_STAGE_*
sint32 AXSetDeviceUpsampleStage(sint32 device, int upsampleStage)
{
if (device != AX_DEV_TV && device != AX_DEV_DRC)
return -1;
__AXDeviceUpsampleStage[device] = upsampleStage;
return 0;
}
sint32 AXGetDeviceUpsampleStage(sint32 device, uint32be* upsampleStage)
{
if (device != AX_DEV_TV && device != AX_DEV_DRC)
return -1;
*upsampleStage = __AXDeviceUpsampleStage[device];
return 0;
}
sint32 AXGetInputSamplesPerFrame()
{
if (sndGeneric.initParam.rendererFreq == AX_RENDERER_FREQ_48KHZ)
return AX_SAMPLES_PER_3MS_48KHZ;
return AX_SAMPLES_PER_3MS_32KHZ;
}
sint32 AXGetInputSamplesPerSec()
{
sint32 samplesPerFrame = AXGetInputSamplesPerFrame();
sint32 samplesPerSecond = (samplesPerFrame * 1000) / 3;
return samplesPerSecond;
}
struct AXUpsampler
{
sint32 samples[AX_SAMPLES_MAX];
};
struct
{
AXUpsampler upsamplerArray[6];
bool useLinearUpsampler; // false -> FIR, true -> linear
}__AXTVUpsampler;
struct
{
AXUpsampler upsamplerArray[4];
bool useLinearUpsampler; // false -> FIR, true -> linear
}__AXDRCUpsampler[2];
void AXUpsampler_Init(AXUpsampler* upsampler)
{
memset(upsampler, 0, sizeof(AXUpsampler));
}
struct AXFINALMIXCBPARAM
{
/* +0x00 */ MEMPTR<MEMPTR<sint32>> data;
/* +0x04 */ uint16be numChannelInput;
/* +0x06 */ uint16be numSamples;
/* +0x08 */ uint16be numDevices;
/* +0x0A */ uint16be numChannelOutput;
};
static_assert(offsetof(AXFINALMIXCBPARAM, data) == 0x00);
static_assert(offsetof(AXFINALMIXCBPARAM, numChannelInput) == 0x04);
static_assert(offsetof(AXFINALMIXCBPARAM, numSamples) == 0x06);
static_assert(offsetof(AXFINALMIXCBPARAM, numDevices) == 0x08);
static_assert(offsetof(AXFINALMIXCBPARAM, numChannelOutput) == 0x0A);
SysAllocator<AXFINALMIXCBPARAM> __AXFinalMixCBStructTV;
SysAllocator<AXFINALMIXCBPARAM> __AXFinalMixCBStructDRC;
SysAllocator<AXFINALMIXCBPARAM> __AXFinalMixCBStructRMT;
SysAllocator<MEMPTR<sint32>, 6> __AXFinalMixCBStructTV_dataPtrArray;
SysAllocator<MEMPTR<sint32>, 4 * 2> __AXFinalMixCBStructDRC_dataPtrArray;
sint32 __AXFinalMixOutputChannelCount[AX_DEV_COUNT] = { 0 }; // number of output channels returned by final mix callback
// callbacks
MPTR __AXFrameCallback = MPTR_NULL; // set via AXRegisterFrameCallback()
MPTR __AXAppFrameCallback[AX_APP_FRAME_CALLBACK_MAX];
MPTR __AXDeviceFinalMixCallback[AX_DEV_COUNT];
SysAllocator<coreinit::OSMutex, 1> __AXAppFrameCallbackMutex;
void AXResetCallbacks()
{
__AXFrameCallback = MPTR_NULL;
for (sint32 i = 0; i < AX_APP_FRAME_CALLBACK_MAX; i++)
{
__AXAppFrameCallback[i] = MPTR_NULL;
}
coreinit::OSInitMutexEx(__AXAppFrameCallbackMutex.GetPtr(), NULL);
for (sint32 i = 0; i < AX_DEV_COUNT; i++)
__AXDeviceFinalMixCallback[i] = MPTR_NULL;
}
sint32 AXRegisterAppFrameCallback(MPTR funcAddr)
{
if (funcAddr == MPTR_NULL)
return -17;
OSLockMutex(__AXAppFrameCallbackMutex.GetPtr());
for (sint32 i = 0; i < AX_APP_FRAME_CALLBACK_MAX; i++)
{
if (__AXAppFrameCallback[i] == MPTR_NULL)
{
__AXAppFrameCallback[i] = funcAddr;
OSUnlockMutex(__AXAppFrameCallbackMutex.GetPtr());
return 0;
}
}
OSUnlockMutex(__AXAppFrameCallbackMutex.GetPtr());
return -15;
}
sint32 AXDeregisterAppFrameCallback(MPTR funcAddr)
{
if (funcAddr == MPTR_NULL)
return -17;
OSLockMutex(__AXAppFrameCallbackMutex.GetPtr());
for (sint32 i = 0; i < AX_APP_FRAME_CALLBACK_MAX; i++)
{
if (__AXAppFrameCallback[i] == funcAddr)
{
__AXAppFrameCallback[i] = MPTR_NULL;
OSUnlockMutex(__AXAppFrameCallbackMutex.GetPtr());
return 0;
}
}
OSUnlockMutex(__AXAppFrameCallbackMutex.GetPtr());
return -16; // not found
}
MPTR AXRegisterFrameCallback(MPTR funcAddr)
{
MPTR prevCallbackFunc = __AXFrameCallback;
__AXFrameCallback = funcAddr;
return prevCallbackFunc;
}
sint32 __AXTVUpsamplerSampleHistory[AX_TV_CHANNEL_COUNT] = { 0 };
sint32 __AXDRC0UpsamplerSampleHistory[AX_DRC_CHANNEL_COUNT] = { 0 };
sint32 __AXDRC1UpsamplerSampleHistory[AX_DRC_CHANNEL_COUNT] = { 0 };
void AXIst_Init()
{
// todo - double check defaults
__AXDeviceUpsampleStage[AX_DEV_TV] = AX_UPSAMPLE_STAGE_BEFORE_FINALMIX;
__AXDeviceUpsampleStage[AX_DEV_DRC] = AX_UPSAMPLE_STAGE_BEFORE_FINALMIX;
__AXDeviceUpsampleStage[AX_DEV_RMT] = AX_UPSAMPLE_STAGE_BEFORE_FINALMIX;
for (sint32 i = 0; i < AX_TV_CHANNEL_COUNT; i++)
AXUpsampler_Init(__AXTVUpsampler.upsamplerArray + i);
for (sint32 i = 0; i < AX_DRC_CHANNEL_COUNT; i++)
{
AXUpsampler_Init(__AXDRCUpsampler[0].upsamplerArray + i);
AXUpsampler_Init(__AXDRCUpsampler[1].upsamplerArray + i);
}
__AXTVUpsampler.useLinearUpsampler = false;
__AXDRCUpsampler[0].useLinearUpsampler = false;
__AXDRCUpsampler[1].useLinearUpsampler = false;
memset(__AXTVUpsamplerSampleHistory, 0, sizeof(__AXTVUpsamplerSampleHistory));
memset(__AXDRC0UpsamplerSampleHistory, 0, sizeof(__AXDRC0UpsamplerSampleHistory));
memset(__AXDRC1UpsamplerSampleHistory, 0, sizeof(__AXDRC1UpsamplerSampleHistory));
AXResetCallbacks();
}
void AXOut_ResetFinalMixCBData()
{
sint32 inputSamplesPerFrame = AXGetInputSamplesPerFrame();
// TV
__AXFinalMixCBStructTV->data = nullptr;
__AXFinalMixCBStructTV->numChannelInput = 6;
__AXFinalMixCBStructTV->numChannelOutput = 6;
__AXFinalMixCBStructTV->numSamples = inputSamplesPerFrame;
__AXFinalMixCBStructTV->numDevices = 1;
// DRC
__AXFinalMixCBStructDRC->data = nullptr;
__AXFinalMixCBStructDRC->numChannelInput = 4;
__AXFinalMixCBStructDRC->numChannelOutput = 4;
__AXFinalMixCBStructDRC->numSamples = inputSamplesPerFrame;
__AXFinalMixCBStructDRC->numDevices = 2;
// RMT
__AXFinalMixCBStructRMT->data = nullptr;
__AXFinalMixCBStructRMT->numChannelInput = 1;
__AXFinalMixCBStructRMT->numChannelOutput = 1;
__AXFinalMixCBStructRMT->numSamples = 18; // verify
__AXFinalMixCBStructRMT->numDevices = 4;
}
sint32 AXGetDeviceFinalMixCallback(sint32 device, uint32be* funcAddrPtr)
{
if (device != AX_DEV_TV && device != AX_DEV_DRC)
return -1;
*funcAddrPtr = __AXDeviceFinalMixCallback[device];
return 0;
}
sint32 AXRegisterDeviceFinalMixCallback(sint32 device, MPTR funcAddr)
{
if (device != AX_DEV_TV && device != AX_DEV_DRC)
return -1;
__AXDeviceFinalMixCallback[device] = funcAddr;
return 0;
}
SysAllocator<AXRemixMatrices_t, 12> g_remix_matrices;
sint32 AXSetDeviceRemixMatrix(sint32 deviceId, uint32 inputChannelCount, uint32 outputChannelCount, const MEMPTR<float32be>& matrix)
{
// validate parameters
if (deviceId == AX_DEV_TV)
{
if(inputChannelCount > AX_TV_CHANNEL_COUNT)
{
cemuLog_log(LogType::APIErrors, "AXSetDeviceRemixMatrix: Input channel count must be smaller or equal to 6 for TV device");
return -7;
}
if(outputChannelCount != 1 && outputChannelCount != 2 && outputChannelCount != 6)
{
// seems like Watch Dogs uses 4 as outputChannelCount for some reason?
cemuLog_log(LogType::APIErrors, "AXSetDeviceRemixMatrix: Output channel count must be 1, 2 or 6 for TV device");
return -8;
}
}
else if (deviceId == AX_DEV_DRC)
{
if(inputChannelCount > AX_DRC_CHANNEL_COUNT)
{
cemuLog_log(LogType::APIErrors, "AXSetDeviceRemixMatrix: Input channel count must be smaller or equal to 4 for DRC device");
return -7;
}
if(outputChannelCount != 1 && outputChannelCount != 2 && outputChannelCount != 4)
{
cemuLog_log(LogType::APIErrors, "AXSetDeviceRemixMatrix: Output channel count must be 1, 2 or 4 for DRC device");
return -8;
}
}
else
{
cemuLog_log(LogType::APIErrors, "AXSetDeviceRemixMatrix: Only TV (0) and DRC (1) device are supported");
return -1;
}
auto matrices = g_remix_matrices.GetPtr();
// test if we already have an entry and just need to update the matrix data
for (uint32 i = 0; i < g_remix_matrices.GetCount(); ++i)
{
if (g_remix_matrices[i].deviceEntry[deviceId].channelIn == inputChannelCount && g_remix_matrices[i].deviceEntry[deviceId].channelOut == outputChannelCount)
{
g_remix_matrices[i].deviceEntry[deviceId].matrix = matrix;
return 0;
}
}
// add new entry
for (uint32 i = 0; i < g_remix_matrices.GetCount(); ++i)
{
if (g_remix_matrices[i].deviceEntry[deviceId].channelIn == 0 && g_remix_matrices[i].deviceEntry[deviceId].channelOut == 0)
{
g_remix_matrices[i].deviceEntry[deviceId].channelIn = inputChannelCount;
g_remix_matrices[i].deviceEntry[deviceId].channelOut = outputChannelCount;
g_remix_matrices[i].deviceEntry[deviceId].matrix = matrix;
return 0;
}
}
return -9;
}
sint32 AXGetDeviceRemixMatrix(uint32 deviceId, uint32 inputChannelCount, uint32 outputChannelCount, MEMPTR<MEMPTR<float32be>>& matrix)
{
// validate parameters
if (deviceId == AX_DEV_TV)
{
cemu_assert(inputChannelCount <= AX_TV_CHANNEL_COUNT);
cemu_assert(outputChannelCount == 2 || outputChannelCount == 6);
}
else if (deviceId == AX_DEV_DRC)
{
cemu_assert(inputChannelCount <= AX_DRC_CHANNEL_COUNT);
cemu_assert(outputChannelCount == 1 || outputChannelCount == 2);
}
else if (deviceId == AX_DEV_RMT)
{
cemu_assert(false);
}
else
return -1;
for (uint32 i = 0; i < g_remix_matrices.GetCount(); ++i)
{
if (g_remix_matrices[i].deviceEntry[deviceId].channelIn == inputChannelCount && g_remix_matrices[i].deviceEntry[deviceId].channelOut == outputChannelCount)
{
*matrix = g_remix_matrices[i].deviceEntry[deviceId].matrix;
return 0;
}
}
return -10;
}
SysAllocator<sint32, AX_SAMPLES_MAX * AX_TV_CHANNEL_COUNT> __AXTVOutputBuffer;
SysAllocator<sint32, AX_SAMPLES_MAX * AX_DRC_CHANNEL_COUNT * 2> __AXDRCOutputBuffer;
SysAllocator<sint32, AX_SAMPLES_MAX * AX_TV_CHANNEL_COUNT> __AXTempFinalMixTVBuffer;
SysAllocator<sint32, AX_SAMPLES_MAX * AX_DRC_CHANNEL_COUNT * 2> __AXTempFinalMixDRCBuffer;
// 48KHz buffers
SysAllocator<sint32, AX_SAMPLES_MAX * AX_TV_CHANNEL_COUNT> __AXTVBuffer48;
SysAllocator<sint32, AX_SAMPLES_MAX * AX_DRC_CHANNEL_COUNT * 2> __AXDRCBuffer48;
sint32 AXUpsampleLinear32To48(sint32* inputBuffer, sint32* outputBuffer, sint32* sampleHistory, sint32 sampleCount, bool shiftSamples, sint32 channelCount)
{
if (shiftSamples)
{
for (sint32 c = 0; c < channelCount; c++)
{
float samplePrev = (float)sampleHistory[c];
for (sint32 i = 0; i < sampleCount; i += 2)
{
float sample0 = (float)_swapEndianS32(inputBuffer[0]);
float sample1 = (float)_swapEndianS32(inputBuffer[1]);
inputBuffer += 2;
float s0 = samplePrev * 0.66666669f + sample0 * 0.33333331f;
float s1 = sample0;
float s2 = sample1 * 0.66666669f + sample0 * 0.33333331f;
outputBuffer[0] = _swapEndianS32(((sint32)s0) >> 8);
outputBuffer[1] = _swapEndianS32(((sint32)s1) >> 8);
outputBuffer[2] = _swapEndianS32(((sint32)s2) >> 8);
outputBuffer += 3;
samplePrev = sample1;
}
sampleHistory[c] = (sint32)samplePrev;
}
}
else
{
for (sint32 c = 0; c < channelCount; c++)
{
float samplePrev = (float)sampleHistory[c];
for (sint32 i = 0; i < sampleCount; i += 2)
{
float sample0 = (float)_swapEndianS32(inputBuffer[0]);
float sample1 = (float)_swapEndianS32(inputBuffer[1]);
inputBuffer += 2;
float s0 = samplePrev * 0.66666669f + sample0 * 0.33333331f;
float s1 = sample0;
float s2 = sample1 * 0.66666669f + sample0 * 0.33333331f;
outputBuffer[0] = _swapEndianS32(((sint32)s0));
outputBuffer[1] = _swapEndianS32(((sint32)s1));
outputBuffer[2] = _swapEndianS32(((sint32)s2));
outputBuffer += 3;
samplePrev = sample1;
}
sampleHistory[c] = (sint32)samplePrev;
}
}
return (sampleCount / 2) * 3;
}
void AXTransferSamples(sint32* input, sint32* output, sint32 count, bool shiftSamples)
{
if (shiftSamples)
{
for (sint32 i = 0; i < count; i++)
{
sint32 s = _swapEndianS32(input[i]);
s >>= 8;
output[i] = _swapEndianS32(s);
}
}
else
{
for (sint32 i = 0; i < count; i++)
output[i] = input[i];
}
}
void AXIst_ProcessFinalMixCallback()
{
bool forceLinearUpsampler = true;
bool isRenderer48 = sndGeneric.initParam.rendererFreq == AX_RENDERER_FREQ_48KHZ;
sint32 inputSampleCount = AXGetInputSamplesPerFrame();
// TV
if (isRenderer48 || __AXDeviceUpsampleStage[AX_DEV_TV] != AX_UPSAMPLE_STAGE_BEFORE_FINALMIX)
{
// only copy
sint32* inputBuffer = __AXTVOutputBuffer;
sint32* outputBuffer = __AXTempFinalMixTVBuffer.GetPtr();
sint32 sampleCount = inputSampleCount * AX_TV_CHANNEL_COUNT;
for (sint32 i = 0; i < sampleCount; i++)
{
sint32 sample0 = _swapEndianS32(inputBuffer[0]);
sample0 >>= 8;
inputBuffer++;
*outputBuffer = _swapEndianS32(sample0);
outputBuffer++;
}
for (sint32 c = 0; c < AX_TV_CHANNEL_COUNT; c++)
{
__AXFinalMixCBStructTV_dataPtrArray[c] = __AXTempFinalMixTVBuffer.GetPtr() + c * inputSampleCount;
}
__AXFinalMixCBStructTV->numSamples = (uint16)inputSampleCount;
__AXFinalMixCBStructTV->data = __AXFinalMixCBStructTV_dataPtrArray.GetPtr();
}
else
{
// upsample
sint32 upsampledSampleCount;
if (__AXTVUpsampler.useLinearUpsampler || forceLinearUpsampler)
{
upsampledSampleCount = AXUpsampleLinear32To48(__AXTVOutputBuffer, __AXTVBuffer48.GetPtr(), __AXTVUpsamplerSampleHistory, inputSampleCount, true, AX_TV_CHANNEL_COUNT);
}
else
{
cemu_assert(false); // todo
}
for (sint32 c = 0; c < AX_TV_CHANNEL_COUNT; c++)
{
__AXFinalMixCBStructTV_dataPtrArray[c] = __AXTVBuffer48.GetPtr() + c * upsampledSampleCount;
}
__AXFinalMixCBStructTV->numSamples = (uint16)upsampledSampleCount;
__AXFinalMixCBStructTV->data = __AXFinalMixCBStructTV_dataPtrArray.GetPtr();
}
// DRC
if (isRenderer48 || __AXDeviceUpsampleStage[AX_DEV_DRC] != AX_UPSAMPLE_STAGE_BEFORE_FINALMIX)
{
// only copy
sint32* inputBuffer = __AXDRCOutputBuffer;
sint32* outputBuffer = __AXTempFinalMixDRCBuffer.GetPtr();
sint32 sampleCount = inputSampleCount * AX_DRC_CHANNEL_COUNT * 2;
for (sint32 i = 0; i < sampleCount; i++)
{
sint32 sample0 = _swapEndianS32(inputBuffer[0]);
sample0 >>= 8;
inputBuffer++;
*outputBuffer = _swapEndianS32(sample0);
outputBuffer++;
}
for (sint32 c = 0; c < AX_DRC_CHANNEL_COUNT*2; c++)
{
__AXFinalMixCBStructDRC_dataPtrArray[c] = __AXTempFinalMixDRCBuffer.GetPtr() + c * inputSampleCount;
}
__AXFinalMixCBStructDRC->numSamples = (uint16)inputSampleCount;
__AXFinalMixCBStructDRC->data = __AXFinalMixCBStructDRC_dataPtrArray.GetPtr();
}
else
{
// upsample
sint32 upsampledSampleCount;
// DRC0
if (__AXDRCUpsampler[0].useLinearUpsampler || forceLinearUpsampler)
upsampledSampleCount = AXUpsampleLinear32To48(__AXDRCOutputBuffer, __AXDRCBuffer48.GetPtr(), __AXDRC0UpsamplerSampleHistory, inputSampleCount, true, AX_DRC_CHANNEL_COUNT);
else
{
cemu_assert(false); // todo
}
// DRC1
if (__AXDRCUpsampler[1].useLinearUpsampler || forceLinearUpsampler)
upsampledSampleCount = AXUpsampleLinear32To48(__AXDRCOutputBuffer + (upsampledSampleCount*AX_DRC_CHANNEL_COUNT), __AXDRCBuffer48.GetPtr()+inputSampleCount*AX_DRC_CHANNEL_COUNT, __AXDRC1UpsamplerSampleHistory, inputSampleCount, true, AX_DRC_CHANNEL_COUNT);
else
{
cemu_assert(false); // todo
}
for (sint32 c = 0; c < AX_DRC_CHANNEL_COUNT * 2; c++)
__AXFinalMixCBStructDRC_dataPtrArray[c] = __AXDRCBuffer48.GetPtr() + c * upsampledSampleCount;
__AXFinalMixCBStructDRC->numSamples = (uint16)upsampledSampleCount;
__AXFinalMixCBStructDRC->data = __AXFinalMixCBStructDRC_dataPtrArray.GetPtr();
}
// do callbacks
__AXFinalMixOutputChannelCount[0] = AX_TV_CHANNEL_COUNT;
__AXFinalMixOutputChannelCount[1] = AX_DRC_CHANNEL_COUNT;
__AXFinalMixOutputChannelCount[2] = AX_RMT_CHANNEL_COUNT;
for (sint32 i = 0; i < AX_DEV_COUNT; i++)
{
if (__AXDeviceFinalMixCallback[i] == MPTR_NULL)
continue;
MEMPTR<AXFINALMIXCBPARAM> cbStruct;
if (i == AX_DEV_TV)
cbStruct = &__AXFinalMixCBStructTV;
else if (i == AX_DEV_DRC)
cbStruct = &__AXFinalMixCBStructDRC;
else if (i == AX_DEV_RMT)
cbStruct = &__AXFinalMixCBStructRMT;
if (i == 2 && __AXDeviceFinalMixCallback[i])
{
cemu_assert_debug(false); // RMT callbacks need testing
}
PPCCoreCallback(__AXDeviceFinalMixCallback[i], cbStruct);
__AXFinalMixOutputChannelCount[i] = (sint32)cbStruct->numChannelOutput;
}
// handle upsampling
if (isRenderer48)
{
// copy TV
AXTransferSamples(__AXTempFinalMixTVBuffer.GetPtr(), __AXTVBuffer48.GetPtr(), AX_SAMPLES_PER_3MS_48KHZ*AX_TV_CHANNEL_COUNT, false);
// copy DRC 0
AXTransferSamples(__AXTempFinalMixDRCBuffer.GetPtr(), __AXDRCBuffer48.GetPtr(), AX_SAMPLES_PER_3MS_48KHZ*AX_DRC_CHANNEL_COUNT, false);
}
else
{
if (__AXDeviceUpsampleStage[AX_DEV_TV] == AX_UPSAMPLE_STAGE_BEFORE_FINALMIX)
{
// final mix is 48KHz
// no need to copy since samples are already in right buffer
}
else
{
// final mix is 32KHz -> upsample
// TV
sint32 upsampledSampleCount;
if (__AXTVUpsampler.useLinearUpsampler || forceLinearUpsampler)
{
upsampledSampleCount = AXUpsampleLinear32To48(__AXTempFinalMixTVBuffer.GetPtr(), __AXTVBuffer48.GetPtr(), __AXTVUpsamplerSampleHistory, inputSampleCount, false, AX_TV_CHANNEL_COUNT);
}
else
{
cemu_assert(false);
}
// DRC0
if (__AXDRCUpsampler[0].useLinearUpsampler || forceLinearUpsampler)
{
AXUpsampleLinear32To48(__AXTempFinalMixDRCBuffer.GetPtr(), __AXDRCBuffer48.GetPtr(), __AXDRC0UpsamplerSampleHistory, inputSampleCount, false, AX_DRC_CHANNEL_COUNT);
}
else
{
cemu_assert(false);
}
}
}
}
void AXIst_SyncSingleVPB(AXVPB* vpb)
{
uint32 index = vpb->index;
uint32 sync = vpb->sync;
AXVPBInternal_t* internalVPB = __AXVPBInternalVoiceArray + index;
AXVPBInternal_t* internalShadowCopy = __AXVPBInternalVoiceShadowCopyArrayPtr + index;
// shadow copy -> internal data
internalShadowCopy->nextAddrHigh = internalVPB->nextAddrHigh;
internalShadowCopy->nextAddrLow = internalVPB->nextAddrLow;
if (internalVPB->nextToProcess != nullptr)
internalShadowCopy->nextToProcess = __AXVPBInternalVoiceShadowCopyArrayPtr + (sint32)internalVPB->nextToProcess->index;
else
internalShadowCopy->nextToProcess = nullptr;
internalShadowCopy->mixerSelect = internalVPB->mixerSelect;
internalShadowCopy->ukn2A2 = internalVPB->ukn2A2;
internalShadowCopy->reserved296 = internalVPB->reserved296;
internalShadowCopy->reserved298 = internalVPB->reserved298;
internalShadowCopy->reserved29A = internalVPB->reserved29A;
internalShadowCopy->reserved29C = internalVPB->reserved29C;
internalShadowCopy->reserved29E = internalVPB->reserved29E;
// sync current playback state
if ((sync&AX_SYNCFLAG_PLAYBACKSTATE) == 0)
{
uint32 playbackState = _swapEndianU16(internalShadowCopy->playbackState);
vpb->playbackState = playbackState;
internalVPB->playbackState = _swapEndianU16(playbackState);
}
// sync current offset
if ((sync&(AX_SYNCFLAG_CURRENTOFFSET | AX_SYNCFLAG_OFFSETS)) == 0)
{
internalVPB->internalOffsets.currentOffsetPtrHigh = internalShadowCopy->internalOffsets.currentOffsetPtrHigh;
internalVPB->internalOffsets.currentOffsetPtrLow = internalShadowCopy->internalOffsets.currentOffsetPtrLow;
}
// sync volume
if ((sync&AX_SYNCFLAG_VE) == 0)
{
internalVPB->veVolume = internalShadowCopy->veVolume;
}
// sync adpcm data
if ((sync&AX_SYNCFLAG_ADPCMDATA) == 0)
{
for (sint32 i = 0; i < 16; i++)
internalVPB->adpcmData.coef[i] = internalShadowCopy->adpcmData.coef[i];
internalVPB->adpcmData.gain = internalShadowCopy->adpcmData.gain;
internalVPB->adpcmData.scale = internalShadowCopy->adpcmData.scale;
internalVPB->adpcmData.yn1 = internalShadowCopy->adpcmData.yn1;
internalVPB->adpcmData.yn2 = internalShadowCopy->adpcmData.yn2;
}
// sync src data
if ((sync&AX_SYNCFLAG_SRCDATA) == 0)
{
internalVPB->src.currentFrac = internalShadowCopy->src.currentFrac;
internalVPB->src.historySamples[0] = internalShadowCopy->src.historySamples[0];
internalVPB->src.historySamples[1] = internalShadowCopy->src.historySamples[1];
internalVPB->src.historySamples[2] = internalShadowCopy->src.historySamples[2];
internalVPB->src.historySamples[3] = internalShadowCopy->src.historySamples[3];
}
if (AXVoiceProtection_IsProtectedByAnyThread(vpb))
{
// if voice is currently protected, dont sync remaining flags
return;
}
// internal data -> shadow copy
// sync src type
if ((sync&AX_SYNCFLAG_SRCFILTER) != 0)
{
internalShadowCopy->srcFilterMode = internalVPB->srcFilterMode;
internalShadowCopy->srcTapFilter = internalVPB->srcTapFilter;
}
// Sync device mix
if ((sync&AX_SYNCFLAG_DEVICEMIXMASK) != 0)
{
memcpy(internalShadowCopy->deviceMixMaskTV, internalVPB->deviceMixMaskTV, 8);
memcpy(internalShadowCopy->deviceMixMaskDRC, internalVPB->deviceMixMaskDRC, 0x10);
memcpy(internalShadowCopy->deviceMixMaskRMT, internalVPB->deviceMixMaskRMT, 0x20);
}
// sync device mix
if ((sync & AX_SYNCFLAG_DEVICEMIX) != 0)
{
memcpy(internalShadowCopy->deviceMixTV, internalVPB->deviceMixTV, 0x60);
memcpy(internalShadowCopy->deviceMixDRC, internalVPB->deviceMixDRC, 0x80);
memcpy(internalShadowCopy->deviceMixRMT, internalVPB->deviceMixRMT, 0x40);
}
// sync playback state
if ((sync&AX_SYNCFLAG_PLAYBACKSTATE) != 0)
{
internalShadowCopy->playbackState = internalVPB->playbackState;
}
// sync voice type
if ((sync&AX_SYNCFLAG_VOICETYPE) != 0)
{
internalShadowCopy->voiceType = internalVPB->voiceType;
}
// itd
if ((sync&AX_SYNCFLAG_ITD40) == 0)
{
if ((sync&AX_SYNCFLAG_ITD20) != 0)
{
//cemu_assert_debug(false); // sync PB itd
}
}
else
{
// sync itd
internalShadowCopy->reserved176_itdRelated = internalVPB->reserved176_itdRelated;
internalShadowCopy->reserved178_itdRelated = internalVPB->reserved178_itdRelated;
}
// sync volume envelope
// the part below could be incorrect (it seems strange that the delta flag overwrites the full ve flag? But PPC code looks like this)
if ((sync&AX_SYNCFLAG_VEDELTA) != 0)
{
internalShadowCopy->veDelta = internalVPB->veDelta;
}
else if ((sync&AX_SYNCFLAG_VE) != 0)
{
internalShadowCopy->veVolume = internalVPB->veVolume;
internalShadowCopy->veDelta = internalVPB->veDelta;
}
// sync offsets
if ((sync&AX_SYNCFLAG_OFFSETS) != 0)
{
// sync entire offsets block
memcpy(&internalShadowCopy->internalOffsets, &internalVPB->internalOffsets, sizeof(axOffsetsInternal_t));
}
else
{
// sync individual offset fields
if ((sync&AX_SYNCFLAG_LOOPFLAG) != 0)
{
// sync loop flag
internalShadowCopy->internalOffsets.loopFlag = internalVPB->internalOffsets.loopFlag;
}
if ((sync&AX_SYNCFLAG_LOOPOFFSET) != 0)
{
// sync loop offset
internalShadowCopy->internalOffsets.loopOffsetPtrLow = internalVPB->internalOffsets.loopOffsetPtrLow;
internalShadowCopy->internalOffsets.loopOffsetPtrHigh = internalVPB->internalOffsets.loopOffsetPtrHigh;
}
if ((sync&AX_SYNCFLAG_ENDOFFSET) != 0)
{
// sync end offset
internalShadowCopy->internalOffsets.endOffsetPtrLow = internalVPB->internalOffsets.endOffsetPtrLow;
internalShadowCopy->internalOffsets.endOffsetPtrHigh = internalVPB->internalOffsets.endOffsetPtrHigh;
}
if ((sync&AX_SYNCFLAG_CURRENTOFFSET) != 0)
{
// sync current offset
internalShadowCopy->internalOffsets.currentOffsetPtrLow = internalVPB->internalOffsets.currentOffsetPtrLow;
internalShadowCopy->internalOffsets.currentOffsetPtrHigh = internalVPB->internalOffsets.currentOffsetPtrHigh;
}
}
if ((sync&AX_SYNCFLAG_ADPCMDATA) != 0)
{
// sync adpcm data
for (sint32 i = 0; i < 16; i++)
internalShadowCopy->adpcmData.coef[i] = internalVPB->adpcmData.coef[i];
internalShadowCopy->adpcmData.gain = internalVPB->adpcmData.gain;
internalShadowCopy->adpcmData.scale = internalVPB->adpcmData.scale;
}
if ((sync&AX_SYNCFLAG_SRCDATA) != 0)
{
// sync voice all src data
internalShadowCopy->src.ratioHigh = internalVPB->src.ratioHigh;
internalShadowCopy->src.ratioLow = internalVPB->src.ratioLow;
internalShadowCopy->src.currentFrac = internalVPB->src.currentFrac;
internalShadowCopy->src.historySamples[0] = internalVPB->src.historySamples[0];
internalShadowCopy->src.historySamples[1] = internalVPB->src.historySamples[1];
internalShadowCopy->src.historySamples[2] = internalVPB->src.historySamples[2];
internalShadowCopy->src.historySamples[3] = internalVPB->src.historySamples[3];
}
else
{
if ((sync&AX_SYNCFLAG_SRCRATIO) != 0)
{
// sync voice src ratio
internalShadowCopy->src.ratioHigh = internalVPB->src.ratioHigh;
internalShadowCopy->src.ratioLow = internalVPB->src.ratioLow;
}
}
if ((sync&AX_SYNCFLAG_ADPCMLOOP) != 0)
{
// sync voice adpcm loop
internalShadowCopy->adpcmLoop.loopScale = internalVPB->adpcmLoop.loopScale;
internalShadowCopy->adpcmLoop.loopYn1 = internalVPB->adpcmLoop.loopYn1;
internalShadowCopy->adpcmLoop.loopYn2 = internalVPB->adpcmLoop.loopYn2;
}
if ((sync&AX_SYNCFLAG_LPFCOEF) != 0)
{
// sync lpf coef
internalShadowCopy->lpf.a0 = internalVPB->lpf.a0;
internalShadowCopy->lpf.b0 = internalVPB->lpf.b0;
}
else
{
if ((sync&AX_SYNCFLAG_LPFDATA) != 0)
{
// sync lpf
internalShadowCopy->lpf.on = internalVPB->lpf.on;
internalShadowCopy->lpf.yn1 = internalVPB->lpf.yn1;
internalShadowCopy->lpf.a0 = internalVPB->lpf.a0;
internalShadowCopy->lpf.b0 = internalVPB->lpf.b0;
}
}
if ((sync&AX_SYNCFLAG_BIQUADCOEF) != 0)
{
// sync biquad coef
internalShadowCopy->biquad.b0 = internalVPB->biquad.b0;
internalShadowCopy->biquad.b1 = internalVPB->biquad.b1;
internalShadowCopy->biquad.b2 = internalVPB->biquad.b2;
internalShadowCopy->biquad.a1 = internalVPB->biquad.a1;
internalShadowCopy->biquad.a2 = internalVPB->biquad.a2;
}
else if ((sync&AX_SYNCFLAG_BIQUADDATA) != 0)
{
// sync biquad
internalShadowCopy->biquad.on = internalVPB->biquad.on;
internalShadowCopy->biquad.xn1 = internalVPB->biquad.xn1;
internalShadowCopy->biquad.xn2 = internalVPB->biquad.xn2;
internalShadowCopy->biquad.yn1 = internalVPB->biquad.yn1;
internalShadowCopy->biquad.yn2 = internalVPB->biquad.yn2;
internalShadowCopy->biquad.b0 = internalVPB->biquad.b0;
internalShadowCopy->biquad.b1 = internalVPB->biquad.b1;
internalShadowCopy->biquad.b2 = internalVPB->biquad.b2;
internalShadowCopy->biquad.a1 = internalVPB->biquad.a1;
internalShadowCopy->biquad.a2 = internalVPB->biquad.a2;
}
if ((sync&AX_SYNCFLAG_VOICEREMOTEON) != 0)
{
// sync VoiceRmtOn (AXSetVoiceRmtOn)
internalShadowCopy->reserved148_voiceRmtOn = internalVPB->reserved148_voiceRmtOn;
}
if ((sync&AX_SYNCFLAG_4000000) != 0)
{
// todo
}
if ((sync&AX_SYNCFLAG_8000000) != 0)
{
// todo
// AXSetVoiceRmtSrc
}
// other flags todo: 0x10000000, 0x20000000, 0x40000000 for RmtIIR
}
void AXIst_SyncVPB(AXVPBInternal_t** lastProcessedDSPShadowCopy, AXVPBInternal_t** lastProcessedPPCShadowCopy)
{
__AXVoiceListSpinlock.lock();
AXVPBInternal_t* previousInternalDSP = nullptr;
AXVPBInternal_t* previousInternalPPC = nullptr;
for (sint32 priority = AX_PRIORITY_MAX - 1; priority >= AX_PRIORITY_LOWEST; priority--)
{
auto& voiceArray = AXVoiceList_GetListByPriority(priority);
for(auto vpb : voiceArray)
{
sint32 index = vpb->index;
sint32 depop = vpb->depop;
AXVPBInternal_t* internalVPB = __AXVPBInternalVoiceArray + index;
AXVPBInternal_t* internalShadowCopy = __AXVPBInternalVoiceShadowCopyArrayPtr + index;
internalVPB->mixerSelect = vpb->mixerSelect;
AXVPB* nextVpb = vpb->next.GetPtr();
if (depop)
{
AXMix_DepopVoice(internalShadowCopy);
vpb->depop = 0;
}
if (internalVPB->playbackState != _swapEndianU16(1) && vpb->sync == 0)
{
internalVPB->ukn2A2 = 2;
internalShadowCopy->ukn2A2 = 2;
internalVPB->nextAddrHigh = 0;
internalVPB->nextAddrLow = 0;
}
else
{
internalVPB->ukn2A2 = 1;
if (previousInternalPPC)
{
internalVPB->nextAddrHigh = previousInternalPPC->selfAddrHigh;
internalVPB->nextAddrLow = previousInternalPPC->selfAddrLow;
internalVPB->nextToProcess = previousInternalPPC;
previousInternalPPC = internalVPB;
}
else
{
internalVPB->nextAddrHigh = 0;
internalVPB->nextAddrLow = 0;
internalVPB->nextToProcess = nullptr;
previousInternalPPC = internalVPB;
}
AXIst_SyncSingleVPB(vpb);
if (!AXVoiceProtection_IsProtectedByAnyThread(vpb))
{
vpb->depop = 0;
vpb->sync = 0;
}
}
}
}
// depop and reset voices which just stopped playing
auto& freeVoicesArray = AXVoiceList_GetFreeVoices();
for(auto vpb : freeVoicesArray)
{
AXVPBInternal_t* internalVPB = __AXVPBInternalVoiceArray + (sint32)vpb->index;
AXVPBInternal_t* internalShadowCopy = __AXVPBInternalVoiceShadowCopyArrayPtr + (sint32)vpb->index;
if (vpb->depop != (uint32be)0)
{
AXMix_DepopVoice(internalShadowCopy);
vpb->depop = 0;
}
vpb->playbackState = 0;
internalVPB->ukn2A2 = 2;
internalShadowCopy->ukn2A2 = 2;
internalVPB->playbackState = 0;
internalShadowCopy->playbackState = 0;
}
// return last processed DSP/PPC voice internal shadow copy
if (lastProcessedDSPShadowCopy)
{
if (previousInternalDSP)
{
AXVPBInternal_t* internalShadowCopy = __AXVPBInternalVoiceShadowCopyArrayPtr + (sint32)previousInternalDSP->index;
*lastProcessedDSPShadowCopy = internalShadowCopy;
}
else
*lastProcessedDSPShadowCopy = nullptr;
}
if (lastProcessedPPCShadowCopy)
{
if (previousInternalPPC)
{
AXVPBInternal_t* internalShadowCopy = __AXVPBInternalVoiceShadowCopyArrayPtr + (sint32)previousInternalPPC->index;
*lastProcessedPPCShadowCopy = internalShadowCopy;
}
else
*lastProcessedPPCShadowCopy = nullptr;
}
__AXVoiceListSpinlock.unlock();
}
void AXIst_HandleFrameCallbacks()
{
// frame callback
if (__AXFrameCallback != MPTR_NULL)
{
// execute frame callback (no params)
PPCCore_executeCallbackInternal(__AXFrameCallback);
}
// app frame callback
for (sint32 i = 0; i < AX_APP_FRAME_CALLBACK_MAX; i++)
{
if (__AXAppFrameCallback[i] == MPTR_NULL)
continue;
// execute app frame callback (no params)
PPCCore_executeCallbackInternal(__AXAppFrameCallback[i]);
}
}
void AXIst_ApplyDeviceRemix(sint32be* samples, float32be* matrix, sint32 inputChannelCount, sint32 outputChannelCount, sint32 sampleCount)
{
for (auto i = 0; i < sampleCount; ++i)
{
float tmp[6]{};
for(auto j = 0; j < inputChannelCount; ++j)
{
tmp[j] = (float)samples[j * sampleCount + i];
}
float32be* mtx = matrix;
int tmpOut[10]{};
for(auto j = 0; j < outputChannelCount; ++j)
{
tmpOut[j] = 0;
for (auto k = 0; k < inputChannelCount; ++k)
{
tmpOut[j] += (int)(tmp[k] * (*mtx));
mtx++;
}
}
for (auto j = 0; j < outputChannelCount; ++j)
{
samples[j * sampleCount + i] = tmpOut[j];
}
}
}
void AXIst_HandleDeviceRemix()
{
extern SysAllocator<AXRemixMatrices_t, 12> g_remix_matrices;
extern sint32 __AXOutTVOutputChannelCount;
extern sint32 __AXOutDRCOutputChannelCount;
// tv remix matrix
for(uint32 i = 0; i < g_remix_matrices.GetCount(); ++i)
{
const auto& entry = g_remix_matrices[i];
if(entry.deviceEntry[0].channelIn == __AXFinalMixCBStructTV->numChannelInput && entry.deviceEntry[0].channelOut == __AXOutTVOutputChannelCount && !entry.deviceEntry[0].matrix.IsNull())
{
AXIst_ApplyDeviceRemix((sint32be*)__AXTVBuffer48.GetPtr(), entry.deviceEntry[0].matrix.GetPtr(), __AXFinalMixCBStructTV->numChannelInput, __AXOutTVOutputChannelCount, AX_SAMPLES_PER_3MS_48KHZ);
break;
}
}
// drc remix matrix
for (uint32 i = 0; i < g_remix_matrices.GetCount(); ++i)
{
const auto& entry = g_remix_matrices[i];
if (entry.deviceEntry[1].channelIn == __AXFinalMixCBStructDRC->numChannelInput && entry.deviceEntry[1].channelOut == __AXOutDRCOutputChannelCount && !entry.deviceEntry[0].matrix.IsNull())
{
AXIst_ApplyDeviceRemix((sint32be*)__AXDRCBuffer48.GetPtr(), entry.deviceEntry[1].matrix.GetPtr(), __AXFinalMixCBStructDRC->numChannelInput, __AXOutDRCOutputChannelCount, AX_SAMPLES_PER_3MS_48KHZ);
break;
}
}
}
std::atomic_bool __AXIstIsProcessingFrame = false;
SysAllocator<OSThread_t> __AXIstThread;
SysAllocator<uint8, 0x4000> __AXIstThreadStack;
SysAllocator<coreinit::OSMessage, 0x10> __AXIstThreadMsgArray;
SysAllocator<coreinit::OSMessageQueue, 1> __AXIstThreadMsgQueue;
void AXIst_InitThread()
{
__AXIstIsProcessingFrame = false;
// create ist message queue
OSInitMessageQueue(__AXIstThreadMsgQueue.GetPtr(), __AXIstThreadMsgArray.GetPtr(), 0x10);
// create thread
uint8 istThreadAttr = 0;
coreinit::__OSCreateThreadType(__AXIstThread.GetPtr(), PPCInterpreter_makeCallableExportDepr(AXIst_ThreadEntry), 0, &__AXIstThreadMsgQueue, __AXIstThreadStack.GetPtr() + 0x4000, 0x4000, 14, istThreadAttr, OSThread_t::THREAD_TYPE::TYPE_DRIVER);
coreinit::OSResumeThread(__AXIstThread.GetPtr());
}
OSThread_t* AXIst_GetThread()
{
return __AXIstThread.GetPtr();
}
void AXIst_GenerateFrame()
{
// generate one frame (3MS) of audio
__AXIstIsProcessingFrame.store(true);
memset(__AXTVOutputBuffer.GetPtr(), 0, AX_SAMPLES_PER_3MS_48KHZ * AX_TV_CHANNEL_COUNT * sizeof(sint32));
memset(__AXDRCOutputBuffer.GetPtr(), 0, AX_SAMPLES_PER_3MS_48KHZ * AX_DRC_CHANNEL_COUNT * sizeof(sint32));
AXVPBInternal_t* internalShadowCopyDSPHead = nullptr;
AXVPBInternal_t* internalShadowCopyPPCHead = nullptr;
AXIst_SyncVPB(&internalShadowCopyDSPHead, &internalShadowCopyPPCHead);
if (internalShadowCopyDSPHead)
assert_dbg();
AXMix_process(internalShadowCopyPPCHead);
AXOut_ResetFinalMixCBData();
AXIst_ProcessFinalMixCallback();
AXIst_HandleDeviceRemix();
// todo - additional phases. See unimplemented API:
// AXSetDRCVSMode
// AXSetDeviceCompressor
// AXRegisterPostFinalMixCallback
AXOut_SubmitTVFrame(0);
AXOut_SubmitDRCFrame(0);
__AXIstIsProcessingFrame.store(false);
}
void AXIst_ThreadEntry(PPCInterpreter_t* hCPU)
{
while (true)
{
StackAllocator<coreinit::OSMessage, 1> msg;
OSReceiveMessage(__AXIstThreadMsgQueue.GetPtr(), msg.GetPointer(), OS_MESSAGE_BLOCK);
if (msg.GetPointer()->message == 2)
{
cemuLog_logDebug(LogType::Force, "Shut down of AX thread requested");
coreinit::OSExitThread(0);
break;
}
else if (msg.GetPointer()->message != 1)
assert_dbg();
AXIst_GenerateFrame();
numProcessedFrames++;
}
}
SysAllocator<coreinit::OSMessage> _queueFrameMsg;
void AXIst_QueueFrame()
{
coreinit::OSMessage* msg = _queueFrameMsg.GetPtr();
msg->message = 1;
msg->data0 = 0;
msg->data1 = 0;
msg->data2 = 0;
OSSendMessage(__AXIstThreadMsgQueue.GetPtr(), msg, 0);
}
void AXIst_StopThread()
{
cemu_assert_debug(coreinit::OSIsThreadTerminated(AXIst_GetThread()) == false);
// request thread stop
coreinit::OSMessage* msg = _queueFrameMsg.GetPtr();
msg->message = 2;
msg->data0 = 0;
msg->data1 = 0;
msg->data2 = 0;
OSSendMessage(__AXIstThreadMsgQueue.GetPtr(), msg, 0);
while (coreinit::OSIsThreadTerminated(AXIst_GetThread()) == false)
PPCCore_switchToScheduler();
}
bool AXIst_IsFrameBeingProcessed()
{
return __AXIstIsProcessingFrame.load();
}
}
| 36,036
|
C++
|
.cpp
| 993
| 32.607251
| 259
| 0.728183
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,163
|
OSCommon.cpp
|
cemu-project_Cemu/src/Cafe/OS/common/OSCommon.cpp
|
#include "Cafe/HW/Espresso/PPCState.h"
#include "Cafe/OS/libs/proc_ui/proc_ui.h"
#include "Cafe/OS/libs/nsysnet/nsysnet.h"
#include "Cafe/OS/libs/nlibnss/nlibnss.h"
#include "Cafe/OS/libs/nlibcurl/nlibcurl.h"
#include "Cafe/OS/libs/nn_nfp/nn_nfp.h"
#include "Cafe/OS/libs/nn_act/nn_act.h"
#include "Cafe/OS/libs/nn_acp/nn_acp.h"
#include "Cafe/OS/libs/nn_ac/nn_ac.h"
#include "Cafe/OS/libs/nn_uds/nn_uds.h"
#include "Cafe/OS/libs/nn_nim/nn_nim.h"
#include "Cafe/OS/libs/nn_ndm/nn_ndm.h"
#include "Cafe/OS/libs/nn_spm/nn_spm.h"
#include "Cafe/OS/libs/nn_ec/nn_ec.h"
#include "Cafe/OS/libs/nn_boss/nn_boss.h"
#include "Cafe/OS/libs/nn_sl/nn_sl.h"
#include "Cafe/OS/libs/nn_fp/nn_fp.h"
#include "Cafe/OS/libs/nn_olv/nn_olv.h"
#include "Cafe/OS/libs/nn_idbe/nn_idbe.h"
#include "Cafe/OS/libs/nn_save/nn_save.h"
#include "Cafe/OS/libs/erreula/erreula.h"
#include "Cafe/OS/libs/sysapp/sysapp.h"
#include "Cafe/OS/libs/dmae/dmae.h"
#include "Cafe/OS/libs/snd_core/ax.h"
#include "Cafe/OS/libs/gx2/GX2.h"
#include "Cafe/OS/libs/vpad/vpad.h"
#include "Cafe/OS/libs/nsyskbd/nsyskbd.h"
#include "Cafe/OS/libs/nsyshid/nsyshid.h"
#include "Cafe/OS/libs/snd_user/snd_user.h"
#include "Cafe/OS/libs/zlib125/zlib125.h"
#include "Cafe/OS/libs/padscore/padscore.h"
#include "Cafe/OS/libs/camera/camera.h"
#include "../libs/swkbd/swkbd.h"
struct osFunctionEntry_t
{
uint32 libHashA;
uint32 libHashB;
uint32 funcHashA;
uint32 funcHashB;
std::string name;
HLEIDX hleFunc;
osFunctionEntry_t(uint32 libHashA, uint32 libHashB, uint32 funcHashA, uint32 funcHashB, std::string_view name, HLEIDX hleFunc) :
libHashA(libHashA), libHashB(libHashB), funcHashA(funcHashA), funcHashB(funcHashB), name(name), hleFunc(hleFunc) {};
};
typedef struct
{
uint32 libHashA;
uint32 libHashB;
uint32 funcHashA;
uint32 funcHashB;
uint32 vPtr;
}osPointerEntry_t;
std::vector<osFunctionEntry_t>* s_osFunctionTable;
std::vector<osPointerEntry_t> osDataTable;
void osLib_generateHashFromName(const char* name, uint32* hashA, uint32* hashB)
{
uint32 h1 = 0x688BA2BA;
uint32 h2 = 0xF64A71D5;
while( *name )
{
uint32 c = (uint32)*name;
h1 += c;
h1 = (h1<<3)|((h1>>29));
h2 ^= c;
h2 = (h2<<7)|((h2>>25));
h1 += h2;
h2 += c;
h2 = (h2<<3)|((h2>>29));
name++;
}
*hashA = h1;
*hashB = h2;
}
void osLib_addFunctionInternal(const char* libraryName, const char* functionName, void(*osFunction)(PPCInterpreter_t* hCPU))
{
if (!s_osFunctionTable)
s_osFunctionTable = new std::vector<osFunctionEntry_t>(); // replace with static allocation + constinit once we have C++20 available
// calculate hash
uint32 libHashA, libHashB;
uint32 funcHashA, funcHashB;
osLib_generateHashFromName(libraryName, &libHashA, &libHashB);
osLib_generateHashFromName(functionName, &funcHashA, &funcHashB);
std::string hleName = fmt::format("{}.{}", libraryName, functionName);
// if entry already exists, update it
for (auto& it : *s_osFunctionTable)
{
if (it.libHashA == libHashA &&
it.libHashB == libHashB &&
it.funcHashA == funcHashA &&
it.funcHashB == funcHashB)
{
it.hleFunc = PPCInterpreter_registerHLECall(osFunction, hleName);
return;
}
}
s_osFunctionTable->emplace_back(libHashA, libHashB, funcHashA, funcHashB, hleName, PPCInterpreter_registerHLECall(osFunction, hleName));
}
extern "C" DLLEXPORT void osLib_registerHLEFunction(const char* libraryName, const char* functionName, void(*osFunction)(PPCInterpreter_t * hCPU))
{
osLib_addFunctionInternal(libraryName, functionName, osFunction);
}
sint32 osLib_getFunctionIndex(const char* libraryName, const char* functionName)
{
uint32 libHashA, libHashB;
uint32 funcHashA, funcHashB;
osLib_generateHashFromName(libraryName, &libHashA, &libHashB);
osLib_generateHashFromName(functionName, &funcHashA, &funcHashB);
for (auto& it : *s_osFunctionTable)
{
if (it.libHashA == libHashA &&
it.libHashB == libHashB &&
it.funcHashA == funcHashA &&
it.funcHashB == funcHashB)
{
return it.hleFunc;
}
}
return -1;
}
void osLib_addVirtualPointer(const char* libraryName, const char* functionName, uint32 vPtr)
{
// calculate hash
uint32 libHashA, libHashB;
uint32 funcHashA, funcHashB;
osLib_generateHashFromName(libraryName, &libHashA, &libHashB);
osLib_generateHashFromName(functionName, &funcHashA, &funcHashB);
// if entry already exists, update it
for (auto& it : osDataTable)
{
if (it.libHashA == libHashA &&
it.libHashB == libHashB &&
it.funcHashA == funcHashA &&
it.funcHashB == funcHashB)
{
it.vPtr = vPtr;
return;
}
}
// add entry
auto writeIndex = osDataTable.size();
osDataTable.resize(osDataTable.size() + 1);
osDataTable[writeIndex].libHashA = libHashA;
osDataTable[writeIndex].libHashB = libHashB;
osDataTable[writeIndex].funcHashA = funcHashA;
osDataTable[writeIndex].funcHashB = funcHashB;
osDataTable[writeIndex].vPtr = vPtr;
}
uint32 osLib_getPointer(const char* libraryName, const char* functionName)
{
uint32 libHashA, libHashB;
uint32 funcHashA, funcHashB;
osLib_generateHashFromName(libraryName, &libHashA, &libHashB);
osLib_generateHashFromName(functionName, &funcHashA, &funcHashB);
for (auto& it : osDataTable)
{
if (it.libHashA == libHashA &&
it.libHashB == libHashB &&
it.funcHashA == funcHashA &&
it.funcHashB == funcHashB)
{
return it.vPtr;
}
}
return 0xFFFFFFFF;
}
void osLib_returnFromFunction(PPCInterpreter_t* hCPU, uint32 returnValue)
{
hCPU->gpr[3] = returnValue;
hCPU->instructionPointer = hCPU->spr.LR;
}
void osLib_returnFromFunction64(PPCInterpreter_t* hCPU, uint64 returnValue64)
{
hCPU->gpr[3] = (returnValue64>>32)&0xFFFFFFFF;
hCPU->gpr[4] = (returnValue64>>0)&0xFFFFFFFF;
hCPU->instructionPointer = hCPU->spr.LR;
}
void osLib_load()
{
// load HLE modules
coreinit_load();
zlib::load();
gx2_load();
dmae_load();
padscore::load();
vpad::load();
snd_core::loadExports();
nn::erreula::load();
nnAct_load();
nn::acp::load();
nnAc_load();
nnEc_load();
nnBoss_load();
nn::nfp::load();
nnUds_load();
nn::nim::load();
nn::ndm::load();
nn::spm::load();
nn::save::load();
nnSL_load();
nsysnet_load();
nn::fp::load();
nn::olv::load();
nn::idbe::load();
nlibnss::load();
nlibcurl::load();
sysapp_load();
nsyshid::load();
nsyskbd::nsyskbd_load();
swkbd::load();
camera::load();
proc_ui::load();
}
| 6,304
|
C++
|
.cpp
| 212
| 27.716981
| 146
| 0.736305
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,164
|
GraphicPack2Patches.cpp
|
cemu-project_Cemu/src/Cafe/GraphicPack/GraphicPack2Patches.cpp
|
#include "Cafe/GraphicPack/GraphicPack2.h"
#include "Common/FileStream.h"
#include "util/helpers/StringParser.h"
#include "Cemu/PPCAssembler/ppcAssembler.h"
#include "Cafe/OS/RPL/rpl_structs.h"
#include "boost/algorithm/string.hpp"
#include "gui/wxgui.h" // for wxMessageBox
#include "gui/helpers/wxHelpers.h"
// error handler
void PatchErrorHandler::printError(class PatchGroup* patchGroup, sint32 lineNumber, std::string_view errorMsg)
{
if (m_anyErrorTriggered == false)
{
// stage error msg
cemu_assert(m_gp);
if (m_stage == STAGE::PARSER)
cemuLog_writeLineToLog(fmt::format("An error occurred while trying to parse the patches for graphic pack \'{}\'", m_gp->GetName()), true, true);
else if (m_stage == STAGE::APPLY)
cemuLog_writeLineToLog(fmt::format("An error occurred while trying to apply the patches for graphic pack \'{}\'", m_gp->GetName()), true, true);
}
std::string msg;
if (patchGroup == nullptr && lineNumber >= 0)
msg.append(fmt::format("[Line {}] ", lineNumber));
else if (patchGroup && lineNumber >= 0)
msg.append(fmt::format("[{}, Line {}] ", patchGroup->getName(), lineNumber));
else if (patchGroup && lineNumber < 0)
msg.append(fmt::format("[{}] ", patchGroup->getName()));
msg.append(errorMsg);
cemuLog_writeLineToLog(msg, true, true);
m_anyErrorTriggered = true;
if (cemuLog_isLoggingEnabled(LogType::Patches))
errorMessages.emplace_back(msg);
}
void PatchErrorHandler::showStageErrorMessageBox()
{
wxString errorMsg;
if (m_gp)
{
if (m_stage == STAGE::PARSER)
errorMsg.assign(formatWxString(_("Failed to load patches for graphic pack \'{}\'"), m_gp->GetName()));
else
errorMsg.assign(formatWxString(_("Failed to apply patches for graphic pack \'{}\'"), m_gp->GetName()));
}
else
{
cemu_assert_debug(false); // graphic pack should always be set
}
if (cemuLog_isLoggingEnabled(LogType::Patches))
{
errorMsg.append("\n \n")
.append(_("Details:"))
.append("\n");
for (auto& itr : errorMessages)
{
errorMsg.append(itr);
errorMsg.append("\n");
}
}
wxMessageBox(errorMsg, _("Graphic pack error"));
}
// loads Cemu-style patches (patch_<anything>.asm)
// returns true if at least one file was found even if it could not be successfully parsed
bool GraphicPack2::LoadCemuPatches()
{
bool foundPatches = false;
fs::path path(m_rulesPath);
path.remove_filename();
for (auto& p : fs::directory_iterator(path))
{
auto& path = p.path();
if (fs::is_regular_file(p.status()) && path.has_filename())
{
// check if filename matches
std::string filename = _pathToUtf8(path.filename());
if (boost::istarts_with(filename, "patch_") && boost::iends_with(filename, ".asm"))
{
FileStream* patchFile = FileStream::openFile2(path);
if (patchFile)
{
// read file
std::vector<uint8> fileData;
patchFile->extract(fileData);
delete patchFile;
MemStreamReader patchesStream(fileData.data(), (sint32)fileData.size());
// load Cemu style patch file
if (!ParseCemuPatchesTxtInternal(patchesStream))
{
cemuLog_log(LogType::Force, "Error while processing \"{}\". No patches for this graphic pack will be applied.", _pathToUtf8(path));
cemu_assert_debug(list_patchGroups.empty());
return true; // return true since a .asm patch was found even if we could not parse it
}
}
else
{
cemuLog_log(LogType::Force, "Unable to load patch file \"{}\"", _pathToUtf8(path));
}
foundPatches = true;
}
}
}
return foundPatches;
}
void GraphicPack2::LoadPatchFiles()
{
// order of loading patches:
// 1) Load Cemu-style patches (patch_<name>.asm), stop here if at least one patch file exists
// 2) Load Cemuhook patches.txt
if (LoadCemuPatches())
return; // exit if at least one Cemu style patch file was found
// fall back to Cemuhook patches.txt to guarantee backward compatibility
fs::path path(m_rulesPath);
path.remove_filename();
path.append("patches.txt");
FileStream* patchFile = FileStream::openFile2(path);
if (patchFile == nullptr)
return;
// read file
std::vector<uint8> fileData;
patchFile->extract(fileData);
delete patchFile;
cemu_assert_debug(list_patchGroups.empty());
// parse
MemStreamReader patchesStream(fileData.data(), (sint32)fileData.size());
ParseCemuhookPatchesTxtInternal(patchesStream);
}
void GraphicPack2::EnablePatches()
{
std::lock_guard<std::recursive_mutex> lock(mtx_patches);
for (auto& itr : list_modules)
ApplyPatchesForModule(itr);
}
void GraphicPack2::UnloadPatches()
{
if (list_patchGroups.empty())
return;
std::lock_guard<std::recursive_mutex> lock(mtx_patches);
// if any patch groups were applied then revert here
// do this by calling RevertPatchesForModule for every module?
for (auto& itr : list_modules)
RevertPatchesForModule(itr);
// delete all patches
for (auto itr : list_patchGroups)
delete itr;
list_patchGroups.clear();
}
bool GraphicPack2::HasPatches()
{
return !list_patchGroups.empty();
}
const std::vector<PatchGroup*>& GraphicPack2::GetPatchGroups() {
return list_patchGroups;
}
void GraphicPack2::ApplyPatchesForModule(const RPLModule* rpl)
{
if (list_patchGroups.empty())
return;
// gather list of all patch groups that apply to this module
std::vector<PatchGroup*> list_groups;
for (auto itr : list_patchGroups)
{
if (itr->matchesCRC(rpl->patchCRC))
list_groups.emplace_back(itr);
}
// apply all groups at once
if (!list_groups.empty())
ApplyPatchGroups(list_groups, rpl);
}
void GraphicPack2::RevertPatchesForModule(const RPLModule* rpl)
{
if (list_patchGroups.empty())
return;
// gather list of all patch groups that apply to this module
std::vector<PatchGroup*> list_groups;
for (auto itr : list_patchGroups)
{
if (itr->matchesCRC(rpl->patchCRC))
list_groups.emplace_back(itr);
}
// undo all groups at once
if (!list_groups.empty())
UndoPatchGroups(list_groups, rpl);
}
std::recursive_mutex GraphicPack2::mtx_patches;
std::vector<const RPLModule*> GraphicPack2::list_modules;
| 6,014
|
C++
|
.cpp
| 184
| 30.059783
| 147
| 0.724583
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,165
|
GraphicPack2PatchesParser.cpp
|
cemu-project_Cemu/src/Cafe/GraphicPack/GraphicPack2PatchesParser.cpp
|
#include "Cafe/GraphicPack/GraphicPack2.h"
#include "Common/FileStream.h"
#include "util/helpers/StringParser.h"
#include "Cemu/PPCAssembler/ppcAssembler.h"
#include "Cafe/OS/RPL/rpl_structs.h"
sint32 GraphicPack2::GetLengthWithoutComment(const char* str, size_t length)
{
sint32 index = 0;
bool isInString = false;
while (index < length)
{
const char c = str[index];
if (c == '\"')
isInString = !isInString;
else if (c == '#' || c == ';')
{
if (!isInString)
return index;
}
index++;
}
return (sint32)length;
}
void GraphicPack2::LogPatchesSyntaxError(sint32 lineNumber, std::string_view errorMsg)
{
cemuLog_log(LogType::Force, "Syntax error while parsing patch for graphic pack '{}':", _pathToUtf8(this->GetRulesPath()));
if(lineNumber >= 0)
cemuLog_log(LogType::Force, fmt::format("Line {0}: {1}", lineNumber, errorMsg));
else
cemuLog_log(LogType::Force, fmt::format("{0}", errorMsg));
list_patchGroups.clear();
}
void GraphicPack2::CancelParsingPatches()
{
// unload everything, set error flag
cemu_assert_debug(false);
}
void GraphicPack2::AddPatchGroup(PatchGroup* group)
{
if (group->list_moduleMatches.empty())
{
LogPatchesSyntaxError(-1, fmt::format("Group \"{}\" has no moduleMatches definition", group->name));
CancelParsingPatches();
delete group;
return;
}
// calculate code cave size
uint32 codeCaveMaxAddr = 0;
for (auto& itr : group->list_patches)
{
PatchEntryInstruction* patchData = dynamic_cast<PatchEntryInstruction*>(itr);
if (patchData)
{
uint32 patchAddr = patchData->getAddr();
if (patchAddr < 0x00100000)
{
// everything in low 1MB of memory we consider part of the code cave
codeCaveMaxAddr = std::max(codeCaveMaxAddr, patchAddr + patchData->getSize());
}
}
}
uint32 numEstimatedCodeCaveInstr = codeCaveMaxAddr / 4;
if (group->list_patches.size() < (numEstimatedCodeCaveInstr / 8))
{
// if less than 1/8th of the code cave is filled print a warning
cemuLog_log(LogType::Force, "Graphic pack patches: Code cave for group [{}] in gfx pack \"{}\" ranges from 0 to 0x{:x} but has only few instructions. Is this intentional?", group->name, this->m_name, codeCaveMaxAddr);
}
group->codeCaveSize = codeCaveMaxAddr;
list_patchGroups.emplace_back(group);
}
void GraphicPack2::ParseCemuhookPatchesTxtInternal(MemStreamReader& patchesStream)
{
sint32 lineNumber = 0;
PatchGroup* currentGroup = nullptr;
while (true)
{
auto lineStr = patchesStream.readLine();
lineNumber++;
if (patchesStream.hasError())
break;
// trim comment
size_t lineLength = GetLengthWithoutComment(lineStr.data(), lineStr.size());
StringTokenParser parser(lineStr.data(), (sint32)lineLength);
// skip whitespaces at the beginning
parser.skipWhitespaces();
// parse line
if (parser.isEndOfString())
continue;
if (parser.compareCharacter(0, '['))
{
// group
parser.skipCharacters(1);
// find end of group name
const char* groupNameStr = parser.getCurrentPtr();
sint32 groupNameLength = parser.skipToCharacter(']');
if (groupNameLength < 0)
{
LogPatchesSyntaxError(lineNumber, "Expected ']'");
CancelParsingPatches();
return;
}
parser.skipCharacters(1); // skip the ']'
parser.skipWhitespaces();
if (!parser.isEndOfString())
{
LogPatchesSyntaxError(lineNumber, "Unexpected characters after ']'");
CancelParsingPatches();
return;
}
// begin new group
if (currentGroup)
{
AddPatchGroup(currentGroup);
}
currentGroup = new PatchGroup(this, groupNameStr, groupNameLength);
}
else if (parser.compareCharacter(0, '0') && parser.compareCharacterI(1, 'x'))
{
// if the line starts with a hex address then it is a patched location
uint32 patchedAddress;
if (!parser.parseU32(patchedAddress))
{
LogPatchesSyntaxError(lineNumber, "Malformed address");
CancelParsingPatches();
return;
}
if (parser.matchWordI("=") == false)
{
LogPatchesSyntaxError(lineNumber, "Expected '=' after address");
CancelParsingPatches();
return;
}
parser.skipWhitespaces();
parser.trimWhitespaces();
// assemble instruction
std::string instrText(parser.getCurrentPtr(), parser.getCurrentLen());
PPCAssemblerInOut ctx{};
ctx.virtualAddress = patchedAddress;
if (!ppcAssembler_assembleSingleInstruction(instrText.c_str(), &ctx))
{
LogPatchesSyntaxError(lineNumber, fmt::format("Error in assembler: {}", ctx.errorMsg));
CancelParsingPatches();
return;
}
currentGroup->list_patches.emplace_back(new PatchEntryInstruction(lineNumber, patchedAddress, { ctx.outputData.data(), ctx.outputData.size() }, ctx.list_relocs));
}
else if (parser.matchWordI("moduleMatches"))
{
if (currentGroup == nullptr)
{
LogPatchesSyntaxError(lineNumber, "Specified 'ModuleMatches' outside of a group");
CancelParsingPatches();
return;
}
if (parser.matchWordI("=") == false)
{
LogPatchesSyntaxError(lineNumber, "Expected '=' after ModuleMatches");
CancelParsingPatches();
return;
}
// read the checksums
while (true)
{
uint32 checksum = 0;
if (parser.parseU32(checksum) == false)
{
LogPatchesSyntaxError(lineNumber, "Invalid value for ModuleMatches");
CancelParsingPatches();
return;
}
currentGroup->list_moduleMatches.emplace_back(checksum);
if (parser.matchWordI(",") == false)
break;
}
parser.skipWhitespaces();
if (!parser.isEndOfString())
{
LogPatchesSyntaxError(lineNumber, "Unexpected character in line");
CancelParsingPatches();
return;
}
continue;
}
else
{
// Cemuhook requires that user defined symbols start with _ but we are more lenient and allow them to start with letters too
// the downside is that there is some ambiguity and parsing gets a little bit more complex
// check for <symbolName> = pattern
StringTokenParser bakParser;
const char* symbolStr;
sint32 symbolLen;
parser.storeParserState(&bakParser);
if (parser.parseSymbolName(symbolStr, symbolLen) && parser.matchWordI("="))
{
// matches pattern: <symbolName> = ...
parser.skipWhitespaces();
parser.trimWhitespaces();
const char* expressionStr = parser.getCurrentPtr();
sint32 expressionLen = parser.getCurrentLen();
// create entry for symbol value assignment
currentGroup->list_patches.emplace_back(new PatchEntryCemuhookSymbolValue(lineNumber, symbolStr, symbolLen, expressionStr, expressionLen));
continue;
}
else
{
LogPatchesSyntaxError(lineNumber, fmt::format("Invalid syntax"));
CancelParsingPatches();
return;
}
}
}
if (currentGroup)
AddPatchGroup(currentGroup);
}
static inline uint32 INVALID_ORIGIN = 0xFFFFFFFF;
bool GraphicPack2::ParseCemuPatchesTxtInternal(MemStreamReader& patchesStream)
{
sint32 lineNumber = 0;
PatchGroup* currentGroup = nullptr;
struct
{
void reset()
{
currentOrigin = INVALID_ORIGIN;
codeCaveOrigin = 0;
}
void setOrigin(uint32 origin)
{
currentOrigin = origin;
}
void setOriginCodeCave()
{
currentOrigin = codeCaveOrigin;
}
bool isValidOrigin()
{
return currentOrigin != INVALID_ORIGIN;
}
void incrementOrigin(uint32 size)
{
currentOrigin += size;
if (currentOrigin <= 32 * 1024 * 1024)
codeCaveOrigin = std::max(codeCaveOrigin, currentOrigin);
}
uint32 currentOrigin{};
uint32 codeCaveOrigin{};
}originInfo;
// labels dont get emitted immediately, instead they are assigned a VA after the next alignment zone
std::vector<PatchEntryLabel*> scheduledLabels;
// this is to prevent code like this from putting alignment bytes after the label. (The label 'sticks' to the data after it)
// .byte 123
// Label:
// BLR
auto flushLabels = [&]()
{
// flush remaining labels
for (auto& itr : scheduledLabels)
{
itr->setAssignedVA(originInfo.currentOrigin);
currentGroup->list_patches.emplace_back(itr);
}
scheduledLabels.clear();
};
while (true)
{
size_t lineLength;
auto lineStr = patchesStream.readLine();
lineNumber++;
if (patchesStream.hasError())
break;
// trim comment
lineLength = GetLengthWithoutComment(lineStr.data(), lineStr.size());
StringTokenParser parser(lineStr.data(), (sint32)lineLength);
// skip whitespaces at the beginning
parser.skipWhitespaces();
// parse line
if (parser.isEndOfString())
continue;
if (parser.compareCharacter(0, '['))
{
// group
parser.skipCharacters(1);
// find end of group name
const char* groupNameStr = parser.getCurrentPtr();
sint32 groupNameLength = parser.skipToCharacter(']');
if (groupNameLength < 0)
{
LogPatchesSyntaxError(lineNumber, "Expected ']'");
CancelParsingPatches();
return false;
}
parser.skipCharacters(1); // skip the ']'
parser.skipWhitespaces();
if (!parser.isEndOfString())
{
LogPatchesSyntaxError(lineNumber, "Unexpected characters after ']'");
CancelParsingPatches();
return false;
}
// begin new group
if (currentGroup)
{
flushLabels();
AddPatchGroup(currentGroup);
}
currentGroup = new PatchGroup(this, groupNameStr, groupNameLength);
// reset origin tracking
originInfo.reset();
continue;
}
else if (parser.matchWordI("moduleMatches"))
{
if (currentGroup == nullptr)
{
LogPatchesSyntaxError(lineNumber, "Specified 'ModuleMatches' outside of a group");
CancelParsingPatches();
return false;
}
if (parser.matchWordI("=") == false)
{
LogPatchesSyntaxError(lineNumber, "Expected '=' after ModuleMatches");
CancelParsingPatches();
return false;
}
// read the checksums
while (true)
{
uint32 checksum = 0;
if (parser.parseU32(checksum) == false)
{
LogPatchesSyntaxError(lineNumber, "Invalid value for ModuleMatches");
CancelParsingPatches();
return false;
}
currentGroup->list_moduleMatches.emplace_back(checksum);
if (parser.matchWordI(",") == false)
break;
}
parser.skipWhitespaces();
if (!parser.isEndOfString())
{
LogPatchesSyntaxError(lineNumber, "Unexpected character");
CancelParsingPatches();
return false;
}
continue;
}
// if a line starts with <hex_address> = then it temporarily overwrites the origin for the current line
uint32 overwriteOrigin = INVALID_ORIGIN;
if (parser.compareCharacter(0, '0') && parser.compareCharacterI(1, 'x'))
{
uint32 patchedAddress;
if (!parser.parseU32(patchedAddress))
{
LogPatchesSyntaxError(lineNumber, "Malformed address");
CancelParsingPatches();
return false;
}
if (parser.matchWordI("=") == false)
{
LogPatchesSyntaxError(lineNumber, "Expected '=' after address");
CancelParsingPatches();
return false;
}
parser.skipWhitespaces();
parser.trimWhitespaces();
overwriteOrigin = patchedAddress;
}
// check for known directives
if (parser.matchWordI(".origin"))
{
// .origin = <origin> directive
if (overwriteOrigin != INVALID_ORIGIN)
{
LogPatchesSyntaxError(lineNumber, fmt::format(".origin directive must appear alone without <address> = prefix."));
CancelParsingPatches();
return false;
}
if (!parser.matchWordI("="))
{
LogPatchesSyntaxError(lineNumber, fmt::format("Missing '=' after .origin"));
CancelParsingPatches();
return false;
}
// parse origin
uint32 originAddress;
if (parser.matchWordI("codecave"))
{
// keyword codecave means we set the origin to the end of the current known codecave size
originInfo.setOriginCodeCave();
}
else if(parser.parseU32(originAddress))
{
// hex address
originInfo.setOrigin(originAddress);
}
else
{
LogPatchesSyntaxError(lineNumber, fmt::format("\'.origin =\' must be followed by the keyword codecave or a valid address"));
CancelParsingPatches();
return false;
}
continue;
}
// next we attempt to parse symbol assignment
// symbols can be labels or variables. The type is determined by what comes after the symbol name
// <symbolName> = <expression> defines a variable
// <symbolName>: defines a label
StringTokenParser bakParser;
const char* symbolStr;
sint32 symbolLen;
parser.storeParserState(&bakParser);
// check for pattern <symbolName>:
if (parser.parseSymbolName(symbolStr, symbolLen) && parser.matchWordI(":"))
{
// label
parser.skipWhitespaces();
if (!parser.isEndOfString())
{
LogPatchesSyntaxError(lineNumber, fmt::format("Unexpected characters after label"));
CancelParsingPatches();
return false;
}
uint32 labelAddress;
if (overwriteOrigin != INVALID_ORIGIN)
labelAddress = overwriteOrigin;
else
{
if (!originInfo.isValidOrigin())
{
LogPatchesSyntaxError(lineNumber, fmt::format("Defined label has no address assigned or there is no active .origin"));
CancelParsingPatches();
return false;
}
labelAddress = originInfo.currentOrigin;
}
if (overwriteOrigin == INVALID_ORIGIN)
{
// if label is part of code flow, delay emitting it until the next data instruction
// this is so we can avoid generating alignment padding, whose size is unknown in advance, between labels and data instructions
scheduledLabels.emplace_back(new PatchEntryLabel(lineNumber, symbolStr, symbolLen));
}
else
{
PatchEntryLabel* patchLabel = new PatchEntryLabel(lineNumber, symbolStr, symbolLen);
patchLabel->setAssignedVA(labelAddress);
currentGroup->list_patches.emplace_back(patchLabel);
}
continue;
}
parser.restoreParserState(&bakParser);
// check for pattern <symbolName> =
if (parser.parseSymbolName(symbolStr, symbolLen) && parser.matchWordI("="))
{
// variable definition
parser.skipWhitespaces();
parser.trimWhitespaces();
const char* expressionStr = parser.getCurrentPtr();
sint32 expressionLen = parser.getCurrentLen();
// create entry for symbol/variable value assignment
currentGroup->list_patches.emplace_back(new PatchEntryVariableValue(lineNumber, symbolStr, symbolLen, PATCHVARTYPE::UINT, expressionStr, expressionLen));
continue;
}
// if all patterns mismatch then we assume it's an assembly instruction
parser.restoreParserState(&bakParser);
std::string instrText(parser.getCurrentPtr(), parser.getCurrentLen());
PPCAssemblerInOut ctx{};
ctx.forceNoAlignment = overwriteOrigin != INVALID_ORIGIN; // dont auto-align when a fixed address is assigned
if (overwriteOrigin != INVALID_ORIGIN)
ctx.virtualAddress = overwriteOrigin;
else if(originInfo.isValidOrigin())
ctx.virtualAddress = originInfo.currentOrigin;
else
{
LogPatchesSyntaxError(lineNumber, fmt::format("Trying to assemble line but no address specified. (Declare .origin or prefix line with <address> = )"));
CancelParsingPatches();
return false;
}
if (!ppcAssembler_assembleSingleInstruction(instrText.c_str(), &ctx))
{
LogPatchesSyntaxError(lineNumber, fmt::format("Error in assembler: {}", ctx.errorMsg));
CancelParsingPatches();
return false;
}
cemu_assert_debug(ctx.alignmentRequirement != 0);
if (overwriteOrigin == INVALID_ORIGIN)
{
originInfo.incrementOrigin((sint32)ctx.alignmentPaddingSize); // alignment padding
originInfo.incrementOrigin((sint32)ctx.outputData.size()); // instruction size
}
// flush labels
for (auto& itr : scheduledLabels)
{
itr->setAssignedVA(ctx.virtualAddressAligned);
currentGroup->list_patches.emplace_back(itr);
}
scheduledLabels.clear();
// append instruction
currentGroup->list_patches.emplace_back(new PatchEntryInstruction(lineNumber, ctx.virtualAddressAligned, { ctx.outputData.data(), ctx.outputData.size() }, ctx.list_relocs));
}
flushLabels();
if (currentGroup)
AddPatchGroup(currentGroup);
return true;
}
| 15,857
|
C++
|
.cpp
| 505
| 27.691089
| 219
| 0.723956
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,166
|
GraphicPack2PatchesApply.cpp
|
cemu-project_Cemu/src/Cafe/GraphicPack/GraphicPack2PatchesApply.cpp
|
#include "Cafe/GraphicPack/GraphicPack2.h"
#include "Common/FileStream.h"
#include "Cemu/PPCAssembler/ppcAssembler.h"
#include "Cafe/OS/RPL/rpl_structs.h"
#include "Cafe/OS/RPL/rpl_symbol_storage.h"
#include "Cafe/HW/Espresso/Recompiler/PPCRecompiler.h"
#include "Cafe/HW/Espresso/Debugger/DebugSymbolStorage.h"
bool _relocateAddress(PatchGroup* group, PatchContext_t* ctx, uint32 addr, uint32& relocatedAddress)
{
if (addr >= 0 && addr <= 1024 * 1024 * 8)
{
// codecave address
relocatedAddress = group->getCodeCaveBase() + addr;
return true;
}
// check if address is within module section
for (sint32 i = 0; i < ctx->matchedModule->rplHeader.sectionTableEntryCount; i++)
{
auto sect = ctx->matchedModule->sectionTablePtr + i;
if (addr >= sect->virtualAddress && addr < (sect->virtualAddress + sect->sectionSize))
{
relocatedAddress = addr - sect->virtualAddress + memory_getVirtualOffsetFromPointer(ctx->matchedModule->sectionAddressTable2[i].ptr);
return true;
}
}
relocatedAddress = 0;
return false;
}
struct
{
bool hasUnknownVariable;
PatchContext_t* activePatchContext;
PatchGroup* currentGroup;
// additional error information tracking
sint32 lineNumber; // line number of the expression being processed, negative if not available
bool captureUnresolvedSymbols;
}resolverState{};
bool GraphicPack2::ResolvePresetConstant(const std::string& varname, double& value) const
{
const auto var = GetPresetVariable(GetActivePresets(), varname);
if (var)
{
value = var->second;
return true;
}
return false;
}
template<typename T>
T _expressionFuncHA(T input)
{
uint32 u32 = (uint32)input;
u32 = (((u32 >> 16) + ((u32 & 0x8000) ? 1 : 0)) & 0xffff);
return (T)u32;
}
template<typename T>
T _expressionFuncHI(T input)
{
uint32 u32 = (uint32)input;
u32 = (u32 >> 16) & 0xffff;
return (T)u32;
}
template<typename T>
T _expressionFuncLO(T input)
{
uint32 u32 = (uint32)input;
u32 &= 0xffff;
return (T)u32;
}
template<typename T>
T _expressionFuncReloc(T input)
{
uint32 addr = (uint32)input;
uint32 relocatedAddress = 0;
if(!_relocateAddress(resolverState.currentGroup, resolverState.activePatchContext, addr, relocatedAddress))
{
resolverState.activePatchContext->errorHandler.printError(resolverState.currentGroup, resolverState.lineNumber, fmt::format("reloc({0:#08x}): Address does not point to a known memory region", addr));
return (T)0;
}
return (T)relocatedAddress;
}
double _cbResolveConstant(std::string_view varname)
{
std::string varnameOnly;
std::string tokenOnly;
// detect suffix
bool hasSuffix = false;
const auto idx = varname.find('@');
if (idx != std::string_view::npos)
{
hasSuffix = true;
varnameOnly = varname.substr(0, idx);
tokenOnly = varname.substr(idx + 1);
}
else
varnameOnly = varname;
double value;
if (varnameOnly.length() >= 1 && varnameOnly[0] == '$')
{
// resolve preset variable
if (!resolverState.activePatchContext->graphicPack->ResolvePresetConstant(varnameOnly, value))
{
resolverState.hasUnknownVariable = true;
if (resolverState.captureUnresolvedSymbols)
resolverState.activePatchContext->unresolvedSymbols.emplace(resolverState.lineNumber, resolverState.currentGroup, varnameOnly);
return 0.0;
}
}
else if (varnameOnly.length() >= 7 && boost::iequals(varnameOnly.substr(0, 7), "import."))
{
// resolve import
std::string importName = varnameOnly.substr(7);
// detect imports
const auto idxDot = importName.find('.');
bool isValidImport = false;
std::string_view importError = "";
if (idxDot != std::string_view::npos)
{
std::string moduleName = importName.substr(0, idxDot);
std::string functionName = importName.substr(idxDot + 1);
uint32 rplHandle = RPLLoader_GetHandleByModuleName(moduleName.c_str());
if (rplHandle == RPL_INVALID_HANDLE)
{
importError = " (module not found)";
}
else
{
MPTR exportResult = RPLLoader_FindModuleOrHLEExport(rplHandle, false, functionName.c_str());
if (exportResult)
{
isValidImport = true;
value = (double)exportResult;
}
else
importError = " (function not found)";
}
}
else
importError = " (invalid import syntax)";
// error output
if (!isValidImport)
{
resolverState.hasUnknownVariable = true;
if (resolverState.captureUnresolvedSymbols)
{
std::string detailedSymbolName;
detailedSymbolName.assign(importName);
detailedSymbolName.append(importError);
resolverState.activePatchContext->unresolvedSymbols.emplace(resolverState.lineNumber, resolverState.currentGroup, detailedSymbolName);
}
return 0.0;
}
}
else
{
// resolve variable
const auto v = resolverState.activePatchContext->map_values.find(varnameOnly);
if (v == resolverState.activePatchContext->map_values.end())
{
resolverState.hasUnknownVariable = true;
if (resolverState.captureUnresolvedSymbols)
resolverState.activePatchContext->unresolvedSymbols.emplace(resolverState.lineNumber, resolverState.currentGroup, varnameOnly);
return 0.0;
}
value = v->second;
}
if (hasSuffix)
{
std::transform(tokenOnly.cbegin(), tokenOnly.cend(), tokenOnly.begin(), tolower);
if (tokenOnly == "ha")
{
value = _expressionFuncHA<double>(value);
}
else if (tokenOnly == "h" || tokenOnly == "hi")
{
value = _expressionFuncHI<double>(value);
}
else if (tokenOnly == "l" || tokenOnly == "lo")
{
value = _expressionFuncLO<double>(value);
}
else
{
// we treat unknown suffixes as unresolveable symbols
resolverState.hasUnknownVariable = true;
if (resolverState.captureUnresolvedSymbols)
{
std::string detailedSymbolName;
detailedSymbolName.assign(varnameOnly);
detailedSymbolName.append("@");
detailedSymbolName.append(tokenOnly);
detailedSymbolName.append(" (invalid suffix)");
resolverState.activePatchContext->unresolvedSymbols.emplace(resolverState.lineNumber, resolverState.currentGroup, detailedSymbolName);
}
return 0.0;
}
}
return value;
}
double _cbResolveFunction(std::string_view funcname, double input)
{
std::string funcnameLC(funcname);
std::transform(funcnameLC.cbegin(), funcnameLC.cend(), funcnameLC.begin(), tolower);
double value = input;
if (funcnameLC == "ha" || funcnameLC == "ha16")
value = _expressionFuncHA<double>(value);
else if (funcnameLC == "hi" || funcnameLC == "hi16")
value = _expressionFuncHI<double>(value);
else if (funcnameLC == "lo" || funcnameLC == "lo16")
value = _expressionFuncLO<double>(value);
else if (funcnameLC == "reloc")
value = _expressionFuncReloc<double>(value);
else
{
// unresolvable function
resolverState.hasUnknownVariable = true;
if (resolverState.captureUnresolvedSymbols)
{
std::string detailedSymbolName;
detailedSymbolName.assign(funcname);
detailedSymbolName.append("() (unknown function)");
resolverState.activePatchContext->unresolvedSymbols.emplace(resolverState.lineNumber, resolverState.currentGroup, detailedSymbolName);
}
return 0.0;
}
return value;
}
template<typename T>
EXPRESSION_RESOLVE_RESULT _resolveExpression(PatchContext_t& ctx, std::string& expressionString, T& result, sint32 associatedLineNumber = -1)
{
resolverState.lineNumber = associatedLineNumber;
ExpressionParser ep;
try
{
// add all the graphic pack constants
ep.AddConstantCallback(_cbResolveConstant);
ep.SetFunctionCallback(_cbResolveFunction);
resolverState.hasUnknownVariable = false;
result = (T)ep.Evaluate(expressionString);
if (resolverState.hasUnknownVariable)
return EXPRESSION_RESOLVE_RESULT::UNKNOWN_VARIABLE;
}
catch (const std::exception&)
{
cemu_assert_debug(false);
ctx.errorHandler.printError(nullptr, -1, fmt::format("Unexpected error in expression \"{}\"", expressionString));
return EXPRESSION_RESOLVE_RESULT::EXPRESSION_ERROR;
}
return EXPRESSION_RESOLVE_RESULT::AVAILABLE;
}
PATCH_RESOLVE_RESULT translateExpressionResult(EXPRESSION_RESOLVE_RESULT expressionResult)
{
if (expressionResult == EXPRESSION_RESOLVE_RESULT::AVAILABLE)
return PATCH_RESOLVE_RESULT::RESOLVED;
else if (expressionResult == EXPRESSION_RESOLVE_RESULT::EXPRESSION_ERROR)
return PATCH_RESOLVE_RESULT::EXPRESSION_ERROR;
else if (expressionResult == EXPRESSION_RESOLVE_RESULT::UNKNOWN_VARIABLE)
return PATCH_RESOLVE_RESULT::UNKNOWN_VARIABLE;
cemu_assert(false);
return PATCH_RESOLVE_RESULT::EXPRESSION_ERROR;
}
PATCH_RESOLVE_RESULT PatchEntryInstruction::resolveReloc(PatchContext_t& ctx, PPCAssemblerReloc* reloc)
{
MPTR finalRelocAddr = m_relocatedAddr + reloc->m_byteOffset;
if (reloc->m_relocType == PPCASM_RELOC::FLOAT)
{
// resolve float expression
float result;
auto r = _resolveExpression<float>(ctx, reloc->m_expression, result, m_lineNumber);
if (r == EXPRESSION_RESOLVE_RESULT::AVAILABLE)
{
cemu_assert((reloc->m_byteOffset + sizeof(betype<float>)) <= m_length);
*(betype<float>*)(m_dataWithRelocs + reloc->m_byteOffset) = result;
DebugSymbolStorage::StoreDataType(finalRelocAddr, DEBUG_SYMBOL_TYPE::FLOAT);
return PATCH_RESOLVE_RESULT::RESOLVED;
}
else
return translateExpressionResult(r);
}
else if (reloc->m_relocType == PPCASM_RELOC::DOUBLE)
{
// resolve double expression
double result;
auto r = _resolveExpression<double>(ctx, reloc->m_expression, result, m_lineNumber);
if (r == EXPRESSION_RESOLVE_RESULT::AVAILABLE)
{
cemu_assert((reloc->m_byteOffset + sizeof(betype<double>)) <= m_length);
*(betype<double>*)(m_dataWithRelocs + reloc->m_byteOffset) = result;
DebugSymbolStorage::StoreDataType(finalRelocAddr, DEBUG_SYMBOL_TYPE::DOUBLE);
return PATCH_RESOLVE_RESULT::RESOLVED;
}
else
return translateExpressionResult(r);
}
else
{
// resolve uint32 expression
uint32 result;
auto r = _resolveExpression<uint32>(ctx, reloc->m_expression, result, m_lineNumber);
if (r != EXPRESSION_RESOLVE_RESULT::AVAILABLE)
return translateExpressionResult(r);
if (reloc->m_relocType == PPCASM_RELOC::U32)
{
cemu_assert((reloc->m_byteOffset + sizeof(betype<uint32>)) <= m_length);
*(betype<uint32>*)(m_dataWithRelocs + reloc->m_byteOffset) = result;
DebugSymbolStorage::StoreDataType(finalRelocAddr, DEBUG_SYMBOL_TYPE::U32);
return PATCH_RESOLVE_RESULT::RESOLVED;
}
else if (reloc->m_relocType == PPCASM_RELOC::U16)
{
cemu_assert((reloc->m_byteOffset + sizeof(betype<uint16>)) <= m_length);
*(betype<uint16>*)(m_dataWithRelocs + reloc->m_byteOffset) = (uint16)result;
DebugSymbolStorage::StoreDataType(finalRelocAddr, DEBUG_SYMBOL_TYPE::U16);
return PATCH_RESOLVE_RESULT::RESOLVED;
}
else if (reloc->m_relocType == PPCASM_RELOC::U8)
{
cemu_assert((reloc->m_byteOffset + sizeof(betype<uint8>)) <= m_length);
*(betype<uint8>*)(m_dataWithRelocs + reloc->m_byteOffset) = (uint8)result;
DebugSymbolStorage::StoreDataType(finalRelocAddr, DEBUG_SYMBOL_TYPE::U8);
return PATCH_RESOLVE_RESULT::RESOLVED;
}
else if (reloc->m_relocType == PPCASM_RELOC::U32_MASKED_IMM)
{
cemu_assert((reloc->m_byteOffset + sizeof(betype<uint32>)) <= m_length);
uint32 opcode = *(betype<uint32>*)(m_dataWithRelocs + reloc->m_byteOffset);
cemu_assert_debug(reloc->m_bitCount != 0);
uint32 mask = 0xFFFFFFFF >> (32 - reloc->m_bitCount);
mask <<= reloc->m_bitOffset;
opcode &= ~mask;
opcode |= ((result << reloc->m_bitOffset) & mask);
*(betype<uint32>*)(m_dataWithRelocs + reloc->m_byteOffset) = opcode;
return PATCH_RESOLVE_RESULT::RESOLVED;
}
else if (reloc->m_relocType == PPCASM_RELOC::BRANCH_S26)
{
cemu_assert((reloc->m_byteOffset + sizeof(betype<uint32>)) <= m_length);
uint32 opcode = *(betype<uint32>*)(m_dataWithRelocs + reloc->m_byteOffset);
if (opcode & 2)
{
// absolute
if (result >= 0x3FFFFFC)
{
cemuLog_log(LogType::Force, "Target \'{}\' for branch at line {} out of range", reloc->m_expression, m_lineNumber);
return PATCH_RESOLVE_RESULT::VALUE_ERROR;
}
opcode &= ~0x3FFFFFC;
opcode |= (result & 0x3FFFFFC);
}
else
{
// relative
uint32 instrAddr = this->getRelocatedAddr() + reloc->m_byteOffset;
if (result < instrAddr)
{
// jump backwards
uint32 jumpB = instrAddr - result;
if (jumpB > 0x1FFFFFF)
{
ctx.errorHandler.printError(nullptr, m_lineNumber, fmt::format("Target \'{0}\' for branch out of range (use MTCTR + BCTR or similar for long distance branches)", reloc->m_expression.c_str()));
return PATCH_RESOLVE_RESULT::VALUE_ERROR;
}
opcode &= ~0x3FFFFFC;
opcode |= ((~jumpB + 1) & 0x3FFFFFC);
}
else
{
// jump forwards
uint32 jumpF = result - instrAddr;
if (jumpF >= 0x1FFFFFF)
{
ctx.errorHandler.printError(nullptr, m_lineNumber, fmt::format("Target \'{0}\' for branch out of range (use MTCTR + BCTR or similar for long distance branches)", reloc->m_expression.c_str()));
return PATCH_RESOLVE_RESULT::VALUE_ERROR;
}
opcode &= ~0x3FFFFFC;
opcode |= (jumpF & 0x3FFFFFC);
}
}
*(betype<uint32>*)(m_dataWithRelocs + reloc->m_byteOffset) = opcode;
return PATCH_RESOLVE_RESULT::RESOLVED;
}
else if (reloc->m_relocType == PPCASM_RELOC::BRANCH_S16)
{
cemu_assert((reloc->m_byteOffset + sizeof(betype<uint32>)) <= m_length);
uint32 opcode = *(betype<uint32>*)(m_dataWithRelocs + reloc->m_byteOffset);
uint32 instrAddr = this->getRelocatedAddr() + reloc->m_byteOffset;
if (result < instrAddr)
{
// jump backwards
uint32 jumpB = instrAddr - result;
if (jumpB > 0x8000)
{
ctx.errorHandler.printError(nullptr, m_lineNumber, fmt::format("Target \'{0}\' for branch out of range (use MTCTR + BCTR or similar for long distance branches)", reloc->m_expression.c_str()));
return PATCH_RESOLVE_RESULT::VALUE_ERROR;
}
opcode &= ~0xFFFC;
opcode |= ((~jumpB + 1) & 0xFFFC);
}
else
{
// jump forwards
uint32 jumpF = result - instrAddr;
if (jumpF >= 0x8000)
{
ctx.errorHandler.printError(nullptr, m_lineNumber, fmt::format("Target \'{0}\' for branch out of range (use MTCTR + BCTR or similar for long distance branches)", reloc->m_expression.c_str()));
return PATCH_RESOLVE_RESULT::VALUE_ERROR;
}
opcode &= ~0xFFFC;
opcode |= (jumpF & 0xFFFC);
}
*(betype<uint32>*)(m_dataWithRelocs + reloc->m_byteOffset) = opcode;
return PATCH_RESOLVE_RESULT::RESOLVED;
}
// *internalCtx.opcode |= (relativeAddr & 0xFFFC);
cemu_assert_debug(false);
}
return PATCH_RESOLVE_RESULT::UNDEFINED_ERROR;
}
PATCH_RESOLVE_RESULT PatchEntryInstruction::resolve(PatchContext_t& ctx)
{
// relocate patch address
if (!m_addrRelocated)
{
if (_relocateAddress(resolverState.currentGroup, &ctx, m_addr, m_relocatedAddr) == false)
{
cemuLog_log(LogType::Force, "Patches: Address 0x{:08x} (line {}) is not within code cave or any module section", this->getAddr(), this->m_lineNumber);
cemu_assert_debug(false);
return PATCH_RESOLVE_RESULT::INVALID_ADDRESS;
}
m_addrRelocated = true;
}
// apply relocations to instruction
for (auto& itr : this->m_relocs)
{
if(itr.isApplied())
continue;
// evaluate expression and apply reloc to internal buffer
auto r = resolveReloc(ctx, &itr);
if (r == PATCH_RESOLVE_RESULT::RESOLVED)
{
itr.setApplied();
continue;
}
return r;
}
return PATCH_RESOLVE_RESULT::RESOLVED;
}
void PatchEntryInstruction::applyPatch()
{
const uint32 addr = getRelocatedAddr();
if (addr == 0)
{
cemu_assert_debug(false);
return;
}
uint8* patchAddr = (uint8*)memory_base + addr;
memcpy(m_dataBackup, patchAddr, m_length);
memcpy(patchAddr, m_dataWithRelocs, m_length);
PPCRecompiler_invalidateRange(addr, addr + m_length);
}
void PatchEntryInstruction::undoPatch()
{
const uint32 addr = getRelocatedAddr();
if (addr == 0)
{
cemu_assert_debug(false);
return;
}
uint8* patchAddr = (uint8*)memory_base + addr;
memcpy(patchAddr, m_dataBackup, m_length);
PPCRecompiler_invalidateRange(addr, addr + m_length);
rplSymbolStorage_removeRange(addr, m_length);
DebugSymbolStorage::ClearRange(addr, m_length);
}
// returns true on success, false if variable with same name already exists
bool registerU32Variable(PatchContext_t& ctx, std::string& name, uint32 value, PatchGroup* associatedPatchGroup, uint32 associatedLineNumber, bool isAddress)
{
cemuLog_log(LogType::Patches, "Resolved symbol {} with value 0x{:08x}", name.c_str(), value);
if (ctx.map_values.find(name) != ctx.map_values.end())
{
return false;
}
ctx.map_values[name] = value;
// keep track of address symbols for the debugger
rplSymbolStorage_store(ctx.graphicPack->GetName().data(), name.data(), value);
return true;
}
PATCH_RESOLVE_RESULT PatchEntryCemuhookSymbolValue::resolve(PatchContext_t& ctx)
{
uint32 addr;
auto r = _resolveExpression<uint32>(ctx, m_expressionString, addr, m_lineNumber);
if (r == EXPRESSION_RESOLVE_RESULT::AVAILABLE)
{
if (_relocateAddress(resolverState.currentGroup, &ctx, addr, m_resolvedValue))
{
m_isResolved = true;
// register variable
if (!registerU32Variable(ctx, m_symbolName, m_resolvedValue, resolverState.currentGroup, getLineNumber(), true))
{
if (resolverState.captureUnresolvedSymbols)
ctx.errorHandler.printError(resolverState.currentGroup, m_lineNumber, fmt::format("Symbol {} is already defined", m_symbolName));
return PATCH_RESOLVE_RESULT::VARIABLE_CONFLICT;
}
return PATCH_RESOLVE_RESULT::RESOLVED;
}
return PATCH_RESOLVE_RESULT::INVALID_ADDRESS;
}
return translateExpressionResult(r);
}
PATCH_RESOLVE_RESULT PatchEntryLabel::resolve(PatchContext_t& ctx)
{
if (_relocateAddress(resolverState.currentGroup, &ctx, m_address, m_relocatedAddress))
{
m_isResolved = true;
// register variable
if (!registerU32Variable(ctx, m_symbolName, m_relocatedAddress, resolverState.currentGroup, getLineNumber(), true))
{
if (resolverState.captureUnresolvedSymbols)
ctx.errorHandler.printError(resolverState.currentGroup, m_lineNumber, fmt::format("Label {} is already defined", m_symbolName));
return PATCH_RESOLVE_RESULT::VARIABLE_CONFLICT;
}
return PATCH_RESOLVE_RESULT::RESOLVED;
}
if(resolverState.captureUnresolvedSymbols)
ctx.errorHandler.printError(resolverState.currentGroup, m_lineNumber, fmt::format("Address {:#08x} of label {} does not point to any module section or code cave", m_address, m_symbolName));
return PATCH_RESOLVE_RESULT::INVALID_ADDRESS;
}
PATCH_RESOLVE_RESULT PatchEntryVariableValue::resolve(PatchContext_t& ctx)
{
uint32 v;
auto r = _resolveExpression<uint32>(ctx, m_expressionString, v, m_lineNumber);
if (r == EXPRESSION_RESOLVE_RESULT::AVAILABLE)
{
// register variable
if (!registerU32Variable(ctx, m_symbolName, v, resolverState.currentGroup, getLineNumber(), false))
{
if (resolverState.captureUnresolvedSymbols)
ctx.errorHandler.printError(resolverState.currentGroup, m_lineNumber, fmt::format("Variable {} is already defined", m_symbolName));
return PATCH_RESOLVE_RESULT::VARIABLE_CONFLICT;
}
return PATCH_RESOLVE_RESULT::RESOLVED;
}
return translateExpressionResult(r);
}
struct UnresolvedPatches_t
{
PatchGroup* patchGroup;
std::vector<PatchEntry*> list_unresolvedPatches;
};
// returns number of resolved entries
bool _resolverPass(PatchContext_t& patchContext, std::vector<UnresolvedPatches_t>& unresolvedPatches, bool captureUnresolvedSymbols = false)
{
resolverState.captureUnresolvedSymbols = captureUnresolvedSymbols;
sint32 numResolvedEntries = 0;
for (auto& unresolvedGroup : unresolvedPatches)
{
resolverState.currentGroup = unresolvedGroup.patchGroup;
auto& list_unresolvedPatches = unresolvedGroup.list_unresolvedPatches;
for (auto it = list_unresolvedPatches.begin(); it != list_unresolvedPatches.end();)
{
auto r = (*it)->resolve(patchContext);
if (r == PATCH_RESOLVE_RESULT::RESOLVED)
{
// remove from list
it = list_unresolvedPatches.erase(it);
numResolvedEntries++;
continue;
}
else if (r == PATCH_RESOLVE_RESULT::UNKNOWN_VARIABLE)
{
// dependency on other not yet resolved entry, continue iterating
it++;
continue;
}
else if (r == PATCH_RESOLVE_RESULT::INVALID_ADDRESS ||
r == PATCH_RESOLVE_RESULT::VARIABLE_CONFLICT)
{
// errors handled and printed inside resolve()
it++;
continue;
}
else
{
// unknown error
patchContext.errorHandler.printError(resolverState.currentGroup, -1, "Internal error");
it++;
}
}
}
return numResolvedEntries;
}
void GraphicPack2::ApplyPatchGroups(std::vector<PatchGroup*>& groups, const RPLModule* rpl)
{
// init context information
PatchContext_t patchContext{};
patchContext.graphicPack = this;
patchContext.matchedModule = rpl;
resolverState.activePatchContext = &patchContext;
// setup error handler
patchContext.errorHandler.setCurrentGraphicPack(this);
patchContext.errorHandler.setStage(PatchErrorHandler::STAGE::APPLY);
// no group can be applied more than once
for (auto patchGroup : groups)
{
if (patchGroup->isApplied())
{
patchContext.errorHandler.printError(patchGroup, -1, "Group already applied to a different module.");
return;
}
}
// allocate code cave for every group
for (auto patchGroup : groups)
{
if (patchGroup->codeCaveSize > 0)
{
auto codeCaveMem = RPLLoader_AllocateCodeCaveMem(256, patchGroup->codeCaveSize);
cemuLog_log(LogType::Force, "Applying patch group \'{}\' (Codecave: {:08x}-{:08x})", patchGroup->name, codeCaveMem.GetMPTR(), codeCaveMem.GetMPTR() + patchGroup->codeCaveSize);
patchGroup->codeCaveMem = codeCaveMem;
}
else
{
cemuLog_log(LogType::Force, "Applying patch group \'{}\'", patchGroup->name);
patchGroup->codeCaveMem = nullptr;
}
}
// resolve the patch entries
// this means:
// - resolving the expressions for variables and registering them
// - calculating relocated addresses
// - applying relocations to temporary patch buffer
// multiple passes may be necessary since forward and backward references are allowed as well as references across group boundaries
// create a copy of all the patch references and keep the group association intact
std::vector<UnresolvedPatches_t> unresolvedPatches;
unresolvedPatches.resize(groups.size());
for (size_t i = 0; i < groups.size(); i++)
{
unresolvedPatches[i].patchGroup = groups[i];
unresolvedPatches[i].list_unresolvedPatches = groups[i]->list_patches;
}
auto isUnresolvedPatchesEmpty = [&unresolvedPatches]()
{
for (auto& itr : unresolvedPatches)
if (!itr.list_unresolvedPatches.empty())
return false;
return true;
};
// resolve and relocate
for (sint32 pass = 0; pass < 30; pass++)
{
bool isLastPass = (pass == 29);
sint32 numResolvedEntries = _resolverPass(patchContext, unresolvedPatches, false);
if (isUnresolvedPatchesEmpty())
break;
if (numResolvedEntries == 0 || isLastPass)
{
// stuck due to reference to undefined variable or unresolvable cross-references
// iterate all remaining expressions and output them to log
// execute another resolver pass but capture all the unresolved variables this time
patchContext.unresolvedSymbols.clear();
_resolverPass(patchContext, unresolvedPatches, true);
// generate messages
if(isLastPass)
patchContext.errorHandler.printError(nullptr, -1, "Some symbols could not be resolved because the dependency chain is too deep");
for (auto& itr : patchContext.unresolvedSymbols)
patchContext.errorHandler.printError(itr.patchGroup, itr.lineNumber, fmt::format("Unresolved symbol: {}", itr.symbolName));
patchContext.errorHandler.showStageErrorMessageBox();
return;
}
}
if (!isUnresolvedPatchesEmpty() || patchContext.errorHandler.hasError())
{
patchContext.errorHandler.showStageErrorMessageBox();
return;
}
// apply relocated patches
for (auto patchGroup : groups)
{
for (auto& patch : patchGroup->list_patches)
{
PatchEntryInstruction* patchInstruction = dynamic_cast<PatchEntryInstruction*>(patch);
if (patchInstruction == nullptr)
continue;
patchInstruction->applyPatch();
}
}
// mark groups as applied
for (auto patchGroup : groups)
patchGroup->setApplied();
}
void GraphicPack2::UndoPatchGroups(std::vector<PatchGroup*>& groups, const RPLModule* rpl)
{
// restore original data
for (auto patchGroup : groups)
{
if (!patchGroup->isApplied())
continue;
for (auto& patch : patchGroup->list_patches)
{
PatchEntryInstruction* patchInstruction = dynamic_cast<PatchEntryInstruction*>(patch);
if (patchInstruction == nullptr)
continue;
patchInstruction->undoPatch();
}
}
// mark groups as not applied
for (auto patchGroup : groups)
patchGroup->resetApplied();
}
void GraphicPack2::NotifyModuleLoaded(const RPLModule* rpl)
{
cemuLog_log(LogType::Force, "Loaded module \'{}\' with checksum 0x{:08x}", rpl->moduleName2, rpl->patchCRC);
std::lock_guard<std::recursive_mutex> lock(mtx_patches);
list_modules.emplace_back(rpl);
// todo - iterate all active graphic packs and apply any matching patch groups
}
void GraphicPack2::NotifyModuleUnloaded(const RPLModule* rpl)
{
std::lock_guard<std::recursive_mutex> lock(mtx_patches);
list_modules.erase(std::remove(list_modules.begin(), list_modules.end(), rpl), list_modules.end());
}
| 25,267
|
C++
|
.cpp
| 719
| 32.114047
| 201
| 0.738598
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,167
|
GraphicPack2.cpp
|
cemu-project_Cemu/src/Cafe/GraphicPack/GraphicPack2.cpp
|
#include "Cafe/GraphicPack/GraphicPack2.h"
#include "config/CemuConfig.h"
#include "config/ActiveSettings.h"
#include "openssl/sha.h"
#include "Cafe/HW/Latte/Renderer/RendererOuputShader.h"
#include "Cafe/Filesystem/fsc.h"
#include "boost/algorithm/string.hpp"
#include "util/helpers/MapAdaptor.h"
#include "util/helpers/StringParser.h"
#include "Cafe/HW/Latte/Core/LatteTiming.h"
#include "util/IniParser/IniParser.h"
#include "util/helpers/StringHelpers.h"
#include "Cafe/CafeSystem.h"
#include <cinttypes>
std::vector<GraphicPackPtr> GraphicPack2::s_graphic_packs;
std::vector<GraphicPackPtr> GraphicPack2::s_active_graphic_packs;
std::atomic_bool GraphicPack2::s_isReady;
#define GP_LEGACY_VERSION (2)
void GraphicPack2::LoadGraphicPack(fs::path graphicPackPath)
{
fs::path rulesPath = graphicPackPath;
rulesPath.append("rules.txt");
std::unique_ptr<FileStream> fs_rules(FileStream::openFile2(rulesPath));
if (!fs_rules)
return;
std::vector<uint8> rulesData;
fs_rules->extract(rulesData);
IniParser iniParser(rulesData, _pathToUtf8(rulesPath));
if (!iniParser.NextSection())
{
cemuLog_log(LogType::Force, "{}: Does not contain any sections", _pathToUtf8(rulesPath));
return;
}
if (!boost::iequals(iniParser.GetCurrentSectionName(), "Definition"))
{
cemuLog_log(LogType::Force, "{}: [Definition] must be the first section", _pathToUtf8(rulesPath));
return;
}
auto option_version = iniParser.FindOption("version");
if (option_version)
{
sint32 versionNum = -1;
auto [ptr, ec] = std::from_chars(option_version->data(), option_version->data() + option_version->size(), versionNum);
if (ec != std::errc{})
{
cemuLog_log(LogType::Force, "{}: Unable to parse version", _pathToUtf8(rulesPath));
return;
}
if (versionNum > GP_LEGACY_VERSION)
{
GraphicPack2::LoadGraphicPack(rulesPath, iniParser);
return;
}
}
cemuLog_log(LogType::Force, "{}: Outdated graphic pack", _pathToUtf8(rulesPath));
}
void GraphicPack2::LoadAll()
{
std::error_code ec;
fs::path basePath = ActiveSettings::GetUserDataPath("graphicPacks");
for (fs::recursive_directory_iterator it(basePath, ec); it != end(it); ++it)
{
if (!it->is_directory(ec))
continue;
fs::path gfxPackPath = it->path();
if (fs::exists(gfxPackPath / "rules.txt", ec))
{
LoadGraphicPack(gfxPackPath);
it.disable_recursion_pending(); // dont recurse deeper in a gfx pack directory
continue;
}
}
}
bool GraphicPack2::LoadGraphicPack(const fs::path& rulesPath, IniParser& rules)
{
try
{
auto gp = std::make_shared<GraphicPack2>(rulesPath, rules);
// check if enabled and preset set
const auto& config_entries = g_config.data().graphic_pack_entries;
// legacy absolute path checking for not breaking compatibility
auto file = gp->GetRulesPath();
auto it = config_entries.find(file.lexically_normal());
if (it == config_entries.cend())
{
// check for relative path
it = config_entries.find(_utf8ToPath(gp->GetNormalizedPathString()));
}
if (it != config_entries.cend())
{
bool enabled = true;
for (auto& kv : it->second)
{
if (boost::iequals(kv.first, "_disabled"))
{
enabled = false;
continue;
}
gp->SetActivePreset(kv.first, kv.second, false);
}
gp->SetEnabled(enabled);
}
gp->UpdatePresetVisibility();
gp->ValidatePresetSelections();
s_graphic_packs.emplace_back(gp);
return true;
}
catch (const std::exception&)
{
return false;
}
}
bool GraphicPack2::ActivateGraphicPack(const std::shared_ptr<GraphicPack2>& graphic_pack)
{
if (graphic_pack->Activate())
{
s_active_graphic_packs.push_back(graphic_pack);
return true;
}
return false;
}
bool GraphicPack2::DeactivateGraphicPack(const std::shared_ptr<GraphicPack2>& graphic_pack)
{
if (!graphic_pack->IsActivated())
return false;
const auto it = std::find_if(s_active_graphic_packs.begin(), s_active_graphic_packs.end(),
[graphic_pack](const GraphicPackPtr& gp)
{
return gp->GetNormalizedPathString() == graphic_pack->GetNormalizedPathString();
}
);
if (it == s_active_graphic_packs.end())
return false;
graphic_pack->Deactivate();
s_active_graphic_packs.erase(it);
return true;
}
void GraphicPack2::ActivateForCurrentTitle()
{
uint64 titleId = CafeSystem::GetForegroundTitleId();
// activate graphic packs
for (const auto& gp : GraphicPack2::GetGraphicPacks())
{
if (!gp->IsEnabled())
continue;
if (!gp->ContainsTitleId(titleId))
continue;
if (GraphicPack2::ActivateGraphicPack(gp))
{
if (gp->GetPresets().empty())
{
cemuLog_log(LogType::Force, "Activate graphic pack: {}", gp->GetVirtualPath());
}
else
{
std::string logLine;
logLine.assign(fmt::format("Activate graphic pack: {} [Presets: ", gp->GetVirtualPath()));
bool isFirst = true;
for (auto& itr : gp->GetPresets())
{
if (!itr->active)
continue;
if (isFirst)
isFirst = false;
else
logLine.append(",");
logLine.append(itr->name);
}
logLine.append("]");
cemuLog_log(LogType::Force, logLine);
}
}
}
s_isReady = true;
}
void GraphicPack2::Reset()
{
s_active_graphic_packs.clear();
s_isReady = false;
}
void GraphicPack2::ClearGraphicPacks()
{
s_graphic_packs.clear();
s_active_graphic_packs.clear();
}
void GraphicPack2::WaitUntilReady()
{
while (!s_isReady)
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
std::unordered_map<std::string, GraphicPack2::PresetVar> GraphicPack2::ParsePresetVars(IniParser& rules) const
{
ExpressionParser parser;
std::unordered_map<std::string, PresetVar> vars;
for(auto& itr : rules.GetAllOptions())
{
auto option_name = itr.first;
auto option_value = itr.second;
if (option_name.empty() || option_name[0] != '$')
continue;
VarType type = kDouble;
std::string name(option_name);
const auto index = name.find(':');
if(index != std::string::npos)
{
auto type_name = name.substr(index + 1);
name = name.substr(0, index);
trim(name);
trim(type_name);
if (type_name == "double")
type = kDouble;
else if (type_name == "int")
type = kInt;
}
const double value = parser.Evaluate(option_value);
vars.try_emplace(name, std::make_pair(type, value));
parser.AddConstant(name, value);
}
return vars;
}
GraphicPack2::GraphicPack2(fs::path rulesPath, IniParser& rules)
: m_rulesPath(std::move(rulesPath))
{
// we're already in [Definition]
auto option_version = rules.FindOption("version");
if (!option_version)
throw std::exception();
m_version = StringHelpers::ToInt(*option_version, -1);
if (m_version < 0)
{
cemuLog_log(LogType::Force, "{}: Invalid version", _pathToUtf8(m_rulesPath));
throw std::exception();
}
auto option_rendererFilter = rules.FindOption("rendererFilter");
if (option_rendererFilter)
{
if (boost::iequals(*option_rendererFilter, "vulkan"))
m_renderer_api = RendererAPI::Vulkan;
else if (boost::iequals(*option_rendererFilter, "opengl"))
m_renderer_api = RendererAPI::OpenGL;
else
cemuLog_log(LogType::Force, "Unknown value '{}' for rendererFilter option", *option_rendererFilter);
}
auto option_defaultEnabled = rules.FindOption("default");
if(option_defaultEnabled)
{
m_default_enabled = boost::iequals(*option_defaultEnabled, "true") || boost::iequals(*option_defaultEnabled, "1");
m_enabled = m_default_enabled;
}
auto option_allowRendertargetSizeOptimization = rules.FindOption("colorbufferOptimizationAware");
if (option_allowRendertargetSizeOptimization)
m_allowRendertargetSizeOptimization = boost::iequals(*option_allowRendertargetSizeOptimization, "true") || boost::iequals(*option_allowRendertargetSizeOptimization, "1");
auto option_vendorFilter = rules.FindOption("vendorFilter");
if (option_vendorFilter)
{
if (boost::iequals(*option_vendorFilter, "amd"))
m_gfx_vendor = GfxVendor::AMD;
else if (boost::iequals(*option_vendorFilter, "intel"))
m_gfx_vendor = GfxVendor::Intel;
else if (boost::iequals(*option_vendorFilter, "mesa"))
m_gfx_vendor = GfxVendor::Mesa;
else if (boost::iequals(*option_vendorFilter, "nvidia"))
m_gfx_vendor = GfxVendor::Nvidia;
else if (boost::iequals(*option_vendorFilter, "apple"))
m_gfx_vendor = GfxVendor::Apple;
else
cemuLog_log(LogType::Force, "Unknown value '{}' for vendorFilter", *option_vendorFilter);
}
auto option_path = rules.FindOption("path");
if (!option_path)
{
auto gp_name_log = rules.FindOption("name");
cemuLog_log(LogType::Force, "[Definition] section from '{}' graphic pack must contain option: path", gp_name_log.has_value() ? *gp_name_log : "Unknown");
throw std::exception();
}
m_virtualPath = *option_path;
auto option_gp_name = rules.FindOption("name");
if (option_gp_name)
m_name = *option_gp_name;
auto option_description = rules.FindOption("description");
if (option_description)
{
m_description = *option_description;
std::replace(m_description.begin(), m_description.end(), '|', '\n');
}
m_title_ids = ParseTitleIds(rules, "titleIds");
if(m_title_ids.empty())
throw std::exception();
auto option_fsPriority = rules.FindOption("fsPriority");
if (option_fsPriority)
{
std::string tmp(*option_fsPriority);
m_fs_priority = std::stoi(tmp);
}
// load presets
while (rules.NextSection())
{
auto currentSectionName = rules.GetCurrentSectionName();
if (boost::iequals(currentSectionName, "Default"))
{
m_preset_vars = ParsePresetVars(rules);
}
else if (boost::iequals(currentSectionName, "Preset"))
{
const auto preset_name = rules.FindOption("name");
if (!preset_name)
{
cemuLog_log(LogType::Force, "Graphic pack \"{}\": Preset in line {} skipped because it has no name option defined", m_name, rules.GetCurrentSectionLineNumber());
continue;
}
const auto category = rules.FindOption("category");
const auto condition = rules.FindOption("condition");
const auto default_selected = rules.FindOption("default");
try
{
const auto vars = ParsePresetVars(rules);
PresetPtr preset;
if (category && condition)
preset = std::make_shared<Preset>(*category, *preset_name, *condition, vars);
else if (category)
preset = std::make_shared<Preset>(*category, *preset_name, vars);
else
preset = std::make_shared<Preset>(*preset_name, vars);
if (default_selected)
preset->is_default = StringHelpers::ToInt(*default_selected) != 0;
m_presets.emplace_back(preset);
}
catch (const std::exception & ex)
{
cemuLog_log(LogType::Force, "Graphic pack \"{}\": Can't parse preset \"{}\": {}", m_name, *preset_name, ex.what());
}
}
else if (boost::iequals(currentSectionName, "RAM"))
{
for (uint32 i = 0; i < 32; i++)
{
char optionNameBuf[64];
*fmt::format_to(optionNameBuf, "mapping{}", i) = '\0';
const auto mappingOption = rules.FindOption(optionNameBuf);
if (mappingOption)
{
if (m_version <= 5)
{
cemuLog_log(LogType::Force, "Graphic pack \"{}\": [RAM] options are only available for graphic pack version 6 or higher", m_name, optionNameBuf);
throw std::exception();
}
StringTokenParser parser(*mappingOption);
uint32 addrStart = 0, addrEnd = 0;
if (parser.parseU32(addrStart) && parser.matchWordI("-") && parser.parseU32(addrEnd) && parser.isEndOfString())
{
if (addrEnd <= addrStart)
{
cemuLog_log(LogType::Force, "Graphic pack \"{}\": start address (0x{:08x}) must be greater than end address (0x{:08x}) for {}", m_name, addrStart, addrEnd, optionNameBuf);
throw std::exception();
}
else if ((addrStart & 0xFFF) != 0 || (addrEnd & 0xFFF) != 0)
{
cemuLog_log(LogType::Force, "Graphic pack \"{}\": addresses for %s are not aligned to 0x1000", m_name, optionNameBuf);
throw std::exception();
}
else
{
m_ramMappings.emplace_back(addrStart, addrEnd);
}
}
else
{
cemuLog_log(LogType::Force, "Graphic pack \"{}\": has invalid syntax for option {}", m_name, optionNameBuf);
throw std::exception();
}
}
}
}
}
if (m_version >= 5)
{
// store by category
std::unordered_map<std::string, std::vector<PresetPtr>> tmp_map;
// all vars must be defined in the default preset vars before
for (const auto& entry : m_presets)
{
tmp_map[entry->category].emplace_back(entry);
for (auto& kv : entry->variables)
{
const auto it = m_preset_vars.find(kv.first);
if (it == m_preset_vars.cend())
{
cemuLog_log(LogType::Force, "Graphic pack: \"{}\" contains preset variables which are not defined in the default section", m_name);
throw std::exception();
}
// overwrite var type with default var type
kv.second.first = it->second.first;
}
}
// have first entry be default active for every category if no default= is set
for(auto entry : get_values(tmp_map))
{
if (!entry.empty())
{
const auto it = std::find_if(entry.cbegin(), entry.cend(), [](const PresetPtr& preset) { return preset->is_default; });
if (it != entry.cend())
(*it)->active = true;
else
(*entry.begin())->active = true;
}
}
}
else
{
// verify preset data to contain the same keys
std::unordered_map<std::string, std::vector<PresetPtr>> tmp_map;
for (const auto& entry : m_presets)
tmp_map[entry->category].emplace_back(entry);
for (const auto& kv : tmp_map)
{
bool has_default = false;
for (size_t i = 0; i + 1 < kv.second.size(); ++i)
{
auto& p1 = kv.second[i];
auto& p2 = kv.second[i + 1];
if (p1->variables.size() != p2->variables.size())
{
cemuLog_log(LogType::Force, "Graphic pack: \"{}\" contains inconsistent preset variables", m_name);
throw std::exception();
}
std::set<std::string> keys1(get_keys(p1->variables).begin(), get_keys(p1->variables).end());
std::set<std::string> keys2(get_keys(p2->variables).begin(), get_keys(p2->variables).end());
if (keys1 != keys2)
{
cemuLog_log(LogType::Force, "Graphic pack: \"{}\" contains inconsistent preset variables", m_name);
throw std::exception();
}
if(p1->is_default)
{
if(has_default)
cemuLog_log(LogType::Force, "Graphic pack: \"{}\" has more than one preset with the default key set for the same category \"{}\"", m_name, p1->name);
p1->active = true;
has_default = true;
}
}
// have first entry by default active if no default is set
if (!has_default)
kv.second[0]->active = true;
}
}
}
// returns true if enabling, disabling (changeEnableState) or changing presets (changePreset) for the graphic pack requires restarting if the game is already running
bool GraphicPack2::RequiresRestart(bool changeEnableState, bool changePreset)
{
if (!GetTextureRules().empty())
return true;
return false;
}
bool GraphicPack2::Reload()
{
Deactivate();
return Activate();
}
std::string GraphicPack2::GetNormalizedPathString() const
{
return _pathToUtf8(MakeRelativePath(ActiveSettings::GetUserDataPath(), GetRulesPath()).lexically_normal());
}
bool GraphicPack2::ContainsTitleId(uint64_t title_id) const
{
const auto it = std::find_if(m_title_ids.begin(), m_title_ids.end(), [title_id](uint64 id) { return id == title_id; });
return it != m_title_ids.end();
}
bool GraphicPack2::HasActivePreset() const
{
return std::any_of(m_presets.cbegin(), m_presets.cend(), [](const PresetPtr& preset)
{
return preset->active;
});
}
std::string GraphicPack2::GetActivePreset(std::string_view category) const
{
const auto it = std::find_if(m_presets.cbegin(), m_presets.cend(), [category](const PresetPtr& preset)
{
return preset->active && preset->category == category;
});
return it != m_presets.cend() ? (*it)->name : std::string{ "" };
}
void GraphicPack2::UpdatePresetVisibility()
{
// update visiblity of each preset
std::for_each(m_presets.begin(), m_presets.end(), [this](PresetPtr& p)
{
p->visible = m_version >= 5 ? IsPresetVisible(p) : true;
});
}
void GraphicPack2::ValidatePresetSelections()
{
if (m_version < 5)
return; // only applies to new categorized presets
// if any preset is changed then other categories might be affected indirectly
//
// example: selecting the aspect ratio in a resolution graphic pack would change the available presets in the resolution category
// how to handle: select the first available resolution (or the one marked as default)
//
// example: a preset category might be hidden entirely (e.g. due to a separate advanced options dropdown)
// how to handle: leave the previously selected preset
//
// the logic is therefore as follows:
// if there is a preset category with at least 1 visible preset entry then make sure one of those is actually selected
// for completely hidden preset categories we leave the selection as-is
std::vector<std::string> order;
std::unordered_map<std::string, std::vector<GraphicPack2::PresetPtr>> categorizedPresets = GraphicPack2::GetCategorizedPresets(order);
bool changedPresets = false;
for (auto& categoryItr : categorizedPresets)
{
// get selection of this category
size_t numVisiblePresets = 0;
GraphicPack2::PresetPtr defaultSelection = nullptr;
GraphicPack2::PresetPtr selectedPreset = nullptr;
for (auto& presetItr : categoryItr.second)
{
if (presetItr->visible)
{
numVisiblePresets++;
if (!defaultSelection || presetItr->is_default) // the preset marked as default becomes the default selection, otherwise pick first visible one
defaultSelection = presetItr;
}
if (presetItr->active)
{
if (selectedPreset)
{
// multiple selections inside the same group are invalid
presetItr->active = false;
changedPresets = true;
}
else
selectedPreset = presetItr;
}
}
if (numVisiblePresets == 0)
continue; // do not touch selection
if (!selectedPreset)
{
// no selection at all
if (defaultSelection)
{
selectedPreset = defaultSelection;
selectedPreset->active = true;
}
continue;
}
// if the currently selected preset is invisible, update it to the preferred visible selection
if (!selectedPreset->visible)
{
selectedPreset->active = false;
defaultSelection->active = true;
changedPresets = true;
}
}
if (changedPresets)
UpdatePresetVisibility();
}
bool GraphicPack2::SetActivePreset(std::string_view category, std::string_view name, bool update_visibility)
{
// disable currently active preset
std::for_each(m_presets.begin(), m_presets.end(), [category](PresetPtr& p)
{
if(p->category == category)
p->active = false;
});
if (name.empty())
return true;
// enable new preset
const auto it = std::find_if(m_presets.cbegin(), m_presets.cend(), [category, name](const PresetPtr& preset)
{
return preset->category == category && preset->name == name;
});
bool result;
if (it != m_presets.cend())
{
(*it)->active = true;
cemu_assert_debug(std::count_if(m_presets.cbegin(), m_presets.cend(), [category](const PresetPtr& p) { return p->category == category && p->active; }) == 1);
result = true;
}
else
result = false;
if (update_visibility)
{
UpdatePresetVisibility();
ValidatePresetSelections();
}
return result;
}
void GraphicPack2::LoadShaders()
{
fs::path path = GetRulesPath();
for (auto& it : fs::directory_iterator(path.remove_filename()))
{
if (!is_regular_file(it))
continue;
try
{
const auto& p = it.path();
auto filename = p.filename().wstring();
uint64 shader_base_hash = 0;
uint64 shader_aux_hash = 0;
wchar_t shader_type[256]{};
if (filename.size() < 256 && swscanf(filename.c_str(), L"%" SCNx64 "_%" SCNx64 "_%ls", &shader_base_hash, &shader_aux_hash, shader_type) == 3)
{
if (shader_type[0] == 'p' && shader_type[1] == 's')
m_custom_shaders.emplace_back(LoadShader(p, shader_base_hash, shader_aux_hash, GP_SHADER_TYPE::PIXEL));
else if (shader_type[0] == 'v' && shader_type[1] == 's')
m_custom_shaders.emplace_back(LoadShader(p, shader_base_hash, shader_aux_hash, GP_SHADER_TYPE::VERTEX));
else if (shader_type[0] == 'g' && shader_type[1] == 's')
m_custom_shaders.emplace_back(LoadShader(p, shader_base_hash, shader_aux_hash, GP_SHADER_TYPE::GEOMETRY));
}
else if (filename == L"output.glsl")
{
std::ifstream file(p);
if (!file.is_open())
throw std::runtime_error(fmt::format("can't open graphic pack file: {}", _pathToUtf8(p.filename())));
file.seekg(0, std::ios::end);
m_output_shader_source.reserve(file.tellg());
file.seekg(0, std::ios::beg);
m_output_shader_source.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
ApplyShaderPresets(m_output_shader_source);
}
else if (filename == L"upscaling.glsl")
{
std::ifstream file(p);
if (!file.is_open())
throw std::runtime_error(fmt::format("can't open graphic pack file: {}", _pathToUtf8(p.filename())));
file.seekg(0, std::ios::end);
m_upscaling_shader_source.reserve(file.tellg());
file.seekg(0, std::ios::beg);
m_upscaling_shader_source.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
ApplyShaderPresets(m_upscaling_shader_source);
}
else if (filename == L"downscaling.glsl")
{
std::ifstream file(p);
if (!file.is_open())
throw std::runtime_error(fmt::format("can't open graphic pack file: {}", _pathToUtf8(p.filename())));
file.seekg(0, std::ios::end);
m_downscaling_shader_source.reserve(file.tellg());
file.seekg(0, std::ios::beg);
m_downscaling_shader_source.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
ApplyShaderPresets(m_downscaling_shader_source);
}
}
catch (const std::exception& ex)
{
cemuLog_log(LogType::Force, "graphicPack: error while loading custom shader: {}", ex.what());
}
}
}
bool GraphicPack2::SetActivePreset(std::string_view name)
{
return SetActivePreset("", name);
}
bool GraphicPack2::IsPresetVisible(const PresetPtr& preset) const
{
if (preset->condition.empty())
return true;
try
{
TExpressionParser<int> p;
FillPresetConstants(p);
return p.Evaluate(preset->condition) != 0;
}
catch (const std::exception& ex)
{
cemuLog_log(LogType::Force, "error when trying to check visiblity of preset: {}", ex.what());
return false;
}
}
std::optional<GraphicPack2::PresetVar> GraphicPack2::GetPresetVariable(const std::vector<PresetPtr>& presets, std::string_view var_name) const
{
// no priority and visibility filter
if(m_version < 5)
{
for (const auto& preset : presets)
{
const auto it = std::find_if(preset->variables.cbegin(), preset->variables.cend(), [&var_name](auto p) { return p.first == var_name; });
if (it != preset->variables.cend())
return it->second;
}
return {};
}
// visible > none visible > default
for (const auto& preset : presets)
{
if (preset->visible)
{
const auto it = std::find_if(preset->variables.cbegin(), preset->variables.cend(), [&var_name](auto p) { return p.first == var_name; });
if (it != preset->variables.cend())
return it->second;
}
}
for (const auto& preset : presets)
{
if (!preset->visible)
{
const auto it = std::find_if(preset->variables.cbegin(), preset->variables.cend(), [&var_name](auto p) { return p.first == var_name; });
if (it != preset->variables.cend())
return it->second;
}
}
const auto it = std::find_if(m_preset_vars.cbegin(), m_preset_vars.cend(), [&var_name](auto p) { return p.first == var_name; });
if (it != m_preset_vars.cend())
{
return it->second;
}
return {};
}
void GraphicPack2::AddConstantsForCurrentPreset(ExpressionParser& ep)
{
if (m_version < 5)
{
for (const auto& preset : GetActivePresets())
{
for (auto& v : preset->variables)
{
ep.AddConstant(v.first, v.second.second);
}
}
}
else
{
FillPresetConstants(ep);
}
}
void GraphicPack2::_iterateReplacedFiles(const fs::path& currentPath, bool isAOC)
{
uint64 currentTitleId = CafeSystem::GetForegroundTitleId();
uint64 aocTitleId = (currentTitleId & 0xFFFFFFFFull) | 0x0005000c00000000ull;
for (auto& it : fs::recursive_directory_iterator(currentPath))
{
if (fs::is_regular_file(it))
{
fs::path virtualMountPath = fs::relative(it.path(), currentPath);
if (isAOC)
{
virtualMountPath = fs::path(fmt::format("/vol/aoc{:016x}/", aocTitleId)) / virtualMountPath;
}
else
{
virtualMountPath = fs::path("vol/content/") / virtualMountPath;
}
fscDeviceRedirect_add(virtualMountPath.generic_string(), it.file_size(), it.path().generic_string(), m_fs_priority);
}
}
}
void GraphicPack2::LoadReplacedFiles()
{
if (m_patchedFilesLoaded)
return;
m_patchedFilesLoaded = true;
fs::path gfxPackPath = GetRulesPath();
gfxPackPath = gfxPackPath.remove_filename();
// /content/
fs::path contentPath(gfxPackPath);
contentPath.append("content");
std::error_code ec;
if (fs::exists(contentPath, ec))
{
// setup redirections
fscDeviceRedirect_map();
_iterateReplacedFiles(contentPath, false);
}
// /aoc/
fs::path aocPath(gfxPackPath);
aocPath.append("aoc");
if (fs::exists(aocPath, ec))
{
uint64 aocTitleId = CafeSystem::GetForegroundTitleId();
aocTitleId = aocTitleId & 0xFFFFFFFFULL;
aocTitleId |= 0x0005000c00000000ULL;
// setup redirections
fscDeviceRedirect_map();
_iterateReplacedFiles(aocPath, true);
}
}
bool GraphicPack2::Activate()
{
if (m_activated)
return true;
// check if gp should be loaded
if (m_renderer_api.has_value() && m_renderer_api.value() != g_renderer->GetType())
return false;
if (m_gfx_vendor.has_value())
{
auto vendor = g_renderer->GetVendor();
if (m_gfx_vendor.value() != vendor)
return false;
}
FileStream* fs_rules = FileStream::openFile2(m_rulesPath);
if (!fs_rules)
return false;
std::vector<uint8> rulesData;
fs_rules->extract(rulesData);
delete fs_rules;
IniParser rules({ (char*)rulesData.data(), rulesData.size()}, GetNormalizedPathString());
// load rules
try
{
ExpressionParser parser;
AddConstantsForCurrentPreset(parser);
while (rules.NextSection())
{
//const char* category_name = sPref_currentCategoryName(rules);
std::string_view category_name = rules.GetCurrentSectionName();
if (boost::iequals(category_name, "TextureRedefine"))
{
TextureRule rule{};
ParseRule(parser, rules, "width", &rule.filter_settings.width);
ParseRule(parser, rules, "height", &rule.filter_settings.height);
ParseRule(parser, rules, "depth", &rule.filter_settings.depth);
bool inMem1 = false;
if (ParseRule(parser, rules, "inMEM1", &inMem1))
rule.filter_settings.inMEM1 = inMem1 ? TextureRule::FILTER_SETTINGS::MEM1_FILTER::INSIDE : TextureRule::FILTER_SETTINGS::MEM1_FILTER::OUTSIDE;
rule.filter_settings.format_whitelist = ParseList<sint32>(parser, rules, "formats");
rule.filter_settings.format_blacklist = ParseList<sint32>(parser, rules, "formatsExcluded");
rule.filter_settings.tilemode_whitelist = ParseList<sint32>(parser, rules, "tilemodes");
rule.filter_settings.tilemode_blacklist = ParseList<sint32>(parser, rules, "tilemodesExcluded");
ParseRule(parser, rules, "overwriteWidth", &rule.overwrite_settings.width);
ParseRule(parser, rules, "overwriteHeight", &rule.overwrite_settings.height);
ParseRule(parser, rules, "overwriteDepth", &rule.overwrite_settings.depth);
ParseRule(parser, rules, "overwriteFormat", &rule.overwrite_settings.format);
float lod_bias;
if(ParseRule(parser, rules, "overwriteLodBias", &lod_bias))
rule.overwrite_settings.lod_bias = (sint32)(lod_bias * 64.0f);
if(ParseRule(parser, rules, "overwriteRelativeLodBias", &lod_bias))
rule.overwrite_settings.relative_lod_bias = (sint32)(lod_bias * 64.0f);
sint32 anisotropyValue;
if (ParseRule(parser, rules, "overwriteAnisotropy", &anisotropyValue))
{
if (anisotropyValue == 1)
rule.overwrite_settings.anistropic_value = 0;
else if (anisotropyValue == 2)
rule.overwrite_settings.anistropic_value = 1;
else if (anisotropyValue == 4)
rule.overwrite_settings.anistropic_value = 2;
else if (anisotropyValue == 8)
rule.overwrite_settings.anistropic_value = 3;
else if (anisotropyValue == 16)
rule.overwrite_settings.anistropic_value = 4;
else
cemuLog_log(LogType::Force, "Invalid value {} for overwriteAnisotropy in graphic pack {}. Only the values 1, 2, 4, 8 or 16 are allowed.", anisotropyValue, GetNormalizedPathString());
}
m_texture_rules.emplace_back(rule);
}
else if (boost::iequals(category_name, "Control"))
{
ParseRule(parser, rules, "vsyncFrequency", &m_vsync_frequency);
}
else if (boost::iequals(category_name, "OutputShader"))
{
auto option_upscale = rules.FindOption("upscaleMagFilter");
if(option_upscale && boost::iequals(*option_upscale, "NearestNeighbor"))
m_output_settings.upscale_filter = LatteTextureView::MagFilter::kNearestNeighbor;
auto option_downscale = rules.FindOption("NearestNeighbor");
if (option_downscale && boost::iequals(*option_downscale, "NearestNeighbor"))
m_output_settings.downscale_filter = LatteTextureView::MagFilter::kNearestNeighbor;
}
}
}
catch(const std::exception& ex)
{
cemuLog_log(LogType::Force, ex.what());
return false;
}
// load shaders
LoadShaders();
// load patches
LoadPatchFiles();
// enable patch groups
EnablePatches();
// load replaced files
LoadReplacedFiles();
// set custom vsync
if (HasCustomVSyncFrequency())
{
sint32 customVsyncFreq = GetCustomVSyncFrequency();
sint32 globalCustomVsyncFreq = 0;
if (LatteTiming_getCustomVsyncFrequency(globalCustomVsyncFreq))
{
if (customVsyncFreq != globalCustomVsyncFreq)
cemuLog_log(LogType::Force, "rules.txt error: Mismatching vsync frequency {} in graphic pack \'{}\'", customVsyncFreq, GetVirtualPath());
}
else
{
cemuLog_log(LogType::Force, "Set vsync frequency to {} (graphic pack {})", customVsyncFreq, GetVirtualPath());
LatteTiming_setCustomVsyncFrequency(customVsyncFreq);
}
}
m_activated = true;
return true;
}
bool GraphicPack2::Deactivate()
{
if (!m_activated)
return false;
UnloadPatches();
m_activated = false;
m_custom_shaders.clear();
m_texture_rules.clear();
m_output_shader.reset();
m_upscaling_shader.reset();
m_downscaling_shader.reset();
m_output_shader_ud.reset();
m_upscaling_shader_ud.reset();
m_downscaling_shader_ud.reset();
m_output_shader_source.clear();
m_upscaling_shader_source.clear();
m_downscaling_shader_source.clear();
if (HasCustomVSyncFrequency())
{
m_vsync_frequency = -1;
LatteTiming_disableCustomVsyncFrequency();
}
return true;
}
const std::string* GraphicPack2::FindCustomShaderSource(uint64 shaderBaseHash, uint64 shaderAuxHash, GP_SHADER_TYPE type, bool isVulkanRenderer)
{
for (const auto& gp : GraphicPack2::GetActiveGraphicPacks())
{
const auto it = std::find_if(gp->m_custom_shaders.begin(), gp->m_custom_shaders.end(),
[shaderBaseHash, shaderAuxHash, type](const auto& s) { return s.shader_base_hash == shaderBaseHash && s.shader_aux_hash == shaderAuxHash && s.type == type; });
if (it == gp->m_custom_shaders.end())
continue;
if(isVulkanRenderer && (*it).isPreVulkanShader)
continue;
return &it->source;
}
return nullptr;
}
std::unordered_map<std::string, std::vector<GraphicPack2::PresetPtr>> GraphicPack2::GetCategorizedPresets(std::vector<std::string>& order) const
{
order.clear();
std::unordered_map<std::string, std::vector<PresetPtr>> result;
for(const auto& entry : m_presets)
{
result[entry->category].emplace_back(entry);
const auto it = std::find(order.cbegin(), order.cend(), entry->category);
if (it == order.cend())
order.emplace_back(entry->category);
}
return result;
}
bool GraphicPack2::HasShaders() const
{
return !GetCustomShaders().empty()
|| !m_output_shader_source.empty() || !m_upscaling_shader_source.empty() || !m_downscaling_shader_source.empty();
}
RendererOutputShader* GraphicPack2::GetOuputShader(bool render_upside_down)
{
if(render_upside_down)
{
if (m_output_shader_ud)
return m_output_shader_ud.get();
if (!m_output_shader_source.empty())
m_output_shader_ud = std::make_unique<RendererOutputShader>(RendererOutputShader::GetOpenGlVertexSource(render_upside_down), m_output_shader_source);
return m_output_shader_ud.get();
}
else
{
if (m_output_shader)
return m_output_shader.get();
if (!m_output_shader_source.empty())
m_output_shader = std::make_unique<RendererOutputShader>(RendererOutputShader::GetOpenGlVertexSource(render_upside_down), m_output_shader_source);
return m_output_shader.get();
}
}
RendererOutputShader* GraphicPack2::GetUpscalingShader(bool render_upside_down)
{
if (render_upside_down)
{
if (m_upscaling_shader_ud)
return m_upscaling_shader_ud.get();
if (!m_upscaling_shader_source.empty())
m_upscaling_shader_ud = std::make_unique<RendererOutputShader>(RendererOutputShader::GetOpenGlVertexSource(render_upside_down), m_upscaling_shader_source);
return m_upscaling_shader_ud.get();
}
else
{
if (m_upscaling_shader)
return m_upscaling_shader.get();
if (!m_upscaling_shader_source.empty())
m_upscaling_shader = std::make_unique<RendererOutputShader>(RendererOutputShader::GetOpenGlVertexSource(render_upside_down), m_upscaling_shader_source);
return m_upscaling_shader.get();
}
}
RendererOutputShader* GraphicPack2::GetDownscalingShader(bool render_upside_down)
{
if (render_upside_down)
{
if (m_downscaling_shader_ud)
return m_downscaling_shader_ud.get();
if (!m_downscaling_shader_source.empty())
m_downscaling_shader_ud = std::make_unique<RendererOutputShader>(RendererOutputShader::GetOpenGlVertexSource(render_upside_down), m_downscaling_shader_source);
return m_downscaling_shader_ud.get();
}
else
{
if (m_downscaling_shader)
return m_downscaling_shader.get();
if (!m_downscaling_shader_source.empty())
m_downscaling_shader = std::make_unique<RendererOutputShader>(RendererOutputShader::GetOpenGlVertexSource(render_upside_down), m_downscaling_shader_source);
return m_downscaling_shader.get();
}
}
std::vector<GraphicPack2::PresetPtr> GraphicPack2::GetActivePresets() const
{
std::vector<PresetPtr> result;
result.reserve(m_presets.size());
std::copy_if(m_presets.cbegin(), m_presets.cend(), std::back_inserter(result), [](const PresetPtr& p) { return p->active; });
return result;
}
std::vector<uint64> GraphicPack2::ParseTitleIds(IniParser& rules, const char* option_name) const
{
std::vector<uint64> result;
auto option_text = rules.FindOption(option_name);
if (!option_text)
return result;
for (auto& token : TokenizeView(*option_text, ','))
{
try
{
result.emplace_back(ConvertString<uint64>(token, 16));
}
catch (const std::invalid_argument&) {}
}
return result;
}
void GraphicPack2::ApplyShaderPresets(std::string& shader_source) const
{
const auto active_presets = GetActivePresets();
const std::regex regex(R"(\$[a-zA-Z_0-9]+)");
std::smatch match;
size_t offset = 0;
while (std::regex_search(shader_source.cbegin() + offset, shader_source.cend(), match, regex))
{
if (active_presets.empty())
throw std::runtime_error("found variable in shader but no preset is active");
const auto str = match.str();
std::optional<PresetVar> var = GetPresetVariable(active_presets, str);
if(!var)
throw std::runtime_error("using an unknown preset variable in shader");
std::string new_value;
if (var->first == kInt)
new_value = fmt::format("{}", (int)var->second);
else
new_value = fmt::format("{:f}", var->second);
shader_source.replace(match.position() + offset, match.length(), new_value);
offset += match.position() + new_value.length();
}
}
GraphicPack2::CustomShader GraphicPack2::LoadShader(const fs::path& path, uint64 shader_base_hash, uint64 shader_aux_hash, GP_SHADER_TYPE shader_type) const
{
CustomShader shader;
std::ifstream file(path);
if (!file.is_open())
throw std::runtime_error("can't open shader file");
file.seekg(0, std::ios::end);
shader.source.reserve(file.tellg());
file.seekg(0, std::ios::beg);
shader.source.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
ApplyShaderPresets(shader.source);
shader.shader_base_hash = shader_base_hash;
shader.shader_aux_hash = shader_aux_hash;
shader.type = shader_type;
shader.isPreVulkanShader = this->m_version <= 3;
return shader;
}
std::vector<std::pair<MPTR, MPTR>> GraphicPack2::GetActiveRAMMappings()
{
uint64 currentTitleId = CafeSystem::GetForegroundTitleId();
std::vector<std::pair<MPTR, MPTR>> v;
for (const auto& gp : GraphicPack2::GetGraphicPacks())
{
if (!gp->IsEnabled())
continue;
if (!gp->ContainsTitleId(currentTitleId))
continue;
if (!gp->m_ramMappings.empty())
v.insert(v.end(), gp->m_ramMappings.begin(), gp->m_ramMappings.end());
}
std::sort(v.begin(), v.end(),
[](const std::pair<MPTR, MPTR>& a, const std::pair<MPTR, MPTR>& b) -> bool
{
return a.first < b.first;
});
return v;
}
| 37,200
|
C++
|
.cpp
| 1,090
| 30.886239
| 188
| 0.708481
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,168
|
TitleList.cpp
|
cemu-project_Cemu/src/Cafe/TitleList/TitleList.cpp
|
#include "TitleList.h"
#include "Common/FileStream.h"
#include "util/helpers/helpers.h"
#include <zarchive/zarchivereader.h>
bool sTLInitialized{ false };
fs::path sTLCacheFilePath;
// lists for tracking known titles
// note: The list may only contain titles with valid meta data (except for certain system titles). Entries loaded from the cache may not have been parsed yet, but they will use a cached value for titleId and titleVersion
std::mutex sTLMutex;
std::vector<TitleInfo*> sTLList;
std::vector<TitleInfo*> sTLListPending;
std::unordered_multimap<uint64, TitleInfo*> sTLMap;
bool sTLCacheDirty{false};
// paths
fs::path sTLMLCPath;
std::vector<fs::path> sTLScanPaths;
// worker
std::thread sTLRefreshWorker;
bool sTLRefreshWorkerActive{false};
std::atomic_uint32_t sTLRefreshRequests{};
std::atomic_bool sTLIsScanMandatory{ false };
// callback list
struct TitleListCallbackEntry
{
TitleListCallbackEntry(void(*cb)(CafeTitleListCallbackEvent* evt, void* ctx), void* ctx, uint64 uniqueId) :
cb(cb), ctx(ctx), uniqueId(uniqueId) {};
void (*cb)(CafeTitleListCallbackEvent* evt, void* ctx);
void* ctx;
uint64 uniqueId;
};
std::vector<TitleListCallbackEntry> sTLCallbackList;
void CafeTitleList::Initialize(const fs::path cacheXmlFile)
{
std::unique_lock _lock(sTLMutex);
sTLInitialized = true;
sTLCacheFilePath = cacheXmlFile;
LoadCacheFile();
}
void CafeTitleList::LoadCacheFile()
{
sTLIsScanMandatory = true;
cemu_assert_debug(sTLInitialized);
cemu_assert_debug(sTLList.empty());
auto xmlData = FileStream::LoadIntoMemory(sTLCacheFilePath);
if (!xmlData)
return;
pugi::xml_document doc;
if (!doc.load_buffer_inplace(xmlData->data(), xmlData->size(), pugi::parse_default, pugi::xml_encoding::encoding_utf8))
return;
auto titleListNode = doc.child("title_list");
pugi::xml_node itNode = titleListNode.first_child();
for (const auto& titleInfoNode : doc.child("title_list"))
{
TitleId titleId;
if( !TitleIdParser::ParseFromStr(titleInfoNode.attribute("titleId").as_string(), titleId))
continue;
uint16 titleVersion = titleInfoNode.attribute("version").as_uint();
uint32 sdkVersion = titleInfoNode.attribute("sdk_version").as_uint();
TitleInfo::TitleDataFormat format = (TitleInfo::TitleDataFormat)ConvertString<uint32>(titleInfoNode.child_value("format"));
CafeConsoleRegion region = (CafeConsoleRegion)ConvertString<uint32>(titleInfoNode.child_value("region"));
std::string name = titleInfoNode.child_value("name");
std::string path = titleInfoNode.child_value("path");
std::string sub_path = titleInfoNode.child_value("sub_path");
uint32 group_id = ConvertString<uint32>(titleInfoNode.attribute("group_id").as_string(), 16);
uint32 app_type = ConvertString<uint32>(titleInfoNode.attribute("app_type").as_string(), 16);
TitleInfo::CachedInfo cacheEntry;
cacheEntry.titleId = titleId;
cacheEntry.titleVersion = titleVersion;
cacheEntry.sdkVersion = sdkVersion;
cacheEntry.titleDataFormat = format;
cacheEntry.region = region;
cacheEntry.titleName = std::move(name);
cacheEntry.path = _utf8ToPath(path);
cacheEntry.subPath = std::move(sub_path);
cacheEntry.group_id = group_id;
cacheEntry.app_type = app_type;
TitleInfo* ti = new TitleInfo(cacheEntry);
if (!ti->IsValid())
{
cemuLog_log(LogType::Force, "Title cache contained invalid title");
delete ti;
continue;
}
AddTitle(ti);
}
sTLIsScanMandatory = false;
}
void CafeTitleList::StoreCacheFile()
{
cemu_assert_debug(sTLInitialized);
if (sTLCacheFilePath.empty())
return;
std::unique_lock _lock(sTLMutex);
pugi::xml_document doc;
auto declarationNode = doc.append_child(pugi::node_declaration);
declarationNode.append_attribute("version") = "1.0";
declarationNode.append_attribute("encoding") = "UTF-8";
auto title_list_node = doc.append_child("title_list");
for (auto& tiIt : sTLList)
{
TitleInfo::CachedInfo info = tiIt->MakeCacheEntry();
auto titleInfoNode = title_list_node.append_child("title");
titleInfoNode.append_attribute("titleId").set_value(fmt::format("{:016x}", info.titleId).c_str());
titleInfoNode.append_attribute("version").set_value(fmt::format("{:}", info.titleVersion).c_str());
titleInfoNode.append_attribute("sdk_version").set_value(fmt::format("{:}", info.sdkVersion).c_str());
titleInfoNode.append_attribute("group_id").set_value(fmt::format("{:08x}", info.group_id).c_str());
titleInfoNode.append_attribute("app_type").set_value(fmt::format("{:08x}", info.app_type).c_str());
titleInfoNode.append_child("region").append_child(pugi::node_pcdata).set_value(fmt::format("{}", (uint32)info.region).c_str());
titleInfoNode.append_child("name").append_child(pugi::node_pcdata).set_value(info.titleName.c_str());
titleInfoNode.append_child("format").append_child(pugi::node_pcdata).set_value(fmt::format("{}", (uint32)info.titleDataFormat).c_str());
titleInfoNode.append_child("path").append_child(pugi::node_pcdata).set_value(_pathToUtf8(info.path).c_str());
if(!info.subPath.empty())
titleInfoNode.append_child("sub_path").append_child(pugi::node_pcdata).set_value(_pathToUtf8(info.subPath).c_str());
}
fs::path tmpPath = fs::path(sTLCacheFilePath.parent_path()).append(fmt::format("{}__tmp", _pathToUtf8(sTLCacheFilePath.filename())));
std::ofstream fileOut(tmpPath, std::ios::out | std::ios::binary | std::ios::trunc);
if (!fileOut.is_open())
{
cemuLog_log(LogType::Force, "Unable to store title list in {}", _pathToUtf8(tmpPath));
return;
}
doc.save(fileOut, " ", 1, pugi::xml_encoding::encoding_utf8);
fileOut.flush();
fileOut.close();
std::error_code ec;
fs::rename(tmpPath, sTLCacheFilePath, ec);
}
void CafeTitleList::ClearScanPaths()
{
std::unique_lock _lock(sTLMutex);
sTLScanPaths.clear();
}
void CafeTitleList::AddScanPath(fs::path path)
{
std::unique_lock _lock(sTLMutex);
sTLScanPaths.emplace_back(path);
}
void CafeTitleList::SetMLCPath(fs::path path)
{
std::unique_lock _lock(sTLMutex);
std::error_code ec;
if (!fs::is_directory(path, ec))
{
cemuLog_log(LogType::Force, "MLC set to invalid path: {}", _pathToUtf8(path));
return;
}
sTLMLCPath = path;
}
void CafeTitleList::Refresh()
{
std::unique_lock _lock(sTLMutex);
cemu_assert_debug(sTLInitialized);
sTLRefreshRequests++;
if (!sTLRefreshWorkerActive)
{
if (sTLRefreshWorker.joinable())
sTLRefreshWorker.join();
sTLRefreshWorkerActive = true;
sTLRefreshWorker = std::thread(RefreshWorkerThread);
}
sTLIsScanMandatory = false;
}
bool CafeTitleList::IsScanning()
{
std::unique_lock _lock(sTLMutex);
return sTLRefreshWorkerActive;
}
void CafeTitleList::WaitForMandatoryScan()
{
if (!sTLIsScanMandatory)
return;
while (IsScanning())
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
void _RemoveTitleFromMultimap(TitleInfo* titleInfo)
{
auto mapRange = sTLMap.equal_range(titleInfo->GetAppTitleId());
for (auto mapIt = mapRange.first; mapIt != mapRange.second; ++mapIt)
{
if (mapIt->second == titleInfo)
{
sTLMap.erase(mapIt);
return;
}
}
cemu_assert_suspicious();
}
// check if path is a valid title and if it is, permanently add it to the title list
// in the special case that path points to a WUA file, all contained titles will be added
void CafeTitleList::AddTitleFromPath(fs::path path)
{
if (path.has_extension() && boost::iequals(_pathToUtf8(path.extension()), ".wua"))
{
ZArchiveReader* zar = ZArchiveReader::OpenFromFile(path);
if (!zar)
{
cemuLog_log(LogType::Force, "Found {} but it is not a valid Wii U archive file", _pathToUtf8(path));
return;
}
// enumerate all contained titles
ZArchiveNodeHandle rootDir = zar->LookUp("", false, true);
cemu_assert(rootDir != ZARCHIVE_INVALID_NODE);
for (uint32 i = 0; i < zar->GetDirEntryCount(rootDir); i++)
{
ZArchiveReader::DirEntry dirEntry;
if( !zar->GetDirEntry(rootDir, i, dirEntry) )
continue;
if(!dirEntry.isDirectory)
continue;
TitleId parsedId;
uint16 parsedVersion;
if (!TitleInfo::ParseWuaTitleFolderName(dirEntry.name, parsedId, parsedVersion))
{
cemuLog_log(LogType::Force, "Invalid title directory in {}: \"{}\"", _pathToUtf8(path), dirEntry.name);
continue;
}
// valid subdirectory
TitleInfo* titleInfo = new TitleInfo(path, dirEntry.name);
if (titleInfo->IsValid())
AddDiscoveredTitle(titleInfo);
else
delete titleInfo;
}
delete zar;
return;
}
TitleInfo* titleInfo = new TitleInfo(path);
if (titleInfo->IsValid())
AddDiscoveredTitle(titleInfo);
else
delete titleInfo;
}
bool CafeTitleList::RefreshWorkerThread()
{
SetThreadName("TitleListWorker");
while (sTLRefreshRequests.load())
{
sTLRefreshRequests.store(0);
// create copies of all the paths
sTLMutex.lock();
fs::path mlcPath = sTLMLCPath;
std::vector<fs::path> gamePaths = sTLScanPaths;
// remember the current list of known titles
// during the scanning process we will erase matches from the pending list
// at the end of scanning, we can then use this list to identify and remove any titles that are no longer discoverable
sTLListPending = sTLList;
sTLMutex.unlock();
// scan game paths
for (auto& it : gamePaths)
ScanGamePath(it);
// scan MLC
if (!mlcPath.empty())
{
std::error_code ec;
for (auto& it : fs::directory_iterator(mlcPath / "usr/title", ec))
{
if (!it.is_directory(ec))
continue;
ScanMLCPath(it.path());
}
ScanMLCPath(mlcPath / "sys/title/00050010");
ScanMLCPath(mlcPath / "sys/title/00050030");
}
// remove any titles that are still pending
for (auto& itPending : sTLListPending)
{
_RemoveTitleFromMultimap(itPending);
std::erase(sTLList, itPending);
}
// send notifications for removed titles, but only if there exists no other title with the same titleId and version
if (!sTLListPending.empty())
sTLCacheDirty = true;
for (auto& itPending : sTLListPending)
{
CafeTitleListCallbackEvent evt;
evt.eventType = CafeTitleListCallbackEvent::TYPE::TITLE_REMOVED;
evt.titleInfo = itPending;
for (auto& it : sTLCallbackList)
it.cb(&evt, it.ctx);
delete itPending;
}
sTLListPending.clear();
}
sTLMutex.lock();
sTLRefreshWorkerActive = false;
// send notification that scanning finished
CafeTitleListCallbackEvent evt;
evt.eventType = CafeTitleListCallbackEvent::TYPE::SCAN_FINISHED;
evt.titleInfo = nullptr;
for (auto& it : sTLCallbackList)
it.cb(&evt, it.ctx);
sTLMutex.unlock();
if (sTLCacheDirty)
{
StoreCacheFile();
sTLCacheDirty = false;
}
return true;
}
bool _IsKnownFileNameOrExtension(const fs::path& path)
{
std::string fileExtension = _pathToUtf8(path.extension());
for (auto& it : fileExtension)
it = _ansiToLower(it);
if(fileExtension == ".tmd")
{
// must be "title.tmd"
std::string fileName = _pathToUtf8(path.filename());
for (auto& it : fileName)
it = _ansiToLower(it);
return fileName == "title.tmd";
}
return
fileExtension == ".wud" ||
fileExtension == ".wux" ||
fileExtension == ".iso" ||
fileExtension == ".wua" ||
fileExtension == ".wuhb";
// note: To detect extracted titles with RPX we rely on the presence of the content,code,meta directory structure
}
void CafeTitleList::ScanGamePath(const fs::path& path)
{
// scan the whole directory first to determine if this is a title folder
std::vector<fs::path> filesInDirectory;
std::vector<fs::path> dirsInDirectory;
bool hasContentFolder = false, hasCodeFolder = false, hasMetaFolder = false;
std::error_code ec;
for (auto& it : fs::directory_iterator(path, ec))
{
if (it.is_regular_file(ec))
{
filesInDirectory.emplace_back(it.path());
}
else if (it.is_directory(ec))
{
dirsInDirectory.emplace_back(it.path());
std::string dirName = _pathToUtf8(it.path().filename());
if (boost::iequals(dirName, "content"))
hasContentFolder = true;
else if (boost::iequals(dirName, "code"))
hasCodeFolder = true;
else if (boost::iequals(dirName, "meta"))
hasMetaFolder = true;
}
}
// always check individual files
for (auto& it : filesInDirectory)
{
// since checking individual files is slow, we limit it to known file names or extensions
if (!it.has_extension())
continue;
if (!_IsKnownFileNameOrExtension(it))
continue;
AddTitleFromPath(it);
}
// is the current directory a title folder?
if (hasContentFolder && hasCodeFolder && hasMetaFolder)
{
// verify if this folder is a valid title
TitleInfo* titleInfo = new TitleInfo(path);
if (titleInfo->IsValid())
AddDiscoveredTitle(titleInfo);
else
delete titleInfo;
// if there are other folders besides content/code/meta then traverse those
if (dirsInDirectory.size() > 3)
{
for (auto& it : dirsInDirectory)
{
std::string dirName = _pathToUtf8(it.filename());
if (!boost::iequals(dirName, "content") &&
!boost::iequals(dirName, "code") &&
!boost::iequals(dirName, "meta"))
ScanGamePath(it);
}
}
}
else
{
// scan subdirectories
for (auto& it : dirsInDirectory)
ScanGamePath(it);
}
}
void CafeTitleList::ScanMLCPath(const fs::path& path)
{
std::error_code ec;
for (auto& it : fs::directory_iterator(path, ec))
{
if (!it.is_directory())
continue;
// only scan directories which match the title id naming scheme
std::string dirName = _pathToUtf8(it.path().filename());
if(dirName.size() != 8)
continue;
bool containsNoHexCharacter = false;
for (auto& it : dirName)
{
if(it >= 'A' && it <= 'F' ||
it >= 'a' && it <= 'f' ||
it >= '0' && it <= '9')
continue;
containsNoHexCharacter = true;
break;
}
if(containsNoHexCharacter)
continue;
if (fs::is_directory(it.path() / "code", ec) &&
fs::is_directory(it.path() / "content", ec) &&
fs::is_directory(it.path() / "meta", ec))
{
TitleInfo* titleInfo = new TitleInfo(it);
if (titleInfo->IsValid() && titleInfo->ParseXmlInfo())
AddDiscoveredTitle(titleInfo);
else
delete titleInfo;
}
}
}
void CafeTitleList::AddDiscoveredTitle(TitleInfo* titleInfo)
{
cemu_assert_debug(titleInfo->ParseXmlInfo());
std::unique_lock _lock(sTLMutex);
// remove from pending list
auto pendingIt = std::find_if(sTLListPending.begin(), sTLListPending.end(), [titleInfo](const TitleInfo* it) { return it->IsEqualByLocation(*titleInfo); });
if (pendingIt != sTLListPending.end())
sTLListPending.erase(pendingIt);
AddTitle(titleInfo);
}
void CafeTitleList::AddTitle(TitleInfo* titleInfo)
{
// check if title is already known
if (titleInfo->IsCached())
{
bool isKnown = std::any_of(sTLList.cbegin(), sTLList.cend(), [&titleInfo](const TitleInfo* ti) { return titleInfo->IsEqualByLocation(*ti); });
if (isKnown)
{
delete titleInfo;
return;
}
}
else
{
auto it = std::find_if(sTLList.begin(), sTLList.end(), [titleInfo](const TitleInfo* it) { return it->IsEqualByLocation(*titleInfo); });
if (it != sTLList.end())
{
if ((*it)->IsCached())
{
// replace cached entry with newly parsed title
TitleInfo* deletedInfo = *it;
sTLList.erase(it);
_RemoveTitleFromMultimap(deletedInfo);
delete deletedInfo;
}
else
{
// title already known
delete titleInfo;
return;
}
}
}
sTLList.emplace_back(titleInfo);
sTLMap.emplace(titleInfo->GetAppTitleId(), titleInfo);
// send out notification
CafeTitleListCallbackEvent evt;
evt.eventType = CafeTitleListCallbackEvent::TYPE::TITLE_DISCOVERED;
evt.titleInfo = titleInfo;
for (auto& it : sTLCallbackList)
it.cb(&evt, it.ctx);
sTLCacheDirty = true;
}
uint64 CafeTitleList::RegisterCallback(void(*cb)(CafeTitleListCallbackEvent* evt, void* ctx), void* ctx)
{
static std::atomic<uint64_t> sCallbackIdGen = 1;
uint64 id = sCallbackIdGen.fetch_add(1);
std::unique_lock _lock(sTLMutex);
sTLCallbackList.emplace_back(cb, ctx, id);
// immediately notify of all known titles
for (auto& it : sTLList)
{
CafeTitleListCallbackEvent evt;
evt.eventType = CafeTitleListCallbackEvent::TYPE::TITLE_DISCOVERED;
evt.titleInfo = it;
cb(&evt, ctx);
}
// if not scanning then send out scan finished notification
if (!sTLRefreshWorkerActive)
{
CafeTitleListCallbackEvent evt;
evt.eventType = CafeTitleListCallbackEvent::TYPE::SCAN_FINISHED;
evt.titleInfo = nullptr;
for (auto& it : sTLCallbackList)
it.cb(&evt, it.ctx);
}
return id;
}
void CafeTitleList::UnregisterCallback(uint64 id)
{
std::unique_lock _lock(sTLMutex);
auto it = std::find_if(sTLCallbackList.begin(), sTLCallbackList.end(), [id](auto& e) { return e.uniqueId == id; });
cemu_assert(it != sTLCallbackList.end()); // must be a valid callback
sTLCallbackList.erase(it);
}
bool CafeTitleList::HasTitle(TitleId titleId, uint16& versionOut)
{
// todo - optimize?
bool matchFound = false;
versionOut = 0;
std::unique_lock _lock(sTLMutex);
for (auto& it : sTLList)
{
if (it->GetAppTitleId() == titleId)
{
uint16 titleVersion = it->GetAppTitleVersion();
if (titleVersion > versionOut)
versionOut = titleVersion;
matchFound = true;
}
}
return matchFound;
}
bool CafeTitleList::HasTitleAndVersion(TitleId titleId, uint16 version)
{
std::unique_lock _lock(sTLMutex);
for (auto& it : sTLList)
{
if (it->GetAppTitleId() == titleId && it->GetAppTitleVersion() == version)
return true;
}
return false;
}
std::vector<TitleId> CafeTitleList::GetAllTitleIds()
{
std::unordered_set<TitleId> visitedTitleIds;
std::unique_lock _lock(sTLMutex);
std::vector<TitleId> titleIds;
titleIds.reserve(sTLList.size());
for (auto& it : sTLList)
{
TitleId tid = it->GetAppTitleId();
if (visitedTitleIds.find(tid) != visitedTitleIds.end())
continue;
titleIds.emplace_back(tid);
visitedTitleIds.emplace(tid);
}
return titleIds;
}
std::span<TitleInfo*> CafeTitleList::AcquireInternalList()
{
sTLMutex.lock();
return { sTLList.data(), sTLList.size() };
}
void CafeTitleList::ReleaseInternalList()
{
sTLMutex.unlock();
}
bool CafeTitleList::GetFirstByTitleId(TitleId titleId, TitleInfo& titleInfoOut)
{
std::unique_lock _lock(sTLMutex);
auto it = sTLMap.find(titleId);
if (it != sTLMap.end())
{
cemu_assert_debug(it->first == titleId);
titleInfoOut = *it->second;
return true;
}
return false;
}
// takes update or AOC title id and returns the title id of the associated base title
// this can fail if trying to translate an AOC title id without having the base title meta information
bool CafeTitleList::FindBaseTitleId(TitleId titleId, TitleId& titleIdBaseOut)
{
titleId = TitleIdParser::MakeBaseTitleId(titleId);
// aoc to base
// todo - this requires scanning all base titles and their updates to see if they reference this title id
// for now we assume there is a direct match of ids
if (((titleId >> 32) & 0xFF) == 0x0C)
{
titleId &= ~0xFF00000000;
titleId |= 0x0000000000;
}
titleIdBaseOut = titleId;
return true;
}
GameInfo2 CafeTitleList::GetGameInfo(TitleId titleId)
{
GameInfo2 gameInfo;
// find base title id
uint64 baseTitleId;
if (!FindBaseTitleId(titleId, baseTitleId))
{
cemu_assert_suspicious();
}
// determine if an optional update title id exists
TitleIdParser tip(baseTitleId);
bool hasSeparateUpdateTitleId = tip.CanHaveSeparateUpdateTitleId();
uint64 updateTitleId = 0;
if (hasSeparateUpdateTitleId)
updateTitleId = tip.GetSeparateUpdateTitleId();
// scan the title list for base and update
std::unique_lock _lock(sTLMutex);
for (auto& it : sTLList)
{
TitleId appTitleId = it->GetAppTitleId();
if (appTitleId == baseTitleId)
{
gameInfo.SetBase(*it);
}
if (hasSeparateUpdateTitleId && appTitleId == updateTitleId)
{
gameInfo.SetUpdate(*it);
}
}
// if this title can have AOC content then do a second scan
// todo - get a list of all AOC title ids from the base/update meta information
// for now we assume there is a direct match between the base titleId and the aoc titleId
if (tip.CanHaveSeparateUpdateTitleId())
{
uint64 aocTitleId = baseTitleId | 0xC00000000;
for (auto& it : sTLList)
{
TitleId appTitleId = it->GetAppTitleId();
if (appTitleId == aocTitleId)
{
gameInfo.AddAOC(*it); // stores the AOC with the highest title version
}
}
}
return gameInfo;
}
TitleInfo CafeTitleList::GetTitleInfoByUID(uint64 uid)
{
TitleInfo titleInfo;
std::unique_lock _lock(sTLMutex);
for (auto& it : sTLList)
{
if (it->GetUID() == uid)
{
titleInfo = *it;
break;
}
}
return titleInfo;
}
| 20,371
|
C++
|
.cpp
| 645
| 28.965891
| 220
| 0.731809
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,169
|
SaveInfo.cpp
|
cemu-project_Cemu/src/Cafe/TitleList/SaveInfo.cpp
|
#include "SaveInfo.h"
#include "config/ActiveSettings.h"
#include "Common/FileStream.h"
#include "ParsedMetaXml.h"
SaveInfo::SaveInfo(TitleId titleId) : m_titleId(titleId)
{
m_path = GetSavePath(titleId);
std::error_code ec;
m_isValid = fs::is_directory(m_path, ec);
}
std::string SaveInfo::GetStorageSubpathByTitleId(TitleId titleId)
{
// usr/save/<titleIdHigh>/<titleIdLow>/
return fmt::format("usr/save/{:08x}/{:08x}", ((uint64)titleId) >> 32, (uint64)titleId & 0xFFFFFFFF);
}
fs::path SaveInfo::GetSavePath(TitleId titleId)
{
return ActiveSettings::GetMlcPath(GetStorageSubpathByTitleId(titleId));
}
bool SaveInfo::ParseMetaData()
{
if (m_hasMetaLoaded)
return m_parsedMetaXml != nullptr;
m_hasMetaLoaded = true;
auto xmlData = FileStream::LoadIntoMemory(m_path / "meta/meta.xml");
if (!xmlData)
return false;
m_parsedMetaXml = ParsedMetaXml::Parse(xmlData->data(), xmlData->size());
return m_parsedMetaXml != nullptr;
}
| 944
|
C++
|
.cpp
| 30
| 29.833333
| 101
| 0.757409
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,170
|
SaveList.cpp
|
cemu-project_Cemu/src/Cafe/TitleList/SaveList.cpp
|
#include "SaveList.h"
#include <charconv>
#include <util/helpers/helpers.h>
std::mutex sSLMutex;
fs::path sSLMLCPath;
std::vector<SaveInfo*> sSLList;
// callback list
struct SaveListCallbackEntry
{
SaveListCallbackEntry(void(*cb)(CafeSaveListCallbackEvent* evt, void* ctx), void* ctx, uint64 uniqueId) :
cb(cb), ctx(ctx), uniqueId(uniqueId) {};
void (*cb)(CafeSaveListCallbackEvent* evt, void* ctx);
void* ctx;
uint64 uniqueId;
};
std::vector<SaveListCallbackEntry> sSLCallbackList;
// worker thread
std::atomic_bool sSLWorkerThreadActive{false};
void CafeSaveList::Initialize()
{
}
void CafeSaveList::SetMLCPath(fs::path mlcPath)
{
std::unique_lock _lock(sSLMutex);
sSLMLCPath = mlcPath;
}
void CafeSaveList::Refresh()
{
std::unique_lock _lock(sSLMutex);
if (sSLWorkerThreadActive)
return;
sSLWorkerThreadActive = true;
std::thread t(RefreshThreadWorker);
t.detach();
}
void CafeSaveList::RefreshThreadWorker()
{
SetThreadName("SaveListWorker");
// clear save list
for (auto& itSaveInfo : sSLList)
{
for (auto& it : sSLCallbackList)
{
CafeSaveListCallbackEvent evt;
evt.eventType = CafeSaveListCallbackEvent::TYPE::SAVE_REMOVED;
evt.saveInfo = itSaveInfo;
it.cb(&evt, it.ctx);
}
delete itSaveInfo;
}
sSLList.clear();
sSLMutex.lock();
fs::path mlcPath = sSLMLCPath;
sSLMutex.unlock();
std::error_code ec;
for (auto it_titleHigh : fs::directory_iterator(mlcPath / "usr/save", ec))
{
if(!it_titleHigh.is_directory(ec))
continue;
std::string dirName = _pathToUtf8(it_titleHigh.path().filename());
if(dirName.empty())
continue;
uint32 titleIdHigh;
std::from_chars_result r = std::from_chars(dirName.data(), dirName.data() + dirName.size(), titleIdHigh, 16);
if (r.ec != std::errc())
continue;
fs::path tmp = it_titleHigh.path();
for (auto it_titleLow : fs::directory_iterator(tmp, ec))
{
if (!it_titleLow.is_directory(ec))
continue;
dirName = _pathToUtf8(it_titleLow.path().filename());
if (dirName.empty())
continue;
uint32 titleIdLow;
std::from_chars_result r = std::from_chars(dirName.data(), dirName.data() + dirName.size(), titleIdLow, 16);
if (r.ec != std::errc())
continue;
// found save
TitleId titleId = (uint64)titleIdHigh << 32 | (uint64)titleIdLow;
SaveInfo* saveInfo = new SaveInfo(titleId);
if (saveInfo->IsValid())
DiscoveredSave(saveInfo);
else
delete saveInfo;
}
}
sSLMutex.lock();
sSLWorkerThreadActive = false;
sSLMutex.unlock();
// send notification about finished scan
for (auto& it : sSLCallbackList)
{
CafeSaveListCallbackEvent evt;
evt.eventType = CafeSaveListCallbackEvent::TYPE::SCAN_FINISHED;
evt.saveInfo = nullptr;
it.cb(&evt, it.ctx);
}
}
void CafeSaveList::DiscoveredSave(SaveInfo* saveInfo)
{
if (!saveInfo->ParseMetaData())
{
delete saveInfo;
return;
}
std::unique_lock _lock(sSLMutex);
auto it = std::find_if(sSLList.begin(), sSLList.end(), [saveInfo](const SaveInfo* rhs) { return saveInfo->GetTitleId() == rhs->GetTitleId(); });
if (it != sSLList.end())
{
// save already known
delete saveInfo;
return;
}
sSLList.emplace_back(saveInfo);
// send notification
for (auto& it : sSLCallbackList)
{
CafeSaveListCallbackEvent evt;
evt.eventType = CafeSaveListCallbackEvent::TYPE::SAVE_DISCOVERED;
evt.saveInfo = saveInfo;
it.cb(&evt, it.ctx);
}
}
uint64 CafeSaveList::RegisterCallback(void(*cb)(CafeSaveListCallbackEvent* evt, void* ctx), void* ctx)
{
static std::atomic<uint64_t> sCallbackIdGen = 1;
uint64 id = sCallbackIdGen.fetch_add(1);
std::unique_lock _lock(sSLMutex);
sSLCallbackList.emplace_back(cb, ctx, id);
// immediately notify of all known titles
for (auto& it : sSLList)
{
CafeSaveListCallbackEvent evt;
evt.eventType = CafeSaveListCallbackEvent::TYPE::SAVE_DISCOVERED;
evt.saveInfo = it;
cb(&evt, ctx);
}
// if not scanning then send out scan finished notification
if (!sSLWorkerThreadActive)
{
CafeSaveListCallbackEvent evt;
evt.eventType = CafeSaveListCallbackEvent::TYPE::SCAN_FINISHED;
evt.saveInfo = nullptr;
for (auto& it : sSLCallbackList)
it.cb(&evt, it.ctx);
}
return id;
}
void CafeSaveList::UnregisterCallback(uint64 id)
{
std::unique_lock _lock(sSLMutex);
auto it = std::find_if(sSLCallbackList.begin(), sSLCallbackList.end(), [id](auto& e) { return e.uniqueId == id; });
cemu_assert(it != sSLCallbackList.end());
sSLCallbackList.erase(it);
}
SaveInfo CafeSaveList::GetSaveByTitleId(TitleId titleId)
{
std::unique_lock _lock(sSLMutex);
for (auto& it : sSLList)
if (it->GetTitleId() == titleId)
return *it;
return {};
}
| 4,608
|
C++
|
.cpp
| 164
| 25.658537
| 145
| 0.731828
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,171
|
TitleInfo.cpp
|
cemu-project_Cemu/src/Cafe/TitleList/TitleInfo.cpp
|
#include "TitleInfo.h"
#include "Cafe/Filesystem/fscDeviceHostFS.h"
#include "Cafe/Filesystem/WUHB/WUHBReader.h"
#include "Cafe/Filesystem/FST/FST.h"
#include "pugixml.hpp"
#include "Common/FileStream.h"
#include <zarchive/zarchivereader.h>
#include "util/IniParser/IniParser.h"
#include "util/crypto/crc32.h"
#include "config/ActiveSettings.h"
#include "util/helpers/helpers.h"
// detect format by reading file header/footer
CafeTitleFileType DetermineCafeSystemFileType(fs::path filePath)
{
std::unique_ptr<FileStream> fs(FileStream::openFile2(filePath));
if (!fs)
return CafeTitleFileType::UNKNOWN;
// very small files (<32 bytes) are always considered unknown
uint64 fileSize = fs->GetSize();
if (fileSize < 32)
return CafeTitleFileType::UNKNOWN;
// read header bytes
uint8 headerRaw[32]{};
fs->readData(headerRaw, sizeof(headerRaw));
// check for WUX
uint8 wuxHeaderMagic[8] = { 0x57,0x55,0x58,0x30,0x2E,0xD0,0x99,0x10 };
if (memcmp(headerRaw, wuxHeaderMagic, sizeof(wuxHeaderMagic)) == 0)
return CafeTitleFileType::WUX;
// check for RPX
uint8 rpxHeaderMagic[9] = { 0x7F,0x45,0x4C,0x46,0x01,0x02,0x01,0xCA,0xFE };
if (memcmp(headerRaw, rpxHeaderMagic, sizeof(rpxHeaderMagic)) == 0)
return CafeTitleFileType::RPX;
// check for ELF
uint8 elfHeaderMagic[9] = { 0x7F,0x45,0x4C,0x46,0x01,0x02,0x01,0x00,0x00 };
if (memcmp(headerRaw, elfHeaderMagic, sizeof(elfHeaderMagic)) == 0)
return CafeTitleFileType::ELF;
// check for WUD
uint8 wudMagic1[4] = { 0x57,0x55,0x50,0x2D }; // wud files should always start with "WUP-..."
uint8 wudMagic2[4] = { 0xCC,0x54,0x9E,0xB9 };
if (fileSize >= 0x10000)
{
uint8 magic1[4];
fs->SetPosition(0);
fs->readData(magic1, 4);
if (memcmp(magic1, wudMagic1, 4) == 0)
{
uint8 magic2[4];
fs->SetPosition(0x10000);
fs->readData(magic2, 4);
if (memcmp(magic2, wudMagic2, 4) == 0)
{
return CafeTitleFileType::WUD;
}
}
}
// check for WUA
// todo
return CafeTitleFileType::UNKNOWN;
}
TitleInfo::TitleInfo(const fs::path& path)
{
m_isValid = DetectFormat(path, m_fullPath, m_titleFormat);
if (!m_isValid)
m_titleFormat = TitleDataFormat::INVALID_STRUCTURE;
else
{
m_isValid = ParseXmlInfo();
}
if (m_isValid)
CalcUID();
}
TitleInfo::TitleInfo(const fs::path& path, std::string_view subPath)
{
// path must point to a (wua) file
if (!path.has_filename())
{
m_isValid = false;
SetInvalidReason(InvalidReason::BAD_PATH_OR_INACCESSIBLE);
return;
}
m_isValid = true;
m_titleFormat = TitleDataFormat::WIIU_ARCHIVE;
m_fullPath = path;
m_subPath = subPath;
m_isValid = ParseXmlInfo();
if (m_isValid)
CalcUID();
}
TitleInfo::TitleInfo(const TitleInfo::CachedInfo& cachedInfo)
{
m_cachedInfo = new CachedInfo(cachedInfo);
m_fullPath = cachedInfo.path;
m_subPath = cachedInfo.subPath;
m_titleFormat = cachedInfo.titleDataFormat;
// verify some parameters
m_isValid = false;
if (cachedInfo.titleDataFormat != TitleDataFormat::HOST_FS &&
cachedInfo.titleDataFormat != TitleDataFormat::WIIU_ARCHIVE &&
cachedInfo.titleDataFormat != TitleDataFormat::WUHB &&
cachedInfo.titleDataFormat != TitleDataFormat::WUD &&
cachedInfo.titleDataFormat != TitleDataFormat::NUS &&
cachedInfo.titleDataFormat != TitleDataFormat::INVALID_STRUCTURE)
return;
if (cachedInfo.path.empty())
return;
if (cachedInfo.titleDataFormat == TitleDataFormat::WIIU_ARCHIVE && m_subPath.empty())
return; // for wua files the subpath must never be empty (title must not be stored in root of archive)
m_isValid = true;
CalcUID();
}
TitleInfo::~TitleInfo()
{
cemu_assert(m_mountpoints.empty());
delete m_parsedMetaXml;
delete m_parsedAppXml;
delete m_parsedCosXml;
delete m_cachedInfo;
}
TitleInfo::CachedInfo TitleInfo::MakeCacheEntry()
{
cemu_assert_debug(IsValid());
CachedInfo e;
e.titleDataFormat = m_titleFormat;
e.path = m_fullPath;
e.subPath = m_subPath;
e.titleId = GetAppTitleId();
e.titleVersion = GetAppTitleVersion();
e.sdkVersion = GetAppSDKVersion();
e.titleName = GetMetaTitleName();
e.region = GetMetaRegion();
e.group_id = GetAppGroup();
e.app_type = GetAppType();
return e;
}
// WUA can contain multiple titles. Root directory contains one directory for each title. The name must match: <titleId>_v<version>
bool TitleInfo::ParseWuaTitleFolderName(std::string_view name, TitleId& titleIdOut, uint16& titleVersionOut)
{
std::string_view sv = name;
if (sv.size() < 16 + 2)
return false;
TitleId parsedId;
if (!TitleIdParser::ParseFromStr(sv, parsedId))
return false;
sv.remove_prefix(16);
if (sv[0] != '_' || (sv[1] != 'v' && sv[1] != 'v'))
return false;
sv.remove_prefix(2);
if (sv.empty())
return false;
if (sv[0] == '0' && sv.size() != 1) // leading zero not allowed
return false;
uint32 v = 0;
while (!sv.empty())
{
uint8 c = sv[0];
sv.remove_prefix(1);
v *= 10;
if (c >= '0' && c <= '9')
v += (uint32)(c - '0');
else
{
v = 0xFFFFFFFF;
break;
}
}
if (v > 0xFFFF)
return false;
titleIdOut = parsedId;
titleVersionOut = v;
return true;
}
bool TitleInfo::DetectFormat(const fs::path& path, fs::path& pathOut, TitleDataFormat& formatOut)
{
std::error_code ec;
if (path.has_extension() && fs::is_regular_file(path, ec))
{
std::string filenameStr = _pathToUtf8(path.filename());
if (boost::iends_with(filenameStr, ".rpx"))
{
// is in code folder?
fs::path parentPath = path.parent_path();
if (boost::iequals(_pathToUtf8(parentPath.filename()), "code"))
{
parentPath = parentPath.parent_path();
// next to content and meta?
std::error_code ec;
if (fs::exists(parentPath / "content", ec) && fs::exists(parentPath / "meta", ec))
{
formatOut = TitleDataFormat::HOST_FS;
pathOut = parentPath;
return true;
}
}
}
else if (boost::iends_with(filenameStr, ".wud") ||
boost::iends_with(filenameStr, ".wux") ||
boost::iends_with(filenameStr, ".iso"))
{
formatOut = TitleDataFormat::WUD;
pathOut = path;
return true;
}
else if (boost::iequals(filenameStr, "title.tmd"))
{
formatOut = TitleDataFormat::NUS;
pathOut = path;
return true;
}
else if (boost::iends_with(filenameStr, ".wua"))
{
formatOut = TitleDataFormat::WIIU_ARCHIVE;
pathOut = path;
// a Wii U archive file can contain multiple titles but TitleInfo only maps to one
// we use the first base title that we find. This is the most intuitive behavior when someone launches "game.wua"
ZArchiveReader* zar = ZArchiveReader::OpenFromFile(path);
if (!zar)
return false;
ZArchiveNodeHandle rootDir = zar->LookUp("", false, true);
bool foundBase = false;
for (uint32 i = 0; i < zar->GetDirEntryCount(rootDir); i++)
{
ZArchiveReader::DirEntry dirEntry;
if (!zar->GetDirEntry(rootDir, i, dirEntry))
continue;
if (!dirEntry.isDirectory)
continue;
TitleId parsedId;
uint16 parsedVersion;
if (!TitleInfo::ParseWuaTitleFolderName(dirEntry.name, parsedId, parsedVersion))
continue;
TitleIdParser tip(parsedId);
TitleIdParser::TITLE_TYPE tt = tip.GetType();
if (tt == TitleIdParser::TITLE_TYPE::BASE_TITLE || tt == TitleIdParser::TITLE_TYPE::BASE_TITLE_DEMO ||
tt == TitleIdParser::TITLE_TYPE::SYSTEM_TITLE || tt == TitleIdParser::TITLE_TYPE::SYSTEM_OVERLAY_TITLE)
{
m_subPath = dirEntry.name;
foundBase = true;
break;
}
}
delete zar;
return foundBase;
}
else if (boost::iends_with(filenameStr, ".wuhb"))
{
std::unique_ptr<WUHBReader> reader{WUHBReader::FromPath(path)};
if(reader)
{
formatOut = TitleDataFormat::WUHB;
pathOut = path;
return true;
}
}
// note: Since a Wii U archive file (.wua) contains multiple titles we shouldn't auto-detect them here
// instead TitleInfo has a second constructor which takes a subpath
// unable to determine type by extension, check contents
CafeTitleFileType fileType = DetermineCafeSystemFileType(path);
if (fileType == CafeTitleFileType::WUD ||
fileType == CafeTitleFileType::WUX)
{
formatOut = TitleDataFormat::WUD;
pathOut = path;
return true;
}
}
else
{
// does it point to the root folder of a title?
std::error_code ec;
if (fs::exists(path / "content", ec) && fs::exists(path / "meta", ec) && fs::exists(path / "code", ec))
{
formatOut = TitleDataFormat::HOST_FS;
pathOut = path;
return true;
}
}
SetInvalidReason(InvalidReason::UNKNOWN_FORMAT);
return false;
}
bool TitleInfo::IsValid() const
{
return m_isValid;
}
fs::path TitleInfo::GetPath() const
{
if (!m_isValid)
{
cemu_assert_suspicious();
return {};
}
return m_fullPath;
}
void TitleInfo::CalcUID()
{
cemu_assert_debug(m_isValid);
if (!m_isValid)
{
m_uid = 0;
return;
}
// get absolute normalized path
fs::path normalizedPath;
if (m_fullPath.is_relative())
{
normalizedPath = ActiveSettings::GetUserDataPath();
normalizedPath /= m_fullPath;
}
else
normalizedPath = m_fullPath;
normalizedPath = normalizedPath.lexically_normal();
uint64 h = fs::hash_value(normalizedPath);
// for WUA files also hash the subpath
if (m_titleFormat == TitleDataFormat::WIIU_ARCHIVE)
{
uint64 subHash = std::hash<std::string_view>{}(m_subPath);
h += subHash;
}
m_uid = h;
}
uint64 TitleInfo::GetUID()
{
cemu_assert_debug(m_isValid);
return m_uid;
}
void TitleInfo::SetInvalidReason(InvalidReason reason)
{
if(m_invalidReason == InvalidReason::NONE)
m_invalidReason = reason; // only update reason when it hasn't been set before
}
std::mutex sZArchivePoolMtx;
std::map<fs::path, std::pair<uint32, ZArchiveReader*>> sZArchivePool;
ZArchiveReader* _ZArchivePool_AcquireInstance(const fs::path& path)
{
std::unique_lock _lock(sZArchivePoolMtx);
auto it = sZArchivePool.find(path);
if (it != sZArchivePool.end())
{
it->second.first++; // increment ref count
return it->second.second;
}
_lock.unlock();
// opening wua files can be expensive, so we do it outside of the lock
ZArchiveReader* zar = ZArchiveReader::OpenFromFile(path);
if (!zar)
return nullptr;
_lock.lock();
// check if another instance was allocated in the meantime
it = sZArchivePool.find(path);
if (it != sZArchivePool.end())
{
delete zar;
it->second.first++; // increment ref count
return it->second.second;
}
sZArchivePool.emplace(std::piecewise_construct,
std::forward_as_tuple(path),
std::forward_as_tuple(1, zar)
);
return zar;
}
void _ZArchivePool_ReleaseInstance(const fs::path& path, ZArchiveReader* zar)
{
std::unique_lock _lock(sZArchivePoolMtx);
auto it = sZArchivePool.find(path);
cemu_assert(it != sZArchivePool.end());
cemu_assert(it->second.second == zar);
it->second.first--; // decrement ref count
if (it->second.first == 0)
{
delete it->second.second;
sZArchivePool.erase(it);
}
}
bool TitleInfo::Mount(std::string_view virtualPath, std::string_view subfolder, sint32 mountPriority)
{
cemu_assert_debug(subfolder.empty() || (subfolder.front() != '/' || subfolder.front() != '\\')); // only relative subfolder allowed
cemu_assert(m_isValid);
if (m_titleFormat == TitleDataFormat::HOST_FS)
{
fs::path hostFSPath = m_fullPath;
hostFSPath.append(subfolder);
bool r = FSCDeviceHostFS_Mount(std::string(virtualPath).c_str(), _pathToUtf8(hostFSPath), mountPriority);
cemu_assert_debug(r);
if (!r)
{
cemuLog_log(LogType::Force, "Failed to mount {} to {}", virtualPath, subfolder);
SetInvalidReason(InvalidReason::BAD_PATH_OR_INACCESSIBLE);
return false;
}
}
else if (m_titleFormat == TitleDataFormat::WUD || m_titleFormat == TitleDataFormat::NUS)
{
FSTVolume::ErrorCode fstError;
if (m_mountpoints.empty())
{
cemu_assert_debug(!m_wudVolume);
if(m_titleFormat == TitleDataFormat::WUD)
m_wudVolume = FSTVolume::OpenFromDiscImage(m_fullPath, &fstError); // open wud/wux
else
m_wudVolume = FSTVolume::OpenFromContentFolder(m_fullPath.parent_path(), &fstError); // open from .app files directory, the path points to /title.tmd
}
if (!m_wudVolume)
{
if (fstError == FSTVolume::ErrorCode::DISC_KEY_MISSING)
SetInvalidReason(InvalidReason::NO_DISC_KEY);
else if (fstError == FSTVolume::ErrorCode::TITLE_TIK_MISSING)
SetInvalidReason(InvalidReason::NO_TITLE_TIK);
return false;
}
bool r = FSCDeviceWUD_Mount(virtualPath, subfolder, m_wudVolume, mountPriority);
cemu_assert_debug(r);
if (!r)
{
cemuLog_log(LogType::Force, "Failed to mount {} to {}", virtualPath, subfolder);
delete m_wudVolume;
return false;
}
}
else if (m_titleFormat == TitleDataFormat::WIIU_ARCHIVE)
{
if (!m_zarchive)
{
m_zarchive = _ZArchivePool_AcquireInstance(m_fullPath);
if (!m_zarchive)
return false;
}
bool r = FSCDeviceWUA_Mount(virtualPath, std::string(m_subPath).append("/").append(subfolder), m_zarchive, mountPriority);
if (!r)
{
cemuLog_log(LogType::Force, "Failed to mount {} to {}", virtualPath, subfolder);
_ZArchivePool_ReleaseInstance(m_fullPath, m_zarchive);
return false;
}
}
else if (m_titleFormat == TitleDataFormat::WUHB)
{
if (!m_wuhbreader)
{
m_wuhbreader = WUHBReader::FromPath(m_fullPath);
if (!m_wuhbreader)
return false;
}
bool r = FSCDeviceWUHB_Mount(virtualPath, subfolder, m_wuhbreader, mountPriority);
if (!r)
{
cemuLog_log(LogType::Force, "Failed to mount {} to {}", virtualPath, subfolder);
delete m_wuhbreader;
m_wuhbreader = nullptr;
return false;
}
}
else
{
cemu_assert_unimplemented();
}
m_mountpoints.emplace_back(mountPriority, virtualPath);
return true;
}
void TitleInfo::Unmount(std::string_view virtualPath)
{
for (auto& itr : m_mountpoints)
{
if (!boost::equals(itr.second, virtualPath))
continue;
fsc_unmount(itr.second.c_str(), itr.first);
std::erase(m_mountpoints, itr);
// if the last mount point got unmounted, close any open devices
if (m_mountpoints.empty())
{
if (m_wudVolume)
{
cemu_assert_debug(m_titleFormat == TitleDataFormat::WUD || m_titleFormat == TitleDataFormat::NUS);
delete m_wudVolume;
m_wudVolume = nullptr;
}
if (m_zarchive)
{
_ZArchivePool_ReleaseInstance(m_fullPath, m_zarchive);
if (m_mountpoints.empty())
m_zarchive = nullptr;
}
if (m_wuhbreader)
{
cemu_assert_debug(m_titleFormat == TitleDataFormat::WUHB);
delete m_wuhbreader;
m_wuhbreader = nullptr;
}
}
return;
}
cemu_assert_suspicious(); // unmount on unknown path
}
void TitleInfo::UnmountAll()
{
while (!m_mountpoints.empty())
Unmount(m_mountpoints.front().second);
}
std::atomic_uint64_t sTempMountingPathCounter = 1;
std::string TitleInfo::GetUniqueTempMountingPath()
{
uint64_t v = sTempMountingPathCounter.fetch_add(1);
return fmt::format("/internal/tempMount{:016x}/", v);
}
bool TitleInfo::ParseXmlInfo()
{
cemu_assert(m_isValid);
if (m_hasParsedXmlFiles)
return m_isValid;
m_hasParsedXmlFiles = true;
std::string mountPath = GetUniqueTempMountingPath();
bool r = Mount(mountPath, "", FSC_PRIORITY_BASE);
if (!r)
return false;
// meta/meta.xml
auto xmlData = fsc_extractFile(fmt::format("{}meta/meta.xml", mountPath).c_str());
if(xmlData)
m_parsedMetaXml = ParsedMetaXml::Parse(xmlData->data(), xmlData->size());
if(!m_parsedMetaXml)
{
// meta/meta.ini (WUHB)
auto iniData = fsc_extractFile(fmt::format("{}meta/meta.ini", mountPath).c_str());
if (iniData)
m_parsedMetaXml = ParseAromaIni(*iniData);
if(m_parsedMetaXml)
{
m_parsedCosXml = new ParsedCosXml{.argstr = "root.rpx"};
m_parsedAppXml = new ParsedAppXml{m_parsedMetaXml->m_title_id, 0, 0, 0, 0};
}
}
// code/app.xml
xmlData = fsc_extractFile(fmt::format("{}code/app.xml", mountPath).c_str());
if(xmlData)
ParseAppXml(*xmlData);
// code/cos.xml
xmlData = fsc_extractFile(fmt::format("{}code/cos.xml", mountPath).c_str());
if (xmlData)
m_parsedCosXml = ParsedCosXml::Parse(xmlData->data(), xmlData->size());
Unmount(mountPath);
// some system titles dont have a meta.xml file
bool allowMissingMetaXml = false;
if(m_parsedAppXml && this->IsSystemDataTitle())
{
allowMissingMetaXml = true;
}
if ((allowMissingMetaXml == false && !m_parsedMetaXml) || !m_parsedAppXml || !m_parsedCosXml)
{
bool hasAnyXml = m_parsedMetaXml || m_parsedAppXml || m_parsedCosXml;
if (hasAnyXml)
cemuLog_log(LogType::Force, "Title has missing meta .xml files. Title path: {}", _pathToUtf8(m_fullPath));
delete m_parsedMetaXml;
delete m_parsedAppXml;
delete m_parsedCosXml;
m_parsedMetaXml = nullptr;
m_parsedAppXml = nullptr;
m_parsedCosXml = nullptr;
m_isValid = false;
SetInvalidReason(InvalidReason::MISSING_XML_FILES);
return false;
}
m_isValid = true;
return true;
}
ParsedMetaXml* TitleInfo::ParseAromaIni(std::span<unsigned char> content)
{
IniParser parser{content};
while (parser.NextSection() && parser.GetCurrentSectionName() != "menu")
continue;
if (parser.GetCurrentSectionName() != "menu")
return nullptr;
auto parsed = std::make_unique<ParsedMetaXml>();
const auto author = parser.FindOption("author");
if (author)
parsed->m_publisher[(size_t)CafeConsoleLanguage::EN] = *author;
const auto longName = parser.FindOption("longname");
if (longName)
parsed->m_long_name[(size_t)CafeConsoleLanguage::EN] = *longName;
const auto shortName = parser.FindOption("shortname");
if (shortName)
parsed->m_short_name[(size_t)CafeConsoleLanguage::EN] = *shortName;
auto checksumInput = std::string{*author}.append(*longName).append(*shortName);
parsed->m_title_id = (0x0005000Full<<32) | crc32_calc(checksumInput.data(), checksumInput.length());
return parsed.release();
}
bool TitleInfo::ParseAppXml(std::vector<uint8>& appXmlData)
{
pugi::xml_document app_doc;
if (!app_doc.load_buffer_inplace(appXmlData.data(), appXmlData.size()))
return false;
const auto root = app_doc.child("app");
if (!root)
return false;
m_parsedAppXml = new ParsedAppXml();
for (const auto& child : root.children())
{
std::string_view name = child.name();
if (name == "title_version")
m_parsedAppXml->title_version = (uint16)std::stoull(child.text().as_string(), nullptr, 16);
else if (name == "title_id")
m_parsedAppXml->title_id = std::stoull(child.text().as_string(), nullptr, 16);
else if (name == "app_type")
m_parsedAppXml->app_type = (uint32)std::stoull(child.text().as_string(), nullptr, 16);
else if (name == "group_id")
m_parsedAppXml->group_id = (uint32)std::stoull(child.text().as_string(), nullptr, 16);
else if (name == "sdk_version")
m_parsedAppXml->sdk_version = (uint32)std::stoull(child.text().as_string(), nullptr, 10);
}
return true;
}
TitleId TitleInfo::GetAppTitleId() const
{
cemu_assert_debug(m_isValid);
if (m_parsedAppXml)
return m_parsedAppXml->title_id;
if (m_cachedInfo)
return m_cachedInfo->titleId;
cemu_assert_suspicious();
return 0;
}
uint16 TitleInfo::GetAppTitleVersion() const
{
cemu_assert_debug(m_isValid);
if (m_parsedAppXml)
return m_parsedAppXml->title_version;
if (m_cachedInfo)
return m_cachedInfo->titleVersion;
cemu_assert_suspicious();
return 0;
}
uint32 TitleInfo::GetAppSDKVersion() const
{
cemu_assert_debug(m_isValid);
if (m_parsedAppXml)
return m_parsedAppXml->sdk_version;
if (m_cachedInfo)
return m_cachedInfo->sdkVersion;
cemu_assert_suspicious();
return 0;
}
uint32 TitleInfo::GetAppGroup() const
{
cemu_assert_debug(m_isValid);
if (m_parsedAppXml)
return m_parsedAppXml->group_id;
if (m_cachedInfo)
return m_cachedInfo->group_id;
cemu_assert_suspicious();
return 0;
}
uint32 TitleInfo::GetAppType() const
{
cemu_assert_debug(m_isValid);
if (m_parsedAppXml)
return m_parsedAppXml->app_type;
if (m_cachedInfo)
return m_cachedInfo->app_type;
cemu_assert_suspicious();
return 0;
}
TitleIdParser::TITLE_TYPE TitleInfo::GetTitleType()
{
TitleIdParser tip(GetAppTitleId());
return tip.GetType();
}
std::string TitleInfo::GetMetaTitleName() const
{
cemu_assert_debug(m_isValid);
if (m_parsedMetaXml)
{
std::string titleNameCfgLanguage;
titleNameCfgLanguage = m_parsedMetaXml->GetLongName(GetConfig().console_language);
if (titleNameCfgLanguage.empty()) //Get English Title
titleNameCfgLanguage = m_parsedMetaXml->GetLongName(CafeConsoleLanguage::EN);
if (titleNameCfgLanguage.empty()) //Unknown Title
titleNameCfgLanguage = "Unknown Title";
return titleNameCfgLanguage;
}
if (m_cachedInfo)
return m_cachedInfo->titleName;
return "";
}
CafeConsoleRegion TitleInfo::GetMetaRegion() const
{
cemu_assert_debug(m_isValid);
if (m_parsedMetaXml)
return m_parsedMetaXml->GetRegion();
if (m_cachedInfo)
return m_cachedInfo->region;
return CafeConsoleRegion::JPN;
}
uint32 TitleInfo::GetOlvAccesskey() const
{
cemu_assert_debug(m_isValid);
if (m_parsedMetaXml)
return m_parsedMetaXml->GetOlvAccesskey();
cemu_assert_suspicious();
return -1;
}
std::string TitleInfo::GetArgStr() const
{
cemu_assert_debug(m_parsedCosXml);
if (!m_parsedCosXml)
return "";
return m_parsedCosXml->argstr;
}
std::string TitleInfo::GetPrintPath() const
{
if (!m_isValid)
return "invalid";
std::string tmp;
tmp.append(_pathToUtf8(m_fullPath));
switch (m_titleFormat)
{
case TitleDataFormat::HOST_FS:
tmp.append(" [Folder]");
break;
case TitleDataFormat::WUD:
tmp.append(" [WUD]");
break;
case TitleDataFormat::NUS:
tmp.append(" [NUS]");
break;
case TitleDataFormat::WIIU_ARCHIVE:
tmp.append(" [WUA]");
break;
case TitleDataFormat::WUHB:
tmp.append(" [WUHB]");
break;
default:
break;
}
if (m_titleFormat == TitleDataFormat::WIIU_ARCHIVE)
tmp.append(fmt::format(" [{}]", m_subPath));
return tmp;
}
std::string TitleInfo::GetInstallPath() const
{
TitleId titleId = GetAppTitleId();
TitleIdParser tip(titleId);
std::string tmp;
if (tip.IsSystemTitle())
tmp = fmt::format("sys/title/{:08x}/{:08x}", GetTitleIdHigh(titleId), GetTitleIdLow(titleId));
else
tmp = fmt::format("usr/title/{:08x}/{:08x}", GetTitleIdHigh(titleId), GetTitleIdLow(titleId));
return tmp;
}
ParsedCosXml* ParsedCosXml::Parse(uint8* xmlData, size_t xmlLen)
{
pugi::xml_document app_doc;
if (!app_doc.load_buffer_inplace(xmlData, xmlLen))
return nullptr;
const auto root = app_doc.child("app");
if (!root)
return nullptr;
ParsedCosXml* parsedCos = new ParsedCosXml();
auto node = root.child("argstr");
if (node)
parsedCos->argstr = node.text().as_string();
// parse permissions
auto permissionsNode = root.child("permissions");
for(uint32 permissionIndex = 0; permissionIndex < 19; ++permissionIndex)
{
std::string permissionName = fmt::format("p{}", permissionIndex);
auto permissionNode = permissionsNode.child(permissionName.c_str());
if (!permissionNode)
break;
parsedCos->permissions[permissionIndex].group = static_cast<CosCapabilityGroup>(ConvertString<uint32>(permissionNode.child("group").text().as_string(), 10));
parsedCos->permissions[permissionIndex].mask = static_cast<CosCapabilityBits>(ConvertString<uint64>(permissionNode.child("mask").text().as_string(), 16));
}
return parsedCos;
}
| 23,079
|
C++
|
.cpp
| 770
| 27.254545
| 159
| 0.720192
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,172
|
iosu_mcp.cpp
|
cemu-project_Cemu/src/Cafe/IOSU/legacy/iosu_mcp.cpp
|
#include "iosu_ioctl.h"
#include "iosu_mcp.h"
#include "Cafe/OS/libs/nn_common.h"
#include "util/tinyxml2/tinyxml2.h"
#include "config/CemuConfig.h"
#include "Cafe/TitleList/GameInfo.h"
#include "util/helpers/helpers.h"
#include "Cafe/TitleList/TitleList.h"
#include "Cafe/CafeSystem.h"
#include "Cafe/IOSU/iosu_ipc_common.h"
#include "Cafe/IOSU/kernel/iosu_kernel.h"
using namespace iosu::kernel;
namespace iosu
{
struct
{
bool isInitialized;
}iosuMcp = { 0 };
std::recursive_mutex sTitleInfoMutex;
bool sHasAllTitlesMounted = false;
uint32 mcpBuildTitleList(MCPTitleInfo* titleList, uint32 maxTitlesToCopy, std::function<bool(const TitleInfo&)> filterFunc)
{
CafeTitleList::WaitForMandatoryScan();
std::set<TitleId> titleIdsVisited;
auto cafeTitleList = CafeTitleList::AcquireInternalList();
uint32 numTitlesCopied = 0;
for (auto& it : cafeTitleList)
{
if (numTitlesCopied == maxTitlesToCopy)
break;
uint64 titleId = it->GetAppTitleId();
if (titleIdsVisited.find(titleId) != titleIdsVisited.end())
continue;
if (!filterFunc(*it))
continue;
titleIdsVisited.emplace(titleId);
if (titleList)
{
auto& titleOut = titleList[numTitlesCopied];
titleOut.titleIdHigh = (uint32)(titleId >> 32);
titleOut.titleIdLow = (uint32)(titleId & 0xFFFFFFFF);
titleOut.titleVersion = it->GetAppTitleVersion();
titleOut.appGroup = it->GetAppGroup();
titleOut.appType = it->GetAppType();
std::string titlePath = CafeSystem::GetMlcStoragePath(titleId);
strcpy(titleOut.appPath, titlePath.c_str());
strcpy((char*)titleOut.deviceName, "mlc");
titleOut.osVersion = 0; // todo
titleOut.sdkVersion = it->GetAppSDKVersion();
}
numTitlesCopied++;
}
CafeTitleList::ReleaseInternalList();
if (!sHasAllTitlesMounted)
{
CafeSystem::MlcStorageMountAllTitles();
sHasAllTitlesMounted = true;
}
return numTitlesCopied;
}
sint32 mcpGetTitleList(MCPTitleInfo* titleList, uint32 titleListBufferSize, uint32be* titleCount)
{
std::unique_lock _lock(sTitleInfoMutex);
uint32 maxEntryCount = titleListBufferSize / sizeof(MCPTitleInfo);
*titleCount = mcpBuildTitleList(titleList, maxEntryCount, [](const TitleInfo& titleInfo) -> bool { return true; });
return 0;
}
sint32 mcpGetTitleCount()
{
std::unique_lock _lock(sTitleInfoMutex);
return mcpBuildTitleList(nullptr, 0xFFFFFFFF, [](const TitleInfo& titleInfo) -> bool { return true; });
}
sint32 mcpGetTitleListByAppType(MCPTitleInfo* titleList, uint32 titleListBufferSize, uint32be* titleCount, uint32 appType)
{
std::unique_lock _lock(sTitleInfoMutex);
uint32 maxEntryCount = titleListBufferSize / sizeof(MCPTitleInfo);
*titleCount = mcpBuildTitleList(titleList, maxEntryCount, [appType](const TitleInfo& titleInfo) -> bool { return titleInfo.GetAppType() == appType; });
return 0;
}
sint32 mcpGetTitleListByTitleId(MCPTitleInfo* titleList, uint32 titleListBufferSize, uint32be* titleCount, uint64 titleId)
{
std::unique_lock _lock(sTitleInfoMutex);
uint32 maxEntryCount = titleListBufferSize / sizeof(MCPTitleInfo);
*titleCount = mcpBuildTitleList(titleList, maxEntryCount, [titleId](const TitleInfo& titleInfo) -> bool { return titleInfo.GetAppTitleId() == titleId; });
return 0;
}
int iosuMcp_thread()
{
SetThreadName("iosuMcp_thread");
while (true)
{
uint32 returnValue = 0; // Ioctl return value
ioQueueEntry_t* ioQueueEntry = iosuIoctl_getNextWithWait(IOS_DEVICE_MCP);
if (ioQueueEntry->request == IOSU_MCP_REQUEST_CEMU)
{
iosuMcpCemuRequest_t* mcpCemuRequest = (iosuMcpCemuRequest_t*)ioQueueEntry->bufferVectors[0].buffer.GetPtr();
if (mcpCemuRequest->requestCode == IOSU_MCP_GET_TITLE_LIST)
{
uint32be titleCount = mcpCemuRequest->titleListRequest.titleCount;
mcpCemuRequest->returnCode = mcpGetTitleList(mcpCemuRequest->titleListRequest.titleList.GetPtr(), mcpCemuRequest->titleListRequest.titleListBufferSize, &titleCount);
mcpCemuRequest->titleListRequest.titleCount = titleCount;
}
else if (mcpCemuRequest->requestCode == IOSU_MCP_GET_TITLE_LIST_BY_APP_TYPE)
{
uint32be titleCount = mcpCemuRequest->titleListRequest.titleCount;
mcpCemuRequest->returnCode = mcpGetTitleListByAppType(mcpCemuRequest->titleListRequest.titleList.GetPtr(), mcpCemuRequest->titleListRequest.titleListBufferSize, &titleCount, mcpCemuRequest->titleListRequest.appType);
mcpCemuRequest->titleListRequest.titleCount = titleCount;
}
else if (mcpCemuRequest->requestCode == IOSU_MCP_GET_TITLE_INFO)
{
uint32be titleCount = mcpCemuRequest->titleListRequest.titleCount;
mcpCemuRequest->returnCode = mcpGetTitleListByTitleId(mcpCemuRequest->titleListRequest.titleList.GetPtr(), mcpCemuRequest->titleListRequest.titleListBufferSize, &titleCount, mcpCemuRequest->titleListRequest.titleId);
mcpCemuRequest->titleListRequest.titleCount = titleCount;
}
else if (mcpCemuRequest->requestCode == IOSU_MCP_GET_TITLE_COUNT)
{
uint32be titleCount = mcpGetTitleCount();
mcpCemuRequest->returnCode = titleCount;
mcpCemuRequest->titleListRequest.titleCount = titleCount;
}
else
assert_dbg();
}
else
assert_dbg();
iosuIoctl_completeRequest(ioQueueEntry, returnValue);
}
return 0;
}
// deprecated
void iosuMcp_init()
{
if (iosuMcp.isInitialized)
return;
std::thread t(iosuMcp_thread);
t.detach();
iosuMcp.isInitialized = true;
}
namespace mcp
{
IOSMsgQueueId sMCPIoMsgQueue;
SysAllocator<iosu::kernel::IOSMessage, 352> _m_sMCPIoMsgQueueMsgBuffer;
std::thread sMCPIoThread;
struct MCPClient
{
std::string workingDirectory;
bool isAllocated{ false };
void AllocateAndInitialize()
{
isAllocated = true;
workingDirectory = std::string("/");
}
void ReleaseAndCleanup()
{
isAllocated = false;
}
};
std::array<MCPClient, 256> sMCPClientArray;
IOS_ERROR MCPAllocateClient(sint32& indexOut)
{
for (size_t i = 0; i < sMCPClientArray.size(); i++)
{
if (sMCPClientArray[i].isAllocated)
continue;
sMCPClientArray[i].AllocateAndInitialize();
indexOut = (sint32)i;
return IOS_ERROR_OK;
}
return IOS_ERROR::IOS_ERROR_MAXIMUM_REACHED;
}
void MCPIoThread()
{
SetThreadName("IOSU-MCP");
IOSMessage msg;
while (true)
{
IOS_ERROR r = IOS_ReceiveMessage(sMCPIoMsgQueue, &msg, 0);
cemu_assert(!IOS_ResultIsError(r));
if (msg == 0)
return; // shutdown signaled
IPCCommandBody* cmd = MEMPTR<IPCCommandBody>(msg).GetPtr();
uint32 clientHandle = (uint32)cmd->devHandle;
if (cmd->cmdId == IPCCommandId::IOS_OPEN)
{
sint32 clientIndex = 0;
r = MCPAllocateClient(clientIndex);
if (r != IOS_ERROR_OK)
{
IOS_ResourceReply(cmd, r);
continue;
}
IOS_ResourceReply(cmd, (IOS_ERROR)clientIndex);
continue;
}
else if (cmd->cmdId == IPCCommandId::IOS_CLOSE)
{
cemu_assert(clientHandle < sMCPClientArray.size());
sMCPClientArray[clientHandle].ReleaseAndCleanup();
IOS_ResourceReply(cmd, IOS_ERROR_OK);
continue;
}
else if (cmd->cmdId == IPCCommandId::IOS_IOCTL)
{
cemu_assert(clientHandle < sMCPClientArray.size());
cemu_assert(sMCPClientArray[clientHandle].isAllocated);
IOS_ResourceReply(cmd, (IOS_ERROR)0x80000000);
continue;
}
else if (cmd->cmdId == IPCCommandId::IOS_IOCTLV)
{
cemu_assert_unimplemented();
//uint32 requestId = cmd->args[0];
//uint32 numIn = cmd->args[1];
//uint32 numOut = cmd->args[2];
//IPCIoctlVector* vec = MEMPTR<IPCIoctlVector>{ cmd->args[3] }.GetPtr();
IOS_ResourceReply(cmd, IOS_ERROR_INVALID);
continue;
}
else
{
cemuLog_log(LogType::Force, "/dev/mcp: Unsupported IPC cmdId");
cemu_assert_suspicious();
IOS_ResourceReply(cmd, IOS_ERROR_INVALID);
}
}
}
void Init()
{
for (auto& it : sMCPClientArray)
it.ReleaseAndCleanup();
sMCPIoMsgQueue = (IOSMsgQueueId)IOS_CreateMessageQueue(_m_sMCPIoMsgQueueMsgBuffer.GetPtr(), _m_sMCPIoMsgQueueMsgBuffer.GetCount());
IOS_ERROR r = IOS_RegisterResourceManager("/dev/mcp", sMCPIoMsgQueue);
IOS_DeviceAssociateId("/dev/mcp", 11);
cemu_assert(!IOS_ResultIsError(r));
sMCPIoThread = std::thread(MCPIoThread);
}
void Shutdown()
{
IOS_SendMessage(sMCPIoMsgQueue, 0, 0);
sMCPIoThread.join();
}
};
}
| 8,434
|
C++
|
.cpp
| 243
| 30.650206
| 221
| 0.731594
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,173
|
iosu_ioctl.cpp
|
cemu-project_Cemu/src/Cafe/IOSU/legacy/iosu_ioctl.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "iosu_ioctl.h"
#include "util/helpers/ringbuffer.h"
#include "util/helpers/Semaphore.h"
// deprecated IOCTL handling code
RingBuffer<ioQueueEntry_t*, 256> _ioctlRingbuffer[IOS_DEVICE_COUNT];
CounterSemaphore _ioctlRingbufferSemaphore[IOS_DEVICE_COUNT];
std::mutex ioctlMutex;
sint32 iosuIoctl_pushAndWait(uint32 ioctlHandle, ioQueueEntry_t* ioQueueEntry)
{
if (ioctlHandle != IOS_DEVICE_ACT && ioctlHandle != IOS_DEVICE_ACP_MAIN && ioctlHandle != IOS_DEVICE_MCP && ioctlHandle != IOS_DEVICE_BOSS && ioctlHandle != IOS_DEVICE_NIM && ioctlHandle != IOS_DEVICE_FPD)
{
cemuLog_logDebug(LogType::Force, "Unsupported IOSU device {}", ioctlHandle);
cemu_assert_debug(false);
return 0;
}
__OSLockScheduler();
ioctlMutex.lock();
ioQueueEntry->ppcThread = coreinit::OSGetCurrentThread();
_ioctlRingbuffer[ioctlHandle].Push(ioQueueEntry);
ioctlMutex.unlock();
_ioctlRingbufferSemaphore[ioctlHandle].increment();
coreinit::__OSSuspendThreadInternal(coreinit::OSGetCurrentThread());
if (ioQueueEntry->isCompleted == false)
assert_dbg();
__OSUnlockScheduler();
return ioQueueEntry->returnValue;
}
ioQueueEntry_t* iosuIoctl_getNextWithWait(uint32 deviceIndex)
{
_ioctlRingbufferSemaphore[deviceIndex].decrementWithWait();
if (_ioctlRingbuffer[deviceIndex].HasData() == false)
assert_dbg();
return _ioctlRingbuffer[deviceIndex].Pop();
}
ioQueueEntry_t* iosuIoctl_getNextWithTimeout(uint32 deviceIndex, sint32 ms)
{
if (!_ioctlRingbufferSemaphore[deviceIndex].decrementWithWaitAndTimeout(ms))
return nullptr; // timeout or spurious wake up
if (_ioctlRingbuffer[deviceIndex].HasData() == false)
return nullptr;
return _ioctlRingbuffer[deviceIndex].Pop();
}
void iosuIoctl_completeRequest(ioQueueEntry_t* ioQueueEntry, uint32 returnValue)
{
ioQueueEntry->returnValue = returnValue;
ioQueueEntry->isCompleted = true;
coreinit::OSResumeThread(ioQueueEntry->ppcThread);
}
void iosuIoctl_init()
{
for (sint32 i = 0; i < IOS_DEVICE_COUNT; i++)
{
_ioctlRingbuffer[i].Clear();
}
}
| 2,104
|
C++
|
.cpp
| 57
| 35
| 206
| 0.785363
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,174
|
iosu_nim.cpp
|
cemu-project_Cemu/src/Cafe/IOSU/legacy/iosu_nim.cpp
|
#include "iosu_nim.h"
#include "iosu_ioctl.h"
#include "iosu_act.h"
#include "iosu_mcp.h"
#include "util/crypto/aes128.h"
#include "curl/curl.h"
#include "openssl/bn.h"
#include "openssl/x509.h"
#include "openssl/ssl.h"
#include "util/helpers/helpers.h"
#include "Cemu/napi/napi.h"
#include "Cemu/ncrypto/ncrypto.h"
#include "Cafe/CafeSystem.h"
namespace iosu
{
namespace nim
{
struct NIMTitleLatestVersion
{
uint64 titleId;
uint32 version;
};
#define PACKAGE_TYPE_UPDATE (1)
struct NIMPackage
{
uint64 titleId;
uint16 version;
uint8 type;
};
struct
{
bool isInitialized;
// version list
sint32 latestVersion;
char fqdn[256];
std::vector<NIMTitleLatestVersion> titlesLatestVersion;
// nim packages
// note: Seems like scope.rpx expects the number of packages to never change after the initial GetNum call?
std::vector<NIMPackage*> packages;
bool packageListReady;
bool backgroundThreadStarted;
} g_nim = {};
bool nim_CheckDownloadsDisabled()
{
// currently for the Wii U menu we disable NIM to speed up boot times
uint64 tid = CafeSystem::GetForegroundTitleId();
return tid == 0x0005001010040000 || tid == 0x0005001010040100 || tid == 0x0005001010040200;
}
bool nim_getLatestVersion()
{
g_nim.latestVersion = -1;
NAPI::AuthInfo authInfo;
authInfo.country = NCrypto::GetCountryAsString(Account::GetCurrentAccount().GetCountry());
authInfo.region = NCrypto::SEEPROM_GetRegion();
auto versionListVersionResult = NAPI::TAG_GetVersionListVersion(authInfo);
if (!versionListVersionResult.isValid)
return false;
if (versionListVersionResult.fqdnURL.size() >= 256)
{
cemuLog_log(LogType::Force, "NIM: fqdn URL too long");
return false;
}
g_nim.latestVersion = (sint32)versionListVersionResult.version;
strcpy(g_nim.fqdn, versionListVersionResult.fqdnURL.c_str());
return true;
}
bool nim_getVersionList()
{
g_nim.titlesLatestVersion.clear();
NAPI::AuthInfo authInfo;
authInfo.country = NCrypto::GetCountryAsString(Account::GetCurrentAccount().GetCountry());
authInfo.region = NCrypto::SEEPROM_GetRegion();
auto versionListVersionResult = NAPI::TAG_GetVersionListVersion(authInfo);
if (!versionListVersionResult.isValid)
return false;
auto versionListResult = TAG_GetVersionList(authInfo, versionListVersionResult.fqdnURL, versionListVersionResult.version);
if (!versionListResult.isValid)
return false;
for (auto& itr : versionListResult.titleVersionList)
{
NIMTitleLatestVersion titleLatestVersion;
titleLatestVersion.titleId = itr.first;
titleLatestVersion.version = itr.second;
g_nim.titlesLatestVersion.push_back(titleLatestVersion);
}
return true;
}
NIMTitleLatestVersion* nim_findTitleLatestVersion(uint64 titleId)
{
for (auto& titleLatestVersion : g_nim.titlesLatestVersion)
{
if (titleLatestVersion.titleId == titleId)
return &titleLatestVersion;
}
return nullptr;
}
void nim_buildDownloadList()
{
if(nim_CheckDownloadsDisabled())
{
cemuLog_logDebug(LogType::Force, "nim_buildDownloadList: Downloads are disabled for this title");
g_nim.packages.clear();
return;
}
sint32 titleCount = mcpGetTitleCount();
MCPTitleInfo* titleList = (MCPTitleInfo*)malloc(titleCount * sizeof(MCPTitleInfo));
memset(titleList, 0, titleCount * sizeof(MCPTitleInfo));
uint32be titleCountBE = titleCount;
if (mcpGetTitleList(titleList, titleCount * sizeof(MCPTitleInfo), &titleCountBE) != 0)
{
cemuLog_log(LogType::Force, "IOSU: nim failed to acquire title list");
free(titleList);
return;
}
titleCount = titleCountBE;
// check for game updates
for (sint32 i = 0; i < titleCount; i++)
{
if( titleList[i].titleIdHigh != 0x00050000 )
continue;
// find update title in title version list
uint64 titleId = (0x0005000EULL << 32) | ((uint64)(uint32)titleList[i].titleIdLow);
NIMTitleLatestVersion* latestVersionInfo = nim_findTitleLatestVersion(titleId);
if(latestVersionInfo == nullptr)
continue;
// compare version
if(latestVersionInfo->version <= (uint32)titleList[i].titleVersion )
continue; // already on latest version
// add to packages
NIMPackage* nimPackage = (NIMPackage*)malloc(sizeof(NIMPackage));
memset(nimPackage, 0, sizeof(NIMPackage));
nimPackage->titleId = titleId;
nimPackage->type = PACKAGE_TYPE_UPDATE;
g_nim.packages.push_back(nimPackage);
}
// check for AOC/titles to download
// todo
free(titleList);
}
void nim_getPackagesInfo(uint64* titleIdList, sint32 count, titlePackageInfo_t* packageInfoList)
{
memset(packageInfoList, 0, sizeof(titlePackageInfo_t)*count);
if(nim_CheckDownloadsDisabled())
return;
for (sint32 i = 0; i < count; i++)
{
uint64 titleId = _swapEndianU64(titleIdList[i]);
titlePackageInfo_t* packageInfo = packageInfoList + i;
packageInfo->titleId = _swapEndianU64(titleIdList[0]);
packageInfo->ukn0C = 1; // update
// pending
packageInfo->ukn48 = 0; // with 0 there is no progress bar, with 3 there is a progress bar
packageInfo->ukn40 = (5 << 20) | (0 << 27) | (1<<31) | (0x30000<<0);
packageInfo->ukn0F = 1;
}
}
struct idbeIconCacheEntry_t
{
void setIconData(NAPI::IDBEIconDataV0& newIconData)
{
iconData = newIconData;
hasIconData = true;
}
void setNoIcon()
{
hasIconData = false;
iconData = {};
}
uint64 titleId;
uint32 lastRequestTime;
bool hasIconData{ false };
NAPI::IDBEIconDataV0 iconData{};
};
std::vector<idbeIconCacheEntry_t> idbeIconCache;
void idbe_addIconToCache(uint64 titleId, NAPI::IDBEIconDataV0* iconData)
{
idbeIconCacheEntry_t newCacheEntry;
newCacheEntry.titleId = titleId;
newCacheEntry.lastRequestTime = GetTickCount();
if (iconData)
newCacheEntry.setIconData(*iconData);
else
newCacheEntry.setNoIcon();
idbeIconCache.push_back(newCacheEntry);
}
sint32 nim_getIconDatabaseEntry(uint64 titleId, void* idbeIconOutput)
{
// if titleId is an update, replace it with gameId instead
if ((uint32)(titleId >> 32) == 0x0005000EULL)
{
titleId &= ~0xF00000000ULL;
}
for (auto& entry : idbeIconCache)
{
if (entry.titleId == titleId)
{
if( entry.hasIconData )
memcpy(idbeIconOutput, &entry.iconData, sizeof(NAPI::IDBEIconDataV0));
else
memset(idbeIconOutput, 0, sizeof(NAPI::IDBEIconDataV0));
return 0;
}
}
auto result = NAPI::IDBE_Request(ActiveSettings::GetNetworkService(), titleId);
if (!result)
{
memset(idbeIconOutput, 0, sizeof(NAPI::IDBEIconDataV0));
cemuLog_log(LogType::Force, "NIM: Unable to download IDBE icon");
return 0;
}
// add new cache entry
idbe_addIconToCache(titleId, &*result);
// return result
memcpy(idbeIconOutput, &*result, sizeof(NAPI::IDBEIconDataV0));
return 0;
}
void nim_backgroundThread()
{
while (iosuAct_isAccountDataLoaded() == false)
{
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
if (nim_getLatestVersion())
{
if (nim_getVersionList())
{
nim_buildDownloadList();
}
}
g_nim.packageListReady = true;
}
void iosuNim_waitUntilPackageListReady()
{
if (g_nim.backgroundThreadStarted == false)
{
cemuLog_log(LogType::Force, "IOSU: Starting nim background thread");
std::thread t(nim_backgroundThread);
t.detach();
g_nim.backgroundThreadStarted = true;
}
while (g_nim.packageListReady == false)
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
void iosuNim_thread()
{
SetThreadName("iosuNim_thread");
while (true)
{
uint32 returnValue = 0; // Ioctl return value
ioQueueEntry_t* ioQueueEntry = iosuIoctl_getNextWithWait(IOS_DEVICE_NIM);
if (ioQueueEntry->request == IOSU_NIM_REQUEST_CEMU)
{
iosuNimCemuRequest_t* nimCemuRequest = (iosuNimCemuRequest_t*)ioQueueEntry->bufferVectors[0].buffer.GetPtr();
if (nimCemuRequest->requestCode == IOSU_NIM_GET_ICON_DATABASE_ENTRY)
{
nimCemuRequest->returnCode = nim_getIconDatabaseEntry(nimCemuRequest->titleId, nimCemuRequest->ptr.GetPtr());
}
else if (nimCemuRequest->requestCode == IOSU_NIM_GET_PACKAGE_COUNT)
{
iosuNim_waitUntilPackageListReady();
nimCemuRequest->resultU32.u32 = (uint32)g_nim.packages.size();
nimCemuRequest->returnCode = 0;
}
else if (nimCemuRequest->requestCode == IOSU_NIM_GET_PACKAGES_TITLEID)
{
iosuNim_waitUntilPackageListReady();
uint32 maxCount = nimCemuRequest->maxCount;
uint64* titleIdList = (uint64*)nimCemuRequest->ptr.GetPtr();
uint32 count = 0;
memset(titleIdList, 0, sizeof(uint64) * maxCount);
for (auto& package : g_nim.packages)
{
titleIdList[count] = _swapEndianU64(package->titleId);
count++;
if (count >= maxCount)
break;
}
nimCemuRequest->returnCode = 0;
}
else if (nimCemuRequest->requestCode == IOSU_NIM_GET_PACKAGES_INFO)
{
iosuNim_waitUntilPackageListReady();
uint32 maxCount = nimCemuRequest->maxCount;
uint64* titleIdList = (uint64*)nimCemuRequest->ptr.GetPtr();
titlePackageInfo_t* packageInfo = (titlePackageInfo_t*)nimCemuRequest->ptr2.GetPtr();
nim_getPackagesInfo(titleIdList, maxCount, packageInfo);
nimCemuRequest->returnCode = 0;
}
else
cemu_assert_unimplemented();
}
else
cemu_assert_unimplemented();
iosuIoctl_completeRequest(ioQueueEntry, returnValue);
}
return;
}
void Initialize()
{
if (g_nim.isInitialized)
return;
std::vector<idbeIconCacheEntry_t> idbeIconCache = std::vector<idbeIconCacheEntry_t>();
g_nim.titlesLatestVersion = std::vector<NIMTitleLatestVersion>();
g_nim.packages = std::vector<NIMPackage*>();
g_nim.packageListReady = false;
g_nim.backgroundThreadStarted = false;
std::thread t2(iosuNim_thread);
t2.detach();
g_nim.isInitialized = true;
}
}
}
| 10,117
|
C++
|
.cpp
| 312
| 28.022436
| 125
| 0.712487
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,175
|
iosu_boss.cpp
|
cemu-project_Cemu/src/Cafe/IOSU/legacy/iosu_boss.cpp
|
#include "iosu_boss.h"
#include <sstream>
#include <iomanip>
#include <thread>
#include <algorithm>
#include <array>
#include <queue>
#include <filesystem>
#include <fstream>
#include "config/ActiveSettings.h"
#include "config/NetworkSettings.h"
#include "curl/curl.h"
#include "openssl/bn.h"
#include "openssl/x509.h"
#include "openssl/ssl.h"
#include "iosu_ioctl.h"
#include "Cafe/OS/libs/nn_common.h"
#include "iosu_act.h"
#include "iosu_crypto.h"
#include "util/crypto/aes128.h"
#include "config/CemuConfig.h"
#include "util/helpers/helpers.h"
#include "Cemu/ncrypto/ncrypto.h"
#include "Cafe/CafeSystem.h"
namespace iosu
{
enum TurnState
{
kUnknown = 0,
kStopped = 1,
kStoppedByPolicyList = 2,
kWaitTime = 3,
kWaitRun = 4,
kWaitResume = 5,
kRunning = 6,
kFinished = 7,
kSuccess = 16,
kError = 17,
};
enum class ContentType
{
kUnknownContent,
kXmlContent,
kBinaryFile,
kText,
};
enum class FileType
{
kUnknownFile,
kAppData,
};
enum TaskSettingType : uint32
{
kRawDlTaskSetting = 0x10000698,
};
struct TaskFile
{
TaskFile(std::string file_name, uint32 data_id, FileType type, std::string url, uint32 size)
: file_name(file_name), data_id(data_id), file_type(type), url(url), size(size) {}
std::string file_name;
uint32 data_id;
FileType file_type;
std::string url;
uint32 size;
uint64 last_modified = 0;
};
struct TaskSetting
{
static const uint32 kBossCode = 0x7C0;
static const uint32 kBossCodeLen = 0x20;
static const uint32 kURL = 0x48;
static const uint32 kURLLen = 0x100;
static const uint32 kClientCert = 0x41;
static const uint32 kCACert = 0x188;
static const uint32 kServiceToken = 0x590;
static const uint32 kServiceTokenLen = 0x200;
static const uint32 kDirectorySizeLimit = 0x7F0;
static const uint32 kDirectoryName = 0x7C8;
static const uint32 kDirectoryNameLen = 0x8;
static const uint32 kFileName = 0x7D0;
static const uint32 kNbdlFileName = 0x7F8;
static const uint32 kFileNameLen = 0x20;
std::array<uint8, 0x1000> settings;
uint32be taskType; // +0x1000
};
static_assert(sizeof(TaskSetting) == 0x1004, "sizeof(TaskSetting_t)");
struct Task
{
char task_id[8]{};
uint32 account_id;
uint64 title_id;
TaskSetting task_settings;
uint32 exec_count = 0;
std::shared_ptr<CURL> curl;
uint64 content_length = 0;
uint64 processed_length = 0;
uint32 turn_state = 0;
uint32 wait_state = 0;
long http_status_code = 0;
ContentType content_type = ContentType::kUnknownContent;
std::vector<uint8> result_buffer;
std::queue<TaskFile> queued_files;
std::vector<uint8> file_buffer;
uint32 processed_file_size = 0;
Task(const char* id, uint32 account_id, uint64 title_id, TaskSetting* settings)
{
strncpy(task_id, id, sizeof(task_id));
this->account_id = account_id;
this->title_id = title_id;
this->task_settings.settings = settings->settings;
this->task_settings.taskType = settings->taskType;
curl = std::shared_ptr<CURL>(curl_easy_init(), curl_easy_cleanup);
if(GetConfig().proxy_server.GetValue() != "")
{
curl_easy_setopt(curl.get(), CURLOPT_PROXY, GetConfig().proxy_server.GetValue().c_str());
}
}
};
#define FAD_ENTRY_MAX_COUNT (512)
struct BossStorageFadEntry
{
char name[0x20];
uint32be fileNameId;
uint32 ukn24;
uint32 ukn28;
uint32 ukn2C;
uint32 ukn30;
uint32be timestampRelated; // guessed
};
static_assert(sizeof(BossStorageFadEntry) == 0x38, "sizeof(BossStorageFadEntry)");
struct BossStorageFadFile
{
uint8 _00[0x08];
BossStorageFadEntry entries[FAD_ENTRY_MAX_COUNT];
};
static_assert(sizeof(BossStorageFadFile) == 28680, "sizeof(BossStorageFadFile)");
struct BossNbdlHeader
{
/* +0x00 */
uint32be magic;
/* +0x04 */
uint32be version; // guessed
/* +0x08 */
uint16be ukn08; // must always be 1
/* +0x0A */
uint16be ukn0A; // must always be 2
/* +0x0C */
uint8 nonce[0xC];
/* +0x18 */
uint32 padding18; // unused
/* +0x1C */
uint32 padding1C; // unused
/* +0x20 */
struct
{
uint8 uknHashData[0x20];
} encryptedHeader;
} ;
static_assert(sizeof(BossNbdlHeader) == 0x40, "BossNbdlHeader has invalid size");
static_assert(offsetof(BossNbdlHeader, encryptedHeader) == 0x20, "offsetof(BossNbdlHeader, encryptedHeader)");
struct
{
bool is_initialized;
std::vector<Task> tasks;
} g_boss = {};
/*
X-BOSS-Closed
X-BOSS-TitleId
X-Boss-UniqueId
�\r���\r�(X-BOSS-Digest
LOAD:E01038B4 0000000C C %susr/boss/
LOAD:E0103A6C 00000011 C %susr/boss/%08x/
LOAD:E0103B04 00000016 C %susr/boss/%08x/%08x/
LOAD:E0103B1C 0000001B C %susr/boss/%08x/%08x/user/
LOAD:E0103B5C 00000020 C %susr/boss/%08x/%08x/user/%08x/
LOAD:E0103B38 00000022 C %susr/boss/%08x/%08x/user/common/
LOAD:E0103AC4 00000020 C %susr/boss/%08x/%08x/user/temp/
LOAD:E01106DC 0000000A C /dev/boss
LOAD:05063698 0000001C C /vol/storage_mlc01/usr/boss
LOAD:E2299CA8 00000028 C /vol/storage_mlc01/usr/save/system/boss
*/
template <typename ... TArgs>
curl_slist* append_header_param(struct curl_slist* list, const char* format, TArgs&& ... args)
{
return curl_slist_append(list, fmt::format(fmt::runtime(format), std::forward<TArgs>(args)...).c_str());
}
bool starts_with(const char* str, const char* pre)
{
const size_t len_string = strlen(str);
const size_t len_prefix = strlen(pre);
return len_string < len_prefix ? false : strncmp(pre, str, len_prefix) == 0;
}
size_t task_write_callback(char* ptr, size_t size, size_t nmemb, void* userdata)
{
Task* task = (Task*)userdata;
const size_t writeByteSize = size * nmemb;
//if (task->result_buffer.size() - task->processed_length < writeByteSize)
// task->result_buffer.resize(task->result_buffer.size() + writeByteSize);
//writeByteSize = min(writeByteSize, task->result_buffer.capacity() - task->processed_length);
//cemuLog_logDebug(LogType::Force, "task_write_callback: {} (processed: {})", writeByteSize, task->processed_length);
if (writeByteSize > 0)
{
//memcpy(task->result_buffer.data() + task->processed_length, ptr, writeByteSize);
task->result_buffer.insert(task->result_buffer.end(), ptr, ptr + writeByteSize);
task->processed_length += writeByteSize;
}
return writeByteSize;
}
size_t task_download_header_callback(char* ptr, size_t size, size_t nitems, void* userdata)
{
//cemuLog_logDebug(LogType::Force, "\tHeader: {}", ptr);
return size * nitems;
}
size_t task_download_filecallback(char* ptr, size_t size, size_t nmemb, void* userdata)
{
Task* task = (Task*)userdata;
const size_t writeByteSize = size * nmemb;
//writeByteSize = min(writeByteSize, task->file_buffer.capacity() - task->processed_file_size);
if (writeByteSize > 0)
{
//memcpy(task->file_buffer.data() + task->processed_file_size, ptr, writeByteSize);
task->file_buffer.insert(task->file_buffer.end(), ptr, ptr + writeByteSize);
task->processed_file_size += writeByteSize;
}
return writeByteSize;
}
size_t task_header_callback(char* ptr, size_t size, size_t nitems, void* userdata)
{
Task* task = (Task*)userdata;
if (starts_with(ptr, "Content-Length: "))
{
task->content_length = strtol(&ptr[16], nullptr, 0);
task->result_buffer.clear();
task->result_buffer.reserve(task->content_length);
task->processed_length = 0;
}
else if (starts_with(ptr, "Content-Type: "))
{
const char* type = &ptr[14];
if (starts_with(type, "application/xml") || starts_with(type, "text/xml"))
task->content_type = ContentType::kXmlContent;
else if (starts_with(type, "x-application/octet-stream"))
task->content_type = ContentType::kBinaryFile;
else if (starts_with(type, "text/html"))
task->content_type = ContentType::kText;
else
{
cemuLog_logDebug(LogType::Force, "task_header_callback: unknown content type > {}", type);
}
}
else if (starts_with(ptr, "Last-Modified: "))
{
// TODO timestamp (?)
}
//cemuLog_logDebug(LogType::Force, "task_header_callback: len {} ({}) and type {}", task->content_length, task->result_buffer.capacity(), task->content_type);
//cemuLog_logDebug(LogType::Force, "\t{}", ptr);
return size * nitems;
}
static CURLcode task_sslctx_function(CURL* curl, void* sslctx, void* param)
{
auto task_settings = (TaskSetting*)param;
if (task_settings->taskType == kRawDlTaskSetting)
{
cemuLog_logDebug(LogType::Force, "sslctx_function: adding client cert: {}", (int)task_settings->settings[TaskSetting::kClientCert]);
if (!iosuCrypto_addClientCertificate(sslctx, task_settings->settings[TaskSetting::kClientCert]))
assert_dbg();
uint32 location = TaskSetting::kCACert;
for (int i = 0; i < 3; ++i)
{
if (task_settings->settings[location] != 0)
{
cemuLog_logDebug(LogType::Force, "sslctx_function: adding ca cert: {}", (int)task_settings->settings[location]);
if (!iosuCrypto_addCACertificate(sslctx, task_settings->settings[location]))
{
cemuLog_log(LogType::Force, "Failed to load CA certificate file");
assert_dbg();
}
}
location += TaskSetting::kCACert;
}
}
else
{
if (!iosuCrypto_addCACertificate(sslctx, 105))
{
cemuLog_log(LogType::Force, "Failed to load certificate file");
assert_dbg();
}
if (!iosuCrypto_addClientCertificate(sslctx, 3))
{
cemuLog_log(LogType::Force, "Failed to load client certificate file");
assert_dbg();
}
}
SSL_CTX_set_cipher_list((SSL_CTX*)sslctx, "AES256-SHA");
// TLS_RSA_WITH_AES_256_CBC_SHA (in CURL it's called rsa_aes_256_sha)
SSL_CTX_set_mode((SSL_CTX*)sslctx, SSL_MODE_AUTO_RETRY);
SSL_CTX_set_verify_depth((SSL_CTX*)sslctx, 2);
SSL_CTX_set_verify((SSL_CTX*)sslctx, SSL_VERIFY_PEER, nullptr);
return CURLE_OK;
}
auto get_task(const char* taskId, uint32 accountId, uint64 titleId)
{
const auto it = std::find_if(g_boss.tasks.begin(), g_boss.tasks.end(), [taskId, accountId, titleId](const Task& task)
{
return 0 == strncmp(taskId, task.task_id, sizeof(Task::task_id)) && accountId == task.account_id && titleId == task.
title_id;
});
return it;
}
bool parse_xml_content(Task& task)
{
tinyxml2::XMLDocument doc;
//cemuLog_log(LogType::Force, (char*)task.result_buffer.data());
if (doc.Parse((const char*)task.result_buffer.data(), task.processed_length) != tinyxml2::XML_SUCCESS)
return false;
for (tinyxml2::XMLElement* sheet = doc.FirstChildElement("TaskSheet"); sheet; sheet = sheet->
NextSiblingElement("TaskSheet"))
{
const auto files = sheet->FirstChildElement("Files");
if (!files)
continue;
for (tinyxml2::XMLElement* file = files->FirstChildElement("File"); file; file = file->NextSiblingElement("File"))
{
auto file_name = file->FirstChildElement("Filename");
if (!file_name)
continue;
auto data_id = file->FirstChildElement("DataId");
if (!data_id)
continue;
auto type = file->FirstChildElement("Type");
if (!type)
continue;
auto url = file->FirstChildElement("Url");
if (!url)
continue;
auto size = file->FirstChildElement("Size");
if (!size)
continue;
FileType file_type;
if (0 == strcmp(type->GetText(), "AppData"))
file_type = FileType::kAppData;
else
{
file_type = FileType::kUnknownFile;
}
task.queued_files.emplace(file_name->GetText(), data_id->IntText(), file_type, url->GetText(), size->IntText());
}
}
return true;
}
const uint64 kTimeStampConvertSeconds = 946684800ULL;
BossStorageFadEntry* boss_storage_fad_find_entry(BossStorageFadFile& fad_file, uint32 data_id)
{
for (auto& entry : fad_file.entries)
{
if (entry.fileNameId == data_id)
return &entry;
}
return nullptr;
}
void boss_storage_fad_append_or_update(BossStorageFadFile& fad_file, const char* name, uint32 data_id, uint64 timestamp)
{
for (auto& entry : fad_file.entries)
{
if (entry.fileNameId == 0 || strcmp(entry.name, name) == 0)
{
entry.fileNameId = data_id;
strcpy(entry.name, name);
entry.timestampRelated = (uint32)(timestamp - kTimeStampConvertSeconds); // time since 2000
return;
}
}
}
uint32 task_run(const char* taskId, uint32 accountId, uint64 titleId)
{
const auto it = get_task(taskId, accountId, titleId);
if (it == g_boss.tasks.cend())
{
//it->turn_state = kError;
//it->wait_state = TRUE;
return BUILD_NN_RESULT(NN_RESULT_LEVEL_FATAL, NN_RESULT_MODULE_NN_BOSS, 0);
}
if (!ActiveSettings::IsOnlineEnabled())
{
it->turn_state = kError;
it->wait_state = TRUE;
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_BOSS, 0);
}
cemuLog_logDebug(LogType::Force, "task run state: {} | exec: {} (tasks: {})", it->turn_state, it->exec_count, g_boss.tasks.size());
it->turn_state = kRunning;
it->exec_count++;
/*
https://nppl.app.nintendo.net/p01/policylist/1/1/AT
https://npts.app.nintendo.net/p01/tasksheet/1/zvGSM4kO***kKnpT/schdat2?c=XX&l=en
https://npts.app.nintendo.net/p01/tasksheet/1/zvGSM4kO***kKnpT/optdat2?c=XX&l=en
https://npts.app.nintendo.net/p01/tasksheet/1/8UsM86l***jFk8z/wood1?c=XX&l=en
https://npts.app.nintendo.net/p01/tasksheet/1/8UsM86l***kjFk8z/woodBGM?c=XX&l=en
https://npts.app.nintendo.net/p01/tasksheet/%s/%s/%s/%s?c=%s&l=%s
https://npts.app.nintendo.net/p01/tasksheet/%s/%s/%s?c=%s&l=%s
1 == version
bossCode
initFile
*/
uint32 turnstate = kSuccess;
struct curl_slist* list_headerParam = nullptr;
list_headerParam = append_header_param(list_headerParam, "X-BOSS-Digest"); // ???
list_headerParam = append_header_param(list_headerParam, "X-Boss-UniqueId: {:05x}", ((titleId >> 8) & 0xFFFFF)); // %05x
list_headerParam = append_header_param(list_headerParam, "X-BOSS-TitleId: /usr/packages/title/{:016x}", titleId); // "/usr/packages/title/%016llx"
CURL* curl = it->curl.get();
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 2);
#ifdef CEMU_DEBUG_ASSERT
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
char errbuf[CURL_ERROR_SIZE]{};
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
#else
curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);
#endif
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, task_write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &(*it));
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, task_header_callback);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &(*it));
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0x3C);
if (IsNetworkServiceSSLDisabled(ActiveSettings::GetNetworkService()))
{
curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0L);
}
else
{
curl_easy_setopt(curl, CURLOPT_SSL_CTX_FUNCTION, task_sslctx_function);
curl_easy_setopt(curl, CURLOPT_SSL_CTX_DATA, &it->task_settings);
curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_0);
}
std::string requestUrl;
if(it->task_settings.taskType == kRawDlTaskSetting)
{
char serviceToken[TaskSetting::kServiceTokenLen];
strncpy(serviceToken, (char*)&it->task_settings.settings[TaskSetting::kServiceToken], TaskSetting::kServiceTokenLen);
list_headerParam = append_header_param(list_headerParam, "X-Nintendo-ServiceToken: {}", serviceToken);
char url[TaskSetting::kURLLen + 1]{};
strncpy(url, (char*)&it->task_settings.settings[TaskSetting::kURL], TaskSetting::kURLLen);
requestUrl.assign(url);
}
else
{
char languageCode[8];
switch (GetConfig().console_language)
{
case CafeConsoleLanguage::JA:
strcpy(languageCode, "ja");
break;
case CafeConsoleLanguage::EN:
strcpy(languageCode, "en");
break;
case CafeConsoleLanguage::FR:
strcpy(languageCode, "fr");
break;
case CafeConsoleLanguage::DE:
strcpy(languageCode, "de");
break;
case CafeConsoleLanguage::IT:
strcpy(languageCode, "it");
break;
case CafeConsoleLanguage::ES:
strcpy(languageCode, "es");
break;
case CafeConsoleLanguage::ZH:
strcpy(languageCode, "zh");
break;
case CafeConsoleLanguage::KO:
strcpy(languageCode, "ko");
break;
case CafeConsoleLanguage::NL:
strcpy(languageCode, "nl");
break;
case CafeConsoleLanguage::PT:
strcpy(languageCode, "pt");
break;
case CafeConsoleLanguage::RU:
strcpy(languageCode, "ru");
break;
case CafeConsoleLanguage::TW:
strcpy(languageCode, "tw"); // usually zh-tw?
break;
default:
strcpy(languageCode, "en");
break;
}
const char* countryCode = NCrypto::GetCountryAsString(Account::GetCurrentAccount().GetCountry());
char boss_code[0x20];
strncpy(boss_code, (char*)&it->task_settings.settings[TaskSetting::kBossCode], TaskSetting::kBossCodeLen);
switch (ActiveSettings::GetNetworkService())
{
case NetworkService::Pretendo:
requestUrl = PretendoURLs::BOSSURL;
break;
case NetworkService::Custom:
requestUrl = GetNetworkConfig().urls.BOSS.GetValue();
break;
case NetworkService::Nintendo:
default:
requestUrl = NintendoURLs::BOSSURL;
break;
}
requestUrl.append(fmt::format(fmt::runtime("/{}/{}/{}?c={}&l={}"), "1", boss_code, it->task_id, countryCode, languageCode));
}
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list_headerParam);
curl_easy_setopt(curl, CURLOPT_URL, requestUrl.c_str());
int curl_result = curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &it->http_status_code);
static_assert(sizeof(it->http_status_code) == sizeof(long));
//it->turn_state = kFinished;
curl_slist_free_all(list_headerParam);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, nullptr);
if (curl_result != CURLE_OK)
{
#ifdef CEMU_DEBUG_ASSERT
cemuLog_logDebug(LogType::Force, "curl error buff: {}", errbuf);
#endif
it->turn_state = kError;
it->wait_state = TRUE;
cemuLog_logDebug(LogType::Force, "task_run curl fail: {}", curl_result);
return BUILD_NN_RESULT(NN_RESULT_LEVEL_FATAL, NN_RESULT_MODULE_NN_BOSS, 0);
}
else
{
if (it->http_status_code != 200)
{
cemuLog_logDebug(LogType::Force, "BOSS task_run: Received unexpected HTTP response code");
}
if (it->http_status_code == 404)
{
// todo - is this correct behavior?
it->turn_state = kError;
it->wait_state = TRUE;
cemuLog_logDebug(LogType::Force, "task_run failed due to 404 error");
return BUILD_NN_RESULT(NN_RESULT_LEVEL_FATAL, NN_RESULT_MODULE_NN_BOSS, 0);
}
}
switch (it->content_type)
{
case ContentType::kXmlContent:
parse_xml_content(*it);
break;
case ContentType::kBinaryFile:
break;
case ContentType::kText:
cemuLog_logDebug(LogType::Force, "task_run returns text: {}", fmt::ptr(it->result_buffer.data()));
break;
}
if (!it->queued_files.empty())
{
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, task_download_header_callback);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, task_download_filecallback);
std::string taskIdStr = it->task_id;
try
{
fs::path path = ActiveSettings::GetMlcPath("usr/boss/{:08x}/{:08x}/user/common/data/{}", (uint32)(it->title_id >> 32), (uint32)(it->title_id & 0xFFFFFFFF), taskIdStr);
if (!fs::exists(path))
fs::create_directories(path);
char targetFileName[TaskSetting::kFileNameLen + 1]{};
strncpy(targetFileName, (char*)&it->task_settings.settings[TaskSetting::kNbdlFileName], TaskSetting::kFileNameLen);
cemuLog_logDebug(LogType::Force, "\tnbdl task target filename: \"{}\"", targetFileName);
const bool hasFileName = targetFileName[0] != '\0';
while (!it->queued_files.empty())
{
auto file = it->queued_files.front();
it->queued_files.pop();
// download only specific file
if (hasFileName && file.file_name != targetFileName)
continue;
it->processed_file_size = 0;
it->file_buffer.clear();
it->file_buffer.reserve(file.size);
// create/open fad db content
BossStorageFadFile fad_content{};
fs::path db_file = ActiveSettings::GetMlcPath("usr/boss/{:08x}/{:08x}/user/common/{:08x}/{}", (uint32)(it->title_id >> 32), (uint32)(it->title_id & 0xFFFFFFFF), it->account_id, taskIdStr);
if (!fs::exists(db_file))
fs::create_directories(db_file);
db_file /= "fad.db";
std::ifstream fad_file(db_file, std::ios::in | std::ios::binary);
if (fad_file.is_open())
{
if (!fad_file.read((char*)&fad_content, sizeof(BossStorageFadFile)))
fad_content = {};
fad_file.close();
}
auto currentEntry = boss_storage_fad_find_entry(fad_content, file.data_id);
//TODO deep dive into IOSU to figure out how caching actually works on th Wii U
if(currentEntry && fs::exists(path / fmt::format(L"{:08x}", file.data_id)))
{
uint64 timestamp = (uint64)currentEntry->timestampRelated + kTimeStampConvertSeconds;
curl_easy_setopt(curl, CURLOPT_TIMEVALUE, timestamp);
curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
}
else
{
curl_easy_setopt(curl, CURLOPT_TIMEVALUE, 0);
curl_easy_setopt(curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
}
curl_easy_setopt(curl, CURLOPT_FILETIME, 1L);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, task_download_header_callback);
curl_easy_setopt(curl, CURLOPT_URL, file.url.c_str());
curl_result = curl_easy_perform(curl);
if (curl_result != CURLE_OK)
{
cemuLog_logDebug(LogType::Force, "task_run curl failed on file download ({}): {} > {}", curl_result, file.file_name, file.url);
if (hasFileName)
{
turnstate = kError;
break;
}
else
continue;
}
long unmet = 1;
const CURLcode result = curl_easy_getinfo(curl, CURLINFO_CONDITION_UNMET, &unmet);
if(result == CURLE_OK && unmet == 1)
{
// file is already up2date
if (hasFileName)
break;
else
continue;
}
if(it->processed_file_size != file.size)
{
cemuLog_logDebug(LogType::Force, "task_run file download size mismatch: {} > {} > {} from {} bytes", file.file_name, file.url, it->processed_file_size, file.size);
if (hasFileName)
{
turnstate = kError;
break;
}
else
continue;
}
uint64 filetime;
curl_easy_getinfo(curl, CURLINFO_FILETIME, &filetime);
// dunno about that one
it->processed_length += it->processed_file_size;
it->content_length += file.size;
// bossAesKey = OTP.XorKey ^ bossXor
// bossXor: 33 AC 6D 15 C2 26 0A 91 3B BF 73 C3 55 D8 66 04
uint8 bossAesKey[16] = { 0x39,0x70,0x57,0x35,0x58,0x70,0x34,0x58,0x37,0x41,0x7a,0x30,0x71,0x5a,0x70,0x74 }; // "9pW5Xp4X7Az0qZpt"
BossNbdlHeader* nbdlHeader = (BossNbdlHeader*)it->file_buffer.data();
if (nbdlHeader->magic != 'boss')
break;
if (nbdlHeader->version != 0x20001)
break;
if (nbdlHeader->ukn08 != 1)
break;
if (nbdlHeader->ukn0A != 2)
break;
// file must be padded to 16 byte alignment for AES decryption (padding is cut off after decryption)
const uint32 file_size = (it->processed_file_size + 0xF) & (~0xF);
if (file_size != it->processed_file_size)
{
it->file_buffer.resize(file_size);
nbdlHeader = (BossNbdlHeader*)it->file_buffer.data();
}
// prepare nonce for AES128-CTR
uint8 aesNonce[0x10];
memset(aesNonce, 0, sizeof(aesNonce));
memcpy(aesNonce, nbdlHeader->nonce, 0xC);
aesNonce[0xF] = 1;
// decrypt header
AES128CTR_transform(it->file_buffer.data() + offsetof(BossNbdlHeader, encryptedHeader), sizeof(BossNbdlHeader::encryptedHeader), bossAesKey, aesNonce);
// decrypt everything else
AES128CTR_transform(it->file_buffer.data() + sizeof(BossNbdlHeader), file_size - sizeof(BossNbdlHeader), bossAesKey, aesNonce);
try
{
// create file with content
fs::path file_path = path / fmt::format(L"{:08x}", file.data_id);
std::ofstream new_file(file_path, std::ios::out | std::ios::binary | std::ios::trunc);
new_file.write((char*)it->file_buffer.data() + sizeof(BossNbdlHeader), it->processed_file_size - sizeof(BossNbdlHeader));
new_file.flush();
new_file.close();
boss_storage_fad_append_or_update(fad_content, file.file_name.c_str(), file.data_id, filetime);
std::ofstream fad_file_updated(db_file, std::ios::out | std::ios::binary | std::ios::trunc);
fad_file_updated.write((char*)&fad_content, sizeof(BossStorageFadFile));
fad_file_updated.flush();
fad_file_updated.close();
}
catch (const std::exception& ex)
{
cemuLog_logDebug(LogType::Force, "file error: {}", ex.what());
}
if (hasFileName)
break;
}
}
catch (const std::exception& ex)
{
cemuLog_logDebug(LogType::Force, "dir error: {}", ex.what());
}
}
if (it->task_settings.taskType == kRawDlTaskSetting)
{
char directoryName[TaskSetting::kDirectoryNameLen + 1]{};
if (it->task_settings.settings[TaskSetting::kDirectoryName] != '\0')
strncpy(directoryName, (char*)&it->task_settings.settings[TaskSetting::kDirectoryName], TaskSetting::kDirectoryNameLen);
else
strncpy(directoryName, it->task_id, TaskSetting::kDirectoryNameLen);
char fileName[TaskSetting::kFileNameLen + 1]{};
strncpy(fileName, (char*)&it->task_settings.settings[TaskSetting::kFileName], TaskSetting::kFileNameLen);
// mcl01\usr\boss\00050000\1018dd00\user\<persistentId>\<storageName>\<filename>
fs::path path = ActiveSettings::GetMlcPath("usr/boss/{:08x}/{:08x}/user/{:08x}", (uint32)(it->title_id >> 32),
(uint32)(it->title_id & 0xFFFFFFFF), iosuAct_getAccountIdOfCurrentAccount());
path /= directoryName;
if (!fs::exists(path))
fs::create_directories(path);
path /= fileName;
std::ofstream file(path);
if (file.is_open())
{
file.write((char*)it->result_buffer.data(), it->result_buffer.size());
file.flush();
file.close();
}
}
it->turn_state = turnstate;
it->wait_state = TRUE;
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_BOSS, 0);
}
bool task_is_registered(const char* taskId, uint32 accountId, uint64 titleId)
{
const auto it = get_task(taskId, accountId, titleId);
return it != g_boss.tasks.cend();
}
bool task_wait(const char* taskId, uint32 accountId, uint64 titleId, uint32 wait_state, uint32 timeout = 0)
{
const auto it = get_task(taskId, accountId, titleId);
if (it == g_boss.tasks.cend())
{
return false;
}
const auto start = tick_cached();
while (it->wait_state != wait_state)
{
if (timeout != 0 && (uint32)std::chrono::duration_cast<std::chrono::seconds>(tick_cached() - start).count() >= timeout)
{
cemuLog_logDebug(LogType::Force, "task_wait: timeout reached -> {} seconds passed", timeout);
return false;
}
std::this_thread::yield();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return true;
}
uint32 task_register(const char* taskId, uint32 accountId, uint64 titleId, void* settings)
{
g_boss.tasks.emplace_back(taskId, accountId, titleId, (TaskSetting*)settings);
g_boss.tasks[g_boss.tasks.size() - 1].turn_state = kWaitTime;
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_BOSS, 0);
}
uint32 task_register_immediate_run(const char* taskId, uint32 accountId, uint64 titleId, void* settings)
{
g_boss.tasks.emplace_back(taskId, accountId, titleId, (TaskSetting*)settings);
g_boss.tasks[g_boss.tasks.size() - 1].turn_state = kWaitRun;
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_BOSS, 0);
}
void task_unregister(const char* taskId, uint32 accountId, uint64 titleId)
{
const auto it = get_task(taskId, accountId, titleId);
if (it != g_boss.tasks.cend())
g_boss.tasks.erase(it);
}
std::pair<uint32, uint64> task_get_content_length(const char* taskId, uint32 accountId, uint64 titleId)
{
const auto it = get_task(taskId, accountId, titleId);
return it != g_boss.tasks.cend() ? std::make_pair(it->exec_count, it->content_length) : std::make_pair(0u, (uint64)0);
}
std::pair<uint32, uint64> task_get_processed_length(const char* taskId, uint32 accountId, uint64 titleId)
{
const auto it = get_task(taskId, accountId, titleId);
return it != g_boss.tasks.cend() ? std::make_pair(it->exec_count, it->processed_length) : std::make_pair(0u, (uint64)0);
}
std::pair<uint32, long> task_get_http_status_code(const char* taskId, uint32 accountId, uint64 titleId)
{
const auto it = get_task(taskId, accountId, titleId);
return it != g_boss.tasks.cend() ? std::make_pair(it->exec_count, it->http_status_code) : std::make_pair(0u, (long)0);
}
std::pair<uint32, uint32> task_get_turn_state(const char* taskId, uint32 accountId, uint64 titleId)
{
const auto it = get_task(taskId, accountId, titleId);
return it != g_boss.tasks.cend() ? std::make_pair(it->exec_count, it->turn_state) : std::make_pair(0u, (uint32)0);
}
uint32 task_stop_scheduling(const char* task_id, uint32 account_id, uint64 title_id)
{
const auto it = get_task(task_id, account_id, title_id);
if (it != g_boss.tasks.cend())
{
it->turn_state = kStopped;
// todo actually cancel the task if currently running (curl call)
// curl_easy_pause() -> resume on start scheduling if paused
}
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_BOSS, 0);
}
void boss_thread()
{
SetThreadName("boss_thread");
while (true)
{
const uint32 return_value = 0; // Ioctl return value
ioQueueEntry_t* ioQueueEntry = iosuIoctl_getNextWithWait(IOS_DEVICE_BOSS);
if (ioQueueEntry->request == IOSU_BOSS_REQUEST_CEMU)
{
iosuBossCemuRequest_t* cemu_request = (iosuBossCemuRequest_t*)ioQueueEntry->bufferVectors[0].buffer.GetPtr();
cemu_request->returnCode = 0;
uint64 title_id;
if (cemu_request->titleId == 0)
title_id = CafeSystem::GetForegroundTitleId();
else
title_id = cemu_request->titleId;
uint32 account_id;
if (cemu_request->accountId == 0)
account_id = iosuAct_getAccountIdOfCurrentAccount();
else
account_id = cemu_request->accountId;
if (cemu_request->requestCode == IOSU_NN_BOSS_TASK_RUN)
{
cemu_request->returnCode = task_run(cemu_request->taskId, account_id, title_id);
}
else if (cemu_request->requestCode == IOSU_NN_BOSS_TASK_GET_CONTENT_LENGTH)
{
auto result = task_get_content_length(cemu_request->taskId, account_id, title_id);
cemu_request->u64.exec_count = std::get<0>(result);
cemu_request->u64.result = std::get<1>(result);
}
else if (cemu_request->requestCode == IOSU_NN_BOSS_TASK_GET_PROCESSED_LENGTH)
{
auto result = task_get_processed_length(cemu_request->taskId, account_id, title_id);
cemu_request->u64.exec_count = std::get<0>(result);
cemu_request->u64.result = std::get<1>(result);
}
else if (cemu_request->requestCode == IOSU_NN_BOSS_TASK_GET_HTTP_STATUS_CODE)
{
auto result = task_get_http_status_code(cemu_request->taskId, account_id, title_id);
cemu_request->u32.exec_count = std::get<0>(result);
cemu_request->u32.result = std::get<1>(result);
}
else if (cemu_request->requestCode == IOSU_NN_BOSS_TASK_GET_TURN_STATE)
{
auto result = task_get_turn_state(cemu_request->taskId, account_id, title_id);
cemu_request->u32.exec_count = std::get<0>(result);
cemu_request->u32.result = std::get<1>(result);
}
else if (cemu_request->requestCode == IOSU_NN_BOSS_TASK_WAIT)
{
cemu_request->returnCode = task_wait(cemu_request->taskId, account_id, title_id, cemu_request->waitState,
cemu_request->timeout);
}
else if (cemu_request->requestCode == IOSU_NN_BOSS_TASK_REGISTER)
{
cemu_request->returnCode = task_register(cemu_request->taskId, account_id, title_id, cemu_request->settings);
}
else if (cemu_request->requestCode == IOSU_NN_BOSS_TASK_IS_REGISTERED)
{
cemu_request->returnCode = task_is_registered(cemu_request->taskId, account_id, title_id) ? TRUE : FALSE;
}
else if (cemu_request->requestCode == IOSU_NN_BOSS_TASK_REGISTER_FOR_IMMEDIATE_RUN)
{
cemu_request->returnCode = task_register_immediate_run(cemu_request->taskId, account_id, title_id,
cemu_request->settings);
}
else if (cemu_request->requestCode == IOSU_NN_BOSS_TASK_UNREGISTER)
{
task_unregister(cemu_request->taskId, account_id, title_id);
}
else if (cemu_request->requestCode == IOSU_NN_BOSS_TASK_START_SCHEDULING)
{
// we just run it no matter what
//if(cemu_request->bool_parameter)
cemu_request->returnCode = task_run(cemu_request->taskId, account_id, title_id);
/*else
{
const auto it = get_task(cemu_request->taskId, account_id, title_id);
if (it != g_boss.tasks.cend())
{
it->turn_state = kWaitRun;
}
}*/
}
else if (cemu_request->requestCode == IOSU_NN_BOSS_TASK_STOP_SCHEDULING)
{
cemu_request->returnCode = task_stop_scheduling(cemu_request->taskId, account_id, title_id);
}
else
assert_dbg();
}
else
assert_dbg();
iosuIoctl_completeRequest(ioQueueEntry, return_value);
}
}
void boss_init()
{
if (g_boss.is_initialized)
return;
// start the boss thread
std::thread t(boss_thread);
t.detach();
g_boss.is_initialized = true;
}
}
| 33,533
|
C++
|
.cpp
| 906
| 32.779249
| 193
| 0.689143
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,176
|
iosu_act.cpp
|
cemu-project_Cemu/src/Cafe/IOSU/legacy/iosu_act.cpp
|
#include "iosu_act.h"
#include "iosu_ioctl.h"
#include "Cafe/OS/libs/nn_common.h"
#include "gui/CemuApp.h"
#include <algorithm>
#include <mutex>
#include "openssl/evp.h" /* EVP_Digest */
#include "openssl/sha.h" /* SHA256_DIGEST_LENGTH */
#include "Cafe/Account/Account.h"
#include "config/ActiveSettings.h"
#include "util/helpers/helpers.h"
#include "Cemu/napi/napi.h"
#include "Cemu/ncrypto/ncrypto.h"
#include "Cafe/IOSU/kernel/iosu_kernel.h"
#include "Cafe/IOSU/nn/iosu_nn_service.h"
using namespace iosu::kernel;
using NexToken = NAPI::ACTNexToken;
static_assert(sizeof(NexToken) == 0x25C);
struct
{
bool isInitialized;
std::mutex actMutex;
}iosuAct = { };
// account manager
struct actAccountData_t
{
bool isValid;
// options
bool isNetworkAccount;
bool hasParseError; // set if any occurs while parsing account.dat
// IDs
uint8 uuid[16];
uint32 persistentId;
uint64 transferableIdBase;
uint32 simpleAddressId;
uint32 principalId;
// NNID
char accountId[64];
uint8 accountPasswordCache[32];
// country & language
uint32 countryIndex;
char country[8];
// Mii
FFLData_t miiData;
uint16le miiNickname[ACT_NICKNAME_LENGTH];
bool IsNetworkAccount() const
{
return isNetworkAccount; // todo - IOSU only checks if accountId is not empty?
}
};
#define IOSU_ACT_ACCOUNT_MAX_COUNT (0xC)
actAccountData_t _actAccountData[IOSU_ACT_ACCOUNT_MAX_COUNT] = {};
bool _actAccountDataInitialized = false;
void FillAccountData(const Account& account, const bool online_enabled, int index)
{
cemu_assert_debug(index < IOSU_ACT_ACCOUNT_MAX_COUNT);
auto& data = _actAccountData[index];
data.isValid = true;
// options
data.isNetworkAccount = account.IsValidOnlineAccount();
data.hasParseError = false;
// IDs
std::copy(account.GetUuid().cbegin(), account.GetUuid().cend(), data.uuid);
data.persistentId = account.GetPersistentId();
data.transferableIdBase = account.GetTransferableIdBase();
data.simpleAddressId = account.GetSimpleAddressId();
data.principalId = account.GetPrincipalId();
// NNID
std::copy(account.GetAccountId().begin(), account.GetAccountId().end(), data.accountId);
std::copy(account.GetAccountPasswordCache().begin(), account.GetAccountPasswordCache().end(), data.accountPasswordCache);
// country & language
data.countryIndex = account.GetCountry();
strcpy(data.country, NCrypto::GetCountryAsString(data.countryIndex));
// Mii
std::copy(account.GetMiiData().begin(), account.GetMiiData().end(), (uint8*)&data.miiData);
std::copy(account.GetMiiName().begin(), account.GetMiiName().end(), data.miiNickname);
// if online mode is disabled, make all accounts offline
if(!online_enabled)
{
data.isNetworkAccount = false;
data.principalId = 0;
data.simpleAddressId = 0;
memset(data.accountId, 0x00, sizeof(data.accountId));
}
}
void iosuAct_loadAccounts()
{
if (_actAccountDataInitialized)
return;
const bool online_enabled = ActiveSettings::IsOnlineEnabled();
const auto persistent_id = ActiveSettings::GetPersistentId();
// first account is always our selected one
int counter = 0;
const auto& first_acc = Account::GetAccount(persistent_id);
FillAccountData(first_acc, online_enabled, counter);
++counter;
// enable multiple accounts for cafe functions (badly tested)
//for (const auto& account : Account::GetAccounts())
//{
// if (first_acc.GetPersistentId() != account.GetPersistentId())
// {
// FillAccountData(account, online_enabled, counter);
// ++counter;
// }
//}
cemuLog_log(LogType::Force, "IOSU_ACT: using account {} in first slot", boost::nowide::narrow(first_acc.GetMiiName()));
_actAccountDataInitialized = true;
}
bool iosuAct_isAccountDataLoaded()
{
return _actAccountDataInitialized;
}
uint32 iosuAct_acquirePrincipalIdByAccountId(const char* nnid, uint32* pid)
{
NAPI::AuthInfo authInfo;
NAPI::NAPI_MakeAuthInfoFromCurrentAccount(authInfo);
NAPI::ACTConvertNnidToPrincipalIdResult result = NAPI::ACT_ACTConvertNnidToPrincipalId(authInfo, nnid);
if (result.isValid() && result.isFound)
{
*pid = result.principalId;
}
else
{
*pid = 0;
return BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_ACT, 0); // what error should we return? The friend list app expects nn_act.AcquirePrincipalIdByAccountId to never return an error
}
return 0;
}
sint32 iosuAct_getAccountIndexBySlot(uint8 slot)
{
if (slot == iosu::act::ACT_SLOT_CURRENT)
return 0;
if (slot == 0xFF)
return 0; // ?
cemu_assert_debug(slot != 0);
cemu_assert_debug(slot <= IOSU_ACT_ACCOUNT_MAX_COUNT);
return slot - 1;
}
uint32 iosuAct_getAccountIdOfCurrentAccount()
{
cemu_assert_debug(_actAccountData[0].isValid);
return _actAccountData[0].persistentId;
}
// IOSU act API interface
static const auto ACTResult_Ok = 0;
static const auto ACTResult_InvalidValue = BUILD_NN_RESULT(NN_RESULT_LEVEL_LVL6, NN_RESULT_MODULE_NN_ACT, 0x12F00); // 0xC0712F00
static const auto ACTResult_OutOfRange = BUILD_NN_RESULT(NN_RESULT_LEVEL_LVL6, NN_RESULT_MODULE_NN_ACT, 0x12D80); // 0xC0712D80
static const auto ACTResult_AccountDoesNotExist = BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_ACT, NN_ACT_RESULT_ACCOUNT_DOES_NOT_EXIST); // 0xA071F480
static const auto ACTResult_NotANetworkAccount = BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_ACT, 0x1FE80); // 0xA071FE80
nnResult ServerActErrorCodeToNNResult(NAPI::ACT_ERROR_CODE ec)
{
switch (ec)
{
case (NAPI::ACT_ERROR_CODE)1:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2401);
case (NAPI::ACT_ERROR_CODE)2:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2402);
case (NAPI::ACT_ERROR_CODE)3:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2403);
case (NAPI::ACT_ERROR_CODE)4:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2458);
case (NAPI::ACT_ERROR_CODE)5:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2642);
case (NAPI::ACT_ERROR_CODE)6:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2641);
case (NAPI::ACT_ERROR_CODE)7:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2522);
case (NAPI::ACT_ERROR_CODE)8:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2534);
case (NAPI::ACT_ERROR_CODE)9:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2404);
case (NAPI::ACT_ERROR_CODE)10:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2451);
case (NAPI::ACT_ERROR_CODE)11:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2511);
case (NAPI::ACT_ERROR_CODE)12:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2812);
case (NAPI::ACT_ERROR_CODE)100:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2571);
case (NAPI::ACT_ERROR_CODE)101:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2572);
case (NAPI::ACT_ERROR_CODE)103:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2575);
case (NAPI::ACT_ERROR_CODE)104:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2452);
case (NAPI::ACT_ERROR_CODE)105:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2592);
case (NAPI::ACT_ERROR_CODE)106:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2611);
case (NAPI::ACT_ERROR_CODE)107:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2502);
case (NAPI::ACT_ERROR_CODE)108:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2802);
case (NAPI::ACT_ERROR_CODE)109:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2503);
case (NAPI::ACT_ERROR_CODE)110:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2501);
case (NAPI::ACT_ERROR_CODE)111:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2632);
case (NAPI::ACT_ERROR_CODE)112:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2631);
case (NAPI::ACT_ERROR_CODE)113:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2452);
case (NAPI::ACT_ERROR_CODE)114:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2593);
case (NAPI::ACT_ERROR_CODE)115:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2591);
case (NAPI::ACT_ERROR_CODE)116:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2614);
case (NAPI::ACT_ERROR_CODE)117:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2651);
case (NAPI::ACT_ERROR_CODE)118:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2484);
case (NAPI::ACT_ERROR_CODE)119:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2803);
case (NAPI::ACT_ERROR_CODE)120:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2813);
case (NAPI::ACT_ERROR_CODE)121:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2804);
case (NAPI::ACT_ERROR_CODE)122:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2814);
case (NAPI::ACT_ERROR_CODE)123:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2882);
case (NAPI::ACT_ERROR_CODE)124:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2512);
case (NAPI::ACT_ERROR_CODE)125:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2485);
case (NAPI::ACT_ERROR_CODE)126:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2805);
case (NAPI::ACT_ERROR_CODE)127:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2815);
case (NAPI::ACT_ERROR_CODE)128:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2661);
case (NAPI::ACT_ERROR_CODE)129:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2615);
case (NAPI::ACT_ERROR_CODE)130:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2531);
case (NAPI::ACT_ERROR_CODE)131:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2616);
case (NAPI::ACT_ERROR_CODE)132:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2822);
case (NAPI::ACT_ERROR_CODE)133:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2832);
case (NAPI::ACT_ERROR_CODE)134:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2823);
case (NAPI::ACT_ERROR_CODE)135:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2833);
case (NAPI::ACT_ERROR_CODE)136:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2824);
case (NAPI::ACT_ERROR_CODE)137:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2834);
case (NAPI::ACT_ERROR_CODE)138:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2825);
case (NAPI::ACT_ERROR_CODE)139:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2835);
case (NAPI::ACT_ERROR_CODE)142:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2635);
case (NAPI::ACT_ERROR_CODE)143:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2634);
case (NAPI::ACT_ERROR_CODE)1004:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2503);
case (NAPI::ACT_ERROR_CODE)1006:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2471);
case (NAPI::ACT_ERROR_CODE)1016:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2532);
case (NAPI::ACT_ERROR_CODE)1017:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2483);
case (NAPI::ACT_ERROR_CODE)1018:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2533);
case (NAPI::ACT_ERROR_CODE)1019:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2481);
case (NAPI::ACT_ERROR_CODE)1020:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2473);
case NAPI::ACT_ERROR_CODE::ACT_GAME_SERVER_NOT_FOUND:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2482);
case (NAPI::ACT_ERROR_CODE)1022:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2472);
case (NAPI::ACT_ERROR_CODE)1023:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2612);
case (NAPI::ACT_ERROR_CODE)1024:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2535);
case (NAPI::ACT_ERROR_CODE)1025:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2536);
case (NAPI::ACT_ERROR_CODE)1031:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2537);
case (NAPI::ACT_ERROR_CODE)1032:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2636);
case (NAPI::ACT_ERROR_CODE)1033:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2662);
case (NAPI::ACT_ERROR_CODE)1035:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2671);
case (NAPI::ACT_ERROR_CODE)1036:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2679);
case (NAPI::ACT_ERROR_CODE)1037:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2672);
case (NAPI::ACT_ERROR_CODE)1038:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2674);
case (NAPI::ACT_ERROR_CODE)1039:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2680);
case (NAPI::ACT_ERROR_CODE)1040:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2675);
case (NAPI::ACT_ERROR_CODE)1041:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2673);
case (NAPI::ACT_ERROR_CODE)1042:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2676);
case (NAPI::ACT_ERROR_CODE)1043:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2681);
case (NAPI::ACT_ERROR_CODE)1044:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2678);
case (NAPI::ACT_ERROR_CODE)1045:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2677);
case (NAPI::ACT_ERROR_CODE)1046:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2596);
case (NAPI::ACT_ERROR_CODE)1100:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2541);
case (NAPI::ACT_ERROR_CODE)1101:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2542);
case (NAPI::ACT_ERROR_CODE)1103:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2594);
case (NAPI::ACT_ERROR_CODE)1104:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2576);
case (NAPI::ACT_ERROR_CODE)1105:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2613);
case (NAPI::ACT_ERROR_CODE)1106:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2633);
case (NAPI::ACT_ERROR_CODE)1107:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2577);
case (NAPI::ACT_ERROR_CODE)1111:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2538);
case (NAPI::ACT_ERROR_CODE)1115:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2597);
case (NAPI::ACT_ERROR_CODE)1125:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2585);
case (NAPI::ACT_ERROR_CODE)1126:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2586);
case (NAPI::ACT_ERROR_CODE)1134:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2587);
case (NAPI::ACT_ERROR_CODE)1200:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2884);
case (NAPI::ACT_ERROR_CODE)2001:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2931);
case (NAPI::ACT_ERROR_CODE)2002:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2881);
case (NAPI::ACT_ERROR_CODE)2999:
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, (NN_ERROR_CODE)2883);
default:
break;
}
cemuLog_log(LogType::Force, "Received unknown ACT error code {}", (uint32)ec);
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, NN_ERROR_CODE::ACT_UNKNOWN_SERVER_ERROR);
}
namespace iosu
{
namespace act
{
uint8 getCurrentAccountSlot()
{
return 1;
}
actAccountData_t* GetAccountBySlotNo(uint8 slotNo)
{
// only call this while holding actMutex
uint8 accIndex;
if(slotNo == iosu::act::ACT_SLOT_CURRENT)
{
accIndex = getCurrentAccountSlot() - 1;
cemu_assert_debug(accIndex >= 0 && accIndex < IOSU_ACT_ACCOUNT_MAX_COUNT);
}
else if(slotNo > 0 && slotNo <= IOSU_ACT_ACCOUNT_MAX_COUNT)
accIndex = slotNo - 1;
else
{
return nullptr;
}
if(!_actAccountData[accIndex].isValid)
return nullptr;
return &_actAccountData[accIndex];
}
// has ownership of account data
// while any thread has a LockedAccount in non-null state no other thread can access the account data
class LockedAccount
{
public:
LockedAccount(uint8 slotNo)
{
iosuAct.actMutex.lock();
m_account = GetAccountBySlotNo(slotNo);
if(!m_account)
iosuAct.actMutex.unlock();
}
~LockedAccount()
{
if(m_account)
iosuAct.actMutex.unlock();
}
void Release()
{
if(m_account)
iosuAct.actMutex.unlock();
m_account = nullptr;
}
actAccountData_t* operator->()
{
return m_account;
}
actAccountData_t& operator*()
{
return *m_account;
}
LockedAccount(const LockedAccount&) = delete;
LockedAccount& operator=(const LockedAccount&) = delete;
operator bool() const { return m_account != nullptr; }
private:
actAccountData_t* m_account{nullptr};
};
bool getPrincipalId(uint8 slot, uint32* principalId)
{
sint32 accountIndex = iosuAct_getAccountIndexBySlot(slot);
if (_actAccountData[accountIndex].isValid == false)
{
*principalId = 0;
return false;
}
*principalId = _actAccountData[accountIndex].principalId;
return true;
}
bool getAccountId(uint8 slot, char* accountId)
{
sint32 accountIndex = iosuAct_getAccountIndexBySlot(slot);
if (_actAccountData[accountIndex].isValid == false)
{
*accountId = '\0';
return false;
}
strcpy(accountId, _actAccountData[accountIndex].accountId);
return true;
}
// returns empty string if invalid
std::string getAccountId2(uint8 slot)
{
sint32 accountIndex = iosuAct_getAccountIndexBySlot(slot);
if (_actAccountData[accountIndex].isValid == false)
return {};
return {_actAccountData[accountIndex].accountId};
}
bool getMii(uint8 slot, FFLData_t* fflData)
{
sint32 accountIndex = iosuAct_getAccountIndexBySlot(slot);
if (_actAccountData[accountIndex].isValid == false)
{
return false;
}
memcpy(fflData, &_actAccountData[accountIndex].miiData, sizeof(FFLData_t));
return true;
}
// return screenname in little-endian wide characters
bool getScreenname(uint8 slot, uint16 screenname[ACT_NICKNAME_LENGTH])
{
sint32 accountIndex = iosuAct_getAccountIndexBySlot(slot);
if (_actAccountData[accountIndex].isValid == false)
{
screenname[0] = '\0';
return false;
}
for (sint32 i = 0; i < ACT_NICKNAME_LENGTH; i++)
{
screenname[i] = (uint16)_actAccountData[accountIndex].miiNickname[i];
}
return true;
}
bool getCountryIndex(uint8 slot, uint32* countryIndex)
{
sint32 accountIndex = iosuAct_getAccountIndexBySlot(slot);
if (_actAccountData[accountIndex].isValid == false)
{
*countryIndex = 0;
return false;
}
*countryIndex = _actAccountData[accountIndex].countryIndex;
return true;
}
bool GetPersistentId(uint8 slot, uint32* persistentId)
{
sint32 accountIndex = iosuAct_getAccountIndexBySlot(slot);
if(!_actAccountData[accountIndex].isValid)
{
*persistentId = 0;
return false;
}
*persistentId = _actAccountData[accountIndex].persistentId;
return true;
}
nnResult AcquireNexToken(uint8 accountSlot, uint64 titleId, uint16 titleVersion, uint32 serverId, uint8* tokenOut, uint32 tokenLen)
{
if (accountSlot != ACT_SLOT_CURRENT)
return ACTResult_InvalidValue;
LockedAccount account(accountSlot);
if (!account)
return ACTResult_AccountDoesNotExist;
if (!account->IsNetworkAccount())
return ACTResult_NotANetworkAccount;
cemu_assert_debug(ActiveSettings::IsOnlineEnabled());
if (tokenLen != sizeof(NexToken))
return ACTResult_OutOfRange;
NAPI::AuthInfo authInfo;
NAPI::NAPI_MakeAuthInfoFromCurrentAccount(authInfo);
NAPI::ACTGetNexTokenResult nexTokenResult = NAPI::ACT_GetNexToken_WithCache(authInfo, titleId, titleVersion, serverId);
if (nexTokenResult.isValid())
{
memcpy(tokenOut, &nexTokenResult.nexToken, sizeof(NexToken));
return ACTResult_Ok;
}
else if (nexTokenResult.apiError == NAPI_RESULT::SERVICE_ERROR)
{
nnResult returnCode = ServerActErrorCodeToNNResult(nexTokenResult.serviceError);
cemu_assert_debug((returnCode&0x80000000) != 0);
return returnCode;
}
return nnResultStatus(NN_RESULT_MODULE_NN_ACT, NN_ERROR_CODE::ACT_UNKNOWN_SERVER_ERROR);
}
nnResult AcquireIndependentServiceToken(uint8 accountSlot, uint64 titleId, uint16 titleVersion, std::string_view clientId, uint8* tokenOut, uint32 tokenLen)
{
static constexpr size_t IndependentTokenMaxLength = 512+1; // 512 bytes + null terminator
if(accountSlot != ACT_SLOT_CURRENT)
return ACTResult_InvalidValue;
LockedAccount account(accountSlot);
if (!account)
return ACTResult_AccountDoesNotExist;
if (!account->IsNetworkAccount())
return ACTResult_NotANetworkAccount;
cemu_assert_debug(ActiveSettings::IsOnlineEnabled());
if (tokenLen < IndependentTokenMaxLength)
return ACTResult_OutOfRange;
NAPI::AuthInfo authInfo;
NAPI::NAPI_MakeAuthInfoFromCurrentAccount(authInfo);
account.Release();
NAPI::ACTGetIndependentTokenResult tokenResult = NAPI::ACT_GetIndependentToken_WithCache(authInfo, titleId, titleVersion, clientId);
uint32 returnCode = 0;
if (tokenResult.isValid())
{
for (size_t i = 0; i < std::min(tokenResult.token.size(), (size_t)IndependentTokenMaxLength); i++)
{
tokenOut[i] = tokenResult.token[i];
tokenOut[i + 1] = '\0';
}
returnCode = 0;
}
else
{
returnCode = 0x80000000; // todo - proper error codes
}
return returnCode;
}
class ActService : public iosu::nn::IPCService
{
public:
ActService() : iosu::nn::IPCService("/dev/act") {}
nnResult ServiceCall(uint32 serviceId, void* request, void* response) override
{
cemuLog_log(LogType::Force, "Unsupported service call to /dev/act");
cemu_assert_unimplemented();
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_ACT, 0);
}
};
ActService gActService;
void Initialize()
{
gActService.Start();
}
void Stop()
{
gActService.Stop();
}
}
}
// IOSU act IO
typedef struct
{
/* +0x00 */ uint32be ukn00;
/* +0x04 */ uint32be ukn04;
/* +0x08 */ uint32be ukn08;
/* +0x0C */ uint32be subcommandCode;
/* +0x10 */ uint8 ukn10;
/* +0x11 */ uint8 ukn11;
/* +0x12 */ uint8 ukn12;
/* +0x13 */ uint8 accountSlot;
/* +0x14 */ uint32be unique; // is this command specific?
}cmdActRequest00_t;
typedef struct
{
uint32be returnCode;
uint8 transferableIdBase[8];
}cmdActGetTransferableIDResult_t;
#define ACT_SUBCMD_GET_TRANSFERABLE_ID 4
#define ACT_SUBCMD_INITIALIZE 0x14
#define _cancelIfAccountDoesNotExist() \
if (_actAccountData[accountIndex].isValid == false) \
{ \
/* account does not exist*/ \
ioctlReturnValue = 0; \
actCemuRequest->setACTReturnCode(BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_ACT, NN_ACT_RESULT_ACCOUNT_DOES_NOT_EXIST)); /* 0xA071F480 */ \
actCemuRequest->resultU64.u64 = 0; \
iosuIoctl_completeRequest(ioQueueEntry, ioctlReturnValue); \
continue; \
}
int iosuAct_thread()
{
SetThreadName("iosuAct_thread");
while (true)
{
uint32 ioctlReturnValue = 0;
ioQueueEntry_t* ioQueueEntry = iosuIoctl_getNextWithWait(IOS_DEVICE_ACT);
if (ioQueueEntry->request == 0)
{
if (ioQueueEntry->countIn != 1 || ioQueueEntry->countOut != 1)
{
assert_dbg();
}
ioBufferVector_t* vectorsDebug = ioQueueEntry->bufferVectors.GetPtr();
void* outputBuffer = ioQueueEntry->bufferVectors[0].buffer.GetPtr();
cmdActRequest00_t* requestCmd = (cmdActRequest00_t*)ioQueueEntry->bufferVectors[0].unknownBuffer.GetPtr();
if (requestCmd->subcommandCode == ACT_SUBCMD_INITIALIZE)
{
// do nothing for now (there is no result?)
}
else if (requestCmd->subcommandCode == ACT_SUBCMD_GET_TRANSFERABLE_ID)
{
cmdActGetTransferableIDResult_t* cmdResult = (cmdActGetTransferableIDResult_t*)outputBuffer;
cmdResult->returnCode = 0;
*(uint64*)cmdResult->transferableIdBase = _swapEndianU64(0x1122334455667788);
}
else
assert_dbg();
}
else if (ioQueueEntry->request == IOSU_ACT_REQUEST_CEMU)
{
iosuActCemuRequest_t* actCemuRequest = (iosuActCemuRequest_t*)ioQueueEntry->bufferVectors[0].buffer.GetPtr();
sint32 accountIndex;
ioctlReturnValue = 0;
if (actCemuRequest->requestCode == IOSU_ARC_ACCOUNT_ID)
{
accountIndex = iosuAct_getAccountIndexBySlot(actCemuRequest->accountSlot);
_cancelIfAccountDoesNotExist();
strcpy(actCemuRequest->resultString.strBuffer, _actAccountData[accountIndex].accountId);
actCemuRequest->setACTReturnCode(0);
}
else if (actCemuRequest->requestCode == IOSU_ARC_UUID)
{
accountIndex = iosuAct_getAccountIndexBySlot(actCemuRequest->accountSlot);
if (actCemuRequest->accountSlot == 0xFF)
{
// common uuid (placeholder algorithm)
for (uint32 i = 0; i < 16; i++)
actCemuRequest->resultBinary.binBuffer[i] = i * 0x74 + i + ~i + i * 133;
}
else
{
_cancelIfAccountDoesNotExist();
memcpy(actCemuRequest->resultBinary.binBuffer, _actAccountData[accountIndex].uuid, 16);
}
cemu_assert_debug(actCemuRequest->uuidName != -1); // todo
if (actCemuRequest->uuidName != -1 && actCemuRequest->uuidName != -2)
{
// generate name based UUID
// format:
// first 10 bytes of UUID + 6 bytes of a hash
// hash algorithm:
// sha256 of
// 4 bytes uuidName (big-endian)
// 4 bytes 0x3A275E09 (big-endian)
// 6 bytes from the end of UUID
// bytes 10-15 are used from the hash and replace the last 6 bytes of the UUID
EVP_MD_CTX *ctx_sha256 = EVP_MD_CTX_new();
EVP_DigestInit(ctx_sha256, EVP_sha256());
uint32 name = (uint32)actCemuRequest->uuidName;
uint8 tempArray[] = {
static_cast<uint8>((name >> 24) & 0xFF),
static_cast<uint8>((name >> 16) & 0xFF),
static_cast<uint8>((name >> 8) & 0xFF),
static_cast<uint8>((name >> 0) & 0xFF),
0x3A,
0x27,
0x5E,
0x09,
};
EVP_DigestUpdate(ctx_sha256, tempArray, sizeof(tempArray));
EVP_DigestUpdate(ctx_sha256, actCemuRequest->resultBinary.binBuffer+10, 6);
uint8 h[SHA256_DIGEST_LENGTH];
EVP_DigestFinal_ex(ctx_sha256, h, NULL);
EVP_MD_CTX_free(ctx_sha256);
memcpy(actCemuRequest->resultBinary.binBuffer + 0xA, h + 0xA, 6);
}
else if (actCemuRequest->uuidName == -2)
{
// return account uuid
}
else
{
cemuLog_logDebug(LogType::Force, "Gen UUID unknown mode {}", actCemuRequest->uuidName);
}
actCemuRequest->setACTReturnCode(0);
}
else if (actCemuRequest->requestCode == IOSU_ARC_SIMPLEADDRESS)
{
accountIndex = iosuAct_getAccountIndexBySlot(actCemuRequest->accountSlot);
_cancelIfAccountDoesNotExist();
actCemuRequest->resultU32.u32 = _actAccountData[accountIndex].simpleAddressId;
actCemuRequest->setACTReturnCode(0);
}
else if (actCemuRequest->requestCode == IOSU_ARC_PRINCIPALID)
{
accountIndex = iosuAct_getAccountIndexBySlot(actCemuRequest->accountSlot);
_cancelIfAccountDoesNotExist();
actCemuRequest->resultU32.u32 = _actAccountData[accountIndex].principalId;
actCemuRequest->setACTReturnCode(0);
}
else if (actCemuRequest->requestCode == IOSU_ARC_TRANSFERABLEID)
{
accountIndex = iosuAct_getAccountIndexBySlot(actCemuRequest->accountSlot);
_cancelIfAccountDoesNotExist();
actCemuRequest->resultU64.u64 = _actAccountData[accountIndex].transferableIdBase;
// todo - transferable also contains a unique id
actCemuRequest->setACTReturnCode(0);
}
else if (actCemuRequest->requestCode == IOSU_ARC_PERSISTENTID)
{
if(actCemuRequest->accountSlot != 0)
{
accountIndex = iosuAct_getAccountIndexBySlot(actCemuRequest->accountSlot);
_cancelIfAccountDoesNotExist();
actCemuRequest->resultU32.u32 = _actAccountData[accountIndex].persistentId;
actCemuRequest->setACTReturnCode(0);
}
else
{
// F1 Race Stars calls IsSlotOccupied and indirectly GetPersistentId on slot 0 which is not valid
actCemuRequest->resultU32.u32 = 0;
actCemuRequest->setACTReturnCode(0);
}
}
else if (actCemuRequest->requestCode == IOSU_ARC_COUNTRY)
{
accountIndex = iosuAct_getAccountIndexBySlot(actCemuRequest->accountSlot);
_cancelIfAccountDoesNotExist();
strcpy(actCemuRequest->resultString.strBuffer, _actAccountData[accountIndex].country);
actCemuRequest->setACTReturnCode(0);
}
else if (actCemuRequest->requestCode == IOSU_ARC_ISNETWORKACCOUNT)
{
accountIndex = iosuAct_getAccountIndexBySlot(actCemuRequest->accountSlot);
_cancelIfAccountDoesNotExist();
actCemuRequest->resultU32.u32 = _actAccountData[accountIndex].isNetworkAccount;
actCemuRequest->setACTReturnCode(0);
}
else if (actCemuRequest->requestCode == IOSU_ARC_ACQUIRENEXTOKEN)
{
nnResult r = iosu::act::AcquireNexToken(actCemuRequest->accountSlot, actCemuRequest->titleId, actCemuRequest->titleVersion, actCemuRequest->serverId, actCemuRequest->resultBinary.binBuffer, sizeof(NexToken));
actCemuRequest->setACTReturnCode(r);
}
else if (actCemuRequest->requestCode == IOSU_ARC_ACQUIREINDEPENDENTTOKEN)
{
nnResult r = iosu::act::AcquireIndependentServiceToken(actCemuRequest->accountSlot, actCemuRequest->titleId, actCemuRequest->titleVersion, actCemuRequest->clientId, actCemuRequest->resultBinary.binBuffer, sizeof(actCemuRequest->resultBinary.binBuffer));
actCemuRequest->setACTReturnCode(r);
}
else if (actCemuRequest->requestCode == IOSU_ARC_ACQUIREPIDBYNNID)
{
uint32 returnCode = iosuAct_acquirePrincipalIdByAccountId(actCemuRequest->clientId, &actCemuRequest->resultU32.u32);
actCemuRequest->setACTReturnCode(returnCode);
}
else if (actCemuRequest->requestCode == IOSU_ARC_MIIDATA)
{
accountIndex = iosuAct_getAccountIndexBySlot(actCemuRequest->accountSlot);
_cancelIfAccountDoesNotExist();
memcpy(actCemuRequest->resultBinary.binBuffer, &_actAccountData[accountIndex].miiData, sizeof(FFLData_t));
actCemuRequest->setACTReturnCode(0);
}
else if (actCemuRequest->requestCode == IOSU_ARC_INIT)
{
iosuAct_loadAccounts();
actCemuRequest->setACTReturnCode(0);
}
else
assert_dbg();
}
else
{
assert_dbg();
}
iosuIoctl_completeRequest(ioQueueEntry, ioctlReturnValue);
}
return 0;
}
void iosuAct_init_depr()
{
if (iosuAct.isInitialized)
return;
std::thread t(iosuAct_thread);
t.detach();
iosuAct.isInitialized = true;
}
bool iosuAct_isInitialized()
{
return iosuAct.isInitialized;
}
uint16 FFLCalculateCRC16(uint8* input, sint32 length)
{
uint16 crc = 0;
for (sint32 c = 0; c < length; c++)
{
for (sint32 f = 0; f < 8; f++)
{
if ((crc & 0x8000) != 0)
{
uint16 t = crc << 1;
crc = t ^ 0x1021;
}
else
{
crc <<= 1;
}
}
crc ^= (uint16)input[c];
}
return crc;
}
| 31,218
|
C++
|
.cpp
| 825
| 34.527273
| 257
| 0.740354
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,177
|
iosu_crypto.cpp
|
cemu-project_Cemu/src/Cafe/IOSU/legacy/iosu_crypto.cpp
|
#include "iosu_crypto.h"
#include "config/ActiveSettings.h"
#include "openssl/bn.h"
#include "openssl/obj_mac.h"
#include "openssl/ec.h"
#include "openssl/x509.h"
#include "openssl/ssl.h"
#include "openssl/ecdsa.h"
#include "util/crypto/aes128.h"
#include "Common/FileStream.h"
uint8 otpMem[1024];
bool hasOtpMem = false;
uint8 seepromMem[512];
bool hasSeepromMem = false;
struct
{
bool hasCertificates;
struct
{
bool isValid;
sint32 id;
X509* cert;
std::vector<uint8> certData;
RSA* pkey;
std::vector<uint8> pkeyDERData;
}certList[256];
sint32 certListCount;
}iosuCryptoCertificates = { 0 };
CertECC_t g_wiiuDeviceCert;
void iosuCrypto_readOtpData(void* output, sint32 wordIndex, sint32 size)
{
memcpy(output, otpMem + wordIndex * 4, size);
}
void iosuCrypto_readOtpData(uint32be& output, sint32 wordIndex)
{
memcpy(&output, otpMem + wordIndex * 4, sizeof(uint32be));
}
void iosuCrypto_readSeepromData(void* output, sint32 wordIndex, sint32 size)
{
memcpy(output, seepromMem + wordIndex * 2, size);
}
bool iosuCrypto_getDeviceId(uint32* deviceId)
{
uint32be deviceIdBE;
*deviceId = 0;
if (!hasOtpMem)
return false;
iosuCrypto_readOtpData(&deviceIdBE, 0x87, sizeof(uint32));
*deviceId = (uint32)deviceIdBE;
return true;
}
void iosuCrypto_getDeviceSerialString(char* serialString)
{
char serialStringPart0[32]; // code
char serialStringPart1[32]; // serial
if (hasSeepromMem == false)
{
strcpy(serialString, "FEH000000000");
return;
}
memset(serialStringPart0, 0, sizeof(serialStringPart0));
memset(serialStringPart1, 0, sizeof(serialStringPart1));
iosuCrypto_readSeepromData(serialStringPart0, 0xAC, 8);
iosuCrypto_readSeepromData(serialStringPart1, 0xB0, 0x10);
sprintf(serialString, "%s%s", serialStringPart0, serialStringPart1);
}
static const char* base64_charset =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
int iosuCrypto_base64Encode(unsigned char const* bytes_to_encode, unsigned int inputLen, char* output)
{
int i = 0;
int j = 0;
unsigned char charArray_3[3];
unsigned char charArray_4[4];
sint32 outputLength = 0;
while (inputLen--)
{
charArray_3[i++] = *(bytes_to_encode++);
if (i == 3)
{
charArray_4[0] = (charArray_3[0] & 0xfc) >> 2;
charArray_4[1] = ((charArray_3[0] & 0x03) << 4) + ((charArray_3[1] & 0xf0) >> 4);
charArray_4[2] = ((charArray_3[1] & 0x0f) << 2) + ((charArray_3[2] & 0xc0) >> 6);
charArray_4[3] = charArray_3[2] & 0x3f;
for (i = 0; (i < 4); i++)
{
output[outputLength] = base64_charset[charArray_4[i]];
outputLength++;
}
i = 0;
}
}
if (i)
{
for (j = i; j < 3; j++)
charArray_3[j] = '\0';
charArray_4[0] = (charArray_3[0] & 0xfc) >> 2;
charArray_4[1] = ((charArray_3[0] & 0x03) << 4) + ((charArray_3[1] & 0xf0) >> 4);
charArray_4[2] = ((charArray_3[1] & 0x0f) << 2) + ((charArray_3[2] & 0xc0) >> 6);
charArray_4[3] = charArray_3[2] & 0x3f;
for (j = 0; j < (i + 1); j++)
{
output[outputLength] = base64_charset[charArray_4[j]];
outputLength++;
}
while (i++ < 3)
{
output[outputLength] = '=';
outputLength++;
}
}
return outputLength;
}
std::string iosuCrypto_base64Encode(unsigned char const* bytes_to_encode, unsigned int inputLen)
{
int encodedLen = inputLen / 3 * 4 + 16;
std::string strB64;
strB64.resize(encodedLen);
int outputLen = iosuCrypto_base64Encode(bytes_to_encode, inputLen, strB64.data());
cemu_assert_debug(outputLen < strB64.size());
strB64.resize(outputLen);
return strB64;
}
static_assert(sizeof(CertECC_t) == sizeof(CertECC_t));
EC_KEY* ECCPubKey_getPublicKey(ECCPubKey& pubKey) // verified and works
{
BIGNUM* bn_r = BN_new();
BIGNUM* bn_s = BN_new();
BN_bin2bn(pubKey.keyData + 0, 30, bn_r);
BN_bin2bn(pubKey.keyData + 30, 30, bn_s);
EC_KEY* ec_pubKey = EC_KEY_new_by_curve_name(NID_sect233r1);
int r = EC_KEY_set_public_key_affine_coordinates(ec_pubKey, bn_r, bn_s);
BN_free(bn_r);
BN_free(bn_s);
return ec_pubKey;
}
ECDSA_SIG* ECCPubKey_getSignature(CertECC_t& cert)
{
BIGNUM* bn_r = BN_new();
BIGNUM* bn_s = BN_new();
BN_bin2bn(cert.signature + 0, 30, bn_r);
BN_bin2bn(cert.signature + 30, 30, bn_s);
//EC_KEY* ec_pubKey = EC_KEY_new_by_curve_name(NID_sect233r1);
//int r = EC_KEY_set_public_key_affine_coordinates(ec_pubKey, bn_r, bn_s);
ECDSA_SIG* ec_sig = ECDSA_SIG_new();
//ECDSA_do_sign_ex
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
ECDSA_SIG_set0(ec_sig, bn_r, bn_s);
#else
BN_copy(ec_sig->r, bn_r);
BN_copy(ec_sig->s, bn_s);
#endif
BN_free(bn_r);
BN_free(bn_s);
return ec_sig;
}
void ECCPubKey_setSignature(CertECC_t& cert, ECDSA_SIG* sig)
{
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
const BIGNUM* sig_r = nullptr, * sig_s = nullptr;
ECDSA_SIG_get0(sig, &sig_r, &sig_s);
sint32 lenR = BN_num_bytes(sig_r);
sint32 lenS = BN_num_bytes(sig_s);
cemu_assert_debug(lenR <= 30);
cemu_assert_debug(lenS <= 30);
memset(cert.signature, 0, sizeof(cert.signature));
BN_bn2bin(sig_r, cert.signature + (30 - lenR));
BN_bn2bin(sig_s, cert.signature + 60 / 2 + (30 - lenS));
#else
sint32 lenR = BN_num_bytes(sig->r);
sint32 lenS = BN_num_bytes(sig->s);
cemu_assert_debug(lenR <= 30);
cemu_assert_debug(lenS <= 30);
memset(cert.signature, 0, sizeof(cert.signature));
BN_bn2bin(sig->r, cert.signature + (30 - lenR));
BN_bn2bin(sig->s, cert.signature + 60 / 2 + (30 - lenS));
#endif
}
ECCPrivKey g_consoleCertPrivKey{};
void iosuCrypto_getDeviceCertPrivateKey(void* privKeyOut, sint32 len)
{
cemu_assert(len == 30);
memcpy(privKeyOut, g_consoleCertPrivKey.keyData, 30);
}
void iosuCrypto_getDeviceCertificate(void* certOut, sint32 len)
{
cemu_assert(len == 0x180);
memcpy(certOut, &g_wiiuDeviceCert, 0x180);
}
void iosuCrypto_generateDeviceCertificate()
{
static_assert(sizeof(g_wiiuDeviceCert) == 0x180);
memset(&g_wiiuDeviceCert, 0, sizeof(g_wiiuDeviceCert));
if (!hasOtpMem)
return; // cant generate certificate without OPT
// set header based on otp security mode
g_wiiuDeviceCert.sigType = CertECC_t::SIGTYPE::ECC_SHA256;
g_wiiuDeviceCert.ukn0C0[0] = 0x00;
g_wiiuDeviceCert.ukn0C0[1] = 0x00;
g_wiiuDeviceCert.ukn0C0[2] = 0x00;
g_wiiuDeviceCert.ukn0C0[3] = 0x02;
iosuCrypto_readOtpData(g_wiiuDeviceCert.signature, 0xA3, 0x3C);
uint32be caValue;
iosuCrypto_readOtpData(caValue, 0xA1);
uint32be msValue;
iosuCrypto_readOtpData(msValue, 0xA0);
sprintf(g_wiiuDeviceCert.certificateSubject, "Root-CA%08x-MS%08x", (uint32)caValue, (uint32)msValue);
uint32be ngNameValue;
iosuCrypto_readOtpData(ngNameValue, 0x87);
sprintf(g_wiiuDeviceCert.ngName, "NG%08x", (uint32)ngNameValue);
iosuCrypto_readOtpData(&g_wiiuDeviceCert.ngKeyId, 0xA2, sizeof(uint32));
uint8 privateKey[0x20];
memset(privateKey, 0, sizeof(privateKey));
iosuCrypto_readOtpData(privateKey, 0x88, 0x1E);
memcpy(g_consoleCertPrivKey.keyData, privateKey, 30);
auto context = BN_CTX_new();
BN_CTX_start(context);
BIGNUM* bn_privKey = BN_CTX_get(context);
BN_bin2bn(privateKey, 0x1E, bn_privKey);
EC_GROUP *group = EC_GROUP_new_by_curve_name(NID_sect233r1);
EC_POINT *pubkey = EC_POINT_new(group);
EC_POINT_mul(group, pubkey, bn_privKey, NULL, NULL, NULL);
BIGNUM* bn_x = BN_CTX_get(context);
BIGNUM* bn_y = BN_CTX_get(context);
EC_POINT_get_affine_coordinates(group, pubkey, bn_x, bn_y, NULL);
uint8 publicKeyOutput[0x3C];
memset(publicKeyOutput, 0, sizeof(publicKeyOutput));
sint32 lenX = BN_num_bytes(bn_x);
sint32 lenY = BN_num_bytes(bn_y);
BN_bn2bin(bn_x, publicKeyOutput + (0x1E - lenX)); // todo - verify if the bias is correct
BN_bn2bin(bn_y, publicKeyOutput + 0x3C / 2 + (0x1E - lenY));
memcpy(g_wiiuDeviceCert.publicKey, publicKeyOutput, 0x3C);
// clean up
EC_POINT_free(pubkey);
BN_CTX_end(context); // clears all BN variables
BN_CTX_free(context);
}
sint32 iosuCrypto_getDeviceCertificateBase64Encoded(char* output)
{
iosuCrypto_base64Encode((uint8*)&g_wiiuDeviceCert, sizeof(g_wiiuDeviceCert), output);
sint32 len = sizeof(g_wiiuDeviceCert) / 3 * 4;
output[len] = '\0';
return len;
}
bool iosuCrypto_loadCertificate(uint32 id, std::wstring_view mlcSubpath, std::wstring_view pkeyMlcSubpath)
{
X509* cert = nullptr;
// load cert data
const auto certPath = ActiveSettings::GetMlcPath(mlcSubpath);
auto certData = FileStream::LoadIntoMemory(certPath);
if (!certData)
return false; // file missing
// get optional aes encrypted private key data
std::optional<std::vector<uint8>> pkeyData;
if (!pkeyMlcSubpath.empty())
{
const auto pkeyPath = ActiveSettings::GetMlcPath(pkeyMlcSubpath);
pkeyData = FileStream::LoadIntoMemory(pkeyPath);
if (!pkeyData || pkeyData->empty())
{
cemuLog_log(LogType::Force, "Unable to load private key file {}", pkeyPath.generic_string());
return false;
}
else if ((pkeyData->size() % 16) != 0)
{
cemuLog_log(LogType::Force, "Private key file has invalid length. Possibly corrupted? File: {}", pkeyPath.generic_string());
return false;
}
}
// load certificate
unsigned char* tempPtr = (unsigned char*)certData->data();
cert = d2i_X509(nullptr, (const unsigned char**)&tempPtr, certData->size());
if (cert == nullptr)
{
cemuLog_log(LogType::Force, "IOSU_CRYPTO: Unable to load certificate \"{}\"", boost::nowide::narrow(std::wstring(mlcSubpath)));
return false;
}
// load optional rsa key
RSA* pkeyRSA = nullptr;
if (pkeyData)
{
cemu_assert((pkeyData->size() & 15) == 0);
uint8 aesKey[16];
uint8 iv[16] = { 0 };
uint8 pkeyDecryptedData[4096];
// decrypt pkey
iosuCrypto_readOtpData(aesKey, 0x120 / 4, 16);
AES128_CBC_decrypt(pkeyDecryptedData, pkeyData->data(), pkeyData->size(), aesKey, iv);
// convert to OpenSSL RSA pkey
unsigned char* pkeyTempPtr = pkeyDecryptedData;
pkeyRSA = d2i_RSAPrivateKey(nullptr, (const unsigned char **)&pkeyTempPtr, pkeyData->size());
if (pkeyRSA == nullptr)
{
cemuLog_log(LogType::Force, "IOSU_CRYPTO: Unable to decrypt private key \"{}\"", boost::nowide::narrow(std::wstring(pkeyMlcSubpath)));
return false;
}
// encode private key as DER
EVP_PKEY *evpPkey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(evpPkey, pkeyRSA);
std::vector<uint8> derPKeyData(1024 * 32);
unsigned char* derPkeyTemp = derPKeyData.data();
sint32 derPkeySize = i2d_PrivateKey(evpPkey, &derPkeyTemp);
derPKeyData.resize(derPkeySize);
derPKeyData.shrink_to_fit();
iosuCryptoCertificates.certList[iosuCryptoCertificates.certListCount].pkeyDERData = derPKeyData;
}
// register certificate and optional pkey
iosuCryptoCertificates.certList[iosuCryptoCertificates.certListCount].cert = cert;
iosuCryptoCertificates.certList[iosuCryptoCertificates.certListCount].certData = *certData;
iosuCryptoCertificates.certList[iosuCryptoCertificates.certListCount].pkey = pkeyRSA;
iosuCryptoCertificates.certList[iosuCryptoCertificates.certListCount].id = id;
iosuCryptoCertificates.certList[iosuCryptoCertificates.certListCount].isValid = true;
iosuCryptoCertificates.certListCount++;
return true;
}
bool iosuCrypto_addClientCertificate(void* sslctx, sint32 certificateId)
{
SSL_CTX* ctx = (SSL_CTX*)sslctx;
// find entry
for (sint32 i = 0; i < iosuCryptoCertificates.certListCount; i++)
{
if (iosuCryptoCertificates.certList[i].isValid && iosuCryptoCertificates.certList[i].id == certificateId)
{
if (SSL_CTX_use_certificate(ctx, iosuCryptoCertificates.certList[i].cert) != 1)
{
cemuLog_log(LogType::Force, "Unable to setup certificate {}", certificateId);
return false;
}
if (SSL_CTX_use_RSAPrivateKey(ctx, iosuCryptoCertificates.certList[i].pkey) != 1)
{
cemuLog_log(LogType::Force, "Unable to setup certificate {} RSA private key", certificateId);
return false;
}
if (SSL_CTX_check_private_key(ctx) == false)
{
cemuLog_log(LogType::Force, "Certificate private key could not be validated (verify required files for online mode or disable online mode)");
}
return true;
}
}
cemuLog_log(LogType::Force, "Certificate not found (verify required files for online mode or disable online mode)");
return false;
}
bool iosuCrypto_addCACertificate(void* sslctx, sint32 certificateId)
{
SSL_CTX* ctx = (SSL_CTX*)sslctx;
// find entry
for (sint32 i = 0; i < iosuCryptoCertificates.certListCount; i++)
{
if (iosuCryptoCertificates.certList[i].isValid && iosuCryptoCertificates.certList[i].id == certificateId)
{
X509_STORE* store = SSL_CTX_get_cert_store((SSL_CTX*)sslctx);
X509_STORE_add_cert(store, iosuCryptoCertificates.certList[i].cert);
return true;
}
}
return false;
}
bool iosuCrypto_addCustomCACertificate(void* sslctx, uint8* certData, sint32 certLength)
{
SSL_CTX* ctx = (SSL_CTX*)sslctx;
X509_STORE* store = SSL_CTX_get_cert_store((SSL_CTX*)sslctx);
unsigned char* tempPtr = (unsigned char*)certData;
X509* cert = d2i_X509(NULL, (const unsigned char**)&tempPtr, certLength);
if (cert == nullptr)
{
cemuLog_log(LogType::Force, "Invalid custom server PKI certificate");
return false;
}
X509_STORE_add_cert(store, cert);
return true;
}
uint8* iosuCrypto_getCertificateDataById(sint32 certificateId, sint32* certificateSize)
{
for (sint32 i = 0; i < iosuCryptoCertificates.certListCount; i++)
{
if (iosuCryptoCertificates.certList[i].isValid && iosuCryptoCertificates.certList[i].id == certificateId)
{
*certificateSize = iosuCryptoCertificates.certList[i].certData.size();
return iosuCryptoCertificates.certList[i].certData.data();
}
}
return nullptr;
}
uint8* iosuCrypto_getCertificatePrivateKeyById(sint32 certificateId, sint32* certificateSize)
{
for (sint32 i = 0; i < iosuCryptoCertificates.certListCount; i++)
{
if (iosuCryptoCertificates.certList[i].isValid && iosuCryptoCertificates.certList[i].id == certificateId)
{
*certificateSize = iosuCryptoCertificates.certList[i].pkeyDERData.size();
return iosuCryptoCertificates.certList[i].pkeyDERData.data();
}
}
return nullptr;
}
struct
{
const int id;
const wchar_t name[256];
const wchar_t key[256];
} const g_certificates[] = {
// NINTENDO CLIENT CERTS
{ 1, L"ccerts/WIIU_COMMON_1_CERT.der", L"ccerts/WIIU_COMMON_1_RSA_KEY.aes" },
{ 3, L"ccerts/WIIU_ACCOUNT_1_CERT.der", L"ccerts/WIIU_ACCOUNT_1_RSA_KEY.aes" },
{ 4, L"ccerts/WIIU_OLIVE_1_CERT.der", L"ccerts/WIIU_OLIVE_1_RSA_KEY.aes" },
{ 5, L"ccerts/WIIU_VINO_1_CERT.der", L"ccerts/WIIU_VINO_1_RSA_KEY.aes" },
{ 6, L"ccerts/WIIU_WOOD_1_CERT.der", L"ccerts/WIIU_WOOD_1_RSA_KEY.aes" },
{ 7, L"ccerts/WIIU_OLIVE_1_CERT.der", L"ccerts/WIIU_OLIVE_1_RSA_KEY.aes" },
{ 8, L"ccerts/WIIU_WOOD_1_CERT.der", L"ccerts/WIIU_WOOD_1_RSA_KEY.aes" },
// NINTENDO CA CERTS
{ 100, L"scerts/CACERT_NINTENDO_CA.der", L"" },
{ 101, L"scerts/CACERT_NINTENDO_CA_G2.der", L"" },
{ 102, L"scerts/CACERT_NINTENDO_CA_G3.der", L"" },
{ 103, L"scerts/CACERT_NINTENDO_CLASS2_CA.der", L"" },
{ 104, L"scerts/CACERT_NINTENDO_CLASS2_CA_G2.der", L"" },
{ 105, L"scerts/CACERT_NINTENDO_CLASS2_CA_G3.der", L"" },
// COMMERCIAL CA CERTS
{ 1001, L"scerts/BALTIMORE_CYBERTRUST_ROOT_CA.der", L"" },
{ 1002, L"scerts/CYBERTRUST_GLOBAL_ROOT_CA.der", L"" },
{ 1003, L"scerts/VERIZON_GLOBAL_ROOT_CA.der", L"" },
{ 1004, L"scerts/GLOBALSIGN_ROOT_CA.der", L"" },
{ 1005, L"scerts/GLOBALSIGN_ROOT_CA_R2.der", L"" },
{ 1006, L"scerts/GLOBALSIGN_ROOT_CA_R3.der", L"" },
{ 1007, L"scerts/VERISIGN_CLASS3_PUBLIC_PRIMARY_CA_G3.der", L"" },
{ 1008, L"scerts/VERISIGN_UNIVERSAL_ROOT_CA.der", L"" },
{ 1009, L"scerts/VERISIGN_CLASS3_PUBLIC_PRIMARY_CA_G5.der", L"" },
{ 1010, L"scerts/THAWTE_PRIMARY_ROOT_CA_G3.der", L"" },
{ 1011, L"scerts/THAWTE_PRIMARY_ROOT_CA.der", L"" },
{ 1012, L"scerts/GEOTRUST_GLOBAL_CA.der", L"" },
{ 1013, L"scerts/GEOTRUST_GLOBAL_CA2.der", L"" },
{ 1014, L"scerts/GEOTRUST_PRIMARY_CA.der", L"" },
{ 1015, L"scerts/GEOTRUST_PRIMARY_CA_G3.der", L"" },
{ 1016, L"scerts/ADDTRUST_EXT_CA_ROOT.der", L"" },
{ 1017, L"scerts/COMODO_CA.der", L"" },
{ 1018, L"scerts/UTN_DATACORP_SGC_CA.der", L"" },
{ 1019, L"scerts/UTN_USERFIRST_HARDWARE_CA.der" , L"" },
{ 1020, L"scerts/DIGICERT_HIGH_ASSURANCE_EV_ROOT_CA.der", L"" },
{ 1021, L"scerts/DIGICERT_ASSURED_ID_ROOT_CA.der", L"" },
{ 1022, L"scerts/DIGICERT_GLOBAL_ROOT_CA.der", L"" },
{ 1023, L"scerts/GTE_CYBERTRUST_GLOBAL_ROOT.der", L"" },
{ 1024, L"scerts/VERISIGN_CLASS3_PUBLIC_PRIMARY_CA.der", L"" },
{ 1025, L"scerts/THAWTE_PREMIUM_SERVER_CA.der", L"" },
{ 1026, L"scerts/EQUIFAX_SECURE_CA.der", L"" },
{ 1027, L"scerts/ENTRUST_SECURE_SERVER_CA.der", L"" },
{ 1028, L"scerts/VERISIGN_CLASS3_PUBLIC_PRIMARY_CA_G2.der", L"" },
{ 1029, L"scerts/ENTRUST_CA_2048.der", L"" },
{ 1030, L"scerts/ENTRUST_ROOT_CA.der", L"" },
{ 1031, L"scerts/ENTRUST_ROOT_CA_G2.der", L"" },
{ 1032, L"scerts/DIGICERT_ASSURED_ID_ROOT_CA_G2.der", L"" },
{ 1033, L"scerts/DIGICERT_GLOBAL_ROOT_CA_G2.der", L"" },
};
void iosuCrypto_loadSSLCertificates()
{
if (iosuCryptoCertificates.hasCertificates)
return;
if (!hasOtpMem)
return; // cant load certificates without OTP keys
// load CA certificate
bool hasAllCertificates = true;
for( const auto& c : g_certificates )
{
std::wstring certDir = L"sys/title/0005001b/10054000/content/";
std::wstring certFilePath = certDir + c.name;
std::wstring keyFilePath;
if( *c.key )
keyFilePath = certDir + c.key;
else
keyFilePath.clear();
if (iosuCrypto_loadCertificate(c.id, certFilePath, keyFilePath) == false)
{
cemuLog_log(LogType::Force, "Unable to load certificate \"{}\"", boost::nowide::narrow(certFilePath));
hasAllCertificates = false;
}
}
iosuCryptoCertificates.hasCertificates = hasAllCertificates; // true
}
void iosuCrypto_init()
{
// load OTP dump
if (std::ifstream otp_file(ActiveSettings::GetUserDataPath("otp.bin"), std::ifstream::in | std::ios::binary); otp_file.is_open())
{
otp_file.seekg(0, std::ifstream::end);
const auto length = otp_file.tellg();
otp_file.seekg(0, std::ifstream::beg);
// verify if OTP is ok
if (length != 1024) // todo - should also check some fixed values to verify integrity of otp dump
{
cemuLog_log(LogType::Force, "IOSU_CRYPTO: otp.bin has wrong size (must be 1024 bytes)");
hasOtpMem = false;
}
else
{
otp_file.read((char*)otpMem, 1024);
hasOtpMem = (bool)otp_file;
}
}
else
{
cemuLog_log(LogType::Force, "IOSU_CRYPTO: No otp.bin found. Online mode cannot be used");
hasOtpMem = false;
}
if (std::ifstream seeprom_file(ActiveSettings::GetUserDataPath("seeprom.bin"), std::ifstream::in | std::ios::binary); seeprom_file.is_open())
{
seeprom_file.seekg(0, std::ifstream::end);
const auto length = seeprom_file.tellg();
seeprom_file.seekg(0, std::ifstream::beg);
// verify if seeprom is ok
if (length != 512) // todo - maybe check some known values to verify integrity of seeprom
{
cemuLog_log(LogType::Force, "IOSU_CRYPTO: seeprom.bin has wrong size (must be 512 bytes)");
hasSeepromMem = false;
}
else
{
seeprom_file.read((char*)seepromMem, 512);
hasSeepromMem = (bool)seeprom_file;
}
}
else
{
cemuLog_log(LogType::Force, "IOSU_CRYPTO: No Seeprom.bin found. Online mode cannot be used");
hasSeepromMem = false;
}
// generate device certificate
iosuCrypto_generateDeviceCertificate();
// load SSL certificates
iosuCrypto_loadSSLCertificates();
}
bool iosuCrypto_checkRequirementMLCFile(std::string_view mlcSubpath, std::string& additionalErrorInfo_filePath)
{
const auto path = ActiveSettings::GetMlcPath(mlcSubpath);
additionalErrorInfo_filePath = _pathToUtf8(path);
sint32 fileDataSize = 0;
auto fileData = FileStream::LoadIntoMemory(path);
if (!fileData)
return false;
return true;
}
sint32 iosuCrypt_checkRequirementsForOnlineMode(std::string& additionalErrorInfo)
{
std::error_code ec;
// check if otp.bin is present
const auto otp_file = ActiveSettings::GetUserDataPath("otp.bin");
if(!fs::exists(otp_file, ec))
return IOS_CRYPTO_ONLINE_REQ_OTP_MISSING;
if(fs::file_size(otp_file, ec) != 1024)
return IOS_CRYPTO_ONLINE_REQ_OTP_CORRUPTED;
// check if seeprom.bin is present
const auto seeprom_file = ActiveSettings::GetUserDataPath("seeprom.bin");
if (!fs::exists(seeprom_file, ec))
return IOS_CRYPTO_ONLINE_REQ_SEEPROM_MISSING;
if (fs::file_size(seeprom_file, ec) != 512)
return IOS_CRYPTO_ONLINE_REQ_SEEPROM_CORRUPTED;
for (const auto& c : g_certificates)
{
std::string subPath = fmt::format("sys/title/0005001b/10054000/content/{}", boost::nowide::narrow(c.name));
if (iosuCrypto_checkRequirementMLCFile(subPath, additionalErrorInfo) == false)
{
cemuLog_log(LogType::Force, "Missing dumped file for online mode: {}", subPath);
return IOS_CRYPTO_ONLINE_REQ_MISSING_FILE;
}
if (*c.key)
{
std::string subPath = fmt::format("sys/title/0005001b/10054000/content/{}", boost::nowide::narrow(c.key));
if (iosuCrypto_checkRequirementMLCFile(subPath, additionalErrorInfo) == false)
{
cemuLog_log(LogType::Force, "Missing dumped file for online mode: {}", subPath);
return IOS_CRYPTO_ONLINE_REQ_MISSING_FILE;
}
}
}
return IOS_CRYPTO_ONLINE_REQ_OK;
}
std::vector<const wchar_t*> iosuCrypt_getCertificateKeys()
{
std::vector<const wchar_t*> result;
result.reserve(std::size(g_certificates));
for (const auto& c : g_certificates)
{
if (c.key[0] == '\0')
continue;
result.emplace_back(c.key);
}
return result;
}
std::vector<const wchar_t*> iosuCrypt_getCertificateNames()
{
std::vector<const wchar_t*> result;
result.reserve(std::size(g_certificates));
for (const auto& c : g_certificates)
{
result.emplace_back(c.name);
}
return result;
}
| 21,498
|
C++
|
.cpp
| 598
| 33.550167
| 145
| 0.722446
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,178
|
iosu_fpd.cpp
|
cemu-project_Cemu/src/Cafe/IOSU/legacy/iosu_fpd.cpp
|
#include "iosu_act.h"
#include "iosu_fpd.h"
#include "Cemu/nex/nex.h"
#include "Cemu/nex/nexFriends.h"
#include "util/helpers/helpers.h"
#include "config/CemuConfig.h"
#include "Cafe/CafeSystem.h"
#include "config/ActiveSettings.h"
#include "Cemu/napi/napi.h"
#include "util/helpers/StringHelpers.h"
#include "Cafe/IOSU/iosu_types_common.h"
#include "Cafe/IOSU/nn/iosu_nn_service.h"
#include "Common/CafeString.h"
std::mutex g_friend_notification_mutex;
std::vector< std::pair<std::string, int> > g_friend_notifications;
namespace iosu
{
namespace fpd
{
using NotificationRunningId = uint64;
struct NotificationEntry
{
NotificationEntry(uint64 index, NexFriends::NOTIFICATION_TYPE type, uint32 pid) : timestamp(std::chrono::steady_clock::now()), runningId(index), type(type), pid(pid) {}
std::chrono::steady_clock::time_point timestamp;
NotificationRunningId runningId;
NexFriends::NOTIFICATION_TYPE type;
uint32 pid;
};
class
{
public:
void TrackNotification(NexFriends::NOTIFICATION_TYPE type, uint32 pid)
{
std::unique_lock _l(m_mtxNotificationQueue);
m_notificationQueue.emplace_back(m_notificationQueueIndex++, type, pid);
}
void RemoveExpired()
{
// remove entries older than 10 seconds
std::chrono::steady_clock::time_point expireTime = std::chrono::steady_clock::now() - std::chrono::seconds(10);
std::erase_if(m_notificationQueue, [expireTime](const auto& notification) {
return notification.timestamp < expireTime;
});
}
std::optional<NotificationEntry> GetNextNotification(NotificationRunningId& previousRunningId)
{
std::unique_lock _l(m_mtxNotificationQueue);
auto it = std::lower_bound(m_notificationQueue.begin(), m_notificationQueue.end(), previousRunningId, [](const auto& notification, const auto& runningId) {
return notification.runningId <= runningId;
});
size_t itIndex = it - m_notificationQueue.begin();
if(it == m_notificationQueue.end())
return std::nullopt;
previousRunningId = it->runningId;
return *it;
}
private:
std::vector<NotificationEntry> m_notificationQueue;
std::mutex m_mtxNotificationQueue;
std::atomic_uint64_t m_notificationQueueIndex{1};
}g_NotificationQueue;
struct
{
bool isThreadStarted;
bool isInitialized2;
NexFriends* nexFriendSession;
std::mutex mtxFriendSession;
// session state
std::atomic_bool sessionStarted{false};
// current state
nexPresenceV2 myPresence;
}g_fpd = {};
void OverlayNotificationHandler(NexFriends::NOTIFICATION_TYPE type, uint32 pid)
{
cemuLog_logDebug(LogType::Force, "Friends::Notification {:02x} pid {:08x}", type, pid);
if(!GetConfig().notification.friends)
return;
std::unique_lock lock(g_friend_notification_mutex);
std::string message;
if(type == NexFriends::NOTIFICATION_TYPE::NOTIFICATION_TYPE_ONLINE)
{
g_friend_notifications.emplace_back("Connected to friend service", 5000);
if(g_fpd.nexFriendSession && g_fpd.nexFriendSession->getPendingFriendRequestCount() > 0)
g_friend_notifications.emplace_back(fmt::format("You have {} pending friend request(s)", g_fpd.nexFriendSession->getPendingFriendRequestCount()), 5000);
}
else
{
std::string msg_format;
switch(type)
{
case NexFriends::NOTIFICATION_TYPE_ONLINE: break;
case NexFriends::NOTIFICATION_TYPE_FRIEND_LOGIN: msg_format = "{} is now online"; break;
case NexFriends::NOTIFICATION_TYPE_FRIEND_LOGOFF: msg_format = "{} is now offline"; break;
case NexFriends::NOTIFICATION_TYPE_FRIEND_PRESENCE_CHANGE: break;
case NexFriends::NOTIFICATION_TYPE_ADDED_FRIEND: msg_format = "{} has been added to your friend list"; break;
case NexFriends::NOTIFICATION_TYPE_REMOVED_FRIEND: msg_format = "{} has been removed from your friend list"; break;
case NexFriends::NOTIFICATION_TYPE_ADDED_OUTGOING_REQUEST: break;
case NexFriends::NOTIFICATION_TYPE_REMOVED_OUTGOING_REQUEST: break;
case NexFriends::NOTIFICATION_TYPE_ADDED_INCOMING_REQUEST: msg_format = "{} wants to add you to his friend list"; break;
case NexFriends::NOTIFICATION_TYPE_REMOVED_INCOMING_REQUEST: break;
default: ;
}
if (!msg_format.empty())
{
std::string name = fmt::format("{:#x}", pid);
if (g_fpd.nexFriendSession)
{
const std::string tmp = g_fpd.nexFriendSession->getAccountNameByPid(pid);
if (!tmp.empty())
name = tmp;
}
g_friend_notifications.emplace_back(fmt::format(fmt::runtime(msg_format), name), 5000);
}
}
}
void NotificationHandler(NexFriends::NOTIFICATION_TYPE type, uint32 pid)
{
OverlayNotificationHandler(type, pid);
g_NotificationQueue.TrackNotification(type, pid);
}
void convertMultiByteStringToBigEndianWidechar(const char* input, uint16be* output, sint32 maxOutputLength)
{
std::basic_string<uint16be> beStr = StringHelpers::FromUtf8(input);
if (beStr.size() >= maxOutputLength - 1)
beStr.resize(maxOutputLength-1);
for (size_t i = 0; i < beStr.size(); i++)
output[i] = beStr[i];
output[beStr.size()] = '\0';
}
void convertFPDTimestampToDate(uint64 timestamp, FPDDate* fpdDate)
{
// if the timestamp is zero then still return a valid date
if (timestamp == 0)
{
fpdDate->second = 0;
fpdDate->minute = 0;
fpdDate->hour = 0;
fpdDate->day = 1;
fpdDate->month = 1;
fpdDate->year = 1970;
return;
}
fpdDate->second = (uint8)((timestamp) & 0x3F);
fpdDate->minute = (uint8)((timestamp >> 6) & 0x3F);
fpdDate->hour = (uint8)((timestamp >> 12) & 0x1F);
fpdDate->day = (uint8)((timestamp >> 17) & 0x1F);
fpdDate->month = (uint8)((timestamp >> 22) & 0xF);
fpdDate->year = (uint16)((timestamp >> 26));
}
uint64 convertDateToFPDTimestamp(FPDDate* fpdDate)
{
uint64 t = 0;
t |= (uint64)fpdDate->second;
t |= ((uint64)fpdDate->minute<<6);
t |= ((uint64)fpdDate->hour<<12);
t |= ((uint64)fpdDate->day<<17);
t |= ((uint64)fpdDate->month<<22);
t |= ((uint64)(uint16)fpdDate->year<<26);
return t;
}
void NexPresenceToGameMode(const nexPresenceV2* presence, GameMode* gameMode)
{
memset(gameMode, 0, sizeof(GameMode));
gameMode->joinFlagMask = presence->joinFlagMask;
gameMode->matchmakeType = presence->joinAvailability;
gameMode->joinGameId = presence->gameId;
gameMode->joinGameMode = presence->gameMode;
gameMode->hostPid = presence->hostPid;
gameMode->groupId = presence->groupId;
memcpy(gameMode->appSpecificData, presence->appSpecificData, 0x14);
}
void GameModeToNexPresence(const GameMode* gameMode, nexPresenceV2* presence)
{
*presence = {};
presence->joinFlagMask = gameMode->joinFlagMask;
presence->joinAvailability = (uint8)(uint32)gameMode->matchmakeType;
presence->gameId = gameMode->joinGameId;
presence->gameMode = gameMode->joinGameMode;
presence->hostPid = gameMode->hostPid;
presence->groupId = gameMode->groupId;
memcpy(presence->appSpecificData, gameMode->appSpecificData, 0x14);
}
void NexFriendToFPDFriendData(const nexFriend* frd, FriendData* friendData)
{
memset(friendData, 0, sizeof(FriendData));
// setup friend data
friendData->type = 1; // friend
friendData->pid = frd->nnaInfo.principalInfo.principalId;
memcpy(friendData->mii, frd->nnaInfo.principalInfo.mii.miiData, FFL_SIZE);
strcpy((char*)friendData->nnid, frd->nnaInfo.principalInfo.nnid);
// screenname
convertMultiByteStringToBigEndianWidechar(frd->nnaInfo.principalInfo.mii.miiNickname, friendData->screenname, sizeof(friendData->screenname) / sizeof(uint16be));
friendData->friendExtraData.isOnline = frd->presence.isOnline != 0 ? 1 : 0;
friendData->friendExtraData.gameKey.titleId = frd->presence.gameKey.titleId;
friendData->friendExtraData.gameKey.ukn08 = frd->presence.gameKey.ukn;
NexPresenceToGameMode(&frd->presence, &friendData->friendExtraData.gameMode);
auto fixed_presence_msg = '\0' + frd->presence.msg; // avoid first character of comment from being cut off
friendData->friendExtraData.gameModeDescription.assignFromUTF8(fixed_presence_msg);
auto fixed_comment = '\0' + frd->comment.commentString; // avoid first character of comment from being cut off
friendData->friendExtraData.comment.assignFromUTF8(fixed_comment);
// set valid dates
friendData->uknDate.year = 2018;
friendData->uknDate.day = 1;
friendData->uknDate.month = 1;
friendData->uknDate.hour = 1;
friendData->uknDate.minute = 1;
friendData->uknDate.second = 1;
friendData->friendExtraData.approvalTime.year = 2018;
friendData->friendExtraData.approvalTime.day = 1;
friendData->friendExtraData.approvalTime.month = 1;
friendData->friendExtraData.approvalTime.hour = 1;
friendData->friendExtraData.approvalTime.minute = 1;
friendData->friendExtraData.approvalTime.second = 1;
convertFPDTimestampToDate(frd->lastOnlineTimestamp, &friendData->friendExtraData.lastOnline);
}
void NexFriendRequestToFPDFriendData(const nexFriendRequest* frdReq, bool isIncoming, FriendData* friendData)
{
memset(friendData, 0, sizeof(FriendData));
// setup friend data
friendData->type = 0; // friend request
friendData->pid = frdReq->principalInfo.principalId;
memcpy(friendData->mii, frdReq->principalInfo.mii.miiData, FFL_SIZE);
strcpy((char*)friendData->nnid, frdReq->principalInfo.nnid);
// screenname
convertMultiByteStringToBigEndianWidechar(frdReq->principalInfo.mii.miiNickname, friendData->screenname, sizeof(friendData->screenname) / sizeof(uint16be));
convertMultiByteStringToBigEndianWidechar(frdReq->message.commentStr.c_str(), friendData->requestExtraData.comment, sizeof(friendData->requestExtraData.comment) / sizeof(uint16be));
FPDDate expireDate;
convertFPDTimestampToDate(frdReq->message.expireTimestamp, &expireDate);
bool isProvisional = frdReq->message.expireTimestamp == 0;
//friendData->requestExtraData.ukn0A8 = 0; // no change?
//friendData->requestExtraData.ukn0A0 = 0; // if not set -> provisional friend request
//friendData->requestExtraData.ukn0A4 = isProvisional ? 0 : 123; // no change?
friendData->requestExtraData.messageId = frdReq->message.messageId;
///* +0x0A8 */ uint8 ukn0A8;
///* +0x0A9 */ uint8 ukn0A9; // comment language? (guessed)
///* +0x0AA */ uint16be comment[0x40];
///* +0x12A */ uint8 ukn12A; // ingame name language? (guessed)
///* +0x12B */ uint8 _padding12B;
// set valid dates
friendData->uknDate.year = 2018;
friendData->uknDate.day = 20;
friendData->uknDate.month = 4;
friendData->uknDate.hour = 12;
friendData->uknDate.minute = 1;
friendData->uknDate.second = 1;
friendData->requestExtraData.uknData0.year = 2018;
friendData->requestExtraData.uknData0.day = 24;
friendData->requestExtraData.uknData0.month = 4;
friendData->requestExtraData.uknData0.hour = 1;
friendData->requestExtraData.uknData0.minute = 1;
friendData->requestExtraData.uknData0.second = 1;
// this is the date used for 'Expires in'
convertFPDTimestampToDate(frdReq->message.expireTimestamp, &friendData->requestExtraData.uknData1);
}
void NexFriendRequestToFPDFriendRequest(const nexFriendRequest* frdReq, bool isIncoming, FriendRequest* friendRequest)
{
memset(friendRequest, 0, sizeof(FriendRequest));
friendRequest->pid = frdReq->principalInfo.principalId;
strncpy((char*)friendRequest->nnid, frdReq->principalInfo.nnid, sizeof(friendRequest->nnid));
friendRequest->nnid[sizeof(friendRequest->nnid) - 1] = '\0';
memcpy(friendRequest->miiData, frdReq->principalInfo.mii.miiData, sizeof(friendRequest->miiData));
convertMultiByteStringToBigEndianWidechar(frdReq->message.commentStr.c_str(), friendRequest->message, sizeof(friendRequest->message) / sizeof(friendRequest->message[0]));
convertMultiByteStringToBigEndianWidechar(frdReq->principalInfo.mii.miiNickname, friendRequest->screenname, sizeof(friendRequest->screenname) / sizeof(friendRequest->screenname[0]));
friendRequest->isMarkedAsReceived = 1;
friendRequest->ukn98 = _swapEndianU64(frdReq->message.messageId);
convertFPDTimestampToDate(0, &friendRequest->uknDate);
convertFPDTimestampToDate(0, &friendRequest->uknDate2);
convertFPDTimestampToDate(frdReq->message.expireTimestamp, &friendRequest->expireDate);
}
struct FPProfile
{
uint8be country;
uint8be area;
uint16be unused;
};
static_assert(sizeof(FPProfile) == 4);
struct SelfPresence
{
uint8be ukn[0x130]; // todo
};
static_assert(sizeof(SelfPresence) == 0x130);
struct SelfPlayingGame
{
uint8be ukn0[0x10];
};
static_assert(sizeof(SelfPlayingGame) == 0x10);
static const auto FPResult_Ok = 0;
static const auto FPResult_InvalidIPCParam = BUILD_NN_RESULT(NN_RESULT_LEVEL_LVL6, NN_RESULT_MODULE_NN_FP, 0x680);
static const auto FPResult_RequestFailed = BUILD_NN_RESULT(NN_RESULT_LEVEL_FATAL, NN_RESULT_MODULE_NN_FP, 0); // figure out proper error code
static const auto FPResult_Aborted = BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_FP, 0x3480);
class FPDService : public iosu::nn::IPCSimpleService
{
struct NotificationAsyncRequest
{
NotificationAsyncRequest(IPCCommandBody* cmd, uint32 maxNumEntries, FPDNotification* notificationsOut, uint32be* countOut)
: cmd(cmd), maxNumEntries(maxNumEntries), notificationsOut(notificationsOut), countOut(countOut)
{
}
IPCCommandBody* cmd;
uint32 maxNumEntries;
FPDNotification* notificationsOut;
uint32be* countOut;
};
struct FPDClient
{
bool hasLoggedIn{false};
uint32 notificationMask{0};
NotificationRunningId prevRunningId{0};
std::vector<NotificationAsyncRequest> notificationRequests;
};
// storage for async IPC requests
std::vector<IPCCommandBody*> m_asyncLoginRequests;
std::vector<FPDClient*> m_clients;
public:
FPDService() : iosu::nn::IPCSimpleService("/dev/fpd") {}
std::string GetThreadName() override
{
return "IOSUModule::FPD";
}
void StartService() override
{
cemu_assert_debug(m_asyncLoginRequests.empty());
}
void StopService() override
{
m_asyncLoginRequests.clear();
for(auto& it : m_clients)
delete it;
m_clients.clear();
}
void* CreateClientObject() override
{
FPDClient* client = new FPDClient();
m_clients.push_back(client);
return client;
}
void DestroyClientObject(void* clientObject) override
{
FPDClient* client = (FPDClient*)clientObject;
std::erase(m_clients, client);
delete client;
}
void SendQueuedNotifications(FPDClient* client)
{
if (client->notificationRequests.empty())
return;
if (client->notificationRequests.size() > 1)
cemuLog_log(LogType::Force, "FPD: More than one simultanous notification query not supported");
NotificationAsyncRequest& request = client->notificationRequests[0];
uint32 numNotifications = 0;
while(numNotifications < request.maxNumEntries)
{
auto notification = g_NotificationQueue.GetNextNotification(client->prevRunningId);
if (!notification)
break;
uint32 flag = 1 << static_cast<uint32>(notification->type);
if((client->notificationMask & flag) == 0)
continue;
request.notificationsOut[numNotifications].type = static_cast<uint32>(notification->type);
request.notificationsOut[numNotifications].pid = notification->pid;
numNotifications++;
}
if (numNotifications == 0)
return;
*request.countOut = numNotifications;
ServiceCallAsyncRespond(request.cmd, FPResult_Ok);
client->notificationRequests.erase(client->notificationRequests.begin());
}
void TimerUpdate() override
{
// called once a second while service is running
std::unique_lock _l(g_fpd.mtxFriendSession);
if (!g_fpd.nexFriendSession)
return;
g_fpd.nexFriendSession->update();
while(!m_asyncLoginRequests.empty())
{
if(g_fpd.nexFriendSession->isOnline())
{
ServiceCallAsyncRespond(m_asyncLoginRequests.front(), FPResult_Ok);
m_asyncLoginRequests.erase(m_asyncLoginRequests.begin());
}
else
break;
}
// handle notification responses
g_NotificationQueue.RemoveExpired();
for(auto& client : m_clients)
SendQueuedNotifications(client);
}
uint32 ServiceCall(void* clientObject, uint32 requestId, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut) override
{
// for /dev/fpd input and output vectors are swapped
std::swap(vecIn, vecOut);
std::swap(numVecIn, numVecOut);
FPDClient* fpdClient = (FPDClient*)clientObject;
switch(static_cast<FPD_REQUEST_ID>(requestId))
{
case FPD_REQUEST_ID::SetNotificationMask:
return CallHandler_SetNotificationMask(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetNotificationAsync:
return CallHandler_GetNotificationAsync(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::SetLedEventMask:
cemuLog_logDebug(LogType::Force, "[/dev/fpd] SetLedEventMask is todo");
return FPResult_Ok;
case FPD_REQUEST_ID::LoginAsync:
return CallHandler_LoginAsync(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::HasLoggedIn:
return CallHandler_HasLoggedIn(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::IsOnline:
return CallHandler_IsOnline(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetMyPrincipalId:
return CallHandler_GetMyPrincipalId(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetMyAccountId:
return CallHandler_GetMyAccountId(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetMyScreenName:
return CallHandler_GetMyScreenName(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetMyMii:
return CallHandler_GetMyMii(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetMyProfile:
return CallHandler_GetMyProfile(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetMyPresence:
return CallHandler_GetMyPresence(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetMyComment:
return CallHandler_GetMyComment(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetMyPreference:
return CallHandler_GetMyPreference(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetMyPlayingGame:
return CallHandler_GetMyPlayingGame(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetFriendAccountId:
return CallHandler_GetFriendAccountId(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetFriendScreenName:
return CallHandler_GetFriendScreenName(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetFriendMii:
return CallHandler_GetFriendMii(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetFriendPresence:
return CallHandler_GetFriendPresence(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetFriendRelationship:
return CallHandler_GetFriendRelationship(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetFriendList:
return CallHandler_GetFriendList_GetFriendListAll(fpdClient, vecIn, numVecIn, vecOut, numVecOut, false);
case FPD_REQUEST_ID::GetFriendListAll:
return CallHandler_GetFriendList_GetFriendListAll(fpdClient, vecIn, numVecIn, vecOut, numVecOut, true);
case FPD_REQUEST_ID::GetFriendRequestList:
return CallHandler_GetFriendRequestList(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetFriendRequestListEx:
return CallHandler_GetFriendRequestListEx(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetBlackList:
return CallHandler_GetBlackList(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetFriendListEx:
return CallHandler_GetFriendListEx(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::UpdateCommentAsync:
return CallHandler_UpdateCommentAsync(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::UpdatePreferenceAsync:
return CallHandler_UpdatePreferenceAsync(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::AddFriendRequestByPlayRecordAsync:
return CallHandler_AddFriendRequestAsync(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::AcceptFriendRequestAsync:
return CallHandler_AcceptFriendRequestAsync(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::DeleteFriendRequestAsync:
return CallHandler_DeleteFriendRequestAsync(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::CancelFriendRequestAsync:
return CallHandler_CancelFriendRequestAsync(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::MarkFriendRequestsAsReceivedAsync:
return CallHandler_MarkFriendRequestsAsReceivedAsync(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::RemoveFriendAsync:
return CallHandler_RemoveFriendAsync(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::DeleteFriendFlagsAsync:
return CallHandler_DeleteFriendFlagsAsync(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetBasicInfoAsync:
return CallHandler_GetBasicInfoAsync(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::CheckSettingStatusAsync:
return CallHandler_CheckSettingStatusAsync(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::IsPreferenceValid:
return CallHandler_IsPreferenceValid(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::GetRequestBlockSettingAsync:
return CallHandler_GetRequestBlockSettingAsync(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::AddFriendAsyncByPid:
return CallHandler_AddFriendAsyncByPid(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
case FPD_REQUEST_ID::UpdateGameModeVariation1:
case FPD_REQUEST_ID::UpdateGameModeVariation2:
return CallHandler_UpdateGameMode(fpdClient, vecIn, numVecIn, vecOut, numVecOut);
default:
cemuLog_log(LogType::Force, "Unsupported service call {} to /dev/fpd", requestId);
return BUILD_NN_RESULT(NN_RESULT_LEVEL_FATAL, NN_RESULT_MODULE_NN_FP, 0);
}
}
#define DeclareInputPtr(__Name, __T, __count, __vecIndex) if(sizeof(__T)*(__count) != vecIn[__vecIndex].size) { cemuLog_log(LogType::Force, "FPD: IPC buffer has incorrect size"); return FPResult_InvalidIPCParam;}; __T* __Name = ((__T*)vecIn[__vecIndex].basePhys.GetPtr())
#define DeclareInput(__Name, __T, __vecIndex) if(sizeof(__T) != vecIn[__vecIndex].size) { cemuLog_log(LogType::Force, "FPD: IPC buffer has incorrect size"); return FPResult_InvalidIPCParam;}; __T __Name = *((__T*)vecIn[__vecIndex].basePhys.GetPtr())
#define DeclareOutputPtr(__Name, __T, __count, __vecIndex) if(sizeof(__T)*(__count) != vecOut[__vecIndex].size) { cemuLog_log(LogType::Force, "FPD: IPC buffer has incorrect size"); return FPResult_InvalidIPCParam;}; __T* __Name = ((__T*)vecOut[__vecIndex].basePhys.GetPtr())
template<typename T>
static nnResult WriteValueOutput(IPCIoctlVector* vec, const T& value)
{
if(vec->size != sizeof(T))
return FPResult_InvalidIPCParam;
*(T*)vec->basePhys.GetPtr() = value;
return FPResult_Ok;
}
nnResult CallHandler_SetNotificationMask(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 1 || numVecOut != 0)
return FPResult_InvalidIPCParam;
DeclareInput(notificationMask, uint32be, 0);
fpdClient->notificationMask = notificationMask;
return FPResult_Ok;
}
nnResult CallHandler_GetNotificationAsync(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 0 || numVecOut != 2)
return FPResult_InvalidIPCParam;
if((vecOut[0].size % sizeof(FPDNotification)) != 0 || vecOut[0].size < sizeof(FPDNotification))
{
cemuLog_log(LogType::Force, "FPD GetNotificationAsync: Unexpected output size");
return FPResult_InvalidIPCParam;
}
IPCCommandBody* cmd = ServiceCallDelayCurrentResponse();
DeclareOutputPtr(countOut, uint32be, 1, 1);
uint32 maxCount = vecOut[0].size / sizeof(FPDNotification);
DeclareOutputPtr(notificationList, FPDNotification, maxCount, 0);
fpdClient->notificationRequests.emplace_back(cmd, maxCount, notificationList, countOut);
SendQueuedNotifications(fpdClient); // if any notifications are queued, send them immediately
return FPResult_Ok;
}
nnResult CallHandler_LoginAsync(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 0 || numVecOut != 0)
return FPResult_InvalidIPCParam;
if (!ActiveSettings::IsOnlineEnabled())
{
// not online, fail immediately
return FPResult_Ok; // Splatoon expects this to always return success otherwise it will softlock. This should be FPResult_Aborted?
}
StartFriendSession();
fpdClient->hasLoggedIn = true;
IPCCommandBody* cmd = ServiceCallDelayCurrentResponse();
m_asyncLoginRequests.emplace_back(cmd);
return FPResult_Ok;
}
nnResult CallHandler_HasLoggedIn(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 0 || numVecOut != 1)
return FPResult_InvalidIPCParam;
return WriteValueOutput<uint32be>(vecOut, fpdClient->hasLoggedIn ? 1 : 0);
}
nnResult CallHandler_IsOnline(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 0 || numVecOut != 1)
return FPResult_InvalidIPCParam;
bool isOnline = g_fpd.nexFriendSession ? g_fpd.nexFriendSession->isOnline() : false;
return WriteValueOutput<uint32be>(vecOut, isOnline?1:0);
}
nnResult CallHandler_GetMyPrincipalId(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 0 || numVecOut != 1)
return FPResult_InvalidIPCParam;
uint8 slot = iosu::act::getCurrentAccountSlot();
uint32 pid = 0;
iosu::act::getPrincipalId(slot, &pid);
return WriteValueOutput<uint32be>(vecOut, pid);
}
nnResult CallHandler_GetMyAccountId(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 0 || numVecOut != 1)
return FPResult_InvalidIPCParam;
uint8 slot = iosu::act::getCurrentAccountSlot();
std::string accountId = iosu::act::getAccountId2(slot);
if(vecOut->size != ACT_ACCOUNTID_LENGTH)
{
cemuLog_log(LogType::Force, "GetMyAccountId: Unexpected output size");
return FPResult_InvalidIPCParam;
}
if(accountId.length() > ACT_ACCOUNTID_LENGTH-1)
{
cemuLog_log(LogType::Force, "GetMyAccountId: AccountID is too long");
return FPResult_InvalidIPCParam;
}
if(accountId.empty())
{
cemuLog_log(LogType::Force, "GetMyAccountId: AccountID is empty");
return FPResult_InvalidIPCParam; // should return 0xC0C00800 ?
}
char* outputStr = (char*)vecOut->basePhys.GetPtr();
memset(outputStr, 0, ACT_ACCOUNTID_LENGTH);
memcpy(outputStr, accountId.data(), accountId.length());
return FPResult_Ok;
}
nnResult CallHandler_GetMyScreenName(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 0 || numVecOut != 1)
return FPResult_InvalidIPCParam;
uint8 slot = iosu::act::getCurrentAccountSlot();
if(vecOut->size != ACT_NICKNAME_SIZE*sizeof(uint16be))
{
cemuLog_log(LogType::Force, "GetMyScreenName: Unexpected output size");
return FPResult_InvalidIPCParam;
}
uint16 screenname[ACT_NICKNAME_SIZE]{0};
bool r = iosu::act::getScreenname(slot, screenname);
if (!r)
{
cemuLog_log(LogType::Force, "GetMyScreenName: Screenname is empty");
return FPResult_InvalidIPCParam; // should return 0xC0C00800 ?
}
uint16be* outputStr = (uint16be*)vecOut->basePhys.GetPtr();
for(sint32 i = 0; i < ACT_NICKNAME_SIZE; i++)
outputStr[i] = screenname[i];
return FPResult_Ok;
}
nnResult CallHandler_GetMyMii(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 0 || numVecOut != 1)
return FPResult_InvalidIPCParam;
uint8 slot = iosu::act::getCurrentAccountSlot();
if(vecOut->size != FFL_SIZE)
{
cemuLog_log(LogType::Force, "GetMyMii: Unexpected output size");
return FPResult_InvalidIPCParam;
}
bool r = iosu::act::getMii(slot, (FFLData_t*)vecOut->basePhys.GetPtr());
if (!r)
{
cemuLog_log(LogType::Force, "GetMyMii: Mii is empty");
return FPResult_InvalidIPCParam; // should return 0xC0C00800 ?
}
return FPResult_Ok;
}
nnResult CallHandler_GetMyProfile(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 0 || numVecOut != 1)
return FPResult_InvalidIPCParam;
uint8 slot = iosu::act::getCurrentAccountSlot();
FPProfile profile{0};
// todo
cemuLog_log(LogType::Force, "GetMyProfile is todo");
return WriteValueOutput<FPProfile>(vecOut, profile);
}
nnResult CallHandler_GetMyPresence(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 0 || numVecOut != 1)
return FPResult_InvalidIPCParam;
uint8 slot = iosu::act::getCurrentAccountSlot();
SelfPresence selfPresence{0};
cemuLog_log(LogType::Force, "GetMyPresence is todo");
return WriteValueOutput<SelfPresence>(vecOut, selfPresence);
}
nnResult CallHandler_GetMyComment(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 0 || numVecOut != 1)
return FPResult_InvalidIPCParam;
std::basic_string<uint16be> myComment;
if(g_fpd.nexFriendSession)
{
if(vecOut->size != MY_COMMENT_LENGTH * sizeof(uint16be))
{
cemuLog_log(LogType::Force, "GetMyComment: Unexpected output size");
return FPResult_InvalidIPCParam;
}
nexComment myNexComment;
g_fpd.nexFriendSession->getMyComment(myNexComment);
myComment = StringHelpers::FromUtf8(myNexComment.commentString);
}
myComment.insert(0, 1, '\0');
memcpy(vecOut->basePhys.GetPtr(), myComment.c_str(), MY_COMMENT_LENGTH * sizeof(uint16be));
return FPResult_Ok;
}
nnResult CallHandler_GetMyPreference(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 0 || numVecOut != 1)
return FPResult_InvalidIPCParam;
FPDPreference selfPreference{0};
if(g_fpd.nexFriendSession)
{
nexPrincipalPreference nexPreference;
g_fpd.nexFriendSession->getMyPreference(nexPreference);
selfPreference.showOnline = nexPreference.showOnline;
selfPreference.showGame = nexPreference.showGame;
selfPreference.blockFriendRequests = nexPreference.blockFriendRequests;
selfPreference.ukn = 0;
}
else
memset(&selfPreference, 0, sizeof(FPDPreference));
return WriteValueOutput<FPDPreference>(vecOut, selfPreference);
}
nnResult CallHandler_GetMyPlayingGame(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 0 || numVecOut != 1)
return FPResult_InvalidIPCParam;
GameKey selfPlayingGame
{
CafeSystem::GetForegroundTitleId(),
CafeSystem::GetForegroundTitleVersion(),
{0,0,0,0,0,0}
};
if (GetTitleIdHigh(CafeSystem::GetForegroundTitleId()) != 0x00050000)
{
selfPlayingGame.titleId = 0;
selfPlayingGame.ukn08 = 0;
}
return WriteValueOutput<GameKey>(vecOut, selfPlayingGame);
}
nnResult CallHandler_GetFriendAccountId(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 2 || numVecOut != 1)
return FPResult_InvalidIPCParam;
// todo - online check
DeclareInput(count, uint32be, 1);
DeclareInputPtr(pidList, uint32be, count, 0);
DeclareOutputPtr(accountId, CafeString<ACT_ACCOUNTID_LENGTH>, count, 0);
memset(accountId, 0, ACT_ACCOUNTID_LENGTH * count);
if (g_fpd.nexFriendSession)
{
for (uint32 i = 0; i < count; i++)
{
const uint32 pid = pidList[i];
auto& nnidOutput = accountId[i];
nexFriend frd;
nexFriendRequest frdReq;
if (g_fpd.nexFriendSession->getFriendByPID(frd, pid))
{
nnidOutput.assign(frd.nnaInfo.principalInfo.nnid);
continue;
}
bool incoming = false;
if (g_fpd.nexFriendSession->getFriendRequestByPID(frdReq, &incoming, pid))
{
nnidOutput.assign(frdReq.principalInfo.nnid);
continue;
}
cemuLog_log(LogType::Force, "GetFriendAccountId: PID {} not found", pid);
}
}
return FPResult_Ok;
}
nnResult CallHandler_GetFriendScreenName(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
static_assert(sizeof(CafeWideString<ACT_NICKNAME_SIZE>) == 11*2);
if(numVecIn != 3 || numVecOut != 2)
return FPResult_InvalidIPCParam;
DeclareInput(count, uint32be, 1);
DeclareInputPtr(pidList, uint32be, count, 0);
DeclareInput(replaceNonAscii, uint8be, 2);
DeclareOutputPtr(nameList, CafeWideString<ACT_NICKNAME_SIZE>, count, 0);
uint8be* languageList = nullptr;
if(vecOut[1].size > 0) // languageList is optional
{
DeclareOutputPtr(_languageList, uint8be, count, 1);
languageList = _languageList;
}
memset(nameList, 0, ACT_NICKNAME_SIZE * sizeof(CafeWideString<ACT_NICKNAME_SIZE>));
if (g_fpd.nexFriendSession)
{
for (uint32 i = 0; i < count; i++)
{
const uint32 pid = pidList[i];
CafeWideString<ACT_NICKNAME_SIZE>& screennameOutput = nameList[i];
if (languageList)
languageList[i] = 0; // unknown
nexFriend frd;
nexFriendRequest frdReq;
if (g_fpd.nexFriendSession->getFriendByPID(frd, pid))
{
screennameOutput.assignFromUTF8(frd.nnaInfo.principalInfo.mii.miiNickname);
if (languageList)
languageList[i] = frd.nnaInfo.principalInfo.regionGuessed;
continue;
}
bool incoming = false;
if (g_fpd.nexFriendSession->getFriendRequestByPID(frdReq, &incoming, pid))
{
screennameOutput.assignFromUTF8(frdReq.principalInfo.mii.miiNickname);
if (languageList)
languageList[i] = frdReq.principalInfo.regionGuessed;
continue;
}
cemuLog_log(LogType::Force, "GetFriendScreenName: PID {} not found", pid);
}
}
return FPResult_Ok;
}
nnResult CallHandler_GetFriendMii(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 2 || numVecOut != 1)
return FPResult_InvalidIPCParam;
DeclareInput(count, uint32be, 1);
DeclareInputPtr(pidList, uint32be, count, 0);
DeclareOutputPtr(miiList, FFLData_t, count, 0);
memset(miiList, 0, sizeof(FFLData_t) * count);
if (g_fpd.nexFriendSession)
{
for (uint32 i = 0; i < count; i++)
{
const uint32 pid = pidList[i];
FFLData_t& miiOutput = miiList[i];
nexFriend frd;
nexFriendRequest frdReq;
if (g_fpd.nexFriendSession->getFriendByPID(frd, pid))
{
memcpy(&miiOutput, frd.nnaInfo.principalInfo.mii.miiData, FFL_SIZE);
continue;
}
bool incoming = false;
if (g_fpd.nexFriendSession->getFriendRequestByPID(frdReq, &incoming, pid))
{
memcpy(&miiOutput, frdReq.principalInfo.mii.miiData, FFL_SIZE);
continue;
}
}
}
return FPResult_Ok;
}
nnResult CallHandler_GetFriendPresence(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 2 || numVecOut != 1)
return FPResult_InvalidIPCParam;
DeclareInput(count, uint32be, 1);
DeclareInputPtr(pidList, uint32be, count, 0);
DeclareOutputPtr(presenceList, FriendPresence, count, 0);
memset(presenceList, 0, sizeof(FriendPresence) * count);
if (g_fpd.nexFriendSession)
{
for (uint32 i = 0; i < count; i++)
{
FriendPresence& presenceOutput = presenceList[i];
const uint32 pid = pidList[i];
nexFriend frd;
if (g_fpd.nexFriendSession->getFriendByPID(frd, pid))
{
presenceOutput.isOnline = frd.presence.isOnline ? 1 : 0;
presenceOutput.isValid = 1;
// todo - region and subregion
presenceOutput.gameMode.joinFlagMask = frd.presence.joinFlagMask;
presenceOutput.gameMode.matchmakeType = frd.presence.joinAvailability;
presenceOutput.gameMode.joinGameId = frd.presence.gameId;
presenceOutput.gameMode.joinGameMode = frd.presence.gameMode;
presenceOutput.gameMode.hostPid = frd.presence.hostPid;
presenceOutput.gameMode.groupId = frd.presence.groupId;
memcpy(presenceOutput.gameMode.appSpecificData, frd.presence.appSpecificData, 0x14);
}
else
{
cemuLog_log(LogType::Force, "GetFriendPresence: PID {} not found", pid);
}
}
}
return FPResult_Ok;
}
nnResult CallHandler_GetFriendRelationship(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if(numVecIn != 2 || numVecOut != 1)
return FPResult_InvalidIPCParam;
// todo - check for valid session (same for all GetFriend* functions)
DeclareInput(count, uint32be, 1);
DeclareInputPtr(pidList, uint32be, count, 0);
DeclareOutputPtr(relationshipList, uint8be, count, 0); // correct?
for(uint32 i=0; i<count; i++)
relationshipList[i] = RELATIONSHIP_INVALID;
if (g_fpd.nexFriendSession)
{
for (uint32 i = 0; i < count; i++)
{
const uint32 pid = pidList[i];
uint8be& relationshipOutput = relationshipList[i];
nexFriend frd;
nexFriendRequest frdReq;
bool incoming;
if (g_fpd.nexFriendSession->getFriendByPID(frd, pid))
{
relationshipOutput = RELATIONSHIP_FRIEND;
continue;
}
else if (g_fpd.nexFriendSession->getFriendRequestByPID(frdReq, &incoming, pid))
{
if (incoming)
relationshipOutput = RELATIONSHIP_FRIENDREQUEST_IN;
else
relationshipOutput = RELATIONSHIP_FRIENDREQUEST_OUT;
}
}
}
return FPResult_Ok;
}
nnResult CallHandler_GetFriendList_GetFriendListAll(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut, bool isAll)
{
std::unique_lock _l(g_fpd.mtxFriendSession);
if(numVecIn != 2 || numVecOut != 2)
return FPResult_InvalidIPCParam;
DeclareInput(startIndex, uint32be, 0);
DeclareInput(maxCount, uint32be, 1);
if (maxCount * sizeof(FriendPID) != vecOut[0].size || vecOut[0].basePhys.IsNull())
{
cemuLog_log(LogType::Force, "GetFriendListAll: pid list buffer size is incorrect");
return FPResult_InvalidIPCParam;
}
if (!g_fpd.nexFriendSession)
return WriteValueOutput<uint32be>(vecOut+1, 0);
betype<FriendPID>* pidList = (betype<FriendPID>*)vecOut[0].basePhys.GetPtr();
std::vector<FriendPID> temporaryPidList;
temporaryPidList.resize(std::min<size_t>(maxCount, 500));
uint32 pidCount = 0;
g_fpd.nexFriendSession->getFriendPIDs(temporaryPidList.data(), &pidCount, startIndex, temporaryPidList.size(), isAll);
std::copy(temporaryPidList.begin(), temporaryPidList.begin() + pidCount, pidList);
return WriteValueOutput<uint32be>(vecOut+1, pidCount);
}
nnResult CallHandler_GetFriendRequestList(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
std::unique_lock _l(g_fpd.mtxFriendSession);
if(numVecIn != 2 || numVecOut != 2)
return FPResult_InvalidIPCParam;
DeclareInput(startIndex, uint32be, 0);
DeclareInput(maxCount, uint32be, 1);
if(maxCount * sizeof(FriendPID) != vecOut[0].size || vecOut[0].basePhys.IsNull())
{
cemuLog_log(LogType::Force, "GetFriendRequestList: pid list buffer size is incorrect");
return FPResult_InvalidIPCParam;
}
if (!g_fpd.nexFriendSession)
return WriteValueOutput<uint32be>(vecOut+1, 0);
betype<FriendPID>* pidList = (betype<FriendPID>*)vecOut[0].basePhys.GetPtr();
std::vector<FriendPID> temporaryPidList;
temporaryPidList.resize(std::min<size_t>(maxCount, 500));
uint32 pidCount = 0;
g_fpd.nexFriendSession->getFriendRequestPIDs(temporaryPidList.data(), &pidCount, startIndex, temporaryPidList.size(), true, false);
std::copy(temporaryPidList.begin(), temporaryPidList.begin() + pidCount, pidList);
return WriteValueOutput<uint32be>(vecOut+1, pidCount);
}
nnResult CallHandler_GetFriendRequestListEx(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
std::unique_lock _l(g_fpd.mtxFriendSession);
if(numVecIn != 2 || numVecOut != 1)
return FPResult_InvalidIPCParam;
DeclareInput(count, uint32be, 1);
DeclareInputPtr(pidList, uint32be, count, 0);
DeclareOutputPtr(friendRequests, FriendRequest, count, 0);
memset(friendRequests, 0, sizeof(FriendRequest) * count);
if (!g_fpd.nexFriendSession)
return FPResult_Ok;
for(uint32 i=0; i<count; i++)
{
nexFriendRequest frdReq;
bool incoming = false;
if (!g_fpd.nexFriendSession->getFriendRequestByPID(frdReq, &incoming, pidList[i]))
{
cemuLog_log(LogType::Force, "GetFriendRequestListEx: Failed to get friend request");
return FPResult_RequestFailed;
}
NexFriendRequestToFPDFriendRequest(&frdReq, incoming, friendRequests + i);
}
return FPResult_Ok;
}
nnResult CallHandler_GetBlackList(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
std::unique_lock _l(g_fpd.mtxFriendSession);
if(numVecIn != 2 || numVecOut != 2)
return FPResult_InvalidIPCParam;
DeclareInput(startIndex, uint32be, 0);
DeclareInput(maxCount, uint32be, 1);
if(maxCount * sizeof(FriendPID) != vecOut[0].size)
{
cemuLog_log(LogType::Force, "GetBlackList: pid list buffer size is incorrect");
return FPResult_InvalidIPCParam;
}
if (!g_fpd.nexFriendSession)
return WriteValueOutput<uint32be>(vecOut+1, 0);
betype<FriendPID>* pidList = (betype<FriendPID>*)vecOut[0].basePhys.GetPtr();
// todo!
cemuLog_logDebug(LogType::Force, "GetBlackList is todo");
uint32 countOut = 0;
return WriteValueOutput<uint32be>(vecOut+1, countOut);
}
nnResult CallHandler_GetFriendListEx(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
std::unique_lock _l(g_fpd.mtxFriendSession);
if(numVecIn != 2 || numVecOut != 1)
return FPResult_InvalidIPCParam;
DeclareInput(count, uint32be, 1);
DeclareInputPtr(pidList, betype<FriendPID>, count, 0);
if(count * sizeof(FriendPID) != vecIn[0].size)
{
cemuLog_log(LogType::Force, "GetFriendListEx: pid input list buffer size is incorrect");
return FPResult_InvalidIPCParam;
}
if(count * sizeof(FriendData) != vecOut[0].size)
{
cemuLog_log(LogType::Force, "GetFriendListEx: Friend output list buffer size is incorrect");
return FPResult_InvalidIPCParam;
}
FriendData* friendOutput = (FriendData*)vecOut[0].basePhys.GetPtr();
memset(friendOutput, 0, sizeof(FriendData) * count);
if (g_fpd.nexFriendSession)
{
for (uint32 i = 0; i < count; i++)
{
uint32 pid = pidList[i];
FriendData* friendData = friendOutput + i;
nexFriend frd;
nexFriendRequest frdReq;
if (g_fpd.nexFriendSession->getFriendByPID(frd, pid))
{
NexFriendToFPDFriendData(&frd, friendData);
continue;
}
bool incoming = false;
if (g_fpd.nexFriendSession->getFriendRequestByPID(frdReq, &incoming, pid))
{
NexFriendRequestToFPDFriendData(&frdReq, incoming, friendData);
continue;
}
cemuLog_logDebug(LogType::Force, "GetFriendListEx: Failed to find friend or request with pid {}", pid);
memset(friendData, 0, sizeof(FriendData));
}
}
return FPResult_Ok;
}
static void NexBasicInfoToBasicInfo(const nexPrincipalBasicInfo& nexBasicInfo, FriendBasicInfo& basicInfo)
{
memset(&basicInfo, 0, sizeof(FriendBasicInfo));
basicInfo.pid = nexBasicInfo.principalId;
strcpy(basicInfo.nnid, nexBasicInfo.nnid);
convertMultiByteStringToBigEndianWidechar(nexBasicInfo.mii.miiNickname, basicInfo.screenname, sizeof(basicInfo.screenname) / sizeof(uint16be));
memcpy(basicInfo.miiData, nexBasicInfo.mii.miiData, FFL_SIZE);
basicInfo.uknDate90.day = 1;
basicInfo.uknDate90.month = 1;
basicInfo.uknDate90.hour = 1;
basicInfo.uknDate90.minute = 1;
basicInfo.uknDate90.second = 1;
// unknown values not set:
// ukn15
// ukn2E
// ukn2F
}
nnResult CallHandler_GetBasicInfoAsync(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
std::unique_lock _l(g_fpd.mtxFriendSession);
if (numVecIn != 2 || numVecOut != 1)
return FPResult_InvalidIPCParam;
DeclareInput(count, uint32be, 1);
DeclareInputPtr(pidListBE, betype<FriendPID>, count, 0);
DeclareOutputPtr(basicInfoList, FriendBasicInfo, count, 0);
if (!g_fpd.nexFriendSession)
{
memset(basicInfoList, 0, sizeof(FriendBasicInfo) * sizeof(count));
return FPResult_Ok;
}
IPCCommandBody* cmd = ServiceCallDelayCurrentResponse();
std::vector<uint32> pidList;
std::copy(pidListBE, pidListBE + count, std::back_inserter(pidList));
g_fpd.nexFriendSession->requestPrincipleBaseInfoByPID(pidList.data(), count, [cmd, basicInfoList, count](NexFriends::RpcErrorCode result, std::span<nexPrincipalBasicInfo> basicInfo) -> void {
if (result != NexFriends::ERR_NONE)
return ServiceCallAsyncRespond(cmd, FPResult_RequestFailed);
cemu_assert_debug(basicInfo.size() == count);
for(uint32 i = 0; i < count; i++)
NexBasicInfoToBasicInfo(basicInfo[i], basicInfoList[i]);
ServiceCallAsyncRespond(cmd, FPResult_Ok);
});
return FPResult_Ok;
}
nnResult CallHandler_UpdateCommentAsync(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
std::unique_lock _l(g_fpd.mtxFriendSession);
if (numVecIn != 1 || numVecOut != 0)
return FPResult_InvalidIPCParam;
if (!g_fpd.nexFriendSession)
return FPResult_RequestFailed;
uint32 messageLength = vecIn[0].size / sizeof(uint16be);
DeclareInputPtr(newComment, uint16be, messageLength, 0);
if (messageLength == 0 || newComment[messageLength-1] != 0)
{
cemuLog_log(LogType::Force, "UpdateCommentAsync: Message must contain at least a null-termination character");
return FPResult_InvalidIPCParam;
}
IPCCommandBody* cmd = ServiceCallDelayCurrentResponse();
auto utf8_comment = StringHelpers::ToUtf8(newComment, messageLength);
nexComment temporaryComment;
temporaryComment.ukn0 = 0;
temporaryComment.commentString = utf8_comment;
temporaryComment.ukn1 = 0;
g_fpd.nexFriendSession->updateCommentAsync(temporaryComment, [cmd](NexFriends::RpcErrorCode result) {
if (result != NexFriends::ERR_NONE)
return ServiceCallAsyncRespond(cmd, FPResult_RequestFailed);
ServiceCallAsyncRespond(cmd, FPResult_Ok);
});
return FPResult_Ok;
}
nnResult CallHandler_UpdatePreferenceAsync(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
std::unique_lock _l(g_fpd.mtxFriendSession);
if (numVecIn != 1 || numVecOut != 0)
return FPResult_InvalidIPCParam;
if (!g_fpd.nexFriendSession)
return FPResult_RequestFailed;
DeclareInputPtr(newPreference, FPDPreference, 1, 0);
IPCCommandBody* cmd = ServiceCallDelayCurrentResponse();
g_fpd.nexFriendSession->updatePreferencesAsync(nexPrincipalPreference(newPreference->showOnline != 0 ? 1 : 0, newPreference->showGame != 0 ? 1 : 0, newPreference->blockFriendRequests != 0 ? 1 : 0), [cmd](NexFriends::RpcErrorCode result){
if (result != NexFriends::ERR_NONE)
return ServiceCallAsyncRespond(cmd, FPResult_RequestFailed);
ServiceCallAsyncRespond(cmd, FPResult_Ok);
});
return FPResult_Ok;
}
nnResult CallHandler_AddFriendRequestAsync(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
std::unique_lock _l(g_fpd.mtxFriendSession);
if (numVecIn != 2 || numVecOut != 0)
return FPResult_InvalidIPCParam;
if (!g_fpd.nexFriendSession)
return FPResult_RequestFailed;
DeclareInputPtr(playRecord, RecentPlayRecordEx, 1, 0);
uint32 msgLength = vecIn[1].size/sizeof(uint16be);
DeclareInputPtr(msgBE, uint16be, msgLength, 1);
if(msgLength == 0 || msgBE[msgLength-1] != 0)
{
cemuLog_log(LogType::Force, "AddFriendRequestAsync: Message must contain at least a null-termination character and end with one");
return FPResult_InvalidIPCParam;
}
std::string msg = StringHelpers::ToUtf8({ msgBE, msgLength-1 });
IPCCommandBody* cmd = ServiceCallDelayCurrentResponse();
g_fpd.nexFriendSession->addFriendRequest(playRecord->pid, msg.data(), [cmd](NexFriends::RpcErrorCode result){
if (result != NexFriends::ERR_NONE)
return ServiceCallAsyncRespond(cmd, FPResult_RequestFailed);
ServiceCallAsyncRespond(cmd, FPResult_Ok);
});
return FPResult_Ok;
}
nnResult CallHandler_AcceptFriendRequestAsync(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
std::unique_lock _l(g_fpd.mtxFriendSession);
if (numVecIn != 1 || numVecOut != 0)
return FPResult_InvalidIPCParam;
if (!g_fpd.nexFriendSession)
return FPResult_RequestFailed;
DeclareInput(requestId, uint64be, 0);
nexFriendRequest frq;
bool isIncoming;
if (!g_fpd.nexFriendSession->getFriendRequestByMessageId(frq, &isIncoming, requestId))
return FPResult_RequestFailed;
if(!isIncoming)
{
cemuLog_log(LogType::Force, "AcceptFriendRequestAsync: Trying to accept outgoing friend request");
return FPResult_RequestFailed;
}
IPCCommandBody* cmd = ServiceCallDelayCurrentResponse();
g_fpd.nexFriendSession->acceptFriendRequest(requestId, [cmd](NexFriends::RpcErrorCode result){
if (result != NexFriends::ERR_NONE)
return ServiceCallAsyncRespond(cmd, FPResult_RequestFailed);
return ServiceCallAsyncRespond(cmd, FPResult_Ok);
});
return FPResult_Ok;
}
nnResult CallHandler_DeleteFriendRequestAsync(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
// reject incoming friend request
std::unique_lock _l(g_fpd.mtxFriendSession);
if (numVecIn != 1 || numVecOut != 0)
return FPResult_InvalidIPCParam;
if (!g_fpd.nexFriendSession)
return FPResult_RequestFailed;
DeclareInput(requestId, uint64be, 0);
nexFriendRequest frq;
bool isIncoming;
if (!g_fpd.nexFriendSession->getFriendRequestByMessageId(frq, &isIncoming, requestId))
return FPResult_RequestFailed;
if(!isIncoming)
{
cemuLog_log(LogType::Force, "CancelFriendRequestAsync: Trying to block outgoing friend request");
return FPResult_RequestFailed;
}
IPCCommandBody* cmd = ServiceCallDelayCurrentResponse();
g_fpd.nexFriendSession->deleteFriendRequest(requestId, [cmd](NexFriends::RpcErrorCode result){
if (result != NexFriends::ERR_NONE)
return ServiceCallAsyncRespond(cmd, FPResult_RequestFailed);
return ServiceCallAsyncRespond(cmd, FPResult_Ok);
});
return FPResult_Ok;
}
nnResult CallHandler_CancelFriendRequestAsync(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
// retract outgoing friend request
std::unique_lock _l(g_fpd.mtxFriendSession);
if (numVecIn != 1 || numVecOut != 0)
return FPResult_InvalidIPCParam;
if (!g_fpd.nexFriendSession)
return FPResult_RequestFailed;
DeclareInput(requestId, uint64be, 0);
nexFriendRequest frq;
bool isIncoming;
if (!g_fpd.nexFriendSession->getFriendRequestByMessageId(frq, &isIncoming, requestId))
return FPResult_RequestFailed;
if(isIncoming)
{
cemuLog_log(LogType::Force, "CancelFriendRequestAsync: Trying to cancel incoming friend request");
return FPResult_RequestFailed;
}
IPCCommandBody* cmd = ServiceCallDelayCurrentResponse();
g_fpd.nexFriendSession->removeFriend(frq.principalInfo.principalId, [cmd](NexFriends::RpcErrorCode result){
if (result != NexFriends::ERR_NONE)
return ServiceCallAsyncRespond(cmd, FPResult_RequestFailed);
return ServiceCallAsyncRespond(cmd, FPResult_Ok);
});
return FPResult_Ok;
}
nnResult CallHandler_MarkFriendRequestsAsReceivedAsync(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
std::unique_lock _l(g_fpd.mtxFriendSession);
if (numVecIn != 2 || numVecOut != 0)
return FPResult_InvalidIPCParam;
if (!g_fpd.nexFriendSession)
return FPResult_RequestFailed;
DeclareInput(count, uint32be, 1);
DeclareInputPtr(requestIdsBE, uint64be, count, 0);
IPCCommandBody* cmd = ServiceCallDelayCurrentResponse();
// endian convert
std::vector<uint64> requestIds;
std::copy(requestIdsBE, requestIdsBE + count, std::back_inserter(requestIds));
g_fpd.nexFriendSession->markFriendRequestsAsReceived(requestIds.data(), requestIds.size(), [cmd](NexFriends::RpcErrorCode result){
if (result != NexFriends::ERR_NONE)
return ServiceCallAsyncRespond(cmd, FPResult_RequestFailed);
return ServiceCallAsyncRespond(cmd, FPResult_Ok);
});
return FPResult_Ok;
}
nnResult CallHandler_RemoveFriendAsync(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
std::unique_lock _l(g_fpd.mtxFriendSession);
if (numVecIn != 1 || numVecOut != 0)
return FPResult_InvalidIPCParam;
if (!g_fpd.nexFriendSession)
return FPResult_RequestFailed;
DeclareInput(pid, uint32be, 0);
IPCCommandBody* cmd = ServiceCallDelayCurrentResponse();
g_fpd.nexFriendSession->removeFriend(pid, [cmd](NexFriends::RpcErrorCode result){
if (result != NexFriends::ERR_NONE)
return ServiceCallAsyncRespond(cmd, FPResult_RequestFailed);
return ServiceCallAsyncRespond(cmd, FPResult_Ok);
});
return FPResult_Ok;
}
nnResult CallHandler_DeleteFriendFlagsAsync(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
std::unique_lock _l(g_fpd.mtxFriendSession);
if (numVecIn != 3 || numVecOut != 0)
return FPResult_InvalidIPCParam;
if (!g_fpd.nexFriendSession)
return FPResult_RequestFailed;
DeclareInput(pid, uint32be, 0);
cemuLog_logDebug(LogType::Force, "DeleteFriendFlagsAsync is todo");
return FPResult_Ok;
}
nnResult CallHandler_CheckSettingStatusAsync(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if (numVecIn != 0 || numVecOut != 1)
return FPResult_InvalidIPCParam;
if (vecOut[0].size != sizeof(uint8be))
return FPResult_InvalidIPCParam;
if (!g_fpd.nexFriendSession)
return FPResult_RequestFailed;
IPCCommandBody* cmd = ServiceCallDelayCurrentResponse();
// for now we respond immediately
uint8 settingsStatus = 1; // todo - figure out what this status means
auto r = WriteValueOutput<uint8be>(vecOut, settingsStatus);
ServiceCallAsyncRespond(cmd, r);
cemuLog_log(LogType::Force, "CheckSettingStatusAsync is todo");
return FPResult_Ok;
}
nnResult CallHandler_IsPreferenceValid(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if (numVecIn != 0 || numVecOut != 1)
return 0;
if (!g_fpd.nexFriendSession)
return 0;
// we currently automatically put the preferences into a valid state on session creation if they are not set yet
return WriteValueOutput<uint32be>(vecOut, 1); // if we return 0, the friend app will show the first time setup screen
}
nnResult CallHandler_GetRequestBlockSettingAsync(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut) // todo
{
if (numVecIn != 2 || numVecOut != 1)
return FPResult_InvalidIPCParam;
if (!g_fpd.nexFriendSession)
return FPResult_RequestFailed;
DeclareInput(count, uint32be, 1);
DeclareInputPtr(pidList, betype<FriendPID>, count, 0);
DeclareOutputPtr(settingList, uint8be, count, 0);
cemuLog_log(LogType::Force, "GetRequestBlockSettingAsync is todo");
for (uint32 i = 0; i < count; i++)
settingList[i] = 0;
// implementation is todo. Used by friend list app when adding a friend
// 0 means not blocked. Friend app will continue with GetBasicInformation()
// 1 means blocked. Friend app will continue with AddFriendAsync to add the user as a provisional friend
return FPResult_Ok;
}
nnResult CallHandler_AddFriendAsyncByPid(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if (numVecIn != 1 || numVecOut != 0)
return FPResult_InvalidIPCParam;
if (!g_fpd.nexFriendSession)
return FPResult_RequestFailed;
DeclareInput(pid, uint32be, 0);
cemuLog_log(LogType::Force, "AddFriendAsyncByPid is todo");
return FPResult_Ok;
}
nnResult CallHandler_UpdateGameMode(FPDClient* fpdClient, IPCIoctlVector* vecIn, uint32 numVecIn, IPCIoctlVector* vecOut, uint32 numVecOut)
{
if (numVecIn != 2 || numVecOut != 0)
return FPResult_InvalidIPCParam;
if (!g_fpd.nexFriendSession)
return FPResult_RequestFailed;
DeclareInputPtr(gameMode, iosu::fpd::GameMode, 1, 0);
uint32 messageLength = vecIn[1].size / sizeof(uint16be);
if(messageLength == 0 || (vecIn[1].size%sizeof(uint16be)) != 0)
{
cemuLog_log(LogType::Force, "UpdateGameMode: Message must contain at least a null-termination character");
return FPResult_InvalidIPCParam;
}
DeclareInputPtr(gameModeMessage, uint16be, messageLength, 1);
messageLength--;
GameModeToNexPresence(gameMode, &g_fpd.myPresence);
g_fpd.nexFriendSession->updateMyPresence(g_fpd.myPresence);
// todo - message
return FPResult_Ok;
}
void StartFriendSession()
{
bool expected = false;
if (!g_fpd.sessionStarted.compare_exchange_strong(expected, true))
return;
cemu_assert(!g_fpd.nexFriendSession);
NAPI::AuthInfo authInfo;
NAPI::NAPI_MakeAuthInfoFromCurrentAccount(authInfo);
NAPI::ACTGetNexTokenResult nexTokenResult = NAPI::ACT_GetNexToken_WithCache(authInfo, 0x0005001010001C00, 0x0000, 0x00003200);
if (!nexTokenResult.isValid())
{
cemuLog_logDebug(LogType::Force, "IOSU_FPD: Failed to acquire nex token for friend server");
g_fpd.myPresence.isOnline = 0;
return;
}
// get values needed for friend session
uint32 myPid;
uint8 currentSlot = iosu::act::getCurrentAccountSlot();
iosu::act::getPrincipalId(currentSlot, &myPid);
char accountId[256] = { 0 };
iosu::act::getAccountId(currentSlot, accountId);
FFLData_t miiData;
act::getMii(currentSlot, &miiData);
uint16 screenName[ACT_NICKNAME_LENGTH + 1] = { 0 };
act::getScreenname(currentSlot, screenName);
uint32 countryCode = 0;
act::getCountryIndex(currentSlot, &countryCode);
// init presence
g_fpd.myPresence.isOnline = 1;
if (GetTitleIdHigh(CafeSystem::GetForegroundTitleId()) == 0x00050000)
{
g_fpd.myPresence.gameKey.titleId = CafeSystem::GetForegroundTitleId();
g_fpd.myPresence.gameKey.ukn = CafeSystem::GetForegroundTitleVersion();
}
else
{
g_fpd.myPresence.gameKey.titleId = 0; // icon will not be ??? or invalid to others
g_fpd.myPresence.gameKey.ukn = 0;
}
// resolve potential domain to IP address
struct addrinfo hints = {0}, *addrs;
hints.ai_family = AF_INET;
const int status = getaddrinfo(nexTokenResult.nexToken.host, NULL, &hints, &addrs);
if (status != 0)
{
cemuLog_log(LogType::Force, "IOSU_FPD: Failed to resolve hostname {}", nexTokenResult.nexToken.host);
return;
}
char addrstr[NI_MAXHOST];
getnameinfo(addrs->ai_addr, addrs->ai_addrlen, addrstr, sizeof addrstr, NULL, 0, NI_NUMERICHOST);
cemuLog_log(LogType::Force, "IOSU_FPD: Resolved IP for hostname {}, {}", nexTokenResult.nexToken.host, addrstr);
// start session
const uint32_t hostIp = ((struct sockaddr_in*)addrs->ai_addr)->sin_addr.s_addr;
freeaddrinfo(addrs);
g_fpd.mtxFriendSession.lock();
g_fpd.nexFriendSession = new NexFriends(hostIp, nexTokenResult.nexToken.port, "ridfebb9", myPid, nexTokenResult.nexToken.nexPassword, nexTokenResult.nexToken.token, accountId, (uint8*)&miiData, (wchar_t*)screenName, (uint8)countryCode, g_fpd.myPresence);
g_fpd.nexFriendSession->setNotificationHandler(NotificationHandler);
g_fpd.mtxFriendSession.unlock();
cemuLog_log(LogType::Force, "IOSU_FPD: Created friend server session");
}
void StopFriendSession()
{
std::unique_lock _l(g_fpd.mtxFriendSession);
bool expected = true;
if (!g_fpd.sessionStarted.compare_exchange_strong(expected, false) )
return;
delete g_fpd.nexFriendSession;
g_fpd.nexFriendSession = nullptr;
}
private:
};
FPDService gFPDService;
class : public ::IOSUModule
{
void TitleStart() override
{
gFPDService.Start();
gFPDService.SetTimerUpdate(1000); // call TimerUpdate() once a second
}
void TitleStop() override
{
gFPDService.StopFriendSession();
gFPDService.Stop();
}
}sIOSUModuleNNFPD;
IOSUModule* GetModule()
{
return static_cast<IOSUModule*>(&sIOSUModuleNNFPD);
}
}
}
| 63,128
|
C++
|
.cpp
| 1,410
| 39.668794
| 277
| 0.730141
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,179
|
iosu_acp.cpp
|
cemu-project_Cemu/src/Cafe/IOSU/legacy/iosu_acp.cpp
|
#include "iosu_ioctl.h"
#include "iosu_acp.h"
#include "Cafe/OS/libs/nn_common.h"
#include "util/tinyxml2/tinyxml2.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "Cafe/OS/libs/nn_save/nn_save.h"
#include "util/helpers/helpers.h"
#include "Cafe/OS/libs/nn_acp/nn_acp.h"
#include "Cafe/OS/libs/coreinit/coreinit_FS.h"
#include "Cafe/Filesystem/fsc.h"
//#include "Cafe/HW/Espresso/PPCState.h"
#include "Cafe/IOSU/iosu_types_common.h"
#include "Cafe/IOSU/nn/iosu_nn_service.h"
#include "Cafe/IOSU/legacy/iosu_act.h"
#include "Cafe/CafeSystem.h"
#include "config/ActiveSettings.h"
#include <inttypes.h>
using ACPDeviceType = iosu::acp::ACPDeviceType;
static_assert(sizeof(acpMetaXml_t) == 0x3440);
static_assert(offsetof(acpMetaXml_t, title_id) == 0x0000);
static_assert(offsetof(acpMetaXml_t, boss_id) == 0x0008);
static_assert(offsetof(acpMetaXml_t, os_version) == 0x0010);
static_assert(offsetof(acpMetaXml_t, app_size) == 0x0018);
static_assert(offsetof(acpMetaXml_t, common_save_size) == 0x0020);
static_assert(offsetof(acpMetaXml_t, version) == 0x0048);
static_assert(offsetof(acpMetaXml_t, product_code) == 0x004C);
static_assert(offsetof(acpMetaXml_t, logo_type) == 0x00B4);
static_assert(offsetof(acpMetaXml_t, pc_cero) == 0x0100);
static_assert(offsetof(acpMetaXml_t, longname_ja) == 0x038C);
static_assert(offsetof(acpMetaXml_t, shortname_ja) == 0x1B8C);
static_assert(offsetof(acpMetaXml_t, publisher_ja) == 0x278C);
static_assert(sizeof(acpMetaData_t) == 0x1AB00);
static_assert(offsetof(acpMetaData_t, bootMovie) == 0);
static_assert(offsetof(acpMetaData_t, bootLogoTex) == 0x13B38);
namespace iosu
{
struct
{
bool isInitialized;
}iosuAcp = { 0 };
void _xml_parseU32(tinyxml2::XMLElement* xmlElement, const char* name, uint32be* v)
{
tinyxml2::XMLElement* subElement = xmlElement->FirstChildElement(name);
*v = 0;
if (subElement == nullptr)
return;
const char* text = subElement->GetText();
uint32 value;
if (sscanf(text, "%u", &value) == 0)
return;
*v = value;
}
void _xml_parseHex16(tinyxml2::XMLElement* xmlElement, const char* name, uint16be* v)
{
tinyxml2::XMLElement* subElement = xmlElement->FirstChildElement(name);
*v = 0;
if (subElement == nullptr)
return;
const char* text = subElement->GetText();
uint32 value;
if (sscanf(text, "%x", &value) == 0)
return;
*v = value;
}
void _xml_parseHex32(tinyxml2::XMLElement* xmlElement, const char* name, uint32be* v)
{
tinyxml2::XMLElement* subElement = xmlElement->FirstChildElement(name);
*v = 0;
if (subElement == nullptr)
return;
const char* text = subElement->GetText();
uint32 value;
if (sscanf(text, "%x", &value) == 0)
return;
*v = value;
}
void _xml_parseHex64(tinyxml2::XMLElement* xmlElement, const char* name, uint64* v)
{
tinyxml2::XMLElement* subElement = xmlElement->FirstChildElement(name);
*v = 0;
if (subElement == nullptr)
return;
const char* text = subElement->GetText();
uint64 value;
if (sscanf(text, "%" SCNx64, &value) == 0)
return;
*v = _swapEndianU64(value);
}
void _xml_parseString_(tinyxml2::XMLElement* xmlElement, const char* name, char* output, sint32 maxLength)
{
tinyxml2::XMLElement* subElement = xmlElement->FirstChildElement(name);
output[0] = '\0';
if (subElement == nullptr)
return;
const char* text = subElement->GetText();
if (text == nullptr)
{
output[0] = '\0';
return;
}
strncpy(output, text, maxLength - 1);
output[maxLength - 1] = '\0';
}
#define _metaXml_parseString(__xmlElement, __name, __output) _xml_parseString_(__xmlElement, __name, __output, sizeof(__output));
void parseSaveMetaXml(uint8* metaXmlData, sint32 metaXmlLength, acpMetaXml_t* metaXml)
{
memset(metaXml, 0, sizeof(acpMetaXml_t));
tinyxml2::XMLDocument appXml;
appXml.Parse((const char*)metaXmlData, metaXmlLength);
uint32 titleVersion = 0xFFFFFFFF;
tinyxml2::XMLElement* menuElement = appXml.FirstChildElement("menu");
if (menuElement)
{
_xml_parseHex64(menuElement, "title_id", &metaXml->title_id);
_xml_parseHex64(menuElement, "boss_id", &metaXml->boss_id);
_xml_parseHex64(menuElement, "os_version", &metaXml->os_version);
_xml_parseHex64(menuElement, "app_size", &metaXml->app_size);
_xml_parseHex64(menuElement, "common_save_size", &metaXml->common_save_size);
_xml_parseHex64(menuElement, "account_save_size", &metaXml->account_save_size);
_xml_parseHex64(menuElement, "common_boss_size", &metaXml->common_boss_size);
_xml_parseHex64(menuElement, "account_boss_size", &metaXml->account_boss_size);
_xml_parseHex64(menuElement, "join_game_mode_mask", &metaXml->join_game_mode_mask);
_xml_parseU32(menuElement, "version", &metaXml->version);
_metaXml_parseString(menuElement, "product_code", metaXml->product_code);
_metaXml_parseString(menuElement, "content_platform", metaXml->content_platform);
_metaXml_parseString(menuElement, "company_code", metaXml->company_code);
_metaXml_parseString(menuElement, "mastering_date", metaXml->mastering_date);
_xml_parseU32(menuElement, "logo_type", &metaXml->logo_type);
_xml_parseU32(menuElement, "app_launch_type", &metaXml->app_launch_type);
_xml_parseU32(menuElement, "invisible_flag", &metaXml->invisible_flag);
_xml_parseU32(menuElement, "no_managed_flag", &metaXml->no_managed_flag);
_xml_parseU32(menuElement, "no_event_log", &metaXml->no_event_log);
_xml_parseU32(menuElement, "no_icon_database", &metaXml->no_icon_database);
_xml_parseU32(menuElement, "launching_flag", &metaXml->launching_flag);
_xml_parseU32(menuElement, "install_flag", &metaXml->install_flag);
_xml_parseU32(menuElement, "closing_msg", &metaXml->closing_msg);
_xml_parseU32(menuElement, "title_version", &metaXml->title_version);
_xml_parseHex32(menuElement, "group_id", &metaXml->group_id);
_xml_parseU32(menuElement, "save_no_rollback", &metaXml->save_no_rollback);
_xml_parseU32(menuElement, "bg_daemon_enable", &metaXml->bg_daemon_enable);
_xml_parseHex32(menuElement, "join_game_id", &metaXml->join_game_id);
_xml_parseU32(menuElement, "olv_accesskey", &metaXml->olv_accesskey);
_xml_parseU32(menuElement, "wood_tin", &metaXml->wood_tin);
_xml_parseU32(menuElement, "e_manual", &metaXml->e_manual);
_xml_parseU32(menuElement, "e_manual_version", &metaXml->e_manual_version);
_xml_parseHex32(menuElement, "region", &metaXml->region);
_xml_parseU32(menuElement, "pc_cero", &metaXml->pc_cero);
_xml_parseU32(menuElement, "pc_esrb", &metaXml->pc_esrb);
_xml_parseU32(menuElement, "pc_bbfc", &metaXml->pc_bbfc);
_xml_parseU32(menuElement, "pc_usk", &metaXml->pc_usk);
_xml_parseU32(menuElement, "pc_pegi_gen", &metaXml->pc_pegi_gen);
_xml_parseU32(menuElement, "pc_pegi_fin", &metaXml->pc_pegi_fin);
_xml_parseU32(menuElement, "pc_pegi_prt", &metaXml->pc_pegi_prt);
_xml_parseU32(menuElement, "pc_pegi_bbfc", &metaXml->pc_pegi_bbfc);
_xml_parseU32(menuElement, "pc_cob", &metaXml->pc_cob);
_xml_parseU32(menuElement, "pc_grb", &metaXml->pc_grb);
_xml_parseU32(menuElement, "pc_cgsrr", &metaXml->pc_cgsrr);
_xml_parseU32(menuElement, "pc_oflc", &metaXml->pc_oflc);
_xml_parseU32(menuElement, "pc_reserved0", &metaXml->pc_reserved0);
_xml_parseU32(menuElement, "pc_reserved1", &metaXml->pc_reserved1);
_xml_parseU32(menuElement, "pc_reserved2", &metaXml->pc_reserved2);
_xml_parseU32(menuElement, "pc_reserved3", &metaXml->pc_reserved3);
_xml_parseU32(menuElement, "ext_dev_nunchaku", &metaXml->ext_dev_nunchaku);
_xml_parseU32(menuElement, "ext_dev_classic", &metaXml->ext_dev_classic);
_xml_parseU32(menuElement, "ext_dev_urcc", &metaXml->ext_dev_urcc);
_xml_parseU32(menuElement, "ext_dev_board", &metaXml->ext_dev_board);
_xml_parseU32(menuElement, "ext_dev_usb_keyboard", &metaXml->ext_dev_usb_keyboard);
_xml_parseU32(menuElement, "ext_dev_etc", &metaXml->ext_dev_etc);
_metaXml_parseString(menuElement, "ext_dev_etc_name", metaXml->ext_dev_etc_name);
_xml_parseU32(menuElement, "eula_version", &metaXml->eula_version);
_xml_parseU32(menuElement, "drc_use", &metaXml->drc_use);
_xml_parseU32(menuElement, "network_use", &metaXml->network_use);
_xml_parseU32(menuElement, "online_account_use", &metaXml->online_account_use);
_xml_parseU32(menuElement, "direct_boot", &metaXml->direct_boot);
_xml_parseU32(menuElement, "reserved_flag0", &(metaXml->reserved_flag[0]));
_xml_parseU32(menuElement, "reserved_flag1", &(metaXml->reserved_flag[1]));
_xml_parseU32(menuElement, "reserved_flag2", &(metaXml->reserved_flag[2]));
_xml_parseU32(menuElement, "reserved_flag3", &(metaXml->reserved_flag[3]));
_xml_parseU32(menuElement, "reserved_flag4", &(metaXml->reserved_flag[4]));
_xml_parseU32(menuElement, "reserved_flag5", &(metaXml->reserved_flag[5]));
_xml_parseU32(menuElement, "reserved_flag6", &(metaXml->reserved_flag[6]));
_xml_parseU32(menuElement, "reserved_flag7", &(metaXml->reserved_flag[7]));
_metaXml_parseString(menuElement, "longname_ja", metaXml->longname_ja);
_metaXml_parseString(menuElement, "longname_en", metaXml->longname_en);
_metaXml_parseString(menuElement, "longname_fr", metaXml->longname_fr);
_metaXml_parseString(menuElement, "longname_de", metaXml->longname_de);
_metaXml_parseString(menuElement, "longname_it", metaXml->longname_it);
_metaXml_parseString(menuElement, "longname_es", metaXml->longname_es);
_metaXml_parseString(menuElement, "longname_zhs", metaXml->longname_zhs);
_metaXml_parseString(menuElement, "longname_ko", metaXml->longname_ko);
_metaXml_parseString(menuElement, "longname_nl", metaXml->longname_nl);
_metaXml_parseString(menuElement, "longname_pt", metaXml->longname_pt);
_metaXml_parseString(menuElement, "longname_ru", metaXml->longname_ru);
_metaXml_parseString(menuElement, "longname_zht", metaXml->longname_zht);
_metaXml_parseString(menuElement, "shortname_ja", metaXml->shortname_ja);
_metaXml_parseString(menuElement, "shortname_en", metaXml->shortname_en);
_metaXml_parseString(menuElement, "shortname_fr", metaXml->shortname_fr);
_metaXml_parseString(menuElement, "shortname_de", metaXml->shortname_de);
_metaXml_parseString(menuElement, "shortname_it", metaXml->shortname_it);
_metaXml_parseString(menuElement, "shortname_es", metaXml->shortname_es);
_metaXml_parseString(menuElement, "shortname_zhs", metaXml->shortname_zhs);
_metaXml_parseString(menuElement, "shortname_ko", metaXml->shortname_ko);
_metaXml_parseString(menuElement, "shortname_nl", metaXml->shortname_nl);
_metaXml_parseString(menuElement, "shortname_pt", metaXml->shortname_pt);
_metaXml_parseString(menuElement, "shortname_ru", metaXml->shortname_ru);
_metaXml_parseString(menuElement, "shortname_zht", metaXml->shortname_zht);
_metaXml_parseString(menuElement, "publisher_ja", metaXml->publisher_ja);
_metaXml_parseString(menuElement, "publisher_en", metaXml->publisher_en);
_metaXml_parseString(menuElement, "publisher_fr", metaXml->publisher_fr);
_metaXml_parseString(menuElement, "publisher_de", metaXml->publisher_de);
_metaXml_parseString(menuElement, "publisher_it", metaXml->publisher_it);
_metaXml_parseString(menuElement, "publisher_es", metaXml->publisher_es);
_metaXml_parseString(menuElement, "publisher_zhs", metaXml->publisher_zhs);
_metaXml_parseString(menuElement, "publisher_ko", metaXml->publisher_ko);
_metaXml_parseString(menuElement, "publisher_nl", metaXml->publisher_nl);
_metaXml_parseString(menuElement, "publisher_pt", metaXml->publisher_pt);
_metaXml_parseString(menuElement, "publisher_ru", metaXml->publisher_ru);
_metaXml_parseString(menuElement, "publisher_zht", metaXml->publisher_zht);
for (sint32 i = 0; i < 32; i++)
{
char tempStr[256];
sprintf(tempStr, "add_on_unique_id%d", i);
_xml_parseU32(menuElement, tempStr, &(metaXml->add_on_unique_id[i]));
}
}
}
bool _is8DigitHex(const char* str)
{
if (strlen(str) != 8)
return false;
for (sint32 f = 0; f < 8; f++)
{
if (str[f] >= '0' && str[f] <= '9')
continue;
if (str[f] >= 'a' && str[f] <= 'f')
continue;
if (str[f] >= 'A' && str[f] <= 'F')
continue;
return false;
}
return true;
}
sint32 ACPGetSaveDataTitleIdList(uint32 storageDeviceGuessed, acpTitleId_t* titleIdList, sint32 maxCount, uint32be* countOut)
{
sint32 count = 0;
const char* devicePath = "/vol/storage_mlc01/";
if (storageDeviceGuessed != 3)
cemu_assert_unimplemented();
char searchPath[FSA_CMD_PATH_MAX_LENGTH];
sprintf(searchPath, "%susr/save/", devicePath);
sint32 fscStatus = 0;
FSCVirtualFile* fscDirIteratorTitleIdHigh = fsc_openDirIterator(searchPath, &fscStatus);
FSCDirEntry dirEntryTitleIdHigh;
FSCDirEntry dirEntryTitleIdLow;
if(fscDirIteratorTitleIdHigh)
{
while (fsc_nextDir(fscDirIteratorTitleIdHigh, &dirEntryTitleIdHigh))
{
// is 8-digit hex?
if(_is8DigitHex(dirEntryTitleIdHigh.path) == false)
continue;
uint32 titleIdHigh;
sscanf(dirEntryTitleIdHigh.path, "%x", &titleIdHigh);
sprintf(searchPath, "%susr/save/%08x/", devicePath, titleIdHigh);
FSCVirtualFile* fscDirIteratorTitleIdLow = fsc_openDirIterator(searchPath, &fscStatus);
if (fscDirIteratorTitleIdLow)
{
while (fsc_nextDir(fscDirIteratorTitleIdLow, &dirEntryTitleIdLow))
{
// is 8-digit hex?
if (_is8DigitHex(dirEntryTitleIdLow.path) == false)
continue;
uint32 titleIdLow;
sscanf(dirEntryTitleIdLow.path, "%x", &titleIdLow);
// check if /meta/meta.xml exists
char tempPath[FSA_CMD_PATH_MAX_LENGTH];
sprintf(tempPath, "%susr/save/%08x/%08x/meta/meta.xml", devicePath, titleIdHigh, titleIdLow);
if (fsc_doesFileExist(tempPath))
{
if (count < maxCount)
{
titleIdList[count].titleIdHigh = titleIdHigh;
titleIdList[count].titleIdLow = titleIdLow;
count++;
}
}
else
{
cemuLog_logDebug(LogType::Force, "ACPGetSaveDataTitleIdList(): Missing meta.xml for save {:08x}-{:08x}", titleIdHigh, titleIdLow);
}
}
fsc_close(fscDirIteratorTitleIdLow);
}
}
fsc_close(fscDirIteratorTitleIdHigh);
}
*countOut = count;
return 0;
}
sint32 ACPGetTitleSaveMetaXml(uint64 titleId, acpMetaXml_t* acpMetaXml, sint32 uknType)
{
// uknType is probably the storage device?
if (uknType != 3) // mlc01 ?
assert_dbg();
char xmlPath[FSA_CMD_PATH_MAX_LENGTH];
sprintf(xmlPath, "%susr/save/%08x/%08x/meta/meta.xml", "/vol/storage_mlc01/", (uint32)(titleId>>32), (uint32)(titleId&0xFFFFFFFF));
uint32 saveMetaXmlSize = 0;
uint8* saveMetaXmlData = fsc_extractFile(xmlPath, &saveMetaXmlSize);
if (saveMetaXmlData)
{
parseSaveMetaXml(saveMetaXmlData, saveMetaXmlSize, acpMetaXml);
free(saveMetaXmlData);
}
else
{
cemuLog_log(LogType::Force, "ACPGetTitleSaveMetaXml(): Meta file \"{}\" does not exist", xmlPath);
memset(acpMetaXml, 0, sizeof(acpMetaXml_t));
}
return 0;
}
sint32 ACPGetTitleMetaData(uint64 titleId, acpMetaData_t* acpMetaData)
{
memset(acpMetaData, 0, sizeof(acpMetaData_t));
char titlePath[1024];
if (((titleId >> 32) & 0x10) != 0)
{
sprintf(titlePath, "/vol/storage_mlc01/sys/title/%08x/%08x/", (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF));
}
else
{
sprintf(titlePath, "/vol/storage_mlc01/usr/title/%08x/%08x/", (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF));
}
char filePath[FSA_CMD_PATH_MAX_LENGTH];
sprintf(filePath, "%smeta/bootMovie.h264", titlePath);
// bootMovie.h264
uint32 metaBootMovieSize = 0;
uint8* metaBootMovieData = fsc_extractFile(filePath, &metaBootMovieSize);
if (metaBootMovieData)
{
memcpy(acpMetaData->bootMovie, metaBootMovieData, std::min<uint32>(metaBootMovieSize, sizeof(acpMetaData->bootMovie)));
free(metaBootMovieData);
}
else
cemuLog_log(LogType::Force, "ACPGetTitleMetaData(): Unable to load \"{}\"", filePath);
// bootLogoTex.tga
sprintf(filePath, "%smeta/bootLogoTex.tga", titlePath);
uint32 metaBootLogoSize = 0;
uint8* metaBootLogoData = fsc_extractFile(filePath, &metaBootLogoSize);
if (metaBootLogoData)
{
memcpy(acpMetaData->bootLogoTex, metaBootLogoData, std::min<uint32>(metaBootLogoSize, sizeof(acpMetaData->bootLogoTex)));
free(metaBootLogoData);
}
else
cemuLog_log(LogType::Force, "ACPGetTitleMetaData(): Unable to load \"{}\"", filePath);
return 0;
}
sint32 ACPGetTitleMetaXml(uint64 titleId, acpMetaXml_t* acpMetaXml)
{
memset(acpMetaXml, 0, sizeof(acpMetaXml_t));
char titlePath[1024];
if (((titleId >> 32) & 0x10) != 0)
{
sprintf(titlePath, "/vol/storage_mlc01/sys/title/%08x/%08x/", (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF));
}
else
{
sprintf(titlePath, "/vol/storage_mlc01/usr/title/%08x/%08x/", (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF));
}
char filePath[FSA_CMD_PATH_MAX_LENGTH];
sprintf(filePath, "%smeta/meta.xml", titlePath);
uint32 metaXmlSize = 0;
uint8* metaXmlData = fsc_extractFile(filePath, &metaXmlSize);
if (metaXmlData)
{
parseSaveMetaXml(metaXmlData, metaXmlSize, acpMetaXml);
free(metaXmlData);
}
else
{
cemuLog_log(LogType::Force, "ACPGetTitleMetaXml(): Meta file \"{}\" does not exist", filePath);
}
return 0;
}
sint32 ACPGetTitleSaveDirEx(uint64 titleId, uint32 storageDeviceGuessed, acpSaveDirInfo_t* saveDirInfo, sint32 maxCount, uint32be* countOut)
{
sint32 count = 0;
const char* devicePath = "/vol/storage_mlc01/";
if (storageDeviceGuessed != 3)
cemu_assert_unimplemented();
char searchPath[FSA_CMD_PATH_MAX_LENGTH];
char tempPath[FSA_CMD_PATH_MAX_LENGTH];
sint32 fscStatus = 0;
// add common dir
sprintf(searchPath, "%susr/save/%08x/%08x/user/common/", devicePath, (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF));
if (fsc_doesDirectoryExist(searchPath))
{
acpSaveDirInfo_t* entry = saveDirInfo + count;
if (count < maxCount)
{
// get dir size
sprintf(tempPath, "%susr/save/%08x/%08x/user/common/", devicePath, (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF));
FSCVirtualFile* fscDir = fsc_open(tempPath, FSC_ACCESS_FLAG::OPEN_DIR, &fscStatus);
uint64 dirSize = 0;
if (fscDir)
{
dirSize = fsc_getFileSize(fscDir);
fsc_close(fscDir);
}
memset(entry, 0, sizeof(acpSaveDirInfo_t));
entry->ukn00 = (uint32)(titleId>>32);
entry->ukn04 = (uint32)(titleId&0xFFFFFFFF);
entry->persistentId = 0; // 0 -> common save
entry->ukn0C = 0;
entry->sizeA = _swapEndianU64(0); // ukn
entry->sizeB = _swapEndianU64(dirSize);
entry->time = _swapEndianU64((coreinit::coreinit_getOSTime() / ESPRESSO_TIMER_CLOCK));
sprintf(entry->path, "%susr/save/%08x/%08x/meta/", devicePath, (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF));
count++;
}
}
// add user directories
sprintf(searchPath, "%susr/save/%08x/%08x/user/", devicePath, (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF));
FSCVirtualFile* fscDirIterator = fsc_openDirIterator(searchPath, &fscStatus);
if (fscDirIterator == nullptr)
{
cemuLog_log(LogType::Force, "ACPGetTitleSaveDirEx(): Failed to iterate directories in \"{}\"", searchPath);
*countOut = 0;
}
else
{
FSCDirEntry dirEntry;
while( fsc_nextDir(fscDirIterator, &dirEntry) )
{
if(dirEntry.isDirectory == false)
continue;
// is 8-digit hex name? (persistent id)
if(_is8DigitHex(dirEntry.path) == false )
continue;
uint32 persistentId = 0;
sscanf(dirEntry.path, "%x", &persistentId);
acpSaveDirInfo_t* entry = saveDirInfo + count;
if (count < maxCount)
{
memset(entry, 0, sizeof(acpSaveDirInfo_t));
entry->ukn00 = (uint32)(titleId >> 32); // titleId?
entry->ukn04 = (uint32)(titleId & 0xFFFFFFFF); // titleId?
entry->persistentId = persistentId; // 0 -> common save
entry->ukn0C = 0;
entry->sizeA = _swapEndianU64(0);
entry->sizeB = _swapEndianU64(0);
entry->time = _swapEndianU64((coreinit::coreinit_getOSTime() / ESPRESSO_TIMER_CLOCK));
sprintf(entry->path, "%susr/save/%08x/%08x/meta/", devicePath, (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF));
count++;
}
}
fsc_close(fscDirIterator);
}
*countOut = count;
return 0;
}
int iosuAcp_thread()
{
SetThreadName("iosuAcp_thread");
while (true)
{
uint32 returnValue = 0; // Ioctl return value
ioQueueEntry_t* ioQueueEntry = iosuIoctl_getNextWithWait(IOS_DEVICE_ACP_MAIN);
if (ioQueueEntry->request == IOSU_ACP_REQUEST_CEMU)
{
iosuAcpCemuRequest_t* acpCemuRequest = (iosuAcpCemuRequest_t*)ioQueueEntry->bufferVectors[0].buffer.GetPtr();
if (acpCemuRequest->requestCode == IOSU_ACP_GET_SAVE_DATA_TITLE_ID_LIST)
{
uint32be count = 0;
acpCemuRequest->returnCode = ACPGetSaveDataTitleIdList(acpCemuRequest->type, (acpTitleId_t*)acpCemuRequest->ptr.GetPtr(), acpCemuRequest->maxCount, &count);
acpCemuRequest->resultU32.u32 = count;
}
else if (acpCemuRequest->requestCode == IOSU_ACP_GET_TITLE_SAVE_META_XML)
{
acpCemuRequest->returnCode = ACPGetTitleSaveMetaXml(acpCemuRequest->titleId, (acpMetaXml_t*)acpCemuRequest->ptr.GetPtr(), acpCemuRequest->type);
}
else if (acpCemuRequest->requestCode == IOSU_ACP_GET_TITLE_SAVE_DIR)
{
uint32be count = 0;
acpCemuRequest->returnCode = ACPGetTitleSaveDirEx(acpCemuRequest->titleId, acpCemuRequest->type, (acpSaveDirInfo_t*)acpCemuRequest->ptr.GetPtr(), acpCemuRequest->maxCount, &count);
acpCemuRequest->resultU32.u32 = count;
}
else if (acpCemuRequest->requestCode == IOSU_ACP_GET_TITLE_META_DATA)
{
acpCemuRequest->returnCode = ACPGetTitleMetaData(acpCemuRequest->titleId, (acpMetaData_t*)acpCemuRequest->ptr.GetPtr());
}
else if (acpCemuRequest->requestCode == IOSU_ACP_GET_TITLE_META_XML)
{
acpCemuRequest->returnCode = ACPGetTitleMetaXml(acpCemuRequest->titleId, (acpMetaXml_t*)acpCemuRequest->ptr.GetPtr());
}
else if (acpCemuRequest->requestCode == IOSU_ACP_CREATE_SAVE_DIR_EX)
{
acpCemuRequest->returnCode = acp::ACPCreateSaveDirEx(acpCemuRequest->accountSlot, acpCemuRequest->titleId);
}
else
cemu_assert_unimplemented();
}
else
cemu_assert_unimplemented();
iosuIoctl_completeRequest(ioQueueEntry, returnValue);
}
return 0;
}
void iosuAcp_init()
{
if (iosuAcp.isInitialized)
return;
std::thread t(iosuAcp_thread);
t.detach();
iosuAcp.isInitialized = true;
}
bool iosuAcp_isInitialized()
{
return iosuAcp.isInitialized;
}
/* Above is the legacy implementation. Below is the new style implementation which also matches the official IPC protocol and works with the real nn_acp.rpl */
namespace acp
{
uint64 _ACPGetTimestamp()
{
return coreinit::coreinit_getOSTime() / ESPRESSO_TIMER_CLOCK;
}
nnResult ACPUpdateSaveTimeStamp(uint32 persistentId, uint64 titleId, ACPDeviceType deviceType)
{
if (deviceType == ACPDeviceType::UnknownType)
{
return (nnResult)0xA030FB80;
}
// create or modify the saveinfo
const auto saveinfoPath = ActiveSettings::GetMlcPath("usr/save/{:08x}/{:08x}/meta/saveinfo.xml", GetTitleIdHigh(titleId), GetTitleIdLow(titleId));
auto saveinfoData = FileStream::LoadIntoMemory(saveinfoPath);
if (saveinfoData && !saveinfoData->empty())
{
namespace xml = tinyxml2;
xml::XMLDocument doc;
tinyxml2::XMLError xmlError = doc.Parse((const char*)saveinfoData->data(), saveinfoData->size());
if (xmlError == xml::XML_SUCCESS || xmlError == xml::XML_ERROR_EMPTY_DOCUMENT)
{
xml::XMLNode* child = doc.FirstChild();
// check for declaration -> <?xml version="1.0" encoding="utf-8"?>
if (!child || !child->ToDeclaration())
{
xml::XMLDeclaration* decl = doc.NewDeclaration();
doc.InsertFirstChild(decl);
}
xml::XMLElement* info = doc.FirstChildElement("info");
if (!info)
{
info = doc.NewElement("info");
doc.InsertEndChild(info);
}
// find node with persistentId
char tmp[64];
sprintf(tmp, "%08x", persistentId);
bool foundNode = false;
for (xml::XMLElement* account = info->FirstChildElement("account"); account; account = account->NextSiblingElement("account"))
{
if (account->Attribute("persistentId", tmp))
{
// found the entry! -> update timestamp
xml::XMLElement* timestamp = account->FirstChildElement("timestamp");
sprintf(tmp, "%" PRIx64, _ACPGetTimestamp());
if (timestamp)
timestamp->SetText(tmp);
else
{
timestamp = doc.NewElement("timestamp");
account->InsertFirstChild(timestamp);
}
foundNode = true;
break;
}
}
if (!foundNode)
{
tinyxml2::XMLElement* account = doc.NewElement("account");
{
sprintf(tmp, "%08x", persistentId);
account->SetAttribute("persistentId", tmp);
tinyxml2::XMLElement* timestamp = doc.NewElement("timestamp");
{
sprintf(tmp, "%" PRIx64, _ACPGetTimestamp());
timestamp->SetText(tmp);
}
account->InsertFirstChild(timestamp);
}
info->InsertFirstChild(account);
}
// update file
tinyxml2::XMLPrinter printer;
doc.Print(&printer);
FileStream* fs = FileStream::createFile2(saveinfoPath);
if (fs)
{
fs->writeString(printer.CStr());
delete fs;
}
}
}
return NN_RESULT_SUCCESS;
}
void CreateSaveMetaFiles(uint32 persistentId, uint64 titleId)
{
std::string titlePath = CafeSystem::GetMlcStoragePath(CafeSystem::GetForegroundTitleId());
sint32 fscStatus;
FSCVirtualFile* fscFile = fsc_open((titlePath + "/meta/meta.xml").c_str(), FSC_ACCESS_FLAG::OPEN_FILE | FSC_ACCESS_FLAG::READ_PERMISSION, &fscStatus);
if (fscFile)
{
sint32 fileSize = fsc_getFileSize(fscFile);
std::unique_ptr<uint8[]> fileContent = std::make_unique<uint8[]>(fileSize);
fsc_readFile(fscFile, fileContent.get(), fileSize);
fsc_close(fscFile);
const auto outPath = ActiveSettings::GetMlcPath("usr/save/{:08x}/{:08x}/meta/meta.xml", GetTitleIdHigh(titleId), GetTitleIdLow(titleId));
std::ofstream myFile(outPath, std::ios::out | std::ios::binary);
myFile.write((char*)fileContent.get(), fileSize);
myFile.close();
}
fscFile = fsc_open((titlePath + "/meta/iconTex.tga").c_str(), FSC_ACCESS_FLAG::OPEN_FILE | FSC_ACCESS_FLAG::READ_PERMISSION, &fscStatus);
if (fscFile)
{
sint32 fileSize = fsc_getFileSize(fscFile);
std::unique_ptr<uint8[]> fileContent = std::make_unique<uint8[]>(fileSize);
fsc_readFile(fscFile, fileContent.get(), fileSize);
fsc_close(fscFile);
const auto outPath = ActiveSettings::GetMlcPath("usr/save/{:08x}/{:08x}/meta/iconTex.tga", GetTitleIdHigh(titleId), GetTitleIdLow(titleId));
std::ofstream myFile(outPath, std::ios::out | std::ios::binary);
myFile.write((char*)fileContent.get(), fileSize);
myFile.close();
}
ACPUpdateSaveTimeStamp(persistentId, titleId, iosu::acp::ACPDeviceType::InternalDeviceType);
}
sint32 _ACPCreateSaveDir(uint32 persistentId, uint64 titleId, ACPDeviceType type)
{
uint32 high = GetTitleIdHigh(titleId) & (~0xC);
uint32 low = GetTitleIdLow(titleId);
sint32 fscStatus = FSC_STATUS_FILE_NOT_FOUND;
char path[256];
sprintf(path, "%susr/boss/", "/vol/storage_mlc01/");
fsc_createDir(path, &fscStatus);
sprintf(path, "%susr/boss/%08x/", "/vol/storage_mlc01/", high);
fsc_createDir(path, &fscStatus);
sprintf(path, "%susr/boss/%08x/%08x/", "/vol/storage_mlc01/", high, low);
fsc_createDir(path, &fscStatus);
sprintf(path, "%susr/boss/%08x/%08x/user/", "/vol/storage_mlc01/", high, low);
fsc_createDir(path, &fscStatus);
sprintf(path, "%susr/boss/%08x/%08x/user/common", "/vol/storage_mlc01/", high, low);
fsc_createDir(path, &fscStatus);
sprintf(path, "%susr/boss/%08x/%08x/user/%08x/", "/vol/storage_mlc01/", high, low, persistentId == 0 ? 0x80000001 : persistentId);
fsc_createDir(path, &fscStatus);
sprintf(path, "%susr/save/%08x/", "/vol/storage_mlc01/", high);
fsc_createDir(path, &fscStatus);
sprintf(path, "%susr/save/%08x/%08x/", "/vol/storage_mlc01/", high, low);
fsc_createDir(path, &fscStatus);
sprintf(path, "%susr/save/%08x/%08x/meta/", "/vol/storage_mlc01/", high, low);
fsc_createDir(path, &fscStatus);
sprintf(path, "%susr/save/%08x/%08x/user/", "/vol/storage_mlc01/", high, low);
fsc_createDir(path, &fscStatus);
sprintf(path, "%susr/save/%08x/%08x/user/common", "/vol/storage_mlc01/", high, low);
fsc_createDir(path, &fscStatus);
sprintf(path, "%susr/save/%08x/%08x/user/%08x", "/vol/storage_mlc01/", high, low, persistentId == 0 ? 0x80000001 : persistentId);
fsc_createDir(path, &fscStatus);
// copy xml meta files
CreateSaveMetaFiles(persistentId, titleId);
return 0;
}
nnResult ACPCreateSaveDir(uint32 persistentId, ACPDeviceType type)
{
uint64 titleId = CafeSystem::GetForegroundTitleId();
return _ACPCreateSaveDir(persistentId, titleId, type);
}
sint32 ACPCreateSaveDirEx(uint8 accountSlot, uint64 titleId)
{
uint32 persistentId = 0;
cemu_assert_debug(accountSlot >= 1 && accountSlot <= 13); // outside valid slot range?
bool r = iosu::act::GetPersistentId(accountSlot, &persistentId);
cemu_assert_debug(r);
return _ACPCreateSaveDir(persistentId, titleId, ACPDeviceType::InternalDeviceType);
}
nnResult ACPGetOlvAccesskey(uint32be* accessKey)
{
*accessKey = CafeSystem::GetForegroundTitleOlvAccesskey();
return 0;
}
class AcpMainService : public iosu::nn::IPCService
{
public:
AcpMainService() : iosu::nn::IPCService("/dev/acp_main") {}
nnResult ServiceCall(uint32 serviceId, void* request, void* response) override
{
cemuLog_log(LogType::Force, "Unsupported service call to /dev/acp_main");
cemu_assert_unimplemented();
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_ACP, 0);
}
};
AcpMainService gACPMainService;
class : public ::IOSUModule
{
void TitleStart() override
{
gACPMainService.Start();
// gACPMainService.SetTimerUpdate(1000); // call TimerUpdate() once a second
}
void TitleStop() override
{
gACPMainService.Stop();
}
}sIOSUModuleNNACP;
IOSUModule* GetModule()
{
return static_cast<IOSUModule*>(&sIOSUModuleNNACP);
}
} // namespace acp
} // namespace iosu
| 30,603
|
C++
|
.cpp
| 718
| 38.491643
| 185
| 0.707788
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,180
|
iosu_nn_service.cpp
|
cemu-project_Cemu/src/Cafe/IOSU/nn/iosu_nn_service.cpp
|
#include "iosu_nn_service.h"
#include "../kernel/iosu_kernel.h"
#include "util/helpers/helpers.h"
using namespace iosu::kernel;
namespace iosu
{
namespace nn
{
/* IPCSimpleService */
void IPCSimpleService::Start()
{
if (m_isRunning.exchange(true))
return;
m_threadInitialized = false;
m_requestStop = false;
m_serviceThread = std::thread(&IPCSimpleService::ServiceThread, this);
while (!m_threadInitialized) std::this_thread::sleep_for(std::chrono::milliseconds(10));
StartService();
}
void IPCSimpleService::Stop()
{
if (!m_isRunning.exchange(false))
return;
m_requestStop = true;
StopService();
if(m_timerId != IOSInvalidTimerId)
IOS_DestroyTimer(m_timerId);
m_timerId = IOSInvalidTimerId;
IOS_SendMessage(m_msgQueueId, 0, 0); // wake up thread
m_serviceThread.join();
}
void IPCSimpleService::ServiceThread()
{
if(!GetThreadName().empty())
SetThreadName(GetThreadName().c_str());
m_msgQueueId = IOS_CreateMessageQueue(_m_msgBuffer.GetPtr(), _m_msgBuffer.GetCount());
cemu_assert(!IOS_ResultIsError((IOS_ERROR)m_msgQueueId));
IOS_ERROR r = IOS_RegisterResourceManager(m_devicePath.c_str(), m_msgQueueId);
cemu_assert(!IOS_ResultIsError(r));
m_threadInitialized = true;
while (true)
{
IOSMessage msg;
r = IOS_ReceiveMessage(m_msgQueueId, &msg, 0);
cemu_assert(!IOS_ResultIsError(r));
if (msg == 0)
{
cemu_assert_debug(m_requestStop);
break;
}
else if(msg == 1)
{
TimerUpdate();
continue;
}
IPCCommandBody* cmd = MEMPTR<IPCCommandBody>(msg).GetPtr();
if (cmd->cmdId == IPCCommandId::IOS_OPEN)
{
void* clientObject = CreateClientObject();
if(clientObject == nullptr)
{
cemuLog_log(LogType::Force, "IPCSimpleService[{}]: Maximum handle count reached or handle rejected", m_devicePath);
IOS_ResourceReply(cmd, IOS_ERROR_MAXIMUM_REACHED);
continue;
}
IOSDevHandle newHandle = GetFreeHandle();
m_clientObjects[newHandle] = clientObject;
IOS_ResourceReply(cmd, (IOS_ERROR)newHandle);
continue;
}
else if (cmd->cmdId == IPCCommandId::IOS_CLOSE)
{
void* clientObject = GetClientObjectByHandle(cmd->devHandle);
if (clientObject)
DestroyClientObject(clientObject);
IOS_ResourceReply(cmd, IOS_ERROR_OK);
continue;
}
else if (cmd->cmdId == IPCCommandId::IOS_IOCTLV)
{
void* clientObject = GetClientObjectByHandle(cmd->devHandle);
if (!clientObject)
{
cemuLog_log(LogType::Force, "IPCSimpleService[{}]: Invalid IPC handle", m_devicePath);
IOS_ResourceReply(cmd, IOS_ERROR_INVALID);
continue;
}
uint32 requestId = cmd->args[0];
uint32 numIn = cmd->args[1];
uint32 numOut = cmd->args[2];
IPCIoctlVector* vec = MEMPTR<IPCIoctlVector>{ cmd->args[3] }.GetPtr();
IPCIoctlVector* vecIn = vec + 0; // the ordering of vecIn/vecOut differs from IPCService
IPCIoctlVector* vecOut = vec + numIn;
m_delayResponse = false;
m_activeCmd = cmd;
uint32 result = ServiceCall(clientObject, requestId, vecIn, numIn, vecOut, numOut);
if (!m_delayResponse)
IOS_ResourceReply(cmd, (IOS_ERROR)result);
m_activeCmd = nullptr;
continue;
}
else
{
cemuLog_log(LogType::Force, "IPCSimpleService[{}]: Unsupported IPC cmdId {}", m_devicePath, (uint32)cmd->cmdId.value());
cemu_assert_unimplemented();
IOS_ResourceReply(cmd, IOS_ERROR_INVALID);
}
}
IOS_DestroyMessageQueue(m_msgQueueId);
m_threadInitialized = false;
}
void IPCSimpleService::SetTimerUpdate(uint32 milliseconds)
{
if(m_timerId != IOSInvalidTimerId)
IOS_DestroyTimer(m_timerId);
m_timerId = IOS_CreateTimer(milliseconds * 1000, milliseconds * 1000, m_msgQueueId, 1);
}
IPCCommandBody* IPCSimpleService::ServiceCallDelayCurrentResponse()
{
cemu_assert_debug(m_activeCmd);
m_delayResponse = true;
return m_activeCmd;
}
void IPCSimpleService::ServiceCallAsyncRespond(IPCCommandBody* response, uint32 r)
{
IOS_ResourceReply(response, (IOS_ERROR)r);
}
/* IPCService */
void IPCService::Start()
{
if (m_isRunning.exchange(true))
return;
m_threadInitialized = false;
m_requestStop = false;
m_serviceThread = std::thread(&IPCService::ServiceThread, this);
while (!m_threadInitialized) std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
void IPCService::Stop()
{
if (!m_isRunning.exchange(false))
return;
m_requestStop = true;
IOS_SendMessage(m_msgQueueId, 0, 0); // wake up thread
m_serviceThread.join();
}
void IPCService::ServiceThread()
{
std::string serviceName = m_devicePath.substr(m_devicePath.find_last_of('/') == std::string::npos ? 0 : m_devicePath.find_last_of('/') + 1);
serviceName.insert(0, "NNsvc_");
SetThreadName(serviceName.c_str());
m_msgQueueId = IOS_CreateMessageQueue(_m_msgBuffer.GetPtr(), _m_msgBuffer.GetCount());
cemu_assert(!IOS_ResultIsError((IOS_ERROR)m_msgQueueId));
IOS_ERROR r = IOS_RegisterResourceManager(m_devicePath.c_str(), m_msgQueueId);
cemu_assert(!IOS_ResultIsError(r));
m_threadInitialized = true;
while (true)
{
IOSMessage msg;
IOS_ERROR r = IOS_ReceiveMessage(m_msgQueueId, &msg, 0);
cemu_assert(!IOS_ResultIsError(r));
if (msg == 0)
{
cemu_assert_debug(m_requestStop);
break;
}
IPCCommandBody* cmd = MEMPTR<IPCCommandBody>(msg).GetPtr();
if (cmd->cmdId == IPCCommandId::IOS_OPEN)
{
IOS_ResourceReply(cmd, (IOS_ERROR)CreateClientHandle());
continue;
}
else if (cmd->cmdId == IPCCommandId::IOS_CLOSE)
{
CloseClientHandle((IOSDevHandle)(uint32)cmd->devHandle);
IOS_ResourceReply(cmd, IOS_ERROR_OK);
continue;
}
else if (cmd->cmdId == IPCCommandId::IOS_IOCTLV)
{
uint32 requestId = cmd->args[0];
uint32 numIn = cmd->args[1];
uint32 numOut = cmd->args[2];
IPCIoctlVector* vec = MEMPTR<IPCIoctlVector>{ cmd->args[3] }.GetPtr();
IPCIoctlVector* vecIn = vec + numIn;
IPCIoctlVector* vecOut = vec + 0;
cemu_assert(vecIn->size >= 80 && !vecIn->basePhys.IsNull());
IPCServiceRequest* serviceRequest = MEMPTR<IPCServiceRequest>(vecIn->basePhys).GetPtr();
IPCServiceResponse* serviceResponse = MEMPTR<IPCServiceResponse>(vecOut->basePhys).GetPtr();
serviceResponse->nnResultCode = (uint32)ServiceCall(serviceRequest->serviceId, nullptr, nullptr);
IOS_ResourceReply(cmd, IOS_ERROR_OK);
continue;
}
else
{
cemuLog_log(LogType::Force, "{}: Unsupported cmdId", m_devicePath);
cemu_assert_unimplemented();
IOS_ResourceReply(cmd, IOS_ERROR_INVALID);
}
}
IOS_DestroyMessageQueue(m_msgQueueId);
m_threadInitialized = false;
}
};
};
| 6,833
|
C++
|
.cpp
| 204
| 28.794118
| 143
| 0.68682
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,181
|
iosu_odm.cpp
|
cemu-project_Cemu/src/Cafe/IOSU/ODM/iosu_odm.cpp
|
#include <util/helpers/helpers.h>
#include "iosu_odm.h"
#include "config/ActiveSettings.h"
#include "Common/FileStream.h"
#include "util/helpers/Semaphore.h"
#include "../kernel/iosu_kernel.h"
namespace iosu
{
namespace odm
{
using namespace iosu::kernel;
std::string s_devicePath = "/dev/odm";
std::thread s_serviceThread;
std::atomic_bool s_requestStop{false};
std::atomic_bool s_isRunning{false};
std::atomic_bool s_threadInitialized{ false };
IOSMsgQueueId s_msgQueueId;
SysAllocator<iosu::kernel::IOSMessage, 128> _s_msgBuffer;
enum class ODM_CMD_OPERATION_TYPE
{
CHECK_STATE = 4,
UKN_5 = 5,
};
enum class ODM_STATE
{
NONE = 0,
INITIAL = 1,
AUTHENTICATION = 2,
WAIT_FOR_DISC_READY = 3,
CAFE_DISC = 4,
RVL_DISC = 5,
CLEANING_DISC = 6,
INVALID_DISC = 8,
DIRTY_DISC = 9,
NO_DISC = 10,
INVALID_DRIVE = 11,
FATAL = 12,
HARD_FATAL = 13,
SHUTDOWN = 14,
};
void ODMHandleCommandIoctl(uint32 clientHandle, IPCCommandBody* cmd, ODM_CMD_OPERATION_TYPE operationId, void* ptrIn, uint32 sizeIn, void* ptrOut, uint32 sizeOut)
{
switch(operationId)
{
case ODM_CMD_OPERATION_TYPE::CHECK_STATE:
{
*(uint32be*)ptrOut = (uint32)ODM_STATE::NO_DISC;
break;
}
case ODM_CMD_OPERATION_TYPE::UKN_5:
{
// does this return anything?
break;
}
default:
{
cemuLog_log(LogType::Force, "ODMHandleCommandIoctl: Unknown operationId %d\n", (uint32)operationId);
break;
}
}
IOS_ResourceReply(cmd, IOS_ERROR_OK);
}
uint32 CreateClientHandle()
{
return 1; // we dont care about handles for now
}
void CloseClientHandle(uint32 handle)
{
}
void ODMServiceThread()
{
SetThreadName("ODMService");
s_msgQueueId = IOS_CreateMessageQueue(_s_msgBuffer.GetPtr(), _s_msgBuffer.GetCount());
cemu_assert(!IOS_ResultIsError((IOS_ERROR)s_msgQueueId));
IOS_ERROR r = IOS_RegisterResourceManager(s_devicePath.c_str(), s_msgQueueId);
cemu_assert(!IOS_ResultIsError(r));
s_threadInitialized = true;
while (true)
{
IOSMessage msg;
IOS_ERROR r = IOS_ReceiveMessage(s_msgQueueId, &msg, 0);
cemu_assert(!IOS_ResultIsError(r));
if (msg == 0)
{
cemu_assert_debug(s_requestStop);
break;
}
IPCCommandBody* cmd = MEMPTR<IPCCommandBody>(msg).GetPtr();
uint32 clientHandle = (uint32)cmd->devHandle;
if (cmd->cmdId == IPCCommandId::IOS_OPEN)
{
IOS_ResourceReply(cmd, (IOS_ERROR)CreateClientHandle());
continue;
}
else if (cmd->cmdId == IPCCommandId::IOS_CLOSE)
{
CloseClientHandle((IOSDevHandle)(uint32)cmd->devHandle);
IOS_ResourceReply(cmd, IOS_ERROR_OK);
continue;
}
else if (cmd->cmdId == IPCCommandId::IOS_IOCTLV)
{
uint32 requestId = cmd->args[0];
uint32 numIn = cmd->args[1];
uint32 numOut = cmd->args[2];
IPCIoctlVector* vec = MEMPTR<IPCIoctlVector>{ cmd->args[3] }.GetPtr();
IPCIoctlVector* vecIn = vec + numIn;
IPCIoctlVector* vecOut = vec + 0;
cemuLog_log(LogType::Force, "{}: Received unsupported Ioctlv cmd", s_devicePath);
IOS_ResourceReply(cmd, IOS_ERROR_INVALID);
continue;
}
else if (cmd->cmdId == IPCCommandId::IOS_IOCTL)
{
ODMHandleCommandIoctl(clientHandle, cmd, (ODM_CMD_OPERATION_TYPE)cmd->args[0].value(), MEMPTR<void>(cmd->args[1]), cmd->args[2], MEMPTR<void>(cmd->args[3]), cmd->args[4]);
}
else
{
cemuLog_log(LogType::Force, "{}: Unsupported cmdId", s_devicePath);
cemu_assert_unimplemented();
IOS_ResourceReply(cmd, IOS_ERROR_INVALID);
}
}
s_threadInitialized = false;
}
void Initialize()
{
if (s_isRunning.exchange(true))
return;
s_threadInitialized = false;
s_requestStop = false;
s_serviceThread = std::thread(&ODMServiceThread);
while (!s_threadInitialized) std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
void Shutdown()
{
if (!s_isRunning.exchange(false))
return;
s_requestStop = true;
IOS_SendMessage(s_msgQueueId, 0, 0);
s_serviceThread.join();
}
}
}
| 4,103
|
C++
|
.cpp
| 144
| 24.256944
| 176
| 0.674354
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,182
|
iosu_ccr_nfc.cpp
|
cemu-project_Cemu/src/Cafe/IOSU/ccr_nfc/iosu_ccr_nfc.cpp
|
#include "iosu_ccr_nfc.h"
#include "Cafe/IOSU/kernel/iosu_kernel.h"
#include "util/crypto/aes128.h"
#include <openssl/evp.h>
#include <openssl/hmac.h>
namespace iosu
{
namespace ccr_nfc
{
IOSMsgQueueId sCCRNFCMsgQueue;
SysAllocator<iosu::kernel::IOSMessage, 0x20> sCCRNFCMsgQueueMsgBuffer;
std::thread sCCRNFCThread;
constexpr uint8 sNfcKey[] = { 0xC1, 0x2B, 0x07, 0x10, 0xD7, 0x2C, 0xEB, 0x5D, 0x43, 0x49, 0xB7, 0x43, 0xE3, 0xCA, 0xD2, 0x24 };
constexpr uint8 sNfcKeyIV[] = { 0x4F, 0xD3, 0x9A, 0x6E, 0x79, 0xFC, 0xEA, 0xAD, 0x99, 0x90, 0x4D, 0xB8, 0xEE, 0x38, 0xE9, 0xDB };
constexpr uint8 sUnfixedInfosMagicBytes[] = { 0x00, 0x00, 0xDB, 0x4B, 0x9E, 0x3F, 0x45, 0x27, 0x8F, 0x39, 0x7E, 0xFF, 0x9B, 0x4F, 0xB9, 0x93 };
constexpr uint8 sLockedSecretMagicBytes[] = { 0xFD, 0xC8, 0xA0, 0x76, 0x94, 0xB8, 0x9E, 0x4C, 0x47, 0xD3, 0x7D, 0xE8, 0xCE, 0x5C, 0x74, 0xC1 };
constexpr uint8 sUnfixedInfosString[] = { 0x75, 0x6E, 0x66, 0x69, 0x78, 0x65, 0x64, 0x20, 0x69, 0x6E, 0x66, 0x6F, 0x73, 0x00, 0x00, 0x00 };
constexpr uint8 sLockedSecretString[] = { 0x6C, 0x6F, 0x63, 0x6B, 0x65, 0x64, 0x20, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, 0x00, 0x00, 0x00 };
constexpr uint8 sLockedSecretHmacKey[] = { 0x7F, 0x75, 0x2D, 0x28, 0x73, 0xA2, 0x00, 0x17, 0xFE, 0xF8, 0x5C, 0x05, 0x75, 0x90, 0x4B, 0x6D };
constexpr uint8 sUnfixedInfosHmacKey[] = { 0x1D, 0x16, 0x4B, 0x37, 0x5B, 0x72, 0xA5, 0x57, 0x28, 0xB9, 0x1D, 0x64, 0xB6, 0xA3, 0xC2, 0x05 };
uint8 sLockedSecretInternalKey[0x10];
uint8 sLockedSecretInternalNonce[0x10];
uint8 sLockedSecretInternalHmacKey[0x10];
uint8 sUnfixedInfosInternalKey[0x10];
uint8 sUnfixedInfosInternalNonce[0x10];
uint8 sUnfixedInfosInternalHmacKey[0x10];
sint32 __CCRNFCValidateCryptData(CCRNFCCryptData* data, uint32 size, bool validateOffsets)
{
if (!data)
{
return CCR_NFC_ERROR;
}
if (size != sizeof(CCRNFCCryptData))
{
return CCR_NFC_ERROR;
}
if (!validateOffsets)
{
return 0;
}
// Make sure all offsets are within bounds
if (data->version == 0)
{
if (data->unfixedInfosHmacOffset < 0x1C9 && data->unfixedInfosOffset < 0x1C9 &&
data->lockedSecretHmacOffset < 0x1C9 && data->lockedSecretOffset < 0x1C9 &&
data->lockedSecretSize < 0x1C9 && data->unfixedInfosSize < 0x1C9)
{
return 0;
}
}
else if (data->version == 2)
{
if (data->unfixedInfosHmacOffset < 0x21D && data->unfixedInfosOffset < 0x21D &&
data->lockedSecretHmacOffset < 0x21D && data->lockedSecretOffset < 0x21D &&
data->lockedSecretSize < 0x21D && data->unfixedInfosSize < 0x21D)
{
return 0;
}
}
return CCR_NFC_ERROR;
}
sint32 CCRNFCAESCTRCrypt(const uint8* key, const void* ivNonce, const void* inData, uint32 inSize, void* outData, uint32 outSize)
{
uint8 tmpIv[0x10];
memcpy(tmpIv, ivNonce, sizeof(tmpIv));
memcpy(outData, inData, inSize);
AES128CTR_transform((uint8*)outData, outSize, (uint8*)key, tmpIv);
return 0;
}
sint32 __CCRNFCGenerateKey(const uint8* hmacKey, uint32 hmacKeySize, const uint8* name, uint32 nameSize, const uint8* inData, uint32 inSize, uint8* outData, uint32 outSize)
{
if (nameSize != 0xe || outSize != 0x40)
{
return CCR_NFC_ERROR;
}
// Create a buffer containing 2 counter bytes, the key name, and the key data
uint8 buffer[0x50];
buffer[0] = 0;
buffer[1] = 0;
memcpy(buffer + 2, name, nameSize);
memcpy(buffer + nameSize + 2, inData, inSize);
uint16 counter = 0;
while (outSize > 0)
{
// Set counter bytes and increment counter
buffer[0] = (counter >> 8) & 0xFF;
buffer[1] = counter & 0xFF;
counter++;
uint32 dataSize = outSize;
if (!HMAC(EVP_sha256(), hmacKey, hmacKeySize, buffer, sizeof(buffer), outData, &dataSize))
{
return CCR_NFC_ERROR;
}
outSize -= 0x20;
outData += 0x20;
}
return 0;
}
sint32 __CCRNFCGenerateInternalKeys(const CCRNFCCryptData* in, const uint8* keyGenSalt)
{
uint8 lockedSecretBuffer[0x40] = { 0 };
uint8 unfixedInfosBuffer[0x40] = { 0 };
uint8 outBuffer[0x40] = { 0 };
// Fill the locked secret buffer
memcpy(lockedSecretBuffer, sLockedSecretMagicBytes, sizeof(sLockedSecretMagicBytes));
if (in->version == 0)
{
// For Version 0 this is the 16-byte Format Info
memcpy(lockedSecretBuffer + 0x10, in->data + in->uuidOffset, 0x10);
}
else if (in->version == 2)
{
// For Version 2 this is 2 times the 7-byte UID + 1 check byte
memcpy(lockedSecretBuffer + 0x10, in->data + in->uuidOffset, 8);
memcpy(lockedSecretBuffer + 0x18, in->data + in->uuidOffset, 8);
}
else
{
return CCR_NFC_ERROR;
}
// Append key generation salt
memcpy(lockedSecretBuffer + 0x20, keyGenSalt, 0x20);
// Generate the key output
sint32 res = __CCRNFCGenerateKey(sLockedSecretHmacKey, sizeof(sLockedSecretHmacKey), sLockedSecretString, 0xe, lockedSecretBuffer, sizeof(lockedSecretBuffer), outBuffer, sizeof(outBuffer));
if (res != 0)
{
return res;
}
// Unpack the key buffer
memcpy(sLockedSecretInternalKey, outBuffer, 0x10);
memcpy(sLockedSecretInternalNonce, outBuffer + 0x10, 0x10);
memcpy(sLockedSecretInternalHmacKey, outBuffer + 0x20, 0x10);
// Fill the unfixed infos buffer
memcpy(unfixedInfosBuffer, in->data + in->seedOffset, 2);
memcpy(unfixedInfosBuffer + 2, sUnfixedInfosMagicBytes + 2, 0xe);
if (in->version == 0)
{
// For Version 0 this is the 16-byte Format Info
memcpy(unfixedInfosBuffer + 0x10, in->data + in->uuidOffset, 0x10);
}
else if (in->version == 2)
{
// For Version 2 this is 2 times the 7-byte UID + 1 check byte
memcpy(unfixedInfosBuffer + 0x10, in->data + in->uuidOffset, 8);
memcpy(unfixedInfosBuffer + 0x18, in->data + in->uuidOffset, 8);
}
else
{
return CCR_NFC_ERROR;
}
// Append key generation salt
memcpy(unfixedInfosBuffer + 0x20, keyGenSalt, 0x20);
// Generate the key output
res = __CCRNFCGenerateKey(sUnfixedInfosHmacKey, sizeof(sUnfixedInfosHmacKey), sUnfixedInfosString, 0xe, unfixedInfosBuffer, sizeof(unfixedInfosBuffer), outBuffer, sizeof(outBuffer));
if (res != 0)
{
return res;
}
// Unpack the key buffer
memcpy(sUnfixedInfosInternalKey, outBuffer, 0x10);
memcpy(sUnfixedInfosInternalNonce, outBuffer + 0x10, 0x10);
memcpy(sUnfixedInfosInternalHmacKey, outBuffer + 0x20, 0x10);
return 0;
}
sint32 __CCRNFCCryptData(const CCRNFCCryptData* in, CCRNFCCryptData* out, bool decrypt)
{
// Decrypt key generation salt
uint8 keyGenSalt[0x20];
sint32 res = CCRNFCAESCTRCrypt(sNfcKey, sNfcKeyIV, in->data + in->keyGenSaltOffset, 0x20, keyGenSalt, sizeof(keyGenSalt));
if (res != 0)
{
return res;
}
// Prepare internal keys
res = __CCRNFCGenerateInternalKeys(in, keyGenSalt);
if (res != 0)
{
return res;
}
if (decrypt)
{
// Only version 0 tags have an encrypted locked secret area
if (in->version == 0)
{
res = CCRNFCAESCTRCrypt(sLockedSecretInternalKey, sLockedSecretInternalNonce, in->data + in->lockedSecretOffset, in->lockedSecretSize, out->data + in->lockedSecretOffset, in->lockedSecretSize);
if (res != 0)
{
return res;
}
}
// Decrypt unfxied infos
res = CCRNFCAESCTRCrypt(sUnfixedInfosInternalKey, sUnfixedInfosInternalNonce, in->data + in->unfixedInfosOffset, in->unfixedInfosSize, out->data + in->unfixedInfosOffset, in->unfixedInfosSize);
if (res != 0)
{
return res;
}
// Verify HMACs
uint8 hmacBuffer[0x20];
uint32 hmacLen = sizeof(hmacBuffer);
if (!HMAC(EVP_sha256(), sLockedSecretInternalHmacKey, sizeof(sLockedSecretInternalHmacKey), out->data + in->lockedSecretHmacOffset + 0x20, (in->dataSize - in->lockedSecretHmacOffset) - 0x20, hmacBuffer, &hmacLen))
{
return CCR_NFC_ERROR;
}
if (memcmp(in->data + in->lockedSecretHmacOffset, hmacBuffer, 0x20) != 0)
{
return CCR_NFC_INVALID_LOCKED_SECRET;
}
if (in->version == 0)
{
hmacLen = sizeof(hmacBuffer);
res = HMAC(EVP_sha256(), sUnfixedInfosInternalHmacKey, sizeof(sUnfixedInfosInternalHmacKey), out->data + in->unfixedInfosHmacOffset + 0x20, (in->dataSize - in->unfixedInfosHmacOffset) - 0x20, hmacBuffer, &hmacLen) ? 0 : CCR_NFC_ERROR;
}
else
{
hmacLen = sizeof(hmacBuffer);
res = HMAC(EVP_sha256(), sUnfixedInfosInternalHmacKey, sizeof(sUnfixedInfosInternalHmacKey), out->data + in->unfixedInfosHmacOffset + 0x21, (in->dataSize - in->unfixedInfosHmacOffset) - 0x21, hmacBuffer, &hmacLen) ? 0 : CCR_NFC_ERROR;
}
if (memcmp(in->data + in->unfixedInfosHmacOffset, hmacBuffer, 0x20) != 0)
{
return CCR_NFC_INVALID_UNFIXED_INFOS;
}
}
else
{
uint8 hmacBuffer[0x20];
uint32 hmacLen = sizeof(hmacBuffer);
if (!HMAC(EVP_sha256(), sLockedSecretInternalHmacKey, sizeof(sLockedSecretInternalHmacKey), out->data + in->lockedSecretHmacOffset + 0x20, (in->dataSize - in->lockedSecretHmacOffset) - 0x20, hmacBuffer, &hmacLen))
{
return CCR_NFC_ERROR;
}
if (memcmp(in->data + in->lockedSecretHmacOffset, hmacBuffer, 0x20) != 0)
{
return CCR_NFC_INVALID_LOCKED_SECRET;
}
// Only version 0 tags have an encrypted locked secret area
if (in->version == 0)
{
uint32 hmacLen = 0x20;
if (!HMAC(EVP_sha256(), sUnfixedInfosInternalHmacKey, sizeof(sUnfixedInfosInternalHmacKey), out->data + in->unfixedInfosHmacOffset + 0x20, (in->dataSize - in->unfixedInfosHmacOffset) - 0x20, out->data + in->unfixedInfosHmacOffset, &hmacLen))
{
return CCR_NFC_ERROR;
}
res = CCRNFCAESCTRCrypt(sLockedSecretInternalKey, sLockedSecretInternalNonce, in->data + in->lockedSecretOffset, in->lockedSecretSize, out->data + in->lockedSecretOffset, in->lockedSecretSize);
if (res != 0)
{
return res;
}
}
else
{
uint32 hmacLen = 0x20;
if (!HMAC(EVP_sha256(), sUnfixedInfosInternalHmacKey, sizeof(sUnfixedInfosInternalHmacKey), out->data + in->unfixedInfosHmacOffset + 0x21, (in->dataSize - in->unfixedInfosHmacOffset) - 0x21, out->data + in->unfixedInfosHmacOffset, &hmacLen))
{
return CCR_NFC_ERROR;
}
}
res = CCRNFCAESCTRCrypt(sUnfixedInfosInternalKey, sUnfixedInfosInternalNonce, in->data + in->unfixedInfosOffset, in->unfixedInfosSize, out->data + in->unfixedInfosOffset, in->unfixedInfosSize);
if (res != 0)
{
return res;
}
}
return res;
}
void CCRNFCThread()
{
iosu::kernel::IOSMessage msg;
while (true)
{
IOS_ERROR error = iosu::kernel::IOS_ReceiveMessage(sCCRNFCMsgQueue, &msg, 0);
cemu_assert(!IOS_ResultIsError(error));
// Check for system exit
if (msg == 0xf00dd00d)
{
return;
}
IPCCommandBody* cmd = MEMPTR<IPCCommandBody>(msg).GetPtr();
if (cmd->cmdId == IPCCommandId::IOS_OPEN)
{
iosu::kernel::IOS_ResourceReply(cmd, IOS_ERROR_OK);
}
else if (cmd->cmdId == IPCCommandId::IOS_CLOSE)
{
iosu::kernel::IOS_ResourceReply(cmd, IOS_ERROR_OK);
}
else if (cmd->cmdId == IPCCommandId::IOS_IOCTL)
{
sint32 result;
uint32 requestId = cmd->args[0];
void* ptrIn = MEMPTR<void>(cmd->args[1]);
uint32 sizeIn = cmd->args[2];
void* ptrOut = MEMPTR<void>(cmd->args[3]);
uint32 sizeOut = cmd->args[4];
if ((result = __CCRNFCValidateCryptData(static_cast<CCRNFCCryptData*>(ptrIn), sizeIn, true)) == 0 &&
(result = __CCRNFCValidateCryptData(static_cast<CCRNFCCryptData*>(ptrOut), sizeOut, false)) == 0)
{
// Initialize outData with inData
memcpy(ptrOut, ptrIn, sizeIn);
switch (requestId)
{
case 1: // encrypt
result = __CCRNFCCryptData(static_cast<CCRNFCCryptData*>(ptrIn), static_cast<CCRNFCCryptData*>(ptrOut), false);
break;
case 2: // decrypt
result = __CCRNFCCryptData(static_cast<CCRNFCCryptData*>(ptrIn), static_cast<CCRNFCCryptData*>(ptrOut), true);
break;
default:
cemuLog_log(LogType::Force, "/dev/ccr_nfc: Unsupported IOCTL requestId");
cemu_assert_suspicious();
result = IOS_ERROR_INVALID;
break;
}
}
iosu::kernel::IOS_ResourceReply(cmd, static_cast<IOS_ERROR>(result));
}
else
{
cemuLog_log(LogType::Force, "/dev/ccr_nfc: Unsupported IPC cmdId");
cemu_assert_suspicious();
iosu::kernel::IOS_ResourceReply(cmd, IOS_ERROR_INVALID);
}
}
}
class : public ::IOSUModule
{
void SystemLaunch() override
{
sCCRNFCMsgQueue = iosu::kernel::IOS_CreateMessageQueue(sCCRNFCMsgQueueMsgBuffer.GetPtr(), sCCRNFCMsgQueueMsgBuffer.GetCount());
cemu_assert(!IOS_ResultIsError(static_cast<IOS_ERROR>(sCCRNFCMsgQueue)));
IOS_ERROR error = iosu::kernel::IOS_RegisterResourceManager("/dev/ccr_nfc", sCCRNFCMsgQueue);
cemu_assert(!IOS_ResultIsError(error));
sCCRNFCThread = std::thread(CCRNFCThread);
}
void SystemExit() override
{
if (sCCRNFCMsgQueue < 0)
{
return;
}
iosu::kernel::IOS_SendMessage(sCCRNFCMsgQueue, 0xf00dd00d, 0);
sCCRNFCThread.join();
iosu::kernel::IOS_DestroyMessageQueue(sCCRNFCMsgQueue);
sCCRNFCMsgQueue = -1;
}
} sIOSUModuleCCRNFC;
IOSUModule* GetModule()
{
return &sIOSUModuleCCRNFC;
}
}
}
| 13,376
|
C++
|
.cpp
| 351
| 33.310541
| 246
| 0.689206
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,183
|
iosu_kernel.cpp
|
cemu-project_Cemu/src/Cafe/IOSU/kernel/iosu_kernel.cpp
|
#include "iosu_kernel.h"
#include "util/helpers/fspinlock.h"
#include "util/helpers/helpers.h"
#include "Cafe/OS/libs/coreinit/coreinit_IPC.h"
#include "util/highresolutiontimer/HighResolutionTimer.h"
namespace iosu
{
namespace kernel
{
std::mutex sInternalMutex;
void IOS_DestroyResourceManagerForQueueId(IOSMsgQueueId msgQueueId);
void _IPCDestroyAllHandlesForMsgQueue(IOSMsgQueueId msgQueueId);
static void _assume_lock()
{
#ifdef CEMU_DEBUG_ASSERT
cemu_assert_debug(!sInternalMutex.try_lock());
#endif
}
/* message queue */
struct IOSMessageQueue
{
// placeholder
/* +0x00 */ uint32be ukn00;
/* +0x04 */ uint32be ukn04;
/* +0x08 */ uint32be numQueuedMessages;
/* +0x0C */ uint32be readIndex;
/* +0x10 */ uint32be msgArraySize; // 0 if queue is not allocated
/* +0x14 */ MEMPTR<betype<IOSMessage>> msgArray;
/* +0x18 */ IOSMsgQueueId queueHandle;
/* +0x1C */ uint32be ukn1C;
uint32 GetWriteIndex()
{
uint32 idx = readIndex + numQueuedMessages;
if (idx >= msgArraySize)
idx -= msgArraySize;
return idx;
}
/* HLE extension */
std::condition_variable cv_send;
std::condition_variable cv_recv;
};
std::array<IOSMessageQueue, 750> sMsgQueuePool;
IOS_ERROR _IOS_GetMessageQueue(IOSMsgQueueId queueHandle, IOSMessageQueue*& queueOut)
{
_assume_lock();
uint32 index = (queueHandle & 0xFFF);
if (index >= sMsgQueuePool.size())
return IOS_ERROR_INVALID;
IOSMessageQueue& q = sMsgQueuePool.at(index);
if(q.queueHandle != queueHandle)
return IOS_ERROR_INVALID;
queueOut = &q;
return IOS_ERROR_OK;
}
IOSMsgQueueId IOS_CreateMessageQueue(IOSMessage* messageArray, uint32 messageCount)
{
std::unique_lock _l(sInternalMutex);
cemu_assert(messageCount != 0);
auto it = std::find_if(sMsgQueuePool.begin(), sMsgQueuePool.end(), [](const IOSMessageQueue& q) { return q.msgArraySize == 0; });
if (it == sMsgQueuePool.end())
{
cemu_assert_suspicious();
return IOS_ERROR_MAXIMUM_REACHED;
}
size_t index = std::distance(sMsgQueuePool.begin(), it);
IOSMessageQueue& msgQueue = sMsgQueuePool.at(index);
// create queue handle
static uint32 sQueueHandleCounter = 0;
uint32 queueHandle = (uint32)index | ((sQueueHandleCounter<<12)&0x7FFFFFFF);
sQueueHandleCounter++;
msgQueue.queueHandle = queueHandle;
msgQueue.msgArraySize = messageCount;
msgQueue.msgArray = (betype<IOSMessage>*)messageArray;
msgQueue.numQueuedMessages = 0;
msgQueue.readIndex = 0;
return queueHandle;
}
IOS_ERROR IOS_DestroyMessageQueue(IOSMsgQueueId msgQueueId)
{
std::unique_lock _l(sInternalMutex);
IOSMessageQueue* msgQueue = nullptr;
IOS_ERROR r = _IOS_GetMessageQueue(msgQueueId, msgQueue);
if (r != IOS_ERROR_OK)
return r;
msgQueue->msgArraySize = 0;
msgQueue->queueHandle = 0;
IOS_DestroyResourceManagerForQueueId(msgQueueId);
return IOS_ERROR_OK;
}
IOS_ERROR IOS_SendMessage(IOSMsgQueueId msgQueueId, IOSMessage message, uint32 flags)
{
std::unique_lock _l(sInternalMutex);
cemu_assert_debug(flags == 0 || flags == 1);
bool dontBlock = (flags & 1) != 0;
IOSMessageQueue* msgQueue = nullptr;
IOS_ERROR r = _IOS_GetMessageQueue(msgQueueId, msgQueue);
if (r != IOS_ERROR_OK)
return r;
while (true)
{
if (msgQueue->numQueuedMessages == msgQueue->msgArraySize)
{
if (dontBlock)
return IOS_ERROR_WOULD_BLOCK;
}
else
break;
msgQueue->cv_send.wait(_l);
// after returning from wait, make sure the queue handle is unchanged
if (msgQueue->queueHandle != msgQueueId)
return IOS_ERROR_INVALID;
}
uint32 writeIndex = msgQueue->GetWriteIndex();
msgQueue->msgArray[writeIndex] = message;
msgQueue->numQueuedMessages += 1;
msgQueue->cv_recv.notify_one();
return IOS_ERROR_OK;
}
IOS_ERROR IOS_ReceiveMessage(IOSMsgQueueId msgQueueId, IOSMessage* messageOut, uint32 flags)
{
std::unique_lock _l(sInternalMutex);
cemu_assert_debug(flags == 0 || flags == 1);
bool dontBlock = (flags & 1) != 0;
IOSMessageQueue* msgQueue = nullptr;
IOS_ERROR r = _IOS_GetMessageQueue(msgQueueId, msgQueue);
if (r != IOS_ERROR_OK)
return r;
while (true)
{
if (msgQueue->numQueuedMessages == 0)
{
if (dontBlock)
return IOS_ERROR_NONE_AVAILABLE;
}
else
break;
msgQueue->cv_recv.wait(_l);
// after returning from wait, make sure the queue handle is unchanged
if (msgQueue->queueHandle != msgQueueId)
return IOS_ERROR_INVALID;
}
*messageOut = msgQueue->msgArray[(uint32)msgQueue->readIndex];
msgQueue->readIndex = msgQueue->readIndex + 1;
if (msgQueue->readIndex >= msgQueue->msgArraySize)
msgQueue->readIndex -= msgQueue->msgArraySize;
msgQueue->numQueuedMessages -= 1;
msgQueue->cv_send.notify_one();
return IOS_ERROR_OK;
}
/* timer */
std::mutex sTimerMutex;
std::condition_variable sTimerCV;
std::atomic_bool sTimerThreadStop;
struct IOSTimer
{
IOSMsgQueueId queueId;
uint32 message;
HRTick nextFire;
HRTick repeat;
bool isValid;
};
std::vector<IOSTimer> sTimers;
std::vector<IOSTimerId> sTimersFreeHandles;
auto sTimerSortComparator = [](const IOSTimerId& idA, const IOSTimerId& idB)
{
// order by nextFire, then by timerId to avoid duplicate keys
IOSTimer& timerA = sTimers[idA];
IOSTimer& timerB = sTimers[idB];
if (timerA.nextFire != timerB.nextFire)
return timerA.nextFire < timerB.nextFire;
return idA < idB;
};
std::set<IOSTimerId, decltype(sTimerSortComparator)> sTimerByFireTime;
IOSTimer& IOS_GetFreeTimer()
{
cemu_assert_debug(!sTimerMutex.try_lock()); // lock must be held by current thread
if (sTimersFreeHandles.empty())
return sTimers.emplace_back();
IOSTimerId timerId = sTimersFreeHandles.back();
sTimersFreeHandles.pop_back();
return sTimers[timerId];
}
void IOS_TimerSetNextFireTime(IOSTimer& timer, HRTick nextFire)
{
cemu_assert_debug(!sTimerMutex.try_lock()); // lock must be held by current thread
IOSTimerId timerId = &timer - sTimers.data();
auto it = sTimerByFireTime.find(timerId);
if(it != sTimerByFireTime.end())
sTimerByFireTime.erase(it);
timer.nextFire = nextFire;
if(nextFire != 0)
sTimerByFireTime.insert(timerId);
}
void IOS_StopTimerInternal(IOSTimerId timerId)
{
cemu_assert_debug(!sTimerMutex.try_lock());
IOS_TimerSetNextFireTime(sTimers[timerId], 0);
}
IOS_ERROR IOS_CreateTimer(uint32 startMicroseconds, uint32 repeatMicroseconds, uint32 queueId, uint32 message)
{
std::unique_lock _l(sTimerMutex);
IOSTimer& timer = IOS_GetFreeTimer();
timer.queueId = queueId;
timer.message = message;
HRTick nextFire = HighResolutionTimer::now().getTick() + HighResolutionTimer::microsecondsToTicks(startMicroseconds);
timer.repeat = HighResolutionTimer::microsecondsToTicks(repeatMicroseconds);
IOS_TimerSetNextFireTime(timer, nextFire);
timer.isValid = true;
sTimerCV.notify_one();
return (IOS_ERROR)(&timer - sTimers.data());
}
IOS_ERROR IOS_StopTimer(IOSTimerId timerId)
{
std::unique_lock _l(sTimerMutex);
if (timerId >= sTimers.size() || !sTimers[timerId].isValid)
return IOS_ERROR_INVALID;
IOS_StopTimerInternal(timerId);
return IOS_ERROR_OK;
}
IOS_ERROR IOS_DestroyTimer(IOSTimerId timerId)
{
std::unique_lock _l(sTimerMutex);
if (timerId >= sTimers.size() || !sTimers[timerId].isValid)
return IOS_ERROR_INVALID;
IOS_StopTimerInternal(timerId);
sTimers[timerId].isValid = false;
sTimersFreeHandles.push_back(timerId);
return IOS_ERROR_OK;
}
void IOSTimerThread()
{
SetThreadName("IOS-Timer");
std::unique_lock _l(sTimerMutex);
while (!sTimerThreadStop)
{
if (sTimerByFireTime.empty())
{
sTimerCV.wait_for(_l, std::chrono::milliseconds(10000));
continue;
}
IOSTimerId timerId = *sTimerByFireTime.begin();
IOSTimer& timer = sTimers[timerId];
HRTick now = HighResolutionTimer::now().getTick();
if (now >= timer.nextFire)
{
if(timer.repeat == 0)
IOS_TimerSetNextFireTime(timer, 0);
else
IOS_TimerSetNextFireTime(timer, timer.nextFire + timer.repeat);
IOSMsgQueueId queueId = timer.queueId;
uint32 message = timer.message;
// fire timer
_l.unlock();
IOSMessage msg;
IOS_SendMessage(queueId, message, 1);
_l.lock();
continue;
}
else
{
sTimerCV.wait_for(_l, std::chrono::microseconds(HighResolutionTimer::ticksToMicroseconds(timer.nextFire - now)));
}
}
}
/* devices and IPC */
struct IOSResourceManager
{
bool isSet{false};
std::string path;
IOSMsgQueueId msgQueueId;
};
std::array<IOSResourceManager, 512> sDeviceResources;
IOSResourceManager* _IOS_FindResourceManager(const char* devicePath)
{
_assume_lock();
std::string_view devicePathSV{ devicePath };
for (auto& it : sDeviceResources)
{
if (it.isSet && it.path == devicePathSV)
return ⁢
}
return nullptr;
}
IOSResourceManager* _IOS_CreateNewResourceManager(const char* devicePath, IOSMsgQueueId msgQueueId)
{
_assume_lock();
std::string_view devicePathSV{ devicePath };
for (auto& it : sDeviceResources)
{
if (!it.isSet)
{
it.isSet = true;
it.path = devicePath;
it.msgQueueId = msgQueueId;
return ⁢
}
}
return nullptr;
}
IOS_ERROR IOS_RegisterResourceManager(const char* devicePath, IOSMsgQueueId msgQueueId)
{
std::unique_lock _lock(sInternalMutex);
if (_IOS_FindResourceManager(devicePath))
{
cemu_assert_suspicious();
return IOS_ERROR_INVALID; // correct error code?
}
// verify if queue is valid
IOSMessageQueue* msgQueue;
IOS_ERROR r = _IOS_GetMessageQueue(msgQueueId, msgQueue);
if (r != IOS_ERROR_OK)
return r;
// create resource manager
IOSResourceManager* resourceMgr = _IOS_CreateNewResourceManager(devicePath, msgQueueId);
if (!resourceMgr)
return IOS_ERROR_MAXIMUM_REACHED;
return IOS_ERROR_OK;
}
void IOS_DestroyResourceManagerForQueueId(IOSMsgQueueId msgQueueId)
{
_assume_lock();
// destroy all IPC handles associated with this queue
_IPCDestroyAllHandlesForMsgQueue(msgQueueId);
// destroy device resource manager
for (auto& it : sDeviceResources)
{
if (it.isSet && it.msgQueueId == msgQueueId)
{
it.isSet = false;
it.path.clear();
it.msgQueueId = 0;
}
}
}
IOS_ERROR IOS_DeviceAssociateId(const char* devicePath, uint32 id)
{
// not yet implemented
return IOS_ERROR_OK;
}
/* IPC */
struct IOSDispatchableCommand
{
// stores a copy of incoming IPC requests with some extra information required for replies
IPCCommandBody body; // our dispatchable copy
IPCIoctlVector vecCopy[8]; // our copy of the Ioctlv vector array
IPCCommandBody* originalBody; // the original command that was sent to us
uint32 ppcCoreIndex;
IOSDevHandle replyHandle; // handle for outgoing replies
bool isAllocated{false};
};
SysAllocator<IOSDispatchableCommand, 96> sIPCDispatchableCommandPool;
std::queue<IOSDispatchableCommand*> sIPCFreeDispatchableCommands;
FSpinlock sIPCDispatchableCommandPoolLock;
void _IPCInitDispatchablePool()
{
sIPCDispatchableCommandPoolLock.lock();
while (!sIPCFreeDispatchableCommands.empty())
sIPCFreeDispatchableCommands.pop();
for (size_t i = 0; i < sIPCDispatchableCommandPool.GetCount(); i++)
sIPCFreeDispatchableCommands.push(sIPCDispatchableCommandPool.GetPtr()+i);
sIPCDispatchableCommandPoolLock.unlock();
}
IOSDispatchableCommand* _IPCAllocateDispatchableCommand()
{
sIPCDispatchableCommandPoolLock.lock();
if (sIPCFreeDispatchableCommands.empty())
{
cemuLog_log(LogType::Force, "IOS: Exhausted pool of dispatchable commands");
sIPCDispatchableCommandPoolLock.unlock();
return nullptr;
}
IOSDispatchableCommand* cmd = sIPCFreeDispatchableCommands.front();
sIPCFreeDispatchableCommands.pop();
cemu_assert_debug(!cmd->isAllocated);
cmd->isAllocated = true;
sIPCDispatchableCommandPoolLock.unlock();
return cmd;
}
void _IPCReleaseDispatchableCommand(IOSDispatchableCommand* cmd)
{
sIPCDispatchableCommandPoolLock.lock();
cemu_assert_debug(cmd->isAllocated);
cmd->isAllocated = false;
sIPCFreeDispatchableCommands.push(cmd);
sIPCDispatchableCommandPoolLock.unlock();
}
static constexpr size_t MAX_NUM_ACTIVE_DEV_HANDLES = 96; // per process
struct IPCActiveDeviceHandle
{
bool isSet{false};
uint32 handleCheckValue{0};
std::string path;
IOSMsgQueueId msgQueueId;
// dispatch target handle (retrieved via IOS_OPEN command to dispatch target)
bool hasDispatchTargetHandle{false};
IOSDevHandle dispatchTargetHandle;
};
IPCActiveDeviceHandle sActiveDeviceHandles[MAX_NUM_ACTIVE_DEV_HANDLES];
IOS_ERROR _IPCCreateResourceHandle(const char* devicePath, IOSDevHandle& handleOut)
{
std::unique_lock _lock(sInternalMutex);
static uint32 sHandleCreationCounter = 1;
// find resource manager for device
IOSResourceManager* resMgr = _IOS_FindResourceManager(devicePath);
if (!resMgr)
{
cemuLog_log(LogType::Force, "IOSU-Kernel: IOS_Open() could not open {}", devicePath);
return IOS_ERROR_INVALID;
}
IOSMsgQueueId msgQueueId = resMgr->msgQueueId;
_lock.unlock();
// create new handle
sint32 deviceHandleIndex = -1;
for (size_t i = 0; i < MAX_NUM_ACTIVE_DEV_HANDLES; i++)
{
if (!sActiveDeviceHandles[i].isSet)
{
deviceHandleIndex = (sint32)i;
break;
}
}
cemu_assert_debug(deviceHandleIndex >= 0);
if (deviceHandleIndex < 0)
return IOS_ERROR_MAXIMUM_REACHED;
// calc handle
uint32 devHandle = deviceHandleIndex | ((sHandleCreationCounter << 12) & 0x7FFFFFFF);
sHandleCreationCounter++;
// init handle instance
sActiveDeviceHandles[deviceHandleIndex].isSet = true;
sActiveDeviceHandles[deviceHandleIndex].handleCheckValue = devHandle;
sActiveDeviceHandles[deviceHandleIndex].path = devicePath;
sActiveDeviceHandles[deviceHandleIndex].msgQueueId = msgQueueId;
sActiveDeviceHandles[deviceHandleIndex].hasDispatchTargetHandle = false;
handleOut = devHandle;
return IOS_ERROR_OK;
}
IOS_ERROR _IPCDestroyResourceHandle(IOSDevHandle devHandle)
{
std::unique_lock _lock(sInternalMutex);
uint32 index = devHandle & 0xFFF;
cemu_assert(index < MAX_NUM_ACTIVE_DEV_HANDLES);
if (!sActiveDeviceHandles[index].isSet)
{
cemuLog_log(LogType::Force, "_IPCDispatchToResourceManager(): Resource manager destroyed before all IPC commands were processed");
return IOS_ERROR_INVALID;
}
if (devHandle != sActiveDeviceHandles[index].handleCheckValue)
{
cemuLog_log(LogType::Force, "_IPCDispatchToResourceManager(): Mismatching handle");
return IOS_ERROR_INVALID;
}
sActiveDeviceHandles[index].isSet = false;
sActiveDeviceHandles[index].handleCheckValue = 0;
sActiveDeviceHandles[index].hasDispatchTargetHandle = false;
_lock.unlock();
return IOS_ERROR_OK;
}
void _IPCDestroyAllHandlesForMsgQueue(IOSMsgQueueId msgQueueId)
{
_assume_lock();
for (auto& it : sActiveDeviceHandles)
{
if (it.isSet && it.msgQueueId == msgQueueId)
{
it.isSet = false;
it.path.clear();
it.handleCheckValue = 0;
it.hasDispatchTargetHandle = false;
it.msgQueueId = 0;
}
}
}
IOS_ERROR _IPCAssignDispatchTargetHandle(IOSDevHandle devHandle, IOSDevHandle internalHandle)
{
std::unique_lock _lock(sInternalMutex);
uint32 index = devHandle & 0xFFF;
cemu_assert(index < MAX_NUM_ACTIVE_DEV_HANDLES);
if (!sActiveDeviceHandles[index].isSet)
{
cemuLog_log(LogType::Force, "_IPCDispatchToResourceManager(): Resource manager destroyed before all IPC commands were processed");
return IOS_ERROR_INVALID;
}
if (devHandle != sActiveDeviceHandles[index].handleCheckValue)
{
cemuLog_log(LogType::Force, "_IPCDispatchToResourceManager(): Mismatching handle");
return IOS_ERROR_INVALID;
}
cemu_assert_debug(!sActiveDeviceHandles[index].hasDispatchTargetHandle);
sActiveDeviceHandles[index].hasDispatchTargetHandle = true;
sActiveDeviceHandles[index].dispatchTargetHandle = internalHandle;
_lock.unlock();
return IOS_ERROR_OK;
}
IOS_ERROR _IPCDispatchToResourceManager(IOSDevHandle devHandle, IOSDispatchableCommand* dispatchCmd)
{
std::unique_lock _lock(sInternalMutex);
uint32 index = devHandle & 0xFFF;
cemu_assert(index < MAX_NUM_ACTIVE_DEV_HANDLES);
if (!sActiveDeviceHandles[index].isSet)
{
cemuLog_log(LogType::Force, "_IPCDispatchToResourceManager(): Resource manager destroyed before all IPC commands were processed");
return IOS_ERROR_INVALID;
}
if (devHandle != sActiveDeviceHandles[index].handleCheckValue)
{
cemuLog_log(LogType::Force, "_IPCDispatchToResourceManager(): Mismatching handle");
return IOS_ERROR_INVALID;
}
IOSMsgQueueId msgQueueId = sActiveDeviceHandles[index].msgQueueId;
if (dispatchCmd->body.cmdId == IPCCommandId::IOS_OPEN)
{
cemu_assert(!sActiveDeviceHandles[index].hasDispatchTargetHandle);
dispatchCmd->body.devHandle = 0;
}
else
{
cemu_assert(sActiveDeviceHandles[index].hasDispatchTargetHandle);
dispatchCmd->body.devHandle = sActiveDeviceHandles[index].dispatchTargetHandle;
}
_lock.unlock();
MEMPTR<IOSDispatchableCommand> msgVal{ dispatchCmd };
IOS_ERROR r = IOS_SendMessage(msgQueueId, msgVal.GetMPTR(), 1);
if(r != IOS_ERROR_OK)
cemuLog_log(LogType::Force, "_IPCDispatchToResourceManager(): SendMessage returned {}", (sint32)r);
return r;
}
std::mutex sMtxReply[3];
void _IPCReplyAndRelease(IOSDispatchableCommand* dispatchCmd, uint32 result)
{
cemu_assert(dispatchCmd->ppcCoreIndex < 3);
std::unique_lock _l(sMtxReply[(uint32)dispatchCmd->ppcCoreIndex]);
cemu_assert(dispatchCmd >= sIPCDispatchableCommandPool.GetPtr() && dispatchCmd < sIPCDispatchableCommandPool.GetPtr() + sIPCDispatchableCommandPool.GetCount());
dispatchCmd->originalBody->result = result;
// submit to COS
IPCCommandBody* responseArray[1];
responseArray[0] = dispatchCmd->originalBody;
coreinit::IPCDriver_NotifyResponses(dispatchCmd->ppcCoreIndex, responseArray, 1);
_IPCReleaseDispatchableCommand(dispatchCmd);
}
IOS_ERROR _IPCHandlerIn_IOS_Open(IOSDispatchableCommand* dispatchCmd)
{
IPCCommandBody& cmd = dispatchCmd->body;
const char* name = MEMPTR<const char>(cmd.args[0]).GetPtr();
uint32 nameLenPlusOne = cmd.args[1];
cemu_assert(nameLenPlusOne > 0);
uint32 flags = cmd.args[2];
cemu_assert_debug(flags == 0);
std::string devicePath{ name, nameLenPlusOne - 1 };
IOSDevHandle handle;
IOS_ERROR r = _IPCCreateResourceHandle(devicePath.c_str(), handle);
if (r != IOS_ERROR_OK)
return r;
dispatchCmd->replyHandle = handle;
dispatchCmd->body.devHandle = 0;
r = _IPCDispatchToResourceManager(handle, dispatchCmd);
return r;
}
IOS_ERROR _IPCHandlerIn_IOS_Close(IOSDispatchableCommand* dispatchCmd)
{
IPCCommandBody& cmd = dispatchCmd->body;
IOS_ERROR r = _IPCDispatchToResourceManager(dispatchCmd->body.devHandle, dispatchCmd);
return r;
}
IOS_ERROR _IPCHandlerIn_IOS_Ioctl(IOSDispatchableCommand* dispatchCmd)
{
IPCCommandBody& cmd = dispatchCmd->body;
IOS_ERROR r = _IPCDispatchToResourceManager(dispatchCmd->body.devHandle, dispatchCmd);
return r;
}
IOS_ERROR _IPCHandlerIn_IOS_Ioctlv(IOSDispatchableCommand* dispatchCmd)
{
IPCCommandBody& cmd = dispatchCmd->body;
uint32 requestId = dispatchCmd->body.args[0];
uint32 numIn = dispatchCmd->body.args[1];
uint32 numOut = dispatchCmd->body.args[2];
IPCIoctlVector* vec = MEMPTR<IPCIoctlVector>(cmd.args[3]).GetPtr();
// copy the vector array
uint32 numVec = numIn + numOut;
if (numVec <= 8)
{
std::copy(vec, vec + numVec, dispatchCmd->vecCopy);
dispatchCmd->body.args[3] = MEMPTR<IPCIoctlVector>(vec).GetMPTR();
}
else
{
// reuse the original vector pointer
cemuLog_log(LogType::Force, "Info: Ioctlv command with more than 8 vectors");
}
return _IPCDispatchToResourceManager(dispatchCmd->body.devHandle, dispatchCmd);
}
// normally COS kernel handles this, but currently we skip the IPC getting proxied through it
IOS_ERROR _IPCHandlerIn_TranslateVectorAddresses(IOSDispatchableCommand* dispatchCmd)
{
uint32 numIn = dispatchCmd->body.args[1];
uint32 numOut = dispatchCmd->body.args[2];
IPCIoctlVector* vec = MEMPTR<IPCIoctlVector>(dispatchCmd->body.args[3]).GetPtr();
for (uint32 i = 0; i < numIn + numOut; i++)
{
if (vec[i].baseVirt == nullptr && vec[i].size != 0)
return IOS_ERROR_INVALID;
// todo - check for valid pointer range
vec[i].basePhys = vec[i].baseVirt;
}
return IOS_ERROR_OK;
}
// called by COS directly
void IPCSubmitFromCOS(uint32 ppcCoreIndex, IPCCommandBody* cmd)
{
// create a copy of the cmd
IOSDispatchableCommand* dispatchCmd = _IPCAllocateDispatchableCommand();
dispatchCmd->body = *cmd;
dispatchCmd->originalBody = cmd;
dispatchCmd->ppcCoreIndex = ppcCoreIndex;
dispatchCmd->replyHandle = cmd->devHandle;
// forward command to device
IOS_ERROR r = IOS_ERROR_INVALID;
switch ((IPCCommandId)cmd->cmdId)
{
case IPCCommandId::IOS_OPEN:
dispatchCmd->replyHandle = 0;
r = _IPCHandlerIn_IOS_Open(dispatchCmd);
break;
case IPCCommandId::IOS_CLOSE:
r = _IPCHandlerIn_IOS_Close(dispatchCmd);
break;
case IPCCommandId::IOS_IOCTL:
r = _IPCHandlerIn_IOS_Ioctl(dispatchCmd);
break;
case IPCCommandId::IOS_IOCTLV:
r = _IPCHandlerIn_TranslateVectorAddresses(dispatchCmd);
if(r < 0)
cemuLog_log(LogType::Force, "Ioctlv error");
else
r = _IPCHandlerIn_IOS_Ioctlv(dispatchCmd);
break;
default:
cemuLog_log(LogType::Force, "Invalid IPC command {}", (uint32)(IPCCommandId)cmd->cmdId);
break;
}
if (r < 0)
{
cemuLog_log(LogType::Force, "Error occurred while trying to dispatch IPC");
_IPCReplyAndRelease(dispatchCmd, r);
// in non-error case the device handler will send the result asynchronously via IOS_ResourceReply
}
}
IOS_ERROR IOS_ResourceReply(IPCCommandBody* cmd, IOS_ERROR result)
{
IOSDispatchableCommand* dispatchCmd = (IOSDispatchableCommand*)cmd;
cemu_assert(dispatchCmd >= sIPCDispatchableCommandPool.GetPtr() && dispatchCmd < sIPCDispatchableCommandPool.GetPtr() + sIPCDispatchableCommandPool.GetCount());
cemu_assert_debug(dispatchCmd->isAllocated);
dispatchCmd->originalBody->result = result;
if (dispatchCmd->originalBody->cmdId == IPCCommandId::IOS_OPEN)
{
IOSDevHandle devHandle = dispatchCmd->replyHandle;
if (IOS_ResultIsError(result))
{
cemuLog_log(LogType::Force, "IOS_ResourceReply(): Target device triggered an error on IOS_OPEN");
// dispatch target returned error, destroy our device handle again
IOS_ERROR r = _IPCDestroyResourceHandle(devHandle);
cemu_assert(r == IOS_ERROR_OK);
}
else
{
cemu_assert(_IPCAssignDispatchTargetHandle(devHandle, (IOSDevHandle)result) == IOS_ERROR_OK);
result = (IOS_ERROR)(uint32)devHandle;
}
}
else if (dispatchCmd->originalBody->cmdId == IPCCommandId::IOS_CLOSE)
{
if (IOS_ResultIsError(result))
{
cemuLog_log(LogType::Force, "IOS_ResourceReply(): Target device triggered an error on IOS_CLOSE");
}
// reply, then destroy handle
IOSDevHandle devHandle = dispatchCmd->replyHandle;
_IPCReplyAndRelease(dispatchCmd, result);
IOS_ERROR r = _IPCDestroyResourceHandle(devHandle);
cemu_assert_debug(r == IOS_ERROR::IOS_ERROR_OK);
return IOS_ERROR_OK;
}
_IPCReplyAndRelease(dispatchCmd, result);
return IOS_ERROR_OK;
}
class : public ::IOSUModule
{
void SystemLaunch() override
{
_IPCInitDispatchablePool();
// start timer thread
sTimerThreadStop = false;
m_timerThread = std::thread(IOSTimerThread);
}
void SystemExit() override
{
// stop timer thread
sTimerThreadStop = true;
sTimerCV.notify_one();
m_timerThread.join();
// reset resources
// todo
}
std::thread m_timerThread;
}sIOSUModuleKernel;
IOSUModule* GetModule()
{
return static_cast<IOSUModule*>(&sIOSUModuleKernel);
}
}
}
| 24,515
|
C++
|
.cpp
| 710
| 30.340845
| 164
| 0.727246
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,184
|
iosu_fsa.cpp
|
cemu-project_Cemu/src/Cafe/IOSU/fsa/iosu_fsa.cpp
|
#include "fsa_types.h"
#include "iosu_fsa.h"
#include "Cafe/IOSU/kernel/iosu_kernel.h"
#include "Cafe/Filesystem/fsc.h"
#include "util/helpers/helpers.h"
#include "Cafe/OS/libs/coreinit/coreinit_FS.h" // get rid of this dependency, requires reworking some of the IPC stuff. See locations where we use coreinit::FSCmdBlockBody_t
#include "Cafe/HW/Latte/Core/LatteBufferCache.h" // also remove this dependency
#include "Cafe/HW/MMU/MMU.h"
using namespace iosu::kernel;
namespace iosu
{
namespace fsa
{
IOSMsgQueueId sFSAIoMsgQueue;
SysAllocator<iosu::kernel::IOSMessage, 352> _m_sFSAIoMsgQueueMsgBuffer;
std::thread sFSAIoThread;
struct FSAClient // IOSU's counterpart to the coreinit FSClient struct
{
std::string workingDirectory;
bool isAllocated{false};
void AllocateAndInitialize()
{
isAllocated = true;
workingDirectory = std::string("/");
}
void ReleaseAndCleanup()
{
isAllocated = false;
}
};
std::array<FSAClient, 624> sFSAClientArray;
IOS_ERROR FSAAllocateClient(sint32& indexOut)
{
for (size_t i = 0; i < sFSAClientArray.size(); i++)
{
if (sFSAClientArray[i].isAllocated)
continue;
sFSAClientArray[i].AllocateAndInitialize();
indexOut = (sint32)i;
return IOS_ERROR_OK;
}
return (IOS_ERROR)0xFFFCFFEE;
}
FSA_RESULT FSA_convertFSCtoFSAStatus(sint32 fscError)
{
if (fscError == FSC_STATUS_OK)
return FSA_RESULT::OK;
else if (fscError == FSC_STATUS_FILE_NOT_FOUND)
return FSA_RESULT::NOT_FOUND;
else if (fscError == FSC_STATUS_ALREADY_EXISTS)
return FSA_RESULT::ALREADY_EXISTS;
cemu_assert_unimplemented();
return FSA_RESULT::FATAL_ERROR;
}
std::string __FSATranslatePath(FSAClient* fsaClient, std::string_view input, bool endWithSlash = false)
{
std::string tmp;
if (input.empty())
{
tmp.assign(fsaClient->workingDirectory);
if (endWithSlash)
tmp.push_back('/');
return tmp;
}
char c = input.front();
cemu_assert_debug(c != '\\'); // how to handle backward slashes?
if (c == '/')
{
// absolute path
tmp.assign("/"); // keep the leading slash
}
else if (c == '~')
{
cemu_assert_debug(false);
input.remove_prefix(1);
tmp.assign("/");
}
else
{
// in all other cases the path is relative to the working directory
tmp.assign(fsaClient->workingDirectory);
}
// parse path
size_t idx = 0;
while (idx < input.size())
{
c = input[idx];
if (c == '/')
{
idx++;
continue; // filter leading and repeated slashes
}
if (c == '.')
{
if ((input.size() - idx) >= 3 && input[idx + 1] == '.' && input[idx + 2] == '/')
{
// "../"
while(!tmp.empty())
{
if(tmp.back() == '/')
{
tmp.pop_back();
break;
}
tmp.pop_back();
}
idx += 3;
continue;
}
else if ((input.size() - idx) == 2 && input[idx + 1] == '.')
{
// ".." at the end
while(!tmp.empty())
{
if(tmp.back() == '/')
{
tmp.pop_back();
break;
}
tmp.pop_back();
}
idx += 2;
continue;
}
else if ((input.size() - idx) >= 2 && input[idx + 1] == '/')
{
// "./"
idx += 2;
continue;
}
}
if (!tmp.empty() && tmp.back() != '/')
tmp.push_back('/');
while (idx < input.size())
{
c = input[idx];
if (c == '/')
break;
tmp.push_back(c);
idx++;
}
}
if (endWithSlash)
{
if (tmp.empty() || tmp.back() != '/')
tmp.push_back('/');
}
return tmp;
}
FSCVirtualFile* __FSAOpenNode(FSAClient* client, std::string_view path, FSC_ACCESS_FLAG accessFlags, sint32& fscStatus)
{
std::string translatedPath = __FSATranslatePath(client, path);
return fsc_open(translatedPath.c_str(), accessFlags, &fscStatus);
}
class _FSAHandleTable {
struct _FSAHandleResource
{
bool isAllocated{false};
FSCVirtualFile* fscFile;
uint16 handleCheckValue;
};
public:
FSA_RESULT AllocateHandle(FSResHandle& handleOut, FSCVirtualFile* fscFile)
{
for (size_t i = 0; i < m_handleTable.size(); i++)
{
auto& it = m_handleTable.at(i);
if (it.isAllocated)
continue;
uint16 checkValue = (uint16)m_currentCounter;
m_currentCounter++;
it.handleCheckValue = checkValue;
it.fscFile = fscFile;
it.isAllocated = true;
uint32 handleVal = ((uint32)i << 16) | (uint32)checkValue;
handleOut = (FSResHandle)handleVal;
return FSA_RESULT::OK;
}
cemuLog_log(LogType::Force, "FSA: Ran out of file handles");
return FSA_RESULT::FATAL_ERROR;
}
FSA_RESULT ReleaseHandle(FSResHandle handle)
{
uint16 index = (uint16)((uint32)handle >> 16);
uint16 checkValue = (uint16)(handle & 0xFFFF);
if (index >= m_handleTable.size())
return FSA_RESULT::INVALID_FILE_HANDLE;
auto& it = m_handleTable.at(index);
if (!it.isAllocated)
return FSA_RESULT::INVALID_FILE_HANDLE;
if (it.handleCheckValue != checkValue)
return FSA_RESULT::INVALID_FILE_HANDLE;
it.fscFile = nullptr;
it.isAllocated = false;
return FSA_RESULT::OK;
}
FSCVirtualFile* GetByHandle(FSResHandle handle)
{
uint16 index = (uint16)((uint32)handle >> 16);
uint16 checkValue = (uint16)(handle & 0xFFFF);
if (index >= m_handleTable.size())
return nullptr;
auto& it = m_handleTable.at(index);
if (!it.isAllocated)
return nullptr;
if (it.handleCheckValue != checkValue)
return nullptr;
return it.fscFile;
}
private:
uint32 m_currentCounter = 1;
std::array<_FSAHandleResource, 0x3C0> m_handleTable;
};
_FSAHandleTable sFileHandleTable;
_FSAHandleTable sDirHandleTable;
FSA_RESULT __FSAOpenFile(FSAClient* client, const char* path, const char* accessModifierStr, sint32* fileHandle)
{
*fileHandle = FS_INVALID_HANDLE_VALUE;
FSC_ACCESS_FLAG accessModifier = FSC_ACCESS_FLAG::NONE;
bool truncateFile = false; // todo: Support for this
bool isAppend = false; // todo: proper support for this (all write operations should move cursor to the end of the file?)
if (strcmp(accessModifierStr, "r") == 0 || strcmp(accessModifierStr, "rb") == 0)
accessModifier = FSC_ACCESS_FLAG::READ_PERMISSION;
else if (strcmp(accessModifierStr, "r+") == 0)
{
// the cursor will be set to the beginning of the file
// allows read and write access
accessModifier = FSC_ACCESS_FLAG::READ_PERMISSION | FSC_ACCESS_FLAG::WRITE_PERMISSION; // read, write
}
else if (strcmp(accessModifierStr, "w") == 0)
{
accessModifier = FSC_ACCESS_FLAG::READ_PERMISSION | FSC_ACCESS_FLAG::WRITE_PERMISSION | FSC_ACCESS_FLAG::FILE_ALWAYS_CREATE; // create new file & write
truncateFile = true;
}
else if (strcmp(accessModifierStr, "w+") == 0)
{
accessModifier = FSC_ACCESS_FLAG::READ_PERMISSION | FSC_ACCESS_FLAG::WRITE_PERMISSION | FSC_ACCESS_FLAG::FILE_ALWAYS_CREATE; // create new file & read & write
truncateFile = true;
}
else if (strcmp(accessModifierStr, "wb") == 0) // used in Super Meat Boy
{
// b flag is allowed has no effect
accessModifier = FSC_ACCESS_FLAG::READ_PERMISSION | FSC_ACCESS_FLAG::WRITE_PERMISSION | FSC_ACCESS_FLAG::FILE_ALWAYS_CREATE; // create new file & write
truncateFile = true;
}
else if (strcmp(accessModifierStr, "a+") == 0)
{
accessModifier = FSC_ACCESS_FLAG::READ_PERMISSION | FSC_ACCESS_FLAG::WRITE_PERMISSION | FSC_ACCESS_FLAG::FILE_ALLOW_CREATE | FSC_ACCESS_FLAG::IS_APPEND;
isAppend = true;
}
else if (strcmp(accessModifierStr, "a") == 0)
{
accessModifier = FSC_ACCESS_FLAG::WRITE_PERMISSION | FSC_ACCESS_FLAG::FILE_ALLOW_CREATE | FSC_ACCESS_FLAG::IS_APPEND;
isAppend = true;
}
else
cemu_assert_debug(false);
accessModifier |= FSC_ACCESS_FLAG::OPEN_DIR | FSC_ACCESS_FLAG::OPEN_FILE;
sint32 fscStatus;
FSCVirtualFile* fscFile = __FSAOpenNode(client, path, accessModifier, fscStatus);
if (!fscFile)
return FSA_RESULT::NOT_FOUND;
if (fscFile->fscGetType() != FSC_TYPE_FILE)
{
delete fscFile;
return FSA_RESULT::NOT_FILE;
}
if (isAppend)
fsc_setFileSeek(fscFile, fsc_getFileSize(fscFile));
FSResHandle fsFileHandle;
FSA_RESULT r = sFileHandleTable.AllocateHandle(fsFileHandle, fscFile);
if (r != FSA_RESULT::OK)
{
cemuLog_log(LogType::Force, "Exceeded maximum number of FSA file handles");
delete fscFile;
return FSA_RESULT::MAX_FILES;
}
*fileHandle = fsFileHandle;
cemuLog_log(LogType::CoreinitFile, "Open file {} (access: {} result: ok handle: 0x{})", path, accessModifierStr, (uint32)*fileHandle);
return FSA_RESULT::OK;
}
FSA_RESULT __FSAOpenDirectory(FSAClient* client, std::string_view path, sint32* dirHandle)
{
*dirHandle = FS_INVALID_HANDLE_VALUE;
sint32 fscStatus;
FSCVirtualFile* fscFile = __FSAOpenNode(client, path, FSC_ACCESS_FLAG::OPEN_DIR | FSC_ACCESS_FLAG::OPEN_FILE, fscStatus);
if (!fscFile)
return FSA_RESULT::NOT_FOUND;
if (fscFile->fscGetType() != FSC_TYPE_DIRECTORY)
{
delete fscFile;
return FSA_RESULT::NOT_DIR;
}
FSResHandle fsDirHandle;
FSA_RESULT r = sDirHandleTable.AllocateHandle(fsDirHandle, fscFile);
if (r != FSA_RESULT::OK)
{
delete fscFile;
return FSA_RESULT::MAX_DIRS;
}
*dirHandle = fsDirHandle;
cemuLog_log(LogType::CoreinitFile, "Open directory {} (result: ok handle: 0x{})", path, (uint32)*dirHandle);
return FSA_RESULT::OK;
}
FSA_RESULT __FSACloseFile(uint32 fileHandle)
{
uint8 handleType = 0;
FSCVirtualFile* fscFile = sFileHandleTable.GetByHandle(fileHandle);
if (!fscFile)
{
cemuLog_logDebug(LogType::Force, "__FSACloseFile(): Invalid handle (0x{:08x})", fileHandle);
return FSA_RESULT::INVALID_FILE_HANDLE;
}
// unregister file
sFileHandleTable.ReleaseHandle(fileHandle); // todo - use the error code of this
fsc_close(fscFile);
return FSA_RESULT::OK;
}
FSA_RESULT FSAProcessCmd_remove(FSAClient* client, FSAShimBuffer* shimBuffer)
{
std::string path = __FSATranslatePath(client, (char*)shimBuffer->request.cmdRemove.path);
sint32 fscStatus = FSC_STATUS_FILE_NOT_FOUND;
fsc_remove(path.c_str(), &fscStatus);
return FSA_convertFSCtoFSAStatus(fscStatus);
}
FSA_RESULT FSAProcessCmd_makeDir(FSAClient* client, FSAShimBuffer* shimBuffer)
{
std::string path = __FSATranslatePath(client, (char*)shimBuffer->request.cmdMakeDir.path);
sint32 fscStatus = FSC_STATUS_FILE_NOT_FOUND;
fsc_createDir(path.c_str(), &fscStatus);
return FSA_convertFSCtoFSAStatus(fscStatus);
}
FSA_RESULT FSAProcessCmd_rename(FSAClient* client, FSAShimBuffer* shimBuffer)
{
std::string srcPath = __FSATranslatePath(client, (char*)shimBuffer->request.cmdRename.srcPath);
std::string dstPath = __FSATranslatePath(client, (char*)shimBuffer->request.cmdRename.dstPath);
sint32 fscStatus = FSC_STATUS_FILE_NOT_FOUND;
fsc_rename(srcPath.c_str(), dstPath.c_str(), &fscStatus);
return FSA_convertFSCtoFSAStatus(fscStatus);
}
bool __FSA_GetStatFromFSCFile(FSCVirtualFile* fscFile, FSStat_t* fsStatOut)
{
memset(fsStatOut, 0x00, sizeof(FSStat_t));
FSFlag statFlag = FSFlag::NONE;
if (fsc_isDirectory(fscFile))
{
// note: Only quota (save) directories have the size field set. For other directories it's zero.
// Hyrule Warriors relies on the size field being zero for /vol/content/data/. Otherwise it will try to read it like a file and get stuck in an endless loop.
// Art Academy reads the size for save directories
statFlag |= FSFlag::IS_DIR;
fsStatOut->size = 0;
}
else if (fsc_isFile(fscFile))
{
fsStatOut->size = fsc_getFileSize(fscFile);
statFlag |= FSFlag::IS_FILE;
}
else
{
cemu_assert_suspicious();
}
fsStatOut->permissions = 0x777; // format matches unix (fstat) permissions?
fsStatOut->flag = statFlag;
return true;
}
FSA_RESULT __FSA_GetFileStat(FSAClient* client, const char* path, FSStat_t* fsStatOut)
{
sint32 fscStatus;
FSCVirtualFile* fscFile = __FSAOpenNode(client, path, FSC_ACCESS_FLAG::OPEN_FILE | FSC_ACCESS_FLAG::OPEN_DIR, fscStatus);
if (!fscFile)
return FSA_convertFSCtoFSAStatus(fscStatus);
__FSA_GetStatFromFSCFile(fscFile, fsStatOut);
delete fscFile;
return FSA_RESULT::OK;
}
FSA_RESULT FSAProcessCmd_queryInfo(FSAClient* client, FSAShimBuffer* shimBuffer)
{
char* path = (char*)shimBuffer->request.cmdQueryInfo.query;
uint32 queryType = shimBuffer->request.cmdQueryInfo.queryType;
// handle query
sint32 fscStatus = FSC_STATUS_OK;
if (queryType == FSA_QUERY_TYPE_STAT)
{
FSStat_t* fsStat = &shimBuffer->response.cmdQueryInfo.queryStat.stat;
FSA_RESULT fsaStatus = __FSA_GetFileStat(client, path, fsStat);
return fsaStatus;
}
else if (queryType == FSA_QUERY_TYPE_FREESPACE)
{
sint32 fscStatus;
FSCVirtualFile* fscFile = __FSAOpenNode(client, path, FSC_ACCESS_FLAG::OPEN_FILE | FSC_ACCESS_FLAG::OPEN_DIR, fscStatus);
if (!fscFile)
return FSA_convertFSCtoFSAStatus(fscStatus);
betype<uint64>* fsStatSize = &shimBuffer->response.cmdQueryInfo.queryFreeSpace.freespace;
*fsStatSize = 30ull * 1024 * 1024 * 1024; // placeholder value. How is this determined?
delete fscFile;
return FSA_RESULT::OK;
}
else if (queryType == FSA_QUERY_TYPE_DEVICE_INFO)
{
FSADeviceInfo_t* deviceInfo = &shimBuffer->response.cmdQueryInfo.queryDeviceInfo.info;
// always report hardcoded values for now.
deviceInfo->deviceSectorSize = 512;
deviceInfo->deviceSizeInSectors = (32ull * 1024 * 1024 * 1024) / deviceInfo->deviceSectorSize;
cemu_assert_suspicious();
return FSA_RESULT::OK;
}
else
cemu_assert_unimplemented();
return FSA_convertFSCtoFSAStatus(fscStatus);
}
FSA_RESULT FSAProcessCmd_getStatFile(FSAClient* client, FSAShimBuffer* shimBuffer)
{
FSFileHandle2 fileHandle = shimBuffer->request.cmdGetStatFile.fileHandle;
FSStat_t* statOut = &shimBuffer->response.cmdStatFile.statOut;
FSCVirtualFile* fscFile = sFileHandleTable.GetByHandle(fileHandle);
if (!fscFile)
return FSA_RESULT::NOT_FOUND;
cemu_assert_debug(fsc_isFile(fscFile));
__FSA_GetStatFromFSCFile(fscFile, statOut);
return FSA_RESULT::OK;
}
FSA_RESULT FSAProcessCmd_read(FSAClient* client, FSAShimBuffer* shimBuffer, MEMPTR<void> destPtr, uint32be transferSize)
{
uint32 transferElementSize = shimBuffer->request.cmdReadFile.size;
uint32 filePos = shimBuffer->request.cmdReadFile.filePos;
uint32 fileHandle = shimBuffer->request.cmdReadFile.fileHandle;
uint32 flags = shimBuffer->request.cmdReadFile.flag;
FSCVirtualFile* fscFile = sFileHandleTable.GetByHandle(fileHandle);
if (!fscFile)
return FSA_RESULT::INVALID_FILE_HANDLE;
uint32 bytesToRead = transferSize;
// update file position if flag is set
if ((flags & FSA_CMD_FLAG_SET_POS) != 0)
fsc_setFileSeek(fscFile, filePos);
// todo: File permissions
uint32 bytesSuccessfullyRead = fsc_readFile(fscFile, destPtr, bytesToRead);
if (transferElementSize == 0)
return FSA_RESULT::OK;
LatteBufferCache_notifyDCFlush(destPtr.GetMPTR(), bytesToRead);
return (FSA_RESULT)(bytesSuccessfullyRead / transferElementSize); // return number of elements read
}
FSA_RESULT FSAProcessCmd_write(FSAClient* client, FSAShimBuffer* shimBuffer, MEMPTR<void> destPtr, uint32be transferSize)
{
uint32 transferElementSize = shimBuffer->request.cmdWriteFile.size;
uint32 filePos = shimBuffer->request.cmdWriteFile.filePos;
uint32 fileHandle = shimBuffer->request.cmdWriteFile.fileHandle;
uint32 flags = shimBuffer->request.cmdWriteFile.flag;
FSCVirtualFile* fscFile = sFileHandleTable.GetByHandle(fileHandle);
if (!fscFile)
return FSA_RESULT::INVALID_FILE_HANDLE;
cemu_assert_debug((transferSize % transferElementSize) == 0);
uint32 bytesToWrite = transferSize;
// check for write permission (should this happen before or after setting file position?)
if (!fsc_isWritable(fscFile))
{
cemu_assert_debug(false);
return FSA_RESULT::PERMISSION_ERROR;
}
// update file position if flag is set
if ((flags & FSA_CMD_FLAG_SET_POS) != 0)
fsc_setFileSeek(fscFile, filePos);
uint32 bytesSuccessfullyWritten = fsc_writeFile(fscFile, destPtr, bytesToWrite);
debug_printf("FSAProcessCmd_write(): Writing 0x%08x bytes (bytes actually written: 0x%08x)\n", bytesToWrite, bytesSuccessfullyWritten);
return (FSA_RESULT)(bytesSuccessfullyWritten / transferElementSize); // return number of elements read
}
FSA_RESULT FSAProcessCmd_setPos(FSAClient* client, FSAShimBuffer* shimBuffer)
{
uint32 fileHandle = shimBuffer->request.cmdSetPosFile.fileHandle;
uint32 filePos = shimBuffer->request.cmdSetPosFile.filePos;
FSCVirtualFile* fscFile = sFileHandleTable.GetByHandle(fileHandle);
if (!fscFile)
return FSA_RESULT::INVALID_FILE_HANDLE;
fsc_setFileSeek(fscFile, filePos);
return FSA_RESULT::OK;
}
FSA_RESULT FSAProcessCmd_getPos(FSAClient* client, FSAShimBuffer* shimBuffer)
{
uint32 fileHandle = shimBuffer->request.cmdGetPosFile.fileHandle;
FSCVirtualFile* fscFile = sFileHandleTable.GetByHandle(fileHandle);
if (!fscFile)
return FSA_RESULT::INVALID_FILE_HANDLE;
uint32 filePos = fsc_getFileSeek(fscFile);
shimBuffer->response.cmdGetPosFile.filePos = filePos;
return FSA_RESULT::OK;
}
FSA_RESULT FSAProcessCmd_openFile(FSAClient* client, FSAShimBuffer* shimBuffer)
{
sint32 fileHandle = 0;
FSA_RESULT fsaResult = __FSAOpenFile(client, (char*)shimBuffer->request.cmdOpenFile.path, (char*)shimBuffer->request.cmdOpenFile.mode, &fileHandle);
shimBuffer->response.cmdOpenFile.fileHandleOutput = fileHandle;
return fsaResult;
}
FSA_RESULT FSAProcessCmd_closeFile(FSAClient* client, FSAShimBuffer* shimBuffer)
{
return __FSACloseFile(shimBuffer->request.cmdCloseFile.fileHandle);
}
FSA_RESULT FSAProcessCmd_openDir(FSAClient* client, FSAShimBuffer* shimBuffer)
{
sint32 dirHandle = 0;
FSA_RESULT fsaResult = __FSAOpenDirectory(client, (const char*)shimBuffer->request.cmdOpenFile.path, &dirHandle);
shimBuffer->response.cmdOpenDir.dirHandleOutput = dirHandle;
return fsaResult;
}
FSA_RESULT FSAProcessCmd_readDir(FSAClient* client, FSAShimBuffer* shimBuffer)
{
FSCVirtualFile* fscFile = sDirHandleTable.GetByHandle((sint32)shimBuffer->request.cmdReadDir.dirHandle);
if (!fscFile)
return FSA_RESULT::INVALID_DIR_HANDLE;
FSDirEntry_t* dirEntryOut = &shimBuffer->response.cmdReadDir.dirEntry;
FSCDirEntry fscDirEntry;
if (fsc_nextDir(fscFile, &fscDirEntry) == false)
return FSA_RESULT::END_OF_DIRECTORY;
strcpy(dirEntryOut->name, fscDirEntry.path);
FSFlag statFlag = FSFlag::NONE;
dirEntryOut->stat.size = 0;
if (fscDirEntry.isDirectory)
{
statFlag |= FSFlag::IS_DIR;
}
else if (fscDirEntry.isFile)
{
statFlag |= FSFlag::IS_FILE;
dirEntryOut->stat.size = fscDirEntry.fileSize;
}
dirEntryOut->stat.flag = statFlag;
dirEntryOut->stat.permissions = 0x777;
return FSA_RESULT::OK;
}
FSA_RESULT FSAProcessCmd_closeDir(FSAClient* client, FSAShimBuffer* shimBuffer)
{
FSCVirtualFile* fscFile = sDirHandleTable.GetByHandle((sint32)shimBuffer->request.cmdReadDir.dirHandle);
if (!fscFile)
{
cemuLog_logDebug(LogType::Force, "CloseDir: Invalid handle (0x{:08x})", (sint32)shimBuffer->request.cmdReadDir.dirHandle);
return FSA_RESULT::INVALID_DIR_HANDLE;
}
sDirHandleTable.ReleaseHandle(shimBuffer->request.cmdReadDir.dirHandle);
fsc_close(fscFile);
return FSA_RESULT::OK;
}
FSA_RESULT FSAProcessCmd_flushQuota(FSAClient* client, FSAShimBuffer* shimBuffer)
{
return FSA_RESULT::OK;
}
FSA_RESULT FSAProcessCmd_rewindDir(FSAClient* client, FSAShimBuffer* shimBuffer)
{
FSCVirtualFile* fscFile = sDirHandleTable.GetByHandle((sint32)shimBuffer->request.cmdRewindDir.dirHandle);
if (!fscFile)
{
cemuLog_logDebug(LogType::Force, "RewindDir: Invalid handle (0x{:08x})", (sint32)shimBuffer->request.cmdRewindDir.dirHandle);
return FSA_RESULT::INVALID_DIR_HANDLE;
}
if (!fscFile->fscRewindDir())
return FSA_RESULT::FATAL_ERROR;
return FSA_RESULT::OK;
}
FSA_RESULT FSAProcessCmd_flushFile(FSAClient* client, FSAShimBuffer* shimBuffer)
{
return FSA_RESULT::OK;
}
FSA_RESULT FSAProcessCmd_appendFile(FSAClient* client, FSAShimBuffer* shimBuffer)
{
FSCVirtualFile* fscFile = sFileHandleTable.GetByHandle(shimBuffer->request.cmdAppendFile.fileHandle);
if (!fscFile)
return FSA_RESULT::INVALID_FILE_HANDLE;
#ifdef CEMU_DEBUG_ASSERT
cemuLog_log(LogType::Force, "FSAProcessCmd_appendFile(): size 0x{:08x} count 0x{:08x} (todo)\n", shimBuffer->request.cmdAppendFile.size, shimBuffer->request.cmdAppendFile.count);
#endif
return (FSA_RESULT)(shimBuffer->request.cmdAppendFile.count.value());
}
FSA_RESULT FSAProcessCmd_truncateFile(FSAClient* client, FSAShimBuffer* shimBuffer)
{
FSFileHandle2 fileHandle = shimBuffer->request.cmdTruncateFile.fileHandle;
FSCVirtualFile* fscFile = sFileHandleTable.GetByHandle(fileHandle);
if (!fscFile)
return FSA_RESULT::INVALID_FILE_HANDLE;
fsc_setFileLength(fscFile, fsc_getFileSeek(fscFile));
return FSA_RESULT::OK;
}
FSA_RESULT FSAProcessCmd_isEof(FSAClient* client, FSAShimBuffer* shimBuffer)
{
uint32 fileHandle = shimBuffer->request.cmdIsEof.fileHandle;
FSCVirtualFile* fscFile = sFileHandleTable.GetByHandle(fileHandle);
if (!fscFile)
return FSA_RESULT::INVALID_FILE_HANDLE;
uint32 filePos = fsc_getFileSeek(fscFile);
uint32 fileSize = fsc_getFileSize(fscFile);
if (filePos >= fileSize)
return FSA_RESULT::END_OF_FILE;
return FSA_RESULT::OK;
}
FSA_RESULT FSAProcessCmd_getCwd(FSAClient* client, FSAShimBuffer* shimBuffer)
{
char* pathOutput = shimBuffer->response.cmdGetCWD.path;
sint32 pathOutputMaxLen = sizeof(shimBuffer->response.cmdGetCWD.path);
cemu_assert(pathOutputMaxLen > 0);
sint32 fscStatus = FSC_STATUS_OK;
strncpy(pathOutput, client->workingDirectory.data(), std::min(client->workingDirectory.size() + 1, (size_t)pathOutputMaxLen));
pathOutput[pathOutputMaxLen - 1] = '\0';
return FSA_convertFSCtoFSAStatus(fscStatus);
}
FSA_RESULT FSAProcessCmd_changeDir(FSAClient* client, FSAShimBuffer* shimBuffer)
{
const char* path = (const char*)shimBuffer->request.cmdChangeDir.path;
shimBuffer->request.cmdChangeDir.path[sizeof(shimBuffer->request.cmdChangeDir.path) - 1] = '\0';
sint32 fscStatus = FSC_STATUS_OK;
client->workingDirectory.assign(__FSATranslatePath(client, path, true));
return FSA_convertFSCtoFSAStatus(fscStatus);
}
void FSAHandleCommandIoctlv(FSAClient* client, IPCCommandBody* cmd, FSA_CMD_OPERATION_TYPE operationId, uint32 numIn, uint32 numOut, IPCIoctlVector* vec)
{
FSA_RESULT fsaResult = FSA_RESULT::FATAL_ERROR;
switch (operationId)
{
case FSA_CMD_OPERATION_TYPE::READ:
{
fsaResult = FSAProcessCmd_read(client, (FSAShimBuffer*)vec[0].basePhys.GetPtr(), vec[1].basePhys, vec[1].size);
break;
}
case FSA_CMD_OPERATION_TYPE::WRITE:
{
fsaResult = FSAProcessCmd_write(client, (FSAShimBuffer*)vec[0].basePhys.GetPtr(), vec[1].basePhys, vec[1].size);
break;
}
case FSA_CMD_OPERATION_TYPE::CHANGEDIR:
case FSA_CMD_OPERATION_TYPE::GETCWD:
case FSA_CMD_OPERATION_TYPE::MAKEDIR:
case FSA_CMD_OPERATION_TYPE::RENAME:
case FSA_CMD_OPERATION_TYPE::OPENDIR:
case FSA_CMD_OPERATION_TYPE::READDIR:
case FSA_CMD_OPERATION_TYPE::CLOSEDIR:
case FSA_CMD_OPERATION_TYPE::OPENFILE:
case FSA_CMD_OPERATION_TYPE::REMOVE:
case FSA_CMD_OPERATION_TYPE::GETPOS:
case FSA_CMD_OPERATION_TYPE::SETPOS:
case FSA_CMD_OPERATION_TYPE::ISEOF:
case FSA_CMD_OPERATION_TYPE::GETSTATFILE:
case FSA_CMD_OPERATION_TYPE::CLOSEFILE:
case FSA_CMD_OPERATION_TYPE::QUERYINFO:
case FSA_CMD_OPERATION_TYPE::APPENDFILE:
case FSA_CMD_OPERATION_TYPE::TRUNCATEFILE:
case FSA_CMD_OPERATION_TYPE::FLUSHQUOTA:
{
// These are IOCTL and no IOCTLV
cemu_assert_error();
break;
}
default:
{
cemu_assert_unimplemented();
break;
}
}
IOS_ResourceReply(cmd, (IOS_ERROR)fsaResult);
}
void FSAHandleCommandIoctl(FSAClient* client, IPCCommandBody* cmd, FSA_CMD_OPERATION_TYPE operationId, void* ptrIn, void* ptrOut)
{
FSAShimBuffer* shimBuffer = (FSAShimBuffer*)ptrIn;
FSA_RESULT fsaResult = FSA_RESULT::FATAL_ERROR;
switch (operationId)
{
case FSA_CMD_OPERATION_TYPE::REMOVE:
{
fsaResult = FSAProcessCmd_remove(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::CHANGEDIR:
{
fsaResult = FSAProcessCmd_changeDir(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::GETCWD:
{
fsaResult = FSAProcessCmd_getCwd(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::MAKEDIR:
{
fsaResult = FSAProcessCmd_makeDir(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::RENAME:
{
fsaResult = FSAProcessCmd_rename(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::OPENDIR:
{
fsaResult = FSAProcessCmd_openDir(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::READDIR:
{
fsaResult = FSAProcessCmd_readDir(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::CLOSEDIR:
{
fsaResult = FSAProcessCmd_closeDir(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::OPENFILE:
{
fsaResult = FSAProcessCmd_openFile(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::GETPOS:
{
fsaResult = FSAProcessCmd_getPos(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::SETPOS:
{
fsaResult = FSAProcessCmd_setPos(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::ISEOF:
{
fsaResult = FSAProcessCmd_isEof(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::GETSTATFILE:
{
fsaResult = FSAProcessCmd_getStatFile(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::CLOSEFILE:
{
fsaResult = FSAProcessCmd_closeFile(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::QUERYINFO:
{
fsaResult = FSAProcessCmd_queryInfo(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::APPENDFILE:
{
fsaResult = FSAProcessCmd_appendFile(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::TRUNCATEFILE:
{
fsaResult = FSAProcessCmd_truncateFile(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::FLUSHQUOTA:
{
fsaResult = FSAProcessCmd_flushQuota(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::REWINDDIR:
{
fsaResult = FSAProcessCmd_rewindDir(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::FLUSHFILE:
{
fsaResult = FSAProcessCmd_flushFile(client, shimBuffer);
break;
}
case FSA_CMD_OPERATION_TYPE::READ:
case FSA_CMD_OPERATION_TYPE::WRITE:
{
// These commands are IOCTLVs not IOCTL
cemu_assert_error();
}
}
IOS_ResourceReply(cmd, (IOS_ERROR)fsaResult);
}
void FSAIoThread()
{
SetThreadName("IOSU-FSA");
IOSMessage msg;
while (true)
{
IOS_ERROR r = IOS_ReceiveMessage(sFSAIoMsgQueue, &msg, 0);
cemu_assert(!IOS_ResultIsError(r));
if (msg == 0)
return; // shutdown signaled
IPCCommandBody* cmd = MEMPTR<IPCCommandBody>(msg).GetPtr();
uint32 clientHandle = (uint32)cmd->devHandle;
if (cmd->cmdId == IPCCommandId::IOS_OPEN)
{
sint32 clientIndex = 0;
r = FSAAllocateClient(clientIndex);
if (r != IOS_ERROR_OK)
{
IOS_ResourceReply(cmd, r);
continue;
}
IOS_ResourceReply(cmd, (IOS_ERROR)clientIndex);
continue;
}
else if (cmd->cmdId == IPCCommandId::IOS_CLOSE)
{
cemu_assert(clientHandle < sFSAClientArray.size());
sFSAClientArray[clientHandle].ReleaseAndCleanup();
IOS_ResourceReply(cmd, IOS_ERROR_OK);
continue;
}
else if (cmd->cmdId == IPCCommandId::IOS_IOCTL)
{
cemu_assert(clientHandle < sFSAClientArray.size());
cemu_assert(sFSAClientArray[clientHandle].isAllocated);
FSAHandleCommandIoctl(sFSAClientArray.data() + clientHandle, cmd, (FSA_CMD_OPERATION_TYPE)cmd->args[0].value(), MEMPTR<void>(cmd->args[1]), MEMPTR<void>(cmd->args[3]));
}
else if (cmd->cmdId == IPCCommandId::IOS_IOCTLV)
{
cemu_assert(clientHandle < sFSAClientArray.size());
cemu_assert(sFSAClientArray[clientHandle].isAllocated);
FSA_CMD_OPERATION_TYPE requestId = (FSA_CMD_OPERATION_TYPE)cmd->args[0].value();
uint32 numIn = cmd->args[1];
uint32 numOut = cmd->args[2];
IPCIoctlVector* vec = MEMPTR<IPCIoctlVector>{cmd->args[3]}.GetPtr();
FSAHandleCommandIoctlv(sFSAClientArray.data() + clientHandle, cmd, requestId, numIn, numOut, vec);
}
else
{
cemuLog_log(LogType::Force, "/dev/fsa: Unsupported IPC cmdId");
cemu_assert_suspicious();
IOS_ResourceReply(cmd, IOS_ERROR_INVALID);
}
}
}
void Initialize()
{
for (auto& it : sFSAClientArray)
it.ReleaseAndCleanup();
sFSAIoMsgQueue = (IOSMsgQueueId)IOS_CreateMessageQueue(_m_sFSAIoMsgQueueMsgBuffer.GetPtr(), _m_sFSAIoMsgQueueMsgBuffer.GetCount());
IOS_ERROR r = IOS_RegisterResourceManager("/dev/fsa", sFSAIoMsgQueue);
IOS_DeviceAssociateId("/dev/fsa", 11);
cemu_assert(!IOS_ResultIsError(r));
sFSAIoThread = std::thread(FSAIoThread);
}
void Shutdown()
{
IOS_SendMessage(sFSAIoMsgQueue, 0, 0);
sFSAIoThread.join();
}
} // namespace fsa
} // namespace iosu
| 30,247
|
C++
|
.cpp
| 843
| 31.029656
| 181
| 0.69984
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,185
|
iosu_pdm.cpp
|
cemu-project_Cemu/src/Cafe/IOSU/PDM/iosu_pdm.cpp
|
#include <util/helpers/helpers.h>
#include "iosu_pdm.h"
#include "Cafe/CafeSystem.h"
#include "config/ActiveSettings.h"
#include "Common/FileStream.h"
#include "util/helpers/Semaphore.h"
#if BOOST_OS_LINUX
// using chrono::year_month_date and other features require a relatively recent stdlibc++
// to avoid upping the required version we use the STL reference implementation for now
#include "Common/unix/date.h"
namespace chrono_d = date;
#else
namespace chrono_d = std::chrono;
#endif
namespace iosu
{
namespace pdm
{
std::recursive_mutex sPlaystatsLock;
std::recursive_mutex sDiaryLock;
fs::path GetPDFile(const char* filename)
{
// todo - support for per-account tracking
return ActiveSettings::GetMlcPath(fmt::format("usr/save/system/pdm/80000001/{}", filename));
}
void MakeDirectory()
{
fs::path path = GetPDFile(".");
std::error_code ec;
fs::create_directories(path, ec);
}
chrono_d::year_month_day GetDateFromDayIndex(uint16 dayIndex)
{
chrono_d::sys_days startDateDay(chrono_d::year(2000) / chrono_d::January / chrono_d::day(1));
chrono_d::sys_days lastPlayedDay = startDateDay + chrono_d::days(dayIndex);
return chrono_d::year_month_day(lastPlayedDay);
}
uint16 GetTodaysDayIndex()
{
chrono_d::sys_days startDateDay(chrono_d::year(2000) / chrono_d::January / chrono_d::day(1));
chrono_d::sys_days currentDateDay = chrono_d::floor<chrono_d::days>(std::chrono::system_clock::now());
return (uint16)(currentDateDay - startDateDay).count();
}
struct PlayStatsEntry
{
uint32be titleIdHigh;
uint32be titleIdLow;
uint32be totalMinutesPlayed;
uint16be numTimesLaunched;
uint16be firstLaunchDayIndex; // first time this title was launched
uint16be mostRecentDayIndex; // last time this title was played
uint16be ukn12; // maybe just padding?
};
static_assert(sizeof(PlayStatsEntry) == 0x14);
struct
{
FileStream* fs{};
uint32be numEntries;
PlayStatsEntry entry[NUM_PLAY_STATS_ENTRIES];
}PlayStats;
void CreatePlaystats()
{
PlayStats.fs = FileStream::createFile2(GetPDFile("PlayStats.dat"));
if (!PlayStats.fs)
{
cemuLog_log(LogType::Force, "Unable to open or create PlayStats.dat");
return;
}
uint32be entryCount = 0;
PlayStats.fs->writeData(&entryCount, sizeof(uint32be));
PlayStats.fs->writeData(PlayStats.entry, NUM_PLAY_STATS_ENTRIES * sizeof(PlayStatsEntry));
static_assert((NUM_PLAY_STATS_ENTRIES * sizeof(PlayStatsEntry)) == 0x1400);
}
void OpenPlaystats()
{
std::unique_lock _l(sPlaystatsLock);
PlayStats.numEntries = 0;
for (size_t i = 0; i < NUM_PLAY_STATS_ENTRIES; i++)
{
auto& e = PlayStats.entry[i];
memset(&e, 0, sizeof(PlayStatsEntry));
}
cemu_assert_debug(!PlayStats.fs);
PlayStats.fs = FileStream::openFile2(GetPDFile("PlayStats.dat"), true);
if (!PlayStats.fs)
{
CreatePlaystats();
return;
}
if (PlayStats.fs->GetSize() != (NUM_PLAY_STATS_ENTRIES * 20 + 4))
{
delete PlayStats.fs;
PlayStats.fs = nullptr;
cemuLog_log(LogType::Force, "PlayStats.dat malformed. Time tracking wont be used");
// dont delete the existing file in case it could still be salvaged (todo) and instead just dont track play time
return;
}
PlayStats.numEntries = 0;
PlayStats.fs->readData(&PlayStats.numEntries, sizeof(uint32be));
if (PlayStats.numEntries > NUM_PLAY_STATS_ENTRIES)
PlayStats.numEntries = NUM_PLAY_STATS_ENTRIES;
PlayStats.fs->readData(PlayStats.entry, NUM_PLAY_STATS_ENTRIES * 20);
}
void ClosePlaystats()
{
std::unique_lock _l(sPlaystatsLock);
if (PlayStats.fs)
{
delete PlayStats.fs;
PlayStats.fs = nullptr;
}
}
void UnloadPlaystats()
{
std::unique_lock _l(sPlaystatsLock);
cemu_assert_debug(!PlayStats.fs); // unloading expects that file is closed
PlayStats.numEntries = 0;
for(auto& it : PlayStats.entry)
it = PlayStatsEntry{};
}
PlayStatsEntry* PlayStats_GetEntry(uint64 titleId)
{
std::unique_lock _l(sPlaystatsLock);
uint32be titleIdHigh = (uint32)(titleId>>32);
uint32be titleIdLow = (uint32)(titleId & 0xFFFFFFFF);
size_t numEntries = PlayStats.numEntries;
for (size_t i = 0; i < numEntries; i++)
{
if (PlayStats.entry[i].titleIdHigh == titleIdHigh && PlayStats.entry[i].titleIdLow == titleIdLow)
return &PlayStats.entry[i];
}
return nullptr;
}
void PlayStats_WriteEntryNoLock(PlayStatsEntry* entry, bool writeEntryCount = false)
{
if (!PlayStats.fs)
return;
size_t entryIndex = entry - PlayStats.entry;
cemu_assert(entryIndex < NUM_PLAY_STATS_ENTRIES);
PlayStats.fs->SetPosition(4 + entryIndex * sizeof(PlayStatsEntry));
if (PlayStats.fs->writeData(entry, sizeof(PlayStatsEntry)) != sizeof(PlayStatsEntry))
{
cemuLog_log(LogType::Force, "Failed to write to PlayStats.dat");
return;
}
if (writeEntryCount)
{
uint32be numEntries = PlayStats.numEntries;
PlayStats.fs->SetPosition(0);
PlayStats.fs->writeData(&numEntries, sizeof(uint32be));
}
}
void PlayStats_WriteEntry(PlayStatsEntry* entry, bool writeEntryCount = false)
{
std::unique_lock _l(sPlaystatsLock);
PlayStats_WriteEntryNoLock(entry, writeEntryCount);
}
PlayStatsEntry* PlayStats_CreateEntry(uint64 titleId)
{
std::unique_lock _l(sPlaystatsLock);
bool entryCountChanged = false;
PlayStatsEntry* newEntry;
if(PlayStats.numEntries < NUM_PLAY_STATS_ENTRIES)
{
newEntry = PlayStats.entry + PlayStats.numEntries;
PlayStats.numEntries += 1;
entryCountChanged = true;
}
else
{
// list is full - find existing entry with least amount of minutes and replace it
newEntry = PlayStats.entry + 0;
for (uint32 i = 1; i < NUM_PLAY_STATS_ENTRIES; i++)
{
if(PlayStats.entry[i].totalMinutesPlayed < newEntry->totalMinutesPlayed)
newEntry = PlayStats.entry + i;
}
}
newEntry->titleIdHigh = (uint32)(titleId >> 32);
newEntry->titleIdLow = (uint32)(titleId & 0xFFFFFFFF);
newEntry->firstLaunchDayIndex = GetTodaysDayIndex();
newEntry->mostRecentDayIndex = newEntry->firstLaunchDayIndex;
newEntry->numTimesLaunched = 1;
newEntry->totalMinutesPlayed = 0;
newEntry->ukn12 = 0;
PlayStats_WriteEntryNoLock(newEntry, entryCountChanged);
return newEntry;
}
// sets last played if entry already exists
// if it does not exist it creates a new entry with first and last played set to today
PlayStatsEntry* PlayStats_BeginNewTracking(uint64 titleId)
{
std::unique_lock _l(sPlaystatsLock);
PlayStatsEntry* entry = PlayStats_GetEntry(titleId);
if (entry)
{
entry->mostRecentDayIndex = GetTodaysDayIndex();
entry->numTimesLaunched += 1;
PlayStats_WriteEntry(entry);
return entry;
}
return PlayStats_CreateEntry(titleId);
}
void PlayStats_CountAdditionalMinutes(PlayStatsEntry* entry, uint32 additionalMinutes)
{
std::unique_lock _l(sPlaystatsLock);
if (additionalMinutes == 0)
return;
entry->totalMinutesPlayed += additionalMinutes;
entry->mostRecentDayIndex = GetTodaysDayIndex();
PlayStats_WriteEntryNoLock(entry);
}
struct PlayDiaryHeader
{
// the play diary is a rolling log
// initially only writeIndex increases
// after the log is filled, writeIndex wraps over and readIndex will increase as well
uint32be readIndex;
uint32be writeIndex;
};
static_assert(sizeof(PlayDiaryEntry) == 0x10);
static_assert(sizeof(PlayDiaryHeader) == 0x8);
struct
{
FileStream* fs{};
PlayDiaryHeader header;
PlayDiaryEntry entry[NUM_PLAY_DIARY_ENTRIES_MAX];
}PlayDiaryData;
void CreatePlayDiary()
{
MakeDirectory();
cemu_assert_debug(!PlayDiaryData.fs);
PlayDiaryData.fs = FileStream::createFile2(GetPDFile("PlayDiary.dat"));
if (!PlayDiaryData.fs)
{
cemuLog_log(LogType::Force, "Failed to read or write PlayDiary.dat, playtime tracking will not be possible");
}
// write header
PlayDiaryData.header.readIndex = 0;
PlayDiaryData.header.writeIndex = 0;
if (PlayDiaryData.fs)
PlayDiaryData.fs->writeData(&PlayDiaryData.header, sizeof(PlayDiaryHeader));
}
void OpenPlayDiary()
{
std::unique_lock _lock(sDiaryLock);
cemu_assert_debug(!PlayDiaryData.fs);
PlayDiaryData.fs = FileStream::openFile2(GetPDFile("PlayDiary.dat"), true);
if (!PlayDiaryData.fs)
{
CreatePlayDiary();
return;
}
// read header
if (PlayDiaryData.fs->readData(&PlayDiaryData.header, sizeof(PlayDiaryHeader)) != sizeof(PlayDiaryHeader))
{
cemuLog_log(LogType::Force, "Failed to read valid PlayDiary header");
delete PlayDiaryData.fs;
PlayDiaryData.fs = nullptr;
CreatePlayDiary();
return;
}
if (PlayDiaryData.header.readIndex > NUM_PLAY_DIARY_ENTRIES_MAX || PlayDiaryData.header.writeIndex > NUM_PLAY_DIARY_ENTRIES_MAX)
{
cemuLog_log(LogType::Force, "Bad value in play diary header (read={} write={})", (uint32)PlayDiaryData.header.readIndex, (uint32)PlayDiaryData.header.writeIndex);
PlayDiaryData.header.readIndex = PlayDiaryData.header.readIndex % NUM_PLAY_DIARY_ENTRIES_MAX;
PlayDiaryData.header.writeIndex = PlayDiaryData.header.writeIndex % NUM_PLAY_DIARY_ENTRIES_MAX;
}
// read entries and set any not-yet-written entries to zero
uint32 readBytes = PlayDiaryData.fs->readData(PlayDiaryData.entry, NUM_PLAY_DIARY_ENTRIES_MAX * sizeof(PlayDiaryEntry));
uint32 readEntries = readBytes / sizeof(PlayDiaryEntry);
while (readEntries < NUM_PLAY_DIARY_ENTRIES_MAX)
{
PlayDiaryData.entry[readEntries].titleId = 0;
PlayDiaryData.entry[readEntries].ukn08 = 0;
PlayDiaryData.entry[readEntries].dayIndex = 0;
PlayDiaryData.entry[readEntries].ukn0E = 0;
readEntries++;
}
}
void ClosePlayDiary()
{
std::unique_lock _lock(sDiaryLock);
if (PlayDiaryData.fs)
{
delete PlayDiaryData.fs;
PlayDiaryData.fs = nullptr;
}
}
void UnloadDiaryData()
{
std::unique_lock _lock(sDiaryLock);
cemu_assert_debug(!PlayDiaryData.fs); // unloading expects that file is closed
PlayDiaryData.header.readIndex = 0;
PlayDiaryData.header.writeIndex = 0;
for (auto& it : PlayDiaryData.entry)
it = PlayDiaryEntry{};
}
uint32 GetDiaryEntries(uint8 accountSlot, PlayDiaryEntry* diaryEntries, uint32 maxEntries)
{
std::unique_lock _lock(sDiaryLock);
uint32 numReadEntries = 0;
uint32 currentEntryIndex = PlayDiaryData.header.readIndex;
while (currentEntryIndex != PlayDiaryData.header.writeIndex && numReadEntries < maxEntries)
{
*diaryEntries = PlayDiaryData.entry[currentEntryIndex];
numReadEntries++;
diaryEntries++;
currentEntryIndex = (currentEntryIndex+1) % NUM_PLAY_DIARY_ENTRIES_MAX;
}
return numReadEntries;
}
bool GetStatForGamelist(uint64 titleId, GameListStat& stat)
{
stat.last_played.year = 0;
stat.last_played.month = 0;
stat.last_played.day = 0;
stat.numMinutesPlayed = 0;
std::unique_lock _lock(sDiaryLock);
// the play stats give us last time played and the total minutes
PlayStatsEntry* playStats = PlayStats_GetEntry(titleId);
if (playStats)
{
stat.numMinutesPlayed = playStats->totalMinutesPlayed;
chrono_d::year_month_day ymd = GetDateFromDayIndex(playStats->mostRecentDayIndex);
stat.last_played.year = (int)ymd.year();
stat.last_played.month = (unsigned int)ymd.month() - 1;
stat.last_played.day = (unsigned int)ymd.day();
}
_lock.unlock();
// check legacy time tracking for game entries in settings.xml
std::unique_lock _lockGC(GetConfig().game_cache_entries_mutex);
for (auto& gameEntry : GetConfig().game_cache_entries)
{
if(gameEntry.title_id != titleId)
continue;
stat.numMinutesPlayed += (gameEntry.legacy_time_played / 60);
if (gameEntry.legacy_last_played != 0)
{
time_t td = gameEntry.legacy_last_played;
tm* date = localtime(&td);
uint32 legacyYear = (uint32)date->tm_year + 1900;
uint32 legacyMonth = (uint32)date->tm_mon;
uint32 legacyDay = (uint32)date->tm_mday;
if (stat.last_played.year == 0 || std::tie(legacyYear, legacyMonth, legacyDay) > std::tie(stat.last_played.year, stat.last_played.month, stat.last_played.day))
{
stat.last_played.year = legacyYear;
stat.last_played.month = legacyMonth;
stat.last_played.day = legacyDay;
}
}
}
return true;
}
std::thread sPDMTimeTrackingThread;
CounterSemaphore sPDMSem;
std::atomic_bool sPDMRequestExitThread{ false };
void TimeTrackingThread(uint64 titleId)
{
SetThreadName("PlayDiaryThread");
PlayStatsEntry* playStatsEntry = PlayStats_BeginNewTracking(titleId);
auto startTime = std::chrono::steady_clock::now();
uint32 prevMinuteCounter = 0;
while (true)
{
sPDMSem.decrementWithWaitAndTimeout(15000);
if (sPDMRequestExitThread.load(std::memory_order::relaxed))
break;
auto currentTime = std::chrono::steady_clock::now();
uint32 elapsedMinutes = std::chrono::duration_cast<std::chrono::minutes>(currentTime - startTime).count();
if (elapsedMinutes > prevMinuteCounter)
{
PlayStats_CountAdditionalMinutes(playStatsEntry, (elapsedMinutes - prevMinuteCounter));
// todo - also update PlayDiary (and other files)
prevMinuteCounter = elapsedMinutes;
}
}
}
class : public ::IOSUModule
{
void PDMLoadAll()
{
OpenPlaystats();
OpenPlayDiary();
}
void PDMUnloadAll()
{
UnloadPlaystats();
UnloadDiaryData();
}
void PDMCloseAll()
{
ClosePlaystats();
ClosePlayDiary();
}
void SystemLaunch() override
{
// todo - add support for per-account handling
PDMLoadAll();
PDMCloseAll(); // close the files again, user may mess with MLC files or change MLC path while no game is running
}
void SystemExit() override
{
PDMCloseAll();
PDMUnloadAll();
}
void TitleStart() override
{
// reload data and keep files open
PDMUnloadAll();
PDMLoadAll();
auto titleId = CafeSystem::GetForegroundTitleId();
sPDMRequestExitThread = false;
sPDMTimeTrackingThread = std::thread(TimeTrackingThread, titleId);
}
void TitleStop() override
{
sPDMRequestExitThread.store(true);
sPDMSem.increment();
if(sPDMTimeTrackingThread.joinable())
sPDMTimeTrackingThread.join();
PDMCloseAll();
}
}sIOSUModuleNNPDM;
IOSUModule* GetModule()
{
return static_cast<IOSUModule*>(&sIOSUModuleNNPDM);
}
};
};
| 14,516
|
C++
|
.cpp
| 430
| 29.674419
| 166
| 0.721028
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,186
|
Account.cpp
|
cemu-project_Cemu/src/Cafe/Account/Account.cpp
|
#include "Account.h"
#include "util/helpers/helpers.h"
#include "util/helpers/SystemException.h"
#include "util/helpers/StringHelpers.h"
#include "config/ActiveSettings.h"
#include "Cafe/IOSU/legacy/iosu_crypto.h"
#include "Common/FileStream.h"
#include <boost/random/uniform_int.hpp>
#include <random>
std::vector<Account> Account::s_account_list;
Account::Account(uint32 persistent_id)
: m_persistent_id(persistent_id) {}
typedef struct
{
uint32be high;
uint32be low;
}FFLDataID_t;
typedef struct
{
/* +0x00 */ uint32 uknFlags;
/* +0x04 */ FFLDataID_t miiId; // bytes 8 and 9 are part of the CRC? (miiId is based on account transferable id?)
/* +0x0C */ uint8 ukn0C[0xA];
/* +0x16 */ uint8 ukn16[2];
/* +0x18 */ uint16 ukn18;
/* +0x1A */ uint16le miiName[10];
/* +0x2E */ uint16 ukn2E;
/* +0x30 */ uint8 ukn30[96 - 0x30];
}FFLData_t;
uint16 FFLCalculateCRC16(uint8* input, sint32 length)
{
cemu_assert_debug((length % 8) == 0);
uint16 crc = 0;
for (sint32 c = 0; c < length; c++)
{
for (sint32 f = 0; f < 8; f++)
{
if ((crc & 0x8000) != 0)
{
uint16 t = crc << 1;
crc = t ^ 0x1021;
}
else
{
crc <<= 1;
}
}
crc ^= (uint16)input[c];
}
return crc;
}
Account::Account(uint32 persistent_id, std::wstring_view mii_name)
: m_persistent_id(persistent_id)
{
if (mii_name.empty())
throw std::system_error(AccountErrc::InvalidMiiName);
static std::random_device s_random_device;
static std::mt19937 s_mte(s_random_device());
// use boost library to escape static asserts in linux builds
boost::random::uniform_int_distribution<uint16> dist(std::numeric_limits<uint8>::min(), std::numeric_limits<uint8>::max());
std::generate(m_uuid.begin(), m_uuid.end(), [&]() { return (uint8)dist(s_mte); });
// 1000004 or 2000004 | lower uint32 from uuid from uuid
m_transferable_id_base = (0x2000004ULL << 32);
m_transferable_id_base |= ((uint64)m_uuid[12] << 24) | ((uint64)m_uuid[13] << 16) | ((uint64)m_uuid[14] << 8) | (uint64)m_uuid[15];
SetMiiName(mii_name);
// todo: generate mii data
// iosuAct_generateDefaultMii
// void* pMiiData = &_actAccountData[accountIndex].miiData;
uint8* fflByteDataBE = m_mii_data.data();
uint16* fflDataBE = (uint16*)m_mii_data.data();
// FFLCreateId is derived from the words at location: 0x7 - 0xb (5 words, so it's a 80 bit id)
for (sint32 i = 0; i < 96 / 2; i++)
fflDataBE[i] = _swapEndianU16(1);
*(uint16*)(fflByteDataBE + 0x3A) = _swapEndianU16(1 | (3 << 9));
*(uint16*)(fflByteDataBE + 0x2) = _swapEndianU16(1 | (1 << 12));
//*(uint32*)(fflByteDataBE + 4) = 0; // transferable id high ?
*(uint32*)(fflByteDataBE + 8) = _swapEndianU32(0x33333 + 0 + 1); // mii id low
// swap endian (apparently it's stored little-endian)
for (sint32 i = 0; i < 96 / 2; i++)
fflDataBE[i] = _swapEndianU16(fflDataBE[i]);
// set default name
FFLData_t* fflData = (FFLData_t*)m_mii_data.data();
const auto tmp_name = GetMiiName();
memset(fflData->miiName, 0, sizeof(fflData->miiName));
std::copy(tmp_name.begin(), tmp_name.end(), fflData->miiName);
// calculate checksum
uint32 crcCounter = 0;
while (FFLCalculateCRC16(m_mii_data.data(), 96) != 0)
{
*(uint32*)(fflDataBE + 2) = _swapEndianU32(crcCounter);
crcCounter++;
}
const auto error = CheckValid();
if (error)
throw std::system_error(error);
}
Account::Account(std::wstring_view file_name)
{
if (!fs::exists(file_name.data()))
throw std::runtime_error("given file doesn't exist");
std::unique_ptr<FileStream> file(FileStream::openFile2(file_name));
if (!file)
throw std::runtime_error("can't open file");
ParseFile(file.get());
const auto error = CheckValid();
if (error)
throw std::system_error(error);
}
std::error_code Account::CheckValid() const
{
if (m_persistent_id < kMinPersistendId)
return AccountErrc::InvalidPersistentId;
if (m_mii_name[0] == '\0')
return AccountErrc::InvalidMiiName;
if (m_mii_data == decltype(m_mii_data){})
return AccountErrc::InvalidMiiData;
// todo: check for other needed properties
return AccountErrc::NoError;
}
std::error_code Account::Load()
{
const auto persistent_id = m_persistent_id;
const fs::path path = GetFileName();
try
{
std::unique_ptr<FileStream> file(FileStream::openFile2(path));
if (!file)
throw std::runtime_error("can't open file");
ParseFile(file.get());
// fix persistent id if it's in the wrong folder
m_persistent_id = persistent_id;
return CheckValid();
}
catch (const std::system_error& ex)
{
return ex.code();
}
catch(const std::exception& ex)
{
cemuLog_log(LogType::Force, "handled error in Account::Load: {}", ex.what());
return AccountErrc::ParseError;
}
}
std::error_code Account::Save()
{
fs::path path = ActiveSettings::GetMlcPath(fmt::format(L"usr/save/system/act/{:08x}", m_persistent_id));
if (!fs::exists(path))
{
std::error_code ec;
fs::create_directories(path, ec);
if (ec)
return ec;
}
path /= "account.dat";
try
{
std::ofstream file;
file.exceptions(std::ios::badbit);
file.open(path);
file << "AccountInstance_20120705" << std::endl;
file << fmt::format("PersistentId={:08x}", m_persistent_id) << std::endl;
file << fmt::format("TransferableIdBase={:x}", m_transferable_id_base) << std::endl;
file << fmt::format("Uuid=");
for (const auto& b : m_uuid)
file << fmt::format("{:02x}", b);
file << std::endl;
file << fmt::format("MiiData=");
for (const auto& b : m_mii_data)
file << fmt::format("{:02x}", b);
file << std::endl;
file << fmt::format("MiiName=");
for (const auto& b : m_mii_name)
file << fmt::format("{:04x}", (uint16)b);
file << std::endl;
file << fmt::format("AccountId={}", m_account_id) << std::endl;
file << fmt::format("BirthYear={:x}", m_birth_year) << std::endl;
file << fmt::format("BirthMonth={:x}", m_birth_month) << std::endl;
file << fmt::format("BirthDay={:x}", m_birth_day) << std::endl;
file << fmt::format("Gender={:x}", m_gender) << std::endl;
file << fmt::format("EmailAddress={}", m_email) << std::endl;
file << fmt::format("Country={:x}", m_country) << std::endl;
file << fmt::format("SimpleAddressId={:x}", m_simple_address_id) << std::endl;
file << fmt::format("PrincipalId={:x}", m_principal_id) << std::endl;
file << fmt::format("IsPasswordCacheEnabled={:x}", m_password_cache_enabled) << std::endl;
file << fmt::format("AccountPasswordCache=");
for (const auto& b : m_account_password_cache)
file << fmt::format("{:02x}", b);
file << std::endl;
// write rest of stuff we got
for(const auto& [key, value] : m_storage)
{
file << fmt::format("{}={}", key, value) << std::endl;
}
file.flush();
file.close();
return CheckValid();
}
catch (const std::system_error& e)
{
return e.code();
}
}
OnlineAccountError Account::GetOnlineAccountError() const
{
if (m_account_id.empty())
return OnlineAccountError::kNoAccountId;
if (!IsPasswordCacheEnabled())
return OnlineAccountError::kNoPasswordCached;
if (m_account_password_cache == decltype(m_account_password_cache){})
return OnlineAccountError::kPasswordCacheEmpty;
/*if (m_simple_address_id == 0) not really needed
return false;*/
if (m_principal_id == 0)
return OnlineAccountError::kNoPrincipalId;
// TODO
return OnlineAccountError::kNone;
}
bool Account::IsValidOnlineAccount() const
{
return GetOnlineAccountError() == OnlineAccountError::kNone;
}
fs::path Account::GetFileName() const
{
return GetFileName(m_persistent_id);
}
std::wstring_view Account::GetMiiName() const
{
const auto it = std::find(m_mii_name.cbegin(), m_mii_name.cend(), '\0');
if(it == m_mii_name.cend())
return { m_mii_name.data(), m_mii_name.size() - 1 };
const size_t count = std::distance(m_mii_name.cbegin(), it);
return { m_mii_name.data(), count};
}
std::string_view Account::GetStorageValue(std::string_view key) const
{
const auto it = m_storage.find(key.data());
if (it == m_storage.cend())
return {};
return it->second;
}
void Account::SetMiiName(std::wstring_view name)
{
m_mii_name = {};
std::copy(name.data(), name.data() + std::min(name.size(), m_mii_name.size() - 1), m_mii_name.begin());
}
const std::vector<Account>& Account::RefreshAccounts()
{
std::vector<Account> result;
const fs::path path = ActiveSettings::GetMlcPath("usr/save/system/act");
if (fs::exists(path))
{
for (const auto& it : fs::directory_iterator(path))
{
if (!fs::is_directory(it))
continue;
const auto file_name = it.path().filename().string();
if (file_name.size() != 8)
continue;
const auto persistent_id = ConvertString<uint32>(file_name, 16);
if (persistent_id < kMinPersistendId)
continue;
Account account(persistent_id);
const auto error = account.Load();
if (!error)
result.emplace_back(account);
}
}
// we always force at least one account
if (result.empty())
{
result.emplace_back(kMinPersistendId, L"default");
result.begin()->Save();
}
s_account_list = result;
UpdatePersisidDat();
return s_account_list;
}
void Account::UpdatePersisidDat()
{
const auto max_id = std::max(kMinPersistendId, GetNextPersistentId() - 1);
const auto file = ActiveSettings::GetMlcPath("usr/save/system/act/persisid.dat");
std::ofstream f(file);
if(f.is_open())
{
f << "PersistentIdManager_20120607" << std::endl << "PersistentIdHead=" << std::hex << max_id << std::endl << std::endl;
f.flush();
f.close();
}
else
cemuLog_log(LogType::Force, "Unable to save persisid.dat");
}
bool Account::HasFreeAccountSlots()
{
return s_account_list.size() < 12;
}
const std::vector<Account>& Account::GetAccounts()
{
if (!s_account_list.empty())
return s_account_list;
return RefreshAccounts();
}
const Account& Account::GetAccount(uint32 persistent_id)
{
for (const auto& account : GetAccounts())
{
if (account.GetPersistentId() == persistent_id)
return account;
}
return *GetAccounts().begin();
}
const Account& Account::GetCurrentAccount()
{
return GetAccount(ActiveSettings::GetPersistentId());
}
uint32 Account::GetNextPersistentId()
{
uint32 result = kMinPersistendId;
const auto file = ActiveSettings::GetMlcPath("usr/save/system/act/persisid.dat");
if(fs::exists(file))
{
std::ifstream f(file);
if(f.is_open())
{
std::string line;
while(std::getline(f, line))
{
if(boost::starts_with(line, "PersistentIdHead="))
{
result = ConvertString<uint32>(line.data() + sizeof("PersistentIdHead=") - 1, 16);
break;
}
}
}
}
// next id
++result;
const auto it = std::max_element(s_account_list.cbegin(), s_account_list.cend(), [](const Account& acc1, const Account& acc2) {return acc1.GetPersistentId() < acc2.GetPersistentId(); });
if (it != s_account_list.cend())
return std::max(result, it->GetPersistentId() + 1);
else
return result;
}
fs::path Account::GetFileName(uint32 persistent_id)
{
if (persistent_id < kMinPersistendId)
throw std::invalid_argument(fmt::format("persistent id {:#x} is invalid", persistent_id));
return ActiveSettings::GetMlcPath(fmt::format("usr/save/system/act/{:08x}/account.dat", persistent_id));
}
OnlineValidator Account::ValidateOnlineFiles() const
{
OnlineValidator result{};
const auto otp = ActiveSettings::GetUserDataPath("otp.bin");
if (!fs::exists(otp))
result.otp = OnlineValidator::FileState::Missing;
else if (fs::file_size(otp) != 1024)
result.otp = OnlineValidator::FileState::Corrupted;
else
result.otp = OnlineValidator::FileState::Ok;
const auto seeprom = ActiveSettings::GetUserDataPath("seeprom.bin");
if (!fs::exists(seeprom))
result.seeprom = OnlineValidator::FileState::Missing;
else if (fs::file_size(seeprom) != 512)
result.seeprom = OnlineValidator::FileState::Corrupted;
else
result.seeprom = OnlineValidator::FileState::Ok;
for(const auto& v : iosuCrypt_getCertificateKeys())
{
const auto p = ActiveSettings::GetMlcPath(L"sys/title/0005001b/10054000/content/{}", v);
if (!fs::exists(p) || !fs::is_regular_file(p))
result.missing_files.emplace_back(p.generic_wstring());
}
for (const auto& v : iosuCrypt_getCertificateNames())
{
const auto p = ActiveSettings::GetMlcPath(L"sys/title/0005001b/10054000/content/{}", v);
if (!fs::exists(p) || !fs::is_regular_file(p))
result.missing_files.emplace_back(p.generic_wstring());
}
result.valid_account = IsValidOnlineAccount();
result.account_error = GetOnlineAccountError();
return result;
}
void Account::ParseFile(class FileStream* file)
{
std::vector<uint8> buffer;
buffer.resize(file->GetSize());
if( file->readData(buffer.data(), buffer.size()) != buffer.size())
throw std::system_error(AccountErrc::ParseError);
for (const auto& s : StringHelpers::StringLineIterator(buffer))
{
std::string_view view = s;
const auto find = view.find('=');
if (find == std::string_view::npos)
continue;
const auto key = view.substr(0, find);
const auto value = view.substr(find + 1);
if (key == "PersistentId")
m_persistent_id = ConvertString<uint32>(value, 16);
else if (key == "TransferableIdBase")
m_transferable_id_base = ConvertString<uint64>(value, 16);
else if (key == "Uuid")
{
if (value.size() != m_uuid.size() * 2) // = 32
throw std::system_error(AccountErrc::InvalidUuid);
for (size_t i = 0; i < m_uuid.size(); ++i)
{
m_uuid[i] = ConvertString<uint8>(value.substr(i * 2, 2), 16);
}
}
else if (key == "MiiData")
{
if (value.size() != m_mii_data.size() * 2) // = 192
throw std::system_error(AccountErrc::InvalidMiiData);
for (size_t i = 0; i < m_mii_data.size(); ++i)
{
m_mii_data[i] = ConvertString<uint8>(value.substr(i * 2, 2), 16);
}
}
else if (key == "MiiName")
{
if(value.size() != m_mii_name.size() * 4) // = 44
throw std::system_error(AccountErrc::InvalidMiiName);
for (size_t i = 0; i < m_mii_name.size(); ++i)
{
m_mii_name[i] = (wchar_t)ConvertString<uint16>(value.substr(i * 4, 4), 16);
}
}
else if (key == "AccountId")
m_account_id = value;
else if (key == "BirthYear")
m_birth_year = ConvertString<uint16>(value, 16);
else if (key == "BirthMonth")
m_birth_month = ConvertString<uint8>(value, 16);
else if (key == "BirthDay")
m_birth_day = ConvertString<uint8>(value, 16);
else if (key == "Gender")
m_gender = ConvertString<uint8>(value, 16);
else if (key == "EmailAddress")
m_email = value;
else if (key == "Country")
m_country = ConvertString<uint32>(value, 16);
else if (key == "SimpleAddressId")
m_simple_address_id = ConvertString<uint32>(value, 16);
else if (key == "PrincipalId")
m_principal_id = ConvertString<uint32>(value, 16);
else if (key == "IsPasswordCacheEnabled")
m_password_cache_enabled = ConvertString<uint8>(value, 16);
else if (key == "AccountPasswordCache")
{
for (size_t i = 0; i < m_account_password_cache.size(); ++i)
{
m_account_password_cache[i] = ConvertString<uint8>(value.substr(i * 2, 2), 16);
}
}
else // store anything else not needed for now
m_storage[std::string(key)] = value;
}
}
#include"openssl/sha.h"
void makePWHash(uint8* input, sint32 length, uint32 magic, uint8* output)
{
uint8 buffer[64 + 8];
if (length > (sizeof(buffer) - 8))
{
cemu_assert_debug(false);
memset(output, 0, 32);
return;
}
buffer[4] = 0x02;
buffer[5] = 0x65;
buffer[6] = 0x43;
buffer[7] = 0x46;
buffer[0] = (magic >> 0) & 0xFF;
buffer[1] = (magic >> 8) & 0xFF;
buffer[2] = (magic >> 16) & 0xFF;
buffer[3] = (magic >> 24) & 0xFF;
memcpy(buffer + 8, input, length);
uint8 md[SHA256_DIGEST_LENGTH];
SHA256(buffer, 8 + length, md);
memcpy(output, md, SHA256_DIGEST_LENGTH);
}
void actPwTest()
{
uint8 pwHash[32];
uint32 principalId = 0x12345678;
uint32 pid = 0x12345678;
makePWHash((uint8*)"pass123", 7, pid, pwHash); // calculates AccountPasswordCache
makePWHash(pwHash, 32, pid, pwHash); // calculates AccountPasswordHash
assert_dbg();
}
| 15,969
|
C++
|
.cpp
| 488
| 29.956967
| 187
| 0.681916
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,187
|
ACR.cpp
|
cemu-project_Cemu/src/Cafe/HW/ACR/ACR.cpp
|
#include "Cafe/HW/MMU/MMU.h"
#include "Cafe/HW/Common/HwReg.h"
namespace HW_ACR
{
struct
{
HWREG::ACR_VI_ADDR viAddr;
HWREG::ACR_VI_CTRL viCtrl;
}g_acr;
/*
Is this some kind of VI emulation interface?
Pattern seen in Twilight Princess HD:
- If Hollywood hardware then read/write old 16bit GC VI register directly
- Otherwise these steps are performed:
VICONTROL |= 1
VIADDR = registerIndex
VIDATA = data
VICONTROL &= ~1
All the register accesses here are 32bit
*/
/* 0x0D00021C | Accesses VI register currently selected by VIADDR */
HWREG::ACR_VI_DATA ACR_VIDATA_R32(PAddr addr)
{
cemuLog_logDebug(LogType::Force, "ACR_VIDATA read with selected reg {:08x}", g_acr.viAddr.get_ADDR());
return HWREG::ACR_VI_DATA();
}
void ACR_VIDATA_W32(PAddr addr, HWREG::ACR_VI_DATA newValue)
{
cemuLog_logDebug(LogType::Force, "ACR_VIDATA write {:08x} with selected reg {:08x}", newValue.get_DATA(), g_acr.viAddr.get_ADDR());
}
/* 0x0D000224 | Controls the selected VI register? */
HWREG::ACR_VI_ADDR ACR_VIADDR_R32(PAddr addr)
{
return g_acr.viAddr;
}
void ACR_VIADDR_W32(PAddr addr, HWREG::ACR_VI_ADDR newValue)
{
g_acr.viAddr = newValue;
}
/* 0x0D000228 | Some kind of VI interface control? */
HWREG::ACR_VI_CTRL ACR_VICONTROL_R32(PAddr addr)
{
return g_acr.viCtrl;
}
void ACR_VICONTROL_W32(PAddr addr, HWREG::ACR_VI_CTRL newValue)
{
g_acr.viCtrl = newValue;
}
RunAtCemuBoot _initACR([]()
{
MMU::RegisterMMIO_32<HWREG::ACR_VI_DATA, ACR_VIDATA_R32, ACR_VIDATA_W32>(MMU::MMIOInterface::INTERFACE_0D000000, 0x21C);
MMU::RegisterMMIO_32<HWREG::ACR_VI_ADDR, ACR_VIADDR_R32, ACR_VIADDR_W32>(MMU::MMIOInterface::INTERFACE_0D000000, 0x224);
MMU::RegisterMMIO_32<HWREG::ACR_VI_CTRL, ACR_VICONTROL_R32, ACR_VICONTROL_W32>(MMU::MMIOInterface::INTERFACE_0D000000, 0x228);
// init
});
}
| 1,847
|
C++
|
.cpp
| 56
| 30.446429
| 133
| 0.729623
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,188
|
PPCTimer.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/PPCTimer.cpp
|
#include "Cafe/HW/Espresso/Const.h"
#include "asm/x64util.h"
#include "config/ActiveSettings.h"
#include "util/helpers/fspinlock.h"
#include "util/highresolutiontimer/HighResolutionTimer.h"
#include "Common/cpu_features.h"
#if defined(ARCH_X86_64)
#include <immintrin.h>
#pragma intrinsic(__rdtsc)
#endif
uint64 _rdtscLastMeasure = 0;
uint64 _rdtscFrequency = 0;
struct uint128_t
{
uint64 low;
uint64 high;
};
static_assert(sizeof(uint128_t) == 16);
uint128_t _rdtscAcc{};
uint64 muldiv64(uint64 a, uint64 b, uint64 d)
{
uint64 diva = a / d;
uint64 moda = a % d;
uint64 divb = b / d;
uint64 modb = b % d;
return diva * b + moda * divb + moda * modb / d;
}
uint64 PPCTimer_estimateRDTSCFrequency()
{
#if defined(ARCH_X86_64)
if (!g_CPUFeatures.x86.invariant_tsc)
cemuLog_log(LogType::Force, "Invariant TSC not supported");
#endif
_mm_mfence();
uint64 tscStart = __rdtsc();
unsigned int startTime = GetTickCount();
HRTick startTick = HighResolutionTimer::now().getTick();
// wait roughly 3 seconds
while (true)
{
if ((GetTickCount() - startTime) >= 3000)
break;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
_mm_mfence();
HRTick stopTick = HighResolutionTimer::now().getTick();
uint64 tscEnd = __rdtsc();
// derive frequency approximation from measured time difference
uint64 tsc_diff = tscEnd - tscStart;
uint64 hrtFreq = 0;
uint64 hrtDiff = HighResolutionTimer::getTimeDiffEx(startTick, stopTick, hrtFreq);
uint64 tsc_freq = muldiv64(tsc_diff, hrtFreq, hrtDiff);
// uint64 freqMultiplier = tsc_freq / hrtFreq;
//cemuLog_log(LogType::Force, "RDTSC measurement test:");
//cemuLog_log(LogType::Force, "TSC-diff: 0x{:016x}", tsc_diff);
//cemuLog_log(LogType::Force, "TSC-freq: 0x{:016x}", tsc_freq);
//cemuLog_log(LogType::Force, "HPC-diff: 0x{:016x}", qpc_diff);
//cemuLog_log(LogType::Force, "HPC-freq: 0x{:016x}", (uint64)qpc_freq.QuadPart);
//cemuLog_log(LogType::Force, "Multiplier: 0x{:016x}", freqMultiplier);
return tsc_freq;
}
int PPCTimer_initThread()
{
_rdtscFrequency = PPCTimer_estimateRDTSCFrequency();
return 0;
}
void PPCTimer_init()
{
std::thread t(PPCTimer_initThread);
t.detach();
_rdtscLastMeasure = __rdtsc();
}
uint64 _tickSummary = 0;
void PPCTimer_start()
{
_rdtscLastMeasure = __rdtsc();
_tickSummary = 0;
}
uint64 PPCTimer_getRawTsc()
{
return __rdtsc();
}
uint64 PPCTimer_microsecondsToTsc(uint64 us)
{
return (us * _rdtscFrequency) / 1000000ULL;
}
uint64 PPCTimer_tscToMicroseconds(uint64 us)
{
uint128_t r{};
r.low = _umul128(us, 1000000ULL, &r.high);
uint64 remainder;
const uint64 microseconds = _udiv128(r.high, r.low, _rdtscFrequency, &remainder);
return microseconds;
}
bool PPCTimer_isReady()
{
return _rdtscFrequency != 0;
}
void PPCTimer_waitForInit()
{
while (!PPCTimer_isReady()) std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
FSpinlock sTimerSpinlock;
// thread safe
uint64 PPCTimer_getFromRDTSC()
{
sTimerSpinlock.lock();
_mm_mfence();
uint64 rdtscCurrentMeasure = __rdtsc();
uint64 rdtscDif = rdtscCurrentMeasure - _rdtscLastMeasure;
// optimized max(rdtscDif, 0) without conditionals
rdtscDif = rdtscDif & ~(uint64)((sint64)rdtscDif >> 63);
uint128_t diff{};
diff.low = _umul128(rdtscDif, Espresso::CORE_CLOCK, &diff.high);
if(rdtscCurrentMeasure > _rdtscLastMeasure)
_rdtscLastMeasure = rdtscCurrentMeasure; // only travel forward in time
uint8 c = 0;
#if BOOST_OS_WINDOWS
c = _addcarry_u64(c, _rdtscAcc.low, diff.low, &_rdtscAcc.low);
_addcarry_u64(c, _rdtscAcc.high, diff.high, &_rdtscAcc.high);
#else
// requires casting because of long / long long nonesense
c = _addcarry_u64(c, _rdtscAcc.low, diff.low, (unsigned long long*)&_rdtscAcc.low);
_addcarry_u64(c, _rdtscAcc.high, diff.high, (unsigned long long*)&_rdtscAcc.high);
#endif
uint64 remainder;
uint64 elapsedTick = _udiv128(_rdtscAcc.high, _rdtscAcc.low, _rdtscFrequency, &remainder);
_rdtscAcc.low = remainder;
_rdtscAcc.high = 0;
// timer scaling
elapsedTick <<= 3ull; // *8
uint8 timerShiftFactor = ActiveSettings::GetTimerShiftFactor();
elapsedTick >>= timerShiftFactor;
_tickSummary += elapsedTick;
sTimerSpinlock.unlock();
return _tickSummary;
}
| 4,218
|
C++
|
.cpp
| 137
| 28.861314
| 91
| 0.73679
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,189
|
PPCSchedulerLLE.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/PPCSchedulerLLE.cpp
|
struct PPCInterpreterLLEContext_t
{
uint8 padding[1024 * 128]; // reserved memory for stack (for recompiler mode)
PPCInterpreter_t cores[3];
};
PPCInterpreterGlobal_t globalCPUState = { 0 };
void PPCCoreLLE_initCore(PPCInterpreter_t* hCPU, uint32 coreIndex)
{
hCPU->spr.UPIR = coreIndex;
hCPU->global = &globalCPUState;
}
#define SCR_C2 (0x200000) // enable core 2
#define SCR_C1 (0x400000) // enable core 1
typedef struct
{
uint32be ukn000;
uint32be ukn004;
uint32be ukn008;
uint32be ukn00C;
uint32be ukn010;
uint32be ukn014;
uint32be busFreq;
uint32be ukn01C;
uint32be ukn020[4];
uint32be ukn030[4];
uint32be ukn040[4];
uint32be ukn050[4];
uint32be ukn060[4];
uint32be ukn070[4];
uint32be ukn080[4];
uint32be ukn090[4];
uint32be ukn0A0[4];
uint32be ukn0B0[4];
uint32be ukn0C0;
struct
{
uint32be id;
uint32be baseAddress;
uint32be size;
}ramInfo[3];
uint32 ukn0E8;
uint32 ukn0EC;
uint32 ukn0F0[4];
uint32 ukn100[8];
uint32 ukn120[8];
uint32 ukn140[8];
uint32 ukn160[8];
uint32 ukn180[8];
uint32 ukn1A0[8];
uint32 ukn1C0[8];
uint32 ukn1E0[8];
uint32 ukn200[8];
uint32 ukn220[8];
uint32 ukn240[8];
uint32 ukn260[8];
uint32 ukn280[8];
uint32 ukn2A0[8];
uint32 ukn2C0[8];
uint32 ukn2E0[8];
uint32 ukn300[8];
uint32 ukn320[8];
uint32 ukn340[8];
uint32 ukn360[8];
uint32 ukn380[8];
uint32be ukn3A0;
uint32be ukn3A4;
uint32be ukn3A8;
uint32be ukn3AC;
uint32be ukn3B0;
uint32be smdpAreaPtr;
uint32be ukn3B8;
uint32be ukn3BC;
uint32 ukn3C0[8];
uint32 ukn3E0[8];
uint32 ukn400;
uint32 ukn404;
uint32 ukn408;
}ppcBootParamBlock_t; // for kernel 5.5.2
static_assert(offsetof(ppcBootParamBlock_t, ramInfo) == 0xC4, "");
static_assert(offsetof(ppcBootParamBlock_t, busFreq) == 0x18, "");
static_assert(offsetof(ppcBootParamBlock_t, smdpAreaPtr) == 0x3B4, "");
static_assert(offsetof(ppcBootParamBlock_t, ukn400) == 0x400, "");
void PPCCoreLLE_setupBootParamBlock()
{
ppcBootParamBlock_t* bootParamBlock = (ppcBootParamBlock_t*)memory_getPointerFromPhysicalOffset(0x01FFF000);
memset(bootParamBlock, 0, sizeof(ppcBootParamBlock_t));
// setup RAM info
//PPCBaseAddress 0x8000000 0x00000000 0x28000000
//PPCSize 0x120000 0x2000000 0xA8000000
bootParamBlock->ukn004 = 0x40C;
bootParamBlock->busFreq = ESPRESSO_BUS_CLOCK;
bootParamBlock->ramInfo[0].id = 0;
bootParamBlock->ramInfo[0].baseAddress = 0x8000000;
bootParamBlock->ramInfo[0].size = 0x120000;
bootParamBlock->ramInfo[1].id = 1;
bootParamBlock->ramInfo[1].baseAddress = 0x00000000;
bootParamBlock->ramInfo[1].size = 0x2000000;
bootParamBlock->ramInfo[2].id = 2;
bootParamBlock->ramInfo[2].baseAddress = 0x28000000;
bootParamBlock->ramInfo[2].size = 0xA8000000;
}
typedef struct
{
uint32be magic;
uint32be count;
uint32 _padding08[14];
/* +0x0040 */ uint32be commandsReadIndex; // written by IOSU
uint32 _padding44[15];
/* +0x0080 */ uint32be commandsWriteIndex;
uint32 _padding84[15];
/* +0x00C0 */ uint32be resultsReadIndex;
uint32 _paddingC4[15];
/* +0x0100 */ uint32be resultsWriteIndex; // written by IOSU
uint32 _padding104[15];
/* +0x0140 */ uint32be commandPtrs[0xC00];
/* +0x3140 */ uint32be resultPtrs[0xC00];
}smdpArea_t;
static_assert(offsetof(smdpArea_t, commandsReadIndex) == 0x0040, "");
static_assert(offsetof(smdpArea_t, commandsWriteIndex) == 0x0080, "");
static_assert(offsetof(smdpArea_t, resultsReadIndex) == 0x00C0, "");
static_assert(offsetof(smdpArea_t, resultsWriteIndex) == 0x0100, "");
static_assert(offsetof(smdpArea_t, resultPtrs) == 0x3140, "");
typedef struct
{
uint32be type;
uint32be ukn04;
uint32be ukn08;
uint32be ukn0C;
uint32be ukn10;
uint32be ukn14;
uint32be ukn18;
uint32be ukn1C;
uint32be ukn20;
uint32be ukn24;
uint32be ukn28;
uint32be ukn2C;
}smdpCommand_t;
void smdpArea_pushResult(smdpArea_t* smdpArea, MPTR result)
{
//smdpArea.
smdpArea->resultPtrs[(uint32)smdpArea->resultsWriteIndex] = result;
smdpArea->resultsWriteIndex = ((uint32)smdpArea->resultsWriteIndex + 1)%(uint32)smdpArea->count;
}
void smdpArea_processCommand(smdpArea_t* smdpArea, smdpCommand_t* cmd)
{
if (cmd->type == 1)
{
cmd->ukn08 = 1;
// cmd->ukn2C ?
cemuLog_logDebug(LogType::Force, "SMDP command received - todo");
smdpArea_pushResult(smdpArea, memory_getVirtualOffsetFromPointer(cmd));
}
else
{
assert_dbg();
}
}
void smdpArea_thread()
{
while (true)
{
ppcBootParamBlock_t* bootParamBlock = (ppcBootParamBlock_t*)memory_getPointerFromPhysicalOffset(0x01FFF000);
if(bootParamBlock->smdpAreaPtr != MPTR_NULL)
{
smdpArea_t* smdpArea = (smdpArea_t*)memory_getPointerFromPhysicalOffset(bootParamBlock->smdpAreaPtr);
if (smdpArea->magic == 'smdp')
{
uint32 cmdReadIndex = smdpArea->commandsReadIndex;
uint32 cmdWriteIndex = smdpArea->commandsWriteIndex;
if (cmdReadIndex != cmdWriteIndex)
{
// new command
smdpArea_processCommand(smdpArea, (smdpCommand_t*)memory_getPointerFromPhysicalOffset(smdpArea->commandPtrs[cmdReadIndex]));
// increment read counter
cmdReadIndex = (cmdReadIndex + 1) % (uint32)smdpArea->count;
smdpArea->commandsReadIndex = cmdReadIndex;
}
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void PPCCoreLLE_startSingleCoreScheduler(uint32 entrypoint)
{
PPCInterpreterLLEContext_t* cpuContext = (PPCInterpreterLLEContext_t*)malloc(sizeof(PPCInterpreterLLEContext_t));
memset(cpuContext, 0, sizeof(PPCInterpreterLLEContext_t));
PPCCoreLLE_setupBootParamBlock();
PPCCoreLLE_initCore(cpuContext->cores + 0, 0);
PPCCoreLLE_initCore(cpuContext->cores + 1, 1);
PPCCoreLLE_initCore(cpuContext->cores + 2, 2);
cpuContext->cores[0].instructionPointer = entrypoint;
cpuContext->cores[1].instructionPointer = 0xFFF00100;
cpuContext->cores[2].instructionPointer = 0xFFF00100;
// todo - calculate instruction pointer when core 1/2 is enabled (because entry point is determined by MSR exception vector bit)
std::thread(smdpArea_thread).detach();
while (true)
{
for (uint32 coreIndex = 0; coreIndex < 3; coreIndex++)
{
PPCInterpreter_t* hCPU = cpuContext->cores+coreIndex;
PPCInterpreter_setCurrentInstance(hCPU);
if (coreIndex == 1)
{
// check SCR core 1 enable bit
if ((globalCPUState.sprGlobal.scr&SCR_C1) == 0)
continue;
}
else if (coreIndex == 2)
{
// check SCR core 2 enable bit
if ((globalCPUState.sprGlobal.scr&SCR_C2) == 0)
continue;
}
hCPU->remainingCycles = 10000;
while ((--hCPU->remainingCycles) >= 0)
{
PPCInterpreterFull_executeInstruction(hCPU);
};
}
}
assert_dbg();
}
| 6,593
|
C++
|
.cpp
| 222
| 27.238739
| 129
| 0.754687
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,190
|
PPCScheduler.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/PPCScheduler.cpp
|
#include "Cafe/OS/libs/gx2/GX2.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/OS/libs/coreinit/coreinit_Alarm.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/HW/Latte/Core/LattePerformanceMonitor.h"
#include "Cafe/HW/Espresso/Recompiler/PPCRecompiler.h"
#include "Cafe/CafeSystem.h"
uint32 ppcThreadQuantum = 45000; // execute 45000 instructions before thread reschedule happens, this value can be overwritten by game profiles
void PPCInterpreter_relinquishTimeslice()
{
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
if( hCPU->remainingCycles >= 0 )
{
hCPU->skippedCycles = hCPU->remainingCycles + 1;
hCPU->remainingCycles = -1;
}
}
void PPCCore_boostQuantum(sint32 numCycles)
{
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
hCPU->remainingCycles += numCycles;
}
void PPCCore_deboostQuantum(sint32 numCycles)
{
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
hCPU->remainingCycles -= numCycles;
}
namespace coreinit
{
void __OSThreadSwitchToNext();
}
void PPCCore_switchToScheduler()
{
cemu_assert_debug(__OSHasSchedulerLock() == false); // scheduler lock must not be hold past thread time slice
cemu_assert_debug(PPCInterpreter_getCurrentInstance()->coreInterruptMask != 0 || CafeSystem::GetForegroundTitleId() == 0x000500001019e600);
__OSLockScheduler();
coreinit::__OSThreadSwitchToNext();
__OSUnlockScheduler();
}
void PPCCore_switchToSchedulerWithLock()
{
cemu_assert_debug(__OSHasSchedulerLock() == true); // scheduler lock must be hold
cemu_assert_debug(PPCInterpreter_getCurrentInstance()->coreInterruptMask != 0 || CafeSystem::GetForegroundTitleId() == 0x000500001019e600);
coreinit::__OSThreadSwitchToNext();
}
void _PPCCore_callbackExit(PPCInterpreter_t* hCPU)
{
PPCInterpreter_relinquishTimeslice();
hCPU->instructionPointer = 0;
}
PPCInterpreter_t* PPCCore_executeCallbackInternal(uint32 functionMPTR)
{
cemu_assert_debug(functionMPTR != 0);
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
// remember LR and instruction pointer
uint32 lr = hCPU->spr.LR;
uint32 ip = hCPU->instructionPointer;
// save area
hCPU->gpr[1] -= 16 * 4;
// set LR
hCPU->spr.LR = PPCInterpreter_makeCallableExportDepr(_PPCCore_callbackExit);
// set instruction pointer
hCPU->instructionPointer = functionMPTR;
// execute code until we return from the function
while (true)
{
hCPU->remainingCycles = ppcThreadQuantum;
hCPU->skippedCycles = 0;
if (hCPU->remainingCycles > 0)
{
// try to enter recompiler immediately
PPCRecompiler_attemptEnter(hCPU, hCPU->instructionPointer);
// execute any remaining instructions in interpreter
while ((--hCPU->remainingCycles) >= 0)
{
PPCInterpreterSlim_executeInstruction(hCPU);
};
}
if (hCPU->instructionPointer == 0)
{
// restore remaining cycles
hCPU->remainingCycles += hCPU->skippedCycles;
hCPU->skippedCycles = 0;
break;
}
coreinit::OSYieldThread();
}
// save area
hCPU->gpr[1] += 16 * 4;
// restore LR and instruction pointer
hCPU->spr.LR = lr;
hCPU->instructionPointer = ip;
return hCPU;
}
void PPCCore_init()
{
}
| 3,141
|
C++
|
.cpp
| 97
| 30.278351
| 143
| 0.771184
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,191
|
PPCInterpreterFPU.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/Interpreter/PPCInterpreterFPU.cpp
|
#include "../PPCState.h"
#include "PPCInterpreterInternal.h"
#include "PPCInterpreterHelper.h"
#include<math.h>
// floating point utility
#include <limits>
#include <array>
const int ieee_double_e_bits = 11; // exponent bits
const int ieee_double_m_bits = 52; // mantissa bits
const int espresso_frsqrte_i_bits = 5; // index bits (the highest bit is the LSB of the exponent)
typedef struct
{
uint32 offset;
uint32 step;
}espresso_frsqrte_entry_t;
espresso_frsqrte_entry_t frsqrteLookupTable[32] =
{
{0x1a7e800, 0x568},{0x17cb800, 0x4f3},{0x1552800, 0x48d},{0x130c000, 0x435},
{0x10f2000, 0x3e7},{0xeff000, 0x3a2},{0xd2e000, 0x365},{0xb7c000, 0x32e},
{0x9e5000, 0x2fc},{0x867000, 0x2d0},{0x6ff000, 0x2a8},{0x5ab800, 0x283},
{0x46a000, 0x261},{0x339800, 0x243},{0x218800, 0x226},{0x105800, 0x20b},
{0x3ffa000, 0x7a4},{0x3c29000, 0x700},{0x38aa000, 0x670},{0x3572000, 0x5f2},
{0x3279000, 0x584},{0x2fb7000, 0x524},{0x2d26000, 0x4cc},{0x2ac0000, 0x47e},
{0x2881000, 0x43a},{0x2665000, 0x3fa},{0x2468000, 0x3c2},{0x2287000, 0x38e},
{0x20c1000, 0x35e},{0x1f12000, 0x332},{0x1d79000, 0x30a},{0x1bf4000, 0x2e6},
};
double frsqrte_espresso(double input)
{
unsigned long long x = *(unsigned long long*)&input;
// 0.0 and -0.0
if ((x << 1) == 0)
{
// result is inf or -inf
x &= ~0x7FFFFFFFFFFFFFFF;
x |= 0x7FF0000000000000;
return *(double*)&x;
}
// get exponent
uint32 e = (x >> ieee_double_m_bits) & ((1ull << ieee_double_e_bits) - 1ull);
// NaN or INF
if (e == 0x7FF)
{
if ((x&((1ull << ieee_double_m_bits) - 1)) == 0)
{
// negative INF returns +NaN
if ((sint64)x < 0)
{
x = 0x7FF8000000000000;
return *(double*)&x;
}
// positive INF returns +0.0
return 0.0;
}
// result is NaN with same sign and same mantissa (todo: verify)
return *(double*)&x;
}
// negative number (other than -0.0)
if ((sint64)x < 0)
{
// result is positive NaN
x = 0x7FF8000000000000;
return *(double*)&x;
}
// todo: handle denormals
// get index (lsb of exponent, remaining bits of mantissa)
uint32 idx = (x >> (ieee_double_m_bits - espresso_frsqrte_i_bits + 1ull))&((1 << espresso_frsqrte_i_bits) - 1);
// get step multiplier
uint32 stepMul = (x >> (ieee_double_m_bits - espresso_frsqrte_i_bits + 1 - 11))&((1 << 11) - 1);
sint32 sum = frsqrteLookupTable[idx].offset - frsqrteLookupTable[idx].step * stepMul;
e = 1023 - ((e - 1021) >> 1);
x &= ~(((1ull << ieee_double_e_bits) - 1ull) << ieee_double_m_bits);
x |= ((unsigned long long)e << ieee_double_m_bits);
x &= ~((1ull << ieee_double_m_bits) - 1ull);
x += ((unsigned long long)sum << 26ull);
return *(double*)&x;
}
const int espresso_fres_i_bits = 5; // index bits
const int espresso_fres_s_bits = 10; // step multiplier bits
typedef struct
{
uint32 offset;
uint32 step;
}espresso_fres_entry_t;
espresso_fres_entry_t fresLookupTable[32] =
{
// table calculated by fres_gen_table()
{0x7ff800, 0x3e1}, {0x783800, 0x3a7}, {0x70ea00, 0x371}, {0x6a0800, 0x340},
{0x638800, 0x313}, {0x5d6200, 0x2ea}, {0x579000, 0x2c4}, {0x520800, 0x2a0},
{0x4cc800, 0x27f}, {0x47ca00, 0x261}, {0x430800, 0x245}, {0x3e8000, 0x22a},
{0x3a2c00, 0x212}, {0x360800, 0x1fb}, {0x321400, 0x1e5}, {0x2e4a00, 0x1d1},
{0x2aa800, 0x1be}, {0x272c00, 0x1ac}, {0x23d600, 0x19b}, {0x209e00, 0x18b},
{0x1d8800, 0x17c}, {0x1a9000, 0x16e}, {0x17ae00, 0x15b}, {0x14f800, 0x15b},
{0x124400, 0x143}, {0xfbe00, 0x143}, {0xd3800, 0x12d}, {0xade00, 0x12d},
{0x88400, 0x11a}, {0x65000, 0x11a}, {0x41c00, 0x108}, {0x20c00, 0x106}
};
double fres_espresso(double input)
{
// based on testing we know that fres uses only the first 15 bits of the mantissa
// seee eeee eeee mmmm mmmm mmmm mmmx xxxx .... (s = sign, e = exponent, m = mantissa, x = not used)
// the mantissa bits are interpreted as following:
// 0000 0000 0000 iiii ifff ffff fff0 ... (i = table look up index , f = step multiplier)
unsigned long long x = *(unsigned long long*)&input;
// get index
uint32 idx = (x >> (ieee_double_m_bits - espresso_fres_i_bits))&((1 << espresso_fres_i_bits) - 1);
// get step multiplier
uint32 stepMul = (x >> (ieee_double_m_bits - espresso_fres_i_bits - 10))&((1 << 10) - 1);
uint32 sum = fresLookupTable[idx].offset - (fresLookupTable[idx].step * stepMul + 1) / 2;
// get exponent
uint32 e = (x >> ieee_double_m_bits) & ((1ull << ieee_double_e_bits) - 1ull);
if (e == 0)
{
// todo?
//x &= 0x7FFFFFFFFFFFFFFFull;
x |= 0x7FF0000000000000ull;
return *(double*)&x;
}
else if (e == 0x7ff) // NaN or INF
{
if ((x&((1ull << ieee_double_m_bits) - 1)) == 0)
{
// negative INF returns -0.0
if ((sint64)x < 0)
{
x = 0x8000000000000000;
return *(double*)&x;
}
// positive INF returns +0.0
return 0.0;
}
// result is NaN with same sign and same mantissa (todo: verify)
return *(double*)&x;
}
// todo - needs more testing (especially NaN and INF values)
e = 2045 - e;
x &= ~(((1ull << ieee_double_e_bits) - 1ull) << ieee_double_m_bits);
x |= ((unsigned long long)e << ieee_double_m_bits);
x &= ~((1ull << ieee_double_m_bits) - 1ull);
x += ((unsigned long long)sum << 29ull);
return *(double*)&x;
}
void fcmpu_espresso(PPCInterpreter_t* hCPU, int crfD, double a, double b)
{
uint32 c;
ppc_setCRBit(hCPU, crfD + 0, 0);
ppc_setCRBit(hCPU, crfD + 1, 0);
ppc_setCRBit(hCPU, crfD + 2, 0);
ppc_setCRBit(hCPU, crfD + 3, 0);
if (IS_NAN(*(uint64*)&a) || IS_NAN(*(uint64*)&b))
{
c = 1;
ppc_setCRBit(hCPU, crfD + CR_BIT_SO, 1);
}
else if (a < b)
{
c = 8;
ppc_setCRBit(hCPU, crfD + CR_BIT_LT, 1);
}
else if (a > b)
{
c = 4;
ppc_setCRBit(hCPU, crfD + CR_BIT_GT, 1);
}
else
{
c = 2;
ppc_setCRBit(hCPU, crfD + CR_BIT_EQ, 1);
}
if (IS_SNAN(*(uint64*)&a) || IS_SNAN(*(uint64*)&b))
hCPU->fpscr |= FPSCR_VXSNAN;
hCPU->fpscr = (hCPU->fpscr & 0xffff0fff) | (c << 12);
}
void PPCInterpreter_FMR(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, rA, frB;
PPC_OPC_TEMPL_X(Opcode, frD, rA, frB);
PPC_ASSERT(rA==0);
hCPU->fpr[frD].fpr = hCPU->fpr[frB].fpr;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FSEL(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
if ( hCPU->fpr[frA].fp0 >= -0.0f )
hCPU->fpr[frD] = hCPU->fpr[frC];
else
hCPU->fpr[frD] = hCPU->fpr[frB];
PPC_ASSERT((Opcode & PPC_OPC_RC) != 0); // update CR1 flags
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FCTIWZ(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB;
PPC_OPC_TEMPL_X(Opcode, frD, frA, frB);
PPC_ASSERT(frA==0);
double b = hCPU->fpr[frB].fpr;
uint64 v;
if (b > (double)0x7FFFFFFF)
{
v = (uint64)0x7FFFFFFF;
}
else if (b < -(double)0x80000000)
{
v = (uint64)0x80000000;
}
else
{
v = (uint64)(uint32)(sint32)b;
}
hCPU->fpr[frD].guint = 0xFFF8000000000000ULL | v;
if (v == 0 && ((*(uint64*)&b) >> 63))
hCPU->fpr[frD].guint |= 0x100000000ull;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FCTIW(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB;
PPC_OPC_TEMPL_X(Opcode, frD, frA, frB);
PPC_ASSERT(frA==0);
double b = hCPU->fpr[frB].fpr;
uint64 v;
if (b > (double)0x7FFFFFFF)
{
v = (uint64)0x7FFFFFFF;
}
else if (b < -(double)0x80000000)
{
v = (uint64)0x80000000;
}
else
{
// todo: Support for other rounding modes than NEAR
double t = b + 0.5;
sint32 i = (sint32)t;
if (t - i < 0 || (t - i == 0 && b > 0))
{
i--;
}
v = (uint64)i;
}
hCPU->fpr[frD].guint = 0xFFF8000000000000ULL | v;
if (v == 0 && ((*(uint64*)&b) >> 63))
hCPU->fpr[frD].guint |= 0x100000000ull;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FNEG(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB;
PPC_OPC_TEMPL_X(Opcode, frD, frA, frB);
PPC_ASSERT(frA==0);
hCPU->fpr[frD].guint = hCPU->fpr[frB].guint ^ (1ULL << 63);
PPC_ASSERT((Opcode & PPC_OPC_RC) != 0); // update CR1 flags
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FRSP(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB;
PPC_OPC_TEMPL_X(Opcode, frD, frA, frB);
PPC_ASSERT(frA==0);
if( PPC_PSE )
{
hCPU->fpr[frD].fp0 = (float)hCPU->fpr[frB].fpr;
hCPU->fpr[frD].fp1 = hCPU->fpr[frD].fp0;
}
else
{
hCPU->fpr[frD].fpr = (float)hCPU->fpr[frB].fpr;
}
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FRSQRTE(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
PPC_ASSERT(frA==0 && frC==0);
hCPU->fpr[frD].fpr = frsqrte_espresso(hCPU->fpr[frB].fpr);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FRES(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
PPC_ASSERT(frA==0 && frC==0);
hCPU->fpr[frD].fpr = fres_espresso(hCPU->fpr[frB].fpr);
if(PPC_PSE)
hCPU->fpr[frD].fp1 = hCPU->fpr[frD].fp0;
PPCInterpreter_nextInstruction(hCPU);
}
// Floating point ALU
void PPCInterpreter_FABS(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB;
PPC_OPC_TEMPL_X(Opcode, frD, frA, frB);
PPC_ASSERT(frA==0);
hCPU->fpr[frD].guint = hCPU->fpr[frB].guint & ~0x8000000000000000;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FNABS(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB;
PPC_OPC_TEMPL_X(Opcode, frD, frA, frB);
PPC_ASSERT(frA==0);
hCPU->fpr[frD].guint = hCPU->fpr[frB].guint | 0x8000000000000000;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FADD(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
PPC_ASSERT(frC==0);
hCPU->fpr[frD].fpr = hCPU->fpr[frA].fpr + hCPU->fpr[frB].fpr;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FDIV(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
PPC_ASSERT(frC==0);
hCPU->fpr[frD].fpr = hCPU->fpr[frA].fpr / hCPU->fpr[frB].fpr;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FSUB(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
PPC_ASSERT(frC==0);
hCPU->fpr[frD].fpr = hCPU->fpr[frA].fpr - hCPU->fpr[frB].fpr;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FMUL(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
PPC_ASSERT(frC == 0);
hCPU->fpr[frD].fpr = hCPU->fpr[frA].fpr * hCPU->fpr[frC].fpr;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FMADD(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
hCPU->fpr[frD].fpr = hCPU->fpr[frA].fpr * hCPU->fpr[frC].fpr + hCPU->fpr[frB].fpr;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FNMADD(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
hCPU->fpr[frD].fpr = -(hCPU->fpr[frA].fpr * hCPU->fpr[frC].fpr + hCPU->fpr[frB].fpr);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FMSUB(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
hCPU->fpr[frD].fpr = (hCPU->fpr[frA].fpr * hCPU->fpr[frC].fpr - hCPU->fpr[frB].fpr);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FNMSUB(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
hCPU->fpr[frD].fpr = -(hCPU->fpr[frA].fpr * hCPU->fpr[frC].fpr - hCPU->fpr[frB].fpr);
PPCInterpreter_nextInstruction(hCPU);
}
// Move
void PPCInterpreter_MFFS(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, rA, rB;
PPC_OPC_TEMPL_X(Opcode, frD, rA, rB);
PPC_ASSERT(rA==0 && rB==0);
hCPU->fpr[frD].guint = (uint64)hCPU->fpscr;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_MTFSF(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frB;
uint32 fm, FM;
PPC_OPC_TEMPL_XFL(Opcode, frB, fm);
FM = ((fm&0x80)?0xf0000000:0)|((fm&0x40)?0x0f000000:0)|((fm&0x20)?0x00f00000:0)|((fm&0x10)?0x000f0000:0)|
((fm&0x08)?0x0000f000:0)|((fm&0x04)?0x00000f00:0)|((fm&0x02)?0x000000f0:0)|((fm&0x01)?0x0000000f:0);
hCPU->fpscr = (hCPU->fpr[frB].guint & FM) | (hCPU->fpscr & ~FM);
PPC_ASSERT((Opcode & PPC_OPC_RC) != 0); // update CR1 flags
static bool logFPSCRWriteOnce = false;
if( logFPSCRWriteOnce == false )
{
cemuLog_log(LogType::Force, "Unsupported write to FPSCR");
logFPSCRWriteOnce = true;
}
PPCInterpreter_nextInstruction(hCPU);
}
// single precision
void PPCInterpreter_FADDS(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
PPC_ASSERT(frB == 0);
// todo: check for RC
hCPU->fpr[frD].fpr = (float)(hCPU->fpr[frA].fpr + hCPU->fpr[frB].fpr);
if (PPC_PSE)
hCPU->fpr[frD].fp1 = hCPU->fpr[frD].fp0;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FSUBS(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
PPC_ASSERT(frB == 0);
hCPU->fpr[frD].fpr = (float)(hCPU->fpr[frA].fpr - hCPU->fpr[frB].fpr);
if (PPC_PSE)
hCPU->fpr[frD].fp1 = hCPU->fpr[frD].fp0;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FDIVS(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
PPC_ASSERT(frB==0);
hCPU->fpr[frD].fpr = (float)(hCPU->fpr[frA].fpr / hCPU->fpr[frB].fpr);
if( PPC_PSE )
hCPU->fpr[frD].fp1 = hCPU->fpr[frD].fp0;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FMULS(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
PPC_ASSERT(frB == 0);
hCPU->fpr[frD].fpr = (float)(hCPU->fpr[frA].fpr * roundTo25BitAccuracy(hCPU->fpr[frC].fpr));
if (PPC_PSE)
hCPU->fpr[frD].fp1 = hCPU->fpr[frD].fp0;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FMADDS(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
hCPU->fpr[frD].fpr = (float)(hCPU->fpr[frA].fpr * roundTo25BitAccuracy(hCPU->fpr[frC].fpr) + hCPU->fpr[frB].fpr);
if (PPC_PSE)
hCPU->fpr[frD].fp1 = hCPU->fpr[frD].fp0;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FNMADDS(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
hCPU->fpr[frD].fpr = (float)-(hCPU->fpr[frA].fpr * roundTo25BitAccuracy(hCPU->fpr[frC].fpr) + hCPU->fpr[frB].fpr);
if (PPC_PSE)
hCPU->fpr[frD].fp1 = hCPU->fpr[frD].fp0;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FMSUBS(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
hCPU->fpr[frD].fp0 = (float)(hCPU->fpr[frA].fp0 * roundTo25BitAccuracy(hCPU->fpr[frC].fp0) - hCPU->fpr[frB].fp0);
if (PPC_PSE)
hCPU->fpr[frD].fp1 = hCPU->fpr[frD].fp0;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FNMSUBS(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int frD, frA, frB, frC;
PPC_OPC_TEMPL_A(Opcode, frD, frA, frB, frC);
hCPU->fpr[frD].fp0 = (float)-(hCPU->fpr[frA].fp0 * roundTo25BitAccuracy(hCPU->fpr[frC].fp0) - hCPU->fpr[frB].fp0);
if (PPC_PSE)
hCPU->fpr[frD].fp1 = hCPU->fpr[frD].fp0;
PPCInterpreter_nextInstruction(hCPU);
}
// Compare
void PPCInterpreter_FCMPO(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int crfD, frA, frB;
PPC_OPC_TEMPL_X(Opcode, crfD, frA, frB);
crfD >>= 2;
hCPU->cr[crfD*4+0] = 0;
hCPU->cr[crfD*4+1] = 0;
hCPU->cr[crfD*4+2] = 0;
hCPU->cr[crfD*4+3] = 0;
uint32 c;
if(IS_NAN(hCPU->fpr[frA].guint) || IS_NAN(hCPU->fpr[frB].guint))
{
c = 1;
hCPU->cr[crfD*4+CR_BIT_SO] = 1;
}
else if(hCPU->fpr[frA].fpr < hCPU->fpr[frB].fpr)
{
c = 8;
hCPU->cr[crfD*4+CR_BIT_LT] = 1;
}
else if(hCPU->fpr[frA].fpr > hCPU->fpr[frB].fpr)
{
c = 4;
hCPU->cr[crfD*4+CR_BIT_GT] = 1;
}
else
{
c = 2;
hCPU->cr[crfD*4+CR_BIT_EQ] = 1;
}
hCPU->fpscr = (hCPU->fpscr & 0xffff0fff) | (c << 12);
if (IS_SNAN (hCPU->fpr[frA].guint) || IS_SNAN (hCPU->fpr[frB].guint))
hCPU->fpscr |= FPSCR_VXSNAN;
else if (!(hCPU->fpscr & FPSCR_VE) || IS_QNAN (hCPU->fpr[frA].guint) || IS_QNAN (hCPU->fpr[frB].guint))
hCPU->fpscr |= FPSCR_VXVC;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_FCMPU(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
int crfD, frA, frB;
PPC_OPC_TEMPL_X(Opcode, crfD, frA, frB);
cemu_assert_debug((crfD % 4) == 0);
fcmpu_espresso(hCPU, crfD, hCPU->fpr[frA].fp0, hCPU->fpr[frB].fp0);
PPCInterpreter_nextInstruction(hCPU);
}
| 17,323
|
C++
|
.cpp
| 545
| 29.499083
| 115
| 0.686187
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,192
|
PPCInterpreterHLE.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/Interpreter/PPCInterpreterHLE.cpp
|
#include "../PPCState.h"
#include "PPCInterpreterInternal.h"
#include "PPCInterpreterHelper.h"
std::unordered_set<std::string> sUnsupportedHLECalls;
void PPCInterpreter_handleUnsupportedHLECall(PPCInterpreter_t* hCPU)
{
const char* libFuncName = (char*)memory_getPointerFromVirtualOffset(hCPU->instructionPointer + 8);
std::string tempString = fmt::format("Unsupported lib call: {}", libFuncName);
if (sUnsupportedHLECalls.find(tempString) == sUnsupportedHLECalls.end())
{
cemuLog_log(LogType::UnsupportedAPI, "{}", tempString);
sUnsupportedHLECalls.emplace(tempString);
}
hCPU->gpr[3] = 0;
PPCInterpreter_nextInstruction(hCPU);
}
std::vector<void(*)(PPCInterpreter_t* hCPU)>* sPPCHLETable{};
HLEIDX PPCInterpreter_registerHLECall(HLECALL hleCall, std::string hleName)
{
if (!sPPCHLETable)
sPPCHLETable = new std::vector<void(*)(PPCInterpreter_t* hCPU)>();
for (sint32 i = 0; i < sPPCHLETable->size(); i++)
{
if ((*sPPCHLETable)[i] == hleCall)
return i;
}
HLEIDX newFuncIndex = (sint32)sPPCHLETable->size();
sPPCHLETable->resize(sPPCHLETable->size() + 1);
(*sPPCHLETable)[newFuncIndex] = hleCall;
return newFuncIndex;
}
HLECALL PPCInterpreter_getHLECall(HLEIDX funcIndex)
{
if (funcIndex < 0 || funcIndex >= sPPCHLETable->size())
return nullptr;
return sPPCHLETable->data()[funcIndex];
}
std::mutex g_hleLogMutex;
void PPCInterpreter_virtualHLE(PPCInterpreter_t* hCPU, unsigned int opcode)
{
uint32 hleFuncId = opcode & 0xFFFF;
if (hleFuncId == 0xFFD0)
{
g_hleLogMutex.lock();
PPCInterpreter_handleUnsupportedHLECall(hCPU);
g_hleLogMutex.unlock();
return;
}
else
{
// os lib function
cemu_assert(hleFuncId < sPPCHLETable->size());
auto hleCall = (*sPPCHLETable)[hleFuncId];
cemu_assert(hleCall);
hleCall(hCPU);
}
}
| 1,776
|
C++
|
.cpp
| 57
| 29.087719
| 99
| 0.756567
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,193
|
PPCInterpreterMain.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/Interpreter/PPCInterpreterMain.cpp
|
#include "PPCInterpreterInternal.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/GameProfile/GameProfile.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
thread_local PPCInterpreter_t* ppcInterpreterCurrentInstance;
// main thread instruction counter and timing
uint64 ppcMainThreadDECCycleValue = 0; // value that was set to dec register
uint64 ppcMainThreadDECCycleStart = 0; // at which cycle the dec register was set, if == 0 -> dec is 0
uint64 ppcCyclesSince2000 = 0;
uint64 ppcCyclesSince2000TimerClock = 0;
uint64 ppcCyclesSince2000_UTC = 0;
PPCInterpreter_t* PPCInterpreter_createInstance(unsigned int Entrypoint)
{
PPCInterpreter_t* pData;
// create instance
uint32 prefixAreaSize = 0x6000; // we need to allocate some bytes before the interpreter struct because the recompiler will use it as stack area (specifically when the exception handler is called)
pData = (PPCInterpreter_t*)((uint8*)malloc(sizeof(PPCInterpreter_t)+prefixAreaSize)+prefixAreaSize);
memset((void*)pData, 0x00, sizeof(PPCInterpreter_t));
// set instruction pointer to entrypoint
pData->instructionPointer = (uint32)Entrypoint;
// set initial register values
pData->gpr[GPR_SP] = 0x00000000;
pData->spr.LR = 0;
// return instance
return pData;
}
TLS_WORKAROUND_NOINLINE PPCInterpreter_t* PPCInterpreter_getCurrentInstance()
{
return ppcInterpreterCurrentInstance;
}
TLS_WORKAROUND_NOINLINE void PPCInterpreter_setCurrentInstance(PPCInterpreter_t* hCPU)
{
ppcInterpreterCurrentInstance = hCPU;
}
uint64 PPCInterpreter_getMainCoreCycleCounter()
{
return PPCTimer_getFromRDTSC();
}
void PPCInterpreter_nextInstruction(PPCInterpreter_t* cpuInterpreter)
{
cpuInterpreter->instructionPointer += 4;
}
void PPCInterpreter_jumpToInstruction(PPCInterpreter_t* cpuInterpreter, uint32 newIP)
{
cpuInterpreter->instructionPointer = (uint32)newIP;
}
void PPCInterpreter_setDEC(PPCInterpreter_t* hCPU, uint32 newValue)
{
hCPU->sprExtended.DEC = newValue;
ppcMainThreadDECCycleStart = PPCInterpreter_getMainCoreCycleCounter();
ppcMainThreadDECCycleValue = newValue;
}
uint32 PPCInterpreter_getXER(PPCInterpreter_t* hCPU)
{
uint32 xerValue = hCPU->spr.XER;
xerValue &= ~(1<<XER_BIT_CA);
if( hCPU->xer_ca )
xerValue |= (1<<XER_BIT_CA);
return xerValue;
}
void PPCInterpreter_setXER(PPCInterpreter_t* hCPU, uint32 v)
{
hCPU->spr.XER = v;
hCPU->xer_ca = (v>>XER_BIT_CA)&1;
}
uint32 PPCInterpreter_getCoreIndex(PPCInterpreter_t* hCPU)
{
return hCPU->spr.UPIR;
};
uint32 PPCInterpreter_getCurrentCoreIndex()
{
return PPCInterpreter_getCurrentInstance()->spr.UPIR;
};
uint8* PPCInterpreterGetStackPointer()
{
return memory_getPointerFromVirtualOffset(PPCInterpreter_getCurrentInstance()->gpr[1]);
}
uint8* PPCInterpreter_PushAndReturnStackPointer(sint32 offset)
{
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
uint8* result = memory_getPointerFromVirtualOffset(hCPU->gpr[1] - offset);
hCPU->gpr[1] -= offset;
return result;
}
void PPCInterpreterModifyStackPointer(sint32 offset)
{
PPCInterpreter_getCurrentInstance()->gpr[1] -= offset;
}
uint32 RPLLoader_MakePPCCallable(void(*ppcCallableExport)(PPCInterpreter_t* hCPU));
// deprecated wrapper, use RPLLoader_MakePPCCallable directly
uint32 PPCInterpreter_makeCallableExportDepr(void (*ppcCallableExport)(PPCInterpreter_t* hCPU))
{
return RPLLoader_MakePPCCallable(ppcCallableExport);
}
| 3,367
|
C++
|
.cpp
| 94
| 34.234043
| 197
| 0.812596
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,194
|
PPCInterpreterPS.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/Interpreter/PPCInterpreterPS.cpp
|
#include "PPCInterpreterInternal.h"
// Gekko paired single math
void PPCInterpreter_PS_ADD(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
hCPU->fpr[frD].fp0 = (float)(hCPU->fpr[frA].fp0 + hCPU->fpr[frB].fp0);
hCPU->fpr[frD].fp1 = (float)(hCPU->fpr[frA].fp1 + hCPU->fpr[frB].fp1);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_SUB(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
hCPU->fpr[frD].fp0 = (float)(hCPU->fpr[frA].fp0 - hCPU->fpr[frB].fp0);
hCPU->fpr[frD].fp1 = (float)(hCPU->fpr[frA].fp1 - hCPU->fpr[frB].fp1);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_MUL(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frC;
frC = (Opcode>>6)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
hCPU->fpr[frD].fp0 = flushDenormalToZero((float)(hCPU->fpr[frA].fp0 * roundTo25BitAccuracy(hCPU->fpr[frC].fp0)));
hCPU->fpr[frD].fp1 = flushDenormalToZero((float)(hCPU->fpr[frA].fp1 * roundTo25BitAccuracy(hCPU->fpr[frC].fp1)));
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_DIV(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
hCPU->fpr[frD].fp0 = (float)(hCPU->fpr[frA].fp0 / hCPU->fpr[frB].fp0);
hCPU->fpr[frD].fp1 = (float)(hCPU->fpr[frA].fp1 / hCPU->fpr[frB].fp1);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_MADD(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB, frC;
frC = (Opcode>>6)&0x1F;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
float s0 = (float)((float)(hCPU->fpr[frA].fp0 * roundTo25BitAccuracy(hCPU->fpr[frC].fp0)) + hCPU->fpr[frB].fp0);
float s1 = (float)((float)(hCPU->fpr[frA].fp1 * roundTo25BitAccuracy(hCPU->fpr[frC].fp1)) + hCPU->fpr[frB].fp1);
hCPU->fpr[frD].fp0 = flushDenormalToZero(s0);
hCPU->fpr[frD].fp1 = flushDenormalToZero(s1);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_NMADD(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB, frC;
frC = (Opcode>>6)&0x1F;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
float s0 = (float)-(hCPU->fpr[frA].fp0 * roundTo25BitAccuracy(hCPU->fpr[frC].fp0) + hCPU->fpr[frB].fp0);
float s1 = (float)-(hCPU->fpr[frA].fp1 * roundTo25BitAccuracy(hCPU->fpr[frC].fp1) + hCPU->fpr[frB].fp1);
hCPU->fpr[frD].fp0 = s0;
hCPU->fpr[frD].fp1 = s1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_MSUB(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB, frC;
frC = (Opcode >> 6) & 0x1F;
frB = (Opcode >> 11) & 0x1F;
frA = (Opcode >> 16) & 0x1F;
frD = (Opcode >> 21) & 0x1F;
float s0 = (float)(hCPU->fpr[frA].fp0 * roundTo25BitAccuracy(hCPU->fpr[frC].fp0) - hCPU->fpr[frB].fp0);
float s1 = (float)(hCPU->fpr[frA].fp1 * roundTo25BitAccuracy(hCPU->fpr[frC].fp1) - hCPU->fpr[frB].fp1);
hCPU->fpr[frD].fp0 = s0;
hCPU->fpr[frD].fp1 = s1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_NMSUB(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB, frC;
frC = (Opcode >> 6) & 0x1F;
frB = (Opcode >> 11) & 0x1F;
frA = (Opcode >> 16) & 0x1F;
frD = (Opcode >> 21) & 0x1F;
float s0 = (float)-(hCPU->fpr[frA].fp0 * roundTo25BitAccuracy(hCPU->fpr[frC].fp0) - hCPU->fpr[frB].fp0);
float s1 = (float)-(hCPU->fpr[frA].fp1 * roundTo25BitAccuracy(hCPU->fpr[frC].fp1) - hCPU->fpr[frB].fp1);
hCPU->fpr[frD].fp0 = s0;
hCPU->fpr[frD].fp1 = s1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_MADDS0(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB, frC;
frC = (Opcode>>6)&0x1F;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
double c = roundTo25BitAccuracy(hCPU->fpr[frC].fp0);
float s0 = (float)(hCPU->fpr[frA].fp0 * c + hCPU->fpr[frB].fp0);
float s1 = (float)(hCPU->fpr[frA].fp1 * c + hCPU->fpr[frB].fp1);
hCPU->fpr[frD].fp0 = s0;
hCPU->fpr[frD].fp1 = s1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_MADDS1(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB, frC;
frC = (Opcode>>6)&0x1F;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
double c = roundTo25BitAccuracy(hCPU->fpr[frC].fp1);
float s0 = (float)(hCPU->fpr[frA].fp0 * c + hCPU->fpr[frB].fp0);
float s1 = (float)(hCPU->fpr[frA].fp1 * c + hCPU->fpr[frB].fp1);
hCPU->fpr[frD].fp0 = s0;
hCPU->fpr[frD].fp1 = s1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_SEL(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB, frC;
frC = (Opcode>>6)&0x1F;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
if( hCPU->fpr[frA].fp0 >= -0.0f )
hCPU->fpr[frD].fp0 = hCPU->fpr[frC].fp0;
else
hCPU->fpr[frD].fp0 = hCPU->fpr[frB].fp0;
if( hCPU->fpr[frA].fp1 >= -0.0f )
hCPU->fpr[frD].fp1 = hCPU->fpr[frC].fp1;
else
hCPU->fpr[frD].fp1 = hCPU->fpr[frB].fp1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_SUM0(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB, frC;
frC = (Opcode>>6)&0x1F;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
float s0 = (float)(hCPU->fpr[frA].fp0 + hCPU->fpr[frB].fp1);
float s1 = (float)hCPU->fpr[frC].fp1;
hCPU->fpr[frD].fp0 = s0;
hCPU->fpr[frD].fp1 = s1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_SUM1(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB, frC;
frC = (Opcode>>6)&0x1F;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
float s0 = (float)hCPU->fpr[frC].fp0;
float s1 = (float)(hCPU->fpr[frA].fp0 + hCPU->fpr[frB].fp1);
hCPU->fpr[frD].fp0 = s0;
hCPU->fpr[frD].fp1 = s1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_MULS0(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frC;
frC = (Opcode>>6)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
double c = roundTo25BitAccuracy(hCPU->fpr[frC].fp0);
float s0 = (float)(hCPU->fpr[frA].fp0 * c);
float s1 = (float)(hCPU->fpr[frA].fp1 * c);
hCPU->fpr[frD].fp0 = s0;
hCPU->fpr[frD].fp1 = s1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_MULS1(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frC;
frC = (Opcode>>6)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
double c = roundTo25BitAccuracy(hCPU->fpr[frC].fp1);
float s0 = (float)(hCPU->fpr[frA].fp0 * c);
float s1 = (float)(hCPU->fpr[frA].fp1 * c);
hCPU->fpr[frD].fp0 = s0;
hCPU->fpr[frD].fp1 = s1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_MR(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frB;
frB = (Opcode>>11)&0x1F;
frD = (Opcode>>21)&0x1F;
hCPU->fpr[frD].fp0 = hCPU->fpr[frB].fp0;
hCPU->fpr[frD].fp1 = hCPU->fpr[frB].fp1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_NEG(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frB;
frB = (Opcode>>11)&0x1F;
frD = (Opcode>>21)&0x1F;
hCPU->fpr[frD].fp0 = -hCPU->fpr[frB].fp0;
hCPU->fpr[frD].fp1 = -hCPU->fpr[frB].fp1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_ABS(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frB;
frB = (Opcode>>11)&0x1F;
frD = (Opcode>>21)&0x1F;
hCPU->fpr[frD].fp0int = hCPU->fpr[frB].fp0int & ~(1ULL << 63);
hCPU->fpr[frD].fp1int = hCPU->fpr[frB].fp1int & ~(1ULL << 63);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_NABS(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frB;
frB = (Opcode>>11)&0x1F;
frD = (Opcode>>21)&0x1F;
hCPU->fpr[frD].fp0int = hCPU->fpr[frB].fp0int | (1ULL << 63);
hCPU->fpr[frD].fp1int = hCPU->fpr[frB].fp1int | (1ULL << 63);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_RSQRTE(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frB;
frB = (Opcode>>11)&0x1F;
frD = (Opcode>>21)&0x1F;
hCPU->fpr[frD].fp0 = (float)frsqrte_espresso(hCPU->fpr[frB].fp0);
hCPU->fpr[frD].fp1 = (float)frsqrte_espresso(hCPU->fpr[frB].fp1);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_MERGE00(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
double s0 = hCPU->fpr[frA].fp0;
double s1 = hCPU->fpr[frB].fp0;
hCPU->fpr[frD].fp0 = s0;
hCPU->fpr[frD].fp1 = s1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_MERGE01(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
double s0 = hCPU->fpr[frA].fp0;
double s1 = hCPU->fpr[frB].fp1;
hCPU->fpr[frD].fp0 = s0;
hCPU->fpr[frD].fp1 = s1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_MERGE10(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
double s0 = hCPU->fpr[frA].fp1;
double s1 = hCPU->fpr[frB].fp0;
hCPU->fpr[frD].fp0 = s0;
hCPU->fpr[frD].fp1 = s1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_MERGE11(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frA, frB;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
frD = (Opcode>>21)&0x1F;
double s0 = hCPU->fpr[frA].fp1;
double s1 = hCPU->fpr[frB].fp1;
hCPU->fpr[frD].fp0 = s0;
hCPU->fpr[frD].fp1 = s1;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_RES(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 frD, frB;
frB = (Opcode>>11)&0x1F;
frD = (Opcode>>21)&0x1F;
hCPU->fpr[frD].fp0 = (float)fres_espresso(hCPU->fpr[frB].fp0);
hCPU->fpr[frD].fp1 = (float)fres_espresso(hCPU->fpr[frB].fp1);
PPCInterpreter_nextInstruction(hCPU);
}
// PS compare
void PPCInterpreter_PS_CMPO0(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 crfD, frA, frB;
uint32 c=0;
frB = (Opcode>>11)&0x1F;
frA = (Opcode>>16)&0x1F;
crfD = (Opcode>>23)&0x7;
double a = hCPU->fpr[frA].fp0;
double b = hCPU->fpr[frB].fp0;
ppc_setCRBit(hCPU, crfD*4+0, 0);
ppc_setCRBit(hCPU, crfD*4+1, 0);
ppc_setCRBit(hCPU, crfD*4+2, 0);
ppc_setCRBit(hCPU, crfD*4+3, 0);
if(IS_NAN(*(uint64*)&a) || IS_NAN(*(uint64*)&b))
{
c = 1;
ppc_setCRBit(hCPU, crfD*4+CR_BIT_SO, 1);
}
else if(a < b)
{
c = 8;
ppc_setCRBit(hCPU, crfD*4+CR_BIT_LT, 1);
}
else if(a > b)
{
c = 4;
ppc_setCRBit(hCPU, crfD*4+CR_BIT_GT, 1);
}
else
{
c = 2;
ppc_setCRBit(hCPU, crfD*4+CR_BIT_EQ, 1);
}
hCPU->fpscr = (hCPU->fpscr & 0xffff0fff) | (c << 12);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_CMPU0(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 crfD, frA, frB;
frB = (Opcode >> 11) & 0x1F;
frA = (Opcode >> 16) & 0x1F;
crfD = (Opcode >> 21) & (0x7<<2);
fcmpu_espresso(hCPU, crfD, hCPU->fpr[frA].fp0, hCPU->fpr[frB].fp0);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_PS_CMPU1(PPCInterpreter_t* hCPU, uint32 Opcode)
{
FPUCheckAvailable();
sint32 crfD, frA, frB;
frB = (Opcode >> 11) & 0x1F;
frA = (Opcode >> 16) & 0x1F;
crfD = (Opcode >> 21) & (0x7 << 2);
double a = hCPU->fpr[frA].fp1;
double b = hCPU->fpr[frB].fp1;
fcmpu_espresso(hCPU, crfD, hCPU->fpr[frA].fp1, hCPU->fpr[frB].fp1);
PPCInterpreter_nextInstruction(hCPU);
}
| 12,071
|
C++
|
.cpp
| 378
| 29.730159
| 114
| 0.690608
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,195
|
PPCInterpreterOPC.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/Interpreter/PPCInterpreterOPC.cpp
|
#include "../PPCState.h"
#include "PPCInterpreterInternal.h"
#include "PPCInterpreterHelper.h"
#include "Cafe/OS/libs/coreinit/coreinit_CodeGen.h"
#include "../Recompiler/PPCRecompiler.h"
#include "../Recompiler/PPCRecompilerX64.h"
#include <float.h>
#include "Cafe/HW/Latte/Core/LatteBufferCache.h"
void PPCInterpreter_MFMSR(PPCInterpreter_t* hCPU, uint32 Opcode)
{
cemuLog_logDebug(LogType::Force, "Rare instruction: MFMSR");
if (hCPU->sprExtended.msr & MSR_PR)
{
PPC_ASSERT(true);
return;
}
int rD, rA, rB;
PPC_OPC_TEMPL_X(Opcode, rD, rA, rB);
hCPU->gpr[rD] = hCPU->sprExtended.msr;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_MTMSR(PPCInterpreter_t* hCPU, uint32 Opcode)
{
cemuLog_logDebug(LogType::Force, "Rare instruction: MTMSR");
if (hCPU->sprExtended.msr & MSR_PR)
{
PPC_ASSERT(true);
return;
}
int rS, rA, rB;
PPC_OPC_TEMPL_X(Opcode, rS, rA, rB);
hCPU->sprExtended.msr = hCPU->gpr[rS];
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_MTFSB1X(PPCInterpreter_t* hCPU, uint32 Opcode)
{
cemuLog_logDebug(LogType::Force, "Rare instruction: MTFSB1X");
int crbD, n1, n2;
PPC_OPC_TEMPL_X(Opcode, crbD, n1, n2);
if (crbD != 1 && crbD != 2)
{
hCPU->fpscr |= 1 << (31 - crbD);
}
if (Opcode & PPC_OPC_RC)
{
// update cr1 flags
PPC_ASSERT(true);
}
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_MCRF(PPCInterpreter_t* hCPU, uint32 Opcode)
{
uint32 crD, crS, b;
PPC_OPC_TEMPL_X(Opcode, crD, crS, b);
crD >>= 2;
crS >>= 2;
for (sint32 i = 0; i<4; i++)
ppc_setCRBit(hCPU, crD * 4 + i, ppc_getCRBit(hCPU, crS * 4 + i));
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_MFCR(PPCInterpreter_t* hCPU, uint32 Opcode)
{
// frequently used by GCC compiled code (e.g. SM64 port)
int rD, rA, rB;
PPC_OPC_TEMPL_X(Opcode, rD, rA, rB);
// in our array: cr0.LT is entry with index 0
// in GPR: cr0.LT is in MSB
uint32 cr = 0;
for (sint32 i = 0; i < 32; i++)
{
cr <<= 1;
if (ppc_getCRBit(hCPU, i) != 0)
cr |= 1;
}
hCPU->gpr[rD] = cr;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_MTCRF(PPCInterpreter_t* hCPU, uint32 Opcode)
{
// frequently used by GCC compiled code (e.g. SM64 port)
// tested
uint32 rS;
uint32 crfMask;
PPC_OPC_TEMPL_XFX(Opcode, rS, crfMask);
for (sint32 crIndex = 0; crIndex < 8; crIndex++)
{
if (!ppc_MTCRFMaskHasCRFieldSet(crfMask, crIndex))
continue;
uint32 crBitBase = crIndex * 4;
uint8 nibble = (uint8)(hCPU->gpr[rS] >> (28 - crIndex * 4));
ppc_setCRBit(hCPU, crBitBase + 0, (nibble >> 3) & 1);
ppc_setCRBit(hCPU, crBitBase + 1, (nibble >> 2) & 1);
ppc_setCRBit(hCPU, crBitBase + 2, (nibble >> 1) & 1);
ppc_setCRBit(hCPU, crBitBase + 3, (nibble >> 0) & 1);
}
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_MCRXR(PPCInterpreter_t* hCPU, uint32 Opcode)
{
// used in Dont Starve: Giant Edition
// also used frequently by Web Browser (webkit?)
uint32 cr;
cr = (Opcode >> (31 - 8)) & 7;
cr >>= 2;
uint32 xer = PPCInterpreter_getXER(hCPU);
uint32 xerBits = (xer >> 28) & 0xF;
// todo - is the order correct?
ppc_setCRBit(hCPU, cr * 4 + 0, (xerBits >> 0) & 1);
ppc_setCRBit(hCPU, cr * 4 + 1, (xerBits >> 1) & 1);
ppc_setCRBit(hCPU, cr * 4 + 2, (xerBits >> 2) & 1);
ppc_setCRBit(hCPU, cr * 4 + 3, (xerBits >> 3) & 1);
// reset copied bits
PPCInterpreter_setXER(hCPU, xer&~0xF0000000);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_TLBIE(PPCInterpreter_t* hCPU, uint32 Opcode)
{
int rS, rA, rB;
PPC_OPC_TEMPL_X(Opcode, rS, rA, rB);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_TLBSYNC(PPCInterpreter_t* hCPU, uint32 Opcode)
{
cemu_assert_unimplemented();
PPCInterpreter_nextInstruction(hCPU);
}
// branch instructions
void PPCInterpreter_BX(PPCInterpreter_t* hCPU, uint32 Opcode)
{
uint32 li;
PPC_OPC_TEMPL_I(Opcode, li);
if ((Opcode & PPC_OPC_AA) == 0)
li += (unsigned int)hCPU->instructionPointer;
if (Opcode & PPC_OPC_LK)
{
// update LR and IP
hCPU->spr.LR = (unsigned int)hCPU->instructionPointer + 4;
hCPU->instructionPointer = li;
PPCInterpreter_jumpToInstruction(hCPU, li);
PPCRecompiler_attemptEnter(hCPU, li);
return;
}
PPCInterpreter_jumpToInstruction(hCPU, li);
}
void PPCInterpreter_BCX(PPCInterpreter_t* hCPU, uint32 Opcode)
{
uint32 BO, BI, BD;
PPC_OPC_TEMPL_B(Opcode, BO, BI, BD);
if (!(BO & 4))
hCPU->spr.CTR--;
bool bo2 = (BO & 2) != 0;
bool bo8 = (BO & 8) != 0; // branch condition true
bool cr = ppc_getCRBit(hCPU, BI) != 0;
if (((BO & 4) || ((hCPU->spr.CTR != 0) ^ bo2))
&& ((BO & 16) || (!(cr ^ bo8))))
{
if (!(Opcode & PPC_OPC_AA))
{
BD += (unsigned int)hCPU->instructionPointer;
}
else
{
// should never happen
cemu_assert_unimplemented();
}
if (Opcode & PPC_OPC_LK)
hCPU->spr.LR = ((unsigned int)hCPU->instructionPointer) + 4;
PPCInterpreter_jumpToInstruction(hCPU, BD);
}
else
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_BCLRX(PPCInterpreter_t* hCPU, uint32 Opcode)
{
uint32 BO, BI, BD;
PPC_OPC_TEMPL_XL(Opcode, BO, BI, BD);
PPC_ASSERT(BD == 0);
if (!(BO & 4))
{
if (hCPU->spr.CTR == 0)
{
PPC_ASSERT(true);
cemuLog_logDebug(LogType::Force, "Decrementer underflow!");
}
hCPU->spr.CTR--;
}
bool bo2 = (BO & 2) ? true : false;
bool bo8 = (BO & 8) ? true : false;
bool cr = ppc_getCRBit(hCPU, BI) != 0;
if (((BO & 4) || ((hCPU->spr.CTR != 0) ^ bo2))
&& ((BO & 16) || (!(cr ^ bo8))))
{
BD = hCPU->spr.LR & 0xfffffffc;
if (Opcode & PPC_OPC_LK)
{
hCPU->spr.LR = (unsigned int)hCPU->instructionPointer + 4;
}
PPCInterpreter_jumpToInstruction(hCPU, BD);
PPCRecompiler_attemptEnter(hCPU, BD);
return;
}
else
{
BD = (unsigned int)hCPU->instructionPointer + 4;
PPCInterpreter_nextInstruction(hCPU);
}
}
void PPCInterpreter_BCCTR(PPCInterpreter_t* hCPU, uint32 Opcode)
{
uint32 x = (unsigned int)hCPU->instructionPointer;
uint32 BO, BI, BD;
PPC_OPC_TEMPL_XL(Opcode, BO, BI, BD);
PPC_ASSERT(BD == 0);
PPC_ASSERT(!(BO & 2));
bool bo8 = (BO & 8) ? true : false;
bool cr = ppc_getCRBit(hCPU, BI) != 0;
if ((BO & 16) || (!(cr ^ bo8)))
{
if (Opcode & PPC_OPC_LK)
{
hCPU->spr.LR = (unsigned int)hCPU->instructionPointer + 4;
hCPU->instructionPointer = (unsigned int)(hCPU->spr.CTR & 0xfffffffc);
}
else
{
hCPU->instructionPointer = (unsigned int)(hCPU->spr.CTR & 0xfffffffc);
}
PPCRecompiler_attemptEnter(hCPU, hCPU->instructionPointer);
}
else
{
hCPU->instructionPointer += 4;
}
}
void PPCInterpreter_DCBT(PPCInterpreter_t* hCPU, uint32 Opcode)
{
sint32 rA, rB;
rA = (Opcode >> (31 - 15)) & 0x1F;
rB = (Opcode >> (31 - 20)) & 0x1F;
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_DCBST(PPCInterpreter_t* hCPU, uint32 Opcode)
{
sint32 rA, rB;
rA = (Opcode >> (31 - 15)) & 0x1F;
rB = (Opcode >> (31 - 20)) & 0x1F;
uint32 ea = (rA ? hCPU->gpr[rA] : 0) + hCPU->gpr[rB];
LatteBufferCache_notifyDCFlush(ea, 32);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_DCBF(PPCInterpreter_t* hCPU, uint32 Opcode)
{
sint32 rA, rB;
rA = (Opcode >> (31 - 15)) & 0x1F;
rB = (Opcode >> (31 - 20)) & 0x1F;
uint32 ea = (rA ? hCPU->gpr[rA] : 0) + hCPU->gpr[rB];
LatteBufferCache_notifyDCFlush(ea, 32);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_DCBZL(PPCInterpreter_t* hCPU, uint32 Opcode) //Undocumented
{
// no-op
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_DCBI(PPCInterpreter_t* hCPU, uint32 Opcode)
{
// no-op
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_ICBI(PPCInterpreter_t* hCPU, uint32 Opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_X(Opcode, rD, rA, rB);
uint32 ea = (rA ? hCPU->gpr[rA] : 0) + hCPU->gpr[rB];
// invalidate range
coreinit::codeGenHandleICBI(ea);
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_EIEIO(PPCInterpreter_t* hCPU, uint32 Opcode)
{
// no effect
// next instruction
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_SC(PPCInterpreter_t* hCPU, uint32 Opcode)
{
cemuLog_logDebug(LogType::Force, "SC executed at 0x{:08x}", hCPU->instructionPointer);
// next instruction
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_SYNC(PPCInterpreter_t* hCPU, uint32 Opcode)
{
// no-op
// next instruction
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_ISYNC(PPCInterpreter_t* hCPU, uint32 Opcode)
{
// no-op
// next instruction
PPCInterpreter_nextInstruction(hCPU);
}
void PPCInterpreter_RFI(PPCInterpreter_t* hCPU, uint32 Opcode)
{
cemuLog_logDebug(LogType::Force, "RFI");
hCPU->sprExtended.msr &= ~(0x87C0FF73 | 0x00040000);
hCPU->sprExtended.msr |= hCPU->sprExtended.srr1 & 0x87c0ff73;
hCPU->sprExtended.msr |= MSR_RI;
hCPU->instructionPointer = (unsigned int)(hCPU->sprExtended.srr0);
}
| 8,797
|
C++
|
.cpp
| 310
| 26.190323
| 87
| 0.696621
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,196
|
PPCInterpreterImpl.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/Interpreter/PPCInterpreterImpl.cpp
|
#include "PPCInterpreterInternal.h"
#include "PPCInterpreterHelper.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
#include "Cafe/HW/Espresso/Debugger/GDBStub.h"
class PPCItpCafeOSUsermode
{
public:
static const bool allowSupervisorMode = false;
static const bool allowDSI = false;
inline static uint32 memory_readCodeU32(PPCInterpreter_t* hCPU, uint32 address)
{
return _swapEndianU32(*(uint32*)(memory_base + address));
}
inline static void ppcMem_writeDataDouble(PPCInterpreter_t* hCPU, uint32 address, double vf)
{
uint64 v = *(uint64*)&vf;
uint32 v1 = v & 0xFFFFFFFF;
uint32 v2 = v >> 32;
uint8* ptr = memory_getPointerFromVirtualOffset(address);
*(uint32*)(ptr + 4) = CPU_swapEndianU32(v1);
*(uint32*)(ptr + 0) = CPU_swapEndianU32(v2);
}
inline static void ppcMem_writeDataU64(PPCInterpreter_t* hCPU, uint32 address, uint64 v)
{
*(uint64*)(memory_getPointerFromVirtualOffset(address)) = CPU_swapEndianU64(v);
}
inline static void ppcMem_writeDataU32(PPCInterpreter_t* hCPU, uint32 address, uint32 v)
{
*(uint32*)(memory_getPointerFromVirtualOffset(address)) = CPU_swapEndianU32(v);
}
inline static void ppcMem_writeDataU16(PPCInterpreter_t* hCPU, uint32 address, uint16 v)
{
*(uint16*)(memory_getPointerFromVirtualOffset(address)) = CPU_swapEndianU16(v);
}
inline static void ppcMem_writeDataU8(PPCInterpreter_t* hCPU, uint32 address, uint8 v)
{
*(uint8*)(memory_getPointerFromVirtualOffset(address)) = v;
}
inline static double ppcMem_readDataDouble(PPCInterpreter_t* hCPU, uint32 address)
{
uint32 v[2];
v[1] = *(uint32*)(memory_getPointerFromVirtualOffset(address));
v[0] = *(uint32*)(memory_getPointerFromVirtualOffset(address) + 4);
v[0] = CPU_swapEndianU32(v[0]);
v[1] = CPU_swapEndianU32(v[1]);
return *(double*)v;
}
inline static float ppcMem_readDataFloat(PPCInterpreter_t* hCPU, uint32 address)
{
uint32 v = *(uint32*)(memory_getPointerFromVirtualOffset(address));
v = CPU_swapEndianU32(v);
return *(float*)&v;
}
inline static uint64 ppcMem_readDataU64(PPCInterpreter_t* hCPU, uint32 address)
{
uint64 v = *(uint64*)(memory_getPointerFromVirtualOffset(address));
return CPU_swapEndianU64(v);
}
inline static uint32 ppcMem_readDataU32(PPCInterpreter_t* hCPU, uint32 address)
{
uint32 v = *(uint32*)(memory_getPointerFromVirtualOffset(address));
return CPU_swapEndianU32(v);
}
inline static uint16 ppcMem_readDataU16(PPCInterpreter_t* hCPU, uint32 address)
{
uint16 v = *(uint16*)(memory_getPointerFromVirtualOffset(address));
return CPU_swapEndianU16(v);
}
inline static uint8 ppcMem_readDataU8(PPCInterpreter_t* hCPU, uint32 address)
{
return *(uint8*)(memory_getPointerFromVirtualOffset(address));
}
inline static uint64 ppcMem_readDataFloatEx(PPCInterpreter_t* hCPU, uint32 addr)
{
return ConvertToDoubleNoFTZ(_swapEndianU32(*(uint32*)(memory_base + addr)));
}
inline static void ppcMem_writeDataFloatEx(PPCInterpreter_t* hCPU, uint32 addr, uint64 value)
{
*(uint32*)(memory_base + addr) = _swapEndianU32(ConvertToSingleNoFTZ(value));
}
inline static uint64 getTB(PPCInterpreter_t* hCPU)
{
return PPCInterpreter_getMainCoreCycleCounter();
}
};
uint32 debug_lastTranslatedHit;
void generateDSIException(PPCInterpreter_t* hCPU, uint32 dataAddress)
{
// todo - check if we are already inside an interrupt handler (in which case the DSI exception is queued and not executed immediately?)
// set flag to cancel current instruction
hCPU->memoryException = true;
hCPU->sprExtended.srr0 = hCPU->instructionPointer;
hCPU->sprExtended.srr1 = hCPU->sprExtended.msr & 0x87C0FFFF;
hCPU->sprExtended.dar = dataAddress;
hCPU->sprExtended.msr &= ~0x04EF36;
hCPU->instructionPointer = 0xFFF00300;
uint32 dsisr = 0;
dsisr |= (1<<(31-1)); // set if no TLB/BAT match found
hCPU->sprExtended.dsisr = dsisr;
}
class PPCItpSupervisorWithMMU
{
public:
static const bool allowSupervisorMode = true;
static const bool allowDSI = true;
inline static uint32 ppcMem_translateVirtualDataToPhysicalAddr(PPCInterpreter_t* hCPU, uint32 vAddr)
{
// check if address translation is disabled for data accesses
if (GET_MSR_BIT(MSR_DR) == 0)
{
return vAddr;
}
#ifdef CEMU_DEBUG_ASSERT
if (hCPU->memoryException)
assert_dbg(); // should not be set anymore
#endif
// how to determine if BAT is valid:
// BAT_entry_valid = (Vs & ~MSR[PR]) | (Vp & MSR[PR]) (The entry has separate enable flags for usermode and supervisor mode)
for (sint32 i = 0; i < 8; i++)
{
// upper
uint32 batU = hCPU->sprExtended.dbatU[i];
uint32 BEPI = ((batU >> 17) & 0x7FFF) << 17;
uint32 Vp = (batU >> 0) & 1;
uint32 Vs = (batU >> 1) & 1;
uint32 BL = (((batU >> 2) & 0x7FF) ^ 0x7FF) << 17;
BL |= 0xF0000000;
if (Vs == 0)
continue; // todo - check if in supervisor/usermode
// lower
uint32 batL = hCPU->sprExtended.dbatL[i];
uint32 PP = (batL >> 0) & 3;
uint32 WIMG = (batL >> 3) & 0xF;
uint32 BRPN = ((batL >> 17) & 0x7FFF) << 17;
// check for match
if ((vAddr&BL) == BEPI)
{
// match
vAddr = (vAddr&~BL) | (BRPN&BL);
debug_lastTranslatedHit = vAddr;
return vAddr;
}
}
// no match
debug_lastTranslatedHit = 0xFFFFFFFF;
// find segment
uint32 segmentIndex = (vAddr>>28);
//uint32 pageIndex = (vAddr >> 12) & 0xFFFF; // for 4KB pages
// uint32 byteOffset = vAddr & 0xFFF; // for 4KB pages
uint32 pageIndex = (vAddr >> 17) & 0x7FF; // for 128KB pages
uint32 byteOffset = vAddr & 0x1FFFF;
uint32 srValue = hCPU->sprExtended.sr[segmentIndex];
uint8 sr_ks = (srValue >> 30) & 1; // supervisor
uint8 sr_kp = (srValue >> 29) & 1; // user mode
uint8 sr_n = (srValue >> 28) & 1; // no-execute
uint32 sr_vsid = (srValue & 0xFFFFFF);
//uint32 vpn = pageIndex | (sr_vsid << 16); // 40bit virtual page number
// look up in page table
//uint32 lookupHash = (sr_vsid ^ pageIndex) & 0x7FFFF; // not correct for 4KB pages? sr_vsid must be shifted?
//uint32 lookupHash = (sr_vsid ^ pageIndex) & 0x7FFFF;
//uint32 lookupHash = ((sr_vsid>>8) ^ pageIndex) & 0x7FFFF;
uint32 lookupHash = ((sr_vsid >> 0) ^ pageIndex) & 0x7FFFF;
//lookupHash ^= 0x7FFFF;
uint32 pageTableAddr = hCPU->sprExtended.sdr1&0xFFFF0000;
uint32 pageTableMask = hCPU->sprExtended.sdr1&0x1FF;
for (uint32 ch = 0; ch < 2; ch++)
{
uint32 ptegSelectLow = (lookupHash & 0x3FF);
uint32 maskOR = (lookupHash >> 10) & pageTableMask;
uint32* pteg = (uint32*)(memory_base + (pageTableAddr | (maskOR << 16)) + ptegSelectLow * 64);
for (sint32 t = 0; t < 8; t++)
{
uint32 w0 = _swapEndianU32(pteg[0]);
uint32 w1 = _swapEndianU32(pteg[1]);
pteg += 2;
if ((w0 & 0x80000000) == 0)
continue; // entry not valid
uint32 abPageIndex = (w0 >> 0) & 0x3F;
uint8 h = (w0 >> 6) & 1;
uint32 ptegVSID = (w0 >> 7) & 0xFFFFFF;
if (abPageIndex == (pageIndex >> 5) && ptegVSID == sr_vsid && h == ch)
{
if (ch == 1)
assert_dbg();
// match
uint32 ptegPhysicalPage = (w1 >> 12) & 0xFFFFF;
// replace page (128KB)
vAddr = (vAddr & ~0xFFFE0000) | (ptegPhysicalPage << 12);
return vAddr;
}
}
// calculate hash 2
lookupHash = ~lookupHash;
}
cemuLog_logDebug(LogType::Force, "DSI exception at 0x{:08x} DataAddress {:08x}", hCPU->instructionPointer, vAddr);
generateDSIException(hCPU, vAddr);
// todo: Check hash func 1
// todo: Check protection bits
// todo: Check supervisor/usermode bits
// also use this function in all the mem stuff below
// note: bat has higher priority than TLB
// since iterating the bats and page table is too slow, we need to pre-process the data somehow.
return vAddr;
}
inline static uint32 ppcMem_translateVirtualCodeToPhysicalAddr(PPCInterpreter_t* hCPU, uint32 vAddr)
{
// check if address translation is disabled for instruction accesses
if (GET_MSR_BIT(MSR_IR) == 0)
{
return vAddr;
}
// how to determine if BAT is valid:
// BAT_entry_valid = (Vs & ~MSR[PR]) | (Vp & MSR[PR]) (The entry has separate enable flags for usermode and supervisor mode)
for (sint32 i = 0; i < 8; i++)
{
// upper
uint32 batU = hCPU->sprExtended.ibatU[i];
uint32 BEPI = ((batU >> 17) & 0x7FFF) << 17;
uint32 Vp = (batU >> 0) & 1;
uint32 Vs = (batU >> 1) & 1;
uint32 BL = (((batU >> 2) & 0x7FF) ^ 0x7FF) << 17;
BL |= 0xF0000000;
if (Vs == 0)
continue; // todo - check if in supervisor/usermode
// lower
uint32 batL = hCPU->sprExtended.ibatL[i];
uint32 PP = (batL >> 0) & 3;
uint32 WIMG = (batL >> 3) & 0xF;
uint32 BRPN = ((batL >> 17) & 0x7FFF) << 17;
// check for match
if ((vAddr&BL) == BEPI)
{
// match
vAddr = (vAddr&~BL) | (BRPN&BL);
debug_lastTranslatedHit = vAddr;
return vAddr;
}
}
assert_dbg();
// no match
// todo - throw exception if translation is enabled?
return vAddr;
}
static uint32 memory_readCodeU32(PPCInterpreter_t* hCPU, uint32 address)
{
return _swapEndianU32(*(uint32*)(memory_base + ppcMem_translateVirtualCodeToPhysicalAddr(hCPU, address)));
}
inline static uint8* ppcMem_getDataPtr(PPCInterpreter_t* hCPU, uint32 vAddr)
{
return memory_base + ppcMem_translateVirtualDataToPhysicalAddr(hCPU, vAddr);
}
inline static void ppcMem_writeDataDouble(PPCInterpreter_t* hCPU, uint32 address, double vf)
{
uint64 v = *(uint64*)&vf;
uint32 v1 = v & 0xFFFFFFFF;
uint32 v2 = v >> 32;
uint8* ptr = ppcMem_getDataPtr(hCPU, address);
*(uint32*)(ptr + 4) = CPU_swapEndianU32(v1);
*(uint32*)(ptr + 0) = CPU_swapEndianU32(v2);
}
inline static void ppcMem_writeDataU64(PPCInterpreter_t* hCPU, uint32 address, uint64 v)
{
*(uint64*)(ppcMem_getDataPtr(hCPU, address)) = CPU_swapEndianU64(v);
}
inline static void ppcMem_writeDataU32(PPCInterpreter_t* hCPU, uint32 address, uint32 v)
{
uint32 pAddr = ppcMem_translateVirtualDataToPhysicalAddr(hCPU, address);
if (hCPU->memoryException)
return;
if (pAddr >= 0x0c000000 && pAddr < 0x0d100000)
{
cemu_assert_unimplemented();
return;
}
*(uint32*)(memory_base + pAddr) = CPU_swapEndianU32(v);
}
inline static void ppcMem_writeDataU16(PPCInterpreter_t* hCPU, uint32 address, uint16 v)
{
*(uint16*)(ppcMem_getDataPtr(hCPU, address)) = CPU_swapEndianU16(v);
}
inline static void ppcMem_writeDataU8(PPCInterpreter_t* hCPU, uint32 address, uint8 v)
{
*(uint8*)(ppcMem_getDataPtr(hCPU, address)) = v;
}
inline static double ppcMem_readDataDouble(PPCInterpreter_t* hCPU, uint32 address)
{
uint32 v[2];
v[1] = *(uint32*)(ppcMem_getDataPtr(hCPU, address));
v[0] = *(uint32*)(ppcMem_getDataPtr(hCPU, address) + 4);
v[0] = CPU_swapEndianU32(v[0]);
v[1] = CPU_swapEndianU32(v[1]);
return *(double*)v;
}
inline static float ppcMem_readDataFloat(PPCInterpreter_t* hCPU, uint32 address)
{
uint32 v = *(uint32*)(ppcMem_getDataPtr(hCPU, address));
v = CPU_swapEndianU32(v);
return *(float*)&v;
}
inline static uint64 ppcMem_readDataU64(PPCInterpreter_t* hCPU, uint32 address)
{
uint64 v = *(uint64*)(ppcMem_getDataPtr(hCPU, address));
return CPU_swapEndianU64(v);
}
inline static uint32 ppcMem_readDataU32(PPCInterpreter_t* hCPU, uint32 address)
{
uint32 pAddr = ppcMem_translateVirtualDataToPhysicalAddr(hCPU, address);
if (hCPU->memoryException)
return 0;
if (pAddr >= 0x01FFF000 && pAddr < 0x02000000)
{
debug_printf("Access u32 boot param block 0x%08x IP %08x LR %08x\n", pAddr, hCPU->instructionPointer, hCPU->spr.LR);
cemuLog_logDebug(LogType::Force, "Access u32 boot param block 0x{:08x} (org {:08x}) IP {:08x}", pAddr, address, hCPU->instructionPointer);
}
if (pAddr >= 0xFFEB73B0 && pAddr < (0xFFEB73B0+0x40C))
{
debug_printf("Access cached u32 boot param block 0x%08x IP %08x LR %08x\n", pAddr, hCPU->instructionPointer, hCPU->spr.LR);
cemuLog_logDebug(LogType::Force, "Access cached u32 boot param block 0x{:08x} (org {:08x}) IP {:08x}", pAddr, address, hCPU->instructionPointer);
}
if (pAddr >= 0x0c000000 && pAddr < 0x0d100000)
{
cemu_assert_unimplemented();
return 0;
}
uint32 v = *(uint32*)(memory_base + pAddr);
return CPU_swapEndianU32(v);
}
inline static uint16 ppcMem_readDataU16(PPCInterpreter_t* hCPU, uint32 address)
{
uint16 v = *(uint16*)(ppcMem_getDataPtr(hCPU, address));
return CPU_swapEndianU16(v);
}
inline static uint8 ppcMem_readDataU8(PPCInterpreter_t* hCPU, uint32 address)
{
uint32 pAddr = ppcMem_translateVirtualDataToPhysicalAddr(hCPU, address);
if (pAddr >= 0x0c000000 && pAddr < 0x0d100000)
{
cemu_assert_unimplemented();
return 0;
}
return *(uint8*)(memory_base + pAddr);
}
inline static uint64 ppcMem_readDataFloatEx(PPCInterpreter_t* hCPU, uint32 addr)
{
return ConvertToDoubleNoFTZ(_swapEndianU32(*(uint32*)(memory_base + addr)));
}
inline static void ppcMem_writeDataFloatEx(PPCInterpreter_t* hCPU, uint32 addr, uint64 value)
{
*(uint32*)(memory_base + addr) = _swapEndianU32(ConvertToSingleNoFTZ(value));
}
inline static uint64 getTB(PPCInterpreter_t* hCPU)
{
return hCPU->global->tb / 20ULL;
}
};
uint32 testIP[100];
uint32 testIPC = 0;
template <typename ppcItpCtrl>
class PPCInterpreterContainer
{
public:
#include "PPCInterpreterSPR.hpp"
#include "PPCInterpreterOPC.hpp"
#include "PPCInterpreterLoadStore.hpp"
#include "PPCInterpreterALU.hpp"
static void executeInstruction(PPCInterpreter_t* hCPU)
{
if constexpr(ppcItpCtrl::allowSupervisorMode)
{
hCPU->global->tb++;
}
#ifdef __DEBUG_OUTPUT_INSTRUCTION
debug_printf("%08x: ", hCPU->instructionPointer);
#endif
uint32 opcode = ppcItpCtrl::memory_readCodeU32(hCPU, hCPU->instructionPointer);
switch ((opcode >> 26))
{
case 0:
debug_printf("ZERO[NOP] | 0x%08X\n", (unsigned int)hCPU->instructionPointer);
#ifdef CEMU_DEBUG_ASSERT
assert_dbg();
while (true) std::this_thread::sleep_for(std::chrono::seconds(1));
#endif
hCPU->instructionPointer += 4;
break;
case 1: // virtual HLE
PPCInterpreter_virtualHLE(hCPU, opcode);
break;
case 4:
switch (PPC_getBits(opcode, 30, 5))
{
case 0: // subcategory compare
switch (PPC_getBits(opcode, 25, 5))
{
case 0: // Sonic All Stars Racing
PPCInterpreter_PS_CMPU0(hCPU, opcode);
break;
case 1:
PPCInterpreter_PS_CMPO0(hCPU, opcode);
break;
case 2: // Assassin's Creed 3, Sonic All Stars Racing
PPCInterpreter_PS_CMPU1(hCPU, opcode);
break;
default:
debug_printf("Unknown execute %04X as [4->0] at %08X\n", PPC_getBits(opcode, 25, 5), hCPU->instructionPointer);
cemu_assert_unimplemented();
break;
}
break;
case 6:
PPCInterpreter_PSQ_LX(hCPU, opcode);
break;
case 7:
PPCInterpreter_PSQ_STX(hCPU, opcode);
break;
case 8:
switch (PPC_getBits(opcode, 25, 5))
{
case 1:
PPCInterpreter_PS_NEG(hCPU, opcode);
break;
case 2:
PPCInterpreter_PS_MR(hCPU, opcode);
break;
case 4:
PPCInterpreter_PS_NABS(hCPU, opcode);
break;
case 8:
PPCInterpreter_PS_ABS(hCPU, opcode);
break;
default:
debug_printf("Unknown execute %04X as [4->8] at %08X\n", PPC_getBits(opcode, 25, 5), hCPU->instructionPointer);
cemu_assert_unimplemented();
break;
}
break;
case 10:
PPCInterpreter_PS_SUM0(hCPU, opcode);
break;
case 11:
PPCInterpreter_PS_SUM1(hCPU, opcode);
break;
case 12:
PPCInterpreter_PS_MULS0(hCPU, opcode);
break;
case 13:
PPCInterpreter_PS_MULS1(hCPU, opcode);
break;
case 14:
PPCInterpreter_PS_MADDS0(hCPU, opcode);
break;
case 15:
PPCInterpreter_PS_MADDS1(hCPU, opcode);
break;
case 16: // sub category - merge
switch (PPC_getBits(opcode, 25, 5))
{
case 16:
PPCInterpreter_PS_MERGE00(hCPU, opcode);
break;
case 17:
PPCInterpreter_PS_MERGE01(hCPU, opcode);
break;
case 18:
PPCInterpreter_PS_MERGE10(hCPU, opcode);
break;
case 19:
PPCInterpreter_PS_MERGE11(hCPU, opcode);
break;
default:
debug_printf("Unknown execute %04X as [4->16] at %08X\n", PPC_getBits(opcode, 25, 5), hCPU->instructionPointer);
debugBreakpoint();
break;
}
break;
case 18:
PPCInterpreter_PS_DIV(hCPU, opcode);
break;
case 20:
PPCInterpreter_PS_SUB(hCPU, opcode);
break;
case 21:
PPCInterpreter_PS_ADD(hCPU, opcode);
break;
case 22:
PPCInterpreter_DCBZL(hCPU, opcode);
break;
case 23:
PPCInterpreter_PS_SEL(hCPU, opcode);
break;
case 24:
PPCInterpreter_PS_RES(hCPU, opcode);
break;
case 25:
PPCInterpreter_PS_MUL(hCPU, opcode);
break;
case 26: // sub category with only one entry - RSQRTE
PPCInterpreter_PS_RSQRTE(hCPU, opcode);
break;
case 28:
PPCInterpreter_PS_MSUB(hCPU, opcode);
break;
case 29:
PPCInterpreter_PS_MADD(hCPU, opcode);
break;
case 30:
PPCInterpreter_PS_NMSUB(hCPU, opcode);
break;
case 31:
PPCInterpreter_PS_NMADD(hCPU, opcode);
break;
default:
debug_printf("Unknown execute %04X as [4] at %08X\n", PPC_getBits(opcode, 30, 5), hCPU->instructionPointer);
cemu_assert_unimplemented();
break;
}
break;
case 7:
PPCInterpreter_MULLI(hCPU, opcode);
break;
case 8:
PPCInterpreter_SUBFIC(hCPU, opcode);
break;
case 10:
PPCInterpreter_CMPLI(hCPU, opcode);
break;
case 11:
PPCInterpreter_CMPI(hCPU, opcode);
break;
case 12:
PPCInterpreter_ADDIC(hCPU, opcode);
break;
case 13:
PPCInterpreter_ADDIC_(hCPU, opcode);
break;
case 14:
PPCInterpreter_ADDI(hCPU, opcode);
break;
case 15:
PPCInterpreter_ADDIS(hCPU, opcode);
break;
case 16:
PPCInterpreter_BCX(hCPU, opcode);
break;
case 17:
if (PPC_getBits(opcode, 30, 1) == 1) {
PPCInterpreter_SC(hCPU, opcode);
}
else {
debug_printf("Unsupported Opcode [0x17 --> 0x0]\n");
cemu_assert_unimplemented();
}
break;
case 18:
PPCInterpreter_BX(hCPU, opcode);
break;
case 19: // opcode category
switch (PPC_getBits(opcode, 30, 10))
{
case 0:
PPCInterpreter_MCRF(hCPU, opcode);
break;
case 16:
PPCInterpreter_BCLRX(hCPU, opcode);
break;
case 33:
PPCInterpreter_CRNOR(hCPU, opcode);
break;
case 50:
PPCInterpreter_RFI(hCPU, opcode);
break;
case 129:
PPCInterpreter_CRANDC(hCPU, opcode);
break;
case 150:
PPCInterpreter_ISYNC(hCPU, opcode);
break;
case 193:
PPCInterpreter_CRXOR(hCPU, opcode);
break;
case 257:
PPCInterpreter_CRAND(hCPU, opcode);
break;
case 289:
PPCInterpreter_CREQV(hCPU, opcode);
break;
case 417:
PPCInterpreter_CRORC(hCPU, opcode);
break;
case 449:
PPCInterpreter_CROR(hCPU, opcode);
break;
case 528:
PPCInterpreter_BCCTR(hCPU, opcode);
break;
default:
debug_printf("Unknown execute %04X as [19] at %08X\n", PPC_getBits(opcode, 30, 10), hCPU->instructionPointer);
cemu_assert_unimplemented();
break;
}
break;
case 20:
PPCInterpreter_RLWIMI(hCPU, opcode);
break;
case 21:
PPCInterpreter_RLWINM(hCPU, opcode);
break;
case 23:
PPCInterpreter_RLWNM(hCPU, opcode);
break;
case 24:
PPCInterpreter_ORI(hCPU, opcode);
break;
case 25:
PPCInterpreter_ORIS(hCPU, opcode);
break;
case 26:
PPCInterpreter_XORI(hCPU, opcode);
break;
case 27:
PPCInterpreter_XORIS(hCPU, opcode);
break;
case 28:
PPCInterpreter_ANDI_(hCPU, opcode);
break;
case 29:
PPCInterpreter_ANDIS_(hCPU, opcode);
break;
case 31: // opcode category
switch (PPC_getBits(opcode, 30, 10))
{
case 0:
PPCInterpreter_CMP(hCPU, opcode);
break;
case 4:
#ifdef CEMU_DEBUG_ASSERT
debug_printf("TW instruction executed at %08x\n", hCPU->instructionPointer);
#endif
PPCInterpreter_TW(hCPU, opcode);
break;
case 8:
PPCInterpreter_SUBFC(hCPU, opcode);
break;
case 10:
PPCInterpreter_ADDC(hCPU, opcode);
break;
case 11:
PPCInterpreter_MULHWU_(hCPU, opcode);
break;
case 19:
PPCInterpreter_MFCR(hCPU, opcode);
break;
case 20:
PPCInterpreter_LWARX(hCPU, opcode);
break;
case 23:
PPCInterpreter_LWZX(hCPU, opcode);
break;
case 24:
PPCInterpreter_SLWX(hCPU, opcode);
break;
case 26:
PPCInterpreter_CNTLZW(hCPU, opcode);
break;
case 28:
PPCInterpreter_ANDX(hCPU, opcode);
break;
case 32:
PPCInterpreter_CMPL(hCPU, opcode);
break;
case 40:
PPCInterpreter_SUBF(hCPU, opcode);
break;
case 54:
PPCInterpreter_DCBST(hCPU, opcode);
break;
case 55:
PPCInterpreter_LWZXU(hCPU, opcode);
break;
case 60:
PPCInterpreter_ANDCX(hCPU, opcode);
break;
case 75:
PPCInterpreter_MULHW_(hCPU, opcode);
break;
case 83:
PPCInterpreter_MFMSR(hCPU, opcode);
break;
case 86:
PPCInterpreter_DCBF(hCPU, opcode);
break;
case 87:
PPCInterpreter_LBZX(hCPU, opcode);
break;
case 104:
PPCInterpreter_NEG(hCPU, opcode);
break;
case 119: // Sonic Lost World
PPCInterpreter_LBZXU(hCPU, opcode);
break;
case 124:
PPCInterpreter_NORX(hCPU, opcode);
break;
case 136:
PPCInterpreter_SUBFE(hCPU, opcode);
break;
case 138:
PPCInterpreter_ADDE(hCPU, opcode);
break;
case 144:
PPCInterpreter_MTCRF(hCPU, opcode);
break;
case 146:
PPCInterpreter_MTMSR(hCPU, opcode);
break;
case 150:
PPCInterpreter_STWCX(hCPU, opcode);
break;
case 151:
PPCInterpreter_STWX(hCPU, opcode);
break;
case 183:
PPCInterpreter_STWUX(hCPU, opcode);
break;
case 200:
PPCInterpreter_SUBFZE(hCPU, opcode);
break;
case 202:
PPCInterpreter_ADDZE(hCPU, opcode);
break;
case 210:
PPCInterpreter_MTSR(hCPU, opcode);
break;
case 215:
PPCInterpreter_STBX(hCPU, opcode);
break;
case 232: // Trine 2
PPCInterpreter_SUBFME(hCPU, opcode);
break;
case 234:
PPCInterpreter_ADDME(hCPU, opcode);
break;
case 235:
PPCInterpreter_MULLW(hCPU, opcode);
break;
case 247:
PPCInterpreter_STBUX(hCPU, opcode);
break;
case 266:
PPCInterpreter_ADD(hCPU, opcode);
break;
case 278:
PPCInterpreter_DCBT(hCPU, opcode);
break;
case 279:
PPCInterpreter_LHZX(hCPU, opcode);
break;
case 284:
PPCInterpreter_EQV(hCPU, opcode);
break;
case 306:
PPCInterpreter_TLBIE(hCPU, opcode);
break;
case 311: // Wii U Menu v177 (US)
PPCInterpreter_LHZUX(hCPU, opcode);
break;
case 316:
PPCInterpreter_XOR(hCPU, opcode);
break;
case 339:
PPCInterpreter_MFSPR(hCPU, opcode);
break;
case 343:
PPCInterpreter_LHAX(hCPU, opcode);
break;
case 371:
PPCInterpreter_MFTB(hCPU, opcode);
break;
case 375: // Wii U Menu v177 (US)
PPCInterpreter_LHAUX(hCPU, opcode);
break;
case 407:
PPCInterpreter_STHX(hCPU, opcode);
break;
case 412:
PPCInterpreter_ORC(hCPU, opcode);
break;
case 439:
PPCInterpreter_STHUX(hCPU, opcode);
break;
case 444:
PPCInterpreter_OR(hCPU, opcode);
break;
case 459:
PPCInterpreter_DIVWU(hCPU, opcode);
break;
case 467:
PPCInterpreter_MTSPR(hCPU, opcode);
break;
case 470:
PPCInterpreter_DCBI(hCPU, opcode);
break;
case 476:
PPCInterpreter_NANDX(hCPU, opcode);
break;
case 491:
PPCInterpreter_DIVW(hCPU, opcode);
break;
case 512:
PPCInterpreter_MCRXR(hCPU, opcode);
break;
case 520: // Affordable Space Adventures + other Unity games
PPCInterpreter_SUBFCO(hCPU, opcode);
break;
case 522:
PPCInterpreter_ADDCO(hCPU, opcode);
break;
case 534:
PPCInterpreter_LWBRX(hCPU, opcode);
break;
case 535:
PPCInterpreter_LFSX(hCPU, opcode);
break;
case 536:
PPCInterpreter_SRWX(hCPU, opcode);
break;
case 552:
PPCInterpreter_SUBFO(hCPU, opcode);
break;
case 566:
PPCInterpreter_TLBSYNC(hCPU, opcode);
break;
case 567:
PPCInterpreter_LFSUX(hCPU, opcode);
break;
case 595:
PPCInterpreter_MFSR(hCPU, opcode);
break;
case 597:
PPCInterpreter_LSWI(hCPU, opcode);
break;
case 598:
PPCInterpreter_SYNC(hCPU, opcode);
break;
case 599:
PPCInterpreter_LFDX(hCPU, opcode);
break;
case 616:
PPCInterpreter_NEGO(hCPU, opcode);
break;
case 631:
PPCInterpreter_LFDUX(hCPU, opcode);
break;
case 648: // 136 | OE
PPCInterpreter_SUBFEO(hCPU, opcode);
break;
case 650: // 138 | OE
PPCInterpreter_ADDEO(hCPU, opcode);
break;
case 662:
PPCInterpreter_STWBRX(hCPU, opcode);
break;
case 663:
PPCInterpreter_STFSX(hCPU, opcode);
break;
case 695:
PPCInterpreter_STFSUX(hCPU, opcode);
break;
case 725:
PPCInterpreter_STSWI(hCPU, opcode);
break;
case 727:
PPCInterpreter_STFDX(hCPU, opcode);
break;
case 747:
PPCInterpreter_MULLWO(hCPU, opcode);
break;
case 759:
PPCInterpreter_STFDUX(hCPU, opcode);
break;
case 778:
PPCInterpreter_ADDO(hCPU, opcode);
break;
case 790:
PPCInterpreter_LHBRX(hCPU, opcode);
break;
case 792:
PPCInterpreter_SRAW(hCPU, opcode);
break;
case 824:
PPCInterpreter_SRAWI(hCPU, opcode);
break;
case 854:
PPCInterpreter_EIEIO(hCPU, opcode);
break;
case 918:
PPCInterpreter_STHBRX(hCPU, opcode);
break;
case 922:
PPCInterpreter_EXTSH(hCPU, opcode);
break;
case 954:
PPCInterpreter_EXTSB(hCPU, opcode);
break;
case 971:
PPCInterpreter_DIVWUO(hCPU, opcode);
break;
case 982:
PPCInterpreter_ICBI(hCPU, opcode);
break;
case 983:
PPCInterpreter_STFIWX(hCPU, opcode);
break;
case 1003:
PPCInterpreter_DIVWO(hCPU, opcode);
break;
case 1014:
PPCInterpreter_DCBZ(hCPU, opcode);
break;
default:
debug_printf("Unknown execute %04X as [31] at %08X\n", PPC_getBits(opcode, 30, 10), hCPU->instructionPointer);
#ifdef CEMU_DEBUG_ASSERT
assert_dbg();
#endif
hCPU->instructionPointer += 4;
break;
}
break;
case 32:
PPCInterpreter_LWZ(hCPU, opcode);
break;
case 33:
PPCInterpreter_LWZU(hCPU, opcode);
break;
case 34:
PPCInterpreter_LBZ(hCPU, opcode);
break;
case 35:
PPCInterpreter_LBZU(hCPU, opcode);
break;
case 36:
PPCInterpreter_STW(hCPU, opcode);
break;
case 37:
PPCInterpreter_STWU(hCPU, opcode);
break;
case 38:
PPCInterpreter_STB(hCPU, opcode);
break;
case 39:
PPCInterpreter_STBU(hCPU, opcode);
break;
case 40:
PPCInterpreter_LHZ(hCPU, opcode);
break;
case 41:
PPCInterpreter_LHZU(hCPU, opcode);
break;
case 42:
PPCInterpreter_LHA(hCPU, opcode);
break;
case 43:
PPCInterpreter_LHAU(hCPU, opcode);
break;
case 44:
PPCInterpreter_STH(hCPU, opcode);
break;
case 45:
PPCInterpreter_STHU(hCPU, opcode);
break;
case 46:
PPCInterpreter_LMW(hCPU, opcode);
break;
case 47:
PPCInterpreter_STMW(hCPU, opcode);
break;
case 48:
PPCInterpreter_LFS(hCPU, opcode);
break;
case 49:
PPCInterpreter_LFSU(hCPU, opcode);
break;
case 50:
PPCInterpreter_LFD(hCPU, opcode);
break;
case 51:
PPCInterpreter_LFDU(hCPU, opcode);
break;
case 52:
PPCInterpreter_STFS(hCPU, opcode);
break;
case 53:
PPCInterpreter_STFSU(hCPU, opcode);
break;
case 54:
PPCInterpreter_STFD(hCPU, opcode);
break;
case 55:
PPCInterpreter_STFDU(hCPU, opcode);
break;
case 56:
PPCInterpreter_PSQ_L(hCPU, opcode);
break;
case 57:
PPCInterpreter_PSQ_LU(hCPU, opcode);
break;
case 59: //Opcode category
switch (PPC_getBits(opcode, 30, 5))
{
case 18:
PPCInterpreter_FDIVS(hCPU, opcode);
break;
case 20:
PPCInterpreter_FSUBS(hCPU, opcode);
break;
case 21:
PPCInterpreter_FADDS(hCPU, opcode);
break;
case 24:
PPCInterpreter_FRES(hCPU, opcode);
break;
case 25:
PPCInterpreter_FMULS(hCPU, opcode);
break;
case 28:
PPCInterpreter_FMSUBS(hCPU, opcode);
break;
case 29:
PPCInterpreter_FMADDS(hCPU, opcode);
break;
case 30:
PPCInterpreter_FNMSUBS(hCPU, opcode);
break;
case 31:
PPCInterpreter_FNMADDS(hCPU, opcode);
break;
default:
debug_printf("Unknown execute %04X as [59] at %08X\n", PPC_getBits(opcode, 30, 10), hCPU->instructionPointer);
cemu_assert_unimplemented();
break;
}
break;
case 60:
PPCInterpreter_PSQ_ST(hCPU, opcode);
break;
case 61:
PPCInterpreter_PSQ_STU(hCPU, opcode);
break;
case 63: // opcode category
switch (PPC_getBits(opcode, 30, 5))
{
case 0:
PPCInterpreter_FCMPU(hCPU, opcode);
break;
case 12:
PPCInterpreter_FRSP(hCPU, opcode);
break;
case 15:
PPCInterpreter_FCTIWZ(hCPU, opcode);
break;
case 18:
PPCInterpreter_FDIV(hCPU, opcode);
break;
case 20:
PPCInterpreter_FSUB(hCPU, opcode);
break;
case 21:
PPCInterpreter_FADD(hCPU, opcode);
break;
case 23:
PPCInterpreter_FSEL(hCPU, opcode);
break;
case 25:
PPCInterpreter_FMUL(hCPU, opcode);
break;
case 26:
PPCInterpreter_FRSQRTE(hCPU, opcode);
break;
case 28:
PPCInterpreter_FMSUB(hCPU, opcode);
break;
case 29:
PPCInterpreter_FMADD(hCPU, opcode);
break;
case 30:
PPCInterpreter_FNMSUB(hCPU, opcode);
break;
case 31:
PPCInterpreter_FNMADD(hCPU, opcode);
break;
default:
switch (PPC_getBits(opcode, 30, 10))
{
case 14:
PPCInterpreter_FCTIW(hCPU, opcode);
break;
case 32:
PPCInterpreter_FCMPO(hCPU, opcode);
break;
case 38:
PPCInterpreter_MTFSB1X(hCPU, opcode);
break;
case 40:
PPCInterpreter_FNEG(hCPU, opcode);
break;
case 72:
PPCInterpreter_FMR(hCPU, opcode);
break;
case 136: // Darksiders 2
PPCInterpreter_FNABS(hCPU, opcode);
break;
case 264:
PPCInterpreter_FABS(hCPU, opcode);
break;
case 583:
PPCInterpreter_MFFS(hCPU, opcode);
break;
case 711: // IBM documentation has this wrong as 771?
PPCInterpreter_MTFSF(hCPU, opcode);
break;
default:
debug_printf("Unknown execute %04X as [63] at %08X\n", PPC_getBits(opcode, 30, 10), hCPU->instructionPointer);
cemu_assert_unimplemented();
break;
}
}
break;
default:
debug_printf("Unknown execute %04X at %08X\n", PPC_getBits(opcode, 5, 6), (unsigned int)hCPU->instructionPointer);
cemu_assert_unimplemented();
}
}
};
// Slim interpreter, trades some features for extra performance
// Used when emulator runs in CafeOS HLE mode
// Assumes the following:
// - No MMU (linear memory with 1:1 mapping of physical to virtual)
// - No interrupts
// - Always runs in user mode
// - Paired single mode is always enabled
void PPCInterpreterSlim_executeInstruction(PPCInterpreter_t* hCPU)
{
PPCInterpreterContainer<PPCItpCafeOSUsermode>::executeInstruction(hCPU);
}
// Full interpreter, supports most PowerPC features
// Used when emulator runs in LLE mode
void PPCInterpreterFull_executeInstruction(PPCInterpreter_t* hCPU)
{
PPCInterpreterContainer<PPCItpSupervisorWithMMU>::executeInstruction(hCPU);
}
| 31,346
|
C++
|
.cpp
| 1,150
| 23.262609
| 148
| 0.688552
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,197
|
Debugger.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/Debugger/Debugger.cpp
|
#include "gui/guiWrapper.h"
#include "Debugger.h"
#include "Cafe/OS/RPL/rpl_structs.h"
#include "Cemu/PPCAssembler/ppcAssembler.h"
#include "Cafe/HW/Espresso/Recompiler/PPCRecompiler.h"
#include "Cemu/ExpressionParser/ExpressionParser.h"
#include "gui/debugger/DebuggerWindow2.h"
#include "Cafe/OS/libs/coreinit/coreinit.h"
#if BOOST_OS_WINDOWS
#include <Windows.h>
#endif
debuggerState_t debuggerState{ };
DebuggerBreakpoint* debugger_getFirstBP(uint32 address)
{
for (auto& it : debuggerState.breakpoints)
{
if (it->address == address)
return it;
}
return nullptr;
}
DebuggerBreakpoint* debugger_getFirstBP(uint32 address, uint8 bpType)
{
for (auto& it : debuggerState.breakpoints)
{
if (it->address == address)
{
DebuggerBreakpoint* bpItr = it;
while (bpItr)
{
if (bpItr->bpType == bpType)
return bpItr;
bpItr = bpItr->next;
}
return nullptr;
}
}
return nullptr;
}
bool debuggerBPChain_hasType(DebuggerBreakpoint* bp, uint8 bpType)
{
while (bp)
{
if (bp->bpType == bpType)
return true;
bp = bp->next;
}
return false;
}
void debuggerBPChain_add(uint32 address, DebuggerBreakpoint* bp)
{
bp->next = nullptr;
DebuggerBreakpoint* existingBP = debugger_getFirstBP(address);
if (existingBP)
{
while (existingBP->next)
existingBP = existingBP->next;
existingBP->next = bp;
return;
}
// no breakpoint chain exists for this address
debuggerState.breakpoints.push_back(bp);
}
uint32 debugger_getAddressOriginalOpcode(uint32 address)
{
auto bpItr = debugger_getFirstBP(address);
while (bpItr)
{
if (bpItr->isExecuteBP())
return bpItr->originalOpcodeValue;
bpItr = bpItr->next;
}
return memory_readU32(address);
}
void debugger_updateMemoryU32(uint32 address, uint32 newValue)
{
bool memChanged = false;
if (newValue != memory_readU32(address))
memChanged = true;
memory_writeU32(address, newValue);
if(memChanged)
PPCRecompiler_invalidateRange(address, address + 4);
}
void debugger_updateExecutionBreakpoint(uint32 address, bool forceRestore)
{
auto bpItr = debugger_getFirstBP(address);
bool hasBP = false;
uint32 originalOpcodeValue;
while (bpItr)
{
if (bpItr->isExecuteBP())
{
if (bpItr->enabled && forceRestore == false)
{
// write TW instruction to memory
debugger_updateMemoryU32(address, DEBUGGER_BP_T_DEBUGGER_TW);
return;
}
else
{
originalOpcodeValue = bpItr->originalOpcodeValue;
hasBP = true;
}
}
bpItr = bpItr->next;
}
if (hasBP)
{
// restore instruction
debugger_updateMemoryU32(address, originalOpcodeValue);
}
}
void debugger_createCodeBreakpoint(uint32 address, uint8 bpType)
{
// check if breakpoint already exists
auto existingBP = debugger_getFirstBP(address);
if (existingBP && debuggerBPChain_hasType(existingBP, bpType))
return; // breakpoint already exists
// get original opcode at address
uint32 originalOpcode = debugger_getAddressOriginalOpcode(address);
// init breakpoint object
DebuggerBreakpoint* bp = new DebuggerBreakpoint(address, originalOpcode, bpType, true);
debuggerBPChain_add(address, bp);
debugger_updateExecutionBreakpoint(address);
}
void debugger_createExecuteBreakpoint(uint32 address)
{
debugger_createCodeBreakpoint(address, DEBUGGER_BP_T_NORMAL);
}
namespace coreinit
{
std::vector<std::thread::native_handle_type>& OSGetSchedulerThreads();
}
void debugger_updateMemoryBreakpoint(DebuggerBreakpoint* bp)
{
std::vector<std::thread::native_handle_type> schedulerThreadHandles = coreinit::OSGetSchedulerThreads();
#if BOOST_OS_WINDOWS
debuggerState.activeMemoryBreakpoint = bp;
for (auto& hThreadNH : schedulerThreadHandles)
{
HANDLE hThread = (HANDLE)hThreadNH;
CONTEXT ctx{};
ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
SuspendThread(hThread);
GetThreadContext(hThread, &ctx);
if (debuggerState.activeMemoryBreakpoint)
{
ctx.Dr0 = (DWORD64)memory_getPointerFromVirtualOffset(bp->address);
ctx.Dr1 = (DWORD64)memory_getPointerFromVirtualOffset(bp->address);
// breakpoint 0
SetBits(ctx.Dr7, 0, 1, 1); // breakpoint #0 enabled: true
SetBits(ctx.Dr7, 16, 2, 1); // breakpoint #0 condition: 1 (write)
SetBits(ctx.Dr7, 18, 2, 3); // breakpoint #0 length: 3 (4 bytes)
// breakpoint 1
SetBits(ctx.Dr7, 2, 1, 1); // breakpoint #1 enabled: true
SetBits(ctx.Dr7, 20, 2, 3); // breakpoint #1 condition: 3 (read & write)
SetBits(ctx.Dr7, 22, 2, 3); // breakpoint #1 length: 3 (4 bytes)
}
else
{
// breakpoint 0
SetBits(ctx.Dr7, 0, 1, 0); // breakpoint #0 enabled: false
SetBits(ctx.Dr7, 16, 2, 0); // breakpoint #0 condition: 1 (write)
SetBits(ctx.Dr7, 18, 2, 0); // breakpoint #0 length: 3 (4 bytes)
// breakpoint 1
SetBits(ctx.Dr7, 2, 1, 0); // breakpoint #1 enabled: false
SetBits(ctx.Dr7, 20, 2, 0); // breakpoint #1 condition: 3 (read & write)
SetBits(ctx.Dr7, 22, 2, 0); // breakpoint #1 length: 3 (4 bytes)
}
SetThreadContext(hThread, &ctx);
ResumeThread(hThread);
}
#else
cemuLog_log(LogType::Force, "Debugger breakpoints are not supported");
#endif
}
void debugger_handleSingleStepException(uint64 dr6)
{
bool triggeredDR0 = GetBits(dr6, 0, 1); // write
bool triggeredDR1 = GetBits(dr6, 1, 1); // read and write
bool catchBP = false;
if (triggeredDR0 && triggeredDR1)
{
// write (and read) access
if (debuggerState.activeMemoryBreakpoint && debuggerState.activeMemoryBreakpoint->bpType == DEBUGGER_BP_T_MEMORY_WRITE)
catchBP = true;
}
else
{
// read access
if (debuggerState.activeMemoryBreakpoint && debuggerState.activeMemoryBreakpoint->bpType == DEBUGGER_BP_T_MEMORY_READ)
catchBP = true;
}
if (catchBP)
{
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
debugger_createCodeBreakpoint(hCPU->instructionPointer + 4, DEBUGGER_BP_T_ONE_SHOT);
}
}
void debugger_createMemoryBreakpoint(uint32 address, bool onRead, bool onWrite)
{
// init breakpoint object
uint8 bpType;
if (onRead && onWrite)
assert_dbg();
else if (onRead)
bpType = DEBUGGER_BP_T_MEMORY_READ;
else
bpType = DEBUGGER_BP_T_MEMORY_WRITE;
DebuggerBreakpoint* bp = new DebuggerBreakpoint(address, 0xFFFFFFFF, bpType, true);
debuggerBPChain_add(address, bp);
// disable any already existing memory breakpoint
if (debuggerState.activeMemoryBreakpoint)
{
debuggerState.activeMemoryBreakpoint->enabled = false;
debuggerState.activeMemoryBreakpoint = nullptr;
}
// activate new breakpoint
debugger_updateMemoryBreakpoint(bp);
}
void debugger_handleEntryBreakpoint(uint32 address)
{
if (!debuggerState.breakOnEntry)
return;
debugger_createCodeBreakpoint(address, DEBUGGER_BP_T_NORMAL);
}
void debugger_deleteBreakpoint(DebuggerBreakpoint* bp)
{
for (auto& it : debuggerState.breakpoints)
{
if (it->address == bp->address)
{
// for execution breakpoints make sure the instruction is restored
if (bp->isExecuteBP())
{
bp->enabled = false;
debugger_updateExecutionBreakpoint(bp->address);
}
// remove
if (it == bp)
{
// remove first in list
debuggerState.breakpoints.erase(std::remove(debuggerState.breakpoints.begin(), debuggerState.breakpoints.end(), bp), debuggerState.breakpoints.end());
DebuggerBreakpoint* nextBP = bp->next;
if (nextBP)
debuggerState.breakpoints.push_back(nextBP);
}
else
{
// remove from list
DebuggerBreakpoint* bpItr = it;
while (bpItr->next != bp)
{
bpItr = bpItr->next;
}
cemu_assert_debug(bpItr->next != bp);
bpItr->next = bp->next;
}
delete bp;
return;
}
}
}
void debugger_toggleExecuteBreakpoint(uint32 address)
{
auto existingBP = debugger_getFirstBP(address, DEBUGGER_BP_T_NORMAL);
if (existingBP)
{
// delete existing breakpoint
debugger_deleteBreakpoint(existingBP);
}
else
{
// create new breakpoint
debugger_createExecuteBreakpoint(address);
}
}
void debugger_forceBreak()
{
debuggerState.debugSession.shouldBreak = true;
}
bool debugger_isTrapped()
{
return debuggerState.debugSession.isTrapped;
}
void debugger_resume()
{
// if there is a breakpoint on the current instruction then do a single 'step into' to skip it
debuggerState.debugSession.run = true;
}
void debugger_toggleBreakpoint(uint32 address, bool state, DebuggerBreakpoint* bp)
{
DebuggerBreakpoint* bpItr = debugger_getFirstBP(address);
while (bpItr)
{
if (bpItr == bp)
{
if (bpItr->bpType == DEBUGGER_BP_T_NORMAL || bpItr->bpType == DEBUGGER_BP_T_LOGGING)
{
bp->enabled = state;
debugger_updateExecutionBreakpoint(address);
debuggerWindow_updateViewThreadsafe2();
}
else if (bpItr->isMemBP())
{
// disable other memory breakpoints
for (auto& it : debuggerState.breakpoints)
{
DebuggerBreakpoint* bpItr2 = it;
while (bpItr2)
{
if (bpItr2->isMemBP() && bpItr2 != bp)
{
bpItr2->enabled = false;
}
bpItr2 = bpItr2->next;
}
}
bpItr->enabled = state;
if (state)
debugger_updateMemoryBreakpoint(bpItr);
else
debugger_updateMemoryBreakpoint(nullptr);
debuggerWindow_updateViewThreadsafe2();
}
return;
}
bpItr = bpItr->next;
}
}
void debugger_createPatch(uint32 address, std::span<uint8> patchData)
{
DebuggerPatch* patch = new DebuggerPatch();
patch->address = address;
patch->length = patchData.size();
patch->data.resize(4);
patch->origData.resize(4);
memcpy(&patch->data.front(), patchData.data(), patchData.size());
memcpy(&patch->origData.front(), memory_getPointerFromVirtualOffset(address), patchData.size());
// get original data from breakpoints
if ((address & 3) != 0)
cemu_assert_debug(false);
for (sint32 i = 0; i < patchData.size() / 4; i++)
{
DebuggerBreakpoint* bpItr = debugger_getFirstBP(address);
while (bpItr)
{
if (bpItr->isExecuteBP())
{
*(uint32*)(&patch->origData.front() + i * 4) = _swapEndianU32(bpItr->originalOpcodeValue);
}
bpItr = bpItr->next;
}
}
// merge with existing patches if the ranges touch
for(sint32 i=0; i<debuggerState.patches.size(); i++)
{
auto& patchItr = debuggerState.patches[i];
if (address + patchData.size() >= patchItr->address && address <= patchItr->address + patchItr->length)
{
uint32 newAddress = std::min(patch->address, patchItr->address);
uint32 newEndAddress = std::max(patch->address + patch->length, patchItr->address + patchItr->length);
uint32 newLength = newEndAddress - newAddress;
DebuggerPatch* newPatch = new DebuggerPatch();
newPatch->address = newAddress;
newPatch->length = newLength;
newPatch->data.resize(newLength);
newPatch->origData.resize(newLength);
memcpy(&newPatch->data.front() + (address - newAddress), &patch->data.front(), patch->length);
memcpy(&newPatch->data.front() + (patchItr->address - newAddress), &patchItr->data.front(), patchItr->length);
memcpy(&newPatch->origData.front() + (address - newAddress), &patch->origData.front(), patch->length);
memcpy(&newPatch->origData.front() + (patchItr->address - newAddress), &patchItr->origData.front(), patchItr->length);
delete patch;
patch = newPatch;
delete patchItr;
// remove currently iterated patch
debuggerState.patches.erase(debuggerState.patches.begin()+i);
i--;
}
}
debuggerState.patches.push_back(patch);
// apply patch (if breakpoints exist then update those instead of actual data)
if ((address & 3) != 0)
cemu_assert_debug(false);
if ((patchData.size() & 3) != 0)
cemu_assert_debug(false);
for (sint32 i = 0; i < patchData.size() / 4; i++)
{
DebuggerBreakpoint* bpItr = debugger_getFirstBP(address);
bool hasActiveExecuteBP = false;
while (bpItr)
{
if (bpItr->isExecuteBP())
{
bpItr->originalOpcodeValue = *(uint32be*)(patchData.data() + i * 4);
if (bpItr->enabled)
hasActiveExecuteBP = true;
}
bpItr = bpItr->next;
}
if (hasActiveExecuteBP == false)
{
memcpy(memory_getPointerFromVirtualOffset(address + i * 4), patchData.data() + i * 4, 4);
PPCRecompiler_invalidateRange(address, address + 4);
}
}
}
bool debugger_hasPatch(uint32 address)
{
for (auto& patch : debuggerState.patches)
{
if (address + 4 > patch->address && address < patch->address + patch->length)
return true;
}
return false;
}
void debugger_stepInto(PPCInterpreter_t* hCPU, bool updateDebuggerWindow = true)
{
bool isRecEnabled = ppcRecompilerEnabled;
ppcRecompilerEnabled = false;
uint32 initialIP = debuggerState.debugSession.instructionPointer;
debugger_updateExecutionBreakpoint(initialIP, true);
PPCInterpreterSlim_executeInstruction(hCPU);
debugger_updateExecutionBreakpoint(initialIP);
debuggerState.debugSession.instructionPointer = hCPU->instructionPointer;
if(updateDebuggerWindow)
debuggerWindow_moveIP();
ppcRecompilerEnabled = isRecEnabled;
}
bool debugger_stepOver(PPCInterpreter_t* hCPU)
{
bool isRecEnabled = ppcRecompilerEnabled;
ppcRecompilerEnabled = false;
// disassemble current instruction
PPCDisassembledInstruction disasmInstr = { 0 };
uint32 initialIP = debuggerState.debugSession.instructionPointer;
debugger_updateExecutionBreakpoint(initialIP, true);
ppcAssembler_disassemble(initialIP, memory_readU32(initialIP), &disasmInstr);
if (disasmInstr.ppcAsmCode != PPCASM_OP_BL &&
disasmInstr.ppcAsmCode != PPCASM_OP_BCTRL)
{
// nothing to skip, use step-into
debugger_stepInto(hCPU);
debugger_updateExecutionBreakpoint(initialIP);
debuggerWindow_moveIP();
ppcRecompilerEnabled = isRecEnabled;
return false;
}
// create one-shot breakpoint at next instruction
debugger_createCodeBreakpoint(initialIP + 4, DEBUGGER_BP_T_ONE_SHOT);
// step over current instruction (to avoid breakpoint)
debugger_stepInto(hCPU);
debuggerWindow_moveIP();
// restore breakpoints
debugger_updateExecutionBreakpoint(initialIP);
// run
ppcRecompilerEnabled = isRecEnabled;
return true;
}
void debugger_createPPCStateSnapshot(PPCInterpreter_t* hCPU)
{
memcpy(debuggerState.debugSession.ppcSnapshot.gpr, hCPU->gpr, sizeof(uint32) * 32);
memcpy(debuggerState.debugSession.ppcSnapshot.fpr, hCPU->fpr, sizeof(FPR_t) * 32);
debuggerState.debugSession.ppcSnapshot.spr_lr = hCPU->spr.LR;
for (uint32 i = 0; i < 32; i++)
debuggerState.debugSession.ppcSnapshot.cr[i] = hCPU->cr[i];
}
void debugger_enterTW(PPCInterpreter_t* hCPU)
{
// handle logging points
DebuggerBreakpoint* bp = debugger_getFirstBP(hCPU->instructionPointer);
bool shouldBreak = debuggerBPChain_hasType(bp, DEBUGGER_BP_T_NORMAL) || debuggerBPChain_hasType(bp, DEBUGGER_BP_T_ONE_SHOT);
while (bp)
{
if (bp->bpType == DEBUGGER_BP_T_LOGGING && bp->enabled)
{
std::string logName = !bp->comment.empty() ? "Breakpoint '"+boost::nowide::narrow(bp->comment)+"'" : fmt::format("Breakpoint at 0x{:08X} (no comment)", bp->address);
std::string logContext = fmt::format("Thread: {:08x} LR: 0x{:08x}", MEMPTR<OSThread_t>(coreinit::OSGetCurrentThread()).GetMPTR(), hCPU->spr.LR, cemuLog_advancedPPCLoggingEnabled() ? " Stack Trace:" : "");
cemuLog_log(LogType::Force, "[Debugger] {} was executed! {}", logName, logContext);
if (cemuLog_advancedPPCLoggingEnabled())
DebugLogStackTrace(coreinit::OSGetCurrentThread(), hCPU->gpr[1]);
break;
}
bp = bp->next;
}
// return early if it's only a non-pausing logging breakpoint to prevent a modified debugger state and GUI updates
if (!shouldBreak)
{
uint32 backupIP = debuggerState.debugSession.instructionPointer;
debuggerState.debugSession.instructionPointer = hCPU->instructionPointer;
debugger_stepInto(hCPU, false);
PPCInterpreterSlim_executeInstruction(hCPU);
debuggerState.debugSession.instructionPointer = backupIP;
return;
}
// handle breakpoints
debuggerState.debugSession.isTrapped = true;
debuggerState.debugSession.debuggedThreadMPTR = MEMPTR<OSThread_t>(coreinit::OSGetCurrentThread()).GetMPTR();
debuggerState.debugSession.instructionPointer = hCPU->instructionPointer;
debuggerState.debugSession.hCPU = hCPU;
debugger_createPPCStateSnapshot(hCPU);
// remove one-shot breakpoint if it exists
DebuggerBreakpoint* singleshotBP = debugger_getFirstBP(debuggerState.debugSession.instructionPointer, DEBUGGER_BP_T_ONE_SHOT);
if (singleshotBP)
debugger_deleteBreakpoint(singleshotBP);
debuggerWindow_notifyDebugBreakpointHit2();
debuggerWindow_updateViewThreadsafe2();
// reset step control
debuggerState.debugSession.stepInto = false;
debuggerState.debugSession.stepOver = false;
debuggerState.debugSession.run = false;
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
// check for step commands
if (debuggerState.debugSession.stepOver)
{
if (debugger_stepOver(hCPU))
{
debugger_createPPCStateSnapshot(hCPU);
break; // if true is returned, continue with execution
}
debugger_createPPCStateSnapshot(hCPU);
debuggerWindow_updateViewThreadsafe2();
debuggerState.debugSession.stepOver = false;
}
if (debuggerState.debugSession.stepInto)
{
debugger_stepInto(hCPU);
debugger_createPPCStateSnapshot(hCPU);
debuggerWindow_updateViewThreadsafe2();
debuggerState.debugSession.stepInto = false;
continue;
}
if (debuggerState.debugSession.run)
{
debugger_createPPCStateSnapshot(hCPU);
debugger_stepInto(hCPU, false);
PPCInterpreterSlim_executeInstruction(hCPU);
debuggerState.debugSession.instructionPointer = hCPU->instructionPointer;
debuggerState.debugSession.run = false;
break;
}
}
debuggerState.debugSession.isTrapped = false;
debuggerState.debugSession.hCPU = nullptr;
debuggerWindow_updateViewThreadsafe2();
debuggerWindow_notifyRun();
}
void debugger_shouldBreak(PPCInterpreter_t* hCPU)
{
if(debuggerState.debugSession.shouldBreak
// exclude emulator trampoline area
&& (hCPU->instructionPointer < MEMORY_CODE_TRAMPOLINE_AREA_ADDR || hCPU->instructionPointer > MEMORY_CODE_TRAMPOLINE_AREA_ADDR + MEMORY_CODE_TRAMPOLINE_AREA_SIZE))
{
debuggerState.debugSession.shouldBreak = false;
const uint32 address = (uint32)hCPU->instructionPointer;
assert_dbg();
//debugger_createBreakpoint(address, DEBUGGER_BP_TYPE_ONE_SHOT);
}
}
void debugger_addParserSymbols(class ExpressionParser& ep)
{
const auto module_count = RPLLoader_GetModuleCount();
const auto module_list = RPLLoader_GetModuleList();
std::vector<double> module_tmp(module_count);
for (int i = 0; i < module_count; i++)
{
const auto module = module_list[i];
if (module)
{
module_tmp[i] = (double)module->regionMappingBase_text.GetMPTR();
ep.AddConstant(module->moduleName2, module_tmp[i]);
}
}
for (sint32 i = 0; i < 32; i++)
ep.AddConstant(fmt::format("r{}", i), debuggerState.debugSession.ppcSnapshot.gpr[i]);
}
| 18,642
|
C++
|
.cpp
| 578
| 29.456747
| 207
| 0.747961
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,198
|
GDBStub.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/Debugger/GDBStub.cpp
|
#include "GDBStub.h"
#include "Debugger.h"
#include "Cafe/HW/Espresso/Recompiler/PPCRecompiler.h"
#include "GDBBreakpoints.h"
#include "util/helpers/helpers.h"
#include "util/ThreadPool/ThreadPool.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/RPL/rpl_structs.h"
#include "Cafe/OS/libs/coreinit/coreinit_Scheduler.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/HW/Espresso/Interpreter/PPCInterpreterInternal.h"
#include "Cafe/HW/Espresso/EspressoISA.h"
#include "Common/socket.h"
#define GET_THREAD_ID(threadPtr) memory_getVirtualOffsetFromPointer(threadPtr)
#define GET_THREAD_BY_ID(threadId) (OSThread_t*)memory_getPointerFromPhysicalOffset(threadId)
static std::vector<MPTR> findNextInstruction(MPTR currAddress, uint32 lr, uint32 ctr)
{
using namespace Espresso;
uint32 nextInstr = memory_readU32(currAddress);
if (GetPrimaryOpcode(nextInstr) == PrimaryOpcode::B)
{
uint32 LI;
bool AA, LK;
decodeOp_B(nextInstr, LI, AA, LK);
if (!AA)
LI += currAddress;
return {LI};
}
if (GetPrimaryOpcode(nextInstr) == PrimaryOpcode::BC)
{
uint32 BD, BI;
BOField BO{};
bool AA, LK;
decodeOp_BC(nextInstr, BD, BO, BI, AA, LK);
if (!LK)
BD += currAddress;
return {currAddress + 4, BD};
}
if (GetPrimaryOpcode(nextInstr) == PrimaryOpcode::GROUP_19 && GetGroup19Opcode(nextInstr) == Opcode19::BCLR)
{
return {currAddress + 4, lr};
}
if (GetPrimaryOpcode(nextInstr) == PrimaryOpcode::GROUP_19 && GetGroup19Opcode(nextInstr) == Opcode19::BCCTR)
{
return {currAddress + 4, ctr};
}
return {currAddress + 4};
}
template<typename F>
static void selectThread(sint64 selectorId, F&& action_for_thread)
{
__OSLockScheduler();
cemu_assert_debug(activeThreadCount != 0);
if (selectorId == -1)
{
for (sint32 i = 0; i < activeThreadCount; i++)
{
action_for_thread(GET_THREAD_BY_ID(activeThread[i]));
}
}
else if (selectorId == 0)
{
// Use first thread if attempted to be stopped
// todo: would this work better if it used main?
action_for_thread(coreinit::OSGetDefaultThread(1));
}
else if (selectorId > 0)
{
for (sint32 i = 0; i < activeThreadCount; i++)
{
auto* thread = GET_THREAD_BY_ID(activeThread[i]);
if (GET_THREAD_ID(thread) == selectorId)
{
action_for_thread(thread);
break;
}
}
}
__OSUnlockScheduler();
}
template<typename F>
static void selectAndBreakThread(sint64 selectorId, F&& action_for_thread)
{
__OSLockScheduler();
cemu_assert_debug(activeThreadCount != 0);
std::vector<OSThread_t*> pausedThreads;
if (selectorId == -1)
{
for (sint32 i = 0; i < activeThreadCount; i++)
{
coreinit::__OSSuspendThreadNolock(GET_THREAD_BY_ID(activeThread[i]));
pausedThreads.emplace_back(GET_THREAD_BY_ID(activeThread[i]));
}
}
else if (selectorId == 0)
{
// Use first thread if attempted to be stopped
OSThread_t* thread = GET_THREAD_BY_ID(activeThread[0]);
for (sint32 i = 0; i < activeThreadCount; i++)
{
if (GET_THREAD_ID(GET_THREAD_BY_ID(activeThread[i])) < GET_THREAD_ID(thread))
{
thread = GET_THREAD_BY_ID(activeThread[i]);
}
}
coreinit::__OSSuspendThreadNolock(thread);
pausedThreads.emplace_back(thread);
}
else if (selectorId > 0)
{
for (sint32 i = 0; i < activeThreadCount; i++)
{
auto* thread = GET_THREAD_BY_ID(activeThread[i]);
if (GET_THREAD_ID(thread) == selectorId)
{
coreinit::__OSSuspendThreadNolock(thread);
pausedThreads.emplace_back(thread);
break;
}
}
}
__OSUnlockScheduler();
for (OSThread_t* thread : pausedThreads)
{
while (coreinit::OSIsThreadRunning(thread))
std::this_thread::sleep_for(std::chrono::milliseconds(50));
action_for_thread(thread);
}
}
static void selectAndResumeThread(sint64 selectorId)
{
__OSLockScheduler();
cemu_assert_debug(activeThreadCount != 0);
if (selectorId == -1)
{
for (sint32 i = 0; i < activeThreadCount; i++)
{
coreinit::__OSResumeThreadInternal(GET_THREAD_BY_ID(activeThread[i]), 4);
}
}
else if (selectorId == 0)
{
// Use first thread if attempted to be stopped
coreinit::__OSResumeThreadInternal(coreinit::OSGetDefaultThread(1), 1);
}
else if (selectorId > 0)
{
for (sint32 i = 0; i < activeThreadCount; i++)
{
auto* thread = GET_THREAD_BY_ID(activeThread[i]);
if (GET_THREAD_ID(thread) == selectorId)
{
coreinit::__OSResumeThreadInternal(thread, 1);
break;
}
}
}
__OSUnlockScheduler();
}
static void waitForBrokenThreads(std::unique_ptr<GDBServer::CommandContext> context, std::string_view reason)
{
// This should pause all threads except trapped thread
// It should however wait for the trapped thread
// The trapped thread should be paused by the trap word instruction handler (aka the running thread)
std::vector<OSThread_t*> threadsList;
__OSLockScheduler();
for (sint32 i = 0; i < activeThreadCount; i++)
{
threadsList.emplace_back(GET_THREAD_BY_ID(activeThread[i]));
}
__OSUnlockScheduler();
for (OSThread_t* thread : threadsList)
{
while (coreinit::OSIsThreadRunning(thread))
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
context->QueueResponse(reason);
}
static void breakThreads(sint64 trappedThread)
{
__OSLockScheduler();
cemu_assert_debug(activeThreadCount != 0);
// First, break other threads
OSThread_t* mainThread = nullptr;
for (sint32 i = 0; i < activeThreadCount; i++)
{
if (GET_THREAD_ID(GET_THREAD_BY_ID(activeThread[i])) == trappedThread)
{
mainThread = GET_THREAD_BY_ID(activeThread[i]);
}
else
{
coreinit::__OSSuspendThreadNolock(GET_THREAD_BY_ID(activeThread[i]));
}
}
// Second, break trapped thread itself which should also pause execution of this handler
// This will temporarily lift the scheduler lock until it's resumed from its suspension
coreinit::__OSSuspendThreadNolock(mainThread);
__OSUnlockScheduler();
}
std::unique_ptr<GDBServer> g_gdbstub;
GDBServer::GDBServer(uint16 port)
: m_port(port)
{
#if BOOST_OS_WINDOWS
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
#endif
}
GDBServer::~GDBServer()
{
if (m_client_socket != INVALID_SOCKET)
{
// close socket from other thread to forcefully stop accept() call
closesocket(m_client_socket);
m_client_socket = INVALID_SOCKET;
}
if (m_server_socket != INVALID_SOCKET)
{
closesocket(m_server_socket);
}
#if BOOST_OS_WINDOWS
WSACleanup();
#endif
m_stopRequested = false;
m_thread.join();
}
bool GDBServer::Initialize()
{
cemuLog_createLogFile(false);
if (m_server_socket = socket(PF_INET, SOCK_STREAM, 0); m_server_socket == SOCKET_ERROR)
return false;
int reuseEnabled = TRUE;
if (setsockopt(m_server_socket, SOL_SOCKET, SO_REUSEADDR, (char*)&reuseEnabled, sizeof(reuseEnabled)) == SOCKET_ERROR)
{
closesocket(m_server_socket);
m_server_socket = INVALID_SOCKET;
return false;
}
int nodelayEnabled = TRUE;
if (setsockopt(m_server_socket, IPPROTO_TCP, TCP_NODELAY, (char*)&nodelayEnabled, sizeof(nodelayEnabled)) == SOCKET_ERROR)
{
closesocket(m_server_socket);
m_server_socket = INVALID_SOCKET;
return false;
}
memset(&m_server_addr, 0, sizeof(m_server_addr));
m_server_addr.sin_family = AF_INET;
m_server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
m_server_addr.sin_port = htons(m_port);
if (bind(m_server_socket, (sockaddr*)&m_server_addr, sizeof(m_server_addr)) == SOCKET_ERROR)
{
closesocket(m_server_socket);
m_server_socket = INVALID_SOCKET;
return false;
}
if (listen(m_server_socket, s_maxGDBClients) == SOCKET_ERROR)
{
closesocket(m_server_socket);
m_server_socket = INVALID_SOCKET;
return false;
}
m_thread = std::thread(std::bind(&GDBServer::ThreadFunc, this));
return true;
}
void GDBServer::ThreadFunc()
{
SetThreadName("GDBServer");
while (!m_stopRequested)
{
if (!m_client_connected)
{
cemuLog_logDebug(LogType::Force, "[GDBStub] Waiting for client to connect on port {}...", m_port);
socklen_t client_addr_size = sizeof(m_client_addr);
m_client_socket = accept(m_server_socket, (struct sockaddr*)&m_client_addr, &client_addr_size);
m_client_connected = m_client_socket != SOCKET_ERROR;
}
else
{
auto receiveMessage = [&](char* buffer, const int32_t length) -> bool {
if (recv(m_client_socket, buffer, length, 0) != SOCKET_ERROR)
return false;
return true;
};
auto readChar = [&]() -> char {
char ret = 0;
recv(m_client_socket, &ret, 1, 0);
return ret;
};
char packetPrefix = readChar();
switch (packetPrefix)
{
case '+':
case '-':
break;
case '\x03':
{
cemuLog_logDebug(LogType::Force, "[GDBStub] Received interrupt (pressed CTRL+C?) from client!");
selectAndBreakThread(-1, [](OSThread_t* thread) {
});
auto thread_status = fmt::format("T05thread:{:08X};", GET_THREAD_ID(coreinit::OSGetDefaultThread(1)));
if (this->m_resumed_context)
{
this->m_resumed_context->QueueResponse(thread_status);
this->m_resumed_context.reset();
}
else
{
auto response_full = fmt::format("+${}#{:02x}", thread_status, CommandContext::CalculateChecksum(thread_status));
send(m_client_socket, response_full.c_str(), (int)response_full.size(), 0);
}
break;
}
case '$':
{
std::string message;
uint8 checkedSum = 0;
for (uint32_t i = 1;; i++)
{
char c = readChar();
if (c == '#')
break;
checkedSum += static_cast<uint8>(c);
message.push_back(c);
if (i >= s_maxPacketSize)
cemuLog_logDebug(LogType::Force, "[GDBStub] Received too big of a buffer: {}", message);
}
char checkSumStr[2];
receiveMessage(checkSumStr, 2);
uint32_t checkSum = std::stoi(std::string(checkSumStr, sizeof(checkSumStr)), nullptr, 16);
assert((checkedSum & 0xFF) == checkSum);
HandleCommand(message);
break;
}
default:
// cemuLog_logDebug(LogType::Force, "[GDBStub] Unknown packet start: {}", packetPrefix);
break;
}
}
}
if (m_client_socket != INVALID_SOCKET)
closesocket(m_client_socket);
}
void GDBServer::HandleCommand(const std::string& command_str)
{
auto context = std::make_unique<CommandContext>(this, command_str);
if (context->IsValid())
{
// cemuLog_logDebug(LogType::Force, "[GDBStub] Extracted Command {}", fmt::join(context->GetArgs(), ","));
}
switch (context->GetType())
{
// Extended commands
case CMDType::QUERY_GET:
case CMDType::QUERY_SET:
return HandleQuery(context);
case CMDType::VCONT:
return HandleVCont(context);
// Regular commands
case CMDType::IS_THREAD_RUNNING:
return CMDIsThreadActive(context);
case CMDType::SET_ACTIVE_THREAD:
return CMDSetActiveThread(context);
case CMDType::ACTIVE_THREAD_STATUS:
return CMDGetThreadStatus(context);
case CMDType::CONTINUE:
return CMDContinue(context);
case CMDType::ACTIVE_THREAD_STEP:
break;
case CMDType::REGISTER_READ:
return CMDReadRegister(context);
case CMDType::REGISTER_SET:
return CMDWriteRegister(context);
case CMDType::REGISTERS_READ:
return CMDReadRegisters(context);
case CMDType::REGISTERS_WRITE:
return CMDWriteRegisters(context);
case CMDType::MEMORY_READ:
return CMDReadMemory(context);
case CMDType::MEMORY_WRITE:
return CMDWriteMemory(context);
case CMDType::BREAKPOINT_SET:
return CMDInsertBreakpoint(context);
case CMDType::BREAKPOINT_REMOVE:
return CMDDeleteBreakpoint(context);
case CMDType::INVALID:
default:
return CMDNotFound(context);
}
CMDNotFound(context);
}
void GDBServer::HandleQuery(std::unique_ptr<CommandContext>& context) const
{
if (!context->IsValid())
return context->QueueResponse(RESPONSE_EMPTY);
const auto& query_cmd = context->GetArgs()[0];
const auto& query_args = context->GetArgs().begin() + 1;
if (query_cmd == "qSupported")
{
context->QueueResponse(s_supportedFeatures);
}
else if (query_cmd == "qAttached")
{
context->QueueResponse("1");
}
else if (query_cmd == "qRcmd")
{
}
else if (query_cmd == "qC")
{
context->QueueResponse("QC");
context->QueueResponse(std::to_string(m_activeThreadContinueSelector));
}
else if (query_cmd == "qOffsets")
{
const auto module_count = RPLLoader_GetModuleCount();
const auto module_list = RPLLoader_GetModuleList();
for (sint32 i = 0; i < module_count; i++)
{
const RPLModule* rpl = module_list[i];
if (rpl->entrypoint == m_entry_point)
{
context->QueueResponse(fmt::format("TextSeg={:08X};DataSeg={:08X}", rpl->regionMappingBase_text.GetMPTR(), rpl->regionMappingBase_data));
}
}
}
else if (query_cmd == "qfThreadInfo")
{
std::vector<std::string> threadIds;
selectThread(-1, [&threadIds](OSThread_t* thread) {
threadIds.emplace_back(fmt::format("{:08X}", memory_getVirtualOffsetFromPointer(thread)));
});
context->QueueResponse(fmt::format("m{}", fmt::join(threadIds, ",")));
}
else if (query_cmd == "qsThreadInfo")
{
context->QueueResponse("l");
}
else if (query_cmd == "qXfer")
{
auto& type = query_args[0];
if (type == "features")
{
auto& annex = query_args[1];
sint64 read_offset = std::stoul(query_args[2], nullptr, 16);
sint64 read_length = std::stoul(query_args[3], nullptr, 16);
if (annex == "target.xml")
{
if (read_offset >= GDBTargetXML.size())
context->QueueResponse("l");
else
{
auto paginated_str = GDBTargetXML.substr(read_offset, read_length);
context->QueueResponse((paginated_str.size() == read_length) ? "m" : "l");
context->QueueResponse(paginated_str);
}
}
else
cemuLog_logDebug(LogType::Force, "[GDBStub] qXfer:features:read:{} isn't a known feature document", annex);
}
else if (type == "threads")
{
sint64 read_offset = std::stoul(query_args[1], nullptr, 16);
sint64 read_length = std::stoul(query_args[2], nullptr, 16);
std::string threads_res;
threads_res += R"(<?xml version="1.0"?>)";
threads_res += "<threads>";
// note: clion seems to default to the first thread
std::map<sint64, std::string> threads_list;
selectThread(-1, [&threads_list](OSThread_t* thread) {
std::string entry;
entry += fmt::format(R"(<thread id="{:x}" core="{}")", GET_THREAD_ID(thread), thread->context.upir.value());
if (!thread->threadName.IsNull())
entry += fmt::format(R"( name="{}")", CommandContext::EscapeXMLString(thread->threadName.GetPtr()));
// todo: could add a human-readable description of the thread here
entry += fmt::format("></thread>");
threads_list.emplace(GET_THREAD_ID(thread), entry);
});
for (auto& entry : threads_list)
{
threads_res += entry.second;
}
threads_res += "</threads>";
if (read_offset >= threads_res.size())
context->QueueResponse("l");
else
{
auto paginated_str = threads_res.substr(read_offset, read_length);
context->QueueResponse((paginated_str.size() == read_length) ? "m" : "l");
context->QueueResponse(paginated_str);
}
}
else if (type == "libraries")
{
sint64 read_offset = std::stoul(query_args[1], nullptr, 16);
sint64 read_length = std::stoul(query_args[2], nullptr, 16);
std::string library_list;
library_list += R"(<?xml version="1.0"?>)";
library_list += "<library-list>";
const auto module_count = RPLLoader_GetModuleCount();
const auto module_list = RPLLoader_GetModuleList();
for (sint32 i = 0; i < module_count; i++)
{
library_list += fmt::format(R"(<library name="{}"><segment address="{:#x}"/></library>)", CommandContext::EscapeXMLString(module_list[i]->moduleName2), module_list[i]->regionMappingBase_text.GetMPTR());
}
library_list += "</library-list>";
if (read_offset >= library_list.size())
context->QueueResponse("l");
else
{
auto paginated_str = library_list.substr(read_offset, read_length);
context->QueueResponse((paginated_str.size() == read_length) ? "m" : "l");
context->QueueResponse(paginated_str);
}
}
else
{
context->QueueResponse(RESPONSE_EMPTY);
}
}
else
{
context->QueueResponse(RESPONSE_EMPTY);
}
}
void GDBServer::HandleVCont(std::unique_ptr<CommandContext>& context)
{
if (!context->IsValid())
{
cemuLog_logDebug(LogType::Force, "[GDBStub] Received unsupported vCont command: {}", context->GetCommand());
// cemu_assert_unimplemented();
return context->QueueResponse(RESPONSE_EMPTY);
}
const std::string& vcont_cmd = context->GetArgs()[0];
if (vcont_cmd == "vCont?")
return context->QueueResponse("vCont;c;C;s;S");
else if (vcont_cmd != "vCont;")
return context->QueueResponse(RESPONSE_EMPTY);
m_resumed_context = std::move(context);
bool resumedNoThreads = true;
for (const auto operation : TokenizeView(m_resumed_context->GetArgs()[1], ';'))
{
// todo: this might have issues with the signal versions (C/S)
// todo: test whether this works with multiple vCont;c:123123;c:123123
std::string_view operationType = operation.substr(0, operation.find(':'));
sint64 threadSelector = operationType.size() == operation.size() ? -1 : std::stoll(std::string(operation.substr(operationType.size() + 1)), nullptr, 16);
if (operationType == "c" || operationType.starts_with("C"))
{
selectAndResumeThread(threadSelector);
resumedNoThreads = false;
}
else if (operationType == "s" || operationType.starts_with("S"))
{
selectThread(threadSelector, [this](OSThread_t* thread) {
auto nextInstructions = findNextInstruction(thread->context.srr0, thread->context.lr, thread->context.ctr);
for (MPTR nextInstr : nextInstructions)
{
auto bpIt = m_patchedInstructions.find(nextInstr);
if (bpIt == m_patchedInstructions.end())
this->m_patchedInstructions.try_emplace(nextInstr, nextInstr, BreakpointType::BP_STEP_POINT, false, "swbreak:;");
else
bpIt->second.PauseOnNextInterrupt();
}
});
}
}
if (resumedNoThreads)
{
selectAndResumeThread(-1);
cemuLog_logDebug(LogType::Force, "[GDBStub] Resumed all threads after skip instructions");
}
}
void GDBServer::CMDContinue(std::unique_ptr<CommandContext>& context)
{
m_resumed_context = std::move(context);
selectAndResumeThread(m_activeThreadContinueSelector);
}
void GDBServer::CMDNotFound(std::unique_ptr<CommandContext>& context)
{
return context->QueueResponse(RESPONSE_EMPTY);
}
void GDBServer::CMDIsThreadActive(std::unique_ptr<CommandContext>& context)
{
sint64 threadSelector = std::stoll(context->GetArgs()[1], nullptr, 16);
bool foundThread = false;
selectThread(threadSelector, [&foundThread](OSThread_t* thread) {
foundThread = true;
});
if (foundThread)
return context->QueueResponse(RESPONSE_OK);
else
return context->QueueResponse(RESPONSE_ERROR);
}
void GDBServer::CMDSetActiveThread(std::unique_ptr<CommandContext>& context)
{
sint64 threadSelector = std::stoll(context->GetArgs()[2], nullptr, 16);
if (threadSelector >= 0)
{
bool foundThread = false;
selectThread(threadSelector, [&foundThread](OSThread_t* thread) {
foundThread = true;
});
if (!foundThread)
return context->QueueResponse(RESPONSE_ERROR);
}
if (context->GetArgs()[1] == "c")
m_activeThreadContinueSelector = threadSelector;
else
m_activeThreadSelector = threadSelector;
return context->QueueResponse(RESPONSE_OK);
}
void GDBServer::CMDGetThreadStatus(std::unique_ptr<CommandContext>& context)
{
selectThread(0, [&context](OSThread_t* thread) {
context->QueueResponse(fmt::format("T05thread:{:08X};", memory_getVirtualOffsetFromPointer(thread)));
});
}
void GDBServer::CMDReadRegister(std::unique_ptr<CommandContext>& context) const
{
sint32 reg = std::stoi(context->GetArgs()[1], nullptr, 16);
selectThread(m_activeThreadSelector, [reg, &context](OSThread_t* thread) {
auto& cpu = thread->context;
if (reg >= RegisterID::R0_START && reg <= RegisterID::R31_END)
{
return context->QueueResponse(fmt::format("{:08X}", CPU_swapEndianU32(cpu.gpr[reg])));
}
else if (reg >= RegisterID::F0_START && reg <= RegisterID::F31_END)
{
return context->QueueResponse(fmt::format("{:016X}", cpu.fp_ps0[reg - RegisterID::F0_START].value()));
}
else if (reg == RegisterID::FPSCR)
{
return context->QueueResponse(fmt::format("{:08X}", cpu.fpscr.fpscr.value()));
}
else
{
switch (reg)
{
case RegisterID::PC: return context->QueueResponse(fmt::format("{:08X}", cpu.srr0));
case RegisterID::MSR: return context->QueueResponse("xxxxxxxx");
case RegisterID::CR: return context->QueueResponse(fmt::format("{:08X}", cpu.cr));
case RegisterID::LR: return context->QueueResponse(fmt::format("{:08X}", CPU_swapEndianU32(cpu.lr)));
case RegisterID::CTR: return context->QueueResponse(fmt::format("{:08X}", cpu.ctr));
case RegisterID::XER: return context->QueueResponse(fmt::format("{:08X}", cpu.xer));
default: break;
}
}
});
}
void GDBServer::CMDWriteRegister(std::unique_ptr<CommandContext>& context) const
{
sint32 reg = std::stoi(context->GetArgs()[1], nullptr, 16);
uint64 value = std::stoll(context->GetArgs()[2], nullptr, 16);
selectThread(m_activeThreadSelector, [reg, value, &context](OSThread_t* thread) {
auto& cpu = thread->context;
if (reg >= RegisterID::R0_START && reg <= RegisterID::R31_END)
{
cpu.gpr[reg] = CPU_swapEndianU32(value);
return context->QueueResponse(RESPONSE_OK);
}
else if (reg >= RegisterID::F0_START && reg <= RegisterID::F31_END)
{
// todo: figure out how to properly write to paired single registers
cpu.fp_ps0[reg - RegisterID::F0_START] = uint64be{value};
return context->QueueResponse(RESPONSE_OK);
}
else if (reg == RegisterID::FPSCR)
{
cpu.fpscr.fpscr = uint32be{(uint32)value};
return context->QueueResponse(RESPONSE_OK);
}
else
{
switch (reg)
{
case RegisterID::PC:
cpu.srr0 = value;
return context->QueueResponse(RESPONSE_OK);
case RegisterID::MSR:
return context->QueueResponse(RESPONSE_ERROR);
case RegisterID::CR:
cpu.cr = value;
return context->QueueResponse(RESPONSE_OK);
case RegisterID::LR:
cpu.lr = CPU_swapEndianU32(value);
return context->QueueResponse(RESPONSE_OK);
case RegisterID::CTR:
cpu.ctr = value;
return context->QueueResponse(RESPONSE_OK);
case RegisterID::XER:
cpu.xer = value;
return context->QueueResponse(RESPONSE_OK);
default:
return context->QueueResponse(RESPONSE_ERROR);
}
}
});
}
void GDBServer::CMDReadRegisters(std::unique_ptr<CommandContext>& context) const
{
selectThread(m_activeThreadSelector, [&context](OSThread_t* thread) {
for (uint32& reg : thread->context.gpr)
{
context->QueueResponse(fmt::format("{:08X}", CPU_swapEndianU32(reg)));
}
});
}
void GDBServer::CMDWriteRegisters(std::unique_ptr<CommandContext>& context) const
{
selectThread(m_activeThreadSelector, [&context](OSThread_t* thread) {
auto& registers = context->GetArgs()[1];
for (uint32 i = 0; i < 32; i++)
{
thread->context.gpr[i] = CPU_swapEndianU32(std::stoi(registers.substr(i * 2, 2), nullptr, 16));
}
});
}
void GDBServer::CMDReadMemory(std::unique_ptr<CommandContext>& context)
{
sint64 addr = std::stoul(context->GetArgs()[1], nullptr, 16);
sint64 length = std::stoul(context->GetArgs()[2], nullptr, 16);
// todo: handle cross-mmu-range memory requests
if (!memory_isAddressRangeAccessible(addr, length))
return context->QueueResponse(RESPONSE_ERROR);
std::string memoryRepr;
uint8* values = memory_getPointerFromVirtualOffset(addr);
for (sint64 i = 0; i < length; i++)
{
memoryRepr += fmt::format("{:02X}", values[i]);
}
auto patchesRange = m_patchedInstructions.lower_bound(addr);
while (patchesRange != m_patchedInstructions.end() && patchesRange->first < (addr + length))
{
auto replStr = fmt::format("{:02X}", patchesRange->second.GetVisibleOpCode());
memoryRepr[(patchesRange->first - addr) * 2] = replStr[0];
memoryRepr[(patchesRange->first - addr) * 2 + 1] = replStr[1];
patchesRange++;
}
return context->QueueResponse(memoryRepr);
}
void GDBServer::CMDWriteMemory(std::unique_ptr<CommandContext>& context)
{
sint64 addr = std::stoul(context->GetArgs()[1], nullptr, 16);
sint64 length = std::stoul(context->GetArgs()[2], nullptr, 16);
auto source = context->GetArgs()[3];
// todo: handle cross-mmu-range memory requests
if (!memory_isAddressRangeAccessible(addr, length))
return context->QueueResponse(RESPONSE_ERROR);
uint8* values = memory_getPointerFromVirtualOffset(addr);
for (sint64 i = 0; i < length; i++)
{
uint8 hexValue;
const std::from_chars_result result = std::from_chars(source.data() + (i * 2), (source.data() + (i * 2) + 2), hexValue, 16);
if (result.ec == std::errc::invalid_argument || result.ec == std::errc::result_out_of_range)
return context->QueueResponse(RESPONSE_ERROR);
if (auto it = m_patchedInstructions.find(addr + i); it != m_patchedInstructions.end())
{
uint32 newOpCode = it->second.GetVisibleOpCode();
uint32 byteIndex = 3 - ((addr + i) % 4); // inverted because of big endian, so address 0 is the highest byte
newOpCode &= ~(0xFF << (byteIndex * 8)); // mask out the byte
newOpCode |= ((uint32)hexValue << (byteIndex * 8)); // set new byte with OR
it->second.WriteNewOpCode(newOpCode);
}
else
{
values[i] = hexValue;
}
}
return context->QueueResponse(RESPONSE_OK);
}
void GDBServer::CMDInsertBreakpoint(std::unique_ptr<CommandContext>& context)
{
auto type = std::stoul(context->GetArgs()[1], nullptr, 16);
MPTR addr = static_cast<MPTR>(std::stoul(context->GetArgs()[2], nullptr, 16));
if (type == 0 || type == 1)
{
auto bp = this->m_patchedInstructions.find(addr);
if (bp != this->m_patchedInstructions.end())
this->m_patchedInstructions.erase(bp);
this->m_patchedInstructions.try_emplace(addr, addr, BreakpointType::BP_PERSISTENT, type == 0, type == 0 ? "swbreak:;" : "hwbreak:;");
}
else if (type == 2 || type == 3 || type == 4)
{
if (this->m_watch_point)
return context->QueueResponse(RESPONSE_ERROR);
this->m_watch_point = std::make_unique<AccessBreakpoint>(addr, (AccessPointType)type);
}
return context->QueueResponse(RESPONSE_OK);
}
void GDBServer::CMDDeleteBreakpoint(std::unique_ptr<CommandContext>& context)
{
auto type = std::stoul(context->GetArgs()[1], nullptr, 16);
MPTR addr = static_cast<MPTR>(std::stoul(context->GetArgs()[2], nullptr, 16));
if (type == 0 || type == 1)
{
auto bp = this->m_patchedInstructions.find(addr);
if (bp == this->m_patchedInstructions.end() || !bp->second.ShouldBreakThreads())
return context->QueueResponse(RESPONSE_ERROR);
else
this->m_patchedInstructions.erase(bp);
}
else if (type == 2 || type == 3 || type == 4)
{
if (!this->m_watch_point || this->m_watch_point->GetAddress() != addr)
return context->QueueResponse(RESPONSE_ERROR);
this->m_watch_point.reset();
}
return context->QueueResponse(RESPONSE_OK);
}
// Internal functions for control
void GDBServer::HandleTrapInstruction(PPCInterpreter_t* hCPU)
{
// First, restore any removed breakpoints
for (auto& bp : m_patchedInstructions)
{
if (bp.second.IsRemoved())
bp.second.Restore();
}
auto patchedBP = m_patchedInstructions.find(hCPU->instructionPointer);
if (patchedBP == m_patchedInstructions.end())
return cemu_assert_suspicious();
// Secondly, delete one-shot breakpoints but also temporarily delete patched instruction to run original instruction
OSThread_t* currThread = coreinit::OSGetCurrentThread();
std::string pauseReason = fmt::format("T05thread:{:08X};core:{:02X};{}", GET_THREAD_ID(currThread), PPCInterpreter_getCoreIndex(hCPU), patchedBP->second.GetReason());
bool pauseThreads = patchedBP->second.ShouldBreakThreads() || patchedBP->second.ShouldBreakThreadsOnNextInterrupt();
if (patchedBP->second.IsPersistent())
{
// Insert new restore breakpoints at next possible instructions which restores breakpoints but won't pause the CPU
std::vector<MPTR> nextInstructions = findNextInstruction(hCPU->instructionPointer, hCPU->spr.LR, hCPU->spr.CTR);
for (MPTR nextInstr : nextInstructions)
{
if (!m_patchedInstructions.contains(nextInstr))
this->m_patchedInstructions.try_emplace(nextInstr, nextInstr, BreakpointType::BP_STEP_POINT, false, "");
}
patchedBP->second.RemoveTemporarily();
}
else
{
m_patchedInstructions.erase(patchedBP);
}
// Thirdly, delete any instructions that were generated by a skip instruction
for (auto it = m_patchedInstructions.cbegin(), next_it = it; it != m_patchedInstructions.cend(); it = next_it)
{
++next_it;
if (it->second.IsSkipBreakpoint())
{
m_patchedInstructions.erase(it);
}
}
// Fourthly, the stub can insert breakpoints that are just meant to restore patched instructions, in which case we just want to continue
if (pauseThreads)
{
cemuLog_logDebug(LogType::Force, "[GDBStub] Got trapped by a breakpoint!");
if (m_resumed_context)
{
// Spin up thread to signal when another GDB stub trap is found
ThreadPool::FireAndForget(&waitForBrokenThreads, std::move(m_resumed_context), pauseReason);
}
breakThreads(GET_THREAD_ID(coreinit::OSGetCurrentThread()));
cemuLog_logDebug(LogType::Force, "[GDBStub] Resumed from a breakpoint!");
}
}
void GDBServer::HandleAccessException(uint64 dr6)
{
bool triggeredWrite = GetBits(dr6, 2, 1);
bool triggeredReadWrite = GetBits(dr6, 3, 1);
std::string response;
if (m_watch_point->GetType() == AccessPointType::BP_WRITE && triggeredWrite)
response = fmt::format("watch:{:08X};", m_watch_point->GetAddress());
else if (m_watch_point->GetType() == AccessPointType::BP_READ && triggeredReadWrite && !triggeredWrite)
response = fmt::format("rwatch:{:08X};", m_watch_point->GetAddress());
else if (m_watch_point->GetType() == AccessPointType::BP_BOTH && triggeredReadWrite)
response = fmt::format("awatch:{:08X};", m_watch_point->GetAddress());
if (!response.empty())
{
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
cemuLog_logDebug(LogType::Force, "Received matching breakpoint exception: {}", response);
auto nextInstructions = findNextInstruction(hCPU->instructionPointer, hCPU->spr.LR, hCPU->spr.CTR);
for (MPTR nextInstr : nextInstructions)
{
auto bpIt = m_patchedInstructions.find(nextInstr);
if (bpIt == m_patchedInstructions.end())
this->m_patchedInstructions.try_emplace(nextInstr, nextInstr, BreakpointType::BP_STEP_POINT, false, response);
else
bpIt->second.PauseOnNextInterrupt();
}
}
}
void GDBServer::HandleEntryStop(uint32 entryAddress)
{
this->m_patchedInstructions.try_emplace(entryAddress, entryAddress, BreakpointType::BP_SINGLE, false, "");
m_entry_point = entryAddress;
}
| 30,462
|
C++
|
.cpp
| 893
| 31.162374
| 206
| 0.711145
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,199
|
GDBBreakpoints.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/Debugger/GDBBreakpoints.cpp
|
#include "GDBBreakpoints.h"
#include "Debugger.h"
#include "Cafe/HW/Espresso/Recompiler/PPCRecompiler.h"
#if defined(ARCH_X86_64) && BOOST_OS_LINUX
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <sys/user.h>
DRType _GetDR(pid_t tid, int drIndex)
{
size_t drOffset = offsetof(struct user, u_debugreg) + drIndex * sizeof(user::u_debugreg[0]);
long v;
v = ptrace(PTRACE_PEEKUSER, tid, drOffset, nullptr);
if (v == -1)
perror("ptrace(PTRACE_PEEKUSER)");
return (DRType)v;
}
void _SetDR(pid_t tid, int drIndex, DRType newValue)
{
size_t drOffset = offsetof(struct user, u_debugreg) + drIndex * sizeof(user::u_debugreg[0]);
long rc = ptrace(PTRACE_POKEUSER, tid, drOffset, newValue);
if (rc == -1)
perror("ptrace(PTRACE_POKEUSER)");
}
DRType _ReadDR6()
{
pid_t tid = gettid();
// linux doesn't let us attach to the current thread / threads in the current thread group
// we have to create a child process which then modifies the debug registers and quits
pid_t child = fork();
if (child == -1)
{
perror("fork");
return 0;
}
if (child == 0)
{
if (ptrace(PTRACE_ATTACH, tid, nullptr, nullptr))
{
perror("attach");
_exit(0);
}
waitpid(tid, NULL, 0);
uint64_t dr6 = _GetDR(tid, 6);
if (ptrace(PTRACE_DETACH, tid, nullptr, nullptr))
perror("detach");
// since the status code only uses the lower 8 bits, we have to discard the rest of DR6
// this should be fine though, since the lower 4 bits of DR6 contain all the bp conditions
_exit(dr6 & 0xff);
}
// wait for child process
int wstatus;
waitpid(child, &wstatus, 0);
return (DRType)WEXITSTATUS(wstatus);
}
#endif
GDBServer::ExecutionBreakpoint::ExecutionBreakpoint(MPTR address, BreakpointType type, bool visible, std::string reason)
: m_address(address), m_removedAfterInterrupt(false), m_reason(std::move(reason))
{
if (type == BreakpointType::BP_SINGLE)
{
this->m_pauseThreads = true;
this->m_restoreAfterInterrupt = false;
this->m_deleteAfterAnyInterrupt = false;
this->m_pauseOnNextInterrupt = false;
this->m_visible = visible;
}
else if (type == BreakpointType::BP_PERSISTENT)
{
this->m_pauseThreads = true;
this->m_restoreAfterInterrupt = true;
this->m_deleteAfterAnyInterrupt = false;
this->m_pauseOnNextInterrupt = false;
this->m_visible = visible;
}
else if (type == BreakpointType::BP_RESTORE_POINT)
{
this->m_pauseThreads = false;
this->m_restoreAfterInterrupt = false;
this->m_deleteAfterAnyInterrupt = false;
this->m_pauseOnNextInterrupt = false;
this->m_visible = false;
}
else if (type == BreakpointType::BP_STEP_POINT)
{
this->m_pauseThreads = false;
this->m_restoreAfterInterrupt = false;
this->m_deleteAfterAnyInterrupt = true;
this->m_pauseOnNextInterrupt = true;
this->m_visible = false;
}
this->m_origOpCode = memory_readU32(address);
memory_writeU32(address, DEBUGGER_BP_T_GDBSTUB_TW);
PPCRecompiler_invalidateRange(address, address + 4);
}
GDBServer::ExecutionBreakpoint::~ExecutionBreakpoint()
{
memory_writeU32(this->m_address, this->m_origOpCode);
PPCRecompiler_invalidateRange(this->m_address, this->m_address + 4);
}
uint32 GDBServer::ExecutionBreakpoint::GetVisibleOpCode() const
{
if (this->m_visible)
return memory_readU32(this->m_address);
else
return this->m_origOpCode;
}
void GDBServer::ExecutionBreakpoint::RemoveTemporarily()
{
memory_writeU32(this->m_address, this->m_origOpCode);
PPCRecompiler_invalidateRange(this->m_address, this->m_address + 4);
this->m_restoreAfterInterrupt = true;
}
void GDBServer::ExecutionBreakpoint::Restore()
{
memory_writeU32(this->m_address, DEBUGGER_BP_T_GDBSTUB_TW);
PPCRecompiler_invalidateRange(this->m_address, this->m_address + 4);
this->m_restoreAfterInterrupt = false;
}
namespace coreinit
{
#if BOOST_OS_LINUX
std::vector<pid_t>& OSGetSchedulerThreadIds();
#endif
std::vector<std::thread::native_handle_type>& OSGetSchedulerThreads();
}
GDBServer::AccessBreakpoint::AccessBreakpoint(MPTR address, AccessPointType type)
: m_address(address), m_type(type)
{
#if defined(ARCH_X86_64) && BOOST_OS_WINDOWS
for (auto& hThreadNH : coreinit::OSGetSchedulerThreads())
{
HANDLE hThread = (HANDLE)hThreadNH;
CONTEXT ctx{};
ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
SuspendThread(hThread);
GetThreadContext(hThread, &ctx);
// use BP 2/3 for gdb stub since cemu's internal debugger uses BP 0/1 already
ctx.Dr2 = (DWORD64)memory_getPointerFromVirtualOffset(address);
ctx.Dr3 = (DWORD64)memory_getPointerFromVirtualOffset(address);
// breakpoint 2
SetBits(ctx.Dr7, 4, 1, 1); // breakpoint #3 enabled: true
SetBits(ctx.Dr7, 24, 2, 1); // breakpoint #3 condition: 1 (write)
SetBits(ctx.Dr7, 26, 2, 3); // breakpoint #3 length: 3 (4 bytes)
// breakpoint 3
SetBits(ctx.Dr7, 6, 1, 1); // breakpoint #4 enabled: true
SetBits(ctx.Dr7, 28, 2, 3); // breakpoint #4 condition: 3 (read & write)
SetBits(ctx.Dr7, 30, 2, 3); // breakpoint #4 length: 3 (4 bytes)
SetThreadContext(hThread, &ctx);
ResumeThread(hThread);
}
#elif defined(ARCH_X86_64) && BOOST_OS_LINUX
// linux doesn't let us attach to threads which are in the same thread group as our current thread
// we have to create a child process which then modifies the debug registers and quits
pid_t child = fork();
if (child == -1)
{
perror("fork");
return;
}
if (child == 0)
{
for (pid_t tid : coreinit::OSGetSchedulerThreadIds())
{
long rc = ptrace(PTRACE_ATTACH, tid, nullptr, nullptr);
if (rc == -1)
perror("ptrace(PTRACE_ATTACH)");
waitpid(tid, nullptr, 0);
DRType dr7 = _GetDR(tid, 7);
// use BP 2/3 for gdb stub since cemu's internal debugger uses BP 0/1 already
DRType dr2 = (uint64)memory_getPointerFromVirtualOffset(address);
DRType dr3 = (uint64)memory_getPointerFromVirtualOffset(address);
// breakpoint 2
SetBits(dr7, 4, 1, 1); // breakpoint #3 enabled: true
SetBits(dr7, 24, 2, 1); // breakpoint #3 condition: 1 (write)
SetBits(dr7, 26, 2, 3); // breakpoint #3 length: 3 (4 bytes)
// breakpoint 3
SetBits(dr7, 6, 1, 1); // breakpoint #4 enabled: true
SetBits(dr7, 28, 2, 3); // breakpoint #4 condition: 3 (read & write)
SetBits(dr7, 30, 2, 3); // breakpoint #4 length: 3 (4 bytes)
_SetDR(tid, 2, dr2);
_SetDR(tid, 3, dr3);
_SetDR(tid, 7, dr7);
rc = ptrace(PTRACE_DETACH, tid, nullptr, nullptr);
if (rc == -1)
perror("ptrace(PTRACE_DETACH)");
}
// exit child process
_exit(0);
}
// wait for child process
waitpid(child, nullptr, 0);
#else
cemuLog_log(LogType::Force, "Debugger read/write breakpoints are not supported on non-x86 CPUs yet.");
#endif
}
GDBServer::AccessBreakpoint::~AccessBreakpoint()
{
#if defined(ARCH_X86_64) && BOOST_OS_WINDOWS
for (auto& hThreadNH : coreinit::OSGetSchedulerThreads())
{
HANDLE hThread = (HANDLE)hThreadNH;
CONTEXT ctx{};
ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
SuspendThread(hThread);
GetThreadContext(hThread, &ctx);
// reset BP 2/3 to zero
ctx.Dr2 = (DWORD64)0;
ctx.Dr3 = (DWORD64)0;
// breakpoint 2
SetBits(ctx.Dr7, 4, 1, 0);
SetBits(ctx.Dr7, 24, 2, 0);
SetBits(ctx.Dr7, 26, 2, 0);
// breakpoint 3
SetBits(ctx.Dr7, 6, 1, 0);
SetBits(ctx.Dr7, 28, 2, 0);
SetBits(ctx.Dr7, 30, 2, 0);
SetThreadContext(hThread, &ctx);
ResumeThread(hThread);
}
#elif defined(ARCH_X86_64) && BOOST_OS_LINUX
// linux doesn't let us attach to threads which are in the same thread group as our current thread
// we have to create a child process which then modifies the debug registers and quits
pid_t child = fork();
if (child == -1)
{
perror("fork");
return;
}
if (child == 0)
{
for (pid_t tid : coreinit::OSGetSchedulerThreadIds())
{
long rc = ptrace(PTRACE_ATTACH, tid, nullptr, nullptr);
if (rc == -1)
perror("ptrace(PTRACE_ATTACH)");
waitpid(tid, nullptr, 0);
DRType dr7 = _GetDR(tid, 7);
// reset BP 2/3 to zero
DRType dr2 = 0;
DRType dr3 = 0;
// breakpoint 2
SetBits(dr7, 4, 1, 0);
SetBits(dr7, 24, 2, 0);
SetBits(dr7, 26, 2, 0);
// breakpoint 3
SetBits(dr7, 6, 1, 0);
SetBits(dr7, 28, 2, 0);
SetBits(dr7, 30, 2, 0);
_SetDR(tid, 2, dr2);
_SetDR(tid, 3, dr3);
_SetDR(tid, 7, dr7);
rc = ptrace(PTRACE_DETACH, tid, nullptr, nullptr);
if (rc == -1)
perror("ptrace(PTRACE_DETACH)");
}
// exit child process
_exit(0);
}
// wait for child process
waitpid(child, nullptr, 0);
#endif
}
| 8,414
|
C++
|
.cpp
| 262
| 29.446565
| 120
| 0.706042
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,200
|
PPCRecompilerX64Gen.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/Recompiler/PPCRecompilerX64Gen.cpp
|
#include "PPCRecompiler.h"
#include "PPCRecompilerIml.h"
#include "PPCRecompilerX64.h"
// x86/x64 extension opcodes that could be useful:
// ANDN
// mulx, rorx, sarx, shlx, shrx
// PDEP, PEXT
void x64Gen_checkBuffer(x64GenContext_t* x64GenContext)
{
// todo
}
void x64Gen_writeU8(x64GenContext_t* x64GenContext, uint8 v)
{
if( x64GenContext->codeBufferIndex+1 > x64GenContext->codeBufferSize )
{
x64GenContext->codeBufferSize *= 2;
x64GenContext->codeBuffer = (uint8*)realloc(x64GenContext->codeBuffer, x64GenContext->codeBufferSize);
}
*(uint8*)(x64GenContext->codeBuffer+x64GenContext->codeBufferIndex) = v;
x64GenContext->codeBufferIndex++;
}
void x64Gen_writeU16(x64GenContext_t* x64GenContext, uint32 v)
{
if( x64GenContext->codeBufferIndex+2 > x64GenContext->codeBufferSize )
{
x64GenContext->codeBufferSize *= 2;
x64GenContext->codeBuffer = (uint8*)realloc(x64GenContext->codeBuffer, x64GenContext->codeBufferSize);
}
*(uint16*)(x64GenContext->codeBuffer+x64GenContext->codeBufferIndex) = v;
x64GenContext->codeBufferIndex += 2;
}
void x64Gen_writeU32(x64GenContext_t* x64GenContext, uint32 v)
{
if( x64GenContext->codeBufferIndex+4 > x64GenContext->codeBufferSize )
{
x64GenContext->codeBufferSize *= 2;
x64GenContext->codeBuffer = (uint8*)realloc(x64GenContext->codeBuffer, x64GenContext->codeBufferSize);
}
*(uint32*)(x64GenContext->codeBuffer+x64GenContext->codeBufferIndex) = v;
x64GenContext->codeBufferIndex += 4;
}
void x64Gen_writeU64(x64GenContext_t* x64GenContext, uint64 v)
{
if( x64GenContext->codeBufferIndex+8 > x64GenContext->codeBufferSize )
{
x64GenContext->codeBufferSize *= 2;
x64GenContext->codeBuffer = (uint8*)realloc(x64GenContext->codeBuffer, x64GenContext->codeBufferSize);
}
*(uint64*)(x64GenContext->codeBuffer+x64GenContext->codeBufferIndex) = v;
x64GenContext->codeBufferIndex += 8;
}
#include "x64Emit.hpp"
void _x64Gen_writeMODRMDeprecated(x64GenContext_t* x64GenContext, sint32 dataRegister, sint32 memRegisterA64, sint32 memRegisterB64, sint32 memImmS32)
{
bool forceUseOffset = false;
if ((memRegisterA64 & 7) == 5)
{
// RBP and R13 have no memImmS32 == 0 encoding, therefore we need to use a 1 byte offset with the value 0
forceUseOffset = true;
}
if (memRegisterB64 == REG_NONE)
{
// memRegisterA64 + memImmS32
uint8 modRM = (dataRegister & 7) * 8 + (memRegisterA64 & 7);
if (forceUseOffset && memImmS32 == 0)
{
// 1 byte offset
modRM |= (1 << 6);
}
if (memImmS32 == 0)
{
// no offset
modRM |= (0 << 6);
}
else if (memImmS32 >= -128 && memImmS32 <= 127)
{
// 1 byte offset
modRM |= (1 << 6);
}
else
{
// 4 byte offset
modRM |= (2 << 6);
}
x64Gen_writeU8(x64GenContext, modRM);
// SIB byte
if ((memRegisterA64 & 7) == 4) // RSP and R12
{
x64Gen_writeU8(x64GenContext, 0x24);
}
// offset
if (((modRM >> 6) & 3) == 0)
; // no offset
else if (((modRM >> 6) & 3) == 1)
x64Gen_writeU8(x64GenContext, (uint8)memImmS32);
else if (((modRM >> 6) & 3) == 2)
x64Gen_writeU32(x64GenContext, (uint32)memImmS32);
else
assert_dbg();
return;
}
// note: Swapping mem register A and mem register B does not work because the instruction prefix defines the register group which might not match (e.g. regA in r0-r8 range and regB in RAX-RDI range)
if( (memRegisterA64&7) == 4 )
{
assert_dbg();
//sint32 temp = memRegisterA64;
//memRegisterA64 = memRegisterB64;
//memRegisterB64 = temp;
}
//if( (memRegisterA64&7) == 5 )
//{
// sint32 temp = memRegisterA64;
// memRegisterA64 = memRegisterB64;
// memRegisterB64 = temp;
//}
if( (memRegisterA64&7) == 4 )
assert_dbg();
uint8 modRM = (0x04<<0)+((dataRegister&7)<<3);
if( forceUseOffset && memImmS32 == 0 )
{
// 1 byte offset
modRM |= (1<<6);
}
if( memImmS32 == 0 )
{
// no offset
modRM |= (0<<6);
}
else if( memImmS32 >= -128 && memImmS32 <= 127 )
{
// 1 byte offset
modRM |= (1<<6);
}
else
{
// 4 byte offset
modRM |= (2<<6);
}
x64Gen_writeU8(x64GenContext, modRM);
// sib byte
x64Gen_writeU8(x64GenContext, 0x00+(memRegisterA64&7)+(memRegisterB64&7)*8);
// offset
if( ((modRM>>6)&3) == 0 )
; // no offset
else if( ((modRM>>6)&3) == 1 )
x64Gen_writeU8(x64GenContext, (uint8)memImmS32);
else if( ((modRM>>6)&3) == 2 )
x64Gen_writeU32(x64GenContext, (uint32)memImmS32);
else
assert_dbg();
}
void x64Emit_mov_reg32_mem32(x64GenContext_t* x64GenContext, sint32 destReg, sint32 memBaseReg64, sint32 memOffset)
{
x64Gen_writeMODRM_dyn<x64_opc_1byte<0x8B>>(x64GenContext, x64MODRM_opr_reg64(destReg), x64MODRM_opr_memReg64(memBaseReg64, memOffset));
}
void x64Emit_mov_mem32_reg32(x64GenContext_t* x64GenContext, sint32 memBaseReg64, sint32 memOffset, sint32 srcReg)
{
x64Gen_writeMODRM_dyn<x64_opc_1byte_rev<0x89>>(x64GenContext, x64MODRM_opr_memReg64(memBaseReg64, memOffset), x64MODRM_opr_reg64(srcReg));
}
void x64Emit_mov_mem64_reg64(x64GenContext_t* x64GenContext, sint32 memBaseReg64, sint32 memOffset, sint32 srcReg)
{
x64Gen_writeMODRM_dyn<x64_opc_1byte_rev<0x89, true>>(x64GenContext, x64MODRM_opr_memReg64(memBaseReg64, memOffset), x64MODRM_opr_reg64(srcReg));
}
void x64Emit_mov_reg64_mem64(x64GenContext_t* x64GenContext, sint32 destReg, sint32 memBaseReg64, sint32 memOffset)
{
x64Gen_writeMODRM_dyn<x64_opc_1byte<0x8B, true>>(x64GenContext, x64MODRM_opr_reg64(destReg), x64MODRM_opr_memReg64(memBaseReg64, memOffset));
}
void x64Emit_mov_reg64_mem32(x64GenContext_t* x64GenContext, sint32 destReg, sint32 memBaseReg64, sint32 memOffset)
{
x64Gen_writeMODRM_dyn<x64_opc_1byte<0x8B>>(x64GenContext, x64MODRM_opr_reg64(destReg), x64MODRM_opr_memReg64(memBaseReg64, memOffset));
}
void x64Emit_mov_mem32_reg64(x64GenContext_t* x64GenContext, sint32 memBaseReg64, sint32 memOffset, sint32 srcReg)
{
x64Gen_writeMODRM_dyn<x64_opc_1byte_rev<0x89>>(x64GenContext, x64MODRM_opr_memReg64(memBaseReg64, memOffset), x64MODRM_opr_reg64(srcReg));
}
void x64Emit_mov_reg64_mem64(x64GenContext_t* x64GenContext, sint32 destReg, sint32 memBaseReg64, sint32 memIndexReg64, sint32 memOffset)
{
x64Gen_writeMODRM_dyn<x64_opc_1byte<0x8B, true>>(x64GenContext, x64MODRM_opr_reg64(destReg), x64MODRM_opr_memRegPlusReg(memBaseReg64, memIndexReg64, memOffset));
}
void x64Emit_mov_reg32_mem32(x64GenContext_t* x64GenContext, sint32 destReg, sint32 memBaseReg64, sint32 memIndexReg64, sint32 memOffset)
{
x64Gen_writeMODRM_dyn<x64_opc_1byte<0x8B>>(x64GenContext, x64MODRM_opr_reg64(destReg), x64MODRM_opr_memRegPlusReg(memBaseReg64, memIndexReg64, memOffset));
}
void x64Emit_mov_reg64b_mem8(x64GenContext_t* x64GenContext, sint32 destReg, sint32 memBaseReg64, sint32 memIndexReg64, sint32 memOffset)
{
x64Gen_writeMODRM_dyn<x64_opc_1byte<0x8A>>(x64GenContext, x64MODRM_opr_reg64(destReg), x64MODRM_opr_memRegPlusReg(memBaseReg64, memIndexReg64, memOffset));
}
void x64Emit_movZX_reg32_mem8(x64GenContext_t* x64GenContext, sint32 destReg, sint32 memBaseReg64, sint32 memIndexReg64, sint32 memOffset)
{
x64Gen_writeMODRM_dyn<x64_opc_2byte<0x0F,0xB6>>(x64GenContext, x64MODRM_opr_reg64(destReg), x64MODRM_opr_memRegPlusReg(memBaseReg64, memIndexReg64, memOffset));
}
void x64Emit_movZX_reg64_mem8(x64GenContext_t* x64GenContext, sint32 destReg, sint32 memBaseReg64, sint32 memOffset)
{
x64Gen_writeMODRM_dyn<x64_opc_2byte<0x0F, 0xB6>>(x64GenContext, x64MODRM_opr_reg64(destReg), x64MODRM_opr_memReg64(memBaseReg64, memOffset));
}
void x64Gen_movSignExtend_reg64Low32_mem8Reg64PlusReg64(x64GenContext_t* x64GenContext, sint32 dstRegister, sint32 memRegisterA64, sint32 memRegisterB64, sint32 memImmS32)
{
// MOVSX <dstReg64> (low dword), BYTE [<reg64> + <reg64> + <imm64>]
if (dstRegister >= 8 && memRegisterA64 >= 8 && memRegisterB64 >= 8)
x64Gen_writeU8(x64GenContext, 0x47);
else if (memRegisterA64 >= 8 && memRegisterB64 >= 8)
x64Gen_writeU8(x64GenContext, 0x43);
else if (dstRegister >= 8 && memRegisterB64 >= 8)
x64Gen_writeU8(x64GenContext, 0x42);
else if (dstRegister >= 8 && memRegisterA64 >= 8)
x64Gen_writeU8(x64GenContext, 0x45);
else if (dstRegister >= 8)
x64Gen_writeU8(x64GenContext, 0x44);
else if (memRegisterA64 >= 8)
x64Gen_writeU8(x64GenContext, 0x41);
else if (memRegisterB64 >= 8)
x64Gen_writeU8(x64GenContext, 0x42);
else if (dstRegister >= 4)
x64Gen_writeU8(x64GenContext, 0x40);
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0xBE);
_x64Gen_writeMODRMDeprecated(x64GenContext, dstRegister, memRegisterA64, memRegisterB64, memImmS32);
}
void x64Gen_mov_mem64Reg64PlusReg64_reg64(x64GenContext_t* x64GenContext, sint32 srcRegister, sint32 memRegisterA64, sint32 memRegisterB64, sint32 memImmS32)
{
// MOV QWORD [<reg64> + <reg64> + <imm64>], <dstReg64>
if( srcRegister >= 8 && memRegisterA64 >= 8 && memRegisterB64 >= 8 )
x64Gen_writeU8(x64GenContext, 0x47|8);
else if( memRegisterA64 >= 8 && memRegisterB64 >= 8 )
x64Gen_writeU8(x64GenContext, 0x43|8);
else if( srcRegister >= 8 && memRegisterB64 >= 8 )
x64Gen_writeU8(x64GenContext, 0x42|8);
else if( srcRegister >= 8 && memRegisterA64 >= 8 )
x64Gen_writeU8(x64GenContext, 0x45|8);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44|8);
else if( memRegisterA64 >= 8 )
x64Gen_writeU8(x64GenContext, 0x41|8);
else if( memRegisterB64 >= 8 )
x64Gen_writeU8(x64GenContext, 0x42|8);
else
x64Gen_writeU8(x64GenContext, 0x48);
x64Gen_writeU8(x64GenContext, 0x89);
_x64Gen_writeMODRMDeprecated(x64GenContext, srcRegister, memRegisterA64, memRegisterB64, memImmS32);
}
void x64Gen_movZeroExtend_reg64Low16_mem16Reg64PlusReg64(x64GenContext_t* x64GenContext, sint32 dstRegister, sint32 memRegisterA64, sint32 memRegisterB64, sint32 memImmS32)
{
// MOV <dstReg64> (low word), WORD [<reg64> + <reg64> + <imm64>]
x64Gen_writeU8(x64GenContext, 0x66); // 16bit prefix
x64Emit_mov_reg32_mem32(x64GenContext, dstRegister, memRegisterA64, memRegisterB64, memImmS32);
}
void x64Gen_movTruncate_mem32Reg64PlusReg64_reg64(x64GenContext_t* x64GenContext, sint32 memRegisterA64, sint32 memRegisterB64, sint32 memImmS32, sint32 srcRegister)
{
// MOV DWORD [<reg64> + <reg64> + <imm64>], <srcReg64> (low dword)
if( srcRegister >= 8 && memRegisterA64 >= 8 && memRegisterB64 >= 8 )
x64Gen_writeU8(x64GenContext, 0x47);
else if( memRegisterA64 >= 8 && memRegisterB64 >= 8 )
x64Gen_writeU8(x64GenContext, 0x43);
else if( srcRegister >= 8 && memRegisterB64 >= 8 )
x64Gen_writeU8(x64GenContext, 0x42);
else if( srcRegister >= 8 && memRegisterA64 >= 8 )
x64Gen_writeU8(x64GenContext, 0x45);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44);
else if( memRegisterA64 >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
else if( memRegisterB64 >= 8 )
x64Gen_writeU8(x64GenContext, 0x42);
x64Gen_writeU8(x64GenContext, 0x89);
_x64Gen_writeMODRMDeprecated(x64GenContext, srcRegister, memRegisterA64, memRegisterB64, memImmS32);
}
void x64Gen_movTruncate_mem16Reg64PlusReg64_reg64(x64GenContext_t* x64GenContext, sint32 memRegisterA64, sint32 memRegisterB64, sint32 memImmS32, sint32 srcRegister)
{
// MOV WORD [<reg64> + <reg64> + <imm64>], <srcReg64> (low dword)
x64Gen_writeU8(x64GenContext, 0x66); // 16bit prefix
x64Gen_movTruncate_mem32Reg64PlusReg64_reg64(x64GenContext, memRegisterA64, memRegisterB64, memImmS32, srcRegister);
}
void x64Gen_movTruncate_mem8Reg64PlusReg64_reg64(x64GenContext_t* x64GenContext, sint32 memRegisterA64, sint32 memRegisterB64, sint32 memImmS32, sint32 srcRegister)
{
// MOV BYTE [<reg64> + <reg64> + <imm64>], <srcReg64> (low byte)
// when no REX byte is present: Source register can range from AL to BH
// when a REX byte is present: Source register can range from AL to DIL or R8B to R15B
// todo: We don't need the REX byte when when the source register is AL,BL,CL or DL and neither memRegister A or B are within r8 - r15
uint8 rexByte = 0x40;
if( srcRegister >= 8 )
rexByte |= (1<<2);
if( memRegisterA64 >= 8 )
rexByte |= (1<<0);
if( memRegisterB64 >= 8 )
rexByte |= (1<<1);
x64Gen_writeU8(x64GenContext, rexByte);
x64Gen_writeU8(x64GenContext, 0x88);
_x64Gen_writeMODRMDeprecated(x64GenContext, srcRegister, memRegisterA64, memRegisterB64, memImmS32);
}
void x64Gen_mov_mem32Reg64_imm32(x64GenContext_t* x64GenContext, sint32 memRegister, uint32 memImmU32, uint32 dataImmU32)
{
// MOV DWORD [<memReg>+<memImmU32>], dataImmU32
if( (memRegister&7) == 4 )
{
if( memRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
sint32 memImmS32 = (sint32)memImmU32;
if( memImmS32 >= -128 && memImmS32 <= 127 )
{
x64Gen_writeU8(x64GenContext, 0xC7);
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint8)memImmU32);
}
else
{
x64Gen_writeU8(x64GenContext, 0xC7);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, memImmU32);
}
x64Gen_writeU32(x64GenContext, dataImmU32);
}
else
{
assert_dbg();
}
}
void x64Gen_mov_mem64Reg64_imm32(x64GenContext_t* x64GenContext, sint32 memRegister, uint32 memImmU32, uint32 dataImmU32)
{
// MOV QWORD [<memReg>+<memImmU32>], dataImmU32
if( memRegister == REG_R14 )
{
sint32 memImmS32 = (sint32)memImmU32;
if( memImmS32 == 0 )
{
x64Gen_writeU8(x64GenContext, 0x49);
x64Gen_writeU8(x64GenContext, 0xC7);
x64Gen_writeU8(x64GenContext, 0x06);
x64Gen_writeU32(x64GenContext, dataImmU32);
}
else if( memImmS32 >= -128 && memImmS32 <= 127 )
{
x64Gen_writeU8(x64GenContext, 0x49);
x64Gen_writeU8(x64GenContext, 0xC7);
x64Gen_writeU8(x64GenContext, 0x46);
x64Gen_writeU8(x64GenContext, (uint8)memImmS32);
x64Gen_writeU32(x64GenContext, dataImmU32);
}
else
{
assert_dbg();
}
}
else
{
assert_dbg();
}
}
void x64Gen_mov_mem8Reg64_imm8(x64GenContext_t* x64GenContext, sint32 memRegister, uint32 memImmU32, uint8 dataImmU8)
{
// MOV BYTE [<memReg64>+<memImmU32>], dataImmU8
if( memRegister == REG_RSP )
{
sint32 memImmS32 = (sint32)memImmU32;
if( memImmS32 >= -128 && memImmS32 <= 127 )
{
x64Gen_writeU8(x64GenContext, 0xC6);
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint8)memImmU32);
}
else
{
x64Gen_writeU8(x64GenContext, 0xC6);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, memImmU32);
}
x64Gen_writeU8(x64GenContext, dataImmU8);
}
else
{
assert_dbg();
}
}
void x64Gen_mov_reg64_imm64(x64GenContext_t* x64GenContext, sint32 destRegister, uint64 immU64)
{
// MOV <destReg64>, <imm64>
x64Gen_writeU8(x64GenContext, 0x48+(destRegister/8));
x64Gen_writeU8(x64GenContext, 0xB8+(destRegister%8));
x64Gen_writeU64(x64GenContext, immU64);
}
void x64Gen_mov_reg64Low32_imm32(x64GenContext_t* x64GenContext, sint32 destRegister, uint64 immU32)
{
// todo: Emit shorter opcode if immU32 is 0 or falls in sint8 range?
// MOV <destReg64>, <imm64>
if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0xB8+(destRegister&7));
x64Gen_writeU32(x64GenContext, (uint32)immU32);
}
void x64Gen_mov_reg64_reg64(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// MOV <destReg64>, <srcReg64>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x4D);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x49);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x4C);
else
x64Gen_writeU8(x64GenContext, 0x48);
x64Gen_writeU8(x64GenContext, 0x89);
x64Gen_writeU8(x64GenContext, 0xC0+(destRegister&7)+(srcRegister&7)*8);
}
void x64Gen_xchg_reg64_reg64(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// XCHG <destReg64>, <srcReg64>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x4D);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x49);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x4C);
else
x64Gen_writeU8(x64GenContext, 0x48);
x64Gen_writeU8(x64GenContext, 0x87);
x64Gen_writeU8(x64GenContext, 0xC0+(destRegister&7)+(srcRegister&7)*8);
}
void x64Gen_mov_reg64Low32_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// MOV <destReg64_low32>, <srcReg64_low32>
if (destRegister >= 8 && srcRegister >= 8)
x64Gen_writeU8(x64GenContext, 0x45);
else if (destRegister >= 8)
x64Gen_writeU8(x64GenContext, 0x41);
else if (srcRegister >= 8)
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x89);
x64Gen_writeU8(x64GenContext, 0xC0 + (destRegister & 7) + (srcRegister & 7) * 8);
}
void x64Gen_cmovcc_reg64Low32_reg64Low32(x64GenContext_t* x64GenContext, uint32 conditionType, sint32 destRegister, sint32 srcRegister)
{
// cMOVcc <destReg64_low32>, <srcReg64_low32>
if (destRegister >= 8 && srcRegister >= 8)
x64Gen_writeU8(x64GenContext, 0x45);
else if (srcRegister >= 8)
x64Gen_writeU8(x64GenContext, 0x41);
else if (destRegister >= 8)
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x0F);
if (conditionType == X86_CONDITION_CARRY || conditionType == X86_CONDITION_UNSIGNED_BELOW)
x64Gen_writeU8(x64GenContext, 0x42);
else if (conditionType == X86_CONDITION_NOT_CARRY || conditionType == X86_CONDITION_UNSIGNED_ABOVE_EQUAL)
x64Gen_writeU8(x64GenContext, 0x43);
else if (conditionType == X86_CONDITION_EQUAL)
x64Gen_writeU8(x64GenContext, 0x44);
else if (conditionType == X86_CONDITION_NOT_EQUAL)
x64Gen_writeU8(x64GenContext, 0x45);
else if (conditionType == X86_CONDITION_UNSIGNED_BELOW_EQUAL)
x64Gen_writeU8(x64GenContext, 0x46);
else if (conditionType == X86_CONDITION_UNSIGNED_ABOVE)
x64Gen_writeU8(x64GenContext, 0x47);
else if (conditionType == X86_CONDITION_SIGN)
x64Gen_writeU8(x64GenContext, 0x48);
else if (conditionType == X86_CONDITION_NOT_SIGN)
x64Gen_writeU8(x64GenContext, 0x49);
else if (conditionType == X86_CONDITION_PARITY)
x64Gen_writeU8(x64GenContext, 0x4A);
else if (conditionType == X86_CONDITION_SIGNED_LESS)
x64Gen_writeU8(x64GenContext, 0x4C);
else if (conditionType == X86_CONDITION_SIGNED_GREATER_EQUAL)
x64Gen_writeU8(x64GenContext, 0x4D);
else if (conditionType == X86_CONDITION_SIGNED_LESS_EQUAL)
x64Gen_writeU8(x64GenContext, 0x4E);
else if (conditionType == X86_CONDITION_SIGNED_GREATER)
x64Gen_writeU8(x64GenContext, 0x4F);
else
{
assert_dbg();
}
x64Gen_writeU8(x64GenContext, 0xC0 + (destRegister & 7) * 8 + (srcRegister & 7));
}
void x64Gen_movSignExtend_reg64Low32_reg64Low16(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// MOVSX <destReg64_lowDWORD>, <srcReg64_lowWORD>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x4D);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x4C);
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0xBF);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7)+(destRegister&7)*8);
}
void x64Gen_movZeroExtend_reg64Low32_reg64Low16(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// MOVZX <destReg64_lowDWORD>, <srcReg64_lowWORD>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x4D);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x4C);
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0xB7);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7)+(destRegister&7)*8);
}
void x64Gen_movSignExtend_reg64Low32_reg64Low8(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// MOVSX <destReg64_lowDWORD>, <srcReg64_lowBYTE>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x4D);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x4C);
else if( srcRegister >= 4 )
x64Gen_writeU8(x64GenContext, 0x40);
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0xBE);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7)+(destRegister&7)*8);
}
void x64Gen_movZeroExtend_reg64Low32_reg64Low8(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// MOVZX <destReg64_lowDWORD>, <srcReg64_lowBYTE>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x4D);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x4C);
else if( srcRegister >= 4 )
x64Gen_writeU8(x64GenContext, 0x40);
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0xB6);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7)+(destRegister&7)*8);
}
void x64Gen_lea_reg64Low32_reg64Low32PlusReg64Low32(x64GenContext_t* x64GenContext, sint32 dstRegister, sint32 memRegisterA64, sint32 memRegisterB64)
{
// MOV <reg32>, DWORD [<reg32> + <reg32>]
if ((memRegisterA64 & 0x7) == 5)
{
// RBP
// swap mem registers to get the shorter instruction encoding
sint32 temp = memRegisterA64;
memRegisterA64 = memRegisterB64;
memRegisterB64 = temp;
}
if ((memRegisterA64 & 0x7) == 4)
{
// RSP
// swap mem registers
sint32 temp = memRegisterA64;
memRegisterA64 = memRegisterB64;
memRegisterB64 = temp;
if ((memRegisterA64 & 0x7) == 4)
assert_dbg(); // double RSP not supported
}
x64Gen_writeU8(x64GenContext, 0x67);
if (dstRegister >= 8 && memRegisterA64 >= 8 && memRegisterB64 >= 8)
x64Gen_writeU8(x64GenContext, 0x47);
else if (dstRegister >= 8 && memRegisterA64 >= 8)
x64Gen_writeU8(x64GenContext, 0x45);
else if (dstRegister >= 8 && memRegisterB64 >= 8)
x64Gen_writeU8(x64GenContext, 0x46);
else if (dstRegister >= 8)
x64Gen_writeU8(x64GenContext, 0x44);
else if (memRegisterA64 >= 8 && memRegisterB64 >= 8)
x64Gen_writeU8(x64GenContext, 0x43);
else if (memRegisterB64 >= 8)
x64Gen_writeU8(x64GenContext, 0x42);
else if (memRegisterA64 >= 8)
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0x8D);
_x64Gen_writeMODRMDeprecated(x64GenContext, dstRegister&0x7, memRegisterA64 & 0x7, memRegisterB64 & 0x7, 0);
}
void _x64_op_reg64Low_mem8Reg64(x64GenContext_t* x64GenContext, sint32 dstRegister, sint32 memRegister64, sint32 memImmS32, uint8 opByte)
{
// OR <dstReg64> (low byte), BYTE [<reg64> + <imm64>]
if (dstRegister >= 8 && memRegister64 >= 8)
x64Gen_writeU8(x64GenContext, 0x45);
if (dstRegister >= 8)
x64Gen_writeU8(x64GenContext, 0x44);
if (memRegister64 >= 8)
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, opByte);
_x64Gen_writeMODRMDeprecated(x64GenContext, dstRegister, memRegister64, REG_NONE, memImmS32);
}
void x64Gen_or_reg64Low8_mem8Reg64(x64GenContext_t* x64GenContext, sint32 dstRegister, sint32 memRegister64, sint32 memImmS32)
{
_x64_op_reg64Low_mem8Reg64(x64GenContext, dstRegister, memRegister64, memImmS32, 0x0A);
}
void x64Gen_and_reg64Low8_mem8Reg64(x64GenContext_t* x64GenContext, sint32 dstRegister, sint32 memRegister64, sint32 memImmS32)
{
_x64_op_reg64Low_mem8Reg64(x64GenContext, dstRegister, memRegister64, memImmS32, 0x22);
}
void x64Gen_mov_mem8Reg64_reg64Low8(x64GenContext_t* x64GenContext, sint32 dstRegister, sint32 memRegister64, sint32 memImmS32)
{
_x64_op_reg64Low_mem8Reg64(x64GenContext, dstRegister, memRegister64, memImmS32, 0x88);
}
void x64Gen_lock_cmpxchg_mem32Reg64PlusReg64_reg64(x64GenContext_t* x64GenContext, sint32 memRegisterA64, sint32 memRegisterB64, sint32 memImmS32, sint32 srcRegister)
{
// LOCK CMPXCHG DWORD [<reg64> + <reg64> + <imm64>], <srcReg64> (low dword)
x64Gen_writeU8(x64GenContext, 0xF0); // LOCK prefix
if( srcRegister >= 8 || memRegisterA64 >= 8|| memRegisterB64 >= 8 )
x64Gen_writeU8(x64GenContext, 0x40+((srcRegister>=8)?4:0)+((memRegisterA64>=8)?1:0)+((memRegisterB64>=8)?2:0));
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0xB1);
_x64Gen_writeMODRMDeprecated(x64GenContext, srcRegister, memRegisterA64, memRegisterB64, memImmS32);
}
void x64Gen_lock_cmpxchg_mem32Reg64_reg64(x64GenContext_t* x64GenContext, sint32 memRegister64, sint32 memImmS32, sint32 srcRegister)
{
// LOCK CMPXCHG DWORD [<reg64> + <imm64>], <srcReg64> (low dword)
x64Gen_writeU8(x64GenContext, 0xF0); // LOCK prefix
if( srcRegister >= 8 || memRegister64 >= 8 )
x64Gen_writeU8(x64GenContext, 0x40+((srcRegister>=8)?4:0)+((memRegister64>=8)?1:0));
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0xB1);
if( memImmS32 == 0 )
{
x64Gen_writeU8(x64GenContext, 0x45+(srcRegister&7)*8);
x64Gen_writeU8(x64GenContext, 0x00);
}
else
assert_dbg();
}
void x64Gen_add_reg64_reg64(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// ADD <destReg>, <srcReg>
x64Gen_writeU8(x64GenContext, 0x48+(destRegister/8)+(srcRegister/8)*4);
x64Gen_writeU8(x64GenContext, 0x01);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7)*8+(destRegister&7));
}
void x64Gen_add_reg64_imm32(x64GenContext_t* x64GenContext, sint32 srcRegister, uint32 immU32)
{
sint32 immS32 = (sint32)immU32;
if (srcRegister >= 8)
x64Gen_writeU8(x64GenContext, 0x49);
else
x64Gen_writeU8(x64GenContext, 0x48);
if (immS32 >= -128 && immS32 <= 127)
{
x64Gen_writeU8(x64GenContext, 0x83);
x64Gen_writeU8(x64GenContext, 0xC0 + (srcRegister & 7));
x64Gen_writeU8(x64GenContext, (uint8)immS32);
}
else
{
x64Gen_writeU8(x64GenContext, 0x81);
x64Gen_writeU8(x64GenContext, 0xC0 + (srcRegister & 7));
x64Gen_writeU32(x64GenContext, immU32);
}
}
void x64Gen_add_reg64Low32_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// ADD <destReg64_low32>, <srcReg64_low32>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x45);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0x01);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7)*8+(destRegister&7));
}
void x64Gen_add_reg64Low32_imm32(x64GenContext_t* x64GenContext, sint32 srcRegister, uint32 immU32)
{
sint32 immS32 = (sint32)immU32;
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
if( immS32 >= -128 && immS32 <= 127 )
{
x64Gen_writeU8(x64GenContext, 0x83);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immS32);
}
else
{
if( srcRegister == REG_RAX )
{
// special EAX short form
x64Gen_writeU8(x64GenContext, 0x05);
}
else
{
x64Gen_writeU8(x64GenContext, 0x81);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7));
}
x64Gen_writeU32(x64GenContext, immU32);
}
}
void x64Gen_sub_reg64Low32_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// SUB <destReg64_low32>, <srcReg64_low32>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x45);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0x29);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7)*8+(destRegister&7));
}
void x64Gen_sub_reg64Low32_imm32(x64GenContext_t* x64GenContext, sint32 srcRegister, uint32 immU32)
{
sint32 immS32 = (sint32)immU32;
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
if( immS32 >= -128 && immS32 <= 127 )
{
x64Gen_writeU8(x64GenContext, 0x83);
x64Gen_writeU8(x64GenContext, 0xE8+(srcRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immS32);
}
else
{
if( srcRegister == REG_RAX )
{
// special EAX short form
x64Gen_writeU8(x64GenContext, 0x2D);
}
else
{
x64Gen_writeU8(x64GenContext, 0x81);
x64Gen_writeU8(x64GenContext, 0xE8+(srcRegister&7));
}
x64Gen_writeU32(x64GenContext, immU32);
}
}
void x64Gen_sub_reg64_imm32(x64GenContext_t* x64GenContext, sint32 srcRegister, uint32 immU32)
{
sint32 immS32 = (sint32)immU32;
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x49);
else
x64Gen_writeU8(x64GenContext, 0x48);
if( immS32 >= -128 && immS32 <= 127 )
{
x64Gen_writeU8(x64GenContext, 0x83);
x64Gen_writeU8(x64GenContext, 0xE8+(srcRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immS32);
}
else
{
x64Gen_writeU8(x64GenContext, 0x81);
x64Gen_writeU8(x64GenContext, 0xE8+(srcRegister&7));
x64Gen_writeU32(x64GenContext, immU32);
}
}
void x64Gen_sub_mem32reg64_imm32(x64GenContext_t* x64GenContext, sint32 memRegister, sint32 memImmS32, uint64 immU32)
{
// SUB <mem32_memReg64>, <imm32>
sint32 immS32 = (sint32)immU32;
if( memRegister == REG_RSP )
{
if( memImmS32 >= 128 )
{
if( immS32 >= -128 && immS32 <= 127 )
{
// 4 byte mem imm + 1 byte imm
x64Gen_writeU8(x64GenContext, 0x83);
x64Gen_writeU8(x64GenContext, 0xAC);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memImmS32);
x64Gen_writeU8(x64GenContext, (uint8)immU32);
}
else
{
// 4 byte mem imm + 4 byte imm
x64Gen_writeU8(x64GenContext, 0x81);
x64Gen_writeU8(x64GenContext, 0xAC);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memImmS32);
x64Gen_writeU32(x64GenContext, (uint32)immU32);
}
}
else
assert_dbg();
}
else
{
assert_dbg();
}
}
void x64Gen_sbb_reg64Low32_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// SBB <destReg64_low32>, <srcReg64_low32>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x45);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0x19);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7)*8+(destRegister&7));
}
void x64Gen_adc_reg64Low32_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// ADC <destReg64_low32>, <srcReg64_low32>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x45);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0x11);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7)*8+(destRegister&7));
}
void x64Gen_adc_reg64Low32_imm32(x64GenContext_t* x64GenContext, sint32 srcRegister, uint32 immU32)
{
sint32 immS32 = (sint32)immU32;
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
if( immS32 >= -128 && immS32 <= 127 )
{
x64Gen_writeU8(x64GenContext, 0x83);
x64Gen_writeU8(x64GenContext, 0xD0+(srcRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immS32);
}
else
{
if( srcRegister == REG_RAX )
{
// special EAX short form
x64Gen_writeU8(x64GenContext, 0x15);
}
else
{
x64Gen_writeU8(x64GenContext, 0x81);
x64Gen_writeU8(x64GenContext, 0xD0+(srcRegister&7));
}
x64Gen_writeU32(x64GenContext, immU32);
}
}
void x64Gen_dec_mem32(x64GenContext_t* x64GenContext, sint32 memoryRegister, uint32 memoryImmU32)
{
// DEC dword [<reg64>+imm]
sint32 memoryImmS32 = (sint32)memoryImmU32;
if (memoryRegister != REG_RSP)
assert_dbg(); // not supported yet
if (memoryImmS32 >= -128 && memoryImmS32 <= 127)
{
x64Gen_writeU8(x64GenContext, 0xFF);
x64Gen_writeU8(x64GenContext, 0x4C);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint8)memoryImmU32);
}
else
{
x64Gen_writeU8(x64GenContext, 0xFF);
x64Gen_writeU8(x64GenContext, 0x8C);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, memoryImmU32);
}
}
void x64Gen_imul_reg64Low32_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 operandRegister)
{
// IMUL <destReg64_low32>, <operandReg64_low32>
if( destRegister >= 8 && operandRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x45);
else if( operandRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0xAF);
x64Gen_writeU8(x64GenContext, 0xC0+(operandRegister&7)+(destRegister&7)*8);
}
void x64Gen_idiv_reg64Low32(x64GenContext_t* x64GenContext, sint32 operandRegister)
{
// IDIV <destReg64_low32>
if( operandRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0xF7);
x64Gen_writeU8(x64GenContext, 0xF8+(operandRegister&7));
}
void x64Gen_div_reg64Low32(x64GenContext_t* x64GenContext, sint32 operandRegister)
{
// DIV <destReg64_low32>
if( operandRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0xF7);
x64Gen_writeU8(x64GenContext, 0xF0+(operandRegister&7));
}
void x64Gen_imul_reg64Low32(x64GenContext_t* x64GenContext, sint32 operandRegister)
{
// IMUL <destReg64_low32>
if( operandRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0xF7);
x64Gen_writeU8(x64GenContext, 0xE8+(operandRegister&7));
}
void x64Gen_mul_reg64Low32(x64GenContext_t* x64GenContext, sint32 operandRegister)
{
// MUL <destReg64_low32>
if( operandRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0xF7);
x64Gen_writeU8(x64GenContext, 0xE0+(operandRegister&7));
}
void x64Gen_and_reg64Low32_imm32(x64GenContext_t* x64GenContext, sint32 srcRegister, uint32 immU32)
{
sint32 immS32 = (sint32)immU32;
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
if( immS32 >= -128 && immS32 <= 127 )
{
x64Gen_writeU8(x64GenContext, 0x83);
x64Gen_writeU8(x64GenContext, 0xE0+(srcRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immS32);
}
else
{
if( srcRegister == REG_RAX )
{
// special EAX short form
x64Gen_writeU8(x64GenContext, 0x25);
}
else
{
x64Gen_writeU8(x64GenContext, 0x81);
x64Gen_writeU8(x64GenContext, 0xE0+(srcRegister&7));
}
x64Gen_writeU32(x64GenContext, immU32);
}
}
void x64Gen_and_reg64Low32_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// AND <destReg64_lowDWORD>, <srcReg64_lowDWORD>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x45);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0x21);
x64Gen_writeU8(x64GenContext, 0xC0+(destRegister&7)+(srcRegister&7)*8);
}
void x64Gen_test_reg64Low32_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// TEST <destReg64_lowDWORD>, <srcReg64_lowDWORD>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x45);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x85);
x64Gen_writeU8(x64GenContext, 0xC0+(destRegister&7)*8+(srcRegister&7));
}
void x64Gen_test_reg64Low32_imm32(x64GenContext_t* x64GenContext, sint32 srcRegister, uint32 immU32)
{
sint32 immS32 = (sint32)immU32;
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
if( srcRegister == REG_RAX )
{
// special EAX short form
x64Gen_writeU8(x64GenContext, 0xA9);
}
else
{
x64Gen_writeU8(x64GenContext, 0xF7);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7));
}
x64Gen_writeU32(x64GenContext, immU32);
}
void x64Gen_cmp_reg64Low32_imm32(x64GenContext_t* x64GenContext, sint32 srcRegister, sint32 immS32)
{
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
if( immS32 >= -128 && immS32 <= 127 )
{
// 83 F8 00 CMP EAX,0
x64Gen_writeU8(x64GenContext, 0x83);
x64Gen_writeU8(x64GenContext, 0xF8+(srcRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immS32);
}
else
{
if( srcRegister == REG_RAX )
{
// special RAX short form
x64Gen_writeU8(x64GenContext, 0x3D);
}
else
{
x64Gen_writeU8(x64GenContext, 0x81);
x64Gen_writeU8(x64GenContext, 0xF8+(srcRegister&7));
}
x64Gen_writeU32(x64GenContext, (uint32)immS32);
}
}
void x64Gen_cmp_reg64Low32_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// CMP <destReg64_lowDWORD>, <srcReg64_lowDWORD>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x45);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0x39);
x64Gen_writeU8(x64GenContext, 0xC0+(destRegister&7)+(srcRegister&7)*8);
}
void x64Gen_cmp_reg64Low32_mem32reg64(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 memRegister, sint32 memImmS32)
{
// CMP <destReg64_lowDWORD>, DWORD [<memRegister>+<immS32>]
if( memRegister == REG_RSP )
{
if( memImmS32 >= -128 && memImmS32 <= 127 )
assert_dbg(); // todo -> Shorter instruction form
if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x3B);
x64Gen_writeU8(x64GenContext, 0x84+(destRegister&7)*8);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memImmS32);
}
else
{
assert_dbg();
}
}
void x64Gen_or_reg64Low32_imm32(x64GenContext_t* x64GenContext, sint32 srcRegister, uint32 immU32)
{
sint32 immS32 = (sint32)immU32;
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
if( immS32 >= -128 && immS32 <= 127 )
{
x64Gen_writeU8(x64GenContext, 0x83);
x64Gen_writeU8(x64GenContext, 0xC8+(srcRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immS32);
}
else
{
if( srcRegister == REG_RAX )
{
// special EAX short form
x64Gen_writeU8(x64GenContext, 0x0D);
}
else
{
x64Gen_writeU8(x64GenContext, 0x81);
x64Gen_writeU8(x64GenContext, 0xC8+(srcRegister&7));
}
x64Gen_writeU32(x64GenContext, immU32);
}
}
void x64Gen_or_reg64Low32_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// OR <destReg64_lowDWORD>, <srcReg64_lowDWORD>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x45);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0x09);
x64Gen_writeU8(x64GenContext, 0xC0+(destRegister&7)+(srcRegister&7)*8);
}
void x64Gen_xor_reg32_reg32(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// XOR <destReg>, <srcReg>
x64Gen_writeU8(x64GenContext, 0x33);
x64Gen_writeU8(x64GenContext, 0xC0+srcRegister+destRegister*8);
}
void x64Gen_xor_reg64Low32_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// XOR <destReg64_lowDWORD>, <srcReg64_lowDWORD>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x45);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0x31);
x64Gen_writeU8(x64GenContext, 0xC0+(destRegister&7)+(srcRegister&7)*8);
}
void x64Gen_xor_reg64Low32_imm32(x64GenContext_t* x64GenContext, sint32 srcRegister, uint32 immU32)
{
sint32 immS32 = (sint32)immU32;
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
if( immS32 >= -128 && immS32 <= 127 )
{
x64Gen_writeU8(x64GenContext, 0x83);
x64Gen_writeU8(x64GenContext, 0xF0+(srcRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immS32);
}
else
{
if( srcRegister == REG_RAX )
{
// special EAX short form
x64Gen_writeU8(x64GenContext, 0x35);
}
else
{
x64Gen_writeU8(x64GenContext, 0x81);
x64Gen_writeU8(x64GenContext, 0xF0+(srcRegister&7));
}
x64Gen_writeU32(x64GenContext, immU32);
}
}
void x64Gen_rol_reg64Low32_imm8(x64GenContext_t* x64GenContext, sint32 srcRegister, sint8 immS8)
{
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
if( immS8 == 1 )
{
// short form for 1 bit ROL
x64Gen_writeU8(x64GenContext, 0xD1);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7));
}
else
{
x64Gen_writeU8(x64GenContext, 0xC1);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immS8);
}
}
void x64Gen_rol_reg64Low32_cl(x64GenContext_t* x64GenContext, sint32 srcRegister)
{
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0xD3);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7));
}
void x64Gen_rol_reg64Low16_imm8(x64GenContext_t* x64GenContext, sint32 srcRegister, sint8 immS8)
{
x64Gen_writeU8(x64GenContext, 0x66); // 16bit prefix
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
if( immS8 == 1 )
{
// short form for 1 bit ROL
x64Gen_writeU8(x64GenContext, 0xD1);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7));
}
else
{
x64Gen_writeU8(x64GenContext, 0xC1);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immS8);
}
}
void x64Gen_rol_reg64_imm8(x64GenContext_t* x64GenContext, sint32 srcRegister, sint8 immS8)
{
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x49);
else
x64Gen_writeU8(x64GenContext, 0x48);
if( immS8 == 1 )
{
// short form for 1 bit ROL
x64Gen_writeU8(x64GenContext, 0xD1);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7));
}
else
{
x64Gen_writeU8(x64GenContext, 0xC1);
x64Gen_writeU8(x64GenContext, 0xC0+(srcRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immS8);
}
}
void x64Gen_shl_reg64Low32_imm8(x64GenContext_t* x64GenContext, sint32 srcRegister, sint8 immS8)
{
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
if( immS8 == 1 )
{
// short form for 1 bit SHL
x64Gen_writeU8(x64GenContext, 0xD1);
x64Gen_writeU8(x64GenContext, 0xF0+(srcRegister&7));
}
else
{
x64Gen_writeU8(x64GenContext, 0xC1);
x64Gen_writeU8(x64GenContext, 0xF0+(srcRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immS8);
}
}
void x64Gen_shr_reg64Low32_imm8(x64GenContext_t* x64GenContext, sint32 srcRegister, sint8 immS8)
{
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
if( immS8 == 1 )
{
// short form for 1 bit SHR
x64Gen_writeU8(x64GenContext, 0xD1);
x64Gen_writeU8(x64GenContext, 0xE8+(srcRegister&7));
}
else
{
x64Gen_writeU8(x64GenContext, 0xC1);
x64Gen_writeU8(x64GenContext, 0xE8+(srcRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immS8);
}
}
void x64Gen_sar_reg64Low32_imm8(x64GenContext_t* x64GenContext, sint32 srcRegister, sint8 immS8)
{
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
if( immS8 == 1 )
{
// short form for 1 bit ROL
x64Gen_writeU8(x64GenContext, 0xD1);
x64Gen_writeU8(x64GenContext, 0xF8+(srcRegister&7));
}
else
{
x64Gen_writeU8(x64GenContext, 0xC1);
x64Gen_writeU8(x64GenContext, 0xF8+(srcRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immS8);
}
}
void x64Gen_not_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister)
{
if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0xF7);
x64Gen_writeU8(x64GenContext, 0xD0+(destRegister&7));
}
void x64Gen_neg_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister)
{
if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0xF7);
x64Gen_writeU8(x64GenContext, 0xD8+(destRegister&7));
}
void x64Gen_cdq(x64GenContext_t* x64GenContext)
{
x64Gen_writeU8(x64GenContext, 0x99);
}
void x64Gen_bswap_reg64(x64GenContext_t* x64GenContext, sint32 destRegister)
{
if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41|8);
else
x64Gen_writeU8(x64GenContext, 0x40|8);
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0xC8+(destRegister&7));
}
void x64Gen_bswap_reg64Lower32bit(x64GenContext_t* x64GenContext, sint32 destRegister)
{
if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0xC8+(destRegister&7));
}
void x64Gen_bswap_reg64Lower16bit(x64GenContext_t* x64GenContext, sint32 destRegister)
{
assert_dbg(); // do not use this instruction, it's result is always undefined. Instead use ROL <reg16>, 8
//x64Gen_writeU8(x64GenContext, 0x66);
//if( destRegister >= 8 )
// x64Gen_writeU8(x64GenContext, 0x41);
//x64Gen_writeU8(x64GenContext, 0x0F);
//x64Gen_writeU8(x64GenContext, 0xC8+(destRegister&7));
}
void x64Gen_lzcnt_reg64Low32_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// SSE4
// LZCNT <destReg>, <srcReg>
x64Gen_writeU8(x64GenContext, 0xF3);
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x45);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0xBD);
x64Gen_writeU8(x64GenContext, 0xC0+(destRegister&7)*8+(srcRegister&7));
}
void x64Gen_bsr_reg64Low32_reg64Low32(x64GenContext_t* x64GenContext, sint32 destRegister, sint32 srcRegister)
{
// BSR <destReg>, <srcReg>
if( destRegister >= 8 && srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x45);
else if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x44);
else if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0xBD);
x64Gen_writeU8(x64GenContext, 0xC0+(destRegister&7)*8+(srcRegister&7));
}
void x64Gen_setcc_mem8(x64GenContext_t* x64GenContext, sint32 conditionType, sint32 memoryRegister, uint32 memoryImmU32)
{
// SETcc [<reg64>+imm]
sint32 memoryImmS32 = (sint32)memoryImmU32;
if( memoryRegister != REG_RSP )
assert_dbg(); // not supported
if( memoryRegister >= 8 )
assert_dbg(); // not supported
if( memoryImmS32 >= -128 && memoryImmS32 <= 127 )
{
if( conditionType == X86_CONDITION_EQUAL )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x94);
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_NOT_EQUAL )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x95);
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_UNSIGNED_ABOVE )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x97);
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_UNSIGNED_ABOVE_EQUAL )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x93);
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_UNSIGNED_BELOW )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x92);
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_UNSIGNED_BELOW_EQUAL )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x96);
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_SIGNED_GREATER )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x9F);
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_SIGNED_GREATER_EQUAL )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x9D);
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_SIGNED_LESS )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x9C);
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_SIGNED_LESS_EQUAL )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x9E);
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_PARITY )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x9A);
x64Gen_writeU8(x64GenContext, 0x44);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint32)memoryImmU32);
}
else
assert_dbg();
}
else
{
if( conditionType == X86_CONDITION_EQUAL )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x94);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_NOT_EQUAL )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x95);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_UNSIGNED_ABOVE )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x97);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_UNSIGNED_ABOVE_EQUAL )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x93);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_UNSIGNED_BELOW || conditionType == X86_CONDITION_CARRY )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x92);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_NOT_CARRY )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x93);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_UNSIGNED_BELOW_EQUAL )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x96);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_SIGNED_GREATER )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x9F);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_SIGNED_GREATER_EQUAL )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x9D);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_SIGNED_LESS )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x9C);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_SIGNED_LESS_EQUAL )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x9E);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_SIGN )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x98);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memoryImmU32);
}
else if( conditionType == X86_CONDITION_PARITY )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x9A);
x64Gen_writeU8(x64GenContext, 0x84);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, (uint32)memoryImmU32);
}
else
assert_dbg();
}
}
void x64Gen_setcc_reg64b(x64GenContext_t* x64GenContext, sint32 conditionType, sint32 dataRegister)
{
// SETcc <reg64_low8>
if (conditionType == X86_CONDITION_NOT_EQUAL)
{
if (dataRegister >= 8)
x64Gen_writeU8(x64GenContext, 0x41);
else if (dataRegister >= 4)
x64Gen_writeU8(x64GenContext, 0x40);
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x95);
x64Gen_writeU8(x64GenContext, 0xC0 + (dataRegister & 7));
}
else if (conditionType == X86_CONDITION_EQUAL)
{
if (dataRegister >= 8)
x64Gen_writeU8(x64GenContext, 0x41);
else if (dataRegister >= 4)
x64Gen_writeU8(x64GenContext, 0x40);
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x94);
x64Gen_writeU8(x64GenContext, 0xC0 + (dataRegister & 7));
}
else
assert_dbg();
}
void x64Gen_bt_mem8(x64GenContext_t* x64GenContext, sint32 memoryRegister, uint32 memoryImmU32, uint8 bitIndex)
{
// BT [<reg64>+imm], bitIndex (bit test)
sint32 memoryImmS32 = (sint32)memoryImmU32;
if( memoryRegister != REG_RSP )
assert_dbg(); // not supported yet
if( memoryImmS32 >= -128 && memoryImmS32 <= 127 )
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0xBA);
x64Gen_writeU8(x64GenContext, 0x64);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU8(x64GenContext, (uint8)memoryImmU32);
x64Gen_writeU8(x64GenContext, bitIndex);
}
else
{
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0xBA);
x64Gen_writeU8(x64GenContext, 0xA4);
x64Gen_writeU8(x64GenContext, 0x24);
x64Gen_writeU32(x64GenContext, memoryImmU32);
x64Gen_writeU8(x64GenContext, bitIndex);
}
}
void x64Gen_cmc(x64GenContext_t* x64GenContext)
{
x64Gen_writeU8(x64GenContext, 0xF5);
}
void x64Gen_jmp_imm32(x64GenContext_t* x64GenContext, uint32 destImm32)
{
x64Gen_writeU8(x64GenContext, 0xE9);
x64Gen_writeU32(x64GenContext, destImm32);
}
void x64Gen_jmp_memReg64(x64GenContext_t* x64GenContext, sint32 memRegister, uint32 immU32)
{
if( memRegister == REG_NONE )
{
assert_dbg();
}
if( memRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
sint32 immS32 = (sint32)immU32;
if( immS32 == 0 )
{
x64Gen_writeU8(x64GenContext, 0xFF);
x64Gen_writeU8(x64GenContext, 0x20+(memRegister&7));
}
else if( immS32 >= -128 && immS32 <= 127 )
{
x64Gen_writeU8(x64GenContext, 0xFF);
x64Gen_writeU8(x64GenContext, 0x60+(memRegister&7));
x64Gen_writeU8(x64GenContext, (uint8)immU32);
}
else
{
x64Gen_writeU8(x64GenContext, 0xFF);
x64Gen_writeU8(x64GenContext, 0xA0+(memRegister&7));
x64Gen_writeU32(x64GenContext, immU32);
}
}
void x64Gen_jmpc_far(x64GenContext_t* x64GenContext, sint32 conditionType, sint32 relativeDest)
{
// far JMPc #+relativeDest
if( conditionType == X86_CONDITION_NONE )
{
// E9 FFFFFFFF
x64Gen_writeU8(x64GenContext, 0xE9);
}
else if( conditionType == X86_CONDITION_UNSIGNED_BELOW || conditionType == X86_CONDITION_CARRY )
{
// 0F 82 FFFFFFFF
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x82);
}
else if( conditionType == X86_CONDITION_NOT_CARRY || conditionType == X86_CONDITION_UNSIGNED_ABOVE_EQUAL )
{
// 0F 83 FFFFFFFF
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x83);
}
else if( conditionType == X86_CONDITION_EQUAL )
{
// 0F 84 FFFFFFFF
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x84);
}
else if( conditionType == X86_CONDITION_NOT_EQUAL )
{
// 0F 85 FFFFFFFF
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x85);
}
else if( conditionType == X86_CONDITION_UNSIGNED_BELOW_EQUAL )
{
// 0F 86 FFFFFFFF
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x86);
}
else if( conditionType == X86_CONDITION_UNSIGNED_ABOVE )
{
// 0F 87 FFFFFFFF
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x87);
}
else if( conditionType == X86_CONDITION_SIGN )
{
// 0F 88 FFFFFFFF
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x88);
}
else if( conditionType == X86_CONDITION_NOT_SIGN )
{
// 0F 89 FFFFFFFF
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x89);
}
else if( conditionType == X86_CONDITION_PARITY )
{
// 0F 8A FFFFFFFF
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x8A);
}
else if( conditionType == X86_CONDITION_SIGNED_LESS )
{
// 0F 8C FFFFFFFF
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x8C);
}
else if( conditionType == X86_CONDITION_SIGNED_GREATER_EQUAL )
{
// 0F 8D FFFFFFFF
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x8D);
}
else if( conditionType == X86_CONDITION_SIGNED_LESS_EQUAL )
{
// 0F 8E FFFFFFFF
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x8E);
}
else if( conditionType == X86_CONDITION_SIGNED_GREATER )
{
// 0F 8F FFFFFFFF
x64Gen_writeU8(x64GenContext, 0x0F);
x64Gen_writeU8(x64GenContext, 0x8F);
}
else
assert_dbg();
x64Gen_writeU32(x64GenContext, (uint32)relativeDest);
}
void x64Gen_jmpc_near(x64GenContext_t* x64GenContext, sint32 conditionType, sint32 relativeDest)
{
// near JMPc #+relativeDest
if (conditionType == X86_CONDITION_NONE)
{
x64Gen_writeU8(x64GenContext, 0xEB);
}
else if (conditionType == X86_CONDITION_UNSIGNED_BELOW || conditionType == X86_CONDITION_CARRY)
{
x64Gen_writeU8(x64GenContext, 0x72);
}
else if (conditionType == X86_CONDITION_NOT_CARRY || conditionType == X86_CONDITION_UNSIGNED_ABOVE_EQUAL)
{
x64Gen_writeU8(x64GenContext, 0x73);
}
else if (conditionType == X86_CONDITION_EQUAL)
{
x64Gen_writeU8(x64GenContext, 0x74);
}
else if (conditionType == X86_CONDITION_NOT_EQUAL)
{
x64Gen_writeU8(x64GenContext, 0x75);
}
else if (conditionType == X86_CONDITION_UNSIGNED_BELOW_EQUAL)
{
x64Gen_writeU8(x64GenContext, 0x76);
}
else if (conditionType == X86_CONDITION_UNSIGNED_ABOVE)
{
x64Gen_writeU8(x64GenContext, 0x77);
}
else if (conditionType == X86_CONDITION_SIGN)
{
x64Gen_writeU8(x64GenContext, 0x78);
}
else if (conditionType == X86_CONDITION_NOT_SIGN)
{
x64Gen_writeU8(x64GenContext, 0x79);
}
else if (conditionType == X86_CONDITION_PARITY)
{
x64Gen_writeU8(x64GenContext, 0x7A);
}
else if (conditionType == X86_CONDITION_SIGNED_LESS)
{
x64Gen_writeU8(x64GenContext, 0x7C);
}
else if (conditionType == X86_CONDITION_SIGNED_GREATER_EQUAL)
{
x64Gen_writeU8(x64GenContext, 0x7D);
}
else if (conditionType == X86_CONDITION_SIGNED_LESS_EQUAL)
{
x64Gen_writeU8(x64GenContext, 0x7E);
}
else if (conditionType == X86_CONDITION_SIGNED_GREATER)
{
x64Gen_writeU8(x64GenContext, 0x7F);
}
else
assert_dbg();
x64Gen_writeU8(x64GenContext, (uint8)relativeDest);
}
void x64Gen_push_reg64(x64GenContext_t* x64GenContext, sint32 srcRegister)
{
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0x50+(srcRegister&7));
}
void x64Gen_pop_reg64(x64GenContext_t* x64GenContext, sint32 destRegister)
{
if( destRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0x58+(destRegister&7));
}
void x64Gen_jmp_reg64(x64GenContext_t* x64GenContext, sint32 srcRegister)
{
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0xFF);
x64Gen_writeU8(x64GenContext, 0xE0+(srcRegister&7));
}
void x64Gen_call_reg64(x64GenContext_t* x64GenContext, sint32 srcRegister)
{
if( srcRegister >= 8 )
x64Gen_writeU8(x64GenContext, 0x41);
x64Gen_writeU8(x64GenContext, 0xFF);
x64Gen_writeU8(x64GenContext, 0xD0+(srcRegister&7));
}
void x64Gen_ret(x64GenContext_t* x64GenContext)
{
x64Gen_writeU8(x64GenContext, 0xC3);
}
void x64Gen_int3(x64GenContext_t* x64GenContext)
{
x64Gen_writeU8(x64GenContext, 0xCC);
}
| 60,648
|
C++
|
.cpp
| 1,767
| 31.863611
| 199
| 0.755509
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,201
|
PPCRecompilerImlGen.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/Recompiler/PPCRecompilerImlGen.cpp
|
#include "Cafe/HW/Espresso/Interpreter/PPCInterpreterInternal.h"
#include "Cafe/HW/Espresso/Interpreter/PPCInterpreterHelper.h"
#include "PPCRecompiler.h"
#include "PPCRecompilerIml.h"
#include "PPCRecompilerX64.h"
#include "PPCRecompilerImlRanges.h"
#include "util/helpers/StringBuf.h"
bool PPCRecompiler_decodePPCInstruction(ppcImlGenContext_t* ppcImlGenContext);
uint32 PPCRecompiler_iterateCurrentInstruction(ppcImlGenContext_t* ppcImlGenContext);
uint32 PPCRecompiler_getInstructionByOffset(ppcImlGenContext_t* ppcImlGenContext, uint32 offset);
PPCRecImlInstruction_t* PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext_t* ppcImlGenContext)
{
if( ppcImlGenContext->imlListCount+1 > ppcImlGenContext->imlListSize )
{
sint32 newSize = ppcImlGenContext->imlListCount*2 + 2;
ppcImlGenContext->imlList = (PPCRecImlInstruction_t*)realloc(ppcImlGenContext->imlList, sizeof(PPCRecImlInstruction_t)*newSize);
ppcImlGenContext->imlListSize = newSize;
}
PPCRecImlInstruction_t* imlInstruction = ppcImlGenContext->imlList+ppcImlGenContext->imlListCount;
memset(imlInstruction, 0x00, sizeof(PPCRecImlInstruction_t));
imlInstruction->crRegister = PPC_REC_INVALID_REGISTER; // dont update any cr register by default
imlInstruction->associatedPPCAddress = ppcImlGenContext->ppcAddressOfCurrentInstruction;
ppcImlGenContext->imlListCount++;
return imlInstruction;
}
void PPCRecompilerImlGen_generateNewInstruction_jumpmark(ppcImlGenContext_t* ppcImlGenContext, uint32 address)
{
// no-op that indicates possible destination of a jump
PPCRecImlInstruction_t* imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_JUMPMARK;
imlInstruction->op_jumpmark.address = address;
}
void PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext_t* ppcImlGenContext, uint32 macroId, uint32 param, uint32 param2, uint16 paramU16)
{
// no-op that indicates possible destination of a jump
PPCRecImlInstruction_t* imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_MACRO;
imlInstruction->operation = macroId;
imlInstruction->op_macro.param = param;
imlInstruction->op_macro.param2 = param2;
imlInstruction->op_macro.paramU16 = paramU16;
}
/*
* Generates a marker for Interpreter -> Recompiler entrypoints
* PPC_ENTER iml instructions have no associated PPC address but the instruction itself has one
*/
void PPCRecompilerImlGen_generateNewInstruction_ppcEnter(ppcImlGenContext_t* ppcImlGenContext, uint32 ppcAddress)
{
// no-op that indicates possible destination of a jump
PPCRecImlInstruction_t* imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_PPC_ENTER;
imlInstruction->operation = 0;
imlInstruction->op_ppcEnter.ppcAddress = ppcAddress;
imlInstruction->op_ppcEnter.x64Offset = 0;
imlInstruction->associatedPPCAddress = 0;
}
void PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext_t* ppcImlGenContext, PPCRecImlInstruction_t* imlInstruction, uint32 operation, uint8 registerResult, uint8 registerA, uint8 crRegister, uint8 crMode)
{
// operation with two register operands (e.g. "t0 = t1")
if(imlInstruction == NULL)
imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_R_R;
imlInstruction->operation = operation;
imlInstruction->crRegister = crRegister;
imlInstruction->crMode = crMode;
imlInstruction->op_r_r.registerResult = registerResult;
imlInstruction->op_r_r.registerA = registerA;
}
void PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext_t* ppcImlGenContext, uint32 operation, uint8 registerResult, uint8 registerA, uint8 registerB, uint8 crRegister=PPC_REC_INVALID_REGISTER, uint8 crMode=0)
{
// operation with three register operands (e.g. "t0 = t1 + t4")
PPCRecImlInstruction_t* imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_R_R_R;
imlInstruction->operation = operation;
imlInstruction->crRegister = crRegister;
imlInstruction->crMode = crMode;
imlInstruction->op_r_r_r.registerResult = registerResult;
imlInstruction->op_r_r_r.registerA = registerA;
imlInstruction->op_r_r_r.registerB = registerB;
}
void PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext_t* ppcImlGenContext, uint32 operation, uint8 registerResult, uint8 registerA, sint32 immS32, uint8 crRegister=PPC_REC_INVALID_REGISTER, uint8 crMode=0)
{
// operation with two register operands and one signed immediate (e.g. "t0 = t1 + 1234")
PPCRecImlInstruction_t* imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_R_R_S32;
imlInstruction->operation = operation;
imlInstruction->crRegister = crRegister;
imlInstruction->crMode = crMode;
imlInstruction->op_r_r_s32.registerResult = registerResult;
imlInstruction->op_r_r_s32.registerA = registerA;
imlInstruction->op_r_r_s32.immS32 = immS32;
}
void PPCRecompilerImlGen_generateNewInstruction_name_r(ppcImlGenContext_t* ppcImlGenContext, uint32 operation, uint8 registerIndex, uint32 name, uint32 copyWidth, bool signExtend, bool bigEndian)
{
// Store name (e.g. "'r3' = t0" which translates to MOV [ESP+offset_r3], reg32)
PPCRecImlInstruction_t* imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_NAME_R;
imlInstruction->operation = operation;
imlInstruction->op_r_name.registerIndex = registerIndex;
imlInstruction->op_r_name.name = name;
imlInstruction->op_r_name.copyWidth = copyWidth;
imlInstruction->op_r_name.flags = (signExtend?PPCREC_IML_OP_FLAG_SIGNEXTEND:0)|(bigEndian?PPCREC_IML_OP_FLAG_SWITCHENDIAN:0);
}
void PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext_t* ppcImlGenContext, uint32 operation, uint8 registerIndex, sint32 immS32, uint32 copyWidth, bool signExtend, bool bigEndian, uint8 crRegister, uint32 crMode)
{
// two variations:
// operation without store (e.g. "'r3' < 123" which has no effect other than updating a condition flags register)
// operation with store (e.g. "'r3' = 123")
PPCRecImlInstruction_t* imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_R_S32;
imlInstruction->operation = operation;
imlInstruction->crRegister = crRegister;
imlInstruction->crMode = crMode;
imlInstruction->op_r_immS32.registerIndex = registerIndex;
imlInstruction->op_r_immS32.immS32 = immS32;
}
void PPCRecompilerImlGen_generateNewInstruction_conditional_r_s32(ppcImlGenContext_t* ppcImlGenContext, PPCRecImlInstruction_t* imlInstruction, uint32 operation, uint8 registerIndex, sint32 immS32, uint32 crRegisterIndex, uint32 crBitIndex, bool bitMustBeSet)
{
if(imlInstruction == NULL)
imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
else
memset(imlInstruction, 0, sizeof(PPCRecImlInstruction_t));
imlInstruction->type = PPCREC_IML_TYPE_CONDITIONAL_R_S32;
imlInstruction->operation = operation;
imlInstruction->crRegister = PPC_REC_INVALID_REGISTER;
// r_s32 operation
imlInstruction->op_conditional_r_s32.registerIndex = registerIndex;
imlInstruction->op_conditional_r_s32.immS32 = immS32;
// condition
imlInstruction->op_conditional_r_s32.crRegisterIndex = crRegisterIndex;
imlInstruction->op_conditional_r_s32.crBitIndex = crBitIndex;
imlInstruction->op_conditional_r_s32.bitMustBeSet = bitMustBeSet;
}
void PPCRecompilerImlGen_generateNewInstruction_jump(ppcImlGenContext_t* ppcImlGenContext, PPCRecImlInstruction_t* imlInstruction, uint32 jumpmarkAddress)
{
// jump
if (imlInstruction == NULL)
imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
else
memset(imlInstruction, 0, sizeof(PPCRecImlInstruction_t));
imlInstruction->type = PPCREC_IML_TYPE_CJUMP;
imlInstruction->crRegister = PPC_REC_INVALID_REGISTER;
imlInstruction->op_conditionalJump.jumpmarkAddress = jumpmarkAddress;
imlInstruction->op_conditionalJump.jumpAccordingToSegment = false;
imlInstruction->op_conditionalJump.condition = PPCREC_JUMP_CONDITION_NONE;
imlInstruction->op_conditionalJump.crRegisterIndex = 0;
imlInstruction->op_conditionalJump.crBitIndex = 0;
imlInstruction->op_conditionalJump.bitMustBeSet = false;
}
// jump based on segment branches
void PPCRecompilerImlGen_generateNewInstruction_jumpSegment(ppcImlGenContext_t* ppcImlGenContext, PPCRecImlInstruction_t* imlInstruction)
{
// jump
if (imlInstruction == NULL)
imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->associatedPPCAddress = 0;
imlInstruction->type = PPCREC_IML_TYPE_CJUMP;
imlInstruction->crRegister = PPC_REC_INVALID_REGISTER;
imlInstruction->op_conditionalJump.jumpmarkAddress = 0;
imlInstruction->op_conditionalJump.jumpAccordingToSegment = true;
imlInstruction->op_conditionalJump.condition = PPCREC_JUMP_CONDITION_NONE;
imlInstruction->op_conditionalJump.crRegisterIndex = 0;
imlInstruction->op_conditionalJump.crBitIndex = 0;
imlInstruction->op_conditionalJump.bitMustBeSet = false;
}
void PPCRecompilerImlGen_generateNewInstruction_noOp(ppcImlGenContext_t* ppcImlGenContext, PPCRecImlInstruction_t* imlInstruction)
{
if (imlInstruction == NULL)
imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_NO_OP;
imlInstruction->operation = 0;
imlInstruction->crRegister = PPC_REC_INVALID_REGISTER;
imlInstruction->crMode = 0;
}
void PPCRecompilerImlGen_generateNewInstruction_cr(ppcImlGenContext_t* ppcImlGenContext, uint32 operation, uint8 crD, uint8 crA, uint8 crB)
{
// multiple variations:
// operation involving only one cr bit (like clear crD bit)
// operation involving three cr bits (like crD = crA or crB)
PPCRecImlInstruction_t* imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_CR;
imlInstruction->operation = operation;
imlInstruction->crRegister = PPC_REC_INVALID_REGISTER;
imlInstruction->crMode = 0;
imlInstruction->op_cr.crD = crD;
imlInstruction->op_cr.crA = crA;
imlInstruction->op_cr.crB = crB;
}
void PPCRecompilerImlGen_generateNewInstruction_conditionalJump(ppcImlGenContext_t* ppcImlGenContext, uint32 jumpmarkAddress, uint32 jumpCondition, uint32 crRegisterIndex, uint32 crBitIndex, bool bitMustBeSet)
{
// conditional jump
PPCRecImlInstruction_t* imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_CJUMP;
imlInstruction->crRegister = PPC_REC_INVALID_REGISTER;
imlInstruction->op_conditionalJump.jumpmarkAddress = jumpmarkAddress;
imlInstruction->op_conditionalJump.condition = jumpCondition;
imlInstruction->op_conditionalJump.crRegisterIndex = crRegisterIndex;
imlInstruction->op_conditionalJump.crBitIndex = crBitIndex;
imlInstruction->op_conditionalJump.bitMustBeSet = bitMustBeSet;
}
void PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext_t* ppcImlGenContext, uint8 registerDestination, uint8 registerMemory, sint32 immS32, uint32 copyWidth, bool signExtend, bool switchEndian)
{
// load from memory
PPCRecImlInstruction_t* imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_LOAD;
imlInstruction->operation = 0;
imlInstruction->crRegister = PPC_REC_INVALID_REGISTER;
imlInstruction->op_storeLoad.registerData = registerDestination;
imlInstruction->op_storeLoad.registerMem = registerMemory;
imlInstruction->op_storeLoad.immS32 = immS32;
imlInstruction->op_storeLoad.copyWidth = copyWidth;
//imlInstruction->op_storeLoad.flags = (signExtend ? PPCREC_IML_OP_FLAG_SIGNEXTEND : 0) | (switchEndian ? PPCREC_IML_OP_FLAG_SWITCHENDIAN : 0);
imlInstruction->op_storeLoad.flags2.swapEndian = switchEndian;
imlInstruction->op_storeLoad.flags2.signExtend = signExtend;
}
void PPCRecompilerImlGen_generateNewInstruction_r_memory_indexed(ppcImlGenContext_t* ppcImlGenContext, uint8 registerDestination, uint8 registerMemory1, uint8 registerMemory2, uint32 copyWidth, bool signExtend, bool switchEndian)
{
// load from memory
PPCRecImlInstruction_t* imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_LOAD_INDEXED;
imlInstruction->operation = 0;
imlInstruction->crRegister = PPC_REC_INVALID_REGISTER;
imlInstruction->op_storeLoad.registerData = registerDestination;
imlInstruction->op_storeLoad.registerMem = registerMemory1;
imlInstruction->op_storeLoad.registerMem2 = registerMemory2;
imlInstruction->op_storeLoad.copyWidth = copyWidth;
//imlInstruction->op_storeLoad.flags = (signExtend?PPCREC_IML_OP_FLAG_SIGNEXTEND:0)|(switchEndian?PPCREC_IML_OP_FLAG_SWITCHENDIAN:0);
imlInstruction->op_storeLoad.flags2.swapEndian = switchEndian;
imlInstruction->op_storeLoad.flags2.signExtend = signExtend;
}
void PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext_t* ppcImlGenContext, uint8 registerSource, uint8 registerMemory, sint32 immS32, uint32 copyWidth, bool switchEndian)
{
// load from memory
PPCRecImlInstruction_t* imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_STORE;
imlInstruction->operation = 0;
imlInstruction->crRegister = PPC_REC_INVALID_REGISTER;
imlInstruction->op_storeLoad.registerData = registerSource;
imlInstruction->op_storeLoad.registerMem = registerMemory;
imlInstruction->op_storeLoad.immS32 = immS32;
imlInstruction->op_storeLoad.copyWidth = copyWidth;
//imlInstruction->op_storeLoad.flags = (switchEndian?PPCREC_IML_OP_FLAG_SWITCHENDIAN:0);
imlInstruction->op_storeLoad.flags2.swapEndian = switchEndian;
imlInstruction->op_storeLoad.flags2.signExtend = false;
}
void PPCRecompilerImlGen_generateNewInstruction_memory_r_indexed(ppcImlGenContext_t* ppcImlGenContext, uint8 registerDestination, uint8 registerMemory1, uint8 registerMemory2, uint32 copyWidth, bool signExtend, bool switchEndian)
{
// load from memory
PPCRecImlInstruction_t* imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_STORE_INDEXED;
imlInstruction->operation = 0;
imlInstruction->crRegister = PPC_REC_INVALID_REGISTER;
imlInstruction->op_storeLoad.registerData = registerDestination;
imlInstruction->op_storeLoad.registerMem = registerMemory1;
imlInstruction->op_storeLoad.registerMem2 = registerMemory2;
imlInstruction->op_storeLoad.copyWidth = copyWidth;
//imlInstruction->op_storeLoad.flags = (signExtend?PPCREC_IML_OP_FLAG_SIGNEXTEND:0)|(switchEndian?PPCREC_IML_OP_FLAG_SWITCHENDIAN:0);
imlInstruction->op_storeLoad.flags2.swapEndian = switchEndian;
imlInstruction->op_storeLoad.flags2.signExtend = signExtend;
}
void PPCRecompilerImlGen_generateNewInstruction_memory_memory(ppcImlGenContext_t* ppcImlGenContext, PPCRecImlInstruction_t* imlInstruction, uint8 srcMemReg, sint32 srcImmS32, uint8 dstMemReg, sint32 dstImmS32, uint8 copyWidth)
{
// copy from memory to memory
if(imlInstruction == NULL)
imlInstruction = PPCRecompilerImlGen_generateNewEmptyInstruction(ppcImlGenContext);
imlInstruction->type = PPCREC_IML_TYPE_MEM2MEM;
imlInstruction->operation = 0;
imlInstruction->crRegister = PPC_REC_INVALID_REGISTER;
imlInstruction->op_mem2mem.src.registerMem = srcMemReg;
imlInstruction->op_mem2mem.src.immS32 = srcImmS32;
imlInstruction->op_mem2mem.dst.registerMem = dstMemReg;
imlInstruction->op_mem2mem.dst.immS32 = dstImmS32;
imlInstruction->op_mem2mem.copyWidth = copyWidth;
}
uint32 PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext_t* ppcImlGenContext, uint32 mappedName)
{
if( mappedName == PPCREC_NAME_NONE )
{
debug_printf("PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(): Invalid mappedName parameter\n");
return PPC_REC_INVALID_REGISTER;
}
for(uint32 i=0; i<(PPC_REC_MAX_VIRTUAL_GPR-1); i++)
{
if( ppcImlGenContext->mappedRegister[i] == PPCREC_NAME_NONE )
{
ppcImlGenContext->mappedRegister[i] = mappedName;
return i;
}
}
return 0;
}
uint32 PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext_t* ppcImlGenContext, uint32 mappedName)
{
for(uint32 i=0; i< PPC_REC_MAX_VIRTUAL_GPR; i++)
{
if( ppcImlGenContext->mappedRegister[i] == mappedName )
{
return i;
}
}
return PPC_REC_INVALID_REGISTER;
}
uint32 PPCRecompilerImlGen_getAndLockFreeTemporaryFPR(ppcImlGenContext_t* ppcImlGenContext, uint32 mappedName)
{
if( mappedName == PPCREC_NAME_NONE )
{
debug_printf("PPCRecompilerImlGen_getAndLockFreeTemporaryFPR(): Invalid mappedName parameter\n");
return PPC_REC_INVALID_REGISTER;
}
for(uint32 i=0; i<255; i++)
{
if( ppcImlGenContext->mappedFPRRegister[i] == PPCREC_NAME_NONE )
{
ppcImlGenContext->mappedFPRRegister[i] = mappedName;
return i;
}
}
return 0;
}
uint32 PPCRecompilerImlGen_findFPRRegisterByMappedName(ppcImlGenContext_t* ppcImlGenContext, uint32 mappedName)
{
for(uint32 i=0; i<255; i++)
{
if( ppcImlGenContext->mappedFPRRegister[i] == mappedName )
{
return i;
}
}
return PPC_REC_INVALID_REGISTER;
}
/*
* Loads a PPC gpr into any of the available IML registers
* If loadNew is false, it will reuse already loaded instances
*/
uint32 PPCRecompilerImlGen_loadRegister(ppcImlGenContext_t* ppcImlGenContext, uint32 mappedName, bool loadNew)
{
if( loadNew == false )
{
uint32 loadedRegisterIndex = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, mappedName);
if( loadedRegisterIndex != PPC_REC_INVALID_REGISTER )
return loadedRegisterIndex;
}
uint32 registerIndex = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, mappedName);
return registerIndex;
}
/*
* Reuse already loaded register if present
* Otherwise create new IML register and map the name. The register contents will be undefined
*/
uint32 PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext_t* ppcImlGenContext, uint32 mappedName)
{
uint32 loadedRegisterIndex = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, mappedName);
if( loadedRegisterIndex != PPC_REC_INVALID_REGISTER )
return loadedRegisterIndex;
uint32 registerIndex = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, mappedName);
return registerIndex;
}
/*
* Loads a PPC fpr into any of the available IML FPU registers
* If loadNew is false, it will check first if the fpr is already loaded into any IML register
*/
uint32 PPCRecompilerImlGen_loadFPRRegister(ppcImlGenContext_t* ppcImlGenContext, uint32 mappedName, bool loadNew)
{
if( loadNew == false )
{
uint32 loadedRegisterIndex = PPCRecompilerImlGen_findFPRRegisterByMappedName(ppcImlGenContext, mappedName);
if( loadedRegisterIndex != PPC_REC_INVALID_REGISTER )
return loadedRegisterIndex;
}
uint32 registerIndex = PPCRecompilerImlGen_getAndLockFreeTemporaryFPR(ppcImlGenContext, mappedName);
return registerIndex;
}
/*
* Checks if a PPC fpr register is already loaded into any IML register
* If no, it will create a new undefined temporary IML FPU register and map the name (effectively overwriting the old ppc register)
*/
uint32 PPCRecompilerImlGen_loadOverwriteFPRRegister(ppcImlGenContext_t* ppcImlGenContext, uint32 mappedName)
{
uint32 loadedRegisterIndex = PPCRecompilerImlGen_findFPRRegisterByMappedName(ppcImlGenContext, mappedName);
if( loadedRegisterIndex != PPC_REC_INVALID_REGISTER )
return loadedRegisterIndex;
uint32 registerIndex = PPCRecompilerImlGen_getAndLockFreeTemporaryFPR(ppcImlGenContext, mappedName);
return registerIndex;
}
void PPCRecompilerImlGen_TW(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
//#ifdef CEMU_DEBUG_ASSERT
// PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, 0, 0);
//#endif
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_LEAVE, ppcImlGenContext->ppcAddressOfCurrentInstruction, 0, 0);
}
bool PPCRecompilerImlGen_MTSPR(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
uint32 rD, spr1, spr2, spr;
PPC_OPC_TEMPL_XO(opcode, rD, spr1, spr2);
spr = spr1 | (spr2<<5);
if (spr == SPR_CTR || spr == SPR_LR)
{
uint32 gprReg = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0 + rD);
if (gprReg == PPC_REC_INVALID_REGISTER)
gprReg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0 + rD);
uint32 sprReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_SPR0 + spr);
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, sprReg, gprReg);
}
else if (spr >= SPR_UGQR0 && spr <= SPR_UGQR7)
{
uint32 gprReg = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0 + rD);
if (gprReg == PPC_REC_INVALID_REGISTER)
gprReg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0 + rD);
uint32 sprReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_SPR0 + spr);
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, sprReg, gprReg);
ppcImlGenContext->tracking.modifiesGQR[spr - SPR_UGQR0] = true;
}
else
return false;
return true;
}
bool PPCRecompilerImlGen_MFSPR(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
uint32 rD, spr1, spr2, spr;
PPC_OPC_TEMPL_XO(opcode, rD, spr1, spr2);
spr = spr1 | (spr2<<5);
if (spr == SPR_LR || spr == SPR_CTR)
{
uint32 sprReg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_SPR0 + spr);
uint32 gprReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0 + rD);
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprReg, sprReg);
}
else if (spr >= SPR_UGQR0 && spr <= SPR_UGQR7)
{
uint32 sprReg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_SPR0 + spr);
uint32 gprReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0 + rD);
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprReg, sprReg);
}
else
return false;
return true;
}
bool PPCRecompilerImlGen_MFTB(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
uint32 rD, spr1, spr2, spr;
PPC_OPC_TEMPL_XO(opcode, rD, spr1, spr2);
spr = spr1 | (spr2<<5);
if (spr == 268 || spr == 269)
{
// TBL / TBU
uint32 param2 = spr | (rD << 16);
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_MFTB, ppcImlGenContext->ppcAddressOfCurrentInstruction, param2, 0);
return true;
}
return false;
}
bool PPCRecompilerImlGen_MFCR(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_X(opcode, rD, rA, rB);
uint32 gprReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0 + rD);
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_MFCR, gprReg, 0, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
return true;
}
bool PPCRecompilerImlGen_MTCRF(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
uint32 rS;
uint32 crMask;
PPC_OPC_TEMPL_XFX(opcode, rS, crMask);
uint32 gprReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0 + rS);
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_MTCRF, gprReg, crMask, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
return true;
}
void PPCRecompilerImlGen_CMP(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
uint32 cr;
int rA, rB;
PPC_OPC_TEMPL_X(opcode, cr, rA, rB);
cr >>= 2;
uint32 gprRegisterA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_COMPARE_SIGNED, gprRegisterA, gprRegisterB, cr, PPCREC_CR_MODE_COMPARE_SIGNED);
}
void PPCRecompilerImlGen_CMPL(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
uint32 cr;
int rA, rB;
PPC_OPC_TEMPL_X(opcode, cr, rA, rB);
cr >>= 2;
uint32 gprRegisterA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_COMPARE_UNSIGNED, gprRegisterA, gprRegisterB, cr, PPCREC_CR_MODE_COMPARE_UNSIGNED);
}
void PPCRecompilerImlGen_CMPI(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
uint32 cr;
int rA;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, cr, rA, imm);
cr >>= 2;
sint32 b = imm;
// load gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_COMPARE_SIGNED, gprRegister, b, 0, false, false, cr, PPCREC_CR_MODE_COMPARE_SIGNED);
}
void PPCRecompilerImlGen_CMPLI(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
uint32 cr;
int rA;
uint32 imm;
PPC_OPC_TEMPL_D_UImm(opcode, cr, rA, imm);
cr >>= 2;
uint32 b = imm;
// load gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_COMPARE_UNSIGNED, gprRegister, (sint32)b, 0, false, false, cr, PPCREC_CR_MODE_COMPARE_UNSIGNED);
}
bool PPCRecompiler_canInlineFunction(MPTR functionPtr, sint32* functionInstructionCount)
{
for (sint32 i = 0; i < 6; i++)
{
uint32 opcode = memory_readU32(functionPtr+i*4);
switch ((opcode >> 26))
{
case 14: // ADDI
case 15: // ADDIS
continue;
case 19: // opcode category 19
switch (PPC_getBits(opcode, 30, 10))
{
case 16:
if (opcode == 0x4E800020)
{
*functionInstructionCount = i;
return true; // BLR
}
return false;
}
return false;
case 32: // LWZ
case 33: // LWZU
case 34: // LBZ
case 35: // LBZU
case 36: // STW
case 37: // STWU
case 38: // STB
case 39: // STBU
case 40: // LHZ
case 41: // LHZU
case 42: // LHA
case 43: // LHAU
case 44: // STH
case 45: // STHU
case 46: // LMW
case 47: // STMW
case 48: // LFS
case 49: // LFSU
case 50: // LFD
case 51: // LFDU
case 52: // STFS
case 53: // STFSU
case 54: // STFD
case 55: // STFDU
continue;
default:
return false;
}
}
return false;
}
void PPCRecompiler_generateInlinedCode(ppcImlGenContext_t* ppcImlGenContext, uint32 startAddress, sint32 instructionCount)
{
for (sint32 i = 0; i < instructionCount; i++)
{
ppcImlGenContext->ppcAddressOfCurrentInstruction = startAddress + i*4;
ppcImlGenContext->cyclesSinceLastBranch++;
if (PPCRecompiler_decodePPCInstruction(ppcImlGenContext))
{
assert_dbg();
}
}
// add range
ppcRecRange_t recRange;
recRange.ppcAddress = startAddress;
recRange.ppcSize = instructionCount*4 + 4; // + 4 because we have to include the BLR
ppcImlGenContext->functionRef->list_ranges.push_back(recRange);
}
bool PPCRecompilerImlGen_B(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
uint32 li;
PPC_OPC_TEMPL_I(opcode, li);
uint32 jumpAddressDest = li;
if( (opcode&PPC_OPC_AA) == 0 )
{
jumpAddressDest = li + (unsigned int)ppcImlGenContext->ppcAddressOfCurrentInstruction;
}
if( opcode&PPC_OPC_LK )
{
// function call
// check if function can be inlined
sint32 inlineFuncInstructionCount = 0;
if (PPCRecompiler_canInlineFunction(jumpAddressDest, &inlineFuncInstructionCount))
{
// generate NOP iml instead of BL macro (this assures that segment PPC range remains intact)
PPCRecompilerImlGen_generateNewInstruction_noOp(ppcImlGenContext, NULL);
//cemuLog_log(LogType::Force, "Inline func 0x{:08x} at {:08x}", jumpAddressDest, ppcImlGenContext->ppcAddressOfCurrentInstruction);
uint32* prevInstructionPtr = ppcImlGenContext->currentInstruction;
ppcImlGenContext->currentInstruction = (uint32*)memory_getPointerFromVirtualOffset(jumpAddressDest);
PPCRecompiler_generateInlinedCode(ppcImlGenContext, jumpAddressDest, inlineFuncInstructionCount);
ppcImlGenContext->currentInstruction = prevInstructionPtr;
return true;
}
// generate funtion call instructions
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_BL, ppcImlGenContext->ppcAddressOfCurrentInstruction, jumpAddressDest, ppcImlGenContext->cyclesSinceLastBranch);
PPCRecompilerImlGen_generateNewInstruction_ppcEnter(ppcImlGenContext, ppcImlGenContext->ppcAddressOfCurrentInstruction+4);
return true;
}
// is jump destination within recompiled function?
if( jumpAddressDest >= ppcImlGenContext->functionRef->ppcAddress && jumpAddressDest < (ppcImlGenContext->functionRef->ppcAddress + ppcImlGenContext->functionRef->ppcSize) )
{
// generate instruction
PPCRecompilerImlGen_generateNewInstruction_jump(ppcImlGenContext, NULL, jumpAddressDest);
}
else
{
// todo: Inline this jump destination if possible (in many cases it's a bunch of GPR/FPR store instructions + BLR)
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_B_FAR, ppcImlGenContext->ppcAddressOfCurrentInstruction, jumpAddressDest, ppcImlGenContext->cyclesSinceLastBranch);
}
return true;
}
bool PPCRecompilerImlGen_BC(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
uint32 BO, BI, BD;
PPC_OPC_TEMPL_B(opcode, BO, BI, BD);
uint32 crRegister = BI/4;
uint32 crBit = BI%4;
uint32 jumpCondition = 0;
bool conditionMustBeTrue = (BO&8)!=0;
bool useDecrementer = (BO&4)==0; // bit not set -> decrement
bool decrementerMustBeZero = (BO&2)!=0; // bit set -> branch if CTR = 0, bit not set -> branch if CTR != 0
bool ignoreCondition = (BO&16)!=0;
uint32 jumpAddressDest = BD;
if( (opcode&PPC_OPC_AA) == 0 )
{
jumpAddressDest = BD + (unsigned int)ppcImlGenContext->ppcAddressOfCurrentInstruction;
}
if( opcode&PPC_OPC_LK )
{
// conditional function calls are not supported
if( ignoreCondition == false )
{
// generate jump condition
if( conditionMustBeTrue )
{
if( crBit == 0 )
jumpCondition = PPCREC_JUMP_CONDITION_GE;
else if( crBit == 1 )
jumpCondition = PPCREC_JUMP_CONDITION_LE;
else if( crBit == 2 )
jumpCondition = PPCREC_JUMP_CONDITION_NE;
else if( crBit == 3 )
jumpCondition = PPCREC_JUMP_CONDITION_NSUMMARYOVERFLOW;
}
else
{
if( crBit == 0 )
jumpCondition = PPCREC_JUMP_CONDITION_L;
else if( crBit == 1 )
jumpCondition = PPCREC_JUMP_CONDITION_G;
else if( crBit == 2 )
jumpCondition = PPCREC_JUMP_CONDITION_E;
else if( crBit == 3 )
jumpCondition = PPCREC_JUMP_CONDITION_SUMMARYOVERFLOW;
}
// generate instruction
//PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, 0, 0);
PPCRecompilerImlGen_generateNewInstruction_conditionalJump(ppcImlGenContext, ppcImlGenContext->ppcAddressOfCurrentInstruction+4, jumpCondition, crRegister, crBit, !conditionMustBeTrue);
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_BL, ppcImlGenContext->ppcAddressOfCurrentInstruction, jumpAddressDest, ppcImlGenContext->cyclesSinceLastBranch);
PPCRecompilerImlGen_generateNewInstruction_ppcEnter(ppcImlGenContext, ppcImlGenContext->ppcAddressOfCurrentInstruction+4);
return true;
}
return false;
}
// generate iml instructions depending on flags
if( useDecrementer )
{
if( ignoreCondition == false )
return false; // not supported for the moment
uint32 ctrRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_SPR0+SPR_CTR, false);
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_SUB, ctrRegister, 1, 0, false, false, PPCREC_CR_REG_TEMP, PPCREC_CR_MODE_ARITHMETIC);
if( decrementerMustBeZero )
PPCRecompilerImlGen_generateNewInstruction_conditionalJump(ppcImlGenContext, jumpAddressDest, PPCREC_JUMP_CONDITION_E, PPCREC_CR_REG_TEMP, 0, false);
else
PPCRecompilerImlGen_generateNewInstruction_conditionalJump(ppcImlGenContext, jumpAddressDest, PPCREC_JUMP_CONDITION_NE, PPCREC_CR_REG_TEMP, 0, false);
return true;
}
else
{
if( ignoreCondition )
{
// branch always, no condition and no decrementer
debugBreakpoint();
crRegister = PPC_REC_INVALID_REGISTER; // not necessary but lets optimizer know we dont care for cr register on this instruction
}
else
{
// generate jump condition
if( conditionMustBeTrue )
{
if( crBit == 0 )
jumpCondition = PPCREC_JUMP_CONDITION_GE;
else if( crBit == 1 )
jumpCondition = PPCREC_JUMP_CONDITION_LE;
else if( crBit == 2 )
jumpCondition = PPCREC_JUMP_CONDITION_NE;
else if( crBit == 3 )
jumpCondition = PPCREC_JUMP_CONDITION_NSUMMARYOVERFLOW;
}
else
{
if( crBit == 0 )
jumpCondition = PPCREC_JUMP_CONDITION_L;
else if( crBit == 1 )
jumpCondition = PPCREC_JUMP_CONDITION_G;
else if( crBit == 2 )
jumpCondition = PPCREC_JUMP_CONDITION_E;
else if( crBit == 3 )
jumpCondition = PPCREC_JUMP_CONDITION_SUMMARYOVERFLOW;
}
if (jumpAddressDest >= ppcImlGenContext->functionRef->ppcAddress && jumpAddressDest < (ppcImlGenContext->functionRef->ppcAddress + ppcImlGenContext->functionRef->ppcSize))
{
// near jump
PPCRecompilerImlGen_generateNewInstruction_conditionalJump(ppcImlGenContext, jumpAddressDest, jumpCondition, crRegister, crBit, conditionMustBeTrue);
}
else
{
// far jump
PPCRecompilerImlGen_generateNewInstruction_conditionalJump(ppcImlGenContext, ppcImlGenContext->ppcAddressOfCurrentInstruction + 4, jumpCondition, crRegister, crBit, !conditionMustBeTrue);
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_B_FAR, ppcImlGenContext->ppcAddressOfCurrentInstruction, jumpAddressDest, ppcImlGenContext->cyclesSinceLastBranch);
PPCRecompilerImlGen_generateNewInstruction_ppcEnter(ppcImlGenContext, ppcImlGenContext->ppcAddressOfCurrentInstruction + 4);
}
}
}
return true;
}
bool PPCRecompilerImlGen_BCLR(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
uint32 BO, BI, BD;
PPC_OPC_TEMPL_XL(opcode, BO, BI, BD);
uint32 crRegister = BI/4;
uint32 crBit = BI%4;
uint32 jumpCondition = 0;
bool conditionMustBeTrue = (BO&8)!=0;
bool useDecrementer = (BO&4)==0; // bit not set -> decrement
bool decrementerMustBeZero = (BO&2)!=0; // bit set -> branch if CTR = 0, bit not set -> branch if CTR != 0
bool ignoreCondition = (BO&16)!=0;
bool saveLR = (opcode&PPC_OPC_LK)!=0;
// since we skip this instruction if the condition is true, we need to invert the logic
bool invertedConditionMustBeTrue = !conditionMustBeTrue;
if( useDecrementer )
{
cemu_assert_debug(false);
return false; // unsupported
}
else
{
if( ignoreCondition )
{
// store LR
if( saveLR )
{
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_BLRL, ppcImlGenContext->ppcAddressOfCurrentInstruction, 0, ppcImlGenContext->cyclesSinceLastBranch);
PPCRecompilerImlGen_generateNewInstruction_ppcEnter(ppcImlGenContext, ppcImlGenContext->ppcAddressOfCurrentInstruction+4);
}
else
{
// branch always, no condition and no decrementer
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_BLR, ppcImlGenContext->ppcAddressOfCurrentInstruction, 0, ppcImlGenContext->cyclesSinceLastBranch);
}
}
else
{
// store LR
if( saveLR )
{
uint32 registerLR = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_SPR0+SPR_LR);
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ASSIGN, registerLR, (ppcImlGenContext->ppcAddressOfCurrentInstruction+4)&0x7FFFFFFF, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
}
// generate jump condition
if( invertedConditionMustBeTrue )
{
if( crBit == 0 )
jumpCondition = PPCREC_JUMP_CONDITION_L;
else if( crBit == 1 )
jumpCondition = PPCREC_JUMP_CONDITION_G;
else if( crBit == 2 )
jumpCondition = PPCREC_JUMP_CONDITION_E;
else if( crBit == 3 )
jumpCondition = PPCREC_JUMP_CONDITION_SUMMARYOVERFLOW;
}
else
{
if( crBit == 0 )
jumpCondition = PPCREC_JUMP_CONDITION_GE;
else if( crBit == 1 )
jumpCondition = PPCREC_JUMP_CONDITION_LE;
else if( crBit == 2 )
jumpCondition = PPCREC_JUMP_CONDITION_NE;
else if( crBit == 3 )
jumpCondition = PPCREC_JUMP_CONDITION_NSUMMARYOVERFLOW;
}
// jump if BCLR condition NOT met (jump to jumpmark of next instruction, essentially skipping current instruction)
PPCRecompilerImlGen_generateNewInstruction_conditionalJump(ppcImlGenContext, ppcImlGenContext->ppcAddressOfCurrentInstruction+4, jumpCondition, crRegister, crBit, invertedConditionMustBeTrue);
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_BLR, ppcImlGenContext->ppcAddressOfCurrentInstruction, 0, ppcImlGenContext->cyclesSinceLastBranch);
}
}
return true;
}
bool PPCRecompilerImlGen_BCCTR(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
uint32 BO, BI, BD;
PPC_OPC_TEMPL_XL(opcode, BO, BI, BD);
uint32 crRegister = BI/4;
uint32 crBit = BI%4;
uint32 jumpCondition = 0;
bool conditionMustBeTrue = (BO&8)!=0;
bool useDecrementer = (BO&4)==0; // bit not set -> decrement
bool decrementerMustBeZero = (BO&2)!=0; // bit set -> branch if CTR = 0, bit not set -> branch if CTR != 0
bool ignoreCondition = (BO&16)!=0;
bool saveLR = (opcode&PPC_OPC_LK)!=0;
// since we skip this instruction if the condition is true, we need to invert the logic
bool invertedConditionMustBeTrue = !conditionMustBeTrue;
if( useDecrementer )
{
assert_dbg();
// if added, dont forget inverted logic
debug_printf("Rec: BCLR unsupported decrementer\n");
return false; // unsupported
}
else
{
if( ignoreCondition )
{
// store LR
if( saveLR )
{
uint32 registerLR = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_SPR0+SPR_LR);
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ASSIGN, registerLR, (ppcImlGenContext->ppcAddressOfCurrentInstruction+4)&0x7FFFFFFF, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_BCTRL, ppcImlGenContext->ppcAddressOfCurrentInstruction, 0, ppcImlGenContext->cyclesSinceLastBranch);
PPCRecompilerImlGen_generateNewInstruction_ppcEnter(ppcImlGenContext, ppcImlGenContext->ppcAddressOfCurrentInstruction+4);
}
else
{
// branch always, no condition and no decrementer
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_BCTR, ppcImlGenContext->ppcAddressOfCurrentInstruction, 0, ppcImlGenContext->cyclesSinceLastBranch);
}
}
else
{
// store LR
if( saveLR )
{
uint32 registerLR = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_SPR0+SPR_LR);
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ASSIGN, registerLR, (ppcImlGenContext->ppcAddressOfCurrentInstruction+4)&0x7FFFFFFF, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
}
// generate jump condition
if( invertedConditionMustBeTrue )
{
if( crBit == 0 )
jumpCondition = PPCREC_JUMP_CONDITION_L;
else if( crBit == 1 )
jumpCondition = PPCREC_JUMP_CONDITION_G;
else if( crBit == 2 )
jumpCondition = PPCREC_JUMP_CONDITION_E;
else if( crBit == 3 )
jumpCondition = PPCREC_JUMP_CONDITION_SUMMARYOVERFLOW;
}
else
{
if( crBit == 0 )
jumpCondition = PPCREC_JUMP_CONDITION_GE;
else if( crBit == 1 )
jumpCondition = PPCREC_JUMP_CONDITION_LE;
else if( crBit == 2 )
jumpCondition = PPCREC_JUMP_CONDITION_NE;
else if( crBit == 3 )
jumpCondition = PPCREC_JUMP_CONDITION_NSUMMARYOVERFLOW;
}
// jump if BCLR condition NOT met (jump to jumpmark of next instruction, essentially skipping current instruction)
PPCRecompilerImlGen_generateNewInstruction_conditionalJump(ppcImlGenContext, ppcImlGenContext->ppcAddressOfCurrentInstruction+4, jumpCondition, crRegister, crBit, invertedConditionMustBeTrue);
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_BCTR, ppcImlGenContext->ppcAddressOfCurrentInstruction, 0, ppcImlGenContext->cyclesSinceLastBranch);
}
}
return true;
}
bool PPCRecompilerImlGen_ISYNC(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
// does not need to be translated
return true;
}
bool PPCRecompilerImlGen_SYNC(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
// does not need to be translated
return true;
}
bool PPCRecompilerImlGen_ADD(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
//hCPU->gpr[rD] = (int)hCPU->gpr[rA] + (int)hCPU->gpr[rB];
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerRB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_ADD, registerRD, registerRA, registerRB, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_ADD, registerRD, registerRA, registerRB);
}
return true;
}
bool PPCRecompilerImlGen_ADDC(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
//hCPU->gpr[rD] = (int)hCPU->gpr[rA] + (int)hCPU->gpr[rB]; -> Update carry
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerRB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( opcode&PPC_OPC_RC )
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_ADD_UPDATE_CARRY, registerRD, registerRA, registerRB, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_ADD_UPDATE_CARRY, registerRD, registerRA, registerRB);
return true;
}
bool PPCRecompilerImlGen_ADDE(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
// hCPU->gpr[rD] = hCPU->gpr[rA] + hCPU->gpr[rB] + ca;
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerRB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( opcode&PPC_OPC_RC )
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_ADD_CARRY_UPDATE_CARRY, registerRD, registerRB, registerRA, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_ADD_CARRY_UPDATE_CARRY, registerRD, registerRB, registerRA);
return true;
}
bool PPCRecompilerImlGen_ADDZE(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
PPC_ASSERT(rB == 0);
//uint32 a = hCPU->gpr[rA];
//uint32 ca = hCPU->xer_ca;
//hCPU->gpr[rD] = a + ca;
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
// move rA to rD
if( registerRA != registerRD )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, registerRD, registerRA);
}
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ADD_CARRY, registerRD, registerRD, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ADD_CARRY, registerRD, registerRD);
}
return true;
}
bool PPCRecompilerImlGen_ADDME(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
PPC_ASSERT(rB == 0);
//uint32 a = hCPU->gpr[rA];
//uint32 ca = hCPU->xer_ca;
//hCPU->gpr[rD] = a + ca + -1;
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
// move rA to rD
if( registerRA != registerRD )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, registerRD, registerRA);
}
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ADD_CARRY_ME, registerRD, registerRD, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ADD_CARRY_ME, registerRD, registerRD);
}
return true;
}
bool PPCRecompilerImlGen_ADDI(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
//hCPU->gpr[rD] = (rA ? (int)hCPU->gpr[rA] : 0) + (int)imm;
if( rA != 0 )
{
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// check if rD is already loaded, else use new temporary register
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext, PPCREC_IML_OP_ADD, registerRD, registerRA, imm);
}
else
{
// rA not used, instruction is value assignment
// rD = imm
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ASSIGN, registerRD, imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
}
// never updates any cr
return true;
}
bool PPCRecompilerImlGen_ADDIS(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rD, rA;
uint32 imm;
PPC_OPC_TEMPL_D_Shift16(opcode, rD, rA, imm);
if( rA != 0 )
{
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// check if rD is already loaded, else use new temporary register
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext, PPCREC_IML_OP_ADD, registerRD, registerRA, (sint32)imm);
}
else
{
// rA not used, instruction turns into simple value assignment
// rD = imm
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ASSIGN, registerRD, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
}
// never updates any cr
return true;
}
bool PPCRecompilerImlGen_ADDIC(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
// rD = rA + imm;
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// check if rD is already loaded, else use new temporary register
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext, PPCREC_IML_OP_ADD_UPDATE_CARRY, registerRD, registerRA, imm);
// never updates any cr
return true;
}
bool PPCRecompilerImlGen_ADDIC_(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
// this opcode is identical to ADDIC but additionally it updates CR0
sint32 rD, rA;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
// rD = rA + imm;
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// check if rD is already loaded, else use new temporary register
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext, PPCREC_IML_OP_ADD_UPDATE_CARRY, registerRD, registerRA, imm, 0, PPCREC_CR_MODE_LOGICAL);
return true;
}
bool PPCRecompilerImlGen_SUBF(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
// hCPU->gpr[rD] = ~hCPU->gpr[rA] + hCPU->gpr[rB] + 1;
// rD = rB - rA
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerRB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( opcode&PPC_OPC_RC )
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_SUB, registerRD, registerRB, registerRA, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_SUB, registerRD, registerRB, registerRA);
return true;
}
bool PPCRecompilerImlGen_SUBFE(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
// hCPU->gpr[rD] = ~hCPU->gpr[rA] + hCPU->gpr[rB] + ca;
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerRB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( opcode&PPC_OPC_RC )
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_SUB_CARRY_UPDATE_CARRY, registerRD, registerRB, registerRA, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_SUB_CARRY_UPDATE_CARRY, registerRD, registerRB, registerRA);
return true;
}
bool PPCRecompilerImlGen_SUBFZE(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
if( rB != 0 )
debugBreakpoint();
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( opcode&PPC_OPC_RC )
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_SUB_CARRY_UPDATE_CARRY, registerRD, registerRA, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_SUB_CARRY_UPDATE_CARRY, registerRD, registerRA);
return true;
}
bool PPCRecompilerImlGen_SUBFC(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
// hCPU->gpr[rD] = ~hCPU->gpr[rA] + hCPU->gpr[rB] + 1;
// rD = rB - rA
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerRB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_SUBFC, registerRD, registerRA, registerRB);
if (opcode & PPC_OPC_RC)
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_AND, registerRD, registerRD, 0, PPCREC_CR_MODE_LOGICAL);
return true;
}
bool PPCRecompilerImlGen_SUBFIC(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
//uint32 a = hCPU->gpr[rA];
//hCPU->gpr[rD] = ~a + imm + 1;
// cr0 is never affected
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext, PPCREC_IML_OP_SUBFC, registerRD, registerRA, imm);
return true;
}
bool PPCRecompilerImlGen_MULLI(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rD, rA;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
// mulli instruction does not modify any flags
uint32 registerResult = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rD, false);
uint32 registerOperand = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext, PPCREC_IML_OP_MULTIPLY_SIGNED, registerResult, registerOperand, (sint32)imm);
return true;
}
bool PPCRecompilerImlGen_MULLW(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
//hCPU->gpr[rD] = hCPU->gpr[rA] * hCPU->gpr[rB];
uint32 registerResult = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rD, false);
uint32 registerOperand1 = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerOperand2 = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
if (opcode & PPC_OPC_OE)
{
return false;
}
if( opcode&PPC_OPC_RC )
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_MULTIPLY_SIGNED, registerResult, registerOperand1, registerOperand2, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_MULTIPLY_SIGNED, registerResult, registerOperand1, registerOperand2);
return true;
}
bool PPCRecompilerImlGen_MULHW(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
//hCPU->gpr[rD] = ((sint64)(sint32)hCPU->gpr[rA] * (sint64)(sint32)hCPU->gpr[rB])>>32;
uint32 registerResult = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rD, false);
uint32 registerOperand1 = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerOperand2 = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
if( opcode&PPC_OPC_RC )
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_MULTIPLY_HIGH_SIGNED, registerResult, registerOperand1, registerOperand2, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_MULTIPLY_HIGH_SIGNED, registerResult, registerOperand1, registerOperand2);
return true;
}
bool PPCRecompilerImlGen_MULHWU(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
//hCPU->gpr[rD] = (hCPU->gpr[rA] * hCPU->gpr[rB])>>32;
uint32 registerResult = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rD, false);
uint32 registerOperand1 = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerOperand2 = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
if( opcode&PPC_OPC_RC )
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_MULTIPLY_HIGH_UNSIGNED, registerResult, registerOperand1, registerOperand2, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_MULTIPLY_HIGH_UNSIGNED, registerResult, registerOperand1, registerOperand2);
return true;
}
bool PPCRecompilerImlGen_DIVW(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
// hCPU->gpr[rD] = (sint32)a / (sint32)b;
uint32 registerResult = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rD, false);
uint32 registerOperand1 = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerOperand2 = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
if (opcode & PPC_OPC_RC)
{
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_DIVIDE_SIGNED, registerResult, registerOperand1, registerOperand2, 0, PPCREC_CR_MODE_ARITHMETIC);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_DIVIDE_SIGNED, registerResult, registerOperand1, registerOperand2);
}
return true;
}
bool PPCRecompilerImlGen_DIVWU(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
// hCPU->gpr[rD] = (uint32)a / (uint32)b;
uint32 registerResult = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rD, false);
uint32 registerOperand1 = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerOperand2 = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
if (opcode & PPC_OPC_RC)
{
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_DIVIDE_UNSIGNED, registerResult, registerOperand1, registerOperand2, 0, PPCREC_CR_MODE_ARITHMETIC);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_DIVIDE_UNSIGNED, registerResult, registerOperand1, registerOperand2);
}
return true;
}
bool PPCRecompilerImlGen_RLWINM(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rS, rA, SH, MB, ME;
PPC_OPC_TEMPL_M(opcode, rS, rA, SH, MB, ME);
uint32 mask = ppc_mask(MB, ME);
//uint32 v = ppc_word_rotl(hCPU->gpr[rS], SH);
//hCPU->gpr[rA] = v & mask;
uint32 registerRS = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false);
uint32 registerRA = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
// handle special forms of RLWINM
if( SH == 0 && SH == (ME-SH) && MB == 0 )
{
// CLRRWI
// todo
}
else if( ME == (31-SH) && MB == 0 )
{
// SLWI
if(opcode&PPC_OPC_RC)
PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext, PPCREC_IML_OP_LEFT_SHIFT, registerRA, registerRS, SH, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext, PPCREC_IML_OP_LEFT_SHIFT, registerRA, registerRS, SH);
return true;
}
else if( SH == (32-MB) && ME == 31 )
{
// SRWI
if(opcode&PPC_OPC_RC)
PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext, PPCREC_IML_OP_RIGHT_SHIFT, registerRA, registerRS, MB, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext, PPCREC_IML_OP_RIGHT_SHIFT, registerRA, registerRS, MB);
return true;
}
// general handler
if( registerRA != registerRS )
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, registerRA, registerRS);
if( SH != 0 )
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_LEFT_ROTATE, registerRA, SH, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
if(opcode&PPC_OPC_RC)
{
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_AND, registerRA, (sint32)mask, 0, false, false, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
if( mask != 0xFFFFFFFF )
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_AND, registerRA, (sint32)mask, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
}
return true;
}
bool PPCRecompilerImlGen_RLWIMI(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rS, rA, SH, MB, ME;
PPC_OPC_TEMPL_M(opcode, rS, rA, SH, MB, ME);
uint32 registerRS = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false);
uint32 registerRA = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
// pack RLWIMI parameters into single integer
uint32 vImm = MB|(ME<<8)|(SH<<16);
PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext, PPCREC_IML_OP_RLWIMI, registerRA, registerRS, (sint32)vImm, PPC_REC_INVALID_REGISTER, 0);
if (opcode & PPC_OPC_RC)
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_AND, registerRA, registerRA, 0, PPCREC_CR_MODE_LOGICAL);
return true;
}
bool PPCRecompilerImlGen_RLWNM(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA, rB, MB, ME;
PPC_OPC_TEMPL_M(opcode, rS, rA, rB, MB, ME);
// uint32 v = ppc_word_rotl(hCPU->gpr[rS], hCPU->gpr[rB]);
uint32 mask = ppc_mask(MB, ME);
// uint32 v = ppc_word_rotl(hCPU->gpr[rS], hCPU->gpr[rB]);
// hCPU->gpr[rA] = v & mask;
uint32 registerRS = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false);
uint32 registerRB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 registerRA = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_LEFT_ROTATE, registerRA, registerRS, registerRB);
if (opcode & PPC_OPC_RC)
{
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_AND, registerRA, (sint32)mask, 32, false, false, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
if( mask != 0xFFFFFFFF )
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_AND, registerRA, (sint32)mask, 32, false, false, PPC_REC_INVALID_REGISTER, 0);
}
return true;
}
bool PPCRecompilerImlGen_SRAW(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
//uint32 SH = hCPU->gpr[rB] & 0x3f;
//hCPU->gpr[rA] = hCPU->gpr[rS];
//hCPU->xer_ca = 0;
//if (hCPU->gpr[rA] & 0x80000000) {
// uint32 ca = 0;
// for (uint32 i=0; i < SH; i++) {
// if (hCPU->gpr[rA] & 1) ca = 1;
// hCPU->gpr[rA] >>= 1;
// hCPU->gpr[rA] |= 0x80000000;
// }
// if (ca) hCPU->xer_ca = 1;
//} else {
// if (SH > 31) {
// hCPU->gpr[rA] = 0;
// } else {
// hCPU->gpr[rA] >>= SH;
// }
//}
//if (Opcode & PPC_OPC_RC) {
// // update cr0 flags
// ppc_update_cr0(hCPU, hCPU->gpr[rA]);
//}
uint32 registerRS = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false);
uint32 registerRB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 registerRA = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if( (opcode&PPC_OPC_RC) != 0 )
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_SRAW, registerRA, registerRS, registerRB, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_SRAW, registerRA, registerRS, registerRB);
return true;
}
bool PPCRecompilerImlGen_SRAWI(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rS, rA;
uint32 SH;
PPC_OPC_TEMPL_X(opcode, rS, rA, SH);
cemu_assert_debug(SH < 32);
uint32 registerRS = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false);
uint32 registerRA = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if( opcode&PPC_OPC_RC )
PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext, PPCREC_IML_OP_SRAW, registerRA, registerRS, (sint32)SH, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext, PPCREC_IML_OP_SRAW, registerRA, registerRS, (sint32)SH);
return true;
}
bool PPCRecompilerImlGen_SLW(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rS, rA, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
uint32 registerRS = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false);
uint32 registerRB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 registerRA = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if (opcode & PPC_OPC_RC)
{
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_SLW, registerRA, registerRS, registerRB, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_SLW, registerRA, registerRS, registerRB, PPC_REC_INVALID_REGISTER, 0);
}
return true;
}
bool PPCRecompilerImlGen_SRW(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rS, rA, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
uint32 registerRS = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false);
uint32 registerRB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 registerRA = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if (opcode & PPC_OPC_RC)
{
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_SRW, registerRA, registerRS, registerRB, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_SRW, registerRA, registerRS, registerRB, PPC_REC_INVALID_REGISTER, 0);
}
return true;
}
bool PPCRecompilerImlGen_EXTSH(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rS, rA, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
PPC_ASSERT(rB==0);
uint32 registerRS = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false);
uint32 registerRA = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if ( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN_S16_TO_S32, registerRA, registerRS, 0, PPCREC_CR_MODE_ARITHMETIC);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN_S16_TO_S32, registerRA, registerRS);
}
return true;
}
bool PPCRecompilerImlGen_EXTSB(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
uint32 registerRS = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false);
uint32 registerRA = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if ( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN_S8_TO_S32, registerRA, registerRS, 0, PPCREC_CR_MODE_ARITHMETIC);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN_S8_TO_S32, registerRA, registerRS);
}
return true;
}
bool PPCRecompilerImlGen_CNTLZW(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
PPC_ASSERT(rB==0);
if( opcode&PPC_OPC_RC )
{
return false;
}
uint32 registerRS = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false);
uint32 registerRA = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_CNTLZW, registerRA, registerRS);
//uint32 n=0;
//uint32 x=0x80000000;
//uint32 v=hCPU->gpr[rS];
//while (!(v & x)) {
// n++;
// if (n==32) break;
// x>>=1;
//}
//hCPU->gpr[rA] = n;
//if (Opcode & PPC_OPC_RC) {
// // update cr0 flags
// ppc_update_cr0(hCPU, hCPU->gpr[rA]);
//}
return true;
}
bool PPCRecompilerImlGen_NEG(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA, rB;
PPC_OPC_TEMPL_XO(opcode, rD, rA, rB);
PPC_ASSERT(rB == 0);
//hCPU->gpr[rD] = -((signed int)hCPU->gpr[rA]);
//if (Opcode & PPC_OPC_RC) {
// // update cr0 flags
// ppc_update_cr0(hCPU, hCPU->gpr[rD]);
//}
uint32 registerRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 registerRD = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NEG, registerRD, registerRA, 0, PPCREC_CR_MODE_ARITHMETIC);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NEG, registerRD, registerRA);
}
return true;
}
void PPCRecompilerImlGen_LWZ(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rA, rD;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return;
}
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// load half
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegister, imm, 32, false, true);
}
void PPCRecompilerImlGen_LWZU(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rA, rD;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return;
}
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// add imm to memory register
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ADD, gprRegister, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// load half
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegister, 0, 32, false, true);
}
void PPCRecompilerImlGen_LHA(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rA, rD;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return;
}
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new temporary register
// load half
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegister, imm, 16, true, true);
}
void PPCRecompilerImlGen_LHAU(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rD;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return;
}
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// add imm to memory register
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ADD, gprRegister, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new temporary register
// load half
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegister, 0, 16, true, true);
}
void PPCRecompilerImlGen_LHZ(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rD;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
// note: Darksiders 2 has this instruction form but it is never executed.
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return;
}
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new temporary register
// load half
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegister, imm, 16, false, true);
}
void PPCRecompilerImlGen_LHZU(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rD;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return;
}
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// add imm to memory register
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ADD, gprRegister, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new temporary register
// load half
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegister, 0, 16, false, true);
}
void PPCRecompilerImlGen_LBZ(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rA, rD;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return;
}
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// load byte
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegister, imm, 8, false, true);
}
void PPCRecompilerImlGen_LBZU(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rA, rD;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return;
}
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// add imm to memory register
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ADD, gprRegister, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// load byte
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegister, 0, 8, false, true);
}
bool PPCRecompilerImlGen_LWZX(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rD, rB;
PPC_OPC_TEMPL_X(opcode, rD, rA, rB);
if( rA == 0 )
{
return false;
}
// hCPU->gpr[rD] = memory_readU8((rA?hCPU->gpr[rA]:0)+hCPU->gpr[rB]);
// load memory rA and rB into register
uint32 gprRegisterA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// load word
PPCRecompilerImlGen_generateNewInstruction_r_memory_indexed(ppcImlGenContext, destinationRegister, gprRegisterA, gprRegisterB, 32, false, true);
return true;
}
bool PPCRecompilerImlGen_LWZUX(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rD, rB;
PPC_OPC_TEMPL_X(opcode, rD, rA, rB);
if( rA == 0 )
{
return false;
}
// load memory rA and rB into register
uint32 gprRegisterA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// add rB to rA
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ADD, gprRegisterA, gprRegisterB);
// load word
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegisterA, 0, 32, false, true);
return true;
}
bool PPCRecompilerImlGen_LWBRX(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rD, rB;
PPC_OPC_TEMPL_X(opcode, rD, rA, rB);
// load memory rA and rB into register
uint32 gprRegisterA = 0;
if( rA )
gprRegisterA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0 + rA, false);
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0 + rB, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0 + rD);
if (destinationRegister == PPC_REC_INVALID_REGISTER)
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0 + rD); // else just create new register
// load word
if( rA )
PPCRecompilerImlGen_generateNewInstruction_r_memory_indexed(ppcImlGenContext, destinationRegister, gprRegisterA, gprRegisterB, 32, false, false);
else
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegisterB, 0, 32, false, false);
return true;
}
bool PPCRecompilerImlGen_LHAX(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rD, rB;
PPC_OPC_TEMPL_X(opcode, rD, rA, rB);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return true;
}
// load memory rA and rB into register
uint32 gprRegisterA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// load half word
PPCRecompilerImlGen_generateNewInstruction_r_memory_indexed(ppcImlGenContext, destinationRegister, gprRegisterA, gprRegisterB, 16, true, true);
return true;
}
bool PPCRecompilerImlGen_LHAUX(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rD, rB;
PPC_OPC_TEMPL_X(opcode, rD, rA, rB);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return true;
}
// load memory rA and rB into register
uint32 gprRegisterA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// add rB to rA
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ADD, gprRegisterA, gprRegisterB);
// load half word
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegisterA, 0, 16, true, true);
return true;
}
bool PPCRecompilerImlGen_LHZX(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rD, rB;
PPC_OPC_TEMPL_X(opcode, rD, rA, rB);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return true;
}
// load memory rA and rB into register
uint32 gprRegisterA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// load half word
PPCRecompilerImlGen_generateNewInstruction_r_memory_indexed(ppcImlGenContext, destinationRegister, gprRegisterA, gprRegisterB, 16, false, true);
return true;
}
bool PPCRecompilerImlGen_LHZUX(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rD, rB;
PPC_OPC_TEMPL_X(opcode, rD, rA, rB);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return true;
}
// load memory rA and rB into register
uint32 gprRegisterA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// add rB to rA
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ADD, gprRegisterA, gprRegisterB);
// load hald word
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegisterA, 0, 16, false, true);
return true;
}
void PPCRecompilerImlGen_LHBRX(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rD, rB;
PPC_OPC_TEMPL_X(opcode, rD, rA, rB);
// load memory rA and rB into register
uint32 gprRegisterA = rA != 0 ? PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0 + rA, false) : 0;
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0 + rB, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0 + rD);
if (destinationRegister == PPC_REC_INVALID_REGISTER)
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0 + rD); // else just create new register
// load half word (little-endian)
if (rA == 0)
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegisterB, 0, 16, false, false);
else
PPCRecompilerImlGen_generateNewInstruction_r_memory_indexed(ppcImlGenContext, destinationRegister, gprRegisterA, gprRegisterB, 16, false, false);
}
bool PPCRecompilerImlGen_LBZX(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rD, rB;
PPC_OPC_TEMPL_X(opcode, rD, rA, rB);
if( rA == 0 )
{
// special case where rA is ignored and only rB is used
return false;
}
// hCPU->gpr[rD] = memory_readU8((rA?hCPU->gpr[rA]:0)+hCPU->gpr[rB]);
// load memory rA and rB into register
uint32 gprRegisterA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// load byte
PPCRecompilerImlGen_generateNewInstruction_r_memory_indexed(ppcImlGenContext, destinationRegister, gprRegisterA, gprRegisterB, 8, false, true);
return true;
}
bool PPCRecompilerImlGen_LBZUX(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rD, rB;
PPC_OPC_TEMPL_X(opcode, rD, rA, rB);
if (rA == 0)
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return true;
}
// load memory rA and rB into register
uint32 gprRegisterA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0 + rA, false);
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0 + rB, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0 + rD);
if (destinationRegister == PPC_REC_INVALID_REGISTER)
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0 + rD); // else just create new register
// add rB to rA
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ADD, gprRegisterA, gprRegisterB);
// load byte
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegisterA, 0, 8, false, true);
return true;
}
bool PPCRecompilerImlGen_LWARX(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rD, rB;
PPC_OPC_TEMPL_X(opcode, rD, rA, rB);
// load memory rA and rB into register
uint32 gprRegisterA = rA != 0?PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false):0;
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// load word
if( rA != 0 )
PPCRecompilerImlGen_generateNewInstruction_r_memory_indexed(ppcImlGenContext, destinationRegister, gprRegisterA, gprRegisterB, PPC_REC_LOAD_LWARX_MARKER, false, true);
else
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegisterB, 0, PPC_REC_LOAD_LWARX_MARKER, false, true);
return true;
}
void PPCRecompilerImlGen_LMW(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rD, rA;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
//uint32 ea = (rA ? hCPU->gpr[rA] : 0) + imm;
sint32 index = 0;
while( rD <= 31 )
{
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// load word
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegister, imm+index*4, 32, false, true);
// next
rD++;
index++;
}
}
void PPCRecompilerImlGen_STW(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rA, rD;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
// note: Darksiders 2 has this instruction form but it is never executed.
//PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return;
}
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// load source register
uint32 sourceRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rD, false); // can be the same as gprRegister
// store word
PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext, sourceRegister, gprRegister, imm, 32, true);
}
void PPCRecompilerImlGen_STWU(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rA, rD;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return;
}
// store&update instructions where rD==rA store the register contents without added imm, therefore we need to handle it differently
// get memory gpr register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// get source register
uint32 sourceRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rD, false); // can be the same as gprRegister
// add imm to memory register early if possible
if( rD != rA )
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ADD, gprRegister, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
// store word
PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext, sourceRegister, gprRegister, (rD==rA)?imm:0, 32, true);
// add imm to memory register late if we couldn't do it early
if( rD == rA )
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ADD, gprRegister, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
}
void PPCRecompilerImlGen_STH(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rA, rD;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return;
}
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// load source register
uint32 sourceRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rD, false); // can be the same as gprRegister
// load half
PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext, sourceRegister, gprRegister, imm, 16, true);
}
void PPCRecompilerImlGen_STHU(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rA, rD;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return;
}
// get memory gpr register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// get source register
uint32 sourceRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rD, false); // can be the same as gprRegister
// add imm to memory register early if possible
if( rD != rA )
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ADD, gprRegister, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
// store word
PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext, sourceRegister, gprRegister, (rD==rA)?imm:0, 16, true);
// add imm to memory register late if we couldn't do it early
if( rD == rA )
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ADD, gprRegister, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
}
void PPCRecompilerImlGen_STB(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rA, rS;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rS, rA, imm);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return;
}
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// load source register
uint32 sourceRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false); // can be the same as gprRegister
// store byte
PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext, sourceRegister, gprRegister, imm, 8, true);
}
void PPCRecompilerImlGen_STBU(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rA, rD;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm);
if( rA == 0 )
{
// special form where gpr is ignored and only imm is used
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_DEBUGBREAK, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->ppcAddressOfCurrentInstruction, ppcImlGenContext->cyclesSinceLastBranch);
return;
}
// get memory gpr register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// get source register
uint32 sourceRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rD, false); // can be the same as gprRegister
// add imm to memory register early if possible
if( rD != rA )
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ADD, gprRegister, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
// store byte
PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext, sourceRegister, gprRegister, (rD==rA)?imm:0, 8, true);
// add imm to memory register late if we couldn't do it early
if( rD == rA )
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_ADD, gprRegister, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
}
// generic indexed store (STWX, STHX, STBX, STWUX. If bitReversed == true -> STHBRX)
bool PPCRecompilerImlGen_STORE_INDEXED(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode, uint32 storeBitWidth, bool byteReversed = false)
{
sint32 rA, rS, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
// prepare registers
uint32 gprRegisterA;
if(rA != 0)
gprRegisterA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0 + rA, false);
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 destinationRegister = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
// store word
if (rA == 0)
{
PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext, destinationRegister, gprRegisterB, 0, storeBitWidth, !byteReversed);
}
else
PPCRecompilerImlGen_generateNewInstruction_memory_r_indexed(ppcImlGenContext, destinationRegister, gprRegisterA, gprRegisterB, storeBitWidth, false, !byteReversed);
return true;
}
bool PPCRecompilerImlGen_STORE_INDEXED_UPDATE(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode, uint32 storeBitWidth)
{
sint32 rA, rS, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
if( rA == 0 )
{
// not supported
return false;
}
if( rS == rA || rS == rB )
{
// prepare registers
uint32 gprRegisterA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 destinationRegister = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
// store word
PPCRecompilerImlGen_generateNewInstruction_memory_r_indexed(ppcImlGenContext, destinationRegister, gprRegisterA, gprRegisterB, storeBitWidth, false, true);
// update EA after store
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ADD, gprRegisterA, gprRegisterB);
return true;
}
// prepare registers
uint32 gprRegisterA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 sourceRegister = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
// update EA
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ADD, gprRegisterA, gprRegisterB);
// store word
PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext, sourceRegister, gprRegisterA, 0, storeBitWidth, true);
return true;
}
bool PPCRecompilerImlGen_STWCX(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rS, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
// prepare registers
uint32 gprRegisterA = rA!=0?PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false):0;
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 destinationRegister = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
// store word
if( rA != 0 )
PPCRecompilerImlGen_generateNewInstruction_memory_r_indexed(ppcImlGenContext, destinationRegister, gprRegisterA, gprRegisterB, PPC_REC_STORE_STWCX_MARKER, false, true);
else
PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext, destinationRegister, gprRegisterB, 0, PPC_REC_STORE_STWCX_MARKER, true);
return true;
}
bool PPCRecompilerImlGen_STWBRX(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rS, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
// prepare registers
uint32 gprRegisterA = rA!=0?PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false):0;
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
uint32 destinationRegister = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
// store word
if( rA != 0 )
PPCRecompilerImlGen_generateNewInstruction_memory_r_indexed(ppcImlGenContext, destinationRegister, gprRegisterA, gprRegisterB, 32, false, false);
else
PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext, destinationRegister, gprRegisterB, 0, 32, false);
return true;
}
void PPCRecompilerImlGen_STMW(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA;
uint32 imm;
PPC_OPC_TEMPL_D_SImm(opcode, rS, rA, imm);
sint32 index = 0;
while( rS <= 31 )
{
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// load source register
uint32 sourceRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false); // can be the same as gprRegister
// store word
PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext, sourceRegister, gprRegister, imm+index*4, 32, true);
// next
rS++;
index++;
}
}
bool PPCRecompilerImlGen_LSWI(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rA, rD, nb;
PPC_OPC_TEMPL_X(opcode, rD, rA, nb);
if( nb == 0 )
nb = 32;
if( nb == 4 )
{
// if nb == 4 this instruction immitates LWZ
if( rA == 0 )
{
#ifdef CEMU_DEBUG_ASSERT
assert_dbg(); // special form where gpr is ignored and only imm is used
#endif
return false;
}
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// load half
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegister, 0, 32, false, true);
return true;
}
else if( nb == 2 )
{
// if nb == 2 this instruction immitates a LHZ but the result is shifted left by 16 bits
if( rA == 0 )
{
#ifdef CEMU_DEBUG_ASSERT
assert_dbg(); // special form where gpr is ignored and only imm is used
#endif
return false;
}
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// load half
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegister, 0, 16, false, true);
// shift
PPCRecompilerImlGen_generateNewInstruction_r_r_s32(ppcImlGenContext, PPCREC_IML_OP_LEFT_SHIFT, destinationRegister, destinationRegister, 16);
return true;
}
else if( nb == 3 )
{
// if nb == 3 this instruction loads a 3-byte big-endian and the result is shifted left by 8 bits
if( rA == 0 )
{
#ifdef CEMU_DEBUG_ASSERT
assert_dbg(); // special form where gpr is ignored and only imm is used
#endif
return false;
}
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// check if destination register is already loaded
uint32 destinationRegister = PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, PPCREC_NAME_R0+rD);
if( destinationRegister == PPC_REC_INVALID_REGISTER )
destinationRegister = PPCRecompilerImlGen_getAndLockFreeTemporaryGPR(ppcImlGenContext, PPCREC_NAME_R0+rD); // else just create new register
// load half
PPCRecompilerImlGen_generateNewInstruction_r_memory(ppcImlGenContext, destinationRegister, gprRegister, 0, PPC_REC_STORE_LSWI_3, false, true);
return true;
}
debug_printf("PPCRecompilerImlGen_LSWI(): Unsupported nb value %d\n", nb);
return false;
}
bool PPCRecompilerImlGen_STSWI(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rA, rS, nb;
PPC_OPC_TEMPL_X(opcode, rS, rA, nb);
if( nb == 0 )
nb = 32;
if( nb == 4 )
{
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// load source register
uint32 sourceRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false); // can be the same as gprRegister
// store word
PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext, sourceRegister, gprRegister, 0, 32, true);
return true;
}
else if( nb == 2 )
{
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// load source register
uint32 sourceRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false); // can be the same as gprRegister
// store half-word (shifted << 16)
PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext, sourceRegister, gprRegister, 0, PPC_REC_STORE_STSWI_2, false);
return true;
}
else if( nb == 3 )
{
// load memory gpr into register
uint32 gprRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false);
// load source register
uint32 sourceRegister = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS, false); // can be the same as gprRegister
// store 3-byte-word (shifted << 8)
PPCRecompilerImlGen_generateNewInstruction_memory_r(ppcImlGenContext, sourceRegister, gprRegister, 0, PPC_REC_STORE_STSWI_3, false);
return true;
}
debug_printf("PPCRecompilerImlGen_STSWI(): Unsupported nb value %d\n", nb);
return false;
}
bool PPCRecompilerImlGen_DCBZ(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rA, rB;
rA = (opcode>>16)&0x1F;
rB = (opcode>>11)&0x1F;
// prepare registers
uint32 gprRegisterA = rA!=0?PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA, false):0;
uint32 gprRegisterB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB, false);
// store
if( rA != 0 )
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_DCBZ, gprRegisterA, gprRegisterB);
else
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_DCBZ, gprRegisterB, gprRegisterB);
return true;
}
bool PPCRecompilerImlGen_OR(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rS, rA, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
// check for MR mnemonic
if( rS == rB )
{
// simple register copy
if( rA != rS ) // check if no-op
{
sint32 gprSourceReg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSourceReg, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSourceReg);
}
}
else
{
if( opcode&PPC_OPC_RC )
{
// no effect but CR is updated
sint32 gprSourceReg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprSourceReg, gprSourceReg, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
// no-op
}
}
}
else
{
// rA = rS | rA
sint32 gprSource1Reg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprSource2Reg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if( gprSource1Reg == gprDestReg || gprSource2Reg == gprDestReg )
{
// make sure we don't overwrite rS or rA
if( gprSource1Reg == gprDestReg )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_OR, gprDestReg, gprSource2Reg);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_OR, gprDestReg, gprSource1Reg);
}
if( opcode&PPC_OPC_RC )
{
// fixme: merge CR update into OR instruction above
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_AND, gprDestReg, gprDestReg, 0, PPCREC_CR_MODE_LOGICAL);
}
}
else
{
// rA = rS
if( gprDestReg != gprSource1Reg )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSource1Reg);
}
// rA |= rB
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_OR, gprDestReg, gprSource2Reg, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_OR, gprDestReg, gprSource2Reg);
}
}
}
return true;
}
bool PPCRecompilerImlGen_ORC(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
// hCPU->gpr[rA] = hCPU->gpr[rS] | ~hCPU->gpr[rB];
sint32 gprSource1Reg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprSource2Reg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if( opcode&PPC_OPC_RC )
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_ORC, gprDestReg, gprSource1Reg, gprSource2Reg, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r_r(ppcImlGenContext, PPCREC_IML_OP_ORC, gprDestReg, gprSource1Reg, gprSource2Reg);
return true;
}
bool PPCRecompilerImlGen_NOR(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int rS, rA, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
//hCPU->gpr[rA] = ~(hCPU->gpr[rS] | hCPU->gpr[rB]);
// check for NOT mnemonic
if( rS == rB )
{
// simple register copy with NOT
sint32 gprSourceReg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if( gprDestReg != gprSourceReg )
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSourceReg);
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NOT, gprDestReg, gprDestReg, 0, PPCREC_CR_MODE_ARITHMETIC);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NOT, gprDestReg, gprDestReg);
}
}
else
{
// rA = rS | rA
sint32 gprSource1Reg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprSource2Reg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if( gprSource1Reg == gprDestReg || gprSource2Reg == gprDestReg )
{
// make sure we don't overwrite rS or rA
if( gprSource1Reg == gprDestReg )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_OR, gprDestReg, gprSource2Reg);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_OR, gprDestReg, gprSource1Reg);
}
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NOT, gprDestReg, gprDestReg);
if( opcode&PPC_OPC_RC )
{
// fixme: merge CR update into OR instruction above
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_AND, gprDestReg, gprDestReg, 0, PPCREC_CR_MODE_LOGICAL);
}
}
else
{
// rA = rS
if( gprDestReg != gprSource1Reg )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSource1Reg);
}
// rA |= rB
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_OR, gprDestReg, gprSource2Reg);
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NOT, gprDestReg, gprDestReg, 0, PPCREC_CR_MODE_ARITHMETIC);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NOT, gprDestReg, gprDestReg);
}
}
}
return true;
}
bool PPCRecompilerImlGen_AND(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
// check for MR mnemonic
if( rS == rB )
{
// simple register copy
if( rA != rS ) // check if no-op
{
sint32 gprSourceReg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSourceReg, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSourceReg);
}
}
else
{
cemu_assert_unimplemented(); // no-op -> verify this case
}
}
else
{
// rA = rS & rA
sint32 gprSource1Reg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprSource2Reg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if( gprSource1Reg == gprDestReg || gprSource2Reg == gprDestReg )
{
// make sure we don't overwrite rS or rA
if( gprSource1Reg == gprDestReg )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_AND, gprDestReg, gprSource2Reg);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_AND, gprDestReg, gprSource1Reg);
}
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_AND, gprDestReg, gprDestReg, 0, PPCREC_CR_MODE_LOGICAL);
}
}
else
{
// rA = rS
if( gprDestReg != gprSource1Reg )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSource1Reg);
}
// rA &= rB
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_AND, gprDestReg, gprSource2Reg, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_AND, gprDestReg, gprSource2Reg);
}
}
}
return true;
}
bool PPCRecompilerImlGen_ANDC(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
//hCPU->gpr[rA] = hCPU->gpr[rS] & ~hCPU->gpr[rB];
//if (Opcode & PPC_OPC_RC) {
if( rS == rB )
{
// result is always 0 -> replace with XOR rA,rA
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_XOR, gprDestReg, gprDestReg, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_XOR, gprDestReg, gprDestReg);
}
}
else if( rA == rB )
{
// rB already in rA, therefore we complement rA first and then AND it with rS
sint32 gprRS = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
// rA = ~rA
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NOT, gprRA, gprRA);
// rA &= rS
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_AND, gprRA, gprRS, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_AND, gprRA, gprRS);
}
}
else
{
// a & (~b) is the same as ~((~a) | b)
sint32 gprRA = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
sint32 gprRB = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB);
sint32 gprRS = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
// move rS to rA (if required)
if( gprRA != gprRS )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprRA, gprRS);
}
// rS already in rA, therefore we complement rS first and then OR it with rB
// rA = ~rA
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NOT, gprRA, gprRA);
// rA |= rB
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_OR, gprRA, gprRB);
// rA = ~rA
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NOT, gprRA, gprRA, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NOT, gprRA, gprRA);
}
}
return true;
}
void PPCRecompilerImlGen_ANDI(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA;
uint32 imm;
PPC_OPC_TEMPL_D_UImm(opcode, rS, rA, imm);
// ANDI. always sets cr0 flags
sint32 gprSourceReg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
// rA = rS
if( gprDestReg != gprSourceReg )
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSourceReg);
// rA &= imm32
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_AND, gprDestReg, (sint32)imm, 0, false, false, 0, PPCREC_CR_MODE_LOGICAL);
}
void PPCRecompilerImlGen_ANDIS(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA;
uint32 imm;
PPC_OPC_TEMPL_D_Shift16(opcode, rS, rA, imm);
// ANDI. always sets cr0 flags
sint32 gprSourceReg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
// rA = rS
if( gprDestReg != gprSourceReg )
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSourceReg);
// rA &= imm32
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_AND, gprDestReg, (sint32)imm, 0, false, false, 0, PPCREC_CR_MODE_LOGICAL);
}
bool PPCRecompilerImlGen_XOR(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
if( rS == rB )
{
// xor register with itself
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_XOR, gprDestReg, gprDestReg, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_XOR, gprDestReg, gprDestReg);
}
}
else
{
// rA = rS ^ rA
sint32 gprSource1Reg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprSource2Reg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if( gprSource1Reg == gprDestReg || gprSource2Reg == gprDestReg )
{
// make sure we don't overwrite rS or rA
if( gprSource1Reg == gprDestReg )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_XOR, gprDestReg, gprSource2Reg);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_XOR, gprDestReg, gprSource1Reg);
}
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_AND, gprDestReg, gprDestReg, 0, PPCREC_CR_MODE_LOGICAL);
}
}
else
{
// rA = rS
if( gprDestReg != gprSource1Reg )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSource1Reg);
}
// rA ^= rB
if( opcode&PPC_OPC_RC )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_XOR, gprDestReg, gprSource2Reg, 0, PPCREC_CR_MODE_LOGICAL);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_XOR, gprDestReg, gprSource2Reg);
}
}
}
return true;
}
bool PPCRecompilerImlGen_EQV(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA, rB;
PPC_OPC_TEMPL_X(opcode, rS, rA, rB);
if( rS == rB )
{
// xor register with itself, then invert
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_XOR, gprDestReg, gprDestReg);
if( opcode&PPC_OPC_RC )
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NOT, gprDestReg, gprDestReg, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NOT, gprDestReg, gprDestReg);
}
else
{
// rA = ~(rS ^ rA)
sint32 gprSource1Reg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprSource2Reg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rB);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
if( gprSource1Reg == gprDestReg || gprSource2Reg == gprDestReg )
{
// make sure we don't overwrite rS or rA
if( gprSource1Reg == gprDestReg )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_XOR, gprDestReg, gprSource2Reg);
}
else
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_XOR, gprDestReg, gprSource1Reg);
}
}
else
{
// rA = rS
if( gprDestReg != gprSource1Reg )
{
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSource1Reg);
}
// rA ^= rB
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_XOR, gprDestReg, gprSource2Reg);
}
if( opcode&PPC_OPC_RC )
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NOT, gprDestReg, gprDestReg, 0, PPCREC_CR_MODE_LOGICAL);
else
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_NOT, gprDestReg, gprDestReg);
}
return true;
}
void PPCRecompilerImlGen_ORI(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA;
uint32 imm;
PPC_OPC_TEMPL_D_UImm(opcode, rS, rA, imm);
// ORI does not set cr0 flags
//hCPU->gpr[rA] = hCPU->gpr[rS] | imm;
sint32 gprSourceReg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
// rA = rS
if( gprDestReg != gprSourceReg )
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSourceReg);
// rA |= imm32
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_OR, gprDestReg, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
}
void PPCRecompilerImlGen_ORIS(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA;
uint32 imm;
PPC_OPC_TEMPL_D_Shift16(opcode, rS, rA, imm);
// ORI does not set cr0 flags
//hCPU->gpr[rA] = hCPU->gpr[rS] | imm;
sint32 gprSourceReg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
// rA = rS
if( gprDestReg != gprSourceReg )
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSourceReg);
// rA |= imm32
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_OR, gprDestReg, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
}
void PPCRecompilerImlGen_XORI(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA;
uint32 imm;
PPC_OPC_TEMPL_D_UImm(opcode, rS, rA, imm);
//hCPU->gpr[rA] = hCPU->gpr[rS] ^ imm;
// XORI does not set cr0 flags
sint32 gprSourceReg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
// rA = rS
if( gprDestReg != gprSourceReg )
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSourceReg);
// rA |= imm32
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_XOR, gprDestReg, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
}
void PPCRecompilerImlGen_XORIS(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
sint32 rS, rA;
uint32 imm;
PPC_OPC_TEMPL_D_Shift16(opcode, rS, rA, imm);
//hCPU->gpr[rA] = hCPU->gpr[rS] ^ imm;
// XORIS does not set cr0 flags
sint32 gprSourceReg = PPCRecompilerImlGen_loadRegister(ppcImlGenContext, PPCREC_NAME_R0+rS);
sint32 gprDestReg = PPCRecompilerImlGen_loadOverwriteRegister(ppcImlGenContext, PPCREC_NAME_R0+rA);
// rA = rS
if( gprDestReg != gprSourceReg )
PPCRecompilerImlGen_generateNewInstruction_r_r(ppcImlGenContext, NULL, PPCREC_IML_OP_ASSIGN, gprDestReg, gprSourceReg);
// rA |= imm32
PPCRecompilerImlGen_generateNewInstruction_r_s32(ppcImlGenContext, PPCREC_IML_OP_XOR, gprDestReg, (sint32)imm, 0, false, false, PPC_REC_INVALID_REGISTER, 0);
}
bool PPCRecompilerImlGen_CROR(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int crD, crA, crB;
PPC_OPC_TEMPL_X(opcode, crD, crA, crB);
PPCRecompilerImlGen_generateNewInstruction_cr(ppcImlGenContext, PPCREC_IML_OP_CR_OR, crD, crA, crB);
return true;
}
bool PPCRecompilerImlGen_CRORC(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int crD, crA, crB;
PPC_OPC_TEMPL_X(opcode, crD, crA, crB);
PPCRecompilerImlGen_generateNewInstruction_cr(ppcImlGenContext, PPCREC_IML_OP_CR_ORC, crD, crA, crB);
return true;
}
bool PPCRecompilerImlGen_CRAND(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int crD, crA, crB;
PPC_OPC_TEMPL_X(opcode, crD, crA, crB);
PPCRecompilerImlGen_generateNewInstruction_cr(ppcImlGenContext, PPCREC_IML_OP_CR_AND, crD, crA, crB);
return true;
}
bool PPCRecompilerImlGen_CRANDC(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int crD, crA, crB;
PPC_OPC_TEMPL_X(opcode, crD, crA, crB);
PPCRecompilerImlGen_generateNewInstruction_cr(ppcImlGenContext, PPCREC_IML_OP_CR_ANDC, crD, crA, crB);
return true;
}
bool PPCRecompilerImlGen_CRXOR(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int crD, crA, crB;
PPC_OPC_TEMPL_X(opcode, crD, crA, crB);
if (crA == crB)
{
// both operands equal, clear bit in crD
// PPC's assert() uses this to pass a parameter to OSPanic
PPCRecompilerImlGen_generateNewInstruction_cr(ppcImlGenContext, PPCREC_IML_OP_CR_CLEAR, crD, 0, 0);
return true;
}
else
{
return false;
}
return true;
}
bool PPCRecompilerImlGen_CREQV(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
int crD, crA, crB;
PPC_OPC_TEMPL_X(opcode, crD, crA, crB);
if (crA == crB)
{
// both operands equal, set bit in crD
PPCRecompilerImlGen_generateNewInstruction_cr(ppcImlGenContext, PPCREC_IML_OP_CR_SET, crD, 0, 0);
return true;
}
else
{
return false;
}
return true;
}
bool PPCRecompilerImlGen_HLE(ppcImlGenContext_t* ppcImlGenContext, uint32 opcode)
{
uint32 hleFuncId = opcode&0xFFFF;
PPCRecompilerImlGen_generateNewInstruction_macro(ppcImlGenContext, PPCREC_IML_MACRO_HLE, ppcImlGenContext->ppcAddressOfCurrentInstruction, hleFuncId, 0);
return true;
}
uint32 PPCRecompiler_iterateCurrentInstruction(ppcImlGenContext_t* ppcImlGenContext)
{
uint32 v = CPU_swapEndianU32(*(ppcImlGenContext->currentInstruction));
ppcImlGenContext->currentInstruction += 1;
return v;
}
uint32 PPCRecompiler_getInstructionByOffset(ppcImlGenContext_t* ppcImlGenContext, uint32 offset)
{
uint32 v = CPU_swapEndianU32(*(ppcImlGenContext->currentInstruction + offset/4));
return v;
}
uint32 PPCRecompiler_getCurrentInstruction(ppcImlGenContext_t* ppcImlGenContext)
{
uint32 v = CPU_swapEndianU32(*(ppcImlGenContext->currentInstruction));
return v;
}
uint32 PPCRecompiler_getPreviousInstruction(ppcImlGenContext_t* ppcImlGenContext)
{
uint32 v = CPU_swapEndianU32(*(ppcImlGenContext->currentInstruction-1));
return v;
}
char _tempOpcodename[32];
const char* PPCRecompiler_getOpcodeDebugName(PPCRecImlInstruction_t* iml)
{
uint32 op = iml->operation;
if (op == PPCREC_IML_OP_ASSIGN)
return "MOV";
else if (op == PPCREC_IML_OP_ADD)
return "ADD";
else if (op == PPCREC_IML_OP_SUB)
return "SUB";
else if (op == PPCREC_IML_OP_ADD_CARRY_UPDATE_CARRY)
return "ADDCSC";
else if (op == PPCREC_IML_OP_OR)
return "OR";
else if (op == PPCREC_IML_OP_AND)
return "AND";
else if (op == PPCREC_IML_OP_XOR)
return "XOR";
else if (op == PPCREC_IML_OP_LEFT_SHIFT)
return "LSH";
else if (op == PPCREC_IML_OP_RIGHT_SHIFT)
return "RSH";
else if (op == PPCREC_IML_OP_MULTIPLY_SIGNED)
return "MULS";
else if (op == PPCREC_IML_OP_DIVIDE_SIGNED)
return "DIVS";
sprintf(_tempOpcodename, "OP0%02x_T%d", iml->operation, iml->type);
return _tempOpcodename;
}
void PPCRecDebug_addRegisterParam(StringBuf& strOutput, sint32 virtualRegister, bool isLast = false)
{
if (isLast)
{
if (virtualRegister < 10)
strOutput.addFmt("t{} ", virtualRegister);
else
strOutput.addFmt("t{}", virtualRegister);
return;
}
if (virtualRegister < 10)
strOutput.addFmt("t{} , ", virtualRegister);
else
strOutput.addFmt("t{}, ", virtualRegister);
}
void PPCRecDebug_addS32Param(StringBuf& strOutput, sint32 val, bool isLast = false)
{
if (isLast)
{
strOutput.addFmt("0x{:08x}", val);
return;
}
strOutput.addFmt("0x{:08x}, ", val);
}
void PPCRecompilerDebug_printLivenessRangeInfo(StringBuf& currentLineText, PPCRecImlSegment_t* imlSegment, sint32 offset)
{
// pad to 70 characters
sint32 index = currentLineText.getLen();
while (index < 70)
{
debug_printf(" ");
index++;
}
raLivenessSubrange_t* subrangeItr = imlSegment->raInfo.linkedList_allSubranges;
while (subrangeItr)
{
if (offset == subrangeItr->start.index)
{
if (false)//subrange->isDirtied && i == subrange->becomesDirtyAtIndex.index)
{
debug_printf("*%-2d", subrangeItr->range->virtualRegister);
}
else
{
debug_printf("|%-2d", subrangeItr->range->virtualRegister);
}
}
else if (false)//subrange->isDirtied && i == subrange->becomesDirtyAtIndex.index )
{
debug_printf("* ");
}
else if (offset >= subrangeItr->start.index && offset < subrangeItr->end.index)
{
debug_printf("| ");
}
else
{
debug_printf(" ");
}
index += 3;
// next
subrangeItr = subrangeItr->link_segmentSubrangesGPR.next;
}
}
void PPCRecompiler_dumpIMLSegment(PPCRecImlSegment_t* imlSegment, sint32 segmentIndex, bool printLivenessRangeInfo)
{
StringBuf strOutput(1024);
strOutput.addFmt("SEGMENT 0x{:04x} 0x{:08x} PPC 0x{:08x} - 0x{:08x} Loop-depth {}", segmentIndex, imlSegment->ppcAddress, imlSegment->ppcAddrMin, imlSegment->ppcAddrMax, imlSegment->loopDepth);
if (imlSegment->isEnterable)
{
strOutput.addFmt(" ENTERABLE (0x{:08x})", imlSegment->enterPPCAddress);
}
else if( imlSegment->isJumpDestination )
{
strOutput.addFmt(" JUMP-DEST (0x{:08x})", imlSegment->jumpDestinationPPCAddress);
}
debug_printf("%s\n", strOutput.c_str());
strOutput.reset();
strOutput.addFmt("SEGMENT NAME 0x{:016x}", (uintptr_t)imlSegment);
debug_printf("%s", strOutput.c_str());
if (printLivenessRangeInfo)
{
PPCRecompilerDebug_printLivenessRangeInfo(strOutput, imlSegment, RA_INTER_RANGE_START);
}
debug_printf("\n");
sint32 lineOffsetParameters = 18;
for(sint32 i=0; i<imlSegment->imlListCount; i++)
{
// don't log NOP instructions unless they have an associated PPC address
if(imlSegment->imlList[i].type == PPCREC_IML_TYPE_NO_OP && imlSegment->imlList[i].associatedPPCAddress == MPTR_NULL)
continue;
strOutput.reset();
strOutput.addFmt("{:08x} ", imlSegment->imlList[i].associatedPPCAddress);
if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_R_NAME || imlSegment->imlList[i].type == PPCREC_IML_TYPE_NAME_R)
{
if(imlSegment->imlList[i].type == PPCREC_IML_TYPE_R_NAME)
strOutput.add("LD_NAME");
else
strOutput.add("ST_NAME");
while ((sint32)strOutput.getLen() < lineOffsetParameters)
strOutput.add(" ");
PPCRecDebug_addRegisterParam(strOutput, imlSegment->imlList[i].op_r_name.registerIndex);
strOutput.addFmt("name_{} (", imlSegment->imlList[i].op_r_name.registerIndex, imlSegment->imlList[i].op_r_name.name);
if( imlSegment->imlList[i].op_r_name.name >= PPCREC_NAME_R0 && imlSegment->imlList[i].op_r_name.name < (PPCREC_NAME_R0+999) )
{
strOutput.addFmt("r{}", imlSegment->imlList[i].op_r_name.name-PPCREC_NAME_R0);
}
else if( imlSegment->imlList[i].op_r_name.name >= PPCREC_NAME_SPR0 && imlSegment->imlList[i].op_r_name.name < (PPCREC_NAME_SPR0+999) )
{
strOutput.addFmt("spr{}", imlSegment->imlList[i].op_r_name.name-PPCREC_NAME_SPR0);
}
else
strOutput.add("ukn");
strOutput.add(")");
}
else if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_R_R )
{
strOutput.addFmt("{}", PPCRecompiler_getOpcodeDebugName(imlSegment->imlList+i));
while ((sint32)strOutput.getLen() < lineOffsetParameters)
strOutput.add(" ");
PPCRecDebug_addRegisterParam(strOutput, imlSegment->imlList[i].op_r_r.registerResult);
PPCRecDebug_addRegisterParam(strOutput, imlSegment->imlList[i].op_r_r.registerA, true);
if( imlSegment->imlList[i].crRegister != PPC_REC_INVALID_REGISTER )
{
strOutput.addFmt(" -> CR{}", imlSegment->imlList[i].crRegister);
}
}
else if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_R_R_R )
{
strOutput.addFmt("{}", PPCRecompiler_getOpcodeDebugName(imlSegment->imlList + i));
while ((sint32)strOutput.getLen() < lineOffsetParameters)
strOutput.add(" ");
PPCRecDebug_addRegisterParam(strOutput, imlSegment->imlList[i].op_r_r_r.registerResult);
PPCRecDebug_addRegisterParam(strOutput, imlSegment->imlList[i].op_r_r_r.registerA);
PPCRecDebug_addRegisterParam(strOutput, imlSegment->imlList[i].op_r_r_r.registerB, true);
if( imlSegment->imlList[i].crRegister != PPC_REC_INVALID_REGISTER )
{
strOutput.addFmt(" -> CR{}", imlSegment->imlList[i].crRegister);
}
}
else if (imlSegment->imlList[i].type == PPCREC_IML_TYPE_R_R_S32)
{
strOutput.addFmt("{}", PPCRecompiler_getOpcodeDebugName(imlSegment->imlList + i));
while ((sint32)strOutput.getLen() < lineOffsetParameters)
strOutput.add(" ");
PPCRecDebug_addRegisterParam(strOutput, imlSegment->imlList[i].op_r_r_s32.registerResult);
PPCRecDebug_addRegisterParam(strOutput, imlSegment->imlList[i].op_r_r_s32.registerA);
PPCRecDebug_addS32Param(strOutput, imlSegment->imlList[i].op_r_r_s32.immS32, true);
if (imlSegment->imlList[i].crRegister != PPC_REC_INVALID_REGISTER)
{
strOutput.addFmt(" -> CR{}", imlSegment->imlList[i].crRegister);
}
}
else if (imlSegment->imlList[i].type == PPCREC_IML_TYPE_R_S32)
{
strOutput.addFmt("{}", PPCRecompiler_getOpcodeDebugName(imlSegment->imlList + i));
while ((sint32)strOutput.getLen() < lineOffsetParameters)
strOutput.add(" ");
PPCRecDebug_addRegisterParam(strOutput, imlSegment->imlList[i].op_r_immS32.registerIndex);
PPCRecDebug_addS32Param(strOutput, imlSegment->imlList[i].op_r_immS32.immS32, true);
if (imlSegment->imlList[i].crRegister != PPC_REC_INVALID_REGISTER)
{
strOutput.addFmt(" -> CR{}", imlSegment->imlList[i].crRegister);
}
}
else if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_JUMPMARK )
{
strOutput.addFmt("jm_{:08x}:", imlSegment->imlList[i].op_jumpmark.address);
}
else if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_PPC_ENTER )
{
strOutput.addFmt("ppcEnter_{:08x}:", imlSegment->imlList[i].op_ppcEnter.ppcAddress);
}
else if(imlSegment->imlList[i].type == PPCREC_IML_TYPE_LOAD || imlSegment->imlList[i].type == PPCREC_IML_TYPE_STORE ||
imlSegment->imlList[i].type == PPCREC_IML_TYPE_LOAD_INDEXED || imlSegment->imlList[i].type == PPCREC_IML_TYPE_STORE_INDEXED )
{
if(imlSegment->imlList[i].type == PPCREC_IML_TYPE_LOAD || imlSegment->imlList[i].type == PPCREC_IML_TYPE_LOAD_INDEXED)
strOutput.add("LD_");
else
strOutput.add("ST_");
if (imlSegment->imlList[i].op_storeLoad.flags2.signExtend)
strOutput.add("S");
else
strOutput.add("U");
strOutput.addFmt("{}", imlSegment->imlList[i].op_storeLoad.copyWidth);
while ((sint32)strOutput.getLen() < lineOffsetParameters)
strOutput.add(" ");
PPCRecDebug_addRegisterParam(strOutput, imlSegment->imlList[i].op_storeLoad.registerData);
if(imlSegment->imlList[i].type == PPCREC_IML_TYPE_LOAD_INDEXED || imlSegment->imlList[i].type == PPCREC_IML_TYPE_STORE_INDEXED)
strOutput.addFmt("[t{}+t{}]", imlSegment->imlList[i].op_storeLoad.registerMem, imlSegment->imlList[i].op_storeLoad.registerMem2);
else
strOutput.addFmt("[t{}+{}]", imlSegment->imlList[i].op_storeLoad.registerMem, imlSegment->imlList[i].op_storeLoad.immS32);
}
else if (imlSegment->imlList[i].type == PPCREC_IML_TYPE_MEM2MEM)
{
strOutput.addFmt("{} [t{}+{}] = [t{}+{}]", imlSegment->imlList[i].op_mem2mem.copyWidth, imlSegment->imlList[i].op_mem2mem.dst.registerMem, imlSegment->imlList[i].op_mem2mem.dst.immS32, imlSegment->imlList[i].op_mem2mem.src.registerMem, imlSegment->imlList[i].op_mem2mem.src.immS32);
}
else if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_CJUMP )
{
if (imlSegment->imlList[i].op_conditionalJump.condition == PPCREC_JUMP_CONDITION_E)
strOutput.add("JE");
else if (imlSegment->imlList[i].op_conditionalJump.condition == PPCREC_JUMP_CONDITION_NE)
strOutput.add("JNE");
else if (imlSegment->imlList[i].op_conditionalJump.condition == PPCREC_JUMP_CONDITION_G)
strOutput.add("JG");
else if (imlSegment->imlList[i].op_conditionalJump.condition == PPCREC_JUMP_CONDITION_GE)
strOutput.add("JGE");
else if (imlSegment->imlList[i].op_conditionalJump.condition == PPCREC_JUMP_CONDITION_L)
strOutput.add("JL");
else if (imlSegment->imlList[i].op_conditionalJump.condition == PPCREC_JUMP_CONDITION_LE)
strOutput.add("JLE");
else if (imlSegment->imlList[i].op_conditionalJump.condition == PPCREC_JUMP_CONDITION_NONE)
strOutput.add("JALW"); // jump always
else
cemu_assert_unimplemented();
strOutput.addFmt(" jm_{:08x} (cr{})", imlSegment->imlList[i].op_conditionalJump.jumpmarkAddress, imlSegment->imlList[i].crRegister);
}
else if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_NO_OP )
{
strOutput.add("NOP");
}
else if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_MACRO )
{
if( imlSegment->imlList[i].operation == PPCREC_IML_MACRO_BLR )
{
strOutput.addFmt("MACRO BLR 0x{:08x} cycles (depr): {}", imlSegment->imlList[i].op_macro.param, (sint32)imlSegment->imlList[i].op_macro.paramU16);
}
else if( imlSegment->imlList[i].operation == PPCREC_IML_MACRO_BLRL )
{
strOutput.addFmt("MACRO BLRL 0x{:08x} cycles (depr): {}", imlSegment->imlList[i].op_macro.param, (sint32)imlSegment->imlList[i].op_macro.paramU16);
}
else if( imlSegment->imlList[i].operation == PPCREC_IML_MACRO_BCTR )
{
strOutput.addFmt("MACRO BCTR 0x{:08x} cycles (depr): {}", imlSegment->imlList[i].op_macro.param, (sint32)imlSegment->imlList[i].op_macro.paramU16);
}
else if( imlSegment->imlList[i].operation == PPCREC_IML_MACRO_BCTRL )
{
strOutput.addFmt("MACRO BCTRL 0x{:08x} cycles (depr): {}", imlSegment->imlList[i].op_macro.param, (sint32)imlSegment->imlList[i].op_macro.paramU16);
}
else if( imlSegment->imlList[i].operation == PPCREC_IML_MACRO_BL )
{
strOutput.addFmt("MACRO BL 0x{:08x} -> 0x{:08x} cycles (depr): {}", imlSegment->imlList[i].op_macro.param, imlSegment->imlList[i].op_macro.param2, (sint32)imlSegment->imlList[i].op_macro.paramU16);
}
else if( imlSegment->imlList[i].operation == PPCREC_IML_MACRO_B_FAR )
{
strOutput.addFmt("MACRO B_FAR 0x{:08x} -> 0x{:08x} cycles (depr): {}", imlSegment->imlList[i].op_macro.param, imlSegment->imlList[i].op_macro.param2, (sint32)imlSegment->imlList[i].op_macro.paramU16);
}
else if( imlSegment->imlList[i].operation == PPCREC_IML_MACRO_LEAVE )
{
strOutput.addFmt("MACRO LEAVE ppc: 0x{:08x}", imlSegment->imlList[i].op_macro.param);
}
else if( imlSegment->imlList[i].operation == PPCREC_IML_MACRO_HLE )
{
strOutput.addFmt("MACRO HLE ppcAddr: 0x{:08x} funcId: 0x{:08x}", imlSegment->imlList[i].op_macro.param, imlSegment->imlList[i].op_macro.param2);
}
else if( imlSegment->imlList[i].operation == PPCREC_IML_MACRO_MFTB )
{
strOutput.addFmt("MACRO MFTB ppcAddr: 0x{:08x} sprId: 0x{:08x}", imlSegment->imlList[i].op_macro.param, imlSegment->imlList[i].op_macro.param2);
}
else if( imlSegment->imlList[i].operation == PPCREC_IML_MACRO_COUNT_CYCLES )
{
strOutput.addFmt("MACRO COUNT_CYCLES cycles: {}", imlSegment->imlList[i].op_macro.param);
}
else
{
strOutput.addFmt("MACRO ukn operation {}", imlSegment->imlList[i].operation);
}
}
else if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_FPR_R_NAME )
{
strOutput.addFmt("fpr_t{} = name_{} (", imlSegment->imlList[i].op_r_name.registerIndex, imlSegment->imlList[i].op_r_name.name);
if( imlSegment->imlList[i].op_r_name.name >= PPCREC_NAME_FPR0 && imlSegment->imlList[i].op_r_name.name < (PPCREC_NAME_FPR0+999) )
{
strOutput.addFmt("fpr{}", imlSegment->imlList[i].op_r_name.name-PPCREC_NAME_FPR0);
}
else if( imlSegment->imlList[i].op_r_name.name >= PPCREC_NAME_TEMPORARY_FPR0 && imlSegment->imlList[i].op_r_name.name < (PPCREC_NAME_TEMPORARY_FPR0+999) )
{
strOutput.addFmt("tempFpr{}", imlSegment->imlList[i].op_r_name.name-PPCREC_NAME_TEMPORARY_FPR0);
}
else
strOutput.add("ukn");
strOutput.add(")");
}
else if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_FPR_NAME_R )
{
strOutput.addFmt("name_{} (", imlSegment->imlList[i].op_r_name.name);
if( imlSegment->imlList[i].op_r_name.name >= PPCREC_NAME_FPR0 && imlSegment->imlList[i].op_r_name.name < (PPCREC_NAME_FPR0+999) )
{
strOutput.addFmt("fpr{}", imlSegment->imlList[i].op_r_name.name-PPCREC_NAME_FPR0);
}
else if( imlSegment->imlList[i].op_r_name.name >= PPCREC_NAME_TEMPORARY_FPR0 && imlSegment->imlList[i].op_r_name.name < (PPCREC_NAME_TEMPORARY_FPR0+999) )
{
strOutput.addFmt("tempFpr{}", imlSegment->imlList[i].op_r_name.name-PPCREC_NAME_TEMPORARY_FPR0);
}
else
strOutput.add("ukn");
strOutput.addFmt(") = fpr_t{}", imlSegment->imlList[i].op_r_name.registerIndex);
}
else if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_FPR_LOAD )
{
strOutput.addFmt("fpr_t{} = ", imlSegment->imlList[i].op_storeLoad.registerData);
if( imlSegment->imlList[i].op_storeLoad.flags2.signExtend )
strOutput.add("S");
else
strOutput.add("U");
strOutput.addFmt("{} [t{}+{}] mode {}", imlSegment->imlList[i].op_storeLoad.copyWidth / 8, imlSegment->imlList[i].op_storeLoad.registerMem, imlSegment->imlList[i].op_storeLoad.immS32, imlSegment->imlList[i].op_storeLoad.mode);
if (imlSegment->imlList[i].op_storeLoad.flags2.notExpanded)
{
strOutput.addFmt(" <No expand>");
}
}
else if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_FPR_STORE )
{
if( imlSegment->imlList[i].op_storeLoad.flags2.signExtend )
strOutput.add("S");
else
strOutput.add("U");
strOutput.addFmt("{} [t{}+{}]", imlSegment->imlList[i].op_storeLoad.copyWidth/8, imlSegment->imlList[i].op_storeLoad.registerMem, imlSegment->imlList[i].op_storeLoad.immS32);
strOutput.addFmt("= fpr_t{} mode {}\n", imlSegment->imlList[i].op_storeLoad.registerData, imlSegment->imlList[i].op_storeLoad.mode);
}
else if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_FPR_R_R )
{
strOutput.addFmt("{:-6} ", PPCRecompiler_getOpcodeDebugName(&imlSegment->imlList[i]));
strOutput.addFmt("fpr{:02d}, fpr{:02d}", imlSegment->imlList[i].op_fpr_r_r.registerResult, imlSegment->imlList[i].op_fpr_r_r.registerOperand);
}
else if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_FPR_R_R_R_R )
{
strOutput.addFmt("{:-6} ", PPCRecompiler_getOpcodeDebugName(&imlSegment->imlList[i]));
strOutput.addFmt("fpr{:02d}, fpr{:02d}, fpr{:02d}, fpr{:02d}", imlSegment->imlList[i].op_fpr_r_r_r_r.registerResult, imlSegment->imlList[i].op_fpr_r_r_r_r.registerOperandA, imlSegment->imlList[i].op_fpr_r_r_r_r.registerOperandB, imlSegment->imlList[i].op_fpr_r_r_r_r.registerOperandC);
}
else if( imlSegment->imlList[i].type == PPCREC_IML_TYPE_FPR_R_R_R )
{
strOutput.addFmt("{:-6} ", PPCRecompiler_getOpcodeDebugName(&imlSegment->imlList[i]));
strOutput.addFmt("fpr{:02d}, fpr{:02d}, fpr{:02d}", imlSegment->imlList[i].op_fpr_r_r_r.registerResult, imlSegment->imlList[i].op_fpr_r_r_r.registerOperandA, imlSegment->imlList[i].op_fpr_r_r_r.registerOperandB);
}
else if (imlSegment->imlList[i].type == PPCREC_IML_TYPE_CJUMP_CYCLE_CHECK)
{
strOutput.addFmt("CYCLE_CHECK jm_{:08x}\n", imlSegment->imlList[i].op_conditionalJump.jumpmarkAddress);
}
else if (imlSegment->imlList[i].type == PPCREC_IML_TYPE_CONDITIONAL_R_S32)
{
strOutput.addFmt("t{} ", imlSegment->imlList[i].op_conditional_r_s32.registerIndex);
bool displayAsHex = false;
if (imlSegment->imlList[i].operation == PPCREC_IML_OP_ASSIGN)
{
displayAsHex = true;
strOutput.add("=");
}
else
strOutput.addFmt("(unknown operation CONDITIONAL_R_S32 {})", imlSegment->imlList[i].operation);
if (displayAsHex)
strOutput.addFmt(" 0x{:x}", imlSegment->imlList[i].op_conditional_r_s32.immS32);
else
strOutput.addFmt(" {}", imlSegment->imlList[i].op_conditional_r_s32.immS32);
strOutput.add(" (conditional)");
if (imlSegment->imlList[i].crRegister != PPC_REC_INVALID_REGISTER)
{
strOutput.addFmt(" -> and update CR{}", imlSegment->imlList[i].crRegister);
}
}
else
{
strOutput.addFmt("Unknown iml type {}", imlSegment->imlList[i].type);
}
debug_printf("%s", strOutput.c_str());
if (printLivenessRangeInfo)
{
PPCRecompilerDebug_printLivenessRangeInfo(strOutput, imlSegment, i);
}
debug_printf("\n");
}
// all ranges
if (printLivenessRangeInfo)
{
debug_printf("Ranges-VirtReg ");
raLivenessSubrange_t* subrangeItr = imlSegment->raInfo.linkedList_allSubranges;
while(subrangeItr)
{
debug_printf("v%-2d", subrangeItr->range->virtualRegister);
subrangeItr = subrangeItr->link_segmentSubrangesGPR.next;
}
debug_printf("\n");
debug_printf("Ranges-PhysReg ");
subrangeItr = imlSegment->raInfo.linkedList_allSubranges;
while (subrangeItr)
{
debug_printf("p%-2d", subrangeItr->range->physicalRegister);
subrangeItr = subrangeItr->link_segmentSubrangesGPR.next;
}
debug_printf("\n");
}
// branch info
debug_printf("Links from: ");
for (sint32 i = 0; i < imlSegment->list_prevSegments.size(); i++)
{
if (i)
debug_printf(", ");
debug_printf("%p", (void*)imlSegment->list_prevSegments[i]);
}
debug_printf("\n");
debug_printf("Links to: ");
if (imlSegment->nextSegmentBranchNotTaken)
debug_printf("%p (no branch), ", (void*)imlSegment->nextSegmentBranchNotTaken);
if (imlSegment->nextSegmentBranchTaken)
debug_printf("%p (branch)", (void*)imlSegment->nextSegmentBranchTaken);
debug_printf("\n");
}
void PPCRecompiler_dumpIML(PPCRecFunction_t* PPCRecFunction, ppcImlGenContext_t* ppcImlGenContext)
{
for(sint32 f=0; f<ppcImlGenContext->segmentListCount; f++)
{
PPCRecImlSegment_t* imlSegment = ppcImlGenContext->segmentList[f];
PPCRecompiler_dumpIMLSegment(imlSegment, f);
debug_printf("\n");
}
}
void PPCRecompilerIml_setSegmentPoint(ppcRecompilerSegmentPoint_t* segmentPoint, PPCRecImlSegment_t* imlSegment, sint32 index)
{
segmentPoint->imlSegment = imlSegment;
segmentPoint->index = index;
if (imlSegment->segmentPointList)
imlSegment->segmentPointList->prev = segmentPoint;
segmentPoint->prev = nullptr;
segmentPoint->next = imlSegment->segmentPointList;
imlSegment->segmentPointList = segmentPoint;
}
void PPCRecompilerIml_removeSegmentPoint(ppcRecompilerSegmentPoint_t* segmentPoint)
{
if (segmentPoint->prev)
segmentPoint->prev->next = segmentPoint->next;
else
segmentPoint->imlSegment->segmentPointList = segmentPoint->next;
if (segmentPoint->next)
segmentPoint->next->prev = segmentPoint->prev;
}
/*
* Insert multiple no-op instructions
* Warning: Can invalidate any previous instruction structs from the same segment
*/
void PPCRecompiler_pushBackIMLInstructions(PPCRecImlSegment_t* imlSegment, sint32 index, sint32 shiftBackCount)
{
cemu_assert(index >= 0 && index <= imlSegment->imlListCount);
if (imlSegment->imlListCount + shiftBackCount > imlSegment->imlListSize)
{
sint32 newSize = imlSegment->imlListCount + shiftBackCount + std::max(2, imlSegment->imlListSize/2);
imlSegment->imlList = (PPCRecImlInstruction_t*)realloc(imlSegment->imlList, sizeof(PPCRecImlInstruction_t)*newSize);
imlSegment->imlListSize = newSize;
}
for (sint32 i = (sint32)imlSegment->imlListCount - 1; i >= index; i--)
{
memcpy(imlSegment->imlList + (i + shiftBackCount), imlSegment->imlList + i, sizeof(PPCRecImlInstruction_t));
}
// fill empty space with NOP instructions
for (sint32 i = 0; i < shiftBackCount; i++)
{
imlSegment->imlList[index + i].type = PPCREC_IML_TYPE_NONE;
}
imlSegment->imlListCount += shiftBackCount;
if (imlSegment->segmentPointList)
{
ppcRecompilerSegmentPoint_t* segmentPoint = imlSegment->segmentPointList;
while (segmentPoint)
{
if (segmentPoint->index != RA_INTER_RANGE_START && segmentPoint->index != RA_INTER_RANGE_END)
{
if (segmentPoint->index >= index)
segmentPoint->index += shiftBackCount;
}
// next
segmentPoint = segmentPoint->next;
}
}
}
/*
* Insert and return new instruction at index
* Warning: Can invalidate any previous instruction structs from the same segment
*/
PPCRecImlInstruction_t* PPCRecompiler_insertInstruction(PPCRecImlSegment_t* imlSegment, sint32 index)
{
PPCRecompiler_pushBackIMLInstructions(imlSegment, index, 1);
return imlSegment->imlList + index;
}
/*
* Append and return new instruction at the end of the segment
* Warning: Can invalidate any previous instruction structs from the same segment
*/
PPCRecImlInstruction_t* PPCRecompiler_appendInstruction(PPCRecImlSegment_t* imlSegment)
{
sint32 index = imlSegment->imlListCount;
if (index >= imlSegment->imlListSize)
{
sint32 newSize = index+1;
imlSegment->imlList = (PPCRecImlInstruction_t*)realloc(imlSegment->imlList, sizeof(PPCRecImlInstruction_t)*newSize);
imlSegment->imlListSize = newSize;
}
imlSegment->imlListCount++;
memset(imlSegment->imlList + index, 0, sizeof(PPCRecImlInstruction_t));
return imlSegment->imlList + index;
}
void PPCRecompilerIml_insertSegments(ppcImlGenContext_t* ppcImlGenContext, sint32 index, sint32 count)
{
if( (ppcImlGenContext->segmentListCount+count) > ppcImlGenContext->segmentListSize )
{
// allocate space for more segments
ppcImlGenContext->segmentListSize += count;
ppcImlGenContext->segmentList = (PPCRecImlSegment_t**)realloc(ppcImlGenContext->segmentList, ppcImlGenContext->segmentListSize*sizeof(PPCRecImlSegment_t*));
}
for(sint32 i=(sint32)ppcImlGenContext->segmentListCount-1; i>=index; i--)
{
memcpy(ppcImlGenContext->segmentList+(i+count), ppcImlGenContext->segmentList+i, sizeof(PPCRecImlSegment_t*));
}
ppcImlGenContext->segmentListCount += count;
for(sint32 i=0; i<count; i++)
{
//memset(ppcImlGenContext->segmentList+index+i, 0x00, sizeof(PPCRecImlSegment_t*));
ppcImlGenContext->segmentList[index+i] = (PPCRecImlSegment_t*)malloc(sizeof(PPCRecImlSegment_t));
memset(ppcImlGenContext->segmentList[index+i], 0x00, sizeof(PPCRecImlSegment_t));
ppcImlGenContext->segmentList[index + i]->list_prevSegments = std::vector<PPCRecImlSegment_t*>();
}
}
/*
* Allocate and init a new iml instruction segment
*/
PPCRecImlSegment_t* PPCRecompiler_generateImlSegment(ppcImlGenContext_t* ppcImlGenContext)
{
if( ppcImlGenContext->segmentListCount >= ppcImlGenContext->segmentListSize )
{
// allocate space for more segments
ppcImlGenContext->segmentListSize *= 2;
ppcImlGenContext->segmentList = (PPCRecImlSegment_t**)realloc(ppcImlGenContext->segmentList, ppcImlGenContext->segmentListSize*sizeof(PPCRecImlSegment_t*));
}
PPCRecImlSegment_t* ppcRecSegment = new PPCRecImlSegment_t();
ppcImlGenContext->segmentList[ppcImlGenContext->segmentListCount] = ppcRecSegment;
ppcImlGenContext->segmentListCount++;
return ppcRecSegment;
}
void PPCRecompiler_freeContext(ppcImlGenContext_t* ppcImlGenContext)
{
if (ppcImlGenContext->imlList)
{
free(ppcImlGenContext->imlList);
ppcImlGenContext->imlList = nullptr;
}
for(sint32 i=0; i<ppcImlGenContext->segmentListCount; i++)
{
free(ppcImlGenContext->segmentList[i]->imlList);
delete ppcImlGenContext->segmentList[i];
}
ppcImlGenContext->segmentListCount = 0;
if (ppcImlGenContext->segmentList)
{
free(ppcImlGenContext->segmentList);
ppcImlGenContext->segmentList = nullptr;
}
}
bool PPCRecompiler_isSuffixInstruction(PPCRecImlInstruction_t* iml)
{
if (iml->type == PPCREC_IML_TYPE_MACRO && (iml->operation == PPCREC_IML_MACRO_BLR || iml->operation == PPCREC_IML_MACRO_BCTR) ||
iml->type == PPCREC_IML_TYPE_MACRO && iml->operation == PPCREC_IML_MACRO_BL ||
iml->type == PPCREC_IML_TYPE_MACRO && iml->operation == PPCREC_IML_MACRO_B_FAR ||
iml->type == PPCREC_IML_TYPE_MACRO && iml->operation == PPCREC_IML_MACRO_BLRL ||
iml->type == PPCREC_IML_TYPE_MACRO && iml->operation == PPCREC_IML_MACRO_BCTRL ||
iml->type == PPCREC_IML_TYPE_MACRO && iml->operation == PPCREC_IML_MACRO_LEAVE ||
iml->type == PPCREC_IML_TYPE_MACRO && iml->operation == PPCREC_IML_MACRO_HLE ||
iml->type == PPCREC_IML_TYPE_MACRO && iml->operation == PPCREC_IML_MACRO_MFTB ||
iml->type == PPCREC_IML_TYPE_PPC_ENTER ||
iml->type == PPCREC_IML_TYPE_CJUMP ||
iml->type == PPCREC_IML_TYPE_CJUMP_CYCLE_CHECK)
return true;
return false;
}
bool PPCRecompiler_decodePPCInstruction(ppcImlGenContext_t* ppcImlGenContext)
{
bool unsupportedInstructionFound = false;
uint32 opcode = PPCRecompiler_iterateCurrentInstruction(ppcImlGenContext);
switch ((opcode >> 26))
{
case 1:
if (PPCRecompilerImlGen_HLE(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 4: // opcode category - paired single
switch (PPC_getBits(opcode, 30, 5))
{
case 0: // subcategory compare
switch (PPC_getBits(opcode, 25, 5))
{
case 0:
PPCRecompilerImlGen_PS_CMPU0(ppcImlGenContext, opcode);
ppcImlGenContext->hasFPUInstruction = true;
break;
case 1:
PPCRecompilerImlGen_PS_CMPO0(ppcImlGenContext, opcode);
ppcImlGenContext->hasFPUInstruction = true;
break;
case 2:
PPCRecompilerImlGen_PS_CMPU1(ppcImlGenContext, opcode);
ppcImlGenContext->hasFPUInstruction = true;
break;
default:
unsupportedInstructionFound = true;
break;
}
break;
case 8: //Sub category - move/negate
switch (PPC_getBits(opcode, 25, 5))
{
case 1: // PS negate
if (PPCRecompilerImlGen_PS_NEG(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 2: // PS move register
if (PPCRecompilerImlGen_PS_MR(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 8: // PS abs
if (PPCRecompilerImlGen_PS_ABS(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
default:
unsupportedInstructionFound = true;
break;
}
break;
case 10:
if (PPCRecompilerImlGen_PS_SUM0(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 11:
if (PPCRecompilerImlGen_PS_SUM1(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 12: // multiply scalar
if (PPCRecompilerImlGen_PS_MULS0(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 13: // multiply scalar
if (PPCRecompilerImlGen_PS_MULS1(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 14: // multiply add scalar
if (PPCRecompilerImlGen_PS_MADDS0(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 15: // multiply add scalar
if (PPCRecompilerImlGen_PS_MADDS1(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 16: // sub category - merge
switch (PPC_getBits(opcode, 25, 5))
{
case 16:
if (PPCRecompilerImlGen_PS_MERGE00(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 17:
if (PPCRecompilerImlGen_PS_MERGE01(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 18:
if (PPCRecompilerImlGen_PS_MERGE10(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 19:
if (PPCRecompilerImlGen_PS_MERGE11(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
default:
unsupportedInstructionFound = true;
break;
}
break;
case 18: // divide paired
if (PPCRecompilerImlGen_PS_DIV(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 20: // sub paired
if (PPCRecompilerImlGen_PS_SUB(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 21: // add paired
if (PPCRecompilerImlGen_PS_ADD(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 23: // select paired
if (PPCRecompilerImlGen_PS_SEL(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 25: // multiply paired
if (PPCRecompilerImlGen_PS_MUL(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 24: // reciprocal paired
if (PPCRecompilerImlGen_PS_RES(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 26: // reciprocal squareroot paired
if (PPCRecompilerImlGen_PS_RSQRTE(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 28: // multiply sub paired
if (PPCRecompilerImlGen_PS_MSUB(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 29: // multiply add paired
if (PPCRecompilerImlGen_PS_MADD(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 30: // negative multiply sub paired
if (PPCRecompilerImlGen_PS_NMSUB(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 31: // negative multiply add paired
if (PPCRecompilerImlGen_PS_NMADD(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
default:
unsupportedInstructionFound = true;
break;
}
break;
case 7: // MULLI
PPCRecompilerImlGen_MULLI(ppcImlGenContext, opcode);
break;
case 8: // SUBFIC
PPCRecompilerImlGen_SUBFIC(ppcImlGenContext, opcode);
break;
case 10: // CMPLI
PPCRecompilerImlGen_CMPLI(ppcImlGenContext, opcode);
break;
case 11: // CMPI
PPCRecompilerImlGen_CMPI(ppcImlGenContext, opcode);
break;
case 12: // ADDIC
if (PPCRecompilerImlGen_ADDIC(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 13: // ADDIC.
if (PPCRecompilerImlGen_ADDIC_(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 14: // ADDI
if (PPCRecompilerImlGen_ADDI(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 15: // ADDIS
if (PPCRecompilerImlGen_ADDIS(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 16: // BC
if (PPCRecompilerImlGen_BC(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 17:
if (PPC_getBits(opcode, 30, 1) == 1)
{
// SC -> no-op
}
else
{
unsupportedInstructionFound = true;
}
break;
case 18: // B
if (PPCRecompilerImlGen_B(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 19: // opcode category 19
switch (PPC_getBits(opcode, 30, 10))
{
case 16:
if (PPCRecompilerImlGen_BCLR(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 129:
if (PPCRecompilerImlGen_CRANDC(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 150:
if (PPCRecompilerImlGen_ISYNC(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 193:
if (PPCRecompilerImlGen_CRXOR(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 257:
if (PPCRecompilerImlGen_CRAND(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 289:
if (PPCRecompilerImlGen_CREQV(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 417:
if (PPCRecompilerImlGen_CRORC(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 449:
if (PPCRecompilerImlGen_CROR(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 528:
if (PPCRecompilerImlGen_BCCTR(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
default:
unsupportedInstructionFound = true;
break;
}
break;
case 20:
if (PPCRecompilerImlGen_RLWIMI(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 21:
if (PPCRecompilerImlGen_RLWINM(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 23:
if (PPCRecompilerImlGen_RLWNM(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 24:
PPCRecompilerImlGen_ORI(ppcImlGenContext, opcode);
break;
case 25:
PPCRecompilerImlGen_ORIS(ppcImlGenContext, opcode);
break;
case 26:
PPCRecompilerImlGen_XORI(ppcImlGenContext, opcode);
break;
case 27:
PPCRecompilerImlGen_XORIS(ppcImlGenContext, opcode);
break;
case 28:
PPCRecompilerImlGen_ANDI(ppcImlGenContext, opcode);
break;
case 29:
PPCRecompilerImlGen_ANDIS(ppcImlGenContext, opcode);
break;
case 31: // opcode category
switch (PPC_getBits(opcode, 30, 10))
{
case 0:
PPCRecompilerImlGen_CMP(ppcImlGenContext, opcode);
break;
case 4:
PPCRecompilerImlGen_TW(ppcImlGenContext, opcode);
break;
case 8:
// todo: Check if we can optimize this pattern:
// SUBFC + SUBFE
// SUBFC
if (PPCRecompilerImlGen_SUBFC(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 10:
if (PPCRecompilerImlGen_ADDC(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 11:
if (PPCRecompilerImlGen_MULHWU(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 19:
if (PPCRecompilerImlGen_MFCR(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 20:
if (PPCRecompilerImlGen_LWARX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 23:
if (PPCRecompilerImlGen_LWZX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 24:
if (PPCRecompilerImlGen_SLW(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 26:
if (PPCRecompilerImlGen_CNTLZW(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 28:
if (PPCRecompilerImlGen_AND(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 32:
PPCRecompilerImlGen_CMPL(ppcImlGenContext, opcode);
break;
case 40:
if (PPCRecompilerImlGen_SUBF(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 54:
// DBCST - Generates no code
break;
case 55:
if (PPCRecompilerImlGen_LWZUX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 60:
if (PPCRecompilerImlGen_ANDC(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 75:
if (PPCRecompilerImlGen_MULHW(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 86:
// DCBF -> No-Op
break;
case 87:
if (PPCRecompilerImlGen_LBZX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 104:
if (PPCRecompilerImlGen_NEG(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 119:
if (PPCRecompilerImlGen_LBZUX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 124:
if (PPCRecompilerImlGen_NOR(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 136:
if (PPCRecompilerImlGen_SUBFE(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 138:
if (PPCRecompilerImlGen_ADDE(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 144:
PPCRecompilerImlGen_MTCRF(ppcImlGenContext, opcode);
break;
case 150:
if (PPCRecompilerImlGen_STWCX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 151:
if (PPCRecompilerImlGen_STORE_INDEXED(ppcImlGenContext, opcode, 32) == false)
unsupportedInstructionFound = true;
break;
case 183:
if (PPCRecompilerImlGen_STORE_INDEXED_UPDATE(ppcImlGenContext, opcode, 32) == false)
unsupportedInstructionFound = true;
break;
case 200:
if (PPCRecompilerImlGen_SUBFZE(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 202:
if (PPCRecompilerImlGen_ADDZE(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 215:
if (PPCRecompilerImlGen_STORE_INDEXED(ppcImlGenContext, opcode, 8) == false)
unsupportedInstructionFound = true;
break;
case 234:
if (PPCRecompilerImlGen_ADDME(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 235:
if (PPCRecompilerImlGen_MULLW(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 247:
if (PPCRecompilerImlGen_STORE_INDEXED_UPDATE(ppcImlGenContext, opcode, 8) == false)
unsupportedInstructionFound = true;
break;
case 266:
if (PPCRecompilerImlGen_ADD(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 279:
if (PPCRecompilerImlGen_LHZX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 284:
PPCRecompilerImlGen_EQV(ppcImlGenContext, opcode);
break;
case 311:
if (PPCRecompilerImlGen_LHZUX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 316:
if (PPCRecompilerImlGen_XOR(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 339:
if (PPCRecompilerImlGen_MFSPR(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 343:
if (PPCRecompilerImlGen_LHAX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 371:
if (PPCRecompilerImlGen_MFTB(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 375:
if (PPCRecompilerImlGen_LHAUX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 407:
if (PPCRecompilerImlGen_STORE_INDEXED(ppcImlGenContext, opcode, 16) == false)
unsupportedInstructionFound = true;
break;
case 412:
if (PPCRecompilerImlGen_ORC(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 439:
if (PPCRecompilerImlGen_STORE_INDEXED_UPDATE(ppcImlGenContext, opcode, 16) == false)
unsupportedInstructionFound = true;
break;
case 444:
if (PPCRecompilerImlGen_OR(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 459:
PPCRecompilerImlGen_DIVWU(ppcImlGenContext, opcode);
break;
case 467:
if (PPCRecompilerImlGen_MTSPR(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 491:
if (PPCRecompilerImlGen_DIVW(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 534:
if (PPCRecompilerImlGen_LWBRX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 535:
if (PPCRecompilerImlGen_LFSX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 536:
if (PPCRecompilerImlGen_SRW(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 567:
if (PPCRecompilerImlGen_LFSUX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 597:
if (PPCRecompilerImlGen_LSWI(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 598:
PPCRecompilerImlGen_SYNC(ppcImlGenContext, opcode);
break;
case 599:
if (PPCRecompilerImlGen_LFDX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 631:
if (PPCRecompilerImlGen_LFDUX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 662:
if (PPCRecompilerImlGen_STWBRX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 663:
if (PPCRecompilerImlGen_STFSX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 695:
if (PPCRecompilerImlGen_STFSUX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 725:
if (PPCRecompilerImlGen_STSWI(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 727:
if (PPCRecompilerImlGen_STFDX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 790:
PPCRecompilerImlGen_LHBRX(ppcImlGenContext, opcode);
break;
case 792:
if (PPCRecompilerImlGen_SRAW(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 824:
if (PPCRecompilerImlGen_SRAWI(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 918: // STHBRX
if (PPCRecompilerImlGen_STORE_INDEXED(ppcImlGenContext, opcode, 16, true) == false)
unsupportedInstructionFound = true;
break;
case 922:
if (PPCRecompilerImlGen_EXTSH(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 954:
if (PPCRecompilerImlGen_EXTSB(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 983:
if (PPCRecompilerImlGen_STFIWX(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
case 1014:
if (PPCRecompilerImlGen_DCBZ(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
break;
default:
unsupportedInstructionFound = true;
break;
}
break;
case 32:
PPCRecompilerImlGen_LWZ(ppcImlGenContext, opcode);
break;
case 33:
PPCRecompilerImlGen_LWZU(ppcImlGenContext, opcode);
break;
case 34:
PPCRecompilerImlGen_LBZ(ppcImlGenContext, opcode);
break;
case 35:
PPCRecompilerImlGen_LBZU(ppcImlGenContext, opcode);
break;
case 36:
PPCRecompilerImlGen_STW(ppcImlGenContext, opcode);
break;
case 37:
PPCRecompilerImlGen_STWU(ppcImlGenContext, opcode);
break;
case 38:
PPCRecompilerImlGen_STB(ppcImlGenContext, opcode);
break;
case 39:
PPCRecompilerImlGen_STBU(ppcImlGenContext, opcode);
break;
case 40:
PPCRecompilerImlGen_LHZ(ppcImlGenContext, opcode);
break;
case 41:
PPCRecompilerImlGen_LHZU(ppcImlGenContext, opcode);
break;
case 42:
PPCRecompilerImlGen_LHA(ppcImlGenContext, opcode);
break;
case 43:
PPCRecompilerImlGen_LHAU(ppcImlGenContext, opcode);
break;
case 44:
PPCRecompilerImlGen_STH(ppcImlGenContext, opcode);
break;
case 45:
PPCRecompilerImlGen_STHU(ppcImlGenContext, opcode);
break;
case 46:
PPCRecompilerImlGen_LMW(ppcImlGenContext, opcode);
break;
case 47:
PPCRecompilerImlGen_STMW(ppcImlGenContext, opcode);
break;
case 48:
if (PPCRecompilerImlGen_LFS(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 49:
if (PPCRecompilerImlGen_LFSU(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 50:
if (PPCRecompilerImlGen_LFD(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 51:
if (PPCRecompilerImlGen_LFDU(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 52:
if (PPCRecompilerImlGen_STFS(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 53:
if (PPCRecompilerImlGen_STFSU(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 54:
if (PPCRecompilerImlGen_STFD(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 55:
if (PPCRecompilerImlGen_STFDU(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 56:
if (PPCRecompilerImlGen_PSQ_L(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 57:
if (PPCRecompilerImlGen_PSQ_LU(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 59: // opcode category
switch (PPC_getBits(opcode, 30, 5))
{
case 18:
if (PPCRecompilerImlGen_FDIVS(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 20:
if (PPCRecompilerImlGen_FSUBS(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 21:
if (PPCRecompilerImlGen_FADDS(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 24:
if (PPCRecompilerImlGen_FRES(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 25:
if (PPCRecompilerImlGen_FMULS(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 28:
if (PPCRecompilerImlGen_FMSUBS(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 29:
if (PPCRecompilerImlGen_FMADDS(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 30:
if (PPCRecompilerImlGen_FNMSUBS(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
default:
unsupportedInstructionFound = true;
break;
}
break;
case 60:
if (PPCRecompilerImlGen_PSQ_ST(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 61:
if (PPCRecompilerImlGen_PSQ_STU(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 63: // opcode category
switch (PPC_getBits(opcode, 30, 5))
{
case 0:
if (PPCRecompilerImlGen_FCMPU(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 12:
if (PPCRecompilerImlGen_FRSP(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 15:
if (PPCRecompilerImlGen_FCTIWZ(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 18:
if (PPCRecompilerImlGen_FDIV(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 20:
if (PPCRecompilerImlGen_FSUB(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 21:
if (PPCRecompilerImlGen_FADD(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 23:
if (PPCRecompilerImlGen_FSEL(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 25:
if (PPCRecompilerImlGen_FMUL(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 26:
if (PPCRecompilerImlGen_FRSQRTE(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 28:
if (PPCRecompilerImlGen_FMSUB(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 29:
if (PPCRecompilerImlGen_FMADD(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 30:
if (PPCRecompilerImlGen_FNMSUB(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
default:
switch (PPC_getBits(opcode, 30, 10))
{
case 32:
if (PPCRecompilerImlGen_FCMPO(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 40:
if (PPCRecompilerImlGen_FNEG(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 72:
if (PPCRecompilerImlGen_FMR(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 136:
if (PPCRecompilerImlGen_FNABS(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
case 264:
if (PPCRecompilerImlGen_FABS(ppcImlGenContext, opcode) == false)
unsupportedInstructionFound = true;
ppcImlGenContext->hasFPUInstruction = true;
break;
default:
unsupportedInstructionFound = true;
break;
}
break;
}
break;
default:
unsupportedInstructionFound = true;
break;
}
return unsupportedInstructionFound;
}
bool PPCRecompiler_generateIntermediateCode(ppcImlGenContext_t& ppcImlGenContext, PPCRecFunction_t* ppcRecFunc, std::set<uint32>& entryAddresses)
{
//ppcImlGenContext_t ppcImlGenContext = { 0 };
ppcImlGenContext.functionRef = ppcRecFunc;
// add entire range
ppcRecRange_t recRange;
recRange.ppcAddress = ppcRecFunc->ppcAddress;
recRange.ppcSize = ppcRecFunc->ppcSize;
ppcRecFunc->list_ranges.push_back(recRange);
// process ppc instructions
ppcImlGenContext.currentInstruction = (uint32*)memory_getPointerFromVirtualOffset(ppcRecFunc->ppcAddress);
bool unsupportedInstructionFound = false;
sint32 numPPCInstructions = ppcRecFunc->ppcSize/4;
sint32 unsupportedInstructionCount = 0;
uint32 unsupportedInstructionLastOffset = 0;
uint32* firstCurrentInstruction = ppcImlGenContext.currentInstruction;
uint32* endCurrentInstruction = ppcImlGenContext.currentInstruction + numPPCInstructions;
while(ppcImlGenContext.currentInstruction < endCurrentInstruction)
{
uint32 addressOfCurrentInstruction = (uint32)((uint8*)ppcImlGenContext.currentInstruction - memory_base);
ppcImlGenContext.ppcAddressOfCurrentInstruction = addressOfCurrentInstruction;
ppcImlGenContext.cyclesSinceLastBranch++;
PPCRecompilerImlGen_generateNewInstruction_jumpmark(&ppcImlGenContext, addressOfCurrentInstruction);
if (entryAddresses.find(addressOfCurrentInstruction) != entryAddresses.end())
{
// add PPCEnter for addresses that are in entryAddresses
PPCRecompilerImlGen_generateNewInstruction_ppcEnter(&ppcImlGenContext, addressOfCurrentInstruction);
}
else if(ppcImlGenContext.currentInstruction != firstCurrentInstruction)
{
// add PPCEnter mark if code is seemingly unreachable (for example if between two unconditional jump instructions without jump goal)
uint32 opcodeCurrent = PPCRecompiler_getCurrentInstruction(&ppcImlGenContext);
uint32 opcodePrevious = PPCRecompiler_getPreviousInstruction(&ppcImlGenContext);
if( ((opcodePrevious>>26) == 18) && ((opcodeCurrent>>26) == 18) )
{
// between two B(L) instructions
// todo: for BL only if they are not inlineable
bool canInlineFunction = false;
if ((opcodePrevious & PPC_OPC_LK) && (opcodePrevious & PPC_OPC_AA) == 0)
{
uint32 li;
PPC_OPC_TEMPL_I(opcodePrevious, li);
sint32 inlineSize = 0;
if (PPCRecompiler_canInlineFunction(li + addressOfCurrentInstruction - 4, &inlineSize))
canInlineFunction = true;
}
if( canInlineFunction == false && (opcodePrevious & PPC_OPC_LK) == false)
PPCRecompilerImlGen_generateNewInstruction_ppcEnter(&ppcImlGenContext, addressOfCurrentInstruction);
}
if( ((opcodePrevious>>26) == 19) && PPC_getBits(opcodePrevious, 30, 10) == 528 )
{
uint32 BO, BI, BD;
PPC_OPC_TEMPL_XL(opcodePrevious, BO, BI, BD);
if( (BO & 16) && (opcodePrevious&PPC_OPC_LK) == 0 )
{
// after unconditional BCTR instruction
PPCRecompilerImlGen_generateNewInstruction_ppcEnter(&ppcImlGenContext, addressOfCurrentInstruction);
}
}
}
unsupportedInstructionFound = PPCRecompiler_decodePPCInstruction(&ppcImlGenContext);
if( unsupportedInstructionFound )
{
unsupportedInstructionCount++;
unsupportedInstructionLastOffset = ppcImlGenContext.ppcAddressOfCurrentInstruction;
unsupportedInstructionFound = false;
//break;
}
}
ppcImlGenContext.ppcAddressOfCurrentInstruction = 0; // reset current instruction offset (any future generated IML instruction will be assigned to ppc address 0)
if( unsupportedInstructionCount > 0 || unsupportedInstructionFound )
{
// could not compile function
debug_printf("Failed recompile due to unknown instruction at 0x%08x\n", unsupportedInstructionLastOffset);
PPCRecompiler_freeContext(&ppcImlGenContext);
return false;
}
// optimize unused jumpmarks away
// first, flag all jumpmarks as unused
std::map<uint32, PPCRecImlInstruction_t*> map_jumpMarks;
for(sint32 i=0; i<ppcImlGenContext.imlListCount; i++)
{
if( ppcImlGenContext.imlList[i].type == PPCREC_IML_TYPE_JUMPMARK )
{
ppcImlGenContext.imlList[i].op_jumpmark.flags |= PPCREC_IML_OP_FLAG_UNUSED;
#ifdef CEMU_DEBUG_ASSERT
if (map_jumpMarks.find(ppcImlGenContext.imlList[i].op_jumpmark.address) != map_jumpMarks.end())
assert_dbg();
#endif
map_jumpMarks.emplace(ppcImlGenContext.imlList[i].op_jumpmark.address, ppcImlGenContext.imlList+i);
}
}
// second, unflag jumpmarks that have at least one reference
for(sint32 i=0; i<ppcImlGenContext.imlListCount; i++)
{
if( ppcImlGenContext.imlList[i].type == PPCREC_IML_TYPE_CJUMP )
{
uint32 jumpDest = ppcImlGenContext.imlList[i].op_conditionalJump.jumpmarkAddress;
auto jumpMarkIml = map_jumpMarks.find(jumpDest);
if (jumpMarkIml != map_jumpMarks.end())
jumpMarkIml->second->op_jumpmark.flags &= ~PPCREC_IML_OP_FLAG_UNUSED;
}
}
// lastly, remove jumpmarks that still have the unused flag set
sint32 currentImlIndex = 0;
for(sint32 i=0; i<ppcImlGenContext.imlListCount; i++)
{
if( ppcImlGenContext.imlList[i].type == PPCREC_IML_TYPE_JUMPMARK && (ppcImlGenContext.imlList[i].op_jumpmark.flags&PPCREC_IML_OP_FLAG_UNUSED) )
{
continue; // skip this instruction
}
// move back instruction
if( currentImlIndex < i )
{
memcpy(ppcImlGenContext.imlList+currentImlIndex, ppcImlGenContext.imlList+i, sizeof(PPCRecImlInstruction_t));
}
currentImlIndex++;
}
// fix intermediate instruction count
ppcImlGenContext.imlListCount = currentImlIndex;
// divide iml instructions into segments
// each segment is defined by one or more instructions with no branches or jump destinations in between
// a branch instruction may only be the very last instruction of a segment
ppcImlGenContext.segmentListCount = 0;
ppcImlGenContext.segmentListSize = 2;
ppcImlGenContext.segmentList = (PPCRecImlSegment_t**)malloc(ppcImlGenContext.segmentListSize*sizeof(PPCRecImlSegment_t*));
sint32 segmentStart = 0;
sint32 segmentImlIndex = 0;
while( segmentImlIndex < ppcImlGenContext.imlListCount )
{
bool genNewSegment = false;
// segment definition:
// If we encounter a branch instruction -> end of segment after current instruction
// If we encounter a jumpmark -> end of segment before current instruction
// If we encounter ppc_enter -> end of segment before current instruction
if( ppcImlGenContext.imlList[segmentImlIndex].type == PPCREC_IML_TYPE_CJUMP ||
(ppcImlGenContext.imlList[segmentImlIndex].type == PPCREC_IML_TYPE_MACRO && (ppcImlGenContext.imlList[segmentImlIndex].operation == PPCREC_IML_MACRO_BLR || ppcImlGenContext.imlList[segmentImlIndex].operation == PPCREC_IML_MACRO_BLRL || ppcImlGenContext.imlList[segmentImlIndex].operation == PPCREC_IML_MACRO_BCTR || ppcImlGenContext.imlList[segmentImlIndex].operation == PPCREC_IML_MACRO_BCTRL)) ||
(ppcImlGenContext.imlList[segmentImlIndex].type == PPCREC_IML_TYPE_MACRO && (ppcImlGenContext.imlList[segmentImlIndex].operation == PPCREC_IML_MACRO_BL)) ||
(ppcImlGenContext.imlList[segmentImlIndex].type == PPCREC_IML_TYPE_MACRO && (ppcImlGenContext.imlList[segmentImlIndex].operation == PPCREC_IML_MACRO_B_FAR)) ||
(ppcImlGenContext.imlList[segmentImlIndex].type == PPCREC_IML_TYPE_MACRO && (ppcImlGenContext.imlList[segmentImlIndex].operation == PPCREC_IML_MACRO_LEAVE)) ||
(ppcImlGenContext.imlList[segmentImlIndex].type == PPCREC_IML_TYPE_MACRO && (ppcImlGenContext.imlList[segmentImlIndex].operation == PPCREC_IML_MACRO_HLE)) ||
(ppcImlGenContext.imlList[segmentImlIndex].type == PPCREC_IML_TYPE_MACRO && (ppcImlGenContext.imlList[segmentImlIndex].operation == PPCREC_IML_MACRO_MFTB)) )
{
// segment ends after current instruction
PPCRecImlSegment_t* ppcRecSegment = PPCRecompiler_generateImlSegment(&ppcImlGenContext);
ppcRecSegment->startOffset = segmentStart;
ppcRecSegment->count = segmentImlIndex-segmentStart+1;
ppcRecSegment->ppcAddress = 0xFFFFFFFF;
segmentStart = segmentImlIndex+1;
}
else if( ppcImlGenContext.imlList[segmentImlIndex].type == PPCREC_IML_TYPE_JUMPMARK ||
ppcImlGenContext.imlList[segmentImlIndex].type == PPCREC_IML_TYPE_PPC_ENTER )
{
// segment ends before current instruction
if( segmentImlIndex > segmentStart )
{
PPCRecImlSegment_t* ppcRecSegment = PPCRecompiler_generateImlSegment(&ppcImlGenContext);
ppcRecSegment->startOffset = segmentStart;
ppcRecSegment->count = segmentImlIndex-segmentStart;
ppcRecSegment->ppcAddress = 0xFFFFFFFF;
segmentStart = segmentImlIndex;
}
}
segmentImlIndex++;
}
if( segmentImlIndex != segmentStart )
{
// final segment
PPCRecImlSegment_t* ppcRecSegment = PPCRecompiler_generateImlSegment(&ppcImlGenContext);
ppcRecSegment->startOffset = segmentStart;
ppcRecSegment->count = segmentImlIndex-segmentStart;
ppcRecSegment->ppcAddress = 0xFFFFFFFF;
segmentStart = segmentImlIndex;
}
// move iml instructions into the segments
for(sint32 s=0; s<ppcImlGenContext.segmentListCount; s++)
{
uint32 imlStartIndex = ppcImlGenContext.segmentList[s]->startOffset;
uint32 imlCount = ppcImlGenContext.segmentList[s]->count;
if( imlCount > 0 )
{
ppcImlGenContext.segmentList[s]->imlListSize = imlCount + 4;
ppcImlGenContext.segmentList[s]->imlList = (PPCRecImlInstruction_t*)malloc(sizeof(PPCRecImlInstruction_t)*ppcImlGenContext.segmentList[s]->imlListSize);
ppcImlGenContext.segmentList[s]->imlListCount = imlCount;
memcpy(ppcImlGenContext.segmentList[s]->imlList, ppcImlGenContext.imlList+imlStartIndex, sizeof(PPCRecImlInstruction_t)*imlCount);
}
else
{
// empty segments are allowed so we can handle multiple PPC entry addresses pointing to the same code
ppcImlGenContext.segmentList[s]->imlList = NULL;
ppcImlGenContext.segmentList[s]->imlListSize = 0;
ppcImlGenContext.segmentList[s]->imlListCount = 0;
}
ppcImlGenContext.segmentList[s]->startOffset = 9999999;
ppcImlGenContext.segmentList[s]->count = 9999999;
}
// clear segment-independent iml list
free(ppcImlGenContext.imlList);
ppcImlGenContext.imlList = NULL;
ppcImlGenContext.imlListCount = 999999; // set to high number to force crash in case old code still uses ppcImlGenContext.imlList
// calculate PPC address of each segment based on iml instructions inside that segment (we need this info to calculate how many cpu cycles each segment takes)
for(sint32 s=0; s<ppcImlGenContext.segmentListCount; s++)
{
uint32 segmentPPCAddrMin = 0xFFFFFFFF;
uint32 segmentPPCAddrMax = 0x00000000;
for(sint32 i=0; i<ppcImlGenContext.segmentList[s]->imlListCount; i++)
{
if( ppcImlGenContext.segmentList[s]->imlList[i].associatedPPCAddress == 0 )
continue;
//if( ppcImlGenContext.segmentList[s]->imlList[i].type == PPCREC_IML_TYPE_JUMPMARK || ppcImlGenContext.segmentList[s]->imlList[i].type == PPCREC_IML_TYPE_NO_OP )
// continue; // jumpmarks and no-op instructions must not affect segment ppc address range
segmentPPCAddrMin = std::min(ppcImlGenContext.segmentList[s]->imlList[i].associatedPPCAddress, segmentPPCAddrMin);
segmentPPCAddrMax = std::max(ppcImlGenContext.segmentList[s]->imlList[i].associatedPPCAddress, segmentPPCAddrMax);
}
if( segmentPPCAddrMin != 0xFFFFFFFF )
{
ppcImlGenContext.segmentList[s]->ppcAddrMin = segmentPPCAddrMin;
ppcImlGenContext.segmentList[s]->ppcAddrMax = segmentPPCAddrMax;
}
else
{
ppcImlGenContext.segmentList[s]->ppcAddrMin = 0;
ppcImlGenContext.segmentList[s]->ppcAddrMax = 0;
}
}
// certain instructions can change the segment state
// ppcEnter instruction marks a segment as enterable (BL, BCTR, etc. instructions can enter at this location from outside)
// jumpmarks mark the segment as a jump destination (within the same function)
for(sint32 s=0; s<ppcImlGenContext.segmentListCount; s++)
{
while( ppcImlGenContext.segmentList[s]->imlListCount > 0 )
{
if( ppcImlGenContext.segmentList[s]->imlList[0].type == PPCREC_IML_TYPE_PPC_ENTER )
{
// mark segment as enterable
if( ppcImlGenContext.segmentList[s]->isEnterable )
assert_dbg(); // should not happen?
ppcImlGenContext.segmentList[s]->isEnterable = true;
ppcImlGenContext.segmentList[s]->enterPPCAddress = ppcImlGenContext.segmentList[s]->imlList[0].op_ppcEnter.ppcAddress;
// remove ppc_enter instruction
ppcImlGenContext.segmentList[s]->imlList[0].type = PPCREC_IML_TYPE_NO_OP;
ppcImlGenContext.segmentList[s]->imlList[0].crRegister = PPC_REC_INVALID_REGISTER;
ppcImlGenContext.segmentList[s]->imlList[0].associatedPPCAddress = 0;
}
else if( ppcImlGenContext.segmentList[s]->imlList[0].type == PPCREC_IML_TYPE_JUMPMARK )
{
// mark segment as jump destination
if( ppcImlGenContext.segmentList[s]->isJumpDestination )
assert_dbg(); // should not happen?
ppcImlGenContext.segmentList[s]->isJumpDestination = true;
ppcImlGenContext.segmentList[s]->jumpDestinationPPCAddress = ppcImlGenContext.segmentList[s]->imlList[0].op_jumpmark.address;
// remove jumpmark instruction
ppcImlGenContext.segmentList[s]->imlList[0].type = PPCREC_IML_TYPE_NO_OP;
ppcImlGenContext.segmentList[s]->imlList[0].crRegister = PPC_REC_INVALID_REGISTER;
ppcImlGenContext.segmentList[s]->imlList[0].associatedPPCAddress = 0;
}
else
break;
}
}
// the first segment is always enterable as the recompiled functions entrypoint
ppcImlGenContext.segmentList[0]->isEnterable = true;
ppcImlGenContext.segmentList[0]->enterPPCAddress = ppcImlGenContext.functionRef->ppcAddress;
// link segments for further inter-segment optimization
PPCRecompilerIML_linkSegments(&ppcImlGenContext);
// optimization pass - replace segments with conditional MOVs if possible
for (sint32 s = 0; s < ppcImlGenContext.segmentListCount; s++)
{
PPCRecImlSegment_t* imlSegment = ppcImlGenContext.segmentList[s];
if (imlSegment->nextSegmentBranchNotTaken == NULL || imlSegment->nextSegmentBranchTaken == NULL)
continue; // not a branching segment
PPCRecImlInstruction_t* lastInstruction = PPCRecompilerIML_getLastInstruction(imlSegment);
if (lastInstruction->type != PPCREC_IML_TYPE_CJUMP || lastInstruction->op_conditionalJump.crRegisterIndex != 0)
continue;
PPCRecImlSegment_t* conditionalSegment = imlSegment->nextSegmentBranchNotTaken;
PPCRecImlSegment_t* finalSegment = imlSegment->nextSegmentBranchTaken;
if(imlSegment->nextSegmentBranchTaken != imlSegment->nextSegmentBranchNotTaken->nextSegmentBranchNotTaken)
continue;
if (imlSegment->nextSegmentBranchNotTaken->imlListCount > 4)
continue;
if(conditionalSegment->list_prevSegments.size() != 1)
continue; // the reduced segment must not be the target of any other branch
if(conditionalSegment->isEnterable)
continue;
// check if the segment contains only iml instructions that can be turned into conditional moves (Value assignment, register assignment)
bool canReduceSegment = true;
for (sint32 f = 0; f < conditionalSegment->imlListCount; f++)
{
PPCRecImlInstruction_t* imlInstruction = conditionalSegment->imlList+f;
if( imlInstruction->type == PPCREC_IML_TYPE_R_S32 && imlInstruction->operation == PPCREC_IML_OP_ASSIGN)
continue;
// todo: Register to register copy
canReduceSegment = false;
break;
}
if( canReduceSegment == false )
continue;
// remove the branch instruction
uint8 branchCond_crRegisterIndex = lastInstruction->op_conditionalJump.crRegisterIndex;
uint8 branchCond_crBitIndex = lastInstruction->op_conditionalJump.crBitIndex;
bool branchCond_bitMustBeSet = lastInstruction->op_conditionalJump.bitMustBeSet;
PPCRecompilerImlGen_generateNewInstruction_noOp(&ppcImlGenContext, lastInstruction);
// append conditional moves based on branch condition
for (sint32 f = 0; f < conditionalSegment->imlListCount; f++)
{
PPCRecImlInstruction_t* imlInstruction = conditionalSegment->imlList + f;
if (imlInstruction->type == PPCREC_IML_TYPE_R_S32 && imlInstruction->operation == PPCREC_IML_OP_ASSIGN)
PPCRecompilerImlGen_generateNewInstruction_conditional_r_s32(&ppcImlGenContext, PPCRecompiler_appendInstruction(imlSegment), PPCREC_IML_OP_ASSIGN, imlInstruction->op_r_immS32.registerIndex, imlInstruction->op_r_immS32.immS32, branchCond_crRegisterIndex, branchCond_crBitIndex, !branchCond_bitMustBeSet);
else
assert_dbg();
}
// update segment links
// source segment: imlSegment, conditional/removed segment: conditionalSegment, final segment: finalSegment
PPCRecompilerIML_removeLink(imlSegment, conditionalSegment);
PPCRecompilerIML_removeLink(imlSegment, finalSegment);
PPCRecompilerIML_removeLink(conditionalSegment, finalSegment);
PPCRecompilerIml_setLinkBranchNotTaken(imlSegment, finalSegment);
// remove all instructions from conditional segment
conditionalSegment->imlListCount = 0;
// if possible, merge imlSegment with finalSegment
if (finalSegment->isEnterable == false && finalSegment->list_prevSegments.size() == 1)
{
// todo: Clean this up and move into separate function PPCRecompilerIML_mergeSegments()
PPCRecompilerIML_removeLink(imlSegment, finalSegment);
if (finalSegment->nextSegmentBranchNotTaken)
{
PPCRecImlSegment_t* tempSegment = finalSegment->nextSegmentBranchNotTaken;
PPCRecompilerIML_removeLink(finalSegment, tempSegment);
PPCRecompilerIml_setLinkBranchNotTaken(imlSegment, tempSegment);
}
if (finalSegment->nextSegmentBranchTaken)
{
PPCRecImlSegment_t* tempSegment = finalSegment->nextSegmentBranchTaken;
PPCRecompilerIML_removeLink(finalSegment, tempSegment);
PPCRecompilerIml_setLinkBranchTaken(imlSegment, tempSegment);
}
// copy IML instructions
for (sint32 f = 0; f < finalSegment->imlListCount; f++)
{
memcpy(PPCRecompiler_appendInstruction(imlSegment), finalSegment->imlList + f, sizeof(PPCRecImlInstruction_t));
}
finalSegment->imlListCount = 0;
//PPCRecompiler_dumpIML(ppcRecFunc, &ppcImlGenContext);
}
// todo: If possible, merge with the segment following conditionalSegment (merging is only possible if the segment is not an entry point or has no other jump sources)
}
// insert cycle counter instruction in every segment that has a cycle count greater zero
for(sint32 s=0; s<ppcImlGenContext.segmentListCount; s++)
{
PPCRecImlSegment_t* imlSegment = ppcImlGenContext.segmentList[s];
if( imlSegment->ppcAddrMin == 0 )
continue;
// count number of PPC instructions in segment
// note: This algorithm correctly counts inlined functions but it doesn't count NO-OP instructions like ISYNC
uint32 lastPPCInstAddr = 0;
uint32 ppcCount2 = 0;
for (sint32 i = 0; i < imlSegment->imlListCount; i++)
{
if (imlSegment->imlList[i].associatedPPCAddress == 0)
continue;
if (imlSegment->imlList[i].associatedPPCAddress == lastPPCInstAddr)
continue;
lastPPCInstAddr = imlSegment->imlList[i].associatedPPCAddress;
ppcCount2++;
}
//uint32 ppcCount = imlSegment->ppcAddrMax-imlSegment->ppcAddrMin+4; -> No longer works with inlined functions
uint32 cycleCount = ppcCount2;// ppcCount / 4;
if( cycleCount > 0 )
{
PPCRecompiler_pushBackIMLInstructions(imlSegment, 0, 1);
imlSegment->imlList[0].type = PPCREC_IML_TYPE_MACRO;
imlSegment->imlList[0].crRegister = PPC_REC_INVALID_REGISTER;
imlSegment->imlList[0].operation = PPCREC_IML_MACRO_COUNT_CYCLES;
imlSegment->imlList[0].op_macro.param = cycleCount;
}
}
// find segments that have a (conditional) jump instruction that points in reverse direction of code flow
// for these segments there is a risk that the recompiler could get trapped in an infinite busy loop.
// todo: We should do a loop-detection prepass where we flag segments that are actually in a loop. We can then use this information below to avoid generating the scheduler-exit code for segments that aren't actually in a loop despite them referencing an earlier segment (which could be an exit segment for example)
uint32 currentLoopEscapeJumpMarker = 0xFF000000; // start in an area where no valid code can be located
for(sint32 s=0; s<ppcImlGenContext.segmentListCount; s++)
{
// todo: This currently uses segment->ppcAddrMin which isn't really reliable. (We already had a problem where function inlining would generate falsified segment ranges by omitting the branch instruction). Find a better solution (use jumpmark/enterable offsets?)
PPCRecImlSegment_t* imlSegment = ppcImlGenContext.segmentList[s];
if( imlSegment->imlListCount == 0 )
continue;
if (imlSegment->imlList[imlSegment->imlListCount - 1].type != PPCREC_IML_TYPE_CJUMP || imlSegment->imlList[imlSegment->imlListCount - 1].op_conditionalJump.jumpmarkAddress > imlSegment->ppcAddrMin)
continue;
if (imlSegment->imlList[imlSegment->imlListCount - 1].type != PPCREC_IML_TYPE_CJUMP || imlSegment->imlList[imlSegment->imlListCount - 1].op_conditionalJump.jumpAccordingToSegment)
continue;
// exclude non-infinite tight loops
if (PPCRecompilerImlAnalyzer_isTightFiniteLoop(imlSegment))
continue;
// potential loop segment found, split this segment into four:
// P0: This segment checks if the remaining cycles counter is still above zero. If yes, it jumps to segment P2 (it's also the jump destination for other segments)
// P1: This segment consists only of a single ppc_leave instruction and is usually skipped. Register unload instructions are later inserted here.
// P2: This segment contains the iml instructions of the original segment
// PEntry: This segment is used to enter the function, it jumps to P0
// All segments are considered to be part of the same PPC instruction range
// The first segment also retains the jump destination and enterable properties from the original segment.
//debug_printf("--- Insert cycle counter check ---\n");
//PPCRecompiler_dumpIML(ppcRecFunc, &ppcImlGenContext);
PPCRecompilerIml_insertSegments(&ppcImlGenContext, s, 2);
imlSegment = NULL;
PPCRecImlSegment_t* imlSegmentP0 = ppcImlGenContext.segmentList[s+0];
PPCRecImlSegment_t* imlSegmentP1 = ppcImlGenContext.segmentList[s+1];
PPCRecImlSegment_t* imlSegmentP2 = ppcImlGenContext.segmentList[s+2];
// create entry point segment
PPCRecompilerIml_insertSegments(&ppcImlGenContext, ppcImlGenContext.segmentListCount, 1);
PPCRecImlSegment_t* imlSegmentPEntry = ppcImlGenContext.segmentList[ppcImlGenContext.segmentListCount-1];
// relink segments
PPCRecompilerIML_relinkInputSegment(imlSegmentP2, imlSegmentP0);
PPCRecompilerIml_setLinkBranchNotTaken(imlSegmentP0, imlSegmentP1);
PPCRecompilerIml_setLinkBranchTaken(imlSegmentP0, imlSegmentP2);
PPCRecompilerIml_setLinkBranchTaken(imlSegmentPEntry, imlSegmentP0);
// update segments
uint32 enterPPCAddress = imlSegmentP2->ppcAddrMin;
if (imlSegmentP2->isEnterable)
enterPPCAddress = imlSegmentP2->enterPPCAddress;
imlSegmentP0->ppcAddress = 0xFFFFFFFF;
imlSegmentP1->ppcAddress = 0xFFFFFFFF;
imlSegmentP2->ppcAddress = 0xFFFFFFFF;
cemu_assert_debug(imlSegmentP2->ppcAddrMin != 0);
// move segment properties from segment P2 to segment P0
imlSegmentP0->isJumpDestination = imlSegmentP2->isJumpDestination;
imlSegmentP0->jumpDestinationPPCAddress = imlSegmentP2->jumpDestinationPPCAddress;
imlSegmentP0->isEnterable = false;
//imlSegmentP0->enterPPCAddress = imlSegmentP2->enterPPCAddress;
imlSegmentP0->ppcAddrMin = imlSegmentP2->ppcAddrMin;
imlSegmentP0->ppcAddrMax = imlSegmentP2->ppcAddrMax;
imlSegmentP2->isJumpDestination = false;
imlSegmentP2->jumpDestinationPPCAddress = 0;
imlSegmentP2->isEnterable = false;
imlSegmentP2->enterPPCAddress = 0;
imlSegmentP2->ppcAddrMin = 0;
imlSegmentP2->ppcAddrMax = 0;
// setup enterable segment
if( enterPPCAddress != 0 && enterPPCAddress != 0xFFFFFFFF )
{
imlSegmentPEntry->isEnterable = true;
imlSegmentPEntry->ppcAddress = enterPPCAddress;
imlSegmentPEntry->enterPPCAddress = enterPPCAddress;
}
// assign new jumpmark to segment P2
imlSegmentP2->isJumpDestination = true;
imlSegmentP2->jumpDestinationPPCAddress = currentLoopEscapeJumpMarker;
currentLoopEscapeJumpMarker++;
// create ppc_leave instruction in segment P1
PPCRecompiler_pushBackIMLInstructions(imlSegmentP1, 0, 1);
imlSegmentP1->imlList[0].type = PPCREC_IML_TYPE_MACRO;
imlSegmentP1->imlList[0].operation = PPCREC_IML_MACRO_LEAVE;
imlSegmentP1->imlList[0].crRegister = PPC_REC_INVALID_REGISTER;
imlSegmentP1->imlList[0].op_macro.param = imlSegmentP0->ppcAddrMin;
imlSegmentP1->imlList[0].associatedPPCAddress = imlSegmentP0->ppcAddrMin;
// create cycle-based conditional instruction in segment P0
PPCRecompiler_pushBackIMLInstructions(imlSegmentP0, 0, 1);
imlSegmentP0->imlList[0].type = PPCREC_IML_TYPE_CJUMP_CYCLE_CHECK;
imlSegmentP0->imlList[0].operation = 0;
imlSegmentP0->imlList[0].crRegister = PPC_REC_INVALID_REGISTER;
imlSegmentP0->imlList[0].op_conditionalJump.jumpmarkAddress = imlSegmentP2->jumpDestinationPPCAddress;
imlSegmentP0->imlList[0].associatedPPCAddress = imlSegmentP0->ppcAddrMin;
// jump instruction for PEntry
PPCRecompiler_pushBackIMLInstructions(imlSegmentPEntry, 0, 1);
PPCRecompilerImlGen_generateNewInstruction_jumpSegment(&ppcImlGenContext, imlSegmentPEntry->imlList + 0);
// skip the newly created segments
s += 2;
}
// isolate entry points from function flow (enterable segments must not be the target of any other segment)
// this simplifies logic during register allocation
PPCRecompilerIML_isolateEnterableSegments(&ppcImlGenContext);
// if GQRs can be predicted, optimize PSQ load/stores
PPCRecompiler_optimizePSQLoadAndStore(&ppcImlGenContext);
// count number of used registers
uint32 numLoadedFPRRegisters = 0;
for(uint32 i=0; i<255; i++)
{
if( ppcImlGenContext.mappedFPRRegister[i] )
numLoadedFPRRegisters++;
}
// insert name store instructions at the end of each segment but before branch instructions
for(sint32 s=0; s<ppcImlGenContext.segmentListCount; s++)
{
PPCRecImlSegment_t* imlSegment = ppcImlGenContext.segmentList[s];
if( ppcImlGenContext.segmentList[s]->imlListCount == 0 )
continue; // ignore empty segments
// analyze segment for register usage
PPCImlOptimizerUsedRegisters_t registersUsed;
for(sint32 i=0; i<imlSegment->imlListCount; i++)
{
PPCRecompiler_checkRegisterUsage(&ppcImlGenContext, imlSegment->imlList+i, ®istersUsed);
//PPCRecompilerImlGen_findRegisterByMappedName(ppcImlGenContext, registersUsed.readGPR1);
sint32 accessedTempReg[5];
// intermediate FPRs
accessedTempReg[0] = registersUsed.readFPR1;
accessedTempReg[1] = registersUsed.readFPR2;
accessedTempReg[2] = registersUsed.readFPR3;
accessedTempReg[3] = registersUsed.readFPR4;
accessedTempReg[4] = registersUsed.writtenFPR1;
for(sint32 f=0; f<5; f++)
{
if( accessedTempReg[f] == -1 )
continue;
uint32 regName = ppcImlGenContext.mappedFPRRegister[accessedTempReg[f]];
if( regName >= PPCREC_NAME_FPR0 && regName < PPCREC_NAME_FPR0+32 )
{
imlSegment->ppcFPRUsed[regName - PPCREC_NAME_FPR0] = true;
}
}
}
}
// merge certain float load+store patterns (must happen before FPR register remapping)
PPCRecompiler_optimizeDirectFloatCopies(&ppcImlGenContext);
// delay byte swapping for certain load+store patterns
PPCRecompiler_optimizeDirectIntegerCopies(&ppcImlGenContext);
if (numLoadedFPRRegisters > 0)
{
if (PPCRecompiler_manageFPRRegisters(&ppcImlGenContext) == false)
{
PPCRecompiler_freeContext(&ppcImlGenContext);
return false;
}
}
PPCRecompilerImm_allocateRegisters(&ppcImlGenContext);
// remove redundant name load and store instructions
PPCRecompiler_reorderConditionModifyInstructions(&ppcImlGenContext);
PPCRecompiler_removeRedundantCRUpdates(&ppcImlGenContext);
return true;
}
| 213,766
|
C++
|
.cpp
| 4,801
| 41.671527
| 401
| 0.777843
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,202
|
PPCRecompilerX64AVX.cpp
|
cemu-project_Cemu/src/Cafe/HW/Espresso/Recompiler/PPCRecompilerX64AVX.cpp
|
#include "PPCRecompiler.h"
#include "PPCRecompilerX64.h"
void _x64Gen_writeMODRMDeprecated(x64GenContext_t* x64GenContext, sint32 dataRegister, sint32 memRegisterA64, sint32 memRegisterB64, sint32 memImmS32);
void _x64Gen_vex128_nds(x64GenContext_t* x64GenContext, uint8 opcodeMap, uint8 additionalOperand, uint8 pp, uint8 vex_ext, uint8 vex_r, uint8 vex_b, uint8 opcode)
{
if(vex_b != 0)
x64Gen_writeU8(x64GenContext, 0xC4); // three byte VEX
else
x64Gen_writeU8(x64GenContext, 0xC5); // two byte VEX
if (vex_b != 0)
{
uint8 vex_x = 0;
x64Gen_writeU8(x64GenContext, (vex_r ? 0x00 : 0x80) | (vex_x ? 0x00 : 0x40) | (vex_b ? 0x00 : 0x20) | 1);
}
x64Gen_writeU8(x64GenContext, (vex_ext<<7) | (((~additionalOperand)&0xF)<<3) | pp);
x64Gen_writeU8(x64GenContext, opcode);
}
#define VEX_PP_0F 0 // guessed
#define VEX_PP_66_0F 1
#define VEX_PP_F3_0F 2 // guessed
#define VEX_PP_F2_0F 3 // guessed
void x64Gen_avx_VPUNPCKHQDQ_xmm_xmm_xmm(x64GenContext_t* x64GenContext, sint32 dstRegister, sint32 srcRegisterA, sint32 srcRegisterB)
{
_x64Gen_vex128_nds(x64GenContext, 0, srcRegisterA, VEX_PP_66_0F, dstRegister < 8 ? 1 : 0, (dstRegister >= 8 && srcRegisterB >= 8) ? 1 : 0, srcRegisterB < 8 ? 0 : 1, 0x6D);
x64Gen_writeU8(x64GenContext, 0xC0 + (srcRegisterB & 7) + (dstRegister & 7) * 8);
}
void x64Gen_avx_VUNPCKHPD_xmm_xmm_xmm(x64GenContext_t* x64GenContext, sint32 dstRegister, sint32 srcRegisterA, sint32 srcRegisterB)
{
_x64Gen_vex128_nds(x64GenContext, 0, srcRegisterA, VEX_PP_66_0F, dstRegister < 8 ? 1 : 0, (dstRegister >= 8 && srcRegisterB >= 8) ? 1 : 0, srcRegisterB < 8 ? 0 : 1, 0x15);
x64Gen_writeU8(x64GenContext, 0xC0 + (srcRegisterB & 7) + (dstRegister & 7) * 8);
}
void x64Gen_avx_VSUBPD_xmm_xmm_xmm(x64GenContext_t* x64GenContext, sint32 dstRegister, sint32 srcRegisterA, sint32 srcRegisterB)
{
_x64Gen_vex128_nds(x64GenContext, 0, srcRegisterA, VEX_PP_66_0F, dstRegister < 8 ? 1 : 0, (dstRegister >= 8 && srcRegisterB >= 8) ? 1 : 0, srcRegisterB < 8 ? 0 : 1, 0x5C);
x64Gen_writeU8(x64GenContext, 0xC0 + (srcRegisterB & 7) + (dstRegister & 7) * 8);
}
| 2,095
|
C++
|
.cpp
| 36
| 56.277778
| 172
| 0.722032
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.